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