dmake: do not set MAKEFLAGS=k
[unleashed/tickless.git] / bin / nc / netcat.c
blob72278e62fe7e0e96d88beb7e7f544988149c2050
1 /* $OpenBSD: netcat.c,v 1.187 2017/07/15 17:27:39 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_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)
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 #ifdef TCP_MD5SIG
99 int Sflag; /* TCP MD5 signature option */
100 #endif
101 int Tflag = -1; /* IP Type of Service */
102 #ifdef SO_RTABLE
103 int rtableid = -1;
104 #endif
106 int usetls; /* use TLS */
107 char *Cflag; /* Public cert file */
108 char *Kflag; /* Private key file */
109 char *oflag; /* OCSP stapling file */
110 char *Rflag = DEFAULT_CA_FILE; /* Root CA file */
111 int tls_cachanged; /* Using non-default CA file */
112 int TLSopt; /* TLS options */
113 char *tls_expectname; /* required name in peer cert */
114 char *tls_expecthash; /* required hash of peer cert */
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 map_tos(char *, int *);
143 int map_tls(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;
169 ret = 1;
170 socksv = 5;
171 host = NULL;
172 uport = NULL;
173 sv = NULL;
175 signal(SIGPIPE, SIG_IGN);
177 while ((ch = getopt(argc, argv,
178 "46C:cDde:FH:hI:i:K:klM:m:NnO:o:P:p:R:rSs:T:tUuV:vW:w:X:x:Z:z"))
179 != -1) {
180 switch (ch) {
181 case '4':
182 family = AF_INET;
183 break;
184 case '6':
185 family = AF_INET6;
186 break;
187 case 'U':
188 family = AF_UNIX;
189 break;
190 case 'X':
191 if (strcasecmp(optarg, "connect") == 0)
192 socksv = -1; /* HTTP proxy CONNECT */
193 else if (strcmp(optarg, "4") == 0)
194 socksv = 4; /* SOCKS v.4 */
195 else if (strcmp(optarg, "5") == 0)
196 socksv = 5; /* SOCKS v.5 */
197 else
198 errx(1, "unsupported proxy protocol");
199 break;
200 case 'C':
201 Cflag = optarg;
202 break;
203 case 'c':
204 usetls = 1;
205 break;
206 case 'd':
207 dflag = 1;
208 break;
209 case 'e':
210 tls_expectname = optarg;
211 break;
212 case 'F':
213 Fflag = 1;
214 break;
215 case 'H':
216 tls_expecthash = optarg;
217 break;
218 case 'h':
219 help();
220 break;
221 case 'i':
222 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
223 if (errstr)
224 errx(1, "interval %s: %s", errstr, optarg);
225 break;
226 case 'K':
227 Kflag = optarg;
228 break;
229 case 'k':
230 kflag = 1;
231 break;
232 case 'l':
233 lflag = 1;
234 break;
235 case 'M':
236 ttl = strtonum(optarg, 0, 255, &errstr);
237 if (errstr)
238 errx(1, "ttl is %s", errstr);
239 break;
240 case 'm':
241 minttl = strtonum(optarg, 0, 255, &errstr);
242 if (errstr)
243 errx(1, "minttl is %s", errstr);
244 break;
245 case 'N':
246 Nflag = 1;
247 break;
248 case 'n':
249 nflag = 1;
250 break;
251 case 'P':
252 Pflag = optarg;
253 break;
254 case 'p':
255 pflag = optarg;
256 break;
257 case 'R':
258 tls_cachanged = 1;
259 Rflag = optarg;
260 break;
261 case 'r':
262 rflag = 1;
263 break;
264 case 's':
265 sflag = optarg;
266 break;
267 case 't':
268 tflag = 1;
269 break;
270 case 'u':
271 uflag = 1;
272 break;
273 #ifdef SO_RTABLE
274 case 'V':
275 rtableid = (int)strtonum(optarg, 0,
276 RT_TABLEID_MAX, &errstr);
277 if (errstr)
278 errx(1, "rtable %s: %s", errstr, optarg);
279 break;
280 #endif
281 case 'v':
282 vflag = 1;
283 break;
284 case 'W':
285 recvlimit = strtonum(optarg, 1, INT_MAX, &errstr);
286 if (errstr)
287 errx(1, "receive limit %s: %s", errstr, optarg);
288 break;
289 case 'w':
290 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
291 if (errstr)
292 errx(1, "timeout %s: %s", errstr, optarg);
293 timeout *= 1000;
294 break;
295 case 'x':
296 xflag = 1;
297 if ((proxy = strdup(optarg)) == NULL)
298 err(1, NULL);
299 break;
300 case 'Z':
301 if (strcmp(optarg, "-") == 0)
302 Zflag = stderr;
303 else if ((Zflag = fopen(optarg, "w")) == NULL)
304 err(1, "can't open %s", optarg);
305 break;
306 case 'z':
307 zflag = 1;
308 break;
309 case 'D':
310 Dflag = 1;
311 break;
312 case 'I':
313 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
314 if (errstr != NULL)
315 errx(1, "TCP receive window %s: %s",
316 errstr, optarg);
317 break;
318 case 'O':
319 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
320 if (errstr != NULL)
321 errx(1, "TCP send window %s: %s",
322 errstr, optarg);
323 break;
324 case 'o':
325 oflag = optarg;
326 break;
327 #ifdef TCP_MD5SIG
328 case 'S':
329 Sflag = 1;
330 break;
331 #endif
332 case 'T':
333 errstr = NULL;
334 errno = 0;
335 if (map_tos(optarg, &Tflag))
336 break;
337 if (map_tls(optarg, &TLSopt))
338 break;
339 if (strlen(optarg) > 1 && optarg[0] == '0' &&
340 optarg[1] == 'x')
341 Tflag = (int)strtol(optarg, NULL, 16);
342 else
343 Tflag = (int)strtonum(optarg, 0, 255,
344 &errstr);
345 if (Tflag < 0 || Tflag > 255 || errstr || errno)
346 errx(1, "illegal tos/tls value %s", optarg);
347 break;
348 default:
349 usage(1);
352 argc -= optind;
353 argv += optind;
355 #ifdef SO_RTABLE
356 if (rtableid >= 0)
357 if (setrtable(rtableid) == -1)
358 err(1, "setrtable");
359 #endif
361 if (family == AF_UNIX) {
362 if (pledge("stdio rpath wpath cpath tmppath unix", NULL) == -1)
363 err(1, "pledge");
364 } else if (Fflag && Pflag) {
365 if (pledge("stdio inet dns sendfd tty", NULL) == -1)
366 err(1, "pledge");
367 } else if (Fflag) {
368 if (pledge("stdio inet dns sendfd", NULL) == -1)
369 err(1, "pledge");
370 } else if (Pflag && usetls) {
371 if (pledge("stdio rpath inet dns tty", NULL) == -1)
372 err(1, "pledge");
373 } else if (Pflag) {
374 if (pledge("stdio inet dns tty", NULL) == -1)
375 err(1, "pledge");
376 } else if (usetls) {
377 if (pledge("stdio rpath inet dns", NULL) == -1)
378 err(1, "pledge");
379 } else if (pledge("stdio inet dns", NULL) == -1)
380 err(1, "pledge");
382 /* Cruft to make sure options are clean, and used properly. */
383 if (argv[0] && !argv[1] && family == AF_UNIX) {
384 host = argv[0];
385 uport = NULL;
386 } else if (argv[0] && !argv[1]) {
387 if (!lflag)
388 usage(1);
389 uport = argv[0];
390 host = NULL;
391 } else if (argv[0] && argv[1]) {
392 host = argv[0];
393 uport = argv[1];
394 } else
395 usage(1);
397 if (lflag && sflag)
398 errx(1, "cannot use -s and -l");
399 if (lflag && pflag)
400 errx(1, "cannot use -p and -l");
401 if (lflag && zflag)
402 errx(1, "cannot use -z and -l");
403 if (!lflag && kflag)
404 errx(1, "must use -l with -k");
405 if (uflag && usetls)
406 errx(1, "cannot use -c and -u");
407 if ((family == AF_UNIX) && usetls)
408 errx(1, "cannot use -c and -U");
409 if ((family == AF_UNIX) && Fflag)
410 errx(1, "cannot use -F and -U");
411 if (Fflag && usetls)
412 errx(1, "cannot use -c and -F");
413 if (TLSopt && !usetls)
414 errx(1, "you must specify -c to use TLS options");
415 if ((TLSopt & (TLS_ALL|TLS_COMPAT)) == (TLS_ALL|TLS_COMPAT))
416 errx(1, "cannot use -T tlsall and -T tlscompat");
417 if (Cflag && !usetls)
418 errx(1, "you must specify -c to use -C");
419 if (Kflag && !usetls)
420 errx(1, "you must specify -c to use -K");
421 if (Zflag && !usetls)
422 errx(1, "you must specify -c to use -Z");
423 if (oflag && !Cflag)
424 errx(1, "you must specify -C to use -o");
425 if (tls_cachanged && !usetls)
426 errx(1, "you must specify -c to use -R");
427 if (tls_expecthash && !usetls)
428 errx(1, "you must specify -c to use -H");
429 if (tls_expectname && !usetls)
430 errx(1, "you must specify -c to use -e");
432 /* Get name of temporary socket for unix datagram client */
433 if ((family == AF_UNIX) && uflag && !lflag) {
434 if (sflag) {
435 unix_dg_tmp_socket = sflag;
436 } else {
437 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
438 UNIX_DG_TMP_SOCKET_SIZE);
439 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
440 err(1, "mktemp");
441 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
445 /* Initialize addrinfo structure. */
446 if (family != AF_UNIX) {
447 memset(&hints, 0, sizeof(struct addrinfo));
448 hints.ai_family = family;
449 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
450 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
451 if (nflag)
452 hints.ai_flags |= AI_NUMERICHOST;
455 if (xflag) {
456 if (uflag)
457 errx(1, "no proxy support for UDP mode");
459 if (lflag)
460 errx(1, "no proxy support for listen");
462 if (family == AF_UNIX)
463 errx(1, "no proxy support for unix sockets");
465 if (sflag)
466 errx(1, "no proxy support for local source address");
468 if (*proxy == '[') {
469 ++proxy;
470 proxyport = strchr(proxy, ']');
471 if (proxyport == NULL)
472 errx(1, "missing closing bracket in proxy");
473 *proxyport++ = '\0';
474 if (*proxyport == '\0')
475 /* Use default proxy port. */
476 proxyport = NULL;
477 else {
478 if (*proxyport == ':')
479 ++proxyport;
480 else
481 errx(1, "garbage proxy port delimiter");
483 } else {
484 proxyport = strrchr(proxy, ':');
485 if (proxyport != NULL)
486 *proxyport++ = '\0';
489 memset(&proxyhints, 0, sizeof(struct addrinfo));
490 proxyhints.ai_family = family;
491 proxyhints.ai_socktype = SOCK_STREAM;
492 proxyhints.ai_protocol = IPPROTO_TCP;
493 if (nflag)
494 proxyhints.ai_flags |= AI_NUMERICHOST;
497 if (usetls) {
498 if (tls_init() == -1)
499 errx(1, "unable to initialize TLS");
500 if ((tls_cfg = tls_config_new()) == NULL)
501 errx(1, "unable to allocate TLS config");
502 if (Rflag && tls_config_set_ca_file(tls_cfg, Rflag) == -1)
503 errx(1, "%s", tls_config_error(tls_cfg));
504 if (Cflag && tls_config_set_cert_file(tls_cfg, Cflag) == -1)
505 errx(1, "%s", tls_config_error(tls_cfg));
506 if (Kflag && tls_config_set_key_file(tls_cfg, Kflag) == -1)
507 errx(1, "%s", tls_config_error(tls_cfg));
508 if (oflag && tls_config_set_ocsp_staple_file(tls_cfg, oflag) == -1)
509 errx(1, "%s", tls_config_error(tls_cfg));
510 if (TLSopt & (TLS_ALL|TLS_COMPAT)) {
511 if (tls_config_set_protocols(tls_cfg,
512 TLS_PROTOCOLS_ALL) != 0)
513 errx(1, "%s", tls_config_error(tls_cfg));
514 if (tls_config_set_ciphers(tls_cfg,
515 (TLSopt & TLS_ALL) ? "all" : "compat") != 0)
516 errx(1, "%s", tls_config_error(tls_cfg));
518 if (!lflag && (TLSopt & TLS_CCERT))
519 errx(1, "clientcert is only valid with -l");
520 if (TLSopt & TLS_NONAME)
521 tls_config_insecure_noverifyname(tls_cfg);
522 if (TLSopt & TLS_NOVERIFY) {
523 if (tls_expecthash != NULL)
524 errx(1, "-H and -T noverify may not be used "
525 "together");
526 tls_config_insecure_noverifycert(tls_cfg);
528 if (TLSopt & TLS_MUSTSTAPLE)
529 tls_config_ocsp_require_stapling(tls_cfg);
531 if (Pflag) {
532 if (pledge("stdio inet dns tty", NULL) == -1)
533 err(1, "pledge");
534 } else if (pledge("stdio inet dns", NULL) == -1)
535 err(1, "pledge");
537 if (lflag) {
538 struct tls *tls_cctx = NULL;
539 int connfd;
540 ret = 0;
542 if (family == AF_UNIX) {
543 if (uflag)
544 s = unix_bind(host, 0);
545 else
546 s = unix_listen(host);
549 if (usetls) {
550 tls_config_verify_client_optional(tls_cfg);
551 if ((tls_ctx = tls_server()) == NULL)
552 errx(1, "tls server creation failed");
553 if (tls_configure(tls_ctx, tls_cfg) == -1)
554 errx(1, "tls configuration failed (%s)",
555 tls_error(tls_ctx));
557 /* Allow only one connection at a time, but stay alive. */
558 for (;;) {
559 if (family != AF_UNIX)
560 s = local_listen(host, uport, hints);
561 if (s < 0)
562 err(1, NULL);
563 if (uflag && kflag) {
565 * For UDP and -k, don't connect the socket,
566 * let it receive datagrams from multiple
567 * socket pairs.
569 readwrite(s, NULL);
570 } else if (uflag && !kflag) {
572 * For UDP and not -k, we will use recvfrom()
573 * initially to wait for a caller, then use
574 * the regular functions to talk to the caller.
576 int rv, plen;
577 char buf[16384];
578 struct sockaddr_storage z;
580 len = sizeof(z);
581 plen = 2048;
582 rv = recvfrom(s, buf, plen, MSG_PEEK,
583 (struct sockaddr *)&z, &len);
584 if (rv < 0)
585 err(1, "recvfrom");
587 rv = connect(s, (struct sockaddr *)&z, len);
588 if (rv < 0)
589 err(1, "connect");
591 if (vflag)
592 report_connect((struct sockaddr *)&z, len, NULL);
594 readwrite(s, NULL);
595 } else {
596 len = sizeof(cliaddr);
597 connfd = accept4(s, (struct sockaddr *)&cliaddr,
598 &len, SOCK_NONBLOCK);
599 if (connfd == -1) {
600 /* For now, all errnos are fatal */
601 err(1, "accept");
603 if (vflag)
604 report_connect((struct sockaddr *)&cliaddr, len,
605 family == AF_UNIX ? host : NULL);
606 if ((usetls) &&
607 (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
608 readwrite(connfd, tls_cctx);
609 if (!usetls)
610 readwrite(connfd, NULL);
611 if (tls_cctx) {
612 timeout_tls(s, tls_cctx, tls_close);
613 tls_free(tls_cctx);
614 tls_cctx = NULL;
616 close(connfd);
618 if (family != AF_UNIX)
619 close(s);
620 else if (uflag) {
621 if (connect(s, NULL, 0) < 0)
622 err(1, "connect");
625 if (!kflag)
626 break;
628 } else if (family == AF_UNIX) {
629 ret = 0;
631 if ((s = unix_connect(host)) > 0) {
632 if (!zflag)
633 readwrite(s, NULL);
634 close(s);
635 } else
636 ret = 1;
638 if (uflag)
639 unlink(unix_dg_tmp_socket);
640 return ret;
642 } else {
643 int i = 0;
645 /* Construct the portlist[] array. */
646 build_ports(uport);
648 /* Cycle through portlist, connecting to each port. */
649 for (s = -1, i = 0; portlist[i] != NULL; i++) {
650 if (s != -1)
651 close(s);
653 if (usetls) {
654 if ((tls_ctx = tls_client()) == NULL)
655 errx(1, "tls client creation failed");
656 if (tls_configure(tls_ctx, tls_cfg) == -1)
657 errx(1, "tls configuration failed (%s)",
658 tls_error(tls_ctx));
660 if (xflag)
661 s = socks_connect(host, portlist[i], hints,
662 proxy, proxyport, proxyhints, socksv,
663 Pflag);
664 else
665 s = remote_connect(host, portlist[i], hints);
667 if (s == -1)
668 continue;
670 ret = 0;
671 if (vflag || zflag) {
672 /* For UDP, make sure we are connected. */
673 if (uflag) {
674 if (udptest(s) == -1) {
675 ret = 1;
676 continue;
680 /* Don't look up port if -n. */
681 if (nflag)
682 sv = NULL;
683 else {
684 sv = getservbyport(
685 ntohs(atoi(portlist[i])),
686 uflag ? "udp" : "tcp");
689 fprintf(stderr,
690 "Connection to %s %s port [%s/%s] "
691 "succeeded!\n", host, portlist[i],
692 uflag ? "udp" : "tcp",
693 sv ? sv->s_name : "*");
695 if (Fflag)
696 fdpass(s);
697 else {
698 if (usetls)
699 tls_setup_client(tls_ctx, s, host);
700 if (!zflag)
701 readwrite(s, tls_ctx);
702 if (tls_ctx) {
703 timeout_tls(s, tls_ctx, tls_close);
704 tls_free(tls_ctx);
705 tls_ctx = NULL;
711 if (s != -1)
712 close(s);
714 tls_config_free(tls_cfg);
716 return ret;
720 * unix_bind()
721 * Returns a unix socket bound to the given path
724 unix_bind(char *path, int flags)
726 struct sockaddr_un s_un;
727 int s, save_errno;
729 /* Create unix domain socket. */
730 if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
731 0)) < 0)
732 return -1;
734 memset(&s_un, 0, sizeof(struct sockaddr_un));
735 s_un.sun_family = AF_UNIX;
737 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
738 sizeof(s_un.sun_path)) {
739 close(s);
740 errno = ENAMETOOLONG;
741 return -1;
744 if (bind(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
745 save_errno = errno;
746 close(s);
747 errno = save_errno;
748 return -1;
751 return s;
755 timeout_tls(int s, struct tls *tls_ctx, int (*func)(struct tls *))
757 struct pollfd pfd;
758 int ret;
760 while ((ret = (*func)(tls_ctx)) != 0) {
761 if (ret == TLS_WANT_POLLIN)
762 pfd.events = POLLIN;
763 else if (ret == TLS_WANT_POLLOUT)
764 pfd.events = POLLOUT;
765 else
766 break;
767 pfd.fd = s;
768 if ((ret = poll(&pfd, 1, timeout)) == 1)
769 continue;
770 else if (ret == 0) {
771 errno = ETIMEDOUT;
772 ret = -1;
773 break;
774 } else
775 err(1, "poll failed");
778 return ret;
781 void
782 tls_setup_client(struct tls *tls_ctx, int s, char *host)
784 const char *errstr;
786 if (tls_connect_socket(tls_ctx, s,
787 tls_expectname ? tls_expectname : host) == -1) {
788 errx(1, "tls connection failed (%s)",
789 tls_error(tls_ctx));
791 if (timeout_tls(s, tls_ctx, tls_handshake) == -1) {
792 if ((errstr = tls_error(tls_ctx)) == NULL)
793 errstr = strerror(errno);
794 errx(1, "tls handshake failed (%s)", errstr);
796 if (vflag)
797 report_tls(tls_ctx, host);
798 if (tls_expecthash && tls_peer_cert_hash(tls_ctx) &&
799 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
800 errx(1, "peer certificate is not %s", tls_expecthash);
801 if (Zflag) {
802 save_peer_cert(tls_ctx, Zflag);
803 if (Zflag != stderr && (fclose(Zflag) != 0))
804 err(1, "fclose failed saving peer cert");
808 struct tls *
809 tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
811 struct tls *tls_cctx;
812 const char *errstr;
814 if (tls_accept_socket(tls_ctx, &tls_cctx, connfd) == -1) {
815 warnx("tls accept failed (%s)", tls_error(tls_ctx));
816 } else if (timeout_tls(connfd, tls_cctx, tls_handshake) == -1) {
817 if ((errstr = tls_error(tls_cctx)) == NULL)
818 errstr = strerror(errno);
819 warnx("tls handshake failed (%s)", errstr);
820 } else {
821 int gotcert = tls_peer_cert_provided(tls_cctx);
823 if (vflag && gotcert)
824 report_tls(tls_cctx, host);
825 if ((TLSopt & TLS_CCERT) && !gotcert)
826 warnx("No client certificate provided");
827 else if (gotcert && tls_peer_cert_hash(tls_ctx) && tls_expecthash &&
828 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
829 warnx("peer certificate is not %s", tls_expecthash);
830 else if (gotcert && tls_expectname &&
831 (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
832 warnx("name (%s) not found in client cert",
833 tls_expectname);
834 else {
835 return tls_cctx;
838 return NULL;
842 * unix_connect()
843 * Returns a socket connected to a local unix socket. Returns -1 on failure.
846 unix_connect(char *path)
848 struct sockaddr_un s_un;
849 int s, save_errno;
851 if (uflag) {
852 if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) < 0)
853 return -1;
854 } else {
855 if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
856 return -1;
859 memset(&s_un, 0, sizeof(struct sockaddr_un));
860 s_un.sun_family = AF_UNIX;
862 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
863 sizeof(s_un.sun_path)) {
864 close(s);
865 errno = ENAMETOOLONG;
866 return -1;
868 if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
869 save_errno = errno;
870 close(s);
871 errno = save_errno;
872 return -1;
874 return s;
879 * unix_listen()
880 * Create a unix domain socket, and listen on it.
883 unix_listen(char *path)
885 int s;
886 if ((s = unix_bind(path, 0)) < 0)
887 return -1;
889 if (listen(s, 5) < 0) {
890 close(s);
891 return -1;
893 return s;
897 * remote_connect()
898 * Returns a socket connected to a remote host. Properly binds to a local
899 * port or source address if needed. Returns -1 on failure.
902 remote_connect(const char *host, const char *port, struct addrinfo hints)
904 struct addrinfo *res, *res0;
905 int s = -1, error, save_errno;
906 #ifdef SO_BINDANY
907 int on = 1;
908 #endif
910 if ((error = getaddrinfo(host, port, &hints, &res0)))
911 errx(1, "getaddrinfo for host \"%s\" port %s: %s", host,
912 port, gai_strerror(error));
914 for (res = res0; res; res = res->ai_next) {
915 if ((s = socket(res->ai_family, res->ai_socktype |
916 SOCK_NONBLOCK, res->ai_protocol)) < 0)
917 continue;
919 /* Bind to a local port or source address if specified. */
920 if (sflag || pflag) {
921 struct addrinfo ahints, *ares;
923 #ifdef SO_BINDANY
924 /* try SO_BINDANY, but don't insist */
925 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
926 #endif
927 memset(&ahints, 0, sizeof(struct addrinfo));
928 ahints.ai_family = res->ai_family;
929 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
930 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
931 ahints.ai_flags = AI_PASSIVE;
932 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
933 errx(1, "getaddrinfo: %s", gai_strerror(error));
935 if (bind(s, (struct sockaddr *)ares->ai_addr,
936 ares->ai_addrlen) < 0)
937 err(1, "bind failed");
938 freeaddrinfo(ares);
941 set_common_sockopts(s, res->ai_family);
943 if (timeout_connect(s, res->ai_addr, res->ai_addrlen) == 0)
944 break;
945 if (vflag)
946 warn("connect to %s port %s (%s) failed", host, port,
947 uflag ? "udp" : "tcp");
949 save_errno = errno;
950 close(s);
951 errno = save_errno;
952 s = -1;
955 freeaddrinfo(res0);
957 return s;
961 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
963 struct pollfd pfd;
964 socklen_t optlen;
965 int optval;
966 int ret;
968 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
969 pfd.fd = s;
970 pfd.events = POLLOUT;
971 if ((ret = poll(&pfd, 1, timeout)) == 1) {
972 optlen = sizeof(optval);
973 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
974 &optval, &optlen)) == 0) {
975 errno = optval;
976 ret = optval == 0 ? 0 : -1;
978 } else if (ret == 0) {
979 errno = ETIMEDOUT;
980 ret = -1;
981 } else
982 err(1, "poll failed");
985 return ret;
989 * local_listen()
990 * Returns a socket listening on a local port, binds to specified source
991 * address. Returns -1 on failure.
994 local_listen(char *host, char *port, struct addrinfo hints)
996 struct addrinfo *res, *res0;
997 int s = -1, save_errno;
998 #ifdef SO_REUSEPORT
999 int ret, x = 1;
1000 #endif
1001 int error;
1003 /* Allow nodename to be null. */
1004 hints.ai_flags |= AI_PASSIVE;
1007 * In the case of binding to a wildcard address
1008 * default to binding to an ipv4 address.
1010 if (host == NULL && hints.ai_family == AF_UNSPEC)
1011 hints.ai_family = AF_INET;
1013 if ((error = getaddrinfo(host, port, &hints, &res0)))
1014 errx(1, "getaddrinfo: %s", gai_strerror(error));
1016 for (res = res0; res; res = res->ai_next) {
1017 if ((s = socket(res->ai_family, res->ai_socktype,
1018 res->ai_protocol)) < 0)
1019 continue;
1021 #ifdef SO_REUSEPORT
1022 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
1023 if (ret == -1)
1024 err(1, NULL);
1025 #endif
1027 set_common_sockopts(s, res->ai_family);
1029 if (bind(s, (struct sockaddr *)res->ai_addr,
1030 res->ai_addrlen) == 0)
1031 break;
1033 save_errno = errno;
1034 close(s);
1035 errno = save_errno;
1036 s = -1;
1039 if (!uflag && s != -1) {
1040 if (listen(s, 1) < 0)
1041 err(1, "listen");
1044 freeaddrinfo(res0);
1046 return s;
1050 * readwrite()
1051 * Loop that polls on the network file descriptor and stdin.
1053 void
1054 readwrite(int net_fd, struct tls *tls_ctx)
1056 struct pollfd pfd[4];
1057 int stdin_fd = STDIN_FILENO;
1058 int stdout_fd = STDOUT_FILENO;
1059 unsigned char netinbuf[BUFSIZE];
1060 size_t netinbufpos = 0;
1061 unsigned char stdinbuf[BUFSIZE];
1062 size_t stdinbufpos = 0;
1063 int n, num_fds;
1064 ssize_t ret;
1066 /* don't read from stdin if requested */
1067 if (dflag)
1068 stdin_fd = -1;
1070 /* stdin */
1071 pfd[POLL_STDIN].fd = stdin_fd;
1072 pfd[POLL_STDIN].events = POLLIN;
1074 /* network out */
1075 pfd[POLL_NETOUT].fd = net_fd;
1076 pfd[POLL_NETOUT].events = 0;
1078 /* network in */
1079 pfd[POLL_NETIN].fd = net_fd;
1080 pfd[POLL_NETIN].events = POLLIN;
1082 /* stdout */
1083 pfd[POLL_STDOUT].fd = stdout_fd;
1084 pfd[POLL_STDOUT].events = 0;
1086 while (1) {
1087 /* both inputs are gone, buffers are empty, we are done */
1088 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
1089 stdinbufpos == 0 && netinbufpos == 0)
1090 return;
1091 /* both outputs are gone, we can't continue */
1092 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1)
1093 return;
1094 /* listen and net in gone, queues empty, done */
1095 if (lflag && pfd[POLL_NETIN].fd == -1 &&
1096 stdinbufpos == 0 && netinbufpos == 0)
1097 return;
1099 /* help says -i is for "wait between lines sent". We read and
1100 * write arbitrary amounts of data, and we don't want to start
1101 * scanning for newlines, so this is as good as it gets */
1102 if (iflag)
1103 sleep(iflag);
1105 /* poll */
1106 num_fds = poll(pfd, 4, timeout);
1108 /* treat poll errors */
1109 if (num_fds == -1)
1110 err(1, "polling error");
1112 /* timeout happened */
1113 if (num_fds == 0)
1114 return;
1116 /* treat socket error conditions */
1117 for (n = 0; n < 4; n++) {
1118 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
1119 pfd[n].fd = -1;
1122 /* reading is possible after HUP */
1123 if (pfd[POLL_STDIN].events & POLLIN &&
1124 pfd[POLL_STDIN].revents & POLLHUP &&
1125 !(pfd[POLL_STDIN].revents & POLLIN))
1126 pfd[POLL_STDIN].fd = -1;
1128 if (pfd[POLL_NETIN].events & POLLIN &&
1129 pfd[POLL_NETIN].revents & POLLHUP &&
1130 !(pfd[POLL_NETIN].revents & POLLIN))
1131 pfd[POLL_NETIN].fd = -1;
1133 if (pfd[POLL_NETOUT].revents & POLLHUP) {
1134 if (Nflag)
1135 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1136 pfd[POLL_NETOUT].fd = -1;
1138 /* if HUP, stop watching stdout */
1139 if (pfd[POLL_STDOUT].revents & POLLHUP)
1140 pfd[POLL_STDOUT].fd = -1;
1141 /* if no net out, stop watching stdin */
1142 if (pfd[POLL_NETOUT].fd == -1)
1143 pfd[POLL_STDIN].fd = -1;
1144 /* if no stdout, stop watching net in */
1145 if (pfd[POLL_STDOUT].fd == -1) {
1146 if (pfd[POLL_NETIN].fd != -1)
1147 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1148 pfd[POLL_NETIN].fd = -1;
1151 /* try to read from stdin */
1152 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
1153 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
1154 &stdinbufpos, NULL);
1155 if (ret == TLS_WANT_POLLIN)
1156 pfd[POLL_STDIN].events = POLLIN;
1157 else if (ret == TLS_WANT_POLLOUT)
1158 pfd[POLL_STDIN].events = POLLOUT;
1159 else if (ret == 0 || ret == -1)
1160 pfd[POLL_STDIN].fd = -1;
1161 /* read something - poll net out */
1162 if (stdinbufpos > 0)
1163 pfd[POLL_NETOUT].events = POLLOUT;
1164 /* filled buffer - remove self from polling */
1165 if (stdinbufpos == BUFSIZE)
1166 pfd[POLL_STDIN].events = 0;
1168 /* try to write to network */
1169 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
1170 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
1171 &stdinbufpos, tls_ctx);
1172 if (ret == TLS_WANT_POLLIN)
1173 pfd[POLL_NETOUT].events = POLLIN;
1174 else if (ret == TLS_WANT_POLLOUT)
1175 pfd[POLL_NETOUT].events = POLLOUT;
1176 else if (ret == -1)
1177 pfd[POLL_NETOUT].fd = -1;
1178 /* buffer empty - remove self from polling */
1179 if (stdinbufpos == 0)
1180 pfd[POLL_NETOUT].events = 0;
1181 /* buffer no longer full - poll stdin again */
1182 if (stdinbufpos < BUFSIZE)
1183 pfd[POLL_STDIN].events = POLLIN;
1185 /* try to read from network */
1186 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
1187 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
1188 &netinbufpos, tls_ctx);
1189 if (ret == TLS_WANT_POLLIN)
1190 pfd[POLL_NETIN].events = POLLIN;
1191 else if (ret == TLS_WANT_POLLOUT)
1192 pfd[POLL_NETIN].events = POLLOUT;
1193 else if (ret == -1)
1194 pfd[POLL_NETIN].fd = -1;
1195 /* eof on net in - remove from pfd */
1196 if (ret == 0) {
1197 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1198 pfd[POLL_NETIN].fd = -1;
1200 if (recvlimit > 0 && ++recvcount >= recvlimit) {
1201 if (pfd[POLL_NETIN].fd != -1)
1202 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1203 pfd[POLL_NETIN].fd = -1;
1204 pfd[POLL_STDIN].fd = -1;
1206 /* read something - poll stdout */
1207 if (netinbufpos > 0)
1208 pfd[POLL_STDOUT].events = POLLOUT;
1209 /* filled buffer - remove self from polling */
1210 if (netinbufpos == BUFSIZE)
1211 pfd[POLL_NETIN].events = 0;
1212 /* handle telnet */
1213 if (tflag)
1214 atelnet(pfd[POLL_NETIN].fd, netinbuf,
1215 netinbufpos);
1217 /* try to write to stdout */
1218 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1219 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1220 &netinbufpos, NULL);
1221 if (ret == TLS_WANT_POLLIN)
1222 pfd[POLL_STDOUT].events = POLLIN;
1223 else if (ret == TLS_WANT_POLLOUT)
1224 pfd[POLL_STDOUT].events = POLLOUT;
1225 else if (ret == -1)
1226 pfd[POLL_STDOUT].fd = -1;
1227 /* buffer empty - remove self from polling */
1228 if (netinbufpos == 0)
1229 pfd[POLL_STDOUT].events = 0;
1230 /* buffer no longer full - poll net in again */
1231 if (netinbufpos < BUFSIZE)
1232 pfd[POLL_NETIN].events = POLLIN;
1235 /* stdin gone and queue empty? */
1236 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1237 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
1238 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1239 pfd[POLL_NETOUT].fd = -1;
1241 /* net in gone and queue empty? */
1242 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1243 pfd[POLL_STDOUT].fd = -1;
1248 ssize_t
1249 drainbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1251 ssize_t n;
1252 ssize_t adjust;
1254 if (tls)
1255 n = tls_write(tls, buf, *bufpos);
1256 else {
1257 n = write(fd, buf, *bufpos);
1258 /* don't treat EAGAIN, EINTR as error */
1259 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1260 n = TLS_WANT_POLLOUT;
1262 if (n <= 0)
1263 return n;
1264 /* adjust buffer */
1265 adjust = *bufpos - n;
1266 if (adjust > 0)
1267 memmove(buf, buf + n, adjust);
1268 *bufpos -= n;
1269 return n;
1272 ssize_t
1273 fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1275 size_t num = BUFSIZE - *bufpos;
1276 ssize_t n;
1278 if (tls)
1279 n = tls_read(tls, buf + *bufpos, num);
1280 else {
1281 n = read(fd, buf + *bufpos, num);
1282 /* don't treat EAGAIN, EINTR as error */
1283 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1284 n = TLS_WANT_POLLIN;
1286 if (n <= 0)
1287 return n;
1288 *bufpos += n;
1289 return n;
1293 * fdpass()
1294 * Pass the connected file descriptor to stdout and exit.
1296 void
1297 fdpass(int nfd)
1299 struct msghdr mh;
1300 union {
1301 struct cmsghdr hdr;
1302 char buf[CMSG_SPACE(sizeof(int))];
1303 } cmsgbuf;
1304 struct cmsghdr *cmsg;
1305 struct iovec iov;
1306 char c = '\0';
1307 ssize_t r;
1308 struct pollfd pfd;
1310 /* Avoid obvious stupidity */
1311 if (isatty(STDOUT_FILENO))
1312 errx(1, "Cannot pass file descriptor to tty");
1314 bzero(&mh, sizeof(mh));
1315 bzero(&cmsgbuf, sizeof(cmsgbuf));
1316 bzero(&iov, sizeof(iov));
1318 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1319 mh.msg_controllen = sizeof(cmsgbuf.buf);
1320 cmsg = CMSG_FIRSTHDR(&mh);
1321 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1322 cmsg->cmsg_level = SOL_SOCKET;
1323 cmsg->cmsg_type = SCM_RIGHTS;
1324 *(int *)CMSG_DATA(cmsg) = nfd;
1326 iov.iov_base = &c;
1327 iov.iov_len = 1;
1328 mh.msg_iov = &iov;
1329 mh.msg_iovlen = 1;
1331 bzero(&pfd, sizeof(pfd));
1332 pfd.fd = STDOUT_FILENO;
1333 pfd.events = POLLOUT;
1334 for (;;) {
1335 r = sendmsg(STDOUT_FILENO, &mh, 0);
1336 if (r == -1) {
1337 if (errno == EAGAIN || errno == EINTR) {
1338 if (poll(&pfd, 1, -1) == -1)
1339 err(1, "poll");
1340 continue;
1342 err(1, "sendmsg");
1343 } else if (r != 1)
1344 errx(1, "sendmsg: unexpected return value %zd", r);
1345 else
1346 break;
1348 exit(0);
1351 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1352 void
1353 atelnet(int nfd, unsigned char *buf, unsigned int size)
1355 unsigned char *p, *end;
1356 unsigned char obuf[4];
1358 if (size < 3)
1359 return;
1360 end = buf + size - 2;
1362 for (p = buf; p < end; p++) {
1363 if (*p != IAC)
1364 continue;
1366 obuf[0] = IAC;
1367 p++;
1368 if ((*p == WILL) || (*p == WONT))
1369 obuf[1] = DONT;
1370 else if ((*p == DO) || (*p == DONT))
1371 obuf[1] = WONT;
1372 else
1373 continue;
1375 p++;
1376 obuf[2] = *p;
1377 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1378 warn("Write Error!");
1384 strtoport(char *portstr, int udp)
1386 struct servent *entry;
1387 const char *errstr;
1388 char *proto;
1389 int port = -1;
1391 proto = udp ? "udp" : "tcp";
1393 port = strtonum(portstr, 1, PORT_MAX, &errstr);
1394 if (errstr == NULL)
1395 return port;
1396 if (errno != EINVAL)
1397 errx(1, "port number %s: %s", errstr, portstr);
1398 if ((entry = getservbyname(portstr, proto)) == NULL)
1399 errx(1, "service \"%s\" unknown", portstr);
1400 return ntohs(entry->s_port);
1404 * build_ports()
1405 * Build an array of ports in portlist[], listing each port
1406 * that we should try to connect to.
1408 void
1409 build_ports(char *p)
1411 char *n;
1412 int hi, lo, cp;
1413 int x = 0;
1415 if ((n = strchr(p, '-')) != NULL) {
1416 *n = '\0';
1417 n++;
1419 /* Make sure the ports are in order: lowest->highest. */
1420 hi = strtoport(n, uflag);
1421 lo = strtoport(p, uflag);
1422 if (lo > hi) {
1423 cp = hi;
1424 hi = lo;
1425 lo = cp;
1429 * Initialize portlist with a random permutation. Based on
1430 * Knuth, as in ip_randomid() in sys/netinet/ip_id.c.
1432 if (rflag) {
1433 for (x = 0; x <= hi - lo; x++) {
1434 cp = arc4random_uniform(x + 1);
1435 portlist[x] = portlist[cp];
1436 if (asprintf(&portlist[cp], "%d", x + lo) < 0)
1437 err(1, "asprintf");
1439 } else { /* Load ports sequentially. */
1440 for (cp = lo; cp <= hi; cp++) {
1441 if (asprintf(&portlist[x], "%d", cp) < 0)
1442 err(1, "asprintf");
1443 x++;
1446 } else {
1447 char *tmp;
1449 hi = strtoport(p, uflag);
1450 if (asprintf(&tmp, "%d", hi) != -1)
1451 portlist[0] = tmp;
1452 else
1453 err(1, NULL);
1458 * udptest()
1459 * Do a few writes to see if the UDP port is there.
1460 * Fails once PF state table is full.
1463 udptest(int s)
1465 int i, ret;
1467 for (i = 0; i <= 3; i++) {
1468 if (write(s, "X", 1) == 1)
1469 ret = 1;
1470 else
1471 ret = -1;
1473 return ret;
1476 void
1477 set_common_sockopts(int s, int af)
1479 int x = 1;
1481 #ifdef TCP_MD5SIG
1482 if (Sflag) {
1483 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1484 &x, sizeof(x)) == -1)
1485 err(1, NULL);
1487 #endif
1488 if (Dflag) {
1489 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1490 &x, sizeof(x)) == -1)
1491 err(1, NULL);
1493 if (Tflag != -1) {
1494 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1495 IP_TOS, &Tflag, sizeof(Tflag)) == -1)
1496 err(1, "set IP ToS");
1498 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1499 IPV6_TCLASS, &Tflag, sizeof(Tflag)) == -1)
1500 err(1, "set IPv6 traffic class");
1502 if (Iflag) {
1503 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1504 &Iflag, sizeof(Iflag)) == -1)
1505 err(1, "set TCP receive buffer size");
1507 if (Oflag) {
1508 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1509 &Oflag, sizeof(Oflag)) == -1)
1510 err(1, "set TCP send buffer size");
1513 if (ttl != -1) {
1514 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1515 IP_TTL, &ttl, sizeof(ttl)))
1516 err(1, "set IP TTL");
1518 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1519 IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)))
1520 err(1, "set IPv6 unicast hops");
1523 if (minttl != -1) {
1524 #ifdef IP_MINTTL
1525 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1526 IP_MINTTL, &minttl, sizeof(minttl)))
1527 err(1, "set IP min TTL");
1528 #endif
1530 #ifdef IPV6_MINHOPCOUNT
1531 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1532 IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)))
1533 err(1, "set IPv6 min hop count");
1534 #endif
1539 map_tos(char *s, int *val)
1541 /* DiffServ Codepoints and other TOS mappings */
1542 const struct toskeywords {
1543 const char *keyword;
1544 int val;
1545 } *t, toskeywords[] = {
1546 { "af11", IPTOS_DSCP_AF11 },
1547 { "af12", IPTOS_DSCP_AF12 },
1548 { "af13", IPTOS_DSCP_AF13 },
1549 { "af21", IPTOS_DSCP_AF21 },
1550 { "af22", IPTOS_DSCP_AF22 },
1551 { "af23", IPTOS_DSCP_AF23 },
1552 { "af31", IPTOS_DSCP_AF31 },
1553 { "af32", IPTOS_DSCP_AF32 },
1554 { "af33", IPTOS_DSCP_AF33 },
1555 { "af41", IPTOS_DSCP_AF41 },
1556 { "af42", IPTOS_DSCP_AF42 },
1557 { "af43", IPTOS_DSCP_AF43 },
1558 { "critical", IPTOS_PREC_CRITIC_ECP },
1559 { "cs0", IPTOS_DSCP_CS0 },
1560 { "cs1", IPTOS_DSCP_CS1 },
1561 { "cs2", IPTOS_DSCP_CS2 },
1562 { "cs3", IPTOS_DSCP_CS3 },
1563 { "cs4", IPTOS_DSCP_CS4 },
1564 { "cs5", IPTOS_DSCP_CS5 },
1565 { "cs6", IPTOS_DSCP_CS6 },
1566 { "cs7", IPTOS_DSCP_CS7 },
1567 { "ef", IPTOS_DSCP_EF },
1568 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1569 { "lowdelay", IPTOS_LOWDELAY },
1570 { "netcontrol", IPTOS_PREC_NETCONTROL },
1571 { "reliability", IPTOS_RELIABILITY },
1572 { "throughput", IPTOS_THROUGHPUT },
1573 { NULL, -1 },
1576 for (t = toskeywords; t->keyword != NULL; t++) {
1577 if (strcmp(s, t->keyword) == 0) {
1578 *val = t->val;
1579 return 1;
1583 return 0;
1587 map_tls(char *s, int *val)
1589 const struct tlskeywords {
1590 const char *keyword;
1591 int val;
1592 } *t, tlskeywords[] = {
1593 { "tlsall", TLS_ALL },
1594 { "noverify", TLS_NOVERIFY },
1595 { "noname", TLS_NONAME },
1596 { "clientcert", TLS_CCERT},
1597 { "muststaple", TLS_MUSTSTAPLE},
1598 { "tlscompat", TLS_COMPAT },
1599 { NULL, -1 },
1602 for (t = tlskeywords; t->keyword != NULL; t++) {
1603 if (strcmp(s, t->keyword) == 0) {
1604 *val |= t->val;
1605 return 1;
1608 return 0;
1611 void
1612 save_peer_cert(struct tls *tls_ctx, FILE *fp)
1614 const char *pem;
1615 size_t plen;
1617 if ((pem = tls_peer_cert_chain_pem(tls_ctx, &plen)) == NULL)
1618 errx(1, "Can't get peer certificate");
1619 if (fprintf(fp, "%.*s", (int)plen, pem) < 0)
1620 err(1, "unable to save peer cert");
1621 if (fflush(fp) != 0)
1622 err(1, "unable to flush peer cert");
1625 void
1626 report_tls(struct tls * tls_ctx, char * host)
1628 time_t t;
1629 const char *ocsp_url;
1631 fprintf(stderr, "TLS handshake negotiated %s/%s with host %s\n",
1632 tls_conn_version(tls_ctx), tls_conn_cipher(tls_ctx), host);
1633 fprintf(stderr, "Peer name: %s\n",
1634 tls_expectname ? tls_expectname : host);
1635 if (tls_peer_cert_subject(tls_ctx))
1636 fprintf(stderr, "Subject: %s\n",
1637 tls_peer_cert_subject(tls_ctx));
1638 if (tls_peer_cert_issuer(tls_ctx))
1639 fprintf(stderr, "Issuer: %s\n",
1640 tls_peer_cert_issuer(tls_ctx));
1641 if ((t = tls_peer_cert_notbefore(tls_ctx)) != -1)
1642 fprintf(stderr, "Valid From: %s", ctime(&t));
1643 if ((t = tls_peer_cert_notafter(tls_ctx)) != -1)
1644 fprintf(stderr, "Valid Until: %s", ctime(&t));
1645 if (tls_peer_cert_hash(tls_ctx))
1646 fprintf(stderr, "Cert Hash: %s\n",
1647 tls_peer_cert_hash(tls_ctx));
1648 ocsp_url = tls_peer_ocsp_url(tls_ctx);
1649 if (ocsp_url != NULL)
1650 fprintf(stderr, "OCSP URL: %s\n", ocsp_url);
1651 switch (tls_peer_ocsp_response_status(tls_ctx)) {
1652 case TLS_OCSP_RESPONSE_SUCCESSFUL:
1653 fprintf(stderr, "OCSP Stapling: %s\n",
1654 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
1655 tls_peer_ocsp_result(tls_ctx));
1656 fprintf(stderr,
1657 " response_status=%d cert_status=%d crl_reason=%d\n",
1658 tls_peer_ocsp_response_status(tls_ctx),
1659 tls_peer_ocsp_cert_status(tls_ctx),
1660 tls_peer_ocsp_crl_reason(tls_ctx));
1661 t = tls_peer_ocsp_this_update(tls_ctx);
1662 fprintf(stderr, " this update: %s",
1663 t != -1 ? ctime(&t) : "\n");
1664 t = tls_peer_ocsp_next_update(tls_ctx);
1665 fprintf(stderr, " next update: %s",
1666 t != -1 ? ctime(&t) : "\n");
1667 t = tls_peer_ocsp_revocation_time(tls_ctx);
1668 fprintf(stderr, " revocation: %s",
1669 t != -1 ? ctime(&t) : "\n");
1670 break;
1671 case -1:
1672 break;
1673 default:
1674 fprintf(stderr, "OCSP Stapling: failure - response_status %d (%s)\n",
1675 tls_peer_ocsp_response_status(tls_ctx),
1676 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
1677 tls_peer_ocsp_result(tls_ctx));
1678 break;
1683 void
1684 report_connect(const struct sockaddr *sa, socklen_t salen, char *path)
1686 char remote_host[NI_MAXHOST];
1687 char remote_port[NI_MAXSERV];
1688 int herr;
1689 int flags = NI_NUMERICSERV;
1691 if (path != NULL) {
1692 fprintf(stderr, "Connection on %s received!\n", path);
1693 return;
1696 if (nflag)
1697 flags |= NI_NUMERICHOST;
1699 if ((herr = getnameinfo(sa, salen,
1700 remote_host, sizeof(remote_host),
1701 remote_port, sizeof(remote_port),
1702 flags)) != 0) {
1703 if (herr == EAI_SYSTEM)
1704 err(1, "getnameinfo");
1705 else
1706 errx(1, "getnameinfo: %s", gai_strerror(herr));
1709 fprintf(stderr,
1710 "Connection from %s %s "
1711 "received!\n", remote_host, remote_port);
1714 void
1715 help(void)
1717 usage(0);
1718 fprintf(stderr, "\tCommand Summary:\n\
1719 \t-4 Use IPv4\n\
1720 \t-6 Use IPv6\n\
1721 \t-C certfile Public key file\n\
1722 \t-c Use TLS\n\
1723 \t-D Enable the debug socket option\n\
1724 \t-d Detach from stdin\n\
1725 \t-e name\t Required name in peer certificate\n\
1726 \t-F Pass socket fd\n\
1727 \t-H hash\t Hash string of peer certificate\n\
1728 \t-h This help text\n\
1729 \t-I length TCP receive buffer length\n\
1730 \t-i interval Delay interval for lines sent, ports scanned\n\
1731 \t-K keyfile Private key file\n\
1732 \t-k Keep inbound sockets open for multiple connects\n\
1733 \t-l Listen mode, for inbound connects\n\
1734 \t-M ttl Outgoing TTL / Hop Limit\n\
1735 \t-m minttl Minimum incoming TTL / Hop Limit\n\
1736 \t-N Shutdown the network socket after EOF on stdin\n\
1737 \t-n Suppress name/port resolutions\n\
1738 \t-O length TCP send buffer length\n\
1739 \t-o staplefile Staple file\n\
1740 \t-P proxyuser\tUsername for proxy authentication\n\
1741 \t-p port\t Specify local port for remote connects\n\
1742 \t-R CAfile CA bundle\n\
1743 \t-r Randomize remote ports\n"
1744 #ifdef TCP_MD5SIG
1746 \t-S Enable the TCP MD5 signature option\n"
1747 #endif
1749 \t-s source Local source address\n\
1750 \t-T keyword TOS value or TLS options\n\
1751 \t-t Answer TELNET negotiation\n\
1752 \t-U Use UNIX domain socket\n\
1753 \t-u UDP mode\n"
1754 #ifdef SO_RTABLE
1756 \t-V rtable Specify alternate routing table\n"
1757 #endif
1759 \t-v Verbose\n\
1760 \t-W recvlimit Terminate after receiving a number of packets\n\
1761 \t-w timeout Timeout for connects and final net reads\n\
1762 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1763 \t-x addr[:port]\tSpecify proxy address and port\n\
1764 \t-Z Peer certificate file\n\
1765 \t-z Zero-I/O mode [used for scanning]\n\
1766 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1767 exit(1);
1770 void
1771 usage(int ret)
1773 fprintf(stderr,
1774 "usage: nc [-46cDdFhklNnrStUuvz] [-C certfile] [-e name] "
1775 "[-H hash] [-I length]\n"
1776 "\t [-i interval] [-K keyfile] [-M ttl] [-m minttl] [-O length]\n"
1777 "\t [-o staplefile] [-P proxy_username] [-p source_port] "
1778 "[-R CAfile]\n"
1779 "\t [-s source] [-T keyword] [-V rtable] [-W recvlimit] "
1780 "[-w timeout]\n"
1781 "\t [-X proxy_protocol] [-x proxy_address[:port]] "
1782 "[-Z peercertfile]\n"
1783 "\t [destination] [port]\n");
1784 if (ret)
1785 exit(1);