1 /* $OpenBSD: netcat.c,v 1.89 2007/02/20 14:11:17 jmc 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>
42 #include <netinet/in.h>
43 #include <netinet/in_systm.h>
45 #include <netipsec/ipsec.h>
47 #include <netinet/tcp.h>
48 #include <netinet/ip.h>
49 #include <arpa/telnet.h>
66 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
69 #define PORT_MAX 65535
70 #define PORT_MAX_LEN 6
72 /* Command Line Options */
73 int Eflag; /* Use IPsec ESP */
74 int dflag; /* detached, no stdin */
75 unsigned int iflag; /* Interval Flag */
76 int jflag; /* use jumbo frames if we can */
77 int kflag; /* More than one connect */
78 int lflag; /* Bind to local port */
79 int nflag; /* Don't do name look up */
80 int oflag; /* Once only: stop on EOF */
81 int 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 Sflag; /* TCP MD5 signature option */
93 int Tflag = -1; /* IP Type of Service */
96 int family = AF_UNSPEC;
97 char *portlist[PORT_MAX+1];
99 void atelnet(int, unsigned char *, unsigned int);
100 void build_ports(char *);
102 int local_listen(char *, char *, struct addrinfo);
104 int remote_connect(const char *, const char *, struct addrinfo);
105 int socks_connect(const char *, const char *, struct addrinfo,
106 const char *, const char *, struct addrinfo, int, const char *);
108 int unix_connect(char *);
109 int unix_listen(char *);
110 void set_common_sockopts(int);
111 int parse_iptos(char *);
115 void add_ipsec_policy(int, char *);
117 char *ipsec_policy[2];
121 main(int argc, char *argv[])
123 int ch, s, ret, socksv, ipsec_count;
125 struct addrinfo hints;
128 struct sockaddr_storage cliaddr;
130 const char *errstr, *proxyhost = "", *proxyport = NULL;
131 struct addrinfo proxyhints;
141 while ((ch = getopt(argc, argv,
142 "46e:DEdhi:jklnoOP:p:rSs:tT:Uuvw:X:x:z")) != -1) {
154 if (strcasecmp(optarg, "connect") == 0)
155 socksv = -1; /* HTTP proxy CONNECT */
156 else if (strcmp(optarg, "4") == 0)
157 socksv = 4; /* SOCKS v.4 */
158 else if (strcmp(optarg, "5") == 0)
159 socksv = 5; /* SOCKS v.5 */
161 errx(1, "unsupported proxy protocol");
168 ipsec_policy[ipsec_count++ % 2] = optarg;
170 errx(1, "IPsec support unavailable.");
175 ipsec_policy[0] = "in ipsec esp/transport//require";
176 ipsec_policy[1] = "out ipsec esp/transport//require";
178 errx(1, "IPsec support unavailable.");
185 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
187 errx(1, "interval %s: %s", errstr, optarg);
231 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
233 errx(1, "timeout %s: %s", errstr, optarg);
238 if ((proxy = strdup(optarg)) == NULL)
251 Tflag = parse_iptos(optarg);
260 /* Cruft to make sure options are clean, and used properly. */
261 if (argv[0] && !argv[1] && family == AF_UNIX) {
263 errx(1, "cannot use -u and -U");
266 } else if (argv[0] && !argv[1]) {
271 } else if (argv[0] && argv[1]) {
278 errx(1, "cannot use -s and -l");
280 errx(1, "cannot use -p and -l");
282 errx(1, "cannot use -z and -l");
284 errx(1, "must use -l with -k");
286 /* Initialize addrinfo structure. */
287 if (family != AF_UNIX) {
288 memset(&hints, 0, sizeof(struct addrinfo));
289 hints.ai_family = family;
290 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
291 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
293 hints.ai_flags |= AI_NUMERICHOST;
298 errx(1, "no proxy support for UDP mode");
301 errx(1, "no proxy support for listen");
303 if (family == AF_UNIX)
304 errx(1, "no proxy support for unix sockets");
306 /* XXX IPv6 transport to proxy would probably work */
307 if (family == AF_INET6)
308 errx(1, "no proxy support for IPv6");
311 errx(1, "no proxy support for local source address");
313 proxyhost = strsep(&proxy, ":");
316 memset(&proxyhints, 0, sizeof(struct addrinfo));
317 proxyhints.ai_family = family;
318 proxyhints.ai_socktype = SOCK_STREAM;
319 proxyhints.ai_protocol = IPPROTO_TCP;
321 proxyhints.ai_flags |= AI_NUMERICHOST;
328 if (family == AF_UNIX)
329 s = unix_listen(host);
331 /* Allow only one connection at a time, but stay alive. */
333 if (family != AF_UNIX)
334 s = local_listen(host, uport, hints);
338 * For UDP, we will use recvfrom() initially
339 * to wait for a caller, then use the regular
340 * functions to talk to the caller.
345 struct sockaddr_storage z;
348 plen = jflag ? 8192 : 1024;
349 rv = recvfrom(s, buf, plen, MSG_PEEK,
350 (struct sockaddr *)&z, &len);
354 rv = connect(s, (struct sockaddr *)&z, len);
360 len = sizeof(cliaddr);
361 connfd = accept(s, (struct sockaddr *)&cliaddr,
367 if (family != AF_UNIX)
373 } else if (family == AF_UNIX) {
376 if ((s = unix_connect(host)) > 0 && !zflag) {
387 /* Construct the portlist[] array. */
390 /* Cycle through portlist, connecting to each port. */
391 for (i = 0; portlist[i] != NULL; i++) {
396 s = socks_connect(host, portlist[i], hints,
397 proxyhost, proxyport, proxyhints, socksv,
400 s = remote_connect(host, portlist[i], hints);
406 if (vflag || zflag) {
407 /* For UDP, make sure we are connected. */
409 if (udptest(s) == -1) {
415 /* Don't look up port if -n. */
420 ntohs(atoi(portlist[i])),
421 uflag ? "udp" : "tcp");
424 printf("Connection to %s %s port [%s/%s] succeeded!\n",
425 host, portlist[i], uflag ? "udp" : "tcp",
426 sv ? sv->s_name : "*");
441 * Returns a socket connected to a local unix socket. Returns -1 on failure.
444 unix_connect(char *path)
446 struct sockaddr_un sun;
449 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
451 (void)fcntl(s, F_SETFD, 1);
453 memset(&sun, 0, sizeof(struct sockaddr_un));
454 sun.sun_family = AF_UNIX;
456 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
457 sizeof(sun.sun_path)) {
459 errno = ENAMETOOLONG;
462 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
472 * Create a unix domain socket, and listen on it.
475 unix_listen(char *path)
477 struct sockaddr_un sun;
480 /* Create unix domain socket. */
481 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
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;
494 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
499 if (listen(s, 5) < 0) {
508 * Returns a socket connected to a remote host. Properly binds to a local
509 * port or source address if needed. Returns -1 on failure.
512 remote_connect(const char *host, const char *port, struct addrinfo hints)
514 struct addrinfo *res, *res0;
517 if ((error = getaddrinfo(host, port, &hints, &res)))
518 errx(1, "getaddrinfo: %s", gai_strerror(error));
522 if ((s = socket(res0->ai_family, res0->ai_socktype,
523 res0->ai_protocol)) < 0)
526 if (ipsec_policy[0] != NULL)
527 add_ipsec_policy(s, ipsec_policy[0]);
528 if (ipsec_policy[1] != NULL)
529 add_ipsec_policy(s, ipsec_policy[1]);
532 /* Bind to a local port or source address if specified. */
533 if (sflag || pflag) {
534 struct addrinfo ahints, *ares;
536 memset(&ahints, 0, sizeof(struct addrinfo));
537 ahints.ai_family = res0->ai_family;
538 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
539 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
540 ahints.ai_flags = AI_PASSIVE;
541 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
542 errx(1, "getaddrinfo: %s", gai_strerror(error));
544 if (bind(s, (struct sockaddr *)ares->ai_addr,
545 ares->ai_addrlen) < 0)
546 errx(1, "bind failed: %s", strerror(errno));
550 set_common_sockopts(s);
552 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
555 warn("connect to %s port %s (%s) failed", host, port,
556 uflag ? "udp" : "tcp");
560 } while ((res0 = res0->ai_next) != NULL);
569 * Returns a socket listening on a local port, binds to specified source
570 * address. Returns -1 on failure.
573 local_listen(char *host, char *port, struct addrinfo hints)
575 struct addrinfo *res, *res0;
579 /* Allow nodename to be null. */
580 hints.ai_flags |= AI_PASSIVE;
583 * In the case of binding to a wildcard address
584 * default to binding to an ipv4 address.
586 if (host == NULL && hints.ai_family == AF_UNSPEC)
587 hints.ai_family = AF_INET;
589 if ((error = getaddrinfo(host, port, &hints, &res)))
590 errx(1, "getaddrinfo: %s", gai_strerror(error));
594 if ((s = socket(res0->ai_family, res0->ai_socktype,
595 res0->ai_protocol)) < 0)
598 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
602 if (ipsec_policy[0] != NULL)
603 add_ipsec_policy(s, ipsec_policy[0]);
604 if (ipsec_policy[1] != NULL)
605 add_ipsec_policy(s, ipsec_policy[1]);
608 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
609 &Oflag, sizeof(Oflag)) == -1)
610 err(1, "disable TCP options");
613 if (bind(s, (struct sockaddr *)res0->ai_addr,
614 res0->ai_addrlen) == 0)
619 } while ((res0 = res0->ai_next) != NULL);
621 if (!uflag && s != -1) {
622 if (listen(s, 1) < 0)
633 * Loop that polls on the network file descriptor and stdin.
638 struct pollfd pfd[2];
639 unsigned char buf[8192];
640 int n, wfd = fileno(stdin);
641 int lfd = fileno(stdout);
644 plen = jflag ? 8192 : 1024;
646 /* Setup Network FD */
648 pfd[0].events = POLLIN;
650 /* Set up STDIN FD. */
652 pfd[1].events = POLLIN;
654 while (pfd[0].fd != -1) {
658 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
660 err(1, "Polling Error");
666 if (pfd[0].revents & POLLIN) {
667 if ((n = read(nfd, buf, plen)) < 0)
670 shutdown(nfd, SHUT_RD);
675 atelnet(nfd, buf, n);
676 if (atomicio(vwrite, lfd, buf, n) != n)
681 if (!dflag && pfd[1].revents & POLLIN) {
682 if ((n = read(wfd, buf, plen)) < 0 ||
686 shutdown(nfd, SHUT_WR);
690 if (atomicio(vwrite, nfd, buf, n) != n)
697 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
699 atelnet(int nfd, unsigned char *buf, unsigned int size)
701 unsigned char *p, *end;
702 unsigned char obuf[4];
707 for (p = buf; p < end; p++) {
713 if ((*p == WILL) || (*p == WONT))
715 if ((*p == DO) || (*p == DONT))
721 if (atomicio(vwrite, nfd, obuf, 3) != 3)
722 warn("Write Error!");
730 * Build an array or ports in portlist[], listing each port
731 * that we should try to connect to.
741 if ((n = strchr(p, '-')) != NULL) {
743 errx(1, "Cannot use -l with multiple ports!");
748 /* Make sure the ports are in order: lowest->highest. */
749 hi = strtonum(n, 1, PORT_MAX, &errstr);
751 errx(1, "port number %s: %s", errstr, n);
752 lo = strtonum(p, 1, PORT_MAX, &errstr);
754 errx(1, "port number %s: %s", errstr, p);
762 /* Load ports sequentially. */
763 for (cp = lo; cp <= hi; cp++) {
764 portlist[x] = calloc(1, PORT_MAX_LEN);
765 if (portlist[x] == NULL)
767 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
771 /* Randomly swap ports. */
776 for (x = 0; x <= (hi - lo); x++) {
777 y = (arc4random() & 0xFFFF) % (hi - lo);
779 portlist[x] = portlist[y];
784 hi = strtonum(p, 1, PORT_MAX, &errstr);
786 errx(1, "port number %s: %s", errstr, p);
787 portlist[0] = calloc(1, PORT_MAX_LEN);
788 if (portlist[0] == NULL)
796 * Do a few writes to see if the UDP port is there.
797 * XXX - Better way of doing this? Doesn't work for IPv6.
798 * Also fails after around 100 ports checked.
805 for (i = 0; i <= 3; i++) {
806 if (write(s, "X", 1) == 1)
815 set_common_sockopts(int s)
820 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
821 &x, sizeof(x)) == -1)
825 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
826 &x, sizeof(x)) == -1)
831 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
832 &x, sizeof(x)) == -1)
837 if (setsockopt(s, IPPROTO_IP, IP_TOS,
838 &Tflag, sizeof(Tflag)) == -1)
839 err(1, "set IP ToS");
842 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
843 &Oflag, sizeof(Oflag)) == -1)
844 err(1, "disable TCP options");
853 if (strcmp(s, "lowdelay") == 0)
854 return (IPTOS_LOWDELAY);
855 if (strcmp(s, "throughput") == 0)
856 return (IPTOS_THROUGHPUT);
857 if (strcmp(s, "reliability") == 0)
858 return (IPTOS_RELIABILITY);
860 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
861 errx(1, "invalid IP Type of Service");
869 fprintf(stderr, "\tCommand Summary:\n\
872 \t-D Enable the debug socket option\n\
873 \t-d Detach from stdin\n");
876 \t-E Use IPsec ESP\n\
877 \t-e policy Use specified IPsec policy\n");
880 \t-h This help text\n\
881 \t-i secs\t Delay interval for lines sent, ports scanned\n\
882 \t-k Keep inbound sockets open for multiple connects\n\
883 \t-l Listen mode, for inbound connects\n\
884 \t-n Suppress name/port resolutions\n\
885 \t-O Disable TCP options\n\
886 \t-o Terminate on EOF on input\n\
887 \t-P proxyuser\tUsername for proxy authentication\n\
888 \t-p port\t Specify local port for remote connects\n\
889 \t-r Randomize remote ports\n\
890 \t-S Enable the TCP MD5 signature option\n\
891 \t-s addr\t Local source address\n\
892 \t-T ToS\t Set IP Type of Service\n\
893 \t-t Answer TELNET negotiation\n\
894 \t-U Use UNIX domain socket\n\
897 \t-w secs\t Timeout for connects and final net reads\n\
898 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
899 \t-x addr[:port]\tSpecify proxy address and port\n\
900 \t-z Zero-I/O mode [used for scanning]\n\
901 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
903 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
910 add_ipsec_policy(int s, char *policy)
915 raw = ipsec_set_policy(policy, strlen(policy));
917 errx(1, "ipsec_set_policy `%s': %s", policy,
919 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
920 ipsec_get_policylen(raw));
922 err(1, "ipsec policy cannot be configured");
925 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
934 fprintf(stderr, "usage: nc [-46DdEhklnOorStUuvz] [-e policy] [-i interval] [-P proxy_username] [-p source_port]\n");
936 fprintf(stderr, "usage: nc [-46DdhklnOorStUuvz] [-i interval] [-P proxy_username] [-p source_port]\n");
938 fprintf(stderr, "\t [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_protocol]\n");
939 fprintf(stderr, "\t [-x proxy_address[:port]] [hostname] [port[s]]\n");