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

Annotation of src/usr.bin/ssh/key.c, Revision 1.84

1.84    ! djm         1: /* $OpenBSD: key.c,v 1.83 2010/02/26 20:29:54 djm Exp $ */
1.1       markus      2: /*
1.11      deraadt     3:  * read_bignum():
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *
                      6:  * As far as I am concerned, the code I have written for this software
                      7:  * can be used freely for any purpose.  Any derived versions of this
                      8:  * software must be clearly marked as such, and if the derived work is
                      9:  * incompatible with the protocol description in the RFC file, it must be
                     10:  * called by a name other than "ssh" or "Secure Shell".
                     11:  *
                     12:  *
1.28      markus     13:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.76      grunk      14:  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
1.1       markus     15:  *
                     16:  * Redistribution and use in source and binary forms, with or without
                     17:  * modification, are permitted provided that the following conditions
                     18:  * are met:
                     19:  * 1. Redistributions of source code must retain the above copyright
                     20:  *    notice, this list of conditions and the following disclaimer.
                     21:  * 2. Redistributions in binary form must reproduce the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer in the
                     23:  *    documentation and/or other materials provided with the distribution.
                     24:  *
                     25:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     26:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     27:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     28:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     29:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     30:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     31:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     32:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     33:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     34:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     35:  */
1.67      deraadt    36:
1.70      grunk      37: #include <sys/param.h>
1.67      deraadt    38: #include <sys/types.h>
1.1       markus     39:
1.2       markus     40: #include <openssl/evp.h>
1.65      stevesk    41:
1.66      stevesk    42: #include <stdio.h>
1.65      stevesk    43: #include <string.h>
1.15      markus     44:
1.1       markus     45: #include "xmalloc.h"
                     46: #include "key.h"
1.12      markus     47: #include "rsa.h"
1.3       markus     48: #include "uuencode.h"
1.12      markus     49: #include "buffer.h"
1.15      markus     50: #include "log.h"
1.83      djm        51: #include "ssh2.h"
                     52:
                     53: static struct KeyCert *
                     54: cert_new(void)
                     55: {
                     56:        struct KeyCert *cert;
                     57:
                     58:        cert = xcalloc(1, sizeof(*cert));
                     59:        buffer_init(&cert->certblob);
                     60:        buffer_init(&cert->constraints);
                     61:        cert->key_id = NULL;
                     62:        cert->principals = NULL;
                     63:        cert->signature_key = NULL;
                     64:        return cert;
                     65: }
1.1       markus     66:
                     67: Key *
                     68: key_new(int type)
                     69: {
                     70:        Key *k;
                     71:        RSA *rsa;
                     72:        DSA *dsa;
1.63      djm        73:        k = xcalloc(1, sizeof(*k));
1.1       markus     74:        k->type = type;
1.3       markus     75:        k->dsa = NULL;
                     76:        k->rsa = NULL;
1.83      djm        77:        k->cert = NULL;
1.1       markus     78:        switch (k->type) {
1.12      markus     79:        case KEY_RSA1:
1.1       markus     80:        case KEY_RSA:
1.83      djm        81:        case KEY_RSA_CERT:
1.38      markus     82:                if ((rsa = RSA_new()) == NULL)
                     83:                        fatal("key_new: RSA_new failed");
                     84:                if ((rsa->n = BN_new()) == NULL)
                     85:                        fatal("key_new: BN_new failed");
                     86:                if ((rsa->e = BN_new()) == NULL)
                     87:                        fatal("key_new: BN_new failed");
1.1       markus     88:                k->rsa = rsa;
                     89:                break;
                     90:        case KEY_DSA:
1.83      djm        91:        case KEY_DSA_CERT:
1.38      markus     92:                if ((dsa = DSA_new()) == NULL)
                     93:                        fatal("key_new: DSA_new failed");
                     94:                if ((dsa->p = BN_new()) == NULL)
                     95:                        fatal("key_new: BN_new failed");
                     96:                if ((dsa->q = BN_new()) == NULL)
                     97:                        fatal("key_new: BN_new failed");
                     98:                if ((dsa->g = BN_new()) == NULL)
                     99:                        fatal("key_new: BN_new failed");
                    100:                if ((dsa->pub_key = BN_new()) == NULL)
                    101:                        fatal("key_new: BN_new failed");
1.1       markus    102:                k->dsa = dsa;
                    103:                break;
1.12      markus    104:        case KEY_UNSPEC:
1.1       markus    105:                break;
                    106:        default:
                    107:                fatal("key_new: bad key type %d", k->type);
                    108:                break;
                    109:        }
1.83      djm       110:
                    111:        if (key_is_cert(k))
                    112:                k->cert = cert_new();
                    113:
1.1       markus    114:        return k;
                    115: }
1.45      deraadt   116:
1.83      djm       117: void
                    118: key_add_private(Key *k)
1.12      markus    119: {
                    120:        switch (k->type) {
                    121:        case KEY_RSA1:
                    122:        case KEY_RSA:
1.83      djm       123:        case KEY_RSA_CERT:
1.38      markus    124:                if ((k->rsa->d = BN_new()) == NULL)
                    125:                        fatal("key_new_private: BN_new failed");
                    126:                if ((k->rsa->iqmp = BN_new()) == NULL)
                    127:                        fatal("key_new_private: BN_new failed");
                    128:                if ((k->rsa->q = BN_new()) == NULL)
                    129:                        fatal("key_new_private: BN_new failed");
                    130:                if ((k->rsa->p = BN_new()) == NULL)
                    131:                        fatal("key_new_private: BN_new failed");
                    132:                if ((k->rsa->dmq1 = BN_new()) == NULL)
                    133:                        fatal("key_new_private: BN_new failed");
                    134:                if ((k->rsa->dmp1 = BN_new()) == NULL)
                    135:                        fatal("key_new_private: BN_new failed");
1.12      markus    136:                break;
                    137:        case KEY_DSA:
1.83      djm       138:        case KEY_DSA_CERT:
1.38      markus    139:                if ((k->dsa->priv_key = BN_new()) == NULL)
                    140:                        fatal("key_new_private: BN_new failed");
1.12      markus    141:                break;
                    142:        case KEY_UNSPEC:
                    143:                break;
                    144:        default:
                    145:                break;
                    146:        }
1.83      djm       147: }
                    148:
                    149: Key *
                    150: key_new_private(int type)
                    151: {
                    152:        Key *k = key_new(type);
                    153:
                    154:        key_add_private(k);
1.12      markus    155:        return k;
                    156: }
1.45      deraadt   157:
1.83      djm       158: static void
                    159: cert_free(struct KeyCert *cert)
                    160: {
                    161:        u_int i;
                    162:
                    163:        buffer_free(&cert->certblob);
                    164:        buffer_free(&cert->constraints);
                    165:        if (cert->key_id != NULL)
                    166:                xfree(cert->key_id);
                    167:        for (i = 0; i < cert->nprincipals; i++)
                    168:                xfree(cert->principals[i]);
                    169:        if (cert->principals != NULL)
                    170:                xfree(cert->principals);
                    171:        if (cert->signature_key != NULL)
                    172:                key_free(cert->signature_key);
                    173: }
                    174:
1.1       markus    175: void
                    176: key_free(Key *k)
                    177: {
1.60      djm       178:        if (k == NULL)
1.62      deraadt   179:                fatal("key_free: key is NULL");
1.1       markus    180:        switch (k->type) {
1.12      markus    181:        case KEY_RSA1:
1.1       markus    182:        case KEY_RSA:
1.83      djm       183:        case KEY_RSA_CERT:
1.1       markus    184:                if (k->rsa != NULL)
                    185:                        RSA_free(k->rsa);
                    186:                k->rsa = NULL;
                    187:                break;
                    188:        case KEY_DSA:
1.83      djm       189:        case KEY_DSA_CERT:
1.1       markus    190:                if (k->dsa != NULL)
                    191:                        DSA_free(k->dsa);
                    192:                k->dsa = NULL;
                    193:                break;
1.12      markus    194:        case KEY_UNSPEC:
                    195:                break;
1.1       markus    196:        default:
                    197:                fatal("key_free: bad key type %d", k->type);
                    198:                break;
                    199:        }
1.83      djm       200:        if (key_is_cert(k)) {
                    201:                if (k->cert != NULL)
                    202:                        cert_free(k->cert);
                    203:                k->cert = NULL;
                    204:        }
                    205:
1.1       markus    206:        xfree(k);
                    207: }
1.55      jakob     208:
1.83      djm       209: static int
                    210: cert_compare(struct KeyCert *a, struct KeyCert *b)
                    211: {
                    212:        if (a == NULL && b == NULL)
                    213:                return 1;
                    214:        if (a == NULL || b == NULL)
                    215:                return 0;
                    216:        if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
                    217:                return 0;
                    218:        if (memcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
                    219:            buffer_len(&a->certblob)) != 0)
                    220:                return 0;
                    221:        return 1;
                    222: }
                    223:
                    224: /*
                    225:  * Compare public portions of key only, allowing comparisons between
                    226:  * certificates and plain keys too.
                    227:  */
1.1       markus    228: int
1.83      djm       229: key_equal_public(const Key *a, const Key *b)
1.1       markus    230: {
1.83      djm       231:        if (a == NULL || b == NULL ||
                    232:            key_type_plain(a->type) != key_type_plain(b->type))
1.1       markus    233:                return 0;
1.83      djm       234:
1.1       markus    235:        switch (a->type) {
1.12      markus    236:        case KEY_RSA1:
1.83      djm       237:        case KEY_RSA_CERT:
1.1       markus    238:        case KEY_RSA:
                    239:                return a->rsa != NULL && b->rsa != NULL &&
                    240:                    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
                    241:                    BN_cmp(a->rsa->n, b->rsa->n) == 0;
1.83      djm       242:        case KEY_DSA_CERT:
1.1       markus    243:        case KEY_DSA:
                    244:                return a->dsa != NULL && b->dsa != NULL &&
                    245:                    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
                    246:                    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
                    247:                    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
                    248:                    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
                    249:        default:
1.3       markus    250:                fatal("key_equal: bad key type %d", a->type);
1.1       markus    251:        }
1.78      stevesk   252:        /* NOTREACHED */
1.1       markus    253: }
                    254:
1.83      djm       255: int
                    256: key_equal(const Key *a, const Key *b)
                    257: {
                    258:        if (a == NULL || b == NULL || a->type != b->type)
                    259:                return 0;
                    260:        if (key_is_cert(a)) {
                    261:                if (!cert_compare(a->cert, b->cert))
                    262:                        return 0;
                    263:        }
                    264:        return key_equal_public(a, b);
                    265: }
                    266:
1.52      jakob     267: u_char*
1.83      djm       268: key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length)
1.1       markus    269: {
1.41      markus    270:        const EVP_MD *md = NULL;
1.21      markus    271:        EVP_MD_CTX ctx;
1.13      markus    272:        u_char *blob = NULL;
1.19      jakob     273:        u_char *retval = NULL;
1.40      markus    274:        u_int len = 0;
1.83      djm       275:        int nlen, elen, otype;
1.1       markus    276:
1.19      jakob     277:        *dgst_raw_length = 0;
                    278:
1.21      markus    279:        switch (dgst_type) {
                    280:        case SSH_FP_MD5:
                    281:                md = EVP_md5();
                    282:                break;
                    283:        case SSH_FP_SHA1:
                    284:                md = EVP_sha1();
                    285:                break;
                    286:        default:
                    287:                fatal("key_fingerprint_raw: bad digest type %d",
                    288:                    dgst_type);
                    289:        }
1.1       markus    290:        switch (k->type) {
1.12      markus    291:        case KEY_RSA1:
1.1       markus    292:                nlen = BN_num_bytes(k->rsa->n);
                    293:                elen = BN_num_bytes(k->rsa->e);
                    294:                len = nlen + elen;
1.3       markus    295:                blob = xmalloc(len);
                    296:                BN_bn2bin(k->rsa->n, blob);
                    297:                BN_bn2bin(k->rsa->e, blob + nlen);
1.1       markus    298:                break;
                    299:        case KEY_DSA:
1.12      markus    300:        case KEY_RSA:
                    301:                key_to_blob(k, &blob, &len);
                    302:                break;
1.83      djm       303:        case KEY_DSA_CERT:
                    304:        case KEY_RSA_CERT:
                    305:                /* We want a fingerprint of the _key_ not of the cert */
                    306:                otype = k->type;
                    307:                k->type = key_type_plain(k->type);
                    308:                key_to_blob(k, &blob, &len);
                    309:                k->type = otype;
                    310:                break;
1.12      markus    311:        case KEY_UNSPEC:
                    312:                return retval;
1.1       markus    313:        default:
1.19      jakob     314:                fatal("key_fingerprint_raw: bad key type %d", k->type);
1.1       markus    315:                break;
                    316:        }
1.3       markus    317:        if (blob != NULL) {
1.19      jakob     318:                retval = xmalloc(EVP_MAX_MD_SIZE);
1.8       markus    319:                EVP_DigestInit(&ctx, md);
                    320:                EVP_DigestUpdate(&ctx, blob, len);
1.39      markus    321:                EVP_DigestFinal(&ctx, retval, dgst_raw_length);
1.3       markus    322:                memset(blob, 0, len);
                    323:                xfree(blob);
1.19      jakob     324:        } else {
                    325:                fatal("key_fingerprint_raw: blob is null");
1.1       markus    326:        }
1.19      jakob     327:        return retval;
                    328: }
                    329:
1.46      deraadt   330: static char *
                    331: key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
1.19      jakob     332: {
                    333:        char *retval;
1.58      djm       334:        u_int i;
1.19      jakob     335:
1.63      djm       336:        retval = xcalloc(1, dgst_raw_len * 3 + 1);
1.36      deraadt   337:        for (i = 0; i < dgst_raw_len; i++) {
1.19      jakob     338:                char hex[4];
                    339:                snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
1.54      avsm      340:                strlcat(retval, hex, dgst_raw_len * 3 + 1);
1.19      jakob     341:        }
1.54      avsm      342:
                    343:        /* Remove the trailing ':' character */
1.19      jakob     344:        retval[(dgst_raw_len * 3) - 1] = '\0';
                    345:        return retval;
                    346: }
                    347:
1.46      deraadt   348: static char *
                    349: key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
1.19      jakob     350: {
                    351:        char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
                    352:        char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
                    353:            'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
1.20      jakob     354:        u_int i, j = 0, rounds, seed = 1;
1.19      jakob     355:        char *retval;
                    356:
                    357:        rounds = (dgst_raw_len / 2) + 1;
1.63      djm       358:        retval = xcalloc((rounds * 6), sizeof(char));
1.20      jakob     359:        retval[j++] = 'x';
                    360:        for (i = 0; i < rounds; i++) {
1.19      jakob     361:                u_int idx0, idx1, idx2, idx3, idx4;
1.20      jakob     362:                if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
                    363:                        idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
1.19      jakob     364:                            seed) % 6;
1.20      jakob     365:                        idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
                    366:                        idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
1.19      jakob     367:                            (seed / 6)) % 6;
1.20      jakob     368:                        retval[j++] = vowels[idx0];
                    369:                        retval[j++] = consonants[idx1];
                    370:                        retval[j++] = vowels[idx2];
                    371:                        if ((i + 1) < rounds) {
                    372:                                idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
                    373:                                idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
                    374:                                retval[j++] = consonants[idx3];
                    375:                                retval[j++] = '-';
                    376:                                retval[j++] = consonants[idx4];
1.19      jakob     377:                                seed = ((seed * 5) +
1.20      jakob     378:                                    ((((u_int)(dgst_raw[2 * i])) * 7) +
                    379:                                    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1.19      jakob     380:                        }
                    381:                } else {
                    382:                        idx0 = seed % 6;
                    383:                        idx1 = 16;
                    384:                        idx2 = seed / 6;
1.20      jakob     385:                        retval[j++] = vowels[idx0];
                    386:                        retval[j++] = consonants[idx1];
                    387:                        retval[j++] = vowels[idx2];
1.19      jakob     388:                }
                    389:        }
1.20      jakob     390:        retval[j++] = 'x';
                    391:        retval[j++] = '\0';
1.19      jakob     392:        return retval;
                    393: }
                    394:
1.70      grunk     395: /*
                    396:  * Draw an ASCII-Art representing the fingerprint so human brain can
                    397:  * profit from its built-in pattern recognition ability.
                    398:  * This technique is called "random art" and can be found in some
                    399:  * scientific publications like this original paper:
                    400:  *
                    401:  * "Hash Visualization: a New Technique to improve Real-World Security",
                    402:  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
                    403:  * Techniques and E-Commerce (CrypTEC '99)
                    404:  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
                    405:  *
                    406:  * The subject came up in a talk by Dan Kaminsky, too.
                    407:  *
                    408:  * If you see the picture is different, the key is different.
                    409:  * If the picture looks the same, you still know nothing.
                    410:  *
                    411:  * The algorithm used here is a worm crawling over a discrete plane,
                    412:  * leaving a trace (augmenting the field) everywhere it goes.
                    413:  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
                    414:  * makes the respective movement vector be ignored for this turn.
                    415:  * Graphs are not unambiguous, because circles in graphs can be
                    416:  * walked in either direction.
                    417:  */
1.74      grunk     418:
                    419: /*
                    420:  * Field sizes for the random art.  Have to be odd, so the starting point
                    421:  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
                    422:  * Else pictures would be too dense, and drawing the frame would
                    423:  * fail, too, because the key type would not fit in anymore.
                    424:  */
                    425: #define        FLDBASE         8
                    426: #define        FLDSIZE_Y       (FLDBASE + 1)
                    427: #define        FLDSIZE_X       (FLDBASE * 2 + 1)
1.70      grunk     428: static char *
1.74      grunk     429: key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
1.70      grunk     430: {
                    431:        /*
                    432:         * Chars to be used after each other every time the worm
                    433:         * intersects with itself.  Matter of taste.
                    434:         */
1.75      grunk     435:        char    *augmentation_string = " .o+=*BOX@%&#/^SE";
1.70      grunk     436:        char    *retval, *p;
1.71      otto      437:        u_char   field[FLDSIZE_X][FLDSIZE_Y];
1.70      grunk     438:        u_int    i, b;
                    439:        int      x, y;
1.72      grunk     440:        size_t   len = strlen(augmentation_string) - 1;
1.70      grunk     441:
                    442:        retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
                    443:
                    444:        /* initialize field */
1.71      otto      445:        memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1.70      grunk     446:        x = FLDSIZE_X / 2;
                    447:        y = FLDSIZE_Y / 2;
                    448:
                    449:        /* process raw key */
                    450:        for (i = 0; i < dgst_raw_len; i++) {
                    451:                int input;
                    452:                /* each byte conveys four 2-bit move commands */
                    453:                input = dgst_raw[i];
                    454:                for (b = 0; b < 4; b++) {
                    455:                        /* evaluate 2 bit, rest is shifted later */
                    456:                        x += (input & 0x1) ? 1 : -1;
                    457:                        y += (input & 0x2) ? 1 : -1;
                    458:
                    459:                        /* assure we are still in bounds */
                    460:                        x = MAX(x, 0);
                    461:                        y = MAX(y, 0);
                    462:                        x = MIN(x, FLDSIZE_X - 1);
                    463:                        y = MIN(y, FLDSIZE_Y - 1);
                    464:
                    465:                        /* augment the field */
1.79      grunk     466:                        if (field[x][y] < len - 2)
                    467:                                field[x][y]++;
1.70      grunk     468:                        input = input >> 2;
                    469:                }
                    470:        }
1.75      grunk     471:
                    472:        /* mark starting point and end point*/
                    473:        field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
                    474:        field[x][y] = len;
1.70      grunk     475:
                    476:        /* fill in retval */
1.77      otto      477:        snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
1.74      grunk     478:        p = strchr(retval, '\0');
1.70      grunk     479:
                    480:        /* output upper border */
1.77      otto      481:        for (i = p - retval - 1; i < FLDSIZE_X; i++)
1.70      grunk     482:                *p++ = '-';
                    483:        *p++ = '+';
                    484:        *p++ = '\n';
                    485:
                    486:        /* output content */
                    487:        for (y = 0; y < FLDSIZE_Y; y++) {
                    488:                *p++ = '|';
                    489:                for (x = 0; x < FLDSIZE_X; x++)
1.72      grunk     490:                        *p++ = augmentation_string[MIN(field[x][y], len)];
1.70      grunk     491:                *p++ = '|';
                    492:                *p++ = '\n';
                    493:        }
                    494:
                    495:        /* output lower border */
                    496:        *p++ = '+';
                    497:        for (i = 0; i < FLDSIZE_X; i++)
                    498:                *p++ = '-';
                    499:        *p++ = '+';
                    500:
                    501:        return retval;
                    502: }
                    503:
1.46      deraadt   504: char *
1.83      djm       505: key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
1.19      jakob     506: {
1.23      markus    507:        char *retval = NULL;
1.19      jakob     508:        u_char *dgst_raw;
1.39      markus    509:        u_int dgst_raw_len;
1.36      deraadt   510:
1.19      jakob     511:        dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
                    512:        if (!dgst_raw)
1.22      markus    513:                fatal("key_fingerprint: null from key_fingerprint_raw()");
1.35      deraadt   514:        switch (dgst_rep) {
1.19      jakob     515:        case SSH_FP_HEX:
                    516:                retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
                    517:                break;
                    518:        case SSH_FP_BUBBLEBABBLE:
                    519:                retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1.70      grunk     520:                break;
                    521:        case SSH_FP_RANDOMART:
1.74      grunk     522:                retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
1.19      jakob     523:                break;
                    524:        default:
1.80      stevesk   525:                fatal("key_fingerprint: bad digest representation %d",
1.19      jakob     526:                    dgst_rep);
                    527:                break;
                    528:        }
                    529:        memset(dgst_raw, 0, dgst_raw_len);
                    530:        xfree(dgst_raw);
1.1       markus    531:        return retval;
                    532: }
                    533:
                    534: /*
                    535:  * Reads a multiple-precision integer in decimal from the buffer, and advances
                    536:  * the pointer.  The integer must already be initialized.  This function is
                    537:  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
                    538:  * last processed (and maybe modified) character.  Note that this may modify
                    539:  * the buffer containing the number.
                    540:  */
1.27      itojun    541: static int
1.1       markus    542: read_bignum(char **cpp, BIGNUM * value)
                    543: {
                    544:        char *cp = *cpp;
                    545:        int old;
                    546:
                    547:        /* Skip any leading whitespace. */
                    548:        for (; *cp == ' ' || *cp == '\t'; cp++)
                    549:                ;
                    550:
                    551:        /* Check that it begins with a decimal digit. */
                    552:        if (*cp < '0' || *cp > '9')
                    553:                return 0;
                    554:
                    555:        /* Save starting position. */
                    556:        *cpp = cp;
                    557:
                    558:        /* Move forward until all decimal digits skipped. */
                    559:        for (; *cp >= '0' && *cp <= '9'; cp++)
                    560:                ;
                    561:
                    562:        /* Save the old terminating character, and replace it by \0. */
                    563:        old = *cp;
                    564:        *cp = 0;
                    565:
                    566:        /* Parse the number. */
                    567:        if (BN_dec2bn(&value, *cpp) == 0)
                    568:                return 0;
                    569:
                    570:        /* Restore old terminating character. */
                    571:        *cp = old;
                    572:
                    573:        /* Move beyond the number and return success. */
                    574:        *cpp = cp;
                    575:        return 1;
                    576: }
1.45      deraadt   577:
1.27      itojun    578: static int
1.1       markus    579: write_bignum(FILE *f, BIGNUM *num)
                    580: {
                    581:        char *buf = BN_bn2dec(num);
                    582:        if (buf == NULL) {
                    583:                error("write_bignum: BN_bn2dec() failed");
                    584:                return 0;
                    585:        }
                    586:        fprintf(f, " %s", buf);
1.33      markus    587:        OPENSSL_free(buf);
1.1       markus    588:        return 1;
                    589: }
1.12      markus    590:
1.32      markus    591: /* returns 1 ok, -1 error */
1.12      markus    592: int
1.3       markus    593: key_read(Key *ret, char **cpp)
1.1       markus    594: {
1.3       markus    595:        Key *k;
1.12      markus    596:        int success = -1;
                    597:        char *cp, *space;
                    598:        int len, n, type;
                    599:        u_int bits;
1.13      markus    600:        u_char *blob;
1.3       markus    601:
                    602:        cp = *cpp;
                    603:
1.35      deraadt   604:        switch (ret->type) {
1.12      markus    605:        case KEY_RSA1:
1.3       markus    606:                /* Get number of bits. */
                    607:                if (*cp < '0' || *cp > '9')
1.12      markus    608:                        return -1;      /* Bad bit count... */
1.3       markus    609:                for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
                    610:                        bits = 10 * bits + *cp - '0';
1.1       markus    611:                if (bits == 0)
1.12      markus    612:                        return -1;
1.3       markus    613:                *cpp = cp;
1.1       markus    614:                /* Get public exponent, public modulus. */
                    615:                if (!read_bignum(cpp, ret->rsa->e))
1.12      markus    616:                        return -1;
1.1       markus    617:                if (!read_bignum(cpp, ret->rsa->n))
1.12      markus    618:                        return -1;
1.82      dtucker   619:                /* validate the claimed number of bits */
                    620:                if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
                    621:                        verbose("key_read: claimed key size %d does not match "
                    622:                           "actual %d", bits, BN_num_bits(ret->rsa->n));
                    623:                        return -1;
                    624:                }
1.12      markus    625:                success = 1;
1.1       markus    626:                break;
1.12      markus    627:        case KEY_UNSPEC:
                    628:        case KEY_RSA:
1.1       markus    629:        case KEY_DSA:
1.83      djm       630:        case KEY_DSA_CERT:
                    631:        case KEY_RSA_CERT:
1.12      markus    632:                space = strchr(cp, ' ');
                    633:                if (space == NULL) {
1.50      markus    634:                        debug3("key_read: missing whitespace");
1.12      markus    635:                        return -1;
                    636:                }
                    637:                *space = '\0';
                    638:                type = key_type_from_name(cp);
                    639:                *space = ' ';
                    640:                if (type == KEY_UNSPEC) {
1.50      markus    641:                        debug3("key_read: missing keytype");
1.12      markus    642:                        return -1;
                    643:                }
                    644:                cp = space+1;
                    645:                if (*cp == '\0') {
                    646:                        debug3("key_read: short string");
                    647:                        return -1;
                    648:                }
                    649:                if (ret->type == KEY_UNSPEC) {
                    650:                        ret->type = type;
                    651:                } else if (ret->type != type) {
                    652:                        /* is a key, but different type */
                    653:                        debug3("key_read: type mismatch");
1.32      markus    654:                        return -1;
1.12      markus    655:                }
1.3       markus    656:                len = 2*strlen(cp);
                    657:                blob = xmalloc(len);
                    658:                n = uudecode(cp, blob, len);
1.6       markus    659:                if (n < 0) {
1.7       markus    660:                        error("key_read: uudecode %s failed", cp);
1.34      markus    661:                        xfree(blob);
1.12      markus    662:                        return -1;
1.6       markus    663:                }
1.53      markus    664:                k = key_from_blob(blob, (u_int)n);
1.34      markus    665:                xfree(blob);
1.7       markus    666:                if (k == NULL) {
1.12      markus    667:                        error("key_read: key_from_blob %s failed", cp);
                    668:                        return -1;
1.7       markus    669:                }
1.12      markus    670:                if (k->type != type) {
                    671:                        error("key_read: type mismatch: encoding error");
                    672:                        key_free(k);
                    673:                        return -1;
                    674:                }
                    675: /*XXXX*/
1.83      djm       676:                if (key_is_cert(ret)) {
                    677:                        if (!key_is_cert(k)) {
                    678:                                error("key_read: loaded key is not a cert");
                    679:                                key_free(k);
                    680:                                return -1;
                    681:                        }
                    682:                        if (ret->cert != NULL)
                    683:                                cert_free(ret->cert);
                    684:                        ret->cert = k->cert;
                    685:                        k->cert = NULL;
                    686:                }
                    687:                if (key_type_plain(ret->type) == KEY_RSA) {
1.12      markus    688:                        if (ret->rsa != NULL)
                    689:                                RSA_free(ret->rsa);
                    690:                        ret->rsa = k->rsa;
                    691:                        k->rsa = NULL;
                    692: #ifdef DEBUG_PK
                    693:                        RSA_print_fp(stderr, ret->rsa, 8);
                    694: #endif
1.83      djm       695:                }
                    696:                if (key_type_plain(ret->type) == KEY_DSA) {
1.12      markus    697:                        if (ret->dsa != NULL)
                    698:                                DSA_free(ret->dsa);
                    699:                        ret->dsa = k->dsa;
                    700:                        k->dsa = NULL;
                    701: #ifdef DEBUG_PK
                    702:                        DSA_print_fp(stderr, ret->dsa, 8);
                    703: #endif
                    704:                }
1.83      djm       705:                success = 1;
1.12      markus    706: /*XXXX*/
1.34      markus    707:                key_free(k);
1.12      markus    708:                if (success != 1)
                    709:                        break;
1.7       markus    710:                /* advance cp: skip whitespace and data */
                    711:                while (*cp == ' ' || *cp == '\t')
                    712:                        cp++;
                    713:                while (*cp != '\0' && *cp != ' ' && *cp != '\t')
                    714:                        cp++;
                    715:                *cpp = cp;
1.1       markus    716:                break;
                    717:        default:
1.3       markus    718:                fatal("key_read: bad key type: %d", ret->type);
1.1       markus    719:                break;
                    720:        }
1.12      markus    721:        return success;
1.1       markus    722: }
1.45      deraadt   723:
1.1       markus    724: int
1.55      jakob     725: key_write(const Key *key, FILE *f)
1.1       markus    726: {
1.40      markus    727:        int n, success = 0;
                    728:        u_int len, bits = 0;
1.49      markus    729:        u_char *blob;
                    730:        char *uu;
1.1       markus    731:
1.83      djm       732:        if (key_is_cert(key)) {
                    733:                if (key->cert == NULL) {
                    734:                        error("%s: no cert data", __func__);
                    735:                        return 0;
                    736:                }
                    737:                if (buffer_len(&key->cert->certblob) == 0) {
                    738:                        error("%s: no signed certificate blob", __func__);
                    739:                        return 0;
                    740:                }
                    741:        }
                    742:
                    743:        switch (key->type) {
                    744:        case KEY_RSA1:
                    745:                if (key->rsa == NULL)
                    746:                        return 0;
1.1       markus    747:                /* size of modulus 'n' */
                    748:                bits = BN_num_bits(key->rsa->n);
                    749:                fprintf(f, "%u", bits);
                    750:                if (write_bignum(f, key->rsa->e) &&
1.83      djm       751:                    write_bignum(f, key->rsa->n))
                    752:                        return 1;
                    753:                error("key_write: failed for RSA key");
                    754:                return 0;
                    755:        case KEY_DSA:
                    756:        case KEY_DSA_CERT:
                    757:                if (key->dsa == NULL)
                    758:                        return 0;
                    759:                break;
                    760:        case KEY_RSA:
                    761:        case KEY_RSA_CERT:
                    762:                if (key->rsa == NULL)
                    763:                        return 0;
                    764:                break;
                    765:        default:
                    766:                return 0;
                    767:        }
                    768:
                    769:        key_to_blob(key, &blob, &len);
                    770:        uu = xmalloc(2*len);
                    771:        n = uuencode(blob, len, uu, 2*len);
                    772:        if (n > 0) {
                    773:                fprintf(f, "%s %s", key_ssh_name(key), uu);
                    774:                success = 1;
1.1       markus    775:        }
1.83      djm       776:        xfree(blob);
                    777:        xfree(uu);
                    778:
1.1       markus    779:        return success;
                    780: }
1.45      deraadt   781:
1.55      jakob     782: const char *
                    783: key_type(const Key *k)
1.4       markus    784: {
                    785:        switch (k->type) {
1.12      markus    786:        case KEY_RSA1:
                    787:                return "RSA1";
1.4       markus    788:        case KEY_RSA:
                    789:                return "RSA";
                    790:        case KEY_DSA:
                    791:                return "DSA";
1.83      djm       792:        case KEY_RSA_CERT:
                    793:                return "RSA-CERT";
                    794:        case KEY_DSA_CERT:
                    795:                return "DSA-CERT";
1.4       markus    796:        }
                    797:        return "unknown";
1.10      markus    798: }
1.45      deraadt   799:
1.55      jakob     800: const char *
                    801: key_ssh_name(const Key *k)
1.12      markus    802: {
                    803:        switch (k->type) {
                    804:        case KEY_RSA:
                    805:                return "ssh-rsa";
                    806:        case KEY_DSA:
                    807:                return "ssh-dss";
1.83      djm       808:        case KEY_RSA_CERT:
                    809:                return "ssh-rsa-cert-v00@openssh.com";
                    810:        case KEY_DSA_CERT:
                    811:                return "ssh-dss-cert-v00@openssh.com";
1.12      markus    812:        }
                    813:        return "ssh-unknown";
                    814: }
1.45      deraadt   815:
1.12      markus    816: u_int
1.55      jakob     817: key_size(const Key *k)
1.35      deraadt   818: {
1.10      markus    819:        switch (k->type) {
1.12      markus    820:        case KEY_RSA1:
1.10      markus    821:        case KEY_RSA:
1.83      djm       822:        case KEY_RSA_CERT:
1.10      markus    823:                return BN_num_bits(k->rsa->n);
                    824:        case KEY_DSA:
1.83      djm       825:        case KEY_DSA_CERT:
1.10      markus    826:                return BN_num_bits(k->dsa->p);
                    827:        }
                    828:        return 0;
1.12      markus    829: }
                    830:
1.27      itojun    831: static RSA *
1.13      markus    832: rsa_generate_private_key(u_int bits)
1.12      markus    833: {
1.17      stevesk   834:        RSA *private;
1.61      deraadt   835:
1.81      markus    836:        private = RSA_generate_key(bits, RSA_F4, NULL, NULL);
1.17      stevesk   837:        if (private == NULL)
                    838:                fatal("rsa_generate_private_key: key generation failed.");
                    839:        return private;
1.12      markus    840: }
                    841:
1.27      itojun    842: static DSA*
1.13      markus    843: dsa_generate_private_key(u_int bits)
1.12      markus    844: {
                    845:        DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL);
1.61      deraadt   846:
1.12      markus    847:        if (private == NULL)
                    848:                fatal("dsa_generate_private_key: DSA_generate_parameters failed");
                    849:        if (!DSA_generate_key(private))
1.17      stevesk   850:                fatal("dsa_generate_private_key: DSA_generate_key failed.");
                    851:        if (private == NULL)
                    852:                fatal("dsa_generate_private_key: NULL.");
1.12      markus    853:        return private;
                    854: }
                    855:
                    856: Key *
1.13      markus    857: key_generate(int type, u_int bits)
1.12      markus    858: {
                    859:        Key *k = key_new(KEY_UNSPEC);
                    860:        switch (type) {
1.17      stevesk   861:        case KEY_DSA:
1.12      markus    862:                k->dsa = dsa_generate_private_key(bits);
                    863:                break;
                    864:        case KEY_RSA:
                    865:        case KEY_RSA1:
                    866:                k->rsa = rsa_generate_private_key(bits);
                    867:                break;
1.83      djm       868:        case KEY_RSA_CERT:
                    869:        case KEY_DSA_CERT:
                    870:                fatal("key_generate: cert keys cannot be generated directly");
1.12      markus    871:        default:
1.17      stevesk   872:                fatal("key_generate: unknown type %d", type);
1.12      markus    873:        }
1.17      stevesk   874:        k->type = type;
1.12      markus    875:        return k;
                    876: }
                    877:
1.83      djm       878: void
                    879: key_cert_copy(const Key *from_key, struct Key *to_key)
                    880: {
                    881:        u_int i;
                    882:        const struct KeyCert *from;
                    883:        struct KeyCert *to;
                    884:
                    885:        if (to_key->cert != NULL) {
                    886:                cert_free(to_key->cert);
                    887:                to_key->cert = NULL;
                    888:        }
                    889:
                    890:        if ((from = from_key->cert) == NULL)
                    891:                return;
                    892:
                    893:        to = to_key->cert = cert_new();
                    894:
                    895:        buffer_append(&to->certblob, buffer_ptr(&from->certblob),
                    896:            buffer_len(&from->certblob));
                    897:
                    898:        buffer_append(&to->constraints, buffer_ptr(&from->constraints),
                    899:            buffer_len(&from->constraints));
                    900:
                    901:        to->type = from->type;
                    902:        to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
                    903:        to->valid_after = from->valid_after;
                    904:        to->valid_before = from->valid_before;
                    905:        to->signature_key = from->signature_key == NULL ?
                    906:            NULL : key_from_private(from->signature_key);
                    907:
                    908:        to->nprincipals = from->nprincipals;
                    909:        if (to->nprincipals > CERT_MAX_PRINCIPALS)
                    910:                fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
                    911:                    __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
                    912:        if (to->nprincipals > 0) {
                    913:                to->principals = xcalloc(from->nprincipals,
                    914:                    sizeof(*to->principals));
                    915:                for (i = 0; i < to->nprincipals; i++)
                    916:                        to->principals[i] = xstrdup(from->principals[i]);
                    917:        }
                    918: }
                    919:
1.12      markus    920: Key *
1.55      jakob     921: key_from_private(const Key *k)
1.12      markus    922: {
                    923:        Key *n = NULL;
                    924:        switch (k->type) {
1.17      stevesk   925:        case KEY_DSA:
1.83      djm       926:        case KEY_DSA_CERT:
1.12      markus    927:                n = key_new(k->type);
1.68      markus    928:                if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
                    929:                    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
                    930:                    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
                    931:                    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
                    932:                        fatal("key_from_private: BN_copy failed");
1.12      markus    933:                break;
                    934:        case KEY_RSA:
                    935:        case KEY_RSA1:
1.83      djm       936:        case KEY_RSA_CERT:
1.12      markus    937:                n = key_new(k->type);
1.68      markus    938:                if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
                    939:                    (BN_copy(n->rsa->e, k->rsa->e) == NULL))
                    940:                        fatal("key_from_private: BN_copy failed");
1.12      markus    941:                break;
                    942:        default:
1.17      stevesk   943:                fatal("key_from_private: unknown type %d", k->type);
1.12      markus    944:                break;
                    945:        }
1.83      djm       946:        if (key_is_cert(k))
                    947:                key_cert_copy(k, n);
1.12      markus    948:        return n;
                    949: }
                    950:
                    951: int
                    952: key_type_from_name(char *name)
                    953: {
1.35      deraadt   954:        if (strcmp(name, "rsa1") == 0) {
1.12      markus    955:                return KEY_RSA1;
1.35      deraadt   956:        } else if (strcmp(name, "rsa") == 0) {
1.12      markus    957:                return KEY_RSA;
1.35      deraadt   958:        } else if (strcmp(name, "dsa") == 0) {
1.12      markus    959:                return KEY_DSA;
1.35      deraadt   960:        } else if (strcmp(name, "ssh-rsa") == 0) {
1.12      markus    961:                return KEY_RSA;
1.35      deraadt   962:        } else if (strcmp(name, "ssh-dss") == 0) {
1.12      markus    963:                return KEY_DSA;
1.83      djm       964:        } else if (strcmp(name, "ssh-rsa-cert-v00@openssh.com") == 0) {
                    965:                return KEY_RSA_CERT;
                    966:        } else if (strcmp(name, "ssh-dss-cert-v00@openssh.com") == 0) {
                    967:                return KEY_DSA_CERT;
1.12      markus    968:        }
1.18      markus    969:        debug2("key_type_from_name: unknown key type '%s'", name);
1.12      markus    970:        return KEY_UNSPEC;
1.25      markus    971: }
                    972:
                    973: int
                    974: key_names_valid2(const char *names)
                    975: {
                    976:        char *s, *cp, *p;
                    977:
                    978:        if (names == NULL || strcmp(names, "") == 0)
                    979:                return 0;
                    980:        s = cp = xstrdup(names);
                    981:        for ((p = strsep(&cp, ",")); p && *p != '\0';
1.36      deraadt   982:            (p = strsep(&cp, ","))) {
1.25      markus    983:                switch (key_type_from_name(p)) {
                    984:                case KEY_RSA1:
                    985:                case KEY_UNSPEC:
                    986:                        xfree(s);
                    987:                        return 0;
                    988:                }
                    989:        }
                    990:        debug3("key names ok: [%s]", names);
                    991:        xfree(s);
                    992:        return 1;
1.12      markus    993: }
                    994:
1.83      djm       995: static int
                    996: cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
                    997: {
                    998:        u_char *principals, *constraints, *sig_key, *sig;
1.84    ! djm       999:        u_int signed_len, plen, clen, sklen, slen, kidlen;
1.83      djm      1000:        Buffer tmp;
                   1001:        char *principal;
                   1002:        int ret = -1;
                   1003:
                   1004:        buffer_init(&tmp);
                   1005:
                   1006:        /* Copy the entire key blob for verification and later serialisation */
                   1007:        buffer_append(&key->cert->certblob, blob, blen);
                   1008:
                   1009:        principals = constraints = sig_key = sig = NULL;
                   1010:        if (buffer_get_int_ret(&key->cert->type, b) != 0 ||
1.84    ! djm      1011:            (key->cert->key_id = buffer_get_string_ret(b, &kidlen)) == NULL ||
1.83      djm      1012:            (principals = buffer_get_string_ret(b, &plen)) == NULL ||
                   1013:            buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
                   1014:            buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
                   1015:            (constraints = buffer_get_string_ret(b, &clen)) == NULL ||
                   1016:            /* skip nonce */ buffer_get_string_ptr_ret(b, NULL) == NULL ||
                   1017:            /* skip reserved */ buffer_get_string_ptr_ret(b, NULL) == NULL ||
                   1018:            (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
                   1019:                error("%s: parse error", __func__);
                   1020:                goto out;
                   1021:        }
                   1022:
1.84    ! djm      1023:        if (kidlen != strlen(key->cert->key_id)) {
        !          1024:                error("%s: key ID contains \\0 character", __func__);
        !          1025:                goto out;
        !          1026:        }
        !          1027:
1.83      djm      1028:        /* Signature is left in the buffer so we can calculate this length */
                   1029:        signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
                   1030:
                   1031:        if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
                   1032:                error("%s: parse error", __func__);
                   1033:                goto out;
                   1034:        }
                   1035:
                   1036:        if (key->cert->type != SSH2_CERT_TYPE_USER &&
                   1037:            key->cert->type != SSH2_CERT_TYPE_HOST) {
                   1038:                error("Unknown certificate type %u", key->cert->type);
                   1039:                goto out;
                   1040:        }
                   1041:
                   1042:        buffer_append(&tmp, principals, plen);
                   1043:        while (buffer_len(&tmp) > 0) {
                   1044:                if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1.84    ! djm      1045:                        error("%s: Too many principals", __func__);
1.83      djm      1046:                        goto out;
                   1047:                }
1.84    ! djm      1048:                if ((principal = buffer_get_string_ret(&tmp, &plen)) == NULL) {
        !          1049:                        error("%s: Principals data invalid", __func__);
        !          1050:                        goto out;
        !          1051:                }
        !          1052:                if (strlen(principal) != plen) {
        !          1053:                        error("%s: Principal contains \\0 character",
        !          1054:                            __func__);
1.83      djm      1055:                        goto out;
                   1056:                }
                   1057:                key->cert->principals = xrealloc(key->cert->principals,
                   1058:                    key->cert->nprincipals + 1, sizeof(*key->cert->principals));
                   1059:                key->cert->principals[key->cert->nprincipals++] = principal;
                   1060:        }
                   1061:
                   1062:        buffer_clear(&tmp);
                   1063:
                   1064:        buffer_append(&key->cert->constraints, constraints, clen);
                   1065:        buffer_append(&tmp, constraints, clen);
                   1066:        /* validate structure */
                   1067:        while (buffer_len(&tmp) != 0) {
                   1068:                if (buffer_get_string_ptr(&tmp, NULL) == NULL ||
                   1069:                    buffer_get_string_ptr(&tmp, NULL) == NULL) {
1.84    ! djm      1070:                        error("%s: Constraints data invalid", __func__);
1.83      djm      1071:                        goto out;
                   1072:                }
                   1073:        }
                   1074:        buffer_clear(&tmp);
                   1075:
                   1076:        if ((key->cert->signature_key = key_from_blob(sig_key,
                   1077:            sklen)) == NULL) {
1.84    ! djm      1078:                error("%s: Signature key invalid", __func__);
1.83      djm      1079:                goto out;
                   1080:        }
                   1081:        if (key->cert->signature_key->type != KEY_RSA &&
                   1082:            key->cert->signature_key->type != KEY_DSA) {
1.84    ! djm      1083:                error("%s: Invalid signature key type %s (%d)", __func__,
1.83      djm      1084:                    key_type(key->cert->signature_key),
                   1085:                    key->cert->signature_key->type);
                   1086:                goto out;
                   1087:        }
                   1088:
                   1089:        switch (key_verify(key->cert->signature_key, sig, slen,
                   1090:            buffer_ptr(&key->cert->certblob), signed_len)) {
                   1091:        case 1:
1.84    ! djm      1092:                ret = 0;
1.83      djm      1093:                break; /* Good signature */
                   1094:        case 0:
1.84    ! djm      1095:                error("%s: Invalid signature on certificate", __func__);
1.83      djm      1096:                goto out;
                   1097:        case -1:
1.84    ! djm      1098:                error("%s: Certificate signature verification failed",
        !          1099:                    __func__);
1.83      djm      1100:                goto out;
                   1101:        }
                   1102:
                   1103:  out:
                   1104:        buffer_free(&tmp);
                   1105:        if (principals != NULL)
                   1106:                xfree(principals);
                   1107:        if (constraints != NULL)
                   1108:                xfree(constraints);
                   1109:        if (sig_key != NULL)
                   1110:                xfree(sig_key);
                   1111:        if (sig != NULL)
                   1112:                xfree(sig);
                   1113:        return ret;
                   1114: }
                   1115:
1.12      markus   1116: Key *
1.55      jakob    1117: key_from_blob(const u_char *blob, u_int blen)
1.12      markus   1118: {
                   1119:        Buffer b;
                   1120:        int rlen, type;
1.57      djm      1121:        char *ktype = NULL;
1.12      markus   1122:        Key *key = NULL;
                   1123:
                   1124: #ifdef DEBUG_PK
                   1125:        dump_base64(stderr, blob, blen);
                   1126: #endif
                   1127:        buffer_init(&b);
                   1128:        buffer_append(&b, blob, blen);
1.57      djm      1129:        if ((ktype = buffer_get_string_ret(&b, NULL)) == NULL) {
                   1130:                error("key_from_blob: can't read key type");
                   1131:                goto out;
                   1132:        }
                   1133:
1.12      markus   1134:        type = key_type_from_name(ktype);
                   1135:
1.35      deraadt  1136:        switch (type) {
1.12      markus   1137:        case KEY_RSA:
1.83      djm      1138:        case KEY_RSA_CERT:
1.12      markus   1139:                key = key_new(type);
1.57      djm      1140:                if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
                   1141:                    buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
                   1142:                        error("key_from_blob: can't read rsa key");
1.83      djm      1143:  badkey:
1.57      djm      1144:                        key_free(key);
                   1145:                        key = NULL;
                   1146:                        goto out;
                   1147:                }
1.12      markus   1148: #ifdef DEBUG_PK
                   1149:                RSA_print_fp(stderr, key->rsa, 8);
                   1150: #endif
                   1151:                break;
                   1152:        case KEY_DSA:
1.83      djm      1153:        case KEY_DSA_CERT:
1.12      markus   1154:                key = key_new(type);
1.57      djm      1155:                if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
                   1156:                    buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
                   1157:                    buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
                   1158:                    buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
                   1159:                        error("key_from_blob: can't read dsa key");
1.83      djm      1160:                        goto badkey;
1.57      djm      1161:                }
1.12      markus   1162: #ifdef DEBUG_PK
                   1163:                DSA_print_fp(stderr, key->dsa, 8);
                   1164: #endif
                   1165:                break;
                   1166:        case KEY_UNSPEC:
                   1167:                key = key_new(type);
                   1168:                break;
                   1169:        default:
                   1170:                error("key_from_blob: cannot handle type %s", ktype);
1.57      djm      1171:                goto out;
1.12      markus   1172:        }
1.83      djm      1173:        if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
                   1174:                error("key_from_blob: can't parse cert data");
                   1175:                goto badkey;
                   1176:        }
1.12      markus   1177:        rlen = buffer_len(&b);
                   1178:        if (key != NULL && rlen != 0)
                   1179:                error("key_from_blob: remaining bytes in key blob %d", rlen);
1.57      djm      1180:  out:
                   1181:        if (ktype != NULL)
                   1182:                xfree(ktype);
1.12      markus   1183:        buffer_free(&b);
                   1184:        return key;
                   1185: }
                   1186:
                   1187: int
1.55      jakob    1188: key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1.12      markus   1189: {
                   1190:        Buffer b;
                   1191:        int len;
                   1192:
                   1193:        if (key == NULL) {
                   1194:                error("key_to_blob: key == NULL");
                   1195:                return 0;
                   1196:        }
                   1197:        buffer_init(&b);
1.35      deraadt  1198:        switch (key->type) {
1.83      djm      1199:        case KEY_DSA_CERT:
                   1200:        case KEY_RSA_CERT:
                   1201:                /* Use the existing blob */
                   1202:                buffer_append(&b, buffer_ptr(&key->cert->certblob),
                   1203:                    buffer_len(&key->cert->certblob));
                   1204:                break;
1.12      markus   1205:        case KEY_DSA:
                   1206:                buffer_put_cstring(&b, key_ssh_name(key));
                   1207:                buffer_put_bignum2(&b, key->dsa->p);
                   1208:                buffer_put_bignum2(&b, key->dsa->q);
                   1209:                buffer_put_bignum2(&b, key->dsa->g);
                   1210:                buffer_put_bignum2(&b, key->dsa->pub_key);
                   1211:                break;
                   1212:        case KEY_RSA:
                   1213:                buffer_put_cstring(&b, key_ssh_name(key));
1.14      markus   1214:                buffer_put_bignum2(&b, key->rsa->e);
1.12      markus   1215:                buffer_put_bignum2(&b, key->rsa->n);
                   1216:                break;
                   1217:        default:
1.31      markus   1218:                error("key_to_blob: unsupported key type %d", key->type);
                   1219:                buffer_free(&b);
                   1220:                return 0;
1.12      markus   1221:        }
                   1222:        len = buffer_len(&b);
1.48      markus   1223:        if (lenp != NULL)
                   1224:                *lenp = len;
                   1225:        if (blobp != NULL) {
                   1226:                *blobp = xmalloc(len);
                   1227:                memcpy(*blobp, buffer_ptr(&b), len);
                   1228:        }
1.12      markus   1229:        memset(buffer_ptr(&b), 0, len);
                   1230:        buffer_free(&b);
                   1231:        return len;
                   1232: }
                   1233:
                   1234: int
                   1235: key_sign(
1.55      jakob    1236:     const Key *key,
1.40      markus   1237:     u_char **sigp, u_int *lenp,
1.55      jakob    1238:     const u_char *data, u_int datalen)
1.12      markus   1239: {
1.35      deraadt  1240:        switch (key->type) {
1.83      djm      1241:        case KEY_DSA_CERT:
1.12      markus   1242:        case KEY_DSA:
                   1243:                return ssh_dss_sign(key, sigp, lenp, data, datalen);
1.83      djm      1244:        case KEY_RSA_CERT:
1.12      markus   1245:        case KEY_RSA:
                   1246:                return ssh_rsa_sign(key, sigp, lenp, data, datalen);
                   1247:        default:
1.56      markus   1248:                error("key_sign: invalid key type %d", key->type);
1.12      markus   1249:                return -1;
                   1250:        }
                   1251: }
                   1252:
1.44      markus   1253: /*
                   1254:  * key_verify returns 1 for a correct signature, 0 for an incorrect signature
                   1255:  * and -1 on error.
                   1256:  */
1.12      markus   1257: int
                   1258: key_verify(
1.55      jakob    1259:     const Key *key,
                   1260:     const u_char *signature, u_int signaturelen,
                   1261:     const u_char *data, u_int datalen)
1.12      markus   1262: {
1.26      markus   1263:        if (signaturelen == 0)
                   1264:                return -1;
                   1265:
1.35      deraadt  1266:        switch (key->type) {
1.83      djm      1267:        case KEY_DSA_CERT:
1.12      markus   1268:        case KEY_DSA:
                   1269:                return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1.83      djm      1270:        case KEY_RSA_CERT:
1.12      markus   1271:        case KEY_RSA:
                   1272:                return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
                   1273:        default:
1.56      markus   1274:                error("key_verify: invalid key type %d", key->type);
1.12      markus   1275:                return -1;
                   1276:        }
1.42      markus   1277: }
                   1278:
                   1279: /* Converts a private to a public key */
                   1280: Key *
1.55      jakob    1281: key_demote(const Key *k)
1.42      markus   1282: {
                   1283:        Key *pk;
1.43      markus   1284:
1.63      djm      1285:        pk = xcalloc(1, sizeof(*pk));
1.42      markus   1286:        pk->type = k->type;
                   1287:        pk->flags = k->flags;
                   1288:        pk->dsa = NULL;
                   1289:        pk->rsa = NULL;
                   1290:
                   1291:        switch (k->type) {
1.83      djm      1292:        case KEY_RSA_CERT:
                   1293:                key_cert_copy(k, pk);
                   1294:                /* FALLTHROUGH */
1.42      markus   1295:        case KEY_RSA1:
                   1296:        case KEY_RSA:
                   1297:                if ((pk->rsa = RSA_new()) == NULL)
                   1298:                        fatal("key_demote: RSA_new failed");
                   1299:                if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
                   1300:                        fatal("key_demote: BN_dup failed");
                   1301:                if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
                   1302:                        fatal("key_demote: BN_dup failed");
                   1303:                break;
1.83      djm      1304:        case KEY_DSA_CERT:
                   1305:                key_cert_copy(k, pk);
                   1306:                /* FALLTHROUGH */
1.42      markus   1307:        case KEY_DSA:
                   1308:                if ((pk->dsa = DSA_new()) == NULL)
                   1309:                        fatal("key_demote: DSA_new failed");
                   1310:                if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
                   1311:                        fatal("key_demote: BN_dup failed");
                   1312:                if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
                   1313:                        fatal("key_demote: BN_dup failed");
                   1314:                if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
                   1315:                        fatal("key_demote: BN_dup failed");
                   1316:                if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
                   1317:                        fatal("key_demote: BN_dup failed");
                   1318:                break;
                   1319:        default:
                   1320:                fatal("key_free: bad key type %d", k->type);
                   1321:                break;
                   1322:        }
                   1323:
                   1324:        return (pk);
1.83      djm      1325: }
                   1326:
                   1327: int
                   1328: key_is_cert(const Key *k)
                   1329: {
                   1330:        return k != NULL &&
                   1331:            (k->type == KEY_RSA_CERT || k->type == KEY_DSA_CERT);
                   1332: }
                   1333:
                   1334: /* Return the cert-less equivalent to a certified key type */
                   1335: int
                   1336: key_type_plain(int type)
                   1337: {
                   1338:        switch (type) {
                   1339:        case KEY_RSA_CERT:
                   1340:                return KEY_RSA;
                   1341:        case KEY_DSA_CERT:
                   1342:                return KEY_DSA;
                   1343:        default:
                   1344:                return type;
                   1345:        }
                   1346: }
                   1347:
                   1348: /* Convert a KEY_RSA or KEY_DSA to their _CERT equivalent */
                   1349: int
                   1350: key_to_certified(Key *k)
                   1351: {
                   1352:        switch (k->type) {
                   1353:        case KEY_RSA:
                   1354:                k->cert = cert_new();
                   1355:                k->type = KEY_RSA_CERT;
                   1356:                return 0;
                   1357:        case KEY_DSA:
                   1358:                k->cert = cert_new();
                   1359:                k->type = KEY_DSA_CERT;
                   1360:                return 0;
                   1361:        default:
                   1362:                error("%s: key has incorrect type %s", __func__, key_type(k));
                   1363:                return -1;
                   1364:        }
                   1365: }
                   1366:
                   1367: /* Convert a KEY_RSA_CERT or KEY_DSA_CERT to their raw key equivalent */
                   1368: int
                   1369: key_drop_cert(Key *k)
                   1370: {
                   1371:        switch (k->type) {
                   1372:        case KEY_RSA_CERT:
                   1373:                cert_free(k->cert);
                   1374:                k->type = KEY_RSA;
                   1375:                return 0;
                   1376:        case KEY_DSA_CERT:
                   1377:                cert_free(k->cert);
                   1378:                k->type = KEY_DSA;
                   1379:                return 0;
                   1380:        default:
                   1381:                error("%s: key has incorrect type %s", __func__, key_type(k));
                   1382:                return -1;
                   1383:        }
                   1384: }
                   1385:
                   1386: /* Sign a KEY_RSA_CERT or KEY_DSA_CERT, (re-)generating the signed certblob */
                   1387: int
                   1388: key_certify(Key *k, Key *ca)
                   1389: {
                   1390:        Buffer principals;
                   1391:        u_char *ca_blob, *sig_blob, nonce[32];
                   1392:        u_int i, ca_len, sig_len;
                   1393:
                   1394:        if (k->cert == NULL) {
                   1395:                error("%s: key lacks cert info", __func__);
                   1396:                return -1;
                   1397:        }
                   1398:
                   1399:        if (!key_is_cert(k)) {
                   1400:                error("%s: certificate has unknown type %d", __func__,
                   1401:                    k->cert->type);
                   1402:                return -1;
                   1403:        }
                   1404:
                   1405:        if (ca->type != KEY_RSA && ca->type != KEY_DSA) {
                   1406:                error("%s: CA key has unsupported type %s", __func__,
                   1407:                    key_type(ca));
                   1408:                return -1;
                   1409:        }
                   1410:
                   1411:        key_to_blob(ca, &ca_blob, &ca_len);
                   1412:
                   1413:        buffer_clear(&k->cert->certblob);
                   1414:        buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
                   1415:
                   1416:        switch (k->type) {
                   1417:        case KEY_DSA_CERT:
                   1418:                buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
                   1419:                buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
                   1420:                buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
                   1421:                buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
                   1422:                break;
                   1423:        case KEY_RSA_CERT:
                   1424:                buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
                   1425:                buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
                   1426:                break;
                   1427:        default:
                   1428:                error("%s: key has incorrect type %s", __func__, key_type(k));
                   1429:                buffer_clear(&k->cert->certblob);
                   1430:                xfree(ca_blob);
                   1431:                return -1;
                   1432:        }
                   1433:
                   1434:        buffer_put_int(&k->cert->certblob, k->cert->type);
                   1435:        buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
                   1436:
                   1437:        buffer_init(&principals);
                   1438:        for (i = 0; i < k->cert->nprincipals; i++)
                   1439:                buffer_put_cstring(&principals, k->cert->principals[i]);
                   1440:        buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
                   1441:            buffer_len(&principals));
                   1442:        buffer_free(&principals);
                   1443:
                   1444:        buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
                   1445:        buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
                   1446:        buffer_put_string(&k->cert->certblob,
                   1447:            buffer_ptr(&k->cert->constraints),
                   1448:            buffer_len(&k->cert->constraints));
                   1449:
                   1450:        arc4random_buf(&nonce, sizeof(nonce));
                   1451:        buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
                   1452:        buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
                   1453:        buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
                   1454:        xfree(ca_blob);
                   1455:
                   1456:        /* Sign the whole mess */
                   1457:        if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
                   1458:            buffer_len(&k->cert->certblob)) != 0) {
                   1459:                error("%s: signature operation failed", __func__);
                   1460:                buffer_clear(&k->cert->certblob);
                   1461:                return -1;
                   1462:        }
                   1463:        /* Append signature and we are done */
                   1464:        buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
                   1465:        xfree(sig_blob);
                   1466:
                   1467:        return 0;
                   1468: }
                   1469:
                   1470: int
                   1471: key_cert_check_authority(const Key *k, int want_host, int require_principal,
                   1472:     const char *name, const char **reason)
                   1473: {
                   1474:        u_int i, principal_matches;
                   1475:        time_t now = time(NULL);
                   1476:
                   1477:        if (want_host) {
                   1478:                if (k->cert->type != SSH2_CERT_TYPE_HOST) {
                   1479:                        *reason = "Certificate invalid: not a host certificate";
                   1480:                        return -1;
                   1481:                }
                   1482:        } else {
                   1483:                if (k->cert->type != SSH2_CERT_TYPE_USER) {
                   1484:                        *reason = "Certificate invalid: not a user certificate";
                   1485:                        return -1;
                   1486:                }
                   1487:        }
                   1488:        if (now < 0) {
                   1489:                error("%s: system clock lies before epoch", __func__);
                   1490:                *reason = "Certificate invalid: not yet valid";
                   1491:                return -1;
                   1492:        }
                   1493:        if ((u_int64_t)now < k->cert->valid_after) {
                   1494:                *reason = "Certificate invalid: not yet valid";
                   1495:                return -1;
                   1496:        }
                   1497:        if ((u_int64_t)now >= k->cert->valid_before) {
                   1498:                *reason = "Certificate invalid: expired";
                   1499:                return -1;
                   1500:        }
                   1501:        if (k->cert->nprincipals == 0) {
                   1502:                if (require_principal) {
                   1503:                        *reason = "Certificate lacks principal list";
                   1504:                        return -1;
                   1505:                }
                   1506:        } else {
                   1507:                principal_matches = 0;
                   1508:                for (i = 0; i < k->cert->nprincipals; i++) {
                   1509:                        if (strcmp(name, k->cert->principals[i]) == 0) {
                   1510:                                principal_matches = 1;
                   1511:                                break;
                   1512:                        }
                   1513:                }
                   1514:                if (!principal_matches) {
                   1515:                        *reason = "Certificate invalid: name is not a listed "
                   1516:                            "principal";
                   1517:                        return -1;
                   1518:                }
                   1519:        }
                   1520:        return 0;
1.4       markus   1521: }