1 /* $OpenBSD: netcat.c,v 1.95 2010/02/27 00:58:56 nicm 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 dflag; /* detached, no stdin */
76 unsigned int iflag; /* Interval Flag */
77 int jflag; /* use jumbo frames if we can */
78 int kflag; /* More than one connect */
79 int lflag; /* Bind to local port */
80 int nflag; /* Don't do name look up */
81 int FreeBSD_Oflag; /* Do not use TCP options */
82 char *Pflag; /* Proxy username */
83 char *pflag; /* Localport flag */
84 int rflag; /* Random ports flag */
85 char *sflag; /* Source Address */
86 int tflag; /* Telnet Emulation */
87 int uflag; /* UDP - Default to TCP */
88 int vflag; /* Verbosity */
89 int xflag; /* Socks proxy */
90 int zflag; /* Port Scan Flag */
91 int Dflag; /* sodebug */
92 int Iflag; /* TCP receive buffer size */
93 int Oflag; /* TCP send buffer size */
94 int Sflag; /* TCP MD5 signature option */
95 int Tflag = -1; /* IP Type of Service */
99 int family = AF_UNSPEC;
100 char *portlist[PORT_MAX+1];
102 void atelnet(int, unsigned char *, unsigned int);
103 void build_ports(char *);
105 int local_listen(char *, char *, struct addrinfo);
107 int remote_connect(const char *, const char *, struct addrinfo);
108 int socks_connect(const char *, const char *, struct addrinfo,
109 const char *, const char *, struct addrinfo, int, const char *);
111 int unix_connect(char *);
112 int unix_listen(char *);
113 void set_common_sockopts(int);
114 int parse_iptos(char *);
118 void add_ipsec_policy(int, char *);
120 char *ipsec_policy[2];
124 main(int argc, char *argv[])
126 int ch, s, ret, socksv, ipsec_count;
128 size_t intsize = sizeof(int);
130 struct addrinfo hints;
133 struct sockaddr_storage cliaddr;
135 const char *errstr, *proxyhost = "", *proxyport = NULL;
136 struct addrinfo proxyhints;
137 struct option longopts[] = {
138 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
151 while ((ch = getopt_long(argc, argv,
152 "46DdEe:hI:i:jklnoO:P:p:rSs:tT:UuV:vw:X:x:z",
153 longopts, NULL)) != -1) {
165 if (strcasecmp(optarg, "connect") == 0)
166 socksv = -1; /* HTTP proxy CONNECT */
167 else if (strcmp(optarg, "4") == 0)
168 socksv = 4; /* SOCKS v.4 */
169 else if (strcmp(optarg, "5") == 0)
170 socksv = 5; /* SOCKS v.5 */
172 errx(1, "unsupported proxy protocol");
179 ipsec_policy[ipsec_count++ % 2] = optarg;
181 errx(1, "IPsec support unavailable.");
186 ipsec_policy[0] = "in ipsec esp/transport//require";
187 ipsec_policy[1] = "out ipsec esp/transport//require";
189 errx(1, "IPsec support unavailable.");
196 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
198 errx(1, "interval %s: %s", errstr, optarg);
215 fprintf(stderr, "option -o is deprecated.\n");
236 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
237 errx(1, "Multiple FIBS not supported");
238 rdomain = (unsigned int)strtonum(optarg, 0,
239 numfibs - 1, &errstr);
241 errx(1, "FIB %s: %s", errstr, optarg);
247 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
249 errx(1, "timeout %s: %s", errstr, optarg);
254 if ((proxy = strdup(optarg)) == NULL)
264 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
266 errx(1, "TCP receive window %s: %s",
270 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
271 if (errstr != NULL) {
272 if (strcmp(errstr, "invalid") != 0)
273 errx(1, "TCP send window %s: %s",
281 Tflag = parse_iptos(optarg);
290 /* Cruft to make sure options are clean, and used properly. */
291 if (argv[0] && !argv[1] && family == AF_UNIX) {
293 errx(1, "cannot use -u and -U");
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 /* Initialize addrinfo structure. */
317 if (family != AF_UNIX) {
318 memset(&hints, 0, sizeof(struct addrinfo));
319 hints.ai_family = family;
320 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
321 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
323 hints.ai_flags |= AI_NUMERICHOST;
328 errx(1, "no proxy support for UDP mode");
331 errx(1, "no proxy support for listen");
333 if (family == AF_UNIX)
334 errx(1, "no proxy support for unix sockets");
336 /* XXX IPv6 transport to proxy would probably work */
337 if (family == AF_INET6)
338 errx(1, "no proxy support for IPv6");
341 errx(1, "no proxy support for local source address");
343 proxyhost = strsep(&proxy, ":");
346 memset(&proxyhints, 0, sizeof(struct addrinfo));
347 proxyhints.ai_family = family;
348 proxyhints.ai_socktype = SOCK_STREAM;
349 proxyhints.ai_protocol = IPPROTO_TCP;
351 proxyhints.ai_flags |= AI_NUMERICHOST;
358 if (family == AF_UNIX)
359 s = unix_listen(host);
361 /* Allow only one connection at a time, but stay alive. */
363 if (family != AF_UNIX)
364 s = local_listen(host, uport, hints);
368 * For UDP, we will use recvfrom() initially
369 * to wait for a caller, then use the regular
370 * functions to talk to the caller.
375 struct sockaddr_storage z;
378 plen = jflag ? 8192 : 1024;
379 rv = recvfrom(s, buf, plen, MSG_PEEK,
380 (struct sockaddr *)&z, &len);
384 rv = connect(s, (struct sockaddr *)&z, len);
390 len = sizeof(cliaddr);
391 connfd = accept(s, (struct sockaddr *)&cliaddr,
397 if (family != AF_UNIX)
403 } else if (family == AF_UNIX) {
406 if ((s = unix_connect(host)) > 0 && !zflag) {
417 /* Construct the portlist[] array. */
420 /* Cycle through portlist, connecting to each port. */
421 for (i = 0; portlist[i] != NULL; i++) {
426 s = socks_connect(host, portlist[i], hints,
427 proxyhost, proxyport, proxyhints, socksv,
430 s = remote_connect(host, portlist[i], hints);
436 if (vflag || zflag) {
437 /* For UDP, make sure we are connected. */
439 if (udptest(s) == -1) {
445 /* Don't look up port if -n. */
450 ntohs(atoi(portlist[i])),
451 uflag ? "udp" : "tcp");
455 "Connection to %s %s port [%s/%s] "
456 "succeeded!\n", host, portlist[i],
457 uflag ? "udp" : "tcp",
458 sv ? sv->s_name : "*");
473 * Returns a socket connected to a local unix socket. Returns -1 on failure.
476 unix_connect(char *path)
478 struct sockaddr_un sun;
481 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
483 (void)fcntl(s, F_SETFD, 1);
485 memset(&sun, 0, sizeof(struct sockaddr_un));
486 sun.sun_family = AF_UNIX;
488 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
489 sizeof(sun.sun_path)) {
491 errno = ENAMETOOLONG;
494 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
504 * Create a unix domain socket, and listen on it.
507 unix_listen(char *path)
509 struct sockaddr_un sun;
512 /* Create unix domain socket. */
513 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
516 memset(&sun, 0, sizeof(struct sockaddr_un));
517 sun.sun_family = AF_UNIX;
519 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
520 sizeof(sun.sun_path)) {
522 errno = ENAMETOOLONG;
526 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
531 if (listen(s, 5) < 0) {
540 * Returns a socket connected to a remote host. Properly binds to a local
541 * port or source address if needed. Returns -1 on failure.
544 remote_connect(const char *host, const char *port, struct addrinfo hints)
546 struct addrinfo *res, *res0;
547 int s, error, on = 1;
549 if ((error = getaddrinfo(host, port, &hints, &res)))
550 errx(1, "getaddrinfo: %s", gai_strerror(error));
554 if ((s = socket(res0->ai_family, res0->ai_socktype,
555 res0->ai_protocol)) < 0)
558 if (ipsec_policy[0] != NULL)
559 add_ipsec_policy(s, ipsec_policy[0]);
560 if (ipsec_policy[1] != NULL)
561 add_ipsec_policy(s, ipsec_policy[1]);
565 if (setfib(rdomain) == -1)
569 /* Bind to a local port or source address if specified. */
570 if (sflag || pflag) {
571 struct addrinfo ahints, *ares;
573 /* try IP_BINDANY, but don't insist */
574 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
575 memset(&ahints, 0, sizeof(struct addrinfo));
576 ahints.ai_family = res0->ai_family;
577 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
578 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
579 ahints.ai_flags = AI_PASSIVE;
580 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
581 errx(1, "getaddrinfo: %s", gai_strerror(error));
583 if (bind(s, (struct sockaddr *)ares->ai_addr,
584 ares->ai_addrlen) < 0)
585 errx(1, "bind failed: %s", strerror(errno));
589 set_common_sockopts(s);
591 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
594 warn("connect to %s port %s (%s) failed", host, port,
595 uflag ? "udp" : "tcp");
599 } while ((res0 = res0->ai_next) != NULL);
608 * Returns a socket listening on a local port, binds to specified source
609 * address. Returns -1 on failure.
612 local_listen(char *host, char *port, struct addrinfo hints)
614 struct addrinfo *res, *res0;
618 /* Allow nodename to be null. */
619 hints.ai_flags |= AI_PASSIVE;
622 * In the case of binding to a wildcard address
623 * default to binding to an ipv4 address.
625 if (host == NULL && hints.ai_family == AF_UNSPEC)
626 hints.ai_family = AF_INET;
628 if ((error = getaddrinfo(host, port, &hints, &res)))
629 errx(1, "getaddrinfo: %s", gai_strerror(error));
633 if ((s = socket(res0->ai_family, res0->ai_socktype,
634 res0->ai_protocol)) < 0)
638 if (setfib(rdomain) == -1)
642 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
646 if (ipsec_policy[0] != NULL)
647 add_ipsec_policy(s, ipsec_policy[0]);
648 if (ipsec_policy[1] != NULL)
649 add_ipsec_policy(s, ipsec_policy[1]);
652 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
653 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
654 err(1, "disable TCP options");
657 if (bind(s, (struct sockaddr *)res0->ai_addr,
658 res0->ai_addrlen) == 0)
663 } while ((res0 = res0->ai_next) != NULL);
665 if (!uflag && s != -1) {
666 if (listen(s, 1) < 0)
677 * Loop that polls on the network file descriptor and stdin.
682 struct pollfd pfd[2];
683 unsigned char buf[8192];
684 int n, wfd = fileno(stdin);
685 int lfd = fileno(stdout);
688 plen = jflag ? 8192 : 1024;
690 /* Setup Network FD */
692 pfd[0].events = POLLIN;
694 /* Set up STDIN FD. */
696 pfd[1].events = POLLIN;
698 while (pfd[0].fd != -1) {
702 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
704 err(1, "Polling Error");
710 if (pfd[0].revents & POLLIN) {
711 if ((n = read(nfd, buf, plen)) < 0)
714 shutdown(nfd, SHUT_RD);
719 atelnet(nfd, buf, n);
720 if (atomicio(vwrite, lfd, buf, n) != n)
725 if (!dflag && pfd[1].revents & POLLIN) {
726 if ((n = read(wfd, buf, plen)) < 0)
729 shutdown(nfd, SHUT_WR);
733 if (atomicio(vwrite, nfd, buf, n) != n)
740 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
742 atelnet(int nfd, unsigned char *buf, unsigned int size)
744 unsigned char *p, *end;
745 unsigned char obuf[4];
749 end = buf + size - 2;
751 for (p = buf; p < end; p++) {
757 if ((*p == WILL) || (*p == WONT))
759 else if ((*p == DO) || (*p == DONT))
766 if (atomicio(vwrite, nfd, obuf, 3) != 3)
767 warn("Write Error!");
773 * Build an array or ports in portlist[], listing each port
774 * that we should try to connect to.
784 if ((n = strchr(p, '-')) != NULL) {
786 errx(1, "Cannot use -l with multiple ports!");
791 /* Make sure the ports are in order: lowest->highest. */
792 hi = strtonum(n, 1, PORT_MAX, &errstr);
794 errx(1, "port number %s: %s", errstr, n);
795 lo = strtonum(p, 1, PORT_MAX, &errstr);
797 errx(1, "port number %s: %s", errstr, p);
805 /* Load ports sequentially. */
806 for (cp = lo; cp <= hi; cp++) {
807 portlist[x] = calloc(1, PORT_MAX_LEN);
808 if (portlist[x] == NULL)
810 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
814 /* Randomly swap ports. */
819 for (x = 0; x <= (hi - lo); x++) {
820 y = (arc4random() & 0xFFFF) % (hi - lo);
822 portlist[x] = portlist[y];
827 hi = strtonum(p, 1, PORT_MAX, &errstr);
829 errx(1, "port number %s: %s", errstr, p);
830 portlist[0] = calloc(1, PORT_MAX_LEN);
831 if (portlist[0] == NULL)
839 * Do a few writes to see if the UDP port is there.
840 * XXX - Better way of doing this? Doesn't work for IPv6.
841 * Also fails after around 100 ports checked.
848 for (i = 0; i <= 3; i++) {
849 if (write(s, "X", 1) == 1)
858 set_common_sockopts(int s)
863 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
864 &x, sizeof(x)) == -1)
868 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
869 &x, sizeof(x)) == -1)
874 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
875 &x, sizeof(x)) == -1)
880 if (setsockopt(s, IPPROTO_IP, IP_TOS,
881 &Tflag, sizeof(Tflag)) == -1)
882 err(1, "set IP ToS");
885 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
886 &Iflag, sizeof(Iflag)) == -1)
887 err(1, "set TCP receive buffer size");
890 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
891 &Oflag, sizeof(Oflag)) == -1)
892 err(1, "set TCP send buffer size");
895 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
896 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
897 err(1, "disable TCP options");
906 if (strcmp(s, "lowdelay") == 0)
907 return (IPTOS_LOWDELAY);
908 if (strcmp(s, "throughput") == 0)
909 return (IPTOS_THROUGHPUT);
910 if (strcmp(s, "reliability") == 0)
911 return (IPTOS_RELIABILITY);
913 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
914 errx(1, "invalid IP Type of Service");
922 fprintf(stderr, "\tCommand Summary:\n\
925 \t-D Enable the debug socket option\n\
926 \t-d Detach from stdin\n");
929 \t-E Use IPsec ESP\n\
930 \t-e policy Use specified IPsec policy\n");
933 \t-h This help text\n\
934 \t-I length TCP receive buffer length\n\
935 \t-i secs\t Delay interval for lines sent, ports scanned\n\
936 \t-k Keep inbound sockets open for multiple connects\n\
937 \t-l Listen mode, for inbound connects\n\
938 \t-n Suppress name/port resolutions\n\
939 \t--no-tcpopt Disable TCP options\n\
940 \t-O length TCP send buffer length\n\
941 \t-P proxyuser\tUsername for proxy authentication\n\
942 \t-p port\t Specify local port for remote connects\n\
943 \t-r Randomize remote ports\n\
944 \t-S Enable the TCP MD5 signature option\n\
945 \t-s addr\t Local source address\n\
946 \t-T ToS\t Set IP Type of Service\n\
947 \t-t Answer TELNET negotiation\n\
948 \t-U Use UNIX domain socket\n\
950 \t-V fib Specify alternate routing table (FIB)\n\
952 \t-w secs\t Timeout for connects and final net reads\n\
953 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
954 \t-x addr[:port]\tSpecify proxy address and port\n\
955 \t-z Zero-I/O mode [used for scanning]\n\
956 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
958 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
965 add_ipsec_policy(int s, char *policy)
970 raw = ipsec_set_policy(policy, strlen(policy));
972 errx(1, "ipsec_set_policy `%s': %s", policy,
974 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
975 ipsec_get_policylen(raw));
977 err(1, "ipsec policy cannot be configured");
980 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
990 "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
992 "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
994 "\t [-P proxy_username] [-p source_port] [-s source_ip_address] [-T ToS]\n"
995 "\t [-V fib] [-w timeout] [-X proxy_protocol]\n"
996 "\t [-x proxy_address[:port]] [hostname] [port]\n");