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