xref: /openssh-portable/regress/netcat.c (revision d500b59a)
1 /* $OpenBSD: netcat.c,v 1.126 2014/10/30 16:08:31 tedu Exp $ */
2 /*
3  * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *   notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *   notice, this list of conditions and the following disclaimer in the
13  *   documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *   derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * Re-written nc(1) for OpenBSD. Original implementation by
31  * *Hobbit* <hobbit@avian.org>.
32  */
33 
34 #include "includes.h"
35 
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <sys/time.h>
39 #include <sys/uio.h>
40 #include <sys/un.h>
41 
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <netinet/ip.h>
45 
46 #include <errno.h>
47 #include <netdb.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <fcntl.h>
54 #include <limits.h>
55 #include "atomicio.h"
56 
57 #ifdef HAVE_POLL_H
58 #include <poll.h>
59 #else
60 # ifdef HAVE_SYS_POLL_H
61 #  include <sys/poll.h>
62 # endif
63 #endif
64 #ifdef HAVE_ERR_H
65 # include <err.h>
66 #endif
67 
68 /* Telnet options from arpa/telnet.h */
69 #define IAC	255
70 #define DONT	254
71 #define DO	253
72 #define WONT	252
73 #define WILL	251
74 
75 #ifndef SUN_LEN
76 #define SUN_LEN(su) \
77 	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
78 #endif
79 
80 #define PORT_MAX	65535
81 #define PORT_MAX_LEN	6
82 #define UNIX_DG_TMP_SOCKET_SIZE	19
83 
84 #define POLL_STDIN 0
85 #define POLL_NETOUT 1
86 #define POLL_NETIN 2
87 #define POLL_STDOUT 3
88 #define BUFSIZE 16384
89 
90 /* Command Line Options */
91 int	dflag;					/* detached, no stdin */
92 int	Fflag;					/* fdpass sock to stdout */
93 unsigned int iflag;				/* Interval Flag */
94 int	kflag;					/* More than one connect */
95 int	lflag;					/* Bind to local port */
96 int	Nflag;					/* shutdown() network socket */
97 int	nflag;					/* Don't do name look up */
98 char   *Pflag;					/* Proxy username */
99 char   *pflag;					/* Localport flag */
100 int	rflag;					/* Random ports flag */
101 char   *sflag;					/* Source Address */
102 int	tflag;					/* Telnet Emulation */
103 int	uflag;					/* UDP - Default to TCP */
104 int	vflag;					/* Verbosity */
105 int	xflag;					/* Socks proxy */
106 int	zflag;					/* Port Scan Flag */
107 int	Dflag;					/* sodebug */
108 int	Iflag;					/* TCP receive buffer size */
109 int	Oflag;					/* TCP send buffer size */
110 int	Sflag;					/* TCP MD5 signature option */
111 int	Tflag = -1;				/* IP Type of Service */
112 int	rtableid = -1;
113 
114 int timeout = -1;
115 int family = AF_UNSPEC;
116 char *portlist[PORT_MAX+1];
117 char *unix_dg_tmp_socket;
118 
119 void	atelnet(int, unsigned char *, unsigned int);
120 void	build_ports(char *);
121 void	help(void);
122 int	local_listen(char *, char *, struct addrinfo);
123 void	readwrite(int);
124 void	fdpass(int nfd) __attribute__((noreturn));
125 int	remote_connect(const char *, const char *, struct addrinfo);
126 int	timeout_connect(int, const struct sockaddr *, socklen_t);
127 int	socks_connect(const char *, const char *, struct addrinfo,
128 	    const char *, const char *, struct addrinfo, int, const char *);
129 int	udptest(int);
130 int	unix_bind(char *);
131 int	unix_connect(char *);
132 int	unix_listen(char *);
133 void	set_common_sockopts(int);
134 int	map_tos(char *, int *);
135 void	report_connect(const struct sockaddr *, socklen_t);
136 void	usage(int);
137 ssize_t drainbuf(int, unsigned char *, size_t *);
138 ssize_t fillbuf(int, unsigned char *, size_t *);
139 
140 
141 int
main(int argc,char * argv[])142 main(int argc, char *argv[])
143 {
144 	int ch, s, ret, socksv;
145 	char *host, *uport;
146 	struct addrinfo hints;
147 	struct servent *sv;
148 	socklen_t len;
149 	struct sockaddr_storage cliaddr;
150 	char *proxy = NULL;
151 	const char *errstr, *proxyhost = "", *proxyport = NULL;
152 	struct addrinfo proxyhints;
153 	char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
154 
155 	ret = 1;
156 	s = 0;
157 	socksv = 5;
158 	host = NULL;
159 	uport = NULL;
160 	sv = NULL;
161 
162 	while ((ch = getopt(argc, argv,
163 	    "46DdFhI:i:klNnO:P:p:rSs:tT:UuV:vw:X:x:z")) != -1) {
164 		switch (ch) {
165 		case '4':
166 			family = AF_INET;
167 			break;
168 		case '6':
169 			family = AF_INET6;
170 			break;
171 		case 'U':
172 			family = AF_UNIX;
173 			break;
174 		case 'X':
175 			if (strcasecmp(optarg, "connect") == 0)
176 				socksv = -1; /* HTTP proxy CONNECT */
177 			else if (strcmp(optarg, "4") == 0)
178 				socksv = 4; /* SOCKS v.4 */
179 			else if (strcmp(optarg, "5") == 0)
180 				socksv = 5; /* SOCKS v.5 */
181 			else
182 				errx(1, "unsupported proxy protocol");
183 			break;
184 		case 'd':
185 			dflag = 1;
186 			break;
187 		case 'F':
188 			Fflag = 1;
189 			break;
190 		case 'h':
191 			help();
192 			break;
193 		case 'i':
194 			iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
195 			if (errstr)
196 				errx(1, "interval %s: %s", errstr, optarg);
197 			break;
198 		case 'k':
199 			kflag = 1;
200 			break;
201 		case 'l':
202 			lflag = 1;
203 			break;
204 		case 'N':
205 			Nflag = 1;
206 			break;
207 		case 'n':
208 			nflag = 1;
209 			break;
210 		case 'P':
211 			Pflag = optarg;
212 			break;
213 		case 'p':
214 			pflag = optarg;
215 			break;
216 		case 'r':
217 			rflag = 1;
218 			break;
219 		case 's':
220 			sflag = optarg;
221 			break;
222 		case 't':
223 			tflag = 1;
224 			break;
225 		case 'u':
226 			uflag = 1;
227 			break;
228 #ifdef SO_RTABLE
229 		case 'V':
230 			rtableid = (int)strtonum(optarg, 0,
231 			    RT_TABLEID_MAX, &errstr);
232 			if (errstr)
233 				errx(1, "rtable %s: %s", errstr, optarg);
234 			break;
235 #endif
236 		case 'v':
237 			vflag = 1;
238 			break;
239 		case 'w':
240 			timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
241 			if (errstr)
242 				errx(1, "timeout %s: %s", errstr, optarg);
243 			timeout *= 1000;
244 			break;
245 		case 'x':
246 			xflag = 1;
247 			if ((proxy = strdup(optarg)) == NULL)
248 				errx(1, "strdup");
249 			break;
250 		case 'z':
251 			zflag = 1;
252 			break;
253 		case 'D':
254 			Dflag = 1;
255 			break;
256 		case 'I':
257 			Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
258 			if (errstr != NULL)
259 				errx(1, "TCP receive window %s: %s",
260 				    errstr, optarg);
261 			break;
262 		case 'O':
263 			Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
264 			if (errstr != NULL)
265 				errx(1, "TCP send window %s: %s",
266 				    errstr, optarg);
267 			break;
268 		case 'S':
269 			Sflag = 1;
270 			break;
271 		case 'T':
272 			errstr = NULL;
273 			errno = 0;
274 			if (map_tos(optarg, &Tflag))
275 				break;
276 			if (strlen(optarg) > 1 && optarg[0] == '0' &&
277 			    optarg[1] == 'x')
278 				Tflag = (int)strtol(optarg, NULL, 16);
279 			else
280 				Tflag = (int)strtonum(optarg, 0, 255,
281 				    &errstr);
282 			if (Tflag < 0 || Tflag > 255 || errstr || errno)
283 				errx(1, "illegal tos value %s", optarg);
284 			break;
285 		default:
286 			usage(1);
287 		}
288 	}
289 	argc -= optind;
290 	argv += optind;
291 
292 	/* Cruft to make sure options are clean, and used properly. */
293 	if (argv[0] && !argv[1] && family == AF_UNIX) {
294 		host = argv[0];
295 		uport = NULL;
296 	} else if (argv[0] && !argv[1]) {
297 		if  (!lflag)
298 			usage(1);
299 		uport = argv[0];
300 		host = NULL;
301 	} else if (argv[0] && argv[1]) {
302 		host = argv[0];
303 		uport = argv[1];
304 	} else
305 		usage(1);
306 
307 	if (lflag && sflag)
308 		errx(1, "cannot use -s and -l");
309 	if (lflag && pflag)
310 		errx(1, "cannot use -p and -l");
311 	if (lflag && zflag)
312 		errx(1, "cannot use -z and -l");
313 	if (!lflag && kflag)
314 		errx(1, "must use -l with -k");
315 
316 	/* Get name of temporary socket for unix datagram client */
317 	if ((family == AF_UNIX) && uflag && !lflag) {
318 		if (sflag) {
319 			unix_dg_tmp_socket = sflag;
320 		} else {
321 			strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
322 				UNIX_DG_TMP_SOCKET_SIZE);
323 			if (mktemp(unix_dg_tmp_socket_buf) == NULL)
324 				err(1, "mktemp");
325 			unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
326 		}
327 	}
328 
329 	/* Initialize addrinfo structure. */
330 	if (family != AF_UNIX) {
331 		memset(&hints, 0, sizeof(struct addrinfo));
332 		hints.ai_family = family;
333 		hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
334 		hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
335 		if (nflag)
336 			hints.ai_flags |= AI_NUMERICHOST;
337 	}
338 
339 	if (xflag) {
340 		if (uflag)
341 			errx(1, "no proxy support for UDP mode");
342 
343 		if (lflag)
344 			errx(1, "no proxy support for listen");
345 
346 		if (family == AF_UNIX)
347 			errx(1, "no proxy support for unix sockets");
348 
349 		/* XXX IPv6 transport to proxy would probably work */
350 		if (family == AF_INET6)
351 			errx(1, "no proxy support for IPv6");
352 
353 		if (sflag)
354 			errx(1, "no proxy support for local source address");
355 
356 		proxyhost = strsep(&proxy, ":");
357 		proxyport = proxy;
358 
359 		memset(&proxyhints, 0, sizeof(struct addrinfo));
360 		proxyhints.ai_family = family;
361 		proxyhints.ai_socktype = SOCK_STREAM;
362 		proxyhints.ai_protocol = IPPROTO_TCP;
363 		if (nflag)
364 			proxyhints.ai_flags |= AI_NUMERICHOST;
365 	}
366 
367 	if (lflag) {
368 		int connfd;
369 		ret = 0;
370 
371 		if (family == AF_UNIX) {
372 			if (uflag)
373 				s = unix_bind(host);
374 			else
375 				s = unix_listen(host);
376 		}
377 
378 		/* Allow only one connection at a time, but stay alive. */
379 		for (;;) {
380 			if (family != AF_UNIX)
381 				s = local_listen(host, uport, hints);
382 			if (s < 0)
383 				err(1, "local_listen");
384 			/*
385 			 * For UDP and -k, don't connect the socket, let it
386 			 * receive datagrams from multiple socket pairs.
387 			 */
388 			if (uflag && kflag)
389 				readwrite(s);
390 			/*
391 			 * For UDP and not -k, we will use recvfrom() initially
392 			 * to wait for a caller, then use the regular functions
393 			 * to talk to the caller.
394 			 */
395 			else if (uflag && !kflag) {
396 				int rv, plen;
397 				char buf[16384];
398 				struct sockaddr_storage z;
399 
400 				len = sizeof(z);
401 				plen = 2048;
402 				rv = recvfrom(s, buf, plen, MSG_PEEK,
403 				    (struct sockaddr *)&z, &len);
404 				if (rv < 0)
405 					err(1, "recvfrom");
406 
407 				rv = connect(s, (struct sockaddr *)&z, len);
408 				if (rv < 0)
409 					err(1, "connect");
410 
411 				if (vflag)
412 					report_connect((struct sockaddr *)&z, len);
413 
414 				readwrite(s);
415 			} else {
416 				len = sizeof(cliaddr);
417 				connfd = accept(s, (struct sockaddr *)&cliaddr,
418 				    &len);
419 				if (connfd == -1) {
420 					/* For now, all errnos are fatal */
421 					err(1, "accept");
422 				}
423 				if (vflag)
424 					report_connect((struct sockaddr *)&cliaddr, len);
425 
426 				readwrite(connfd);
427 				close(connfd);
428 			}
429 
430 			if (family != AF_UNIX)
431 				close(s);
432 			else if (uflag) {
433 				if (connect(s, NULL, 0) < 0)
434 					err(1, "connect");
435 			}
436 
437 			if (!kflag)
438 				break;
439 		}
440 	} else if (family == AF_UNIX) {
441 		ret = 0;
442 
443 		if ((s = unix_connect(host)) > 0 && !zflag) {
444 			readwrite(s);
445 			close(s);
446 		} else
447 			ret = 1;
448 
449 		if (uflag)
450 			unlink(unix_dg_tmp_socket);
451 		exit(ret);
452 
453 	} else {
454 		int i = 0;
455 
456 		/* Construct the portlist[] array. */
457 		build_ports(uport);
458 
459 		/* Cycle through portlist, connecting to each port. */
460 		for (i = 0; portlist[i] != NULL; i++) {
461 			if (s)
462 				close(s);
463 
464 			if (xflag)
465 				s = socks_connect(host, portlist[i], hints,
466 				    proxyhost, proxyport, proxyhints, socksv,
467 				    Pflag);
468 			else
469 				s = remote_connect(host, portlist[i], hints);
470 
471 			if (s < 0)
472 				continue;
473 
474 			ret = 0;
475 			if (vflag || zflag) {
476 				/* For UDP, make sure we are connected. */
477 				if (uflag) {
478 					if (udptest(s) == -1) {
479 						ret = 1;
480 						continue;
481 					}
482 				}
483 
484 				/* Don't look up port if -n. */
485 				if (nflag)
486 					sv = NULL;
487 				else {
488 					sv = getservbyport(
489 					    ntohs(atoi(portlist[i])),
490 					    uflag ? "udp" : "tcp");
491 				}
492 
493 				fprintf(stderr,
494 				    "Connection to %s %s port [%s/%s] "
495 				    "succeeded!\n", host, portlist[i],
496 				    uflag ? "udp" : "tcp",
497 				    sv ? sv->s_name : "*");
498 			}
499 			if (Fflag)
500 				fdpass(s);
501 			else if (!zflag)
502 				readwrite(s);
503 		}
504 	}
505 
506 	if (s)
507 		close(s);
508 
509 	exit(ret);
510 }
511 
512 /*
513  * unix_bind()
514  * Returns a unix socket bound to the given path
515  */
516 int
unix_bind(char * path)517 unix_bind(char *path)
518 {
519 	struct sockaddr_un sun_sa;
520 	int s;
521 
522 	/* Create unix domain socket. */
523 	if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
524 	     0)) < 0)
525 		return (-1);
526 
527 	memset(&sun_sa, 0, sizeof(struct sockaddr_un));
528 	sun_sa.sun_family = AF_UNIX;
529 
530 	if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
531 	    sizeof(sun_sa.sun_path)) {
532 		close(s);
533 		errno = ENAMETOOLONG;
534 		return (-1);
535 	}
536 
537 	if (bind(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
538 		close(s);
539 		return (-1);
540 	}
541 	return (s);
542 }
543 
544 /*
545  * unix_connect()
546  * Returns a socket connected to a local unix socket. Returns -1 on failure.
547  */
548 int
unix_connect(char * path)549 unix_connect(char *path)
550 {
551 	struct sockaddr_un sun_sa;
552 	int s;
553 
554 	if (uflag) {
555 		if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
556 			return (-1);
557 	} else {
558 		if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
559 			return (-1);
560 	}
561 	(void)fcntl(s, F_SETFD, FD_CLOEXEC);
562 
563 	memset(&sun_sa, 0, sizeof(struct sockaddr_un));
564 	sun_sa.sun_family = AF_UNIX;
565 
566 	if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
567 	    sizeof(sun_sa.sun_path)) {
568 		close(s);
569 		errno = ENAMETOOLONG;
570 		return (-1);
571 	}
572 	if (connect(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
573 		close(s);
574 		return (-1);
575 	}
576 	return (s);
577 
578 }
579 
580 /*
581  * unix_listen()
582  * Create a unix domain socket, and listen on it.
583  */
584 int
unix_listen(char * path)585 unix_listen(char *path)
586 {
587 	int s;
588 	if ((s = unix_bind(path)) < 0)
589 		return (-1);
590 
591 	if (listen(s, 5) < 0) {
592 		close(s);
593 		return (-1);
594 	}
595 	return (s);
596 }
597 
598 /*
599  * remote_connect()
600  * Returns a socket connected to a remote host. Properly binds to a local
601  * port or source address if needed. Returns -1 on failure.
602  */
603 int
remote_connect(const char * host,const char * port,struct addrinfo hints)604 remote_connect(const char *host, const char *port, struct addrinfo hints)
605 {
606 	struct addrinfo *res, *res0;
607 	int s, error;
608 #if defined(SO_RTABLE) || defined(SO_BINDANY)
609 	int on = 1;
610 #endif
611 
612 	if ((error = getaddrinfo(host, port, &hints, &res)))
613 		errx(1, "getaddrinfo: %s", gai_strerror(error));
614 
615 	res0 = res;
616 	do {
617 		if ((s = socket(res0->ai_family, res0->ai_socktype,
618 		    res0->ai_protocol)) < 0)
619 			continue;
620 
621 #ifdef SO_RTABLE
622 		if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
623 		    &rtableid, sizeof(rtableid)) == -1))
624 			err(1, "setsockopt SO_RTABLE");
625 #endif
626 		/* Bind to a local port or source address if specified. */
627 		if (sflag || pflag) {
628 			struct addrinfo ahints, *ares;
629 
630 #ifdef SO_BINDANY
631 			/* try SO_BINDANY, but don't insist */
632 			setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
633 #endif
634 			memset(&ahints, 0, sizeof(struct addrinfo));
635 			ahints.ai_family = res0->ai_family;
636 			ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
637 			ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
638 			ahints.ai_flags = AI_PASSIVE;
639 			if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
640 				errx(1, "getaddrinfo: %s", gai_strerror(error));
641 
642 			if (bind(s, (struct sockaddr *)ares->ai_addr,
643 			    ares->ai_addrlen) < 0)
644 				err(1, "bind failed");
645 			freeaddrinfo(ares);
646 		}
647 
648 		set_common_sockopts(s);
649 
650 		if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
651 			break;
652 		else if (vflag)
653 			warn("connect to %s port %s (%s) failed", host, port,
654 			    uflag ? "udp" : "tcp");
655 
656 		close(s);
657 		s = -1;
658 	} while ((res0 = res0->ai_next) != NULL);
659 
660 	freeaddrinfo(res);
661 
662 	return (s);
663 }
664 
665 int
timeout_connect(int s,const struct sockaddr * name,socklen_t namelen)666 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
667 {
668 	struct pollfd pfd;
669 	socklen_t optlen;
670 	int flags = 0, optval;
671 	int ret;
672 
673 	if (timeout != -1) {
674 		flags = fcntl(s, F_GETFL, 0);
675 		if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
676 			err(1, "set non-blocking mode");
677 	}
678 
679 	if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
680 		pfd.fd = s;
681 		pfd.events = POLLOUT;
682 		if ((ret = poll(&pfd, 1, timeout)) == 1) {
683 			optlen = sizeof(optval);
684 			if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
685 			    &optval, &optlen)) == 0) {
686 				errno = optval;
687 				ret = optval == 0 ? 0 : -1;
688 			}
689 		} else if (ret == 0) {
690 			errno = ETIMEDOUT;
691 			ret = -1;
692 		} else
693 			err(1, "poll failed");
694 	}
695 
696 	if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
697 		err(1, "restoring flags");
698 
699 	return (ret);
700 }
701 
702 /*
703  * local_listen()
704  * Returns a socket listening on a local port, binds to specified source
705  * address. Returns -1 on failure.
706  */
707 int
local_listen(char * host,char * port,struct addrinfo hints)708 local_listen(char *host, char *port, struct addrinfo hints)
709 {
710 	struct addrinfo *res, *res0;
711 	int s, ret, x = 1;
712 	int error;
713 
714 	/* Allow nodename to be null. */
715 	hints.ai_flags |= AI_PASSIVE;
716 
717 	/*
718 	 * In the case of binding to a wildcard address
719 	 * default to binding to an ipv4 address.
720 	 */
721 	if (host == NULL && hints.ai_family == AF_UNSPEC)
722 		hints.ai_family = AF_INET;
723 
724 	if ((error = getaddrinfo(host, port, &hints, &res)))
725 		errx(1, "getaddrinfo: %s", gai_strerror(error));
726 
727 	res0 = res;
728 	do {
729 		if ((s = socket(res0->ai_family, res0->ai_socktype,
730 		    res0->ai_protocol)) < 0)
731 			continue;
732 
733 #ifdef SO_RTABLE
734 		if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
735 		    &rtableid, sizeof(rtableid)) == -1))
736 			err(1, "setsockopt SO_RTABLE");
737 #endif
738 #ifdef SO_REUSEPORT
739 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
740 		if (ret == -1)
741 			err(1, "setsockopt 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");
747 #endif
748 		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  */
772 void
readwrite(int net_fd)773 readwrite(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 
954 ssize_t
drainbuf(int fd,unsigned char * buf,size_t * bufpos)955 drainbuf(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 
975 ssize_t
fillbuf(int fd,unsigned char * buf,size_t * bufpos)976 fillbuf(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  */
995 void
fdpass(int nfd)996 fdpass(int nfd)
997 {
998 #if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR))
999 	struct msghdr msg;
1000 #ifndef HAVE_ACCRIGHTS_IN_MSGHDR
1001 	union {
1002 		struct cmsghdr hdr;
1003 		char buf[CMSG_SPACE(sizeof(int))];
1004 	} cmsgbuf;
1005 	struct cmsghdr *cmsg;
1006 #endif
1007 	struct iovec vec;
1008 	char ch = '\0';
1009 	struct pollfd pfd;
1010 	ssize_t r;
1011 
1012 	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);
1021 	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;
1025 #endif
1026 
1027 	vec.iov_base = &ch;
1028 	vec.iov_len = 1;
1029 	msg.msg_iov = &vec;
1030 	msg.msg_iovlen = 1;
1031 
1032 	bzero(&pfd, sizeof(pfd));
1033 	pfd.fd = STDOUT_FILENO;
1034 	for (;;) {
1035 		r = sendmsg(STDOUT_FILENO, &msg, 0);
1036 		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);
1050 #else
1051 	errx(1, "%s: file descriptor passing not supported", __func__);
1052 #endif
1053 }
1054 
1055 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1056 void
atelnet(int nfd,unsigned char * buf,unsigned int size)1057 atelnet(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  */
1091 void
build_ports(char * p)1092 build_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)
1121 				errx(1, "calloc");
1122 			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)
1144 			errx(1, "strdup");
1145 	}
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  */
1153 int
udptest(int s)1154 udptest(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 
1167 void
set_common_sockopts(int s)1168 set_common_sockopts(int s)
1169 {
1170 	int x = 1;
1171 
1172 #ifdef TCP_MD5SIG
1173 	if (Sflag) {
1174 		if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1175 			&x, sizeof(x)) == -1)
1176 			err(1, "setsockopt");
1177 	}
1178 #endif
1179 	if (Dflag) {
1180 		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1181 			&x, sizeof(x)) == -1)
1182 			err(1, "setsockopt");
1183 	}
1184 #ifdef IP_TOS
1185 	if (Tflag != -1) {
1186 		if (setsockopt(s, IPPROTO_IP, IP_TOS,
1187 		    &Tflag, sizeof(Tflag)) == -1)
1188 			err(1, "set IP ToS");
1189 	}
1190 #endif
1191 	if (Iflag) {
1192 		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1193 		    &Iflag, sizeof(Iflag)) == -1)
1194 			err(1, "set TCP receive buffer size");
1195 	}
1196 	if (Oflag) {
1197 		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1198 		    &Oflag, sizeof(Oflag)) == -1)
1199 			err(1, "set TCP send buffer size");
1200 	}
1201 }
1202 
1203 int
map_tos(char * s,int * val)1204 map_tos(char *s, int *val)
1205 {
1206 #ifdef IP_TOS
1207 	/* DiffServ Codepoints and other TOS mappings */
1208 	const struct toskeywords {
1209 		const char	*keyword;
1210 		int		 val;
1211 	} *t, toskeywords[] = {
1212 		{ "af11",		IPTOS_DSCP_AF11 },
1213 		{ "af12",		IPTOS_DSCP_AF12 },
1214 		{ "af13",		IPTOS_DSCP_AF13 },
1215 		{ "af21",		IPTOS_DSCP_AF21 },
1216 		{ "af22",		IPTOS_DSCP_AF22 },
1217 		{ "af23",		IPTOS_DSCP_AF23 },
1218 		{ "af31",		IPTOS_DSCP_AF31 },
1219 		{ "af32",		IPTOS_DSCP_AF32 },
1220 		{ "af33",		IPTOS_DSCP_AF33 },
1221 		{ "af41",		IPTOS_DSCP_AF41 },
1222 		{ "af42",		IPTOS_DSCP_AF42 },
1223 		{ "af43",		IPTOS_DSCP_AF43 },
1224 		{ "critical",		IPTOS_PREC_CRITIC_ECP },
1225 		{ "cs0",		IPTOS_DSCP_CS0 },
1226 		{ "cs1",		IPTOS_DSCP_CS1 },
1227 		{ "cs2",		IPTOS_DSCP_CS2 },
1228 		{ "cs3",		IPTOS_DSCP_CS3 },
1229 		{ "cs4",		IPTOS_DSCP_CS4 },
1230 		{ "cs5",		IPTOS_DSCP_CS5 },
1231 		{ "cs6",		IPTOS_DSCP_CS6 },
1232 		{ "cs7",		IPTOS_DSCP_CS7 },
1233 		{ "ef",			IPTOS_DSCP_EF },
1234 		{ "inetcontrol",	IPTOS_PREC_INTERNETCONTROL },
1235 		{ "lowdelay",		IPTOS_LOWDELAY },
1236 		{ "netcontrol",		IPTOS_PREC_NETCONTROL },
1237 		{ "reliability",	IPTOS_RELIABILITY },
1238 		{ "throughput",		IPTOS_THROUGHPUT },
1239 		{ NULL, 		-1 },
1240 	};
1241 
1242 	for (t = toskeywords; t->keyword != NULL; t++) {
1243 		if (strcmp(s, t->keyword) == 0) {
1244 			*val = t->val;
1245 			return (1);
1246 		}
1247 	}
1248 #endif
1249 
1250 	return (0);
1251 }
1252 
1253 void
report_connect(const struct sockaddr * sa,socklen_t salen)1254 report_connect(const struct sockaddr *sa, socklen_t salen)
1255 {
1256 	char remote_host[NI_MAXHOST];
1257 	char remote_port[NI_MAXSERV];
1258 	int herr;
1259 	int flags = NI_NUMERICSERV;
1260 
1261 	if (nflag)
1262 		flags |= NI_NUMERICHOST;
1263 
1264 	if ((herr = getnameinfo(sa, salen,
1265 	    remote_host, sizeof(remote_host),
1266 	    remote_port, sizeof(remote_port),
1267 	    flags)) != 0) {
1268 		if (herr == EAI_SYSTEM)
1269 			err(1, "getnameinfo");
1270 		else
1271 			errx(1, "getnameinfo: %s", gai_strerror(herr));
1272 	}
1273 
1274 	fprintf(stderr,
1275 	    "Connection from %s %s "
1276 	    "received!\n", remote_host, remote_port);
1277 }
1278 
1279 void
help(void)1280 help(void)
1281 {
1282 	usage(0);
1283 	fprintf(stderr, "\tCommand Summary:\n\
1284 	\t-4		Use IPv4\n\
1285 	\t-6		Use IPv6\n\
1286 	\t-D		Enable the debug socket option\n\
1287 	\t-d		Detach from stdin\n\
1288 	\t-F		Pass socket fd\n\
1289 	\t-h		This help text\n\
1290 	\t-I length	TCP receive buffer length\n\
1291 	\t-i secs\t	Delay interval for lines sent, ports scanned\n\
1292 	\t-k		Keep inbound sockets open for multiple connects\n\
1293 	\t-l		Listen mode, for inbound connects\n\
1294 	\t-N		Shutdown the network socket after EOF on stdin\n\
1295 	\t-n		Suppress name/port resolutions\n\
1296 	\t-O length	TCP send buffer length\n\
1297 	\t-P proxyuser\tUsername for proxy authentication\n\
1298 	\t-p port\t	Specify local port for remote connects\n\
1299 	\t-r		Randomize remote ports\n\
1300 	\t-S		Enable the TCP MD5 signature option\n\
1301 	\t-s addr\t	Local source address\n\
1302 	\t-T toskeyword\tSet IP Type of Service\n\
1303 	\t-t		Answer TELNET negotiation\n\
1304 	\t-U		Use UNIX domain socket\n\
1305 	\t-u		UDP mode\n\
1306 	\t-V rtable	Specify alternate routing table\n\
1307 	\t-v		Verbose\n\
1308 	\t-w secs\t	Timeout for connects and final net reads\n\
1309 	\t-X proto	Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1310 	\t-x addr[:port]\tSpecify proxy address and port\n\
1311 	\t-z		Zero-I/O mode [used for scanning]\n\
1312 	Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1313 	exit(1);
1314 }
1315 
1316 void
usage(int ret)1317 usage(int ret)
1318 {
1319 	fprintf(stderr,
1320 	    "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1321 	    "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1322 	    "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1323 	    "\t  [-x proxy_address[:port]] [destination] [port]\n");
1324 	if (ret)
1325 		exit(1);
1326 }
1327 
1328 /* *** src/usr.bin/nc/socks.c *** */
1329 
1330 
1331 /*	$OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $	*/
1332 
1333 /*
1334  * Copyright (c) 1999 Niklas Hallqvist.  All rights reserved.
1335  * Copyright (c) 2004, 2005 Damien Miller.  All rights reserved.
1336  *
1337  * Redistribution and use in source and binary forms, with or without
1338  * modification, are permitted provided that the following conditions
1339  * are met:
1340  * 1. Redistributions of source code must retain the above copyright
1341  *    notice, this list of conditions and the following disclaimer.
1342  * 2. Redistributions in binary form must reproduce the above copyright
1343  *    notice, this list of conditions and the following disclaimer in the
1344  *    documentation and/or other materials provided with the distribution.
1345  *
1346  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1347  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1348  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1349  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1350  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1351  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1352  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1353  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1354  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1355  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1356  */
1357 
1358 #include <sys/types.h>
1359 #include <sys/socket.h>
1360 #include <netinet/in.h>
1361 #include <arpa/inet.h>
1362 
1363 #include <errno.h>
1364 #include <netdb.h>
1365 #include <stdio.h>
1366 #include <stdlib.h>
1367 #include <string.h>
1368 #include <unistd.h>
1369 #include <resolv.h>
1370 
1371 #define SOCKS_PORT	"1080"
1372 #define HTTP_PROXY_PORT	"3128"
1373 #define HTTP_MAXHDRS	64
1374 #define SOCKS_V5	5
1375 #define SOCKS_V4	4
1376 #define SOCKS_NOAUTH	0
1377 #define SOCKS_NOMETHOD	0xff
1378 #define SOCKS_CONNECT	1
1379 #define SOCKS_IPV4	1
1380 #define SOCKS_DOMAIN	3
1381 #define SOCKS_IPV6	4
1382 
1383 int	remote_connect(const char *, const char *, struct addrinfo);
1384 int	socks_connect(const char *, const char *, struct addrinfo,
1385 	    const char *, const char *, struct addrinfo, int,
1386 	    const char *);
1387 
1388 static int
decode_addrport(const char * h,const char * p,struct sockaddr * addr,socklen_t addrlen,int v4only,int numeric)1389 decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1390     socklen_t addrlen, int v4only, int numeric)
1391 {
1392 	int r;
1393 	struct addrinfo hints, *res;
1394 
1395 	bzero(&hints, sizeof(hints));
1396 	hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1397 	hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1398 	hints.ai_socktype = SOCK_STREAM;
1399 	r = getaddrinfo(h, p, &hints, &res);
1400 	/* Don't fatal when attempting to convert a numeric address */
1401 	if (r != 0) {
1402 		if (!numeric) {
1403 			errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1404 			    gai_strerror(r));
1405 		}
1406 		return (-1);
1407 	}
1408 	if (addrlen < res->ai_addrlen) {
1409 		freeaddrinfo(res);
1410 		errx(1, "internal error: addrlen < res->ai_addrlen");
1411 	}
1412 	memcpy(addr, res->ai_addr, res->ai_addrlen);
1413 	freeaddrinfo(res);
1414 	return (0);
1415 }
1416 
1417 static int
proxy_read_line(int fd,char * buf,size_t bufsz)1418 proxy_read_line(int fd, char *buf, size_t bufsz)
1419 {
1420 	size_t off;
1421 
1422 	for(off = 0;;) {
1423 		if (off >= bufsz)
1424 			errx(1, "proxy read too long");
1425 		if (atomicio(read, fd, buf + off, 1) != 1)
1426 			err(1, "proxy read");
1427 		/* Skip CR */
1428 		if (buf[off] == '\r')
1429 			continue;
1430 		if (buf[off] == '\n') {
1431 			buf[off] = '\0';
1432 			break;
1433 		}
1434 		off++;
1435 	}
1436 	return (off);
1437 }
1438 
1439 static const char *
getproxypass(const char * proxyuser,const char * proxyhost)1440 getproxypass(const char *proxyuser, const char *proxyhost)
1441 {
1442 	char prompt[512];
1443 	static char pw[256];
1444 
1445 	snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1446 	   proxyuser, proxyhost);
1447 	if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1448 		errx(1, "Unable to read proxy passphrase");
1449 	return (pw);
1450 }
1451 
1452 int
socks_connect(const char * host,const char * port,struct addrinfo hints,const char * proxyhost,const char * proxyport,struct addrinfo proxyhints,int socksv,const char * proxyuser)1453 socks_connect(const char *host, const char *port,
1454     struct addrinfo hints __attribute__ ((__unused__)),
1455     const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1456     int socksv, const char *proxyuser)
1457 {
1458 	int proxyfd, r, authretry = 0;
1459 	size_t hlen, wlen = 0;
1460 	unsigned char buf[1024];
1461 	size_t cnt;
1462 	struct sockaddr_storage addr;
1463 	struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1464 	struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1465 	in_port_t serverport;
1466 	const char *proxypass = NULL;
1467 
1468 	if (proxyport == NULL)
1469 		proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1470 
1471 	/* Abuse API to lookup port */
1472 	if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1473 	    sizeof(addr), 1, 1) == -1)
1474 		errx(1, "unknown port \"%.64s\"", port);
1475 	serverport = in4->sin_port;
1476 
1477  again:
1478 	if (authretry++ > 3)
1479 		errx(1, "Too many authentication failures");
1480 
1481 	proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1482 
1483 	if (proxyfd < 0)
1484 		return (-1);
1485 
1486 	if (socksv == 5) {
1487 		if (decode_addrport(host, port, (struct sockaddr *)&addr,
1488 		    sizeof(addr), 0, 1) == -1)
1489 			addr.ss_family = 0; /* used in switch below */
1490 
1491 		/* Version 5, one method: no authentication */
1492 		buf[0] = SOCKS_V5;
1493 		buf[1] = 1;
1494 		buf[2] = SOCKS_NOAUTH;
1495 		cnt = atomicio(vwrite, proxyfd, buf, 3);
1496 		if (cnt != 3)
1497 			err(1, "write failed (%zu/3)", cnt);
1498 
1499 		cnt = atomicio(read, proxyfd, buf, 2);
1500 		if (cnt != 2)
1501 			err(1, "read failed (%zu/3)", cnt);
1502 
1503 		if (buf[1] == SOCKS_NOMETHOD)
1504 			errx(1, "authentication method negotiation failed");
1505 
1506 		switch (addr.ss_family) {
1507 		case 0:
1508 			/* Version 5, connect: domain name */
1509 
1510 			/* Max domain name length is 255 bytes */
1511 			hlen = strlen(host);
1512 			if (hlen > 255)
1513 				errx(1, "host name too long for SOCKS5");
1514 			buf[0] = SOCKS_V5;
1515 			buf[1] = SOCKS_CONNECT;
1516 			buf[2] = 0;
1517 			buf[3] = SOCKS_DOMAIN;
1518 			buf[4] = hlen;
1519 			memcpy(buf + 5, host, hlen);
1520 			memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1521 			wlen = 7 + hlen;
1522 			break;
1523 		case AF_INET:
1524 			/* Version 5, connect: IPv4 address */
1525 			buf[0] = SOCKS_V5;
1526 			buf[1] = SOCKS_CONNECT;
1527 			buf[2] = 0;
1528 			buf[3] = SOCKS_IPV4;
1529 			memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1530 			memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1531 			wlen = 10;
1532 			break;
1533 		case AF_INET6:
1534 			/* Version 5, connect: IPv6 address */
1535 			buf[0] = SOCKS_V5;
1536 			buf[1] = SOCKS_CONNECT;
1537 			buf[2] = 0;
1538 			buf[3] = SOCKS_IPV6;
1539 			memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1540 			memcpy(buf + 20, &in6->sin6_port,
1541 			    sizeof in6->sin6_port);
1542 			wlen = 22;
1543 			break;
1544 		default:
1545 			errx(1, "internal error: silly AF");
1546 		}
1547 
1548 		cnt = atomicio(vwrite, proxyfd, buf, wlen);
1549 		if (cnt != wlen)
1550 			err(1, "write failed (%zu/%zu)", cnt, wlen);
1551 
1552 		cnt = atomicio(read, proxyfd, buf, 4);
1553 		if (cnt != 4)
1554 			err(1, "read failed (%zu/4)", cnt);
1555 		if (buf[1] != 0)
1556 			errx(1, "connection failed, SOCKS error %d", buf[1]);
1557 		switch (buf[3]) {
1558 		case SOCKS_IPV4:
1559 			cnt = atomicio(read, proxyfd, buf + 4, 6);
1560 			if (cnt != 6)
1561 				err(1, "read failed (%zu/6)", cnt);
1562 			break;
1563 		case SOCKS_IPV6:
1564 			cnt = atomicio(read, proxyfd, buf + 4, 18);
1565 			if (cnt != 18)
1566 				err(1, "read failed (%zu/18)", cnt);
1567 			break;
1568 		default:
1569 			errx(1, "connection failed, unsupported address type");
1570 		}
1571 	} else if (socksv == 4) {
1572 		/* This will exit on lookup failure */
1573 		decode_addrport(host, port, (struct sockaddr *)&addr,
1574 		    sizeof(addr), 1, 0);
1575 
1576 		/* Version 4 */
1577 		buf[0] = SOCKS_V4;
1578 		buf[1] = SOCKS_CONNECT;	/* connect */
1579 		memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1580 		memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1581 		buf[8] = 0;	/* empty username */
1582 		wlen = 9;
1583 
1584 		cnt = atomicio(vwrite, proxyfd, buf, wlen);
1585 		if (cnt != wlen)
1586 			err(1, "write failed (%zu/%zu)", cnt, wlen);
1587 
1588 		cnt = atomicio(read, proxyfd, buf, 8);
1589 		if (cnt != 8)
1590 			err(1, "read failed (%zu/8)", cnt);
1591 		if (buf[1] != 90)
1592 			errx(1, "connection failed, SOCKS error %d", buf[1]);
1593 	} else if (socksv == -1) {
1594 		/* HTTP proxy CONNECT */
1595 
1596 		/* Disallow bad chars in hostname */
1597 		if (strcspn(host, "\r\n\t []:") != strlen(host))
1598 			errx(1, "Invalid hostname");
1599 
1600 		/* Try to be sane about numeric IPv6 addresses */
1601 		if (strchr(host, ':') != NULL) {
1602 			r = snprintf(buf, sizeof(buf),
1603 			    "CONNECT [%s]:%d HTTP/1.0\r\n",
1604 			    host, ntohs(serverport));
1605 		} else {
1606 			r = snprintf(buf, sizeof(buf),
1607 			    "CONNECT %s:%d HTTP/1.0\r\n",
1608 			    host, ntohs(serverport));
1609 		}
1610 		if (r == -1 || (size_t)r >= sizeof(buf))
1611 			errx(1, "hostname too long");
1612 		r = strlen(buf);
1613 
1614 		cnt = atomicio(vwrite, proxyfd, buf, r);
1615 		if (cnt != (size_t)r)
1616 			err(1, "write failed (%zu/%d)", cnt, r);
1617 
1618 		if (authretry > 1) {
1619 			char resp[1024];
1620 
1621 			proxypass = getproxypass(proxyuser, proxyhost);
1622 			r = snprintf(buf, sizeof(buf), "%s:%s",
1623 			    proxyuser, proxypass);
1624 			if (r == -1 || (size_t)r >= sizeof(buf) ||
1625 			    b64_ntop(buf, strlen(buf), resp,
1626 			    sizeof(resp)) == -1)
1627 				errx(1, "Proxy username/password too long");
1628 			r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1629 			    "Basic %s\r\n", resp);
1630 			if (r == -1 || (size_t)r >= sizeof(buf))
1631 				errx(1, "Proxy auth response too long");
1632 			r = strlen(buf);
1633 			if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1634 				err(1, "write failed (%zu/%d)", cnt, r);
1635 		}
1636 
1637 		/* Terminate headers */
1638 		if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1639 			err(1, "write failed (2/%d)", r);
1640 
1641 		/* Read status reply */
1642 		proxy_read_line(proxyfd, buf, sizeof(buf));
1643 		if (proxyuser != NULL &&
1644 		    strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1645 			if (authretry > 1) {
1646 				fprintf(stderr, "Proxy authentication "
1647 				    "failed\n");
1648 			}
1649 			close(proxyfd);
1650 			goto again;
1651 		} else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1652 		    strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1653 			errx(1, "Proxy error: \"%s\"", buf);
1654 
1655 		/* Headers continue until we hit an empty line */
1656 		for (r = 0; r < HTTP_MAXHDRS; r++) {
1657 			proxy_read_line(proxyfd, buf, sizeof(buf));
1658 			if (*buf == '\0')
1659 				break;
1660 		}
1661 		if (*buf != '\0')
1662 			errx(1, "Too many proxy headers received");
1663 	} else
1664 		errx(1, "Unknown proxy protocol %d", socksv);
1665 
1666 	return (proxyfd);
1667 }
1668 
1669