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