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