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

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