Annotation of src/usr.bin/nc/netcat.c, Revision 1.114
1.114 ! jmc 1: /* $OpenBSD: netcat.c,v 1.113 2013/08/20 16:22:09 djm Exp $ */
1.21 ericj 2: /*
3: * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
1.7 deraadt 4: *
1.21 ericj 5: * Redistribution and use in source and binary forms, with or without
6: * modification, are permitted provided that the following conditions
7: * are met:
1.7 deraadt 8: *
1.21 ericj 9: * 1. Redistributions of source code must retain the above copyright
10: * notice, this list of conditions and the following disclaimer.
11: * 2. Redistributions in binary form must reproduce the above copyright
12: * notice, this list of conditions and the following disclaimer in the
13: * documentation and/or other materials provided with the distribution.
14: * 3. The name of the author may not be used to endorse or promote products
15: * derived from this software without specific prior written permission.
1.7 deraadt 16: *
1.21 ericj 17: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27: */
1.1 deraadt 28:
1.24 ericj 29: /*
30: * Re-written nc(1) for OpenBSD. Original implementation by
1.21 ericj 31: * *Hobbit* <hobbit@avian.org>.
32: */
1.1 deraadt 33:
1.7 deraadt 34: #include <sys/types.h>
1.21 ericj 35: #include <sys/socket.h>
1.7 deraadt 36: #include <sys/time.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.83 dtucker 41: #include <netinet/in_systm.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.21 ericj 48: #include <netdb.h>
49: #include <poll.h>
1.13 ericj 50: #include <stdarg.h>
1.21 ericj 51: #include <stdio.h>
1.1 deraadt 52: #include <stdlib.h>
1.21 ericj 53: #include <string.h>
1.5 art 54: #include <unistd.h>
1.42 ericj 55: #include <fcntl.h>
1.85 millert 56: #include <limits.h>
1.79 avsm 57: #include "atomicio.h"
1.51 vincent 58:
59: #ifndef SUN_LEN
60: #define SUN_LEN(su) \
61: (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
62: #endif
1.1 deraadt 63:
1.55 fgsch 64: #define PORT_MAX 65535
65: #define PORT_MAX_LEN 6
1.99 jeremy 66: #define UNIX_DG_TMP_SOCKET_SIZE 19
1.31 ericj 67:
1.21 ericj 68: /* Command Line Options */
1.68 tedu 69: int dflag; /* detached, no stdin */
1.113 djm 70: int Fflag; /* fdpass sock to stdout */
1.88 ray 71: unsigned int iflag; /* Interval Flag */
1.21 ericj 72: int kflag; /* More than one connect */
73: int lflag; /* Bind to local port */
1.111 sthen 74: int Nflag; /* shutdown() network socket */
1.67 jmc 75: int nflag; /* Don't do name look up */
1.86 djm 76: char *Pflag; /* Proxy username */
1.21 ericj 77: char *pflag; /* Localport flag */
78: int rflag; /* Random ports flag */
79: char *sflag; /* Source Address */
80: int tflag; /* Telnet Emulation */
81: int uflag; /* UDP - Default to TCP */
82: int vflag; /* Verbosity */
1.34 jakob 83: int xflag; /* Socks proxy */
1.21 ericj 84: int zflag; /* Port Scan Flag */
1.73 markus 85: int Dflag; /* sodebug */
1.90 djm 86: int Iflag; /* TCP receive buffer size */
87: int Oflag; /* TCP send buffer size */
1.65 markus 88: int Sflag; /* TCP MD5 signature option */
1.83 dtucker 89: int Tflag = -1; /* IP Type of Service */
1.98 guenther 90: u_int rtableid;
1.21 ericj 91:
1.49 hugh 92: int timeout = -1;
1.21 ericj 93: int family = AF_UNSPEC;
1.63 miod 94: char *portlist[PORT_MAX+1];
1.99 jeremy 95: char *unix_dg_tmp_socket;
1.21 ericj 96:
1.40 millert 97: void atelnet(int, unsigned char *, unsigned int);
98: void build_ports(char *);
99: void help(void);
100: int local_listen(char *, char *, struct addrinfo);
101: void readwrite(int);
1.113 djm 102: void fdpass(int nfd) __attribute__((noreturn));
1.77 otto 103: int remote_connect(const char *, const char *, struct addrinfo);
1.103 fgsch 104: int timeout_connect(int, const struct sockaddr *, socklen_t);
1.86 djm 105: int socks_connect(const char *, const char *, struct addrinfo,
106: const char *, const char *, struct addrinfo, int, const char *);
1.40 millert 107: int udptest(int);
1.99 jeremy 108: int unix_bind(char *);
1.42 ericj 109: int unix_connect(char *);
110: int unix_listen(char *);
1.84 dtucker 111: void set_common_sockopts(int);
1.102 haesbaer 112: int map_tos(char *, int *);
1.108 haesbaer 113: void report_connect(const struct sockaddr *, socklen_t);
1.40 millert 114: void usage(int);
1.1 deraadt 115:
1.21 ericj 116: int
1.37 jakob 117: main(int argc, char *argv[])
1.21 ericj 118: {
1.46 markus 119: int ch, s, ret, socksv;
1.88 ray 120: char *host, *uport;
1.21 ericj 121: struct addrinfo hints;
1.29 smart 122: struct servent *sv;
1.21 ericj 123: socklen_t len;
1.76 hshoexer 124: struct sockaddr_storage cliaddr;
1.34 jakob 125: char *proxy;
1.88 ray 126: const char *errstr, *proxyhost = "", *proxyport = NULL;
1.34 jakob 127: struct addrinfo proxyhints;
1.99 jeremy 128: char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
1.11 ericj 129:
1.29 smart 130: ret = 1;
131: s = 0;
1.46 markus 132: socksv = 5;
1.29 smart 133: host = NULL;
134: uport = NULL;
135: sv = NULL;
136:
1.80 mcbride 137: while ((ch = getopt(argc, argv,
1.113 djm 138: "46DdFhI:i:klNnO:P:p:rSs:tT:UuV:vw:X:x:z")) != -1) {
1.21 ericj 139: switch (ch) {
140: case '4':
141: family = AF_INET;
142: break;
143: case '6':
144: family = AF_INET6;
145: break;
1.42 ericj 146: case 'U':
147: family = AF_UNIX;
148: break;
1.46 markus 149: case 'X':
1.75 djm 150: if (strcasecmp(optarg, "connect") == 0)
151: socksv = -1; /* HTTP proxy CONNECT */
152: else if (strcmp(optarg, "4") == 0)
153: socksv = 4; /* SOCKS v.4 */
154: else if (strcmp(optarg, "5") == 0)
155: socksv = 5; /* SOCKS v.5 */
156: else
157: errx(1, "unsupported proxy protocol");
1.46 markus 158: break;
1.68 tedu 159: case 'd':
160: dflag = 1;
161: break;
1.113 djm 162: case 'F':
163: Fflag = 1;
164: break;
1.21 ericj 165: case 'h':
166: help();
167: break;
168: case 'i':
1.88 ray 169: iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
170: if (errstr)
171: errx(1, "interval %s: %s", errstr, optarg);
1.21 ericj 172: break;
173: case 'k':
174: kflag = 1;
175: break;
176: case 'l':
177: lflag = 1;
178: break;
1.111 sthen 179: case 'N':
180: Nflag = 1;
181: break;
1.21 ericj 182: case 'n':
183: nflag = 1;
184: break;
1.86 djm 185: case 'P':
186: Pflag = optarg;
187: break;
1.21 ericj 188: case 'p':
189: pflag = optarg;
190: break;
191: case 'r':
192: rflag = 1;
193: break;
194: case 's':
195: sflag = optarg;
196: break;
197: case 't':
198: tflag = 1;
199: break;
200: case 'u':
201: uflag = 1;
202: break;
1.93 claudio 203: case 'V':
1.98 guenther 204: rtableid = (unsigned int)strtonum(optarg, 0,
1.93 claudio 205: RT_TABLEID_MAX, &errstr);
206: if (errstr)
1.98 guenther 207: errx(1, "rtable %s: %s", errstr, optarg);
1.93 claudio 208: break;
1.21 ericj 209: case 'v':
210: vflag = 1;
211: break;
1.70 deraadt 212: case 'w':
1.88 ray 213: timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
214: if (errstr)
215: errx(1, "timeout %s: %s", errstr, optarg);
1.49 hugh 216: timeout *= 1000;
1.21 ericj 217: break;
1.34 jakob 218: case 'x':
219: xflag = 1;
1.64 deraadt 220: if ((proxy = strdup(optarg)) == NULL)
221: err(1, NULL);
1.34 jakob 222: break;
1.21 ericj 223: case 'z':
224: zflag = 1;
225: break;
1.73 markus 226: case 'D':
227: Dflag = 1;
228: break;
1.90 djm 229: case 'I':
230: Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
231: if (errstr != NULL)
232: errx(1, "TCP receive window %s: %s",
233: errstr, optarg);
234: break;
235: case 'O':
236: Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
237: if (errstr != NULL)
238: errx(1, "TCP send window %s: %s",
239: errstr, optarg);
240: break;
1.65 markus 241: case 'S':
242: Sflag = 1;
243: break;
1.83 dtucker 244: case 'T':
1.102 haesbaer 245: errstr = NULL;
246: errno = 0;
247: if (map_tos(optarg, &Tflag))
248: break;
249: if (strlen(optarg) > 1 && optarg[0] == '0' &&
250: optarg[1] == 'x')
251: Tflag = (int)strtol(optarg, NULL, 16);
252: else
253: Tflag = (int)strtonum(optarg, 0, 255,
254: &errstr);
255: if (Tflag < 0 || Tflag > 255 || errstr || errno)
256: errx(1, "illegal tos value %s", optarg);
1.83 dtucker 257: break;
1.21 ericj 258: default:
259: usage(1);
260: }
261: }
262: argc -= optind;
263: argv += optind;
1.11 ericj 264:
1.21 ericj 265: /* Cruft to make sure options are clean, and used properly. */
1.42 ericj 266: if (argv[0] && !argv[1] && family == AF_UNIX) {
267: host = argv[0];
268: uport = NULL;
269: } else if (argv[0] && !argv[1]) {
1.21 ericj 270: if (!lflag)
271: usage(1);
272: uport = argv[0];
273: host = NULL;
274: } else if (argv[0] && argv[1]) {
275: host = argv[0];
276: uport = argv[1];
277: } else
278: usage(1);
1.1 deraadt 279:
1.21 ericj 280: if (lflag && sflag)
281: errx(1, "cannot use -s and -l");
282: if (lflag && pflag)
283: errx(1, "cannot use -p and -l");
284: if (lflag && zflag)
1.32 ericj 285: errx(1, "cannot use -z and -l");
1.21 ericj 286: if (!lflag && kflag)
1.32 ericj 287: errx(1, "must use -l with -k");
1.21 ericj 288:
1.99 jeremy 289: /* Get name of temporary socket for unix datagram client */
290: if ((family == AF_UNIX) && uflag && !lflag) {
291: if (sflag) {
292: unix_dg_tmp_socket = sflag;
293: } else {
294: strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
295: UNIX_DG_TMP_SOCKET_SIZE);
296: if (mktemp(unix_dg_tmp_socket_buf) == NULL)
297: err(1, "mktemp");
298: unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
299: }
300: }
301:
1.67 jmc 302: /* Initialize addrinfo structure. */
1.42 ericj 303: if (family != AF_UNIX) {
304: memset(&hints, 0, sizeof(struct addrinfo));
305: hints.ai_family = family;
306: hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
307: hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
308: if (nflag)
309: hints.ai_flags |= AI_NUMERICHOST;
310: }
1.1 deraadt 311:
1.34 jakob 312: if (xflag) {
313: if (uflag)
314: errx(1, "no proxy support for UDP mode");
315:
316: if (lflag)
317: errx(1, "no proxy support for listen");
318:
1.42 ericj 319: if (family == AF_UNIX)
320: errx(1, "no proxy support for unix sockets");
321:
1.34 jakob 322: /* XXX IPv6 transport to proxy would probably work */
323: if (family == AF_INET6)
324: errx(1, "no proxy support for IPv6");
325:
326: if (sflag)
327: errx(1, "no proxy support for local source address");
328:
329: proxyhost = strsep(&proxy, ":");
330: proxyport = proxy;
331:
332: memset(&proxyhints, 0, sizeof(struct addrinfo));
333: proxyhints.ai_family = family;
334: proxyhints.ai_socktype = SOCK_STREAM;
335: proxyhints.ai_protocol = IPPROTO_TCP;
336: if (nflag)
337: proxyhints.ai_flags |= AI_NUMERICHOST;
338: }
339:
1.21 ericj 340: if (lflag) {
341: int connfd;
1.27 ericj 342: ret = 0;
1.1 deraadt 343:
1.99 jeremy 344: if (family == AF_UNIX) {
345: if (uflag)
346: s = unix_bind(host);
347: else
348: s = unix_listen(host);
349: }
1.42 ericj 350:
1.67 jmc 351: /* Allow only one connection at a time, but stay alive. */
1.21 ericj 352: for (;;) {
1.42 ericj 353: if (family != AF_UNIX)
354: s = local_listen(host, uport, hints);
355: if (s < 0)
1.30 smart 356: err(1, NULL);
1.21 ericj 357: /*
1.109 haesbaer 358: * For UDP and -k, don't connect the socket, let it
359: * receive datagrams from multiple socket pairs.
1.21 ericj 360: */
1.109 haesbaer 361: if (uflag && kflag)
362: readwrite(s);
363: /*
364: * For UDP and not -k, we will use recvfrom() initially
365: * to wait for a caller, then use the regular functions
366: * to talk to the caller.
367: */
368: else if (uflag && !kflag) {
1.80 mcbride 369: int rv, plen;
1.97 nicm 370: char buf[16384];
1.21 ericj 371: struct sockaddr_storage z;
372:
373: len = sizeof(z);
1.106 dlg 374: plen = 2048;
1.80 mcbride 375: rv = recvfrom(s, buf, plen, MSG_PEEK,
1.37 jakob 376: (struct sockaddr *)&z, &len);
1.23 ericj 377: if (rv < 0)
1.57 stevesk 378: err(1, "recvfrom");
1.21 ericj 379:
1.37 jakob 380: rv = connect(s, (struct sockaddr *)&z, len);
1.23 ericj 381: if (rv < 0)
1.57 stevesk 382: err(1, "connect");
1.1 deraadt 383:
1.108 haesbaer 384: if (vflag)
385: report_connect((struct sockaddr *)&z, len);
386:
1.99 jeremy 387: readwrite(s);
1.21 ericj 388: } else {
1.78 otto 389: len = sizeof(cliaddr);
1.21 ericj 390: connfd = accept(s, (struct sockaddr *)&cliaddr,
1.37 jakob 391: &len);
1.110 deraadt 392: if (connfd == -1) {
393: /* For now, all errnos are fatal */
394: err(1, "accept");
395: }
1.108 haesbaer 396: if (vflag)
397: report_connect((struct sockaddr *)&cliaddr, len);
398:
1.99 jeremy 399: readwrite(connfd);
400: close(connfd);
1.21 ericj 401: }
1.1 deraadt 402:
1.42 ericj 403: if (family != AF_UNIX)
404: close(s);
1.99 jeremy 405: else if (uflag) {
406: if (connect(s, NULL, 0) < 0)
407: err(1, "connect");
408: }
1.27 ericj 409:
1.21 ericj 410: if (!kflag)
411: break;
1.11 ericj 412: }
1.42 ericj 413: } else if (family == AF_UNIX) {
414: ret = 0;
415:
416: if ((s = unix_connect(host)) > 0 && !zflag) {
417: readwrite(s);
418: close(s);
419: } else
420: ret = 1;
421:
1.99 jeremy 422: if (uflag)
423: unlink(unix_dg_tmp_socket);
1.42 ericj 424: exit(ret);
425:
1.21 ericj 426: } else {
427: int i = 0;
1.6 deraadt 428:
1.67 jmc 429: /* Construct the portlist[] array. */
1.21 ericj 430: build_ports(uport);
1.1 deraadt 431:
1.67 jmc 432: /* Cycle through portlist, connecting to each port. */
1.21 ericj 433: for (i = 0; portlist[i] != NULL; i++) {
434: if (s)
435: close(s);
1.34 jakob 436:
437: if (xflag)
438: s = socks_connect(host, portlist[i], hints,
1.86 djm 439: proxyhost, proxyport, proxyhints, socksv,
440: Pflag);
1.34 jakob 441: else
442: s = remote_connect(host, portlist[i], hints);
443:
444: if (s < 0)
1.21 ericj 445: continue;
1.1 deraadt 446:
1.21 ericj 447: ret = 0;
448: if (vflag || zflag) {
1.67 jmc 449: /* For UDP, make sure we are connected. */
1.21 ericj 450: if (uflag) {
1.50 vincent 451: if (udptest(s) == -1) {
1.21 ericj 452: ret = 1;
453: continue;
454: }
455: }
1.1 deraadt 456:
1.67 jmc 457: /* Don't look up port if -n. */
1.21 ericj 458: if (nflag)
459: sv = NULL;
460: else {
461: sv = getservbyport(
1.37 jakob 462: ntohs(atoi(portlist[i])),
463: uflag ? "udp" : "tcp");
1.21 ericj 464: }
1.50 vincent 465:
1.94 mpf 466: fprintf(stderr,
467: "Connection to %s %s port [%s/%s] "
468: "succeeded!\n", host, portlist[i],
469: uflag ? "udp" : "tcp",
1.37 jakob 470: sv ? sv->s_name : "*");
1.21 ericj 471: }
1.113 djm 472: if (Fflag)
473: fdpass(s);
474: else if (!zflag)
1.21 ericj 475: readwrite(s);
1.7 deraadt 476: }
1.11 ericj 477: }
1.1 deraadt 478:
1.21 ericj 479: if (s)
480: close(s);
481:
482: exit(ret);
1.7 deraadt 483: }
1.1 deraadt 484:
1.11 ericj 485: /*
1.99 jeremy 486: * unix_bind()
487: * Returns a unix socket bound to the given path
1.42 ericj 488: */
489: int
1.99 jeremy 490: unix_bind(char *path)
1.42 ericj 491: {
492: struct sockaddr_un sun;
493: int s;
494:
1.99 jeremy 495: /* Create unix domain socket. */
496: if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
497: 0)) < 0)
1.50 vincent 498: return (-1);
1.42 ericj 499:
500: memset(&sun, 0, sizeof(struct sockaddr_un));
501: sun.sun_family = AF_UNIX;
1.60 avsm 502:
503: if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
504: sizeof(sun.sun_path)) {
505: close(s);
506: errno = ENAMETOOLONG;
507: return (-1);
508: }
1.99 jeremy 509:
510: if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.50 vincent 511: close(s);
512: return (-1);
1.42 ericj 513: }
514: return (s);
515: }
516:
517: /*
1.99 jeremy 518: * unix_connect()
519: * Returns a socket connected to a local unix socket. Returns -1 on failure.
1.42 ericj 520: */
521: int
1.99 jeremy 522: unix_connect(char *path)
1.42 ericj 523: {
524: struct sockaddr_un sun;
525: int s;
526:
1.99 jeremy 527: if (uflag) {
528: if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
529: return (-1);
530: } else {
531: if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
532: return (-1);
533: }
1.112 okan 534: (void)fcntl(s, F_SETFD, FD_CLOEXEC);
1.42 ericj 535:
1.60 avsm 536: memset(&sun, 0, sizeof(struct sockaddr_un));
1.42 ericj 537: sun.sun_family = AF_UNIX;
1.60 avsm 538:
539: if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
540: sizeof(sun.sun_path)) {
541: close(s);
542: errno = ENAMETOOLONG;
543: return (-1);
544: }
1.99 jeremy 545: if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
1.42 ericj 546: close(s);
547: return (-1);
548: }
1.99 jeremy 549: return (s);
550:
551: }
552:
553: /*
554: * unix_listen()
555: * Create a unix domain socket, and listen on it.
556: */
557: int
558: unix_listen(char *path)
559: {
560: int s;
561: if ((s = unix_bind(path)) < 0)
562: return (-1);
1.42 ericj 563:
564: if (listen(s, 5) < 0) {
565: close(s);
566: return (-1);
567: }
568: return (s);
569: }
570:
571: /*
1.21 ericj 572: * remote_connect()
1.67 jmc 573: * Returns a socket connected to a remote host. Properly binds to a local
574: * port or source address if needed. Returns -1 on failure.
1.11 ericj 575: */
1.21 ericj 576: int
1.77 otto 577: remote_connect(const char *host, const char *port, struct addrinfo hints)
1.21 ericj 578: {
579: struct addrinfo *res, *res0;
1.91 markus 580: int s, error, on = 1;
1.21 ericj 581:
582: if ((error = getaddrinfo(host, port, &hints, &res)))
1.56 stevesk 583: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21 ericj 584:
585: res0 = res;
586: do {
587: if ((s = socket(res0->ai_family, res0->ai_socktype,
1.37 jakob 588: res0->ai_protocol)) < 0)
1.21 ericj 589: continue;
590:
1.98 guenther 591: if (rtableid) {
1.101 mikeb 592: if (setsockopt(s, SOL_SOCKET, SO_RTABLE, &rtableid,
1.98 guenther 593: sizeof(rtableid)) == -1)
594: err(1, "setsockopt SO_RTABLE");
1.93 claudio 595: }
596:
1.67 jmc 597: /* Bind to a local port or source address if specified. */
1.21 ericj 598: if (sflag || pflag) {
599: struct addrinfo ahints, *ares;
1.6 deraadt 600:
1.91 markus 601: /* try SO_BINDANY, but don't insist */
602: setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
1.21 ericj 603: memset(&ahints, 0, sizeof(struct addrinfo));
604: ahints.ai_family = res0->ai_family;
605: ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
606: ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
1.25 ericj 607: ahints.ai_flags = AI_PASSIVE;
1.38 jakob 608: if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
1.56 stevesk 609: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21 ericj 610:
611: if (bind(s, (struct sockaddr *)ares->ai_addr,
1.62 millert 612: ares->ai_addrlen) < 0)
1.21 ericj 613: errx(1, "bind failed: %s", strerror(errno));
614: freeaddrinfo(ares);
1.6 deraadt 615: }
1.81 marius 616:
617: set_common_sockopts(s);
1.6 deraadt 618:
1.103 fgsch 619: if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
1.6 deraadt 620: break;
1.71 mcbride 621: else if (vflag)
622: warn("connect to %s port %s (%s) failed", host, port,
623: uflag ? "udp" : "tcp");
1.34 jakob 624:
1.21 ericj 625: close(s);
626: s = -1;
627: } while ((res0 = res0->ai_next) != NULL);
628:
629: freeaddrinfo(res);
1.1 deraadt 630:
1.21 ericj 631: return (s);
1.103 fgsch 632: }
633:
634: int
635: timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
636: {
637: struct pollfd pfd;
638: socklen_t optlen;
639: int flags, optval;
640: int ret;
641:
642: if (timeout != -1) {
643: flags = fcntl(s, F_GETFL, 0);
644: if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
645: err(1, "set non-blocking mode");
646: }
647:
648: if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
649: pfd.fd = s;
650: pfd.events = POLLOUT;
651: if ((ret = poll(&pfd, 1, timeout)) == 1) {
652: optlen = sizeof(optval);
653: if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
654: &optval, &optlen)) == 0) {
655: errno = optval;
656: ret = optval == 0 ? 0 : -1;
657: }
658: } else if (ret == 0) {
659: errno = ETIMEDOUT;
660: ret = -1;
661: } else
662: err(1, "poll failed");
663: }
664:
665: if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
666: err(1, "restoring flags");
667:
668: return (ret);
1.7 deraadt 669: }
1.1 deraadt 670:
1.11 ericj 671: /*
1.21 ericj 672: * local_listen()
1.67 jmc 673: * Returns a socket listening on a local port, binds to specified source
674: * address. Returns -1 on failure.
1.11 ericj 675: */
1.21 ericj 676: int
1.37 jakob 677: local_listen(char *host, char *port, struct addrinfo hints)
1.21 ericj 678: {
679: struct addrinfo *res, *res0;
680: int s, ret, x = 1;
681: int error;
1.6 deraadt 682:
1.67 jmc 683: /* Allow nodename to be null. */
1.21 ericj 684: hints.ai_flags |= AI_PASSIVE;
1.7 deraadt 685:
1.21 ericj 686: /*
687: * In the case of binding to a wildcard address
688: * default to binding to an ipv4 address.
689: */
690: if (host == NULL && hints.ai_family == AF_UNSPEC)
691: hints.ai_family = AF_INET;
1.1 deraadt 692:
1.21 ericj 693: if ((error = getaddrinfo(host, port, &hints, &res)))
1.70 deraadt 694: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.14 ericj 695:
1.21 ericj 696: res0 = res;
697: do {
698: if ((s = socket(res0->ai_family, res0->ai_socktype,
1.82 marius 699: res0->ai_protocol)) < 0)
1.21 ericj 700: continue;
1.1 deraadt 701:
1.98 guenther 702: if (rtableid) {
703: if (setsockopt(s, IPPROTO_IP, SO_RTABLE, &rtableid,
704: sizeof(rtableid)) == -1)
705: err(1, "setsockopt SO_RTABLE");
1.93 claudio 706: }
707:
1.21 ericj 708: ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
709: if (ret == -1)
1.30 smart 710: err(1, NULL);
1.81 marius 711:
712: set_common_sockopts(s);
1.1 deraadt 713:
1.21 ericj 714: if (bind(s, (struct sockaddr *)res0->ai_addr,
1.37 jakob 715: res0->ai_addrlen) == 0)
1.21 ericj 716: break;
1.1 deraadt 717:
1.21 ericj 718: close(s);
719: s = -1;
720: } while ((res0 = res0->ai_next) != NULL);
1.1 deraadt 721:
1.47 ericj 722: if (!uflag && s != -1) {
1.21 ericj 723: if (listen(s, 1) < 0)
1.57 stevesk 724: err(1, "listen");
1.12 ericj 725: }
1.1 deraadt 726:
1.21 ericj 727: freeaddrinfo(res);
1.1 deraadt 728:
1.21 ericj 729: return (s);
1.7 deraadt 730: }
731:
1.11 ericj 732: /*
1.21 ericj 733: * readwrite()
734: * Loop that polls on the network file descriptor and stdin.
1.11 ericj 735: */
1.21 ericj 736: void
1.37 jakob 737: readwrite(int nfd)
1.6 deraadt 738: {
1.52 vincent 739: struct pollfd pfd[2];
1.97 nicm 740: unsigned char buf[16384];
1.79 avsm 741: int n, wfd = fileno(stdin);
1.21 ericj 742: int lfd = fileno(stdout);
1.80 mcbride 743: int plen;
744:
1.106 dlg 745: plen = 2048;
1.21 ericj 746:
747: /* Setup Network FD */
748: pfd[0].fd = nfd;
749: pfd[0].events = POLLIN;
750:
1.67 jmc 751: /* Set up STDIN FD. */
1.21 ericj 752: pfd[1].fd = wfd;
753: pfd[1].events = POLLIN;
754:
1.54 aaron 755: while (pfd[0].fd != -1) {
1.21 ericj 756: if (iflag)
757: sleep(iflag);
758:
1.68 tedu 759: if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
1.21 ericj 760: close(nfd);
1.52 vincent 761: err(1, "Polling Error");
1.21 ericj 762: }
1.49 hugh 763:
764: if (n == 0)
765: return;
1.21 ericj 766:
767: if (pfd[0].revents & POLLIN) {
1.80 mcbride 768: if ((n = read(nfd, buf, plen)) < 0)
1.21 ericj 769: return;
1.52 vincent 770: else if (n == 0) {
771: shutdown(nfd, SHUT_RD);
772: pfd[0].fd = -1;
773: pfd[0].events = 0;
1.21 ericj 774: } else {
775: if (tflag)
776: atelnet(nfd, buf, n);
1.79 avsm 777: if (atomicio(vwrite, lfd, buf, n) != n)
1.21 ericj 778: return;
1.6 deraadt 779: }
1.21 ericj 780: }
781:
1.68 tedu 782: if (!dflag && pfd[1].revents & POLLIN) {
1.80 mcbride 783: if ((n = read(wfd, buf, plen)) < 0)
1.21 ericj 784: return;
1.52 vincent 785: else if (n == 0) {
1.111 sthen 786: if (Nflag)
787: shutdown(nfd, SHUT_WR);
1.52 vincent 788: pfd[1].fd = -1;
789: pfd[1].events = 0;
790: } else {
1.79 avsm 791: if (atomicio(vwrite, nfd, buf, n) != n)
1.21 ericj 792: return;
1.50 vincent 793: }
1.21 ericj 794: }
1.11 ericj 795: }
1.113 djm 796: }
797:
798: /*
799: * fdpass()
800: * Pass the connected file descriptor to stdout and exit.
801: */
802: void
803: fdpass(int nfd)
804: {
805: struct msghdr mh;
806: union {
807: struct cmsghdr hdr;
808: char buf[CMSG_SPACE(sizeof(int))];
809: } cmsgbuf;
810: struct cmsghdr *cmsg;
811: struct iovec iov;
812: char c = '\0';
813: ssize_t r;
814: struct pollfd pfd;
815:
816: /* Avoid obvious stupidity */
817: if (isatty(STDOUT_FILENO))
818: errx(1, "Cannot pass file descriptor to tty");
819:
820: bzero(&mh, sizeof(mh));
821: bzero(&cmsgbuf, sizeof(cmsgbuf));
822: bzero(&iov, sizeof(iov));
823: bzero(&pfd, sizeof(pfd));
824:
825: mh.msg_control = (caddr_t)&cmsgbuf.buf;
826: mh.msg_controllen = sizeof(cmsgbuf.buf);
827: cmsg = CMSG_FIRSTHDR(&mh);
828: cmsg->cmsg_len = CMSG_LEN(sizeof(int));
829: cmsg->cmsg_level = SOL_SOCKET;
830: cmsg->cmsg_type = SCM_RIGHTS;
831: *(int *)CMSG_DATA(cmsg) = nfd;
832:
833: iov.iov_base = &c;
834: iov.iov_len = 1;
835: mh.msg_iov = &iov;
836: mh.msg_iovlen = 1;
837:
838: bzero(&pfd, sizeof(pfd));
839: pfd.fd = STDOUT_FILENO;
840: for (;;) {
841: r = sendmsg(STDOUT_FILENO, &mh, 0);
842: if (r == -1) {
843: if (errno == EAGAIN || errno == EINTR) {
844: pfd.events = POLLOUT;
845: if (poll(&pfd, 1, -1) == -1)
846: err(1, "poll");
847: continue;
848: }
849: err(1, "sendmsg");
850: } else if (r == -1)
851: errx(1, "sendmsg: unexpected return value %zd", r);
852: else
853: break;
854: }
855: exit(0);
1.7 deraadt 856: }
1.50 vincent 857:
1.67 jmc 858: /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1.21 ericj 859: void
1.37 jakob 860: atelnet(int nfd, unsigned char *buf, unsigned int size)
1.6 deraadt 861: {
1.24 ericj 862: unsigned char *p, *end;
863: unsigned char obuf[4];
864:
1.95 nicm 865: if (size < 3)
866: return;
867: end = buf + size - 2;
1.24 ericj 868:
869: for (p = buf; p < end; p++) {
1.21 ericj 870: if (*p != IAC)
1.95 nicm 871: continue;
1.24 ericj 872:
1.25 ericj 873: obuf[0] = IAC;
1.24 ericj 874: p++;
1.50 vincent 875: if ((*p == WILL) || (*p == WONT))
1.24 ericj 876: obuf[1] = DONT;
1.95 nicm 877: else if ((*p == DO) || (*p == DONT))
1.24 ericj 878: obuf[1] = WONT;
1.95 nicm 879: else
880: continue;
881:
882: p++;
883: obuf[2] = *p;
884: if (atomicio(vwrite, nfd, obuf, 3) != 3)
885: warn("Write Error!");
1.11 ericj 886: }
1.7 deraadt 887: }
888:
1.11 ericj 889: /*
1.21 ericj 890: * build_ports()
1.105 lum 891: * Build an array of ports in portlist[], listing each port
1.67 jmc 892: * that we should try to connect to.
1.11 ericj 893: */
1.21 ericj 894: void
1.37 jakob 895: build_ports(char *p)
1.6 deraadt 896: {
1.88 ray 897: const char *errstr;
898: char *n;
1.21 ericj 899: int hi, lo, cp;
900: int x = 0;
901:
902: if ((n = strchr(p, '-')) != NULL) {
903: *n = '\0';
904: n++;
905:
1.67 jmc 906: /* Make sure the ports are in order: lowest->highest. */
1.88 ray 907: hi = strtonum(n, 1, PORT_MAX, &errstr);
908: if (errstr)
909: errx(1, "port number %s: %s", errstr, n);
910: lo = strtonum(p, 1, PORT_MAX, &errstr);
911: if (errstr)
912: errx(1, "port number %s: %s", errstr, p);
1.21 ericj 913:
914: if (lo > hi) {
915: cp = hi;
916: hi = lo;
917: lo = cp;
918: }
919:
1.67 jmc 920: /* Load ports sequentially. */
1.21 ericj 921: for (cp = lo; cp <= hi; cp++) {
1.55 fgsch 922: portlist[x] = calloc(1, PORT_MAX_LEN);
923: if (portlist[x] == NULL)
924: err(1, NULL);
925: snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1.21 ericj 926: x++;
927: }
928:
1.67 jmc 929: /* Randomly swap ports. */
1.21 ericj 930: if (rflag) {
931: int y;
932: char *c;
933:
934: for (x = 0; x <= (hi - lo); x++) {
935: y = (arc4random() & 0xFFFF) % (hi - lo);
936: c = portlist[x];
937: portlist[x] = portlist[y];
938: portlist[y] = c;
1.6 deraadt 939: }
1.11 ericj 940: }
1.21 ericj 941: } else {
1.88 ray 942: hi = strtonum(p, 1, PORT_MAX, &errstr);
943: if (errstr)
944: errx(1, "port number %s: %s", errstr, p);
1.96 nicm 945: portlist[0] = strdup(p);
1.55 fgsch 946: if (portlist[0] == NULL)
947: err(1, NULL);
1.11 ericj 948: }
1.13 ericj 949: }
950:
951: /*
1.21 ericj 952: * udptest()
953: * Do a few writes to see if the UDP port is there.
1.105 lum 954: * Fails once PF state table is full.
1.13 ericj 955: */
1.21 ericj 956: int
1.37 jakob 957: udptest(int s)
1.13 ericj 958: {
1.74 deraadt 959: int i, ret;
1.13 ericj 960:
1.52 vincent 961: for (i = 0; i <= 3; i++) {
1.74 deraadt 962: if (write(s, "X", 1) == 1)
1.21 ericj 963: ret = 1;
1.14 ericj 964: else
1.21 ericj 965: ret = -1;
1.14 ericj 966: }
1.21 ericj 967: return (ret);
1.81 marius 968: }
969:
1.84 dtucker 970: void
1.81 marius 971: set_common_sockopts(int s)
972: {
973: int x = 1;
974:
975: if (Sflag) {
976: if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
977: &x, sizeof(x)) == -1)
978: err(1, NULL);
979: }
980: if (Dflag) {
981: if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
982: &x, sizeof(x)) == -1)
983: err(1, NULL);
984: }
1.83 dtucker 985: if (Tflag != -1) {
986: if (setsockopt(s, IPPROTO_IP, IP_TOS,
987: &Tflag, sizeof(Tflag)) == -1)
988: err(1, "set IP ToS");
989: }
1.90 djm 990: if (Iflag) {
991: if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
992: &Iflag, sizeof(Iflag)) == -1)
993: err(1, "set TCP receive buffer size");
994: }
995: if (Oflag) {
996: if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
997: &Oflag, sizeof(Oflag)) == -1)
998: err(1, "set TCP send buffer size");
999: }
1.83 dtucker 1000: }
1001:
1002: int
1.102 haesbaer 1003: map_tos(char *s, int *val)
1.83 dtucker 1004: {
1.102 haesbaer 1005: /* DiffServ Codepoints and other TOS mappings */
1006: const struct toskeywords {
1007: const char *keyword;
1008: int val;
1009: } *t, toskeywords[] = {
1010: { "af11", IPTOS_DSCP_AF11 },
1011: { "af12", IPTOS_DSCP_AF12 },
1012: { "af13", IPTOS_DSCP_AF13 },
1013: { "af21", IPTOS_DSCP_AF21 },
1014: { "af22", IPTOS_DSCP_AF22 },
1015: { "af23", IPTOS_DSCP_AF23 },
1016: { "af31", IPTOS_DSCP_AF31 },
1017: { "af32", IPTOS_DSCP_AF32 },
1018: { "af33", IPTOS_DSCP_AF33 },
1019: { "af41", IPTOS_DSCP_AF41 },
1020: { "af42", IPTOS_DSCP_AF42 },
1021: { "af43", IPTOS_DSCP_AF43 },
1022: { "critical", IPTOS_PREC_CRITIC_ECP },
1023: { "cs0", IPTOS_DSCP_CS0 },
1024: { "cs1", IPTOS_DSCP_CS1 },
1025: { "cs2", IPTOS_DSCP_CS2 },
1026: { "cs3", IPTOS_DSCP_CS3 },
1027: { "cs4", IPTOS_DSCP_CS4 },
1028: { "cs5", IPTOS_DSCP_CS5 },
1029: { "cs6", IPTOS_DSCP_CS6 },
1030: { "cs7", IPTOS_DSCP_CS7 },
1031: { "ef", IPTOS_DSCP_EF },
1032: { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1033: { "lowdelay", IPTOS_LOWDELAY },
1034: { "netcontrol", IPTOS_PREC_NETCONTROL },
1035: { "reliability", IPTOS_RELIABILITY },
1036: { "throughput", IPTOS_THROUGHPUT },
1037: { NULL, -1 },
1038: };
1039:
1040: for (t = toskeywords; t->keyword != NULL; t++) {
1041: if (strcmp(s, t->keyword) == 0) {
1042: *val = t->val;
1043: return (1);
1044: }
1045: }
1.83 dtucker 1046:
1.102 haesbaer 1047: return (0);
1.108 haesbaer 1048: }
1049:
1050: void
1051: report_connect(const struct sockaddr *sa, socklen_t salen)
1052: {
1053: char remote_host[NI_MAXHOST];
1054: char remote_port[NI_MAXSERV];
1055: int herr;
1056: int flags = NI_NUMERICSERV;
1057:
1058: if (nflag)
1059: flags |= NI_NUMERICHOST;
1060:
1061: if ((herr = getnameinfo(sa, salen,
1062: remote_host, sizeof(remote_host),
1063: remote_port, sizeof(remote_port),
1064: flags)) != 0) {
1065: if (herr == EAI_SYSTEM)
1066: err(1, "getnameinfo");
1067: else
1068: errx(1, "getnameinfo: %s", gai_strerror(herr));
1069: }
1070:
1071: fprintf(stderr,
1072: "Connection from %s %s "
1073: "received!\n", remote_host, remote_port);
1.7 deraadt 1074: }
1.1 deraadt 1075:
1.11 ericj 1076: void
1.58 deraadt 1077: help(void)
1.1 deraadt 1078: {
1.21 ericj 1079: usage(0);
1080: fprintf(stderr, "\tCommand Summary:\n\
1081: \t-4 Use IPv4\n\
1082: \t-6 Use IPv6\n\
1.73 markus 1083: \t-D Enable the debug socket option\n\
1.69 tedu 1084: \t-d Detach from stdin\n\
1.114 ! jmc 1085: \t-F Pass socket fd\n\
1.21 ericj 1086: \t-h This help text\n\
1.90 djm 1087: \t-I length TCP receive buffer length\n\
1.21 ericj 1088: \t-i secs\t Delay interval for lines sent, ports scanned\n\
1089: \t-k Keep inbound sockets open for multiple connects\n\
1090: \t-l Listen mode, for inbound connects\n\
1.111 sthen 1091: \t-N Shutdown the network socket after EOF on stdin\n\
1.22 jasoni 1092: \t-n Suppress name/port resolutions\n\
1.90 djm 1093: \t-O length TCP send buffer length\n\
1.86 djm 1094: \t-P proxyuser\tUsername for proxy authentication\n\
1.36 jakob 1095: \t-p port\t Specify local port for remote connects\n\
1.21 ericj 1096: \t-r Randomize remote ports\n\
1.67 jmc 1097: \t-S Enable the TCP MD5 signature option\n\
1.21 ericj 1098: \t-s addr\t Local source address\n\
1.102 haesbaer 1099: \t-T toskeyword\tSet IP Type of Service\n\
1.21 ericj 1100: \t-t Answer TELNET negotiation\n\
1.67 jmc 1101: \t-U Use UNIX domain socket\n\
1.21 ericj 1102: \t-u UDP mode\n\
1.98 guenther 1103: \t-V rtable Specify alternate routing table\n\
1.21 ericj 1104: \t-v Verbose\n\
1105: \t-w secs\t Timeout for connects and final net reads\n\
1.75 djm 1106: \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1107: \t-x addr[:port]\tSpecify proxy address and port\n\
1.21 ericj 1108: \t-z Zero-I/O mode [used for scanning]\n\
1109: Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1110: exit(1);
1.11 ericj 1111: }
1112:
1113: void
1.37 jakob 1114: usage(int ret)
1.11 ericj 1115: {
1.92 sobrado 1116: fprintf(stderr,
1.114 ! jmc 1117: "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1.100 jeremy 1118: "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1.98 guenther 1119: "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1.100 jeremy 1120: "\t [-x proxy_address[:port]] [destination] [port]\n");
1.21 ericj 1121: if (ret)
1122: exit(1);
1.7 deraadt 1123: }