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

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