1 /* $OpenBSD: netcat.c,v 1.82 2005/07/24 09:33:56 marius 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.
30 * Re-written nc(1) for OpenBSD. Original implementation by
31 * *Hobbit* <hobbit@avian.org>.
34 #include <sys/types.h>
35 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <netinet/tcp.h>
41 #include <arpa/telnet.h>
47 #endif /* __DragonFly__ */
60 (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
63 #define PORT_MAX 65535
64 #define PORT_MAX_LEN 6
66 /* Command Line Options */
67 int dflag
; /* detached, no stdin */
68 int iflag
; /* Interval Flag */
70 int jflag
; /* use jumbo frames if we can */
71 #endif /* !__DragonFly__ */
72 int kflag
; /* More than one connect */
73 int lflag
; /* Bind to local port */
74 int nflag
; /* Don't do name look up */
75 char *pflag
; /* Localport flag */
76 int rflag
; /* Random ports flag */
77 char *sflag
; /* Source Address */
78 int tflag
; /* Telnet Emulation */
79 int uflag
; /* UDP - Default to TCP */
80 int vflag
; /* Verbosity */
81 int xflag
; /* Socks proxy */
82 int zflag
; /* Port Scan Flag */
83 int Dflag
; /* sodebug */
85 int Sflag
; /* TCP MD5 signature option */
86 #endif /* !__DragonFly__ */
89 int family
= AF_UNSPEC
;
90 char *portlist
[PORT_MAX
+1];
92 void atelnet(int, unsigned char *, unsigned int);
93 void build_ports(char *);
95 int local_listen(char *, char *, struct addrinfo
);
97 int remote_connect(const char *, const char *, struct addrinfo
);
98 int socks_connect(const char *, const char *, struct addrinfo
, const char *, const char *,
99 struct addrinfo
, int);
101 int unix_connect(char *);
102 int unix_listen(char *);
103 int set_common_sockopts(int);
107 main(int argc
, char *argv
[])
109 int ch
, s
, ret
, socksv
;
110 char *host
, *uport
, *endp
;
111 struct addrinfo hints
;
114 struct sockaddr_storage cliaddr
;
116 const char *proxyhost
= "", *proxyport
= NULL
;
117 struct addrinfo proxyhints
;
127 while ((ch
= getopt(argc
, argv
,
128 "46Ddhi:jklnp:rSs:tUuvw:X:x:z")) != -1) {
140 if (strcasecmp(optarg
, "connect") == 0)
141 socksv
= -1; /* HTTP proxy CONNECT */
142 else if (strcmp(optarg
, "4") == 0)
143 socksv
= 4; /* SOCKS v.4 */
144 else if (strcmp(optarg
, "5") == 0)
145 socksv
= 5; /* SOCKS v.5 */
147 errx(1, "unsupported proxy protocol");
156 iflag
= (int)strtoul(optarg
, &endp
, 10);
157 if (iflag
< 0 || *endp
!= '\0')
158 errx(1, "interval cannot be negative");
160 #ifndef __DragonFly__
164 #endif /* !__DragonFly__ */
193 timeout
= (int)strtoul(optarg
, &endp
, 10);
194 if (timeout
< 0 || *endp
!= '\0')
195 errx(1, "timeout cannot be negative");
196 if (timeout
>= (INT_MAX
/ 1000))
197 errx(1, "timeout too large");
204 if ((proxy
= strdup(optarg
)) == NULL
)
213 #ifndef __DragonFly__
217 #endif /* !__DragonFly__ */
225 /* Cruft to make sure options are clean, and used properly. */
226 if (argv
[0] && !argv
[1] && family
== AF_UNIX
) {
228 errx(1, "cannot use -u and -U");
231 } else if (argv
[0] && !argv
[1]) {
236 } else if (argv
[0] && argv
[1]) {
243 errx(1, "cannot use -s and -l");
245 errx(1, "cannot use -p and -l");
247 errx(1, "cannot use -z and -l");
249 errx(1, "must use -l with -k");
251 /* Initialize addrinfo structure. */
252 if (family
!= AF_UNIX
) {
253 memset(&hints
, 0, sizeof(struct addrinfo
));
254 hints
.ai_family
= family
;
255 hints
.ai_socktype
= uflag
? SOCK_DGRAM
: SOCK_STREAM
;
256 hints
.ai_protocol
= uflag
? IPPROTO_UDP
: IPPROTO_TCP
;
258 hints
.ai_flags
|= AI_NUMERICHOST
;
263 errx(1, "no proxy support for UDP mode");
266 errx(1, "no proxy support for listen");
268 if (family
== AF_UNIX
)
269 errx(1, "no proxy support for unix sockets");
271 /* XXX IPv6 transport to proxy would probably work */
272 if (family
== AF_INET6
)
273 errx(1, "no proxy support for IPv6");
276 errx(1, "no proxy support for local source address");
278 proxyhost
= strsep(&proxy
, ":");
281 memset(&proxyhints
, 0, sizeof(struct addrinfo
));
282 proxyhints
.ai_family
= family
;
283 proxyhints
.ai_socktype
= SOCK_STREAM
;
284 proxyhints
.ai_protocol
= IPPROTO_TCP
;
286 proxyhints
.ai_flags
|= AI_NUMERICHOST
;
293 if (family
== AF_UNIX
)
294 s
= unix_listen(host
);
296 /* Allow only one connection at a time, but stay alive. */
298 if (family
!= AF_UNIX
)
299 s
= local_listen(host
, uport
, hints
);
303 * For UDP, we will use recvfrom() initially
304 * to wait for a caller, then use the regular
305 * functions to talk to the caller.
310 struct sockaddr_storage z
;
313 #ifndef __DragonFly__
314 plen
= jflag
? 8192 : 1024;
315 #else /* __DragonFly__ */
317 #endif /* !__DragonFly__ */
318 rv
= recvfrom(s
, buf
, plen
, MSG_PEEK
,
319 (struct sockaddr
*)&z
, &len
);
323 rv
= connect(s
, (struct sockaddr
*)&z
, len
);
329 len
= sizeof(cliaddr
);
330 connfd
= accept(s
, (struct sockaddr
*)&cliaddr
,
336 if (family
!= AF_UNIX
)
342 } else if (family
== AF_UNIX
) {
345 if ((s
= unix_connect(host
)) > 0 && !zflag
) {
356 /* Construct the portlist[] array. */
359 /* Cycle through portlist, connecting to each port. */
360 for (i
= 0; portlist
[i
] != NULL
; i
++) {
365 s
= socks_connect(host
, portlist
[i
], hints
,
366 proxyhost
, proxyport
, proxyhints
, socksv
);
368 s
= remote_connect(host
, portlist
[i
], hints
);
374 if (vflag
|| zflag
) {
375 /* For UDP, make sure we are connected. */
377 if (udptest(s
) == -1) {
383 /* Don't look up port if -n. */
388 ntohs(atoi(portlist
[i
])),
389 uflag
? "udp" : "tcp");
392 printf("Connection to %s %s port [%s/%s] succeeded!\n",
393 host
, portlist
[i
], uflag
? "udp" : "tcp",
394 sv
? sv
->s_name
: "*");
409 * Returns a socket connected to a local unix socket. Returns -1 on failure.
412 unix_connect(char *path
)
414 struct sockaddr_un sun
;
417 if ((s
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
419 (void)fcntl(s
, F_SETFD
, 1);
421 memset(&sun
, 0, sizeof(struct sockaddr_un
));
422 sun
.sun_family
= AF_UNIX
;
424 if (strlcpy(sun
.sun_path
, path
, sizeof(sun
.sun_path
)) >=
425 sizeof(sun
.sun_path
)) {
427 errno
= ENAMETOOLONG
;
430 if (connect(s
, (struct sockaddr
*)&sun
, SUN_LEN(&sun
)) < 0) {
440 * Create a unix domain socket, and listen on it.
443 unix_listen(char *path
)
445 struct sockaddr_un sun
;
448 /* Create unix domain socket. */
449 if ((s
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
452 memset(&sun
, 0, sizeof(struct sockaddr_un
));
453 sun
.sun_family
= AF_UNIX
;
455 if (strlcpy(sun
.sun_path
, path
, sizeof(sun
.sun_path
)) >=
456 sizeof(sun
.sun_path
)) {
458 errno
= ENAMETOOLONG
;
462 if (bind(s
, (struct sockaddr
*)&sun
, SUN_LEN(&sun
)) < 0) {
467 if (listen(s
, 5) < 0) {
476 * Returns a socket connected to a remote host. Properly binds to a local
477 * port or source address if needed. Returns -1 on failure.
480 remote_connect(const char *host
, const char *port
, struct addrinfo hints
)
482 struct addrinfo
*res
, *res0
;
485 if ((error
= getaddrinfo(host
, port
, &hints
, &res
)))
486 errx(1, "getaddrinfo: %s", gai_strerror(error
));
490 if ((s
= socket(res0
->ai_family
, res0
->ai_socktype
,
491 res0
->ai_protocol
)) < 0)
494 /* Bind to a local port or source address if specified. */
495 if (sflag
|| pflag
) {
496 struct addrinfo ahints
, *ares
;
498 if (!(sflag
&& pflag
)) {
505 memset(&ahints
, 0, sizeof(struct addrinfo
));
506 ahints
.ai_family
= res0
->ai_family
;
507 ahints
.ai_socktype
= uflag
? SOCK_DGRAM
: SOCK_STREAM
;
508 ahints
.ai_protocol
= uflag
? IPPROTO_UDP
: IPPROTO_TCP
;
509 ahints
.ai_flags
= AI_PASSIVE
;
510 if ((error
= getaddrinfo(sflag
, pflag
, &ahints
, &ares
)))
511 errx(1, "getaddrinfo: %s", gai_strerror(error
));
513 if (bind(s
, (struct sockaddr
*)ares
->ai_addr
,
514 ares
->ai_addrlen
) < 0)
515 errx(1, "bind failed: %s", strerror(errno
));
519 set_common_sockopts(s
);
521 if (connect(s
, res0
->ai_addr
, res0
->ai_addrlen
) == 0)
524 warn("connect to %s port %s (%s) failed", host
, port
,
525 uflag
? "udp" : "tcp");
529 } while ((res0
= res0
->ai_next
) != NULL
);
538 * Returns a socket listening on a local port, binds to specified source
539 * address. Returns -1 on failure.
542 local_listen(char *host
, char *port
, struct addrinfo hints
)
544 struct addrinfo
*res
, *res0
;
548 /* Allow nodename to be null. */
549 hints
.ai_flags
|= AI_PASSIVE
;
552 * In the case of binding to a wildcard address
553 * default to binding to an ipv4 address.
555 if (host
== NULL
&& hints
.ai_family
== AF_UNSPEC
)
556 hints
.ai_family
= AF_INET
;
558 if ((error
= getaddrinfo(host
, port
, &hints
, &res
)))
559 errx(1, "getaddrinfo: %s", gai_strerror(error
));
563 if ((s
= socket(res0
->ai_family
, res0
->ai_socktype
,
564 res0
->ai_protocol
)) < 0)
567 ret
= setsockopt(s
, SOL_SOCKET
, SO_REUSEPORT
, &x
, sizeof(x
));
571 set_common_sockopts(s
);
573 if (bind(s
, (struct sockaddr
*)res0
->ai_addr
,
574 res0
->ai_addrlen
) == 0)
579 } while ((res0
= res0
->ai_next
) != NULL
);
581 if (!uflag
&& s
!= -1) {
582 if (listen(s
, 1) < 0)
593 * Loop that polls on the network file descriptor and stdin.
601 int nfd_open
= 1, wfd_open
= 1;
603 struct pollfd pfd
[2];
605 unsigned char buf
[8192];
606 int n
, wfd
= fileno(stdin
);
607 int lfd
= fileno(stdout
);
610 #ifndef __DragonFly__
611 plen
= jflag
? 8192 : 1024;
612 #else /* __DragonFly__ */
614 #endif /* !__DragonFly__ */
617 /* Setup Network FD */
619 pfd
[0].events
= POLLIN
;
621 /* Set up STDIN FD. */
623 pfd
[1].events
= POLLIN
;
629 while (pfd
[0].fd
!= -1) {
637 FD_SET(nfd
, &readfds
);
639 FD_SET(wfd
, &readfds
);
644 if ((n
= select(nfd
+ 1, &readfds
, NULL
, NULL
, (timeout
== -1) ? NULL
: &tv
)) < 0) {
646 if ((n
= poll(pfd
, 2 - dflag
, timeout
)) < 0) {
649 err(1, "Polling Error");
656 if (FD_ISSET(nfd
, &readfds
)) {
658 if (pfd
[0].revents
& POLLIN
) {
660 if ((n
= read(nfd
, buf
, plen
)) < 0)
663 shutdown(nfd
, SHUT_RD
);
672 atelnet(nfd
, buf
, n
);
673 if (atomicio(vwrite
, lfd
, buf
, n
) != n
)
679 if (!dflag
&& FD_ISSET(wfd
, &readfds
)) {
681 if (!dflag
&& pfd
[1].revents
& POLLIN
) {
683 if ((n
= read(wfd
, buf
, plen
)) < 0)
686 shutdown(nfd
, SHUT_WR
);
694 if (atomicio(vwrite
, nfd
, buf
, n
) != n
)
701 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
703 atelnet(int nfd
, unsigned char *buf
, unsigned int size
)
705 unsigned char *p
, *end
;
706 unsigned char obuf
[4];
711 for (p
= buf
; p
< end
; p
++) {
717 if ((*p
== WILL
) || (*p
== WONT
))
719 if ((*p
== DO
) || (*p
== DONT
))
725 if (atomicio(vwrite
, nfd
, obuf
, 3) != 3)
726 warn("Write Error!");
734 * Build an array or ports in portlist[], listing each port
735 * that we should try to connect to.
744 if ((n
= strchr(p
, '-')) != NULL
) {
746 errx(1, "Cannot use -l with multiple ports!");
751 /* Make sure the ports are in order: lowest->highest. */
752 hi
= (int)strtoul(n
, &endp
, 10);
753 if (hi
<= 0 || hi
> PORT_MAX
|| *endp
!= '\0')
754 errx(1, "port range not valid");
755 lo
= (int)strtoul(p
, &endp
, 10);
756 if (lo
<= 0 || lo
> PORT_MAX
|| *endp
!= '\0')
757 errx(1, "port range not valid");
765 /* Load ports sequentially. */
766 for (cp
= lo
; cp
<= hi
; cp
++) {
767 portlist
[x
] = calloc(1, PORT_MAX_LEN
);
768 if (portlist
[x
] == NULL
)
770 snprintf(portlist
[x
], PORT_MAX_LEN
, "%d", cp
);
774 /* Randomly swap ports. */
779 for (x
= 0; x
<= (hi
- lo
); x
++) {
780 y
= (arc4random() & 0xFFFF) % (hi
- lo
);
782 portlist
[x
] = portlist
[y
];
787 hi
= (int)strtoul(p
, &endp
, 10);
788 if (hi
<= 0 || hi
> PORT_MAX
|| *endp
!= '\0')
789 errx(1, "port range not valid");
790 portlist
[0] = calloc(1, PORT_MAX_LEN
);
791 if (portlist
[0] == NULL
)
799 * Do a few writes to see if the UDP port is there.
800 * XXX - Better way of doing this? Doesn't work for IPv6.
801 * Also fails after around 100 ports checked.
808 for (i
= 0; i
<= 3; i
++) {
809 if (write(s
, "X", 1) == 1)
818 set_common_sockopts(int s
)
822 #ifndef __DragonFly__
824 if (setsockopt(s
, IPPROTO_TCP
, TCP_MD5SIG
,
825 &x
, sizeof(x
)) == -1)
828 #endif /* !__DragonFly__ */
830 if (setsockopt(s
, SOL_SOCKET
, SO_DEBUG
,
831 &x
, sizeof(x
)) == -1)
834 #ifndef __DragonFly__
836 if (setsockopt(s
, SOL_SOCKET
, SO_JUMBO
,
837 &x
, sizeof(x
)) == -1)
840 #endif /* !__DragonFly__ */
847 fprintf(stderr
, "\tCommand Summary:\n\
850 \t-D Enable the debug socket option\n\
851 \t-d Detach from stdin\n\
852 \t-h This help text\n\
853 \t-i secs\t Delay interval for lines sent, ports scanned\n\
854 \t-k Keep inbound sockets open for multiple connects\n\
855 \t-l Listen mode, for inbound connects\n\
856 \t-n Suppress name/port resolutions\n\
857 \t-p port\t Specify local port for remote connects\n\
858 \t-r Randomize remote ports\n\
860 \t-s addr\t Local source address\n\
861 \t-t Answer TELNET negotiation\n\
862 \t-U Use UNIX domain socket\n\
865 \t-w secs\t Timeout for connects and final net reads\n\
866 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
867 \t-x addr[:port]\tSpecify proxy address and port\n\
868 \t-z Zero-I/O mode [used for scanning]\n\
869 Port numbers can be individual or ranges: lo-hi [inclusive]\n",
870 #ifndef __DragonFly__
871 " \t-S Enable the TCP MD5 signature option\n"
872 #else /* __DragonFly__ */
874 #endif /* !__DragonFly__ */
882 #ifndef __DragonFly__
883 fprintf(stderr
, "usage: nc [-46DdhklnrStUuvz] [-i interval] [-p source_port]\n");
884 #else /* __DragonFly__ */
885 fprintf(stderr
, "usage: nc [-46DdhklnrtUuvz] [-i interval] [-p source_port]\n");
886 #endif /* !__DragonFly__ */
887 fprintf(stderr
, "\t [-s source_ip_address] [-w timeout] [-X proxy_version]\n");
888 fprintf(stderr
, "\t [-x proxy_address[:port]] [hostname] [port[s]]\n");