1 /* $OpenBSD: netcat.c,v 1.100 2011/01/09 22:16:46 jeremy Exp $ */
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * Re-written nc(1) for OpenBSD. Original implementation by
33 * *Hobbit* <hobbit@avian.org>.
36 #include <sys/limits.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
43 #include <netinet/in.h>
44 #include <netinet/in_systm.h>
46 #include <netipsec/ipsec.h>
48 #include <netinet/tcp.h>
49 #include <netinet/ip.h>
50 #include <arpa/telnet.h>
68 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
71 #define PORT_MAX 65535
72 #define PORT_MAX_LEN 6
73 #define UNIX_DG_TMP_SOCKET_SIZE 19
75 /* Command Line Options */
76 int dflag; /* detached, no stdin */
77 unsigned int iflag; /* Interval Flag */
78 int jflag; /* use jumbo frames if we can */
79 int kflag; /* More than one connect */
80 int lflag; /* Bind to local port */
81 int nflag; /* Don't do name look up */
82 int FreeBSD_Oflag; /* Do not use TCP options */
83 char *Pflag; /* Proxy username */
84 char *pflag; /* Localport flag */
85 int rflag; /* Random ports flag */
86 char *sflag; /* Source Address */
87 int tflag; /* Telnet Emulation */
88 int uflag; /* UDP - Default to TCP */
89 int vflag; /* Verbosity */
90 int xflag; /* Socks proxy */
91 int zflag; /* Port Scan Flag */
92 int Dflag; /* sodebug */
93 int Iflag; /* TCP receive buffer size */
94 int Oflag; /* TCP send buffer size */
95 int Sflag; /* TCP MD5 signature option */
96 int Tflag = -1; /* IP Type of Service */
100 int family = AF_UNSPEC;
101 char *portlist[PORT_MAX+1];
102 char *unix_dg_tmp_socket;
104 void atelnet(int, unsigned char *, unsigned int);
105 void build_ports(char *);
107 int local_listen(char *, char *, struct addrinfo);
109 int remote_connect(const char *, const char *, struct addrinfo);
110 int socks_connect(const char *, const char *, struct addrinfo,
111 const char *, const char *, struct addrinfo, int, const char *);
113 int unix_bind(char *);
114 int unix_connect(char *);
115 int unix_listen(char *);
116 void set_common_sockopts(int);
117 int parse_iptos(char *);
121 void add_ipsec_policy(int, char *);
123 char *ipsec_policy[2];
127 main(int argc, char *argv[])
129 int ch, s, ret, socksv, ipsec_count;
131 size_t intsize = sizeof(int);
133 struct addrinfo hints;
136 struct sockaddr_storage cliaddr;
138 const char *errstr, *proxyhost = "", *proxyport = NULL;
139 struct addrinfo proxyhints;
140 char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
141 struct option longopts[] = {
142 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
154 while ((ch = getopt_long(argc, argv,
155 "46DdEe:hI:i:jklnoO:P:p:rSs:tT:UuV:vw:X:x:z",
156 longopts, NULL)) != -1) {
168 if (strcasecmp(optarg, "connect") == 0)
169 socksv = -1; /* HTTP proxy CONNECT */
170 else if (strcmp(optarg, "4") == 0)
171 socksv = 4; /* SOCKS v.4 */
172 else if (strcmp(optarg, "5") == 0)
173 socksv = 5; /* SOCKS v.5 */
175 errx(1, "unsupported proxy protocol");
182 ipsec_policy[ipsec_count++ % 2] = optarg;
184 errx(1, "IPsec support unavailable.");
189 ipsec_policy[0] = "in ipsec esp/transport//require";
190 ipsec_policy[1] = "out ipsec esp/transport//require";
192 errx(1, "IPsec support unavailable.");
199 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
201 errx(1, "interval %s: %s", errstr, optarg);
218 fprintf(stderr, "option -o is deprecated.\n");
239 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
240 errx(1, "Multiple FIBS not supported");
241 rtableid = (unsigned int)strtonum(optarg, 0,
242 numfibs - 1, &errstr);
244 errx(1, "rtable %s: %s", errstr, optarg);
250 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
252 errx(1, "timeout %s: %s", errstr, optarg);
257 if ((proxy = strdup(optarg)) == NULL)
267 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
269 errx(1, "TCP receive window %s: %s",
273 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
274 if (errstr != NULL) {
275 if (strcmp(errstr, "invalid") != 0)
276 errx(1, "TCP send window %s: %s",
284 Tflag = parse_iptos(optarg);
293 /* Cruft to make sure options are clean, and used properly. */
294 if (argv[0] && !argv[1] && family == AF_UNIX) {
297 } else if (argv[0] && !argv[1]) {
302 } else if (argv[0] && argv[1]) {
309 errx(1, "cannot use -s and -l");
311 errx(1, "cannot use -p and -l");
313 errx(1, "cannot use -z and -l");
315 errx(1, "must use -l with -k");
317 /* Get name of temporary socket for unix datagram client */
318 if ((family == AF_UNIX) && uflag && !lflag) {
320 unix_dg_tmp_socket = sflag;
322 strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
323 UNIX_DG_TMP_SOCKET_SIZE);
324 if (mktemp(unix_dg_tmp_socket_buf) == NULL)
326 unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
330 /* Initialize addrinfo structure. */
331 if (family != AF_UNIX) {
332 memset(&hints, 0, sizeof(struct addrinfo));
333 hints.ai_family = family;
334 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
335 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
337 hints.ai_flags |= AI_NUMERICHOST;
342 errx(1, "no proxy support for UDP mode");
345 errx(1, "no proxy support for listen");
347 if (family == AF_UNIX)
348 errx(1, "no proxy support for unix sockets");
350 /* XXX IPv6 transport to proxy would probably work */
351 if (family == AF_INET6)
352 errx(1, "no proxy support for IPv6");
355 errx(1, "no proxy support for local source address");
357 proxyhost = strsep(&proxy, ":");
360 memset(&proxyhints, 0, sizeof(struct addrinfo));
361 proxyhints.ai_family = family;
362 proxyhints.ai_socktype = SOCK_STREAM;
363 proxyhints.ai_protocol = IPPROTO_TCP;
365 proxyhints.ai_flags |= AI_NUMERICHOST;
372 if (family == AF_UNIX) {
376 s = unix_listen(host);
379 /* Allow only one connection at a time, but stay alive. */
381 if (family != AF_UNIX)
382 s = local_listen(host, uport, hints);
386 * For UDP, we will use recvfrom() initially
387 * to wait for a caller, then use the regular
388 * functions to talk to the caller.
393 struct sockaddr_storage z;
396 plen = jflag ? 16384 : 2048;
397 rv = recvfrom(s, buf, plen, MSG_PEEK,
398 (struct sockaddr *)&z, &len);
402 rv = connect(s, (struct sockaddr *)&z, len);
408 len = sizeof(cliaddr);
409 connfd = accept(s, (struct sockaddr *)&cliaddr,
415 if (family != AF_UNIX)
418 if (connect(s, NULL, 0) < 0)
425 } else if (family == AF_UNIX) {
428 if ((s = unix_connect(host)) > 0 && !zflag) {
435 unlink(unix_dg_tmp_socket);
441 /* Construct the portlist[] array. */
444 /* Cycle through portlist, connecting to each port. */
445 for (i = 0; portlist[i] != NULL; i++) {
450 s = socks_connect(host, portlist[i], hints,
451 proxyhost, proxyport, proxyhints, socksv,
454 s = remote_connect(host, portlist[i], hints);
460 if (vflag || zflag) {
461 /* For UDP, make sure we are connected. */
463 if (udptest(s) == -1) {
469 /* Don't look up port if -n. */
474 ntohs(atoi(portlist[i])),
475 uflag ? "udp" : "tcp");
479 "Connection to %s %s port [%s/%s] "
480 "succeeded!\n", host, portlist[i],
481 uflag ? "udp" : "tcp",
482 sv ? sv->s_name : "*");
497 * Returns a unix socket bound to the given path
500 unix_bind(char *path)
502 struct sockaddr_un sun;
505 /* Create unix domain socket. */
506 if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
510 memset(&sun, 0, sizeof(struct sockaddr_un));
511 sun.sun_family = AF_UNIX;
513 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
514 sizeof(sun.sun_path)) {
516 errno = ENAMETOOLONG;
520 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
529 * Returns a socket connected to a local unix socket. Returns -1 on failure.
532 unix_connect(char *path)
534 struct sockaddr_un sun;
538 if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
541 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
544 (void)fcntl(s, F_SETFD, 1);
546 memset(&sun, 0, sizeof(struct sockaddr_un));
547 sun.sun_family = AF_UNIX;
549 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
550 sizeof(sun.sun_path)) {
552 errno = ENAMETOOLONG;
555 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
565 * Create a unix domain socket, and listen on it.
568 unix_listen(char *path)
571 if ((s = unix_bind(path)) < 0)
574 if (listen(s, 5) < 0) {
583 * Returns a socket connected to a remote host. Properly binds to a local
584 * port or source address if needed. Returns -1 on failure.
587 remote_connect(const char *host, const char *port, struct addrinfo hints)
589 struct addrinfo *res, *res0;
590 int s, error, on = 1;
592 if ((error = getaddrinfo(host, port, &hints, &res)))
593 errx(1, "getaddrinfo: %s", gai_strerror(error));
597 if ((s = socket(res0->ai_family, res0->ai_socktype,
598 res0->ai_protocol)) < 0)
601 if (ipsec_policy[0] != NULL)
602 add_ipsec_policy(s, ipsec_policy[0]);
603 if (ipsec_policy[1] != NULL)
604 add_ipsec_policy(s, ipsec_policy[1]);
608 if (setfib(rtableid) == -1)
612 /* Bind to a local port or source address if specified. */
613 if (sflag || pflag) {
614 struct addrinfo ahints, *ares;
616 /* try IP_BINDANY, but don't insist */
617 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
618 memset(&ahints, 0, sizeof(struct addrinfo));
619 ahints.ai_family = res0->ai_family;
620 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
621 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
622 ahints.ai_flags = AI_PASSIVE;
623 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
624 errx(1, "getaddrinfo: %s", gai_strerror(error));
626 if (bind(s, (struct sockaddr *)ares->ai_addr,
627 ares->ai_addrlen) < 0)
628 errx(1, "bind failed: %s", strerror(errno));
632 set_common_sockopts(s);
634 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
637 warn("connect to %s port %s (%s) failed", host, port,
638 uflag ? "udp" : "tcp");
642 } while ((res0 = res0->ai_next) != NULL);
651 * Returns a socket listening on a local port, binds to specified source
652 * address. Returns -1 on failure.
655 local_listen(char *host, char *port, struct addrinfo hints)
657 struct addrinfo *res, *res0;
661 /* Allow nodename to be null. */
662 hints.ai_flags |= AI_PASSIVE;
665 * In the case of binding to a wildcard address
666 * default to binding to an ipv4 address.
668 if (host == NULL && hints.ai_family == AF_UNSPEC)
669 hints.ai_family = AF_INET;
671 if ((error = getaddrinfo(host, port, &hints, &res)))
672 errx(1, "getaddrinfo: %s", gai_strerror(error));
676 if ((s = socket(res0->ai_family, res0->ai_socktype,
677 res0->ai_protocol)) < 0)
681 if (setfib(rtableid) == -1)
685 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
689 if (ipsec_policy[0] != NULL)
690 add_ipsec_policy(s, ipsec_policy[0]);
691 if (ipsec_policy[1] != NULL)
692 add_ipsec_policy(s, ipsec_policy[1]);
695 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
696 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
697 err(1, "disable TCP options");
700 if (bind(s, (struct sockaddr *)res0->ai_addr,
701 res0->ai_addrlen) == 0)
706 } while ((res0 = res0->ai_next) != NULL);
708 if (!uflag && s != -1) {
709 if (listen(s, 1) < 0)
720 * Loop that polls on the network file descriptor and stdin.
725 struct pollfd pfd[2];
726 unsigned char buf[16384];
727 int n, wfd = fileno(stdin);
728 int lfd = fileno(stdout);
731 plen = jflag ? 16384 : 2048;
733 /* Setup Network FD */
735 pfd[0].events = POLLIN;
737 /* Set up STDIN FD. */
739 pfd[1].events = POLLIN;
741 while (pfd[0].fd != -1) {
745 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
747 err(1, "Polling Error");
753 if (pfd[0].revents & POLLIN) {
754 if ((n = read(nfd, buf, plen)) < 0)
757 shutdown(nfd, SHUT_RD);
762 atelnet(nfd, buf, n);
763 if (atomicio(vwrite, lfd, buf, n) != n)
768 if (!dflag && pfd[1].revents & POLLIN) {
769 if ((n = read(wfd, buf, plen)) < 0)
772 shutdown(nfd, SHUT_WR);
776 if (atomicio(vwrite, nfd, buf, n) != n)
783 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
785 atelnet(int nfd, unsigned char *buf, unsigned int size)
787 unsigned char *p, *end;
788 unsigned char obuf[4];
792 end = buf + size - 2;
794 for (p = buf; p < end; p++) {
800 if ((*p == WILL) || (*p == WONT))
802 else if ((*p == DO) || (*p == DONT))
809 if (atomicio(vwrite, nfd, obuf, 3) != 3)
810 warn("Write Error!");
816 * Build an array or ports in portlist[], listing each port
817 * that we should try to connect to.
827 if ((n = strchr(p, '-')) != NULL) {
829 errx(1, "Cannot use -l with multiple ports!");
834 /* Make sure the ports are in order: lowest->highest. */
835 hi = strtonum(n, 1, PORT_MAX, &errstr);
837 errx(1, "port number %s: %s", errstr, n);
838 lo = strtonum(p, 1, PORT_MAX, &errstr);
840 errx(1, "port number %s: %s", errstr, p);
848 /* Load ports sequentially. */
849 for (cp = lo; cp <= hi; cp++) {
850 portlist[x] = calloc(1, PORT_MAX_LEN);
851 if (portlist[x] == NULL)
853 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
857 /* Randomly swap ports. */
862 for (x = 0; x <= (hi - lo); x++) {
863 y = (arc4random() & 0xFFFF) % (hi - lo);
865 portlist[x] = portlist[y];
870 hi = strtonum(p, 1, PORT_MAX, &errstr);
872 errx(1, "port number %s: %s", errstr, p);
873 portlist[0] = strdup(p);
874 if (portlist[0] == NULL)
881 * Do a few writes to see if the UDP port is there.
882 * XXX - Better way of doing this? Doesn't work for IPv6.
883 * Also fails after around 100 ports checked.
890 for (i = 0; i <= 3; i++) {
891 if (write(s, "X", 1) == 1)
900 set_common_sockopts(int s)
905 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
906 &x, sizeof(x)) == -1)
910 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
911 &x, sizeof(x)) == -1)
916 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
917 &x, sizeof(x)) == -1)
922 if (setsockopt(s, IPPROTO_IP, IP_TOS,
923 &Tflag, sizeof(Tflag)) == -1)
924 err(1, "set IP ToS");
927 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
928 &Iflag, sizeof(Iflag)) == -1)
929 err(1, "set TCP receive buffer size");
932 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
933 &Oflag, sizeof(Oflag)) == -1)
934 err(1, "set TCP send buffer size");
937 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
938 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
939 err(1, "disable TCP options");
948 if (strcmp(s, "lowdelay") == 0)
949 return (IPTOS_LOWDELAY);
950 if (strcmp(s, "throughput") == 0)
951 return (IPTOS_THROUGHPUT);
952 if (strcmp(s, "reliability") == 0)
953 return (IPTOS_RELIABILITY);
955 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
956 errx(1, "invalid IP Type of Service");
964 fprintf(stderr, "\tCommand Summary:\n\
967 \t-D Enable the debug socket option\n\
968 \t-d Detach from stdin\n");
971 \t-E Use IPsec ESP\n\
972 \t-e policy Use specified IPsec policy\n");
975 \t-h This help text\n\
976 \t-I length TCP receive buffer length\n\
977 \t-i secs\t Delay interval for lines sent, ports scanned\n\
978 \t-k Keep inbound sockets open for multiple connects\n\
979 \t-l Listen mode, for inbound connects\n\
980 \t-n Suppress name/port resolutions\n\
981 \t--no-tcpopt Disable TCP options\n\
982 \t-O length TCP send buffer length\n\
983 \t-P proxyuser\tUsername for proxy authentication\n\
984 \t-p port\t Specify local port for remote connects\n\
985 \t-r Randomize remote ports\n\
986 \t-S Enable the TCP MD5 signature option\n\
987 \t-s addr\t Local source address\n\
988 \t-T ToS\t Set IP Type of Service\n\
989 \t-t Answer TELNET negotiation\n\
990 \t-U Use UNIX domain socket\n\
992 \t-V rtable Specify alternate routing table\n\
994 \t-w secs\t Timeout for connects and final net reads\n\
995 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
996 \t-x addr[:port]\tSpecify proxy address and port\n\
997 \t-z Zero-I/O mode [used for scanning]\n\
998 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1000 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
1007 add_ipsec_policy(int s, char *policy)
1012 raw = ipsec_set_policy(policy, strlen(policy));
1014 errx(1, "ipsec_set_policy `%s': %s", policy,
1016 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1017 ipsec_get_policylen(raw));
1019 err(1, "ipsec policy cannot be configured");
1022 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1032 "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1034 "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
1036 "\t [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1037 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1038 "\t [-x proxy_address[:port]] [destination] [port]\n");