1 /* $OpenBSD: netcat.c,v 1.91 2008/05/09 09:00:11 markus 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>
67 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
70 #define PORT_MAX 65535
71 #define PORT_MAX_LEN 6
73 /* Command Line Options */
74 int Eflag; /* Use IPsec ESP */
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 oflag; /* Once only: stop on EOF */
82 int FreeBSD_Oflag; /* Do not use TCP options */
83 char *Pflag; /* Proxy username */
84 char *pflag; /* Localport flag */
85 int rflag; /* Random ports flag */
86 char *sflag; /* Source Address */
87 int tflag; /* Telnet Emulation */
88 int uflag; /* UDP - Default to TCP */
89 int vflag; /* Verbosity */
90 int xflag; /* Socks proxy */
91 int zflag; /* Port Scan Flag */
92 int Dflag; /* sodebug */
93 int Iflag; /* TCP receive buffer size */
94 int Oflag; /* TCP send buffer size */
95 int Sflag; /* TCP MD5 signature option */
96 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 struct addrinfo hints;
131 struct sockaddr_storage cliaddr;
133 const char *errstr, *proxyhost = "", *proxyport = NULL;
134 struct addrinfo proxyhints;
135 struct option longopts[] = {
136 { "no-tcpopt", no_argument, &FreeBSD_Oflag, 1 },
148 while ((ch = getopt_long(argc, argv,
149 "46e:DEdhi:jklnoI:O:P:p:rSs:tT:Uuvw:X:x:z",
150 longopts, NULL)) != -1) {
162 if (strcasecmp(optarg, "connect") == 0)
163 socksv = -1; /* HTTP proxy CONNECT */
164 else if (strcmp(optarg, "4") == 0)
165 socksv = 4; /* SOCKS v.4 */
166 else if (strcmp(optarg, "5") == 0)
167 socksv = 5; /* SOCKS v.5 */
169 errx(1, "unsupported proxy protocol");
176 ipsec_policy[ipsec_count++ % 2] = optarg;
178 errx(1, "IPsec support unavailable.");
183 ipsec_policy[0] = "in ipsec esp/transport//require";
184 ipsec_policy[1] = "out ipsec esp/transport//require";
186 errx(1, "IPsec support unavailable.");
193 iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
195 errx(1, "interval %s: %s", errstr, optarg);
236 timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
238 errx(1, "timeout %s: %s", errstr, optarg);
243 if ((proxy = strdup(optarg)) == NULL)
253 Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
255 errx(1, "TCP receive window %s: %s",
259 Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
260 if (errstr != NULL) {
261 if (strcmp(errstr, "invalid") != 0)
262 errx(1, "TCP send window %s: %s",
270 Tflag = parse_iptos(optarg);
281 /* Cruft to make sure options are clean, and used properly. */
282 if (argv[0] && !argv[1] && family == AF_UNIX) {
284 errx(1, "cannot use -u and -U");
287 } else if (argv[0] && !argv[1]) {
292 } else if (argv[0] && argv[1]) {
299 errx(1, "cannot use -s and -l");
301 errx(1, "cannot use -p and -l");
303 errx(1, "cannot use -z and -l");
305 errx(1, "must use -l with -k");
307 /* Initialize addrinfo structure. */
308 if (family != AF_UNIX) {
309 memset(&hints, 0, sizeof(struct addrinfo));
310 hints.ai_family = family;
311 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
312 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
314 hints.ai_flags |= AI_NUMERICHOST;
319 errx(1, "no proxy support for UDP mode");
322 errx(1, "no proxy support for listen");
324 if (family == AF_UNIX)
325 errx(1, "no proxy support for unix sockets");
327 /* XXX IPv6 transport to proxy would probably work */
328 if (family == AF_INET6)
329 errx(1, "no proxy support for IPv6");
332 errx(1, "no proxy support for local source address");
334 proxyhost = strsep(&proxy, ":");
337 memset(&proxyhints, 0, sizeof(struct addrinfo));
338 proxyhints.ai_family = family;
339 proxyhints.ai_socktype = SOCK_STREAM;
340 proxyhints.ai_protocol = IPPROTO_TCP;
342 proxyhints.ai_flags |= AI_NUMERICHOST;
349 if (family == AF_UNIX)
350 s = unix_listen(host);
352 /* Allow only one connection at a time, but stay alive. */
354 if (family != AF_UNIX)
355 s = local_listen(host, uport, hints);
359 * For UDP, we will use recvfrom() initially
360 * to wait for a caller, then use the regular
361 * functions to talk to the caller.
366 struct sockaddr_storage z;
369 plen = jflag ? 8192 : 1024;
370 rv = recvfrom(s, buf, plen, MSG_PEEK,
371 (struct sockaddr *)&z, &len);
375 rv = connect(s, (struct sockaddr *)&z, len);
381 len = sizeof(cliaddr);
382 connfd = accept(s, (struct sockaddr *)&cliaddr,
388 if (family != AF_UNIX)
394 } else if (family == AF_UNIX) {
397 if ((s = unix_connect(host)) > 0 && !zflag) {
408 /* Construct the portlist[] array. */
411 /* Cycle through portlist, connecting to each port. */
412 for (i = 0; portlist[i] != NULL; i++) {
417 s = socks_connect(host, portlist[i], hints,
418 proxyhost, proxyport, proxyhints, socksv,
421 s = remote_connect(host, portlist[i], hints);
427 if (vflag || zflag) {
428 /* For UDP, make sure we are connected. */
430 if (udptest(s) == -1) {
436 /* Don't look up port if -n. */
441 ntohs(atoi(portlist[i])),
442 uflag ? "udp" : "tcp");
445 printf("Connection to %s %s port [%s/%s] succeeded!\n",
446 host, portlist[i], uflag ? "udp" : "tcp",
447 sv ? sv->s_name : "*");
462 * Returns a socket connected to a local unix socket. Returns -1 on failure.
465 unix_connect(char *path)
467 struct sockaddr_un sun;
470 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
472 (void)fcntl(s, F_SETFD, 1);
474 memset(&sun, 0, sizeof(struct sockaddr_un));
475 sun.sun_family = AF_UNIX;
477 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
478 sizeof(sun.sun_path)) {
480 errno = ENAMETOOLONG;
483 if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
493 * Create a unix domain socket, and listen on it.
496 unix_listen(char *path)
498 struct sockaddr_un sun;
501 /* Create unix domain socket. */
502 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
505 memset(&sun, 0, sizeof(struct sockaddr_un));
506 sun.sun_family = AF_UNIX;
508 if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
509 sizeof(sun.sun_path)) {
511 errno = ENAMETOOLONG;
515 if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
520 if (listen(s, 5) < 0) {
529 * Returns a socket connected to a remote host. Properly binds to a local
530 * port or source address if needed. Returns -1 on failure.
533 remote_connect(const char *host, const char *port, struct addrinfo hints)
535 struct addrinfo *res, *res0;
536 int s, error, on = 1;
538 if ((error = getaddrinfo(host, port, &hints, &res)))
539 errx(1, "getaddrinfo: %s", gai_strerror(error));
543 if ((s = socket(res0->ai_family, res0->ai_socktype,
544 res0->ai_protocol)) < 0)
547 if (ipsec_policy[0] != NULL)
548 add_ipsec_policy(s, ipsec_policy[0]);
549 if (ipsec_policy[1] != NULL)
550 add_ipsec_policy(s, ipsec_policy[1]);
553 /* Bind to a local port or source address if specified. */
554 if (sflag || pflag) {
555 struct addrinfo ahints, *ares;
558 /* try SO_BINDANY, but don't insist */
559 setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
561 memset(&ahints, 0, sizeof(struct addrinfo));
562 ahints.ai_family = res0->ai_family;
563 ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
564 ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
565 ahints.ai_flags = AI_PASSIVE;
566 if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
567 errx(1, "getaddrinfo: %s", gai_strerror(error));
569 if (bind(s, (struct sockaddr *)ares->ai_addr,
570 ares->ai_addrlen) < 0)
571 errx(1, "bind failed: %s", strerror(errno));
575 set_common_sockopts(s);
577 if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
580 warn("connect to %s port %s (%s) failed", host, port,
581 uflag ? "udp" : "tcp");
585 } while ((res0 = res0->ai_next) != NULL);
594 * Returns a socket listening on a local port, binds to specified source
595 * address. Returns -1 on failure.
598 local_listen(char *host, char *port, struct addrinfo hints)
600 struct addrinfo *res, *res0;
604 /* Allow nodename to be null. */
605 hints.ai_flags |= AI_PASSIVE;
608 * In the case of binding to a wildcard address
609 * default to binding to an ipv4 address.
611 if (host == NULL && hints.ai_family == AF_UNSPEC)
612 hints.ai_family = AF_INET;
614 if ((error = getaddrinfo(host, port, &hints, &res)))
615 errx(1, "getaddrinfo: %s", gai_strerror(error));
619 if ((s = socket(res0->ai_family, res0->ai_socktype,
620 res0->ai_protocol)) < 0)
623 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
627 if (ipsec_policy[0] != NULL)
628 add_ipsec_policy(s, ipsec_policy[0]);
629 if (ipsec_policy[1] != NULL)
630 add_ipsec_policy(s, ipsec_policy[1]);
633 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
634 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
635 err(1, "disable TCP options");
638 if (bind(s, (struct sockaddr *)res0->ai_addr,
639 res0->ai_addrlen) == 0)
644 } while ((res0 = res0->ai_next) != NULL);
646 if (!uflag && s != -1) {
647 if (listen(s, 1) < 0)
658 * Loop that polls on the network file descriptor and stdin.
663 struct pollfd pfd[2];
664 unsigned char buf[8192];
665 int n, wfd = fileno(stdin);
666 int lfd = fileno(stdout);
669 plen = jflag ? 8192 : 1024;
671 /* Setup Network FD */
673 pfd[0].events = POLLIN;
675 /* Set up STDIN FD. */
677 pfd[1].events = POLLIN;
679 while (pfd[0].fd != -1) {
683 if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
685 err(1, "Polling Error");
691 if (pfd[0].revents & POLLIN) {
692 if ((n = read(nfd, buf, plen)) < 0)
695 shutdown(nfd, SHUT_RD);
700 atelnet(nfd, buf, n);
701 if (atomicio(vwrite, lfd, buf, n) != n)
706 if (!dflag && pfd[1].revents & POLLIN) {
707 if ((n = read(wfd, buf, plen)) < 0 ||
711 shutdown(nfd, SHUT_WR);
715 if (atomicio(vwrite, nfd, buf, n) != n)
722 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
724 atelnet(int nfd, unsigned char *buf, unsigned int size)
726 unsigned char *p, *end;
727 unsigned char obuf[4];
732 for (p = buf; p < end; p++) {
738 if ((*p == WILL) || (*p == WONT))
740 if ((*p == DO) || (*p == DONT))
746 if (atomicio(vwrite, nfd, obuf, 3) != 3)
747 warn("Write Error!");
755 * Build an array or ports in portlist[], listing each port
756 * that we should try to connect to.
766 if ((n = strchr(p, '-')) != NULL) {
768 errx(1, "Cannot use -l with multiple ports!");
773 /* Make sure the ports are in order: lowest->highest. */
774 hi = strtonum(n, 1, PORT_MAX, &errstr);
776 errx(1, "port number %s: %s", errstr, n);
777 lo = strtonum(p, 1, PORT_MAX, &errstr);
779 errx(1, "port number %s: %s", errstr, p);
787 /* Load ports sequentially. */
788 for (cp = lo; cp <= hi; cp++) {
789 portlist[x] = calloc(1, PORT_MAX_LEN);
790 if (portlist[x] == NULL)
792 snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
796 /* Randomly swap ports. */
801 for (x = 0; x <= (hi - lo); x++) {
802 y = (arc4random() & 0xFFFF) % (hi - lo);
804 portlist[x] = portlist[y];
809 hi = strtonum(p, 1, PORT_MAX, &errstr);
811 errx(1, "port number %s: %s", errstr, p);
812 portlist[0] = calloc(1, PORT_MAX_LEN);
813 if (portlist[0] == NULL)
821 * Do a few writes to see if the UDP port is there.
822 * XXX - Better way of doing this? Doesn't work for IPv6.
823 * Also fails after around 100 ports checked.
830 for (i = 0; i <= 3; i++) {
831 if (write(s, "X", 1) == 1)
840 set_common_sockopts(int s)
845 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
846 &x, sizeof(x)) == -1)
850 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
851 &x, sizeof(x)) == -1)
856 if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
857 &x, sizeof(x)) == -1)
862 if (setsockopt(s, IPPROTO_IP, IP_TOS,
863 &Tflag, sizeof(Tflag)) == -1)
864 err(1, "set IP ToS");
867 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
868 &Iflag, sizeof(Iflag)) == -1)
869 err(1, "set TCP receive buffer size");
872 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
873 &Oflag, sizeof(Oflag)) == -1)
874 err(1, "set TCP send buffer size");
877 if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
878 &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
879 err(1, "disable TCP options");
888 if (strcmp(s, "lowdelay") == 0)
889 return (IPTOS_LOWDELAY);
890 if (strcmp(s, "throughput") == 0)
891 return (IPTOS_THROUGHPUT);
892 if (strcmp(s, "reliability") == 0)
893 return (IPTOS_RELIABILITY);
895 if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
896 errx(1, "invalid IP Type of Service");
904 fprintf(stderr, "\tCommand Summary:\n\
907 \t-D Enable the debug socket option\n\
908 \t-d Detach from stdin\n");
911 \t-E Use IPsec ESP\n\
912 \t-e policy Use specified IPsec policy\n");
915 \t-h This help text\n\
916 \t-I length TCP receive buffer length\n\
917 \t-i secs\t Delay interval for lines sent, ports scanned\n\
918 \t-k Keep inbound sockets open for multiple connects\n\
919 \t-l Listen mode, for inbound connects\n\
920 \t-n Suppress name/port resolutions\n\
921 \t--no-tcpopt Disable TCP options\n\
922 \t-O length TCP send buffer length\n\
923 \t-o Terminate on EOF on input\n\
924 \t-P proxyuser\tUsername for proxy authentication\n\
925 \t-p port\t Specify local port for remote connects\n\
926 \t-r Randomize remote ports\n\
927 \t-S Enable the TCP MD5 signature option\n\
928 \t-s addr\t Local source address\n\
929 \t-T ToS\t Set IP Type of Service\n\
930 \t-t Answer TELNET negotiation\n\
931 \t-U Use UNIX domain socket\n\
934 \t-w secs\t Timeout for connects and final net reads\n\
935 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
936 \t-x addr[:port]\tSpecify proxy address and port\n\
937 \t-z Zero-I/O mode [used for scanning]\n\
938 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
940 fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
947 add_ipsec_policy(int s, char *policy)
952 raw = ipsec_set_policy(policy, strlen(policy));
954 errx(1, "ipsec_set_policy `%s': %s", policy,
956 e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
957 ipsec_get_policylen(raw));
959 err(1, "ipsec policy cannot be configured");
962 fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
971 fprintf(stderr, "usage: nc [-46DdEhklnorStUuvz] [-e policy] [-I receive_buffer_len] [-i interval]\n");
973 fprintf(stderr, "usage: nc [-46DdhklnorStUuvz] [-I receive_buffer_len] [-i interval]\n");
975 fprintf(stderr, "\t [-O send_buffer_len] [-P proxy_username] [-p source_port]\n");
976 fprintf(stderr, "\t [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_protocol]\n");
977 fprintf(stderr, "\t [-x proxy_address[:port]] [hostname] [port[s]]\n");