blob: 56bd09de54855b85a9b8c9bf719ec4564650988c [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>
Damien Miller293cac52014-12-22 16:30:42 +110045
Damien Miller293cac52014-12-22 16:30:42 +110046#include <errno.h>
47#include <netdb.h>
Damien Miller293cac52014-12-22 16:30:42 +110048#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
Damien Millera05adf92015-03-04 00:55:48 -080057#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
Damien Miller8aaec702016-07-14 09:48:48 +100064#ifdef HAVE_ERR_H
65# include <err.h>
66#endif
Damien Millera05adf92015-03-04 00:55:48 -080067
Damien Miller673a1c12015-04-16 11:40:20 +100068/* 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
Damien Miller293cac52014-12-22 16:30:42 +110075#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 */
91int dflag; /* detached, no stdin */
92int Fflag; /* fdpass sock to stdout */
93unsigned int iflag; /* Interval Flag */
94int kflag; /* More than one connect */
95int lflag; /* Bind to local port */
96int Nflag; /* shutdown() network socket */
97int nflag; /* Don't do name look up */
98char *Pflag; /* Proxy username */
99char *pflag; /* Localport flag */
100int rflag; /* Random ports flag */
101char *sflag; /* Source Address */
102int tflag; /* Telnet Emulation */
103int uflag; /* UDP - Default to TCP */
104int vflag; /* Verbosity */
105int xflag; /* Socks proxy */
106int zflag; /* Port Scan Flag */
107int Dflag; /* sodebug */
108int Iflag; /* TCP receive buffer size */
109int Oflag; /* TCP send buffer size */
110int Sflag; /* TCP MD5 signature option */
111int Tflag = -1; /* IP Type of Service */
112int rtableid = -1;
113
114int timeout = -1;
115int family = AF_UNSPEC;
116char *portlist[PORT_MAX+1];
117char *unix_dg_tmp_socket;
118
119void atelnet(int, unsigned char *, unsigned int);
120void build_ports(char *);
121void help(void);
122int local_listen(char *, char *, struct addrinfo);
123void readwrite(int);
124void fdpass(int nfd) __attribute__((noreturn));
125int remote_connect(const char *, const char *, struct addrinfo);
126int timeout_connect(int, const struct sockaddr *, socklen_t);
127int socks_connect(const char *, const char *, struct addrinfo,
128 const char *, const char *, struct addrinfo, int, const char *);
129int udptest(int);
130int unix_bind(char *);
131int unix_connect(char *);
132int unix_listen(char *);
133void set_common_sockopts(int);
134int map_tos(char *, int *);
135void report_connect(const struct sockaddr *, socklen_t);
136void usage(int);
137ssize_t drainbuf(int, unsigned char *, size_t *);
138ssize_t fillbuf(int, unsigned char *, size_t *);
139
Tim Rice13af3422015-02-24 07:56:47 -0800140
Damien Miller293cac52014-12-22 16:30:42 +1100141int
142main(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)
Damien Millere47536b2015-02-28 08:20:11 -0800248 errx(1, "strdup");
Damien Miller293cac52014-12-22 16:30:42 +1100249 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)
Damien Millere47536b2015-02-28 08:20:11 -0800383 err(1, "local_listen");
Damien Miller293cac52014-12-22 16:30:42 +1100384 /*
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 */
516int
517unix_bind(char *path)
518{
Tim Rice13af3422015-02-24 07:56:47 -0800519 struct sockaddr_un sun_sa;
Damien Miller293cac52014-12-22 16:30:42 +1100520 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
Tim Rice13af3422015-02-24 07:56:47 -0800527 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
528 sun_sa.sun_family = AF_UNIX;
Damien Miller293cac52014-12-22 16:30:42 +1100529
Tim Rice13af3422015-02-24 07:56:47 -0800530 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
531 sizeof(sun_sa.sun_path)) {
Damien Miller293cac52014-12-22 16:30:42 +1100532 close(s);
533 errno = ENAMETOOLONG;
534 return (-1);
535 }
536
Tim Rice13af3422015-02-24 07:56:47 -0800537 if (bind(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
Damien Miller293cac52014-12-22 16:30:42 +1100538 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 */
548int
549unix_connect(char *path)
550{
Tim Rice13af3422015-02-24 07:56:47 -0800551 struct sockaddr_un sun_sa;
Damien Miller293cac52014-12-22 16:30:42 +1100552 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
Tim Rice13af3422015-02-24 07:56:47 -0800563 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
564 sun_sa.sun_family = AF_UNIX;
Damien Miller293cac52014-12-22 16:30:42 +1100565
Tim Rice13af3422015-02-24 07:56:47 -0800566 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
567 sizeof(sun_sa.sun_path)) {
Damien Miller293cac52014-12-22 16:30:42 +1100568 close(s);
569 errno = ENAMETOOLONG;
570 return (-1);
571 }
Tim Rice13af3422015-02-24 07:56:47 -0800572 if (connect(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
Damien Miller293cac52014-12-22 16:30:42 +1100573 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 */
584int
585unix_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 */
603int
604remote_connect(const char *host, const char *port, struct addrinfo hints)
605{
606 struct addrinfo *res, *res0;
607 int s, error;
Damien Millere47536b2015-02-28 08:20:11 -0800608#if defined(SO_RTABLE) || defined(SO_BINDANY)
Damien Miller293cac52014-12-22 16:30:42 +1100609 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
665int
666timeout_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 */
707int
708local_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
Damien Millerc3321102015-01-15 02:59:51 +1100738#ifdef SO_REUSEPORT
Damien Miller293cac52014-12-22 16:30:42 +1100739 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
740 if (ret == -1)
Darren Tuckeraee49b22018-02-08 12:36:22 +1100741 err(1, "setsockopt SO_REUSEPORT");
742#endif
743#ifdef SO_REUSEADDR
744 ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
745 if (ret == -1)
746 err(1, "setsockopt SO_REUSEADDR");
Damien Millerc3321102015-01-15 02:59:51 +1100747#endif
Damien Miller293cac52014-12-22 16:30:42 +1100748 set_common_sockopts(s);
749
750 if (bind(s, (struct sockaddr *)res0->ai_addr,
751 res0->ai_addrlen) == 0)
752 break;
753
754 close(s);
755 s = -1;
756 } while ((res0 = res0->ai_next) != NULL);
757
758 if (!uflag && s != -1) {
759 if (listen(s, 1) < 0)
760 err(1, "listen");
761 }
762
763 freeaddrinfo(res);
764
765 return (s);
766}
767
768/*
769 * readwrite()
770 * Loop that polls on the network file descriptor and stdin.
771 */
772void
773readwrite(int net_fd)
774{
775 struct pollfd pfd[4];
776 int stdin_fd = STDIN_FILENO;
777 int stdout_fd = STDOUT_FILENO;
778 unsigned char netinbuf[BUFSIZE];
779 size_t netinbufpos = 0;
780 unsigned char stdinbuf[BUFSIZE];
781 size_t stdinbufpos = 0;
782 int n, num_fds;
783 ssize_t ret;
784
785 /* don't read from stdin if requested */
786 if (dflag)
787 stdin_fd = -1;
788
789 /* stdin */
790 pfd[POLL_STDIN].fd = stdin_fd;
791 pfd[POLL_STDIN].events = POLLIN;
792
793 /* network out */
794 pfd[POLL_NETOUT].fd = net_fd;
795 pfd[POLL_NETOUT].events = 0;
796
797 /* network in */
798 pfd[POLL_NETIN].fd = net_fd;
799 pfd[POLL_NETIN].events = POLLIN;
800
801 /* stdout */
802 pfd[POLL_STDOUT].fd = stdout_fd;
803 pfd[POLL_STDOUT].events = 0;
804
805 while (1) {
806 /* both inputs are gone, buffers are empty, we are done */
807 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
808 && stdinbufpos == 0 && netinbufpos == 0) {
809 close(net_fd);
810 return;
811 }
812 /* both outputs are gone, we can't continue */
813 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
814 close(net_fd);
815 return;
816 }
817 /* listen and net in gone, queues empty, done */
818 if (lflag && pfd[POLL_NETIN].fd == -1
819 && stdinbufpos == 0 && netinbufpos == 0) {
820 close(net_fd);
821 return;
822 }
823
824 /* help says -i is for "wait between lines sent". We read and
825 * write arbitrary amounts of data, and we don't want to start
826 * scanning for newlines, so this is as good as it gets */
827 if (iflag)
828 sleep(iflag);
829
830 /* poll */
831 num_fds = poll(pfd, 4, timeout);
832
833 /* treat poll errors */
834 if (num_fds == -1) {
835 close(net_fd);
836 err(1, "polling error");
837 }
838
839 /* timeout happened */
840 if (num_fds == 0)
841 return;
842
843 /* treat socket error conditions */
844 for (n = 0; n < 4; n++) {
845 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
846 pfd[n].fd = -1;
847 }
848 }
849 /* reading is possible after HUP */
850 if (pfd[POLL_STDIN].events & POLLIN &&
851 pfd[POLL_STDIN].revents & POLLHUP &&
852 ! (pfd[POLL_STDIN].revents & POLLIN))
853 pfd[POLL_STDIN].fd = -1;
854
855 if (pfd[POLL_NETIN].events & POLLIN &&
856 pfd[POLL_NETIN].revents & POLLHUP &&
857 ! (pfd[POLL_NETIN].revents & POLLIN))
858 pfd[POLL_NETIN].fd = -1;
859
860 if (pfd[POLL_NETOUT].revents & POLLHUP) {
861 if (Nflag)
862 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
863 pfd[POLL_NETOUT].fd = -1;
864 }
865 /* if HUP, stop watching stdout */
866 if (pfd[POLL_STDOUT].revents & POLLHUP)
867 pfd[POLL_STDOUT].fd = -1;
868 /* if no net out, stop watching stdin */
869 if (pfd[POLL_NETOUT].fd == -1)
870 pfd[POLL_STDIN].fd = -1;
871 /* if no stdout, stop watching net in */
872 if (pfd[POLL_STDOUT].fd == -1) {
873 if (pfd[POLL_NETIN].fd != -1)
874 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
875 pfd[POLL_NETIN].fd = -1;
876 }
877
878 /* try to read from stdin */
879 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
880 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
881 &stdinbufpos);
882 /* error or eof on stdin - remove from pfd */
883 if (ret == 0 || ret == -1)
884 pfd[POLL_STDIN].fd = -1;
885 /* read something - poll net out */
886 if (stdinbufpos > 0)
887 pfd[POLL_NETOUT].events = POLLOUT;
888 /* filled buffer - remove self from polling */
889 if (stdinbufpos == BUFSIZE)
890 pfd[POLL_STDIN].events = 0;
891 }
892 /* try to write to network */
893 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
894 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
895 &stdinbufpos);
896 if (ret == -1)
897 pfd[POLL_NETOUT].fd = -1;
898 /* buffer empty - remove self from polling */
899 if (stdinbufpos == 0)
900 pfd[POLL_NETOUT].events = 0;
901 /* buffer no longer full - poll stdin again */
902 if (stdinbufpos < BUFSIZE)
903 pfd[POLL_STDIN].events = POLLIN;
904 }
905 /* try to read from network */
906 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
907 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
908 &netinbufpos);
909 if (ret == -1)
910 pfd[POLL_NETIN].fd = -1;
911 /* eof on net in - remove from pfd */
912 if (ret == 0) {
913 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
914 pfd[POLL_NETIN].fd = -1;
915 }
916 /* read something - poll stdout */
917 if (netinbufpos > 0)
918 pfd[POLL_STDOUT].events = POLLOUT;
919 /* filled buffer - remove self from polling */
920 if (netinbufpos == BUFSIZE)
921 pfd[POLL_NETIN].events = 0;
922 /* handle telnet */
923 if (tflag)
924 atelnet(pfd[POLL_NETIN].fd, netinbuf,
925 netinbufpos);
926 }
927 /* try to write to stdout */
928 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
929 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
930 &netinbufpos);
931 if (ret == -1)
932 pfd[POLL_STDOUT].fd = -1;
933 /* buffer empty - remove self from polling */
934 if (netinbufpos == 0)
935 pfd[POLL_STDOUT].events = 0;
936 /* buffer no longer full - poll net in again */
937 if (netinbufpos < BUFSIZE)
938 pfd[POLL_NETIN].events = POLLIN;
939 }
940
941 /* stdin gone and queue empty? */
942 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
943 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
944 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
945 pfd[POLL_NETOUT].fd = -1;
946 }
947 /* net in gone and queue empty? */
948 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
949 pfd[POLL_STDOUT].fd = -1;
950 }
951 }
952}
953
954ssize_t
955drainbuf(int fd, unsigned char *buf, size_t *bufpos)
956{
957 ssize_t n;
958 ssize_t adjust;
959
960 n = write(fd, buf, *bufpos);
961 /* don't treat EAGAIN, EINTR as error */
962 if (n == -1 && (errno == EAGAIN || errno == EINTR))
963 n = -2;
964 if (n <= 0)
965 return n;
966 /* adjust buffer */
967 adjust = *bufpos - n;
968 if (adjust > 0)
969 memmove(buf, buf + n, adjust);
970 *bufpos -= n;
971 return n;
972}
973
974
975ssize_t
976fillbuf(int fd, unsigned char *buf, size_t *bufpos)
977{
978 size_t num = BUFSIZE - *bufpos;
979 ssize_t n;
980
981 n = read(fd, buf + *bufpos, num);
982 /* don't treat EAGAIN, EINTR as error */
983 if (n == -1 && (errno == EAGAIN || errno == EINTR))
984 n = -2;
985 if (n <= 0)
986 return n;
987 *bufpos += n;
988 return n;
989}
990
991/*
992 * fdpass()
993 * Pass the connected file descriptor to stdout and exit.
994 */
995void
996fdpass(int nfd)
997{
Damien Miller1ad3a772015-02-26 20:33:22 -0800998#if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR))
999 struct msghdr msg;
1000#ifndef HAVE_ACCRIGHTS_IN_MSGHDR
Damien Miller293cac52014-12-22 16:30:42 +11001001 union {
1002 struct cmsghdr hdr;
1003 char buf[CMSG_SPACE(sizeof(int))];
1004 } cmsgbuf;
1005 struct cmsghdr *cmsg;
Damien Miller1ad3a772015-02-26 20:33:22 -08001006#endif
1007 struct iovec vec;
1008 char ch = '\0';
Damien Miller293cac52014-12-22 16:30:42 +11001009 struct pollfd pfd;
Damien Miller1ad3a772015-02-26 20:33:22 -08001010 ssize_t r;
Damien Miller293cac52014-12-22 16:30:42 +11001011
Damien Miller1ad3a772015-02-26 20:33:22 -08001012 memset(&msg, 0, sizeof(msg));
1013#ifdef HAVE_ACCRIGHTS_IN_MSGHDR
1014 msg.msg_accrights = (caddr_t)&nfd;
1015 msg.msg_accrightslen = sizeof(nfd);
1016#else
1017 memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1018 msg.msg_control = (caddr_t)&cmsgbuf.buf;
1019 msg.msg_controllen = sizeof(cmsgbuf.buf);
1020 cmsg = CMSG_FIRSTHDR(&msg);
Damien Miller293cac52014-12-22 16:30:42 +11001021 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1022 cmsg->cmsg_level = SOL_SOCKET;
1023 cmsg->cmsg_type = SCM_RIGHTS;
1024 *(int *)CMSG_DATA(cmsg) = nfd;
Damien Miller1ad3a772015-02-26 20:33:22 -08001025#endif
Damien Miller293cac52014-12-22 16:30:42 +11001026
Damien Miller1ad3a772015-02-26 20:33:22 -08001027 vec.iov_base = &ch;
1028 vec.iov_len = 1;
1029 msg.msg_iov = &vec;
1030 msg.msg_iovlen = 1;
Damien Miller293cac52014-12-22 16:30:42 +11001031
1032 bzero(&pfd, sizeof(pfd));
1033 pfd.fd = STDOUT_FILENO;
1034 for (;;) {
Damien Miller1ad3a772015-02-26 20:33:22 -08001035 r = sendmsg(STDOUT_FILENO, &msg, 0);
Damien Miller293cac52014-12-22 16:30:42 +11001036 if (r == -1) {
1037 if (errno == EAGAIN || errno == EINTR) {
1038 pfd.events = POLLOUT;
1039 if (poll(&pfd, 1, -1) == -1)
1040 err(1, "poll");
1041 continue;
1042 }
1043 err(1, "sendmsg");
1044 } else if (r == -1)
1045 errx(1, "sendmsg: unexpected return value %zd", r);
1046 else
1047 break;
1048 }
1049 exit(0);
Damien Miller1ad3a772015-02-26 20:33:22 -08001050#else
1051 errx(1, "%s: file descriptor passing not supported", __func__);
1052#endif
Damien Miller293cac52014-12-22 16:30:42 +11001053}
1054
1055/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1056void
1057atelnet(int nfd, unsigned char *buf, unsigned int size)
1058{
1059 unsigned char *p, *end;
1060 unsigned char obuf[4];
1061
1062 if (size < 3)
1063 return;
1064 end = buf + size - 2;
1065
1066 for (p = buf; p < end; p++) {
1067 if (*p != IAC)
1068 continue;
1069
1070 obuf[0] = IAC;
1071 p++;
1072 if ((*p == WILL) || (*p == WONT))
1073 obuf[1] = DONT;
1074 else if ((*p == DO) || (*p == DONT))
1075 obuf[1] = WONT;
1076 else
1077 continue;
1078
1079 p++;
1080 obuf[2] = *p;
1081 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1082 warn("Write Error!");
1083 }
1084}
1085
1086/*
1087 * build_ports()
1088 * Build an array of ports in portlist[], listing each port
1089 * that we should try to connect to.
1090 */
1091void
1092build_ports(char *p)
1093{
1094 const char *errstr;
1095 char *n;
1096 int hi, lo, cp;
1097 int x = 0;
1098
1099 if ((n = strchr(p, '-')) != NULL) {
1100 *n = '\0';
1101 n++;
1102
1103 /* Make sure the ports are in order: lowest->highest. */
1104 hi = strtonum(n, 1, PORT_MAX, &errstr);
1105 if (errstr)
1106 errx(1, "port number %s: %s", errstr, n);
1107 lo = strtonum(p, 1, PORT_MAX, &errstr);
1108 if (errstr)
1109 errx(1, "port number %s: %s", errstr, p);
1110
1111 if (lo > hi) {
1112 cp = hi;
1113 hi = lo;
1114 lo = cp;
1115 }
1116
1117 /* Load ports sequentially. */
1118 for (cp = lo; cp <= hi; cp++) {
1119 portlist[x] = calloc(1, PORT_MAX_LEN);
1120 if (portlist[x] == NULL)
Damien Millere47536b2015-02-28 08:20:11 -08001121 errx(1, "calloc");
Damien Miller293cac52014-12-22 16:30:42 +11001122 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1123 x++;
1124 }
1125
1126 /* Randomly swap ports. */
1127 if (rflag) {
1128 int y;
1129 char *c;
1130
1131 for (x = 0; x <= (hi - lo); x++) {
1132 y = (arc4random() & 0xFFFF) % (hi - lo);
1133 c = portlist[x];
1134 portlist[x] = portlist[y];
1135 portlist[y] = c;
1136 }
1137 }
1138 } else {
1139 hi = strtonum(p, 1, PORT_MAX, &errstr);
1140 if (errstr)
1141 errx(1, "port number %s: %s", errstr, p);
1142 portlist[0] = strdup(p);
1143 if (portlist[0] == NULL)
Damien Millere47536b2015-02-28 08:20:11 -08001144 errx(1, "strdup");
Damien Miller293cac52014-12-22 16:30:42 +11001145 }
1146}
1147
1148/*
1149 * udptest()
1150 * Do a few writes to see if the UDP port is there.
1151 * Fails once PF state table is full.
1152 */
1153int
1154udptest(int s)
1155{
1156 int i, ret;
1157
1158 for (i = 0; i <= 3; i++) {
1159 if (write(s, "X", 1) == 1)
1160 ret = 1;
1161 else
1162 ret = -1;
1163 }
1164 return (ret);
1165}
1166
1167void
1168set_common_sockopts(int s)
1169{
1170 int x = 1;
1171
Damien Miller69ff64f2015-01-27 23:07:43 +11001172#ifdef TCP_MD5SIG
Damien Miller293cac52014-12-22 16:30:42 +11001173 if (Sflag) {
1174 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1175 &x, sizeof(x)) == -1)
Damien Millere47536b2015-02-28 08:20:11 -08001176 err(1, "setsockopt");
Damien Miller293cac52014-12-22 16:30:42 +11001177 }
Damien Miller69ff64f2015-01-27 23:07:43 +11001178#endif
Damien Miller293cac52014-12-22 16:30:42 +11001179 if (Dflag) {
1180 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1181 &x, sizeof(x)) == -1)
Damien Millere47536b2015-02-28 08:20:11 -08001182 err(1, "setsockopt");
Damien Miller293cac52014-12-22 16:30:42 +11001183 }
1184 if (Tflag != -1) {
1185 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1186 &Tflag, sizeof(Tflag)) == -1)
1187 err(1, "set IP ToS");
1188 }
1189 if (Iflag) {
1190 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1191 &Iflag, sizeof(Iflag)) == -1)
1192 err(1, "set TCP receive buffer size");
1193 }
1194 if (Oflag) {
1195 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1196 &Oflag, sizeof(Oflag)) == -1)
1197 err(1, "set TCP send buffer size");
1198 }
1199}
1200
1201int
1202map_tos(char *s, int *val)
1203{
1204 /* DiffServ Codepoints and other TOS mappings */
1205 const struct toskeywords {
1206 const char *keyword;
1207 int val;
1208 } *t, toskeywords[] = {
1209 { "af11", IPTOS_DSCP_AF11 },
1210 { "af12", IPTOS_DSCP_AF12 },
1211 { "af13", IPTOS_DSCP_AF13 },
1212 { "af21", IPTOS_DSCP_AF21 },
1213 { "af22", IPTOS_DSCP_AF22 },
1214 { "af23", IPTOS_DSCP_AF23 },
1215 { "af31", IPTOS_DSCP_AF31 },
1216 { "af32", IPTOS_DSCP_AF32 },
1217 { "af33", IPTOS_DSCP_AF33 },
1218 { "af41", IPTOS_DSCP_AF41 },
1219 { "af42", IPTOS_DSCP_AF42 },
1220 { "af43", IPTOS_DSCP_AF43 },
1221 { "critical", IPTOS_PREC_CRITIC_ECP },
1222 { "cs0", IPTOS_DSCP_CS0 },
1223 { "cs1", IPTOS_DSCP_CS1 },
1224 { "cs2", IPTOS_DSCP_CS2 },
1225 { "cs3", IPTOS_DSCP_CS3 },
1226 { "cs4", IPTOS_DSCP_CS4 },
1227 { "cs5", IPTOS_DSCP_CS5 },
1228 { "cs6", IPTOS_DSCP_CS6 },
1229 { "cs7", IPTOS_DSCP_CS7 },
1230 { "ef", IPTOS_DSCP_EF },
1231 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1232 { "lowdelay", IPTOS_LOWDELAY },
1233 { "netcontrol", IPTOS_PREC_NETCONTROL },
1234 { "reliability", IPTOS_RELIABILITY },
1235 { "throughput", IPTOS_THROUGHPUT },
1236 { NULL, -1 },
1237 };
1238
1239 for (t = toskeywords; t->keyword != NULL; t++) {
1240 if (strcmp(s, t->keyword) == 0) {
1241 *val = t->val;
1242 return (1);
1243 }
1244 }
1245
1246 return (0);
1247}
1248
1249void
1250report_connect(const struct sockaddr *sa, socklen_t salen)
1251{
1252 char remote_host[NI_MAXHOST];
1253 char remote_port[NI_MAXSERV];
1254 int herr;
1255 int flags = NI_NUMERICSERV;
1256
1257 if (nflag)
1258 flags |= NI_NUMERICHOST;
1259
1260 if ((herr = getnameinfo(sa, salen,
1261 remote_host, sizeof(remote_host),
1262 remote_port, sizeof(remote_port),
1263 flags)) != 0) {
1264 if (herr == EAI_SYSTEM)
1265 err(1, "getnameinfo");
1266 else
1267 errx(1, "getnameinfo: %s", gai_strerror(herr));
1268 }
1269
1270 fprintf(stderr,
1271 "Connection from %s %s "
1272 "received!\n", remote_host, remote_port);
1273}
1274
1275void
1276help(void)
1277{
1278 usage(0);
1279 fprintf(stderr, "\tCommand Summary:\n\
1280 \t-4 Use IPv4\n\
1281 \t-6 Use IPv6\n\
1282 \t-D Enable the debug socket option\n\
1283 \t-d Detach from stdin\n\
1284 \t-F Pass socket fd\n\
1285 \t-h This help text\n\
1286 \t-I length TCP receive buffer length\n\
1287 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1288 \t-k Keep inbound sockets open for multiple connects\n\
1289 \t-l Listen mode, for inbound connects\n\
1290 \t-N Shutdown the network socket after EOF on stdin\n\
1291 \t-n Suppress name/port resolutions\n\
1292 \t-O length TCP send buffer length\n\
1293 \t-P proxyuser\tUsername for proxy authentication\n\
1294 \t-p port\t Specify local port for remote connects\n\
1295 \t-r Randomize remote ports\n\
1296 \t-S Enable the TCP MD5 signature option\n\
1297 \t-s addr\t Local source address\n\
1298 \t-T toskeyword\tSet IP Type of Service\n\
1299 \t-t Answer TELNET negotiation\n\
1300 \t-U Use UNIX domain socket\n\
1301 \t-u UDP mode\n\
1302 \t-V rtable Specify alternate routing table\n\
1303 \t-v Verbose\n\
1304 \t-w secs\t Timeout for connects and final net reads\n\
1305 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1306 \t-x addr[:port]\tSpecify proxy address and port\n\
1307 \t-z Zero-I/O mode [used for scanning]\n\
1308 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1309 exit(1);
1310}
1311
1312void
1313usage(int ret)
1314{
1315 fprintf(stderr,
1316 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1317 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1318 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1319 "\t [-x proxy_address[:port]] [destination] [port]\n");
1320 if (ret)
1321 exit(1);
1322}
1323
1324/* *** src/usr.bin/nc/socks.c *** */
1325
1326
1327/* $OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $ */
1328
1329/*
1330 * Copyright (c) 1999 Niklas Hallqvist. All rights reserved.
1331 * Copyright (c) 2004, 2005 Damien Miller. All rights reserved.
1332 *
1333 * Redistribution and use in source and binary forms, with or without
1334 * modification, are permitted provided that the following conditions
1335 * are met:
1336 * 1. Redistributions of source code must retain the above copyright
1337 * notice, this list of conditions and the following disclaimer.
1338 * 2. Redistributions in binary form must reproduce the above copyright
1339 * notice, this list of conditions and the following disclaimer in the
1340 * documentation and/or other materials provided with the distribution.
1341 *
1342 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1343 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1344 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1345 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1346 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1347 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1348 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1349 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1350 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1351 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1352 */
1353
1354#include <sys/types.h>
1355#include <sys/socket.h>
1356#include <netinet/in.h>
1357#include <arpa/inet.h>
1358
Damien Miller293cac52014-12-22 16:30:42 +11001359#include <errno.h>
1360#include <netdb.h>
1361#include <stdio.h>
1362#include <stdlib.h>
1363#include <string.h>
1364#include <unistd.h>
1365#include <resolv.h>
1366
1367#define SOCKS_PORT "1080"
1368#define HTTP_PROXY_PORT "3128"
1369#define HTTP_MAXHDRS 64
1370#define SOCKS_V5 5
1371#define SOCKS_V4 4
1372#define SOCKS_NOAUTH 0
1373#define SOCKS_NOMETHOD 0xff
1374#define SOCKS_CONNECT 1
1375#define SOCKS_IPV4 1
1376#define SOCKS_DOMAIN 3
1377#define SOCKS_IPV6 4
1378
1379int remote_connect(const char *, const char *, struct addrinfo);
1380int socks_connect(const char *, const char *, struct addrinfo,
1381 const char *, const char *, struct addrinfo, int,
1382 const char *);
1383
1384static int
1385decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1386 socklen_t addrlen, int v4only, int numeric)
1387{
1388 int r;
1389 struct addrinfo hints, *res;
1390
1391 bzero(&hints, sizeof(hints));
1392 hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1393 hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1394 hints.ai_socktype = SOCK_STREAM;
1395 r = getaddrinfo(h, p, &hints, &res);
1396 /* Don't fatal when attempting to convert a numeric address */
1397 if (r != 0) {
1398 if (!numeric) {
1399 errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1400 gai_strerror(r));
1401 }
1402 return (-1);
1403 }
1404 if (addrlen < res->ai_addrlen) {
1405 freeaddrinfo(res);
1406 errx(1, "internal error: addrlen < res->ai_addrlen");
1407 }
1408 memcpy(addr, res->ai_addr, res->ai_addrlen);
1409 freeaddrinfo(res);
1410 return (0);
1411}
1412
1413static int
1414proxy_read_line(int fd, char *buf, size_t bufsz)
1415{
1416 size_t off;
1417
1418 for(off = 0;;) {
1419 if (off >= bufsz)
1420 errx(1, "proxy read too long");
1421 if (atomicio(read, fd, buf + off, 1) != 1)
1422 err(1, "proxy read");
1423 /* Skip CR */
1424 if (buf[off] == '\r')
1425 continue;
1426 if (buf[off] == '\n') {
1427 buf[off] = '\0';
1428 break;
1429 }
1430 off++;
1431 }
1432 return (off);
1433}
1434
1435static const char *
1436getproxypass(const char *proxyuser, const char *proxyhost)
1437{
1438 char prompt[512];
1439 static char pw[256];
1440
1441 snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1442 proxyuser, proxyhost);
1443 if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1444 errx(1, "Unable to read proxy passphrase");
1445 return (pw);
1446}
1447
1448int
1449socks_connect(const char *host, const char *port,
1450 struct addrinfo hints __attribute__ ((__unused__)),
1451 const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1452 int socksv, const char *proxyuser)
1453{
1454 int proxyfd, r, authretry = 0;
Damien Miller2fab9b02015-03-04 07:41:27 +11001455 size_t hlen, wlen = 0;
Damien Miller293cac52014-12-22 16:30:42 +11001456 unsigned char buf[1024];
1457 size_t cnt;
1458 struct sockaddr_storage addr;
1459 struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1460 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1461 in_port_t serverport;
1462 const char *proxypass = NULL;
1463
1464 if (proxyport == NULL)
1465 proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1466
1467 /* Abuse API to lookup port */
1468 if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1469 sizeof(addr), 1, 1) == -1)
1470 errx(1, "unknown port \"%.64s\"", port);
1471 serverport = in4->sin_port;
1472
1473 again:
1474 if (authretry++ > 3)
1475 errx(1, "Too many authentication failures");
1476
1477 proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1478
1479 if (proxyfd < 0)
1480 return (-1);
1481
1482 if (socksv == 5) {
1483 if (decode_addrport(host, port, (struct sockaddr *)&addr,
1484 sizeof(addr), 0, 1) == -1)
1485 addr.ss_family = 0; /* used in switch below */
1486
1487 /* Version 5, one method: no authentication */
1488 buf[0] = SOCKS_V5;
1489 buf[1] = 1;
1490 buf[2] = SOCKS_NOAUTH;
1491 cnt = atomicio(vwrite, proxyfd, buf, 3);
1492 if (cnt != 3)
1493 err(1, "write failed (%zu/3)", cnt);
1494
1495 cnt = atomicio(read, proxyfd, buf, 2);
1496 if (cnt != 2)
1497 err(1, "read failed (%zu/3)", cnt);
1498
1499 if (buf[1] == SOCKS_NOMETHOD)
1500 errx(1, "authentication method negotiation failed");
1501
1502 switch (addr.ss_family) {
1503 case 0:
1504 /* Version 5, connect: domain name */
1505
1506 /* Max domain name length is 255 bytes */
1507 hlen = strlen(host);
1508 if (hlen > 255)
1509 errx(1, "host name too long for SOCKS5");
1510 buf[0] = SOCKS_V5;
1511 buf[1] = SOCKS_CONNECT;
1512 buf[2] = 0;
1513 buf[3] = SOCKS_DOMAIN;
1514 buf[4] = hlen;
1515 memcpy(buf + 5, host, hlen);
1516 memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1517 wlen = 7 + hlen;
1518 break;
1519 case AF_INET:
1520 /* Version 5, connect: IPv4 address */
1521 buf[0] = SOCKS_V5;
1522 buf[1] = SOCKS_CONNECT;
1523 buf[2] = 0;
1524 buf[3] = SOCKS_IPV4;
1525 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1526 memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1527 wlen = 10;
1528 break;
1529 case AF_INET6:
1530 /* Version 5, connect: IPv6 address */
1531 buf[0] = SOCKS_V5;
1532 buf[1] = SOCKS_CONNECT;
1533 buf[2] = 0;
1534 buf[3] = SOCKS_IPV6;
1535 memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1536 memcpy(buf + 20, &in6->sin6_port,
1537 sizeof in6->sin6_port);
1538 wlen = 22;
1539 break;
1540 default:
1541 errx(1, "internal error: silly AF");
1542 }
1543
1544 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1545 if (cnt != wlen)
1546 err(1, "write failed (%zu/%zu)", cnt, wlen);
1547
1548 cnt = atomicio(read, proxyfd, buf, 4);
1549 if (cnt != 4)
1550 err(1, "read failed (%zu/4)", cnt);
1551 if (buf[1] != 0)
1552 errx(1, "connection failed, SOCKS error %d", buf[1]);
1553 switch (buf[3]) {
1554 case SOCKS_IPV4:
1555 cnt = atomicio(read, proxyfd, buf + 4, 6);
1556 if (cnt != 6)
1557 err(1, "read failed (%zu/6)", cnt);
1558 break;
1559 case SOCKS_IPV6:
1560 cnt = atomicio(read, proxyfd, buf + 4, 18);
1561 if (cnt != 18)
1562 err(1, "read failed (%zu/18)", cnt);
1563 break;
1564 default:
1565 errx(1, "connection failed, unsupported address type");
1566 }
1567 } else if (socksv == 4) {
1568 /* This will exit on lookup failure */
1569 decode_addrport(host, port, (struct sockaddr *)&addr,
1570 sizeof(addr), 1, 0);
1571
1572 /* Version 4 */
1573 buf[0] = SOCKS_V4;
1574 buf[1] = SOCKS_CONNECT; /* connect */
1575 memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1576 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1577 buf[8] = 0; /* empty username */
1578 wlen = 9;
1579
1580 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1581 if (cnt != wlen)
1582 err(1, "write failed (%zu/%zu)", cnt, wlen);
1583
1584 cnt = atomicio(read, proxyfd, buf, 8);
1585 if (cnt != 8)
1586 err(1, "read failed (%zu/8)", cnt);
1587 if (buf[1] != 90)
1588 errx(1, "connection failed, SOCKS error %d", buf[1]);
1589 } else if (socksv == -1) {
1590 /* HTTP proxy CONNECT */
1591
1592 /* Disallow bad chars in hostname */
1593 if (strcspn(host, "\r\n\t []:") != strlen(host))
1594 errx(1, "Invalid hostname");
1595
1596 /* Try to be sane about numeric IPv6 addresses */
1597 if (strchr(host, ':') != NULL) {
1598 r = snprintf(buf, sizeof(buf),
1599 "CONNECT [%s]:%d HTTP/1.0\r\n",
1600 host, ntohs(serverport));
1601 } else {
1602 r = snprintf(buf, sizeof(buf),
1603 "CONNECT %s:%d HTTP/1.0\r\n",
1604 host, ntohs(serverport));
1605 }
1606 if (r == -1 || (size_t)r >= sizeof(buf))
1607 errx(1, "hostname too long");
1608 r = strlen(buf);
1609
1610 cnt = atomicio(vwrite, proxyfd, buf, r);
1611 if (cnt != (size_t)r)
1612 err(1, "write failed (%zu/%d)", cnt, r);
1613
1614 if (authretry > 1) {
1615 char resp[1024];
1616
1617 proxypass = getproxypass(proxyuser, proxyhost);
1618 r = snprintf(buf, sizeof(buf), "%s:%s",
1619 proxyuser, proxypass);
1620 if (r == -1 || (size_t)r >= sizeof(buf) ||
1621 b64_ntop(buf, strlen(buf), resp,
1622 sizeof(resp)) == -1)
1623 errx(1, "Proxy username/password too long");
1624 r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1625 "Basic %s\r\n", resp);
1626 if (r == -1 || (size_t)r >= sizeof(buf))
1627 errx(1, "Proxy auth response too long");
1628 r = strlen(buf);
1629 if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1630 err(1, "write failed (%zu/%d)", cnt, r);
1631 }
1632
1633 /* Terminate headers */
1634 if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1635 err(1, "write failed (2/%d)", r);
1636
1637 /* Read status reply */
1638 proxy_read_line(proxyfd, buf, sizeof(buf));
1639 if (proxyuser != NULL &&
1640 strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1641 if (authretry > 1) {
1642 fprintf(stderr, "Proxy authentication "
1643 "failed\n");
1644 }
1645 close(proxyfd);
1646 goto again;
1647 } else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1648 strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1649 errx(1, "Proxy error: \"%s\"", buf);
1650
1651 /* Headers continue until we hit an empty line */
1652 for (r = 0; r < HTTP_MAXHDRS; r++) {
1653 proxy_read_line(proxyfd, buf, sizeof(buf));
1654 if (*buf == '\0')
1655 break;
1656 }
1657 if (*buf != '\0')
1658 errx(1, "Too many proxy headers received");
1659 } else
1660 errx(1, "Unknown proxy protocol %d", socksv);
1661
1662 return (proxyfd);
1663}
1664