1 /* $OpenBSD: netcat.c,v 1.217 2020/02/12 14:46:36 schwarze Exp $ */
3 * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4 * Copyright (c) 2015 Bob Beck. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * Re-written nc(1) for OpenBSD. Original implementation by
32 * *Hobbit* <hobbit@avian.org>.
37 #include <sys/types.h>
38 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <netinet/ip.h>
45 #include <arpa/telnet.h>
47 # include <linux/in6.h>
49 #if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
50 # include <bsd/readpassphrase.h>
53 #ifndef IPTOS_LOWDELAY
54 # define IPTOS_LOWDELAY 0x10
55 # define IPTOS_THROUGHPUT 0x08
56 # define IPTOS_RELIABILITY 0x04
57 # define IPTOS_LOWCOST 0x02
58 # define IPTOS_MINCOST IPTOS_LOWCOST
59 #endif /* IPTOS_LOWDELAY */
61 # ifndef IPTOS_DSCP_AF11
62 # define IPTOS_DSCP_AF11 0x28
63 # define IPTOS_DSCP_AF12 0x30
64 # define IPTOS_DSCP_AF13 0x38
65 # define IPTOS_DSCP_AF21 0x48
66 # define IPTOS_DSCP_AF22 0x50
67 # define IPTOS_DSCP_AF23 0x58
68 # define IPTOS_DSCP_AF31 0x68
69 # define IPTOS_DSCP_AF32 0x70
70 # define IPTOS_DSCP_AF33 0x78
71 # define IPTOS_DSCP_AF41 0x88
72 # define IPTOS_DSCP_AF42 0x90
73 # define IPTOS_DSCP_AF43 0x98
74 # define IPTOS_DSCP_EF 0xb8
75 #endif /* IPTOS_DSCP_AF11 */
77 #ifndef IPTOS_DSCP_CS0
78 # define IPTOS_DSCP_CS0 0x00
79 # define IPTOS_DSCP_CS1 0x20
80 # define IPTOS_DSCP_CS2 0x40
81 # define IPTOS_DSCP_CS3 0x60
82 # define IPTOS_DSCP_CS4 0x80
83 # define IPTOS_DSCP_CS5 0xa0
84 # define IPTOS_DSCP_CS6 0xc0
85 # define IPTOS_DSCP_CS7 0xe0
86 #endif /* IPTOS_DSCP_CS0 */
89 # define IPTOS_DSCP_EF 0xb8
90 #endif /* IPTOS_DSCP_EF */
111 #include <bsd/stdlib.h>
112 #include <bsd/string.h>
114 #include "atomicio.h"
116 #define PORT_MAX 65535
117 #define UNIX_DG_TMP_SOCKET_SIZE 19
120 #define POLL_NETOUT 1
122 #define POLL_STDOUT 3
123 #define BUFSIZE 16384
126 # define TLS_NOVERIFY (1 << 1)
127 # define TLS_NONAME (1 << 2)
128 # define TLS_CCERT (1 << 3)
129 # define TLS_MUSTSTAPLE (1 << 4)
132 #define CONNECTION_SUCCESS 0
133 #define CONNECTION_FAILED 1
134 #define CONNECTION_TIMEOUT 2
136 #define UDP_SCAN_TIMEOUT 3 /* Seconds */
138 /* Command Line Options */
139 int bflag
; /* Allow Broadcast */
140 int dflag
; /* detached, no stdin */
141 int Fflag
; /* fdpass sock to stdout */
142 unsigned int iflag
; /* Interval Flag */
143 int kflag
; /* More than one connect */
144 int lflag
; /* Bind to local port */
145 int Nflag
; /* shutdown() network socket */
146 int nflag
; /* Don't do name look up */
147 char *Pflag
; /* Proxy username */
148 char *pflag
; /* Localport flag */
149 int qflag
= -1; /* Quit after some secs */
150 int rflag
; /* Random ports flag */
151 char *sflag
; /* Source Address */
152 int tflag
; /* Telnet Emulation */
153 int uflag
; /* UDP - Default to TCP */
154 int dccpflag
; /* DCCP - Default to TCP */
155 int vflag
; /* Verbosity */
156 int xflag
; /* Socks proxy */
157 int zflag
; /* Port Scan Flag */
158 int Dflag
; /* sodebug */
159 int Iflag
; /* TCP receive buffer size */
160 int Oflag
; /* TCP send buffer size */
161 int Sflag
; /* TCP MD5 signature option */
162 int Tflag
= -1; /* IP Type of Service */
166 int usetls
; /* use TLS */
167 const char *Cflag
; /* Public cert file */
168 const char *Kflag
; /* Private key file */
169 const char *oflag
; /* OCSP stapling file */
170 const char *Rflag
; /* Root CA file */
171 int tls_cachanged
; /* Using non-default CA file */
172 int TLSopt
; /* TLS options */
173 char *tls_expectname
; /* required name in peer cert */
174 char *tls_expecthash
; /* required hash of peer cert */
175 char *tls_ciphers
; /* TLS ciphers */
176 char *tls_protocols
; /* TLS protocols */
177 FILE *Zflag
; /* file to save peer cert */
179 int Cflag
= 0; /* CRLF line-ending */
182 # if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
183 char Sflag_password
[TCP_MD5SIG_MAXKEYLEN
];
185 int recvcount
, recvlimit
;
187 int family
= AF_UNSPEC
;
188 char *portlist
[PORT_MAX
+1];
189 char *unix_dg_tmp_socket
;
193 void atelnet(int, unsigned char *, unsigned int);
194 int strtoport(char *portstr
, int udp
);
195 void build_ports(char **);
196 void help(void) __attribute__((noreturn
));
197 int local_listen(const char *, const char *, struct addrinfo
);
199 void readwrite(int, struct tls
*);
203 void fdpass(int nfd
) __attribute__((noreturn
));
204 int remote_connect(const char *, const char *, struct addrinfo
, char *);
206 int timeout_tls(int, struct tls
*, int (*)(struct tls
*));
208 int timeout_connect(int, const struct sockaddr
*, socklen_t
);
209 int socks_connect(const char *, const char *, struct addrinfo
,
210 const char *, const char *, struct addrinfo
, int, const char *);
212 int unix_bind(char *, int);
213 int unix_connect(char *);
214 int unix_listen(char *);
215 void set_common_sockopts(int, const struct sockaddr
*);
216 int process_tos_opt(char *, int *);
218 int process_tls_opt(char *, int *);
219 void save_peer_cert(struct tls
*_tls_ctx
, FILE *_fp
);
221 void report_sock(const char *, const struct sockaddr
*, socklen_t
, char *);
223 void report_tls(struct tls
*tls_ctx
, char * host
);
227 ssize_t
drainbuf(int, unsigned char *, size_t *, struct tls
*);
228 ssize_t
fillbuf(int, unsigned char *, size_t *, struct tls
*);
229 void tls_setup_client(struct tls
*, int, char *);
230 struct tls
*tls_setup_server(struct tls
*, int, char *);
232 ssize_t
drainbuf(int, unsigned char *, size_t *, int);
233 ssize_t
fillbuf(int, unsigned char *, size_t *);
236 char *proto_name(int uflag
, int dccpflag
);
237 static int connect_with_timeout(int fd
, const struct sockaddr
*sa
,
238 socklen_t salen
, int ctimeout
);
243 main(int argc
, char *argv
[])
245 int ch
, s
= -1, ret
, socksv
;
247 char ipaddr
[NI_MAXHOST
];
248 struct addrinfo hints
;
252 struct sockaddr_storage storage
;
253 struct sockaddr_un forunix
;
255 char *proxy
= NULL
, *proxyport
= NULL
;
257 struct addrinfo proxyhints
;
258 char unix_dg_tmp_socket_buf
[UNIX_DG_TMP_SOCKET_SIZE
];
260 struct tls_config
*tls_cfg
= NULL
;
261 struct tls
*tls_ctx
= NULL
;
271 Rflag
= tls_default_ca_cert_file();
274 signal(SIGPIPE
, SIG_IGN
);
276 while ((ch
= getopt(argc
, argv
,
278 "46bC:cDde:FH:hI:i:K:klM:m:NnO:o:P:p:q:R:rSs:T:tUuV:vW:w:X:x:Z:z"))
280 "46bCDdFhI:i:klM:m:NnO:P:p:q:rSs:T:tUuV:vW:w:X:x:Zz"))
291 # if defined(SO_BROADCAST)
294 errx(1, "no broadcast frame support available");
301 if (strcasecmp(optarg
, "connect") == 0)
302 socksv
= -1; /* HTTP proxy CONNECT */
303 else if (strcmp(optarg
, "4") == 0)
304 socksv
= 4; /* SOCKS v.4 */
305 else if (strcmp(optarg
, "5") == 0)
306 socksv
= 5; /* SOCKS v.5 */
308 errx(1, "unsupported proxy protocol");
327 tls_expectname
= optarg
;
335 tls_expecthash
= optarg
;
342 iflag
= strtonum(optarg
, 0, UINT_MAX
, &errstr
);
344 errx(1, "interval %s: %s", errstr
, optarg
);
358 ttl
= strtonum(optarg
, 0, 255, &errstr
);
360 errx(1, "ttl is %s", errstr
);
363 minttl
= strtonum(optarg
, 0, 255, &errstr
);
365 errx(1, "minttl is %s", errstr
);
380 qflag
= strtonum(optarg
, INT_MIN
, INT_MAX
, &errstr
);
382 errx(1, "quit timer %s: %s", errstr
, optarg
);
405 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
408 errx(1, "no DCCP support available");
412 # if defined(RT_TABLEID_MAX)
413 rtableid
= (int)strtonum(optarg
, 0,
414 RT_TABLEID_MAX
, &errstr
);
416 errx(1, "rtable %s: %s", errstr
, optarg
);
418 errx(1, "no alternate routing table support available");
425 recvlimit
= strtonum(optarg
, 1, INT_MAX
, &errstr
);
427 errx(1, "receive limit %s: %s", errstr
, optarg
);
430 timeout
= strtonum(optarg
, 0, INT_MAX
/ 1000, &errstr
);
432 errx(1, "timeout %s: %s", errstr
, optarg
);
437 if ((proxy
= strdup(optarg
)) == NULL
)
442 if (strcmp(optarg
, "-") == 0)
444 else if ((Zflag
= fopen(optarg
, "w")) == NULL
)
445 err(1, "can't open %s", optarg
);
455 Iflag
= strtonum(optarg
, 1, 65536 << 14, &errstr
);
457 errx(1, "TCP receive window %s: %s",
461 Oflag
= strtonum(optarg
, 1, 65536 << 14, &errstr
);
463 errx(1, "TCP send window %s: %s",
472 # if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
473 if (readpassphrase("TCP MD5SIG password: ",
474 Sflag_password
, TCP_MD5SIG_MAXKEYLEN
, RPP_REQUIRE_TTY
) == NULL
)
475 errx(1, "Unable to read TCP MD5SIG password");
478 errx(1, "no TCP MD5 signature support available");
485 if (process_tls_opt(optarg
, &TLSopt
))
488 if (process_tos_opt(optarg
, &Tflag
))
490 if (strlen(optarg
) > 1 && optarg
[0] == '0' &&
492 Tflag
= (int)strtol(optarg
, NULL
, 16);
494 Tflag
= (int)strtonum(optarg
, 0, 255,
496 if (Tflag
< 0 || Tflag
> 255 || errstr
|| errno
)
498 errx(1, "illegal tos/tls value %s", optarg
);
500 errx(1, "illegal tos value %s", optarg
);
510 # if defined(RT_TABLEID_MAX)
512 if (setrtable(rtableid
) == -1)
516 /* Cruft to make sure options are clean, and used properly. */
517 if (argc
== 0 && lflag
) {
520 } else if (argc
== 1 && !pflag
&&
521 /* `nc -l 12345` or `nc -U bar` or `nc -uU -s foo bar` */
522 (!sflag
|| (family
== AF_UNIX
&& uflag
&& !lflag
))) {
523 if (family
== AF_UNIX
) {
530 } else if (argc
>= 2) {
531 if (lflag
&& (pflag
|| sflag
|| argc
> 2))
532 usage(1); /* conflict */
538 if (family
== AF_UNIX
) {
539 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
541 errx(1, "cannot use -Z and -U");
544 errx(1, "cannot use port with -U");
546 errx(1, "missing socket pathname");
547 } else if (!uport
|| !*uport
)
548 errx(1, "missing port number");
551 errx(1, "cannot use -z and -l");
555 if (Cflag
&& unveil(Cflag
, "r") == -1)
557 if (unveil(Rflag
, "r") == -1)
559 if (Kflag
&& unveil(Kflag
, "r") == -1)
561 if (oflag
&& unveil(oflag
, "r") == -1)
563 } else if (family
== AF_UNIX
&& uflag
&& lflag
&& !kflag
) {
565 * After recvfrom(2) from client, the server connects
566 * to the client socket. As the client path is determined
567 * during runtime, we cannot unveil(2).
570 if (family
== AF_UNIX
) {
571 if (unveil(host
, "rwc") == -1)
573 if (uflag
&& !kflag
) {
575 if (unveil(sflag
, "rwc") == -1)
578 if (unveil("/tmp", "rwc") == -1)
583 /* no filesystem visibility */
584 if (unveil("/", "") == -1)
591 errx(1, "must use -l with -k");
594 errx(1, "cannot use -c and -u");
595 if ((family
== AF_UNIX
) && usetls
)
596 errx(1, "cannot use -c and -U");
598 if ((family
== AF_UNIX
) && Fflag
)
599 errx(1, "cannot use -F and -U");
602 errx(1, "cannot use -c and -F");
603 if (TLSopt
&& !usetls
)
604 errx(1, "you must specify -c to use TLS options");
605 if (Cflag
&& !usetls
)
606 errx(1, "you must specify -c to use -C");
607 if (Kflag
&& !usetls
)
608 errx(1, "you must specify -c to use -K");
609 if (Zflag
&& !usetls
)
610 errx(1, "you must specify -c to use -Z");
612 errx(1, "you must specify -C to use -o");
613 if (tls_cachanged
&& !usetls
)
614 errx(1, "you must specify -c to use -R");
615 if (tls_expecthash
&& !usetls
)
616 errx(1, "you must specify -c to use -H");
617 if (tls_expectname
&& !usetls
)
618 errx(1, "you must specify -c to use -e");
621 /* Get name of temporary socket for unix datagram client */
622 if ((family
== AF_UNIX
) && uflag
&& !lflag
) {
624 unix_dg_tmp_socket
= sflag
;
626 strlcpy(unix_dg_tmp_socket_buf
, "/tmp/nc.XXXXXXXXXX",
627 UNIX_DG_TMP_SOCKET_SIZE
);
628 if (mkstemp(unix_dg_tmp_socket_buf
) == -1)
630 unix_dg_tmp_socket
= unix_dg_tmp_socket_buf
;
634 /* Initialize addrinfo structure. */
635 if (family
!= AF_UNIX
) {
636 memset(&hints
, 0, sizeof(struct addrinfo
));
637 hints
.ai_family
= family
;
639 hints
.ai_socktype
= SOCK_DGRAM
;
640 hints
.ai_protocol
= IPPROTO_UDP
;
642 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
644 hints
.ai_socktype
= SOCK_DCCP
;
645 hints
.ai_protocol
= IPPROTO_DCCP
;
649 hints
.ai_socktype
= SOCK_STREAM
;
650 hints
.ai_protocol
= IPPROTO_TCP
;
653 hints
.ai_flags
|= AI_NUMERICHOST
;
658 errx(1, "no proxy support for UDP mode");
659 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
661 errx(1, "no proxy support for DCCP mode");
664 errx(1, "no proxy support for listen");
666 if (family
== AF_UNIX
)
667 errx(1, "no proxy support for unix sockets");
670 errx(1, "no proxy support for local source address");
674 proxyport
= strchr(proxy
, ']');
675 if (proxyport
== NULL
)
676 errx(1, "missing closing bracket in proxy");
678 if (*proxyport
== '\0')
679 /* Use default proxy port. */
682 if (*proxyport
== ':')
685 errx(1, "garbage proxy port delimiter");
688 proxyport
= strrchr(proxy
, ':');
689 if (proxyport
!= NULL
)
693 memset(&proxyhints
, 0, sizeof(struct addrinfo
));
694 proxyhints
.ai_family
= family
;
695 proxyhints
.ai_socktype
= SOCK_STREAM
;
696 proxyhints
.ai_protocol
= IPPROTO_TCP
;
698 proxyhints
.ai_flags
|= AI_NUMERICHOST
;
703 if ((tls_cfg
= tls_config_new()) == NULL
)
704 errx(1, "unable to allocate TLS config");
705 if (Rflag
&& tls_config_set_ca_file(tls_cfg
, Rflag
) == -1)
706 errx(1, "%s", tls_config_error(tls_cfg
));
707 if (Cflag
&& tls_config_set_cert_file(tls_cfg
, Cflag
) == -1)
708 errx(1, "%s", tls_config_error(tls_cfg
));
709 if (Kflag
&& tls_config_set_key_file(tls_cfg
, Kflag
) == -1)
710 errx(1, "%s", tls_config_error(tls_cfg
));
711 if (oflag
&& tls_config_set_ocsp_staple_file(tls_cfg
, oflag
) == -1)
712 errx(1, "%s", tls_config_error(tls_cfg
));
713 if (tls_config_parse_protocols(&protocols
, tls_protocols
) == -1)
714 errx(1, "invalid TLS protocols `%s'", tls_protocols
);
715 if (tls_config_set_protocols(tls_cfg
, protocols
) == -1)
716 errx(1, "%s", tls_config_error(tls_cfg
));
717 if (tls_config_set_ciphers(tls_cfg
, tls_ciphers
) == -1)
718 errx(1, "%s", tls_config_error(tls_cfg
));
719 if (!lflag
&& (TLSopt
& TLS_CCERT
))
720 errx(1, "clientcert is only valid with -l");
721 if (TLSopt
& TLS_NONAME
)
722 tls_config_insecure_noverifyname(tls_cfg
);
723 if (TLSopt
& TLS_NOVERIFY
) {
724 if (tls_expecthash
!= NULL
)
725 errx(1, "-H and -T noverify may not be used "
727 tls_config_insecure_noverifycert(tls_cfg
);
729 if (TLSopt
& TLS_MUSTSTAPLE
)
730 tls_config_ocsp_require_stapling(tls_cfg
);
733 if (pledge("stdio inet dns tty", NULL
) == -1)
735 } else if (pledge("stdio inet dns", NULL
) == -1)
742 if (family
== AF_UNIX
) {
744 s
= unix_bind(host
, 0);
746 s
= unix_listen(host
);
748 s
= local_listen(host
, *uport
, hints
);
754 tls_config_verify_client_optional(tls_cfg
);
755 if ((tls_ctx
= tls_server()) == NULL
)
756 errx(1, "tls server creation failed");
757 if (tls_configure(tls_ctx
, tls_cfg
) == -1)
758 errx(1, "tls configuration failed (%s)",
762 /* Allow only one connection at a time, but stay alive. */
764 if (uflag
&& kflag
) {
766 * For UDP and -k, don't connect the socket,
767 * let it receive datagrams from multiple
775 } else if (uflag
&& !kflag
) {
777 * For UDP and not -k, we will use recvfrom()
778 * initially to wait for a caller, then use
779 * the regular functions to talk to the caller.
783 struct sockaddr_storage z
;
786 rv
= recvfrom(s
, buf
, sizeof(buf
), MSG_PEEK
,
787 (struct sockaddr
*)&z
, &len
);
791 rv
= connect(s
, (struct sockaddr
*)&z
, len
);
796 report_sock("Connection received",
797 (struct sockaddr
*)&z
, len
,
798 family
== AF_UNIX
? host
: NULL
);
803 struct tls
*tls_cctx
= NULL
;
810 len
= sizeof(cliaddr
);
811 connfd
= accept4(s
, (struct sockaddr
*)&cliaddr
,
812 &len
, SOCK_NONBLOCK
);
814 /* For now, all errnos are fatal */
818 report_sock("Connection received",
819 (struct sockaddr
*)&cliaddr
, len
,
820 family
== AF_UNIX
? host
: NULL
);
823 (tls_cctx
= tls_setup_server(tls_ctx
, connfd
, host
)))
824 readwrite(connfd
, tls_cctx
);
826 readwrite(connfd
, NULL
);
828 timeout_tls(s
, tls_cctx
, tls_close
);
836 if (family
== AF_UNIX
&& uflag
) {
837 if (connect(s
, NULL
, 0) == -1)
847 } else if (family
== AF_UNIX
) {
850 if ((s
= unix_connect(host
)) > 0) {
864 unlink(unix_dg_tmp_socket
);
870 /* Construct the portlist[] array. */
873 /* Cycle through portlist, connecting to each port. */
874 for (s
= -1, i
= 0; portlist
[i
] != NULL
; i
++) {
882 if ((tls_ctx
= tls_client()) == NULL
)
883 errx(1, "tls client creation failed");
884 if (tls_configure(tls_ctx
, tls_cfg
) == -1)
885 errx(1, "tls configuration failed (%s)",
890 s
= socks_connect(host
, portlist
[i
], hints
,
891 proxy
, proxyport
, proxyhints
, socksv
,
894 s
= remote_connect(host
, portlist
[i
], hints
,
902 /* For UDP, make sure we are connected. */
904 if (udptest(s
) == -1) {
910 char *proto
= proto_name(uflag
, dccpflag
);
911 /* Don't look up port if -n. */
916 ntohs(atoi(portlist
[i
])),
920 fprintf(stderr
, "Connection to %s", host
);
923 * if we aren't connecting thru a proxy and
924 * there is something to report, print IP
927 && (strcmp(host
, ipaddr
) != 0))
928 fprintf(stderr
, " (%s)", ipaddr
);
930 fprintf(stderr
, " %s port [%s/%s] succeeded!\n",
932 sv
? sv
->s_name
: "*");
939 tls_setup_client(tls_ctx
, s
, host
);
941 readwrite(s
, tls_ctx
);
943 timeout_tls(s
, tls_ctx
, tls_close
);
956 tls_config_free(tls_cfg
);
964 * Returns a unix socket bound to the given path
967 unix_bind(char *path
, int flags
)
969 struct sockaddr_un s_un
;
972 /* Create unix domain socket. */
973 if ((s
= socket(AF_UNIX
, flags
| (uflag
? SOCK_DGRAM
: SOCK_STREAM
),
979 memset(&s_un
, 0, sizeof(struct sockaddr_un
));
980 s_un
.sun_family
= AF_UNIX
;
982 if (strlcpy(s_un
.sun_path
, path
, sizeof(s_un
.sun_path
)) >=
983 sizeof(s_un
.sun_path
)) {
985 errno
= ENAMETOOLONG
;
989 if (bind(s
, (struct sockaddr
*)&s_un
, sizeof(s_un
)) == -1) {
996 report_sock("Bound", NULL
, 0, path
);
1003 timeout_tls(int s
, struct tls
*tls_ctx
, int (*func
)(struct tls
*))
1008 while ((ret
= (*func
)(tls_ctx
)) != 0) {
1009 if (ret
== TLS_WANT_POLLIN
)
1010 pfd
.events
= POLLIN
;
1011 else if (ret
== TLS_WANT_POLLOUT
)
1012 pfd
.events
= POLLOUT
;
1016 if ((ret
= poll(&pfd
, 1, timeout
)) == 1)
1018 else if (ret
== 0) {
1023 err(1, "poll failed");
1030 tls_setup_client(struct tls
*tls_ctx
, int s
, char *host
)
1034 if (tls_connect_socket(tls_ctx
, s
,
1035 tls_expectname
? tls_expectname
: host
) == -1) {
1036 errx(1, "tls connection failed (%s)",
1037 tls_error(tls_ctx
));
1039 if (timeout_tls(s
, tls_ctx
, tls_handshake
) == -1) {
1040 if ((errstr
= tls_error(tls_ctx
)) == NULL
)
1041 errstr
= strerror(errno
);
1042 errx(1, "tls handshake failed (%s)", errstr
);
1045 report_tls(tls_ctx
, host
);
1046 if (tls_expecthash
&& (tls_peer_cert_hash(tls_ctx
) == NULL
||
1047 strcmp(tls_expecthash
, tls_peer_cert_hash(tls_ctx
)) != 0))
1048 errx(1, "peer certificate is not %s", tls_expecthash
);
1050 save_peer_cert(tls_ctx
, Zflag
);
1051 if (Zflag
!= stderr
&& (fclose(Zflag
) != 0))
1052 err(1, "fclose failed saving peer cert");
1057 tls_setup_server(struct tls
*tls_ctx
, int connfd
, char *host
)
1059 struct tls
*tls_cctx
;
1062 if (tls_accept_socket(tls_ctx
, &tls_cctx
, connfd
) == -1) {
1063 warnx("tls accept failed (%s)", tls_error(tls_ctx
));
1064 } else if (timeout_tls(connfd
, tls_cctx
, tls_handshake
) == -1) {
1065 if ((errstr
= tls_error(tls_cctx
)) == NULL
)
1066 errstr
= strerror(errno
);
1067 warnx("tls handshake failed (%s)", errstr
);
1069 int gotcert
= tls_peer_cert_provided(tls_cctx
);
1071 if (vflag
&& gotcert
)
1072 report_tls(tls_cctx
, host
);
1073 if ((TLSopt
& TLS_CCERT
) && !gotcert
)
1074 warnx("No client certificate provided");
1075 else if (gotcert
&& tls_expecthash
&&
1076 (tls_peer_cert_hash(tls_cctx
) == NULL
||
1077 strcmp(tls_expecthash
, tls_peer_cert_hash(tls_cctx
)) != 0))
1078 warnx("peer certificate is not %s", tls_expecthash
);
1079 else if (gotcert
&& tls_expectname
&&
1080 (!tls_peer_cert_contains_name(tls_cctx
, tls_expectname
)))
1081 warnx("name (%s) not found in client cert",
1093 * Returns a socket connected to a local unix socket. Returns -1 on failure.
1096 unix_connect(char *path
)
1098 struct sockaddr_un s_un
;
1102 if ((s
= unix_bind(unix_dg_tmp_socket
, SOCK_CLOEXEC
)) == -1)
1105 if ((s
= socket(AF_UNIX
, SOCK_STREAM
| SOCK_CLOEXEC
, 0)) == -1) {
1106 errx(1, "create unix socket failed");
1111 memset(&s_un
, 0, sizeof(struct sockaddr_un
));
1112 s_un
.sun_family
= AF_UNIX
;
1114 if (strlcpy(s_un
.sun_path
, path
, sizeof(s_un
.sun_path
)) >=
1115 sizeof(s_un
.sun_path
)) {
1117 errno
= ENAMETOOLONG
;
1118 warn("unix connect abandoned");
1121 if (connect(s
, (struct sockaddr
*)&s_un
, sizeof(s_un
)) == -1) {
1123 warn("unix connect failed");
1134 * Create a unix domain socket, and listen on it.
1137 unix_listen(char *path
)
1141 if ((s
= unix_bind(path
, 0)) == -1)
1143 if (listen(s
, 5) == -1) {
1148 report_sock("Listening", NULL
, 0, path
);
1153 char *proto_name(int uflag
, int dccpflag
) {
1159 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
1160 else if (dccpflag
) {
1173 * Returns a socket connected to a remote host. Properly binds to a local
1174 * port or source address if needed. Returns -1 on failure.
1177 remote_connect(const char *host
, const char *port
, struct addrinfo hints
,
1180 struct addrinfo
*res
, *res0
;
1181 int s
= -1, error
, herr
, on
= 1, save_errno
;
1183 if ((error
= getaddrinfo(host
, port
, &hints
, &res0
)))
1184 errx(1, "getaddrinfo for host \"%s\" port %s: %s", host
,
1185 port
, gai_strerror(error
));
1187 for (res
= res0
; res
; res
= res
->ai_next
) {
1188 if ((s
= socket(res
->ai_family
, res
->ai_socktype
|
1189 SOCK_NONBLOCK
, res
->ai_protocol
)) == -1)
1192 /* Bind to a local port or source address if specified. */
1193 if (sflag
|| pflag
) {
1194 struct addrinfo ahints
, *ares
;
1196 # if defined (SO_BINDANY)
1197 /* try SO_BINDANY, but don't insist */
1198 setsockopt(s
, SOL_SOCKET
, SO_BINDANY
, &on
, sizeof(on
));
1200 memset(&ahints
, 0, sizeof(struct addrinfo
));
1201 ahints
.ai_family
= res
->ai_family
;
1203 ahints
.ai_socktype
= SOCK_DGRAM
;
1204 ahints
.ai_protocol
= IPPROTO_UDP
;
1207 # if defined(IPPROTO_DCCP) && defined(SOCK_DCCP)
1208 else if (dccpflag
) {
1209 hints
.ai_socktype
= SOCK_DCCP
;
1210 hints
.ai_protocol
= IPPROTO_DCCP
;
1214 ahints
.ai_socktype
= SOCK_STREAM
;
1215 ahints
.ai_protocol
= IPPROTO_TCP
;
1217 ahints
.ai_flags
= AI_PASSIVE
;
1218 if ((error
= getaddrinfo(sflag
, pflag
, &ahints
, &ares
)))
1219 errx(1, "getaddrinfo: %s", gai_strerror(error
));
1221 if (bind(s
, (struct sockaddr
*)ares
->ai_addr
,
1222 ares
->ai_addrlen
) == -1)
1223 err(1, "bind failed");
1227 set_common_sockopts(s
, res
->ai_addr
);
1229 if (ipaddr
!= NULL
) {
1230 herr
= getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
1231 ipaddr
, NI_MAXHOST
, NULL
, 0, NI_NUMERICHOST
);
1236 err(1, "getnameinfo");
1238 errx(1, "getnameinfo: %s", gai_strerror(herr
));
1242 if ((error
= connect_with_timeout(s
, res
->ai_addr
, res
->ai_addrlen
,
1243 timeout
)) == CONNECTION_SUCCESS
)
1246 char *proto
= proto_name(uflag
, dccpflag
);
1249 /* only print IP if there is something to report */
1250 if (nflag
|| ipaddr
== NULL
||
1251 (strncmp(host
, ipaddr
, NI_MAXHOST
) == 0))
1252 warn("connect to %s port %s (%s) %s", host
,
1254 error
== CONNECTION_TIMEOUT
? "timed out" : "failed");
1256 warn("connect to %s (%s) port %s (%s) %s",
1257 host
, ipaddr
, port
, proto
,
1258 error
== CONNECTION_TIMEOUT
? "timed out" : "failed");
1273 timeout_connect(int s
, const struct sockaddr
*name
, socklen_t namelen
)
1280 if ((ret
= connect(s
, name
, namelen
)) != 0 && errno
== EINPROGRESS
) {
1282 pfd
.events
= POLLOUT
;
1283 if ((ret
= poll(&pfd
, 1, timeout
)) == 1) {
1284 optlen
= sizeof(optval
);
1285 if ((ret
= getsockopt(s
, SOL_SOCKET
, SO_ERROR
,
1286 &optval
, &optlen
)) == 0) {
1288 ret
= optval
== 0 ? 0 : -1;
1290 } else if (ret
== 0) {
1294 err(1, "poll failed");
1300 static int connect_with_timeout(int fd
, const struct sockaddr
*sa
,
1301 socklen_t salen
, int ctimeout
)
1304 struct timeval tv
, *tvp
= NULL
;
1305 fd_set connect_fdset
;
1309 orig_flags
= fcntl(fd
, F_GETFL
, 0);
1310 if (fcntl(fd
, F_SETFL
, orig_flags
| O_NONBLOCK
) < 0 ) {
1311 warn("can't set O_NONBLOCK - timeout not available");
1312 if (connect(fd
, sa
, salen
) == 0)
1313 return CONNECTION_SUCCESS
;
1315 return CONNECTION_FAILED
;
1318 /* set connect timeout */
1320 tv
.tv_sec
= (time_t)ctimeout
/1000;
1325 /* attempt the connection */
1326 err
= connect(fd
, sa
, salen
);
1327 if (err
!= 0 && errno
== EINPROGRESS
) {
1328 /* connection is proceeding
1329 * it is complete (or failed) when select returns */
1331 /* initialize connect_fdset */
1332 FD_ZERO(&connect_fdset
);
1333 FD_SET(fd
, &connect_fdset
);
1337 err
= select(fd
+ 1, NULL
, &connect_fdset
,
1339 } while (err
< 0 && errno
== EINTR
);
1343 errx(1,"select error: %s", strerror(errno
));
1344 /* we have reached a timeout */
1346 return CONNECTION_TIMEOUT
;
1347 /* select returned successfully, but we must test socket
1348 * error for result */
1350 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
) < 0)
1351 errx(1, "getsockopt error: %s", strerror(errno
));
1352 /* setup errno according to the result returned by
1358 /* return aborted if an error occured, and valid otherwise */
1359 fcntl(fd
, F_SETFL
, orig_flags
);
1360 return (err
!= 0)? CONNECTION_FAILED
: CONNECTION_SUCCESS
;
1365 * Returns a socket listening on a local port, binds to specified source
1366 * address. Returns -1 on failure.
1369 local_listen(const char *host
, const char *port
, struct addrinfo hints
)
1371 struct addrinfo
*res
, *res0
;
1372 int s
= -1, ret
, x
= 1, save_errno
;
1375 /* Allow nodename to be null. */
1376 hints
.ai_flags
|= AI_PASSIVE
;
1379 * In the case of binding to a wildcard address
1380 * default to binding to an ipv4 address.
1382 if (host
== NULL
&& hints
.ai_family
== AF_UNSPEC
)
1383 hints
.ai_family
= AF_INET
;
1385 if ((error
= getaddrinfo(host
, port
, &hints
, &res0
)))
1386 errx(1, "getaddrinfo: %s", gai_strerror(error
));
1388 for (res
= res0
; res
; res
= res
->ai_next
) {
1389 if ((s
= socket(res
->ai_family
, res
->ai_socktype
,
1390 res
->ai_protocol
)) == -1)
1393 ret
= setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, &x
, sizeof(x
));
1397 # if defined(SO_REUSEPORT)
1398 ret
= setsockopt(s
, SOL_SOCKET
, SO_REUSEPORT
, &x
, sizeof(x
));
1403 set_common_sockopts(s
, res
->ai_addr
);
1405 if (bind(s
, (struct sockaddr
*)res
->ai_addr
,
1406 res
->ai_addrlen
) == 0)
1415 if (!uflag
&& s
!= -1) {
1416 if (listen(s
, 1) == -1)
1419 if (vflag
&& s
!= -1) {
1420 struct sockaddr_storage ss
;
1424 if (getsockname(s
, (struct sockaddr
*)&ss
, &len
) == -1)
1425 err(1, "getsockname");
1426 report_sock(uflag
? "Bound" : "Listening",
1427 (struct sockaddr
*)&ss
, len
, NULL
);
1437 * Loop that polls on the network file descriptor and stdin.
1441 readwrite(int net_fd
, struct tls
*tls_ctx
)
1443 readwrite(int net_fd
)
1446 struct pollfd pfd
[4];
1447 int stdin_fd
= STDIN_FILENO
;
1448 int stdout_fd
= STDOUT_FILENO
;
1449 unsigned char netinbuf
[BUFSIZE
];
1450 size_t netinbufpos
= 0;
1451 unsigned char stdinbuf
[BUFSIZE
];
1452 size_t stdinbufpos
= 0;
1456 /* don't read from stdin if requested */
1461 pfd
[POLL_STDIN
].fd
= stdin_fd
;
1462 pfd
[POLL_STDIN
].events
= POLLIN
;
1465 pfd
[POLL_NETOUT
].fd
= net_fd
;
1466 pfd
[POLL_NETOUT
].events
= 0;
1469 pfd
[POLL_NETIN
].fd
= net_fd
;
1470 pfd
[POLL_NETIN
].events
= POLLIN
;
1473 pfd
[POLL_STDOUT
].fd
= stdout_fd
;
1474 pfd
[POLL_STDOUT
].events
= 0;
1477 /* both inputs are gone, buffers are empty, we are done */
1478 if (pfd
[POLL_STDIN
].fd
== -1 && pfd
[POLL_NETIN
].fd
== -1 &&
1479 stdinbufpos
== 0 && netinbufpos
== 0) {
1484 /* both outputs are gone, we can't continue */
1485 if (pfd
[POLL_NETOUT
].fd
== -1 && pfd
[POLL_STDOUT
].fd
== -1) {
1490 /* listen and net in gone, queues empty, done */
1491 if (lflag
&& pfd
[POLL_NETIN
].fd
== -1 &&
1492 stdinbufpos
== 0 && netinbufpos
== 0) {
1497 signal(SIGALRM
, quit
);
1502 num_fds
= poll(pfd
, 4, timeout
);
1504 /* treat poll errors */
1506 err(1, "polling error");
1508 /* timeout happened */
1512 /* treat socket error conditions */
1513 for (n
= 0; n
< 4; n
++) {
1514 if (pfd
[n
].revents
& (POLLERR
|POLLNVAL
)) {
1518 /* reading is possible after HUP */
1519 if (pfd
[POLL_STDIN
].events
& POLLIN
&&
1520 pfd
[POLL_STDIN
].revents
& POLLHUP
&&
1521 !(pfd
[POLL_STDIN
].revents
& POLLIN
))
1522 pfd
[POLL_STDIN
].fd
= -1;
1524 if (pfd
[POLL_NETIN
].events
& POLLIN
&&
1525 pfd
[POLL_NETIN
].revents
& POLLHUP
&&
1526 !(pfd
[POLL_NETIN
].revents
& POLLIN
))
1527 pfd
[POLL_NETIN
].fd
= -1;
1529 if (pfd
[POLL_NETOUT
].revents
& POLLHUP
) {
1531 shutdown(pfd
[POLL_NETOUT
].fd
, SHUT_WR
);
1532 pfd
[POLL_NETOUT
].fd
= -1;
1534 /* if HUP, stop watching stdout */
1535 if (pfd
[POLL_STDOUT
].revents
& POLLHUP
)
1536 pfd
[POLL_STDOUT
].fd
= -1;
1537 /* if no net out, stop watching stdin */
1538 if (pfd
[POLL_NETOUT
].fd
== -1)
1539 pfd
[POLL_STDIN
].fd
= -1;
1540 /* if no stdout, stop watching net in */
1541 if (pfd
[POLL_STDOUT
].fd
== -1) {
1542 if (pfd
[POLL_NETIN
].fd
!= -1)
1543 shutdown(pfd
[POLL_NETIN
].fd
, SHUT_RD
);
1544 pfd
[POLL_NETIN
].fd
= -1;
1547 /* try to read from stdin */
1548 if (pfd
[POLL_STDIN
].revents
& POLLIN
&& stdinbufpos
< BUFSIZE
) {
1549 ret
= fillbuf(pfd
[POLL_STDIN
].fd
, stdinbuf
,
1551 &stdinbufpos
, NULL
);
1552 if (ret
== TLS_WANT_POLLIN
)
1553 pfd
[POLL_STDIN
].events
= POLLIN
;
1554 else if (ret
== TLS_WANT_POLLOUT
)
1555 pfd
[POLL_STDIN
].events
= POLLOUT
;
1560 if (ret
== 0 || ret
== -1)
1561 pfd
[POLL_STDIN
].fd
= -1;
1562 /* read something - poll net out */
1563 if (stdinbufpos
> 0)
1564 pfd
[POLL_NETOUT
].events
= POLLOUT
;
1565 /* filled buffer - remove self from polling */
1566 if (stdinbufpos
== BUFSIZE
)
1567 pfd
[POLL_STDIN
].events
= 0;
1569 /* try to write to network */
1570 if (pfd
[POLL_NETOUT
].revents
& POLLOUT
&& stdinbufpos
> 0) {
1571 ret
= drainbuf(pfd
[POLL_NETOUT
].fd
, stdinbuf
,
1573 &stdinbufpos
, tls_ctx
);
1574 if (ret
== TLS_WANT_POLLIN
)
1575 pfd
[POLL_NETOUT
].events
= POLLIN
;
1576 else if (ret
== TLS_WANT_POLLOUT
)
1577 pfd
[POLL_NETOUT
].events
= POLLOUT
;
1580 &stdinbufpos
, (iflag
|| Cflag
) ? 1 : 0);
1583 pfd
[POLL_NETOUT
].fd
= -1;
1584 /* buffer empty - remove self from polling */
1585 if (stdinbufpos
== 0)
1586 pfd
[POLL_NETOUT
].events
= 0;
1587 /* buffer no longer full - poll stdin again */
1588 if (stdinbufpos
< BUFSIZE
)
1589 pfd
[POLL_STDIN
].events
= POLLIN
;
1591 /* try to read from network */
1592 if (pfd
[POLL_NETIN
].revents
& POLLIN
&& netinbufpos
< BUFSIZE
) {
1593 ret
= fillbuf(pfd
[POLL_NETIN
].fd
, netinbuf
,
1595 &netinbufpos
, tls_ctx
);
1596 if (ret
== TLS_WANT_POLLIN
)
1597 pfd
[POLL_NETIN
].events
= POLLIN
;
1598 else if (ret
== TLS_WANT_POLLOUT
)
1599 pfd
[POLL_NETIN
].events
= POLLOUT
;
1605 pfd
[POLL_NETIN
].fd
= -1;
1606 /* eof on net in - remove from pfd */
1608 shutdown(pfd
[POLL_NETIN
].fd
, SHUT_RD
);
1609 pfd
[POLL_NETIN
].fd
= -1;
1611 if (recvlimit
> 0 && ++recvcount
>= recvlimit
) {
1612 if (pfd
[POLL_NETIN
].fd
!= -1)
1613 shutdown(pfd
[POLL_NETIN
].fd
, SHUT_RD
);
1614 pfd
[POLL_NETIN
].fd
= -1;
1615 pfd
[POLL_STDIN
].fd
= -1;
1617 /* read something - poll stdout */
1618 if (netinbufpos
> 0)
1619 pfd
[POLL_STDOUT
].events
= POLLOUT
;
1620 /* filled buffer - remove self from polling */
1621 if (netinbufpos
== BUFSIZE
)
1622 pfd
[POLL_NETIN
].events
= 0;
1625 atelnet(pfd
[POLL_NETIN
].fd
, netinbuf
,
1628 /* try to write to stdout */
1629 if (pfd
[POLL_STDOUT
].revents
& POLLOUT
&& netinbufpos
> 0) {
1630 ret
= drainbuf(pfd
[POLL_STDOUT
].fd
, netinbuf
,
1632 &netinbufpos
, NULL
);
1633 if (ret
== TLS_WANT_POLLIN
)
1634 pfd
[POLL_STDOUT
].events
= POLLIN
;
1635 else if (ret
== TLS_WANT_POLLOUT
)
1636 pfd
[POLL_STDOUT
].events
= POLLOUT
;
1642 pfd
[POLL_STDOUT
].fd
= -1;
1643 /* buffer empty - remove self from polling */
1644 if (netinbufpos
== 0)
1645 pfd
[POLL_STDOUT
].events
= 0;
1646 /* buffer no longer full - poll net in again */
1647 if (netinbufpos
< BUFSIZE
)
1648 pfd
[POLL_NETIN
].events
= POLLIN
;
1651 /* stdin gone and queue empty? */
1652 if (pfd
[POLL_STDIN
].fd
== -1 && stdinbufpos
== 0) {
1653 if (pfd
[POLL_NETOUT
].fd
!= -1 && Nflag
)
1654 shutdown(pfd
[POLL_NETOUT
].fd
, SHUT_WR
);
1655 pfd
[POLL_NETOUT
].fd
= -1;
1656 /* #817050: handle UDP sockets and kflag */
1657 if ((lflag
|| uflag
) && pfd
[POLL_NETIN
].fd
!= -1 &&
1658 qflag
>= 0 && netinbufpos
== 0) {
1659 shutdown(pfd
[POLL_NETIN
].fd
, SHUT_RD
);
1660 pfd
[POLL_NETIN
].fd
= -1;
1664 /* net in gone and queue empty? */
1665 if (pfd
[POLL_NETIN
].fd
== -1 && netinbufpos
== 0) {
1666 pfd
[POLL_STDOUT
].fd
= -1;
1672 drainbuf(int fd
, unsigned char *buf
, size_t *bufpos
, int oneline
)
1676 unsigned char *lf
= NULL
;
1679 lf
= memchr(buf
, '\n', *bufpos
);
1684 else if (Cflag
&& (lf
== buf
|| buf
[lf
- buf
- 1] != '\r')) {
1691 n
= write(fd
, buf
, n
);
1693 /* don't treat EAGAIN, EINTR as error */
1694 if (n
== -1 && (errno
== EAGAIN
|| errno
== EINTR
))
1696 if (oneline
== 2 && n
>= 0)
1701 if (oneline
== 2 && (r
= atomicio(vwrite
, fd
, "\r\n", 2)) != 2)
1702 err(1, "write failed (%zu/2)", r
);
1703 if (oneline
> 0 && iflag
)
1707 adjust
= *bufpos
- n
;
1709 memmove(buf
, buf
+ n
, adjust
);
1716 fillbuf(int fd
, unsigned char *buf
, size_t *bufpos
, struct tls
*tls
)
1718 fillbuf(int fd
, unsigned char *buf
, size_t *bufpos
)
1721 size_t num
= BUFSIZE
- *bufpos
;
1726 n
= tls_read(tls
, buf
+ *bufpos
, num
);
1728 errx(1, "tls read failed (%s)", tls_error(tls
));
1731 n
= read(fd
, buf
+ *bufpos
, num
);
1732 /* don't treat EAGAIN, EINTR as error */
1733 if (n
== -1 && (errno
== EAGAIN
|| errno
== EINTR
))
1735 n
= TLS_WANT_POLLIN
;
1748 * Pass the connected file descriptor to stdout and exit.
1756 char buf
[CMSG_SPACE(sizeof(int))];
1758 struct cmsghdr
*cmsg
;
1764 /* Avoid obvious stupidity */
1765 if (isatty(STDOUT_FILENO
))
1766 errx(1, "Cannot pass file descriptor to tty");
1768 memset(&mh
, 0, sizeof(mh
));
1769 memset(&cmsgbuf
, 0, sizeof(cmsgbuf
));
1770 memset(&iov
, 0, sizeof(iov
));
1772 mh
.msg_control
= (caddr_t
)&cmsgbuf
.buf
;
1773 mh
.msg_controllen
= sizeof(cmsgbuf
.buf
);
1774 cmsg
= CMSG_FIRSTHDR(&mh
);
1775 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
1776 cmsg
->cmsg_level
= SOL_SOCKET
;
1777 cmsg
->cmsg_type
= SCM_RIGHTS
;
1778 *(int *)CMSG_DATA(cmsg
) = nfd
;
1785 memset(&pfd
, 0, sizeof(pfd
));
1786 pfd
.fd
= STDOUT_FILENO
;
1787 pfd
.events
= POLLOUT
;
1789 r
= sendmsg(STDOUT_FILENO
, &mh
, 0);
1791 if (errno
== EAGAIN
|| errno
== EINTR
) {
1792 if (poll(&pfd
, 1, -1) == -1)
1798 errx(1, "sendmsg: unexpected return value %zd", r
);
1805 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1807 atelnet(int nfd
, unsigned char *buf
, unsigned int size
)
1809 unsigned char *p
, *end
;
1810 unsigned char obuf
[4];
1814 end
= buf
+ size
- 2;
1816 for (p
= buf
; p
< end
; p
++) {
1822 if ((*p
== WILL
) || (*p
== WONT
))
1824 else if ((*p
== DO
) || (*p
== DONT
))
1831 if (atomicio(vwrite
, nfd
, obuf
, 3) != 3)
1832 warn("Write Error!");
1838 strtoport(char *portstr
, int udp
)
1840 struct servent
*entry
;
1845 proto
= udp
? "udp" : "tcp";
1847 port
= strtonum(portstr
, 1, PORT_MAX
, &errstr
);
1850 if (errno
!= EINVAL
)
1851 errx(1, "port number %s: %s", errstr
, portstr
);
1852 if ((entry
= getservbyname(portstr
, proto
)) == NULL
)
1853 errx(1, "service \"%s\" unknown", portstr
);
1854 return ntohs(entry
->s_port
);
1859 * Build an array of ports in portlist[], listing each port
1860 * that we should try to connect to.
1863 build_ports(char **p
)
1871 char *proto
= proto_name(uflag
, dccpflag
);
1872 for (i
= 0; p
[i
] != NULL
; i
++) {
1873 sv
= getservbyname(p
[i
], proto
);
1875 if (asprintf(&portlist
[x
], "%d", ntohs(sv
->s_port
)) < 0)
1878 } else if (isdigit((unsigned char)*p
[i
]) && (n
= strchr(p
[i
], '-')) != NULL
) {
1882 /* Make sure the ports are in order: lowest->highest. */
1883 hi
= strtoport(n
, uflag
);
1884 lo
= strtoport(p
[i
], uflag
);
1891 /* Load ports sequentially. */
1892 for (cp
= lo
; cp
<= hi
; cp
++) {
1893 if (asprintf(&portlist
[x
], "%d", cp
) == -1)
1898 hi
= strtoport(p
[i
], uflag
);
1899 if (asprintf(&portlist
[x
], "%d", hi
) < 0)
1906 * Initialize portlist with a random permutation using
1907 * Fisher–Yates shuffle.
1910 for (i
= x
-1; i
> 0; i
--) {
1911 cp
= arc4random_uniform(i
+1);
1914 portlist
[i
] = portlist
[cp
];
1923 * Do a few writes to see if the UDP port is there.
1924 * Fails once PF state table is full.
1931 if ((write(s
, "X", 1) != 1) ||
1932 ((write(s
, "X", 1) != 1) && (errno
== ECONNREFUSED
)))
1935 /* Give the remote host some time to reply. */
1936 for (i
= 0, t
= (timeout
== -1) ? UDP_SCAN_TIMEOUT
: (timeout
/ 1000);
1939 if ((write(s
, "X", 1) != 1) && (errno
== ECONNREFUSED
))
1946 set_common_sockopts(int s
, const struct sockaddr
* sa
)
1949 int af
= sa
->sa_family
;
1951 # if defined(SO_BROADCAST)
1953 /* allow datagram sockets to send packets to a broadcast address
1954 * (this option has no effect on stream-oriented sockets) */
1955 if (setsockopt(s
, SOL_SOCKET
, SO_BROADCAST
,
1956 &x
, sizeof(x
)) == -1)
1960 # if defined(TCP_MD5SIG_EXT) && defined(TCP_MD5SIG_MAXKEYLEN)
1962 struct tcp_md5sig sig
;
1963 memset(&sig
, 0, sizeof(sig
));
1964 memcpy(&sig
.tcpm_addr
, sa
, sizeof(struct sockaddr_storage
));
1965 sig
.tcpm_keylen
= TCP_MD5SIG_MAXKEYLEN
< strlen(Sflag_password
)
1966 ? TCP_MD5SIG_MAXKEYLEN
1967 : strlen(Sflag_password
);
1968 memcpy(sig
.tcpm_key
, Sflag_password
, sig
.tcpm_keylen
);
1969 sig
.tcpm_flags
= TCP_MD5SIG_FLAG_PREFIX
;
1970 if (setsockopt(s
, IPPROTO_TCP
, TCP_MD5SIG_EXT
,
1971 &sig
, sizeof(sig
)) == -1)
1976 if (setsockopt(s
, SOL_SOCKET
, SO_DEBUG
,
1977 &x
, sizeof(x
)) == -1)
1981 if (af
== AF_INET
&& setsockopt(s
, IPPROTO_IP
,
1982 IP_TOS
, &Tflag
, sizeof(Tflag
)) == -1)
1983 err(1, "set IP ToS");
1985 #if defined(IPV6_TCLASS)
1986 else if (af
== AF_INET6
&& setsockopt(s
, IPPROTO_IPV6
,
1987 IPV6_TCLASS
, &Tflag
, sizeof(Tflag
)) == -1)
1988 err(1, "set IPv6 traffic class");
1990 else if (af
== AF_INET6
)
1991 errx(1, "can't set IPv6 traffic class (unavailable)");
1995 if (setsockopt(s
, SOL_SOCKET
, SO_RCVBUF
,
1996 &Iflag
, sizeof(Iflag
)) == -1)
1997 err(1, "set TCP receive buffer size");
2000 if (setsockopt(s
, SOL_SOCKET
, SO_SNDBUF
,
2001 &Oflag
, sizeof(Oflag
)) == -1)
2002 err(1, "set TCP send buffer size");
2006 if (af
== AF_INET
&& setsockopt(s
, IPPROTO_IP
,
2007 IP_TTL
, &ttl
, sizeof(ttl
)))
2008 err(1, "set IP TTL");
2010 #if defined(IPV6_UNICAST_HOPS)
2011 else if (af
== AF_INET6
&& setsockopt(s
, IPPROTO_IPV6
,
2012 IPV6_UNICAST_HOPS
, &ttl
, sizeof(ttl
)))
2013 err(1, "set IPv6 unicast hops");
2015 else if (af
== AF_INET6
)
2016 errx(1, "can't set IPv6 unicast hops (unavailable)");
2021 #if defined(IP_MINTTL)
2022 if (af
== AF_INET
&& setsockopt(s
, IPPROTO_IP
,
2023 IP_MINTTL
, &minttl
, sizeof(minttl
)))
2024 err(1, "set IP min TTL");
2027 errx(1, "can't set IP min TTL (unavailable)");
2030 #if defined(IPV6_MINHOPCOUNT)
2031 else if (af
== AF_INET6
&& setsockopt(s
, IPPROTO_IPV6
,
2032 IPV6_MINHOPCOUNT
, &minttl
, sizeof(minttl
)))
2033 err(1, "set IPv6 min hop count");
2035 else if (af
== AF_INET6
)
2036 errx(1, "can't set IPv6 min hop count (unavailable)");
2042 process_tos_opt(char *s
, int *val
)
2044 /* DiffServ Codepoints and other TOS mappings */
2045 const struct toskeywords
{
2046 const char *keyword
;
2048 } *t
, toskeywords
[] = {
2049 { "af11", IPTOS_DSCP_AF11
},
2050 { "af12", IPTOS_DSCP_AF12
},
2051 { "af13", IPTOS_DSCP_AF13
},
2052 { "af21", IPTOS_DSCP_AF21
},
2053 { "af22", IPTOS_DSCP_AF22
},
2054 { "af23", IPTOS_DSCP_AF23
},
2055 { "af31", IPTOS_DSCP_AF31
},
2056 { "af32", IPTOS_DSCP_AF32
},
2057 { "af33", IPTOS_DSCP_AF33
},
2058 { "af41", IPTOS_DSCP_AF41
},
2059 { "af42", IPTOS_DSCP_AF42
},
2060 { "af43", IPTOS_DSCP_AF43
},
2061 { "critical", IPTOS_PREC_CRITIC_ECP
},
2062 { "cs0", IPTOS_DSCP_CS0
},
2063 { "cs1", IPTOS_DSCP_CS1
},
2064 { "cs2", IPTOS_DSCP_CS2
},
2065 { "cs3", IPTOS_DSCP_CS3
},
2066 { "cs4", IPTOS_DSCP_CS4
},
2067 { "cs5", IPTOS_DSCP_CS5
},
2068 { "cs6", IPTOS_DSCP_CS6
},
2069 { "cs7", IPTOS_DSCP_CS7
},
2070 { "ef", IPTOS_DSCP_EF
},
2071 { "inetcontrol", IPTOS_PREC_INTERNETCONTROL
},
2072 { "lowcost", IPTOS_LOWCOST
},
2073 { "lowdelay", IPTOS_LOWDELAY
},
2074 { "netcontrol", IPTOS_PREC_NETCONTROL
},
2075 { "reliability", IPTOS_RELIABILITY
},
2076 { "throughput", IPTOS_THROUGHPUT
},
2080 for (t
= toskeywords
; t
->keyword
!= NULL
; t
++) {
2081 if (strcmp(s
, t
->keyword
) == 0) {
2092 process_tls_opt(char *s
, int *flags
)
2097 const struct tlskeywords
{
2098 const char *keyword
;
2101 } *t
, tlskeywords
[] = {
2102 { "ciphers", -1, &tls_ciphers
},
2103 { "clientcert", TLS_CCERT
, NULL
},
2104 { "muststaple", TLS_MUSTSTAPLE
, NULL
},
2105 { "noverify", TLS_NOVERIFY
, NULL
},
2106 { "noname", TLS_NONAME
, NULL
},
2107 { "protocols", -1, &tls_protocols
},
2112 if ((v
= strchr(s
, '=')) != NULL
) {
2117 for (t
= tlskeywords
; t
->keyword
!= NULL
; t
++) {
2118 if (strlen(t
->keyword
) == len
&&
2119 strncmp(s
, t
->keyword
, len
) == 0) {
2120 if (t
->value
!= NULL
) {
2122 errx(1, "invalid tls value `%s'", s
);
2134 save_peer_cert(struct tls
*tls_ctx
, FILE *fp
)
2139 if ((pem
= tls_peer_cert_chain_pem(tls_ctx
, &plen
)) == NULL
)
2140 errx(1, "Can't get peer certificate");
2141 if (fprintf(fp
, "%.*s", (int)plen
, pem
) < 0)
2142 err(1, "unable to save peer cert");
2143 if (fflush(fp
) != 0)
2144 err(1, "unable to flush peer cert");
2148 report_tls(struct tls
* tls_ctx
, char * host
)
2151 const char *ocsp_url
;
2153 fprintf(stderr
, "TLS handshake negotiated %s/%s with host %s\n",
2154 tls_conn_version(tls_ctx
), tls_conn_cipher(tls_ctx
), host
);
2155 fprintf(stderr
, "Peer name: %s\n",
2156 tls_expectname
? tls_expectname
: host
);
2157 if (tls_peer_cert_subject(tls_ctx
))
2158 fprintf(stderr
, "Subject: %s\n",
2159 tls_peer_cert_subject(tls_ctx
));
2160 if (tls_peer_cert_issuer(tls_ctx
))
2161 fprintf(stderr
, "Issuer: %s\n",
2162 tls_peer_cert_issuer(tls_ctx
));
2163 if ((t
= tls_peer_cert_notbefore(tls_ctx
)) != -1)
2164 fprintf(stderr
, "Valid From: %s", ctime(&t
));
2165 if ((t
= tls_peer_cert_notafter(tls_ctx
)) != -1)
2166 fprintf(stderr
, "Valid Until: %s", ctime(&t
));
2167 if (tls_peer_cert_hash(tls_ctx
))
2168 fprintf(stderr
, "Cert Hash: %s\n",
2169 tls_peer_cert_hash(tls_ctx
));
2170 ocsp_url
= tls_peer_ocsp_url(tls_ctx
);
2171 if (ocsp_url
!= NULL
)
2172 fprintf(stderr
, "OCSP URL: %s\n", ocsp_url
);
2173 switch (tls_peer_ocsp_response_status(tls_ctx
)) {
2174 case TLS_OCSP_RESPONSE_SUCCESSFUL
:
2175 fprintf(stderr
, "OCSP Stapling: %s\n",
2176 tls_peer_ocsp_result(tls_ctx
) == NULL
? "" :
2177 tls_peer_ocsp_result(tls_ctx
));
2179 " response_status=%d cert_status=%d crl_reason=%d\n",
2180 tls_peer_ocsp_response_status(tls_ctx
),
2181 tls_peer_ocsp_cert_status(tls_ctx
),
2182 tls_peer_ocsp_crl_reason(tls_ctx
));
2183 t
= tls_peer_ocsp_this_update(tls_ctx
);
2184 fprintf(stderr
, " this update: %s",
2185 t
!= -1 ? ctime(&t
) : "\n");
2186 t
= tls_peer_ocsp_next_update(tls_ctx
);
2187 fprintf(stderr
, " next update: %s",
2188 t
!= -1 ? ctime(&t
) : "\n");
2189 t
= tls_peer_ocsp_revocation_time(tls_ctx
);
2190 fprintf(stderr
, " revocation: %s",
2191 t
!= -1 ? ctime(&t
) : "\n");
2196 fprintf(stderr
, "OCSP Stapling: failure - response_status %d (%s)\n",
2197 tls_peer_ocsp_response_status(tls_ctx
),
2198 tls_peer_ocsp_result(tls_ctx
) == NULL
? "" :
2199 tls_peer_ocsp_result(tls_ctx
));
2207 report_sock(const char *msg
, const struct sockaddr
*sa
, socklen_t salen
,
2210 char host
[NI_MAXHOST
], port
[NI_MAXSERV
];
2212 int flags
= NI_NUMERICSERV
;
2215 fprintf(stderr
, "%s on %s\n", msg
, path
);
2220 flags
|= NI_NUMERICHOST
;
2222 herr
= getnameinfo(sa
, salen
, host
, sizeof(host
), port
, sizeof(port
),
2228 warn("getnameinfo");
2231 warnx("getnameinfo: %s", gai_strerror(herr
));
2235 fprintf(stderr
, "%s on %s %s\n", msg
, host
, port
);
2241 # if defined(DEBIAN_VERSION)
2242 fprintf(stderr
, "OpenBSD netcat (Debian patchlevel " DEBIAN_VERSION
")\n");
2245 fprintf(stderr
, "\tCommand Summary:\n\
2248 \t-b Allow broadcast\n\
2249 \t-C Send CRLF as line-ending\n\
2250 \t-D Enable the debug socket option\n\
2251 \t-d Detach from stdin\n\
2252 \t-F Pass socket fd\n\
2253 \t-h This help text\n\
2254 \t-I length TCP receive buffer length\n\
2255 \t-i interval Delay interval for lines sent, ports scanned\n\
2256 \t-k Keep inbound sockets open for multiple connects\n\
2257 \t-l Listen mode, for inbound connects\n\
2258 \t-M ttl Outgoing TTL / Hop Limit\n\
2259 \t-m minttl Minimum incoming TTL / Hop Limit\n\
2260 \t-N Shutdown the network socket after EOF on stdin\n\
2261 \t-n Suppress name/port resolutions\n\
2262 \t-O length TCP send buffer length\n\
2263 \t-P proxyuser\tUsername for proxy authentication\n\
2264 \t-p port\t Specify local port for remote connects\n\
2265 \t-q secs\t quit after EOF on stdin and delay of secs\n\
2266 \t-r Randomize remote ports\n\
2267 \t-S Enable the TCP MD5 signature option\n\
2268 \t-s sourceaddr Local source address\n\
2269 \t-T keyword TOS value\n\
2270 \t-t Answer TELNET negotiation\n\
2271 \t-U Use UNIX domain socket\n\
2273 \t-V rtable Specify alternate routing table\n\
2275 \t-W recvlimit Terminate after receiving a number of packets\n\
2276 \t-w timeout Timeout for connects and final net reads\n\
2277 \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
2278 \t-x addr[:port]\tSpecify proxy address and port\n\
2280 \t-z Zero-I/O mode [used for scanning]\n\
2281 Port numbers can be individual or ranges: lo-hi [inclusive]\n");
2289 "usage: nc [-46CDdFhklNnrStUuvZz] [-I length] [-i interval] [-M ttl]\n"
2290 "\t [-m minttl] [-O length] [-P proxy_username] [-p source_port]\n"
2291 "\t [-q seconds] [-s sourceaddr] [-T keyword] [-V rtable] [-W recvlimit]\n"
2292 "\t [-w timeout] [-X proxy_protocol] [-x proxy_address[:port]]\n"
2293 "\t [destination] [port]\n");
2300 * handler for a "-q" timeout (exit 0 instead of 1)