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

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