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>.
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>
69 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
72 #define PORT_MAX 65535
73 #define PORT_MAX_LEN 6
74 #define UNIX_DG_TMP_SOCKET_SIZE 19
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 */
108 int family = AF_UNSPEC;
109 char *portlist[PORT_MAX+1];
110 char *unix_dg_tmp_socket;
112 void atelnet(int, unsigned char *, unsigned int);
113 void build_ports(char *);
115 int local_listen(char *, char *, struct addrinfo);
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 *);
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);
130 ssize_t drainbuf(int, unsigned char *, size_t *);
131 ssize_t fillbuf(int, unsigned char *, size_t *);
134 void add_ipsec_policy(int, int, char *);
136 char *ipsec_policy[2];
140 main(int argc, char *argv[])
142 int ch, s, ret, socksv, ipsec_count;
144 size_t intsize = sizeof(int);
146 struct addrinfo hints;
149 struct sockaddr_storage cliaddr;
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 },
167 signal(SIGPIPE, SIG_IGN);
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) {
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 */
190 errx(1, "unsupported proxy protocol");
197 ipsec_policy[ipsec_count++ % 2] = optarg;
199 errx(1, "IPsec support unavailable.");
204 ipsec_policy[0] = "in ipsec esp/transport//require";
205 ipsec_policy[1] = "out ipsec esp/transport//require";
207 errx(1, "IPsec support unavailable.");
217 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
219 errx(1, "interval %s: %s", errstr, optarg);
234 fprintf(stderr, "option -o is deprecated.\n");
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);
260 errx(1, "rtable %s: %s", errstr, optarg);
266 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
268 errx(1, "timeout %s: %s", errstr, optarg);
273 if ((proxy = strdup(optarg)) == NULL)
283 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
285 errx(1, "TCP receive window %s: %s",
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",
302 if (map_tos(optarg, &Tflag))
304 if (strlen(optarg) > 1 && optarg[0] == '0' &&
306 Tflag = (int)strtol(optarg, NULL, 16);
308 Tflag = (int)strtonum(optarg, 0, 255,
310 if (Tflag < 0 || Tflag > 255 || errstr || errno)
311 errx(1, "illegal tos value %s", optarg);
320 /* Cruft to make sure options are clean, and used properly. */
321 if (argv[0] && !argv[1] && family == AF_UNIX) {
324 } else if (argv[0] && !argv[1]) {
329 } else if (argv[0] && argv[1]) {
336 errx(1, "cannot use -s and -l");
338 errx(1, "cannot use -p and -l");
340 errx(1, "cannot use -z and -l");
342 errx(1, "must use -l with -k");
344 /* Get name of temporary socket for unix datagram client */
345 if ((family == AF_UNIX) && uflag && !lflag) {
347 unix_dg_tmp_socket = sflag;
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)
353 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
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;
364 hints.ai_flags |= AI_NUMERICHOST;
369 errx(1, "no proxy support for UDP mode");
372 errx(1, "no proxy support for listen");
374 if (family == AF_UNIX)
375 errx(1, "no proxy support for unix sockets");
377 /* XXX IPv6 transport to proxy would probably work */
378 if (family == AF_INET6)
379 errx(1, "no proxy support for IPv6");
382 errx(1, "no proxy support for local source address");
384 proxyhost = strsep(&proxy, ":");
387 memset(&proxyhints, 0, sizeof(struct addrinfo));
388 proxyhints.ai_family = family;
389 proxyhints.ai_socktype = SOCK_STREAM;
390 proxyhints.ai_protocol = IPPROTO_TCP;
392 proxyhints.ai_flags |= AI_NUMERICHOST;
399 if (family == AF_UNIX) {
403 s = unix_listen(host);
406 /* Allow only one connection at a time, but stay alive. */
408 if (family != AF_UNIX)
409 s = local_listen(host, uport, hints);
413 * For UDP and -k, don't connect the socket, let it
414 * receive datagrams from multiple socket pairs.
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.
423 else if (uflag && !kflag) {
426 struct sockaddr_storage z;
430 rv = recvfrom(s, buf, plen, MSG_PEEK,
431 (struct sockaddr *)&z, &len);
435 rv = connect(s, (struct sockaddr *)&z, len);
440 report_connect((struct sockaddr *)&z, len);
444 len = sizeof(cliaddr);
445 connfd = accept(s, (struct sockaddr *)&cliaddr,
448 /* For now, all errnos are fatal */
452 report_connect((struct sockaddr *)&cliaddr, len);
458 if (family != AF_UNIX)
461 if (connect(s, NULL, 0) < 0)
468 } else if (family == AF_UNIX) {
471 if ((s = unix_connect(host)) > 0 && !zflag) {
478 unlink(unix_dg_tmp_socket);
484 /* Construct the portlist[] array. */
487 /* Cycle through portlist, connecting to each port. */
488 for (i = 0; portlist[i] != NULL; i++) {
493 s = socks_connect(host, portlist[i], hints,
494 proxyhost, proxyport, proxyhints, socksv,
497 s = remote_connect(host, portlist[i], hints);
503 if (vflag || zflag) {
504 /* For UDP, make sure we are connected. */
506 if (udptest(s) == -1) {
512 /* Don't look up port if -n. */
517 ntohs(atoi(portlist[i])),
518 uflag ? "udp" : "tcp");
522 "Connection to %s %s port [%s/%s] "
523 "succeeded!\n", host, portlist[i],
524 uflag ? "udp" : "tcp",
525 sv ? sv->s_name : "*");
542 * Returns a unix socket bound to the given path
545 unix_bind(char *path)
547 struct sockaddr_un sun;
550 /* Create unix domain socket. */
551 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
555 memset(&sun, 0, sizeof(struct sockaddr_un));
556 sun.sun_family = AF_UNIX;
558 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
559 sizeof(sun.sun_path)) {
561 errno = ENAMETOOLONG;
565 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
574 * Returns a socket connected to a local unix socket. Returns -1 on failure.
577 unix_connect(char *path)
579 struct sockaddr_un sun;
583 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
586 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
589 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
591 memset(&sun, 0, sizeof(struct sockaddr_un));
592 sun.sun_family = AF_UNIX;
594 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
595 sizeof(sun.sun_path)) {
597 errno = ENAMETOOLONG;
600 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
610 * Create a unix domain socket, and listen on it.
613 unix_listen(char *path)
616 if ((s = unix_bind(path)) < 0)
619 if (listen(s, 5) < 0) {
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.
632 remote_connect(const char *host, const char *port, struct addrinfo hints)
634 struct addrinfo *res, *res0;
635 int s, error, on = 1;
637 if ((error = getaddrinfo(host, port, &hints, &res)))
638 errx(1, "getaddrinfo: %s", gai_strerror(error));
642 if ((s = socket(res0->ai_family, res0->ai_socktype,
643 res0->ai_protocol)) < 0)
646 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
647 &rtableid, sizeof(rtableid)) == -1))
648 err(1, "setsockopt SO_SETFIB");
650 /* Bind to a local port or source address if specified. */
651 if (sflag || pflag) {
652 struct addrinfo ahints, *ares;
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));
664 if (bind(s, (struct sockaddr *)ares->ai_addr,
665 ares->ai_addrlen) < 0)
666 err(1, "bind failed");
670 set_common_sockopts(s, res0->ai_family);
672 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
675 warn("connect to %s port %s (%s) failed", host, port,
676 uflag ? "udp" : "tcp");
680 } while ((res0 = res0->ai_next) != NULL);
688 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
696 flags = fcntl(s, F_GETFL, 0);
697 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
698 err(1, "set non-blocking mode");
701 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
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) {
709 ret = optval == 0 ? 0 : -1;
711 } else if (ret == 0) {
715 err(1, "poll failed");
718 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
719 err(1, "restoring flags");
726 * Returns a socket listening on a local port, binds to specified source
727 * address. Returns -1 on failure.
730 local_listen(char *host, char *port, struct addrinfo hints)
732 struct addrinfo *res, *res0;
736 /* Allow nodename to be null. */
737 hints.ai_flags |= AI_PASSIVE;
740 * In the case of binding to a wildcard address
741 * default to binding to an ipv4 address.
743 if (host == NULL && hints.ai_family == AF_UNSPEC)
744 hints.ai_family = AF_INET;
746 if ((error = getaddrinfo(host, port, &hints, &res)))
747 errx(1, "getaddrinfo: %s", gai_strerror(error));
751 if ((s = socket(res0->ai_family, res0->ai_socktype,
752 res0->ai_protocol)) < 0)
755 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
756 &rtableid, sizeof(rtableid)) == -1))
757 err(1, "setsockopt SO_SETFIB");
759 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
764 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
765 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
766 err(1, "disable TCP options");
769 set_common_sockopts(s, res0->ai_family);
771 if (bind(s, (struct sockaddr *)res0->ai_addr,
772 res0->ai_addrlen) == 0)
777 } while ((res0 = res0->ai_next) != NULL);
779 if (!uflag && s != -1) {
780 if (listen(s, 1) < 0)
791 * Loop that polls on the network file descriptor and stdin.
794 readwrite(int net_fd)
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;
806 /* don't read from stdin if requested */
811 pfd[POLL_STDIN].fd = stdin_fd;
812 pfd[POLL_STDIN].events = POLLIN;
815 pfd[POLL_NETOUT].fd = net_fd;
816 pfd[POLL_NETOUT].events = 0;
819 pfd[POLL_NETIN].fd = net_fd;
820 pfd[POLL_NETIN].events = POLLIN;
823 pfd[POLL_STDOUT].fd = stdout_fd;
824 pfd[POLL_STDOUT].events = 0;
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) {
833 /* both outputs are gone, we can't continue */
834 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
838 /* listen and net in gone, queues empty, done */
839 if (lflag && pfd[POLL_NETIN].fd == -1
840 && stdinbufpos == 0 && netinbufpos == 0) {
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 */
852 num_fds = poll(pfd, 4, timeout);
854 /* treat poll errors */
857 err(1, "polling error");
860 /* timeout happened */
864 /* treat socket error conditions */
865 for (n = 0; n < 4; n++) {
866 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
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;
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;
881 if (pfd[POLL_NETOUT].revents & POLLHUP) {
883 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
884 pfd[POLL_NETOUT].fd = -1;
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;
899 /* try to read from stdin */
900 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
901 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
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 */
908 pfd[POLL_NETOUT].events = POLLOUT;
909 /* filled buffer - remove self from polling */
910 if (stdinbufpos == BUFSIZE)
911 pfd[POLL_STDIN].events = 0;
913 /* try to write to network */
914 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
915 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
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;
926 /* try to read from network */
927 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
928 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
931 pfd[POLL_NETIN].fd = -1;
932 /* eof on net in - remove from pfd */
934 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
935 pfd[POLL_NETIN].fd = -1;
937 /* read something - poll stdout */
939 pfd[POLL_STDOUT].events = POLLOUT;
940 /* filled buffer - remove self from polling */
941 if (netinbufpos == BUFSIZE)
942 pfd[POLL_NETIN].events = 0;
945 atelnet(pfd[POLL_NETIN].fd, netinbuf,
948 /* try to write to stdout */
949 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
950 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
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;
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;
968 /* net in gone and queue empty? */
969 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
970 pfd[POLL_STDOUT].fd = -1;
976 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
981 n = write(fd, buf, *bufpos);
982 /* don't treat EAGAIN, EINTR as error */
983 if (n == -1 && (errno == EAGAIN || errno == EINTR))
988 adjust = *bufpos - n;
990 memmove(buf, buf + n, adjust);
997 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
999 size_t num = BUFSIZE - *bufpos;
1002 n = read(fd, buf + *bufpos, num);
1003 /* don't treat EAGAIN, EINTR as error */
1004 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1014 * Pass the connected file descriptor to stdout and exit.
1022 char buf[CMSG_SPACE(sizeof(int))];
1024 struct cmsghdr *cmsg;
1030 /* Avoid obvious stupidity */
1031 if (isatty(STDOUT_FILENO))
1032 errx(1, "Cannot pass file descriptor to tty");
1034 bzero(&mh, sizeof(mh));
1035 bzero(&cmsgbuf, sizeof(cmsgbuf));
1036 bzero(&iov, sizeof(iov));
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;
1051 bzero(&pfd, sizeof(pfd));
1052 pfd.fd = STDOUT_FILENO;
1053 pfd.events = POLLOUT;
1055 r = sendmsg(STDOUT_FILENO, &mh, 0);
1057 if (errno == EAGAIN || errno == EINTR) {
1058 if (poll(&pfd, 1, -1) == -1)
1064 errx(1, "sendmsg: unexpected return value %zd", r);
1071 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1073 atelnet(int nfd, unsigned char *buf, unsigned int size)
1075 unsigned char *p, *end;
1076 unsigned char obuf[4];
1080 end = buf + size - 2;
1082 for (p = buf; p < end; p++) {
1088 if ((*p == WILL) || (*p == WONT))
1090 else if ((*p == DO) || (*p == DONT))
1097 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1098 warn("Write Error!");
1104 * Build an array of ports in portlist[], listing each port
1105 * that we should try to connect to.
1108 build_ports(char *p)
1115 if ((n = strchr(p, '-')) != NULL) {
1119 /* Make sure the ports are in order: lowest->highest. */
1120 hi = strtonum(n, 1, PORT_MAX, &errstr);
1122 errx(1, "port number %s: %s", errstr, n);
1123 lo = strtonum(p, 1, PORT_MAX, &errstr);
1125 errx(1, "port number %s: %s", errstr, p);
1133 /* Load ports sequentially. */
1134 for (cp = lo; cp <= hi; cp++) {
1135 portlist[x] = calloc(1, PORT_MAX_LEN);
1136 if (portlist[x] == NULL)
1138 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1142 /* Randomly swap ports. */
1147 for (x = 0; x <= (hi - lo); x++) {
1148 y = (arc4random() & 0xFFFF) % (hi - lo);
1150 portlist[x] = portlist[y];
1155 hi = strtonum(p, 1, PORT_MAX, &errstr);
1157 errx(1, "port number %s: %s", errstr, p);
1158 portlist[0] = strdup(p);
1159 if (portlist[0] == NULL)
1166 * Do a few writes to see if the UDP port is there.
1167 * Fails once PF state table is full.
1174 for (i = 0; i <= 3; i++) {
1175 if (write(s, "X", 1) == 1)
1184 set_common_sockopts(int s, int af)
1189 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1190 &x, sizeof(x)) == -1)
1194 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1195 &x, sizeof(x)) == -1)
1201 if (af == AF_INET6) {
1202 proto = IPPROTO_IPV6;
1203 option = IPV6_TCLASS;
1209 if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1210 err(1, "set IP ToS");
1213 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1214 &Iflag, sizeof(Iflag)) == -1)
1215 err(1, "set TCP receive buffer size");
1218 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1219 &Oflag, sizeof(Oflag)) == -1)
1220 err(1, "set TCP send buffer size");
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");
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]);
1236 map_tos(char *s, int *val)
1238 /* DiffServ Codepoints and other TOS mappings */
1239 const struct toskeywords {
1240 const char *keyword;
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 },
1273 for (t = toskeywords; t->keyword != NULL; t++) {
1274 if (strcmp(s, t->keyword) == 0) {
1284 report_connect(const struct sockaddr *sa, socklen_t salen)
1286 char remote_host[NI_MAXHOST];
1287 char remote_port[NI_MAXSERV];
1289 int flags = NI_NUMERICSERV;
1292 flags |= NI_NUMERICHOST;
1294 if ((herr = getnameinfo(sa, salen,
1295 remote_host, sizeof(remote_host),
1296 remote_port, sizeof(remote_port),
1298 if (herr == EAI_SYSTEM)
1299 err(1, "getnameinfo");
1301 errx(1, "getnameinfo: %s", gai_strerror(herr));
1305 "Connection from %s %s "
1306 "received!\n", remote_host, remote_port);
1313 fprintf(stderr, "\tCommand Summary:\n\
1316 \t-D Enable the debug socket option\n\
1317 \t-d Detach from stdin\n");
1320 \t-E Use IPsec ESP\n\
1321 \t-e policy Use specified IPsec policy\n");
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\
1343 \t-V rtable Specify alternate routing table\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");
1351 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1358 add_ipsec_policy(int s, int af, char *policy)
1363 raw = ipsec_set_policy(policy, strlen(policy));
1365 errx(1, "ipsec_set_policy `%s': %s", policy,
1368 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1369 ipsec_get_policylen(raw));
1371 e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1372 ipsec_get_policylen(raw));
1374 err(1, "ipsec policy cannot be configured");
1377 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1387 "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1389 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
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");