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

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