1 /* $OpenBSD: netcat.c,v 1.93 2009/06/05 00:18:10 claudio 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
74 /* Command Line Options */
75 int Eflag; /* Use IPsec ESP */
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 oflag; /* Once only: stop on EOF */
83 int FreeBSD_Oflag; /* Do not use TCP options */
84 char *Pflag; /* Proxy username */
85 char *pflag; /* Localport flag */
86 int rflag; /* Random ports flag */
87 char *sflag; /* Source Address */
88 int tflag; /* Telnet Emulation */
89 int uflag; /* UDP - Default to TCP */
90 int vflag; /* Verbosity */
91 int xflag; /* Socks proxy */
92 int zflag; /* Port Scan Flag */
93 int Dflag; /* sodebug */
94 int Iflag; /* TCP receive buffer size */
95 int Oflag; /* TCP send buffer size */
96 int Sflag; /* TCP MD5 signature option */
97 int Tflag = -1; /* IP Type of Service */
101 int family = AF_UNSPEC;
102 char *portlist[PORT_MAX+1];
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_connect(char *);
114 int unix_listen(char *);
115 void set_common_sockopts(int);
116 int parse_iptos(char *);
120 void add_ipsec_policy(int, char *);
122 char *ipsec_policy[2];
126 main(int argc, char *argv[])
128 int ch, s, ret, socksv, ipsec_count;
130 size_t intsize = sizeof(int);
132 struct addrinfo hints;
135 struct sockaddr_storage cliaddr;
137 const char *errstr, *proxyhost = "", *proxyport = NULL;
138 struct addrinfo proxyhints;
139 struct option longopts[] = {
140 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
153 while ((ch = getopt_long(argc, argv,
154 "46DdEe:hI:i:jklnO:oP:p:rSs:tT:UuV:vw:X:x:z",
155 longopts, NULL)) != -1) {
167 if (strcasecmp(optarg, "connect") == 0)
168 socksv = -1; /* HTTP proxy CONNECT */
169 else if (strcmp(optarg, "4") == 0)
170 socksv = 4; /* SOCKS v.4 */
171 else if (strcmp(optarg, "5") == 0)
172 socksv = 5; /* SOCKS v.5 */
174 errx(1, "unsupported proxy protocol");
181 ipsec_policy[ipsec_count++ % 2] = optarg;
183 errx(1, "IPsec support unavailable.");
188 ipsec_policy[0] = "in ipsec esp/transport//require";
189 ipsec_policy[1] = "out ipsec esp/transport//require";
191 errx(1, "IPsec support unavailable.");
198 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
200 errx(1, "interval %s: %s", errstr, optarg);
238 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
239 errx(1, "Multiple FIBS not supported");
240 rdomain = (unsigned int)strtonum(optarg, 0,
241 numfibs - 1, &errstr);
243 errx(1, "FIB %s: %s", errstr, optarg);
249 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
251 errx(1, "timeout %s: %s", errstr, optarg);
256 if ((proxy = strdup(optarg)) == NULL)
266 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
268 errx(1, "TCP receive window %s: %s",
272 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
273 if (errstr != NULL) {
274 if (strcmp(errstr, "invalid") != 0)
275 errx(1, "TCP send window %s: %s",
283 Tflag = parse_iptos(optarg);
294 /* Cruft to make sure options are clean, and used properly. */
295 if (argv[0] && !argv[1] && family == AF_UNIX) {
297 errx(1, "cannot use -u and -U");
300 } else if (argv[0] && !argv[1]) {
305 } else if (argv[0] && argv[1]) {
312 errx(1, "cannot use -s and -l");
314 errx(1, "cannot use -p and -l");
316 errx(1, "cannot use -z and -l");
318 errx(1, "must use -l with -k");
320 /* Initialize addrinfo structure. */
321 if (family != AF_UNIX) {
322 memset(&hints, 0, sizeof(struct addrinfo));
323 hints.ai_family = family;
324 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
325 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
327 hints.ai_flags |= AI_NUMERICHOST;
332 errx(1, "no proxy support for UDP mode");
335 errx(1, "no proxy support for listen");
337 if (family == AF_UNIX)
338 errx(1, "no proxy support for unix sockets");
340 /* XXX IPv6 transport to proxy would probably work */
341 if (family == AF_INET6)
342 errx(1, "no proxy support for IPv6");
345 errx(1, "no proxy support for local source address");
347 proxyhost = strsep(&proxy, ":");
350 memset(&proxyhints, 0, sizeof(struct addrinfo));
351 proxyhints.ai_family = family;
352 proxyhints.ai_socktype = SOCK_STREAM;
353 proxyhints.ai_protocol = IPPROTO_TCP;
355 proxyhints.ai_flags |= AI_NUMERICHOST;
362 if (family == AF_UNIX)
363 s = unix_listen(host);
365 /* Allow only one connection at a time, but stay alive. */
367 if (family != AF_UNIX)
368 s = local_listen(host, uport, hints);
372 * For UDP, we will use recvfrom() initially
373 * to wait for a caller, then use the regular
374 * functions to talk to the caller.
379 struct sockaddr_storage z;
382 plen = jflag ? 8192 : 1024;
383 rv = recvfrom(s, buf, plen, MSG_PEEK,
384 (struct sockaddr *)&z, &len);
388 rv = connect(s, (struct sockaddr *)&z, len);
394 len = sizeof(cliaddr);
395 connfd = accept(s, (struct sockaddr *)&cliaddr,
401 if (family != AF_UNIX)
407 } else if (family == AF_UNIX) {
410 if ((s = unix_connect(host)) > 0 && !zflag) {
421 /* Construct the portlist[] array. */
424 /* Cycle through portlist, connecting to each port. */
425 for (i = 0; portlist[i] != NULL; i++) {
430 s = socks_connect(host, portlist[i], hints,
431 proxyhost, proxyport, proxyhints, socksv,
434 s = remote_connect(host, portlist[i], hints);
440 if (vflag || zflag) {
441 /* For UDP, make sure we are connected. */
443 if (udptest(s) == -1) {
449 /* Don't look up port if -n. */
454 ntohs(atoi(portlist[i])),
455 uflag ? "udp" : "tcp");
458 printf("Connection to %s %s port [%s/%s] succeeded!\n",
459 host, portlist[i], uflag ? "udp" : "tcp",
460 sv ? sv->s_name : "*");
475 * Returns a socket connected to a local unix socket. Returns -1 on failure.
478 unix_connect(char *path)
480 struct sockaddr_un sun;
483 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
485 (void)fcntl(s, F_SETFD, 1);
487 memset(&sun, 0, sizeof(struct sockaddr_un));
488 sun.sun_family = AF_UNIX;
490 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
491 sizeof(sun.sun_path)) {
493 errno = ENAMETOOLONG;
496 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
506 * Create a unix domain socket, and listen on it.
509 unix_listen(char *path)
511 struct sockaddr_un sun;
514 /* Create unix domain socket. */
515 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
518 memset(&sun, 0, sizeof(struct sockaddr_un));
519 sun.sun_family = AF_UNIX;
521 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
522 sizeof(sun.sun_path)) {
524 errno = ENAMETOOLONG;
528 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
533 if (listen(s, 5) < 0) {
542 * Returns a socket connected to a remote host. Properly binds to a local
543 * port or source address if needed. Returns -1 on failure.
546 remote_connect(const char *host, const char *port, struct addrinfo hints)
548 struct addrinfo *res, *res0;
549 int s, error, on = 1;
551 if ((error = getaddrinfo(host, port, &hints, &res)))
552 errx(1, "getaddrinfo: %s", gai_strerror(error));
556 if ((s = socket(res0->ai_family, res0->ai_socktype,
557 res0->ai_protocol)) < 0)
560 if (ipsec_policy[0] != NULL)
561 add_ipsec_policy(s, ipsec_policy[0]);
562 if (ipsec_policy[1] != NULL)
563 add_ipsec_policy(s, ipsec_policy[1]);
567 if (setfib(rdomain) == -1)
571 /* Bind to a local port or source address if specified. */
572 if (sflag || pflag) {
573 struct addrinfo ahints, *ares;
576 /* try SO_BINDANY, but don't insist */
577 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
579 memset(&ahints, 0, sizeof(struct addrinfo));
580 ahints.ai_family = res0->ai_family;
581 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
582 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
583 ahints.ai_flags = AI_PASSIVE;
584 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
585 errx(1, "getaddrinfo: %s", gai_strerror(error));
587 if (bind(s, (struct sockaddr *)ares->ai_addr,
588 ares->ai_addrlen) < 0)
589 errx(1, "bind failed: %s", strerror(errno));
593 set_common_sockopts(s);
595 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
598 warn("connect to %s port %s (%s) failed", host, port,
599 uflag ? "udp" : "tcp");
603 } while ((res0 = res0->ai_next) != NULL);
612 * Returns a socket listening on a local port, binds to specified source
613 * address. Returns -1 on failure.
616 local_listen(char *host, char *port, struct addrinfo hints)
618 struct addrinfo *res, *res0;
622 /* Allow nodename to be null. */
623 hints.ai_flags |= AI_PASSIVE;
626 * In the case of binding to a wildcard address
627 * default to binding to an ipv4 address.
629 if (host == NULL && hints.ai_family == AF_UNSPEC)
630 hints.ai_family = AF_INET;
632 if ((error = getaddrinfo(host, port, &hints, &res)))
633 errx(1, "getaddrinfo: %s", gai_strerror(error));
637 if ((s = socket(res0->ai_family, res0->ai_socktype,
638 res0->ai_protocol)) < 0)
642 if (setfib(rdomain) == -1)
646 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
650 if (ipsec_policy[0] != NULL)
651 add_ipsec_policy(s, ipsec_policy[0]);
652 if (ipsec_policy[1] != NULL)
653 add_ipsec_policy(s, ipsec_policy[1]);
656 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
657 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
658 err(1, "disable TCP options");
661 if (bind(s, (struct sockaddr *)res0->ai_addr,
662 res0->ai_addrlen) == 0)
667 } while ((res0 = res0->ai_next) != NULL);
669 if (!uflag && s != -1) {
670 if (listen(s, 1) < 0)
681 * Loop that polls on the network file descriptor and stdin.
686 struct pollfd pfd[2];
687 unsigned char buf[8192];
688 int n, wfd = fileno(stdin);
689 int lfd = fileno(stdout);
692 plen = jflag ? 8192 : 1024;
694 /* Setup Network FD */
696 pfd[0].events = POLLIN;
698 /* Set up STDIN FD. */
700 pfd[1].events = POLLIN;
702 while (pfd[0].fd != -1) {
706 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
708 err(1, "Polling Error");
714 if (pfd[0].revents & POLLIN) {
715 if ((n = read(nfd, buf, plen)) < 0)
718 shutdown(nfd, SHUT_RD);
723 atelnet(nfd, buf, n);
724 if (atomicio(vwrite, lfd, buf, n) != n)
729 if (!dflag && pfd[1].revents & POLLIN) {
730 if ((n = read(wfd, buf, plen)) < 0 ||
734 shutdown(nfd, SHUT_WR);
738 if (atomicio(vwrite, nfd, buf, n) != n)
745 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
747 atelnet(int nfd, unsigned char *buf, unsigned int size)
749 unsigned char *p, *end;
750 unsigned char obuf[4];
755 for (p = buf; p < end; p++) {
761 if ((*p == WILL) || (*p == WONT))
763 if ((*p == DO) || (*p == DONT))
769 if (atomicio(vwrite, nfd, obuf, 3) != 3)
770 warn("Write Error!");
778 * Build an array or ports in portlist[], listing each port
779 * that we should try to connect to.
789 if ((n = strchr(p, '-')) != NULL) {
791 errx(1, "Cannot use -l with multiple ports!");
796 /* Make sure the ports are in order: lowest->highest. */
797 hi = strtonum(n, 1, PORT_MAX, &errstr);
799 errx(1, "port number %s: %s", errstr, n);
800 lo = strtonum(p, 1, PORT_MAX, &errstr);
802 errx(1, "port number %s: %s", errstr, p);
810 /* Load ports sequentially. */
811 for (cp = lo; cp <= hi; cp++) {
812 portlist[x] = calloc(1, PORT_MAX_LEN);
813 if (portlist[x] == NULL)
815 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
819 /* Randomly swap ports. */
824 for (x = 0; x <= (hi - lo); x++) {
825 y = (arc4random() & 0xFFFF) % (hi - lo);
827 portlist[x] = portlist[y];
832 hi = strtonum(p, 1, PORT_MAX, &errstr);
834 errx(1, "port number %s: %s", errstr, p);
835 portlist[0] = calloc(1, PORT_MAX_LEN);
836 if (portlist[0] == NULL)
844 * Do a few writes to see if the UDP port is there.
845 * XXX - Better way of doing this? Doesn't work for IPv6.
846 * Also fails after around 100 ports checked.
853 for (i = 0; i <= 3; i++) {
854 if (write(s, "X", 1) == 1)
863 set_common_sockopts(int s)
868 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
869 &x, sizeof(x)) == -1)
873 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
874 &x, sizeof(x)) == -1)
879 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
880 &x, sizeof(x)) == -1)
885 if (setsockopt(s, IPPROTO_IP, IP_TOS,
886 &Tflag, sizeof(Tflag)) == -1)
887 err(1, "set IP ToS");
890 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
891 &Iflag, sizeof(Iflag)) == -1)
892 err(1, "set TCP receive buffer size");
895 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
896 &Oflag, sizeof(Oflag)) == -1)
897 err(1, "set TCP send buffer size");
900 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
901 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
902 err(1, "disable TCP options");
911 if (strcmp(s, "lowdelay") == 0)
912 return (IPTOS_LOWDELAY);
913 if (strcmp(s, "throughput") == 0)
914 return (IPTOS_THROUGHPUT);
915 if (strcmp(s, "reliability") == 0)
916 return (IPTOS_RELIABILITY);
918 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
919 errx(1, "invalid IP Type of Service");
927 fprintf(stderr, "\tCommand Summary:\n\
930 \t-D Enable the debug socket option\n\
931 \t-d Detach from stdin\n");
934 \t-E Use IPsec ESP\n\
935 \t-e policy Use specified IPsec policy\n");
938 \t-h This help text\n\
939 \t-I length TCP receive buffer length\n\
940 \t-i secs\t Delay interval for lines sent, ports scanned\n\
941 \t-k Keep inbound sockets open for multiple connects\n\
942 \t-l Listen mode, for inbound connects\n\
943 \t-n Suppress name/port resolutions\n\
944 \t--no-tcpopt Disable TCP options\n\
945 \t-O length TCP send buffer length\n\
946 \t-o Terminate on EOF on input\n\
947 \t-P proxyuser\tUsername for proxy authentication\n\
948 \t-p port\t Specify local port for remote connects\n\
949 \t-r Randomize remote ports\n\
950 \t-S Enable the TCP MD5 signature option\n\
951 \t-s addr\t Local source address\n\
952 \t-T ToS\t Set IP Type of Service\n\
953 \t-t Answer TELNET negotiation\n\
954 \t-U Use UNIX domain socket\n\
956 \t-V fib Specify alternate routing table (FIB)\n\
958 \t-w secs\t Timeout for connects and final net reads\n\
959 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
960 \t-x addr[:port]\tSpecify proxy address and port\n\
961 \t-z Zero-I/O mode [used for scanning]\n\
962 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
964 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
971 add_ipsec_policy(int s, char *policy)
976 raw = ipsec_set_policy(policy, strlen(policy));
978 errx(1, "ipsec_set_policy `%s': %s", policy,
980 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
981 ipsec_get_policylen(raw));
983 err(1, "ipsec policy cannot be configured");
986 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
996 "usage: nc [-46DdEhklnorStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
998 "usage: nc [-46DdhklnorStUuvz] [-I length] [-i interval] [-O length]\n"
1000 "\t [-P proxy_username] [-p source_port] [-s source_ip_address] [-T ToS]\n"
1001 "\t [-V fib] [-w timeout] [-X proxy_protocol]\n"
1002 "\t [-x proxy_address[:port]] [hostname] [port]\n");