[BACK]Return to ssh-keyscan.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/ssh-keyscan.c, Revision 1.156

1.156   ! tobias      1: /* $OpenBSD: ssh-keyscan.c,v 1.155 2024/01/11 01:45:36 djm Exp $ */
1.1       markus      2: /*
                      3:  * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
                      4:  *
                      5:  * Modification and redistribution in source and binary forms is
                      6:  * permitted provided that due credit is given to the author and the
1.23      pvalchev    7:  * OpenBSD project by leaving this copyright notice intact.
1.1       markus      8:  */
                      9:
1.65      stevesk    10: #include <sys/types.h>
                     11: #include <sys/socket.h>
1.1       markus     12: #include <sys/queue.h>
1.74      djm        13: #include <sys/time.h>
1.59      stevesk    14: #include <sys/resource.h>
1.58      stevesk    15:
1.130     djm        16: #ifdef WITH_OPENSSL
1.69      stevesk    17: #include <openssl/bn.h>
1.130     djm        18: #endif
1.69      stevesk    19:
1.1       markus     20: #include <errno.h>
1.153     djm        21: #include <limits.h>
1.67      stevesk    22: #include <netdb.h>
1.66      stevesk    23: #include <stdarg.h>
1.72      stevesk    24: #include <stdio.h>
1.71      stevesk    25: #include <stdlib.h>
1.141     deraadt    26: #include <poll.h>
1.73      deraadt    27: #include <signal.h>
1.69      stevesk    28: #include <string.h>
1.68      stevesk    29: #include <unistd.h>
1.1       markus     30:
                     31: #include "xmalloc.h"
                     32: #include "ssh.h"
1.95      markus     33: #include "sshbuf.h"
                     34: #include "sshkey.h"
1.73      deraadt    35: #include "cipher.h"
1.150     djm        36: #include "digest.h"
1.26      markus     37: #include "kex.h"
                     38: #include "compat.h"
                     39: #include "myproposal.h"
                     40: #include "packet.h"
                     41: #include "dispatch.h"
1.11      markus     42: #include "log.h"
1.18      deraadt    43: #include "atomicio.h"
1.26      markus     44: #include "misc.h"
1.51      djm        45: #include "hostfile.h"
1.95      markus     46: #include "ssherr.h"
                     47: #include "ssh_api.h"
1.117     djm        48: #include "dns.h"
1.147     djm        49: #include "addr.h"
1.1       markus     50:
1.26      markus     51: /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
                     52:    Default value is AF_UNSPEC means both IPv4 and IPv6. */
                     53: int IPv4or6 = AF_UNSPEC;
                     54:
                     55: int ssh_port = SSH_DEFAULT_PORT;
1.1       markus     56:
1.112     djm        57: #define KT_DSA         (1)
                     58: #define KT_RSA         (1<<1)
                     59: #define KT_ECDSA       (1<<2)
                     60: #define KT_ED25519     (1<<3)
1.118     markus     61: #define KT_XMSS                (1<<4)
1.131     djm        62: #define KT_ECDSA_SK    (1<<5)
                     63: #define KT_ED25519_SK  (1<<6)
1.112     djm        64:
                     65: #define KT_MIN         KT_DSA
1.131     djm        66: #define KT_MAX         KT_ED25519_SK
1.26      markus     67:
1.103     djm        68: int get_cert = 0;
1.131     djm        69: int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
1.1       markus     70:
1.51      djm        71: int hash_hosts = 0;            /* Hash hostname on output */
                     72:
1.117     djm        73: int print_sshfp = 0;           /* Print SSHFP records instead of known_hosts */
                     74:
1.126     djm        75: int found_one = 0;             /* Successfully found a key */
                     76:
1.150     djm        77: int hashalg = -1;              /* Hash for SSHFP records or -1 for all */
                     78:
1.1       markus     79: #define MAXMAXFD 256
                     80:
                     81: /* The number of seconds after which to give up on a TCP connection */
                     82: int timeout = 5;
                     83:
                     84: int maxfd;
1.18      deraadt    85: #define MAXCON (maxfd - 10)
1.1       markus     86:
1.3       markus     87: extern char *__progname;
1.141     deraadt    88: struct pollfd *read_wait;
1.1       markus     89: int ncon;
                     90:
                     91: /*
                     92:  * Keep a connection structure for each file descriptor.  The state
                     93:  * associated with file descriptor n is held in fdcon[n].
                     94:  */
                     95: typedef struct Connection {
1.6       markus     96:        u_char c_status;        /* State of connection on this file desc. */
1.1       markus     97: #define CS_UNUSED 0            /* File descriptor unused */
                     98: #define CS_CON 1               /* Waiting to connect/read greeting */
                     99: #define CS_SIZE 2              /* Waiting to read initial packet size */
                    100: #define CS_KEYS 3              /* Waiting to read public key packet */
                    101:        int c_fd;               /* Quick lookup: c->c_fd == c - fdcon */
                    102:        int c_plen;             /* Packet length field for ssh packet */
                    103:        int c_len;              /* Total bytes which must be read. */
                    104:        int c_off;              /* Length of data read so far. */
1.112     djm       105:        int c_keytype;          /* Only one of KT_* */
1.100     miod      106:        sig_atomic_t c_done;    /* SSH2 done */
1.1       markus    107:        char *c_namebase;       /* Address to free for c_name and c_namelist */
                    108:        char *c_name;           /* Hostname of connection for errors */
                    109:        char *c_namelist;       /* Pointer to other possible addresses */
                    110:        char *c_output_name;    /* Hostname of connection for output */
                    111:        char *c_data;           /* Data read from this fd */
1.95      markus    112:        struct ssh *c_ssh;      /* SSH-connection */
1.141     deraadt   113:        struct timespec c_ts;   /* Time at which connection gets aborted */
1.1       markus    114:        TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
                    115: } con;
                    116:
                    117: TAILQ_HEAD(conlist, Connection) tq;    /* Timeout Queue */
                    118: con *fdcon;
                    119:
1.95      markus    120: static void keyprint(con *c, struct sshkey *key);
                    121:
1.24      itojun    122: static int
1.1       markus    123: fdlim_get(int hard)
                    124: {
                    125:        struct rlimit rlfd;
1.17      deraadt   126:
1.128     deraadt   127:        if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
1.1       markus    128:                return (-1);
1.153     djm       129:        if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY ||
                    130:            (hard ? rlfd.rlim_max : rlfd.rlim_cur) > INT_MAX)
1.46      djm       131:                return sysconf(_SC_OPEN_MAX);
1.153     djm       132:        return hard ? rlfd.rlim_max : rlfd.rlim_cur;
1.1       markus    133: }
                    134:
1.24      itojun    135: static int
1.1       markus    136: fdlim_set(int lim)
                    137: {
                    138:        struct rlimit rlfd;
1.39      deraadt   139:
1.1       markus    140:        if (lim <= 0)
                    141:                return (-1);
1.128     deraadt   142:        if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
1.1       markus    143:                return (-1);
                    144:        rlfd.rlim_cur = lim;
1.128     deraadt   145:        if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
1.1       markus    146:                return (-1);
                    147:        return (0);
                    148: }
                    149:
                    150: /*
                    151:  * This is an strsep function that returns a null field for adjacent
                    152:  * separators.  This is the same as the 4.4BSD strsep, but different from the
                    153:  * one in the GNU libc.
                    154:  */
1.24      itojun    155: static char *
1.1       markus    156: xstrsep(char **str, const char *delim)
                    157: {
                    158:        char *s, *e;
                    159:
                    160:        if (!**str)
                    161:                return (NULL);
                    162:
                    163:        s = *str;
                    164:        e = s + strcspn(s, delim);
                    165:
                    166:        if (*e != '\0')
                    167:                *e++ = '\0';
                    168:        *str = e;
                    169:
                    170:        return (s);
                    171: }
                    172:
                    173: /*
                    174:  * Get the next non-null token (like GNU strsep).  Strsep() will return a
                    175:  * null token for two adjacent separators, so we may have to loop.
                    176:  */
1.24      itojun    177: static char *
1.1       markus    178: strnnsep(char **stringp, char *delim)
                    179: {
                    180:        char *tok;
                    181:
                    182:        do {
                    183:                tok = xstrsep(stringp, delim);
                    184:        } while (tok && *tok == '\0');
                    185:        return (tok);
                    186: }
                    187:
1.26      markus    188:
                    189: static int
1.95      markus    190: key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
1.26      markus    191: {
1.95      markus    192:        con *c;
                    193:
                    194:        if ((c = ssh_get_app_data(ssh)) != NULL)
                    195:                keyprint(c, hostkey);
                    196:        /* always abort key exchange */
                    197:        return -1;
1.26      markus    198: }
                    199:
                    200: static int
                    201: ssh2_capable(int remote_major, int remote_minor)
                    202: {
                    203:        switch (remote_major) {
                    204:        case 1:
                    205:                if (remote_minor == 99)
                    206:                        return 1;
                    207:                break;
                    208:        case 2:
                    209:                return 1;
                    210:        default:
                    211:                break;
                    212:        }
                    213:        return 0;
                    214: }
                    215:
1.95      markus    216: static void
1.26      markus    217: keygrab_ssh2(con *c)
                    218: {
1.91      markus    219:        char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
1.95      markus    220:        int r;
1.26      markus    221:
1.103     djm       222:        switch (c->c_keytype) {
                    223:        case KT_DSA:
                    224:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
                    225:                    "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
                    226:                break;
                    227:        case KT_RSA:
                    228:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
1.129     djm       229:                    "rsa-sha2-512-cert-v01@openssh.com,"
                    230:                    "rsa-sha2-256-cert-v01@openssh.com,"
                    231:                    "ssh-rsa-cert-v01@openssh.com" :
                    232:                    "rsa-sha2-512,"
                    233:                    "rsa-sha2-256,"
                    234:                    "ssh-rsa";
1.103     djm       235:                break;
                    236:        case KT_ED25519:
                    237:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
                    238:                    "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
                    239:                break;
1.118     markus    240:        case KT_XMSS:
                    241:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
                    242:                    "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
                    243:                break;
1.103     djm       244:        case KT_ECDSA:
                    245:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
                    246:                    "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
                    247:                    "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
                    248:                    "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
                    249:                    "ecdsa-sha2-nistp256,"
                    250:                    "ecdsa-sha2-nistp384,"
                    251:                    "ecdsa-sha2-nistp521";
                    252:                break;
1.131     djm       253:        case KT_ECDSA_SK:
                    254:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
                    255:                    "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
                    256:                    "sk-ecdsa-sha2-nistp256@openssh.com";
                    257:                break;
                    258:        case KT_ED25519_SK:
                    259:                myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
                    260:                    "sk-ssh-ed25519-cert-v01@openssh.com" :
                    261:                    "sk-ssh-ed25519@openssh.com";
                    262:                break;
1.103     djm       263:        default:
                    264:                fatal("unknown key type %d", c->c_keytype);
                    265:                break;
                    266:        }
1.95      markus    267:        if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
                    268:                free(c->c_ssh);
                    269:                fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
                    270:                exit(1);
                    271:        }
1.92      markus    272: #ifdef WITH_OPENSSL
1.125     djm       273:        c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
                    274:        c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
                    275:        c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
                    276:        c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
                    277:        c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
1.95      markus    278:        c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
                    279:        c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
1.125     djm       280:        c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
1.92      markus    281: #endif
1.125     djm       282:        c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
1.138     djm       283:        c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
1.95      markus    284:        ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
                    285:        /*
                    286:         * do the key-exchange until an error occurs or until
                    287:         * the key_print_wrapper() callback sets c_done.
                    288:         */
1.114     markus    289:        ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
1.26      markus    290: }
                    291:
                    292: static void
1.108     djm       293: keyprint_one(const char *host, struct sshkey *key)
1.26      markus    294: {
1.140     dtucker   295:        char *hostport = NULL, *hashed = NULL;
                    296:        const char *known_host;
1.152     djm       297:        int r = 0;
1.51      djm       298:
1.126     djm       299:        found_one = 1;
                    300:
1.117     djm       301:        if (print_sshfp) {
1.150     djm       302:                export_dns_rr(host, key, stdout, 0, hashalg);
1.117     djm       303:                return;
                    304:        }
                    305:
1.108     djm       306:        hostport = put_host_port(host, ssh_port);
1.109     djm       307:        lowercase(hostport);
1.144     djm       308:        if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
1.51      djm       309:                fatal("host_hash failed");
1.108     djm       310:        known_host = hash_hosts ? hashed : hostport;
1.103     djm       311:        if (!get_cert)
1.152     djm       312:                r = fprintf(stdout, "%s ", known_host);
                    313:        if (r >= 0 && sshkey_write(key, stdout) == 0)
                    314:                (void)fputs("\n", stdout);
1.140     dtucker   315:        free(hashed);
1.101     djm       316:        free(hostport);
1.102     djm       317: }
                    318:
                    319: static void
                    320: keyprint(con *c, struct sshkey *key)
                    321: {
                    322:        char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
                    323:        char *host, *ohosts;
                    324:
                    325:        if (key == NULL)
                    326:                return;
1.103     djm       327:        if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
1.102     djm       328:                keyprint_one(hosts, key);
                    329:                return;
                    330:        }
                    331:        ohosts = hosts = xstrdup(hosts);
                    332:        while ((host = strsep(&hosts, ",")) != NULL)
                    333:                keyprint_one(host, key);
                    334:        free(ohosts);
1.1       markus    335: }
                    336:
1.24      itojun    337: static int
1.1       markus    338: tcpconnect(char *host)
                    339: {
                    340:        struct addrinfo hints, *ai, *aitop;
                    341:        char strport[NI_MAXSERV];
                    342:        int gaierr, s = -1;
                    343:
1.26      markus    344:        snprintf(strport, sizeof strport, "%d", ssh_port);
1.1       markus    345:        memset(&hints, 0, sizeof(hints));
1.26      markus    346:        hints.ai_family = IPv4or6;
1.1       markus    347:        hints.ai_socktype = SOCK_STREAM;
1.97      djm       348:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
                    349:                error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
                    350:                return -1;
                    351:        }
1.1       markus    352:        for (ai = aitop; ai; ai = ai->ai_next) {
1.81      dtucker   353:                s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1.128     deraadt   354:                if (s == -1) {
1.1       markus    355:                        error("socket: %s", strerror(errno));
                    356:                        continue;
                    357:                }
1.49      djm       358:                if (set_nonblock(s) == -1)
1.136     djm       359:                        fatal_f("set_nonblock(%d)", s);
1.128     deraadt   360:                if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
1.1       markus    361:                    errno != EINPROGRESS)
                    362:                        error("connect (`%s'): %s", host, strerror(errno));
                    363:                else
                    364:                        break;
                    365:                close(s);
                    366:                s = -1;
                    367:        }
                    368:        freeaddrinfo(aitop);
                    369:        return s;
                    370: }
                    371:
1.24      itojun    372: static int
1.147     djm       373: conalloc(const char *iname, const char *oname, int keytype)
1.1       markus    374: {
1.39      deraadt   375:        char *namebase, *name, *namelist;
1.1       markus    376:        int s;
                    377:
                    378:        namebase = namelist = xstrdup(iname);
                    379:
                    380:        do {
                    381:                name = xstrsep(&namelist, ",");
                    382:                if (!name) {
1.87      djm       383:                        free(namebase);
1.1       markus    384:                        return (-1);
                    385:                }
                    386:        } while ((s = tcpconnect(name)) < 0);
                    387:
                    388:        if (s >= maxfd)
1.4       markus    389:                fatal("conalloc: fdno %d too high", s);
1.1       markus    390:        if (fdcon[s].c_status)
1.4       markus    391:                fatal("conalloc: attempt to reuse fdno %d", s);
1.1       markus    392:
1.136     djm       393:        debug3_f("oname %s kt %d", oname, keytype);
1.1       markus    394:        fdcon[s].c_fd = s;
                    395:        fdcon[s].c_status = CS_CON;
                    396:        fdcon[s].c_namebase = namebase;
                    397:        fdcon[s].c_name = name;
                    398:        fdcon[s].c_namelist = namelist;
                    399:        fdcon[s].c_output_name = xstrdup(oname);
                    400:        fdcon[s].c_data = (char *) &fdcon[s].c_plen;
                    401:        fdcon[s].c_len = 4;
                    402:        fdcon[s].c_off = 0;
1.26      markus    403:        fdcon[s].c_keytype = keytype;
1.141     deraadt   404:        monotime_ts(&fdcon[s].c_ts);
                    405:        fdcon[s].c_ts.tv_sec += timeout;
1.1       markus    406:        TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
1.141     deraadt   407:        read_wait[s].fd = s;
                    408:        read_wait[s].events = POLLIN;
1.1       markus    409:        ncon++;
                    410:        return (s);
                    411: }
                    412:
1.24      itojun    413: static void
1.1       markus    414: confree(int s)
                    415: {
                    416:        if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
1.4       markus    417:                fatal("confree: attempt to free bad fdno %d", s);
1.87      djm       418:        free(fdcon[s].c_namebase);
                    419:        free(fdcon[s].c_output_name);
1.1       markus    420:        if (fdcon[s].c_status == CS_KEYS)
1.87      djm       421:                free(fdcon[s].c_data);
1.1       markus    422:        fdcon[s].c_status = CS_UNUSED;
1.26      markus    423:        fdcon[s].c_keytype = 0;
1.95      markus    424:        if (fdcon[s].c_ssh) {
                    425:                ssh_packet_close(fdcon[s].c_ssh);
                    426:                free(fdcon[s].c_ssh);
                    427:                fdcon[s].c_ssh = NULL;
1.115     dtucker   428:        } else
                    429:                close(s);
1.1       markus    430:        TAILQ_REMOVE(&tq, &fdcon[s], c_link);
1.141     deraadt   431:        read_wait[s].fd = -1;
                    432:        read_wait[s].events = 0;
1.1       markus    433:        ncon--;
                    434: }
                    435:
1.24      itojun    436: static void
1.1       markus    437: contouch(int s)
                    438: {
                    439:        TAILQ_REMOVE(&tq, &fdcon[s], c_link);
1.141     deraadt   440:        monotime_ts(&fdcon[s].c_ts);
                    441:        fdcon[s].c_ts.tv_sec += timeout;
1.1       markus    442:        TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
                    443: }
                    444:
1.24      itojun    445: static int
1.1       markus    446: conrecycle(int s)
                    447: {
1.39      deraadt   448:        con *c = &fdcon[s];
1.1       markus    449:        int ret;
                    450:
1.26      markus    451:        ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
1.1       markus    452:        confree(s);
                    453:        return (ret);
                    454: }
                    455:
1.24      itojun    456: static void
1.1       markus    457: congreet(int s)
                    458: {
1.55      djm       459:        int n = 0, remote_major = 0, remote_minor = 0;
1.26      markus    460:        char buf[256], *cp;
1.33      markus    461:        char remote_version[sizeof buf];
1.55      djm       462:        size_t bufsiz;
1.1       markus    463:        con *c = &fdcon[s];
                    464:
1.112     djm       465:        /* send client banner */
                    466:        n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
                    467:            PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
                    468:        if (n < 0 || (size_t)n >= sizeof(buf)) {
                    469:                error("snprintf: buffer too small");
                    470:                confree(s);
                    471:                return;
                    472:        }
                    473:        if (atomicio(vwrite, s, buf, n) != (size_t)n) {
                    474:                error("write (%s): %s", c->c_name, strerror(errno));
                    475:                confree(s);
                    476:                return;
                    477:        }
                    478:
1.146     dtucker   479:        /*
                    480:         * Read the server banner as per RFC4253 section 4.2.  The "SSH-"
1.154     jsg       481:         * protocol identification string may be preceded by an arbitrarily
1.146     dtucker   482:         * large banner which we must read and ignore.  Loop while reading
                    483:         * newline-terminated lines until we have one starting with "SSH-".
                    484:         * The ID string cannot be longer than 255 characters although the
1.154     jsg       485:         * preceding banner lines may (in which case they'll be discarded
1.146     dtucker   486:         * in multiple iterations of the outer loop).
                    487:         */
1.57      djm       488:        for (;;) {
                    489:                memset(buf, '\0', sizeof(buf));
                    490:                bufsiz = sizeof(buf);
                    491:                cp = buf;
                    492:                while (bufsiz-- &&
                    493:                    (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
                    494:                        if (*cp == '\r')
                    495:                                *cp = '\n';
                    496:                        cp++;
                    497:                }
                    498:                if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
                    499:                        break;
1.27      markus    500:        }
1.54      avsm      501:        if (n == 0) {
                    502:                switch (errno) {
                    503:                case EPIPE:
                    504:                        error("%s: Connection closed by remote host", c->c_name);
                    505:                        break;
                    506:                case ECONNREFUSED:
                    507:                        break;
                    508:                default:
1.1       markus    509:                        error("read (%s): %s", c->c_name, strerror(errno));
1.54      avsm      510:                        break;
                    511:                }
1.1       markus    512:                conrecycle(s);
1.146     dtucker   513:                return;
                    514:        }
                    515:        if (cp >= buf + sizeof(buf)) {
                    516:                error("%s: greeting exceeds allowable length", c->c_name);
                    517:                confree(s);
1.1       markus    518:                return;
                    519:        }
1.21      millert   520:        if (*cp != '\n' && *cp != '\r') {
1.1       markus    521:                error("%s: bad greeting", c->c_name);
                    522:                confree(s);
                    523:                return;
                    524:        }
1.21      millert   525:        *cp = '\0';
1.98      djm       526:        if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
                    527:                fatal("ssh_packet_set_connection failed");
1.99      djm       528:        ssh_packet_set_timeout(c->c_ssh, timeout, 1);
1.95      markus    529:        ssh_set_app_data(c->c_ssh, c);  /* back link */
1.139     djm       530:        c->c_ssh->compat = 0;
1.33      markus    531:        if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
                    532:            &remote_major, &remote_minor, remote_version) == 3)
1.139     djm       533:                compat_banner(c->c_ssh, remote_version);
1.112     djm       534:        if (!ssh2_capable(remote_major, remote_minor)) {
                    535:                debug("%s doesn't support ssh2", c->c_name);
1.33      markus    536:                confree(s);
                    537:                return;
1.26      markus    538:        }
1.117     djm       539:        fprintf(stderr, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
                    540:            c->c_name, ssh_port, chop(buf));
1.112     djm       541:        keygrab_ssh2(c);
                    542:        confree(s);
1.1       markus    543: }
                    544:
1.24      itojun    545: static void
1.1       markus    546: conread(int s)
                    547: {
1.39      deraadt   548:        con *c = &fdcon[s];
1.54      avsm      549:        size_t n;
1.1       markus    550:
                    551:        if (c->c_status == CS_CON) {
                    552:                congreet(s);
                    553:                return;
                    554:        }
1.50      avsm      555:        n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
1.54      avsm      556:        if (n == 0) {
1.1       markus    557:                error("read (%s): %s", c->c_name, strerror(errno));
                    558:                confree(s);
                    559:                return;
                    560:        }
                    561:        c->c_off += n;
                    562:
                    563:        if (c->c_off == c->c_len)
                    564:                switch (c->c_status) {
                    565:                case CS_SIZE:
                    566:                        c->c_plen = htonl(c->c_plen);
                    567:                        c->c_len = c->c_plen + 8 - (c->c_plen & 7);
                    568:                        c->c_off = 0;
                    569:                        c->c_data = xmalloc(c->c_len);
                    570:                        c->c_status = CS_KEYS;
                    571:                        break;
                    572:                default:
1.4       markus    573:                        fatal("conread: invalid status %d", c->c_status);
1.1       markus    574:                        break;
                    575:                }
                    576:
                    577:        contouch(s);
                    578: }
                    579:
1.24      itojun    580: static void
1.1       markus    581: conloop(void)
                    582: {
1.141     deraadt   583:        struct timespec seltime, now;
1.39      deraadt   584:        con *c;
1.1       markus    585:        int i;
                    586:
1.141     deraadt   587:        monotime_ts(&now);
1.36      itojun    588:        c = TAILQ_FIRST(&tq);
1.1       markus    589:
1.141     deraadt   590:        if (c && timespeccmp(&c->c_ts, &now, >))
                    591:                timespecsub(&c->c_ts, &now, &seltime);
1.132     cheloha   592:        else
1.141     deraadt   593:                timespecclear(&seltime);
1.1       markus    594:
1.145     deraadt   595:        while (ppoll(read_wait, maxfd, &seltime, NULL) == -1) {
                    596:                if (errno == EAGAIN || errno == EINTR)
                    597:                        continue;
                    598:                error("poll error");
                    599:        }
1.16      deraadt   600:
1.18      deraadt   601:        for (i = 0; i < maxfd; i++) {
1.141     deraadt   602:                if (read_wait[i].revents & (POLLHUP|POLLERR|POLLNVAL))
1.1       markus    603:                        confree(i);
1.143     djm       604:                else if (read_wait[i].revents & (POLLIN|POLLHUP))
1.1       markus    605:                        conread(i);
1.18      deraadt   606:        }
1.1       markus    607:
1.36      itojun    608:        c = TAILQ_FIRST(&tq);
1.141     deraadt   609:        while (c && timespeccmp(&c->c_ts, &now, <)) {
1.1       markus    610:                int s = c->c_fd;
1.18      deraadt   611:
1.36      itojun    612:                c = TAILQ_NEXT(c, c_link);
1.1       markus    613:                conrecycle(s);
                    614:        }
                    615: }
                    616:
1.26      markus    617: static void
1.147     djm       618: do_one_host(char *host)
1.1       markus    619: {
1.26      markus    620:        char *name = strnnsep(&host, " \t\n");
                    621:        int j;
1.1       markus    622:
1.31      markus    623:        if (name == NULL)
                    624:                return;
1.112     djm       625:        for (j = KT_MIN; j <= KT_MAX; j *= 2) {
1.26      markus    626:                if (get_keytypes & j) {
                    627:                        while (ncon >= MAXCON)
                    628:                                conloop();
                    629:                        conalloc(name, *host ? host : name, j);
1.1       markus    630:                }
1.147     djm       631:        }
                    632: }
                    633:
                    634: static void
                    635: do_host(char *host)
                    636: {
                    637:        char daddr[128];
                    638:        struct xaddr addr, end_addr;
                    639:        u_int masklen;
                    640:
                    641:        if (host == NULL)
                    642:                return;
                    643:        if (addr_pton_cidr(host, &addr, &masklen) != 0) {
                    644:                /* Assume argument is a hostname */
                    645:                do_one_host(host);
                    646:        } else {
                    647:                /* Argument is a CIDR range */
                    648:                debug("CIDR range %s", host);
                    649:                end_addr = addr;
                    650:                if (addr_host_to_all1s(&end_addr, masklen) != 0)
                    651:                        goto badaddr;
                    652:                /*
                    653:                 * Note: we deliberately include the all-zero/ones addresses.
                    654:                 */
                    655:                for (;;) {
                    656:                        if (addr_ntop(&addr, daddr, sizeof(daddr)) != 0) {
                    657:  badaddr:
                    658:                                error("Invalid address %s", host);
                    659:                                return;
                    660:                        }
                    661:                        debug("CIDR expand: address %s", daddr);
                    662:                        do_one_host(daddr);
                    663:                        if (addr_cmp(&addr, &end_addr) == 0)
                    664:                                break;
                    665:                        addr_increment(&addr);
                    666:                };
1.1       markus    667:        }
                    668: }
                    669:
1.34      markus    670: void
1.134     djm       671: sshfatal(const char *file, const char *func, int line, int showfunc,
1.135     djm       672:     LogLevel level, const char *suffix, const char *fmt, ...)
1.26      markus    673: {
1.34      markus    674:        va_list args;
1.39      deraadt   675:
1.34      markus    676:        va_start(args, fmt);
1.137     djm       677:        sshlogv(file, func, line, showfunc, level, suffix, fmt, args);
1.34      markus    678:        va_end(args);
1.133     djm       679:        cleanup_exit(255);
1.26      markus    680: }
                    681:
                    682: static void
1.1       markus    683: usage(void)
                    684: {
1.77      sobrado   685:        fprintf(stderr,
1.151     jmc       686:            "usage: ssh-keyscan [-46cDHv] [-f file] [-O option] [-p port] [-T timeout]\n"
                    687:            "                   [-t type] [host | addrlist namelist]\n");
1.25      jakob     688:        exit(1);
1.1       markus    689: }
                    690:
                    691: int
                    692: main(int argc, char **argv)
                    693: {
1.26      markus    694:        int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
1.82      djm       695:        int opt, fopt_count = 0, j;
1.120     markus    696:        char *tname, *cp, *line = NULL;
                    697:        size_t linesize = 0;
1.82      djm       698:        FILE *fp;
1.26      markus    699:
                    700:        extern int optind;
                    701:        extern char *optarg;
1.1       markus    702:
                    703:        TAILQ_INIT(&tq);
1.56      djm       704:
                    705:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    706:        sanitise_stdfd();
1.1       markus    707:
1.26      markus    708:        if (argc <= 1)
1.1       markus    709:                usage();
                    710:
1.150     djm       711:        while ((opt = getopt(argc, argv, "cDHv46O:p:T:t:f:")) != -1) {
1.26      markus    712:                switch (opt) {
1.51      djm       713:                case 'H':
                    714:                        hash_hosts = 1;
1.103     djm       715:                        break;
                    716:                case 'c':
                    717:                        get_cert = 1;
1.117     djm       718:                        break;
                    719:                case 'D':
                    720:                        print_sshfp = 1;
1.51      djm       721:                        break;
1.26      markus    722:                case 'p':
                    723:                        ssh_port = a2port(optarg);
1.78      djm       724:                        if (ssh_port <= 0) {
1.26      markus    725:                                fprintf(stderr, "Bad port '%s'\n", optarg);
                    726:                                exit(1);
                    727:                        }
                    728:                        break;
                    729:                case 'T':
1.38      stevesk   730:                        timeout = convtime(optarg);
                    731:                        if (timeout == -1 || timeout == 0) {
                    732:                                fprintf(stderr, "Bad timeout '%s'\n", optarg);
1.1       markus    733:                                usage();
1.38      stevesk   734:                        }
1.26      markus    735:                        break;
                    736:                case 'v':
                    737:                        if (!debug_flag) {
                    738:                                debug_flag = 1;
                    739:                                log_level = SYSLOG_LEVEL_DEBUG1;
                    740:                        }
                    741:                        else if (log_level < SYSLOG_LEVEL_DEBUG3)
                    742:                                log_level++;
                    743:                        else
                    744:                                fatal("Too high debugging level.");
                    745:                        break;
                    746:                case 'f':
                    747:                        if (strcmp(optarg, "-") == 0)
                    748:                                optarg = NULL;
                    749:                        argv[fopt_count++] = optarg;
1.150     djm       750:                        break;
                    751:                case 'O':
                    752:                        /* Maybe other misc options in the future too */
                    753:                        if (strncmp(optarg, "hashalg=", 8) != 0)
                    754:                                fatal("Unsupported -O option");
                    755:                        if ((hashalg = ssh_digest_alg_by_name(
                    756:                            optarg + 8)) == -1)
                    757:                                fatal("Unsupported hash algorithm");
1.26      markus    758:                        break;
                    759:                case 't':
                    760:                        get_keytypes = 0;
                    761:                        tname = strtok(optarg, ",");
                    762:                        while (tname) {
1.95      markus    763:                                int type = sshkey_type_from_name(tname);
1.107     djm       764:
1.26      markus    765:                                switch (type) {
1.155     djm       766: #ifdef WITH_DSA
1.26      markus    767:                                case KEY_DSA:
                    768:                                        get_keytypes |= KT_DSA;
1.83      djm       769:                                        break;
1.155     djm       770: #endif
1.83      djm       771:                                case KEY_ECDSA:
                    772:                                        get_keytypes |= KT_ECDSA;
1.26      markus    773:                                        break;
                    774:                                case KEY_RSA:
                    775:                                        get_keytypes |= KT_RSA;
1.89      markus    776:                                        break;
                    777:                                case KEY_ED25519:
                    778:                                        get_keytypes |= KT_ED25519;
1.118     markus    779:                                        break;
                    780:                                case KEY_XMSS:
                    781:                                        get_keytypes |= KT_XMSS;
1.131     djm       782:                                        break;
                    783:                                case KEY_ED25519_SK:
                    784:                                        get_keytypes |= KT_ED25519_SK;
                    785:                                        break;
                    786:                                case KEY_ECDSA_SK:
                    787:                                        get_keytypes |= KT_ECDSA_SK;
1.26      markus    788:                                        break;
                    789:                                case KEY_UNSPEC:
1.107     djm       790:                                default:
                    791:                                        fatal("Unknown key type \"%s\"", tname);
1.26      markus    792:                                }
                    793:                                tname = strtok(NULL, ",");
                    794:                        }
                    795:                        break;
                    796:                case '4':
                    797:                        IPv4or6 = AF_INET;
                    798:                        break;
                    799:                case '6':
                    800:                        IPv4or6 = AF_INET6;
                    801:                        break;
                    802:                default:
                    803:                        usage();
1.1       markus    804:                }
                    805:        }
1.26      markus    806:        if (optind == argc && !fopt_count)
1.1       markus    807:                usage();
                    808:
1.26      markus    809:        log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
                    810:
1.1       markus    811:        maxfd = fdlim_get(1);
                    812:        if (maxfd < 0)
1.4       markus    813:                fatal("%s: fdlim_get: bad value", __progname);
1.1       markus    814:        if (maxfd > MAXMAXFD)
                    815:                maxfd = MAXMAXFD;
1.18      deraadt   816:        if (MAXCON <= 0)
1.4       markus    817:                fatal("%s: not enough file descriptors", __progname);
1.1       markus    818:        if (maxfd > fdlim_get(0))
                    819:                fdlim_set(maxfd);
1.63      djm       820:        fdcon = xcalloc(maxfd, sizeof(con));
1.141     deraadt   821:        read_wait = xcalloc(maxfd, sizeof(struct pollfd));
1.142     deraadt   822:        for (j = 0; j < maxfd; j++)
                    823:                read_wait[j].fd = -1;
1.1       markus    824:
1.82      djm       825:        for (j = 0; j < fopt_count; j++) {
                    826:                if (argv[j] == NULL)
                    827:                        fp = stdin;
                    828:                else if ((fp = fopen(argv[j], "r")) == NULL)
1.156   ! tobias    829:                        fatal("%s: %s: %s", __progname,
        !           830:                            fp == stdin ? "<stdin>" : argv[j], strerror(errno));
1.82      djm       831:
1.120     markus    832:                while (getline(&line, &linesize, fp) != -1) {
1.82      djm       833:                        /* Chomp off trailing whitespace and comments */
                    834:                        if ((cp = strchr(line, '#')) == NULL)
                    835:                                cp = line + strlen(line) - 1;
                    836:                        while (cp >= line) {
                    837:                                if (*cp == ' ' || *cp == '\t' ||
                    838:                                    *cp == '\n' || *cp == '#')
                    839:                                        *cp-- = '\0';
                    840:                                else
                    841:                                        break;
                    842:                        }
                    843:
                    844:                        /* Skip empty lines */
                    845:                        if (*line == '\0')
1.28      danh      846:                                continue;
1.82      djm       847:
                    848:                        do_host(line);
1.26      markus    849:                }
1.82      djm       850:
                    851:                if (ferror(fp))
1.156   ! tobias    852:                        fatal("%s: %s: %s", __progname,
        !           853:                            fp == stdin ? "<stdin>" : argv[j], strerror(errno));
1.82      djm       854:
1.156   ! tobias    855:                if (fp != stdin)
        !           856:                        fclose(fp);
1.26      markus    857:        }
1.120     markus    858:        free(line);
1.26      markus    859:
                    860:        while (optind < argc)
                    861:                do_host(argv[optind++]);
1.1       markus    862:
                    863:        while (ncon > 0)
                    864:                conloop();
                    865:
1.126     djm       866:        return found_one ? 0 : 1;
1.1       markus    867: }