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