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