FEATURES: add notes about compilation env changes
[unleashed.git] / bin / nc / netcat.c
blob45e4dbcdcea24e056af706077460c81ed72785bf
1 /* $OpenBSD: netcat.c,v 1.195 2018/10/04 17:04:50 bluhm 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(const char *, const 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 /* Cruft to make sure options are clean, and used properly. */
363 if (argv[0] && !argv[1] && family == AF_UNIX) {
364 host = argv[0];
365 uport = NULL;
366 } else if (argv[0] && !argv[1]) {
367 if (!lflag)
368 usage(1);
369 uport = argv[0];
370 host = NULL;
371 } else if (argv[0] && argv[1]) {
372 host = argv[0];
373 uport = argv[1];
374 } else
375 usage(1);
377 if (usetls) {
378 if (Cflag && unveil(Cflag, "r") == -1)
379 err(1, "unveil");
380 if (unveil(Rflag, "r") == -1)
381 err(1, "unveil");
382 if (Kflag && unveil(Kflag, "r") == -1)
383 err(1, "unveil");
384 if (oflag && unveil(oflag, "r") == -1)
385 err(1, "unveil");
386 } else {
387 if (family == AF_UNIX) {
388 if (unveil(host, "rwc") == -1)
389 err(1, "unveil");
390 if (uflag && !lflag) {
391 if (unveil(sflag ? sflag : "/tmp", "rwc") == -1)
392 err(1, "unveil");
394 } else {
395 if (unveil("/", "") == -1)
396 err(1, "unveil");
400 if (family == AF_UNIX) {
401 if (pledge("stdio rpath wpath cpath tmppath unix", NULL) == -1)
402 err(1, "pledge");
403 } else if (Fflag && Pflag) {
404 if (pledge("stdio inet dns sendfd tty", NULL) == -1)
405 err(1, "pledge");
406 } else if (Fflag) {
407 if (pledge("stdio inet dns sendfd", NULL) == -1)
408 err(1, "pledge");
409 } else if (Pflag && usetls) {
410 if (pledge("stdio rpath inet dns tty", NULL) == -1)
411 err(1, "pledge");
412 } else if (Pflag) {
413 if (pledge("stdio inet dns tty", NULL) == -1)
414 err(1, "pledge");
415 } else if (usetls) {
416 if (pledge("stdio rpath inet dns", NULL) == -1)
417 err(1, "pledge");
418 } else if (pledge("stdio inet dns", NULL) == -1)
419 err(1, "pledge");
421 if (lflag && sflag)
422 errx(1, "cannot use -s and -l");
423 if (lflag && pflag)
424 errx(1, "cannot use -p and -l");
425 if (lflag && zflag)
426 errx(1, "cannot use -z and -l");
427 if (!lflag && kflag)
428 errx(1, "must use -l with -k");
429 if (uflag && usetls)
430 errx(1, "cannot use -c and -u");
431 if ((family == AF_UNIX) && usetls)
432 errx(1, "cannot use -c and -U");
433 if ((family == AF_UNIX) && Fflag)
434 errx(1, "cannot use -F and -U");
435 if (Fflag && usetls)
436 errx(1, "cannot use -c and -F");
437 if (TLSopt && !usetls)
438 errx(1, "you must specify -c to use TLS options");
439 if (Cflag && !usetls)
440 errx(1, "you must specify -c to use -C");
441 if (Kflag && !usetls)
442 errx(1, "you must specify -c to use -K");
443 if (Zflag && !usetls)
444 errx(1, "you must specify -c to use -Z");
445 if (oflag && !Cflag)
446 errx(1, "you must specify -C to use -o");
447 if (tls_cachanged && !usetls)
448 errx(1, "you must specify -c to use -R");
449 if (tls_expecthash && !usetls)
450 errx(1, "you must specify -c to use -H");
451 if (tls_expectname && !usetls)
452 errx(1, "you must specify -c to use -e");
454 /* Get name of temporary socket for unix datagram client */
455 if ((family == AF_UNIX) && uflag && !lflag) {
456 if (sflag) {
457 unix_dg_tmp_socket = sflag;
458 } else {
459 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
460 UNIX_DG_TMP_SOCKET_SIZE);
461 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
462 err(1, "mktemp");
463 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
467 /* Initialize addrinfo structure. */
468 if (family != AF_UNIX) {
469 memset(&hints, 0, sizeof(struct addrinfo));
470 hints.ai_family = family;
471 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
472 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
473 if (nflag)
474 hints.ai_flags |= AI_NUMERICHOST;
477 if (xflag) {
478 if (uflag)
479 errx(1, "no proxy support for UDP mode");
481 if (lflag)
482 errx(1, "no proxy support for listen");
484 if (family == AF_UNIX)
485 errx(1, "no proxy support for unix sockets");
487 if (sflag)
488 errx(1, "no proxy support for local source address");
490 if (*proxy == '[') {
491 ++proxy;
492 proxyport = strchr(proxy, ']');
493 if (proxyport == NULL)
494 errx(1, "missing closing bracket in proxy");
495 *proxyport++ = '\0';
496 if (*proxyport == '\0')
497 /* Use default proxy port. */
498 proxyport = NULL;
499 else {
500 if (*proxyport == ':')
501 ++proxyport;
502 else
503 errx(1, "garbage proxy port delimiter");
505 } else {
506 proxyport = strrchr(proxy, ':');
507 if (proxyport != NULL)
508 *proxyport++ = '\0';
511 memset(&proxyhints, 0, sizeof(struct addrinfo));
512 proxyhints.ai_family = family;
513 proxyhints.ai_socktype = SOCK_STREAM;
514 proxyhints.ai_protocol = IPPROTO_TCP;
515 if (nflag)
516 proxyhints.ai_flags |= AI_NUMERICHOST;
519 if (usetls) {
520 if ((tls_cfg = tls_config_new()) == NULL)
521 errx(1, "unable to allocate TLS config");
522 if (Rflag && tls_config_set_ca_file(tls_cfg, Rflag) == -1)
523 errx(1, "%s", tls_config_error(tls_cfg));
524 if (Cflag && tls_config_set_cert_file(tls_cfg, Cflag) == -1)
525 errx(1, "%s", tls_config_error(tls_cfg));
526 if (Kflag && tls_config_set_key_file(tls_cfg, Kflag) == -1)
527 errx(1, "%s", tls_config_error(tls_cfg));
528 if (oflag && tls_config_set_ocsp_staple_file(tls_cfg, oflag) == -1)
529 errx(1, "%s", tls_config_error(tls_cfg));
530 if (tls_config_parse_protocols(&protocols, tls_protocols) == -1)
531 errx(1, "invalid TLS protocols `%s'", tls_protocols);
532 if (tls_config_set_protocols(tls_cfg, protocols) == -1)
533 errx(1, "%s", tls_config_error(tls_cfg));
534 if (tls_config_set_ciphers(tls_cfg, tls_ciphers) == -1)
535 errx(1, "%s", tls_config_error(tls_cfg));
536 if (!lflag && (TLSopt & TLS_CCERT))
537 errx(1, "clientcert is only valid with -l");
538 if (TLSopt & TLS_NONAME)
539 tls_config_insecure_noverifyname(tls_cfg);
540 if (TLSopt & TLS_NOVERIFY) {
541 if (tls_expecthash != NULL)
542 errx(1, "-H and -T noverify may not be used "
543 "together");
544 tls_config_insecure_noverifycert(tls_cfg);
546 if (TLSopt & TLS_MUSTSTAPLE)
547 tls_config_ocsp_require_stapling(tls_cfg);
549 if (Pflag) {
550 if (pledge("stdio inet dns tty", NULL) == -1)
551 err(1, "pledge");
552 } else if (pledge("stdio inet dns", NULL) == -1)
553 err(1, "pledge");
555 if (lflag) {
556 ret = 0;
558 if (family == AF_UNIX) {
559 if (uflag)
560 s = unix_bind(host, 0);
561 else
562 s = unix_listen(host);
565 if (usetls) {
566 tls_config_verify_client_optional(tls_cfg);
567 if ((tls_ctx = tls_server()) == NULL)
568 errx(1, "tls server creation failed");
569 if (tls_configure(tls_ctx, tls_cfg) == -1)
570 errx(1, "tls configuration failed (%s)",
571 tls_error(tls_ctx));
573 /* Allow only one connection at a time, but stay alive. */
574 for (;;) {
575 if (family != AF_UNIX) {
576 if (s != -1)
577 close(s);
578 s = local_listen(host, uport, hints);
580 if (s < 0)
581 err(1, NULL);
582 if (uflag && kflag) {
584 * For UDP and -k, don't connect the socket,
585 * let it receive datagrams from multiple
586 * socket pairs.
588 readwrite(s, NULL);
589 } else if (uflag && !kflag) {
591 * For UDP and not -k, we will use recvfrom()
592 * initially to wait for a caller, then use
593 * the regular functions to talk to the caller.
595 int rv;
596 char buf[2048];
597 struct sockaddr_storage z;
599 len = sizeof(z);
600 rv = recvfrom(s, buf, sizeof(buf), MSG_PEEK,
601 (struct sockaddr *)&z, &len);
602 if (rv < 0)
603 err(1, "recvfrom");
605 rv = connect(s, (struct sockaddr *)&z, len);
606 if (rv < 0)
607 err(1, "connect");
609 if (vflag)
610 report_connect((struct sockaddr *)&z, len, NULL);
612 readwrite(s, NULL);
613 } else {
614 struct tls *tls_cctx = NULL;
615 int connfd;
617 len = sizeof(cliaddr);
618 connfd = accept4(s, (struct sockaddr *)&cliaddr,
619 &len, SOCK_NONBLOCK);
620 if (connfd == -1) {
621 /* For now, all errnos are fatal */
622 err(1, "accept");
624 if (vflag)
625 report_connect((struct sockaddr *)&cliaddr, len,
626 family == AF_UNIX ? host : NULL);
627 if ((usetls) &&
628 (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
629 readwrite(connfd, tls_cctx);
630 if (!usetls)
631 readwrite(connfd, NULL);
632 if (tls_cctx)
633 timeout_tls(s, tls_cctx, tls_close);
634 close(connfd);
635 tls_free(tls_cctx);
637 if (family == AF_UNIX && uflag) {
638 if (connect(s, NULL, 0) < 0)
639 err(1, "connect");
642 if (!kflag)
643 break;
645 } else if (family == AF_UNIX) {
646 ret = 0;
648 if ((s = unix_connect(host)) > 0) {
649 if (!zflag)
650 readwrite(s, NULL);
651 close(s);
652 } else
653 ret = 1;
655 if (uflag)
656 unlink(unix_dg_tmp_socket);
657 return ret;
659 } else {
660 int i = 0;
662 /* Construct the portlist[] array. */
663 build_ports(uport);
665 /* Cycle through portlist, connecting to each port. */
666 for (s = -1, i = 0; portlist[i] != NULL; i++) {
667 if (s != -1)
668 close(s);
669 tls_free(tls_ctx);
670 tls_ctx = NULL;
672 if (usetls) {
673 if ((tls_ctx = tls_client()) == NULL)
674 errx(1, "tls client creation failed");
675 if (tls_configure(tls_ctx, tls_cfg) == -1)
676 errx(1, "tls configuration failed (%s)",
677 tls_error(tls_ctx));
679 if (xflag)
680 s = socks_connect(host, portlist[i], hints,
681 proxy, proxyport, proxyhints, socksv,
682 Pflag);
683 else
684 s = remote_connect(host, portlist[i], hints);
686 if (s == -1)
687 continue;
689 ret = 0;
690 if (vflag || zflag) {
691 /* For UDP, make sure we are connected. */
692 if (uflag) {
693 if (udptest(s) == -1) {
694 ret = 1;
695 continue;
699 /* Don't look up port if -n. */
700 if (nflag)
701 sv = NULL;
702 else {
703 sv = getservbyport(
704 ntohs(atoi(portlist[i])),
705 uflag ? "udp" : "tcp");
708 fprintf(stderr,
709 "Connection to %s %s port [%s/%s] "
710 "succeeded!\n", host, portlist[i],
711 uflag ? "udp" : "tcp",
712 sv ? sv->s_name : "*");
714 if (Fflag)
715 fdpass(s);
716 else {
717 if (usetls)
718 tls_setup_client(tls_ctx, s, host);
719 if (!zflag)
720 readwrite(s, tls_ctx);
721 if (tls_ctx)
722 timeout_tls(s, tls_ctx, tls_close);
727 if (s != -1)
728 close(s);
729 tls_free(tls_ctx);
730 tls_config_free(tls_cfg);
732 return ret;
736 * unix_bind()
737 * Returns a unix socket bound to the given path
740 unix_bind(char *path, int flags)
742 struct sockaddr_un s_un;
743 int s, save_errno;
745 /* Create unix domain socket. */
746 if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
747 0)) < 0)
748 return -1;
750 memset(&s_un, 0, sizeof(struct sockaddr_un));
751 s_un.sun_family = AF_UNIX;
753 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
754 sizeof(s_un.sun_path)) {
755 close(s);
756 errno = ENAMETOOLONG;
757 return -1;
760 if (bind(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
761 save_errno = errno;
762 close(s);
763 errno = save_errno;
764 return -1;
767 return s;
771 timeout_tls(int s, struct tls *tls_ctx, int (*func)(struct tls *))
773 struct pollfd pfd;
774 int ret;
776 while ((ret = (*func)(tls_ctx)) != 0) {
777 if (ret == TLS_WANT_POLLIN)
778 pfd.events = POLLIN;
779 else if (ret == TLS_WANT_POLLOUT)
780 pfd.events = POLLOUT;
781 else
782 break;
783 pfd.fd = s;
784 if ((ret = poll(&pfd, 1, timeout)) == 1)
785 continue;
786 else if (ret == 0) {
787 errno = ETIMEDOUT;
788 ret = -1;
789 break;
790 } else
791 err(1, "poll failed");
794 return ret;
797 void
798 tls_setup_client(struct tls *tls_ctx, int s, char *host)
800 const char *errstr;
802 if (tls_connect_socket(tls_ctx, s,
803 tls_expectname ? tls_expectname : host) == -1) {
804 errx(1, "tls connection failed (%s)",
805 tls_error(tls_ctx));
807 if (timeout_tls(s, tls_ctx, tls_handshake) == -1) {
808 if ((errstr = tls_error(tls_ctx)) == NULL)
809 errstr = strerror(errno);
810 errx(1, "tls handshake failed (%s)", errstr);
812 if (vflag)
813 report_tls(tls_ctx, host);
814 if (tls_expecthash && tls_peer_cert_hash(tls_ctx) &&
815 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
816 errx(1, "peer certificate is not %s", tls_expecthash);
817 if (Zflag) {
818 save_peer_cert(tls_ctx, Zflag);
819 if (Zflag != stderr && (fclose(Zflag) != 0))
820 err(1, "fclose failed saving peer cert");
824 struct tls *
825 tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
827 struct tls *tls_cctx;
828 const char *errstr;
830 if (tls_accept_socket(tls_ctx, &tls_cctx, connfd) == -1) {
831 warnx("tls accept failed (%s)", tls_error(tls_ctx));
832 } else if (timeout_tls(connfd, tls_cctx, tls_handshake) == -1) {
833 if ((errstr = tls_error(tls_cctx)) == NULL)
834 errstr = strerror(errno);
835 warnx("tls handshake failed (%s)", errstr);
836 } else {
837 int gotcert = tls_peer_cert_provided(tls_cctx);
839 if (vflag && gotcert)
840 report_tls(tls_cctx, host);
841 if ((TLSopt & TLS_CCERT) && !gotcert)
842 warnx("No client certificate provided");
843 else if (gotcert && tls_peer_cert_hash(tls_ctx) && tls_expecthash &&
844 strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
845 warnx("peer certificate is not %s", tls_expecthash);
846 else if (gotcert && tls_expectname &&
847 (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
848 warnx("name (%s) not found in client cert",
849 tls_expectname);
850 else {
851 return tls_cctx;
854 return NULL;
858 * unix_connect()
859 * Returns a socket connected to a local unix socket. Returns -1 on failure.
862 unix_connect(char *path)
864 struct sockaddr_un s_un;
865 int s, save_errno;
867 if (uflag) {
868 if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) < 0)
869 return -1;
870 } else {
871 if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
872 return -1;
875 memset(&s_un, 0, sizeof(struct sockaddr_un));
876 s_un.sun_family = AF_UNIX;
878 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
879 sizeof(s_un.sun_path)) {
880 close(s);
881 errno = ENAMETOOLONG;
882 return -1;
884 if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
885 save_errno = errno;
886 close(s);
887 errno = save_errno;
888 return -1;
890 return s;
895 * unix_listen()
896 * Create a unix domain socket, and listen on it.
899 unix_listen(char *path)
901 int s;
902 if ((s = unix_bind(path, 0)) < 0)
903 return -1;
905 if (listen(s, 5) < 0) {
906 close(s);
907 return -1;
909 return s;
913 * remote_connect()
914 * Returns a socket connected to a remote host. Properly binds to a local
915 * port or source address if needed. Returns -1 on failure.
918 remote_connect(const char *host, const char *port, struct addrinfo hints)
920 struct addrinfo *res, *res0;
921 int s = -1, error, save_errno;
922 #ifdef SO_BINDANY
923 int on = 1;
924 #endif
926 if ((error = getaddrinfo(host, port, &hints, &res0)))
927 errx(1, "getaddrinfo for host \"%s\" port %s: %s", host,
928 port, gai_strerror(error));
930 for (res = res0; res; res = res->ai_next) {
931 if ((s = socket(res->ai_family, res->ai_socktype |
932 SOCK_NONBLOCK, res->ai_protocol)) < 0)
933 continue;
935 /* Bind to a local port or source address if specified. */
936 if (sflag || pflag) {
937 struct addrinfo ahints, *ares;
939 #ifdef SO_BINDANY
940 /* try SO_BINDANY, but don't insist */
941 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
942 #endif
943 memset(&ahints, 0, sizeof(struct addrinfo));
944 ahints.ai_family = res->ai_family;
945 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
946 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
947 ahints.ai_flags = AI_PASSIVE;
948 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
949 errx(1, "getaddrinfo: %s", gai_strerror(error));
951 if (bind(s, (struct sockaddr *)ares->ai_addr,
952 ares->ai_addrlen) < 0)
953 err(1, "bind failed");
954 freeaddrinfo(ares);
957 set_common_sockopts(s, res->ai_family);
959 if (timeout_connect(s, res->ai_addr, res->ai_addrlen) == 0)
960 break;
961 if (vflag)
962 warn("connect to %s port %s (%s) failed", host, port,
963 uflag ? "udp" : "tcp");
965 save_errno = errno;
966 close(s);
967 errno = save_errno;
968 s = -1;
971 freeaddrinfo(res0);
973 return s;
977 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
979 struct pollfd pfd;
980 socklen_t optlen;
981 int optval;
982 int ret;
984 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
985 pfd.fd = s;
986 pfd.events = POLLOUT;
987 if ((ret = poll(&pfd, 1, timeout)) == 1) {
988 optlen = sizeof(optval);
989 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
990 &optval, &optlen)) == 0) {
991 errno = optval;
992 ret = optval == 0 ? 0 : -1;
994 } else if (ret == 0) {
995 errno = ETIMEDOUT;
996 ret = -1;
997 } else
998 err(1, "poll failed");
1001 return ret;
1005 * local_listen()
1006 * Returns a socket listening on a local port, binds to specified source
1007 * address. Returns -1 on failure.
1010 local_listen(const char *host, const char *port, struct addrinfo hints)
1012 struct addrinfo *res, *res0;
1013 int s = -1, save_errno;
1014 #ifdef SO_REUSEPORT
1015 int ret, x = 1;
1016 #endif
1017 int error;
1019 /* Allow nodename to be null. */
1020 hints.ai_flags |= AI_PASSIVE;
1023 * In the case of binding to a wildcard address
1024 * default to binding to an ipv4 address.
1026 if (host == NULL && hints.ai_family == AF_UNSPEC)
1027 hints.ai_family = AF_INET;
1029 if ((error = getaddrinfo(host, port, &hints, &res0)))
1030 errx(1, "getaddrinfo: %s", gai_strerror(error));
1032 for (res = res0; res; res = res->ai_next) {
1033 if ((s = socket(res->ai_family, res->ai_socktype,
1034 res->ai_protocol)) < 0)
1035 continue;
1037 #ifdef SO_REUSEPORT
1038 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
1039 if (ret == -1)
1040 err(1, NULL);
1041 #endif
1043 set_common_sockopts(s, res->ai_family);
1045 if (bind(s, (struct sockaddr *)res->ai_addr,
1046 res->ai_addrlen) == 0)
1047 break;
1049 save_errno = errno;
1050 close(s);
1051 errno = save_errno;
1052 s = -1;
1055 if (!uflag && s != -1) {
1056 if (listen(s, 1) < 0)
1057 err(1, "listen");
1060 freeaddrinfo(res0);
1062 return s;
1066 * readwrite()
1067 * Loop that polls on the network file descriptor and stdin.
1069 void
1070 readwrite(int net_fd, struct tls *tls_ctx)
1072 struct pollfd pfd[4];
1073 int stdin_fd = STDIN_FILENO;
1074 int stdout_fd = STDOUT_FILENO;
1075 unsigned char netinbuf[BUFSIZE];
1076 size_t netinbufpos = 0;
1077 unsigned char stdinbuf[BUFSIZE];
1078 size_t stdinbufpos = 0;
1079 int n, num_fds;
1080 ssize_t ret;
1082 /* don't read from stdin if requested */
1083 if (dflag)
1084 stdin_fd = -1;
1086 /* stdin */
1087 pfd[POLL_STDIN].fd = stdin_fd;
1088 pfd[POLL_STDIN].events = POLLIN;
1090 /* network out */
1091 pfd[POLL_NETOUT].fd = net_fd;
1092 pfd[POLL_NETOUT].events = 0;
1094 /* network in */
1095 pfd[POLL_NETIN].fd = net_fd;
1096 pfd[POLL_NETIN].events = POLLIN;
1098 /* stdout */
1099 pfd[POLL_STDOUT].fd = stdout_fd;
1100 pfd[POLL_STDOUT].events = 0;
1102 while (1) {
1103 /* both inputs are gone, buffers are empty, we are done */
1104 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
1105 stdinbufpos == 0 && netinbufpos == 0)
1106 return;
1107 /* both outputs are gone, we can't continue */
1108 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1)
1109 return;
1110 /* listen and net in gone, queues empty, done */
1111 if (lflag && pfd[POLL_NETIN].fd == -1 &&
1112 stdinbufpos == 0 && netinbufpos == 0)
1113 return;
1115 /* help says -i is for "wait between lines sent". We read and
1116 * write arbitrary amounts of data, and we don't want to start
1117 * scanning for newlines, so this is as good as it gets */
1118 if (iflag)
1119 sleep(iflag);
1121 /* poll */
1122 num_fds = poll(pfd, 4, timeout);
1124 /* treat poll errors */
1125 if (num_fds == -1)
1126 err(1, "polling error");
1128 /* timeout happened */
1129 if (num_fds == 0)
1130 return;
1132 /* treat socket error conditions */
1133 for (n = 0; n < 4; n++) {
1134 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
1135 pfd[n].fd = -1;
1138 /* reading is possible after HUP */
1139 if (pfd[POLL_STDIN].events & POLLIN &&
1140 pfd[POLL_STDIN].revents & POLLHUP &&
1141 !(pfd[POLL_STDIN].revents & POLLIN))
1142 pfd[POLL_STDIN].fd = -1;
1144 if (pfd[POLL_NETIN].events & POLLIN &&
1145 pfd[POLL_NETIN].revents & POLLHUP &&
1146 !(pfd[POLL_NETIN].revents & POLLIN))
1147 pfd[POLL_NETIN].fd = -1;
1149 if (pfd[POLL_NETOUT].revents & POLLHUP) {
1150 if (Nflag)
1151 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1152 pfd[POLL_NETOUT].fd = -1;
1154 /* if HUP, stop watching stdout */
1155 if (pfd[POLL_STDOUT].revents & POLLHUP)
1156 pfd[POLL_STDOUT].fd = -1;
1157 /* if no net out, stop watching stdin */
1158 if (pfd[POLL_NETOUT].fd == -1)
1159 pfd[POLL_STDIN].fd = -1;
1160 /* if no stdout, stop watching net in */
1161 if (pfd[POLL_STDOUT].fd == -1) {
1162 if (pfd[POLL_NETIN].fd != -1)
1163 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1164 pfd[POLL_NETIN].fd = -1;
1167 /* try to read from stdin */
1168 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
1169 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
1170 &stdinbufpos, NULL);
1171 if (ret == TLS_WANT_POLLIN)
1172 pfd[POLL_STDIN].events = POLLIN;
1173 else if (ret == TLS_WANT_POLLOUT)
1174 pfd[POLL_STDIN].events = POLLOUT;
1175 else if (ret == 0 || ret == -1)
1176 pfd[POLL_STDIN].fd = -1;
1177 /* read something - poll net out */
1178 if (stdinbufpos > 0)
1179 pfd[POLL_NETOUT].events = POLLOUT;
1180 /* filled buffer - remove self from polling */
1181 if (stdinbufpos == BUFSIZE)
1182 pfd[POLL_STDIN].events = 0;
1184 /* try to write to network */
1185 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
1186 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
1187 &stdinbufpos, tls_ctx);
1188 if (ret == TLS_WANT_POLLIN)
1189 pfd[POLL_NETOUT].events = POLLIN;
1190 else if (ret == TLS_WANT_POLLOUT)
1191 pfd[POLL_NETOUT].events = POLLOUT;
1192 else if (ret == -1)
1193 pfd[POLL_NETOUT].fd = -1;
1194 /* buffer empty - remove self from polling */
1195 if (stdinbufpos == 0)
1196 pfd[POLL_NETOUT].events = 0;
1197 /* buffer no longer full - poll stdin again */
1198 if (stdinbufpos < BUFSIZE)
1199 pfd[POLL_STDIN].events = POLLIN;
1201 /* try to read from network */
1202 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
1203 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
1204 &netinbufpos, tls_ctx);
1205 if (ret == TLS_WANT_POLLIN)
1206 pfd[POLL_NETIN].events = POLLIN;
1207 else if (ret == TLS_WANT_POLLOUT)
1208 pfd[POLL_NETIN].events = POLLOUT;
1209 else if (ret == -1)
1210 pfd[POLL_NETIN].fd = -1;
1211 /* eof on net in - remove from pfd */
1212 if (ret == 0) {
1213 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1214 pfd[POLL_NETIN].fd = -1;
1216 if (recvlimit > 0 && ++recvcount >= recvlimit) {
1217 if (pfd[POLL_NETIN].fd != -1)
1218 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1219 pfd[POLL_NETIN].fd = -1;
1220 pfd[POLL_STDIN].fd = -1;
1222 /* read something - poll stdout */
1223 if (netinbufpos > 0)
1224 pfd[POLL_STDOUT].events = POLLOUT;
1225 /* filled buffer - remove self from polling */
1226 if (netinbufpos == BUFSIZE)
1227 pfd[POLL_NETIN].events = 0;
1228 /* handle telnet */
1229 if (tflag)
1230 atelnet(pfd[POLL_NETIN].fd, netinbuf,
1231 netinbufpos);
1233 /* try to write to stdout */
1234 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1235 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1236 &netinbufpos, NULL);
1237 if (ret == TLS_WANT_POLLIN)
1238 pfd[POLL_STDOUT].events = POLLIN;
1239 else if (ret == TLS_WANT_POLLOUT)
1240 pfd[POLL_STDOUT].events = POLLOUT;
1241 else if (ret == -1)
1242 pfd[POLL_STDOUT].fd = -1;
1243 /* buffer empty - remove self from polling */
1244 if (netinbufpos == 0)
1245 pfd[POLL_STDOUT].events = 0;
1246 /* buffer no longer full - poll net in again */
1247 if (netinbufpos < BUFSIZE)
1248 pfd[POLL_NETIN].events = POLLIN;
1251 /* stdin gone and queue empty? */
1252 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1253 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
1254 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1255 pfd[POLL_NETOUT].fd = -1;
1257 /* net in gone and queue empty? */
1258 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1259 pfd[POLL_STDOUT].fd = -1;
1264 ssize_t
1265 drainbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1267 ssize_t n;
1268 ssize_t adjust;
1270 if (tls)
1271 n = tls_write(tls, buf, *bufpos);
1272 else {
1273 n = write(fd, buf, *bufpos);
1274 /* don't treat EAGAIN, EINTR as error */
1275 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1276 n = TLS_WANT_POLLOUT;
1278 if (n <= 0)
1279 return n;
1280 /* adjust buffer */
1281 adjust = *bufpos - n;
1282 if (adjust > 0)
1283 memmove(buf, buf + n, adjust);
1284 *bufpos -= n;
1285 return n;
1288 ssize_t
1289 fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1291 size_t num = BUFSIZE - *bufpos;
1292 ssize_t n;
1294 if (tls)
1295 n = tls_read(tls, buf + *bufpos, num);
1296 else {
1297 n = read(fd, buf + *bufpos, num);
1298 /* don't treat EAGAIN, EINTR as error */
1299 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1300 n = TLS_WANT_POLLIN;
1302 if (n <= 0)
1303 return n;
1304 *bufpos += n;
1305 return n;
1309 * fdpass()
1310 * Pass the connected file descriptor to stdout and exit.
1312 void
1313 fdpass(int nfd)
1315 struct msghdr mh;
1316 union {
1317 struct cmsghdr hdr;
1318 char buf[CMSG_SPACE(sizeof(int))];
1319 } cmsgbuf;
1320 struct cmsghdr *cmsg;
1321 struct iovec iov;
1322 char c = '\0';
1323 ssize_t r;
1324 struct pollfd pfd;
1326 /* Avoid obvious stupidity */
1327 if (isatty(STDOUT_FILENO))
1328 errx(1, "Cannot pass file descriptor to tty");
1330 bzero(&mh, sizeof(mh));
1331 bzero(&cmsgbuf, sizeof(cmsgbuf));
1332 bzero(&iov, sizeof(iov));
1334 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1335 mh.msg_controllen = sizeof(cmsgbuf.buf);
1336 cmsg = CMSG_FIRSTHDR(&mh);
1337 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1338 cmsg->cmsg_level = SOL_SOCKET;
1339 cmsg->cmsg_type = SCM_RIGHTS;
1340 *(int *)CMSG_DATA(cmsg) = nfd;
1342 iov.iov_base = &c;
1343 iov.iov_len = 1;
1344 mh.msg_iov = &iov;
1345 mh.msg_iovlen = 1;
1347 bzero(&pfd, sizeof(pfd));
1348 pfd.fd = STDOUT_FILENO;
1349 pfd.events = POLLOUT;
1350 for (;;) {
1351 r = sendmsg(STDOUT_FILENO, &mh, 0);
1352 if (r == -1) {
1353 if (errno == EAGAIN || errno == EINTR) {
1354 if (poll(&pfd, 1, -1) == -1)
1355 err(1, "poll");
1356 continue;
1358 err(1, "sendmsg");
1359 } else if (r != 1)
1360 errx(1, "sendmsg: unexpected return value %zd", r);
1361 else
1362 break;
1364 exit(0);
1367 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1368 void
1369 atelnet(int nfd, unsigned char *buf, unsigned int size)
1371 unsigned char *p, *end;
1372 unsigned char obuf[4];
1374 if (size < 3)
1375 return;
1376 end = buf + size - 2;
1378 for (p = buf; p < end; p++) {
1379 if (*p != IAC)
1380 continue;
1382 obuf[0] = IAC;
1383 p++;
1384 if ((*p == WILL) || (*p == WONT))
1385 obuf[1] = DONT;
1386 else if ((*p == DO) || (*p == DONT))
1387 obuf[1] = WONT;
1388 else
1389 continue;
1391 p++;
1392 obuf[2] = *p;
1393 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1394 warn("Write Error!");
1400 strtoport(char *portstr, int udp)
1402 struct servent *entry;
1403 const char *errstr;
1404 char *proto;
1405 int port = -1;
1407 proto = udp ? "udp" : "tcp";
1409 port = strtonum(portstr, 1, PORT_MAX, &errstr);
1410 if (errstr == NULL)
1411 return port;
1412 if (errno != EINVAL)
1413 errx(1, "port number %s: %s", errstr, portstr);
1414 if ((entry = getservbyname(portstr, proto)) == NULL)
1415 errx(1, "service \"%s\" unknown", portstr);
1416 return ntohs(entry->s_port);
1420 * build_ports()
1421 * Build an array of ports in portlist[], listing each port
1422 * that we should try to connect to.
1424 void
1425 build_ports(char *p)
1427 char *n;
1428 int hi, lo, cp;
1429 int x = 0;
1431 if ((n = strchr(p, '-')) != NULL) {
1432 *n = '\0';
1433 n++;
1435 /* Make sure the ports are in order: lowest->highest. */
1436 hi = strtoport(n, uflag);
1437 lo = strtoport(p, uflag);
1438 if (lo > hi) {
1439 cp = hi;
1440 hi = lo;
1441 lo = cp;
1445 * Initialize portlist with a random permutation. Based on
1446 * Knuth, as in ip_randomid() in sys/netinet/ip_id.c.
1448 if (rflag) {
1449 for (x = 0; x <= hi - lo; x++) {
1450 cp = arc4random_uniform(x + 1);
1451 portlist[x] = portlist[cp];
1452 if (asprintf(&portlist[cp], "%d", x + lo) < 0)
1453 err(1, "asprintf");
1455 } else { /* Load ports sequentially. */
1456 for (cp = lo; cp <= hi; cp++) {
1457 if (asprintf(&portlist[x], "%d", cp) < 0)
1458 err(1, "asprintf");
1459 x++;
1462 } else {
1463 char *tmp;
1465 hi = strtoport(p, uflag);
1466 if (asprintf(&tmp, "%d", hi) != -1)
1467 portlist[0] = tmp;
1468 else
1469 err(1, NULL);
1474 * udptest()
1475 * Do a few writes to see if the UDP port is there.
1476 * Fails once PF state table is full.
1479 udptest(int s)
1481 int i, ret;
1483 for (i = 0; i <= 3; i++) {
1484 if (write(s, "X", 1) == 1)
1485 ret = 1;
1486 else
1487 ret = -1;
1489 return ret;
1492 void
1493 set_common_sockopts(int s, int af)
1495 int x = 1;
1497 #ifdef TCP_MD5SIG
1498 if (Sflag) {
1499 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1500 &x, sizeof(x)) == -1)
1501 err(1, NULL);
1503 #endif
1504 if (Dflag) {
1505 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1506 &x, sizeof(x)) == -1)
1507 err(1, NULL);
1509 if (Tflag != -1) {
1510 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1511 IP_TOS, &Tflag, sizeof(Tflag)) == -1)
1512 err(1, "set IP ToS");
1514 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1515 IPV6_TCLASS, &Tflag, sizeof(Tflag)) == -1)
1516 err(1, "set IPv6 traffic class");
1518 if (Iflag) {
1519 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1520 &Iflag, sizeof(Iflag)) == -1)
1521 err(1, "set TCP receive buffer size");
1523 if (Oflag) {
1524 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1525 &Oflag, sizeof(Oflag)) == -1)
1526 err(1, "set TCP send buffer size");
1529 if (ttl != -1) {
1530 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1531 IP_TTL, &ttl, sizeof(ttl)))
1532 err(1, "set IP TTL");
1534 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1535 IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)))
1536 err(1, "set IPv6 unicast hops");
1539 if (minttl != -1) {
1540 #ifdef IP_MINTTL
1541 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1542 IP_MINTTL, &minttl, sizeof(minttl)))
1543 err(1, "set IP min TTL");
1544 #endif
1546 #ifdef IPV6_MINHOPCOUNT
1547 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1548 IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)))
1549 err(1, "set IPv6 min hop count");
1550 #endif
1555 process_tos_opt(char *s, int *val)
1557 /* DiffServ Codepoints and other TOS mappings */
1558 const struct toskeywords {
1559 const char *keyword;
1560 int val;
1561 } *t, toskeywords[] = {
1562 { "af11", IPTOS_DSCP_AF11 },
1563 { "af12", IPTOS_DSCP_AF12 },
1564 { "af13", IPTOS_DSCP_AF13 },
1565 { "af21", IPTOS_DSCP_AF21 },
1566 { "af22", IPTOS_DSCP_AF22 },
1567 { "af23", IPTOS_DSCP_AF23 },
1568 { "af31", IPTOS_DSCP_AF31 },
1569 { "af32", IPTOS_DSCP_AF32 },
1570 { "af33", IPTOS_DSCP_AF33 },
1571 { "af41", IPTOS_DSCP_AF41 },
1572 { "af42", IPTOS_DSCP_AF42 },
1573 { "af43", IPTOS_DSCP_AF43 },
1574 { "critical", IPTOS_PREC_CRITIC_ECP },
1575 { "cs0", IPTOS_DSCP_CS0 },
1576 { "cs1", IPTOS_DSCP_CS1 },
1577 { "cs2", IPTOS_DSCP_CS2 },
1578 { "cs3", IPTOS_DSCP_CS3 },
1579 { "cs4", IPTOS_DSCP_CS4 },
1580 { "cs5", IPTOS_DSCP_CS5 },
1581 { "cs6", IPTOS_DSCP_CS6 },
1582 { "cs7", IPTOS_DSCP_CS7 },
1583 { "ef", IPTOS_DSCP_EF },
1584 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1585 { "lowdelay", IPTOS_LOWDELAY },
1586 { "netcontrol", IPTOS_PREC_NETCONTROL },
1587 { "reliability", IPTOS_RELIABILITY },
1588 { "throughput", IPTOS_THROUGHPUT },
1589 { NULL, -1 },
1592 for (t = toskeywords; t->keyword != NULL; t++) {
1593 if (strcmp(s, t->keyword) == 0) {
1594 *val = t->val;
1595 return 1;
1599 return 0;
1603 process_tls_opt(char *s, int *flags)
1605 size_t len;
1606 char *v;
1608 const struct tlskeywords {
1609 const char *keyword;
1610 int flag;
1611 char **value;
1612 } *t, tlskeywords[] = {
1613 { "ciphers", -1, &tls_ciphers },
1614 { "clientcert", TLS_CCERT, NULL },
1615 { "muststaple", TLS_MUSTSTAPLE, NULL },
1616 { "noverify", TLS_NOVERIFY, NULL },
1617 { "noname", TLS_NONAME, NULL },
1618 { "protocols", -1, &tls_protocols },
1619 { NULL, -1, NULL },
1622 len = strlen(s);
1623 if ((v = strchr(s, '=')) != NULL) {
1624 len = v - s;
1625 v++;
1628 for (t = tlskeywords; t->keyword != NULL; t++) {
1629 if (strlen(t->keyword) == len &&
1630 strncmp(s, t->keyword, len) == 0) {
1631 if (t->value != NULL) {
1632 if (v == NULL)
1633 errx(1, "invalid tls value `%s'", s);
1634 *t->value = v;
1635 } else {
1636 *flags |= t->flag;
1638 return 1;
1641 return 0;
1644 void
1645 save_peer_cert(struct tls *tls_ctx, FILE *fp)
1647 const char *pem;
1648 size_t plen;
1650 if ((pem = tls_peer_cert_chain_pem(tls_ctx, &plen)) == NULL)
1651 errx(1, "Can't get peer certificate");
1652 if (fprintf(fp, "%.*s", (int)plen, pem) < 0)
1653 err(1, "unable to save peer cert");
1654 if (fflush(fp) != 0)
1655 err(1, "unable to flush peer cert");
1658 void
1659 report_tls(struct tls * tls_ctx, char * host)
1661 time_t t;
1662 const char *ocsp_url;
1664 fprintf(stderr, "TLS handshake negotiated %s/%s with host %s\n",
1665 tls_conn_version(tls_ctx), tls_conn_cipher(tls_ctx), host);
1666 fprintf(stderr, "Peer name: %s\n",
1667 tls_expectname ? tls_expectname : host);
1668 if (tls_peer_cert_subject(tls_ctx))
1669 fprintf(stderr, "Subject: %s\n",
1670 tls_peer_cert_subject(tls_ctx));
1671 if (tls_peer_cert_issuer(tls_ctx))
1672 fprintf(stderr, "Issuer: %s\n",
1673 tls_peer_cert_issuer(tls_ctx));
1674 if ((t = tls_peer_cert_notbefore(tls_ctx)) != -1)
1675 fprintf(stderr, "Valid From: %s", ctime(&t));
1676 if ((t = tls_peer_cert_notafter(tls_ctx)) != -1)
1677 fprintf(stderr, "Valid Until: %s", ctime(&t));
1678 if (tls_peer_cert_hash(tls_ctx))
1679 fprintf(stderr, "Cert Hash: %s\n",
1680 tls_peer_cert_hash(tls_ctx));
1681 ocsp_url = tls_peer_ocsp_url(tls_ctx);
1682 if (ocsp_url != NULL)
1683 fprintf(stderr, "OCSP URL: %s\n", ocsp_url);
1684 switch (tls_peer_ocsp_response_status(tls_ctx)) {
1685 case TLS_OCSP_RESPONSE_SUCCESSFUL:
1686 fprintf(stderr, "OCSP Stapling: %s\n",
1687 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
1688 tls_peer_ocsp_result(tls_ctx));
1689 fprintf(stderr,
1690 " response_status=%d cert_status=%d crl_reason=%d\n",
1691 tls_peer_ocsp_response_status(tls_ctx),
1692 tls_peer_ocsp_cert_status(tls_ctx),
1693 tls_peer_ocsp_crl_reason(tls_ctx));
1694 t = tls_peer_ocsp_this_update(tls_ctx);
1695 fprintf(stderr, " this update: %s",
1696 t != -1 ? ctime(&t) : "\n");
1697 t = tls_peer_ocsp_next_update(tls_ctx);
1698 fprintf(stderr, " next update: %s",
1699 t != -1 ? ctime(&t) : "\n");
1700 t = tls_peer_ocsp_revocation_time(tls_ctx);
1701 fprintf(stderr, " revocation: %s",
1702 t != -1 ? ctime(&t) : "\n");
1703 break;
1704 case -1:
1705 break;
1706 default:
1707 fprintf(stderr, "OCSP Stapling: failure - response_status %d (%s)\n",
1708 tls_peer_ocsp_response_status(tls_ctx),
1709 tls_peer_ocsp_result(tls_ctx) == NULL ? "" :
1710 tls_peer_ocsp_result(tls_ctx));
1711 break;
1716 void
1717 report_connect(const struct sockaddr *sa, socklen_t salen, char *path)
1719 char remote_host[NI_MAXHOST];
1720 char remote_port[NI_MAXSERV];
1721 int herr;
1722 int flags = NI_NUMERICSERV;
1724 if (path != NULL) {
1725 fprintf(stderr, "Connection on %s received!\n", path);
1726 return;
1729 if (nflag)
1730 flags |= NI_NUMERICHOST;
1732 if ((herr = getnameinfo(sa, salen,
1733 remote_host, sizeof(remote_host),
1734 remote_port, sizeof(remote_port),
1735 flags)) != 0) {
1736 if (herr == EAI_SYSTEM)
1737 err(1, "getnameinfo");
1738 else
1739 errx(1, "getnameinfo: %s", gai_strerror(herr));
1742 fprintf(stderr,
1743 "Connection from %s %s "
1744 "received!\n", remote_host, remote_port);
1747 void
1748 help(void)
1750 usage(0);
1751 fprintf(stderr, "\tCommand Summary:\n\
1752 \t-4 Use IPv4\n\
1753 \t-6 Use IPv6\n\
1754 \t-C certfile Public key file\n\
1755 \t-c Use TLS\n\
1756 \t-D Enable the debug socket option\n\
1757 \t-d Detach from stdin\n\
1758 \t-e name\t Required name in peer certificate\n\
1759 \t-F Pass socket fd\n\
1760 \t-H hash\t Hash string of peer certificate\n\
1761 \t-h This help text\n\
1762 \t-I length TCP receive buffer length\n\
1763 \t-i interval Delay interval for lines sent, ports scanned\n\
1764 \t-K keyfile Private key file\n\
1765 \t-k Keep inbound sockets open for multiple connects\n\
1766 \t-l Listen mode, for inbound connects\n\
1767 \t-M ttl Outgoing TTL / Hop Limit\n\
1768 \t-m minttl Minimum incoming TTL / Hop Limit\n\
1769 \t-N Shutdown the network socket after EOF on stdin\n\
1770 \t-n Suppress name/port resolutions\n\
1771 \t-O length TCP send buffer length\n\
1772 \t-o staplefile Staple file\n\
1773 \t-P proxyuser\tUsername for proxy authentication\n\
1774 \t-p port\t Specify local port for remote connects\n\
1775 \t-R CAfile CA bundle\n\
1776 \t-r Randomize remote ports\n"
1777 #ifdef TCP_MD5SIG
1779 \t-S Enable the TCP MD5 signature option\n"
1780 #endif
1782 \t-s source Local source address\n\
1783 \t-T keyword TOS value or TLS options\n\
1784 \t-t Answer TELNET negotiation\n\
1785 \t-U Use UNIX domain socket\n\
1786 \t-u UDP mode\n"
1787 #ifdef SO_RTABLE
1789 \t-V rtable Specify alternate routing table\n"
1790 #endif
1792 \t-v Verbose\n\
1793 \t-W recvlimit Terminate after receiving a number of packets\n\
1794 \t-w timeout Timeout for connects and final net reads\n\
1795 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1796 \t-x addr[:port]\tSpecify proxy address and port\n\
1797 \t-Z Peer certificate file\n\
1798 \t-z Zero-I/O mode [used for scanning]\n\
1799 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1800 exit(1);
1803 void
1804 usage(int ret)
1806 fprintf(stderr,
1807 "usage: nc [-46cDdFhklNnrStUuvz] [-C certfile] [-e name] "
1808 "[-H hash] [-I length]\n"
1809 "\t [-i interval] [-K keyfile] [-M ttl] [-m minttl] [-O length]\n"
1810 "\t [-o staplefile] [-P proxy_username] [-p source_port] "
1811 "[-R CAfile]\n"
1812 "\t [-s source] [-T keyword] [-V rtable] [-W recvlimit] "
1813 "[-w timeout]\n"
1814 "\t [-X proxy_protocol] [-x proxy_address[:port]] "
1815 "[-Z peercertfile]\n"
1816 "\t [destination] [port]\n");
1817 if (ret)
1818 exit(1);