1 /* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl Exp $ */ 2 /* 3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org> 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 3. The name of the author may not be used to endorse or promote products 15 * derived from this software without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 * 28 * $FreeBSD$ 29 */ 30 31 /* 32 * Re-written nc(1) for OpenBSD. Original implementation by 33 * *Hobbit* <hobbit@avian.org>. 34 */ 35 36 #include <sys/limits.h> 37 #include <sys/types.h> 38 #include <sys/socket.h> 39 #include <sys/sysctl.h> 40 #include <sys/time.h> 41 #include <sys/uio.h> 42 #include <sys/un.h> 43 44 #include <netinet/in.h> 45 #ifdef IPSEC 46 #include <netipsec/ipsec.h> 47 #endif 48 #include <netinet/tcp.h> 49 #include <netinet/ip.h> 50 #include <arpa/telnet.h> 51 52 #include <err.h> 53 #include <errno.h> 54 #include <getopt.h> 55 #include <fcntl.h> 56 #include <limits.h> 57 #include <netdb.h> 58 #include <poll.h> 59 #include <signal.h> 60 #include <stdarg.h> 61 #include <stdio.h> 62 #include <stdlib.h> 63 #include <string.h> 64 #include <unistd.h> 65 #include "atomicio.h" 66 67 #ifndef SUN_LEN 68 #define SUN_LEN(su) \ 69 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path)) 70 #endif 71 72 #define PORT_MAX 65535 73 #define PORT_MAX_LEN 6 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 82 /* Command Line Options */ 83 int dflag; /* detached, no stdin */ 84 int Fflag; /* fdpass sock to stdout */ 85 unsigned int iflag; /* Interval Flag */ 86 int kflag; /* More than one connect */ 87 int lflag; /* Bind to local port */ 88 int Nflag; /* shutdown() network socket */ 89 int nflag; /* Don't do name look up */ 90 int FreeBSD_Oflag; /* Do not use TCP options */ 91 char *Pflag; /* Proxy username */ 92 char *pflag; /* Localport flag */ 93 int rflag; /* Random ports flag */ 94 char *sflag; /* Source Address */ 95 int tflag; /* Telnet Emulation */ 96 int uflag; /* UDP - Default to TCP */ 97 int vflag; /* Verbosity */ 98 int xflag; /* Socks proxy */ 99 int zflag; /* Port Scan Flag */ 100 int Dflag; /* sodebug */ 101 int Iflag; /* TCP receive buffer size */ 102 int Oflag; /* TCP send buffer size */ 103 int Sflag; /* TCP MD5 signature option */ 104 int Tflag = -1; /* IP Type of Service */ 105 int rtableid = -1; 106 107 int timeout = -1; 108 int family = AF_UNSPEC; 109 char *portlist[PORT_MAX+1]; 110 char *unix_dg_tmp_socket; 111 112 void atelnet(int, unsigned char *, unsigned int); 113 void build_ports(char *); 114 void help(void); 115 int local_listen(char *, char *, struct addrinfo); 116 void readwrite(int); 117 void fdpass(int nfd) __attribute__((noreturn)); 118 int remote_connect(const char *, const char *, struct addrinfo); 119 int timeout_connect(int, const struct sockaddr *, socklen_t); 120 int socks_connect(const char *, const char *, struct addrinfo, 121 const char *, const char *, struct addrinfo, int, const char *); 122 int udptest(int); 123 int unix_bind(char *); 124 int unix_connect(char *); 125 int unix_listen(char *); 126 void set_common_sockopts(int, int); 127 int map_tos(char *, int *); 128 void report_connect(const struct sockaddr *, socklen_t); 129 void usage(int); 130 ssize_t drainbuf(int, unsigned char *, size_t *); 131 ssize_t fillbuf(int, unsigned char *, size_t *); 132 133 #ifdef IPSEC 134 void add_ipsec_policy(int, int, char *); 135 136 char *ipsec_policy[2]; 137 #endif 138 139 int 140 main(int argc, char *argv[]) 141 { 142 int ch, s, ret, socksv, ipsec_count; 143 int numfibs; 144 size_t intsize = sizeof(int); 145 char *host, *uport; 146 struct addrinfo hints; 147 struct servent *sv; 148 socklen_t len; 149 struct sockaddr_storage cliaddr; 150 char *proxy; 151 const char *errstr, *proxyhost = "", *proxyport = NULL; 152 struct addrinfo proxyhints; 153 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE]; 154 struct option longopts[] = { 155 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 }, 156 { NULL, 0, NULL, 0 } 157 }; 158 159 ret = 1; 160 ipsec_count = 0; 161 s = 0; 162 socksv = 5; 163 host = NULL; 164 uport = NULL; 165 sv = NULL; 166 167 signal(SIGPIPE, SIG_IGN); 168 169 while ((ch = getopt_long(argc, argv, 170 "46DdEe:FhI:i:klNnoO:P:p:rSs:tT:UuV:vw:X:x:z", 171 longopts, NULL)) != -1) { 172 switch (ch) { 173 case '4': 174 family = AF_INET; 175 break; 176 case '6': 177 family = AF_INET6; 178 break; 179 case 'U': 180 family = AF_UNIX; 181 break; 182 case 'X': 183 if (strcasecmp(optarg, "connect") == 0) 184 socksv = -1; /* HTTP proxy CONNECT */ 185 else if (strcmp(optarg, "4") == 0) 186 socksv = 4; /* SOCKS v.4 */ 187 else if (strcmp(optarg, "5") == 0) 188 socksv = 5; /* SOCKS v.5 */ 189 else 190 errx(1, "unsupported proxy protocol"); 191 break; 192 case 'd': 193 dflag = 1; 194 break; 195 case 'e': 196 #ifdef IPSEC 197 ipsec_policy[ipsec_count++ % 2] = optarg; 198 #else 199 errx(1, "IPsec support unavailable."); 200 #endif 201 break; 202 case 'E': 203 #ifdef IPSEC 204 ipsec_policy[0] = "in ipsec esp/transport//require"; 205 ipsec_policy[1] = "out ipsec esp/transport//require"; 206 #else 207 errx(1, "IPsec support unavailable."); 208 #endif 209 break; 210 case 'F': 211 Fflag = 1; 212 break; 213 case 'h': 214 help(); 215 break; 216 case 'i': 217 iflag = strtonum(optarg, 0, UINT_MAX, &errstr); 218 if (errstr) 219 errx(1, "interval %s: %s", errstr, optarg); 220 break; 221 case 'k': 222 kflag = 1; 223 break; 224 case 'l': 225 lflag = 1; 226 break; 227 case 'N': 228 Nflag = 1; 229 break; 230 case 'n': 231 nflag = 1; 232 break; 233 case 'o': 234 fprintf(stderr, "option -o is deprecated.\n"); 235 break; 236 case 'P': 237 Pflag = optarg; 238 break; 239 case 'p': 240 pflag = optarg; 241 break; 242 case 'r': 243 rflag = 1; 244 break; 245 case 's': 246 sflag = optarg; 247 break; 248 case 't': 249 tflag = 1; 250 break; 251 case 'u': 252 uflag = 1; 253 break; 254 case 'V': 255 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1) 256 errx(1, "Multiple FIBS not supported"); 257 rtableid = (int)strtonum(optarg, 0, 258 numfibs - 1, &errstr); 259 if (errstr) 260 errx(1, "rtable %s: %s", errstr, optarg); 261 break; 262 case 'v': 263 vflag = 1; 264 break; 265 case 'w': 266 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr); 267 if (errstr) 268 errx(1, "timeout %s: %s", errstr, optarg); 269 timeout *= 1000; 270 break; 271 case 'x': 272 xflag = 1; 273 if ((proxy = strdup(optarg)) == NULL) 274 err(1, NULL); 275 break; 276 case 'z': 277 zflag = 1; 278 break; 279 case 'D': 280 Dflag = 1; 281 break; 282 case 'I': 283 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr); 284 if (errstr != NULL) 285 errx(1, "TCP receive window %s: %s", 286 errstr, optarg); 287 break; 288 case 'O': 289 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr); 290 if (errstr != NULL) { 291 if (strcmp(errstr, "invalid") != 0) 292 errx(1, "TCP send window %s: %s", 293 errstr, optarg); 294 } 295 break; 296 case 'S': 297 Sflag = 1; 298 break; 299 case 'T': 300 errstr = NULL; 301 errno = 0; 302 if (map_tos(optarg, &Tflag)) 303 break; 304 if (strlen(optarg) > 1 && optarg[0] == '0' && 305 optarg[1] == 'x') 306 Tflag = (int)strtol(optarg, NULL, 16); 307 else 308 Tflag = (int)strtonum(optarg, 0, 255, 309 &errstr); 310 if (Tflag < 0 || Tflag > 255 || errstr || errno) 311 errx(1, "illegal tos value %s", optarg); 312 break; 313 default: 314 usage(1); 315 } 316 } 317 argc -= optind; 318 argv += optind; 319 320 /* Cruft to make sure options are clean, and used properly. */ 321 if (argv[0] && !argv[1] && family == AF_UNIX) { 322 host = argv[0]; 323 uport = NULL; 324 } else if (argv[0] && !argv[1]) { 325 if (!lflag) 326 usage(1); 327 uport = argv[0]; 328 host = NULL; 329 } else if (argv[0] && argv[1]) { 330 host = argv[0]; 331 uport = argv[1]; 332 } else 333 usage(1); 334 335 if (lflag && sflag) 336 errx(1, "cannot use -s and -l"); 337 if (lflag && pflag) 338 errx(1, "cannot use -p and -l"); 339 if (lflag && zflag) 340 errx(1, "cannot use -z and -l"); 341 if (!lflag && kflag) 342 errx(1, "must use -l with -k"); 343 344 /* Get name of temporary socket for unix datagram client */ 345 if ((family == AF_UNIX) && uflag && !lflag) { 346 if (sflag) { 347 unix_dg_tmp_socket = sflag; 348 } else { 349 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX", 350 UNIX_DG_TMP_SOCKET_SIZE); 351 if (mktemp(unix_dg_tmp_socket_buf) == NULL) 352 err(1, "mktemp"); 353 unix_dg_tmp_socket = unix_dg_tmp_socket_buf; 354 } 355 } 356 357 /* Initialize addrinfo structure. */ 358 if (family != AF_UNIX) { 359 memset(&hints, 0, sizeof(struct addrinfo)); 360 hints.ai_family = family; 361 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM; 362 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP; 363 if (nflag) 364 hints.ai_flags |= AI_NUMERICHOST; 365 } 366 367 if (xflag) { 368 if (uflag) 369 errx(1, "no proxy support for UDP mode"); 370 371 if (lflag) 372 errx(1, "no proxy support for listen"); 373 374 if (family == AF_UNIX) 375 errx(1, "no proxy support for unix sockets"); 376 377 /* XXX IPv6 transport to proxy would probably work */ 378 if (family == AF_INET6) 379 errx(1, "no proxy support for IPv6"); 380 381 if (sflag) 382 errx(1, "no proxy support for local source address"); 383 384 proxyhost = strsep(&proxy, ":"); 385 proxyport = proxy; 386 387 memset(&proxyhints, 0, sizeof(struct addrinfo)); 388 proxyhints.ai_family = family; 389 proxyhints.ai_socktype = SOCK_STREAM; 390 proxyhints.ai_protocol = IPPROTO_TCP; 391 if (nflag) 392 proxyhints.ai_flags |= AI_NUMERICHOST; 393 } 394 395 if (lflag) { 396 int connfd; 397 ret = 0; 398 399 if (family == AF_UNIX) { 400 if (uflag) 401 s = unix_bind(host); 402 else 403 s = unix_listen(host); 404 } 405 406 /* Allow only one connection at a time, but stay alive. */ 407 for (;;) { 408 if (family != AF_UNIX) 409 s = local_listen(host, uport, hints); 410 if (s < 0) 411 err(1, NULL); 412 /* 413 * For UDP and -k, don't connect the socket, let it 414 * receive datagrams from multiple socket pairs. 415 */ 416 if (uflag && kflag) 417 readwrite(s); 418 /* 419 * For UDP and not -k, we will use recvfrom() initially 420 * to wait for a caller, then use the regular functions 421 * to talk to the caller. 422 */ 423 else if (uflag && !kflag) { 424 int rv, plen; 425 char buf[16384]; 426 struct sockaddr_storage z; 427 428 len = sizeof(z); 429 plen = 2048; 430 rv = recvfrom(s, buf, plen, MSG_PEEK, 431 (struct sockaddr *)&z, &len); 432 if (rv < 0) 433 err(1, "recvfrom"); 434 435 rv = connect(s, (struct sockaddr *)&z, len); 436 if (rv < 0) 437 err(1, "connect"); 438 439 if (vflag) 440 report_connect((struct sockaddr *)&z, len); 441 442 readwrite(s); 443 } else { 444 len = sizeof(cliaddr); 445 connfd = accept(s, (struct sockaddr *)&cliaddr, 446 &len); 447 if (connfd == -1) { 448 /* For now, all errnos are fatal */ 449 err(1, "accept"); 450 } 451 if (vflag) 452 report_connect((struct sockaddr *)&cliaddr, len); 453 454 readwrite(connfd); 455 close(connfd); 456 } 457 458 if (family != AF_UNIX) 459 close(s); 460 else if (uflag) { 461 if (connect(s, NULL, 0) < 0) 462 err(1, "connect"); 463 } 464 465 if (!kflag) 466 break; 467 } 468 } else if (family == AF_UNIX) { 469 ret = 0; 470 471 if ((s = unix_connect(host)) > 0 && !zflag) { 472 readwrite(s); 473 close(s); 474 } else 475 ret = 1; 476 477 if (uflag) 478 unlink(unix_dg_tmp_socket); 479 exit(ret); 480 481 } else { 482 int i = 0; 483 484 /* Construct the portlist[] array. */ 485 build_ports(uport); 486 487 /* Cycle through portlist, connecting to each port. */ 488 for (i = 0; portlist[i] != NULL; i++) { 489 if (s) 490 close(s); 491 492 if (xflag) 493 s = socks_connect(host, portlist[i], hints, 494 proxyhost, proxyport, proxyhints, socksv, 495 Pflag); 496 else 497 s = remote_connect(host, portlist[i], hints); 498 499 if (s < 0) 500 continue; 501 502 ret = 0; 503 if (vflag || zflag) { 504 /* For UDP, make sure we are connected. */ 505 if (uflag) { 506 if (udptest(s) == -1) { 507 ret = 1; 508 continue; 509 } 510 } 511 512 /* Don't look up port if -n. */ 513 if (nflag) 514 sv = NULL; 515 else { 516 sv = getservbyport( 517 ntohs(atoi(portlist[i])), 518 uflag ? "udp" : "tcp"); 519 } 520 521 fprintf(stderr, 522 "Connection to %s %s port [%s/%s] " 523 "succeeded!\n", host, portlist[i], 524 uflag ? "udp" : "tcp", 525 sv ? sv->s_name : "*"); 526 } 527 if (Fflag) 528 fdpass(s); 529 else if (!zflag) 530 readwrite(s); 531 } 532 } 533 534 if (s) 535 close(s); 536 537 exit(ret); 538 } 539 540 /* 541 * unix_bind() 542 * Returns a unix socket bound to the given path 543 */ 544 int 545 unix_bind(char *path) 546 { 547 struct sockaddr_un sun; 548 int s; 549 550 /* Create unix domain socket. */ 551 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM, 552 0)) < 0) 553 return (-1); 554 555 memset(&sun, 0, sizeof(struct sockaddr_un)); 556 sun.sun_family = AF_UNIX; 557 558 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >= 559 sizeof(sun.sun_path)) { 560 close(s); 561 errno = ENAMETOOLONG; 562 return (-1); 563 } 564 565 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) { 566 close(s); 567 return (-1); 568 } 569 return (s); 570 } 571 572 /* 573 * unix_connect() 574 * Returns a socket connected to a local unix socket. Returns -1 on failure. 575 */ 576 int 577 unix_connect(char *path) 578 { 579 struct sockaddr_un sun; 580 int s; 581 582 if (uflag) { 583 if ((s = unix_bind(unix_dg_tmp_socket)) < 0) 584 return (-1); 585 } else { 586 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) 587 return (-1); 588 } 589 (void)fcntl(s, F_SETFD, FD_CLOEXEC); 590 591 memset(&sun, 0, sizeof(struct sockaddr_un)); 592 sun.sun_family = AF_UNIX; 593 594 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >= 595 sizeof(sun.sun_path)) { 596 close(s); 597 errno = ENAMETOOLONG; 598 return (-1); 599 } 600 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) { 601 close(s); 602 return (-1); 603 } 604 return (s); 605 606 } 607 608 /* 609 * unix_listen() 610 * Create a unix domain socket, and listen on it. 611 */ 612 int 613 unix_listen(char *path) 614 { 615 int s; 616 if ((s = unix_bind(path)) < 0) 617 return (-1); 618 619 if (listen(s, 5) < 0) { 620 close(s); 621 return (-1); 622 } 623 return (s); 624 } 625 626 /* 627 * remote_connect() 628 * Returns a socket connected to a remote host. Properly binds to a local 629 * port or source address if needed. Returns -1 on failure. 630 */ 631 int 632 remote_connect(const char *host, const char *port, struct addrinfo hints) 633 { 634 struct addrinfo *res, *res0; 635 int s, error, on = 1; 636 637 if ((error = getaddrinfo(host, port, &hints, &res))) 638 errx(1, "getaddrinfo: %s", gai_strerror(error)); 639 640 res0 = res; 641 do { 642 if ((s = socket(res0->ai_family, res0->ai_socktype, 643 res0->ai_protocol)) < 0) 644 continue; 645 646 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB, 647 &rtableid, sizeof(rtableid)) == -1)) 648 err(1, "setsockopt SO_SETFIB"); 649 650 /* Bind to a local port or source address if specified. */ 651 if (sflag || pflag) { 652 struct addrinfo ahints, *ares; 653 654 /* try IP_BINDANY, but don't insist */ 655 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on)); 656 memset(&ahints, 0, sizeof(struct addrinfo)); 657 ahints.ai_family = res0->ai_family; 658 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM; 659 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP; 660 ahints.ai_flags = AI_PASSIVE; 661 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares))) 662 errx(1, "getaddrinfo: %s", gai_strerror(error)); 663 664 if (bind(s, (struct sockaddr *)ares->ai_addr, 665 ares->ai_addrlen) < 0) 666 err(1, "bind failed"); 667 freeaddrinfo(ares); 668 } 669 670 set_common_sockopts(s, res0->ai_family); 671 672 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0) 673 break; 674 else if (vflag) 675 warn("connect to %s port %s (%s) failed", host, port, 676 uflag ? "udp" : "tcp"); 677 678 close(s); 679 s = -1; 680 } while ((res0 = res0->ai_next) != NULL); 681 682 freeaddrinfo(res); 683 684 return (s); 685 } 686 687 int 688 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen) 689 { 690 struct pollfd pfd; 691 socklen_t optlen; 692 int flags, optval; 693 int ret; 694 695 if (timeout != -1) { 696 flags = fcntl(s, F_GETFL, 0); 697 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1) 698 err(1, "set non-blocking mode"); 699 } 700 701 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) { 702 pfd.fd = s; 703 pfd.events = POLLOUT; 704 if ((ret = poll(&pfd, 1, timeout)) == 1) { 705 optlen = sizeof(optval); 706 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR, 707 &optval, &optlen)) == 0) { 708 errno = optval; 709 ret = optval == 0 ? 0 : -1; 710 } 711 } else if (ret == 0) { 712 errno = ETIMEDOUT; 713 ret = -1; 714 } else 715 err(1, "poll failed"); 716 } 717 718 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1) 719 err(1, "restoring flags"); 720 721 return (ret); 722 } 723 724 /* 725 * local_listen() 726 * Returns a socket listening on a local port, binds to specified source 727 * address. Returns -1 on failure. 728 */ 729 int 730 local_listen(char *host, char *port, struct addrinfo hints) 731 { 732 struct addrinfo *res, *res0; 733 int s, ret, x = 1; 734 int error; 735 736 /* Allow nodename to be null. */ 737 hints.ai_flags |= AI_PASSIVE; 738 739 /* 740 * In the case of binding to a wildcard address 741 * default to binding to an ipv4 address. 742 */ 743 if (host == NULL && hints.ai_family == AF_UNSPEC) 744 hints.ai_family = AF_INET; 745 746 if ((error = getaddrinfo(host, port, &hints, &res))) 747 errx(1, "getaddrinfo: %s", gai_strerror(error)); 748 749 res0 = res; 750 do { 751 if ((s = socket(res0->ai_family, res0->ai_socktype, 752 res0->ai_protocol)) < 0) 753 continue; 754 755 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB, 756 &rtableid, sizeof(rtableid)) == -1)) 757 err(1, "setsockopt SO_SETFIB"); 758 759 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x)); 760 if (ret == -1) 761 err(1, NULL); 762 763 if (FreeBSD_Oflag) { 764 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT, 765 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1) 766 err(1, "disable TCP options"); 767 } 768 769 set_common_sockopts(s, res0->ai_family); 770 771 if (bind(s, (struct sockaddr *)res0->ai_addr, 772 res0->ai_addrlen) == 0) 773 break; 774 775 close(s); 776 s = -1; 777 } while ((res0 = res0->ai_next) != NULL); 778 779 if (!uflag && s != -1) { 780 if (listen(s, 1) < 0) 781 err(1, "listen"); 782 } 783 784 freeaddrinfo(res); 785 786 return (s); 787 } 788 789 /* 790 * readwrite() 791 * Loop that polls on the network file descriptor and stdin. 792 */ 793 void 794 readwrite(int net_fd) 795 { 796 struct pollfd pfd[4]; 797 int stdin_fd = STDIN_FILENO; 798 int stdout_fd = STDOUT_FILENO; 799 unsigned char netinbuf[BUFSIZE]; 800 size_t netinbufpos = 0; 801 unsigned char stdinbuf[BUFSIZE]; 802 size_t stdinbufpos = 0; 803 int n, num_fds; 804 ssize_t ret; 805 806 /* don't read from stdin if requested */ 807 if (dflag) 808 stdin_fd = -1; 809 810 /* stdin */ 811 pfd[POLL_STDIN].fd = stdin_fd; 812 pfd[POLL_STDIN].events = POLLIN; 813 814 /* network out */ 815 pfd[POLL_NETOUT].fd = net_fd; 816 pfd[POLL_NETOUT].events = 0; 817 818 /* network in */ 819 pfd[POLL_NETIN].fd = net_fd; 820 pfd[POLL_NETIN].events = POLLIN; 821 822 /* stdout */ 823 pfd[POLL_STDOUT].fd = stdout_fd; 824 pfd[POLL_STDOUT].events = 0; 825 826 while (1) { 827 /* both inputs are gone, buffers are empty, we are done */ 828 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 829 && stdinbufpos == 0 && netinbufpos == 0) { 830 close(net_fd); 831 return; 832 } 833 /* both outputs are gone, we can't continue */ 834 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) { 835 close(net_fd); 836 return; 837 } 838 /* listen and net in gone, queues empty, done */ 839 if (lflag && pfd[POLL_NETIN].fd == -1 840 && stdinbufpos == 0 && netinbufpos == 0) { 841 close(net_fd); 842 return; 843 } 844 845 /* help says -i is for "wait between lines sent". We read and 846 * write arbitrary amounts of data, and we don't want to start 847 * scanning for newlines, so this is as good as it gets */ 848 if (iflag) 849 sleep(iflag); 850 851 /* poll */ 852 num_fds = poll(pfd, 4, timeout); 853 854 /* treat poll errors */ 855 if (num_fds == -1) { 856 close(net_fd); 857 err(1, "polling error"); 858 } 859 860 /* timeout happened */ 861 if (num_fds == 0) 862 return; 863 864 /* treat socket error conditions */ 865 for (n = 0; n < 4; n++) { 866 if (pfd[n].revents & (POLLERR|POLLNVAL)) { 867 pfd[n].fd = -1; 868 } 869 } 870 /* reading is possible after HUP */ 871 if (pfd[POLL_STDIN].events & POLLIN && 872 pfd[POLL_STDIN].revents & POLLHUP && 873 ! (pfd[POLL_STDIN].revents & POLLIN)) 874 pfd[POLL_STDIN].fd = -1; 875 876 if (pfd[POLL_NETIN].events & POLLIN && 877 pfd[POLL_NETIN].revents & POLLHUP && 878 ! (pfd[POLL_NETIN].revents & POLLIN)) 879 pfd[POLL_NETIN].fd = -1; 880 881 if (pfd[POLL_NETOUT].revents & POLLHUP) { 882 if (Nflag) 883 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR); 884 pfd[POLL_NETOUT].fd = -1; 885 } 886 /* if HUP, stop watching stdout */ 887 if (pfd[POLL_STDOUT].revents & POLLHUP) 888 pfd[POLL_STDOUT].fd = -1; 889 /* if no net out, stop watching stdin */ 890 if (pfd[POLL_NETOUT].fd == -1) 891 pfd[POLL_STDIN].fd = -1; 892 /* if no stdout, stop watching net in */ 893 if (pfd[POLL_STDOUT].fd == -1) { 894 if (pfd[POLL_NETIN].fd != -1) 895 shutdown(pfd[POLL_NETIN].fd, SHUT_RD); 896 pfd[POLL_NETIN].fd = -1; 897 } 898 899 /* try to read from stdin */ 900 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) { 901 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf, 902 &stdinbufpos); 903 /* error or eof on stdin - remove from pfd */ 904 if (ret == 0 || ret == -1) 905 pfd[POLL_STDIN].fd = -1; 906 /* read something - poll net out */ 907 if (stdinbufpos > 0) 908 pfd[POLL_NETOUT].events = POLLOUT; 909 /* filled buffer - remove self from polling */ 910 if (stdinbufpos == BUFSIZE) 911 pfd[POLL_STDIN].events = 0; 912 } 913 /* try to write to network */ 914 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) { 915 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf, 916 &stdinbufpos); 917 if (ret == -1) 918 pfd[POLL_NETOUT].fd = -1; 919 /* buffer empty - remove self from polling */ 920 if (stdinbufpos == 0) 921 pfd[POLL_NETOUT].events = 0; 922 /* buffer no longer full - poll stdin again */ 923 if (stdinbufpos < BUFSIZE) 924 pfd[POLL_STDIN].events = POLLIN; 925 } 926 /* try to read from network */ 927 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) { 928 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf, 929 &netinbufpos); 930 if (ret == -1) 931 pfd[POLL_NETIN].fd = -1; 932 /* eof on net in - remove from pfd */ 933 if (ret == 0) { 934 shutdown(pfd[POLL_NETIN].fd, SHUT_RD); 935 pfd[POLL_NETIN].fd = -1; 936 } 937 /* read something - poll stdout */ 938 if (netinbufpos > 0) 939 pfd[POLL_STDOUT].events = POLLOUT; 940 /* filled buffer - remove self from polling */ 941 if (netinbufpos == BUFSIZE) 942 pfd[POLL_NETIN].events = 0; 943 /* handle telnet */ 944 if (tflag) 945 atelnet(pfd[POLL_NETIN].fd, netinbuf, 946 netinbufpos); 947 } 948 /* try to write to stdout */ 949 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) { 950 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf, 951 &netinbufpos); 952 if (ret == -1) 953 pfd[POLL_STDOUT].fd = -1; 954 /* buffer empty - remove self from polling */ 955 if (netinbufpos == 0) 956 pfd[POLL_STDOUT].events = 0; 957 /* buffer no longer full - poll net in again */ 958 if (netinbufpos < BUFSIZE) 959 pfd[POLL_NETIN].events = POLLIN; 960 } 961 962 /* stdin gone and queue empty? */ 963 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) { 964 if (pfd[POLL_NETOUT].fd != -1 && Nflag) 965 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR); 966 pfd[POLL_NETOUT].fd = -1; 967 } 968 /* net in gone and queue empty? */ 969 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) { 970 pfd[POLL_STDOUT].fd = -1; 971 } 972 } 973 } 974 975 ssize_t 976 drainbuf(int fd, unsigned char *buf, size_t *bufpos) 977 { 978 ssize_t n; 979 ssize_t adjust; 980 981 n = write(fd, buf, *bufpos); 982 /* don't treat EAGAIN, EINTR as error */ 983 if (n == -1 && (errno == EAGAIN || errno == EINTR)) 984 n = -2; 985 if (n <= 0) 986 return n; 987 /* adjust buffer */ 988 adjust = *bufpos - n; 989 if (adjust > 0) 990 memmove(buf, buf + n, adjust); 991 *bufpos -= n; 992 return n; 993 } 994 995 996 ssize_t 997 fillbuf(int fd, unsigned char *buf, size_t *bufpos) 998 { 999 size_t num = BUFSIZE - *bufpos; 1000 ssize_t n; 1001 1002 n = read(fd, buf + *bufpos, num); 1003 /* don't treat EAGAIN, EINTR as error */ 1004 if (n == -1 && (errno == EAGAIN || errno == EINTR)) 1005 n = -2; 1006 if (n <= 0) 1007 return n; 1008 *bufpos += n; 1009 return n; 1010 } 1011 1012 /* 1013 * fdpass() 1014 * Pass the connected file descriptor to stdout and exit. 1015 */ 1016 void 1017 fdpass(int nfd) 1018 { 1019 struct msghdr mh; 1020 union { 1021 struct cmsghdr hdr; 1022 char buf[CMSG_SPACE(sizeof(int))]; 1023 } cmsgbuf; 1024 struct cmsghdr *cmsg; 1025 struct iovec iov; 1026 char c = '\0'; 1027 ssize_t r; 1028 struct pollfd pfd; 1029 1030 /* Avoid obvious stupidity */ 1031 if (isatty(STDOUT_FILENO)) 1032 errx(1, "Cannot pass file descriptor to tty"); 1033 1034 bzero(&mh, sizeof(mh)); 1035 bzero(&cmsgbuf, sizeof(cmsgbuf)); 1036 bzero(&iov, sizeof(iov)); 1037 1038 mh.msg_control = (caddr_t)&cmsgbuf.buf; 1039 mh.msg_controllen = sizeof(cmsgbuf.buf); 1040 cmsg = CMSG_FIRSTHDR(&mh); 1041 cmsg->cmsg_len = CMSG_LEN(sizeof(int)); 1042 cmsg->cmsg_level = SOL_SOCKET; 1043 cmsg->cmsg_type = SCM_RIGHTS; 1044 *(int *)CMSG_DATA(cmsg) = nfd; 1045 1046 iov.iov_base = &c; 1047 iov.iov_len = 1; 1048 mh.msg_iov = &iov; 1049 mh.msg_iovlen = 1; 1050 1051 bzero(&pfd, sizeof(pfd)); 1052 pfd.fd = STDOUT_FILENO; 1053 pfd.events = POLLOUT; 1054 for (;;) { 1055 r = sendmsg(STDOUT_FILENO, &mh, 0); 1056 if (r == -1) { 1057 if (errno == EAGAIN || errno == EINTR) { 1058 if (poll(&pfd, 1, -1) == -1) 1059 err(1, "poll"); 1060 continue; 1061 } 1062 err(1, "sendmsg"); 1063 } else if (r != 1) 1064 errx(1, "sendmsg: unexpected return value %zd", r); 1065 else 1066 break; 1067 } 1068 exit(0); 1069 } 1070 1071 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */ 1072 void 1073 atelnet(int nfd, unsigned char *buf, unsigned int size) 1074 { 1075 unsigned char *p, *end; 1076 unsigned char obuf[4]; 1077 1078 if (size < 3) 1079 return; 1080 end = buf + size - 2; 1081 1082 for (p = buf; p < end; p++) { 1083 if (*p != IAC) 1084 continue; 1085 1086 obuf[0] = IAC; 1087 p++; 1088 if ((*p == WILL) || (*p == WONT)) 1089 obuf[1] = DONT; 1090 else if ((*p == DO) || (*p == DONT)) 1091 obuf[1] = WONT; 1092 else 1093 continue; 1094 1095 p++; 1096 obuf[2] = *p; 1097 if (atomicio(vwrite, nfd, obuf, 3) != 3) 1098 warn("Write Error!"); 1099 } 1100 } 1101 1102 /* 1103 * build_ports() 1104 * Build an array of ports in portlist[], listing each port 1105 * that we should try to connect to. 1106 */ 1107 void 1108 build_ports(char *p) 1109 { 1110 const char *errstr; 1111 char *n; 1112 int hi, lo, cp; 1113 int x = 0; 1114 1115 if ((n = strchr(p, '-')) != NULL) { 1116 *n = '\0'; 1117 n++; 1118 1119 /* Make sure the ports are in order: lowest->highest. */ 1120 hi = strtonum(n, 1, PORT_MAX, &errstr); 1121 if (errstr) 1122 errx(1, "port number %s: %s", errstr, n); 1123 lo = strtonum(p, 1, PORT_MAX, &errstr); 1124 if (errstr) 1125 errx(1, "port number %s: %s", errstr, p); 1126 1127 if (lo > hi) { 1128 cp = hi; 1129 hi = lo; 1130 lo = cp; 1131 } 1132 1133 /* Load ports sequentially. */ 1134 for (cp = lo; cp <= hi; cp++) { 1135 portlist[x] = calloc(1, PORT_MAX_LEN); 1136 if (portlist[x] == NULL) 1137 err(1, NULL); 1138 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp); 1139 x++; 1140 } 1141 1142 /* Randomly swap ports. */ 1143 if (rflag) { 1144 int y; 1145 char *c; 1146 1147 for (x = 0; x <= (hi - lo); x++) { 1148 y = (arc4random() & 0xFFFF) % (hi - lo); 1149 c = portlist[x]; 1150 portlist[x] = portlist[y]; 1151 portlist[y] = c; 1152 } 1153 } 1154 } else { 1155 hi = strtonum(p, 1, PORT_MAX, &errstr); 1156 if (errstr) 1157 errx(1, "port number %s: %s", errstr, p); 1158 portlist[0] = strdup(p); 1159 if (portlist[0] == NULL) 1160 err(1, NULL); 1161 } 1162 } 1163 1164 /* 1165 * udptest() 1166 * Do a few writes to see if the UDP port is there. 1167 * Fails once PF state table is full. 1168 */ 1169 int 1170 udptest(int s) 1171 { 1172 int i, ret; 1173 1174 for (i = 0; i <= 3; i++) { 1175 if (write(s, "X", 1) == 1) 1176 ret = 1; 1177 else 1178 ret = -1; 1179 } 1180 return (ret); 1181 } 1182 1183 void 1184 set_common_sockopts(int s, int af) 1185 { 1186 int x = 1; 1187 1188 if (Sflag) { 1189 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG, 1190 &x, sizeof(x)) == -1) 1191 err(1, NULL); 1192 } 1193 if (Dflag) { 1194 if (setsockopt(s, SOL_SOCKET, SO_DEBUG, 1195 &x, sizeof(x)) == -1) 1196 err(1, NULL); 1197 } 1198 if (Tflag != -1) { 1199 int proto, option; 1200 1201 if (af == AF_INET6) { 1202 proto = IPPROTO_IPV6; 1203 option = IPV6_TCLASS; 1204 } else { 1205 proto = IPPROTO_IP; 1206 option = IP_TOS; 1207 } 1208 1209 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1) 1210 err(1, "set IP ToS"); 1211 } 1212 if (Iflag) { 1213 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, 1214 &Iflag, sizeof(Iflag)) == -1) 1215 err(1, "set TCP receive buffer size"); 1216 } 1217 if (Oflag) { 1218 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, 1219 &Oflag, sizeof(Oflag)) == -1) 1220 err(1, "set TCP send buffer size"); 1221 } 1222 if (FreeBSD_Oflag) { 1223 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT, 1224 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1) 1225 err(1, "disable TCP options"); 1226 } 1227 #ifdef IPSEC 1228 if (ipsec_policy[0] != NULL) 1229 add_ipsec_policy(s, af, ipsec_policy[0]); 1230 if (ipsec_policy[1] != NULL) 1231 add_ipsec_policy(s, af, ipsec_policy[1]); 1232 #endif 1233 } 1234 1235 int 1236 map_tos(char *s, int *val) 1237 { 1238 /* DiffServ Codepoints and other TOS mappings */ 1239 const struct toskeywords { 1240 const char *keyword; 1241 int val; 1242 } *t, toskeywords[] = { 1243 { "af11", IPTOS_DSCP_AF11 }, 1244 { "af12", IPTOS_DSCP_AF12 }, 1245 { "af13", IPTOS_DSCP_AF13 }, 1246 { "af21", IPTOS_DSCP_AF21 }, 1247 { "af22", IPTOS_DSCP_AF22 }, 1248 { "af23", IPTOS_DSCP_AF23 }, 1249 { "af31", IPTOS_DSCP_AF31 }, 1250 { "af32", IPTOS_DSCP_AF32 }, 1251 { "af33", IPTOS_DSCP_AF33 }, 1252 { "af41", IPTOS_DSCP_AF41 }, 1253 { "af42", IPTOS_DSCP_AF42 }, 1254 { "af43", IPTOS_DSCP_AF43 }, 1255 { "critical", IPTOS_PREC_CRITIC_ECP }, 1256 { "cs0", IPTOS_DSCP_CS0 }, 1257 { "cs1", IPTOS_DSCP_CS1 }, 1258 { "cs2", IPTOS_DSCP_CS2 }, 1259 { "cs3", IPTOS_DSCP_CS3 }, 1260 { "cs4", IPTOS_DSCP_CS4 }, 1261 { "cs5", IPTOS_DSCP_CS5 }, 1262 { "cs6", IPTOS_DSCP_CS6 }, 1263 { "cs7", IPTOS_DSCP_CS7 }, 1264 { "ef", IPTOS_DSCP_EF }, 1265 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL }, 1266 { "lowdelay", IPTOS_LOWDELAY }, 1267 { "netcontrol", IPTOS_PREC_NETCONTROL }, 1268 { "reliability", IPTOS_RELIABILITY }, 1269 { "throughput", IPTOS_THROUGHPUT }, 1270 { NULL, -1 }, 1271 }; 1272 1273 for (t = toskeywords; t->keyword != NULL; t++) { 1274 if (strcmp(s, t->keyword) == 0) { 1275 *val = t->val; 1276 return (1); 1277 } 1278 } 1279 1280 return (0); 1281 } 1282 1283 void 1284 report_connect(const struct sockaddr *sa, socklen_t salen) 1285 { 1286 char remote_host[NI_MAXHOST]; 1287 char remote_port[NI_MAXSERV]; 1288 int herr; 1289 int flags = NI_NUMERICSERV; 1290 1291 if (nflag) 1292 flags |= NI_NUMERICHOST; 1293 1294 if ((herr = getnameinfo(sa, salen, 1295 remote_host, sizeof(remote_host), 1296 remote_port, sizeof(remote_port), 1297 flags)) != 0) { 1298 if (herr == EAI_SYSTEM) 1299 err(1, "getnameinfo"); 1300 else 1301 errx(1, "getnameinfo: %s", gai_strerror(herr)); 1302 } 1303 1304 fprintf(stderr, 1305 "Connection from %s %s " 1306 "received!\n", remote_host, remote_port); 1307 } 1308 1309 void 1310 help(void) 1311 { 1312 usage(0); 1313 fprintf(stderr, "\tCommand Summary:\n\ 1314 \t-4 Use IPv4\n\ 1315 \t-6 Use IPv6\n\ 1316 \t-D Enable the debug socket option\n\ 1317 \t-d Detach from stdin\n"); 1318 #ifdef IPSEC 1319 fprintf(stderr, "\ 1320 \t-E Use IPsec ESP\n\ 1321 \t-e policy Use specified IPsec policy\n"); 1322 #endif 1323 fprintf(stderr, "\ 1324 \t-F Pass socket fd\n\ 1325 \t-h This help text\n\ 1326 \t-I length TCP receive buffer length\n\ 1327 \t-i secs\t Delay interval for lines sent, ports scanned\n\ 1328 \t-k Keep inbound sockets open for multiple connects\n\ 1329 \t-l Listen mode, for inbound connects\n\ 1330 \t-N Shutdown the network socket after EOF on stdin\n\ 1331 \t-n Suppress name/port resolutions\n\ 1332 \t--no-tcpopt Disable TCP options\n\ 1333 \t-O length TCP send buffer length\n\ 1334 \t-P proxyuser\tUsername for proxy authentication\n\ 1335 \t-p port\t Specify local port for remote connects\n\ 1336 \t-r Randomize remote ports\n\ 1337 \t-S Enable the TCP MD5 signature option\n\ 1338 \t-s addr\t Local source address\n\ 1339 \t-T toskeyword\tSet IP Type of Service\n\ 1340 \t-t Answer TELNET negotiation\n\ 1341 \t-U Use UNIX domain socket\n\ 1342 \t-u UDP mode\n\ 1343 \t-V rtable Specify alternate routing table\n\ 1344 \t-v Verbose\n\ 1345 \t-w secs\t Timeout for connects and final net reads\n\ 1346 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\ 1347 \t-x addr[:port]\tSpecify proxy address and port\n\ 1348 \t-z Zero-I/O mode [used for scanning]\n\ 1349 Port numbers can be individual or ranges: lo-hi [inclusive]\n"); 1350 #ifdef IPSEC 1351 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n"); 1352 #endif 1353 exit(1); 1354 } 1355 1356 #ifdef IPSEC 1357 void 1358 add_ipsec_policy(int s, int af, char *policy) 1359 { 1360 char *raw; 1361 int e; 1362 1363 raw = ipsec_set_policy(policy, strlen(policy)); 1364 if (raw == NULL) 1365 errx(1, "ipsec_set_policy `%s': %s", policy, 1366 ipsec_strerror()); 1367 if (af == AF_INET) 1368 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw, 1369 ipsec_get_policylen(raw)); 1370 if (af == AF_INET6) 1371 e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw, 1372 ipsec_get_policylen(raw)); 1373 if (e < 0) 1374 err(1, "ipsec policy cannot be configured"); 1375 free(raw); 1376 if (vflag) 1377 fprintf(stderr, "ipsec policy configured: `%s'\n", policy); 1378 return; 1379 } 1380 #endif /* IPSEC */ 1381 1382 void 1383 usage(int ret) 1384 { 1385 fprintf(stderr, 1386 #ifdef IPSEC 1387 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n" 1388 #else 1389 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n" 1390 #endif 1391 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n" 1392 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n" 1393 "\t [-x proxy_address[:port]] [destination] [port]\n"); 1394 if (ret) 1395 exit(1); 1396 } 1397