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