1 /* $OpenBSD: netcat.c,v 1.126 2014/10/30 16:08:31 tedu 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.
30 * Re-written nc(1) for OpenBSD. Original implementation by
31 * *Hobbit* <hobbit@avian.org>.
36 #include <sys/types.h>
37 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <netinet/ip.h>
60 # ifdef HAVE_SYS_POLL_H
61 # include <sys/poll.h>
68 /* Telnet options from arpa/telnet.h */
77 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
80 #define PORT_MAX 65535
81 #define PORT_MAX_LEN 6
82 #define UNIX_DG_TMP_SOCKET_SIZE 19
90 /* Command Line Options */
91 int dflag; /* detached, no stdin */
92 int Fflag; /* fdpass sock to stdout */
93 unsigned int iflag; /* Interval Flag */
94 int kflag; /* More than one connect */
95 int lflag; /* Bind to local port */
96 int Nflag; /* shutdown() network socket */
97 int nflag; /* Don't do name look up */
98 char *Pflag; /* Proxy username */
99 char *pflag; /* Localport flag */
100 int rflag; /* Random ports flag */
101 char *sflag; /* Source Address */
102 int tflag; /* Telnet Emulation */
103 int uflag; /* UDP - Default to TCP */
104 int vflag; /* Verbosity */
105 int xflag; /* Socks proxy */
106 int zflag; /* Port Scan Flag */
107 int Dflag; /* sodebug */
108 int Iflag; /* TCP receive buffer size */
109 int Oflag; /* TCP send buffer size */
110 int Sflag; /* TCP MD5 signature option */
111 int Tflag = -1; /* IP Type of Service */
115 int family = AF_UNSPEC;
116 char *portlist[PORT_MAX+1];
117 char *unix_dg_tmp_socket;
119 void atelnet(int, unsigned char *, unsigned int);
120 void build_ports(char *);
122 int local_listen(char *, char *, struct addrinfo);
124 void fdpass(int nfd) __attribute__((noreturn));
125 int remote_connect(const char *, const char *, struct addrinfo);
126 int timeout_connect(int, const struct sockaddr *, socklen_t);
127 int socks_connect(const char *, const char *, struct addrinfo,
128 const char *, const char *, struct addrinfo, int, const char *);
130 int unix_bind(char *);
131 int unix_connect(char *);
132 int unix_listen(char *);
133 void set_common_sockopts(int);
134 int map_tos(char *, int *);
135 void report_connect(const struct sockaddr *, socklen_t);
137 ssize_t drainbuf(int, unsigned char *, size_t *);
138 ssize_t fillbuf(int, unsigned char *, size_t *);
142 main(int argc, char *argv[])
144 int ch, s, ret, socksv;
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];
162 while ((ch = getopt(argc, argv,
163 "46DdFhI:i:klNnO:P:p:rSs:tT:UuV:vw:X:x:z")) != -1) {
175 if (strcasecmp(optarg, "connect") == 0)
176 socksv = -1; /* HTTP proxy CONNECT */
177 else if (strcmp(optarg, "4") == 0)
178 socksv = 4; /* SOCKS v.4 */
179 else if (strcmp(optarg, "5") == 0)
180 socksv = 5; /* SOCKS v.5 */
182 errx(1, "unsupported proxy protocol");
194 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
196 errx(1, "interval %s: %s", errstr, optarg);
230 rtableid = (int)strtonum(optarg, 0,
231 RT_TABLEID_MAX, &errstr);
233 errx(1, "rtable %s: %s", errstr, optarg);
240 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
242 errx(1, "timeout %s: %s", errstr, optarg);
247 if ((proxy = strdup(optarg)) == NULL)
257 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
259 errx(1, "TCP receive window %s: %s",
263 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
265 errx(1, "TCP send window %s: %s",
274 if (map_tos(optarg, &Tflag))
276 if (strlen(optarg) > 1 && optarg[0] == '0' &&
278 Tflag = (int)strtol(optarg, NULL, 16);
280 Tflag = (int)strtonum(optarg, 0, 255,
282 if (Tflag < 0 || Tflag > 255 || errstr || errno)
283 errx(1, "illegal tos value %s", optarg);
292 /* Cruft to make sure options are clean, and used properly. */
293 if (argv[0] && !argv[1] && family == AF_UNIX) {
296 } else if (argv[0] && !argv[1]) {
301 } else if (argv[0] && argv[1]) {
308 errx(1, "cannot use -s and -l");
310 errx(1, "cannot use -p and -l");
312 errx(1, "cannot use -z and -l");
314 errx(1, "must use -l with -k");
316 /* Get name of temporary socket for unix datagram client */
317 if ((family == AF_UNIX) && uflag && !lflag) {
319 unix_dg_tmp_socket = sflag;
321 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
322 UNIX_DG_TMP_SOCKET_SIZE);
323 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
325 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
329 /* Initialize addrinfo structure. */
330 if (family != AF_UNIX) {
331 memset(&hints, 0, sizeof(struct addrinfo));
332 hints.ai_family = family;
333 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
334 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
336 hints.ai_flags |= AI_NUMERICHOST;
341 errx(1, "no proxy support for UDP mode");
344 errx(1, "no proxy support for listen");
346 if (family == AF_UNIX)
347 errx(1, "no proxy support for unix sockets");
349 /* XXX IPv6 transport to proxy would probably work */
350 if (family == AF_INET6)
351 errx(1, "no proxy support for IPv6");
354 errx(1, "no proxy support for local source address");
356 proxyhost = strsep(&proxy, ":");
359 memset(&proxyhints, 0, sizeof(struct addrinfo));
360 proxyhints.ai_family = family;
361 proxyhints.ai_socktype = SOCK_STREAM;
362 proxyhints.ai_protocol = IPPROTO_TCP;
364 proxyhints.ai_flags |= AI_NUMERICHOST;
371 if (family == AF_UNIX) {
375 s = unix_listen(host);
378 /* Allow only one connection at a time, but stay alive. */
380 if (family != AF_UNIX)
381 s = local_listen(host, uport, hints);
383 err(1, "local_listen");
385 * For UDP and -k, don't connect the socket, let it
386 * receive datagrams from multiple socket pairs.
391 * For UDP and not -k, we will use recvfrom() initially
392 * to wait for a caller, then use the regular functions
393 * to talk to the caller.
395 else if (uflag && !kflag) {
398 struct sockaddr_storage z;
402 rv = recvfrom(s, buf, plen, MSG_PEEK,
403 (struct sockaddr *)&z, &len);
407 rv = connect(s, (struct sockaddr *)&z, len);
412 report_connect((struct sockaddr *)&z, len);
416 len = sizeof(cliaddr);
417 connfd = accept(s, (struct sockaddr *)&cliaddr,
420 /* For now, all errnos are fatal */
424 report_connect((struct sockaddr *)&cliaddr, len);
430 if (family != AF_UNIX)
433 if (connect(s, NULL, 0) < 0)
440 } else if (family == AF_UNIX) {
443 if ((s = unix_connect(host)) > 0 && !zflag) {
450 unlink(unix_dg_tmp_socket);
456 /* Construct the portlist[] array. */
459 /* Cycle through portlist, connecting to each port. */
460 for (i = 0; portlist[i] != NULL; i++) {
465 s = socks_connect(host, portlist[i], hints,
466 proxyhost, proxyport, proxyhints, socksv,
469 s = remote_connect(host, portlist[i], hints);
475 if (vflag || zflag) {
476 /* For UDP, make sure we are connected. */
478 if (udptest(s) == -1) {
484 /* Don't look up port if -n. */
489 ntohs(atoi(portlist[i])),
490 uflag ? "udp" : "tcp");
494 "Connection to %s %s port [%s/%s] "
495 "succeeded!\n", host, portlist[i],
496 uflag ? "udp" : "tcp",
497 sv ? sv->s_name : "*");
514 * Returns a unix socket bound to the given path
517 unix_bind(char *path)
519 struct sockaddr_un sun_sa;
522 /* Create unix domain socket. */
523 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
527 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
528 sun_sa.sun_family = AF_UNIX;
530 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
531 sizeof(sun_sa.sun_path)) {
533 errno = ENAMETOOLONG;
537 if (bind(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
546 * Returns a socket connected to a local unix socket. Returns -1 on failure.
549 unix_connect(char *path)
551 struct sockaddr_un sun_sa;
555 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
558 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
561 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
563 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
564 sun_sa.sun_family = AF_UNIX;
566 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
567 sizeof(sun_sa.sun_path)) {
569 errno = ENAMETOOLONG;
572 if (connect(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
582 * Create a unix domain socket, and listen on it.
585 unix_listen(char *path)
588 if ((s = unix_bind(path)) < 0)
591 if (listen(s, 5) < 0) {
600 * Returns a socket connected to a remote host. Properly binds to a local
601 * port or source address if needed. Returns -1 on failure.
604 remote_connect(const char *host, const char *port, struct addrinfo hints)
606 struct addrinfo *res, *res0;
608 #if defined(SO_RTABLE) || defined(SO_BINDANY)
612 if ((error = getaddrinfo(host, port, &hints, &res)))
613 errx(1, "getaddrinfo: %s", gai_strerror(error));
617 if ((s = socket(res0->ai_family, res0->ai_socktype,
618 res0->ai_protocol)) < 0)
622 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
623 &rtableid, sizeof(rtableid)) == -1))
624 err(1, "setsockopt SO_RTABLE");
626 /* Bind to a local port or source address if specified. */
627 if (sflag || pflag) {
628 struct addrinfo ahints, *ares;
631 /* try SO_BINDANY, but don't insist */
632 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
634 memset(&ahints, 0, sizeof(struct addrinfo));
635 ahints.ai_family = res0->ai_family;
636 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
637 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
638 ahints.ai_flags = AI_PASSIVE;
639 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
640 errx(1, "getaddrinfo: %s", gai_strerror(error));
642 if (bind(s, (struct sockaddr *)ares->ai_addr,
643 ares->ai_addrlen) < 0)
644 err(1, "bind failed");
648 set_common_sockopts(s);
650 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
653 warn("connect to %s port %s (%s) failed", host, port,
654 uflag ? "udp" : "tcp");
658 } while ((res0 = res0->ai_next) != NULL);
666 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
670 int flags = 0, optval;
674 flags = fcntl(s, F_GETFL, 0);
675 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
676 err(1, "set non-blocking mode");
679 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
681 pfd.events = POLLOUT;
682 if ((ret = poll(&pfd, 1, timeout)) == 1) {
683 optlen = sizeof(optval);
684 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
685 &optval, &optlen)) == 0) {
687 ret = optval == 0 ? 0 : -1;
689 } else if (ret == 0) {
693 err(1, "poll failed");
696 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
697 err(1, "restoring flags");
704 * Returns a socket listening on a local port, binds to specified source
705 * address. Returns -1 on failure.
708 local_listen(char *host, char *port, struct addrinfo hints)
710 struct addrinfo *res, *res0;
714 /* Allow nodename to be null. */
715 hints.ai_flags |= AI_PASSIVE;
718 * In the case of binding to a wildcard address
719 * default to binding to an ipv4 address.
721 if (host == NULL && hints.ai_family == AF_UNSPEC)
722 hints.ai_family = AF_INET;
724 if ((error = getaddrinfo(host, port, &hints, &res)))
725 errx(1, "getaddrinfo: %s", gai_strerror(error));
729 if ((s = socket(res0->ai_family, res0->ai_socktype,
730 res0->ai_protocol)) < 0)
734 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
735 &rtableid, sizeof(rtableid)) == -1))
736 err(1, "setsockopt SO_RTABLE");
739 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
741 err(1, "setsockopt");
743 set_common_sockopts(s);
745 if (bind(s, (struct sockaddr *)res0->ai_addr,
746 res0->ai_addrlen) == 0)
751 } while ((res0 = res0->ai_next) != NULL);
753 if (!uflag && s != -1) {
754 if (listen(s, 1) < 0)
765 * Loop that polls on the network file descriptor and stdin.
768 readwrite(int net_fd)
770 struct pollfd pfd[4];
771 int stdin_fd = STDIN_FILENO;
772 int stdout_fd = STDOUT_FILENO;
773 unsigned char netinbuf[BUFSIZE];
774 size_t netinbufpos = 0;
775 unsigned char stdinbuf[BUFSIZE];
776 size_t stdinbufpos = 0;
780 /* don't read from stdin if requested */
785 pfd[POLL_STDIN].fd = stdin_fd;
786 pfd[POLL_STDIN].events = POLLIN;
789 pfd[POLL_NETOUT].fd = net_fd;
790 pfd[POLL_NETOUT].events = 0;
793 pfd[POLL_NETIN].fd = net_fd;
794 pfd[POLL_NETIN].events = POLLIN;
797 pfd[POLL_STDOUT].fd = stdout_fd;
798 pfd[POLL_STDOUT].events = 0;
801 /* both inputs are gone, buffers are empty, we are done */
802 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
803 && stdinbufpos == 0 && netinbufpos == 0) {
807 /* both outputs are gone, we can't continue */
808 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
812 /* listen and net in gone, queues empty, done */
813 if (lflag && pfd[POLL_NETIN].fd == -1
814 && stdinbufpos == 0 && netinbufpos == 0) {
819 /* help says -i is for "wait between lines sent". We read and
820 * write arbitrary amounts of data, and we don't want to start
821 * scanning for newlines, so this is as good as it gets */
826 num_fds = poll(pfd, 4, timeout);
828 /* treat poll errors */
831 err(1, "polling error");
834 /* timeout happened */
838 /* treat socket error conditions */
839 for (n = 0; n < 4; n++) {
840 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
844 /* reading is possible after HUP */
845 if (pfd[POLL_STDIN].events & POLLIN &&
846 pfd[POLL_STDIN].revents & POLLHUP &&
847 ! (pfd[POLL_STDIN].revents & POLLIN))
848 pfd[POLL_STDIN].fd = -1;
850 if (pfd[POLL_NETIN].events & POLLIN &&
851 pfd[POLL_NETIN].revents & POLLHUP &&
852 ! (pfd[POLL_NETIN].revents & POLLIN))
853 pfd[POLL_NETIN].fd = -1;
855 if (pfd[POLL_NETOUT].revents & POLLHUP) {
857 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
858 pfd[POLL_NETOUT].fd = -1;
860 /* if HUP, stop watching stdout */
861 if (pfd[POLL_STDOUT].revents & POLLHUP)
862 pfd[POLL_STDOUT].fd = -1;
863 /* if no net out, stop watching stdin */
864 if (pfd[POLL_NETOUT].fd == -1)
865 pfd[POLL_STDIN].fd = -1;
866 /* if no stdout, stop watching net in */
867 if (pfd[POLL_STDOUT].fd == -1) {
868 if (pfd[POLL_NETIN].fd != -1)
869 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
870 pfd[POLL_NETIN].fd = -1;
873 /* try to read from stdin */
874 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
875 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
877 /* error or eof on stdin - remove from pfd */
878 if (ret == 0 || ret == -1)
879 pfd[POLL_STDIN].fd = -1;
880 /* read something - poll net out */
882 pfd[POLL_NETOUT].events = POLLOUT;
883 /* filled buffer - remove self from polling */
884 if (stdinbufpos == BUFSIZE)
885 pfd[POLL_STDIN].events = 0;
887 /* try to write to network */
888 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
889 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
892 pfd[POLL_NETOUT].fd = -1;
893 /* buffer empty - remove self from polling */
894 if (stdinbufpos == 0)
895 pfd[POLL_NETOUT].events = 0;
896 /* buffer no longer full - poll stdin again */
897 if (stdinbufpos < BUFSIZE)
898 pfd[POLL_STDIN].events = POLLIN;
900 /* try to read from network */
901 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
902 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
905 pfd[POLL_NETIN].fd = -1;
906 /* eof on net in - remove from pfd */
908 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
909 pfd[POLL_NETIN].fd = -1;
911 /* read something - poll stdout */
913 pfd[POLL_STDOUT].events = POLLOUT;
914 /* filled buffer - remove self from polling */
915 if (netinbufpos == BUFSIZE)
916 pfd[POLL_NETIN].events = 0;
919 atelnet(pfd[POLL_NETIN].fd, netinbuf,
922 /* try to write to stdout */
923 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
924 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
927 pfd[POLL_STDOUT].fd = -1;
928 /* buffer empty - remove self from polling */
929 if (netinbufpos == 0)
930 pfd[POLL_STDOUT].events = 0;
931 /* buffer no longer full - poll net in again */
932 if (netinbufpos < BUFSIZE)
933 pfd[POLL_NETIN].events = POLLIN;
936 /* stdin gone and queue empty? */
937 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
938 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
939 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
940 pfd[POLL_NETOUT].fd = -1;
942 /* net in gone and queue empty? */
943 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
944 pfd[POLL_STDOUT].fd = -1;
950 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
955 n = write(fd, buf, *bufpos);
956 /* don't treat EAGAIN, EINTR as error */
957 if (n == -1 && (errno == EAGAIN || errno == EINTR))
962 adjust = *bufpos - n;
964 memmove(buf, buf + n, adjust);
971 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
973 size_t num = BUFSIZE - *bufpos;
976 n = read(fd, buf + *bufpos, num);
977 /* don't treat EAGAIN, EINTR as error */
978 if (n == -1 && (errno == EAGAIN || errno == EINTR))
988 * Pass the connected file descriptor to stdout and exit.
993 #if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR))
995 #ifndef HAVE_ACCRIGHTS_IN_MSGHDR
998 char buf[CMSG_SPACE(sizeof(int))];
1000 struct cmsghdr *cmsg;
1007 memset(&msg, 0, sizeof(msg));
1008 #ifdef HAVE_ACCRIGHTS_IN_MSGHDR
1009 msg.msg_accrights = (caddr_t)&nfd;
1010 msg.msg_accrightslen = sizeof(nfd);
1012 memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1013 msg.msg_control = (caddr_t)&cmsgbuf.buf;
1014 msg.msg_controllen = sizeof(cmsgbuf.buf);
1015 cmsg = CMSG_FIRSTHDR(&msg);
1016 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1017 cmsg->cmsg_level = SOL_SOCKET;
1018 cmsg->cmsg_type = SCM_RIGHTS;
1019 *(int *)CMSG_DATA(cmsg) = nfd;
1027 bzero(&pfd, sizeof(pfd));
1028 pfd.fd = STDOUT_FILENO;
1030 r = sendmsg(STDOUT_FILENO, &msg, 0);
1032 if (errno == EAGAIN || errno == EINTR) {
1033 pfd.events = POLLOUT;
1034 if (poll(&pfd, 1, -1) == -1)
1040 errx(1, "sendmsg: unexpected return value %zd", r);
1046 errx(1, "%s: file descriptor passing not supported", __func__);
1050 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1052 atelnet(int nfd, unsigned char *buf, unsigned int size)
1054 unsigned char *p, *end;
1055 unsigned char obuf[4];
1059 end = buf + size - 2;
1061 for (p = buf; p < end; p++) {
1067 if ((*p == WILL) || (*p == WONT))
1069 else if ((*p == DO) || (*p == DONT))
1076 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1077 warn("Write Error!");
1083 * Build an array of ports in portlist[], listing each port
1084 * that we should try to connect to.
1087 build_ports(char *p)
1094 if ((n = strchr(p, '-')) != NULL) {
1098 /* Make sure the ports are in order: lowest->highest. */
1099 hi = strtonum(n, 1, PORT_MAX, &errstr);
1101 errx(1, "port number %s: %s", errstr, n);
1102 lo = strtonum(p, 1, PORT_MAX, &errstr);
1104 errx(1, "port number %s: %s", errstr, p);
1112 /* Load ports sequentially. */
1113 for (cp = lo; cp <= hi; cp++) {
1114 portlist[x] = calloc(1, PORT_MAX_LEN);
1115 if (portlist[x] == NULL)
1117 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1121 /* Randomly swap ports. */
1126 for (x = 0; x <= (hi - lo); x++) {
1127 y = (arc4random() & 0xFFFF) % (hi - lo);
1129 portlist[x] = portlist[y];
1134 hi = strtonum(p, 1, PORT_MAX, &errstr);
1136 errx(1, "port number %s: %s", errstr, p);
1137 portlist[0] = strdup(p);
1138 if (portlist[0] == NULL)
1145 * Do a few writes to see if the UDP port is there.
1146 * Fails once PF state table is full.
1153 for (i = 0; i <= 3; i++) {
1154 if (write(s, "X", 1) == 1)
1163 set_common_sockopts(int s)
1169 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1170 &x, sizeof(x)) == -1)
1171 err(1, "setsockopt");
1175 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1176 &x, sizeof(x)) == -1)
1177 err(1, "setsockopt");
1180 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1181 &Tflag, sizeof(Tflag)) == -1)
1182 err(1, "set IP ToS");
1185 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1186 &Iflag, sizeof(Iflag)) == -1)
1187 err(1, "set TCP receive buffer size");
1190 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1191 &Oflag, sizeof(Oflag)) == -1)
1192 err(1, "set TCP send buffer size");
1197 map_tos(char *s, int *val)
1199 /* DiffServ Codepoints and other TOS mappings */
1200 const struct toskeywords {
1201 const char *keyword;
1203 } *t, toskeywords[] = {
1204 { "af11", IPTOS_DSCP_AF11 },
1205 { "af12", IPTOS_DSCP_AF12 },
1206 { "af13", IPTOS_DSCP_AF13 },
1207 { "af21", IPTOS_DSCP_AF21 },
1208 { "af22", IPTOS_DSCP_AF22 },
1209 { "af23", IPTOS_DSCP_AF23 },
1210 { "af31", IPTOS_DSCP_AF31 },
1211 { "af32", IPTOS_DSCP_AF32 },
1212 { "af33", IPTOS_DSCP_AF33 },
1213 { "af41", IPTOS_DSCP_AF41 },
1214 { "af42", IPTOS_DSCP_AF42 },
1215 { "af43", IPTOS_DSCP_AF43 },
1216 { "critical", IPTOS_PREC_CRITIC_ECP },
1217 { "cs0", IPTOS_DSCP_CS0 },
1218 { "cs1", IPTOS_DSCP_CS1 },
1219 { "cs2", IPTOS_DSCP_CS2 },
1220 { "cs3", IPTOS_DSCP_CS3 },
1221 { "cs4", IPTOS_DSCP_CS4 },
1222 { "cs5", IPTOS_DSCP_CS5 },
1223 { "cs6", IPTOS_DSCP_CS6 },
1224 { "cs7", IPTOS_DSCP_CS7 },
1225 { "ef", IPTOS_DSCP_EF },
1226 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1227 { "lowdelay", IPTOS_LOWDELAY },
1228 { "netcontrol", IPTOS_PREC_NETCONTROL },
1229 { "reliability", IPTOS_RELIABILITY },
1230 { "throughput", IPTOS_THROUGHPUT },
1234 for (t = toskeywords; t->keyword != NULL; t++) {
1235 if (strcmp(s, t->keyword) == 0) {
1245 report_connect(const struct sockaddr *sa, socklen_t salen)
1247 char remote_host[NI_MAXHOST];
1248 char remote_port[NI_MAXSERV];
1250 int flags = NI_NUMERICSERV;
1253 flags |= NI_NUMERICHOST;
1255 if ((herr = getnameinfo(sa, salen,
1256 remote_host, sizeof(remote_host),
1257 remote_port, sizeof(remote_port),
1259 if (herr == EAI_SYSTEM)
1260 err(1, "getnameinfo");
1262 errx(1, "getnameinfo: %s", gai_strerror(herr));
1266 "Connection from %s %s "
1267 "received!\n", remote_host, remote_port);
1274 fprintf(stderr, "\tCommand Summary:\n\
1277 \t-D Enable the debug socket option\n\
1278 \t-d Detach from stdin\n\
1279 \t-F Pass socket fd\n\
1280 \t-h This help text\n\
1281 \t-I length TCP receive buffer length\n\
1282 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1283 \t-k Keep inbound sockets open for multiple connects\n\
1284 \t-l Listen mode, for inbound connects\n\
1285 \t-N Shutdown the network socket after EOF on stdin\n\
1286 \t-n Suppress name/port resolutions\n\
1287 \t-O length TCP send buffer length\n\
1288 \t-P proxyuser\tUsername for proxy authentication\n\
1289 \t-p port\t Specify local port for remote connects\n\
1290 \t-r Randomize remote ports\n\
1291 \t-S Enable the TCP MD5 signature option\n\
1292 \t-s addr\t Local source address\n\
1293 \t-T toskeyword\tSet IP Type of Service\n\
1294 \t-t Answer TELNET negotiation\n\
1295 \t-U Use UNIX domain socket\n\
1297 \t-V rtable Specify alternate routing table\n\
1299 \t-w secs\t Timeout for connects and final net reads\n\
1300 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1301 \t-x addr[:port]\tSpecify proxy address and port\n\
1302 \t-z Zero-I/O mode [used for scanning]\n\
1303 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1311 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1312 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1313 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1314 "\t [-x proxy_address[:port]] [destination] [port]\n");
1319 /* *** src/usr.bin/nc/socks.c *** */
1322 /* $OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $ */
1325 * Copyright (c) 1999 Niklas Hallqvist. All rights reserved.
1326 * Copyright (c) 2004, 2005 Damien Miller. All rights reserved.
1328 * Redistribution and use in source and binary forms, with or without
1329 * modification, are permitted provided that the following conditions
1331 * 1. Redistributions of source code must retain the above copyright
1332 * notice, this list of conditions and the following disclaimer.
1333 * 2. Redistributions in binary form must reproduce the above copyright
1334 * notice, this list of conditions and the following disclaimer in the
1335 * documentation and/or other materials provided with the distribution.
1337 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1338 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1339 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1340 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1341 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1342 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1343 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1344 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1345 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1346 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1349 #include <sys/types.h>
1350 #include <sys/socket.h>
1351 #include <netinet/in.h>
1352 #include <arpa/inet.h>
1362 #define SOCKS_PORT "1080"
1363 #define HTTP_PROXY_PORT "3128"
1364 #define HTTP_MAXHDRS 64
1367 #define SOCKS_NOAUTH 0
1368 #define SOCKS_NOMETHOD 0xff
1369 #define SOCKS_CONNECT 1
1370 #define SOCKS_IPV4 1
1371 #define SOCKS_DOMAIN 3
1372 #define SOCKS_IPV6 4
1374 int remote_connect(const char *, const char *, struct addrinfo);
1375 int socks_connect(const char *, const char *, struct addrinfo,
1376 const char *, const char *, struct addrinfo, int,
1380 decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1381 socklen_t addrlen, int v4only, int numeric)
1384 struct addrinfo hints, *res;
1386 bzero(&hints, sizeof(hints));
1387 hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1388 hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1389 hints.ai_socktype = SOCK_STREAM;
1390 r = getaddrinfo(h, p, &hints, &res);
1391 /* Don't fatal when attempting to convert a numeric address */
1394 errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1399 if (addrlen < res->ai_addrlen) {
1401 errx(1, "internal error: addrlen < res->ai_addrlen");
1403 memcpy(addr, res->ai_addr, res->ai_addrlen);
1409 proxy_read_line(int fd, char *buf, size_t bufsz)
1415 errx(1, "proxy read too long");
1416 if (atomicio(read, fd, buf + off, 1) != 1)
1417 err(1, "proxy read");
1419 if (buf[off] == '\r')
1421 if (buf[off] == '\n') {
1431 getproxypass(const char *proxyuser, const char *proxyhost)
1434 static char pw[256];
1436 snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1437 proxyuser, proxyhost);
1438 if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1439 errx(1, "Unable to read proxy passphrase");
1444 socks_connect(const char *host, const char *port,
1445 struct addrinfo hints __attribute__ ((__unused__)),
1446 const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1447 int socksv, const char *proxyuser)
1449 int proxyfd, r, authretry = 0;
1450 size_t hlen, wlen = 0;
1451 unsigned char buf[1024];
1453 struct sockaddr_storage addr;
1454 struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1455 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1456 in_port_t serverport;
1457 const char *proxypass = NULL;
1459 if (proxyport == NULL)
1460 proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1462 /* Abuse API to lookup port */
1463 if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1464 sizeof(addr), 1, 1) == -1)
1465 errx(1, "unknown port \"%.64s\"", port);
1466 serverport = in4->sin_port;
1469 if (authretry++ > 3)
1470 errx(1, "Too many authentication failures");
1472 proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1478 if (decode_addrport(host, port, (struct sockaddr *)&addr,
1479 sizeof(addr), 0, 1) == -1)
1480 addr.ss_family = 0; /* used in switch below */
1482 /* Version 5, one method: no authentication */
1485 buf[2] = SOCKS_NOAUTH;
1486 cnt = atomicio(vwrite, proxyfd, buf, 3);
1488 err(1, "write failed (%zu/3)", cnt);
1490 cnt = atomicio(read, proxyfd, buf, 2);
1492 err(1, "read failed (%zu/3)", cnt);
1494 if (buf[1] == SOCKS_NOMETHOD)
1495 errx(1, "authentication method negotiation failed");
1497 switch (addr.ss_family) {
1499 /* Version 5, connect: domain name */
1501 /* Max domain name length is 255 bytes */
1502 hlen = strlen(host);
1504 errx(1, "host name too long for SOCKS5");
1506 buf[1] = SOCKS_CONNECT;
1508 buf[3] = SOCKS_DOMAIN;
1510 memcpy(buf + 5, host, hlen);
1511 memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1515 /* Version 5, connect: IPv4 address */
1517 buf[1] = SOCKS_CONNECT;
1519 buf[3] = SOCKS_IPV4;
1520 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1521 memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1525 /* Version 5, connect: IPv6 address */
1527 buf[1] = SOCKS_CONNECT;
1529 buf[3] = SOCKS_IPV6;
1530 memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1531 memcpy(buf + 20, &in6->sin6_port,
1532 sizeof in6->sin6_port);
1536 errx(1, "internal error: silly AF");
1539 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1541 err(1, "write failed (%zu/%zu)", cnt, wlen);
1543 cnt = atomicio(read, proxyfd, buf, 4);
1545 err(1, "read failed (%zu/4)", cnt);
1547 errx(1, "connection failed, SOCKS error %d", buf[1]);
1550 cnt = atomicio(read, proxyfd, buf + 4, 6);
1552 err(1, "read failed (%zu/6)", cnt);
1555 cnt = atomicio(read, proxyfd, buf + 4, 18);
1557 err(1, "read failed (%zu/18)", cnt);
1560 errx(1, "connection failed, unsupported address type");
1562 } else if (socksv == 4) {
1563 /* This will exit on lookup failure */
1564 decode_addrport(host, port, (struct sockaddr *)&addr,
1565 sizeof(addr), 1, 0);
1569 buf[1] = SOCKS_CONNECT; /* connect */
1570 memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1571 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1572 buf[8] = 0; /* empty username */
1575 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1577 err(1, "write failed (%zu/%zu)", cnt, wlen);
1579 cnt = atomicio(read, proxyfd, buf, 8);
1581 err(1, "read failed (%zu/8)", cnt);
1583 errx(1, "connection failed, SOCKS error %d", buf[1]);
1584 } else if (socksv == -1) {
1585 /* HTTP proxy CONNECT */
1587 /* Disallow bad chars in hostname */
1588 if (strcspn(host, "\r\n\t []:") != strlen(host))
1589 errx(1, "Invalid hostname");
1591 /* Try to be sane about numeric IPv6 addresses */
1592 if (strchr(host, ':') != NULL) {
1593 r = snprintf(buf, sizeof(buf),
1594 "CONNECT [%s]:%d HTTP/1.0\r\n",
1595 host, ntohs(serverport));
1597 r = snprintf(buf, sizeof(buf),
1598 "CONNECT %s:%d HTTP/1.0\r\n",
1599 host, ntohs(serverport));
1601 if (r == -1 || (size_t)r >= sizeof(buf))
1602 errx(1, "hostname too long");
1605 cnt = atomicio(vwrite, proxyfd, buf, r);
1606 if (cnt != (size_t)r)
1607 err(1, "write failed (%zu/%d)", cnt, r);
1609 if (authretry > 1) {
1612 proxypass = getproxypass(proxyuser, proxyhost);
1613 r = snprintf(buf, sizeof(buf), "%s:%s",
1614 proxyuser, proxypass);
1615 if (r == -1 || (size_t)r >= sizeof(buf) ||
1616 b64_ntop(buf, strlen(buf), resp,
1617 sizeof(resp)) == -1)
1618 errx(1, "Proxy username/password too long");
1619 r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1620 "Basic %s\r\n", resp);
1621 if (r == -1 || (size_t)r >= sizeof(buf))
1622 errx(1, "Proxy auth response too long");
1624 if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1625 err(1, "write failed (%zu/%d)", cnt, r);
1628 /* Terminate headers */
1629 if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1630 err(1, "write failed (2/%d)", r);
1632 /* Read status reply */
1633 proxy_read_line(proxyfd, buf, sizeof(buf));
1634 if (proxyuser != NULL &&
1635 strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1636 if (authretry > 1) {
1637 fprintf(stderr, "Proxy authentication "
1642 } else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1643 strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1644 errx(1, "Proxy error: \"%s\"", buf);
1646 /* Headers continue until we hit an empty line */
1647 for (r = 0; r < HTTP_MAXHDRS; r++) {
1648 proxy_read_line(proxyfd, buf, sizeof(buf));
1653 errx(1, "Too many proxy headers received");
1655 errx(1, "Unknown proxy protocol %d", socksv);