Annotation of src/usr.bin/nc/netcat.c, Revision 1.136
1.136 ! deraadt 1: /* $OpenBSD: netcat.c,v 1.135 2015/09/12 07:56:56 jmc Exp $ */
1.21 ericj 2: /*
3: * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
1.133 beck 4: * Copyright (c) 2015 Bob Beck. All rights reserved.
1.7 deraadt 5: *
1.21 ericj 6: * Redistribution and use in source and binary forms, with or without
7: * modification, are permitted provided that the following conditions
8: * are met:
1.7 deraadt 9: *
1.21 ericj 10: * 1. Redistributions of source code must retain the above copyright
11: * notice, this list of conditions and the following disclaimer.
12: * 2. Redistributions in binary form must reproduce the above copyright
13: * notice, this list of conditions and the following disclaimer in the
14: * documentation and/or other materials provided with the distribution.
15: * 3. The name of the author may not be used to endorse or promote products
16: * derived from this software without specific prior written permission.
1.7 deraadt 17: *
1.21 ericj 18: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28: */
1.1 deraadt 29:
1.24 ericj 30: /*
31: * Re-written nc(1) for OpenBSD. Original implementation by
1.21 ericj 32: * *Hobbit* <hobbit@avian.org>.
33: */
1.1 deraadt 34:
1.7 deraadt 35: #include <sys/types.h>
1.21 ericj 36: #include <sys/socket.h>
1.7 deraadt 37: #include <sys/time.h>
1.113 djm 38: #include <sys/uio.h>
1.42 ericj 39: #include <sys/un.h>
1.21 ericj 40:
1.7 deraadt 41: #include <netinet/in.h>
1.65 markus 42: #include <netinet/tcp.h>
1.83 dtucker 43: #include <netinet/ip.h>
1.21 ericj 44: #include <arpa/telnet.h>
1.29 smart 45:
1.11 ericj 46: #include <err.h>
1.7 deraadt 47: #include <errno.h>
1.129 tobias 48: #include <limits.h>
1.21 ericj 49: #include <netdb.h>
50: #include <poll.h>
1.129 tobias 51: #include <signal.h>
1.13 ericj 52: #include <stdarg.h>
1.21 ericj 53: #include <stdio.h>
1.1 deraadt 54: #include <stdlib.h>
1.21 ericj 55: #include <string.h>
1.5 art 56: #include <unistd.h>
1.133 beck 57: #include <tls.h>
1.79 avsm 58: #include "atomicio.h"
1.51 vincent 59:
60: #ifndef SUN_LEN
61: #define SUN_LEN(su) \
62: (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
63: #endif
1.1 deraadt 64:
1.55 fgsch 65: #define PORT_MAX 65535
66: #define PORT_MAX_LEN 6
1.99 jeremy 67: #define UNIX_DG_TMP_SOCKET_SIZE 19
1.31 ericj 68:
1.125 tedu 69: #define POLL_STDIN 0
70: #define POLL_NETOUT 1
71: #define POLL_NETIN 2
72: #define POLL_STDOUT 3
1.126 tedu 73: #define BUFSIZE 16384
1.133 beck 74: #define DEFAULT_CA_FILE "/etc/ssl/cert.pem"
75:
76: #define TLS_LEGACY (1 << 1)
77: #define TLS_NOVERIFY (1 << 2)
78: #define TLS_NONAME (1 << 3)
79: #define TLS_CCERT (1 << 4)
1.125 tedu 80:
1.21 ericj 81: /* Command Line Options */
1.68 tedu 82: int dflag; /* detached, no stdin */
1.113 djm 83: int Fflag; /* fdpass sock to stdout */
1.88 ray 84: unsigned int iflag; /* Interval Flag */
1.21 ericj 85: int kflag; /* More than one connect */
86: int lflag; /* Bind to local port */
1.111 sthen 87: int Nflag; /* shutdown() network socket */
1.67 jmc 88: int nflag; /* Don't do name look up */
1.86 djm 89: char *Pflag; /* Proxy username */
1.21 ericj 90: char *pflag; /* Localport flag */
91: int rflag; /* Random ports flag */
92: char *sflag; /* Source Address */
93: int tflag; /* Telnet Emulation */
94: int uflag; /* UDP - Default to TCP */
95: int vflag; /* Verbosity */
1.34 jakob 96: int xflag; /* Socks proxy */
1.21 ericj 97: int zflag; /* Port Scan Flag */
1.73 markus 98: int Dflag; /* sodebug */
1.90 djm 99: int Iflag; /* TCP receive buffer size */
100: int Oflag; /* TCP send buffer size */
1.65 markus 101: int Sflag; /* TCP MD5 signature option */
1.83 dtucker 102: int Tflag = -1; /* IP Type of Service */
1.117 sthen 103: int rtableid = -1;
1.21 ericj 104:
1.133 beck 105: int usetls; /* use TLS */
106: char *Cflag; /* Public cert file */
107: char *Kflag; /* Private key file */
108: char *Rflag = DEFAULT_CA_FILE; /* Root CA file */
109: int tls_cachanged; /* Using non-default CA file */
110: int TLSopt; /* TLS options */
111: char *tls_expectname; /* required name in peer cert */
112: char *tls_peerhash; /* hash of peer cert */
113: char *tls_expecthash; /* required hash of peer cert */
114:
1.49 hugh 115: int timeout = -1;
1.21 ericj 116: int family = AF_UNSPEC;
1.63 miod 117: char *portlist[PORT_MAX+1];
1.99 jeremy 118: char *unix_dg_tmp_socket;
1.21 ericj 119:
1.40 millert 120: void atelnet(int, unsigned char *, unsigned int);
121: void build_ports(char *);
122: void help(void);
123: int local_listen(char *, char *, struct addrinfo);
1.133 beck 124: void readwrite(int, struct tls *);
1.113 djm 125: void fdpass(int nfd) __attribute__((noreturn));
1.77 otto 126: int remote_connect(const char *, const char *, struct addrinfo);
1.103 fgsch 127: int timeout_connect(int, const struct sockaddr *, socklen_t);
1.86 djm 128: int socks_connect(const char *, const char *, struct addrinfo,
129: const char *, const char *, struct addrinfo, int, const char *);
1.40 millert 130: int udptest(int);
1.136 ! deraadt 131: int unix_bind(char *, int);
1.42 ericj 132: int unix_connect(char *);
133: int unix_listen(char *);
1.127 jca 134: void set_common_sockopts(int, int);
1.102 haesbaer 135: int map_tos(char *, int *);
1.133 beck 136: int map_tls(char *, int *);
1.108 haesbaer 137: void report_connect(const struct sockaddr *, socklen_t);
1.134 deraadt 138: void report_tls(struct tls *tls_ctx, char * host, char *tls_expectname);
1.40 millert 139: void usage(int);
1.133 beck 140: ssize_t drainbuf(int, unsigned char *, size_t *, struct tls *);
141: ssize_t fillbuf(int, unsigned char *, size_t *, struct tls *);
142: void tls_setup_client(struct tls *, int, char *);
1.134 deraadt 143: struct tls *tls_setup_server(struct tls *, int, char *);
1.1 deraadt 144:
1.21 ericj 145: int
1.37 jakob 146: main(int argc, char *argv[])
1.21 ericj 147: {
1.46 markus 148: int ch, s, ret, socksv;
1.88 ray 149: char *host, *uport;
1.21 ericj 150: struct addrinfo hints;
1.29 smart 151: struct servent *sv;
1.21 ericj 152: socklen_t len;
1.76 hshoexer 153: struct sockaddr_storage cliaddr;
1.34 jakob 154: char *proxy;
1.88 ray 155: const char *errstr, *proxyhost = "", *proxyport = NULL;
1.34 jakob 156: struct addrinfo proxyhints;
1.99 jeremy 157: char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
1.133 beck 158: struct tls_config *tls_cfg = NULL;
159: struct tls *tls_ctx = NULL;
1.11 ericj 160:
1.29 smart 161: ret = 1;
162: s = 0;
1.46 markus 163: socksv = 5;
1.29 smart 164: host = NULL;
165: uport = NULL;
166: sv = NULL;
1.129 tobias 167:
168: signal(SIGPIPE, SIG_IGN);
1.29 smart 169:
1.80 mcbride 170: while ((ch = getopt(argc, argv,
1.133 beck 171: "46C:cDde:FH:hI:i:K:klNnO:P:p:R:rSs:T:tUuV:vw:X:x:z")) != -1) {
1.21 ericj 172: switch (ch) {
173: case '4':
174: family = AF_INET;
175: break;
176: case '6':
177: family = AF_INET6;
178: break;
1.42 ericj 179: case 'U':
180: family = AF_UNIX;
181: break;
1.46 markus 182: case 'X':
1.75 djm 183: if (strcasecmp(optarg, "connect") == 0)
184: socksv = -1; /* HTTP proxy CONNECT */
185: else if (strcmp(optarg, "4") == 0)
186: socksv = 4; /* SOCKS v.4 */
187: else if (strcmp(optarg, "5") == 0)
188: socksv = 5; /* SOCKS v.5 */
189: else
190: errx(1, "unsupported proxy protocol");
1.46 markus 191: break;
1.133 beck 192: case 'C':
193: Cflag = optarg;
194: break;
195: case 'c':
196: usetls = 1;
197: break;
1.68 tedu 198: case 'd':
199: dflag = 1;
200: break;
1.133 beck 201: case 'e':
202: tls_expectname = optarg;
203: break;
1.113 djm 204: case 'F':
205: Fflag = 1;
206: break;
1.133 beck 207: case 'H':
208: tls_expecthash = optarg;
209: break;
1.21 ericj 210: case 'h':
211: help();
212: break;
213: case 'i':
1.88 ray 214: iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
215: if (errstr)
216: errx(1, "interval %s: %s", errstr, optarg);
1.21 ericj 217: break;
1.133 beck 218: case 'K':
219: Kflag = optarg;
220: break;
1.21 ericj 221: case 'k':
222: kflag = 1;
223: break;
224: case 'l':
225: lflag = 1;
226: break;
1.111 sthen 227: case 'N':
228: Nflag = 1;
229: break;
1.21 ericj 230: case 'n':
231: nflag = 1;
232: break;
1.86 djm 233: case 'P':
234: Pflag = optarg;
235: break;
1.21 ericj 236: case 'p':
237: pflag = optarg;
238: break;
1.133 beck 239: case 'R':
240: tls_cachanged = 1;
241: Rflag = optarg;
242: break;
1.21 ericj 243: case 'r':
244: rflag = 1;
245: break;
246: case 's':
247: sflag = optarg;
248: break;
249: case 't':
250: tflag = 1;
251: break;
252: case 'u':
253: uflag = 1;
254: break;
1.93 claudio 255: case 'V':
1.117 sthen 256: rtableid = (int)strtonum(optarg, 0,
1.93 claudio 257: RT_TABLEID_MAX, &errstr);
258: if (errstr)
1.98 guenther 259: errx(1, "rtable %s: %s", errstr, optarg);
1.93 claudio 260: break;
1.21 ericj 261: case 'v':
262: vflag = 1;
263: break;
1.70 deraadt 264: case 'w':
1.88 ray 265: timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
266: if (errstr)
267: errx(1, "timeout %s: %s", errstr, optarg);
1.49 hugh 268: timeout *= 1000;
1.21 ericj 269: break;
1.34 jakob 270: case 'x':
271: xflag = 1;
1.64 deraadt 272: if ((proxy = strdup(optarg)) == NULL)
273: err(1, NULL);
1.34 jakob 274: break;
1.21 ericj 275: case 'z':
276: zflag = 1;
277: break;
1.73 markus 278: case 'D':
279: Dflag = 1;
280: break;
1.90 djm 281: case 'I':
282: Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
283: if (errstr != NULL)
284: errx(1, "TCP receive window %s: %s",
285: errstr, optarg);
286: break;
287: case 'O':
288: Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
289: if (errstr != NULL)
290: errx(1, "TCP send window %s: %s",
291: errstr, optarg);
292: break;
1.65 markus 293: case 'S':
294: Sflag = 1;
295: break;
1.83 dtucker 296: case 'T':
1.102 haesbaer 297: errstr = NULL;
298: errno = 0;
299: if (map_tos(optarg, &Tflag))
300: break;
1.133 beck 301: if (map_tls(optarg, &TLSopt))
302: break;
1.102 haesbaer 303: if (strlen(optarg) > 1 && optarg[0] == '0' &&
304: optarg[1] == 'x')
305: Tflag = (int)strtol(optarg, NULL, 16);
306: else
307: Tflag = (int)strtonum(optarg, 0, 255,
308: &errstr);
309: if (Tflag < 0 || Tflag > 255 || errstr || errno)
1.133 beck 310: errx(1, "illegal tos/tls value %s", optarg);
1.83 dtucker 311: break;
1.21 ericj 312: default:
313: usage(1);
314: }
315: }
316: argc -= optind;
317: argv += optind;
1.11 ericj 318:
1.21 ericj 319: /* Cruft to make sure options are clean, and used properly. */
1.42 ericj 320: if (argv[0] && !argv[1] && family == AF_UNIX) {
321: host = argv[0];
322: uport = NULL;
323: } else if (argv[0] && !argv[1]) {
1.21 ericj 324: if (!lflag)
325: usage(1);
326: uport = argv[0];
327: host = NULL;
328: } else if (argv[0] && argv[1]) {
329: host = argv[0];
330: uport = argv[1];
331: } else
332: usage(1);
1.1 deraadt 333:
1.21 ericj 334: if (lflag && sflag)
335: errx(1, "cannot use -s and -l");
336: if (lflag && pflag)
337: errx(1, "cannot use -p and -l");
338: if (lflag && zflag)
1.32 ericj 339: errx(1, "cannot use -z and -l");
1.21 ericj 340: if (!lflag && kflag)
1.32 ericj 341: errx(1, "must use -l with -k");
1.133 beck 342: if (uflag && usetls)
343: errx(1, "cannot use -c and -u");
344: if ((family == AF_UNIX) && usetls)
345: errx(1, "cannot use -c and -U");
346: if (TLSopt && !usetls)
347: errx(1, "you must specify -c to use TLS options");
348: if (Cflag && !usetls)
349: errx(1, "you must specify -c to use -C");
350: if (Kflag && !usetls)
351: errx(1, "you must specify -c to use -K");
352: if (tls_cachanged && !usetls)
353: errx(1, "you must specify -c to use -R");
354: if (tls_expecthash && !usetls)
355: errx(1, "you must specify -c to use -H");
356: if (tls_expectname && !usetls)
357: errx(1, "you must specify -c to use -e");
1.21 ericj 358:
1.99 jeremy 359: /* Get name of temporary socket for unix datagram client */
360: if ((family == AF_UNIX) && uflag && !lflag) {
361: if (sflag) {
362: unix_dg_tmp_socket = sflag;
363: } else {
364: strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
1.136 ! deraadt 365: UNIX_DG_TMP_SOCKET_SIZE);
1.99 jeremy 366: if (mktemp(unix_dg_tmp_socket_buf) == NULL)
367: err(1, "mktemp");
368: unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
369: }
370: }
371:
1.67 jmc 372: /* Initialize addrinfo structure. */
1.42 ericj 373: if (family != AF_UNIX) {
374: memset(&hints, 0, sizeof(struct addrinfo));
375: hints.ai_family = family;
376: hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
377: hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
378: if (nflag)
379: hints.ai_flags |= AI_NUMERICHOST;
380: }
1.1 deraadt 381:
1.34 jakob 382: if (xflag) {
383: if (uflag)
384: errx(1, "no proxy support for UDP mode");
385:
386: if (lflag)
387: errx(1, "no proxy support for listen");
388:
1.42 ericj 389: if (family == AF_UNIX)
390: errx(1, "no proxy support for unix sockets");
391:
1.34 jakob 392: /* XXX IPv6 transport to proxy would probably work */
393: if (family == AF_INET6)
394: errx(1, "no proxy support for IPv6");
395:
396: if (sflag)
397: errx(1, "no proxy support for local source address");
398:
399: proxyhost = strsep(&proxy, ":");
400: proxyport = proxy;
401:
402: memset(&proxyhints, 0, sizeof(struct addrinfo));
403: proxyhints.ai_family = family;
404: proxyhints.ai_socktype = SOCK_STREAM;
405: proxyhints.ai_protocol = IPPROTO_TCP;
406: if (nflag)
407: proxyhints.ai_flags |= AI_NUMERICHOST;
408: }
409:
1.133 beck 410: if (usetls) {
411: if (tls_init() == -1)
412: errx(1, "unable to initialize TLS");
413: if ((tls_cfg = tls_config_new()) == NULL)
414: errx(1, "unable to allocate TLS config");
415: if (Cflag && (tls_config_set_cert_file(tls_cfg, Cflag) == -1))
416: errx(1, "unable to set TLS certificate file %s", Cflag);
417: if (Kflag && (tls_config_set_key_file(tls_cfg, Kflag) == -1))
418: errx(1, "unable to set TLS key file %s", Kflag);
419: if (Rflag && (tls_config_set_ca_file(tls_cfg, Rflag) == -1))
420: errx(1, "unable to set root CA file %s", Rflag);
421: if (TLSopt & TLS_LEGACY) {
422: tls_config_set_protocols(tls_cfg, TLS_PROTOCOLS_ALL);
423: tls_config_set_ciphers(tls_cfg, "legacy");
424: }
425: if (!lflag && (TLSopt & TLS_CCERT))
426: errx(1, "clientcert is only valid with -l");
427: if (TLSopt & TLS_NONAME)
428: tls_config_insecure_noverifyname(tls_cfg);
429: if (TLSopt & TLS_NOVERIFY) {
430: if (tls_expecthash != NULL)
431: errx(1, "-H and -T noverify may not be used"
432: "together");
433: tls_config_insecure_noverifycert(tls_cfg);
434: }
435: }
1.21 ericj 436: if (lflag) {
1.133 beck 437: struct tls *tls_cctx = NULL;
1.21 ericj 438: int connfd;
1.27 ericj 439: ret = 0;
1.1 deraadt 440:
1.99 jeremy 441: if (family == AF_UNIX) {
442: if (uflag)
1.136 ! deraadt 443: s = unix_bind(host, 0);
1.99 jeremy 444: else
445: s = unix_listen(host);
446: }
1.42 ericj 447:
1.133 beck 448: if (usetls) {
449: tls_config_verify_client_optional(tls_cfg);
450: if ((tls_ctx = tls_server()) == NULL)
451: errx(1, "tls server creation failed");
452: if (tls_configure(tls_ctx, tls_cfg) == -1)
453: errx(1, "tls configuration failed (%s)",
454: tls_error(tls_ctx));
455: }
1.67 jmc 456: /* Allow only one connection at a time, but stay alive. */
1.21 ericj 457: for (;;) {
1.42 ericj 458: if (family != AF_UNIX)
459: s = local_listen(host, uport, hints);
460: if (s < 0)
1.30 smart 461: err(1, NULL);
1.21 ericj 462: /*
1.109 haesbaer 463: * For UDP and -k, don't connect the socket, let it
464: * receive datagrams from multiple socket pairs.
1.21 ericj 465: */
1.109 haesbaer 466: if (uflag && kflag)
1.133 beck 467: readwrite(s, NULL);
1.109 haesbaer 468: /*
469: * For UDP and not -k, we will use recvfrom() initially
470: * to wait for a caller, then use the regular functions
471: * to talk to the caller.
472: */
473: else if (uflag && !kflag) {
1.80 mcbride 474: int rv, plen;
1.97 nicm 475: char buf[16384];
1.21 ericj 476: struct sockaddr_storage z;
477:
478: len = sizeof(z);
1.106 dlg 479: plen = 2048;
1.80 mcbride 480: rv = recvfrom(s, buf, plen, MSG_PEEK,
1.37 jakob 481: (struct sockaddr *)&z, &len);
1.23 ericj 482: if (rv < 0)
1.57 stevesk 483: err(1, "recvfrom");
1.21 ericj 484:
1.37 jakob 485: rv = connect(s, (struct sockaddr *)&z, len);
1.23 ericj 486: if (rv < 0)
1.57 stevesk 487: err(1, "connect");
1.1 deraadt 488:
1.108 haesbaer 489: if (vflag)
490: report_connect((struct sockaddr *)&z, len);
491:
1.133 beck 492: readwrite(s, NULL);
1.21 ericj 493: } else {
1.78 otto 494: len = sizeof(cliaddr);
1.132 bluhm 495: connfd = accept4(s, (struct sockaddr *)&cliaddr,
496: &len, SOCK_NONBLOCK);
1.110 deraadt 497: if (connfd == -1) {
498: /* For now, all errnos are fatal */
1.125 tedu 499: err(1, "accept");
1.110 deraadt 500: }
1.108 haesbaer 501: if (vflag)
502: report_connect((struct sockaddr *)&cliaddr, len);
1.133 beck 503: if ((usetls) &&
1.134 deraadt 504: (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
1.133 beck 505: readwrite(connfd, tls_cctx);
506: if (!usetls)
507: readwrite(connfd, NULL);
508: if (tls_cctx) {
509: int i;
1.136 ! deraadt 510:
1.133 beck 511: do {
512: i = tls_close(tls_cctx);
513: } while (i == TLS_WANT_POLLIN ||
514: i == TLS_WANT_POLLOUT);
515: tls_free(tls_cctx);
516: tls_cctx = NULL;
517: }
1.99 jeremy 518: close(connfd);
1.21 ericj 519: }
1.42 ericj 520: if (family != AF_UNIX)
521: close(s);
1.99 jeremy 522: else if (uflag) {
523: if (connect(s, NULL, 0) < 0)
524: err(1, "connect");
525: }
1.27 ericj 526:
1.21 ericj 527: if (!kflag)
528: break;
1.11 ericj 529: }
1.42 ericj 530: } else if (family == AF_UNIX) {
531: ret = 0;
532:
533: if ((s = unix_connect(host)) > 0 && !zflag) {
1.133 beck 534: readwrite(s, NULL);
1.42 ericj 535: close(s);
536: } else
537: ret = 1;
538:
1.99 jeremy 539: if (uflag)
540: unlink(unix_dg_tmp_socket);
1.42 ericj 541: exit(ret);
542:
1.21 ericj 543: } else {
544: int i = 0;
1.6 deraadt 545:
1.67 jmc 546: /* Construct the portlist[] array. */
1.21 ericj 547: build_ports(uport);
1.1 deraadt 548:
1.67 jmc 549: /* Cycle through portlist, connecting to each port. */
1.21 ericj 550: for (i = 0; portlist[i] != NULL; i++) {
551: if (s)
552: close(s);
1.34 jakob 553:
1.133 beck 554: if (usetls) {
555: if ((tls_ctx = tls_client()) == NULL)
556: errx(1, "tls client creation failed");
557: if (tls_configure(tls_ctx, tls_cfg) == -1)
558: errx(1, "tls configuration failed (%s)",
559: tls_error(tls_ctx));
560: }
1.34 jakob 561: if (xflag)
562: s = socks_connect(host, portlist[i], hints,
1.86 djm 563: proxyhost, proxyport, proxyhints, socksv,
564: Pflag);
1.34 jakob 565: else
566: s = remote_connect(host, portlist[i], hints);
567:
568: if (s < 0)
1.21 ericj 569: continue;
1.1 deraadt 570:
1.21 ericj 571: ret = 0;
572: if (vflag || zflag) {
1.67 jmc 573: /* For UDP, make sure we are connected. */
1.21 ericj 574: if (uflag) {
1.50 vincent 575: if (udptest(s) == -1) {
1.21 ericj 576: ret = 1;
577: continue;
578: }
579: }
1.1 deraadt 580:
1.67 jmc 581: /* Don't look up port if -n. */
1.21 ericj 582: if (nflag)
583: sv = NULL;
584: else {
585: sv = getservbyport(
1.37 jakob 586: ntohs(atoi(portlist[i])),
587: uflag ? "udp" : "tcp");
1.21 ericj 588: }
1.50 vincent 589:
1.94 mpf 590: fprintf(stderr,
591: "Connection to %s %s port [%s/%s] "
592: "succeeded!\n", host, portlist[i],
593: uflag ? "udp" : "tcp",
1.37 jakob 594: sv ? sv->s_name : "*");
1.21 ericj 595: }
1.113 djm 596: if (Fflag)
597: fdpass(s);
1.133 beck 598: else {
599: if (usetls)
600: tls_setup_client(tls_ctx, s, host);
601: if (!zflag)
602: readwrite(s, tls_ctx);
603: if (tls_ctx) {
604: int j;
1.136 ! deraadt 605:
1.133 beck 606: do {
607: j = tls_close(tls_ctx);
608: } while (j == TLS_WANT_POLLIN ||
609: j == TLS_WANT_POLLOUT);
610: tls_free(tls_ctx);
611: tls_ctx = NULL;
612: }
613: }
1.7 deraadt 614: }
1.11 ericj 615: }
1.1 deraadt 616:
1.21 ericj 617: if (s)
618: close(s);
619:
1.133 beck 620: free(tls_peerhash);
621: tls_config_free(tls_cfg);
622:
1.21 ericj 623: exit(ret);
1.7 deraadt 624: }
1.1 deraadt 625:
1.11 ericj 626: /*
1.99 jeremy 627: * unix_bind()
628: * Returns a unix socket bound to the given path
1.42 ericj 629: */
630: int
1.136 ! deraadt 631: unix_bind(char *path, int flags)
1.42 ericj 632: {
633: struct sockaddr_un sun;
634: int s;
635:
1.99 jeremy 636: /* Create unix domain socket. */
1.136 ! deraadt 637: if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
! 638: 0)) < 0)
1.50 vincent 639: return (-1);
1.42 ericj 640:
641: memset(&sun, 0, sizeof(struct sockaddr_un));
642: sun.sun_family = AF_UNIX;
1.60 avsm 643:
644: if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
645: sizeof(sun.sun_path)) {
646: close(s);
647: errno = ENAMETOOLONG;
648: return (-1);
649: }
1.99 jeremy 650:
651: if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.50 vincent 652: close(s);
653: return (-1);
1.42 ericj 654: }
655: return (s);
656: }
657:
1.133 beck 658: void
659: tls_setup_client(struct tls *tls_ctx, int s, char *host)
660:
661: {
662: int i;
1.136 ! deraadt 663:
1.133 beck 664: if (tls_connect_socket(tls_ctx, s,
665: tls_expectname ? tls_expectname : host) == -1) {
666: errx(1, "tls connection failed (%s)",
667: tls_error(tls_ctx));
668: }
669: do {
670: if ((i = tls_handshake(tls_ctx)) == -1)
671: errx(1, "tls handshake failed (%s)",
672: tls_error(tls_ctx));
673: } while (i == TLS_WANT_POLLIN || i == TLS_WANT_POLLOUT);
674: if (tls_peer_cert_hash(tls_ctx, &tls_peerhash) == -1)
675: errx(1, "hash of peer certificate failed");
676: if (vflag)
677: report_tls(tls_ctx, host, tls_expectname);
678: if (tls_expecthash && tls_peerhash &&
679: strcmp(tls_expecthash, tls_peerhash) != 0)
680: errx(1, "peer certificate is not %s", tls_expecthash);
681: }
682: struct tls *
683: tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
684: {
685: struct tls *tls_cctx;
1.136 ! deraadt 686:
1.133 beck 687: if (tls_accept_socket(tls_ctx, &tls_cctx,
688: connfd) == -1) {
689: warnx("tls accept failed (%s)",
690: tls_error(tls_ctx));
691: tls_cctx = NULL;
692: } else {
693: int i;
1.136 ! deraadt 694:
1.133 beck 695: do {
696: if ((i = tls_handshake(tls_cctx)) == -1)
697: warnx("tls handshake failed (%s)",
698: tls_error(tls_cctx));
699: } while(i == TLS_WANT_POLLIN || i == TLS_WANT_POLLOUT);
700: }
701: if (tls_cctx) {
702: int gotcert = tls_peer_cert_provided(tls_cctx);
1.136 ! deraadt 703:
1.133 beck 704: if (gotcert && tls_peer_cert_hash(tls_cctx, &tls_peerhash) == -1)
705: warn("hash of peer certificate failed");
706: if (vflag && gotcert)
707: report_tls(tls_cctx, host, tls_expectname);
708: if ((TLSopt & TLS_CCERT) && !gotcert)
709: warnx("No client certificate provided");
710: else if (gotcert && tls_peerhash && tls_expecthash &&
711: strcmp(tls_expecthash, tls_peerhash) != 0)
712: warnx("peer certificate is not %s", tls_expecthash);
713: else if (gotcert && tls_expectname &&
1.134 deraadt 714: (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
1.133 beck 715: warnx("name (%s) not found in client cert",
716: tls_expectname);
717: else {
718: return tls_cctx;
719: }
720: }
721: return NULL;
722: }
1.42 ericj 723: /*
1.99 jeremy 724: * unix_connect()
725: * Returns a socket connected to a local unix socket. Returns -1 on failure.
1.42 ericj 726: */
727: int
1.99 jeremy 728: unix_connect(char *path)
1.42 ericj 729: {
730: struct sockaddr_un sun;
731: int s;
732:
1.99 jeremy 733: if (uflag) {
1.136 ! deraadt 734: if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) < 0)
1.99 jeremy 735: return (-1);
736: } else {
1.136 ! deraadt 737: if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
1.99 jeremy 738: return (-1);
739: }
1.42 ericj 740:
1.60 avsm 741: memset(&sun, 0, sizeof(struct sockaddr_un));
1.42 ericj 742: sun.sun_family = AF_UNIX;
1.60 avsm 743:
744: if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
745: sizeof(sun.sun_path)) {
746: close(s);
747: errno = ENAMETOOLONG;
748: return (-1);
749: }
1.99 jeremy 750: if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.42 ericj 751: close(s);
752: return (-1);
753: }
1.99 jeremy 754: return (s);
755:
756: }
757:
758: /*
759: * unix_listen()
760: * Create a unix domain socket, and listen on it.
761: */
762: int
763: unix_listen(char *path)
764: {
765: int s;
1.136 ! deraadt 766: if ((s = unix_bind(path, 0)) < 0)
1.99 jeremy 767: return (-1);
1.42 ericj 768:
769: if (listen(s, 5) < 0) {
770: close(s);
771: return (-1);
772: }
773: return (s);
774: }
775:
776: /*
1.21 ericj 777: * remote_connect()
1.67 jmc 778: * Returns a socket connected to a remote host. Properly binds to a local
779: * port or source address if needed. Returns -1 on failure.
1.11 ericj 780: */
1.21 ericj 781: int
1.77 otto 782: remote_connect(const char *host, const char *port, struct addrinfo hints)
1.21 ericj 783: {
784: struct addrinfo *res, *res0;
1.91 markus 785: int s, error, on = 1;
1.21 ericj 786:
787: if ((error = getaddrinfo(host, port, &hints, &res)))
1.56 stevesk 788: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21 ericj 789:
790: res0 = res;
791: do {
1.132 bluhm 792: if ((s = socket(res0->ai_family, res0->ai_socktype |
793: SOCK_NONBLOCK, res0->ai_protocol)) < 0)
1.21 ericj 794: continue;
795:
1.117 sthen 796: if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
797: &rtableid, sizeof(rtableid)) == -1))
1.115 phessler 798: err(1, "setsockopt SO_RTABLE");
1.93 claudio 799:
1.67 jmc 800: /* Bind to a local port or source address if specified. */
1.21 ericj 801: if (sflag || pflag) {
802: struct addrinfo ahints, *ares;
1.6 deraadt 803:
1.91 markus 804: /* try SO_BINDANY, but don't insist */
805: setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
1.21 ericj 806: memset(&ahints, 0, sizeof(struct addrinfo));
807: ahints.ai_family = res0->ai_family;
808: ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
809: ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
1.25 ericj 810: ahints.ai_flags = AI_PASSIVE;
1.38 jakob 811: if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
1.56 stevesk 812: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21 ericj 813:
814: if (bind(s, (struct sockaddr *)ares->ai_addr,
1.62 millert 815: ares->ai_addrlen) < 0)
1.119 guenther 816: err(1, "bind failed");
1.21 ericj 817: freeaddrinfo(ares);
1.6 deraadt 818: }
1.81 marius 819:
1.127 jca 820: set_common_sockopts(s, res0->ai_family);
1.6 deraadt 821:
1.103 fgsch 822: if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
1.6 deraadt 823: break;
1.71 mcbride 824: else if (vflag)
825: warn("connect to %s port %s (%s) failed", host, port,
826: uflag ? "udp" : "tcp");
1.34 jakob 827:
1.21 ericj 828: close(s);
829: s = -1;
830: } while ((res0 = res0->ai_next) != NULL);
831:
832: freeaddrinfo(res);
1.1 deraadt 833:
1.21 ericj 834: return (s);
1.103 fgsch 835: }
836:
837: int
838: timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
839: {
840: struct pollfd pfd;
841: socklen_t optlen;
1.132 bluhm 842: int optval;
1.103 fgsch 843: int ret;
844:
845: if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
846: pfd.fd = s;
847: pfd.events = POLLOUT;
848: if ((ret = poll(&pfd, 1, timeout)) == 1) {
849: optlen = sizeof(optval);
850: if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
851: &optval, &optlen)) == 0) {
852: errno = optval;
853: ret = optval == 0 ? 0 : -1;
854: }
855: } else if (ret == 0) {
856: errno = ETIMEDOUT;
857: ret = -1;
858: } else
859: err(1, "poll failed");
860: }
861:
862: return (ret);
1.7 deraadt 863: }
1.1 deraadt 864:
1.11 ericj 865: /*
1.21 ericj 866: * local_listen()
1.67 jmc 867: * Returns a socket listening on a local port, binds to specified source
868: * address. Returns -1 on failure.
1.11 ericj 869: */
1.21 ericj 870: int
1.37 jakob 871: local_listen(char *host, char *port, struct addrinfo hints)
1.21 ericj 872: {
873: struct addrinfo *res, *res0;
874: int s, ret, x = 1;
875: int error;
1.6 deraadt 876:
1.67 jmc 877: /* Allow nodename to be null. */
1.21 ericj 878: hints.ai_flags |= AI_PASSIVE;
1.7 deraadt 879:
1.21 ericj 880: /*
881: * In the case of binding to a wildcard address
882: * default to binding to an ipv4 address.
883: */
884: if (host == NULL && hints.ai_family == AF_UNSPEC)
885: hints.ai_family = AF_INET;
1.1 deraadt 886:
1.21 ericj 887: if ((error = getaddrinfo(host, port, &hints, &res)))
1.70 deraadt 888: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.14 ericj 889:
1.21 ericj 890: res0 = res;
891: do {
892: if ((s = socket(res0->ai_family, res0->ai_socktype,
1.82 marius 893: res0->ai_protocol)) < 0)
1.21 ericj 894: continue;
1.1 deraadt 895:
1.118 jca 896: if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
1.117 sthen 897: &rtableid, sizeof(rtableid)) == -1))
1.115 phessler 898: err(1, "setsockopt SO_RTABLE");
1.93 claudio 899:
1.21 ericj 900: ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
901: if (ret == -1)
1.30 smart 902: err(1, NULL);
1.81 marius 903:
1.127 jca 904: set_common_sockopts(s, res0->ai_family);
1.1 deraadt 905:
1.21 ericj 906: if (bind(s, (struct sockaddr *)res0->ai_addr,
1.37 jakob 907: res0->ai_addrlen) == 0)
1.21 ericj 908: break;
1.1 deraadt 909:
1.21 ericj 910: close(s);
911: s = -1;
912: } while ((res0 = res0->ai_next) != NULL);
1.1 deraadt 913:
1.47 ericj 914: if (!uflag && s != -1) {
1.21 ericj 915: if (listen(s, 1) < 0)
1.57 stevesk 916: err(1, "listen");
1.12 ericj 917: }
1.1 deraadt 918:
1.21 ericj 919: freeaddrinfo(res);
1.1 deraadt 920:
1.21 ericj 921: return (s);
1.7 deraadt 922: }
923:
1.11 ericj 924: /*
1.21 ericj 925: * readwrite()
926: * Loop that polls on the network file descriptor and stdin.
1.11 ericj 927: */
1.21 ericj 928: void
1.133 beck 929: readwrite(int net_fd, struct tls *tls_ctx)
1.6 deraadt 930: {
1.125 tedu 931: struct pollfd pfd[4];
932: int stdin_fd = STDIN_FILENO;
933: int stdout_fd = STDOUT_FILENO;
934: unsigned char netinbuf[BUFSIZE];
935: size_t netinbufpos = 0;
936: unsigned char stdinbuf[BUFSIZE];
937: size_t stdinbufpos = 0;
1.130 chl 938: int n, num_fds;
1.125 tedu 939: ssize_t ret;
940:
941: /* don't read from stdin if requested */
942: if (dflag)
943: stdin_fd = -1;
944:
945: /* stdin */
946: pfd[POLL_STDIN].fd = stdin_fd;
947: pfd[POLL_STDIN].events = POLLIN;
948:
949: /* network out */
950: pfd[POLL_NETOUT].fd = net_fd;
951: pfd[POLL_NETOUT].events = 0;
952:
953: /* network in */
954: pfd[POLL_NETIN].fd = net_fd;
955: pfd[POLL_NETIN].events = POLLIN;
956:
957: /* stdout */
958: pfd[POLL_STDOUT].fd = stdout_fd;
959: pfd[POLL_STDOUT].events = 0;
960:
961: while (1) {
962: /* both inputs are gone, buffers are empty, we are done */
1.134 deraadt 963: if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
964: stdinbufpos == 0 && netinbufpos == 0) {
1.125 tedu 965: close(net_fd);
966: return;
967: }
968: /* both outputs are gone, we can't continue */
969: if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
970: close(net_fd);
971: return;
972: }
973: /* listen and net in gone, queues empty, done */
1.134 deraadt 974: if (lflag && pfd[POLL_NETIN].fd == -1 &&
975: stdinbufpos == 0 && netinbufpos == 0) {
1.125 tedu 976: close(net_fd);
977: return;
978: }
1.21 ericj 979:
1.125 tedu 980: /* help says -i is for "wait between lines sent". We read and
981: * write arbitrary amounts of data, and we don't want to start
982: * scanning for newlines, so this is as good as it gets */
1.21 ericj 983: if (iflag)
984: sleep(iflag);
985:
1.125 tedu 986: /* poll */
987: num_fds = poll(pfd, 4, timeout);
988:
989: /* treat poll errors */
990: if (num_fds == -1) {
991: close(net_fd);
992: err(1, "polling error");
1.21 ericj 993: }
1.49 hugh 994:
1.125 tedu 995: /* timeout happened */
996: if (num_fds == 0)
1.49 hugh 997: return;
1.21 ericj 998:
1.125 tedu 999: /* treat socket error conditions */
1000: for (n = 0; n < 4; n++) {
1001: if (pfd[n].revents & (POLLERR|POLLNVAL)) {
1002: pfd[n].fd = -1;
1.6 deraadt 1003: }
1.21 ericj 1004: }
1.125 tedu 1005: /* reading is possible after HUP */
1006: if (pfd[POLL_STDIN].events & POLLIN &&
1007: pfd[POLL_STDIN].revents & POLLHUP &&
1.134 deraadt 1008: !(pfd[POLL_STDIN].revents & POLLIN))
1009: pfd[POLL_STDIN].fd = -1;
1.125 tedu 1010:
1011: if (pfd[POLL_NETIN].events & POLLIN &&
1012: pfd[POLL_NETIN].revents & POLLHUP &&
1.134 deraadt 1013: !(pfd[POLL_NETIN].revents & POLLIN))
1014: pfd[POLL_NETIN].fd = -1;
1.125 tedu 1015:
1016: if (pfd[POLL_NETOUT].revents & POLLHUP) {
1017: if (Nflag)
1018: shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1019: pfd[POLL_NETOUT].fd = -1;
1020: }
1021: /* if HUP, stop watching stdout */
1022: if (pfd[POLL_STDOUT].revents & POLLHUP)
1023: pfd[POLL_STDOUT].fd = -1;
1024: /* if no net out, stop watching stdin */
1025: if (pfd[POLL_NETOUT].fd == -1)
1026: pfd[POLL_STDIN].fd = -1;
1027: /* if no stdout, stop watching net in */
1028: if (pfd[POLL_STDOUT].fd == -1) {
1029: if (pfd[POLL_NETIN].fd != -1)
1030: shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1031: pfd[POLL_NETIN].fd = -1;
1032: }
1.21 ericj 1033:
1.125 tedu 1034: /* try to read from stdin */
1035: if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
1036: ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
1.133 beck 1037: &stdinbufpos, NULL);
1038: if (ret == TLS_WANT_POLLIN)
1039: pfd[POLL_STDIN].events = POLLIN;
1040: else if (ret == TLS_WANT_POLLOUT)
1041: pfd[POLL_STDIN].events = POLLOUT;
1042: else if (ret == 0 || ret == -1)
1.125 tedu 1043: pfd[POLL_STDIN].fd = -1;
1044: /* read something - poll net out */
1045: if (stdinbufpos > 0)
1046: pfd[POLL_NETOUT].events = POLLOUT;
1047: /* filled buffer - remove self from polling */
1048: if (stdinbufpos == BUFSIZE)
1049: pfd[POLL_STDIN].events = 0;
1050: }
1051: /* try to write to network */
1052: if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
1053: ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
1.133 beck 1054: &stdinbufpos, tls_ctx);
1055: if (ret == TLS_WANT_POLLIN)
1056: pfd[POLL_NETOUT].events = POLLIN;
1057: else if (ret == TLS_WANT_POLLOUT)
1058: pfd[POLL_NETOUT].events = POLLOUT;
1059: else if (ret == -1)
1.125 tedu 1060: pfd[POLL_NETOUT].fd = -1;
1061: /* buffer empty - remove self from polling */
1062: if (stdinbufpos == 0)
1063: pfd[POLL_NETOUT].events = 0;
1064: /* buffer no longer full - poll stdin again */
1065: if (stdinbufpos < BUFSIZE)
1066: pfd[POLL_STDIN].events = POLLIN;
1067: }
1068: /* try to read from network */
1069: if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
1070: ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
1.133 beck 1071: &netinbufpos, tls_ctx);
1072: if (ret == TLS_WANT_POLLIN)
1073: pfd[POLL_NETIN].events = POLLIN;
1074: else if (ret == TLS_WANT_POLLOUT)
1075: pfd[POLL_NETIN].events = POLLOUT;
1076: else if (ret == -1)
1.125 tedu 1077: pfd[POLL_NETIN].fd = -1;
1078: /* eof on net in - remove from pfd */
1079: if (ret == 0) {
1080: shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1081: pfd[POLL_NETIN].fd = -1;
1.50 vincent 1082: }
1.125 tedu 1083: /* read something - poll stdout */
1084: if (netinbufpos > 0)
1085: pfd[POLL_STDOUT].events = POLLOUT;
1086: /* filled buffer - remove self from polling */
1087: if (netinbufpos == BUFSIZE)
1088: pfd[POLL_NETIN].events = 0;
1089: /* handle telnet */
1090: if (tflag)
1091: atelnet(pfd[POLL_NETIN].fd, netinbuf,
1092: netinbufpos);
1093: }
1094: /* try to write to stdout */
1095: if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1096: ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1.133 beck 1097: &netinbufpos, NULL);
1098: if (ret == TLS_WANT_POLLIN)
1099: pfd[POLL_STDOUT].events = POLLIN;
1100: else if (ret == TLS_WANT_POLLOUT)
1101: pfd[POLL_STDOUT].events = POLLOUT;
1102: else if (ret == -1)
1.125 tedu 1103: pfd[POLL_STDOUT].fd = -1;
1104: /* buffer empty - remove self from polling */
1105: if (netinbufpos == 0)
1106: pfd[POLL_STDOUT].events = 0;
1107: /* buffer no longer full - poll net in again */
1108: if (netinbufpos < BUFSIZE)
1109: pfd[POLL_NETIN].events = POLLIN;
1110: }
1111:
1112: /* stdin gone and queue empty? */
1113: if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1114: if (pfd[POLL_NETOUT].fd != -1 && Nflag)
1115: shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1116: pfd[POLL_NETOUT].fd = -1;
1117: }
1118: /* net in gone and queue empty? */
1119: if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1120: pfd[POLL_STDOUT].fd = -1;
1.21 ericj 1121: }
1.11 ericj 1122: }
1.125 tedu 1123: }
1124:
1125: ssize_t
1.133 beck 1126: drainbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1.125 tedu 1127: {
1128: ssize_t n;
1129: ssize_t adjust;
1130:
1.133 beck 1131: if (tls)
1132: n = tls_write(tls, buf, *bufpos);
1133: else {
1134: n = write(fd, buf, *bufpos);
1135: /* don't treat EAGAIN, EINTR as error */
1136: if (n == -1 && (errno == EAGAIN || errno == EINTR))
1137: n = TLS_WANT_POLLOUT;
1138: }
1.125 tedu 1139: if (n <= 0)
1140: return n;
1141: /* adjust buffer */
1142: adjust = *bufpos - n;
1143: if (adjust > 0)
1144: memmove(buf, buf + n, adjust);
1145: *bufpos -= n;
1146: return n;
1147: }
1148:
1149:
1150: ssize_t
1.133 beck 1151: fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1.125 tedu 1152: {
1153: size_t num = BUFSIZE - *bufpos;
1154: ssize_t n;
1155:
1.133 beck 1156: if (tls)
1157: n = tls_read(tls, buf + *bufpos, num);
1158: else {
1159: n = read(fd, buf + *bufpos, num);
1160: /* don't treat EAGAIN, EINTR as error */
1161: if (n == -1 && (errno == EAGAIN || errno == EINTR))
1162: n = TLS_WANT_POLLIN;
1163: }
1.125 tedu 1164: if (n <= 0)
1165: return n;
1166: *bufpos += n;
1167: return n;
1.113 djm 1168: }
1169:
1170: /*
1171: * fdpass()
1172: * Pass the connected file descriptor to stdout and exit.
1173: */
1174: void
1175: fdpass(int nfd)
1176: {
1177: struct msghdr mh;
1178: union {
1179: struct cmsghdr hdr;
1180: char buf[CMSG_SPACE(sizeof(int))];
1181: } cmsgbuf;
1182: struct cmsghdr *cmsg;
1183: struct iovec iov;
1184: char c = '\0';
1185: ssize_t r;
1186: struct pollfd pfd;
1187:
1188: /* Avoid obvious stupidity */
1189: if (isatty(STDOUT_FILENO))
1190: errx(1, "Cannot pass file descriptor to tty");
1191:
1192: bzero(&mh, sizeof(mh));
1193: bzero(&cmsgbuf, sizeof(cmsgbuf));
1194: bzero(&iov, sizeof(iov));
1195:
1196: mh.msg_control = (caddr_t)&cmsgbuf.buf;
1197: mh.msg_controllen = sizeof(cmsgbuf.buf);
1198: cmsg = CMSG_FIRSTHDR(&mh);
1199: cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1200: cmsg->cmsg_level = SOL_SOCKET;
1201: cmsg->cmsg_type = SCM_RIGHTS;
1202: *(int *)CMSG_DATA(cmsg) = nfd;
1203:
1204: iov.iov_base = &c;
1205: iov.iov_len = 1;
1206: mh.msg_iov = &iov;
1207: mh.msg_iovlen = 1;
1208:
1209: bzero(&pfd, sizeof(pfd));
1210: pfd.fd = STDOUT_FILENO;
1.128 tobias 1211: pfd.events = POLLOUT;
1.113 djm 1212: for (;;) {
1213: r = sendmsg(STDOUT_FILENO, &mh, 0);
1214: if (r == -1) {
1215: if (errno == EAGAIN || errno == EINTR) {
1216: if (poll(&pfd, 1, -1) == -1)
1217: err(1, "poll");
1218: continue;
1219: }
1220: err(1, "sendmsg");
1.128 tobias 1221: } else if (r != 1)
1.113 djm 1222: errx(1, "sendmsg: unexpected return value %zd", r);
1223: else
1224: break;
1225: }
1226: exit(0);
1.7 deraadt 1227: }
1.50 vincent 1228:
1.67 jmc 1229: /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1.21 ericj 1230: void
1.37 jakob 1231: atelnet(int nfd, unsigned char *buf, unsigned int size)
1.6 deraadt 1232: {
1.24 ericj 1233: unsigned char *p, *end;
1234: unsigned char obuf[4];
1235:
1.95 nicm 1236: if (size < 3)
1237: return;
1238: end = buf + size - 2;
1.24 ericj 1239:
1240: for (p = buf; p < end; p++) {
1.21 ericj 1241: if (*p != IAC)
1.95 nicm 1242: continue;
1.24 ericj 1243:
1.25 ericj 1244: obuf[0] = IAC;
1.24 ericj 1245: p++;
1.50 vincent 1246: if ((*p == WILL) || (*p == WONT))
1.24 ericj 1247: obuf[1] = DONT;
1.95 nicm 1248: else if ((*p == DO) || (*p == DONT))
1.24 ericj 1249: obuf[1] = WONT;
1.95 nicm 1250: else
1251: continue;
1252:
1253: p++;
1254: obuf[2] = *p;
1255: if (atomicio(vwrite, nfd, obuf, 3) != 3)
1256: warn("Write Error!");
1.11 ericj 1257: }
1.7 deraadt 1258: }
1259:
1.11 ericj 1260: /*
1.21 ericj 1261: * build_ports()
1.105 lum 1262: * Build an array of ports in portlist[], listing each port
1.67 jmc 1263: * that we should try to connect to.
1.11 ericj 1264: */
1.21 ericj 1265: void
1.37 jakob 1266: build_ports(char *p)
1.6 deraadt 1267: {
1.88 ray 1268: const char *errstr;
1269: char *n;
1.21 ericj 1270: int hi, lo, cp;
1271: int x = 0;
1272:
1273: if ((n = strchr(p, '-')) != NULL) {
1274: *n = '\0';
1275: n++;
1276:
1.67 jmc 1277: /* Make sure the ports are in order: lowest->highest. */
1.88 ray 1278: hi = strtonum(n, 1, PORT_MAX, &errstr);
1279: if (errstr)
1280: errx(1, "port number %s: %s", errstr, n);
1281: lo = strtonum(p, 1, PORT_MAX, &errstr);
1282: if (errstr)
1283: errx(1, "port number %s: %s", errstr, p);
1.21 ericj 1284:
1285: if (lo > hi) {
1286: cp = hi;
1287: hi = lo;
1288: lo = cp;
1289: }
1290:
1.67 jmc 1291: /* Load ports sequentially. */
1.21 ericj 1292: for (cp = lo; cp <= hi; cp++) {
1.55 fgsch 1293: portlist[x] = calloc(1, PORT_MAX_LEN);
1294: if (portlist[x] == NULL)
1295: err(1, NULL);
1296: snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1.21 ericj 1297: x++;
1298: }
1299:
1.67 jmc 1300: /* Randomly swap ports. */
1.21 ericj 1301: if (rflag) {
1302: int y;
1303: char *c;
1304:
1305: for (x = 0; x <= (hi - lo); x++) {
1306: y = (arc4random() & 0xFFFF) % (hi - lo);
1307: c = portlist[x];
1308: portlist[x] = portlist[y];
1309: portlist[y] = c;
1.6 deraadt 1310: }
1.11 ericj 1311: }
1.21 ericj 1312: } else {
1.88 ray 1313: hi = strtonum(p, 1, PORT_MAX, &errstr);
1314: if (errstr)
1315: errx(1, "port number %s: %s", errstr, p);
1.96 nicm 1316: portlist[0] = strdup(p);
1.55 fgsch 1317: if (portlist[0] == NULL)
1318: err(1, NULL);
1.11 ericj 1319: }
1.13 ericj 1320: }
1321:
1322: /*
1.21 ericj 1323: * udptest()
1324: * Do a few writes to see if the UDP port is there.
1.105 lum 1325: * Fails once PF state table is full.
1.13 ericj 1326: */
1.21 ericj 1327: int
1.37 jakob 1328: udptest(int s)
1.13 ericj 1329: {
1.74 deraadt 1330: int i, ret;
1.13 ericj 1331:
1.52 vincent 1332: for (i = 0; i <= 3; i++) {
1.74 deraadt 1333: if (write(s, "X", 1) == 1)
1.21 ericj 1334: ret = 1;
1.14 ericj 1335: else
1.21 ericj 1336: ret = -1;
1.14 ericj 1337: }
1.21 ericj 1338: return (ret);
1.81 marius 1339: }
1340:
1.84 dtucker 1341: void
1.127 jca 1342: set_common_sockopts(int s, int af)
1.81 marius 1343: {
1344: int x = 1;
1345:
1346: if (Sflag) {
1347: if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1348: &x, sizeof(x)) == -1)
1349: err(1, NULL);
1350: }
1351: if (Dflag) {
1352: if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1353: &x, sizeof(x)) == -1)
1354: err(1, NULL);
1355: }
1.83 dtucker 1356: if (Tflag != -1) {
1.127 jca 1357: int proto, option;
1358:
1359: if (af == AF_INET6) {
1360: proto = IPPROTO_IPV6;
1361: option = IPV6_TCLASS;
1362: } else {
1363: proto = IPPROTO_IP;
1364: option = IP_TOS;
1365: }
1366:
1367: if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1.83 dtucker 1368: err(1, "set IP ToS");
1369: }
1.90 djm 1370: if (Iflag) {
1371: if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1372: &Iflag, sizeof(Iflag)) == -1)
1373: err(1, "set TCP receive buffer size");
1374: }
1375: if (Oflag) {
1376: if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1377: &Oflag, sizeof(Oflag)) == -1)
1378: err(1, "set TCP send buffer size");
1379: }
1.83 dtucker 1380: }
1381:
1382: int
1.102 haesbaer 1383: map_tos(char *s, int *val)
1.83 dtucker 1384: {
1.102 haesbaer 1385: /* DiffServ Codepoints and other TOS mappings */
1386: const struct toskeywords {
1387: const char *keyword;
1388: int val;
1389: } *t, toskeywords[] = {
1390: { "af11", IPTOS_DSCP_AF11 },
1391: { "af12", IPTOS_DSCP_AF12 },
1392: { "af13", IPTOS_DSCP_AF13 },
1393: { "af21", IPTOS_DSCP_AF21 },
1394: { "af22", IPTOS_DSCP_AF22 },
1395: { "af23", IPTOS_DSCP_AF23 },
1396: { "af31", IPTOS_DSCP_AF31 },
1397: { "af32", IPTOS_DSCP_AF32 },
1398: { "af33", IPTOS_DSCP_AF33 },
1399: { "af41", IPTOS_DSCP_AF41 },
1400: { "af42", IPTOS_DSCP_AF42 },
1401: { "af43", IPTOS_DSCP_AF43 },
1402: { "critical", IPTOS_PREC_CRITIC_ECP },
1403: { "cs0", IPTOS_DSCP_CS0 },
1404: { "cs1", IPTOS_DSCP_CS1 },
1405: { "cs2", IPTOS_DSCP_CS2 },
1406: { "cs3", IPTOS_DSCP_CS3 },
1407: { "cs4", IPTOS_DSCP_CS4 },
1408: { "cs5", IPTOS_DSCP_CS5 },
1409: { "cs6", IPTOS_DSCP_CS6 },
1410: { "cs7", IPTOS_DSCP_CS7 },
1411: { "ef", IPTOS_DSCP_EF },
1412: { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1413: { "lowdelay", IPTOS_LOWDELAY },
1414: { "netcontrol", IPTOS_PREC_NETCONTROL },
1415: { "reliability", IPTOS_RELIABILITY },
1416: { "throughput", IPTOS_THROUGHPUT },
1.134 deraadt 1417: { NULL, -1 },
1.102 haesbaer 1418: };
1419:
1420: for (t = toskeywords; t->keyword != NULL; t++) {
1421: if (strcmp(s, t->keyword) == 0) {
1422: *val = t->val;
1423: return (1);
1424: }
1425: }
1.83 dtucker 1426:
1.102 haesbaer 1427: return (0);
1.108 haesbaer 1428: }
1429:
1.133 beck 1430: int
1431: map_tls(char *s, int *val)
1432: {
1433: const struct tlskeywords {
1434: const char *keyword;
1435: int val;
1436: } *t, tlskeywords[] = {
1437: { "tlslegacy", TLS_LEGACY },
1438: { "noverify", TLS_NOVERIFY },
1439: { "noname", TLS_NONAME },
1440: { "clientcert", TLS_CCERT},
1.134 deraadt 1441: { NULL, -1 },
1.133 beck 1442: };
1443:
1444: for (t = tlskeywords; t->keyword != NULL; t++) {
1445: if (strcmp(s, t->keyword) == 0) {
1446: *val |= t->val;
1447: return (1);
1448: }
1449: }
1450: return (0);
1451: }
1452:
1453: void
1454: report_tls(struct tls * tls_ctx, char * host, char *tls_expectname)
1455: {
1456: char *subject = NULL, *issuer = NULL;
1457: if (tls_peer_cert_subject(tls_ctx, &subject) == -1)
1458: errx(1, "unable to get certificate subject");
1459: if (tls_peer_cert_issuer(tls_ctx, &issuer) == -1)
1460: errx(1, "unable to get certificate issuer");
1461: fprintf(stderr, "TLS handshake completed with %s\n", host);
1462: fprintf(stderr, "Peer name %s\n",
1463: tls_expectname ? tls_expectname : host);
1464: if (subject)
1465: fprintf(stderr, "Subject: %s\n", subject);
1466: if (issuer)
1467: fprintf(stderr, "Issuer: %s\n", issuer);
1468: if (tls_peerhash)
1469: fprintf(stderr, "Cert Hash: %s\n", tls_peerhash);
1470: free(subject);
1471: free(issuer);
1472: }
1.108 haesbaer 1473: void
1474: report_connect(const struct sockaddr *sa, socklen_t salen)
1475: {
1476: char remote_host[NI_MAXHOST];
1477: char remote_port[NI_MAXSERV];
1478: int herr;
1479: int flags = NI_NUMERICSERV;
1.134 deraadt 1480:
1.108 haesbaer 1481: if (nflag)
1482: flags |= NI_NUMERICHOST;
1.134 deraadt 1483:
1.108 haesbaer 1484: if ((herr = getnameinfo(sa, salen,
1485: remote_host, sizeof(remote_host),
1486: remote_port, sizeof(remote_port),
1487: flags)) != 0) {
1488: if (herr == EAI_SYSTEM)
1489: err(1, "getnameinfo");
1490: else
1491: errx(1, "getnameinfo: %s", gai_strerror(herr));
1492: }
1.134 deraadt 1493:
1.108 haesbaer 1494: fprintf(stderr,
1495: "Connection from %s %s "
1496: "received!\n", remote_host, remote_port);
1.7 deraadt 1497: }
1.1 deraadt 1498:
1.11 ericj 1499: void
1.58 deraadt 1500: help(void)
1.1 deraadt 1501: {
1.21 ericj 1502: usage(0);
1503: fprintf(stderr, "\tCommand Summary:\n\
1504: \t-4 Use IPv4\n\
1505: \t-6 Use IPv6\n\
1.135 jmc 1506: \t-C certfile Public key file\n\
1507: \t-c Use TLS\n\
1.73 markus 1508: \t-D Enable the debug socket option\n\
1.69 tedu 1509: \t-d Detach from stdin\n\
1.135 jmc 1510: \t-e name\t Required name in peer certificate\n\
1.114 jmc 1511: \t-F Pass socket fd\n\
1.135 jmc 1512: \t-H hash\t Hash string of peer certificate\n\
1.21 ericj 1513: \t-h This help text\n\
1.90 djm 1514: \t-I length TCP receive buffer length\n\
1.135 jmc 1515: \t-i interval Delay interval for lines sent, ports scanned\n\
1516: \t-K keyfile Private key file\n\
1.21 ericj 1517: \t-k Keep inbound sockets open for multiple connects\n\
1518: \t-l Listen mode, for inbound connects\n\
1.111 sthen 1519: \t-N Shutdown the network socket after EOF on stdin\n\
1.22 jasoni 1520: \t-n Suppress name/port resolutions\n\
1.90 djm 1521: \t-O length TCP send buffer length\n\
1.86 djm 1522: \t-P proxyuser\tUsername for proxy authentication\n\
1.36 jakob 1523: \t-p port\t Specify local port for remote connects\n\
1.135 jmc 1524: \t-R CAfile CA bundle\n\
1.21 ericj 1525: \t-r Randomize remote ports\n\
1.67 jmc 1526: \t-S Enable the TCP MD5 signature option\n\
1.135 jmc 1527: \t-s source Local source address\n\
1528: \t-T keyword TOS value or TLS options\n\
1.21 ericj 1529: \t-t Answer TELNET negotiation\n\
1.67 jmc 1530: \t-U Use UNIX domain socket\n\
1.21 ericj 1531: \t-u UDP mode\n\
1.98 guenther 1532: \t-V rtable Specify alternate routing table\n\
1.21 ericj 1533: \t-v Verbose\n\
1.135 jmc 1534: \t-w timeout Timeout for connects and final net reads\n\
1.75 djm 1535: \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1536: \t-x addr[:port]\tSpecify proxy address and port\n\
1.21 ericj 1537: \t-z Zero-I/O mode [used for scanning]\n\
1538: Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1539: exit(1);
1.11 ericj 1540: }
1541:
1542: void
1.37 jakob 1543: usage(int ret)
1.11 ericj 1544: {
1.92 sobrado 1545: fprintf(stderr,
1.135 jmc 1546: "usage: nc [-46cDdFhklNnrStUuvz] [-C certfile] [-e name] "
1547: "[-H hash] [-I length]\n"
1548: "\t [-i interval] [-K keyfile] [-O length] [-P proxy_username]\n"
1549: "\t [-p source_port] [-R CAfile] [-s source] "
1550: "[-T keyword] [-V rtable]\n"
1551: "\t [-w timeout] [-X proxy_protocol] [-x proxy_address[:port]]\n"
1.133 beck 1552: "\t [destination] [port]\n");
1.21 ericj 1553: if (ret)
1554: exit(1);
1.7 deraadt 1555: }