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 char *Pflag; /* Proxy username */
82 char *pflag; /* Localport flag */
83 int rflag; /* Random ports flag */
84 char *sflag; /* Source Address */
85 int tflag; /* Telnet Emulation */
86 int uflag; /* UDP - Default to TCP */
87 int vflag; /* Verbosity */
88 int xflag; /* Socks proxy */
89 int zflag; /* Port Scan Flag */
90 int Dflag; /* sodebug */
91 int Sflag; /* TCP MD5 signature option */
92 int Tflag = -1; /* IP Type of Service */
95 int family = AF_UNSPEC;
96 char *portlist[PORT_MAX+1];
98 void atelnet(int, unsigned char *, unsigned int);
99 void build_ports(char *);
101 int local_listen(char *, char *, struct addrinfo);
103 int remote_connect(const char *, const char *, struct addrinfo);
104 int socks_connect(const char *, const char *, struct addrinfo,
105 const char *, const char *, struct addrinfo, int, const char *);
107 int unix_connect(char *);
108 int unix_listen(char *);
109 void set_common_sockopts(int);
110 int parse_iptos(char *);
114 void add_ipsec_policy(int, char *);
116 char *ipsec_policy[2];
120 main(int argc, char *argv[])
122 int ch, s, ret, socksv, ipsec_count;
124 struct addrinfo hints;
127 struct sockaddr_storage cliaddr;
129 const char *errstr, *proxyhost = "", *proxyport = NULL;
130 struct addrinfo proxyhints;
140 while ((ch = getopt(argc, argv,
141 "46e:DEdhi:jklnoP:p:rSs:tT:Uuvw:X:x:z")) != -1) {
153 if (strcasecmp(optarg, "connect") == 0)
154 socksv = -1; /* HTTP proxy CONNECT */
155 else if (strcmp(optarg, "4") == 0)
156 socksv = 4; /* SOCKS v.4 */
157 else if (strcmp(optarg, "5") == 0)
158 socksv = 5; /* SOCKS v.5 */
160 errx(1, "unsupported proxy protocol");
167 ipsec_policy[ipsec_count++ % 2] = optarg;
169 errx(1, "IPsec support unavailable.");
174 ipsec_policy[0] = "in ipsec esp/transport//require";
175 ipsec_policy[1] = "out ipsec esp/transport//require";
177 errx(1, "IPsec support unavailable.");
184 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
186 errx(1, "interval %s: %s", errstr, optarg);
227 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
229 errx(1, "timeout %s: %s", errstr, optarg);
234 if ((proxy = strdup(optarg)) == NULL)
247 Tflag = parse_iptos(optarg);
256 /* Cruft to make sure options are clean, and used properly. */
257 if (argv[0] && !argv[1] && family == AF_UNIX) {
259 errx(1, "cannot use -u and -U");
262 } else if (argv[0] && !argv[1]) {
267 } else if (argv[0] && argv[1]) {
274 errx(1, "cannot use -s and -l");
276 errx(1, "cannot use -p and -l");
278 errx(1, "cannot use -z and -l");
280 errx(1, "must use -l with -k");
282 /* Initialize addrinfo structure. */
283 if (family != AF_UNIX) {
284 memset(&hints, 0, sizeof(struct addrinfo));
285 hints.ai_family = family;
286 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
287 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
289 hints.ai_flags |= AI_NUMERICHOST;
294 errx(1, "no proxy support for UDP mode");
297 errx(1, "no proxy support for listen");
299 if (family == AF_UNIX)
300 errx(1, "no proxy support for unix sockets");
302 /* XXX IPv6 transport to proxy would probably work */
303 if (family == AF_INET6)
304 errx(1, "no proxy support for IPv6");
307 errx(1, "no proxy support for local source address");
309 proxyhost = strsep(&proxy, ":");
312 memset(&proxyhints, 0, sizeof(struct addrinfo));
313 proxyhints.ai_family = family;
314 proxyhints.ai_socktype = SOCK_STREAM;
315 proxyhints.ai_protocol = IPPROTO_TCP;
317 proxyhints.ai_flags |= AI_NUMERICHOST;
324 if (family == AF_UNIX)
325 s = unix_listen(host);
327 /* Allow only one connection at a time, but stay alive. */
329 if (family != AF_UNIX)
330 s = local_listen(host, uport, hints);
334 * For UDP, we will use recvfrom() initially
335 * to wait for a caller, then use the regular
336 * functions to talk to the caller.
341 struct sockaddr_storage z;
344 plen = jflag ? 8192 : 1024;
345 rv = recvfrom(s, buf, plen, MSG_PEEK,
346 (struct sockaddr *)&z, &len);
350 rv = connect(s, (struct sockaddr *)&z, len);
356 len = sizeof(cliaddr);
357 connfd = accept(s, (struct sockaddr *)&cliaddr,
363 if (family != AF_UNIX)
369 } else if (family == AF_UNIX) {
372 if ((s = unix_connect(host)) > 0 && !zflag) {
383 /* Construct the portlist[] array. */
386 /* Cycle through portlist, connecting to each port. */
387 for (i = 0; portlist[i] != NULL; i++) {
392 s = socks_connect(host, portlist[i], hints,
393 proxyhost, proxyport, proxyhints, socksv,
396 s = remote_connect(host, portlist[i], hints);
402 if (vflag || zflag) {
403 /* For UDP, make sure we are connected. */
405 if (udptest(s) == -1) {
411 /* Don't look up port if -n. */
416 ntohs(atoi(portlist[i])),
417 uflag ? "udp" : "tcp");
420 printf("Connection to %s %s port [%s/%s] succeeded!\n",
421 host, portlist[i], uflag ? "udp" : "tcp",
422 sv ? sv->s_name : "*");
437 * Returns a socket connected to a local unix socket. Returns -1 on failure.
440 unix_connect(char *path)
442 struct sockaddr_un sun;
445 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
447 (void)fcntl(s, F_SETFD, 1);
449 memset(&sun, 0, sizeof(struct sockaddr_un));
450 sun.sun_family = AF_UNIX;
452 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
453 sizeof(sun.sun_path)) {
455 errno = ENAMETOOLONG;
458 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
468 * Create a unix domain socket, and listen on it.
471 unix_listen(char *path)
473 struct sockaddr_un sun;
476 /* Create unix domain socket. */
477 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
480 memset(&sun, 0, sizeof(struct sockaddr_un));
481 sun.sun_family = AF_UNIX;
483 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
484 sizeof(sun.sun_path)) {
486 errno = ENAMETOOLONG;
490 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
495 if (listen(s, 5) < 0) {
504 * Returns a socket connected to a remote host. Properly binds to a local
505 * port or source address if needed. Returns -1 on failure.
508 remote_connect(const char *host, const char *port, struct addrinfo hints)
510 struct addrinfo *res, *res0;
513 if ((error = getaddrinfo(host, port, &hints, &res)))
514 errx(1, "getaddrinfo: %s", gai_strerror(error));
518 if ((s = socket(res0->ai_family, res0->ai_socktype,
519 res0->ai_protocol)) < 0)
522 if (ipsec_policy[0] != NULL)
523 add_ipsec_policy(s, ipsec_policy[0]);
524 if (ipsec_policy[1] != NULL)
525 add_ipsec_policy(s, ipsec_policy[1]);
528 /* Bind to a local port or source address if specified. */
529 if (sflag || pflag) {
530 struct addrinfo ahints, *ares;
532 memset(&ahints, 0, sizeof(struct addrinfo));
533 ahints.ai_family = res0->ai_family;
534 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
535 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
536 ahints.ai_flags = AI_PASSIVE;
537 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
538 errx(1, "getaddrinfo: %s", gai_strerror(error));
540 if (bind(s, (struct sockaddr *)ares->ai_addr,
541 ares->ai_addrlen) < 0)
542 errx(1, "bind failed: %s", strerror(errno));
546 set_common_sockopts(s);
548 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
551 warn("connect to %s port %s (%s) failed", host, port,
552 uflag ? "udp" : "tcp");
556 } while ((res0 = res0->ai_next) != NULL);
565 * Returns a socket listening on a local port, binds to specified source
566 * address. Returns -1 on failure.
569 local_listen(char *host, char *port, struct addrinfo hints)
571 struct addrinfo *res, *res0;
575 /* Allow nodename to be null. */
576 hints.ai_flags |= AI_PASSIVE;
579 * In the case of binding to a wildcard address
580 * default to binding to an ipv4 address.
582 if (host == NULL && hints.ai_family == AF_UNSPEC)
583 hints.ai_family = AF_INET;
585 if ((error = getaddrinfo(host, port, &hints, &res)))
586 errx(1, "getaddrinfo: %s", gai_strerror(error));
590 if ((s = socket(res0->ai_family, res0->ai_socktype,
591 res0->ai_protocol)) < 0)
594 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
598 if (ipsec_policy[0] != NULL)
599 add_ipsec_policy(s, ipsec_policy[0]);
600 if (ipsec_policy[1] != NULL)
601 add_ipsec_policy(s, ipsec_policy[1]);
604 if (bind(s, (struct sockaddr *)res0->ai_addr,
605 res0->ai_addrlen) == 0)
610 } while ((res0 = res0->ai_next) != NULL);
612 if (!uflag && s != -1) {
613 if (listen(s, 1) < 0)
624 * Loop that polls on the network file descriptor and stdin.
629 struct pollfd pfd[2];
630 unsigned char buf[8192];
631 int n, wfd = fileno(stdin);
632 int lfd = fileno(stdout);
635 plen = jflag ? 8192 : 1024;
637 /* Setup Network FD */
639 pfd[0].events = POLLIN;
641 /* Set up STDIN FD. */
643 pfd[1].events = POLLIN;
645 while (pfd[0].fd != -1) {
649 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
651 err(1, "Polling Error");
657 if (pfd[0].revents & POLLIN) {
658 if ((n = read(nfd, buf, plen)) < 0)
661 shutdown(nfd, SHUT_RD);
666 atelnet(nfd, buf, n);
667 if (atomicio(vwrite, lfd, buf, n) != n)
672 if (!dflag && pfd[1].revents & POLLIN) {
673 if ((n = read(wfd, buf, plen)) < 0 ||
677 shutdown(nfd, SHUT_WR);
681 if (atomicio(vwrite, nfd, buf, n) != n)
688 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
690 atelnet(int nfd, unsigned char *buf, unsigned int size)
692 unsigned char *p, *end;
693 unsigned char obuf[4];
698 for (p = buf; p < end; p++) {
704 if ((*p == WILL) || (*p == WONT))
706 if ((*p == DO) || (*p == DONT))
712 if (atomicio(vwrite, nfd, obuf, 3) != 3)
713 warn("Write Error!");
721 * Build an array or ports in portlist[], listing each port
722 * that we should try to connect to.
732 if ((n = strchr(p, '-')) != NULL) {
734 errx(1, "Cannot use -l with multiple ports!");
739 /* Make sure the ports are in order: lowest->highest. */
740 hi = strtonum(n, 1, PORT_MAX, &errstr);
742 errx(1, "port number %s: %s", errstr, n);
743 lo = strtonum(p, 1, PORT_MAX, &errstr);
745 errx(1, "port number %s: %s", errstr, p);
753 /* Load ports sequentially. */
754 for (cp = lo; cp <= hi; cp++) {
755 portlist[x] = calloc(1, PORT_MAX_LEN);
756 if (portlist[x] == NULL)
758 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
762 /* Randomly swap ports. */
767 for (x = 0; x <= (hi - lo); x++) {
768 y = (arc4random() & 0xFFFF) % (hi - lo);
770 portlist[x] = portlist[y];
775 hi = strtonum(p, 1, PORT_MAX, &errstr);
777 errx(1, "port number %s: %s", errstr, p);
778 portlist[0] = calloc(1, PORT_MAX_LEN);
779 if (portlist[0] == NULL)
787 * Do a few writes to see if the UDP port is there.
788 * XXX - Better way of doing this? Doesn't work for IPv6.
789 * Also fails after around 100 ports checked.
796 for (i = 0; i <= 3; i++) {
797 if (write(s, "X", 1) == 1)
806 set_common_sockopts(int s)
811 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
812 &x, sizeof(x)) == -1)
816 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
817 &x, sizeof(x)) == -1)
822 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
823 &x, sizeof(x)) == -1)
828 if (setsockopt(s, IPPROTO_IP, IP_TOS,
829 &Tflag, sizeof(Tflag)) == -1)
830 err(1, "set IP ToS");
839 if (strcmp(s, "lowdelay") == 0)
840 return (IPTOS_LOWDELAY);
841 if (strcmp(s, "throughput") == 0)
842 return (IPTOS_THROUGHPUT);
843 if (strcmp(s, "reliability") == 0)
844 return (IPTOS_RELIABILITY);
846 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
847 errx(1, "invalid IP Type of Service");
855 fprintf(stderr, "\tCommand Summary:\n\
860 \t-e policy Use specified IPsec policy\n\
861 \t-E Use IPsec ESP\n");
864 \t-D Enable the debug socket option\n\
865 \t-d Detach from stdin\n\
866 \t-h This help text\n\
867 \t-i secs\t Delay interval for lines sent, ports scanned\n\
868 \t-k Keep inbound sockets open for multiple connects\n\
869 \t-l Listen mode, for inbound connects\n\
870 \t-n Suppress name/port resolutions\n\
871 \t-P proxyuser\tUsername for proxy authentication\n\
872 \t-p port\t Specify local port for remote connects\n\
873 \t-r Randomize remote ports\n\
874 \t-S Enable the TCP MD5 signature option\n\
875 \t-s addr\t Local source address\n\
876 \t-T ToS\t Set IP Type of Service\n\
877 \t-t Answer TELNET negotiation\n\
878 \t-U Use UNIX domain socket\n\
881 \t-w secs\t Timeout for connects and final net reads\n\
882 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
883 \t-x addr[:port]\tSpecify proxy address and port\n\
884 \t-z Zero-I/O mode [used for scanning]\n\
885 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
887 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
894 add_ipsec_policy(int s, char *policy)
899 raw = ipsec_set_policy(policy, strlen(policy));
901 errx(1, "ipsec_set_policy `%s': %s", policy,
903 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
904 ipsec_get_policylen(raw));
906 err(1, "ipsec policy cannot be configured");
909 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
918 fprintf(stderr, "usage: nc [-46DEdhklnrStUuvz] [-e policy] [-i interval] [-P proxy_username] [-p source_port]\n");
920 fprintf(stderr, "usage: nc [-46DdhklnrStUuvz] [-i interval] [-P proxy_username] [-p source_port]\n");
922 fprintf(stderr, "\t [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_protocol]\n");
923 fprintf(stderr, "\t [-x proxy_address[:port]] [hostname] [port[s]]\n");