1 /* $OpenBSD: netcat.c,v 1.127 2015/02/14 22:40:22 jca 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>.
36 #include <sys/limits.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
44 #include <netinet/in.h>
46 #include <netipsec/ipsec.h>
48 #include <netinet/tcp.h>
49 #include <netinet/ip.h>
50 #include <arpa/telnet.h>
68 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
71 #define PORT_MAX 65535
72 #define PORT_MAX_LEN 6
73 #define UNIX_DG_TMP_SOCKET_SIZE 19
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 */
107 int family = AF_UNSPEC;
108 char *portlist[PORT_MAX+1];
109 char *unix_dg_tmp_socket;
111 void atelnet(int, unsigned char *, unsigned int);
112 void build_ports(char *);
114 int local_listen(char *, char *, struct addrinfo);
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 *);
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);
129 ssize_t drainbuf(int, unsigned char *, size_t *);
130 ssize_t fillbuf(int, unsigned char *, size_t *);
133 void add_ipsec_policy(int, char *);
135 char *ipsec_policy[2];
139 main(int argc, char *argv[])
141 int ch, s, ret, socksv, ipsec_count;
143 size_t intsize = sizeof(int);
145 struct addrinfo hints;
148 struct sockaddr_storage cliaddr;
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 },
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) {
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 */
187 errx(1, "unsupported proxy protocol");
194 ipsec_policy[ipsec_count++ % 2] = optarg;
196 errx(1, "IPsec support unavailable.");
201 ipsec_policy[0] = "in ipsec esp/transport//require";
202 ipsec_policy[1] = "out ipsec esp/transport//require";
204 errx(1, "IPsec support unavailable.");
214 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
216 errx(1, "interval %s: %s", errstr, optarg);
231 fprintf(stderr, "option -o is deprecated.\n");
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);
257 errx(1, "rtable %s: %s", errstr, optarg);
263 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
265 errx(1, "timeout %s: %s", errstr, optarg);
270 if ((proxy = strdup(optarg)) == NULL)
280 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
282 errx(1, "TCP receive window %s: %s",
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",
299 if (map_tos(optarg, &Tflag))
301 if (strlen(optarg) > 1 && optarg[0] == '0' &&
303 Tflag = (int)strtol(optarg, NULL, 16);
305 Tflag = (int)strtonum(optarg, 0, 255,
307 if (Tflag < 0 || Tflag > 255 || errstr || errno)
308 errx(1, "illegal tos value %s", optarg);
317 /* Cruft to make sure options are clean, and used properly. */
318 if (argv[0] && !argv[1] && family == AF_UNIX) {
321 } else if (argv[0] && !argv[1]) {
326 } else if (argv[0] && argv[1]) {
333 errx(1, "cannot use -s and -l");
335 errx(1, "cannot use -p and -l");
337 errx(1, "cannot use -z and -l");
339 errx(1, "must use -l with -k");
341 /* Get name of temporary socket for unix datagram client */
342 if ((family == AF_UNIX) && uflag && !lflag) {
344 unix_dg_tmp_socket = sflag;
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)
350 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
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;
361 hints.ai_flags |= AI_NUMERICHOST;
366 errx(1, "no proxy support for UDP mode");
369 errx(1, "no proxy support for listen");
371 if (family == AF_UNIX)
372 errx(1, "no proxy support for unix sockets");
374 /* XXX IPv6 transport to proxy would probably work */
375 if (family == AF_INET6)
376 errx(1, "no proxy support for IPv6");
379 errx(1, "no proxy support for local source address");
381 proxyhost = strsep(&proxy, ":");
384 memset(&proxyhints, 0, sizeof(struct addrinfo));
385 proxyhints.ai_family = family;
386 proxyhints.ai_socktype = SOCK_STREAM;
387 proxyhints.ai_protocol = IPPROTO_TCP;
389 proxyhints.ai_flags |= AI_NUMERICHOST;
396 if (family == AF_UNIX) {
400 s = unix_listen(host);
403 /* Allow only one connection at a time, but stay alive. */
405 if (family != AF_UNIX)
406 s = local_listen(host, uport, hints);
410 * For UDP and -k, don't connect the socket, let it
411 * receive datagrams from multiple socket pairs.
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.
420 else if (uflag && !kflag) {
423 struct sockaddr_storage z;
427 rv = recvfrom(s, buf, plen, MSG_PEEK,
428 (struct sockaddr *)&z, &len);
432 rv = connect(s, (struct sockaddr *)&z, len);
437 report_connect((struct sockaddr *)&z, len);
441 len = sizeof(cliaddr);
442 connfd = accept(s, (struct sockaddr *)&cliaddr,
445 /* For now, all errnos are fatal */
449 report_connect((struct sockaddr *)&cliaddr, len);
455 if (family != AF_UNIX)
458 if (connect(s, NULL, 0) < 0)
465 } else if (family == AF_UNIX) {
468 if ((s = unix_connect(host)) > 0 && !zflag) {
475 unlink(unix_dg_tmp_socket);
481 /* Construct the portlist[] array. */
484 /* Cycle through portlist, connecting to each port. */
485 for (i = 0; portlist[i] != NULL; i++) {
490 s = socks_connect(host, portlist[i], hints,
491 proxyhost, proxyport, proxyhints, socksv,
494 s = remote_connect(host, portlist[i], hints);
500 if (vflag || zflag) {
501 /* For UDP, make sure we are connected. */
503 if (udptest(s) == -1) {
509 /* Don't look up port if -n. */
514 ntohs(atoi(portlist[i])),
515 uflag ? "udp" : "tcp");
519 "Connection to %s %s port [%s/%s] "
520 "succeeded!\n", host, portlist[i],
521 uflag ? "udp" : "tcp",
522 sv ? sv->s_name : "*");
539 * Returns a unix socket bound to the given path
542 unix_bind(char *path)
544 struct sockaddr_un sun;
547 /* Create unix domain socket. */
548 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
552 memset(&sun, 0, sizeof(struct sockaddr_un));
553 sun.sun_family = AF_UNIX;
555 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
556 sizeof(sun.sun_path)) {
558 errno = ENAMETOOLONG;
562 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
571 * Returns a socket connected to a local unix socket. Returns -1 on failure.
574 unix_connect(char *path)
576 struct sockaddr_un sun;
580 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
583 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
586 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
588 memset(&sun, 0, sizeof(struct sockaddr_un));
589 sun.sun_family = AF_UNIX;
591 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
592 sizeof(sun.sun_path)) {
594 errno = ENAMETOOLONG;
597 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
607 * Create a unix domain socket, and listen on it.
610 unix_listen(char *path)
613 if ((s = unix_bind(path)) < 0)
616 if (listen(s, 5) < 0) {
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.
629 remote_connect(const char *host, const char *port, struct addrinfo hints)
631 struct addrinfo *res, *res0;
632 int s, error, on = 1;
634 if ((error = getaddrinfo(host, port, &hints, &res)))
635 errx(1, "getaddrinfo: %s", gai_strerror(error));
639 if ((s = socket(res0->ai_family, res0->ai_socktype,
640 res0->ai_protocol)) < 0)
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]);
649 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
650 &rtableid, sizeof(rtableid)) == -1))
651 err(1, "setsockopt SO_SETFIB");
653 /* Bind to a local port or source address if specified. */
654 if (sflag || pflag) {
655 struct addrinfo ahints, *ares;
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));
667 if (bind(s, (struct sockaddr *)ares->ai_addr,
668 ares->ai_addrlen) < 0)
669 err(1, "bind failed");
673 set_common_sockopts(s, res0->ai_family);
675 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
678 warn("connect to %s port %s (%s) failed", host, port,
679 uflag ? "udp" : "tcp");
683 } while ((res0 = res0->ai_next) != NULL);
691 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
699 flags = fcntl(s, F_GETFL, 0);
700 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
701 err(1, "set non-blocking mode");
704 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
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) {
712 ret = optval == 0 ? 0 : -1;
714 } else if (ret == 0) {
718 err(1, "poll failed");
721 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
722 err(1, "restoring flags");
729 * Returns a socket listening on a local port, binds to specified source
730 * address. Returns -1 on failure.
733 local_listen(char *host, char *port, struct addrinfo hints)
735 struct addrinfo *res, *res0;
739 /* Allow nodename to be null. */
740 hints.ai_flags |= AI_PASSIVE;
743 * In the case of binding to a wildcard address
744 * default to binding to an ipv4 address.
746 if (host == NULL && hints.ai_family == AF_UNSPEC)
747 hints.ai_family = AF_INET;
749 if ((error = getaddrinfo(host, port, &hints, &res)))
750 errx(1, "getaddrinfo: %s", gai_strerror(error));
754 if ((s = socket(res0->ai_family, res0->ai_socktype,
755 res0->ai_protocol)) < 0)
758 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
759 &rtableid, sizeof(rtableid)) == -1))
760 err(1, "setsockopt SO_SETFIB");
762 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
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]);
772 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
773 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
774 err(1, "disable TCP options");
777 set_common_sockopts(s, res0->ai_family);
779 if (bind(s, (struct sockaddr *)res0->ai_addr,
780 res0->ai_addrlen) == 0)
785 } while ((res0 = res0->ai_next) != NULL);
787 if (!uflag && s != -1) {
788 if (listen(s, 1) < 0)
799 * Loop that polls on the network file descriptor and stdin.
802 readwrite(int net_fd)
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;
814 /* don't read from stdin if requested */
819 pfd[POLL_STDIN].fd = stdin_fd;
820 pfd[POLL_STDIN].events = POLLIN;
823 pfd[POLL_NETOUT].fd = net_fd;
824 pfd[POLL_NETOUT].events = 0;
827 pfd[POLL_NETIN].fd = net_fd;
828 pfd[POLL_NETIN].events = POLLIN;
831 pfd[POLL_STDOUT].fd = stdout_fd;
832 pfd[POLL_STDOUT].events = 0;
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) {
841 /* both outputs are gone, we can't continue */
842 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
846 /* listen and net in gone, queues empty, done */
847 if (lflag && pfd[POLL_NETIN].fd == -1
848 && stdinbufpos == 0 && netinbufpos == 0) {
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 */
860 num_fds = poll(pfd, 4, timeout);
862 /* treat poll errors */
865 err(1, "polling error");
868 /* timeout happened */
872 /* treat socket error conditions */
873 for (n = 0; n < 4; n++) {
874 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
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;
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;
889 if (pfd[POLL_NETOUT].revents & POLLHUP) {
891 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
892 pfd[POLL_NETOUT].fd = -1;
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;
907 /* try to read from stdin */
908 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
909 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
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 */
916 pfd[POLL_NETOUT].events = POLLOUT;
917 /* filled buffer - remove self from polling */
918 if (stdinbufpos == BUFSIZE)
919 pfd[POLL_STDIN].events = 0;
921 /* try to write to network */
922 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
923 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
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;
934 /* try to read from network */
935 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
936 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
939 pfd[POLL_NETIN].fd = -1;
940 /* eof on net in - remove from pfd */
942 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
943 pfd[POLL_NETIN].fd = -1;
945 /* read something - poll stdout */
947 pfd[POLL_STDOUT].events = POLLOUT;
948 /* filled buffer - remove self from polling */
949 if (netinbufpos == BUFSIZE)
950 pfd[POLL_NETIN].events = 0;
953 atelnet(pfd[POLL_NETIN].fd, netinbuf,
956 /* try to write to stdout */
957 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
958 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
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;
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;
976 /* net in gone and queue empty? */
977 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
978 pfd[POLL_STDOUT].fd = -1;
984 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
989 n = write(fd, buf, *bufpos);
990 /* don't treat EAGAIN, EINTR as error */
991 if (n == -1 && (errno == EAGAIN || errno == EINTR))
996 adjust = *bufpos - n;
998 memmove(buf, buf + n, adjust);
1005 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1007 size_t num = BUFSIZE - *bufpos;
1010 n = read(fd, buf + *bufpos, num);
1011 /* don't treat EAGAIN, EINTR as error */
1012 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1022 * Pass the connected file descriptor to stdout and exit.
1030 char buf[CMSG_SPACE(sizeof(int))];
1032 struct cmsghdr *cmsg;
1038 /* Avoid obvious stupidity */
1039 if (isatty(STDOUT_FILENO))
1040 errx(1, "Cannot pass file descriptor to tty");
1042 bzero(&mh, sizeof(mh));
1043 bzero(&cmsgbuf, sizeof(cmsgbuf));
1044 bzero(&iov, sizeof(iov));
1045 bzero(&pfd, sizeof(pfd));
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;
1060 bzero(&pfd, sizeof(pfd));
1061 pfd.fd = STDOUT_FILENO;
1063 r = sendmsg(STDOUT_FILENO, &mh, 0);
1065 if (errno == EAGAIN || errno == EINTR) {
1066 pfd.events = POLLOUT;
1067 if (poll(&pfd, 1, -1) == -1)
1073 errx(1, "sendmsg: unexpected return value %zd", r);
1080 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1082 atelnet(int nfd, unsigned char *buf, unsigned int size)
1084 unsigned char *p, *end;
1085 unsigned char obuf[4];
1089 end = buf + size - 2;
1091 for (p = buf; p < end; p++) {
1097 if ((*p == WILL) || (*p == WONT))
1099 else if ((*p == DO) || (*p == DONT))
1106 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1107 warn("Write Error!");
1113 * Build an array of ports in portlist[], listing each port
1114 * that we should try to connect to.
1117 build_ports(char *p)
1124 if ((n = strchr(p, '-')) != NULL) {
1128 /* Make sure the ports are in order: lowest->highest. */
1129 hi = strtonum(n, 1, PORT_MAX, &errstr);
1131 errx(1, "port number %s: %s", errstr, n);
1132 lo = strtonum(p, 1, PORT_MAX, &errstr);
1134 errx(1, "port number %s: %s", errstr, p);
1142 /* Load ports sequentially. */
1143 for (cp = lo; cp <= hi; cp++) {
1144 portlist[x] = calloc(1, PORT_MAX_LEN);
1145 if (portlist[x] == NULL)
1147 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1151 /* Randomly swap ports. */
1156 for (x = 0; x <= (hi - lo); x++) {
1157 y = (arc4random() & 0xFFFF) % (hi - lo);
1159 portlist[x] = portlist[y];
1164 hi = strtonum(p, 1, PORT_MAX, &errstr);
1166 errx(1, "port number %s: %s", errstr, p);
1167 portlist[0] = strdup(p);
1168 if (portlist[0] == NULL)
1175 * Do a few writes to see if the UDP port is there.
1176 * Fails once PF state table is full.
1183 for (i = 0; i <= 3; i++) {
1184 if (write(s, "X", 1) == 1)
1193 set_common_sockopts(int s, int af)
1198 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1199 &x, sizeof(x)) == -1)
1203 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1204 &x, sizeof(x)) == -1)
1210 if (af == AF_INET6) {
1211 proto = IPPROTO_IPV6;
1212 option = IPV6_TCLASS;
1218 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1219 err(1, "set IP ToS");
1222 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1223 &Iflag, sizeof(Iflag)) == -1)
1224 err(1, "set TCP receive buffer size");
1227 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1228 &Oflag, sizeof(Oflag)) == -1)
1229 err(1, "set TCP send buffer size");
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");
1239 map_tos(char *s, int *val)
1241 /* DiffServ Codepoints and other TOS mappings */
1242 const struct toskeywords {
1243 const char *keyword;
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 },
1276 for (t = toskeywords; t->keyword != NULL; t++) {
1277 if (strcmp(s, t->keyword) == 0) {
1287 report_connect(const struct sockaddr *sa, socklen_t salen)
1289 char remote_host[NI_MAXHOST];
1290 char remote_port[NI_MAXSERV];
1292 int flags = NI_NUMERICSERV;
1295 flags |= NI_NUMERICHOST;
1297 if ((herr = getnameinfo(sa, salen,
1298 remote_host, sizeof(remote_host),
1299 remote_port, sizeof(remote_port),
1301 if (herr == EAI_SYSTEM)
1302 err(1, "getnameinfo");
1304 errx(1, "getnameinfo: %s", gai_strerror(herr));
1308 "Connection from %s %s "
1309 "received!\n", remote_host, remote_port);
1316 fprintf(stderr, "\tCommand Summary:\n\
1319 \t-D Enable the debug socket option\n\
1320 \t-d Detach from stdin\n");
1323 \t-E Use IPsec ESP\n\
1324 \t-e policy Use specified IPsec policy\n");
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\
1346 \t-V rtable Specify alternate routing table\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");
1354 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1361 add_ipsec_policy(int s, char *policy)
1366 raw = ipsec_set_policy(policy, strlen(policy));
1368 errx(1, "ipsec_set_policy `%s': %s", policy,
1370 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1371 ipsec_get_policylen(raw));
1373 err(1, "ipsec policy cannot be configured");
1376 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1386 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1388 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
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");