[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.206

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