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