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 SO_REUSEPORT");
744 ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
746 err(1, "setsockopt SO_REUSEADDR");
748 set_common_sockopts(s);
750 if (bind(s, (struct sockaddr *)res0->ai_addr,
751 res0->ai_addrlen) == 0)
756 } while ((res0 = res0->ai_next) != NULL);
758 if (!uflag && s != -1) {
759 if (listen(s, 1) < 0)
770 * Loop that polls on the network file descriptor and stdin.
773 readwrite(int net_fd)
775 struct pollfd pfd[4];
776 int stdin_fd = STDIN_FILENO;
777 int stdout_fd = STDOUT_FILENO;
778 unsigned char netinbuf[BUFSIZE];
779 size_t netinbufpos = 0;
780 unsigned char stdinbuf[BUFSIZE];
781 size_t stdinbufpos = 0;
785 /* don't read from stdin if requested */
790 pfd[POLL_STDIN].fd = stdin_fd;
791 pfd[POLL_STDIN].events = POLLIN;
794 pfd[POLL_NETOUT].fd = net_fd;
795 pfd[POLL_NETOUT].events = 0;
798 pfd[POLL_NETIN].fd = net_fd;
799 pfd[POLL_NETIN].events = POLLIN;
802 pfd[POLL_STDOUT].fd = stdout_fd;
803 pfd[POLL_STDOUT].events = 0;
806 /* both inputs are gone, buffers are empty, we are done */
807 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
808 && stdinbufpos == 0 && netinbufpos == 0) {
812 /* both outputs are gone, we can't continue */
813 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
817 /* listen and net in gone, queues empty, done */
818 if (lflag && pfd[POLL_NETIN].fd == -1
819 && stdinbufpos == 0 && netinbufpos == 0) {
824 /* help says -i is for "wait between lines sent". We read and
825 * write arbitrary amounts of data, and we don't want to start
826 * scanning for newlines, so this is as good as it gets */
831 num_fds = poll(pfd, 4, timeout);
833 /* treat poll errors */
836 err(1, "polling error");
839 /* timeout happened */
843 /* treat socket error conditions */
844 for (n = 0; n < 4; n++) {
845 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
849 /* reading is possible after HUP */
850 if (pfd[POLL_STDIN].events & POLLIN &&
851 pfd[POLL_STDIN].revents & POLLHUP &&
852 ! (pfd[POLL_STDIN].revents & POLLIN))
853 pfd[POLL_STDIN].fd = -1;
855 if (pfd[POLL_NETIN].events & POLLIN &&
856 pfd[POLL_NETIN].revents & POLLHUP &&
857 ! (pfd[POLL_NETIN].revents & POLLIN))
858 pfd[POLL_NETIN].fd = -1;
860 if (pfd[POLL_NETOUT].revents & POLLHUP) {
862 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
863 pfd[POLL_NETOUT].fd = -1;
865 /* if HUP, stop watching stdout */
866 if (pfd[POLL_STDOUT].revents & POLLHUP)
867 pfd[POLL_STDOUT].fd = -1;
868 /* if no net out, stop watching stdin */
869 if (pfd[POLL_NETOUT].fd == -1)
870 pfd[POLL_STDIN].fd = -1;
871 /* if no stdout, stop watching net in */
872 if (pfd[POLL_STDOUT].fd == -1) {
873 if (pfd[POLL_NETIN].fd != -1)
874 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
875 pfd[POLL_NETIN].fd = -1;
878 /* try to read from stdin */
879 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
880 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
882 /* error or eof on stdin - remove from pfd */
883 if (ret == 0 || ret == -1)
884 pfd[POLL_STDIN].fd = -1;
885 /* read something - poll net out */
887 pfd[POLL_NETOUT].events = POLLOUT;
888 /* filled buffer - remove self from polling */
889 if (stdinbufpos == BUFSIZE)
890 pfd[POLL_STDIN].events = 0;
892 /* try to write to network */
893 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
894 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
897 pfd[POLL_NETOUT].fd = -1;
898 /* buffer empty - remove self from polling */
899 if (stdinbufpos == 0)
900 pfd[POLL_NETOUT].events = 0;
901 /* buffer no longer full - poll stdin again */
902 if (stdinbufpos < BUFSIZE)
903 pfd[POLL_STDIN].events = POLLIN;
905 /* try to read from network */
906 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
907 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
910 pfd[POLL_NETIN].fd = -1;
911 /* eof on net in - remove from pfd */
913 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
914 pfd[POLL_NETIN].fd = -1;
916 /* read something - poll stdout */
918 pfd[POLL_STDOUT].events = POLLOUT;
919 /* filled buffer - remove self from polling */
920 if (netinbufpos == BUFSIZE)
921 pfd[POLL_NETIN].events = 0;
924 atelnet(pfd[POLL_NETIN].fd, netinbuf,
927 /* try to write to stdout */
928 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
929 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
932 pfd[POLL_STDOUT].fd = -1;
933 /* buffer empty - remove self from polling */
934 if (netinbufpos == 0)
935 pfd[POLL_STDOUT].events = 0;
936 /* buffer no longer full - poll net in again */
937 if (netinbufpos < BUFSIZE)
938 pfd[POLL_NETIN].events = POLLIN;
941 /* stdin gone and queue empty? */
942 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
943 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
944 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
945 pfd[POLL_NETOUT].fd = -1;
947 /* net in gone and queue empty? */
948 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
949 pfd[POLL_STDOUT].fd = -1;
955 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
960 n = write(fd, buf, *bufpos);
961 /* don't treat EAGAIN, EINTR as error */
962 if (n == -1 && (errno == EAGAIN || errno == EINTR))
967 adjust = *bufpos - n;
969 memmove(buf, buf + n, adjust);
976 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
978 size_t num = BUFSIZE - *bufpos;
981 n = read(fd, buf + *bufpos, num);
982 /* don't treat EAGAIN, EINTR as error */
983 if (n == -1 && (errno == EAGAIN || errno == EINTR))
993 * Pass the connected file descriptor to stdout and exit.
998 #if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR))
1000 #ifndef HAVE_ACCRIGHTS_IN_MSGHDR
1003 char buf[CMSG_SPACE(sizeof(int))];
1005 struct cmsghdr *cmsg;
1012 memset(&msg, 0, sizeof(msg));
1013 #ifdef HAVE_ACCRIGHTS_IN_MSGHDR
1014 msg.msg_accrights = (caddr_t)&nfd;
1015 msg.msg_accrightslen = sizeof(nfd);
1017 memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1018 msg.msg_control = (caddr_t)&cmsgbuf.buf;
1019 msg.msg_controllen = sizeof(cmsgbuf.buf);
1020 cmsg = CMSG_FIRSTHDR(&msg);
1021 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1022 cmsg->cmsg_level = SOL_SOCKET;
1023 cmsg->cmsg_type = SCM_RIGHTS;
1024 *(int *)CMSG_DATA(cmsg) = nfd;
1032 bzero(&pfd, sizeof(pfd));
1033 pfd.fd = STDOUT_FILENO;
1035 r = sendmsg(STDOUT_FILENO, &msg, 0);
1037 if (errno == EAGAIN || errno == EINTR) {
1038 pfd.events = POLLOUT;
1039 if (poll(&pfd, 1, -1) == -1)
1045 errx(1, "sendmsg: unexpected return value %zd", r);
1051 errx(1, "%s: file descriptor passing not supported", __func__);
1055 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1057 atelnet(int nfd, unsigned char *buf, unsigned int size)
1059 unsigned char *p, *end;
1060 unsigned char obuf[4];
1064 end = buf + size - 2;
1066 for (p = buf; p < end; p++) {
1072 if ((*p == WILL) || (*p == WONT))
1074 else if ((*p == DO) || (*p == DONT))
1081 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1082 warn("Write Error!");
1088 * Build an array of ports in portlist[], listing each port
1089 * that we should try to connect to.
1092 build_ports(char *p)
1099 if ((n = strchr(p, '-')) != NULL) {
1103 /* Make sure the ports are in order: lowest->highest. */
1104 hi = strtonum(n, 1, PORT_MAX, &errstr);
1106 errx(1, "port number %s: %s", errstr, n);
1107 lo = strtonum(p, 1, PORT_MAX, &errstr);
1109 errx(1, "port number %s: %s", errstr, p);
1117 /* Load ports sequentially. */
1118 for (cp = lo; cp <= hi; cp++) {
1119 portlist[x] = calloc(1, PORT_MAX_LEN);
1120 if (portlist[x] == NULL)
1122 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1126 /* Randomly swap ports. */
1131 for (x = 0; x <= (hi - lo); x++) {
1132 y = (arc4random() & 0xFFFF) % (hi - lo);
1134 portlist[x] = portlist[y];
1139 hi = strtonum(p, 1, PORT_MAX, &errstr);
1141 errx(1, "port number %s: %s", errstr, p);
1142 portlist[0] = strdup(p);
1143 if (portlist[0] == NULL)
1150 * Do a few writes to see if the UDP port is there.
1151 * Fails once PF state table is full.
1158 for (i = 0; i <= 3; i++) {
1159 if (write(s, "X", 1) == 1)
1168 set_common_sockopts(int s)
1174 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1175 &x, sizeof(x)) == -1)
1176 err(1, "setsockopt");
1180 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1181 &x, sizeof(x)) == -1)
1182 err(1, "setsockopt");
1185 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1186 &Tflag, sizeof(Tflag)) == -1)
1187 err(1, "set IP ToS");
1190 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1191 &Iflag, sizeof(Iflag)) == -1)
1192 err(1, "set TCP receive buffer size");
1195 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1196 &Oflag, sizeof(Oflag)) == -1)
1197 err(1, "set TCP send buffer size");
1202 map_tos(char *s, int *val)
1204 /* DiffServ Codepoints and other TOS mappings */
1205 const struct toskeywords {
1206 const char *keyword;
1208 } *t, toskeywords[] = {
1209 { "af11", IPTOS_DSCP_AF11 },
1210 { "af12", IPTOS_DSCP_AF12 },
1211 { "af13", IPTOS_DSCP_AF13 },
1212 { "af21", IPTOS_DSCP_AF21 },
1213 { "af22", IPTOS_DSCP_AF22 },
1214 { "af23", IPTOS_DSCP_AF23 },
1215 { "af31", IPTOS_DSCP_AF31 },
1216 { "af32", IPTOS_DSCP_AF32 },
1217 { "af33", IPTOS_DSCP_AF33 },
1218 { "af41", IPTOS_DSCP_AF41 },
1219 { "af42", IPTOS_DSCP_AF42 },
1220 { "af43", IPTOS_DSCP_AF43 },
1221 { "critical", IPTOS_PREC_CRITIC_ECP },
1222 { "cs0", IPTOS_DSCP_CS0 },
1223 { "cs1", IPTOS_DSCP_CS1 },
1224 { "cs2", IPTOS_DSCP_CS2 },
1225 { "cs3", IPTOS_DSCP_CS3 },
1226 { "cs4", IPTOS_DSCP_CS4 },
1227 { "cs5", IPTOS_DSCP_CS5 },
1228 { "cs6", IPTOS_DSCP_CS6 },
1229 { "cs7", IPTOS_DSCP_CS7 },
1230 { "ef", IPTOS_DSCP_EF },
1231 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1232 { "lowdelay", IPTOS_LOWDELAY },
1233 { "netcontrol", IPTOS_PREC_NETCONTROL },
1234 { "reliability", IPTOS_RELIABILITY },
1235 { "throughput", IPTOS_THROUGHPUT },
1239 for (t = toskeywords; t->keyword != NULL; t++) {
1240 if (strcmp(s, t->keyword) == 0) {
1250 report_connect(const struct sockaddr *sa, socklen_t salen)
1252 char remote_host[NI_MAXHOST];
1253 char remote_port[NI_MAXSERV];
1255 int flags = NI_NUMERICSERV;
1258 flags |= NI_NUMERICHOST;
1260 if ((herr = getnameinfo(sa, salen,
1261 remote_host, sizeof(remote_host),
1262 remote_port, sizeof(remote_port),
1264 if (herr == EAI_SYSTEM)
1265 err(1, "getnameinfo");
1267 errx(1, "getnameinfo: %s", gai_strerror(herr));
1271 "Connection from %s %s "
1272 "received!\n", remote_host, remote_port);
1279 fprintf(stderr, "\tCommand Summary:\n\
1282 \t-D Enable the debug socket option\n\
1283 \t-d Detach from stdin\n\
1284 \t-F Pass socket fd\n\
1285 \t-h This help text\n\
1286 \t-I length TCP receive buffer length\n\
1287 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1288 \t-k Keep inbound sockets open for multiple connects\n\
1289 \t-l Listen mode, for inbound connects\n\
1290 \t-N Shutdown the network socket after EOF on stdin\n\
1291 \t-n Suppress name/port resolutions\n\
1292 \t-O length TCP send buffer length\n\
1293 \t-P proxyuser\tUsername for proxy authentication\n\
1294 \t-p port\t Specify local port for remote connects\n\
1295 \t-r Randomize remote ports\n\
1296 \t-S Enable the TCP MD5 signature option\n\
1297 \t-s addr\t Local source address\n\
1298 \t-T toskeyword\tSet IP Type of Service\n\
1299 \t-t Answer TELNET negotiation\n\
1300 \t-U Use UNIX domain socket\n\
1302 \t-V rtable Specify alternate routing table\n\
1304 \t-w secs\t Timeout for connects and final net reads\n\
1305 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1306 \t-x addr[:port]\tSpecify proxy address and port\n\
1307 \t-z Zero-I/O mode [used for scanning]\n\
1308 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1316 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1317 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1318 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1319 "\t [-x proxy_address[:port]] [destination] [port]\n");
1324 /* *** src/usr.bin/nc/socks.c *** */
1327 /* $OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $ */
1330 * Copyright (c) 1999 Niklas Hallqvist. All rights reserved.
1331 * Copyright (c) 2004, 2005 Damien Miller. All rights reserved.
1333 * Redistribution and use in source and binary forms, with or without
1334 * modification, are permitted provided that the following conditions
1336 * 1. Redistributions of source code must retain the above copyright
1337 * notice, this list of conditions and the following disclaimer.
1338 * 2. Redistributions in binary form must reproduce the above copyright
1339 * notice, this list of conditions and the following disclaimer in the
1340 * documentation and/or other materials provided with the distribution.
1342 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1343 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1344 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1345 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1346 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1347 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1348 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1349 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1350 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1351 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1354 #include <sys/types.h>
1355 #include <sys/socket.h>
1356 #include <netinet/in.h>
1357 #include <arpa/inet.h>
1367 #define SOCKS_PORT "1080"
1368 #define HTTP_PROXY_PORT "3128"
1369 #define HTTP_MAXHDRS 64
1372 #define SOCKS_NOAUTH 0
1373 #define SOCKS_NOMETHOD 0xff
1374 #define SOCKS_CONNECT 1
1375 #define SOCKS_IPV4 1
1376 #define SOCKS_DOMAIN 3
1377 #define SOCKS_IPV6 4
1379 int remote_connect(const char *, const char *, struct addrinfo);
1380 int socks_connect(const char *, const char *, struct addrinfo,
1381 const char *, const char *, struct addrinfo, int,
1385 decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1386 socklen_t addrlen, int v4only, int numeric)
1389 struct addrinfo hints, *res;
1391 bzero(&hints, sizeof(hints));
1392 hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1393 hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1394 hints.ai_socktype = SOCK_STREAM;
1395 r = getaddrinfo(h, p, &hints, &res);
1396 /* Don't fatal when attempting to convert a numeric address */
1399 errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1404 if (addrlen < res->ai_addrlen) {
1406 errx(1, "internal error: addrlen < res->ai_addrlen");
1408 memcpy(addr, res->ai_addr, res->ai_addrlen);
1414 proxy_read_line(int fd, char *buf, size_t bufsz)
1420 errx(1, "proxy read too long");
1421 if (atomicio(read, fd, buf + off, 1) != 1)
1422 err(1, "proxy read");
1424 if (buf[off] == '\r')
1426 if (buf[off] == '\n') {
1436 getproxypass(const char *proxyuser, const char *proxyhost)
1439 static char pw[256];
1441 snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1442 proxyuser, proxyhost);
1443 if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1444 errx(1, "Unable to read proxy passphrase");
1449 socks_connect(const char *host, const char *port,
1450 struct addrinfo hints __attribute__ ((__unused__)),
1451 const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1452 int socksv, const char *proxyuser)
1454 int proxyfd, r, authretry = 0;
1455 size_t hlen, wlen = 0;
1456 unsigned char buf[1024];
1458 struct sockaddr_storage addr;
1459 struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1460 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1461 in_port_t serverport;
1462 const char *proxypass = NULL;
1464 if (proxyport == NULL)
1465 proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1467 /* Abuse API to lookup port */
1468 if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1469 sizeof(addr), 1, 1) == -1)
1470 errx(1, "unknown port \"%.64s\"", port);
1471 serverport = in4->sin_port;
1474 if (authretry++ > 3)
1475 errx(1, "Too many authentication failures");
1477 proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1483 if (decode_addrport(host, port, (struct sockaddr *)&addr,
1484 sizeof(addr), 0, 1) == -1)
1485 addr.ss_family = 0; /* used in switch below */
1487 /* Version 5, one method: no authentication */
1490 buf[2] = SOCKS_NOAUTH;
1491 cnt = atomicio(vwrite, proxyfd, buf, 3);
1493 err(1, "write failed (%zu/3)", cnt);
1495 cnt = atomicio(read, proxyfd, buf, 2);
1497 err(1, "read failed (%zu/3)", cnt);
1499 if (buf[1] == SOCKS_NOMETHOD)
1500 errx(1, "authentication method negotiation failed");
1502 switch (addr.ss_family) {
1504 /* Version 5, connect: domain name */
1506 /* Max domain name length is 255 bytes */
1507 hlen = strlen(host);
1509 errx(1, "host name too long for SOCKS5");
1511 buf[1] = SOCKS_CONNECT;
1513 buf[3] = SOCKS_DOMAIN;
1515 memcpy(buf + 5, host, hlen);
1516 memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1520 /* Version 5, connect: IPv4 address */
1522 buf[1] = SOCKS_CONNECT;
1524 buf[3] = SOCKS_IPV4;
1525 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1526 memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1530 /* Version 5, connect: IPv6 address */
1532 buf[1] = SOCKS_CONNECT;
1534 buf[3] = SOCKS_IPV6;
1535 memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1536 memcpy(buf + 20, &in6->sin6_port,
1537 sizeof in6->sin6_port);
1541 errx(1, "internal error: silly AF");
1544 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1546 err(1, "write failed (%zu/%zu)", cnt, wlen);
1548 cnt = atomicio(read, proxyfd, buf, 4);
1550 err(1, "read failed (%zu/4)", cnt);
1552 errx(1, "connection failed, SOCKS error %d", buf[1]);
1555 cnt = atomicio(read, proxyfd, buf + 4, 6);
1557 err(1, "read failed (%zu/6)", cnt);
1560 cnt = atomicio(read, proxyfd, buf + 4, 18);
1562 err(1, "read failed (%zu/18)", cnt);
1565 errx(1, "connection failed, unsupported address type");
1567 } else if (socksv == 4) {
1568 /* This will exit on lookup failure */
1569 decode_addrport(host, port, (struct sockaddr *)&addr,
1570 sizeof(addr), 1, 0);
1574 buf[1] = SOCKS_CONNECT; /* connect */
1575 memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1576 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1577 buf[8] = 0; /* empty username */
1580 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1582 err(1, "write failed (%zu/%zu)", cnt, wlen);
1584 cnt = atomicio(read, proxyfd, buf, 8);
1586 err(1, "read failed (%zu/8)", cnt);
1588 errx(1, "connection failed, SOCKS error %d", buf[1]);
1589 } else if (socksv == -1) {
1590 /* HTTP proxy CONNECT */
1592 /* Disallow bad chars in hostname */
1593 if (strcspn(host, "\r\n\t []:") != strlen(host))
1594 errx(1, "Invalid hostname");
1596 /* Try to be sane about numeric IPv6 addresses */
1597 if (strchr(host, ':') != NULL) {
1598 r = snprintf(buf, sizeof(buf),
1599 "CONNECT [%s]:%d HTTP/1.0\r\n",
1600 host, ntohs(serverport));
1602 r = snprintf(buf, sizeof(buf),
1603 "CONNECT %s:%d HTTP/1.0\r\n",
1604 host, ntohs(serverport));
1606 if (r == -1 || (size_t)r >= sizeof(buf))
1607 errx(1, "hostname too long");
1610 cnt = atomicio(vwrite, proxyfd, buf, r);
1611 if (cnt != (size_t)r)
1612 err(1, "write failed (%zu/%d)", cnt, r);
1614 if (authretry > 1) {
1617 proxypass = getproxypass(proxyuser, proxyhost);
1618 r = snprintf(buf, sizeof(buf), "%s:%s",
1619 proxyuser, proxypass);
1620 if (r == -1 || (size_t)r >= sizeof(buf) ||
1621 b64_ntop(buf, strlen(buf), resp,
1622 sizeof(resp)) == -1)
1623 errx(1, "Proxy username/password too long");
1624 r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1625 "Basic %s\r\n", resp);
1626 if (r == -1 || (size_t)r >= sizeof(buf))
1627 errx(1, "Proxy auth response too long");
1629 if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1630 err(1, "write failed (%zu/%d)", cnt, r);
1633 /* Terminate headers */
1634 if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1635 err(1, "write failed (2/%d)", r);
1637 /* Read status reply */
1638 proxy_read_line(proxyfd, buf, sizeof(buf));
1639 if (proxyuser != NULL &&
1640 strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1641 if (authretry > 1) {
1642 fprintf(stderr, "Proxy authentication "
1647 } else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1648 strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1649 errx(1, "Proxy error: \"%s\"", buf);
1651 /* Headers continue until we hit an empty line */
1652 for (r = 0; r < HTTP_MAXHDRS; r++) {
1653 proxy_read_line(proxyfd, buf, sizeof(buf));
1658 errx(1, "Too many proxy headers received");
1660 errx(1, "Unknown proxy protocol %d", socksv);