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