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

1.1       markus      1: /*
                      2:  * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
                      3:  *
                      4:  * Modification and redistribution in source and binary forms is
                      5:  * permitted provided that due credit is given to the author and the
                      6:  * OpenBSD project (for instance by leaving this copyright notice
                      7:  * intact).
                      8:  */
                      9:
                     10: #include "includes.h"
1.6     ! markus     11: RCSID("$OpenBSD: ssh-keyscan.c,v 1.5 2000/12/19 22:48:08 markus Exp $");
1.1       markus     12:
                     13: #include <sys/queue.h>
                     14: #include <errno.h>
                     15:
1.5       markus     16: #include <openssl/bn.h>
                     17: #include <openssl/rsa.h>
                     18: #include <openssl/dsa.h>
1.1       markus     19:
                     20: #include "xmalloc.h"
                     21: #include "ssh.h"
                     22: #include "key.h"
                     23: #include "buffer.h"
                     24: #include "bufaux.h"
                     25:
                     26: static int argno = 1;          /* Number of argument currently being parsed */
                     27:
                     28: int family = AF_UNSPEC;                /* IPv4, IPv6 or both */
                     29:
                     30: #define PORT 22
                     31: #define MAXMAXFD 256
                     32:
                     33: /* The number of seconds after which to give up on a TCP connection */
                     34: int timeout = 5;
                     35:
                     36: int maxfd;
                     37: #define maxcon (maxfd - 10)
                     38:
1.3       markus     39: extern char *__progname;
1.1       markus     40: fd_set read_wait;
                     41: int ncon;
                     42:
                     43: /*
                     44:  * Keep a connection structure for each file descriptor.  The state
                     45:  * associated with file descriptor n is held in fdcon[n].
                     46:  */
                     47: typedef struct Connection {
1.6     ! markus     48:        u_char c_status;        /* State of connection on this file desc. */
1.1       markus     49: #define CS_UNUSED 0            /* File descriptor unused */
                     50: #define CS_CON 1               /* Waiting to connect/read greeting */
                     51: #define CS_SIZE 2              /* Waiting to read initial packet size */
                     52: #define CS_KEYS 3              /* Waiting to read public key packet */
                     53:        int c_fd;               /* Quick lookup: c->c_fd == c - fdcon */
                     54:        int c_plen;             /* Packet length field for ssh packet */
                     55:        int c_len;              /* Total bytes which must be read. */
                     56:        int c_off;              /* Length of data read so far. */
                     57:        char *c_namebase;       /* Address to free for c_name and c_namelist */
                     58:        char *c_name;           /* Hostname of connection for errors */
                     59:        char *c_namelist;       /* Pointer to other possible addresses */
                     60:        char *c_output_name;    /* Hostname of connection for output */
                     61:        char *c_data;           /* Data read from this fd */
                     62:        struct timeval c_tv;    /* Time at which connection gets aborted */
                     63:        TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
                     64: } con;
                     65:
                     66: TAILQ_HEAD(conlist, Connection) tq;    /* Timeout Queue */
                     67: con *fdcon;
                     68:
                     69: /*
                     70:  *  This is just a wrapper around fgets() to make it usable.
                     71:  */
                     72:
                     73: /* Stress-test.  Increase this later. */
                     74: #define LINEBUF_SIZE 16
                     75:
                     76: typedef struct {
                     77:        char *buf;
1.6     ! markus     78:        u_int size;
1.1       markus     79:        int lineno;
                     80:        const char *filename;
                     81:        FILE *stream;
                     82:        void (*errfun) (const char *,...);
                     83: } Linebuf;
                     84:
                     85: static inline Linebuf *
                     86: Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
                     87: {
                     88:        Linebuf *lb;
                     89:
                     90:        if (!(lb = malloc(sizeof(*lb)))) {
                     91:                if (errfun)
                     92:                        (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
                     93:                return (NULL);
                     94:        }
                     95:        if (filename) {
                     96:                lb->filename = filename;
                     97:                if (!(lb->stream = fopen(filename, "r"))) {
                     98:                        free(lb);
                     99:                        if (errfun)
                    100:                                (*errfun) ("%s: %s\n", filename, strerror(errno));
                    101:                        return (NULL);
                    102:                }
                    103:        } else {
                    104:                lb->filename = "(stdin)";
                    105:                lb->stream = stdin;
                    106:        }
                    107:
                    108:        if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
                    109:                if (errfun)
                    110:                        (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
                    111:                free(lb);
                    112:                return (NULL);
                    113:        }
                    114:        lb->errfun = errfun;
                    115:        lb->lineno = 0;
                    116:        return (lb);
                    117: }
                    118:
                    119: static inline void
                    120: Linebuf_free(Linebuf * lb)
                    121: {
                    122:        fclose(lb->stream);
                    123:        free(lb->buf);
                    124:        free(lb);
                    125: }
                    126:
                    127: static inline void
                    128: Linebuf_restart(Linebuf * lb)
                    129: {
                    130:        clearerr(lb->stream);
                    131:        rewind(lb->stream);
                    132:        lb->lineno = 0;
                    133: }
                    134:
                    135: static inline int
                    136: Linebuf_lineno(Linebuf * lb)
                    137: {
                    138:        return (lb->lineno);
                    139: }
                    140:
                    141: static inline char *
                    142: getline(Linebuf * lb)
                    143: {
                    144:        int n = 0;
                    145:
                    146:        lb->lineno++;
                    147:        for (;;) {
                    148:                /* Read a line */
                    149:                if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
                    150:                        if (ferror(lb->stream) && lb->errfun)
                    151:                                (*lb->errfun) ("%s: %s\n", lb->filename, strerror(errno));
                    152:                        return (NULL);
                    153:                }
                    154:                n = strlen(lb->buf);
                    155:
                    156:                /* Return it or an error if it fits */
                    157:                if (n > 0 && lb->buf[n - 1] == '\n') {
                    158:                        lb->buf[n - 1] = '\0';
                    159:                        return (lb->buf);
                    160:                }
                    161:                if (n != lb->size - 1) {
                    162:                        if (lb->errfun)
                    163:                                (*lb->errfun) ("%s: skipping incomplete last line\n", lb->filename);
                    164:                        return (NULL);
                    165:                }
                    166:                /* Double the buffer if we need more space */
                    167:                if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
                    168:                        if (lb->errfun)
                    169:                                (*lb->errfun) ("linebuf (%s): realloc failed\n", lb->filename);
                    170:                        return (NULL);
                    171:                }
                    172:        }
                    173: }
                    174:
                    175: static int
                    176: fdlim_get(int hard)
                    177: {
                    178:        struct rlimit rlfd;
                    179:        if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
                    180:                return (-1);
                    181:        if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
                    182:                return 10000;
                    183:        else
                    184:                return hard ? rlfd.rlim_max : rlfd.rlim_cur;
                    185: }
                    186:
                    187: static int
                    188: fdlim_set(int lim)
                    189: {
                    190:        struct rlimit rlfd;
                    191:        if (lim <= 0)
                    192:                return (-1);
                    193:        if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
                    194:                return (-1);
                    195:        rlfd.rlim_cur = lim;
                    196:        if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
                    197:                return (-1);
                    198:        return (0);
                    199: }
                    200:
                    201: /*
                    202:  * This is an strsep function that returns a null field for adjacent
                    203:  * separators.  This is the same as the 4.4BSD strsep, but different from the
                    204:  * one in the GNU libc.
                    205:  */
                    206: inline char *
                    207: xstrsep(char **str, const char *delim)
                    208: {
                    209:        char *s, *e;
                    210:
                    211:        if (!**str)
                    212:                return (NULL);
                    213:
                    214:        s = *str;
                    215:        e = s + strcspn(s, delim);
                    216:
                    217:        if (*e != '\0')
                    218:                *e++ = '\0';
                    219:        *str = e;
                    220:
                    221:        return (s);
                    222: }
                    223:
                    224: /*
                    225:  * Get the next non-null token (like GNU strsep).  Strsep() will return a
                    226:  * null token for two adjacent separators, so we may have to loop.
                    227:  */
                    228: char *
                    229: strnnsep(char **stringp, char *delim)
                    230: {
                    231:        char *tok;
                    232:
                    233:        do {
                    234:                tok = xstrsep(stringp, delim);
                    235:        } while (tok && *tok == '\0');
                    236:        return (tok);
                    237: }
                    238:
                    239: void
                    240: keyprint(char *host, char *output_name, char *kd, int len)
                    241: {
                    242:        static Key *rsa;
                    243:        static Buffer msg;
                    244:
                    245:        if (rsa == NULL) {
                    246:                buffer_init(&msg);
                    247:                rsa = key_new(KEY_RSA1);
                    248:        }
                    249:        buffer_append(&msg, kd, len);
                    250:        buffer_consume(&msg, 8 - (len & 7));    /* padding */
                    251:        if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
                    252:                error("%s: invalid packet type", host);
                    253:                buffer_clear(&msg);
                    254:                return;
                    255:        }
                    256:        buffer_consume(&msg, 8);                /* cookie */
                    257:
                    258:        /* server key */
                    259:        (void) buffer_get_int(&msg);
                    260:        buffer_get_bignum(&msg, rsa->rsa->e);
                    261:        buffer_get_bignum(&msg, rsa->rsa->n);
                    262:
                    263:        /* host key */
                    264:        (void) buffer_get_int(&msg);
                    265:        buffer_get_bignum(&msg, rsa->rsa->e);
                    266:        buffer_get_bignum(&msg, rsa->rsa->n);
                    267:        buffer_clear(&msg);
                    268:
                    269:        fprintf(stdout, "%s ", output_name ? output_name : host);
                    270:        key_write(rsa, stdout);
                    271:        fputs("\n", stdout);
                    272: }
                    273:
                    274: int
                    275: tcpconnect(char *host)
                    276: {
                    277:        struct addrinfo hints, *ai, *aitop;
                    278:        char strport[NI_MAXSERV];
                    279:        int gaierr, s = -1;
                    280:
                    281:        snprintf(strport, sizeof strport, "%d", PORT);
                    282:        memset(&hints, 0, sizeof(hints));
                    283:        hints.ai_family = family;
                    284:        hints.ai_socktype = SOCK_STREAM;
                    285:        if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
                    286:                fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
                    287:        for (ai = aitop; ai; ai = ai->ai_next) {
                    288:                s = socket(ai->ai_family, SOCK_STREAM, 0);
                    289:                if (s < 0) {
                    290:                        error("socket: %s", strerror(errno));
                    291:                        continue;
                    292:                }
                    293:                if (fcntl(s, F_SETFL, O_NDELAY) < 0)
                    294:                        fatal("F_SETFL: %s", strerror(errno));
                    295:                if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
                    296:                    errno != EINPROGRESS)
                    297:                        error("connect (`%s'): %s", host, strerror(errno));
                    298:                else
                    299:                        break;
                    300:                close(s);
                    301:                s = -1;
                    302:        }
                    303:        freeaddrinfo(aitop);
                    304:        return s;
                    305: }
                    306:
                    307: int
                    308: conalloc(char *iname, char *oname)
                    309: {
                    310:        int s;
                    311:        char *namebase, *name, *namelist;
                    312:
                    313:        namebase = namelist = xstrdup(iname);
                    314:
                    315:        do {
                    316:                name = xstrsep(&namelist, ",");
                    317:                if (!name) {
                    318:                        free(namebase);
                    319:                        return (-1);
                    320:                }
                    321:        } while ((s = tcpconnect(name)) < 0);
                    322:
                    323:        if (s >= maxfd)
1.4       markus    324:                fatal("conalloc: fdno %d too high", s);
1.1       markus    325:        if (fdcon[s].c_status)
1.4       markus    326:                fatal("conalloc: attempt to reuse fdno %d", s);
1.1       markus    327:
                    328:        fdcon[s].c_fd = s;
                    329:        fdcon[s].c_status = CS_CON;
                    330:        fdcon[s].c_namebase = namebase;
                    331:        fdcon[s].c_name = name;
                    332:        fdcon[s].c_namelist = namelist;
                    333:        fdcon[s].c_output_name = xstrdup(oname);
                    334:        fdcon[s].c_data = (char *) &fdcon[s].c_plen;
                    335:        fdcon[s].c_len = 4;
                    336:        fdcon[s].c_off = 0;
                    337:        gettimeofday(&fdcon[s].c_tv, NULL);
                    338:        fdcon[s].c_tv.tv_sec += timeout;
                    339:        TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
                    340:        FD_SET(s, &read_wait);
                    341:        ncon++;
                    342:        return (s);
                    343: }
                    344:
                    345: void
                    346: confree(int s)
                    347: {
                    348:        close(s);
                    349:        if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
1.4       markus    350:                fatal("confree: attempt to free bad fdno %d", s);
1.1       markus    351:        free(fdcon[s].c_namebase);
                    352:        free(fdcon[s].c_output_name);
                    353:        if (fdcon[s].c_status == CS_KEYS)
                    354:                free(fdcon[s].c_data);
                    355:        fdcon[s].c_status = CS_UNUSED;
                    356:        TAILQ_REMOVE(&tq, &fdcon[s], c_link);
                    357:        FD_CLR(s, &read_wait);
                    358:        ncon--;
                    359: }
                    360:
                    361: void
                    362: contouch(int s)
                    363: {
                    364:        TAILQ_REMOVE(&tq, &fdcon[s], c_link);
                    365:        gettimeofday(&fdcon[s].c_tv, NULL);
                    366:        fdcon[s].c_tv.tv_sec += timeout;
                    367:        TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
                    368: }
                    369:
                    370: int
                    371: conrecycle(int s)
                    372: {
                    373:        int ret;
                    374:        con *c = &fdcon[s];
                    375:        char *iname, *oname;
                    376:
                    377:        iname = xstrdup(c->c_namelist);
                    378:        oname = c->c_output_name;
                    379:        c->c_output_name = NULL;/* prevent it from being freed */
                    380:        confree(s);
                    381:        ret = conalloc(iname, oname);
                    382:        free(iname);
                    383:        return (ret);
                    384: }
                    385:
                    386: void
                    387: congreet(int s)
                    388: {
                    389:        char buf[80];
                    390:        int n;
                    391:        con *c = &fdcon[s];
                    392:
                    393:        n = read(s, buf, sizeof(buf));
                    394:        if (n < 0) {
                    395:                if (errno != ECONNREFUSED)
                    396:                        error("read (%s): %s", c->c_name, strerror(errno));
                    397:                conrecycle(s);
                    398:                return;
                    399:        }
                    400:        if (buf[n - 1] != '\n') {
                    401:                error("%s: bad greeting", c->c_name);
                    402:                confree(s);
                    403:                return;
                    404:        }
                    405:        buf[n - 1] = '\0';
                    406:        fprintf(stderr, "# %s %s\n", c->c_name, buf);
                    407:        n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
                    408:        if (write(s, buf, n) != n) {
                    409:                error("write (%s): %s", c->c_name, strerror(errno));
                    410:                confree(s);
                    411:                return;
                    412:        }
                    413:        c->c_status = CS_SIZE;
                    414:        contouch(s);
                    415: }
                    416:
                    417: void
                    418: conread(int s)
                    419: {
                    420:        int n;
                    421:        con *c = &fdcon[s];
                    422:
                    423:        if (c->c_status == CS_CON) {
                    424:                congreet(s);
                    425:                return;
                    426:        }
                    427:        n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
                    428:        if (n < 0) {
                    429:                error("read (%s): %s", c->c_name, strerror(errno));
                    430:                confree(s);
                    431:                return;
                    432:        }
                    433:        c->c_off += n;
                    434:
                    435:        if (c->c_off == c->c_len)
                    436:                switch (c->c_status) {
                    437:                case CS_SIZE:
                    438:                        c->c_plen = htonl(c->c_plen);
                    439:                        c->c_len = c->c_plen + 8 - (c->c_plen & 7);
                    440:                        c->c_off = 0;
                    441:                        c->c_data = xmalloc(c->c_len);
                    442:                        c->c_status = CS_KEYS;
                    443:                        break;
                    444:                case CS_KEYS:
                    445:                        keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
                    446:                        confree(s);
                    447:                        return;
                    448:                        break;
                    449:                default:
1.4       markus    450:                        fatal("conread: invalid status %d", c->c_status);
1.1       markus    451:                        break;
                    452:                }
                    453:
                    454:        contouch(s);
                    455: }
                    456:
                    457: void
                    458: conloop(void)
                    459: {
                    460:        fd_set r, e;
                    461:        struct timeval seltime, now;
                    462:        int i;
                    463:        con *c;
                    464:
                    465:        gettimeofday(&now, NULL);
                    466:        c = tq.tqh_first;
                    467:
                    468:        if (c &&
                    469:            (c->c_tv.tv_sec > now.tv_sec ||
                    470:             (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
                    471:                seltime = c->c_tv;
                    472:                seltime.tv_sec -= now.tv_sec;
                    473:                seltime.tv_usec -= now.tv_usec;
                    474:                if ((int) seltime.tv_usec < 0) {
                    475:                        seltime.tv_usec += 1000000;
                    476:                        seltime.tv_sec--;
                    477:                }
                    478:        } else
                    479:                seltime.tv_sec = seltime.tv_usec = 0;
                    480:
                    481:        r = e = read_wait;
                    482:        select(maxfd, &r, NULL, &e, &seltime);
                    483:        for (i = 0; i < maxfd; i++)
                    484:                if (FD_ISSET(i, &e)) {
                    485:                        error("%s: exception!", fdcon[i].c_name);
                    486:                        confree(i);
                    487:                } else if (FD_ISSET(i, &r))
                    488:                        conread(i);
                    489:
                    490:        c = tq.tqh_first;
                    491:        while (c &&
                    492:               (c->c_tv.tv_sec < now.tv_sec ||
                    493:                (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
                    494:                int s = c->c_fd;
                    495:                c = c->c_link.tqe_next;
                    496:                conrecycle(s);
                    497:        }
                    498: }
                    499:
                    500: char *
                    501: nexthost(int argc, char **argv)
                    502: {
                    503:        static Linebuf *lb;
                    504:
                    505:        for (;;) {
                    506:                if (!lb) {
                    507:                        if (argno >= argc)
                    508:                                return (NULL);
                    509:                        if (argv[argno][0] != '-')
                    510:                                return (argv[argno++]);
                    511:                        if (!strcmp(argv[argno], "--")) {
                    512:                                if (++argno >= argc)
                    513:                                        return (NULL);
                    514:                                return (argv[argno++]);
                    515:                        } else if (!strncmp(argv[argno], "-f", 2)) {
                    516:                                char *fname;
                    517:                                if (argv[argno][2])
                    518:                                        fname = &argv[argno++][2];
                    519:                                else if (++argno >= argc) {
                    520:                                        error("missing filename for `-f'");
                    521:                                        return (NULL);
                    522:                                } else
                    523:                                        fname = argv[argno++];
                    524:                                if (!strcmp(fname, "-"))
                    525:                                        fname = NULL;
1.2       markus    526:                                lb = Linebuf_alloc(fname, error);
1.1       markus    527:                        } else
                    528:                                error("ignoring invalid/misplaced option `%s'", argv[argno++]);
                    529:                } else {
                    530:                        char *line;
                    531:                        line = getline(lb);
                    532:                        if (line)
                    533:                                return (line);
                    534:                        Linebuf_free(lb);
                    535:                        lb = NULL;
                    536:                }
                    537:        }
                    538: }
                    539:
                    540: static void
                    541: usage(void)
                    542: {
1.4       markus    543:        fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
1.1       markus    544:        return;
                    545: }
                    546:
                    547: int
                    548: main(int argc, char **argv)
                    549: {
                    550:        char *host = NULL;
                    551:
                    552:        TAILQ_INIT(&tq);
                    553:
                    554:        if (argc <= argno)
                    555:                usage();
                    556:
                    557:        if (argv[1][0] == '-' && argv[1][1] == 't') {
                    558:                argno++;
                    559:                if (argv[1][2])
                    560:                        timeout = atoi(&argv[1][2]);
                    561:                else {
                    562:                        if (argno >= argc)
                    563:                                usage();
                    564:                        timeout = atoi(argv[argno++]);
                    565:                }
                    566:                if (timeout <= 0)
                    567:                        usage();
                    568:        }
                    569:        if (argc <= argno)
                    570:                usage();
                    571:
                    572:        maxfd = fdlim_get(1);
                    573:        if (maxfd < 0)
1.4       markus    574:                fatal("%s: fdlim_get: bad value", __progname);
1.1       markus    575:        if (maxfd > MAXMAXFD)
                    576:                maxfd = MAXMAXFD;
                    577:        if (maxcon <= 0)
1.4       markus    578:                fatal("%s: not enough file descriptors", __progname);
1.1       markus    579:        if (maxfd > fdlim_get(0))
                    580:                fdlim_set(maxfd);
                    581:        fdcon = xmalloc(maxfd * sizeof(con));
                    582:
                    583:        do {
                    584:                while (ncon < maxcon) {
                    585:                        char *name;
                    586:
                    587:                        host = nexthost(argc, argv);
                    588:                        if (host == NULL)
                    589:                                break;
                    590:                        name = strnnsep(&host, " \t\n");
                    591:                        conalloc(name, *host ? host : name);
                    592:                }
                    593:                conloop();
                    594:        } while (host);
                    595:        while (ncon > 0)
                    596:                conloop();
                    597:
                    598:        return (0);
                    599: }