blob: 3f100bdd63cf6b7dd53f820280b92c748a534d7c [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)
272 err(1, NULL);
273 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)
407 err(1, NULL);
408 /*
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;
632#ifdef SO_RTABLE
633 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)
765 err(1, NULL);
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{
1017 struct msghdr mh;
1018 union {
1019 struct cmsghdr hdr;
1020 char buf[CMSG_SPACE(sizeof(int))];
1021 } cmsgbuf;
1022 struct cmsghdr *cmsg;
1023 struct iovec iov;
1024 char c = '\0';
1025 ssize_t r;
1026 struct pollfd pfd;
1027
1028 /* Avoid obvious stupidity */
1029 if (isatty(STDOUT_FILENO))
1030 errx(1, "Cannot pass file descriptor to tty");
1031
1032 bzero(&mh, sizeof(mh));
1033 bzero(&cmsgbuf, sizeof(cmsgbuf));
1034 bzero(&iov, sizeof(iov));
1035 bzero(&pfd, sizeof(pfd));
1036
1037 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1038 mh.msg_controllen = sizeof(cmsgbuf.buf);
1039 cmsg = CMSG_FIRSTHDR(&mh);
1040 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;
1044
1045 iov.iov_base = &c;
1046 iov.iov_len = 1;
1047 mh.msg_iov = &iov;
1048 mh.msg_iovlen = 1;
1049
1050 bzero(&pfd, sizeof(pfd));
1051 pfd.fd = STDOUT_FILENO;
1052 for (;;) {
1053 r = sendmsg(STDOUT_FILENO, &mh, 0);
1054 if (r == -1) {
1055 if (errno == EAGAIN || errno == EINTR) {
1056 pfd.events = POLLOUT;
1057 if (poll(&pfd, 1, -1) == -1)
1058 err(1, "poll");
1059 continue;
1060 }
1061 err(1, "sendmsg");
1062 } else if (r == -1)
1063 errx(1, "sendmsg: unexpected return value %zd", r);
1064 else
1065 break;
1066 }
1067 exit(0);
1068}
1069
1070/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1071void
1072atelnet(int nfd, unsigned char *buf, unsigned int size)
1073{
1074 unsigned char *p, *end;
1075 unsigned char obuf[4];
1076
1077 if (size < 3)
1078 return;
1079 end = buf + size - 2;
1080
1081 for (p = buf; p < end; p++) {
1082 if (*p != IAC)
1083 continue;
1084
1085 obuf[0] = IAC;
1086 p++;
1087 if ((*p == WILL) || (*p == WONT))
1088 obuf[1] = DONT;
1089 else if ((*p == DO) || (*p == DONT))
1090 obuf[1] = WONT;
1091 else
1092 continue;
1093
1094 p++;
1095 obuf[2] = *p;
1096 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1097 warn("Write Error!");
1098 }
1099}
1100
1101/*
1102 * build_ports()
1103 * Build an array of ports in portlist[], listing each port
1104 * that we should try to connect to.
1105 */
1106void
1107build_ports(char *p)
1108{
1109 const char *errstr;
1110 char *n;
1111 int hi, lo, cp;
1112 int x = 0;
1113
1114 if ((n = strchr(p, '-')) != NULL) {
1115 *n = '\0';
1116 n++;
1117
1118 /* Make sure the ports are in order: lowest->highest. */
1119 hi = strtonum(n, 1, PORT_MAX, &errstr);
1120 if (errstr)
1121 errx(1, "port number %s: %s", errstr, n);
1122 lo = strtonum(p, 1, PORT_MAX, &errstr);
1123 if (errstr)
1124 errx(1, "port number %s: %s", errstr, p);
1125
1126 if (lo > hi) {
1127 cp = hi;
1128 hi = lo;
1129 lo = cp;
1130 }
1131
1132 /* Load ports sequentially. */
1133 for (cp = lo; cp <= hi; cp++) {
1134 portlist[x] = calloc(1, PORT_MAX_LEN);
1135 if (portlist[x] == NULL)
1136 err(1, NULL);
1137 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1138 x++;
1139 }
1140
1141 /* Randomly swap ports. */
1142 if (rflag) {
1143 int y;
1144 char *c;
1145
1146 for (x = 0; x <= (hi - lo); x++) {
1147 y = (arc4random() & 0xFFFF) % (hi - lo);
1148 c = portlist[x];
1149 portlist[x] = portlist[y];
1150 portlist[y] = c;
1151 }
1152 }
1153 } else {
1154 hi = strtonum(p, 1, PORT_MAX, &errstr);
1155 if (errstr)
1156 errx(1, "port number %s: %s", errstr, p);
1157 portlist[0] = strdup(p);
1158 if (portlist[0] == NULL)
1159 err(1, NULL);
1160 }
1161}
1162
1163/*
1164 * udptest()
1165 * Do a few writes to see if the UDP port is there.
1166 * Fails once PF state table is full.
1167 */
1168int
1169udptest(int s)
1170{
1171 int i, ret;
1172
1173 for (i = 0; i <= 3; i++) {
1174 if (write(s, "X", 1) == 1)
1175 ret = 1;
1176 else
1177 ret = -1;
1178 }
1179 return (ret);
1180}
1181
1182void
1183set_common_sockopts(int s)
1184{
1185 int x = 1;
1186
Damien Miller69ff64f2015-01-27 23:07:43 +11001187#ifdef TCP_MD5SIG
Damien Miller293cac52014-12-22 16:30:42 +11001188 if (Sflag) {
1189 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1190 &x, sizeof(x)) == -1)
1191 err(1, NULL);
1192 }
Damien Miller69ff64f2015-01-27 23:07:43 +11001193#endif
Damien Miller293cac52014-12-22 16:30:42 +11001194 if (Dflag) {
1195 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1196 &x, sizeof(x)) == -1)
1197 err(1, NULL);
1198 }
1199 if (Tflag != -1) {
1200 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1201 &Tflag, sizeof(Tflag)) == -1)
1202 err(1, "set IP ToS");
1203 }
1204 if (Iflag) {
1205 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1206 &Iflag, sizeof(Iflag)) == -1)
1207 err(1, "set TCP receive buffer size");
1208 }
1209 if (Oflag) {
1210 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1211 &Oflag, sizeof(Oflag)) == -1)
1212 err(1, "set TCP send buffer size");
1213 }
1214}
1215
1216int
1217map_tos(char *s, int *val)
1218{
1219 /* DiffServ Codepoints and other TOS mappings */
1220 const struct toskeywords {
1221 const char *keyword;
1222 int val;
1223 } *t, toskeywords[] = {
1224 { "af11", IPTOS_DSCP_AF11 },
1225 { "af12", IPTOS_DSCP_AF12 },
1226 { "af13", IPTOS_DSCP_AF13 },
1227 { "af21", IPTOS_DSCP_AF21 },
1228 { "af22", IPTOS_DSCP_AF22 },
1229 { "af23", IPTOS_DSCP_AF23 },
1230 { "af31", IPTOS_DSCP_AF31 },
1231 { "af32", IPTOS_DSCP_AF32 },
1232 { "af33", IPTOS_DSCP_AF33 },
1233 { "af41", IPTOS_DSCP_AF41 },
1234 { "af42", IPTOS_DSCP_AF42 },
1235 { "af43", IPTOS_DSCP_AF43 },
1236 { "critical", IPTOS_PREC_CRITIC_ECP },
1237 { "cs0", IPTOS_DSCP_CS0 },
1238 { "cs1", IPTOS_DSCP_CS1 },
1239 { "cs2", IPTOS_DSCP_CS2 },
1240 { "cs3", IPTOS_DSCP_CS3 },
1241 { "cs4", IPTOS_DSCP_CS4 },
1242 { "cs5", IPTOS_DSCP_CS5 },
1243 { "cs6", IPTOS_DSCP_CS6 },
1244 { "cs7", IPTOS_DSCP_CS7 },
1245 { "ef", IPTOS_DSCP_EF },
1246 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1247 { "lowdelay", IPTOS_LOWDELAY },
1248 { "netcontrol", IPTOS_PREC_NETCONTROL },
1249 { "reliability", IPTOS_RELIABILITY },
1250 { "throughput", IPTOS_THROUGHPUT },
1251 { NULL, -1 },
1252 };
1253
1254 for (t = toskeywords; t->keyword != NULL; t++) {
1255 if (strcmp(s, t->keyword) == 0) {
1256 *val = t->val;
1257 return (1);
1258 }
1259 }
1260
1261 return (0);
1262}
1263
1264void
1265report_connect(const struct sockaddr *sa, socklen_t salen)
1266{
1267 char remote_host[NI_MAXHOST];
1268 char remote_port[NI_MAXSERV];
1269 int herr;
1270 int flags = NI_NUMERICSERV;
1271
1272 if (nflag)
1273 flags |= NI_NUMERICHOST;
1274
1275 if ((herr = getnameinfo(sa, salen,
1276 remote_host, sizeof(remote_host),
1277 remote_port, sizeof(remote_port),
1278 flags)) != 0) {
1279 if (herr == EAI_SYSTEM)
1280 err(1, "getnameinfo");
1281 else
1282 errx(1, "getnameinfo: %s", gai_strerror(herr));
1283 }
1284
1285 fprintf(stderr,
1286 "Connection from %s %s "
1287 "received!\n", remote_host, remote_port);
1288}
1289
1290void
1291help(void)
1292{
1293 usage(0);
1294 fprintf(stderr, "\tCommand Summary:\n\
1295 \t-4 Use IPv4\n\
1296 \t-6 Use IPv6\n\
1297 \t-D Enable the debug socket option\n\
1298 \t-d Detach from stdin\n\
1299 \t-F Pass socket fd\n\
1300 \t-h This help text\n\
1301 \t-I length TCP receive buffer length\n\
1302 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1303 \t-k Keep inbound sockets open for multiple connects\n\
1304 \t-l Listen mode, for inbound connects\n\
1305 \t-N Shutdown the network socket after EOF on stdin\n\
1306 \t-n Suppress name/port resolutions\n\
1307 \t-O length TCP send buffer length\n\
1308 \t-P proxyuser\tUsername for proxy authentication\n\
1309 \t-p port\t Specify local port for remote connects\n\
1310 \t-r Randomize remote ports\n\
1311 \t-S Enable the TCP MD5 signature option\n\
1312 \t-s addr\t Local source address\n\
1313 \t-T toskeyword\tSet IP Type of Service\n\
1314 \t-t Answer TELNET negotiation\n\
1315 \t-U Use UNIX domain socket\n\
1316 \t-u UDP mode\n\
1317 \t-V rtable Specify alternate routing table\n\
1318 \t-v Verbose\n\
1319 \t-w secs\t Timeout for connects and final net reads\n\
1320 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1321 \t-x addr[:port]\tSpecify proxy address and port\n\
1322 \t-z Zero-I/O mode [used for scanning]\n\
1323 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1324 exit(1);
1325}
1326
1327void
1328usage(int ret)
1329{
1330 fprintf(stderr,
1331 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1332 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1333 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1334 "\t [-x proxy_address[:port]] [destination] [port]\n");
1335 if (ret)
1336 exit(1);
1337}
1338
1339/* *** src/usr.bin/nc/socks.c *** */
1340
1341
1342/* $OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $ */
1343
1344/*
1345 * Copyright (c) 1999 Niklas Hallqvist. All rights reserved.
1346 * Copyright (c) 2004, 2005 Damien Miller. All rights reserved.
1347 *
1348 * Redistribution and use in source and binary forms, with or without
1349 * modification, are permitted provided that the following conditions
1350 * are met:
1351 * 1. Redistributions of source code must retain the above copyright
1352 * notice, this list of conditions and the following disclaimer.
1353 * 2. Redistributions in binary form must reproduce the above copyright
1354 * notice, this list of conditions and the following disclaimer in the
1355 * documentation and/or other materials provided with the distribution.
1356 *
1357 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1358 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1359 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1360 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1361 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1362 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1363 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1364 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1365 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1366 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1367 */
1368
1369#include <sys/types.h>
1370#include <sys/socket.h>
1371#include <netinet/in.h>
1372#include <arpa/inet.h>
1373
Damien Miller293cac52014-12-22 16:30:42 +11001374#include <errno.h>
1375#include <netdb.h>
1376#include <stdio.h>
1377#include <stdlib.h>
1378#include <string.h>
1379#include <unistd.h>
1380#include <resolv.h>
1381
1382#define SOCKS_PORT "1080"
1383#define HTTP_PROXY_PORT "3128"
1384#define HTTP_MAXHDRS 64
1385#define SOCKS_V5 5
1386#define SOCKS_V4 4
1387#define SOCKS_NOAUTH 0
1388#define SOCKS_NOMETHOD 0xff
1389#define SOCKS_CONNECT 1
1390#define SOCKS_IPV4 1
1391#define SOCKS_DOMAIN 3
1392#define SOCKS_IPV6 4
1393
1394int remote_connect(const char *, const char *, struct addrinfo);
1395int socks_connect(const char *, const char *, struct addrinfo,
1396 const char *, const char *, struct addrinfo, int,
1397 const char *);
1398
1399static int
1400decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1401 socklen_t addrlen, int v4only, int numeric)
1402{
1403 int r;
1404 struct addrinfo hints, *res;
1405
1406 bzero(&hints, sizeof(hints));
1407 hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1408 hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1409 hints.ai_socktype = SOCK_STREAM;
1410 r = getaddrinfo(h, p, &hints, &res);
1411 /* Don't fatal when attempting to convert a numeric address */
1412 if (r != 0) {
1413 if (!numeric) {
1414 errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1415 gai_strerror(r));
1416 }
1417 return (-1);
1418 }
1419 if (addrlen < res->ai_addrlen) {
1420 freeaddrinfo(res);
1421 errx(1, "internal error: addrlen < res->ai_addrlen");
1422 }
1423 memcpy(addr, res->ai_addr, res->ai_addrlen);
1424 freeaddrinfo(res);
1425 return (0);
1426}
1427
1428static int
1429proxy_read_line(int fd, char *buf, size_t bufsz)
1430{
1431 size_t off;
1432
1433 for(off = 0;;) {
1434 if (off >= bufsz)
1435 errx(1, "proxy read too long");
1436 if (atomicio(read, fd, buf + off, 1) != 1)
1437 err(1, "proxy read");
1438 /* Skip CR */
1439 if (buf[off] == '\r')
1440 continue;
1441 if (buf[off] == '\n') {
1442 buf[off] = '\0';
1443 break;
1444 }
1445 off++;
1446 }
1447 return (off);
1448}
1449
1450static const char *
1451getproxypass(const char *proxyuser, const char *proxyhost)
1452{
1453 char prompt[512];
1454 static char pw[256];
1455
1456 snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1457 proxyuser, proxyhost);
1458 if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1459 errx(1, "Unable to read proxy passphrase");
1460 return (pw);
1461}
1462
1463int
1464socks_connect(const char *host, const char *port,
1465 struct addrinfo hints __attribute__ ((__unused__)),
1466 const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1467 int socksv, const char *proxyuser)
1468{
1469 int proxyfd, r, authretry = 0;
1470 size_t hlen, wlen;
1471 unsigned char buf[1024];
1472 size_t cnt;
1473 struct sockaddr_storage addr;
1474 struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1475 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1476 in_port_t serverport;
1477 const char *proxypass = NULL;
1478
1479 if (proxyport == NULL)
1480 proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1481
1482 /* Abuse API to lookup port */
1483 if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1484 sizeof(addr), 1, 1) == -1)
1485 errx(1, "unknown port \"%.64s\"", port);
1486 serverport = in4->sin_port;
1487
1488 again:
1489 if (authretry++ > 3)
1490 errx(1, "Too many authentication failures");
1491
1492 proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1493
1494 if (proxyfd < 0)
1495 return (-1);
1496
1497 if (socksv == 5) {
1498 if (decode_addrport(host, port, (struct sockaddr *)&addr,
1499 sizeof(addr), 0, 1) == -1)
1500 addr.ss_family = 0; /* used in switch below */
1501
1502 /* Version 5, one method: no authentication */
1503 buf[0] = SOCKS_V5;
1504 buf[1] = 1;
1505 buf[2] = SOCKS_NOAUTH;
1506 cnt = atomicio(vwrite, proxyfd, buf, 3);
1507 if (cnt != 3)
1508 err(1, "write failed (%zu/3)", cnt);
1509
1510 cnt = atomicio(read, proxyfd, buf, 2);
1511 if (cnt != 2)
1512 err(1, "read failed (%zu/3)", cnt);
1513
1514 if (buf[1] == SOCKS_NOMETHOD)
1515 errx(1, "authentication method negotiation failed");
1516
1517 switch (addr.ss_family) {
1518 case 0:
1519 /* Version 5, connect: domain name */
1520
1521 /* Max domain name length is 255 bytes */
1522 hlen = strlen(host);
1523 if (hlen > 255)
1524 errx(1, "host name too long for SOCKS5");
1525 buf[0] = SOCKS_V5;
1526 buf[1] = SOCKS_CONNECT;
1527 buf[2] = 0;
1528 buf[3] = SOCKS_DOMAIN;
1529 buf[4] = hlen;
1530 memcpy(buf + 5, host, hlen);
1531 memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1532 wlen = 7 + hlen;
1533 break;
1534 case AF_INET:
1535 /* Version 5, connect: IPv4 address */
1536 buf[0] = SOCKS_V5;
1537 buf[1] = SOCKS_CONNECT;
1538 buf[2] = 0;
1539 buf[3] = SOCKS_IPV4;
1540 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1541 memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1542 wlen = 10;
1543 break;
1544 case AF_INET6:
1545 /* Version 5, connect: IPv6 address */
1546 buf[0] = SOCKS_V5;
1547 buf[1] = SOCKS_CONNECT;
1548 buf[2] = 0;
1549 buf[3] = SOCKS_IPV6;
1550 memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1551 memcpy(buf + 20, &in6->sin6_port,
1552 sizeof in6->sin6_port);
1553 wlen = 22;
1554 break;
1555 default:
1556 errx(1, "internal error: silly AF");
1557 }
1558
1559 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1560 if (cnt != wlen)
1561 err(1, "write failed (%zu/%zu)", cnt, wlen);
1562
1563 cnt = atomicio(read, proxyfd, buf, 4);
1564 if (cnt != 4)
1565 err(1, "read failed (%zu/4)", cnt);
1566 if (buf[1] != 0)
1567 errx(1, "connection failed, SOCKS error %d", buf[1]);
1568 switch (buf[3]) {
1569 case SOCKS_IPV4:
1570 cnt = atomicio(read, proxyfd, buf + 4, 6);
1571 if (cnt != 6)
1572 err(1, "read failed (%zu/6)", cnt);
1573 break;
1574 case SOCKS_IPV6:
1575 cnt = atomicio(read, proxyfd, buf + 4, 18);
1576 if (cnt != 18)
1577 err(1, "read failed (%zu/18)", cnt);
1578 break;
1579 default:
1580 errx(1, "connection failed, unsupported address type");
1581 }
1582 } else if (socksv == 4) {
1583 /* This will exit on lookup failure */
1584 decode_addrport(host, port, (struct sockaddr *)&addr,
1585 sizeof(addr), 1, 0);
1586
1587 /* Version 4 */
1588 buf[0] = SOCKS_V4;
1589 buf[1] = SOCKS_CONNECT; /* connect */
1590 memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1591 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1592 buf[8] = 0; /* empty username */
1593 wlen = 9;
1594
1595 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1596 if (cnt != wlen)
1597 err(1, "write failed (%zu/%zu)", cnt, wlen);
1598
1599 cnt = atomicio(read, proxyfd, buf, 8);
1600 if (cnt != 8)
1601 err(1, "read failed (%zu/8)", cnt);
1602 if (buf[1] != 90)
1603 errx(1, "connection failed, SOCKS error %d", buf[1]);
1604 } else if (socksv == -1) {
1605 /* HTTP proxy CONNECT */
1606
1607 /* Disallow bad chars in hostname */
1608 if (strcspn(host, "\r\n\t []:") != strlen(host))
1609 errx(1, "Invalid hostname");
1610
1611 /* Try to be sane about numeric IPv6 addresses */
1612 if (strchr(host, ':') != NULL) {
1613 r = snprintf(buf, sizeof(buf),
1614 "CONNECT [%s]:%d HTTP/1.0\r\n",
1615 host, ntohs(serverport));
1616 } else {
1617 r = snprintf(buf, sizeof(buf),
1618 "CONNECT %s:%d HTTP/1.0\r\n",
1619 host, ntohs(serverport));
1620 }
1621 if (r == -1 || (size_t)r >= sizeof(buf))
1622 errx(1, "hostname too long");
1623 r = strlen(buf);
1624
1625 cnt = atomicio(vwrite, proxyfd, buf, r);
1626 if (cnt != (size_t)r)
1627 err(1, "write failed (%zu/%d)", cnt, r);
1628
1629 if (authretry > 1) {
1630 char resp[1024];
1631
1632 proxypass = getproxypass(proxyuser, proxyhost);
1633 r = snprintf(buf, sizeof(buf), "%s:%s",
1634 proxyuser, proxypass);
1635 if (r == -1 || (size_t)r >= sizeof(buf) ||
1636 b64_ntop(buf, strlen(buf), resp,
1637 sizeof(resp)) == -1)
1638 errx(1, "Proxy username/password too long");
1639 r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1640 "Basic %s\r\n", resp);
1641 if (r == -1 || (size_t)r >= sizeof(buf))
1642 errx(1, "Proxy auth response too long");
1643 r = strlen(buf);
1644 if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1645 err(1, "write failed (%zu/%d)", cnt, r);
1646 }
1647
1648 /* Terminate headers */
1649 if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1650 err(1, "write failed (2/%d)", r);
1651
1652 /* Read status reply */
1653 proxy_read_line(proxyfd, buf, sizeof(buf));
1654 if (proxyuser != NULL &&
1655 strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1656 if (authretry > 1) {
1657 fprintf(stderr, "Proxy authentication "
1658 "failed\n");
1659 }
1660 close(proxyfd);
1661 goto again;
1662 } else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1663 strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1664 errx(1, "Proxy error: \"%s\"", buf);
1665
1666 /* Headers continue until we hit an empty line */
1667 for (r = 0; r < HTTP_MAXHDRS; r++) {
1668 proxy_read_line(proxyfd, buf, sizeof(buf));
1669 if (*buf == '\0')
1670 break;
1671 }
1672 if (*buf != '\0')
1673 errx(1, "Too many proxy headers received");
1674 } else
1675 errx(1, "Unknown proxy protocol %d", socksv);
1676
1677 return (proxyfd);
1678}
1679