Annotation of src/usr.bin/nc/netcat.c, Revision 1.121
1.121 ! tedu 1: /* $OpenBSD: netcat.c,v 1.120 2014/06/10 16:23:07 tedu 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.117 sthen 90: int rtableid = -1;
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.117 sthen 204: rtableid = (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.117 sthen 591: if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
592: &rtableid, sizeof(rtableid)) == -1))
1.115 phessler 593: err(1, "setsockopt SO_RTABLE");
1.93 claudio 594:
1.67 jmc 595: /* Bind to a local port or source address if specified. */
1.21 ericj 596: if (sflag || pflag) {
597: struct addrinfo ahints, *ares;
1.6 deraadt 598:
1.91 markus 599: /* try SO_BINDANY, but don't insist */
600: setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
1.21 ericj 601: memset(&ahints, 0, sizeof(struct addrinfo));
602: ahints.ai_family = res0->ai_family;
603: ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
604: ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
1.25 ericj 605: ahints.ai_flags = AI_PASSIVE;
1.38 jakob 606: if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
1.56 stevesk 607: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.21 ericj 608:
609: if (bind(s, (struct sockaddr *)ares->ai_addr,
1.62 millert 610: ares->ai_addrlen) < 0)
1.119 guenther 611: err(1, "bind failed");
1.21 ericj 612: freeaddrinfo(ares);
1.6 deraadt 613: }
1.81 marius 614:
615: set_common_sockopts(s);
1.6 deraadt 616:
1.103 fgsch 617: if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
1.6 deraadt 618: break;
1.71 mcbride 619: else if (vflag)
620: warn("connect to %s port %s (%s) failed", host, port,
621: uflag ? "udp" : "tcp");
1.34 jakob 622:
1.21 ericj 623: close(s);
624: s = -1;
625: } while ((res0 = res0->ai_next) != NULL);
626:
627: freeaddrinfo(res);
1.1 deraadt 628:
1.21 ericj 629: return (s);
1.103 fgsch 630: }
631:
632: int
633: timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
634: {
635: struct pollfd pfd;
636: socklen_t optlen;
637: int flags, optval;
638: int ret;
639:
640: if (timeout != -1) {
641: flags = fcntl(s, F_GETFL, 0);
642: if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
643: err(1, "set non-blocking mode");
644: }
645:
646: if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
647: pfd.fd = s;
648: pfd.events = POLLOUT;
649: if ((ret = poll(&pfd, 1, timeout)) == 1) {
650: optlen = sizeof(optval);
651: if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
652: &optval, &optlen)) == 0) {
653: errno = optval;
654: ret = optval == 0 ? 0 : -1;
655: }
656: } else if (ret == 0) {
657: errno = ETIMEDOUT;
658: ret = -1;
659: } else
660: err(1, "poll failed");
661: }
662:
663: if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
664: err(1, "restoring flags");
665:
666: return (ret);
1.7 deraadt 667: }
1.1 deraadt 668:
1.11 ericj 669: /*
1.21 ericj 670: * local_listen()
1.67 jmc 671: * Returns a socket listening on a local port, binds to specified source
672: * address. Returns -1 on failure.
1.11 ericj 673: */
1.21 ericj 674: int
1.37 jakob 675: local_listen(char *host, char *port, struct addrinfo hints)
1.21 ericj 676: {
677: struct addrinfo *res, *res0;
678: int s, ret, x = 1;
679: int error;
1.6 deraadt 680:
1.67 jmc 681: /* Allow nodename to be null. */
1.21 ericj 682: hints.ai_flags |= AI_PASSIVE;
1.7 deraadt 683:
1.21 ericj 684: /*
685: * In the case of binding to a wildcard address
686: * default to binding to an ipv4 address.
687: */
688: if (host == NULL && hints.ai_family == AF_UNSPEC)
689: hints.ai_family = AF_INET;
1.1 deraadt 690:
1.21 ericj 691: if ((error = getaddrinfo(host, port, &hints, &res)))
1.70 deraadt 692: errx(1, "getaddrinfo: %s", gai_strerror(error));
1.14 ericj 693:
1.21 ericj 694: res0 = res;
695: do {
696: if ((s = socket(res0->ai_family, res0->ai_socktype,
1.82 marius 697: res0->ai_protocol)) < 0)
1.21 ericj 698: continue;
1.1 deraadt 699:
1.118 jca 700: if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
1.117 sthen 701: &rtableid, sizeof(rtableid)) == -1))
1.115 phessler 702: err(1, "setsockopt SO_RTABLE");
1.93 claudio 703:
1.21 ericj 704: ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
705: if (ret == -1)
1.30 smart 706: err(1, NULL);
1.81 marius 707:
708: set_common_sockopts(s);
1.1 deraadt 709:
1.21 ericj 710: if (bind(s, (struct sockaddr *)res0->ai_addr,
1.37 jakob 711: res0->ai_addrlen) == 0)
1.21 ericj 712: break;
1.1 deraadt 713:
1.21 ericj 714: close(s);
715: s = -1;
716: } while ((res0 = res0->ai_next) != NULL);
1.1 deraadt 717:
1.47 ericj 718: if (!uflag && s != -1) {
1.21 ericj 719: if (listen(s, 1) < 0)
1.57 stevesk 720: err(1, "listen");
1.12 ericj 721: }
1.1 deraadt 722:
1.21 ericj 723: freeaddrinfo(res);
1.1 deraadt 724:
1.21 ericj 725: return (s);
1.7 deraadt 726: }
727:
1.11 ericj 728: /*
1.21 ericj 729: * readwrite()
730: * Loop that polls on the network file descriptor and stdin.
1.11 ericj 731: */
1.21 ericj 732: void
1.37 jakob 733: readwrite(int nfd)
1.6 deraadt 734: {
1.52 vincent 735: struct pollfd pfd[2];
1.121 ! tedu 736: unsigned char buf[16 * 1024];
1.79 avsm 737: int n, wfd = fileno(stdin);
1.21 ericj 738: int lfd = fileno(stdout);
1.80 mcbride 739: int plen;
740:
1.120 tedu 741: plen = sizeof(buf);
1.21 ericj 742:
743: /* Setup Network FD */
744: pfd[0].fd = nfd;
745: pfd[0].events = POLLIN;
746:
1.67 jmc 747: /* Set up STDIN FD. */
1.21 ericj 748: pfd[1].fd = wfd;
749: pfd[1].events = POLLIN;
750:
1.54 aaron 751: while (pfd[0].fd != -1) {
1.21 ericj 752: if (iflag)
753: sleep(iflag);
754:
1.68 tedu 755: if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
1.21 ericj 756: close(nfd);
1.52 vincent 757: err(1, "Polling Error");
1.21 ericj 758: }
1.49 hugh 759:
760: if (n == 0)
761: return;
1.21 ericj 762:
763: if (pfd[0].revents & POLLIN) {
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.68 tedu 778: if (!dflag && pfd[1].revents & POLLIN) {
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: }