1 /* $OpenBSD: netcat.c,v 1.98 2010/07/03 04:44:51 guenther 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 },
150 while ((ch = getopt_long(argc, argv,
151 "46DdEe:hI:i:jklnoO:P:p:rSs:tT:UuV:vw:X:x:z",
152 longopts, NULL)) != -1) {
164 if (strcasecmp(optarg, "connect") == 0)
165 socksv = -1; /* HTTP proxy CONNECT */
166 else if (strcmp(optarg, "4") == 0)
167 socksv = 4; /* SOCKS v.4 */
168 else if (strcmp(optarg, "5") == 0)
169 socksv = 5; /* SOCKS v.5 */
171 errx(1, "unsupported proxy protocol");
178 ipsec_policy[ipsec_count++ % 2] = optarg;
180 errx(1, "IPsec support unavailable.");
185 ipsec_policy[0] = "in ipsec esp/transport//require";
186 ipsec_policy[1] = "out ipsec esp/transport//require";
188 errx(1, "IPsec support unavailable.");
195 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
197 errx(1, "interval %s: %s", errstr, optarg);
214 fprintf(stderr, "option -o is deprecated.\n");
235 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
236 errx(1, "Multiple FIBS not supported");
237 rtableid = (unsigned int)strtonum(optarg, 0,
238 numfibs - 1, &errstr);
240 errx(1, "rtable %s: %s", errstr, optarg);
246 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
248 errx(1, "timeout %s: %s", errstr, optarg);
253 if ((proxy = strdup(optarg)) == NULL)
263 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
265 errx(1, "TCP receive window %s: %s",
269 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
270 if (errstr != NULL) {
271 if (strcmp(errstr, "invalid") != 0)
272 errx(1, "TCP send window %s: %s",
280 Tflag = parse_iptos(optarg);
289 /* Cruft to make sure options are clean, and used properly. */
290 if (argv[0] && !argv[1] && family == AF_UNIX) {
292 errx(1, "cannot use -u and -U");
295 } else if (argv[0] && !argv[1]) {
300 } else if (argv[0] && argv[1]) {
307 errx(1, "cannot use -s and -l");
309 errx(1, "cannot use -p and -l");
311 errx(1, "cannot use -z and -l");
313 errx(1, "must use -l with -k");
315 /* Initialize addrinfo structure. */
316 if (family != AF_UNIX) {
317 memset(&hints, 0, sizeof(struct addrinfo));
318 hints.ai_family = family;
319 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
320 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
322 hints.ai_flags |= AI_NUMERICHOST;
327 errx(1, "no proxy support for UDP mode");
330 errx(1, "no proxy support for listen");
332 if (family == AF_UNIX)
333 errx(1, "no proxy support for unix sockets");
335 /* XXX IPv6 transport to proxy would probably work */
336 if (family == AF_INET6)
337 errx(1, "no proxy support for IPv6");
340 errx(1, "no proxy support for local source address");
342 proxyhost = strsep(&proxy, ":");
345 memset(&proxyhints, 0, sizeof(struct addrinfo));
346 proxyhints.ai_family = family;
347 proxyhints.ai_socktype = SOCK_STREAM;
348 proxyhints.ai_protocol = IPPROTO_TCP;
350 proxyhints.ai_flags |= AI_NUMERICHOST;
357 if (family == AF_UNIX)
358 s = unix_listen(host);
360 /* Allow only one connection at a time, but stay alive. */
362 if (family != AF_UNIX)
363 s = local_listen(host, uport, hints);
367 * For UDP, we will use recvfrom() initially
368 * to wait for a caller, then use the regular
369 * functions to talk to the caller.
374 struct sockaddr_storage z;
377 plen = jflag ? 16384 : 2048;
378 rv = recvfrom(s, buf, plen, MSG_PEEK,
379 (struct sockaddr *)&z, &len);
383 rv = connect(s, (struct sockaddr *)&z, len);
389 len = sizeof(cliaddr);
390 connfd = accept(s, (struct sockaddr *)&cliaddr,
396 if (family != AF_UNIX)
402 } else if (family == AF_UNIX) {
405 if ((s = unix_connect(host)) > 0 && !zflag) {
416 /* Construct the portlist[] array. */
419 /* Cycle through portlist, connecting to each port. */
420 for (i = 0; portlist[i] != NULL; i++) {
425 s = socks_connect(host, portlist[i], hints,
426 proxyhost, proxyport, proxyhints, socksv,
429 s = remote_connect(host, portlist[i], hints);
435 if (vflag || zflag) {
436 /* For UDP, make sure we are connected. */
438 if (udptest(s) == -1) {
444 /* Don't look up port if -n. */
449 ntohs(atoi(portlist[i])),
450 uflag ? "udp" : "tcp");
454 "Connection to %s %s port [%s/%s] "
455 "succeeded!\n", host, portlist[i],
456 uflag ? "udp" : "tcp",
457 sv ? sv->s_name : "*");
472 * Returns a socket connected to a local unix socket. Returns -1 on failure.
475 unix_connect(char *path)
477 struct sockaddr_un sun;
480 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
482 (void)fcntl(s, F_SETFD, 1);
484 memset(&sun, 0, sizeof(struct sockaddr_un));
485 sun.sun_family = AF_UNIX;
487 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
488 sizeof(sun.sun_path)) {
490 errno = ENAMETOOLONG;
493 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
503 * Create a unix domain socket, and listen on it.
506 unix_listen(char *path)
508 struct sockaddr_un sun;
511 /* Create unix domain socket. */
512 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
515 memset(&sun, 0, sizeof(struct sockaddr_un));
516 sun.sun_family = AF_UNIX;
518 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
519 sizeof(sun.sun_path)) {
521 errno = ENAMETOOLONG;
525 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
530 if (listen(s, 5) < 0) {
539 * Returns a socket connected to a remote host. Properly binds to a local
540 * port or source address if needed. Returns -1 on failure.
543 remote_connect(const char *host, const char *port, struct addrinfo hints)
545 struct addrinfo *res, *res0;
546 int s, error, on = 1;
548 if ((error = getaddrinfo(host, port, &hints, &res)))
549 errx(1, "getaddrinfo: %s", gai_strerror(error));
553 if ((s = socket(res0->ai_family, res0->ai_socktype,
554 res0->ai_protocol)) < 0)
557 if (ipsec_policy[0] != NULL)
558 add_ipsec_policy(s, ipsec_policy[0]);
559 if (ipsec_policy[1] != NULL)
560 add_ipsec_policy(s, ipsec_policy[1]);
564 if (setfib(rtableid) == -1)
568 /* Bind to a local port or source address if specified. */
569 if (sflag || pflag) {
570 struct addrinfo ahints, *ares;
572 /* try IP_BINDANY, but don't insist */
573 setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
574 memset(&ahints, 0, sizeof(struct addrinfo));
575 ahints.ai_family = res0->ai_family;
576 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
577 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
578 ahints.ai_flags = AI_PASSIVE;
579 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
580 errx(1, "getaddrinfo: %s", gai_strerror(error));
582 if (bind(s, (struct sockaddr *)ares->ai_addr,
583 ares->ai_addrlen) < 0)
584 errx(1, "bind failed: %s", strerror(errno));
588 set_common_sockopts(s);
590 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
593 warn("connect to %s port %s (%s) failed", host, port,
594 uflag ? "udp" : "tcp");
598 } while ((res0 = res0->ai_next) != NULL);
607 * Returns a socket listening on a local port, binds to specified source
608 * address. Returns -1 on failure.
611 local_listen(char *host, char *port, struct addrinfo hints)
613 struct addrinfo *res, *res0;
617 /* Allow nodename to be null. */
618 hints.ai_flags |= AI_PASSIVE;
621 * In the case of binding to a wildcard address
622 * default to binding to an ipv4 address.
624 if (host == NULL && hints.ai_family == AF_UNSPEC)
625 hints.ai_family = AF_INET;
627 if ((error = getaddrinfo(host, port, &hints, &res)))
628 errx(1, "getaddrinfo: %s", gai_strerror(error));
632 if ((s = socket(res0->ai_family, res0->ai_socktype,
633 res0->ai_protocol)) < 0)
637 if (setfib(rtableid) == -1)
641 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
645 if (ipsec_policy[0] != NULL)
646 add_ipsec_policy(s, ipsec_policy[0]);
647 if (ipsec_policy[1] != NULL)
648 add_ipsec_policy(s, ipsec_policy[1]);
651 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
652 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
653 err(1, "disable TCP options");
656 if (bind(s, (struct sockaddr *)res0->ai_addr,
657 res0->ai_addrlen) == 0)
662 } while ((res0 = res0->ai_next) != NULL);
664 if (!uflag && s != -1) {
665 if (listen(s, 1) < 0)
676 * Loop that polls on the network file descriptor and stdin.
681 struct pollfd pfd[2];
682 unsigned char buf[16384];
683 int n, wfd = fileno(stdin);
684 int lfd = fileno(stdout);
687 plen = jflag ? 16384 : 2048;
689 /* Setup Network FD */
691 pfd[0].events = POLLIN;
693 /* Set up STDIN FD. */
695 pfd[1].events = POLLIN;
697 while (pfd[0].fd != -1) {
701 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
703 err(1, "Polling Error");
709 if (pfd[0].revents & POLLIN) {
710 if ((n = read(nfd, buf, plen)) < 0)
713 shutdown(nfd, SHUT_RD);
718 atelnet(nfd, buf, n);
719 if (atomicio(vwrite, lfd, buf, n) != n)
724 if (!dflag && pfd[1].revents & POLLIN) {
725 if ((n = read(wfd, buf, plen)) < 0)
728 shutdown(nfd, SHUT_WR);
732 if (atomicio(vwrite, nfd, buf, n) != n)
739 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
741 atelnet(int nfd, unsigned char *buf, unsigned int size)
743 unsigned char *p, *end;
744 unsigned char obuf[4];
748 end = buf + size - 2;
750 for (p = buf; p < end; p++) {
756 if ((*p == WILL) || (*p == WONT))
758 else if ((*p == DO) || (*p == DONT))
765 if (atomicio(vwrite, nfd, obuf, 3) != 3)
766 warn("Write Error!");
772 * Build an array or ports in portlist[], listing each port
773 * that we should try to connect to.
783 if ((n = strchr(p, '-')) != NULL) {
785 errx(1, "Cannot use -l with multiple ports!");
790 /* Make sure the ports are in order: lowest->highest. */
791 hi = strtonum(n, 1, PORT_MAX, &errstr);
793 errx(1, "port number %s: %s", errstr, n);
794 lo = strtonum(p, 1, PORT_MAX, &errstr);
796 errx(1, "port number %s: %s", errstr, p);
804 /* Load ports sequentially. */
805 for (cp = lo; cp <= hi; cp++) {
806 portlist[x] = calloc(1, PORT_MAX_LEN);
807 if (portlist[x] == NULL)
809 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
813 /* Randomly swap ports. */
818 for (x = 0; x <= (hi - lo); x++) {
819 y = (arc4random() & 0xFFFF) % (hi - lo);
821 portlist[x] = portlist[y];
826 hi = strtonum(p, 1, PORT_MAX, &errstr);
828 errx(1, "port number %s: %s", errstr, p);
829 portlist[0] = strdup(p);
830 if (portlist[0] == NULL)
837 * Do a few writes to see if the UDP port is there.
838 * XXX - Better way of doing this? Doesn't work for IPv6.
839 * Also fails after around 100 ports checked.
846 for (i = 0; i <= 3; i++) {
847 if (write(s, "X", 1) == 1)
856 set_common_sockopts(int s)
861 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
862 &x, sizeof(x)) == -1)
866 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
867 &x, sizeof(x)) == -1)
872 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
873 &x, sizeof(x)) == -1)
878 if (setsockopt(s, IPPROTO_IP, IP_TOS,
879 &Tflag, sizeof(Tflag)) == -1)
880 err(1, "set IP ToS");
883 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
884 &Iflag, sizeof(Iflag)) == -1)
885 err(1, "set TCP receive buffer size");
888 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
889 &Oflag, sizeof(Oflag)) == -1)
890 err(1, "set TCP send buffer size");
893 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
894 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
895 err(1, "disable TCP options");
904 if (strcmp(s, "lowdelay") == 0)
905 return (IPTOS_LOWDELAY);
906 if (strcmp(s, "throughput") == 0)
907 return (IPTOS_THROUGHPUT);
908 if (strcmp(s, "reliability") == 0)
909 return (IPTOS_RELIABILITY);
911 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
912 errx(1, "invalid IP Type of Service");
920 fprintf(stderr, "\tCommand Summary:\n\
923 \t-D Enable the debug socket option\n\
924 \t-d Detach from stdin\n");
927 \t-E Use IPsec ESP\n\
928 \t-e policy Use specified IPsec policy\n");
931 \t-h This help text\n\
932 \t-I length TCP receive buffer length\n\
933 \t-i secs\t Delay interval for lines sent, ports scanned\n\
934 \t-k Keep inbound sockets open for multiple connects\n\
935 \t-l Listen mode, for inbound connects\n\
936 \t-n Suppress name/port resolutions\n\
937 \t--no-tcpopt Disable TCP options\n\
938 \t-O length TCP send buffer length\n\
939 \t-P proxyuser\tUsername for proxy authentication\n\
940 \t-p port\t Specify local port for remote connects\n\
941 \t-r Randomize remote ports\n\
942 \t-S Enable the TCP MD5 signature option\n\
943 \t-s addr\t Local source address\n\
944 \t-T ToS\t Set IP Type of Service\n\
945 \t-t Answer TELNET negotiation\n\
946 \t-U Use UNIX domain socket\n\
948 \t-V rtable Specify alternate routing table\n\
950 \t-w secs\t Timeout for connects and final net reads\n\
951 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
952 \t-x addr[:port]\tSpecify proxy address and port\n\
953 \t-z Zero-I/O mode [used for scanning]\n\
954 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
956 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
963 add_ipsec_policy(int s, char *policy)
968 raw = ipsec_set_policy(policy, strlen(policy));
970 errx(1, "ipsec_set_policy `%s': %s", policy,
972 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
973 ipsec_get_policylen(raw));
975 err(1, "ipsec policy cannot be configured");
978 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
988 "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
990 "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
992 "\t [-P proxy_username] [-p source_port] [-s source_ip_address] [-T ToS]\n"
993 "\t [-V rtable] [-w timeout] [-X proxy_protocol]\n"
994 "\t [-x proxy_address[:port]] [hostname] [port]\n");