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