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

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