GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/nc/netcat.c Lines: 0 870 0.0 %
Date: 2017-11-13 Branches: 0 727 0.0 %

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