Merge commit 'db1c88f6dab43484b6c33636600ac4596ff4c354'
[unleashed.git] / bin / nc / netcat.c
blob51c846ba059681df1ab437fbcfb416e447212d0a
1 /* $OpenBSD: netcat.c,v 1.190 2018/03/19 16:35:29 jsing Exp $ */
2 /*
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4 * Copyright (c) 2015 Bob Beck. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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.
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.
31 * Re-written nc(1) for OpenBSD. Original implementation by
32 * *Hobbit* <hobbit@avian.org>.
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/uio.h>
38 #include <sys/un.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <netinet/ip.h>
43 #include <arpa/telnet.h>
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>
59 #include "atomicio.h"
61 #define PORT_MAX 65535
62 #define UNIX_DG_TMP_SOCKET_SIZE 19
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"
71 #define TLS_NOVERIFY (1 << 1)
72 #define TLS_NONAME (1 << 2)
73 #define TLS_CCERT (1 << 3)
74 #define TLS_MUSTSTAPLE (1 << 4)
76 /* Command Line Options */
77 int dflag; /* detached, no stdin */
78 int Fflag; /* fdpass sock to stdout */
79 unsigned int iflag; /* Interval Flag */
80 int kflag; /* More than one connect */
81 int lflag; /* Bind to local port */
82 int Nflag; /* shutdown() network socket */
83 int nflag; /* Don't do name look up */
84 char *Pflag; /* Proxy username */
85 char *pflag; /* Localport flag */
86 int rflag; /* Random ports flag */
87 char *sflag; /* Source Address */
88 int tflag; /* Telnet Emulation */
89 int uflag; /* UDP - Default to TCP */
90 int vflag; /* Verbosity */
91 int xflag; /* Socks proxy */
92 int zflag; /* Port Scan Flag */
93 int Dflag; /* sodebug */
94 int Iflag; /* TCP receive buffer size */
95 int Oflag; /* TCP send buffer size */
96 #ifdef TCP_MD5SIG
97 int Sflag; /* TCP MD5 signature option */
98 #endif
99 int Tflag = -1; /* IP Type of Service */
100 #ifdef SO_RTABLE
101 int rtableid = -1;
102 #endif
104 int usetls; /* use TLS */
105 char *Cflag; /* Public cert file */
106 char *Kflag; /* Private key file */
107 char *oflag; /* OCSP stapling file */
108 char *Rflag = DEFAULT_CA_FILE; /* Root CA file */
109 int tls_cachanged; /* Using non-default CA file */
110 int TLSopt; /* TLS options */
111 char *tls_expectname; /* required name in peer cert */
112 char *tls_expecthash; /* required hash of peer cert */
113 char *tls_ciphers; /* TLS ciphers */
114 char *tls_protocols; /* TLS protocols */
115 FILE *Zflag; /* file to save peer cert */
117 int recvcount, recvlimit;
118 int timeout = -1;
119 int family = AF_UNSPEC;
120 char *portlist[PORT_MAX+1];
121 char *unix_dg_tmp_socket;
122 int ttl = -1;
123 int minttl = -1;
125 void atelnet(int, unsigned char *, unsigned int);
126 int strtoport(char *portstr, int udp);
127 void build_ports(char *);
128 void help(void) __attribute__((noreturn));
129 int local_listen(char *, char *, struct addrinfo);
130 void readwrite(int, struct tls *);
131 void fdpass(int nfd) __attribute__((noreturn));
132 int remote_connect(const char *, const char *, struct addrinfo);
133 int timeout_tls(int, struct tls *, int (*)(struct tls *));
134 int timeout_connect(int, const struct sockaddr *, socklen_t);
135 int socks_connect(const char *, const char *, struct addrinfo,
136 const char *, const char *, struct addrinfo, int, const char *);
137 int udptest(int);
138 int unix_bind(char *, int);
139 int unix_connect(char *);
140 int unix_listen(char *);
141 void set_common_sockopts(int, int);
142 int process_tos_opt(char *, int *);
143 int process_tls_opt(char *, int *);
144 void save_peer_cert(struct tls *_tls_ctx, FILE *_fp);
145 void report_connect(const struct sockaddr *, socklen_t, char *);
146 void report_tls(struct tls *tls_ctx, char * host);
147 void usage(int);
148 ssize_t drainbuf(int, unsigned char *, size_t *, struct tls *);
149 ssize_t fillbuf(int, unsigned char *, size_t *, struct tls *);
150 void tls_setup_client(struct tls *, int, char *);
151 struct tls *tls_setup_server(struct tls *, int, char *);
154 main(int argc, char *argv[])
156 int ch, s = -1, ret, socksv;
157 char *host, *uport;
158 struct addrinfo hints;
159 struct servent *sv;
160 socklen_t len;
161 struct sockaddr_storage cliaddr;
162 char *proxy = NULL, *proxyport = NULL;
163 const char *errstr;
164 struct addrinfo proxyhints;
165 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
166 struct tls_config *tls_cfg = NULL;
167 struct tls *tls_ctx = NULL;
168 uint32_t protocols;
170 ret = 1;
171 socksv = 5;
172 host = NULL;
173 uport = NULL;
174 sv = NULL;
176 signal(SIGPIPE, SIG_IGN);
178 while ((ch = getopt(argc, argv,
179 "46C:cDde:FH:hI:i:K:klM:m:NnO:o:P:p:R:rSs:T:tUuV:vW:w:X:x:Z:z"))
180 != -1) {
181 switch (ch) {
182 case '4':
183 family = AF_INET;
184 break;
185 case '6':
186 family = AF_INET6;
187 break;
188 case 'U':
189 family = AF_UNIX;
190 break;
191 case 'X':
192 if (strcasecmp(optarg, "connect") == 0)
193 socksv = -1; /* HTTP proxy CONNECT */
194 else if (strcmp(optarg, "4") == 0)
195 socksv = 4; /* SOCKS v.4 */
196 else if (strcmp(optarg, "5") == 0)
197 socksv = 5; /* SOCKS v.5 */
198 else
199 errx(1, "unsupported proxy protocol");
200 break;
201 case 'C':
202 Cflag = optarg;
203 break;
204 case 'c':
205 usetls = 1;
206 break;
207 case 'd':
208 dflag = 1;
209 break;
210 case 'e':
211 tls_expectname = optarg;
212 break;
213 case 'F':
214 Fflag = 1;
215 break;
216 case 'H':
217 tls_expecthash = optarg;
218 break;
219 case 'h':
220 help();
221 break;
222 case 'i':
223 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
224 if (errstr)
225 errx(1, "interval %s: %s", errstr, optarg);
226 break;
227 case 'K':
228 Kflag = optarg;
229 break;
230 case 'k':
231 kflag = 1;
232 break;
233 case 'l':
234 lflag = 1;
235 break;
236 case 'M':
237 ttl = strtonum(optarg, 0, 255, &errstr);
238 if (errstr)
239 errx(1, "ttl is %s", errstr);
240 break;
241 case 'm':
242 minttl = strtonum(optarg, 0, 255, &errstr);
243 if (errstr)
244 errx(1, "minttl is %s", errstr);
245 break;
246 case 'N':
247 Nflag = 1;
248 break;
249 case 'n':
250 nflag = 1;
251 break;
252 case 'P':
253 Pflag = optarg;
254 break;
255 case 'p':
256 pflag = optarg;
257 break;
258 case 'R':
259 tls_cachanged = 1;
260 Rflag = optarg;
261 break;
262 case 'r':
263 rflag = 1;
264 break;
265 case 's':
266 sflag = optarg;
267 break;
268 case 't':
269 tflag = 1;
270 break;
271 case 'u':
272 uflag = 1;
273 break;
274 #ifdef SO_RTABLE
275 case 'V':
276 rtableid = (int)strtonum(optarg, 0,
277 RT_TABLEID_MAX, &errstr);
278 if (errstr)
279 errx(1, "rtable %s: %s", errstr, optarg);
280 break;
281 #endif
282 case 'v':
283 vflag = 1;
284 break;
285 case 'W':
286 recvlimit = strtonum(optarg, 1, INT_MAX, &errstr);
287 if (errstr)
288 errx(1, "receive limit %s: %s", errstr, optarg);
289 break;
290 case 'w':
291 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
292 if (errstr)
293 errx(1, "timeout %s: %s", errstr, optarg);
294 timeout *= 1000;
295 break;
296 case 'x':
297 xflag = 1;
298 if ((proxy = strdup(optarg)) == NULL)
299 err(1, NULL);
300 break;
301 case 'Z':
302 if (strcmp(optarg, "-") == 0)
303 Zflag = stderr;
304 else if ((Zflag = fopen(optarg, "w")) == NULL)
305 err(1, "can't open %s", optarg);
306 break;
307 case 'z':
308 zflag = 1;
309 break;
310 case 'D':
311 Dflag = 1;
312 break;
313 case 'I':
314 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
315 if (errstr != NULL)
316 errx(1, "TCP receive window %s: %s",
317 errstr, optarg);
318 break;
319 case 'O':
320 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
321 if (errstr != NULL)
322 errx(1, "TCP send window %s: %s",
323 errstr, optarg);
324 break;
325 case 'o':
326 oflag = optarg;
327 break;
328 #ifdef TCP_MD5SIG
329 case 'S':
330 Sflag = 1;
331 break;
332 #endif
333 case 'T':
334 errstr = NULL;
335 errno = 0;
336 if (process_tls_opt(optarg, &TLSopt))
337 break;
338 if (process_tos_opt(optarg, &Tflag))
339 break;
340 if (strlen(optarg) > 1 && optarg[0] == '0' &&
341 optarg[1] == 'x')
342 Tflag = (int)strtol(optarg, NULL, 16);
343 else
344 Tflag = (int)strtonum(optarg, 0, 255,
345 &errstr);
346 if (Tflag < 0 || Tflag > 255 || errstr || errno)
347 errx(1, "illegal tos/tls value %s", optarg);
348 break;
349 default:
350 usage(1);
353 argc -= optind;
354 argv += optind;
356 #ifdef SO_RTABLE
357 if (rtableid >= 0)
358 if (setrtable(rtableid) == -1)
359 err(1, "setrtable");
360 #endif
362 if (family == AF_UNIX) {
363 if (pledge("stdio rpath wpath cpath tmppath unix", NULL) == -1)
364 err(1, "pledge");
365 } else if (Fflag && Pflag) {
366 if (pledge("stdio inet dns sendfd tty", NULL) == -1)
367 err(1, "pledge");
368 } else if (Fflag) {
369 if (pledge("stdio inet dns sendfd", NULL) == -1)
370 err(1, "pledge");
371 } else if (Pflag && usetls) {
372 if (pledge("stdio rpath inet dns tty", NULL) == -1)
373 err(1, "pledge");
374 } else if (Pflag) {
375 if (pledge("stdio inet dns tty", NULL) == -1)
376 err(1, "pledge");
377 } else if (usetls) {
378 if (pledge("stdio rpath inet dns", NULL) == -1)
379 err(1, "pledge");
380 } else if (pledge("stdio inet dns", NULL) == -1)
381 err(1, "pledge");
383 /* Cruft to make sure options are clean, and used properly. */
384 if (argv[0] && !argv[1] && family == AF_UNIX) {
385 host = argv[0];
386 uport = NULL;
387 } else if (argv[0] && !argv[1]) {
388 if (!lflag)
389 usage(1);
390 uport = argv[0];
391 host = NULL;
392 } else if (argv[0] && argv[1]) {
393 host = argv[0];
394 uport = argv[1];
395 } else
396 usage(1);
398 if (lflag && sflag)
399 errx(1, "cannot use -s and -l");
400 if (lflag && pflag)
401 errx(1, "cannot use -p and -l");
402 if (lflag && zflag)
403 errx(1, "cannot use -z and -l");
404 if (!lflag && kflag)
405 errx(1, "must use -l with -k");
406 if (uflag && usetls)
407 errx(1, "cannot use -c and -u");
408 if ((family == AF_UNIX) && usetls)
409 errx(1, "cannot use -c and -U");
410 if ((family == AF_UNIX) && Fflag)
411 errx(1, "cannot use -F and -U");
412 if (Fflag && usetls)
413 errx(1, "cannot use -c and -F");
414 if (TLSopt && !usetls)
415 errx(1, "you must specify -c to use TLS options");
416 if (Cflag && !usetls)
417 errx(1, "you must specify -c to use -C");
418 if (Kflag && !usetls)
419 errx(1, "you must specify -c to use -K");
420 if (Zflag && !usetls)
421 errx(1, "you must specify -c to use -Z");
422 if (oflag && !Cflag)
423 errx(1, "you must specify -C to use -o");
424 if (tls_cachanged && !usetls)
425 errx(1, "you must specify -c to use -R");
426 if (tls_expecthash && !usetls)
427 errx(1, "you must specify -c to use -H");
428 if (tls_expectname && !usetls)
429 errx(1, "you must specify -c to use -e");
431 /* Get name of temporary socket for unix datagram client */
432 if ((family == AF_UNIX) && uflag && !lflag) {
433 if (sflag) {
434 unix_dg_tmp_socket = sflag;
435 } else {
436 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
437 UNIX_DG_TMP_SOCKET_SIZE);
438 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
439 err(1, "mktemp");
440 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
444 /* Initialize addrinfo structure. */
445 if (family != AF_UNIX) {
446 memset(&hints, 0, sizeof(struct addrinfo));
447 hints.ai_family = family;
448 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
449 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
450 if (nflag)
451 hints.ai_flags |= AI_NUMERICHOST;
454 if (xflag) {
455 if (uflag)
456 errx(1, "no proxy support for UDP mode");
458 if (lflag)
459 errx(1, "no proxy support for listen");
461 if (family == AF_UNIX)
462 errx(1, "no proxy support for unix sockets");
464 if (sflag)
465 errx(1, "no proxy support for local source address");
467 if (*proxy == '[') {
468 ++proxy;
469 proxyport = strchr(proxy, ']');
470 if (proxyport == NULL)
471 errx(1, "missing closing bracket in proxy");
472 *proxyport++ = '\0';
473 if (*proxyport == '\0')
474 /* Use default proxy port. */
475 proxyport = NULL;
476 else {
477 if (*proxyport == ':')
478 ++proxyport;
479 else
480 errx(1, "garbage proxy port delimiter");
482 } else {
483 proxyport = strrchr(proxy, ':');
484 if (proxyport != NULL)
485 *proxyport++ = '\0';
488 memset(&proxyhints, 0, sizeof(struct addrinfo));
489 proxyhints.ai_family = family;
490 proxyhints.ai_socktype = SOCK_STREAM;
491 proxyhints.ai_protocol = IPPROTO_TCP;
492 if (nflag)
493 proxyhints.ai_flags |= AI_NUMERICHOST;
496 if (usetls) {
497 if ((tls_cfg = tls_config_new()) == NULL)
498 errx(1, "unable to allocate TLS config");
499 if (Rflag && tls_config_set_ca_file(tls_cfg, Rflag) == -1)
500 errx(1, "%s", tls_config_error(tls_cfg));
501 if (Cflag && tls_config_set_cert_file(tls_cfg, Cflag) == -1)
502 errx(1, "%s", tls_config_error(tls_cfg));
503 if (Kflag && tls_config_set_key_file(tls_cfg, Kflag) == -1)
504 errx(1, "%s", tls_config_error(tls_cfg));
505 if (oflag && tls_config_set_ocsp_staple_file(tls_cfg, oflag) == -1)
506 errx(1, "%s", tls_config_error(tls_cfg));
507 if (tls_config_parse_protocols(&protocols, tls_protocols) == -1)
508 errx(1, "invalid TLS protocols `%s'", tls_protocols);
509 if (tls_config_set_protocols(tls_cfg, protocols) == -1)
510 errx(1, "%s", tls_config_error(tls_cfg));
511 if (tls_config_set_ciphers(tls_cfg, tls_ciphers) == -1)
512 errx(1, "%s", tls_config_error(tls_cfg));
513 if (!lflag && (TLSopt & TLS_CCERT))
514 errx(1, "clientcert is only valid with -l");
515 if (TLSopt & TLS_NONAME)
516 tls_config_insecure_noverifyname(tls_cfg);
517 if (TLSopt & TLS_NOVERIFY) {
518 if (tls_expecthash != NULL)
519 errx(1, "-H and -T noverify may not be used "
520 "together");
521 tls_config_insecure_noverifycert(tls_cfg);
523 if (TLSopt & TLS_MUSTSTAPLE)
524 tls_config_ocsp_require_stapling(tls_cfg);
526 if (Pflag) {
527 if (pledge("stdio inet dns tty", NULL) == -1)
528 err(1, "pledge");
529 } else if (pledge("stdio inet dns", NULL) == -1)
530 err(1, "pledge");
532 if (lflag) {
533 struct tls *tls_cctx = NULL;
534 int connfd;
535 ret = 0;
537 if (family == AF_UNIX) {
538 if (uflag)
539 s = unix_bind(host, 0);
540 else
541 s = unix_listen(host);
544 if (usetls) {
545 tls_config_verify_client_optional(tls_cfg);
546 if ((tls_ctx = tls_server()) == NULL)
547 errx(1, "tls server creation failed");
548 if (tls_configure(tls_ctx, tls_cfg) == -1)
549 errx(1, "tls configuration failed (%s)",
550 tls_error(tls_ctx));
552 /* Allow only one connection at a time, but stay alive. */
553 for (;;) {
554 if (family != AF_UNIX)
555 s = local_listen(host, uport, hints);
556 if (s < 0)
557 err(1, NULL);
558 if (uflag && kflag) {
560 * For UDP and -k, don't connect the socket,
561 * let it receive datagrams from multiple
562 * socket pairs.
564 readwrite(s, NULL);
565 } else if (uflag && !kflag) {
567 * For UDP and not -k, we will use recvfrom()
568 * initially to wait for a caller, then use
569 * the regular functions to talk to the caller.
571 int rv;
572 char buf[2048];
573 struct sockaddr_storage z;
575 len = sizeof(z);
576 rv = recvfrom(s, buf, sizeof(buf), MSG_PEEK,
577 (struct sockaddr *)&z, &len);
578 if (rv < 0)
579 err(1, "recvfrom");
581 rv = connect(s, (struct sockaddr *)&z, len);
582 if (rv < 0)
583 err(1, "connect");
585 if (vflag)
586 report_connect((struct sockaddr *)&z, len, NULL);
588 readwrite(s, NULL);
589 } else {
590 len = sizeof(cliaddr);
591 connfd = accept4(s, (struct sockaddr *)&cliaddr,
592 &len, SOCK_NONBLOCK);
593 if (connfd == -1) {
594 /* For now, all errnos are fatal */
595 err(1, "accept");
597 if (vflag)
598 report_connect((struct sockaddr *)&cliaddr, len,
599 family == AF_UNIX ? host : NULL);
600 if ((usetls) &&
601 (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
602 readwrite(connfd, tls_cctx);
603 if (!usetls)
604 readwrite(connfd, NULL);
605 if (tls_cctx) {
606 timeout_tls(s, tls_cctx, tls_close);
607 tls_free(tls_cctx);
608 tls_cctx = NULL;
610 close(connfd);
612 if (family != AF_UNIX)
613 close(s);
614 else if (uflag) {
615 if (connect(s, NULL, 0) < 0)
616 err(1, "connect");
619 if (!kflag)
620 break;
622 } else if (family == AF_UNIX) {
623 ret = 0;
625 if ((s = unix_connect(host)) > 0) {
626 if (!zflag)
627 readwrite(s, NULL);
628 close(s);
629 } else
630 ret = 1;
632 if (uflag)
633 unlink(unix_dg_tmp_socket);
634 return ret;
636 } else {
637 int i = 0;
639 /* Construct the portlist[] array. */
640 build_ports(uport);
642 /* Cycle through portlist, connecting to each port. */
643 for (s = -1, i = 0; portlist[i] != NULL; i++) {
644 if (s != -1)
645 close(s);
647 if (usetls) {
648 if ((tls_ctx = tls_client()) == NULL)
649 errx(1, "tls client creation failed");
650 if (tls_configure(tls_ctx, tls_cfg) == -1)
651 errx(1, "tls configuration failed (%s)",
652 tls_error(tls_ctx));
654 if (xflag)
655 s = socks_connect(host, portlist[i], hints,
656 proxy, proxyport, proxyhints, socksv,
657 Pflag);
658 else
659 s = remote_connect(host, portlist[i], hints);
661 if (s == -1)
662 continue;
664 ret = 0;
665 if (vflag || zflag) {
666 /* For UDP, make sure we are connected. */
667 if (uflag) {
668 if (udptest(s) == -1) {
669 ret = 1;
670 continue;
674 /* Don't look up port if -n. */
675 if (nflag)
676 sv = NULL;
677 else {
678 sv = getservbyport(
679 ntohs(atoi(portlist[i])),
680 uflag ? "udp" : "tcp");
683 fprintf(stderr,
684 "Connection to %s %s port [%s/%s] "
685 "succeeded!\n", host, portlist[i],
686 uflag ? "udp" : "tcp",
687 sv ? sv->s_name : "*");
689 if (Fflag)
690 fdpass(s);
691 else {
692 if (usetls)
693 tls_setup_client(tls_ctx, s, host);
694 if (!zflag)
695 readwrite(s, tls_ctx);
696 if (tls_ctx) {
697 timeout_tls(s, tls_ctx, tls_close);
698 tls_free(tls_ctx);
699 tls_ctx = NULL;
705 if (s != -1)
706 close(s);
708 tls_config_free(tls_cfg);
710 return ret;
714 * unix_bind()
715 * Returns a unix socket bound to the given path
718 unix_bind(char *path, int flags)
720 struct sockaddr_un s_un;
721 int s, save_errno;
723 /* Create unix domain socket. */
724 if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
725 0)) < 0)
726 return -1;
728 memset(&s_un, 0, sizeof(struct sockaddr_un));
729 s_un.sun_family = AF_UNIX;
731 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
732 sizeof(s_un.sun_path)) {
733 close(s);
734 errno = ENAMETOOLONG;
735 return -1;
738 if (bind(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
739 save_errno = errno;
740 close(s);
741 errno = save_errno;
742 return -1;
745 return s;
749 timeout_tls(int s, struct tls *tls_ctx, int (*func)(struct tls *))
751 struct pollfd pfd;
752 int ret;
754 while ((ret = (*func)(tls_ctx)) != 0) {
755 if (ret == TLS_WANT_POLLIN)
756 pfd.events = POLLIN;
757 else if (ret == TLS_WANT_POLLOUT)
758 pfd.events = POLLOUT;
759 else
760 break;
761 pfd.fd = s;
762 if ((ret = poll(&pfd, 1, timeout)) == 1)
763 continue;
764 else if (ret == 0) {
765 errno = ETIMEDOUT;
766 ret = -1;
767 break;
768 } else
769 err(1, "poll failed");
772 return ret;
775 void
776 tls_setup_client(struct tls *tls_ctx, int s, char *host)
778 const char *errstr;
780 if (tls_connect_socket(tls_ctx, s,
781 tls_expectname ? tls_expectname : host) == -1) {
782 errx(1, "tls connection failed (%s)",
783 tls_error(tls_ctx));
785 if (timeout_tls(s, tls_ctx, tls_handshake) == -1) {
786 if ((errstr = tls_error(tls_ctx)) == NULL)
787 errstr = strerror(errno);
788 errx(1, "tls handshake failed (%s)", errstr);
790 if (vflag)
791 report_tls(tls_ctx, host);
792 if (tls_expecthash && tls_peer_cert_hash(tls_ctx) &&
793 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
794 errx(1, "peer certificate is not %s", tls_expecthash);
795 if (Zflag) {
796 save_peer_cert(tls_ctx, Zflag);
797 if (Zflag != stderr && (fclose(Zflag) != 0))
798 err(1, "fclose failed saving peer cert");
802 struct tls *
803 tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
805 struct tls *tls_cctx;
806 const char *errstr;
808 if (tls_accept_socket(tls_ctx, &tls_cctx, connfd) == -1) {
809 warnx("tls accept failed (%s)", tls_error(tls_ctx));
810 } else if (timeout_tls(connfd, tls_cctx, tls_handshake) == -1) {
811 if ((errstr = tls_error(tls_cctx)) == NULL)
812 errstr = strerror(errno);
813 warnx("tls handshake failed (%s)", errstr);
814 } else {
815 int gotcert = tls_peer_cert_provided(tls_cctx);
817 if (vflag && gotcert)
818 report_tls(tls_cctx, host);
819 if ((TLSopt & TLS_CCERT) && !gotcert)
820 warnx("No client certificate provided");
821 else if (gotcert && tls_peer_cert_hash(tls_ctx) && tls_expecthash &&
822 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
823 warnx("peer certificate is not %s", tls_expecthash);
824 else if (gotcert && tls_expectname &&
825 (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
826 warnx("name (%s) not found in client cert",
827 tls_expectname);
828 else {
829 return tls_cctx;
832 return NULL;
836 * unix_connect()
837 * Returns a socket connected to a local unix socket. Returns -1 on failure.
840 unix_connect(char *path)
842 struct sockaddr_un s_un;
843 int s, save_errno;
845 if (uflag) {
846 if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) < 0)
847 return -1;
848 } else {
849 if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
850 return -1;
853 memset(&s_un, 0, sizeof(struct sockaddr_un));
854 s_un.sun_family = AF_UNIX;
856 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
857 sizeof(s_un.sun_path)) {
858 close(s);
859 errno = ENAMETOOLONG;
860 return -1;
862 if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
863 save_errno = errno;
864 close(s);
865 errno = save_errno;
866 return -1;
868 return s;
873 * unix_listen()
874 * Create a unix domain socket, and listen on it.
877 unix_listen(char *path)
879 int s;
880 if ((s = unix_bind(path, 0)) < 0)
881 return -1;
883 if (listen(s, 5) < 0) {
884 close(s);
885 return -1;
887 return s;
891 * remote_connect()
892 * Returns a socket connected to a remote host. Properly binds to a local
893 * port or source address if needed. Returns -1 on failure.
896 remote_connect(const char *host, const char *port, struct addrinfo hints)
898 struct addrinfo *res, *res0;
899 int s = -1, error, save_errno;
900 #ifdef SO_BINDANY
901 int on = 1;
902 #endif
904 if ((error = getaddrinfo(host, port, &hints, &res0)))
905 errx(1, "getaddrinfo for host \"%s\" port %s: %s", host,
906 port, gai_strerror(error));
908 for (res = res0; res; res = res->ai_next) {
909 if ((s = socket(res->ai_family, res->ai_socktype |
910 SOCK_NONBLOCK, res->ai_protocol)) < 0)
911 continue;
913 /* Bind to a local port or source address if specified. */
914 if (sflag || pflag) {
915 struct addrinfo ahints, *ares;
917 #ifdef SO_BINDANY
918 /* try SO_BINDANY, but don't insist */
919 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
920 #endif
921 memset(&ahints, 0, sizeof(struct addrinfo));
922 ahints.ai_family = res->ai_family;
923 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
924 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
925 ahints.ai_flags = AI_PASSIVE;
926 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
927 errx(1, "getaddrinfo: %s", gai_strerror(error));
929 if (bind(s, (struct sockaddr *)ares->ai_addr,
930 ares->ai_addrlen) < 0)
931 err(1, "bind failed");
932 freeaddrinfo(ares);
935 set_common_sockopts(s, res->ai_family);
937 if (timeout_connect(s, res->ai_addr, res->ai_addrlen) == 0)
938 break;
939 if (vflag)
940 warn("connect to %s port %s (%s) failed", host, port,
941 uflag ? "udp" : "tcp");
943 save_errno = errno;
944 close(s);
945 errno = save_errno;
946 s = -1;
949 freeaddrinfo(res0);
951 return s;
955 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
957 struct pollfd pfd;
958 socklen_t optlen;
959 int optval;
960 int ret;
962 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
963 pfd.fd = s;
964 pfd.events = POLLOUT;
965 if ((ret = poll(&pfd, 1, timeout)) == 1) {
966 optlen = sizeof(optval);
967 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
968 &optval, &optlen)) == 0) {
969 errno = optval;
970 ret = optval == 0 ? 0 : -1;
972 } else if (ret == 0) {
973 errno = ETIMEDOUT;
974 ret = -1;
975 } else
976 err(1, "poll failed");
979 return ret;
983 * local_listen()
984 * Returns a socket listening on a local port, binds to specified source
985 * address. Returns -1 on failure.
988 local_listen(char *host, char *port, struct addrinfo hints)
990 struct addrinfo *res, *res0;
991 int s = -1, save_errno;
992 #ifdef SO_REUSEPORT
993 int ret, x = 1;
994 #endif
995 int error;
997 /* Allow nodename to be null. */
998 hints.ai_flags |= AI_PASSIVE;
1001 * In the case of binding to a wildcard address
1002 * default to binding to an ipv4 address.
1004 if (host == NULL && hints.ai_family == AF_UNSPEC)
1005 hints.ai_family = AF_INET;
1007 if ((error = getaddrinfo(host, port, &hints, &res0)))
1008 errx(1, "getaddrinfo: %s", gai_strerror(error));
1010 for (res = res0; res; res = res->ai_next) {
1011 if ((s = socket(res->ai_family, res->ai_socktype,
1012 res->ai_protocol)) < 0)
1013 continue;
1015 #ifdef SO_REUSEPORT
1016 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
1017 if (ret == -1)
1018 err(1, NULL);
1019 #endif
1021 set_common_sockopts(s, res->ai_family);
1023 if (bind(s, (struct sockaddr *)res->ai_addr,
1024 res->ai_addrlen) == 0)
1025 break;
1027 save_errno = errno;
1028 close(s);
1029 errno = save_errno;
1030 s = -1;
1033 if (!uflag && s != -1) {
1034 if (listen(s, 1) < 0)
1035 err(1, "listen");
1038 freeaddrinfo(res0);
1040 return s;
1044 * readwrite()
1045 * Loop that polls on the network file descriptor and stdin.
1047 void
1048 readwrite(int net_fd, struct tls *tls_ctx)
1050 struct pollfd pfd[4];
1051 int stdin_fd = STDIN_FILENO;
1052 int stdout_fd = STDOUT_FILENO;
1053 unsigned char netinbuf[BUFSIZE];
1054 size_t netinbufpos = 0;
1055 unsigned char stdinbuf[BUFSIZE];
1056 size_t stdinbufpos = 0;
1057 int n, num_fds;
1058 ssize_t ret;
1060 /* don't read from stdin if requested */
1061 if (dflag)
1062 stdin_fd = -1;
1064 /* stdin */
1065 pfd[POLL_STDIN].fd = stdin_fd;
1066 pfd[POLL_STDIN].events = POLLIN;
1068 /* network out */
1069 pfd[POLL_NETOUT].fd = net_fd;
1070 pfd[POLL_NETOUT].events = 0;
1072 /* network in */
1073 pfd[POLL_NETIN].fd = net_fd;
1074 pfd[POLL_NETIN].events = POLLIN;
1076 /* stdout */
1077 pfd[POLL_STDOUT].fd = stdout_fd;
1078 pfd[POLL_STDOUT].events = 0;
1080 while (1) {
1081 /* both inputs are gone, buffers are empty, we are done */
1082 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
1083 stdinbufpos == 0 && netinbufpos == 0)
1084 return;
1085 /* both outputs are gone, we can't continue */
1086 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1)
1087 return;
1088 /* listen and net in gone, queues empty, done */
1089 if (lflag && pfd[POLL_NETIN].fd == -1 &&
1090 stdinbufpos == 0 && netinbufpos == 0)
1091 return;
1093 /* help says -i is for "wait between lines sent". We read and
1094 * write arbitrary amounts of data, and we don't want to start
1095 * scanning for newlines, so this is as good as it gets */
1096 if (iflag)
1097 sleep(iflag);
1099 /* poll */
1100 num_fds = poll(pfd, 4, timeout);
1102 /* treat poll errors */
1103 if (num_fds == -1)
1104 err(1, "polling error");
1106 /* timeout happened */
1107 if (num_fds == 0)
1108 return;
1110 /* treat socket error conditions */
1111 for (n = 0; n < 4; n++) {
1112 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
1113 pfd[n].fd = -1;
1116 /* reading is possible after HUP */
1117 if (pfd[POLL_STDIN].events & POLLIN &&
1118 pfd[POLL_STDIN].revents & POLLHUP &&
1119 !(pfd[POLL_STDIN].revents & POLLIN))
1120 pfd[POLL_STDIN].fd = -1;
1122 if (pfd[POLL_NETIN].events & POLLIN &&
1123 pfd[POLL_NETIN].revents & POLLHUP &&
1124 !(pfd[POLL_NETIN].revents & POLLIN))
1125 pfd[POLL_NETIN].fd = -1;
1127 if (pfd[POLL_NETOUT].revents & POLLHUP) {
1128 if (Nflag)
1129 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1130 pfd[POLL_NETOUT].fd = -1;
1132 /* if HUP, stop watching stdout */
1133 if (pfd[POLL_STDOUT].revents & POLLHUP)
1134 pfd[POLL_STDOUT].fd = -1;
1135 /* if no net out, stop watching stdin */
1136 if (pfd[POLL_NETOUT].fd == -1)
1137 pfd[POLL_STDIN].fd = -1;
1138 /* if no stdout, stop watching net in */
1139 if (pfd[POLL_STDOUT].fd == -1) {
1140 if (pfd[POLL_NETIN].fd != -1)
1141 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1142 pfd[POLL_NETIN].fd = -1;
1145 /* try to read from stdin */
1146 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
1147 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
1148 &stdinbufpos, NULL);
1149 if (ret == TLS_WANT_POLLIN)
1150 pfd[POLL_STDIN].events = POLLIN;
1151 else if (ret == TLS_WANT_POLLOUT)
1152 pfd[POLL_STDIN].events = POLLOUT;
1153 else if (ret == 0 || ret == -1)
1154 pfd[POLL_STDIN].fd = -1;
1155 /* read something - poll net out */
1156 if (stdinbufpos > 0)
1157 pfd[POLL_NETOUT].events = POLLOUT;
1158 /* filled buffer - remove self from polling */
1159 if (stdinbufpos == BUFSIZE)
1160 pfd[POLL_STDIN].events = 0;
1162 /* try to write to network */
1163 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
1164 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
1165 &stdinbufpos, tls_ctx);
1166 if (ret == TLS_WANT_POLLIN)
1167 pfd[POLL_NETOUT].events = POLLIN;
1168 else if (ret == TLS_WANT_POLLOUT)
1169 pfd[POLL_NETOUT].events = POLLOUT;
1170 else if (ret == -1)
1171 pfd[POLL_NETOUT].fd = -1;
1172 /* buffer empty - remove self from polling */
1173 if (stdinbufpos == 0)
1174 pfd[POLL_NETOUT].events = 0;
1175 /* buffer no longer full - poll stdin again */
1176 if (stdinbufpos < BUFSIZE)
1177 pfd[POLL_STDIN].events = POLLIN;
1179 /* try to read from network */
1180 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
1181 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
1182 &netinbufpos, tls_ctx);
1183 if (ret == TLS_WANT_POLLIN)
1184 pfd[POLL_NETIN].events = POLLIN;
1185 else if (ret == TLS_WANT_POLLOUT)
1186 pfd[POLL_NETIN].events = POLLOUT;
1187 else if (ret == -1)
1188 pfd[POLL_NETIN].fd = -1;
1189 /* eof on net in - remove from pfd */
1190 if (ret == 0) {
1191 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1192 pfd[POLL_NETIN].fd = -1;
1194 if (recvlimit > 0 && ++recvcount >= recvlimit) {
1195 if (pfd[POLL_NETIN].fd != -1)
1196 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1197 pfd[POLL_NETIN].fd = -1;
1198 pfd[POLL_STDIN].fd = -1;
1200 /* read something - poll stdout */
1201 if (netinbufpos > 0)
1202 pfd[POLL_STDOUT].events = POLLOUT;
1203 /* filled buffer - remove self from polling */
1204 if (netinbufpos == BUFSIZE)
1205 pfd[POLL_NETIN].events = 0;
1206 /* handle telnet */
1207 if (tflag)
1208 atelnet(pfd[POLL_NETIN].fd, netinbuf,
1209 netinbufpos);
1211 /* try to write to stdout */
1212 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1213 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1214 &netinbufpos, NULL);
1215 if (ret == TLS_WANT_POLLIN)
1216 pfd[POLL_STDOUT].events = POLLIN;
1217 else if (ret == TLS_WANT_POLLOUT)
1218 pfd[POLL_STDOUT].events = POLLOUT;
1219 else if (ret == -1)
1220 pfd[POLL_STDOUT].fd = -1;
1221 /* buffer empty - remove self from polling */
1222 if (netinbufpos == 0)
1223 pfd[POLL_STDOUT].events = 0;
1224 /* buffer no longer full - poll net in again */
1225 if (netinbufpos < BUFSIZE)
1226 pfd[POLL_NETIN].events = POLLIN;
1229 /* stdin gone and queue empty? */
1230 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1231 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
1232 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1233 pfd[POLL_NETOUT].fd = -1;
1235 /* net in gone and queue empty? */
1236 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1237 pfd[POLL_STDOUT].fd = -1;
1242 ssize_t
1243 drainbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1245 ssize_t n;
1246 ssize_t adjust;
1248 if (tls)
1249 n = tls_write(tls, buf, *bufpos);
1250 else {
1251 n = write(fd, buf, *bufpos);
1252 /* don't treat EAGAIN, EINTR as error */
1253 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1254 n = TLS_WANT_POLLOUT;
1256 if (n <= 0)
1257 return n;
1258 /* adjust buffer */
1259 adjust = *bufpos - n;
1260 if (adjust > 0)
1261 memmove(buf, buf + n, adjust);
1262 *bufpos -= n;
1263 return n;
1266 ssize_t
1267 fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1269 size_t num = BUFSIZE - *bufpos;
1270 ssize_t n;
1272 if (tls)
1273 n = tls_read(tls, buf + *bufpos, num);
1274 else {
1275 n = read(fd, buf + *bufpos, num);
1276 /* don't treat EAGAIN, EINTR as error */
1277 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1278 n = TLS_WANT_POLLIN;
1280 if (n <= 0)
1281 return n;
1282 *bufpos += n;
1283 return n;
1287 * fdpass()
1288 * Pass the connected file descriptor to stdout and exit.
1290 void
1291 fdpass(int nfd)
1293 struct msghdr mh;
1294 union {
1295 struct cmsghdr hdr;
1296 char buf[CMSG_SPACE(sizeof(int))];
1297 } cmsgbuf;
1298 struct cmsghdr *cmsg;
1299 struct iovec iov;
1300 char c = '\0';
1301 ssize_t r;
1302 struct pollfd pfd;
1304 /* Avoid obvious stupidity */
1305 if (isatty(STDOUT_FILENO))
1306 errx(1, "Cannot pass file descriptor to tty");
1308 bzero(&mh, sizeof(mh));
1309 bzero(&cmsgbuf, sizeof(cmsgbuf));
1310 bzero(&iov, sizeof(iov));
1312 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1313 mh.msg_controllen = sizeof(cmsgbuf.buf);
1314 cmsg = CMSG_FIRSTHDR(&mh);
1315 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1316 cmsg->cmsg_level = SOL_SOCKET;
1317 cmsg->cmsg_type = SCM_RIGHTS;
1318 *(int *)CMSG_DATA(cmsg) = nfd;
1320 iov.iov_base = &c;
1321 iov.iov_len = 1;
1322 mh.msg_iov = &iov;
1323 mh.msg_iovlen = 1;
1325 bzero(&pfd, sizeof(pfd));
1326 pfd.fd = STDOUT_FILENO;
1327 pfd.events = POLLOUT;
1328 for (;;) {
1329 r = sendmsg(STDOUT_FILENO, &mh, 0);
1330 if (r == -1) {
1331 if (errno == EAGAIN || errno == EINTR) {
1332 if (poll(&pfd, 1, -1) == -1)
1333 err(1, "poll");
1334 continue;
1336 err(1, "sendmsg");
1337 } else if (r != 1)
1338 errx(1, "sendmsg: unexpected return value %zd", r);
1339 else
1340 break;
1342 exit(0);
1345 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1346 void
1347 atelnet(int nfd, unsigned char *buf, unsigned int size)
1349 unsigned char *p, *end;
1350 unsigned char obuf[4];
1352 if (size < 3)
1353 return;
1354 end = buf + size - 2;
1356 for (p = buf; p < end; p++) {
1357 if (*p != IAC)
1358 continue;
1360 obuf[0] = IAC;
1361 p++;
1362 if ((*p == WILL) || (*p == WONT))
1363 obuf[1] = DONT;
1364 else if ((*p == DO) || (*p == DONT))
1365 obuf[1] = WONT;
1366 else
1367 continue;
1369 p++;
1370 obuf[2] = *p;
1371 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1372 warn("Write Error!");
1378 strtoport(char *portstr, int udp)
1380 struct servent *entry;
1381 const char *errstr;
1382 char *proto;
1383 int port = -1;
1385 proto = udp ? "udp" : "tcp";
1387 port = strtonum(portstr, 1, PORT_MAX, &errstr);
1388 if (errstr == NULL)
1389 return port;
1390 if (errno != EINVAL)
1391 errx(1, "port number %s: %s", errstr, portstr);
1392 if ((entry = getservbyname(portstr, proto)) == NULL)
1393 errx(1, "service \"%s\" unknown", portstr);
1394 return ntohs(entry->s_port);
1398 * build_ports()
1399 * Build an array of ports in portlist[], listing each port
1400 * that we should try to connect to.
1402 void
1403 build_ports(char *p)
1405 char *n;
1406 int hi, lo, cp;
1407 int x = 0;
1409 if ((n = strchr(p, '-')) != NULL) {
1410 *n = '\0';
1411 n++;
1413 /* Make sure the ports are in order: lowest->highest. */
1414 hi = strtoport(n, uflag);
1415 lo = strtoport(p, uflag);
1416 if (lo > hi) {
1417 cp = hi;
1418 hi = lo;
1419 lo = cp;
1423 * Initialize portlist with a random permutation. Based on
1424 * Knuth, as in ip_randomid() in sys/netinet/ip_id.c.
1426 if (rflag) {
1427 for (x = 0; x <= hi - lo; x++) {
1428 cp = arc4random_uniform(x + 1);
1429 portlist[x] = portlist[cp];
1430 if (asprintf(&portlist[cp], "%d", x + lo) < 0)
1431 err(1, "asprintf");
1433 } else { /* Load ports sequentially. */
1434 for (cp = lo; cp <= hi; cp++) {
1435 if (asprintf(&portlist[x], "%d", cp) < 0)
1436 err(1, "asprintf");
1437 x++;
1440 } else {
1441 char *tmp;
1443 hi = strtoport(p, uflag);
1444 if (asprintf(&tmp, "%d", hi) != -1)
1445 portlist[0] = tmp;
1446 else
1447 err(1, NULL);
1452 * udptest()
1453 * Do a few writes to see if the UDP port is there.
1454 * Fails once PF state table is full.
1457 udptest(int s)
1459 int i, ret;
1461 for (i = 0; i <= 3; i++) {
1462 if (write(s, "X", 1) == 1)
1463 ret = 1;
1464 else
1465 ret = -1;
1467 return ret;
1470 void
1471 set_common_sockopts(int s, int af)
1473 int x = 1;
1475 #ifdef TCP_MD5SIG
1476 if (Sflag) {
1477 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1478 &x, sizeof(x)) == -1)
1479 err(1, NULL);
1481 #endif
1482 if (Dflag) {
1483 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1484 &x, sizeof(x)) == -1)
1485 err(1, NULL);
1487 if (Tflag != -1) {
1488 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1489 IP_TOS, &Tflag, sizeof(Tflag)) == -1)
1490 err(1, "set IP ToS");
1492 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1493 IPV6_TCLASS, &Tflag, sizeof(Tflag)) == -1)
1494 err(1, "set IPv6 traffic class");
1496 if (Iflag) {
1497 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1498 &Iflag, sizeof(Iflag)) == -1)
1499 err(1, "set TCP receive buffer size");
1501 if (Oflag) {
1502 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1503 &Oflag, sizeof(Oflag)) == -1)
1504 err(1, "set TCP send buffer size");
1507 if (ttl != -1) {
1508 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1509 IP_TTL, &ttl, sizeof(ttl)))
1510 err(1, "set IP TTL");
1512 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1513 IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)))
1514 err(1, "set IPv6 unicast hops");
1517 if (minttl != -1) {
1518 #ifdef IP_MINTTL
1519 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1520 IP_MINTTL, &minttl, sizeof(minttl)))
1521 err(1, "set IP min TTL");
1522 #endif
1524 #ifdef IPV6_MINHOPCOUNT
1525 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1526 IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)))
1527 err(1, "set IPv6 min hop count");
1528 #endif
1533 process_tos_opt(char *s, int *val)
1535 /* DiffServ Codepoints and other TOS mappings */
1536 const struct toskeywords {
1537 const char *keyword;
1538 int val;
1539 } *t, toskeywords[] = {
1540 { "af11", IPTOS_DSCP_AF11 },
1541 { "af12", IPTOS_DSCP_AF12 },
1542 { "af13", IPTOS_DSCP_AF13 },
1543 { "af21", IPTOS_DSCP_AF21 },
1544 { "af22", IPTOS_DSCP_AF22 },
1545 { "af23", IPTOS_DSCP_AF23 },
1546 { "af31", IPTOS_DSCP_AF31 },
1547 { "af32", IPTOS_DSCP_AF32 },
1548 { "af33", IPTOS_DSCP_AF33 },
1549 { "af41", IPTOS_DSCP_AF41 },
1550 { "af42", IPTOS_DSCP_AF42 },
1551 { "af43", IPTOS_DSCP_AF43 },
1552 { "critical", IPTOS_PREC_CRITIC_ECP },
1553 { "cs0", IPTOS_DSCP_CS0 },
1554 { "cs1", IPTOS_DSCP_CS1 },
1555 { "cs2", IPTOS_DSCP_CS2 },
1556 { "cs3", IPTOS_DSCP_CS3 },
1557 { "cs4", IPTOS_DSCP_CS4 },
1558 { "cs5", IPTOS_DSCP_CS5 },
1559 { "cs6", IPTOS_DSCP_CS6 },
1560 { "cs7", IPTOS_DSCP_CS7 },
1561 { "ef", IPTOS_DSCP_EF },
1562 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1563 { "lowdelay", IPTOS_LOWDELAY },
1564 { "netcontrol", IPTOS_PREC_NETCONTROL },
1565 { "reliability", IPTOS_RELIABILITY },
1566 { "throughput", IPTOS_THROUGHPUT },
1567 { NULL, -1 },
1570 for (t = toskeywords; t->keyword != NULL; t++) {
1571 if (strcmp(s, t->keyword) == 0) {
1572 *val = t->val;
1573 return 1;
1577 return 0;
1581 process_tls_opt(char *s, int *flags)
1583 size_t len;
1584 char *v;
1586 const struct tlskeywords {
1587 const char *keyword;
1588 int flag;
1589 char **value;
1590 } *t, tlskeywords[] = {
1591 { "ciphers", -1, &tls_ciphers },
1592 { "clientcert", TLS_CCERT, NULL },
1593 { "muststaple", TLS_MUSTSTAPLE, NULL },
1594 { "noverify", TLS_NOVERIFY, NULL },
1595 { "noname", TLS_NONAME, NULL },
1596 { "protocols", -1, &tls_protocols },
1597 { NULL, -1, NULL },
1600 len = strlen(s);
1601 if ((v = strchr(s, '=')) != NULL) {
1602 len = v - s;
1603 v++;
1606 for (t = tlskeywords; t->keyword != NULL; t++) {
1607 if (strlen(t->keyword) == len &&
1608 strncmp(s, t->keyword, len) == 0) {
1609 if (t->value != NULL) {
1610 if (v == NULL)
1611 errx(1, "invalid tls value `%s'", s);
1612 *t->value = v;
1613 } else {
1614 *flags |= t->flag;
1616 return 1;
1619 return 0;
1622 void
1623 save_peer_cert(struct tls *tls_ctx, FILE *fp)
1625 const char *pem;
1626 size_t plen;
1628 if ((pem = tls_peer_cert_chain_pem(tls_ctx, &plen)) == NULL)
1629 errx(1, "Can't get peer certificate");
1630 if (fprintf(fp, "%.*s", (int)plen, pem) < 0)
1631 err(1, "unable to save peer cert");
1632 if (fflush(fp) != 0)
1633 err(1, "unable to flush peer cert");
1636 void
1637 report_tls(struct tls * tls_ctx, char * host)
1639 time_t t;
1640 const char *ocsp_url;
1642 fprintf(stderr, "TLS handshake negotiated %s/%s with host %s\n",
1643 tls_conn_version(tls_ctx), tls_conn_cipher(tls_ctx), host);
1644 fprintf(stderr, "Peer name: %s\n",
1645 tls_expectname ? tls_expectname : host);
1646 if (tls_peer_cert_subject(tls_ctx))
1647 fprintf(stderr, "Subject: %s\n",
1648 tls_peer_cert_subject(tls_ctx));
1649 if (tls_peer_cert_issuer(tls_ctx))
1650 fprintf(stderr, "Issuer: %s\n",
1651 tls_peer_cert_issuer(tls_ctx));
1652 if ((t = tls_peer_cert_notbefore(tls_ctx)) != -1)
1653 fprintf(stderr, "Valid From: %s", ctime(&t));
1654 if ((t = tls_peer_cert_notafter(tls_ctx)) != -1)
1655 fprintf(stderr, "Valid Until: %s", ctime(&t));
1656 if (tls_peer_cert_hash(tls_ctx))
1657 fprintf(stderr, "Cert Hash: %s\n",
1658 tls_peer_cert_hash(tls_ctx));
1659 ocsp_url = tls_peer_ocsp_url(tls_ctx);
1660 if (ocsp_url != NULL)
1661 fprintf(stderr, "OCSP URL: %s\n", ocsp_url);
1662 switch (tls_peer_ocsp_response_status(tls_ctx)) {
1663 case TLS_OCSP_RESPONSE_SUCCESSFUL:
1664 fprintf(stderr, "OCSP Stapling: %s\n",
1665 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
1666 tls_peer_ocsp_result(tls_ctx));
1667 fprintf(stderr,
1668 " response_status=%d cert_status=%d crl_reason=%d\n",
1669 tls_peer_ocsp_response_status(tls_ctx),
1670 tls_peer_ocsp_cert_status(tls_ctx),
1671 tls_peer_ocsp_crl_reason(tls_ctx));
1672 t = tls_peer_ocsp_this_update(tls_ctx);
1673 fprintf(stderr, " this update: %s",
1674 t != -1 ? ctime(&t) : "\n");
1675 t = tls_peer_ocsp_next_update(tls_ctx);
1676 fprintf(stderr, " next update: %s",
1677 t != -1 ? ctime(&t) : "\n");
1678 t = tls_peer_ocsp_revocation_time(tls_ctx);
1679 fprintf(stderr, " revocation: %s",
1680 t != -1 ? ctime(&t) : "\n");
1681 break;
1682 case -1:
1683 break;
1684 default:
1685 fprintf(stderr, "OCSP Stapling: failure - response_status %d (%s)\n",
1686 tls_peer_ocsp_response_status(tls_ctx),
1687 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
1688 tls_peer_ocsp_result(tls_ctx));
1689 break;
1694 void
1695 report_connect(const struct sockaddr *sa, socklen_t salen, char *path)
1697 char remote_host[NI_MAXHOST];
1698 char remote_port[NI_MAXSERV];
1699 int herr;
1700 int flags = NI_NUMERICSERV;
1702 if (path != NULL) {
1703 fprintf(stderr, "Connection on %s received!\n", path);
1704 return;
1707 if (nflag)
1708 flags |= NI_NUMERICHOST;
1710 if ((herr = getnameinfo(sa, salen,
1711 remote_host, sizeof(remote_host),
1712 remote_port, sizeof(remote_port),
1713 flags)) != 0) {
1714 if (herr == EAI_SYSTEM)
1715 err(1, "getnameinfo");
1716 else
1717 errx(1, "getnameinfo: %s", gai_strerror(herr));
1720 fprintf(stderr,
1721 "Connection from %s %s "
1722 "received!\n", remote_host, remote_port);
1725 void
1726 help(void)
1728 usage(0);
1729 fprintf(stderr, "\tCommand Summary:\n\
1730 \t-4 Use IPv4\n\
1731 \t-6 Use IPv6\n\
1732 \t-C certfile Public key file\n\
1733 \t-c Use TLS\n\
1734 \t-D Enable the debug socket option\n\
1735 \t-d Detach from stdin\n\
1736 \t-e name\t Required name in peer certificate\n\
1737 \t-F Pass socket fd\n\
1738 \t-H hash\t Hash string of peer certificate\n\
1739 \t-h This help text\n\
1740 \t-I length TCP receive buffer length\n\
1741 \t-i interval Delay interval for lines sent, ports scanned\n\
1742 \t-K keyfile Private key file\n\
1743 \t-k Keep inbound sockets open for multiple connects\n\
1744 \t-l Listen mode, for inbound connects\n\
1745 \t-M ttl Outgoing TTL / Hop Limit\n\
1746 \t-m minttl Minimum incoming TTL / Hop Limit\n\
1747 \t-N Shutdown the network socket after EOF on stdin\n\
1748 \t-n Suppress name/port resolutions\n\
1749 \t-O length TCP send buffer length\n\
1750 \t-o staplefile Staple file\n\
1751 \t-P proxyuser\tUsername for proxy authentication\n\
1752 \t-p port\t Specify local port for remote connects\n\
1753 \t-R CAfile CA bundle\n\
1754 \t-r Randomize remote ports\n"
1755 #ifdef TCP_MD5SIG
1757 \t-S Enable the TCP MD5 signature option\n"
1758 #endif
1760 \t-s source Local source address\n\
1761 \t-T keyword TOS value or TLS options\n\
1762 \t-t Answer TELNET negotiation\n\
1763 \t-U Use UNIX domain socket\n\
1764 \t-u UDP mode\n"
1765 #ifdef SO_RTABLE
1767 \t-V rtable Specify alternate routing table\n"
1768 #endif
1770 \t-v Verbose\n\
1771 \t-W recvlimit Terminate after receiving a number of packets\n\
1772 \t-w timeout Timeout for connects and final net reads\n\
1773 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1774 \t-x addr[:port]\tSpecify proxy address and port\n\
1775 \t-Z Peer certificate file\n\
1776 \t-z Zero-I/O mode [used for scanning]\n\
1777 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1778 exit(1);
1781 void
1782 usage(int ret)
1784 fprintf(stderr,
1785 "usage: nc [-46cDdFhklNnrStUuvz] [-C certfile] [-e name] "
1786 "[-H hash] [-I length]\n"
1787 "\t [-i interval] [-K keyfile] [-M ttl] [-m minttl] [-O length]\n"
1788 "\t [-o staplefile] [-P proxy_username] [-p source_port] "
1789 "[-R CAfile]\n"
1790 "\t [-s source] [-T keyword] [-V rtable] [-W recvlimit] "
1791 "[-w timeout]\n"
1792 "\t [-X proxy_protocol] [-x proxy_address[:port]] "
1793 "[-Z peercertfile]\n"
1794 "\t [destination] [port]\n");
1795 if (ret)
1796 exit(1);