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