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