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