1 /* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl Exp $ */
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
32 * Re-written nc(1) for OpenBSD. Original implementation by
33 * *Hobbit* <hobbit@avian.org>.
39 #include <sys/limits.h>
40 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <sys/sysctl.h>
44 #include <sys/qmath.h>
45 #include <sys/stats.h>
50 #include <netinet/in.h>
52 #include <netipsec/ipsec.h>
54 #include <netinet/tcp.h>
55 #include <netinet/ip.h>
56 #include <arpa/telnet.h>
73 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
76 #define PORT_MAX 65535
77 #define PORT_MAX_LEN 6
78 #define UNIX_DG_TMP_SOCKET_SIZE 19
86 /* Command Line Options */
87 int dflag; /* detached, no stdin */
88 int Fflag; /* fdpass sock to stdout */
89 unsigned int iflag; /* Interval Flag */
90 int kflag; /* More than one connect */
91 int lflag; /* Bind to local port */
92 int FreeBSD_Mflag; /* Measure using stats(3) */
93 int Nflag; /* shutdown() network socket */
94 int nflag; /* Don't do name look up */
95 int FreeBSD_Oflag; /* Do not use TCP options */
96 int FreeBSD_sctp; /* Use SCTP */
97 char *Pflag; /* Proxy username */
98 char *pflag; /* Localport flag */
99 int rflag; /* Random ports flag */
100 char *sflag; /* Source Address */
101 int tflag; /* Telnet Emulation */
102 int uflag; /* UDP - Default to TCP */
103 int vflag; /* Verbosity */
104 int xflag; /* Socks proxy */
105 int zflag; /* Port Scan Flag */
106 int Dflag; /* sodebug */
107 int Iflag; /* TCP receive buffer size */
108 int Oflag; /* TCP send buffer size */
109 int Sflag; /* TCP MD5 signature option */
110 int Tflag = -1; /* IP Type of Service */
114 int family = AF_UNSPEC;
115 char *portlist[PORT_MAX+1];
116 char *unix_dg_tmp_socket;
118 void atelnet(int, unsigned char *, unsigned int);
119 void build_ports(char *);
121 int local_listen(char *, char *, struct addrinfo);
123 void fdpass(int nfd) __attribute__((noreturn));
124 int remote_connect(const char *, const char *, struct addrinfo);
125 int timeout_connect(int, const struct sockaddr *, socklen_t);
126 int socks_connect(const char *, const char *, struct addrinfo,
127 const char *, const char *, struct addrinfo, int, const char *);
129 int unix_bind(char *);
130 int unix_connect(char *);
131 int unix_listen(char *);
132 void FreeBSD_stats_setup(int);
133 void FreeBSD_stats_print(int);
134 void set_common_sockopts(int, int);
135 int map_tos(char *, int *);
136 void report_connect(const struct sockaddr *, socklen_t);
138 ssize_t drainbuf(int, unsigned char *, size_t *);
139 ssize_t fillbuf(int, unsigned char *, size_t *);
142 void add_ipsec_policy(int, int, char *);
144 char *ipsec_policy[2];
148 main(int argc, char *argv[])
150 int ch, s, ret, socksv, ipsec_count;
152 size_t intsize = sizeof(int);
154 struct addrinfo hints;
157 struct sockaddr_storage cliaddr;
159 const char *errstr, *proxyhost = "", *proxyport = NULL;
160 struct addrinfo proxyhints;
161 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
162 struct option longopts[] = {
163 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
164 { "sctp", no_argument, &FreeBSD_sctp, 1 },
176 signal(SIGPIPE, SIG_IGN);
178 while ((ch = getopt_long(argc, argv,
179 "46DdEe:FhI:i:klMNnoO:P:p:rSs:tT:UuV:vw:X:x:z",
180 longopts, NULL)) != -1) {
192 if (strcasecmp(optarg, "connect") == 0)
193 socksv = -1; /* HTTP proxy CONNECT */
194 else if (strcmp(optarg, "4") == 0)
195 socksv = 4; /* SOCKS v.4 */
196 else if (strcmp(optarg, "5") == 0)
197 socksv = 5; /* SOCKS v.5 */
199 errx(1, "unsupported proxy protocol");
206 ipsec_policy[ipsec_count++ % 2] = optarg;
208 errx(1, "IPsec support unavailable.");
213 ipsec_policy[0] = "in ipsec esp/transport//require";
214 ipsec_policy[1] = "out ipsec esp/transport//require";
216 errx(1, "IPsec support unavailable.");
226 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
228 errx(1, "interval %s: %s", errstr, optarg);
238 errx(1, "-M requires stats(3) support");
250 fprintf(stderr, "option -o is deprecated.\n");
271 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
272 errx(1, "Multiple FIBS not supported");
273 rtableid = (int)strtonum(optarg, 0,
274 numfibs - 1, &errstr);
276 errx(1, "rtable %s: %s", errstr, optarg);
282 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
284 errx(1, "timeout %s: %s", errstr, optarg);
289 if ((proxy = strdup(optarg)) == NULL)
299 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
301 errx(1, "TCP receive window %s: %s",
305 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
306 if (errstr != NULL) {
307 if (strcmp(errstr, "invalid") != 0)
308 errx(1, "TCP send window %s: %s",
318 if (map_tos(optarg, &Tflag))
320 if (strlen(optarg) > 1 && optarg[0] == '0' &&
322 Tflag = (int)strtol(optarg, NULL, 16);
324 Tflag = (int)strtonum(optarg, 0, 255,
326 if (Tflag < 0 || Tflag > 255 || errstr || errno)
327 errx(1, "illegal tos value %s", optarg);
339 /* Cruft to make sure options are clean, and used properly. */
340 if (argv[0] && !argv[1] && family == AF_UNIX) {
343 } else if (argv[0] && !argv[1]) {
348 } else if (argv[0] && argv[1]) {
355 errx(1, "cannot use -s and -l");
357 errx(1, "cannot use -p and -l");
359 errx(1, "cannot use -z and -l");
361 errx(1, "must use -l with -k");
364 errx(1, "cannot use -u and --sctp");
365 if (family == AF_UNIX)
366 errx(1, "cannot use -U and --sctp");
369 /* Get name of temporary socket for unix datagram client */
370 if ((family == AF_UNIX) && uflag && !lflag) {
372 unix_dg_tmp_socket = sflag;
374 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
375 UNIX_DG_TMP_SOCKET_SIZE);
376 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
378 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
382 /* Initialize addrinfo structure. */
383 if (family != AF_UNIX) {
384 memset(&hints, 0, sizeof(struct addrinfo));
385 hints.ai_family = family;
386 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
387 hints.ai_protocol = uflag ? IPPROTO_UDP :
388 FreeBSD_sctp ? IPPROTO_SCTP : IPPROTO_TCP;
390 hints.ai_flags |= AI_NUMERICHOST;
395 errx(1, "no proxy support for UDP mode");
398 errx(1, "no proxy support for SCTP mode");
401 errx(1, "no proxy support for listen");
403 if (family == AF_UNIX)
404 errx(1, "no proxy support for unix sockets");
406 /* XXX IPv6 transport to proxy would probably work */
407 if (family == AF_INET6)
408 errx(1, "no proxy support for IPv6");
411 errx(1, "no proxy support for local source address");
413 proxyhost = strsep(&proxy, ":");
416 memset(&proxyhints, 0, sizeof(struct addrinfo));
417 proxyhints.ai_family = family;
418 proxyhints.ai_socktype = SOCK_STREAM;
419 proxyhints.ai_protocol = IPPROTO_TCP;
421 proxyhints.ai_flags |= AI_NUMERICHOST;
428 if (family == AF_UNIX) {
432 s = unix_listen(host);
435 /* Allow only one connection at a time, but stay alive. */
437 if (family != AF_UNIX)
438 s = local_listen(host, uport, hints);
442 * For UDP and -k, don't connect the socket, let it
443 * receive datagrams from multiple socket pairs.
448 * For UDP and not -k, we will use recvfrom() initially
449 * to wait for a caller, then use the regular functions
450 * to talk to the caller.
452 else if (uflag && !kflag) {
455 struct sockaddr_storage z;
459 rv = recvfrom(s, buf, plen, MSG_PEEK,
460 (struct sockaddr *)&z, &len);
464 rv = connect(s, (struct sockaddr *)&z, len);
469 report_connect((struct sockaddr *)&z, len);
473 len = sizeof(cliaddr);
474 connfd = accept(s, (struct sockaddr *)&cliaddr,
477 /* For now, all errnos are fatal */
481 report_connect((struct sockaddr *)&cliaddr, len);
484 FreeBSD_stats_setup(connfd);
489 if (family != AF_UNIX)
492 if (connect(s, NULL, 0) < 0)
499 } else if (family == AF_UNIX) {
502 if ((s = unix_connect(host)) > 0 && !zflag) {
509 unlink(unix_dg_tmp_socket);
515 /* Construct the portlist[] array. */
518 /* Cycle through portlist, connecting to each port. */
519 for (i = 0; portlist[i] != NULL; i++) {
524 s = socks_connect(host, portlist[i], hints,
525 proxyhost, proxyport, proxyhints, socksv,
528 s = remote_connect(host, portlist[i], hints);
534 if (vflag || zflag) {
535 /* For UDP, make sure we are connected. */
537 if (udptest(s) == -1) {
543 /* Don't look up port if -n. */
548 ntohs(atoi(portlist[i])),
549 uflag ? "udp" : "tcp");
553 "Connection to %s %s port [%s/%s] "
554 "succeeded!\n", host, portlist[i],
555 uflag ? "udp" : "tcp",
556 sv ? sv->s_name : "*");
573 * Returns a unix socket bound to the given path
576 unix_bind(char *path)
578 struct sockaddr_un sun;
581 /* Create unix domain socket. */
582 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
586 memset(&sun, 0, sizeof(struct sockaddr_un));
587 sun.sun_family = AF_UNIX;
589 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
590 sizeof(sun.sun_path)) {
592 errno = ENAMETOOLONG;
596 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
605 * Returns a socket connected to a local unix socket. Returns -1 on failure.
608 unix_connect(char *path)
610 struct sockaddr_un sun;
614 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
617 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
620 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
622 memset(&sun, 0, sizeof(struct sockaddr_un));
623 sun.sun_family = AF_UNIX;
625 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
626 sizeof(sun.sun_path)) {
628 errno = ENAMETOOLONG;
631 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
641 * Create a unix domain socket, and listen on it.
644 unix_listen(char *path)
647 if ((s = unix_bind(path)) < 0)
650 if (listen(s, 5) < 0) {
659 * Returns a socket connected to a remote host. Properly binds to a local
660 * port or source address if needed. Returns -1 on failure.
663 remote_connect(const char *host, const char *port, struct addrinfo hints)
665 struct addrinfo *res, *res0;
666 int s, error, on = 1;
668 if ((error = getaddrinfo(host, port, &hints, &res)))
669 errx(1, "getaddrinfo: %s", gai_strerror(error));
673 if ((s = socket(res0->ai_family, res0->ai_socktype,
674 res0->ai_protocol)) < 0)
677 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
678 &rtableid, sizeof(rtableid)) == -1))
679 err(1, "setsockopt SO_SETFIB");
681 /* Bind to a local port or source address if specified. */
682 if (sflag || pflag) {
683 struct addrinfo ahints, *ares;
685 /* try IP_BINDANY, but don't insist */
686 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
687 memset(&ahints, 0, sizeof(struct addrinfo));
688 ahints.ai_family = res0->ai_family;
689 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
690 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
691 ahints.ai_flags = AI_PASSIVE;
692 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
693 errx(1, "getaddrinfo: %s", gai_strerror(error));
695 if (bind(s, (struct sockaddr *)ares->ai_addr,
696 ares->ai_addrlen) < 0)
697 err(1, "bind failed");
701 set_common_sockopts(s, res0->ai_family);
703 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
706 warn("connect to %s port %s (%s) failed", host, port,
707 uflag ? "udp" : "tcp");
711 } while ((res0 = res0->ai_next) != NULL);
719 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
727 flags = fcntl(s, F_GETFL, 0);
728 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
729 err(1, "set non-blocking mode");
732 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
734 pfd.events = POLLOUT;
735 if ((ret = poll(&pfd, 1, timeout)) == 1) {
736 optlen = sizeof(optval);
737 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
738 &optval, &optlen)) == 0) {
740 ret = optval == 0 ? 0 : -1;
742 } else if (ret == 0) {
746 err(1, "poll failed");
749 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
750 err(1, "restoring flags");
757 * Returns a socket listening on a local port, binds to specified source
758 * address. Returns -1 on failure.
761 local_listen(char *host, char *port, struct addrinfo hints)
763 struct addrinfo *res, *res0;
767 /* Allow nodename to be null. */
768 hints.ai_flags |= AI_PASSIVE;
771 * In the case of binding to a wildcard address
772 * default to binding to an ipv4 address.
774 if (host == NULL && hints.ai_family == AF_UNSPEC)
775 hints.ai_family = AF_INET;
777 if ((error = getaddrinfo(host, port, &hints, &res)))
778 errx(1, "getaddrinfo: %s", gai_strerror(error));
782 if ((s = socket(res0->ai_family, res0->ai_socktype,
783 res0->ai_protocol)) < 0)
786 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
787 &rtableid, sizeof(rtableid)) == -1))
788 err(1, "setsockopt SO_SETFIB");
790 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
795 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
796 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
797 err(1, "disable TCP options");
800 set_common_sockopts(s, res0->ai_family);
802 if (bind(s, (struct sockaddr *)res0->ai_addr,
803 res0->ai_addrlen) == 0)
808 } while ((res0 = res0->ai_next) != NULL);
810 if (!uflag && s != -1) {
811 if (listen(s, 1) < 0)
822 * Loop that polls on the network file descriptor and stdin.
825 readwrite(int net_fd)
827 struct pollfd pfd[4];
828 int stdin_fd = STDIN_FILENO;
829 int stdout_fd = STDOUT_FILENO;
830 unsigned char netinbuf[BUFSIZE];
831 size_t netinbufpos = 0;
832 unsigned char stdinbuf[BUFSIZE];
833 size_t stdinbufpos = 0;
835 int stats_printed = 0;
838 /* don't read from stdin if requested */
843 pfd[POLL_STDIN].fd = stdin_fd;
844 pfd[POLL_STDIN].events = POLLIN;
847 pfd[POLL_NETOUT].fd = net_fd;
848 pfd[POLL_NETOUT].events = 0;
851 pfd[POLL_NETIN].fd = net_fd;
852 pfd[POLL_NETIN].events = POLLIN;
855 pfd[POLL_STDOUT].fd = stdout_fd;
856 pfd[POLL_STDOUT].events = 0;
859 /* both inputs are gone, buffers are empty, we are done */
860 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
861 && stdinbufpos == 0 && netinbufpos == 0) {
862 if (FreeBSD_Mflag && !stats_printed)
863 FreeBSD_stats_print(net_fd);
867 /* both outputs are gone, we can't continue */
868 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
869 if (FreeBSD_Mflag && !stats_printed)
870 FreeBSD_stats_print(net_fd);
874 /* listen and net in gone, queues empty, done */
875 if (lflag && pfd[POLL_NETIN].fd == -1
876 && stdinbufpos == 0 && netinbufpos == 0) {
877 if (FreeBSD_Mflag && !stats_printed)
878 FreeBSD_stats_print(net_fd);
883 /* help says -i is for "wait between lines sent". We read and
884 * write arbitrary amounts of data, and we don't want to start
885 * scanning for newlines, so this is as good as it gets */
890 num_fds = poll(pfd, 4, timeout);
892 /* treat poll errors */
895 err(1, "polling error");
898 /* timeout happened */
901 FreeBSD_stats_print(net_fd);
905 /* treat socket error conditions */
906 for (n = 0; n < 4; n++) {
907 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
911 /* reading is possible after HUP */
912 if (pfd[POLL_STDIN].events & POLLIN &&
913 pfd[POLL_STDIN].revents & POLLHUP &&
914 ! (pfd[POLL_STDIN].revents & POLLIN))
915 pfd[POLL_STDIN].fd = -1;
917 if (pfd[POLL_NETIN].events & POLLIN &&
918 pfd[POLL_NETIN].revents & POLLHUP &&
919 ! (pfd[POLL_NETIN].revents & POLLIN))
920 pfd[POLL_NETIN].fd = -1;
922 if (pfd[POLL_NETOUT].revents & POLLHUP) {
924 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
925 pfd[POLL_NETOUT].fd = -1;
927 /* if HUP, stop watching stdout */
928 if (pfd[POLL_STDOUT].revents & POLLHUP)
929 pfd[POLL_STDOUT].fd = -1;
930 /* if no net out, stop watching stdin */
931 if (pfd[POLL_NETOUT].fd == -1)
932 pfd[POLL_STDIN].fd = -1;
933 /* if no stdout, stop watching net in */
934 if (pfd[POLL_STDOUT].fd == -1) {
935 if (pfd[POLL_NETIN].fd != -1)
936 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
937 pfd[POLL_NETIN].fd = -1;
940 /* try to read from stdin */
941 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
942 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
944 /* error or eof on stdin - remove from pfd */
945 if (ret == 0 || ret == -1)
946 pfd[POLL_STDIN].fd = -1;
947 /* read something - poll net out */
949 pfd[POLL_NETOUT].events = POLLOUT;
950 /* filled buffer - remove self from polling */
951 if (stdinbufpos == BUFSIZE)
952 pfd[POLL_STDIN].events = 0;
954 /* try to write to network */
955 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
956 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
959 pfd[POLL_NETOUT].fd = -1;
960 /* buffer empty - remove self from polling */
961 if (stdinbufpos == 0)
962 pfd[POLL_NETOUT].events = 0;
963 /* buffer no longer full - poll stdin again */
964 if (stdinbufpos < BUFSIZE)
965 pfd[POLL_STDIN].events = POLLIN;
967 /* try to read from network */
968 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
969 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
972 pfd[POLL_NETIN].fd = -1;
973 /* eof on net in - remove from pfd */
975 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
976 pfd[POLL_NETIN].fd = -1;
978 /* read something - poll stdout */
980 pfd[POLL_STDOUT].events = POLLOUT;
981 /* filled buffer - remove self from polling */
982 if (netinbufpos == BUFSIZE)
983 pfd[POLL_NETIN].events = 0;
986 atelnet(pfd[POLL_NETIN].fd, netinbuf,
989 /* try to write to stdout */
990 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
991 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
994 pfd[POLL_STDOUT].fd = -1;
995 /* buffer empty - remove self from polling */
996 if (netinbufpos == 0)
997 pfd[POLL_STDOUT].events = 0;
998 /* buffer no longer full - poll net in again */
999 if (netinbufpos < BUFSIZE)
1000 pfd[POLL_NETIN].events = POLLIN;
1003 /* stdin gone and queue empty? */
1004 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1005 if (pfd[POLL_NETOUT].fd != -1 && Nflag) {
1006 if (FreeBSD_Mflag) {
1007 FreeBSD_stats_print(net_fd);
1010 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1012 pfd[POLL_NETOUT].fd = -1;
1014 /* net in gone and queue empty? */
1015 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1016 pfd[POLL_STDOUT].fd = -1;
1022 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
1027 n = write(fd, buf, *bufpos);
1028 /* don't treat EAGAIN, EINTR as error */
1029 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1034 adjust = *bufpos - n;
1036 memmove(buf, buf + n, adjust);
1043 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1045 size_t num = BUFSIZE - *bufpos;
1048 n = read(fd, buf + *bufpos, num);
1049 /* don't treat EAGAIN, EINTR as error */
1050 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1060 * Pass the connected file descriptor to stdout and exit.
1068 char buf[CMSG_SPACE(sizeof(int))];
1070 struct cmsghdr *cmsg;
1076 /* Avoid obvious stupidity */
1077 if (isatty(STDOUT_FILENO))
1078 errx(1, "Cannot pass file descriptor to tty");
1080 bzero(&mh, sizeof(mh));
1081 bzero(&cmsgbuf, sizeof(cmsgbuf));
1082 bzero(&iov, sizeof(iov));
1084 mh.msg_control = (caddr_t)&cmsgbuf.buf;
1085 mh.msg_controllen = sizeof(cmsgbuf.buf);
1086 cmsg = CMSG_FIRSTHDR(&mh);
1087 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1088 cmsg->cmsg_level = SOL_SOCKET;
1089 cmsg->cmsg_type = SCM_RIGHTS;
1090 *(int *)CMSG_DATA(cmsg) = nfd;
1097 bzero(&pfd, sizeof(pfd));
1098 pfd.fd = STDOUT_FILENO;
1099 pfd.events = POLLOUT;
1101 r = sendmsg(STDOUT_FILENO, &mh, 0);
1103 if (errno == EAGAIN || errno == EINTR) {
1104 if (poll(&pfd, 1, -1) == -1)
1110 errx(1, "sendmsg: unexpected return value %zd", r);
1117 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1119 atelnet(int nfd, unsigned char *buf, unsigned int size)
1121 unsigned char *p, *end;
1122 unsigned char obuf[4];
1126 end = buf + size - 2;
1128 for (p = buf; p < end; p++) {
1134 if ((*p == WILL) || (*p == WONT))
1136 else if ((*p == DO) || (*p == DONT))
1143 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1144 warn("Write Error!");
1150 * Build an array of ports in portlist[], listing each port
1151 * that we should try to connect to.
1154 build_ports(char *p)
1161 if ((n = strchr(p, '-')) != NULL) {
1165 /* Make sure the ports are in order: lowest->highest. */
1166 hi = strtonum(n, 1, PORT_MAX, &errstr);
1168 errx(1, "port number %s: %s", errstr, n);
1169 lo = strtonum(p, 1, PORT_MAX, &errstr);
1171 errx(1, "port number %s: %s", errstr, p);
1179 /* Load ports sequentially. */
1180 for (cp = lo; cp <= hi; cp++) {
1181 portlist[x] = calloc(1, PORT_MAX_LEN);
1182 if (portlist[x] == NULL)
1184 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1188 /* Randomly swap ports. */
1193 for (x = 0; x <= (hi - lo); x++) {
1194 y = (arc4random() & 0xFFFF) % (hi - lo);
1196 portlist[x] = portlist[y];
1201 hi = strtonum(p, 1, PORT_MAX, &errstr);
1203 errx(1, "port number %s: %s", errstr, p);
1204 portlist[0] = strdup(p);
1205 if (portlist[0] == NULL)
1212 * Do a few writes to see if the UDP port is there.
1213 * Fails once PF state table is full.
1220 for (i = 0; i <= 3; i++) {
1221 if (write(s, "X", 1) == 1)
1230 FreeBSD_stats_setup(int s)
1233 if (setsockopt(s, IPPROTO_TCP, TCP_STATS,
1234 &FreeBSD_Mflag, sizeof(FreeBSD_Mflag)) == -1) {
1235 if (errno == EOPNOTSUPP) {
1236 warnx("getsockopt(TCP_STATS) failed; "
1237 "kernel built without \"options STATS\"?");
1239 err(1, "enable TCP_STATS gathering");
1244 FreeBSD_stats_print(int s)
1247 struct statsblob *statsb;
1249 socklen_t sockoptlen;
1253 * This usleep is a workaround for TCP_STATS reporting
1254 * incorrect values for TXPB.
1259 statsb = malloc(sockoptlen);
1262 error = getsockopt(s, IPPROTO_TCP, TCP_STATS, statsb, &sockoptlen);
1264 if (errno == EOVERFLOW && statsb->cursz > sockoptlen) {
1265 /* Retry with a larger size. */
1266 sockoptlen = statsb->cursz;
1267 statsb = realloc(statsb, sockoptlen);
1270 error = getsockopt(s, IPPROTO_TCP, TCP_STATS,
1271 statsb, &sockoptlen);
1274 err(1, "getsockopt");
1277 sb = sbuf_new_auto();
1278 error = stats_blob_tostr(statsb, sb, SB_STRFMT_JSON, SB_TOSTR_META);
1280 errc(1, error, "stats_blob_tostr");
1282 error = sbuf_finish(sb);
1284 err(1, "sbuf_finish");
1286 fprintf(stderr, "%s\n", sbuf_data(sb));
1291 set_common_sockopts(int s, int af)
1296 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1297 &x, sizeof(x)) == -1)
1301 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1302 &x, sizeof(x)) == -1)
1308 if (af == AF_INET6) {
1309 proto = IPPROTO_IPV6;
1310 option = IPV6_TCLASS;
1316 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1317 err(1, "set IP ToS");
1320 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1321 &Iflag, sizeof(Iflag)) == -1)
1322 err(1, "set TCP receive buffer size");
1325 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1326 &Oflag, sizeof(Oflag)) == -1)
1327 err(1, "set TCP send buffer size");
1329 if (FreeBSD_Oflag) {
1330 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
1331 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
1332 err(1, "disable TCP options");
1335 FreeBSD_stats_setup(s);
1337 if (ipsec_policy[0] != NULL)
1338 add_ipsec_policy(s, af, ipsec_policy[0]);
1339 if (ipsec_policy[1] != NULL)
1340 add_ipsec_policy(s, af, ipsec_policy[1]);
1345 map_tos(char *s, int *val)
1347 /* DiffServ Codepoints and other TOS mappings */
1348 const struct toskeywords {
1349 const char *keyword;
1351 } *t, toskeywords[] = {
1352 { "af11", IPTOS_DSCP_AF11 },
1353 { "af12", IPTOS_DSCP_AF12 },
1354 { "af13", IPTOS_DSCP_AF13 },
1355 { "af21", IPTOS_DSCP_AF21 },
1356 { "af22", IPTOS_DSCP_AF22 },
1357 { "af23", IPTOS_DSCP_AF23 },
1358 { "af31", IPTOS_DSCP_AF31 },
1359 { "af32", IPTOS_DSCP_AF32 },
1360 { "af33", IPTOS_DSCP_AF33 },
1361 { "af41", IPTOS_DSCP_AF41 },
1362 { "af42", IPTOS_DSCP_AF42 },
1363 { "af43", IPTOS_DSCP_AF43 },
1364 { "critical", IPTOS_PREC_CRITIC_ECP },
1365 { "cs0", IPTOS_DSCP_CS0 },
1366 { "cs1", IPTOS_DSCP_CS1 },
1367 { "cs2", IPTOS_DSCP_CS2 },
1368 { "cs3", IPTOS_DSCP_CS3 },
1369 { "cs4", IPTOS_DSCP_CS4 },
1370 { "cs5", IPTOS_DSCP_CS5 },
1371 { "cs6", IPTOS_DSCP_CS6 },
1372 { "cs7", IPTOS_DSCP_CS7 },
1373 { "ef", IPTOS_DSCP_EF },
1374 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1375 { "lowdelay", IPTOS_LOWDELAY },
1376 { "netcontrol", IPTOS_PREC_NETCONTROL },
1377 { "reliability", IPTOS_RELIABILITY },
1378 { "throughput", IPTOS_THROUGHPUT },
1382 for (t = toskeywords; t->keyword != NULL; t++) {
1383 if (strcmp(s, t->keyword) == 0) {
1393 report_connect(const struct sockaddr *sa, socklen_t salen)
1395 char remote_host[NI_MAXHOST];
1396 char remote_port[NI_MAXSERV];
1398 int flags = NI_NUMERICSERV;
1401 flags |= NI_NUMERICHOST;
1403 if ((herr = getnameinfo(sa, salen,
1404 remote_host, sizeof(remote_host),
1405 remote_port, sizeof(remote_port),
1407 if (herr == EAI_SYSTEM)
1408 err(1, "getnameinfo");
1410 errx(1, "getnameinfo: %s", gai_strerror(herr));
1414 "Connection from %s %s "
1415 "received!\n", remote_host, remote_port);
1422 fprintf(stderr, "\tCommand Summary:\n\
1425 \t-D Enable the debug socket option\n\
1426 \t-d Detach from stdin\n");
1429 \t-E Use IPsec ESP\n\
1430 \t-e policy Use specified IPsec policy\n");
1433 \t-F Pass socket fd\n\
1434 \t-h This help text\n\
1435 \t-I length TCP receive buffer length\n\
1436 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1437 \t-k Keep inbound sockets open for multiple connects\n\
1438 \t-l Listen mode, for inbound connects\n\
1439 \t-N Shutdown the network socket after EOF on stdin\n\
1440 \t-n Suppress name/port resolutions\n\
1441 \t--no-tcpopt Disable TCP options\n\
1442 \t--sctp\t SCTP mode\n\
1443 \t-O length TCP send buffer length\n\
1444 \t-P proxyuser\tUsername for proxy authentication\n\
1445 \t-p port\t Specify local port for remote connects\n\
1446 \t-r Randomize remote ports\n\
1447 \t-S Enable the TCP MD5 signature option\n\
1448 \t-s addr\t Local source address\n\
1449 \t-T toskeyword\tSet IP Type of Service\n\
1450 \t-t Answer TELNET negotiation\n\
1451 \t-U Use UNIX domain socket\n\
1453 \t-V rtable Specify alternate routing table\n\
1455 \t-w secs\t Timeout for connects and final net reads\n\
1456 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1457 \t-x addr[:port]\tSpecify proxy address and port\n\
1458 \t-z Zero-I/O mode [used for scanning]\n\
1459 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1461 fprintf(stderr, "\tSee ipsec_set_policy(3) for -e argument format\n");
1468 add_ipsec_policy(int s, int af, char *policy)
1473 raw = ipsec_set_policy(policy, strlen(policy));
1475 errx(1, "ipsec_set_policy `%s': %s", policy,
1478 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1479 ipsec_get_policylen(raw));
1481 e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1482 ipsec_get_policylen(raw));
1484 err(1, "ipsec policy cannot be configured");
1487 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1497 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1499 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1501 "\t [--no-tcpopt] [--sctp]\n"
1502 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1503 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1504 "\t [-x proxy_address[:port]] [destination] [port]\n");