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