Add local patches to LibreSSL.
[dragonfly.git] / crypto / libressl / apps / nc / netcat.c
1 /* $OpenBSD: netcat.c,v 1.203 2019/02/26 17:32:47 jsing Exp $ */
2 /*
3  * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4  * Copyright (c) 2015 Bob Beck.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
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.
17  *
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.
28  */
29
30 /*
31  * Re-written nc(1) for OpenBSD. Original implementation by
32  * *Hobbit* <hobbit@avian.org>.
33  */
34
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/uio.h>
38 #include <sys/un.h>
39
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <netinet/ip.h>
43 #include <arpa/telnet.h>
44
45 #include <ctype.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <limits.h>
49 #include <netdb.h>
50 #include <poll.h>
51 #include <signal.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <time.h>
57 #include <tls.h>
58 #include <unistd.h>
59
60 #include "atomicio.h"
61
62 #if !defined(OpenBSD)
63 #define pledge(request, paths) 0
64 #define unveil(path, permissions) 0
65 #endif
66
67 #define PORT_MAX        65535
68 #define UNIX_DG_TMP_SOCKET_SIZE 19
69
70 #define POLL_STDIN      0
71 #define POLL_NETOUT     1
72 #define POLL_NETIN      2
73 #define POLL_STDOUT     3
74 #define BUFSIZE         16384
75
76 #define TLS_NOVERIFY    (1 << 1)
77 #define TLS_NONAME      (1 << 2)
78 #define TLS_CCERT       (1 << 3)
79 #define TLS_MUSTSTAPLE  (1 << 4)
80
81 /* Command Line Options */
82 int     dflag;                                  /* detached, no stdin */
83 int     Fflag;                                  /* fdpass sock to stdout */
84 unsigned int iflag;                             /* Interval Flag */
85 int     kflag;                                  /* More than one connect */
86 int     lflag;                                  /* Bind to local port */
87 int     Nflag;                                  /* shutdown() network socket */
88 int     nflag;                                  /* Don't do name look up */
89 char   *Pflag;                                  /* Proxy username */
90 char   *pflag;                                  /* Localport flag */
91 int     rflag;                                  /* Random ports flag */
92 char   *sflag;                                  /* Source Address */
93 int     tflag;                                  /* Telnet Emulation */
94 int     uflag;                                  /* UDP - Default to TCP */
95 int     vflag;                                  /* Verbosity */
96 int     xflag;                                  /* Socks proxy */
97 int     zflag;                                  /* Port Scan Flag */
98 int     Dflag;                                  /* sodebug */
99 int     Iflag;                                  /* TCP receive buffer size */
100 int     Oflag;                                  /* TCP send buffer size */
101 #ifdef TCP_MD5SIG
102 int     Sflag;                                  /* TCP MD5 signature option */
103 #endif
104 int     Tflag = -1;                             /* IP Type of Service */
105 #ifdef SO_RTABLE
106 int     rtableid = -1;
107 #endif
108
109 int     usetls;                                 /* use TLS */
110 const char    *Cflag;                           /* Public cert file */
111 const char    *Kflag;                           /* Private key file */
112 const char    *oflag;                           /* OCSP stapling file */
113 const char    *Rflag;                           /* Root CA file */
114 int     tls_cachanged;                          /* Using non-default CA file */
115 int     TLSopt;                                 /* TLS options */
116 char    *tls_expectname;                        /* required name in peer cert */
117 char    *tls_expecthash;                        /* required hash of peer cert */
118 char    *tls_ciphers;                           /* TLS ciphers */
119 char    *tls_protocols;                         /* TLS protocols */
120 FILE    *Zflag;                                 /* file to save peer cert */
121
122 int recvcount, recvlimit;
123 int timeout = -1;
124 int family = AF_UNSPEC;
125 char *portlist[PORT_MAX+1];
126 char *unix_dg_tmp_socket;
127 int ttl = -1;
128 int minttl = -1;
129
130 void    atelnet(int, unsigned char *, unsigned int);
131 int     strtoport(char *portstr, int udp);
132 void    build_ports(char *);
133 void    help(void) __attribute__((noreturn));
134 int     local_listen(const char *, const char *, struct addrinfo);
135 void    readwrite(int, struct tls *);
136 void    fdpass(int nfd) __attribute__((noreturn));
137 int     remote_connect(const char *, const char *, struct addrinfo);
138 int     timeout_tls(int, struct tls *, int (*)(struct tls *));
139 int     timeout_connect(int, const struct sockaddr *, socklen_t);
140 int     socks_connect(const char *, const char *, struct addrinfo,
141             const char *, const char *, struct addrinfo, int, const char *);
142 int     udptest(int);
143 int     unix_bind(char *, int);
144 int     unix_connect(char *);
145 int     unix_listen(char *);
146 void    set_common_sockopts(int, int);
147 int     process_tos_opt(char *, int *);
148 int     process_tls_opt(char *, int *);
149 void    save_peer_cert(struct tls *_tls_ctx, FILE *_fp);
150 void    report_sock(const char *, const struct sockaddr *, socklen_t, char *);
151 void    report_tls(struct tls *tls_ctx, char * host);
152 void    usage(int);
153 ssize_t drainbuf(int, unsigned char *, size_t *, struct tls *);
154 ssize_t fillbuf(int, unsigned char *, size_t *, struct tls *);
155 void    tls_setup_client(struct tls *, int, char *);
156 struct tls *tls_setup_server(struct tls *, int, char *);
157
158 int
159 main(int argc, char *argv[])
160 {
161         int ch, s = -1, ret, socksv;
162         char *host, *uport;
163         struct addrinfo hints;
164         struct servent *sv;
165         socklen_t len;
166         struct sockaddr_storage cliaddr;
167         char *proxy = NULL, *proxyport = NULL;
168         const char *errstr;
169         struct addrinfo proxyhints;
170         char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
171         struct tls_config *tls_cfg = NULL;
172         struct tls *tls_ctx = NULL;
173         uint32_t protocols;
174
175         ret = 1;
176         socksv = 5;
177         host = NULL;
178         uport = NULL;
179         sv = NULL;
180         Rflag = tls_default_ca_cert_file();
181
182         signal(SIGPIPE, SIG_IGN);
183
184         while ((ch = getopt(argc, argv,
185             "46C:cDde:FH:hI:i:K:klM:m:NnO:o:P:p:R:rSs:T:tUuV:vW:w:X:x:Z:z"))
186             != -1) {
187                 switch (ch) {
188                 case '4':
189                         family = AF_INET;
190                         break;
191                 case '6':
192                         family = AF_INET6;
193                         break;
194                 case 'U':
195                         family = AF_UNIX;
196                         break;
197                 case 'X':
198                         if (strcasecmp(optarg, "connect") == 0)
199                                 socksv = -1; /* HTTP proxy CONNECT */
200                         else if (strcmp(optarg, "4") == 0)
201                                 socksv = 4; /* SOCKS v.4 */
202                         else if (strcmp(optarg, "5") == 0)
203                                 socksv = 5; /* SOCKS v.5 */
204                         else
205                                 errx(1, "unsupported proxy protocol");
206                         break;
207                 case 'C':
208                         Cflag = optarg;
209                         break;
210                 case 'c':
211                         usetls = 1;
212                         break;
213                 case 'd':
214                         dflag = 1;
215                         break;
216                 case 'e':
217                         tls_expectname = optarg;
218                         break;
219                 case 'F':
220                         Fflag = 1;
221                         break;
222                 case 'H':
223                         tls_expecthash = optarg;
224                         break;
225                 case 'h':
226                         help();
227                         break;
228                 case 'i':
229                         iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
230                         if (errstr)
231                                 errx(1, "interval %s: %s", errstr, optarg);
232                         break;
233                 case 'K':
234                         Kflag = optarg;
235                         break;
236                 case 'k':
237                         kflag = 1;
238                         break;
239                 case 'l':
240                         lflag = 1;
241                         break;
242                 case 'M':
243                         ttl = strtonum(optarg, 0, 255, &errstr);
244                         if (errstr)
245                                 errx(1, "ttl is %s", errstr);
246                         break;
247                 case 'm':
248                         minttl = strtonum(optarg, 0, 255, &errstr);
249                         if (errstr)
250                                 errx(1, "minttl is %s", errstr);
251                         break;
252                 case 'N':
253                         Nflag = 1;
254                         break;
255                 case 'n':
256                         nflag = 1;
257                         break;
258                 case 'P':
259                         Pflag = optarg;
260                         break;
261                 case 'p':
262                         pflag = optarg;
263                         break;
264                 case 'R':
265                         tls_cachanged = 1;
266                         Rflag = optarg;
267                         break;
268                 case 'r':
269                         rflag = 1;
270                         break;
271                 case 's':
272                         sflag = optarg;
273                         break;
274                 case 't':
275                         tflag = 1;
276                         break;
277                 case 'u':
278                         uflag = 1;
279                         break;
280 #ifdef SO_RTABLE
281                 case 'V':
282                         rtableid = (int)strtonum(optarg, 0,
283                             RT_TABLEID_MAX, &errstr);
284                         if (errstr)
285                                 errx(1, "rtable %s: %s", errstr, optarg);
286                         break;
287 #endif
288                 case 'v':
289                         vflag = 1;
290                         break;
291                 case 'W':
292                         recvlimit = strtonum(optarg, 1, INT_MAX, &errstr);
293                         if (errstr)
294                                 errx(1, "receive limit %s: %s", errstr, optarg);
295                         break;
296                 case 'w':
297                         timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
298                         if (errstr)
299                                 errx(1, "timeout %s: %s", errstr, optarg);
300                         timeout *= 1000;
301                         break;
302                 case 'x':
303                         xflag = 1;
304                         if ((proxy = strdup(optarg)) == NULL)
305                                 err(1, NULL);
306                         break;
307                 case 'Z':
308                         if (strcmp(optarg, "-") == 0)
309                                 Zflag = stderr;
310                         else if ((Zflag = fopen(optarg, "w")) == NULL)
311                                 err(1, "can't open %s", optarg);
312                         break;
313                 case 'z':
314                         zflag = 1;
315                         break;
316                 case 'D':
317                         Dflag = 1;
318                         break;
319                 case 'I':
320                         Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
321                         if (errstr != NULL)
322                                 errx(1, "TCP receive window %s: %s",
323                                     errstr, optarg);
324                         break;
325                 case 'O':
326                         Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
327                         if (errstr != NULL)
328                                 errx(1, "TCP send window %s: %s",
329                                     errstr, optarg);
330                         break;
331                 case 'o':
332                         oflag = optarg;
333                         break;
334 #ifdef TCP_MD5SIG
335                 case 'S':
336                         Sflag = 1;
337                         break;
338 #endif
339                 case 'T':
340                         errstr = NULL;
341                         errno = 0;
342                         if (process_tls_opt(optarg, &TLSopt))
343                                 break;
344                         if (process_tos_opt(optarg, &Tflag))
345                                 break;
346                         if (strlen(optarg) > 1 && optarg[0] == '0' &&
347                             optarg[1] == 'x')
348                                 Tflag = (int)strtol(optarg, NULL, 16);
349                         else
350                                 Tflag = (int)strtonum(optarg, 0, 255,
351                                     &errstr);
352                         if (Tflag < 0 || Tflag > 255 || errstr || errno)
353                                 errx(1, "illegal tos/tls value %s", optarg);
354                         break;
355                 default:
356                         usage(1);
357                 }
358         }
359         argc -= optind;
360         argv += optind;
361
362 #ifdef SO_RTABLE
363         if (rtableid >= 0)
364                 if (setrtable(rtableid) == -1)
365                         err(1, "setrtable");
366 #endif
367
368         /* Cruft to make sure options are clean, and used properly. */
369         if (argv[0] && !argv[1] && family == AF_UNIX) {
370                 host = argv[0];
371                 uport = NULL;
372         } else if (argv[0] && !argv[1]) {
373                 if (!lflag)
374                         usage(1);
375                 uport = argv[0];
376                 host = NULL;
377         } else if (argv[0] && argv[1]) {
378                 host = argv[0];
379                 uport = argv[1];
380         } else
381                 usage(1);
382
383         if (usetls) {
384                 if (Cflag && unveil(Cflag, "r") == -1)
385                         err(1, "unveil");
386                 if (unveil(Rflag, "r") == -1)
387                         err(1, "unveil");
388                 if (Kflag && unveil(Kflag, "r") == -1)
389                         err(1, "unveil");
390                 if (oflag && unveil(oflag, "r") == -1)
391                         err(1, "unveil");
392         } else {
393                 if (family == AF_UNIX) {
394                         if (unveil(host, "rwc") == -1)
395                                 err(1, "unveil");
396                         if (uflag && !lflag) {
397                                 if (unveil(sflag ? sflag : "/tmp", "rwc") == -1)
398                                         err(1, "unveil");
399                         }
400                 } else {
401                         if (unveil("/", "") == -1)
402                                 err(1, "unveil");
403                 }
404         }
405
406         if (family == AF_UNIX) {
407                 if (pledge("stdio rpath wpath cpath tmppath unix", NULL) == -1)
408                         err(1, "pledge");
409         } else if (Fflag && Pflag) {
410                 if (pledge("stdio inet dns sendfd tty", NULL) == -1)
411                         err(1, "pledge");
412         } else if (Fflag) {
413                 if (pledge("stdio inet dns sendfd", NULL) == -1)
414                         err(1, "pledge");
415         } else if (Pflag && usetls) {
416                 if (pledge("stdio rpath inet dns tty", NULL) == -1)
417                         err(1, "pledge");
418         } else if (Pflag) {
419                 if (pledge("stdio inet dns tty", NULL) == -1)
420                         err(1, "pledge");
421         } else if (usetls) {
422                 if (pledge("stdio rpath inet dns", NULL) == -1)
423                         err(1, "pledge");
424         } else if (pledge("stdio inet dns", NULL) == -1)
425                 err(1, "pledge");
426
427         if (lflag && sflag)
428                 errx(1, "cannot use -s and -l");
429         if (lflag && pflag)
430                 errx(1, "cannot use -p and -l");
431         if (lflag && zflag)
432                 errx(1, "cannot use -z and -l");
433         if (!lflag && kflag)
434                 errx(1, "must use -l with -k");
435         if (uflag && usetls)
436                 errx(1, "cannot use -c and -u");
437         if ((family == AF_UNIX) && usetls)
438                 errx(1, "cannot use -c and -U");
439         if ((family == AF_UNIX) && Fflag)
440                 errx(1, "cannot use -F and -U");
441         if (Fflag && usetls)
442                 errx(1, "cannot use -c and -F");
443         if (TLSopt && !usetls)
444                 errx(1, "you must specify -c to use TLS options");
445         if (Cflag && !usetls)
446                 errx(1, "you must specify -c to use -C");
447         if (Kflag && !usetls)
448                 errx(1, "you must specify -c to use -K");
449         if (Zflag && !usetls)
450                 errx(1, "you must specify -c to use -Z");
451         if (oflag && !Cflag)
452                 errx(1, "you must specify -C to use -o");
453         if (tls_cachanged && !usetls)
454                 errx(1, "you must specify -c to use -R");
455         if (tls_expecthash && !usetls)
456                 errx(1, "you must specify -c to use -H");
457         if (tls_expectname && !usetls)
458                 errx(1, "you must specify -c to use -e");
459
460         /* Get name of temporary socket for unix datagram client */
461         if ((family == AF_UNIX) && uflag && !lflag) {
462                 if (sflag) {
463                         unix_dg_tmp_socket = sflag;
464                 } else {
465                         strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
466                             UNIX_DG_TMP_SOCKET_SIZE);
467                         if (mktemp(unix_dg_tmp_socket_buf) == NULL)
468                                 err(1, "mktemp");
469                         unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
470                 }
471         }
472
473         /* Initialize addrinfo structure. */
474         if (family != AF_UNIX) {
475                 memset(&hints, 0, sizeof(struct addrinfo));
476                 hints.ai_family = family;
477                 hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
478                 hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
479                 if (nflag)
480                         hints.ai_flags |= AI_NUMERICHOST;
481         }
482
483         if (xflag) {
484                 if (uflag)
485                         errx(1, "no proxy support for UDP mode");
486
487                 if (lflag)
488                         errx(1, "no proxy support for listen");
489
490                 if (family == AF_UNIX)
491                         errx(1, "no proxy support for unix sockets");
492
493                 if (sflag)
494                         errx(1, "no proxy support for local source address");
495
496                 if (*proxy == '[') {
497                         ++proxy;
498                         proxyport = strchr(proxy, ']');
499                         if (proxyport == NULL)
500                                 errx(1, "missing closing bracket in proxy");
501                         *proxyport++ = '\0';
502                         if (*proxyport == '\0')
503                                 /* Use default proxy port. */
504                                 proxyport = NULL;
505                         else {
506                                 if (*proxyport == ':')
507                                         ++proxyport;
508                                 else
509                                         errx(1, "garbage proxy port delimiter");
510                         }
511                 } else {
512                         proxyport = strrchr(proxy, ':');
513                         if (proxyport != NULL)
514                                 *proxyport++ = '\0';
515                 }
516
517                 memset(&proxyhints, 0, sizeof(struct addrinfo));
518                 proxyhints.ai_family = family;
519                 proxyhints.ai_socktype = SOCK_STREAM;
520                 proxyhints.ai_protocol = IPPROTO_TCP;
521                 if (nflag)
522                         proxyhints.ai_flags |= AI_NUMERICHOST;
523         }
524
525         if (usetls) {
526                 if ((tls_cfg = tls_config_new()) == NULL)
527                         errx(1, "unable to allocate TLS config");
528                 if (Rflag && tls_config_set_ca_file(tls_cfg, Rflag) == -1)
529                         errx(1, "%s", tls_config_error(tls_cfg));
530                 if (Cflag && tls_config_set_cert_file(tls_cfg, Cflag) == -1)
531                         errx(1, "%s", tls_config_error(tls_cfg));
532                 if (Kflag && tls_config_set_key_file(tls_cfg, Kflag) == -1)
533                         errx(1, "%s", tls_config_error(tls_cfg));
534                 if (oflag && tls_config_set_ocsp_staple_file(tls_cfg, oflag) == -1)
535                         errx(1, "%s", tls_config_error(tls_cfg));
536                 if (tls_config_parse_protocols(&protocols, tls_protocols) == -1)
537                         errx(1, "invalid TLS protocols `%s'", tls_protocols);
538                 if (tls_config_set_protocols(tls_cfg, protocols) == -1)
539                         errx(1, "%s", tls_config_error(tls_cfg));
540                 if (tls_config_set_ciphers(tls_cfg, tls_ciphers) == -1)
541                         errx(1, "%s", tls_config_error(tls_cfg));
542                 if (!lflag && (TLSopt & TLS_CCERT))
543                         errx(1, "clientcert is only valid with -l");
544                 if (TLSopt & TLS_NONAME)
545                         tls_config_insecure_noverifyname(tls_cfg);
546                 if (TLSopt & TLS_NOVERIFY) {
547                         if (tls_expecthash != NULL)
548                                 errx(1, "-H and -T noverify may not be used "
549                                     "together");
550                         tls_config_insecure_noverifycert(tls_cfg);
551                 }
552                 if (TLSopt & TLS_MUSTSTAPLE)
553                         tls_config_ocsp_require_stapling(tls_cfg);
554
555                 if (Pflag) {
556                         if (pledge("stdio inet dns tty", NULL) == -1)
557                                 err(1, "pledge");
558                 } else if (pledge("stdio inet dns", NULL) == -1)
559                         err(1, "pledge");
560         }
561         if (lflag) {
562                 ret = 0;
563
564                 if (family == AF_UNIX) {
565                         if (uflag)
566                                 s = unix_bind(host, 0);
567                         else
568                                 s = unix_listen(host);
569                 }
570
571                 if (usetls) {
572                         tls_config_verify_client_optional(tls_cfg);
573                         if ((tls_ctx = tls_server()) == NULL)
574                                 errx(1, "tls server creation failed");
575                         if (tls_configure(tls_ctx, tls_cfg) == -1)
576                                 errx(1, "tls configuration failed (%s)",
577                                     tls_error(tls_ctx));
578                 }
579                 /* Allow only one connection at a time, but stay alive. */
580                 for (;;) {
581                         if (family != AF_UNIX) {
582                                 if (s != -1)
583                                         close(s);
584                                 s = local_listen(host, uport, hints);
585                         }
586                         if (s < 0)
587                                 err(1, NULL);
588                         if (uflag && kflag) {
589                                 /*
590                                  * For UDP and -k, don't connect the socket,
591                                  * let it receive datagrams from multiple
592                                  * socket pairs.
593                                  */
594                                 readwrite(s, NULL);
595                         } else if (uflag && !kflag) {
596                                 /*
597                                  * For UDP and not -k, we will use recvfrom()
598                                  * initially to wait for a caller, then use
599                                  * the regular functions to talk to the caller.
600                                  */
601                                 int rv;
602                                 char buf[2048];
603                                 struct sockaddr_storage z;
604
605                                 len = sizeof(z);
606                                 rv = recvfrom(s, buf, sizeof(buf), MSG_PEEK,
607                                     (struct sockaddr *)&z, &len);
608                                 if (rv < 0)
609                                         err(1, "recvfrom");
610
611                                 rv = connect(s, (struct sockaddr *)&z, len);
612                                 if (rv < 0)
613                                         err(1, "connect");
614
615                                 if (vflag)
616                                         report_sock("Connection received",
617                                             (struct sockaddr *)&z, len, NULL);
618
619                                 readwrite(s, NULL);
620                         } else {
621                                 struct tls *tls_cctx = NULL;
622                                 int connfd;
623
624                                 len = sizeof(cliaddr);
625                                 connfd = accept4(s, (struct sockaddr *)&cliaddr,
626                                     &len, SOCK_NONBLOCK);
627                                 if (connfd == -1) {
628                                         /* For now, all errnos are fatal */
629                                         err(1, "accept");
630                                 }
631                                 if (vflag)
632                                         report_sock("Connection received",
633                                             (struct sockaddr *)&cliaddr, len,
634                                             family == AF_UNIX ? host : NULL);
635                                 if ((usetls) &&
636                                     (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
637                                         readwrite(connfd, tls_cctx);
638                                 if (!usetls)
639                                         readwrite(connfd, NULL);
640                                 if (tls_cctx)
641                                         timeout_tls(s, tls_cctx, tls_close);
642                                 close(connfd);
643                                 tls_free(tls_cctx);
644                         }
645                         if (family == AF_UNIX && uflag) {
646                                 if (connect(s, NULL, 0) < 0)
647                                         err(1, "connect");
648                         }
649
650                         if (!kflag)
651                                 break;
652                 }
653         } else if (family == AF_UNIX) {
654                 ret = 0;
655
656                 if ((s = unix_connect(host)) > 0) {
657                         if (!zflag)
658                                 readwrite(s, NULL);
659                         close(s);
660                 } else {
661                         warn("%s", host);
662                         ret = 1;
663                 }
664
665                 if (uflag)
666                         unlink(unix_dg_tmp_socket);
667                 return ret;
668
669         } else {
670                 int i = 0;
671
672                 /* Construct the portlist[] array. */
673                 build_ports(uport);
674
675                 /* Cycle through portlist, connecting to each port. */
676                 for (s = -1, i = 0; portlist[i] != NULL; i++) {
677                         if (s != -1)
678                                 close(s);
679                         tls_free(tls_ctx);
680                         tls_ctx = NULL;
681
682                         if (usetls) {
683                                 if ((tls_ctx = tls_client()) == NULL)
684                                         errx(1, "tls client creation failed");
685                                 if (tls_configure(tls_ctx, tls_cfg) == -1)
686                                         errx(1, "tls configuration failed (%s)",
687                                             tls_error(tls_ctx));
688                         }
689                         if (xflag)
690                                 s = socks_connect(host, portlist[i], hints,
691                                     proxy, proxyport, proxyhints, socksv,
692                                     Pflag);
693                         else
694                                 s = remote_connect(host, portlist[i], hints);
695
696                         if (s == -1)
697                                 continue;
698
699                         ret = 0;
700                         if (vflag || zflag) {
701                                 /* For UDP, make sure we are connected. */
702                                 if (uflag) {
703                                         if (udptest(s) == -1) {
704                                                 ret = 1;
705                                                 continue;
706                                         }
707                                 }
708
709                                 /* Don't look up port if -n. */
710                                 if (nflag)
711                                         sv = NULL;
712                                 else {
713                                         sv = getservbyport(
714                                             ntohs(atoi(portlist[i])),
715                                             uflag ? "udp" : "tcp");
716                                 }
717
718                                 fprintf(stderr,
719                                     "Connection to %s %s port [%s/%s] "
720                                     "succeeded!\n", host, portlist[i],
721                                     uflag ? "udp" : "tcp",
722                                     sv ? sv->s_name : "*");
723                         }
724                         if (Fflag)
725                                 fdpass(s);
726                         else {
727                                 if (usetls)
728                                         tls_setup_client(tls_ctx, s, host);
729                                 if (!zflag)
730                                         readwrite(s, tls_ctx);
731                                 if (tls_ctx)
732                                         timeout_tls(s, tls_ctx, tls_close);
733                         }
734                 }
735         }
736
737         if (s != -1)
738                 close(s);
739         tls_free(tls_ctx);
740         tls_config_free(tls_cfg);
741
742         return ret;
743 }
744
745 /*
746  * unix_bind()
747  * Returns a unix socket bound to the given path
748  */
749 int
750 unix_bind(char *path, int flags)
751 {
752         struct sockaddr_un s_un;
753         int s, save_errno;
754
755         /* Create unix domain socket. */
756         if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
757             0)) < 0)
758                 return -1;
759
760         memset(&s_un, 0, sizeof(struct sockaddr_un));
761         s_un.sun_family = AF_UNIX;
762
763         if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
764             sizeof(s_un.sun_path)) {
765                 close(s);
766                 errno = ENAMETOOLONG;
767                 return -1;
768         }
769
770         if (bind(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
771                 save_errno = errno;
772                 close(s);
773                 errno = save_errno;
774                 return -1;
775         }
776         if (vflag)
777                 report_sock("Bound", NULL, 0, path);
778
779         return s;
780 }
781
782 int
783 timeout_tls(int s, struct tls *tls_ctx, int (*func)(struct tls *))
784 {
785         struct pollfd pfd;
786         int ret;
787
788         while ((ret = (*func)(tls_ctx)) != 0) {
789                 if (ret == TLS_WANT_POLLIN)
790                         pfd.events = POLLIN;
791                 else if (ret == TLS_WANT_POLLOUT)
792                         pfd.events = POLLOUT;
793                 else
794                         break;
795                 pfd.fd = s;
796                 if ((ret = poll(&pfd, 1, timeout)) == 1)
797                         continue;
798                 else if (ret == 0) {
799                         errno = ETIMEDOUT;
800                         ret = -1;
801                         break;
802                 } else
803                         err(1, "poll failed");
804         }
805
806         return ret;
807 }
808
809 void
810 tls_setup_client(struct tls *tls_ctx, int s, char *host)
811 {
812         const char *errstr;
813
814         if (tls_connect_socket(tls_ctx, s,
815                 tls_expectname ? tls_expectname : host) == -1) {
816                 errx(1, "tls connection failed (%s)",
817                     tls_error(tls_ctx));
818         }
819         if (timeout_tls(s, tls_ctx, tls_handshake) == -1) {
820                 if ((errstr = tls_error(tls_ctx)) == NULL)
821                         errstr = strerror(errno);
822                 errx(1, "tls handshake failed (%s)", errstr);
823         }
824         if (vflag)
825                 report_tls(tls_ctx, host);
826         if (tls_expecthash && tls_peer_cert_hash(tls_ctx) &&
827             strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
828                 errx(1, "peer certificate is not %s", tls_expecthash);
829         if (Zflag) {
830                 save_peer_cert(tls_ctx, Zflag);
831                 if (Zflag != stderr && (fclose(Zflag) != 0))
832                         err(1, "fclose failed saving peer cert");
833         }
834 }
835
836 struct tls *
837 tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
838 {
839         struct tls *tls_cctx;
840         const char *errstr;
841
842         if (tls_accept_socket(tls_ctx, &tls_cctx, connfd) == -1) {
843                 warnx("tls accept failed (%s)", tls_error(tls_ctx));
844         } else if (timeout_tls(connfd, tls_cctx, tls_handshake) == -1) {
845                 if ((errstr = tls_error(tls_cctx)) == NULL)
846                         errstr = strerror(errno);
847                 warnx("tls handshake failed (%s)", errstr);
848         } else {
849                 int gotcert = tls_peer_cert_provided(tls_cctx);
850
851                 if (vflag && gotcert)
852                         report_tls(tls_cctx, host);
853                 if ((TLSopt & TLS_CCERT) && !gotcert)
854                         warnx("No client certificate provided");
855                 else if (gotcert && tls_peer_cert_hash(tls_ctx) && tls_expecthash &&
856                     strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
857                         warnx("peer certificate is not %s", tls_expecthash);
858                 else if (gotcert && tls_expectname &&
859                     (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
860                         warnx("name (%s) not found in client cert",
861                             tls_expectname);
862                 else {
863                         return tls_cctx;
864                 }
865         }
866         return NULL;
867 }
868
869 /*
870  * unix_connect()
871  * Returns a socket connected to a local unix socket. Returns -1 on failure.
872  */
873 int
874 unix_connect(char *path)
875 {
876         struct sockaddr_un s_un;
877         int s, save_errno;
878
879         if (uflag) {
880                 if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) < 0)
881                         return -1;
882         } else {
883                 if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
884                         return -1;
885         }
886
887         memset(&s_un, 0, sizeof(struct sockaddr_un));
888         s_un.sun_family = AF_UNIX;
889
890         if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
891             sizeof(s_un.sun_path)) {
892                 close(s);
893                 errno = ENAMETOOLONG;
894                 return -1;
895         }
896         if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
897                 save_errno = errno;
898                 close(s);
899                 errno = save_errno;
900                 return -1;
901         }
902         return s;
903
904 }
905
906 /*
907  * unix_listen()
908  * Create a unix domain socket, and listen on it.
909  */
910 int
911 unix_listen(char *path)
912 {
913         int s;
914
915         if ((s = unix_bind(path, 0)) < 0)
916                 return -1;
917         if (listen(s, 5) < 0) {
918                 close(s);
919                 return -1;
920         }
921         if (vflag)
922                 report_sock("Listening", NULL, 0, path);
923
924         return s;
925 }
926
927 /*
928  * remote_connect()
929  * Returns a socket connected to a remote host. Properly binds to a local
930  * port or source address if needed. Returns -1 on failure.
931  */
932 int
933 remote_connect(const char *host, const char *port, struct addrinfo hints)
934 {
935         struct addrinfo *res, *res0;
936         int s = -1, error, save_errno;
937 #ifdef SO_BINDANY
938         int on = 1;
939 #endif
940
941         if ((error = getaddrinfo(host, port, &hints, &res0)))
942                 errx(1, "getaddrinfo for host \"%s\" port %s: %s", host,
943                     port, gai_strerror(error));
944
945         for (res = res0; res; res = res->ai_next) {
946                 if ((s = socket(res->ai_family, res->ai_socktype |
947                     SOCK_NONBLOCK, res->ai_protocol)) < 0)
948                         continue;
949
950                 /* Bind to a local port or source address if specified. */
951                 if (sflag || pflag) {
952                         struct addrinfo ahints, *ares;
953
954 #ifdef SO_BINDANY
955                         /* try SO_BINDANY, but don't insist */
956                         setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
957 #endif
958                         memset(&ahints, 0, sizeof(struct addrinfo));
959                         ahints.ai_family = res->ai_family;
960                         ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
961                         ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
962                         ahints.ai_flags = AI_PASSIVE;
963                         if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
964                                 errx(1, "getaddrinfo: %s", gai_strerror(error));
965
966                         if (bind(s, (struct sockaddr *)ares->ai_addr,
967                             ares->ai_addrlen) < 0)
968                                 err(1, "bind failed");
969                         freeaddrinfo(ares);
970                 }
971
972                 set_common_sockopts(s, res->ai_family);
973
974                 if (timeout_connect(s, res->ai_addr, res->ai_addrlen) == 0)
975                         break;
976                 if (vflag)
977                         warn("connect to %s port %s (%s) failed", host, port,
978                             uflag ? "udp" : "tcp");
979
980                 save_errno = errno;
981                 close(s);
982                 errno = save_errno;
983                 s = -1;
984         }
985
986         freeaddrinfo(res0);
987
988         return s;
989 }
990
991 int
992 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
993 {
994         struct pollfd pfd;
995         socklen_t optlen;
996         int optval;
997         int ret;
998
999         if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
1000                 pfd.fd = s;
1001                 pfd.events = POLLOUT;
1002                 if ((ret = poll(&pfd, 1, timeout)) == 1) {
1003                         optlen = sizeof(optval);
1004                         if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
1005                             &optval, &optlen)) == 0) {
1006                                 errno = optval;
1007                                 ret = optval == 0 ? 0 : -1;
1008                         }
1009                 } else if (ret == 0) {
1010                         errno = ETIMEDOUT;
1011                         ret = -1;
1012                 } else
1013                         err(1, "poll failed");
1014         }
1015
1016         return ret;
1017 }
1018
1019 /*
1020  * local_listen()
1021  * Returns a socket listening on a local port, binds to specified source
1022  * address. Returns -1 on failure.
1023  */
1024 int
1025 local_listen(const char *host, const char *port, struct addrinfo hints)
1026 {
1027         struct addrinfo *res, *res0;
1028         int s = -1, save_errno;
1029 #ifdef SO_REUSEPORT
1030         int ret, x = 1;
1031 #endif
1032         int error;
1033
1034         /* Allow nodename to be null. */
1035         hints.ai_flags |= AI_PASSIVE;
1036
1037         /*
1038          * In the case of binding to a wildcard address
1039          * default to binding to an ipv4 address.
1040          */
1041         if (host == NULL && hints.ai_family == AF_UNSPEC)
1042                 hints.ai_family = AF_INET;
1043
1044         if ((error = getaddrinfo(host, port, &hints, &res0)))
1045                 errx(1, "getaddrinfo: %s", gai_strerror(error));
1046
1047         for (res = res0; res; res = res->ai_next) {
1048                 if ((s = socket(res->ai_family, res->ai_socktype,
1049                     res->ai_protocol)) < 0)
1050                         continue;
1051
1052 #ifdef SO_REUSEPORT
1053                 ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
1054                 if (ret == -1)
1055                         err(1, NULL);
1056 #endif
1057
1058                 set_common_sockopts(s, res->ai_family);
1059
1060                 if (bind(s, (struct sockaddr *)res->ai_addr,
1061                     res->ai_addrlen) == 0)
1062                         break;
1063
1064                 save_errno = errno;
1065                 close(s);
1066                 errno = save_errno;
1067                 s = -1;
1068         }
1069
1070         if (!uflag && s != -1) {
1071                 if (listen(s, 1) < 0)
1072                         err(1, "listen");
1073         }
1074         if (vflag && s != -1) {
1075                 struct sockaddr_storage ss;
1076                 socklen_t len;
1077
1078                 len = sizeof(ss);
1079                 if (getsockname(s, (struct sockaddr *)&ss, &len) == -1)
1080                         err(1, "getsockname");
1081                 report_sock(uflag ? "Bound" : "Listening",
1082                     (struct sockaddr *)&ss, len, NULL);
1083         }
1084
1085         freeaddrinfo(res0);
1086
1087         return s;
1088 }
1089
1090 /*
1091  * readwrite()
1092  * Loop that polls on the network file descriptor and stdin.
1093  */
1094 void
1095 readwrite(int net_fd, struct tls *tls_ctx)
1096 {
1097         struct pollfd pfd[4];
1098         int stdin_fd = STDIN_FILENO;
1099         int stdout_fd = STDOUT_FILENO;
1100         unsigned char netinbuf[BUFSIZE];
1101         size_t netinbufpos = 0;
1102         unsigned char stdinbuf[BUFSIZE];
1103         size_t stdinbufpos = 0;
1104         int n, num_fds;
1105         ssize_t ret;
1106
1107         /* don't read from stdin if requested */
1108         if (dflag)
1109                 stdin_fd = -1;
1110
1111         /* stdin */
1112         pfd[POLL_STDIN].fd = stdin_fd;
1113         pfd[POLL_STDIN].events = POLLIN;
1114
1115         /* network out */
1116         pfd[POLL_NETOUT].fd = net_fd;
1117         pfd[POLL_NETOUT].events = 0;
1118
1119         /* network in */
1120         pfd[POLL_NETIN].fd = net_fd;
1121         pfd[POLL_NETIN].events = POLLIN;
1122
1123         /* stdout */
1124         pfd[POLL_STDOUT].fd = stdout_fd;
1125         pfd[POLL_STDOUT].events = 0;
1126
1127         while (1) {
1128                 /* both inputs are gone, buffers are empty, we are done */
1129                 if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
1130                     stdinbufpos == 0 && netinbufpos == 0)
1131                         return;
1132                 /* both outputs are gone, we can't continue */
1133                 if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1)
1134                         return;
1135                 /* listen and net in gone, queues empty, done */
1136                 if (lflag && pfd[POLL_NETIN].fd == -1 &&
1137                     stdinbufpos == 0 && netinbufpos == 0)
1138                         return;
1139
1140                 /* help says -i is for "wait between lines sent". We read and
1141                  * write arbitrary amounts of data, and we don't want to start
1142                  * scanning for newlines, so this is as good as it gets */
1143                 if (iflag)
1144                         sleep(iflag);
1145
1146                 /* poll */
1147                 num_fds = poll(pfd, 4, timeout);
1148
1149                 /* treat poll errors */
1150                 if (num_fds == -1)
1151                         err(1, "polling error");
1152
1153                 /* timeout happened */
1154                 if (num_fds == 0)
1155                         return;
1156
1157                 /* treat socket error conditions */
1158                 for (n = 0; n < 4; n++) {
1159                         if (pfd[n].revents & (POLLERR|POLLNVAL)) {
1160                                 pfd[n].fd = -1;
1161                         }
1162                 }
1163                 /* reading is possible after HUP */
1164                 if (pfd[POLL_STDIN].events & POLLIN &&
1165                     pfd[POLL_STDIN].revents & POLLHUP &&
1166                     !(pfd[POLL_STDIN].revents & POLLIN))
1167                         pfd[POLL_STDIN].fd = -1;
1168
1169                 if (pfd[POLL_NETIN].events & POLLIN &&
1170                     pfd[POLL_NETIN].revents & POLLHUP &&
1171                     !(pfd[POLL_NETIN].revents & POLLIN))
1172                         pfd[POLL_NETIN].fd = -1;
1173
1174                 if (pfd[POLL_NETOUT].revents & POLLHUP) {
1175                         if (Nflag)
1176                                 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1177                         pfd[POLL_NETOUT].fd = -1;
1178                 }
1179                 /* if HUP, stop watching stdout */
1180                 if (pfd[POLL_STDOUT].revents & POLLHUP)
1181                         pfd[POLL_STDOUT].fd = -1;
1182                 /* if no net out, stop watching stdin */
1183                 if (pfd[POLL_NETOUT].fd == -1)
1184                         pfd[POLL_STDIN].fd = -1;
1185                 /* if no stdout, stop watching net in */
1186                 if (pfd[POLL_STDOUT].fd == -1) {
1187                         if (pfd[POLL_NETIN].fd != -1)
1188                                 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1189                         pfd[POLL_NETIN].fd = -1;
1190                 }
1191
1192                 /* try to read from stdin */
1193                 if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
1194                         ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
1195                             &stdinbufpos, NULL);
1196                         if (ret == TLS_WANT_POLLIN)
1197                                 pfd[POLL_STDIN].events = POLLIN;
1198                         else if (ret == TLS_WANT_POLLOUT)
1199                                 pfd[POLL_STDIN].events = POLLOUT;
1200                         else if (ret == 0 || ret == -1)
1201                                 pfd[POLL_STDIN].fd = -1;
1202                         /* read something - poll net out */
1203                         if (stdinbufpos > 0)
1204                                 pfd[POLL_NETOUT].events = POLLOUT;
1205                         /* filled buffer - remove self from polling */
1206                         if (stdinbufpos == BUFSIZE)
1207                                 pfd[POLL_STDIN].events = 0;
1208                 }
1209                 /* try to write to network */
1210                 if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
1211                         ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
1212                             &stdinbufpos, tls_ctx);
1213                         if (ret == TLS_WANT_POLLIN)
1214                                 pfd[POLL_NETOUT].events = POLLIN;
1215                         else if (ret == TLS_WANT_POLLOUT)
1216                                 pfd[POLL_NETOUT].events = POLLOUT;
1217                         else if (ret == -1)
1218                                 pfd[POLL_NETOUT].fd = -1;
1219                         /* buffer empty - remove self from polling */
1220                         if (stdinbufpos == 0)
1221                                 pfd[POLL_NETOUT].events = 0;
1222                         /* buffer no longer full - poll stdin again */
1223                         if (stdinbufpos < BUFSIZE)
1224                                 pfd[POLL_STDIN].events = POLLIN;
1225                 }
1226                 /* try to read from network */
1227                 if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
1228                         ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
1229                             &netinbufpos, tls_ctx);
1230                         if (ret == TLS_WANT_POLLIN)
1231                                 pfd[POLL_NETIN].events = POLLIN;
1232                         else if (ret == TLS_WANT_POLLOUT)
1233                                 pfd[POLL_NETIN].events = POLLOUT;
1234                         else if (ret == -1)
1235                                 pfd[POLL_NETIN].fd = -1;
1236                         /* eof on net in - remove from pfd */
1237                         if (ret == 0) {
1238                                 shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1239                                 pfd[POLL_NETIN].fd = -1;
1240                         }
1241                         if (recvlimit > 0 && ++recvcount >= recvlimit) {
1242                                 if (pfd[POLL_NETIN].fd != -1)
1243                                         shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
1244                                 pfd[POLL_NETIN].fd = -1;
1245                                 pfd[POLL_STDIN].fd = -1;
1246                         }
1247                         /* read something - poll stdout */
1248                         if (netinbufpos > 0)
1249                                 pfd[POLL_STDOUT].events = POLLOUT;
1250                         /* filled buffer - remove self from polling */
1251                         if (netinbufpos == BUFSIZE)
1252                                 pfd[POLL_NETIN].events = 0;
1253                         /* handle telnet */
1254                         if (tflag)
1255                                 atelnet(pfd[POLL_NETIN].fd, netinbuf,
1256                                     netinbufpos);
1257                 }
1258                 /* try to write to stdout */
1259                 if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
1260                         ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
1261                             &netinbufpos, NULL);
1262                         if (ret == TLS_WANT_POLLIN)
1263                                 pfd[POLL_STDOUT].events = POLLIN;
1264                         else if (ret == TLS_WANT_POLLOUT)
1265                                 pfd[POLL_STDOUT].events = POLLOUT;
1266                         else if (ret == -1)
1267                                 pfd[POLL_STDOUT].fd = -1;
1268                         /* buffer empty - remove self from polling */
1269                         if (netinbufpos == 0)
1270                                 pfd[POLL_STDOUT].events = 0;
1271                         /* buffer no longer full - poll net in again */
1272                         if (netinbufpos < BUFSIZE)
1273                                 pfd[POLL_NETIN].events = POLLIN;
1274                 }
1275
1276                 /* stdin gone and queue empty? */
1277                 if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1278                         if (pfd[POLL_NETOUT].fd != -1 && Nflag)
1279                                 shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1280                         pfd[POLL_NETOUT].fd = -1;
1281                 }
1282                 /* net in gone and queue empty? */
1283                 if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1284                         pfd[POLL_STDOUT].fd = -1;
1285                 }
1286         }
1287 }
1288
1289 ssize_t
1290 drainbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1291 {
1292         ssize_t n;
1293         ssize_t adjust;
1294
1295         if (tls) {
1296                 n = tls_write(tls, buf, *bufpos);
1297                 if (n == -1)
1298                         errx(1, "tls write failed (%s)", tls_error(tls));
1299         } else {
1300                 n = write(fd, buf, *bufpos);
1301                 /* don't treat EAGAIN, EINTR as error */
1302                 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1303                         n = TLS_WANT_POLLOUT;
1304         }
1305         if (n <= 0)
1306                 return n;
1307         /* adjust buffer */
1308         adjust = *bufpos - n;
1309         if (adjust > 0)
1310                 memmove(buf, buf + n, adjust);
1311         *bufpos -= n;
1312         return n;
1313 }
1314
1315 ssize_t
1316 fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
1317 {
1318         size_t num = BUFSIZE - *bufpos;
1319         ssize_t n;
1320
1321         if (tls) {
1322                 n = tls_read(tls, buf + *bufpos, num);
1323                 if (n == -1)
1324                         errx(1, "tls read failed (%s)", tls_error(tls));
1325         } else {
1326                 n = read(fd, buf + *bufpos, num);
1327                 /* don't treat EAGAIN, EINTR as error */
1328                 if (n == -1 && (errno == EAGAIN || errno == EINTR))
1329                         n = TLS_WANT_POLLIN;
1330         }
1331         if (n <= 0)
1332                 return n;
1333         *bufpos += n;
1334         return n;
1335 }
1336
1337 /*
1338  * fdpass()
1339  * Pass the connected file descriptor to stdout and exit.
1340  */
1341 void
1342 fdpass(int nfd)
1343 {
1344         struct msghdr mh;
1345         union {
1346                 struct cmsghdr hdr;
1347                 char buf[CMSG_SPACE(sizeof(int))];
1348         } cmsgbuf;
1349         struct cmsghdr *cmsg;
1350         struct iovec iov;
1351         char c = '\0';
1352         ssize_t r;
1353         struct pollfd pfd;
1354
1355         /* Avoid obvious stupidity */
1356         if (isatty(STDOUT_FILENO))
1357                 errx(1, "Cannot pass file descriptor to tty");
1358
1359         memset(&mh, 0, sizeof(mh));
1360         memset(&cmsgbuf, 0, sizeof(cmsgbuf));
1361         memset(&iov, 0, sizeof(iov));
1362
1363         mh.msg_control = (caddr_t)&cmsgbuf.buf;
1364         mh.msg_controllen = sizeof(cmsgbuf.buf);
1365         cmsg = CMSG_FIRSTHDR(&mh);
1366         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1367         cmsg->cmsg_level = SOL_SOCKET;
1368         cmsg->cmsg_type = SCM_RIGHTS;
1369         *(int *)CMSG_DATA(cmsg) = nfd;
1370
1371         iov.iov_base = &c;
1372         iov.iov_len = 1;
1373         mh.msg_iov = &iov;
1374         mh.msg_iovlen = 1;
1375
1376         memset(&pfd, 0, sizeof(pfd));
1377         pfd.fd = STDOUT_FILENO;
1378         pfd.events = POLLOUT;
1379         for (;;) {
1380                 r = sendmsg(STDOUT_FILENO, &mh, 0);
1381                 if (r == -1) {
1382                         if (errno == EAGAIN || errno == EINTR) {
1383                                 if (poll(&pfd, 1, -1) == -1)
1384                                         err(1, "poll");
1385                                 continue;
1386                         }
1387                         err(1, "sendmsg");
1388                 } else if (r != 1)
1389                         errx(1, "sendmsg: unexpected return value %zd", r);
1390                 else
1391                         break;
1392         }
1393         exit(0);
1394 }
1395
1396 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1397 void
1398 atelnet(int nfd, unsigned char *buf, unsigned int size)
1399 {
1400         unsigned char *p, *end;
1401         unsigned char obuf[4];
1402
1403         if (size < 3)
1404                 return;
1405         end = buf + size - 2;
1406
1407         for (p = buf; p < end; p++) {
1408                 if (*p != IAC)
1409                         continue;
1410
1411                 obuf[0] = IAC;
1412                 p++;
1413                 if ((*p == WILL) || (*p == WONT))
1414                         obuf[1] = DONT;
1415                 else if ((*p == DO) || (*p == DONT))
1416                         obuf[1] = WONT;
1417                 else
1418                         continue;
1419
1420                 p++;
1421                 obuf[2] = *p;
1422                 if (atomicio(vwrite, nfd, obuf, 3) != 3)
1423                         warn("Write Error!");
1424         }
1425 }
1426
1427
1428 int
1429 strtoport(char *portstr, int udp)
1430 {
1431         struct servent *entry;
1432         const char *errstr;
1433         char *proto;
1434         int port = -1;
1435
1436         proto = udp ? "udp" : "tcp";
1437
1438         port = strtonum(portstr, 1, PORT_MAX, &errstr);
1439         if (errstr == NULL)
1440                 return port;
1441         if (errno != EINVAL)
1442                 errx(1, "port number %s: %s", errstr, portstr);
1443         if ((entry = getservbyname(portstr, proto)) == NULL)
1444                 errx(1, "service \"%s\" unknown", portstr);
1445         return ntohs(entry->s_port);
1446 }
1447
1448 /*
1449  * build_ports()
1450  * Build an array of ports in portlist[], listing each port
1451  * that we should try to connect to.
1452  */
1453 void
1454 build_ports(char *p)
1455 {
1456         char *n;
1457         int hi, lo, cp;
1458         int x = 0;
1459
1460         if (isdigit((unsigned char)*p) && (n = strchr(p, '-')) != NULL) {
1461                 *n = '\0';
1462                 n++;
1463
1464                 /* Make sure the ports are in order: lowest->highest. */
1465                 hi = strtoport(n, uflag);
1466                 lo = strtoport(p, uflag);
1467                 if (lo > hi) {
1468                         cp = hi;
1469                         hi = lo;
1470                         lo = cp;
1471                 }
1472
1473                 /*
1474                  * Initialize portlist with a random permutation.  Based on
1475                  * Knuth, as in ip_randomid() in sys/netinet/ip_id.c.
1476                  */
1477                 if (rflag) {
1478                         for (x = 0; x <= hi - lo; x++) {
1479                                 cp = arc4random_uniform(x + 1);
1480                                 portlist[x] = portlist[cp];
1481                                 if (asprintf(&portlist[cp], "%d", x + lo) < 0)
1482                                         err(1, "asprintf");
1483                         }
1484                 } else { /* Load ports sequentially. */
1485                         for (cp = lo; cp <= hi; cp++) {
1486                                 if (asprintf(&portlist[x], "%d", cp) < 0)
1487                                         err(1, "asprintf");
1488                                 x++;
1489                         }
1490                 }
1491         } else {
1492                 char *tmp;
1493
1494                 hi = strtoport(p, uflag);
1495                 if (asprintf(&tmp, "%d", hi) != -1)
1496                         portlist[0] = tmp;
1497                 else
1498                         err(1, NULL);
1499         }
1500 }
1501
1502 /*
1503  * udptest()
1504  * Do a few writes to see if the UDP port is there.
1505  * Fails once PF state table is full.
1506  */
1507 int
1508 udptest(int s)
1509 {
1510         int i, ret;
1511
1512         for (i = 0; i <= 3; i++) {
1513                 if (write(s, "X", 1) == 1)
1514                         ret = 1;
1515                 else
1516                         ret = -1;
1517         }
1518         return ret;
1519 }
1520
1521 void
1522 set_common_sockopts(int s, int af)
1523 {
1524         int x = 1;
1525
1526 #ifdef TCP_MD5SIG
1527         if (Sflag) {
1528                 if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1529                         &x, sizeof(x)) == -1)
1530                         err(1, NULL);
1531         }
1532 #endif
1533         if (Dflag) {
1534                 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1535                         &x, sizeof(x)) == -1)
1536                         err(1, NULL);
1537         }
1538         if (Tflag != -1) {
1539                 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1540                     IP_TOS, &Tflag, sizeof(Tflag)) == -1)
1541                         err(1, "set IP ToS");
1542
1543 #ifdef IPV6_TCLASS
1544                 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1545                     IPV6_TCLASS, &Tflag, sizeof(Tflag)) == -1)
1546                         err(1, "set IPv6 traffic class");
1547 #else
1548                 else if (af == AF_INET6) {
1549                         errno = ENOPROTOOPT;
1550                         err(1, "set IPv6 traffic class not supported");
1551                 }
1552 #endif
1553         }
1554         if (Iflag) {
1555                 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1556                     &Iflag, sizeof(Iflag)) == -1)
1557                         err(1, "set TCP receive buffer size");
1558         }
1559         if (Oflag) {
1560                 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1561                     &Oflag, sizeof(Oflag)) == -1)
1562                         err(1, "set TCP send buffer size");
1563         }
1564
1565         if (ttl != -1) {
1566                 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1567                     IP_TTL, &ttl, sizeof(ttl)))
1568                         err(1, "set IP TTL");
1569
1570                 else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1571                     IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)))
1572                         err(1, "set IPv6 unicast hops");
1573         }
1574
1575         if (minttl != -1) {
1576 #ifdef IP_MINTTL
1577                 if (af == AF_INET && setsockopt(s, IPPROTO_IP,
1578                     IP_MINTTL, &minttl, sizeof(minttl)))
1579                         err(1, "set IP min TTL");
1580 #endif
1581
1582 #ifdef IPV6_MINHOPCOUNT
1583                 if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
1584                     IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)))
1585                         err(1, "set IPv6 min hop count");
1586 #endif
1587         }
1588 }
1589
1590 int
1591 process_tos_opt(char *s, int *val)
1592 {
1593         /* DiffServ Codepoints and other TOS mappings */
1594         const struct toskeywords {
1595                 const char      *keyword;
1596                 int              val;
1597         } *t, toskeywords[] = {
1598                 { "af11",               IPTOS_DSCP_AF11 },
1599                 { "af12",               IPTOS_DSCP_AF12 },
1600                 { "af13",               IPTOS_DSCP_AF13 },
1601                 { "af21",               IPTOS_DSCP_AF21 },
1602                 { "af22",               IPTOS_DSCP_AF22 },
1603                 { "af23",               IPTOS_DSCP_AF23 },
1604                 { "af31",               IPTOS_DSCP_AF31 },
1605                 { "af32",               IPTOS_DSCP_AF32 },
1606                 { "af33",               IPTOS_DSCP_AF33 },
1607                 { "af41",               IPTOS_DSCP_AF41 },
1608                 { "af42",               IPTOS_DSCP_AF42 },
1609                 { "af43",               IPTOS_DSCP_AF43 },
1610                 { "critical",           IPTOS_PREC_CRITIC_ECP },
1611                 { "cs0",                IPTOS_DSCP_CS0 },
1612                 { "cs1",                IPTOS_DSCP_CS1 },
1613                 { "cs2",                IPTOS_DSCP_CS2 },
1614                 { "cs3",                IPTOS_DSCP_CS3 },
1615                 { "cs4",                IPTOS_DSCP_CS4 },
1616                 { "cs5",                IPTOS_DSCP_CS5 },
1617                 { "cs6",                IPTOS_DSCP_CS6 },
1618                 { "cs7",                IPTOS_DSCP_CS7 },
1619                 { "ef",                 IPTOS_DSCP_EF },
1620                 { "inetcontrol",        IPTOS_PREC_INTERNETCONTROL },
1621                 { "lowdelay",           IPTOS_LOWDELAY },
1622                 { "netcontrol",         IPTOS_PREC_NETCONTROL },
1623                 { "reliability",        IPTOS_RELIABILITY },
1624                 { "throughput",         IPTOS_THROUGHPUT },
1625                 { NULL,                 -1 },
1626         };
1627
1628         for (t = toskeywords; t->keyword != NULL; t++) {
1629                 if (strcmp(s, t->keyword) == 0) {
1630                         *val = t->val;
1631                         return 1;
1632                 }
1633         }
1634
1635         return 0;
1636 }
1637
1638 int
1639 process_tls_opt(char *s, int *flags)
1640 {
1641         size_t len;
1642         char *v;
1643
1644         const struct tlskeywords {
1645                 const char      *keyword;
1646                 int              flag;
1647                 char            **value;
1648         } *t, tlskeywords[] = {
1649                 { "ciphers",            -1,                     &tls_ciphers },
1650                 { "clientcert",         TLS_CCERT,              NULL },
1651                 { "muststaple",         TLS_MUSTSTAPLE,         NULL },
1652                 { "noverify",           TLS_NOVERIFY,           NULL },
1653                 { "noname",             TLS_NONAME,             NULL },
1654                 { "protocols",          -1,                     &tls_protocols },
1655                 { NULL,                 -1,                     NULL },
1656         };
1657
1658         len = strlen(s);
1659         if ((v = strchr(s, '=')) != NULL) {
1660                 len = v - s;
1661                 v++;
1662         }
1663
1664         for (t = tlskeywords; t->keyword != NULL; t++) {
1665                 if (strlen(t->keyword) == len &&
1666                     strncmp(s, t->keyword, len) == 0) {
1667                         if (t->value != NULL) {
1668                                 if (v == NULL)
1669                                         errx(1, "invalid tls value `%s'", s);
1670                                 *t->value = v;
1671                         } else {
1672                                 *flags |= t->flag;
1673                         }
1674                         return 1;
1675                 }
1676         }
1677         return 0;
1678 }
1679
1680 void
1681 save_peer_cert(struct tls *tls_ctx, FILE *fp)
1682 {
1683         const char *pem;
1684         size_t plen;
1685
1686         if ((pem = tls_peer_cert_chain_pem(tls_ctx, &plen)) == NULL)
1687                 errx(1, "Can't get peer certificate");
1688         if (fprintf(fp, "%.*s", (int)plen, pem) < 0)
1689                 err(1, "unable to save peer cert");
1690         if (fflush(fp) != 0)
1691                 err(1, "unable to flush peer cert");
1692 }
1693
1694 void
1695 report_tls(struct tls * tls_ctx, char * host)
1696 {
1697         time_t t;
1698         const char *ocsp_url;
1699
1700         fprintf(stderr, "TLS handshake negotiated %s/%s with host %s\n",
1701             tls_conn_version(tls_ctx), tls_conn_cipher(tls_ctx), host);
1702         fprintf(stderr, "Peer name: %s\n",
1703             tls_expectname ? tls_expectname : host);
1704         if (tls_peer_cert_subject(tls_ctx))
1705                 fprintf(stderr, "Subject: %s\n",
1706                     tls_peer_cert_subject(tls_ctx));
1707         if (tls_peer_cert_issuer(tls_ctx))
1708                 fprintf(stderr, "Issuer: %s\n",
1709                     tls_peer_cert_issuer(tls_ctx));
1710         if ((t = tls_peer_cert_notbefore(tls_ctx)) != -1)
1711                 fprintf(stderr, "Valid From: %s", ctime(&t));
1712         if ((t = tls_peer_cert_notafter(tls_ctx)) != -1)
1713                 fprintf(stderr, "Valid Until: %s", ctime(&t));
1714         if (tls_peer_cert_hash(tls_ctx))
1715                 fprintf(stderr, "Cert Hash: %s\n",
1716                     tls_peer_cert_hash(tls_ctx));
1717         ocsp_url = tls_peer_ocsp_url(tls_ctx);
1718         if (ocsp_url != NULL)
1719                 fprintf(stderr, "OCSP URL: %s\n", ocsp_url);
1720         switch (tls_peer_ocsp_response_status(tls_ctx)) {
1721         case TLS_OCSP_RESPONSE_SUCCESSFUL:
1722                 fprintf(stderr, "OCSP Stapling: %s\n",
1723                     tls_peer_ocsp_result(tls_ctx) == NULL ?  "" :
1724                     tls_peer_ocsp_result(tls_ctx));
1725                 fprintf(stderr,
1726                     "  response_status=%d cert_status=%d crl_reason=%d\n",
1727                     tls_peer_ocsp_response_status(tls_ctx),
1728                     tls_peer_ocsp_cert_status(tls_ctx),
1729                     tls_peer_ocsp_crl_reason(tls_ctx));
1730                 t = tls_peer_ocsp_this_update(tls_ctx);
1731                 fprintf(stderr, "  this update: %s",
1732                     t != -1 ? ctime(&t) : "\n");
1733                 t =  tls_peer_ocsp_next_update(tls_ctx);
1734                 fprintf(stderr, "  next update: %s",
1735                     t != -1 ? ctime(&t) : "\n");
1736                 t =  tls_peer_ocsp_revocation_time(tls_ctx);
1737                 fprintf(stderr, "  revocation: %s",
1738                     t != -1 ? ctime(&t) : "\n");
1739                 break;
1740         case -1:
1741                 break;
1742         default:
1743                 fprintf(stderr, "OCSP Stapling:  failure - response_status %d (%s)\n",
1744                     tls_peer_ocsp_response_status(tls_ctx),
1745                     tls_peer_ocsp_result(tls_ctx) == NULL ?  "" :
1746                     tls_peer_ocsp_result(tls_ctx));
1747                 break;
1748
1749         }
1750 }
1751
1752 void
1753 report_sock(const char *msg, const struct sockaddr *sa, socklen_t salen,
1754     char *path)
1755 {
1756         char host[NI_MAXHOST], port[NI_MAXSERV];
1757         int herr;
1758         int flags = NI_NUMERICSERV;
1759
1760         if (path != NULL) {
1761                 fprintf(stderr, "%s on %s\n", msg, path);
1762                 return;
1763         }
1764
1765         if (nflag)
1766                 flags |= NI_NUMERICHOST;
1767
1768         if ((herr = getnameinfo(sa, salen, host, sizeof(host),
1769             port, sizeof(port), flags)) != 0) {
1770                 if (herr == EAI_SYSTEM)
1771                         err(1, "getnameinfo");
1772                 else
1773                         errx(1, "getnameinfo: %s", gai_strerror(herr));
1774         }
1775
1776         fprintf(stderr, "%s on %s %s\n", msg, host, port);
1777 }
1778
1779 void
1780 help(void)
1781 {
1782         usage(0);
1783         fprintf(stderr, "\tCommand Summary:\n\
1784         \t-4            Use IPv4\n\
1785         \t-6            Use IPv6\n\
1786         \t-C certfile   Public key file\n\
1787         \t-c            Use TLS\n\
1788         \t-D            Enable the debug socket option\n\
1789         \t-d            Detach from stdin\n\
1790         \t-e name\t     Required name in peer certificate\n\
1791         \t-F            Pass socket fd\n\
1792         \t-H hash\t     Hash string of peer certificate\n\
1793         \t-h            This help text\n\
1794         \t-I length     TCP receive buffer length\n\
1795         \t-i interval   Delay interval for lines sent, ports scanned\n\
1796         \t-K keyfile    Private key file\n\
1797         \t-k            Keep inbound sockets open for multiple connects\n\
1798         \t-l            Listen mode, for inbound connects\n\
1799         \t-M ttl                Outgoing TTL / Hop Limit\n\
1800         \t-m minttl     Minimum incoming TTL / Hop Limit\n\
1801         \t-N            Shutdown the network socket after EOF on stdin\n\
1802         \t-n            Suppress name/port resolutions\n\
1803         \t-O length     TCP send buffer length\n\
1804         \t-o staplefile Staple file\n\
1805         \t-P proxyuser\tUsername for proxy authentication\n\
1806         \t-p port\t     Specify local port for remote connects\n\
1807         \t-R CAfile     CA bundle\n\
1808         \t-r            Randomize remote ports\n"
1809 #ifdef TCP_MD5SIG
1810         "\
1811         \t-S            Enable the TCP MD5 signature option\n"
1812 #endif
1813         "\
1814         \t-s source     Local source address\n\
1815         \t-T keyword    TOS value or TLS options\n\
1816         \t-t            Answer TELNET negotiation\n\
1817         \t-U            Use UNIX domain socket\n\
1818         \t-u            UDP mode\n"
1819 #ifdef SO_RTABLE
1820         "\
1821         \t-V rtable     Specify alternate routing table\n"
1822 #endif
1823         "\
1824         \t-v            Verbose\n\
1825         \t-W recvlimit  Terminate after receiving a number of packets\n\
1826         \t-w timeout    Timeout for connects and final net reads\n\
1827         \t-X proto      Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1828         \t-x addr[:port]\tSpecify proxy address and port\n\
1829         \t-Z            Peer certificate file\n\
1830         \t-z            Zero-I/O mode [used for scanning]\n\
1831         Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1832         exit(1);
1833 }
1834
1835 void
1836 usage(int ret)
1837 {
1838         fprintf(stderr,
1839             "usage: nc [-46cDdFhklNnrStUuvz] [-C certfile] [-e name] "
1840             "[-H hash] [-I length]\n"
1841             "\t  [-i interval] [-K keyfile] [-M ttl] [-m minttl] [-O length]\n"
1842             "\t  [-o staplefile] [-P proxy_username] [-p source_port] "
1843             "[-R CAfile]\n"
1844             "\t  [-s source] [-T keyword] [-V rtable] [-W recvlimit] "
1845             "[-w timeout]\n"
1846             "\t  [-X proxy_protocol] [-x proxy_address[:port]] "
1847             "[-Z peercertfile]\n"
1848             "\t  [destination] [port]\n");
1849         if (ret)
1850                 exit(1);
1851 }