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