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