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>
65 /* Telnet options from arpa/telnet.h */
74 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
77 #define PORT_MAX 65535
78 #define PORT_MAX_LEN 6
79 #define UNIX_DG_TMP_SOCKET_SIZE 19
87 /* Command Line Options */
88 int dflag; /* detached, no stdin */
89 int Fflag; /* fdpass sock to stdout */
90 unsigned int iflag; /* Interval Flag */
91 int kflag; /* More than one connect */
92 int lflag; /* Bind to local port */
93 int Nflag; /* shutdown() network socket */
94 int nflag; /* Don't do name look up */
95 char *Pflag; /* Proxy username */
96 char *pflag; /* Localport flag */
97 int rflag; /* Random ports flag */
98 char *sflag; /* Source Address */
99 int tflag; /* Telnet Emulation */
100 int uflag; /* UDP - Default to TCP */
101 int vflag; /* Verbosity */
102 int xflag; /* Socks proxy */
103 int zflag; /* Port Scan Flag */
104 int Dflag; /* sodebug */
105 int Iflag; /* TCP receive buffer size */
106 int Oflag; /* TCP send buffer size */
107 int Sflag; /* TCP MD5 signature option */
108 int Tflag = -1; /* IP Type of Service */
112 int family = AF_UNSPEC;
113 char *portlist[PORT_MAX+1];
114 char *unix_dg_tmp_socket;
116 void atelnet(int, unsigned char *, unsigned int);
117 void build_ports(char *);
119 int local_listen(char *, char *, struct addrinfo);
121 void fdpass(int nfd) __attribute__((noreturn));
122 int remote_connect(const char *, const char *, struct addrinfo);
123 int timeout_connect(int, const struct sockaddr *, socklen_t);
124 int socks_connect(const char *, const char *, struct addrinfo,
125 const char *, const char *, struct addrinfo, int, const char *);
127 int unix_bind(char *);
128 int unix_connect(char *);
129 int unix_listen(char *);
130 void set_common_sockopts(int);
131 int map_tos(char *, int *);
132 void report_connect(const struct sockaddr *, socklen_t);
134 ssize_t drainbuf(int, unsigned char *, size_t *);
135 ssize_t fillbuf(int, unsigned char *, size_t *);
137 static void err(int, const char *, ...) __attribute__((format(printf, 2, 3)));
138 static void errx(int, const char *, ...) __attribute__((format(printf, 2, 3)));
139 static void warn(const char *, ...) __attribute__((format(printf, 1, 2)));
142 err(int r, const char *fmt, ...)
147 fprintf(stderr, "%s: ", strerror(errno));
148 vfprintf(stderr, fmt, args);
155 errx(int r, const char *fmt, ...)
160 vfprintf(stderr, fmt, args);
167 warn(const char *fmt, ...)
172 fprintf(stderr, "%s: ", strerror(errno));
173 vfprintf(stderr, fmt, args);
179 main(int argc, char *argv[])
181 int ch, s, ret, socksv;
183 struct addrinfo hints;
186 struct sockaddr_storage cliaddr;
188 const char *errstr, *proxyhost = "", *proxyport = NULL;
189 struct addrinfo proxyhints;
190 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
199 while ((ch = getopt(argc, argv,
200 "46DdFhI:i:klNnO:P:p:rSs:tT:UuV:vw:X:x:z")) != -1) {
212 if (strcasecmp(optarg, "connect") == 0)
213 socksv = -1; /* HTTP proxy CONNECT */
214 else if (strcmp(optarg, "4") == 0)
215 socksv = 4; /* SOCKS v.4 */
216 else if (strcmp(optarg, "5") == 0)
217 socksv = 5; /* SOCKS v.5 */
219 errx(1, "unsupported proxy protocol");
231 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
233 errx(1, "interval %s: %s", errstr, optarg);
267 rtableid = (int)strtonum(optarg, 0,
268 RT_TABLEID_MAX, &errstr);
270 errx(1, "rtable %s: %s", errstr, optarg);
277 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
279 errx(1, "timeout %s: %s", errstr, optarg);
284 if ((proxy = strdup(optarg)) == NULL)
294 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
296 errx(1, "TCP receive window %s: %s",
300 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
302 errx(1, "TCP send window %s: %s",
311 if (map_tos(optarg, &Tflag))
313 if (strlen(optarg) > 1 && optarg[0] == '0' &&
315 Tflag = (int)strtol(optarg, NULL, 16);
317 Tflag = (int)strtonum(optarg, 0, 255,
319 if (Tflag < 0 || Tflag > 255 || errstr || errno)
320 errx(1, "illegal tos value %s", optarg);
329 /* Cruft to make sure options are clean, and used properly. */
330 if (argv[0] && !argv[1] && family == AF_UNIX) {
333 } else if (argv[0] && !argv[1]) {
338 } else if (argv[0] && argv[1]) {
345 errx(1, "cannot use -s and -l");
347 errx(1, "cannot use -p and -l");
349 errx(1, "cannot use -z and -l");
351 errx(1, "must use -l with -k");
353 /* Get name of temporary socket for unix datagram client */
354 if ((family == AF_UNIX) && uflag && !lflag) {
356 unix_dg_tmp_socket = sflag;
358 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
359 UNIX_DG_TMP_SOCKET_SIZE);
360 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
362 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
366 /* Initialize addrinfo structure. */
367 if (family != AF_UNIX) {
368 memset(&hints, 0, sizeof(struct addrinfo));
369 hints.ai_family = family;
370 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
371 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
373 hints.ai_flags |= AI_NUMERICHOST;
378 errx(1, "no proxy support for UDP mode");
381 errx(1, "no proxy support for listen");
383 if (family == AF_UNIX)
384 errx(1, "no proxy support for unix sockets");
386 /* XXX IPv6 transport to proxy would probably work */
387 if (family == AF_INET6)
388 errx(1, "no proxy support for IPv6");
391 errx(1, "no proxy support for local source address");
393 proxyhost = strsep(&proxy, ":");
396 memset(&proxyhints, 0, sizeof(struct addrinfo));
397 proxyhints.ai_family = family;
398 proxyhints.ai_socktype = SOCK_STREAM;
399 proxyhints.ai_protocol = IPPROTO_TCP;
401 proxyhints.ai_flags |= AI_NUMERICHOST;
408 if (family == AF_UNIX) {
412 s = unix_listen(host);
415 /* Allow only one connection at a time, but stay alive. */
417 if (family != AF_UNIX)
418 s = local_listen(host, uport, hints);
420 err(1, "local_listen");
422 * For UDP and -k, don't connect the socket, let it
423 * receive datagrams from multiple socket pairs.
428 * For UDP and not -k, we will use recvfrom() initially
429 * to wait for a caller, then use the regular functions
430 * to talk to the caller.
432 else if (uflag && !kflag) {
435 struct sockaddr_storage z;
439 rv = recvfrom(s, buf, plen, MSG_PEEK,
440 (struct sockaddr *)&z, &len);
444 rv = connect(s, (struct sockaddr *)&z, len);
449 report_connect((struct sockaddr *)&z, len);
453 len = sizeof(cliaddr);
454 connfd = accept(s, (struct sockaddr *)&cliaddr,
457 /* For now, all errnos are fatal */
461 report_connect((struct sockaddr *)&cliaddr, len);
467 if (family != AF_UNIX)
470 if (connect(s, NULL, 0) < 0)
477 } else if (family == AF_UNIX) {
480 if ((s = unix_connect(host)) > 0 && !zflag) {
487 unlink(unix_dg_tmp_socket);
493 /* Construct the portlist[] array. */
496 /* Cycle through portlist, connecting to each port. */
497 for (i = 0; portlist[i] != NULL; i++) {
502 s = socks_connect(host, portlist[i], hints,
503 proxyhost, proxyport, proxyhints, socksv,
506 s = remote_connect(host, portlist[i], hints);
512 if (vflag || zflag) {
513 /* For UDP, make sure we are connected. */
515 if (udptest(s) == -1) {
521 /* Don't look up port if -n. */
526 ntohs(atoi(portlist[i])),
527 uflag ? "udp" : "tcp");
531 "Connection to %s %s port [%s/%s] "
532 "succeeded!\n", host, portlist[i],
533 uflag ? "udp" : "tcp",
534 sv ? sv->s_name : "*");
551 * Returns a unix socket bound to the given path
554 unix_bind(char *path)
556 struct sockaddr_un sun_sa;
559 /* Create unix domain socket. */
560 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
564 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
565 sun_sa.sun_family = AF_UNIX;
567 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
568 sizeof(sun_sa.sun_path)) {
570 errno = ENAMETOOLONG;
574 if (bind(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
583 * Returns a socket connected to a local unix socket. Returns -1 on failure.
586 unix_connect(char *path)
588 struct sockaddr_un sun_sa;
592 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
595 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
598 (void)fcntl(s, F_SETFD, FD_CLOEXEC);
600 memset(&sun_sa, 0, sizeof(struct sockaddr_un));
601 sun_sa.sun_family = AF_UNIX;
603 if (strlcpy(sun_sa.sun_path, path, sizeof(sun_sa.sun_path)) >=
604 sizeof(sun_sa.sun_path)) {
606 errno = ENAMETOOLONG;
609 if (connect(s, (struct sockaddr *)&sun_sa, SUN_LEN(&sun_sa)) < 0) {
619 * Create a unix domain socket, and listen on it.
622 unix_listen(char *path)
625 if ((s = unix_bind(path)) < 0)
628 if (listen(s, 5) < 0) {
637 * Returns a socket connected to a remote host. Properly binds to a local
638 * port or source address if needed. Returns -1 on failure.
641 remote_connect(const char *host, const char *port, struct addrinfo hints)
643 struct addrinfo *res, *res0;
645 #if defined(SO_RTABLE) || defined(SO_BINDANY)
649 if ((error = getaddrinfo(host, port, &hints, &res)))
650 errx(1, "getaddrinfo: %s", gai_strerror(error));
654 if ((s = socket(res0->ai_family, res0->ai_socktype,
655 res0->ai_protocol)) < 0)
659 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
660 &rtableid, sizeof(rtableid)) == -1))
661 err(1, "setsockopt SO_RTABLE");
663 /* Bind to a local port or source address if specified. */
664 if (sflag || pflag) {
665 struct addrinfo ahints, *ares;
668 /* try SO_BINDANY, but don't insist */
669 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
671 memset(&ahints, 0, sizeof(struct addrinfo));
672 ahints.ai_family = res0->ai_family;
673 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
674 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
675 ahints.ai_flags = AI_PASSIVE;
676 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
677 errx(1, "getaddrinfo: %s", gai_strerror(error));
679 if (bind(s, (struct sockaddr *)ares->ai_addr,
680 ares->ai_addrlen) < 0)
681 err(1, "bind failed");
685 set_common_sockopts(s);
687 if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
690 warn("connect to %s port %s (%s) failed", host, port,
691 uflag ? "udp" : "tcp");
695 } while ((res0 = res0->ai_next) != NULL);
703 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
707 int flags = 0, optval;
711 flags = fcntl(s, F_GETFL, 0);
712 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
713 err(1, "set non-blocking mode");
716 if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
718 pfd.events = POLLOUT;
719 if ((ret = poll(&pfd, 1, timeout)) == 1) {
720 optlen = sizeof(optval);
721 if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
722 &optval, &optlen)) == 0) {
724 ret = optval == 0 ? 0 : -1;
726 } else if (ret == 0) {
730 err(1, "poll failed");
733 if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
734 err(1, "restoring flags");
741 * Returns a socket listening on a local port, binds to specified source
742 * address. Returns -1 on failure.
745 local_listen(char *host, char *port, struct addrinfo hints)
747 struct addrinfo *res, *res0;
751 /* Allow nodename to be null. */
752 hints.ai_flags |= AI_PASSIVE;
755 * In the case of binding to a wildcard address
756 * default to binding to an ipv4 address.
758 if (host == NULL && hints.ai_family == AF_UNSPEC)
759 hints.ai_family = AF_INET;
761 if ((error = getaddrinfo(host, port, &hints, &res)))
762 errx(1, "getaddrinfo: %s", gai_strerror(error));
766 if ((s = socket(res0->ai_family, res0->ai_socktype,
767 res0->ai_protocol)) < 0)
771 if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_RTABLE,
772 &rtableid, sizeof(rtableid)) == -1))
773 err(1, "setsockopt SO_RTABLE");
776 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
778 err(1, "setsockopt");
780 set_common_sockopts(s);
782 if (bind(s, (struct sockaddr *)res0->ai_addr,
783 res0->ai_addrlen) == 0)
788 } while ((res0 = res0->ai_next) != NULL);
790 if (!uflag && s != -1) {
791 if (listen(s, 1) < 0)
802 * Loop that polls on the network file descriptor and stdin.
805 readwrite(int net_fd)
807 struct pollfd pfd[4];
808 int stdin_fd = STDIN_FILENO;
809 int stdout_fd = STDOUT_FILENO;
810 unsigned char netinbuf[BUFSIZE];
811 size_t netinbufpos = 0;
812 unsigned char stdinbuf[BUFSIZE];
813 size_t stdinbufpos = 0;
817 /* don't read from stdin if requested */
822 pfd[POLL_STDIN].fd = stdin_fd;
823 pfd[POLL_STDIN].events = POLLIN;
826 pfd[POLL_NETOUT].fd = net_fd;
827 pfd[POLL_NETOUT].events = 0;
830 pfd[POLL_NETIN].fd = net_fd;
831 pfd[POLL_NETIN].events = POLLIN;
834 pfd[POLL_STDOUT].fd = stdout_fd;
835 pfd[POLL_STDOUT].events = 0;
838 /* both inputs are gone, buffers are empty, we are done */
839 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
840 && stdinbufpos == 0 && netinbufpos == 0) {
844 /* both outputs are gone, we can't continue */
845 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
849 /* listen and net in gone, queues empty, done */
850 if (lflag && pfd[POLL_NETIN].fd == -1
851 && stdinbufpos == 0 && netinbufpos == 0) {
856 /* help says -i is for "wait between lines sent". We read and
857 * write arbitrary amounts of data, and we don't want to start
858 * scanning for newlines, so this is as good as it gets */
863 num_fds = poll(pfd, 4, timeout);
865 /* treat poll errors */
868 err(1, "polling error");
871 /* timeout happened */
875 /* treat socket error conditions */
876 for (n = 0; n < 4; n++) {
877 if (pfd[n].revents & (POLLERR|POLLNVAL)) {
881 /* reading is possible after HUP */
882 if (pfd[POLL_STDIN].events & POLLIN &&
883 pfd[POLL_STDIN].revents & POLLHUP &&
884 ! (pfd[POLL_STDIN].revents & POLLIN))
885 pfd[POLL_STDIN].fd = -1;
887 if (pfd[POLL_NETIN].events & POLLIN &&
888 pfd[POLL_NETIN].revents & POLLHUP &&
889 ! (pfd[POLL_NETIN].revents & POLLIN))
890 pfd[POLL_NETIN].fd = -1;
892 if (pfd[POLL_NETOUT].revents & POLLHUP) {
894 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
895 pfd[POLL_NETOUT].fd = -1;
897 /* if HUP, stop watching stdout */
898 if (pfd[POLL_STDOUT].revents & POLLHUP)
899 pfd[POLL_STDOUT].fd = -1;
900 /* if no net out, stop watching stdin */
901 if (pfd[POLL_NETOUT].fd == -1)
902 pfd[POLL_STDIN].fd = -1;
903 /* if no stdout, stop watching net in */
904 if (pfd[POLL_STDOUT].fd == -1) {
905 if (pfd[POLL_NETIN].fd != -1)
906 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
907 pfd[POLL_NETIN].fd = -1;
910 /* try to read from stdin */
911 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
912 ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
914 /* error or eof on stdin - remove from pfd */
915 if (ret == 0 || ret == -1)
916 pfd[POLL_STDIN].fd = -1;
917 /* read something - poll net out */
919 pfd[POLL_NETOUT].events = POLLOUT;
920 /* filled buffer - remove self from polling */
921 if (stdinbufpos == BUFSIZE)
922 pfd[POLL_STDIN].events = 0;
924 /* try to write to network */
925 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
926 ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
929 pfd[POLL_NETOUT].fd = -1;
930 /* buffer empty - remove self from polling */
931 if (stdinbufpos == 0)
932 pfd[POLL_NETOUT].events = 0;
933 /* buffer no longer full - poll stdin again */
934 if (stdinbufpos < BUFSIZE)
935 pfd[POLL_STDIN].events = POLLIN;
937 /* try to read from network */
938 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
939 ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
942 pfd[POLL_NETIN].fd = -1;
943 /* eof on net in - remove from pfd */
945 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
946 pfd[POLL_NETIN].fd = -1;
948 /* read something - poll stdout */
950 pfd[POLL_STDOUT].events = POLLOUT;
951 /* filled buffer - remove self from polling */
952 if (netinbufpos == BUFSIZE)
953 pfd[POLL_NETIN].events = 0;
956 atelnet(pfd[POLL_NETIN].fd, netinbuf,
959 /* try to write to stdout */
960 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
961 ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
964 pfd[POLL_STDOUT].fd = -1;
965 /* buffer empty - remove self from polling */
966 if (netinbufpos == 0)
967 pfd[POLL_STDOUT].events = 0;
968 /* buffer no longer full - poll net in again */
969 if (netinbufpos < BUFSIZE)
970 pfd[POLL_NETIN].events = POLLIN;
973 /* stdin gone and queue empty? */
974 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
975 if (pfd[POLL_NETOUT].fd != -1 && Nflag)
976 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
977 pfd[POLL_NETOUT].fd = -1;
979 /* net in gone and queue empty? */
980 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
981 pfd[POLL_STDOUT].fd = -1;
987 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
992 n = write(fd, buf, *bufpos);
993 /* don't treat EAGAIN, EINTR as error */
994 if (n == -1 && (errno == EAGAIN || errno == EINTR))
999 adjust = *bufpos - n;
1001 memmove(buf, buf + n, adjust);
1008 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1010 size_t num = BUFSIZE - *bufpos;
1013 n = read(fd, buf + *bufpos, num);
1014 /* don't treat EAGAIN, EINTR as error */
1015 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1025 * Pass the connected file descriptor to stdout and exit.
1030 #if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR))
1032 #ifndef HAVE_ACCRIGHTS_IN_MSGHDR
1035 char buf[CMSG_SPACE(sizeof(int))];
1037 struct cmsghdr *cmsg;
1044 memset(&msg, 0, sizeof(msg));
1045 #ifdef HAVE_ACCRIGHTS_IN_MSGHDR
1046 msg.msg_accrights = (caddr_t)&nfd;
1047 msg.msg_accrightslen = sizeof(nfd);
1049 memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1050 msg.msg_control = (caddr_t)&cmsgbuf.buf;
1051 msg.msg_controllen = sizeof(cmsgbuf.buf);
1052 cmsg = CMSG_FIRSTHDR(&msg);
1053 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1054 cmsg->cmsg_level = SOL_SOCKET;
1055 cmsg->cmsg_type = SCM_RIGHTS;
1056 *(int *)CMSG_DATA(cmsg) = nfd;
1064 bzero(&pfd, sizeof(pfd));
1065 pfd.fd = STDOUT_FILENO;
1067 r = sendmsg(STDOUT_FILENO, &msg, 0);
1069 if (errno == EAGAIN || errno == EINTR) {
1070 pfd.events = POLLOUT;
1071 if (poll(&pfd, 1, -1) == -1)
1077 errx(1, "sendmsg: unexpected return value %zd", r);
1083 errx(1, "%s: file descriptor passing not supported", __func__);
1087 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1089 atelnet(int nfd, unsigned char *buf, unsigned int size)
1091 unsigned char *p, *end;
1092 unsigned char obuf[4];
1096 end = buf + size - 2;
1098 for (p = buf; p < end; p++) {
1104 if ((*p == WILL) || (*p == WONT))
1106 else if ((*p == DO) || (*p == DONT))
1113 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1114 warn("Write Error!");
1120 * Build an array of ports in portlist[], listing each port
1121 * that we should try to connect to.
1124 build_ports(char *p)
1131 if ((n = strchr(p, '-')) != NULL) {
1135 /* Make sure the ports are in order: lowest->highest. */
1136 hi = strtonum(n, 1, PORT_MAX, &errstr);
1138 errx(1, "port number %s: %s", errstr, n);
1139 lo = strtonum(p, 1, PORT_MAX, &errstr);
1141 errx(1, "port number %s: %s", errstr, p);
1149 /* Load ports sequentially. */
1150 for (cp = lo; cp <= hi; cp++) {
1151 portlist[x] = calloc(1, PORT_MAX_LEN);
1152 if (portlist[x] == NULL)
1154 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1158 /* Randomly swap ports. */
1163 for (x = 0; x <= (hi - lo); x++) {
1164 y = (arc4random() & 0xFFFF) % (hi - lo);
1166 portlist[x] = portlist[y];
1171 hi = strtonum(p, 1, PORT_MAX, &errstr);
1173 errx(1, "port number %s: %s", errstr, p);
1174 portlist[0] = strdup(p);
1175 if (portlist[0] == NULL)
1182 * Do a few writes to see if the UDP port is there.
1183 * Fails once PF state table is full.
1190 for (i = 0; i <= 3; i++) {
1191 if (write(s, "X", 1) == 1)
1200 set_common_sockopts(int s)
1206 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1207 &x, sizeof(x)) == -1)
1208 err(1, "setsockopt");
1212 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1213 &x, sizeof(x)) == -1)
1214 err(1, "setsockopt");
1217 if (setsockopt(s, IPPROTO_IP, IP_TOS,
1218 &Tflag, sizeof(Tflag)) == -1)
1219 err(1, "set IP ToS");
1222 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1223 &Iflag, sizeof(Iflag)) == -1)
1224 err(1, "set TCP receive buffer size");
1227 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1228 &Oflag, sizeof(Oflag)) == -1)
1229 err(1, "set TCP send buffer size");
1234 map_tos(char *s, int *val)
1236 /* DiffServ Codepoints and other TOS mappings */
1237 const struct toskeywords {
1238 const char *keyword;
1240 } *t, toskeywords[] = {
1241 { "af11", IPTOS_DSCP_AF11 },
1242 { "af12", IPTOS_DSCP_AF12 },
1243 { "af13", IPTOS_DSCP_AF13 },
1244 { "af21", IPTOS_DSCP_AF21 },
1245 { "af22", IPTOS_DSCP_AF22 },
1246 { "af23", IPTOS_DSCP_AF23 },
1247 { "af31", IPTOS_DSCP_AF31 },
1248 { "af32", IPTOS_DSCP_AF32 },
1249 { "af33", IPTOS_DSCP_AF33 },
1250 { "af41", IPTOS_DSCP_AF41 },
1251 { "af42", IPTOS_DSCP_AF42 },
1252 { "af43", IPTOS_DSCP_AF43 },
1253 { "critical", IPTOS_PREC_CRITIC_ECP },
1254 { "cs0", IPTOS_DSCP_CS0 },
1255 { "cs1", IPTOS_DSCP_CS1 },
1256 { "cs2", IPTOS_DSCP_CS2 },
1257 { "cs3", IPTOS_DSCP_CS3 },
1258 { "cs4", IPTOS_DSCP_CS4 },
1259 { "cs5", IPTOS_DSCP_CS5 },
1260 { "cs6", IPTOS_DSCP_CS6 },
1261 { "cs7", IPTOS_DSCP_CS7 },
1262 { "ef", IPTOS_DSCP_EF },
1263 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL },
1264 { "lowdelay", IPTOS_LOWDELAY },
1265 { "netcontrol", IPTOS_PREC_NETCONTROL },
1266 { "reliability", IPTOS_RELIABILITY },
1267 { "throughput", IPTOS_THROUGHPUT },
1271 for (t = toskeywords; t->keyword != NULL; t++) {
1272 if (strcmp(s, t->keyword) == 0) {
1282 report_connect(const struct sockaddr *sa, socklen_t salen)
1284 char remote_host[NI_MAXHOST];
1285 char remote_port[NI_MAXSERV];
1287 int flags = NI_NUMERICSERV;
1290 flags |= NI_NUMERICHOST;
1292 if ((herr = getnameinfo(sa, salen,
1293 remote_host, sizeof(remote_host),
1294 remote_port, sizeof(remote_port),
1296 if (herr == EAI_SYSTEM)
1297 err(1, "getnameinfo");
1299 errx(1, "getnameinfo: %s", gai_strerror(herr));
1303 "Connection from %s %s "
1304 "received!\n", remote_host, remote_port);
1311 fprintf(stderr, "\tCommand Summary:\n\
1314 \t-D Enable the debug socket option\n\
1315 \t-d Detach from stdin\n\
1316 \t-F Pass socket fd\n\
1317 \t-h This help text\n\
1318 \t-I length TCP receive buffer length\n\
1319 \t-i secs\t Delay interval for lines sent, ports scanned\n\
1320 \t-k Keep inbound sockets open for multiple connects\n\
1321 \t-l Listen mode, for inbound connects\n\
1322 \t-N Shutdown the network socket after EOF on stdin\n\
1323 \t-n Suppress name/port resolutions\n\
1324 \t-O length TCP send buffer length\n\
1325 \t-P proxyuser\tUsername for proxy authentication\n\
1326 \t-p port\t Specify local port for remote connects\n\
1327 \t-r Randomize remote ports\n\
1328 \t-S Enable the TCP MD5 signature option\n\
1329 \t-s addr\t Local source address\n\
1330 \t-T toskeyword\tSet IP Type of Service\n\
1331 \t-t Answer TELNET negotiation\n\
1332 \t-U Use UNIX domain socket\n\
1334 \t-V rtable Specify alternate routing table\n\
1336 \t-w secs\t Timeout for connects and final net reads\n\
1337 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1338 \t-x addr[:port]\tSpecify proxy address and port\n\
1339 \t-z Zero-I/O mode [used for scanning]\n\
1340 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1348 "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1349 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1350 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1351 "\t [-x proxy_address[:port]] [destination] [port]\n");
1356 /* *** src/usr.bin/nc/socks.c *** */
1359 /* $OpenBSD: socks.c,v 1.20 2012/03/08 09:56:28 espie Exp $ */
1362 * Copyright (c) 1999 Niklas Hallqvist. All rights reserved.
1363 * Copyright (c) 2004, 2005 Damien Miller. All rights reserved.
1365 * Redistribution and use in source and binary forms, with or without
1366 * modification, are permitted provided that the following conditions
1368 * 1. Redistributions of source code must retain the above copyright
1369 * notice, this list of conditions and the following disclaimer.
1370 * 2. Redistributions in binary form must reproduce the above copyright
1371 * notice, this list of conditions and the following disclaimer in the
1372 * documentation and/or other materials provided with the distribution.
1374 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1375 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1376 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1377 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1378 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1379 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1380 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1381 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1382 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1383 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1386 #include <sys/types.h>
1387 #include <sys/socket.h>
1388 #include <netinet/in.h>
1389 #include <arpa/inet.h>
1399 #define SOCKS_PORT "1080"
1400 #define HTTP_PROXY_PORT "3128"
1401 #define HTTP_MAXHDRS 64
1404 #define SOCKS_NOAUTH 0
1405 #define SOCKS_NOMETHOD 0xff
1406 #define SOCKS_CONNECT 1
1407 #define SOCKS_IPV4 1
1408 #define SOCKS_DOMAIN 3
1409 #define SOCKS_IPV6 4
1411 int remote_connect(const char *, const char *, struct addrinfo);
1412 int socks_connect(const char *, const char *, struct addrinfo,
1413 const char *, const char *, struct addrinfo, int,
1417 decode_addrport(const char *h, const char *p, struct sockaddr *addr,
1418 socklen_t addrlen, int v4only, int numeric)
1421 struct addrinfo hints, *res;
1423 bzero(&hints, sizeof(hints));
1424 hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
1425 hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
1426 hints.ai_socktype = SOCK_STREAM;
1427 r = getaddrinfo(h, p, &hints, &res);
1428 /* Don't fatal when attempting to convert a numeric address */
1431 errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
1436 if (addrlen < res->ai_addrlen) {
1438 errx(1, "internal error: addrlen < res->ai_addrlen");
1440 memcpy(addr, res->ai_addr, res->ai_addrlen);
1446 proxy_read_line(int fd, char *buf, size_t bufsz)
1452 errx(1, "proxy read too long");
1453 if (atomicio(read, fd, buf + off, 1) != 1)
1454 err(1, "proxy read");
1456 if (buf[off] == '\r')
1458 if (buf[off] == '\n') {
1468 getproxypass(const char *proxyuser, const char *proxyhost)
1471 static char pw[256];
1473 snprintf(prompt, sizeof(prompt), "Proxy password for %s@%s: ",
1474 proxyuser, proxyhost);
1475 if (readpassphrase(prompt, pw, sizeof(pw), RPP_REQUIRE_TTY) == NULL)
1476 errx(1, "Unable to read proxy passphrase");
1481 socks_connect(const char *host, const char *port,
1482 struct addrinfo hints __attribute__ ((__unused__)),
1483 const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
1484 int socksv, const char *proxyuser)
1486 int proxyfd, r, authretry = 0;
1487 size_t hlen, wlen = 0;
1488 unsigned char buf[1024];
1490 struct sockaddr_storage addr;
1491 struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
1492 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
1493 in_port_t serverport;
1494 const char *proxypass = NULL;
1496 if (proxyport == NULL)
1497 proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
1499 /* Abuse API to lookup port */
1500 if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
1501 sizeof(addr), 1, 1) == -1)
1502 errx(1, "unknown port \"%.64s\"", port);
1503 serverport = in4->sin_port;
1506 if (authretry++ > 3)
1507 errx(1, "Too many authentication failures");
1509 proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
1515 if (decode_addrport(host, port, (struct sockaddr *)&addr,
1516 sizeof(addr), 0, 1) == -1)
1517 addr.ss_family = 0; /* used in switch below */
1519 /* Version 5, one method: no authentication */
1522 buf[2] = SOCKS_NOAUTH;
1523 cnt = atomicio(vwrite, proxyfd, buf, 3);
1525 err(1, "write failed (%zu/3)", cnt);
1527 cnt = atomicio(read, proxyfd, buf, 2);
1529 err(1, "read failed (%zu/3)", cnt);
1531 if (buf[1] == SOCKS_NOMETHOD)
1532 errx(1, "authentication method negotiation failed");
1534 switch (addr.ss_family) {
1536 /* Version 5, connect: domain name */
1538 /* Max domain name length is 255 bytes */
1539 hlen = strlen(host);
1541 errx(1, "host name too long for SOCKS5");
1543 buf[1] = SOCKS_CONNECT;
1545 buf[3] = SOCKS_DOMAIN;
1547 memcpy(buf + 5, host, hlen);
1548 memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
1552 /* Version 5, connect: IPv4 address */
1554 buf[1] = SOCKS_CONNECT;
1556 buf[3] = SOCKS_IPV4;
1557 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1558 memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
1562 /* Version 5, connect: IPv6 address */
1564 buf[1] = SOCKS_CONNECT;
1566 buf[3] = SOCKS_IPV6;
1567 memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
1568 memcpy(buf + 20, &in6->sin6_port,
1569 sizeof in6->sin6_port);
1573 errx(1, "internal error: silly AF");
1576 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1578 err(1, "write failed (%zu/%zu)", cnt, wlen);
1580 cnt = atomicio(read, proxyfd, buf, 4);
1582 err(1, "read failed (%zu/4)", cnt);
1584 errx(1, "connection failed, SOCKS error %d", buf[1]);
1587 cnt = atomicio(read, proxyfd, buf + 4, 6);
1589 err(1, "read failed (%zu/6)", cnt);
1592 cnt = atomicio(read, proxyfd, buf + 4, 18);
1594 err(1, "read failed (%zu/18)", cnt);
1597 errx(1, "connection failed, unsupported address type");
1599 } else if (socksv == 4) {
1600 /* This will exit on lookup failure */
1601 decode_addrport(host, port, (struct sockaddr *)&addr,
1602 sizeof(addr), 1, 0);
1606 buf[1] = SOCKS_CONNECT; /* connect */
1607 memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
1608 memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
1609 buf[8] = 0; /* empty username */
1612 cnt = atomicio(vwrite, proxyfd, buf, wlen);
1614 err(1, "write failed (%zu/%zu)", cnt, wlen);
1616 cnt = atomicio(read, proxyfd, buf, 8);
1618 err(1, "read failed (%zu/8)", cnt);
1620 errx(1, "connection failed, SOCKS error %d", buf[1]);
1621 } else if (socksv == -1) {
1622 /* HTTP proxy CONNECT */
1624 /* Disallow bad chars in hostname */
1625 if (strcspn(host, "\r\n\t []:") != strlen(host))
1626 errx(1, "Invalid hostname");
1628 /* Try to be sane about numeric IPv6 addresses */
1629 if (strchr(host, ':') != NULL) {
1630 r = snprintf(buf, sizeof(buf),
1631 "CONNECT [%s]:%d HTTP/1.0\r\n",
1632 host, ntohs(serverport));
1634 r = snprintf(buf, sizeof(buf),
1635 "CONNECT %s:%d HTTP/1.0\r\n",
1636 host, ntohs(serverport));
1638 if (r == -1 || (size_t)r >= sizeof(buf))
1639 errx(1, "hostname too long");
1642 cnt = atomicio(vwrite, proxyfd, buf, r);
1643 if (cnt != (size_t)r)
1644 err(1, "write failed (%zu/%d)", cnt, r);
1646 if (authretry > 1) {
1649 proxypass = getproxypass(proxyuser, proxyhost);
1650 r = snprintf(buf, sizeof(buf), "%s:%s",
1651 proxyuser, proxypass);
1652 if (r == -1 || (size_t)r >= sizeof(buf) ||
1653 b64_ntop(buf, strlen(buf), resp,
1654 sizeof(resp)) == -1)
1655 errx(1, "Proxy username/password too long");
1656 r = snprintf(buf, sizeof(buf), "Proxy-Authorization: "
1657 "Basic %s\r\n", resp);
1658 if (r == -1 || (size_t)r >= sizeof(buf))
1659 errx(1, "Proxy auth response too long");
1661 if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != (size_t)r)
1662 err(1, "write failed (%zu/%d)", cnt, r);
1665 /* Terminate headers */
1666 if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
1667 err(1, "write failed (2/%d)", r);
1669 /* Read status reply */
1670 proxy_read_line(proxyfd, buf, sizeof(buf));
1671 if (proxyuser != NULL &&
1672 strncmp(buf, "HTTP/1.0 407 ", 12) == 0) {
1673 if (authretry > 1) {
1674 fprintf(stderr, "Proxy authentication "
1679 } else if (strncmp(buf, "HTTP/1.0 200 ", 12) != 0 &&
1680 strncmp(buf, "HTTP/1.1 200 ", 12) != 0)
1681 errx(1, "Proxy error: \"%s\"", buf);
1683 /* Headers continue until we hit an empty line */
1684 for (r = 0; r < HTTP_MAXHDRS; r++) {
1685 proxy_read_line(proxyfd, buf, sizeof(buf));
1690 errx(1, "Too many proxy headers received");
1692 errx(1, "Unknown proxy protocol %d", socksv);