[BACK]Return to netcat.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / nc

Annotation of src/usr.bin/nc/netcat.c, Revision 1.219

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