blob: 6be6e054f9144d3be9a5a1bd1bc88ab36b3de7ef [file] [log] [blame]
Damien Miller293cac52014-12-22 16:30:42 +11001/* $OpenBSD: netcat.c,v 1.126 2014/10/30 16:08:31 tedu Exp $ */
2/*
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
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.
16 *
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 */
28
29/*
30 * Re-written nc(1) for OpenBSD. Original implementation by
31 * *Hobbit* <hobbit@avian.org>.
32 */
33
34#include "includes.h"
35
36#include <sys/types.h>
37#include <sys/socket.h>
38#include <sys/time.h>
39#include <sys/uio.h>
40#include <sys/un.h>
41
42#include <netinet/in.h>
43#include <netinet/tcp.h>
44#include <netinet/ip.h>
45#include <arpa/telnet.h>
46
Damien Miller293cac52014-12-22 16:30:42 +110047#include <errno.h>
48#include <netdb.h>
49#include <poll.h>
50#include <stdarg.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <unistd.h>
55#include <fcntl.h>
56#include <limits.h>
57#include "atomicio.h"
58
59#ifndef SUN_LEN
60#define SUN_LEN(su) \
61 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
62#endif
63
64#define PORT_MAX 65535
65#define PORT_MAX_LEN 6
66#define UNIX_DG_TMP_SOCKET_SIZE 19
67
68#define POLL_STDIN 0
69#define POLL_NETOUT 1
70#define POLL_NETIN 2
71#define POLL_STDOUT 3
72#define BUFSIZE 16384
73
74/* Command Line Options */
75int dflag; /* detached, no stdin */
76int Fflag; /* fdpass sock to stdout */
77unsigned int iflag; /* Interval Flag */
78int kflag; /* More than one connect */
79int lflag; /* Bind to local port */
80int Nflag; /* shutdown() network socket */
81int nflag; /* Don't do name look up */
82char *Pflag; /* Proxy username */
83char *pflag; /* Localport flag */
84int rflag; /* Random ports flag */
85char *sflag; /* Source Address */
86int tflag; /* Telnet Emulation */
87int uflag; /* UDP - Default to TCP */
88int vflag; /* Verbosity */
89int xflag; /* Socks proxy */
90int zflag; /* Port Scan Flag */
91int Dflag; /* sodebug */
92int Iflag; /* TCP receive buffer size */
93int Oflag; /* TCP send buffer size */
94int Sflag; /* TCP MD5 signature option */
95int Tflag = -1; /* IP Type of Service */
96int rtableid = -1;
97
98int timeout = -1;
99int family = AF_UNSPEC;
100char *portlist[PORT_MAX+1];
101char *unix_dg_tmp_socket;
102
103void atelnet(int, unsigned char *, unsigned int);
104void build_ports(char *);
105void help(void);
106int local_listen(char *, char *, struct addrinfo);
107void readwrite(int);
108void fdpass(int nfd) __attribute__((noreturn));
109int remote_connect(const char *, const char *, struct addrinfo);
110int timeout_connect(int, const struct sockaddr *, socklen_t);
111int socks_connect(const char *, const char *, struct addrinfo,
112 const char *, const char *, struct addrinfo, int, const char *);
113int udptest(int);
114int unix_bind(char *);
115int unix_connect(char *);
116int unix_listen(char *);
117void set_common_sockopts(int);
118int map_tos(char *, int *);
119void report_connect(const struct sockaddr *, socklen_t);
120void usage(int);
121ssize_t drainbuf(int, unsigned char *, size_t *);
122ssize_t fillbuf(int, unsigned char *, size_t *);
123
Tim Rice13af3422015-02-24 07:56:47 -0800124static void err(int, const char *, ...) __attribute__((format(printf, 2, 3)));
125static void errx(int, const char *, ...) __attribute__((format(printf, 2, 3)));
126static void warn(const char *, ...) __attribute__((format(printf, 1, 2)));
127
128static void
129err(int r, const char *fmt, ...)
130{
131 va_list args;
132
133 va_start(args, fmt);
134 fprintf(stderr, "%s: ", strerror(errno));
135 vfprintf(stderr, fmt, args);
136 fputc('\n', stderr);
137 va_end(args);
138 exit(r);
139}
140
141static void
142errx(int r, const char *fmt, ...)
143{
144 va_list args;
145
146 va_start(args, fmt);
147 vfprintf(stderr, fmt, args);
148 fputc('\n', stderr);
149 va_end(args);
150 exit(r);
151}
152
153static void
154warn(const char *fmt, ...)
155{
156 va_list args;
157
158 va_start(args, fmt);
159 fprintf(stderr, "%s: ", strerror(errno));
160 vfprintf(stderr, fmt, args);
161 fputc('\n', stderr);
162 va_end(args);
163}
164
Damien Miller293cac52014-12-22 16:30:42 +1100165int
166main(int argc, char *argv[])
167{
168 int ch, s, ret, socksv;
169 char *host, *uport;
170 struct addrinfo hints;
171 struct servent *sv;
172 socklen_t len;
173 struct sockaddr_storage cliaddr;
174 char *proxy = NULL;
175 const char *errstr, *proxyhost = "", *proxyport = NULL;
176 struct addrinfo proxyhints;
177 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
178
179 ret = 1;
180 s = 0;
181 socksv = 5;
182 host = NULL;
183 uport = NULL;
184 sv = NULL;
185
186 while ((ch = getopt(argc, argv,
187 "46DdFhI:i:klNnO:P:p:rSs:tT:UuV:vw:X:x:z")) != -1) {
188 switch (ch) {
189 case '4':
190 family = AF_INET;
191 break;
192 case '6':
193 family = AF_INET6;
194 break;
195 case 'U':
196 family = AF_UNIX;
197 break;
198 case 'X':
199 if (strcasecmp(optarg, "connect") == 0)
200 socksv = -1; /* HTTP proxy CONNECT */
201 else if (strcmp(optarg, "4") == 0)
202 socksv = 4; /* SOCKS v.4 */
203 else if (strcmp(optarg, "5") == 0)
204 socksv = 5; /* SOCKS v.5 */
205 else
206 errx(1, "unsupported proxy protocol");
207 break;
208 case 'd':
209 dflag = 1;
210 break;
211 case 'F':
212 Fflag = 1;
213 break;
214 case 'h':
215 help();
216 break;
217 case 'i':
218 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
219 if (errstr)
220 errx(1, "interval %s: %s", errstr, optarg);
221 break;
222 case 'k':
223 kflag = 1;
224 break;
225 case 'l':
226 lflag = 1;
227 break;
228 case 'N':
229 Nflag = 1;
230 break;
231 case 'n':
232 nflag = 1;
233 break;
234 case 'P':
235 Pflag = optarg;
236 break;
237 case 'p':
238 pflag = optarg;
239 break;
240 case 'r':
241 rflag = 1;
242 break;
243 case 's':
244 sflag = optarg;
245 break;
246 case 't':
247 tflag = 1;
248 break;
249 case 'u':
250 uflag = 1;
251 break;
252#ifdef SO_RTABLE
253 case 'V':
254 rtableid = (int)strtonum(optarg, 0,
255 RT_TABLEID_MAX, &errstr);
256 if (errstr)
257 errx(1, "rtable %s: %s", errstr, optarg);
258 break;
259#endif
260 case 'v':
261 vflag = 1;
262 break;
263 case 'w':
264 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
265 if (errstr)
266 errx(1, "timeout %s: %s", errstr, optarg);
267 timeout *= 1000;
268 break;
269 case 'x':
270 xflag = 1;
271 if ((proxy = strdup(optarg)) == NULL)
Damien Millere47536b2015-02-28 08:20:11 -0800272 errx(1, "strdup");
Damien Miller293cac52014-12-22 16:30:42 +1100273 break;
274 case 'z':
275 zflag = 1;
276 break;
277 case 'D':
278 Dflag = 1;
279 break;
280 case 'I':
281 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
282 if (errstr != NULL)
283 errx(1, "TCP receive window %s: %s",
284 errstr, optarg);
285 break;
286 case 'O':
287 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
288 if (errstr != NULL)
289 errx(1, "TCP send window %s: %s",
290 errstr, optarg);
291 break;
292 case 'S':
293 Sflag = 1;
294 break;
295 case 'T':
296 errstr = NULL;
297 errno = 0;
298 if (map_tos(optarg, &Tflag))
299 break;
300 if (strlen(optarg) > 1 && optarg[0] == '0' &&
301 optarg[1] == 'x')
302 Tflag = (int)strtol(optarg, NULL, 16);
303 else
304 Tflag = (int)strtonum(optarg, 0, 255,
305 &errstr);
306 if (Tflag < 0 || Tflag > 255 || errstr || errno)
307 errx(1, "illegal tos value %s", optarg);
308 break;
309 default:
310 usage(1);
311 }
312 }
313 argc -= optind;
314 argv += optind;
315
316 /* Cruft to make sure options are clean, and used properly. */
317 if (argv[0] && !argv[1] && family == AF_UNIX) {
318 host = argv[0];
319 uport = NULL;
320 } else if (argv[0] && !argv[1]) {
321 if (!lflag)
322 usage(1);
323 uport = argv[0];
324 host = NULL;
325 } else if (argv[0] && argv[1]) {
326 host = argv[0];
327 uport = argv[1];
328 } else
329 usage(1);
330
331 if (lflag && sflag)
332 errx(1, "cannot use -s and -l");
333 if (lflag && pflag)
334 errx(1, "cannot use -p and -l");
335 if (lflag && zflag)
336 errx(1, "cannot use -z and -l");
337 if (!lflag && kflag)
338 errx(1, "must use -l with -k");
339
340 /* Get name of temporary socket for unix datagram client */
341 if ((family == AF_UNIX) && uflag && !lflag) {
342 if (sflag) {
343 unix_dg_tmp_socket = sflag;
344 } else {
345 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
346 UNIX_DG_TMP_SOCKET_SIZE);
347 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
348 err(1, "mktemp");
349 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
350 }
351 }
352
353 /* Initialize addrinfo structure. */
354 if (family != AF_UNIX) {
355 memset(&hints, 0, sizeof(struct addrinfo));
356 hints.ai_family = family;
357 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
358 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
359 if (nflag)
360 hints.ai_flags |= AI_NUMERICHOST;
361 }
362
363 if (xflag) {
364 if (uflag)
365 errx(1, "no proxy support for UDP mode");
366
367 if (lflag)
368 errx(1, "no proxy support for listen");
369
370 if (family == AF_UNIX)
371 errx(1, "no proxy support for unix sockets");
372
373 /* XXX IPv6 transport to proxy would probably work */
374 if (family == AF_INET6)
375 errx(1, "no proxy support for IPv6");
376
377 if (sflag)
378 errx(1, "no proxy support for local source address");
379
380 proxyhost = strsep(&proxy, ":");
381 proxyport = proxy;
382
383 memset(&proxyhints, 0, sizeof(struct addrinfo));
384 proxyhints.ai_family = family;
385 proxyhints.ai_socktype = SOCK_STREAM;
386 proxyhints.ai_protocol = IPPROTO_TCP;
387 if (nflag)
388 proxyhints.ai_flags |= AI_NUMERICHOST;
389 }
390
391 if (lflag) {
392 int connfd;
393 ret = 0;
394
395 if (family == AF_UNIX) {
396 if (uflag)
397 s = unix_bind(host);
398 else
399 s = unix_listen(host);
400 }
401
402 /* Allow only one connection at a time, but stay alive. */
403 for (;;) {
404 if (family != AF_UNIX)
405 s = local_listen(host, uport, hints);
406 if (s < 0)
Damien Millere47536b2015-02-28 08:20:11 -0800407 err(1, "local_listen");
Damien Miller293cac52014-12-22 16:30:42 +1100408 /*
409 * For UDP and -k, don't connect the socket, let it
410 * receive datagrams from multiple socket pairs.
411 */
412 if (uflag && kflag)
413 readwrite(s);
414 /*
415 * For UDP and not -k, we will use recvfrom() initially
416 * to wait for a caller, then use the regular functions
417 * to talk to the caller.
418 */
419 else if (uflag && !kflag) {
420 int rv, plen;
421 char buf[16384];
422 struct sockaddr_storage z;
423
424 len = sizeof(z);
425 plen = 2048;
426 rv = recvfrom(s, buf, plen, MSG_PEEK,
427 (struct sockaddr *)&z, &len);
428 if (rv < 0)
429 err(1, "recvfrom");
430
431 rv = connect(s, (struct sockaddr *)&z, len);
432 if (rv < 0)
433 err(1, "connect");
434
435 if (vflag)
436 report_connect((struct sockaddr *)&z, len);
437
438 readwrite(s);
439 } else {
440 len = sizeof(cliaddr);
441 connfd = accept(s, (struct sockaddr *)&cliaddr,
442 &len);
443 if (connfd == -1) {
444 /* For now, all errnos are fatal */
445 err(1, "accept");
446 }
447 if (vflag)
448 report_connect((struct sockaddr *)&cliaddr, len);
449
450 readwrite(connfd);
451 close(connfd);
452 }
453
454 if (family != AF_UNIX)
455 close(s);
456 else if (uflag) {
457 if (connect(s, NULL, 0) < 0)
458 err(1, "connect");
459 }
460
461 if (!kflag)
462 break;
463 }
464 } else if (family == AF_UNIX) {
465 ret = 0;
466
467 if ((s = unix_connect(host)) > 0 && !zflag) {
468 readwrite(s);
469 close(s);
470 } else
471 ret = 1;
472
473 if (uflag)
474 unlink(unix_dg_tmp_socket);
475 exit(ret);
476
477 } else {
478 int i = 0;
479
480 /* Construct the portlist[] array. */
481 build_ports(uport);
482
483 /* Cycle through portlist, connecting to each port. */
484 for (i = 0; portlist[i] != NULL; i++) {
485 if (s)
486 close(s);
487
488 if (xflag)
489 s = socks_connect(host, portlist[i], hints,
490 proxyhost, proxyport, proxyhints, socksv,
491 Pflag);
492 else
493 s = remote_connect(host, portlist[i], hints);
494
495 if (s < 0)
496 continue;
497
498 ret = 0;
499 if (vflag || zflag) {
500 /* For UDP, make sure we are connected. */
501 if (uflag) {
502 if (udptest(s) == -1) {
503 ret = 1;
504 continue;
505 }
506 }
507
508 /* Don't look up port if -n. */
509 if (nflag)
510 sv = NULL;
511 else {
512 sv = getservbyport(
513 ntohs(atoi(portlist[i])),
514 uflag ? "udp" : "tcp");
515 }
516
517 fprintf(stderr,
518 "Connection to %s %s port [%s/%s] "
519 "succeeded!\n", host, portlist[i],
520 uflag ? "udp" : "tcp",
521 sv ? sv->s_name : "*");
522 }
523 if (Fflag)
524 fdpass(s);
525 else if (!zflag)
526 readwrite(s);
527 }
528 }
529
530 if (s)
531 close(s);
532
533 exit(ret);
534}
535
536/*
537 * unix_bind()
538 * Returns a unix socket bound to the given path
539 */
540int
541unix_bind(char *path)
542{
Tim Rice13af3422015-02-24 07:56:47 -0800543 struct sockaddr_un sun_sa;
Damien Miller293cac52014-12-22 16:30:42 +1100544 int s;
545
546 /* Create unix domain socket. */
547 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
548 0)) < 0)
549 return (-1);
550
Tim Rice13af3422015-02-24 07:56:47 -0800551 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
552 sun_sa.sun_family = AF_UNIX;
Damien Miller293cac52014-12-22 16:30:42 +1100553
Tim Rice13af3422015-02-24 07:56:47 -0800554 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
555 sizeof(sun_sa.sun_path)) {
Damien Miller293cac52014-12-22 16:30:42 +1100556 close(s);
557 errno = ENAMETOOLONG;
558 return (-1);
559 }
560
Tim Rice13af3422015-02-24 07:56:47 -0800561 if (bind(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
Damien Miller293cac52014-12-22 16:30:42 +1100562 close(s);
563 return (-1);
564 }
565 return (s);
566}
567
568/*
569 * unix_connect()
570 * Returns a socket connected to a local unix socket. Returns -1 on failure.
571 */
572int
573unix_connect(char *path)
574{
Tim Rice13af3422015-02-24 07:56:47 -0800575 struct sockaddr_un sun_sa;
Damien Miller293cac52014-12-22 16:30:42 +1100576 int s;
577
578 if (uflag) {
579 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
580 return (-1);
581 } else {
582 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
583 return (-1);
584 }
585 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
586
Tim Rice13af3422015-02-24 07:56:47 -0800587 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
588 sun_sa.sun_family = AF_UNIX;
Damien Miller293cac52014-12-22 16:30:42 +1100589
Tim Rice13af3422015-02-24 07:56:47 -0800590 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
591 sizeof(sun_sa.sun_path)) {
Damien Miller293cac52014-12-22 16:30:42 +1100592 close(s);
593 errno = ENAMETOOLONG;
594 return (-1);
595 }
Tim Rice13af3422015-02-24 07:56:47 -0800596 if (connect(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
Damien Miller293cac52014-12-22 16:30:42 +1100597 close(s);
598 return (-1);
599 }
600 return (s);
601
602}
603
604/*
605 * unix_listen()
606 * Create a unix domain socket, and listen on it.
607 */
608int
609unix_listen(char *path)
610{
611 int s;
612 if ((s = unix_bind(path)) < 0)
613 return (-1);
614
615 if (listen(s, 5) < 0) {
616 close(s);
617 return (-1);
618 }
619 return (s);
620}
621
622/*
623 * remote_connect()
624 * Returns a socket connected to a remote host. Properly binds to a local
625 * port or source address if needed. Returns -1 on failure.
626 */
627int
628remote_connect(const char *host, const char *port, struct addrinfo hints)
629{
630 struct addrinfo *res, *res0;
631 int s, error;
Damien Millere47536b2015-02-28 08:20:11 -0800632#if defined(SO_RTABLE) || defined(SO_BINDANY)
Damien Miller293cac52014-12-22 16:30:42 +1100633 int on = 1;
634#endif
635
636 if ((error = getaddrinfo(host, port, &hints, &res)))
637 errx(1, "getaddrinfo: %s", gai_strerror(error));
638
639 res0 = res;
640 do {
641 if ((s = socket(res0->ai_family, res0->ai_socktype,
642 res0->ai_protocol)) < 0)
643 continue;
644
645#ifdef SO_RTABLE
646 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
647 &rtableid, sizeof(rtableid)) == -1))
648 err(1, "setsockopt SO_RTABLE");
649#endif
650 /* Bind to a local port or source address if specified. */
651 if (sflag || pflag) {
652 struct addrinfo ahints, *ares;
653
654#ifdef SO_BINDANY
655 /* try SO_BINDANY, but don't insist */
656 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
657#endif
658 memset(&ahints, 0, sizeof(struct addrinfo));
659 ahints.ai_family = res0->ai_family;
660 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
661 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
662 ahints.ai_flags = AI_PASSIVE;
663 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
664 errx(1, "getaddrinfo: %s", gai_strerror(error));
665
666 if (bind(s, (struct sockaddr *)ares->ai_addr,
667 ares->ai_addrlen) < 0)
668 err(1, "bind failed");
669 freeaddrinfo(ares);
670 }
671
672 set_common_sockopts(s);
673
674 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
675 break;
676 else if (vflag)
677 warn("connect to %s port %s (%s) failed", host, port,
678 uflag ? "udp" : "tcp");
679
680 close(s);
681 s = -1;
682 } while ((res0 = res0->ai_next) != NULL);
683
684 freeaddrinfo(res);
685
686 return (s);
687}
688
689int
690timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
691{
692 struct pollfd pfd;
693 socklen_t optlen;
694 int flags = 0, optval;
695 int ret;
696
697 if (timeout != -1) {
698 flags = fcntl(s, F_GETFL, 0);
699 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
700 err(1, "set non-blocking mode");
701 }
702
703 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
704 pfd.fd = s;
705 pfd.events = POLLOUT;
706 if ((ret = poll(&pfd, 1, timeout)) == 1) {
707 optlen = sizeof(optval);
708 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
709 &optval, &optlen)) == 0) {
710 errno = optval;
711 ret = optval == 0 ? 0 : -1;
712 }
713 } else if (ret == 0) {
714 errno = ETIMEDOUT;
715 ret = -1;
716 } else
717 err(1, "poll failed");
718 }
719
720 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
721 err(1, "restoring flags");
722
723 return (ret);
724}
725
726/*
727 * local_listen()
728 * Returns a socket listening on a local port, binds to specified source
729 * address. Returns -1 on failure.
730 */
731int
732local_listen(char *host, char *port, struct addrinfo hints)
733{
734 struct addrinfo *res, *res0;
735 int s, ret, x = 1;
736 int error;
737
738 /* Allow nodename to be null. */
739 hints.ai_flags |= AI_PASSIVE;
740
741 /*
742 * In the case of binding to a wildcard address
743 * default to binding to an ipv4 address.
744 */
745 if (host == NULL && hints.ai_family == AF_UNSPEC)
746 hints.ai_family = AF_INET;
747
748 if ((error = getaddrinfo(host, port, &hints, &res)))
749 errx(1, "getaddrinfo: %s", gai_strerror(error));
750
751 res0 = res;
752 do {
753 if ((s = socket(res0->ai_family, res0->ai_socktype,
754 res0->ai_protocol)) < 0)
755 continue;
756
757#ifdef SO_RTABLE
758 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
759 &rtableid, sizeof(rtableid)) == -1))
760 err(1, "setsockopt SO_RTABLE");
761#endif
Damien Millerc3321102015-01-15 02:59:51 +1100762#ifdef SO_REUSEPORT
Damien Miller293cac52014-12-22 16:30:42 +1100763 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
764 if (ret == -1)
Damien Millere47536b2015-02-28 08:20:11 -0800765 err(1, "setsockopt");
Damien Millerc3321102015-01-15 02:59:51 +1100766#endif
Damien Miller293cac52014-12-22 16:30:42 +1100767 set_common_sockopts(s);
768
769 if (bind(s, (struct sockaddr *)res0->ai_addr,
770 res0->ai_addrlen) == 0)
771 break;
772
773 close(s);
774 s = -1;
775 } while ((res0 = res0->ai_next) != NULL);
776
777 if (!uflag && s != -1) {
778 if (listen(s, 1) < 0)
779 err(1, "listen");
780 }
781
782 freeaddrinfo(res);
783
784 return (s);
785}
786
787/*
788 * readwrite()
789 * Loop that polls on the network file descriptor and stdin.
790 */
791void
792readwrite(int net_fd)
793{
794 struct pollfd pfd[4];
795 int stdin_fd = STDIN_FILENO;
796 int stdout_fd = STDOUT_FILENO;
797 unsigned char netinbuf[BUFSIZE];
798 size_t netinbufpos = 0;
799 unsigned char stdinbuf[BUFSIZE];
800 size_t stdinbufpos = 0;
801 int n, num_fds;
802 ssize_t ret;
803
804 /* don't read from stdin if requested */
805 if (dflag)
806 stdin_fd = -1;
807
808 /* stdin */
809 pfd[POLL_STDIN].fd = stdin_fd;
810 pfd[POLL_STDIN].events = POLLIN;
811
812 /* network out */
813 pfd[POLL_NETOUT].fd = net_fd;
814 pfd[POLL_NETOUT].events = 0;
815
816 /* network in */
817 pfd[POLL_NETIN].fd = net_fd;
818 pfd[POLL_NETIN].events = POLLIN;
819
820 /* stdout */
821 pfd[POLL_STDOUT].fd = stdout_fd;
822 pfd[POLL_STDOUT].events = 0;
823
824 while (1) {
825 /* both inputs are gone, buffers are empty, we are done */
826 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
827 && stdinbufpos == 0 && netinbufpos == 0) {
828 close(net_fd);
829 return;
830 }
831 /* both outputs are gone, we can't continue */
832 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
833 close(net_fd);
834 return;
835 }
836 /* listen and net in gone, queues empty, done */
837 if (lflag && pfd[POLL_NETIN].fd == -1
838 && stdinbufpos == 0 && netinbufpos == 0) {
839 close(net_fd);
840 return;
841 }
842
843 /* help says -i is for "wait between lines sent". We read and
844 * write arbitrary amounts of data, and we don't want to start
845 * scanning for newlines, so this is as good as it gets */
846 if (iflag)
847 sleep(iflag);
848
849 /* poll */
850 num_fds = poll(pfd, 4, timeout);
851
852 /* treat poll errors */
853 if (num_fds == -1) {
854 close(net_fd);
855 err(1, "polling error");
856 }
857
858 /* timeout happened */
859 if (num_fds == 0)
860 return;
861
862 /* treat socket error conditions */
863 for (n = 0; n < 4; n++) {
864 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
865 pfd[n].fd = -1;
866 }
867 }
868 /* reading is possible after HUP */
869 if (pfd[POLL_STDIN].events & POLLIN &&
870 pfd[POLL_STDIN].revents & POLLHUP &&
871 ! (pfd[POLL_STDIN].revents & POLLIN))
872 pfd[POLL_STDIN].fd = -1;
873
874 if (pfd[POLL_NETIN].events & POLLIN &&
875 pfd[POLL_NETIN].revents & POLLHUP &&
876 ! (pfd[POLL_NETIN].revents & POLLIN))
877 pfd[POLL_NETIN].fd = -1;
878
879 if (pfd[POLL_NETOUT].revents & POLLHUP) {
880 if (Nflag)
881 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
882 pfd[POLL_NETOUT].fd = -1;
883 }
884 /* if HUP, stop watching stdout */
885 if (pfd[POLL_STDOUT].revents & POLLHUP)
886 pfd[POLL_STDOUT].fd = -1;
887 /* if no net out, stop watching stdin */
888 if (pfd[POLL_NETOUT].fd == -1)
889 pfd[POLL_STDIN].fd = -1;
890 /* if no stdout, stop watching net in */
891 if (pfd[POLL_STDOUT].fd == -1) {
892 if (pfd[POLL_NETIN].fd != -1)
893 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
894 pfd[POLL_NETIN].fd = -1;
895 }
896
897 /* try to read from stdin */
898 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
899 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
900 &stdinbufpos);
901 /* error or eof on stdin - remove from pfd */
902 if (ret == 0 || ret == -1)
903 pfd[POLL_STDIN].fd = -1;
904 /* read something - poll net out */
905 if (stdinbufpos > 0)
906 pfd[POLL_NETOUT].events = POLLOUT;
907 /* filled buffer - remove self from polling */
908 if (stdinbufpos == BUFSIZE)
909 pfd[POLL_STDIN].events = 0;
910 }
911 /* try to write to network */
912 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
913 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
914 &stdinbufpos);
915 if (ret == -1)
916 pfd[POLL_NETOUT].fd = -1;
917 /* buffer empty - remove self from polling */
918 if (stdinbufpos == 0)
919 pfd[POLL_NETOUT].events = 0;
920 /* buffer no longer full - poll stdin again */
921 if (stdinbufpos < BUFSIZE)
922 pfd[POLL_STDIN].events = POLLIN;
923 }
924 /* try to read from network */
925 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
926 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
927 &netinbufpos);
928 if (ret == -1)
929 pfd[POLL_NETIN].fd = -1;
930 /* eof on net in - remove from pfd */
931 if (ret == 0) {
932 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
933 pfd[POLL_NETIN].fd = -1;
934 }
935 /* read something - poll stdout */
936 if (netinbufpos > 0)
937 pfd[POLL_STDOUT].events = POLLOUT;
938 /* filled buffer - remove self from polling */
939 if (netinbufpos == BUFSIZE)
940 pfd[POLL_NETIN].events = 0;
941 /* handle telnet */
942 if (tflag)
943 atelnet(pfd[POLL_NETIN].fd, netinbuf,
944 netinbufpos);
945 }
946 /* try to write to stdout */
947 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
948 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
949 &netinbufpos);
950 if (ret == -1)
951 pfd[POLL_STDOUT].fd = -1;
952 /* buffer empty - remove self from polling */
953 if (netinbufpos == 0)
954 pfd[POLL_STDOUT].events = 0;
955 /* buffer no longer full - poll net in again */
956 if (netinbufpos < BUFSIZE)
957 pfd[POLL_NETIN].events = POLLIN;
958 }
959
960 /* stdin gone and queue empty? */
961 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
962 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
963 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
964 pfd[POLL_NETOUT].fd = -1;
965 }
966 /* net in gone and queue empty? */
967 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
968 pfd[POLL_STDOUT].fd = -1;
969 }
970 }
971}
972
973ssize_t
974drainbuf(int fd, unsigned char *buf, size_t *bufpos)
975{
976 ssize_t n;
977 ssize_t adjust;
978
979 n = write(fd, buf, *bufpos);
980 /* don't treat EAGAIN, EINTR as error */
981 if (n == -1 && (errno == EAGAIN || errno == EINTR))
982 n = -2;
983 if (n <= 0)
984 return n;
985 /* adjust buffer */
986 adjust = *bufpos - n;
987 if (adjust > 0)
988 memmove(buf, buf + n, adjust);
989 *bufpos -= n;
990 return n;
991}
992
993
994ssize_t
995fillbuf(int fd, unsigned char *buf, size_t *bufpos)
996{
997 size_t num = BUFSIZE - *bufpos;
998 ssize_t n;
999
1000 n = read(fd, buf + *bufpos, num);
1001 /* don't treat EAGAIN, EINTR as error */
1002 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1003 n = -2;
1004 if (n <= 0)
1005 return n;
1006 *bufpos += n;
1007 return n;
1008}
1009
1010/*
1011 * fdpass()
1012 * Pass the connected file descriptor to stdout and exit.
1013 */
1014void
1015fdpass(int nfd)
1016{
Damien Miller1ad3a772015-02-26 20:33:22 -08001017#if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR))
1018 struct msghdr msg;
1019#ifndef HAVE_ACCRIGHTS_IN_MSGHDR
Damien Miller293cac52014-12-22 16:30:42 +11001020 union {
1021 struct cmsghdr hdr;
1022 char buf[CMSG_SPACE(sizeof(int))];
1023 } cmsgbuf;
1024 struct cmsghdr *cmsg;
Damien Miller1ad3a772015-02-26 20:33:22 -08001025#endif
1026 struct iovec vec;
1027 char ch = '\0';
Damien Miller293cac52014-12-22 16:30:42 +11001028 struct pollfd pfd;
Damien Miller1ad3a772015-02-26 20:33:22 -08001029 ssize_t r;
Damien Miller293cac52014-12-22 16:30:42 +11001030
Damien Miller1ad3a772015-02-26 20:33:22 -08001031 memset(&msg, 0, sizeof(msg));
1032#ifdef HAVE_ACCRIGHTS_IN_MSGHDR
1033 msg.msg_accrights = (caddr_t)&nfd;
1034 msg.msg_accrightslen = sizeof(nfd);
1035#else
1036 memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1037 msg.msg_control = (caddr_t)&cmsgbuf.buf;
1038 msg.msg_controllen = sizeof(cmsgbuf.buf);
1039 cmsg = CMSG_FIRSTHDR(&msg);
Damien Miller293cac52014-12-22 16:30:42 +11001040 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1041 cmsg->cmsg_level = SOL_SOCKET;
1042 cmsg->cmsg_type = SCM_RIGHTS;
1043 *(int *)CMSG_DATA(cmsg) = nfd;
Damien Miller1ad3a772015-02-26 20:33:22 -08001044#endif
Damien Miller293cac52014-12-22 16:30:42 +11001045
Damien Miller1ad3a772015-02-26 20:33:22 -08001046 vec.iov_base = &ch;
1047 vec.iov_len = 1;
1048 msg.msg_iov = &vec;
1049 msg.msg_iovlen = 1;
Damien Miller293cac52014-12-22 16:30:42 +11001050
1051 bzero(&pfd, sizeof(pfd));
1052 pfd.fd = STDOUT_FILENO;
1053 for (;;) {
Damien Miller1ad3a772015-02-26 20:33:22 -08001054 r = sendmsg(STDOUT_FILENO, &msg, 0);
Damien Miller293cac52014-12-22 16:30:42 +11001055 if (r == -1) {
1056 if (errno == EAGAIN || errno == EINTR) {
1057 pfd.events = POLLOUT;
1058 if (poll(&pfd, 1, -1) == -1)
1059 err(1, "poll");
1060 continue;
1061 }
1062 err(1, "sendmsg");
1063 } else if (r == -1)
1064 errx(1, "sendmsg: unexpected return value %zd", r);
1065 else
1066 break;
1067 }
1068 exit(0);
Damien Miller1ad3a772015-02-26 20:33:22 -08001069#else
1070 errx(1, "%s: file descriptor passing not supported", __func__);
1071#endif
Damien Miller293cac52014-12-22 16:30:42 +11001072}
1073
1074/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1075void
1076atelnet(int nfd, unsigned char *buf, unsigned int size)
1077{
1078 unsigned char *p, *end;
1079 unsigned char obuf[4];
1080
1081 if (size < 3)
1082 return;
1083 end = buf + size - 2;
1084
1085 for (p = buf; p < end; p++) {
1086 if (*p != IAC)
1087 continue;
1088
1089 obuf[0] = IAC;
1090 p++;
1091 if ((*p == WILL) || (*p == WONT))
1092 obuf[1] = DONT;
1093 else if ((*p == DO) || (*p == DONT))
1094 obuf[1] = WONT;
1095 else
1096 continue;
1097
1098 p++;
1099 obuf[2] = *p;
1100 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1101 warn("Write Error!");
1102 }
1103}
1104
1105/*
1106 * build_ports()
1107 * Build an array of ports in portlist[], listing each port
1108 * that we should try to connect to.
1109 */
1110void
1111build_ports(char *p)
1112{
1113 const char *errstr;
1114 char *n;
1115 int hi, lo, cp;
1116 int x = 0;
1117
1118 if ((n = strchr(p, '-')) != NULL) {
1119 *n = '\0';
1120 n++;
1121
1122 /* Make sure the ports are in order: lowest->highest. */
1123 hi = strtonum(n, 1, PORT_MAX, &errstr);
1124 if (errstr)
1125 errx(1, "port number %s: %s", errstr, n);
1126 lo = strtonum(p, 1, PORT_MAX, &errstr);
1127 if (errstr)
1128 errx(1, "port number %s: %s", errstr, p);
1129
1130 if (lo > hi) {
1131 cp = hi;
1132 hi = lo;
1133 lo = cp;
1134 }
1135
1136 /* Load ports sequentially. */
1137 for (cp = lo; cp <= hi; cp++) {
1138 portlist[x] = calloc(1, PORT_MAX_LEN);
1139 if (portlist[x] == NULL)
Damien Millere47536b2015-02-28 08:20:11 -08001140 errx(1, "calloc");
Damien Miller293cac52014-12-22 16:30:42 +11001141 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1142 x++;
1143 }
1144
1145 /* Randomly swap ports. */
1146 if (rflag) {
1147 int y;
1148 char *c;
1149
1150 for (x = 0; x <= (hi - lo); x++) {
1151 y = (arc4random() & 0xFFFF) % (hi - lo);
1152 c = portlist[x];
1153 portlist[x] = portlist[y];
1154 portlist[y] = c;
1155 }
1156 }
1157 } else {
1158 hi = strtonum(p, 1, PORT_MAX, &errstr);
1159 if (errstr)
1160 errx(1, "port number %s: %s", errstr, p);
1161 portlist[0] = strdup(p);
1162 if (portlist[0] == NULL)
Damien Millere47536b2015-02-28 08:20:11 -08001163 errx(1, "strdup");
Damien Miller293cac52014-12-22 16:30:42 +11001164 }
1165}
1166
1167/*
1168 * udptest()
1169 * Do a few writes to see if the UDP port is there.
1170 * Fails once PF state table is full.
1171 */
1172int
1173udptest(int s)
1174{
1175 int i, ret;
1176
1177 for (i = 0; i <= 3; i++) {
1178 if (write(s, "X", 1) == 1)
1179 ret = 1;
1180 else
1181 ret = -1;
1182 }
1183 return (ret);
1184}
1185
1186void
1187set_common_sockopts(int s)
1188{
1189 int x = 1;
1190
Damien Miller69ff64f2015-01-27 23:07:43 +11001191#ifdef TCP_MD5SIG
Damien Miller293cac52014-12-22 16:30:42 +11001192 if (Sflag) {
1193 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1194 &x, sizeof(x)) == -1)
Damien Millere47536b2015-02-28 08:20:11 -08001195 err(1, "setsockopt");
Damien Miller293cac52014-12-22 16:30:42 +11001196 }
Damien Miller69ff64f2015-01-27 23:07:43 +11001197#endif
Damien Miller293cac52014-12-22 16:30:42 +11001198 if (Dflag) {
1199 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1200 &x, sizeof(x)) == -1)
Damien Millere47536b2015-02-28 08:20:11 -08001201 err(1, "setsockopt");
Damien Miller293cac52014-12-22 16:30:42 +11001202 }
1203 if (Tflag != -1) {
1204 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1205 &Tflag, sizeof(Tflag)) == -1)
1206 err(1, "set IP ToS");
1207 }
1208 if (Iflag) {
1209 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1210 &Iflag, sizeof(Iflag)) == -1)
1211 err(1, "set TCP receive buffer size");
1212 }
1213 if (Oflag) {
1214 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1215 &Oflag, sizeof(Oflag)) == -1)
1216 err(1, "set TCP send buffer size");
1217 }
1218}
1219
1220int
1221map_tos(char *s, int *val)
1222{
1223 /* DiffServ Codepoints and other TOS mappings */
1224 const struct toskeywords {
1225 const char *keyword;
1226 int val;
1227 } *t, toskeywords[] = {
1228 { "af11", IPTOS_DSCP_AF11 },
1229 { "af12", IPTOS_DSCP_AF12 },
1230 { "af13", IPTOS_DSCP_AF13 },
1231 { "af21", IPTOS_DSCP_AF21 },
1232 { "af22", IPTOS_DSCP_AF22 },
1233 { "af23", IPTOS_DSCP_AF23 },
1234 { "af31", IPTOS_DSCP_AF31 },
1235 { "af32", IPTOS_DSCP_AF32 },
1236 { "af33", IPTOS_DSCP_AF33 },
1237 { "af41", IPTOS_DSCP_AF41 },
1238 { "af42", IPTOS_DSCP_AF42 },
1239 { "af43", IPTOS_DSCP_AF43 },
1240 { "critical", IPTOS_PREC_CRITIC_ECP },
1241 { "cs0", IPTOS_DSCP_CS0 },
1242 { "cs1", IPTOS_DSCP_CS1 },
1243 { "cs2", IPTOS_DSCP_CS2 },
1244 { "cs3", IPTOS_DSCP_CS3 },
1245 { "cs4", IPTOS_DSCP_CS4 },
1246 { "cs5", IPTOS_DSCP_CS5 },
1247 { "cs6", IPTOS_DSCP_CS6 },
1248 { "cs7", IPTOS_DSCP_CS7 },
1249 { "ef", IPTOS_DSCP_EF },
1250 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1251 { "lowdelay", IPTOS_LOWDELAY },
1252 { "netcontrol", IPTOS_PREC_NETCONTROL },
1253 { "reliability", IPTOS_RELIABILITY },
1254 { "throughput", IPTOS_THROUGHPUT },
1255 { NULL, -1 },
1256 };
1257
1258 for (t = toskeywords; t->keyword != NULL; t++) {
1259 if (strcmp(s, t->keyword) == 0) {
1260 *val = t->val;
1261 return (1);
1262 }
1263 }
1264
1265 return (0);
1266}
1267
1268void
1269report_connect(const struct sockaddr *sa, socklen_t salen)
1270{
1271 char remote_host[NI_MAXHOST];
1272 char remote_port[NI_MAXSERV];
1273 int herr;
1274 int flags = NI_NUMERICSERV;
1275
1276 if (nflag)
1277 flags |= NI_NUMERICHOST;
1278
1279 if ((herr = getnameinfo(sa, salen,
1280 remote_host, sizeof(remote_host),
1281 remote_port, sizeof(remote_port),
1282 flags)) != 0) {
1283 if (herr == EAI_SYSTEM)
1284 err(1, "getnameinfo");
1285 else
1286 errx(1, "getnameinfo: %s", gai_strerror(herr));
1287 }
1288
1289 fprintf(stderr,
1290 "Connection from %s %s "
1291 "received!\n", remote_host, remote_port);
1292}
1293
1294void
1295help(void)
1296{
1297 usage(0);
1298 fprintf(stderr, "\tCommand Summary:\n\
1299 \t-4 Use IPv4\n\
1300 \t-6 Use IPv6\n\
1301 \t-D Enable the debug socket option\n\
1302 \t-d Detach from stdin\n\
1303 \t-F Pass socket fd\n\
1304 \t-h This help text\n\
1305 \t-I length TCP receive buffer length\n\
1306 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1307 \t-k Keep inbound sockets open for multiple connects\n\
1308 \t-l Listen mode, for inbound connects\n\
1309 \t-N Shutdown the network socket after EOF on stdin\n\
1310 \t-n Suppress name/port resolutions\n\
1311 \t-O length TCP send buffer length\n\
1312 \t-P proxyuser\tUsername for proxy authentication\n\
1313 \t-p port\t Specify local port for remote connects\n\
1314 \t-r Randomize remote ports\n\
1315 \t-S Enable the TCP MD5 signature option\n\
1316 \t-s addr\t Local source address\n\
1317 \t-T toskeyword\tSet IP Type of Service\n\
1318 \t-t Answer TELNET negotiation\n\
1319 \t-U Use UNIX domain socket\n\
1320 \t-u UDP mode\n\
1321 \t-V rtable Specify alternate routing table\n\
1322 \t-v Verbose\n\
1323 \t-w secs\t Timeout for connects and final net reads\n\
1324 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1325 \t-x addr[:port]\tSpecify proxy address and port\n\
1326 \t-z Zero-I/O mode [used for scanning]\n\
1327 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1328 exit(1);
1329}
1330
1331void
1332usage(int ret)
1333{
1334 fprintf(stderr,
1335 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1336 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1337 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1338 "\t [-x proxy_address[:port]] [destination] [port]\n");
1339 if (ret)
1340 exit(1);
1341}
1342
1343/* *** src/usr.bin/nc/socks.c *** */
1344
1345
1346/* $OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $ */
1347
1348/*
1349 * Copyright (c) 1999 Niklas Hallqvist. All rights reserved.
1350 * Copyright (c) 2004, 2005 Damien Miller. All rights reserved.
1351 *
1352 * Redistribution and use in source and binary forms, with or without
1353 * modification, are permitted provided that the following conditions
1354 * are met:
1355 * 1. Redistributions of source code must retain the above copyright
1356 * notice, this list of conditions and the following disclaimer.
1357 * 2. Redistributions in binary form must reproduce the above copyright
1358 * notice, this list of conditions and the following disclaimer in the
1359 * documentation and/or other materials provided with the distribution.
1360 *
1361 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1362 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1363 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1364 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1365 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1366 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1367 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1368 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1369 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1370 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1371 */
1372
1373#include <sys/types.h>
1374#include <sys/socket.h>
1375#include <netinet/in.h>
1376#include <arpa/inet.h>
1377
Damien Miller293cac52014-12-22 16:30:42 +11001378#include <errno.h>
1379#include <netdb.h>
1380#include <stdio.h>
1381#include <stdlib.h>
1382#include <string.h>
1383#include <unistd.h>
1384#include <resolv.h>
1385
1386#define SOCKS_PORT "1080"
1387#define HTTP_PROXY_PORT "3128"
1388#define HTTP_MAXHDRS 64
1389#define SOCKS_V5 5
1390#define SOCKS_V4 4
1391#define SOCKS_NOAUTH 0
1392#define SOCKS_NOMETHOD 0xff
1393#define SOCKS_CONNECT 1
1394#define SOCKS_IPV4 1
1395#define SOCKS_DOMAIN 3
1396#define SOCKS_IPV6 4
1397
1398int remote_connect(const char *, const char *, struct addrinfo);
1399int socks_connect(const char *, const char *, struct addrinfo,
1400 const char *, const char *, struct addrinfo, int,
1401 const char *);
1402
1403static int
1404decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1405 socklen_t addrlen, int v4only, int numeric)
1406{
1407 int r;
1408 struct addrinfo hints, *res;
1409
1410 bzero(&hints, sizeof(hints));
1411 hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1412 hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1413 hints.ai_socktype = SOCK_STREAM;
1414 r = getaddrinfo(h, p, &hints, &res);
1415 /* Don't fatal when attempting to convert a numeric address */
1416 if (r != 0) {
1417 if (!numeric) {
1418 errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1419 gai_strerror(r));
1420 }
1421 return (-1);
1422 }
1423 if (addrlen < res->ai_addrlen) {
1424 freeaddrinfo(res);
1425 errx(1, "internal error: addrlen < res->ai_addrlen");
1426 }
1427 memcpy(addr, res->ai_addr, res->ai_addrlen);
1428 freeaddrinfo(res);
1429 return (0);
1430}
1431
1432static int
1433proxy_read_line(int fd, char *buf, size_t bufsz)
1434{
1435 size_t off;
1436
1437 for(off = 0;;) {
1438 if (off >= bufsz)
1439 errx(1, "proxy read too long");
1440 if (atomicio(read, fd, buf + off, 1) != 1)
1441 err(1, "proxy read");
1442 /* Skip CR */
1443 if (buf[off] == '\r')
1444 continue;
1445 if (buf[off] == '\n') {
1446 buf[off] = '\0';
1447 break;
1448 }
1449 off++;
1450 }
1451 return (off);
1452}
1453
1454static const char *
1455getproxypass(const char *proxyuser, const char *proxyhost)
1456{
1457 char prompt[512];
1458 static char pw[256];
1459
1460 snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1461 proxyuser, proxyhost);
1462 if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1463 errx(1, "Unable to read proxy passphrase");
1464 return (pw);
1465}
1466
1467int
1468socks_connect(const char *host, const char *port,
1469 struct addrinfo hints __attribute__ ((__unused__)),
1470 const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1471 int socksv, const char *proxyuser)
1472{
1473 int proxyfd, r, authretry = 0;
Damien Miller2fab9b02015-03-04 07:41:27 +11001474 size_t hlen, wlen = 0;
Damien Miller293cac52014-12-22 16:30:42 +11001475 unsigned char buf[1024];
1476 size_t cnt;
1477 struct sockaddr_storage addr;
1478 struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1479 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1480 in_port_t serverport;
1481 const char *proxypass = NULL;
1482
1483 if (proxyport == NULL)
1484 proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1485
1486 /* Abuse API to lookup port */
1487 if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1488 sizeof(addr), 1, 1) == -1)
1489 errx(1, "unknown port \"%.64s\"", port);
1490 serverport = in4->sin_port;
1491
1492 again:
1493 if (authretry++ > 3)
1494 errx(1, "Too many authentication failures");
1495
1496 proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1497
1498 if (proxyfd < 0)
1499 return (-1);
1500
1501 if (socksv == 5) {
1502 if (decode_addrport(host, port, (struct sockaddr *)&addr,
1503 sizeof(addr), 0, 1) == -1)
1504 addr.ss_family = 0; /* used in switch below */
1505
1506 /* Version 5, one method: no authentication */
1507 buf[0] = SOCKS_V5;
1508 buf[1] = 1;
1509 buf[2] = SOCKS_NOAUTH;
1510 cnt = atomicio(vwrite, proxyfd, buf, 3);
1511 if (cnt != 3)
1512 err(1, "write failed (%zu/3)", cnt);
1513
1514 cnt = atomicio(read, proxyfd, buf, 2);
1515 if (cnt != 2)
1516 err(1, "read failed (%zu/3)", cnt);
1517
1518 if (buf[1] == SOCKS_NOMETHOD)
1519 errx(1, "authentication method negotiation failed");
1520
1521 switch (addr.ss_family) {
1522 case 0:
1523 /* Version 5, connect: domain name */
1524
1525 /* Max domain name length is 255 bytes */
1526 hlen = strlen(host);
1527 if (hlen > 255)
1528 errx(1, "host name too long for SOCKS5");
1529 buf[0] = SOCKS_V5;
1530 buf[1] = SOCKS_CONNECT;
1531 buf[2] = 0;
1532 buf[3] = SOCKS_DOMAIN;
1533 buf[4] = hlen;
1534 memcpy(buf + 5, host, hlen);
1535 memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1536 wlen = 7 + hlen;
1537 break;
1538 case AF_INET:
1539 /* Version 5, connect: IPv4 address */
1540 buf[0] = SOCKS_V5;
1541 buf[1] = SOCKS_CONNECT;
1542 buf[2] = 0;
1543 buf[3] = SOCKS_IPV4;
1544 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1545 memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1546 wlen = 10;
1547 break;
1548 case AF_INET6:
1549 /* Version 5, connect: IPv6 address */
1550 buf[0] = SOCKS_V5;
1551 buf[1] = SOCKS_CONNECT;
1552 buf[2] = 0;
1553 buf[3] = SOCKS_IPV6;
1554 memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1555 memcpy(buf + 20, &in6->sin6_port,
1556 sizeof in6->sin6_port);
1557 wlen = 22;
1558 break;
1559 default:
1560 errx(1, "internal error: silly AF");
1561 }
1562
1563 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1564 if (cnt != wlen)
1565 err(1, "write failed (%zu/%zu)", cnt, wlen);
1566
1567 cnt = atomicio(read, proxyfd, buf, 4);
1568 if (cnt != 4)
1569 err(1, "read failed (%zu/4)", cnt);
1570 if (buf[1] != 0)
1571 errx(1, "connection failed, SOCKS error %d", buf[1]);
1572 switch (buf[3]) {
1573 case SOCKS_IPV4:
1574 cnt = atomicio(read, proxyfd, buf + 4, 6);
1575 if (cnt != 6)
1576 err(1, "read failed (%zu/6)", cnt);
1577 break;
1578 case SOCKS_IPV6:
1579 cnt = atomicio(read, proxyfd, buf + 4, 18);
1580 if (cnt != 18)
1581 err(1, "read failed (%zu/18)", cnt);
1582 break;
1583 default:
1584 errx(1, "connection failed, unsupported address type");
1585 }
1586 } else if (socksv == 4) {
1587 /* This will exit on lookup failure */
1588 decode_addrport(host, port, (struct sockaddr *)&addr,
1589 sizeof(addr), 1, 0);
1590
1591 /* Version 4 */
1592 buf[0] = SOCKS_V4;
1593 buf[1] = SOCKS_CONNECT; /* connect */
1594 memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1595 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1596 buf[8] = 0; /* empty username */
1597 wlen = 9;
1598
1599 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1600 if (cnt != wlen)
1601 err(1, "write failed (%zu/%zu)", cnt, wlen);
1602
1603 cnt = atomicio(read, proxyfd, buf, 8);
1604 if (cnt != 8)
1605 err(1, "read failed (%zu/8)", cnt);
1606 if (buf[1] != 90)
1607 errx(1, "connection failed, SOCKS error %d", buf[1]);
1608 } else if (socksv == -1) {
1609 /* HTTP proxy CONNECT */
1610
1611 /* Disallow bad chars in hostname */
1612 if (strcspn(host, "\r\n\t []:") != strlen(host))
1613 errx(1, "Invalid hostname");
1614
1615 /* Try to be sane about numeric IPv6 addresses */
1616 if (strchr(host, ':') != NULL) {
1617 r = snprintf(buf, sizeof(buf),
1618 "CONNECT [%s]:%d HTTP/1.0\r\n",
1619 host, ntohs(serverport));
1620 } else {
1621 r = snprintf(buf, sizeof(buf),
1622 "CONNECT %s:%d HTTP/1.0\r\n",
1623 host, ntohs(serverport));
1624 }
1625 if (r == -1 || (size_t)r >= sizeof(buf))
1626 errx(1, "hostname too long");
1627 r = strlen(buf);
1628
1629 cnt = atomicio(vwrite, proxyfd, buf, r);
1630 if (cnt != (size_t)r)
1631 err(1, "write failed (%zu/%d)", cnt, r);
1632
1633 if (authretry > 1) {
1634 char resp[1024];
1635
1636 proxypass = getproxypass(proxyuser, proxyhost);
1637 r = snprintf(buf, sizeof(buf), "%s:%s",
1638 proxyuser, proxypass);
1639 if (r == -1 || (size_t)r >= sizeof(buf) ||
1640 b64_ntop(buf, strlen(buf), resp,
1641 sizeof(resp)) == -1)
1642 errx(1, "Proxy username/password too long");
1643 r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1644 "Basic %s\r\n", resp);
1645 if (r == -1 || (size_t)r >= sizeof(buf))
1646 errx(1, "Proxy auth response too long");
1647 r = strlen(buf);
1648 if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1649 err(1, "write failed (%zu/%d)", cnt, r);
1650 }
1651
1652 /* Terminate headers */
1653 if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1654 err(1, "write failed (2/%d)", r);
1655
1656 /* Read status reply */
1657 proxy_read_line(proxyfd, buf, sizeof(buf));
1658 if (proxyuser != NULL &&
1659 strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1660 if (authretry > 1) {
1661 fprintf(stderr, "Proxy authentication "
1662 "failed\n");
1663 }
1664 close(proxyfd);
1665 goto again;
1666 } else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1667 strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1668 errx(1, "Proxy error: \"%s\"", buf);
1669
1670 /* Headers continue until we hit an empty line */
1671 for (r = 0; r < HTTP_MAXHDRS; r++) {
1672 proxy_read_line(proxyfd, buf, sizeof(buf));
1673 if (*buf == '\0')
1674 break;
1675 }
1676 if (*buf != '\0')
1677 errx(1, "Too many proxy headers received");
1678 } else
1679 errx(1, "Unknown proxy protocol %d", socksv);
1680
1681 return (proxyfd);
1682}
1683