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

Annotation of src/usr.bin/ssh/sshkey.c, Revision 1.20

1.20    ! djm         1: /* $OpenBSD: sshkey.c,v 1.19 2015/05/21 04:55:51 djm Exp $ */
1.1       djm         2: /*
                      3:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
                      4:  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
                      5:  * Copyright (c) 2010,2011 Damien Miller.  All rights reserved.
                      6:  *
                      7:  * Redistribution and use in source and binary forms, with or without
                      8:  * modification, are permitted provided that the following conditions
                      9:  * are met:
                     10:  * 1. Redistributions of source code must retain the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer.
                     12:  * 2. Redistributions in binary form must reproduce the above copyright
                     13:  *    notice, this list of conditions and the following disclaimer in the
                     14:  *    documentation and/or other materials provided with the distribution.
                     15:  *
                     16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     17:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     18:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     19:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     20:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     21:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     22:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     23:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     24:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     25:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     26:  */
                     27:
1.13      deraadt    28: #include <sys/param.h> /* MIN MAX */
1.1       djm        29: #include <sys/types.h>
1.7       djm        30: #include <netinet/in.h>
1.1       djm        31:
1.12      djm        32: #ifdef WITH_OPENSSL
1.1       djm        33: #include <openssl/evp.h>
                     34: #include <openssl/err.h>
                     35: #include <openssl/pem.h>
1.12      djm        36: #endif
1.1       djm        37:
                     38: #include "crypto_api.h"
                     39:
                     40: #include <errno.h>
                     41: #include <stdio.h>
                     42: #include <string.h>
                     43: #include <util.h>
1.13      deraadt    44: #include <limits.h>
1.7       djm        45: #include <resolv.h>
1.1       djm        46:
                     47: #include "ssh2.h"
                     48: #include "ssherr.h"
                     49: #include "misc.h"
                     50: #include "sshbuf.h"
                     51: #include "rsa.h"
                     52: #include "cipher.h"
                     53: #include "digest.h"
                     54: #define SSHKEY_INTERNAL
                     55: #include "sshkey.h"
1.11      djm        56: #include "match.h"
1.1       djm        57:
                     58: /* openssh private key file format */
                     59: #define MARK_BEGIN             "-----BEGIN OPENSSH PRIVATE KEY-----\n"
                     60: #define MARK_END               "-----END OPENSSH PRIVATE KEY-----\n"
                     61: #define MARK_BEGIN_LEN         (sizeof(MARK_BEGIN) - 1)
                     62: #define MARK_END_LEN           (sizeof(MARK_END) - 1)
                     63: #define KDFNAME                        "bcrypt"
                     64: #define AUTH_MAGIC             "openssh-key-v1"
                     65: #define SALT_LEN               16
                     66: #define DEFAULT_CIPHERNAME     "aes256-cbc"
                     67: #define        DEFAULT_ROUNDS          16
                     68:
                     69: /* Version identification string for SSH v1 identity files. */
                     70: #define LEGACY_BEGIN           "SSH PRIVATE KEY FILE FORMAT 1.1\n"
                     71:
1.14      djm        72: static int sshkey_from_blob_internal(struct sshbuf *buf,
1.1       djm        73:     struct sshkey **keyp, int allow_cert);
                     74:
                     75: /* Supported key types */
                     76: struct keytype {
                     77:        const char *name;
                     78:        const char *shortname;
                     79:        int type;
                     80:        int nid;
                     81:        int cert;
                     82: };
                     83: static const struct keytype keytypes[] = {
                     84:        { "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0 },
                     85:        { "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
                     86:            KEY_ED25519_CERT, 0, 1 },
                     87: #ifdef WITH_OPENSSL
                     88:        { NULL, "RSA1", KEY_RSA1, 0, 0 },
                     89:        { "ssh-rsa", "RSA", KEY_RSA, 0, 0 },
                     90:        { "ssh-dss", "DSA", KEY_DSA, 0, 0 },
                     91:        { "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0 },
                     92:        { "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0 },
                     93:        { "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0 },
                     94:        { "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1 },
                     95:        { "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1 },
                     96:        { "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
                     97:            KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1 },
                     98:        { "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
                     99:            KEY_ECDSA_CERT, NID_secp384r1, 1 },
                    100:        { "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
                    101:            KEY_ECDSA_CERT, NID_secp521r1, 1 },
                    102: #endif /* WITH_OPENSSL */
                    103:        { NULL, NULL, -1, -1, 0 }
                    104: };
                    105:
                    106: const char *
                    107: sshkey_type(const struct sshkey *k)
                    108: {
                    109:        const struct keytype *kt;
                    110:
                    111:        for (kt = keytypes; kt->type != -1; kt++) {
                    112:                if (kt->type == k->type)
                    113:                        return kt->shortname;
                    114:        }
                    115:        return "unknown";
                    116: }
                    117:
                    118: static const char *
                    119: sshkey_ssh_name_from_type_nid(int type, int nid)
                    120: {
                    121:        const struct keytype *kt;
                    122:
                    123:        for (kt = keytypes; kt->type != -1; kt++) {
                    124:                if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
                    125:                        return kt->name;
                    126:        }
                    127:        return "ssh-unknown";
                    128: }
                    129:
                    130: int
                    131: sshkey_type_is_cert(int type)
                    132: {
                    133:        const struct keytype *kt;
                    134:
                    135:        for (kt = keytypes; kt->type != -1; kt++) {
                    136:                if (kt->type == type)
                    137:                        return kt->cert;
                    138:        }
                    139:        return 0;
                    140: }
                    141:
                    142: const char *
                    143: sshkey_ssh_name(const struct sshkey *k)
                    144: {
                    145:        return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
                    146: }
                    147:
                    148: const char *
                    149: sshkey_ssh_name_plain(const struct sshkey *k)
                    150: {
                    151:        return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
                    152:            k->ecdsa_nid);
                    153: }
                    154:
                    155: int
                    156: sshkey_type_from_name(const char *name)
                    157: {
                    158:        const struct keytype *kt;
                    159:
                    160:        for (kt = keytypes; kt->type != -1; kt++) {
                    161:                /* Only allow shortname matches for plain key types */
                    162:                if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
                    163:                    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
                    164:                        return kt->type;
                    165:        }
                    166:        return KEY_UNSPEC;
                    167: }
                    168:
                    169: int
                    170: sshkey_ecdsa_nid_from_name(const char *name)
                    171: {
                    172:        const struct keytype *kt;
                    173:
1.4       djm       174:        for (kt = keytypes; kt->type != -1; kt++) {
                    175:                if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
                    176:                        continue;
                    177:                if (kt->name != NULL && strcmp(name, kt->name) == 0)
                    178:                        return kt->nid;
                    179:        }
1.1       djm       180:        return -1;
                    181: }
                    182:
                    183: char *
                    184: key_alg_list(int certs_only, int plain_only)
                    185: {
                    186:        char *tmp, *ret = NULL;
                    187:        size_t nlen, rlen = 0;
                    188:        const struct keytype *kt;
                    189:
                    190:        for (kt = keytypes; kt->type != -1; kt++) {
                    191:                if (kt->name == NULL)
                    192:                        continue;
                    193:                if ((certs_only && !kt->cert) || (plain_only && kt->cert))
                    194:                        continue;
                    195:                if (ret != NULL)
                    196:                        ret[rlen++] = '\n';
                    197:                nlen = strlen(kt->name);
                    198:                if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
                    199:                        free(ret);
                    200:                        return NULL;
                    201:                }
                    202:                ret = tmp;
                    203:                memcpy(ret + rlen, kt->name, nlen + 1);
                    204:                rlen += nlen;
                    205:        }
                    206:        return ret;
                    207: }
                    208:
                    209: int
1.11      djm       210: sshkey_names_valid2(const char *names, int allow_wildcard)
1.1       djm       211: {
                    212:        char *s, *cp, *p;
1.11      djm       213:        const struct keytype *kt;
                    214:        int type;
1.1       djm       215:
                    216:        if (names == NULL || strcmp(names, "") == 0)
                    217:                return 0;
                    218:        if ((s = cp = strdup(names)) == NULL)
                    219:                return 0;
                    220:        for ((p = strsep(&cp, ",")); p && *p != '\0';
                    221:            (p = strsep(&cp, ","))) {
1.11      djm       222:                type = sshkey_type_from_name(p);
                    223:                if (type == KEY_RSA1) {
                    224:                        free(s);
                    225:                        return 0;
                    226:                }
                    227:                if (type == KEY_UNSPEC) {
                    228:                        if (allow_wildcard) {
                    229:                                /*
                    230:                                 * Try matching key types against the string.
                    231:                                 * If any has a positive or negative match then
                    232:                                 * the component is accepted.
                    233:                                 */
                    234:                                for (kt = keytypes; kt->type != -1; kt++) {
                    235:                                        if (kt->type == KEY_RSA1)
                    236:                                                continue;
                    237:                                        if (match_pattern_list(kt->name,
1.17      djm       238:                                            p, 0) != 0)
1.11      djm       239:                                                break;
                    240:                                }
                    241:                                if (kt->type != -1)
                    242:                                        continue;
                    243:                        }
1.1       djm       244:                        free(s);
                    245:                        return 0;
                    246:                }
                    247:        }
                    248:        free(s);
                    249:        return 1;
                    250: }
                    251:
                    252: u_int
                    253: sshkey_size(const struct sshkey *k)
                    254: {
                    255:        switch (k->type) {
                    256: #ifdef WITH_OPENSSL
                    257:        case KEY_RSA1:
                    258:        case KEY_RSA:
                    259:        case KEY_RSA_CERT:
                    260:                return BN_num_bits(k->rsa->n);
                    261:        case KEY_DSA:
                    262:        case KEY_DSA_CERT:
                    263:                return BN_num_bits(k->dsa->p);
                    264:        case KEY_ECDSA:
                    265:        case KEY_ECDSA_CERT:
                    266:                return sshkey_curve_nid_to_bits(k->ecdsa_nid);
                    267: #endif /* WITH_OPENSSL */
                    268:        case KEY_ED25519:
                    269:        case KEY_ED25519_CERT:
                    270:                return 256;     /* XXX */
                    271:        }
                    272:        return 0;
                    273: }
                    274:
                    275: static int
                    276: sshkey_type_is_valid_ca(int type)
                    277: {
                    278:        switch (type) {
                    279:        case KEY_RSA:
                    280:        case KEY_DSA:
                    281:        case KEY_ECDSA:
                    282:        case KEY_ED25519:
                    283:                return 1;
                    284:        default:
                    285:                return 0;
                    286:        }
                    287: }
                    288:
                    289: int
                    290: sshkey_is_cert(const struct sshkey *k)
                    291: {
                    292:        if (k == NULL)
                    293:                return 0;
                    294:        return sshkey_type_is_cert(k->type);
                    295: }
                    296:
                    297: /* Return the cert-less equivalent to a certified key type */
                    298: int
                    299: sshkey_type_plain(int type)
                    300: {
                    301:        switch (type) {
                    302:        case KEY_RSA_CERT:
                    303:                return KEY_RSA;
                    304:        case KEY_DSA_CERT:
                    305:                return KEY_DSA;
                    306:        case KEY_ECDSA_CERT:
                    307:                return KEY_ECDSA;
                    308:        case KEY_ED25519_CERT:
                    309:                return KEY_ED25519;
                    310:        default:
                    311:                return type;
                    312:        }
                    313: }
                    314:
                    315: #ifdef WITH_OPENSSL
                    316: /* XXX: these are really begging for a table-driven approach */
                    317: int
                    318: sshkey_curve_name_to_nid(const char *name)
                    319: {
                    320:        if (strcmp(name, "nistp256") == 0)
                    321:                return NID_X9_62_prime256v1;
                    322:        else if (strcmp(name, "nistp384") == 0)
                    323:                return NID_secp384r1;
                    324:        else if (strcmp(name, "nistp521") == 0)
                    325:                return NID_secp521r1;
                    326:        else
                    327:                return -1;
                    328: }
                    329:
                    330: u_int
                    331: sshkey_curve_nid_to_bits(int nid)
                    332: {
                    333:        switch (nid) {
                    334:        case NID_X9_62_prime256v1:
                    335:                return 256;
                    336:        case NID_secp384r1:
                    337:                return 384;
                    338:        case NID_secp521r1:
                    339:                return 521;
                    340:        default:
                    341:                return 0;
                    342:        }
                    343: }
                    344:
                    345: int
                    346: sshkey_ecdsa_bits_to_nid(int bits)
                    347: {
                    348:        switch (bits) {
                    349:        case 256:
                    350:                return NID_X9_62_prime256v1;
                    351:        case 384:
                    352:                return NID_secp384r1;
                    353:        case 521:
                    354:                return NID_secp521r1;
                    355:        default:
                    356:                return -1;
                    357:        }
                    358: }
                    359:
                    360: const char *
                    361: sshkey_curve_nid_to_name(int nid)
                    362: {
                    363:        switch (nid) {
                    364:        case NID_X9_62_prime256v1:
                    365:                return "nistp256";
                    366:        case NID_secp384r1:
                    367:                return "nistp384";
                    368:        case NID_secp521r1:
                    369:                return "nistp521";
                    370:        default:
                    371:                return NULL;
                    372:        }
                    373: }
                    374:
                    375: int
                    376: sshkey_ec_nid_to_hash_alg(int nid)
                    377: {
                    378:        int kbits = sshkey_curve_nid_to_bits(nid);
                    379:
                    380:        if (kbits <= 0)
                    381:                return -1;
                    382:
                    383:        /* RFC5656 section 6.2.1 */
                    384:        if (kbits <= 256)
                    385:                return SSH_DIGEST_SHA256;
                    386:        else if (kbits <= 384)
                    387:                return SSH_DIGEST_SHA384;
                    388:        else
                    389:                return SSH_DIGEST_SHA512;
                    390: }
                    391: #endif /* WITH_OPENSSL */
                    392:
                    393: static void
                    394: cert_free(struct sshkey_cert *cert)
                    395: {
                    396:        u_int i;
                    397:
                    398:        if (cert == NULL)
                    399:                return;
                    400:        if (cert->certblob != NULL)
                    401:                sshbuf_free(cert->certblob);
                    402:        if (cert->critical != NULL)
                    403:                sshbuf_free(cert->critical);
                    404:        if (cert->extensions != NULL)
                    405:                sshbuf_free(cert->extensions);
                    406:        if (cert->key_id != NULL)
                    407:                free(cert->key_id);
                    408:        for (i = 0; i < cert->nprincipals; i++)
                    409:                free(cert->principals[i]);
                    410:        if (cert->principals != NULL)
                    411:                free(cert->principals);
                    412:        if (cert->signature_key != NULL)
                    413:                sshkey_free(cert->signature_key);
                    414:        explicit_bzero(cert, sizeof(*cert));
                    415:        free(cert);
                    416: }
                    417:
                    418: static struct sshkey_cert *
                    419: cert_new(void)
                    420: {
                    421:        struct sshkey_cert *cert;
                    422:
                    423:        if ((cert = calloc(1, sizeof(*cert))) == NULL)
                    424:                return NULL;
                    425:        if ((cert->certblob = sshbuf_new()) == NULL ||
                    426:            (cert->critical = sshbuf_new()) == NULL ||
                    427:            (cert->extensions = sshbuf_new()) == NULL) {
                    428:                cert_free(cert);
                    429:                return NULL;
                    430:        }
                    431:        cert->key_id = NULL;
                    432:        cert->principals = NULL;
                    433:        cert->signature_key = NULL;
                    434:        return cert;
                    435: }
                    436:
                    437: struct sshkey *
                    438: sshkey_new(int type)
                    439: {
                    440:        struct sshkey *k;
                    441: #ifdef WITH_OPENSSL
                    442:        RSA *rsa;
                    443:        DSA *dsa;
                    444: #endif /* WITH_OPENSSL */
                    445:
                    446:        if ((k = calloc(1, sizeof(*k))) == NULL)
                    447:                return NULL;
                    448:        k->type = type;
                    449:        k->ecdsa = NULL;
                    450:        k->ecdsa_nid = -1;
                    451:        k->dsa = NULL;
                    452:        k->rsa = NULL;
                    453:        k->cert = NULL;
                    454:        k->ed25519_sk = NULL;
                    455:        k->ed25519_pk = NULL;
                    456:        switch (k->type) {
                    457: #ifdef WITH_OPENSSL
                    458:        case KEY_RSA1:
                    459:        case KEY_RSA:
                    460:        case KEY_RSA_CERT:
                    461:                if ((rsa = RSA_new()) == NULL ||
                    462:                    (rsa->n = BN_new()) == NULL ||
                    463:                    (rsa->e = BN_new()) == NULL) {
                    464:                        if (rsa != NULL)
                    465:                                RSA_free(rsa);
                    466:                        free(k);
                    467:                        return NULL;
                    468:                }
                    469:                k->rsa = rsa;
                    470:                break;
                    471:        case KEY_DSA:
                    472:        case KEY_DSA_CERT:
                    473:                if ((dsa = DSA_new()) == NULL ||
                    474:                    (dsa->p = BN_new()) == NULL ||
                    475:                    (dsa->q = BN_new()) == NULL ||
                    476:                    (dsa->g = BN_new()) == NULL ||
                    477:                    (dsa->pub_key = BN_new()) == NULL) {
                    478:                        if (dsa != NULL)
                    479:                                DSA_free(dsa);
                    480:                        free(k);
                    481:                        return NULL;
                    482:                }
                    483:                k->dsa = dsa;
                    484:                break;
                    485:        case KEY_ECDSA:
                    486:        case KEY_ECDSA_CERT:
                    487:                /* Cannot do anything until we know the group */
                    488:                break;
                    489: #endif /* WITH_OPENSSL */
                    490:        case KEY_ED25519:
                    491:        case KEY_ED25519_CERT:
                    492:                /* no need to prealloc */
                    493:                break;
                    494:        case KEY_UNSPEC:
                    495:                break;
                    496:        default:
                    497:                free(k);
                    498:                return NULL;
                    499:                break;
                    500:        }
                    501:
                    502:        if (sshkey_is_cert(k)) {
                    503:                if ((k->cert = cert_new()) == NULL) {
                    504:                        sshkey_free(k);
                    505:                        return NULL;
                    506:                }
                    507:        }
                    508:
                    509:        return k;
                    510: }
                    511:
                    512: int
                    513: sshkey_add_private(struct sshkey *k)
                    514: {
                    515:        switch (k->type) {
                    516: #ifdef WITH_OPENSSL
                    517:        case KEY_RSA1:
                    518:        case KEY_RSA:
                    519:        case KEY_RSA_CERT:
                    520: #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
                    521:                if (bn_maybe_alloc_failed(k->rsa->d) ||
                    522:                    bn_maybe_alloc_failed(k->rsa->iqmp) ||
                    523:                    bn_maybe_alloc_failed(k->rsa->q) ||
                    524:                    bn_maybe_alloc_failed(k->rsa->p) ||
                    525:                    bn_maybe_alloc_failed(k->rsa->dmq1) ||
                    526:                    bn_maybe_alloc_failed(k->rsa->dmp1))
                    527:                        return SSH_ERR_ALLOC_FAIL;
                    528:                break;
                    529:        case KEY_DSA:
                    530:        case KEY_DSA_CERT:
                    531:                if (bn_maybe_alloc_failed(k->dsa->priv_key))
                    532:                        return SSH_ERR_ALLOC_FAIL;
                    533:                break;
                    534: #undef bn_maybe_alloc_failed
                    535:        case KEY_ECDSA:
                    536:        case KEY_ECDSA_CERT:
                    537:                /* Cannot do anything until we know the group */
                    538:                break;
                    539: #endif /* WITH_OPENSSL */
                    540:        case KEY_ED25519:
                    541:        case KEY_ED25519_CERT:
                    542:                /* no need to prealloc */
                    543:                break;
                    544:        case KEY_UNSPEC:
                    545:                break;
                    546:        default:
                    547:                return SSH_ERR_INVALID_ARGUMENT;
                    548:        }
                    549:        return 0;
                    550: }
                    551:
                    552: struct sshkey *
                    553: sshkey_new_private(int type)
                    554: {
                    555:        struct sshkey *k = sshkey_new(type);
                    556:
                    557:        if (k == NULL)
                    558:                return NULL;
                    559:        if (sshkey_add_private(k) != 0) {
                    560:                sshkey_free(k);
                    561:                return NULL;
                    562:        }
                    563:        return k;
                    564: }
                    565:
                    566: void
                    567: sshkey_free(struct sshkey *k)
                    568: {
                    569:        if (k == NULL)
                    570:                return;
                    571:        switch (k->type) {
                    572: #ifdef WITH_OPENSSL
                    573:        case KEY_RSA1:
                    574:        case KEY_RSA:
                    575:        case KEY_RSA_CERT:
                    576:                if (k->rsa != NULL)
                    577:                        RSA_free(k->rsa);
                    578:                k->rsa = NULL;
                    579:                break;
                    580:        case KEY_DSA:
                    581:        case KEY_DSA_CERT:
                    582:                if (k->dsa != NULL)
                    583:                        DSA_free(k->dsa);
                    584:                k->dsa = NULL;
                    585:                break;
                    586:        case KEY_ECDSA:
                    587:        case KEY_ECDSA_CERT:
                    588:                if (k->ecdsa != NULL)
                    589:                        EC_KEY_free(k->ecdsa);
                    590:                k->ecdsa = NULL;
                    591:                break;
                    592: #endif /* WITH_OPENSSL */
                    593:        case KEY_ED25519:
                    594:        case KEY_ED25519_CERT:
                    595:                if (k->ed25519_pk) {
                    596:                        explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
                    597:                        free(k->ed25519_pk);
                    598:                        k->ed25519_pk = NULL;
                    599:                }
                    600:                if (k->ed25519_sk) {
                    601:                        explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
                    602:                        free(k->ed25519_sk);
                    603:                        k->ed25519_sk = NULL;
                    604:                }
                    605:                break;
                    606:        case KEY_UNSPEC:
                    607:                break;
                    608:        default:
                    609:                break;
                    610:        }
                    611:        if (sshkey_is_cert(k))
                    612:                cert_free(k->cert);
                    613:        explicit_bzero(k, sizeof(*k));
                    614:        free(k);
                    615: }
                    616:
                    617: static int
                    618: cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
                    619: {
                    620:        if (a == NULL && b == NULL)
                    621:                return 1;
                    622:        if (a == NULL || b == NULL)
                    623:                return 0;
                    624:        if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
                    625:                return 0;
                    626:        if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
                    627:            sshbuf_len(a->certblob)) != 0)
                    628:                return 0;
                    629:        return 1;
                    630: }
                    631:
                    632: /*
                    633:  * Compare public portions of key only, allowing comparisons between
                    634:  * certificates and plain keys too.
                    635:  */
                    636: int
                    637: sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
                    638: {
                    639: #ifdef WITH_OPENSSL
                    640:        BN_CTX *bnctx;
                    641: #endif /* WITH_OPENSSL */
                    642:
                    643:        if (a == NULL || b == NULL ||
                    644:            sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
                    645:                return 0;
                    646:
                    647:        switch (a->type) {
                    648: #ifdef WITH_OPENSSL
                    649:        case KEY_RSA1:
                    650:        case KEY_RSA_CERT:
                    651:        case KEY_RSA:
                    652:                return a->rsa != NULL && b->rsa != NULL &&
                    653:                    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
                    654:                    BN_cmp(a->rsa->n, b->rsa->n) == 0;
                    655:        case KEY_DSA_CERT:
                    656:        case KEY_DSA:
                    657:                return a->dsa != NULL && b->dsa != NULL &&
                    658:                    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
                    659:                    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
                    660:                    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
                    661:                    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
                    662:        case KEY_ECDSA_CERT:
                    663:        case KEY_ECDSA:
                    664:                if (a->ecdsa == NULL || b->ecdsa == NULL ||
                    665:                    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
                    666:                    EC_KEY_get0_public_key(b->ecdsa) == NULL)
                    667:                        return 0;
                    668:                if ((bnctx = BN_CTX_new()) == NULL)
                    669:                        return 0;
                    670:                if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
                    671:                    EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
                    672:                    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
                    673:                    EC_KEY_get0_public_key(a->ecdsa),
                    674:                    EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
                    675:                        BN_CTX_free(bnctx);
                    676:                        return 0;
                    677:                }
                    678:                BN_CTX_free(bnctx);
                    679:                return 1;
                    680: #endif /* WITH_OPENSSL */
                    681:        case KEY_ED25519:
                    682:        case KEY_ED25519_CERT:
                    683:                return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
                    684:                    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
                    685:        default:
                    686:                return 0;
                    687:        }
                    688:        /* NOTREACHED */
                    689: }
                    690:
                    691: int
                    692: sshkey_equal(const struct sshkey *a, const struct sshkey *b)
                    693: {
                    694:        if (a == NULL || b == NULL || a->type != b->type)
                    695:                return 0;
                    696:        if (sshkey_is_cert(a)) {
                    697:                if (!cert_compare(a->cert, b->cert))
                    698:                        return 0;
                    699:        }
                    700:        return sshkey_equal_public(a, b);
                    701: }
                    702:
                    703: static int
                    704: to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
                    705: {
                    706:        int type, ret = SSH_ERR_INTERNAL_ERROR;
                    707:        const char *typename;
                    708:
                    709:        if (key == NULL)
                    710:                return SSH_ERR_INVALID_ARGUMENT;
                    711:
1.19      djm       712:        if (sshkey_is_cert(key)) {
                    713:                if (key->cert == NULL)
                    714:                        return SSH_ERR_EXPECTED_CERT;
                    715:                if (sshbuf_len(key->cert->certblob) == 0)
                    716:                        return SSH_ERR_KEY_LACKS_CERTBLOB;
                    717:        }
1.1       djm       718:        type = force_plain ? sshkey_type_plain(key->type) : key->type;
                    719:        typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
                    720:
                    721:        switch (type) {
                    722: #ifdef WITH_OPENSSL
                    723:        case KEY_DSA_CERT:
                    724:        case KEY_ECDSA_CERT:
                    725:        case KEY_RSA_CERT:
                    726: #endif /* WITH_OPENSSL */
                    727:        case KEY_ED25519_CERT:
                    728:                /* Use the existing blob */
                    729:                /* XXX modified flag? */
                    730:                if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
                    731:                        return ret;
                    732:                break;
                    733: #ifdef WITH_OPENSSL
                    734:        case KEY_DSA:
                    735:                if (key->dsa == NULL)
                    736:                        return SSH_ERR_INVALID_ARGUMENT;
                    737:                if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
                    738:                    (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
                    739:                    (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
                    740:                    (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
                    741:                    (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
                    742:                        return ret;
                    743:                break;
                    744:        case KEY_ECDSA:
                    745:                if (key->ecdsa == NULL)
                    746:                        return SSH_ERR_INVALID_ARGUMENT;
                    747:                if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
                    748:                    (ret = sshbuf_put_cstring(b,
                    749:                    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
                    750:                    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
                    751:                        return ret;
                    752:                break;
                    753:        case KEY_RSA:
                    754:                if (key->rsa == NULL)
                    755:                        return SSH_ERR_INVALID_ARGUMENT;
                    756:                if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
                    757:                    (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
                    758:                    (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
                    759:                        return ret;
                    760:                break;
                    761: #endif /* WITH_OPENSSL */
                    762:        case KEY_ED25519:
                    763:                if (key->ed25519_pk == NULL)
                    764:                        return SSH_ERR_INVALID_ARGUMENT;
                    765:                if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
                    766:                    (ret = sshbuf_put_string(b,
                    767:                    key->ed25519_pk, ED25519_PK_SZ)) != 0)
                    768:                        return ret;
                    769:                break;
                    770:        default:
                    771:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                    772:        }
                    773:        return 0;
                    774: }
                    775:
                    776: int
1.14      djm       777: sshkey_putb(const struct sshkey *key, struct sshbuf *b)
1.1       djm       778: {
                    779:        return to_blob_buf(key, b, 0);
                    780: }
                    781:
                    782: int
1.14      djm       783: sshkey_puts(const struct sshkey *key, struct sshbuf *b)
                    784: {
                    785:        struct sshbuf *tmp;
                    786:        int r;
                    787:
                    788:        if ((tmp = sshbuf_new()) == NULL)
                    789:                return SSH_ERR_ALLOC_FAIL;
                    790:        r = to_blob_buf(key, tmp, 0);
                    791:        if (r == 0)
                    792:                r = sshbuf_put_stringb(b, tmp);
                    793:        sshbuf_free(tmp);
                    794:        return r;
                    795: }
                    796:
                    797: int
                    798: sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
1.1       djm       799: {
                    800:        return to_blob_buf(key, b, 1);
                    801: }
                    802:
                    803: static int
                    804: to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
                    805: {
                    806:        int ret = SSH_ERR_INTERNAL_ERROR;
                    807:        size_t len;
                    808:        struct sshbuf *b = NULL;
                    809:
                    810:        if (lenp != NULL)
                    811:                *lenp = 0;
                    812:        if (blobp != NULL)
                    813:                *blobp = NULL;
                    814:        if ((b = sshbuf_new()) == NULL)
                    815:                return SSH_ERR_ALLOC_FAIL;
                    816:        if ((ret = to_blob_buf(key, b, force_plain)) != 0)
                    817:                goto out;
                    818:        len = sshbuf_len(b);
                    819:        if (lenp != NULL)
                    820:                *lenp = len;
                    821:        if (blobp != NULL) {
                    822:                if ((*blobp = malloc(len)) == NULL) {
                    823:                        ret = SSH_ERR_ALLOC_FAIL;
                    824:                        goto out;
                    825:                }
                    826:                memcpy(*blobp, sshbuf_ptr(b), len);
                    827:        }
                    828:        ret = 0;
                    829:  out:
                    830:        sshbuf_free(b);
                    831:        return ret;
                    832: }
                    833:
                    834: int
                    835: sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
                    836: {
                    837:        return to_blob(key, blobp, lenp, 0);
                    838: }
                    839:
                    840: int
                    841: sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
                    842: {
                    843:        return to_blob(key, blobp, lenp, 1);
                    844: }
                    845:
                    846: int
1.7       djm       847: sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
1.1       djm       848:     u_char **retp, size_t *lenp)
                    849: {
                    850:        u_char *blob = NULL, *ret = NULL;
                    851:        size_t blob_len = 0;
1.7       djm       852:        int r = SSH_ERR_INTERNAL_ERROR;
1.1       djm       853:
                    854:        if (retp != NULL)
                    855:                *retp = NULL;
                    856:        if (lenp != NULL)
                    857:                *lenp = 0;
1.7       djm       858:        if (ssh_digest_bytes(dgst_alg) == 0) {
1.1       djm       859:                r = SSH_ERR_INVALID_ARGUMENT;
                    860:                goto out;
                    861:        }
                    862:
                    863:        if (k->type == KEY_RSA1) {
                    864: #ifdef WITH_OPENSSL
                    865:                int nlen = BN_num_bytes(k->rsa->n);
                    866:                int elen = BN_num_bytes(k->rsa->e);
                    867:
                    868:                blob_len = nlen + elen;
                    869:                if (nlen >= INT_MAX - elen ||
                    870:                    (blob = malloc(blob_len)) == NULL) {
                    871:                        r = SSH_ERR_ALLOC_FAIL;
                    872:                        goto out;
                    873:                }
                    874:                BN_bn2bin(k->rsa->n, blob);
                    875:                BN_bn2bin(k->rsa->e, blob + nlen);
                    876: #endif /* WITH_OPENSSL */
                    877:        } else if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
                    878:                goto out;
                    879:        if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
                    880:                r = SSH_ERR_ALLOC_FAIL;
                    881:                goto out;
                    882:        }
1.7       djm       883:        if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
1.1       djm       884:            ret, SSH_DIGEST_MAX_LENGTH)) != 0)
                    885:                goto out;
                    886:        /* success */
                    887:        if (retp != NULL) {
                    888:                *retp = ret;
                    889:                ret = NULL;
                    890:        }
                    891:        if (lenp != NULL)
1.7       djm       892:                *lenp = ssh_digest_bytes(dgst_alg);
1.1       djm       893:        r = 0;
                    894:  out:
                    895:        free(ret);
                    896:        if (blob != NULL) {
                    897:                explicit_bzero(blob, blob_len);
                    898:                free(blob);
                    899:        }
                    900:        return r;
                    901: }
                    902:
                    903: static char *
1.7       djm       904: fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
                    905: {
                    906:        char *ret;
                    907:        size_t plen = strlen(alg) + 1;
                    908:        size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
                    909:        int r;
                    910:
                    911:        if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
                    912:                return NULL;
                    913:        strlcpy(ret, alg, rlen);
                    914:        strlcat(ret, ":", rlen);
                    915:        if (dgst_raw_len == 0)
                    916:                return ret;
                    917:        if ((r = b64_ntop(dgst_raw, dgst_raw_len,
                    918:            ret + plen, rlen - plen)) == -1) {
                    919:                explicit_bzero(ret, rlen);
                    920:                free(ret);
                    921:                return NULL;
                    922:        }
                    923:        /* Trim padding characters from end */
                    924:        ret[strcspn(ret, "=")] = '\0';
                    925:        return ret;
                    926: }
                    927:
                    928: static char *
                    929: fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1.1       djm       930: {
1.7       djm       931:        char *retval, hex[5];
                    932:        size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
1.1       djm       933:
1.7       djm       934:        if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
1.1       djm       935:                return NULL;
1.7       djm       936:        strlcpy(retval, alg, rlen);
                    937:        strlcat(retval, ":", rlen);
1.1       djm       938:        for (i = 0; i < dgst_raw_len; i++) {
1.7       djm       939:                snprintf(hex, sizeof(hex), "%s%02x",
                    940:                    i > 0 ? ":" : "", dgst_raw[i]);
                    941:                strlcat(retval, hex, rlen);
1.1       djm       942:        }
                    943:        return retval;
                    944: }
                    945:
                    946: static char *
                    947: fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
                    948: {
                    949:        char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
                    950:        char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
                    951:            'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
                    952:        u_int i, j = 0, rounds, seed = 1;
                    953:        char *retval;
                    954:
                    955:        rounds = (dgst_raw_len / 2) + 1;
                    956:        if ((retval = calloc(rounds, 6)) == NULL)
                    957:                return NULL;
                    958:        retval[j++] = 'x';
                    959:        for (i = 0; i < rounds; i++) {
                    960:                u_int idx0, idx1, idx2, idx3, idx4;
                    961:                if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
                    962:                        idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
                    963:                            seed) % 6;
                    964:                        idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
                    965:                        idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
                    966:                            (seed / 6)) % 6;
                    967:                        retval[j++] = vowels[idx0];
                    968:                        retval[j++] = consonants[idx1];
                    969:                        retval[j++] = vowels[idx2];
                    970:                        if ((i + 1) < rounds) {
                    971:                                idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
                    972:                                idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
                    973:                                retval[j++] = consonants[idx3];
                    974:                                retval[j++] = '-';
                    975:                                retval[j++] = consonants[idx4];
                    976:                                seed = ((seed * 5) +
                    977:                                    ((((u_int)(dgst_raw[2 * i])) * 7) +
                    978:                                    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
                    979:                        }
                    980:                } else {
                    981:                        idx0 = seed % 6;
                    982:                        idx1 = 16;
                    983:                        idx2 = seed / 6;
                    984:                        retval[j++] = vowels[idx0];
                    985:                        retval[j++] = consonants[idx1];
                    986:                        retval[j++] = vowels[idx2];
                    987:                }
                    988:        }
                    989:        retval[j++] = 'x';
                    990:        retval[j++] = '\0';
                    991:        return retval;
                    992: }
                    993:
                    994: /*
                    995:  * Draw an ASCII-Art representing the fingerprint so human brain can
                    996:  * profit from its built-in pattern recognition ability.
                    997:  * This technique is called "random art" and can be found in some
                    998:  * scientific publications like this original paper:
                    999:  *
                   1000:  * "Hash Visualization: a New Technique to improve Real-World Security",
                   1001:  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
                   1002:  * Techniques and E-Commerce (CrypTEC '99)
                   1003:  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
                   1004:  *
                   1005:  * The subject came up in a talk by Dan Kaminsky, too.
                   1006:  *
                   1007:  * If you see the picture is different, the key is different.
                   1008:  * If the picture looks the same, you still know nothing.
                   1009:  *
                   1010:  * The algorithm used here is a worm crawling over a discrete plane,
                   1011:  * leaving a trace (augmenting the field) everywhere it goes.
                   1012:  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
                   1013:  * makes the respective movement vector be ignored for this turn.
                   1014:  * Graphs are not unambiguous, because circles in graphs can be
                   1015:  * walked in either direction.
                   1016:  */
                   1017:
                   1018: /*
                   1019:  * Field sizes for the random art.  Have to be odd, so the starting point
                   1020:  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
                   1021:  * Else pictures would be too dense, and drawing the frame would
                   1022:  * fail, too, because the key type would not fit in anymore.
                   1023:  */
                   1024: #define        FLDBASE         8
                   1025: #define        FLDSIZE_Y       (FLDBASE + 1)
                   1026: #define        FLDSIZE_X       (FLDBASE * 2 + 1)
                   1027: static char *
1.7       djm      1028: fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1.1       djm      1029:     const struct sshkey *k)
                   1030: {
                   1031:        /*
                   1032:         * Chars to be used after each other every time the worm
                   1033:         * intersects with itself.  Matter of taste.
                   1034:         */
                   1035:        char    *augmentation_string = " .o+=*BOX@%&#/^SE";
1.7       djm      1036:        char    *retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1.1       djm      1037:        u_char   field[FLDSIZE_X][FLDSIZE_Y];
1.7       djm      1038:        size_t   i, tlen, hlen;
1.1       djm      1039:        u_int    b;
1.3       djm      1040:        int      x, y, r;
1.1       djm      1041:        size_t   len = strlen(augmentation_string) - 1;
                   1042:
                   1043:        if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
                   1044:                return NULL;
                   1045:
                   1046:        /* initialize field */
                   1047:        memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
                   1048:        x = FLDSIZE_X / 2;
                   1049:        y = FLDSIZE_Y / 2;
                   1050:
                   1051:        /* process raw key */
                   1052:        for (i = 0; i < dgst_raw_len; i++) {
                   1053:                int input;
                   1054:                /* each byte conveys four 2-bit move commands */
                   1055:                input = dgst_raw[i];
                   1056:                for (b = 0; b < 4; b++) {
                   1057:                        /* evaluate 2 bit, rest is shifted later */
                   1058:                        x += (input & 0x1) ? 1 : -1;
                   1059:                        y += (input & 0x2) ? 1 : -1;
                   1060:
                   1061:                        /* assure we are still in bounds */
                   1062:                        x = MAX(x, 0);
                   1063:                        y = MAX(y, 0);
                   1064:                        x = MIN(x, FLDSIZE_X - 1);
                   1065:                        y = MIN(y, FLDSIZE_Y - 1);
                   1066:
                   1067:                        /* augment the field */
                   1068:                        if (field[x][y] < len - 2)
                   1069:                                field[x][y]++;
                   1070:                        input = input >> 2;
                   1071:                }
                   1072:        }
                   1073:
                   1074:        /* mark starting point and end point*/
                   1075:        field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
                   1076:        field[x][y] = len;
                   1077:
1.3       djm      1078:        /* assemble title */
                   1079:        r = snprintf(title, sizeof(title), "[%s %u]",
                   1080:                sshkey_type(k), sshkey_size(k));
                   1081:        /* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
                   1082:        if (r < 0 || r > (int)sizeof(title))
1.7       djm      1083:                r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
                   1084:        tlen = (r <= 0) ? 0 : strlen(title);
                   1085:
                   1086:        /* assemble hash ID. */
                   1087:        r = snprintf(hash, sizeof(hash), "[%s]", alg);
                   1088:        hlen = (r <= 0) ? 0 : strlen(hash);
1.1       djm      1089:
                   1090:        /* output upper border */
1.3       djm      1091:        p = retval;
                   1092:        *p++ = '+';
                   1093:        for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
                   1094:                *p++ = '-';
                   1095:        memcpy(p, title, tlen);
                   1096:        p += tlen;
1.7       djm      1097:        for (i += tlen; i < FLDSIZE_X; i++)
1.1       djm      1098:                *p++ = '-';
                   1099:        *p++ = '+';
                   1100:        *p++ = '\n';
                   1101:
                   1102:        /* output content */
                   1103:        for (y = 0; y < FLDSIZE_Y; y++) {
                   1104:                *p++ = '|';
                   1105:                for (x = 0; x < FLDSIZE_X; x++)
                   1106:                        *p++ = augmentation_string[MIN(field[x][y], len)];
                   1107:                *p++ = '|';
                   1108:                *p++ = '\n';
                   1109:        }
                   1110:
                   1111:        /* output lower border */
                   1112:        *p++ = '+';
1.7       djm      1113:        for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
                   1114:                *p++ = '-';
                   1115:        memcpy(p, hash, hlen);
                   1116:        p += hlen;
                   1117:        for (i += hlen; i < FLDSIZE_X; i++)
1.1       djm      1118:                *p++ = '-';
                   1119:        *p++ = '+';
                   1120:
                   1121:        return retval;
                   1122: }
                   1123:
                   1124: char *
1.7       djm      1125: sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1.1       djm      1126:     enum sshkey_fp_rep dgst_rep)
                   1127: {
                   1128:        char *retval = NULL;
                   1129:        u_char *dgst_raw;
                   1130:        size_t dgst_raw_len;
                   1131:
1.7       djm      1132:        if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1.1       djm      1133:                return NULL;
                   1134:        switch (dgst_rep) {
1.7       djm      1135:        case SSH_FP_DEFAULT:
                   1136:                if (dgst_alg == SSH_DIGEST_MD5) {
                   1137:                        retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
                   1138:                            dgst_raw, dgst_raw_len);
                   1139:                } else {
                   1140:                        retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
                   1141:                            dgst_raw, dgst_raw_len);
                   1142:                }
                   1143:                break;
1.1       djm      1144:        case SSH_FP_HEX:
1.7       djm      1145:                retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
                   1146:                    dgst_raw, dgst_raw_len);
                   1147:                break;
                   1148:        case SSH_FP_BASE64:
                   1149:                retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
                   1150:                    dgst_raw, dgst_raw_len);
1.1       djm      1151:                break;
                   1152:        case SSH_FP_BUBBLEBABBLE:
                   1153:                retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
                   1154:                break;
                   1155:        case SSH_FP_RANDOMART:
1.7       djm      1156:                retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
                   1157:                    dgst_raw, dgst_raw_len, k);
1.1       djm      1158:                break;
                   1159:        default:
                   1160:                explicit_bzero(dgst_raw, dgst_raw_len);
                   1161:                free(dgst_raw);
                   1162:                return NULL;
                   1163:        }
                   1164:        explicit_bzero(dgst_raw, dgst_raw_len);
                   1165:        free(dgst_raw);
                   1166:        return retval;
                   1167: }
                   1168:
                   1169: #ifdef WITH_SSH1
                   1170: /*
                   1171:  * Reads a multiple-precision integer in decimal from the buffer, and advances
                   1172:  * the pointer.  The integer must already be initialized.  This function is
                   1173:  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
                   1174:  * last processed character.
                   1175:  */
                   1176: static int
                   1177: read_decimal_bignum(char **cpp, BIGNUM *v)
                   1178: {
                   1179:        char *cp;
                   1180:        size_t e;
                   1181:        int skip = 1;   /* skip white space */
                   1182:
                   1183:        cp = *cpp;
                   1184:        while (*cp == ' ' || *cp == '\t')
                   1185:                cp++;
                   1186:        e = strspn(cp, "0123456789");
                   1187:        if (e == 0)
                   1188:                return SSH_ERR_INVALID_FORMAT;
                   1189:        if (e > SSHBUF_MAX_BIGNUM * 3)
                   1190:                return SSH_ERR_BIGNUM_TOO_LARGE;
                   1191:        if (cp[e] == '\0')
                   1192:                skip = 0;
                   1193:        else if (index(" \t\r\n", cp[e]) == NULL)
                   1194:                return SSH_ERR_INVALID_FORMAT;
                   1195:        cp[e] = '\0';
                   1196:        if (BN_dec2bn(&v, cp) <= 0)
                   1197:                return SSH_ERR_INVALID_FORMAT;
                   1198:        *cpp = cp + e + skip;
                   1199:        return 0;
                   1200: }
                   1201: #endif /* WITH_SSH1 */
                   1202:
                   1203: /* returns 0 ok, and < 0 error */
                   1204: int
                   1205: sshkey_read(struct sshkey *ret, char **cpp)
                   1206: {
                   1207:        struct sshkey *k;
                   1208:        int retval = SSH_ERR_INVALID_FORMAT;
                   1209:        char *cp, *space;
                   1210:        int r, type, curve_nid = -1;
                   1211:        struct sshbuf *blob;
                   1212: #ifdef WITH_SSH1
                   1213:        char *ep;
                   1214:        u_long bits;
                   1215: #endif /* WITH_SSH1 */
                   1216:
                   1217:        cp = *cpp;
                   1218:
                   1219:        switch (ret->type) {
                   1220:        case KEY_RSA1:
                   1221: #ifdef WITH_SSH1
                   1222:                /* Get number of bits. */
                   1223:                bits = strtoul(cp, &ep, 10);
                   1224:                if (*cp == '\0' || index(" \t\r\n", *ep) == NULL ||
                   1225:                    bits == 0 || bits > SSHBUF_MAX_BIGNUM * 8)
                   1226:                        return SSH_ERR_INVALID_FORMAT;  /* Bad bit count... */
                   1227:                /* Get public exponent, public modulus. */
                   1228:                if ((r = read_decimal_bignum(&ep, ret->rsa->e)) < 0)
                   1229:                        return r;
                   1230:                if ((r = read_decimal_bignum(&ep, ret->rsa->n)) < 0)
                   1231:                        return r;
                   1232:                *cpp = ep;
                   1233:                /* validate the claimed number of bits */
                   1234:                if (BN_num_bits(ret->rsa->n) != (int)bits)
                   1235:                        return SSH_ERR_KEY_BITS_MISMATCH;
                   1236:                retval = 0;
                   1237: #endif /* WITH_SSH1 */
                   1238:                break;
                   1239:        case KEY_UNSPEC:
                   1240:        case KEY_RSA:
                   1241:        case KEY_DSA:
                   1242:        case KEY_ECDSA:
                   1243:        case KEY_ED25519:
                   1244:        case KEY_DSA_CERT:
                   1245:        case KEY_ECDSA_CERT:
                   1246:        case KEY_RSA_CERT:
                   1247:        case KEY_ED25519_CERT:
                   1248:                space = strchr(cp, ' ');
                   1249:                if (space == NULL)
                   1250:                        return SSH_ERR_INVALID_FORMAT;
                   1251:                *space = '\0';
                   1252:                type = sshkey_type_from_name(cp);
                   1253:                if (sshkey_type_plain(type) == KEY_ECDSA &&
                   1254:                    (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
                   1255:                        return SSH_ERR_EC_CURVE_INVALID;
                   1256:                *space = ' ';
                   1257:                if (type == KEY_UNSPEC)
                   1258:                        return SSH_ERR_INVALID_FORMAT;
                   1259:                cp = space+1;
                   1260:                if (*cp == '\0')
                   1261:                        return SSH_ERR_INVALID_FORMAT;
1.5       djm      1262:                if (ret->type != KEY_UNSPEC && ret->type != type)
1.1       djm      1263:                        return SSH_ERR_KEY_TYPE_MISMATCH;
                   1264:                if ((blob = sshbuf_new()) == NULL)
                   1265:                        return SSH_ERR_ALLOC_FAIL;
                   1266:                /* trim comment */
                   1267:                space = strchr(cp, ' ');
1.10      markus   1268:                if (space) {
                   1269:                        /* advance 'space': skip whitespace */
                   1270:                        *space++ = '\0';
                   1271:                        while (*space == ' ' || *space == '\t')
                   1272:                                space++;
                   1273:                        *cpp = space;
                   1274:                } else
                   1275:                        *cpp = cp + strlen(cp);
1.1       djm      1276:                if ((r = sshbuf_b64tod(blob, cp)) != 0) {
                   1277:                        sshbuf_free(blob);
                   1278:                        return r;
                   1279:                }
                   1280:                if ((r = sshkey_from_blob(sshbuf_ptr(blob),
                   1281:                    sshbuf_len(blob), &k)) != 0) {
                   1282:                        sshbuf_free(blob);
                   1283:                        return r;
                   1284:                }
                   1285:                sshbuf_free(blob);
                   1286:                if (k->type != type) {
                   1287:                        sshkey_free(k);
                   1288:                        return SSH_ERR_KEY_TYPE_MISMATCH;
                   1289:                }
                   1290:                if (sshkey_type_plain(type) == KEY_ECDSA &&
                   1291:                    curve_nid != k->ecdsa_nid) {
                   1292:                        sshkey_free(k);
                   1293:                        return SSH_ERR_EC_CURVE_MISMATCH;
                   1294:                }
1.5       djm      1295:                ret->type = type;
1.1       djm      1296:                if (sshkey_is_cert(ret)) {
                   1297:                        if (!sshkey_is_cert(k)) {
                   1298:                                sshkey_free(k);
                   1299:                                return SSH_ERR_EXPECTED_CERT;
                   1300:                        }
                   1301:                        if (ret->cert != NULL)
                   1302:                                cert_free(ret->cert);
                   1303:                        ret->cert = k->cert;
                   1304:                        k->cert = NULL;
                   1305:                }
                   1306: #ifdef WITH_OPENSSL
                   1307:                if (sshkey_type_plain(ret->type) == KEY_RSA) {
                   1308:                        if (ret->rsa != NULL)
                   1309:                                RSA_free(ret->rsa);
                   1310:                        ret->rsa = k->rsa;
                   1311:                        k->rsa = NULL;
                   1312: #ifdef DEBUG_PK
                   1313:                        RSA_print_fp(stderr, ret->rsa, 8);
                   1314: #endif
                   1315:                }
                   1316:                if (sshkey_type_plain(ret->type) == KEY_DSA) {
                   1317:                        if (ret->dsa != NULL)
                   1318:                                DSA_free(ret->dsa);
                   1319:                        ret->dsa = k->dsa;
                   1320:                        k->dsa = NULL;
                   1321: #ifdef DEBUG_PK
                   1322:                        DSA_print_fp(stderr, ret->dsa, 8);
                   1323: #endif
                   1324:                }
                   1325:                if (sshkey_type_plain(ret->type) == KEY_ECDSA) {
                   1326:                        if (ret->ecdsa != NULL)
                   1327:                                EC_KEY_free(ret->ecdsa);
                   1328:                        ret->ecdsa = k->ecdsa;
                   1329:                        ret->ecdsa_nid = k->ecdsa_nid;
                   1330:                        k->ecdsa = NULL;
                   1331:                        k->ecdsa_nid = -1;
                   1332: #ifdef DEBUG_PK
                   1333:                        sshkey_dump_ec_key(ret->ecdsa);
                   1334: #endif
                   1335:                }
                   1336: #endif /* WITH_OPENSSL */
                   1337:                if (sshkey_type_plain(ret->type) == KEY_ED25519) {
                   1338:                        free(ret->ed25519_pk);
                   1339:                        ret->ed25519_pk = k->ed25519_pk;
                   1340:                        k->ed25519_pk = NULL;
                   1341: #ifdef DEBUG_PK
                   1342:                        /* XXX */
                   1343: #endif
                   1344:                }
                   1345:                retval = 0;
                   1346: /*XXXX*/
                   1347:                sshkey_free(k);
                   1348:                if (retval != 0)
                   1349:                        break;
                   1350:                break;
                   1351:        default:
                   1352:                return SSH_ERR_INVALID_ARGUMENT;
                   1353:        }
                   1354:        return retval;
                   1355: }
                   1356:
                   1357: int
1.19      djm      1358: sshkey_to_base64(const struct sshkey *key, char **b64p)
1.1       djm      1359: {
1.19      djm      1360:        int r = SSH_ERR_INTERNAL_ERROR;
                   1361:        struct sshbuf *b = NULL;
1.1       djm      1362:        char *uu = NULL;
1.19      djm      1363:
                   1364:        if (b64p != NULL)
                   1365:                *b64p = NULL;
                   1366:        if ((b = sshbuf_new()) == NULL)
                   1367:                return SSH_ERR_ALLOC_FAIL;
                   1368:        if ((r = sshkey_putb(key, b)) != 0)
                   1369:                goto out;
                   1370:        if ((uu = sshbuf_dtob64(b)) == NULL) {
                   1371:                r = SSH_ERR_ALLOC_FAIL;
                   1372:                goto out;
                   1373:        }
                   1374:        /* Success */
                   1375:        if (b64p != NULL) {
                   1376:                *b64p = uu;
                   1377:                uu = NULL;
                   1378:        }
                   1379:        r = 0;
                   1380:  out:
                   1381:        sshbuf_free(b);
                   1382:        free(uu);
                   1383:        return r;
                   1384: }
                   1385:
                   1386: static int
                   1387: sshkey_format_rsa1(const struct sshkey *key, struct sshbuf *b)
                   1388: {
                   1389:        int r = SSH_ERR_INTERNAL_ERROR;
1.1       djm      1390: #ifdef WITH_SSH1
                   1391:        u_int bits = 0;
                   1392:        char *dec_e = NULL, *dec_n = NULL;
                   1393:
1.19      djm      1394:        if (key->rsa == NULL || key->rsa->e == NULL ||
                   1395:            key->rsa->n == NULL) {
                   1396:                r = SSH_ERR_INVALID_ARGUMENT;
                   1397:                goto out;
                   1398:        }
                   1399:        if ((dec_e = BN_bn2dec(key->rsa->e)) == NULL ||
                   1400:            (dec_n = BN_bn2dec(key->rsa->n)) == NULL) {
                   1401:                r = SSH_ERR_ALLOC_FAIL;
                   1402:                goto out;
                   1403:        }
                   1404:        /* size of modulus 'n' */
                   1405:        if ((bits = BN_num_bits(key->rsa->n)) <= 0) {
                   1406:                r = SSH_ERR_INVALID_ARGUMENT;
                   1407:                goto out;
1.1       djm      1408:        }
1.19      djm      1409:        if ((r = sshbuf_putf(b, "%u %s %s", bits, dec_e, dec_n)) != 0)
                   1410:                goto out;
                   1411:
                   1412:        /* Success */
                   1413:        r = 0;
                   1414:  out:
                   1415:        if (dec_e != NULL)
                   1416:                OPENSSL_free(dec_e);
                   1417:        if (dec_n != NULL)
                   1418:                OPENSSL_free(dec_n);
1.1       djm      1419: #endif /* WITH_SSH1 */
1.19      djm      1420:
                   1421:        return r;
                   1422: }
                   1423:
                   1424: static int
                   1425: sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
                   1426: {
                   1427:        int r = SSH_ERR_INTERNAL_ERROR;
                   1428:        char *uu = NULL;
                   1429:
                   1430:        if (key->type == KEY_RSA1) {
                   1431:                if ((r = sshkey_format_rsa1(key, b)) != 0)
1.1       djm      1432:                        goto out;
1.19      djm      1433:        } else {
                   1434:                /* Unsupported key types handled in sshkey_to_base64() */
                   1435:                if ((r = sshkey_to_base64(key, &uu)) != 0)
1.1       djm      1436:                        goto out;
1.19      djm      1437:                if ((r = sshbuf_putf(b, "%s %s",
                   1438:                    sshkey_ssh_name(key), uu)) != 0)
1.1       djm      1439:                        goto out;
1.19      djm      1440:        }
                   1441:        r = 0;
                   1442:  out:
                   1443:        free(uu);
                   1444:        return r;
                   1445: }
                   1446:
                   1447: int
                   1448: sshkey_write(const struct sshkey *key, FILE *f)
                   1449: {
                   1450:        struct sshbuf *b = NULL;
                   1451:        int r = SSH_ERR_INTERNAL_ERROR;
                   1452:
                   1453:        if ((b = sshbuf_new()) == NULL)
                   1454:                return SSH_ERR_ALLOC_FAIL;
                   1455:        if ((r = sshkey_format_text(key, b)) != 0)
1.1       djm      1456:                goto out;
                   1457:        if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
                   1458:                if (feof(f))
                   1459:                        errno = EPIPE;
1.19      djm      1460:                r = SSH_ERR_SYSTEM_ERROR;
1.1       djm      1461:                goto out;
                   1462:        }
1.19      djm      1463:        /* Success */
                   1464:        r = 0;
1.1       djm      1465:  out:
1.19      djm      1466:        sshbuf_free(b);
                   1467:        return r;
1.1       djm      1468: }
                   1469:
                   1470: const char *
                   1471: sshkey_cert_type(const struct sshkey *k)
                   1472: {
                   1473:        switch (k->cert->type) {
                   1474:        case SSH2_CERT_TYPE_USER:
                   1475:                return "user";
                   1476:        case SSH2_CERT_TYPE_HOST:
                   1477:                return "host";
                   1478:        default:
                   1479:                return "unknown";
                   1480:        }
                   1481: }
                   1482:
                   1483: #ifdef WITH_OPENSSL
                   1484: static int
                   1485: rsa_generate_private_key(u_int bits, RSA **rsap)
                   1486: {
                   1487:        RSA *private = NULL;
                   1488:        BIGNUM *f4 = NULL;
                   1489:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1490:
                   1491:        if (rsap == NULL ||
                   1492:            bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
                   1493:            bits > SSHBUF_MAX_BIGNUM * 8)
                   1494:                return SSH_ERR_INVALID_ARGUMENT;
                   1495:        *rsap = NULL;
                   1496:        if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
                   1497:                ret = SSH_ERR_ALLOC_FAIL;
                   1498:                goto out;
                   1499:        }
                   1500:        if (!BN_set_word(f4, RSA_F4) ||
                   1501:            !RSA_generate_key_ex(private, bits, f4, NULL)) {
                   1502:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   1503:                goto out;
                   1504:        }
                   1505:        *rsap = private;
                   1506:        private = NULL;
                   1507:        ret = 0;
                   1508:  out:
                   1509:        if (private != NULL)
                   1510:                RSA_free(private);
                   1511:        if (f4 != NULL)
                   1512:                BN_free(f4);
                   1513:        return ret;
                   1514: }
                   1515:
                   1516: static int
                   1517: dsa_generate_private_key(u_int bits, DSA **dsap)
                   1518: {
                   1519:        DSA *private;
                   1520:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1521:
                   1522:        if (dsap == NULL || bits != 1024)
                   1523:                return SSH_ERR_INVALID_ARGUMENT;
                   1524:        if ((private = DSA_new()) == NULL) {
                   1525:                ret = SSH_ERR_ALLOC_FAIL;
                   1526:                goto out;
                   1527:        }
                   1528:        *dsap = NULL;
                   1529:        if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
                   1530:            NULL, NULL) || !DSA_generate_key(private)) {
                   1531:                DSA_free(private);
                   1532:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   1533:                goto out;
                   1534:        }
                   1535:        *dsap = private;
                   1536:        private = NULL;
                   1537:        ret = 0;
                   1538:  out:
                   1539:        if (private != NULL)
                   1540:                DSA_free(private);
                   1541:        return ret;
                   1542: }
                   1543:
                   1544: int
                   1545: sshkey_ecdsa_key_to_nid(EC_KEY *k)
                   1546: {
                   1547:        EC_GROUP *eg;
                   1548:        int nids[] = {
                   1549:                NID_X9_62_prime256v1,
                   1550:                NID_secp384r1,
                   1551:                NID_secp521r1,
                   1552:                -1
                   1553:        };
                   1554:        int nid;
                   1555:        u_int i;
                   1556:        BN_CTX *bnctx;
                   1557:        const EC_GROUP *g = EC_KEY_get0_group(k);
                   1558:
                   1559:        /*
                   1560:         * The group may be stored in a ASN.1 encoded private key in one of two
                   1561:         * ways: as a "named group", which is reconstituted by ASN.1 object ID
                   1562:         * or explicit group parameters encoded into the key blob. Only the
                   1563:         * "named group" case sets the group NID for us, but we can figure
                   1564:         * it out for the other case by comparing against all the groups that
                   1565:         * are supported.
                   1566:         */
                   1567:        if ((nid = EC_GROUP_get_curve_name(g)) > 0)
                   1568:                return nid;
                   1569:        if ((bnctx = BN_CTX_new()) == NULL)
                   1570:                return -1;
                   1571:        for (i = 0; nids[i] != -1; i++) {
                   1572:                if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
                   1573:                        BN_CTX_free(bnctx);
                   1574:                        return -1;
                   1575:                }
                   1576:                if (EC_GROUP_cmp(g, eg, bnctx) == 0)
                   1577:                        break;
                   1578:                EC_GROUP_free(eg);
                   1579:        }
                   1580:        BN_CTX_free(bnctx);
                   1581:        if (nids[i] != -1) {
                   1582:                /* Use the group with the NID attached */
                   1583:                EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
                   1584:                if (EC_KEY_set_group(k, eg) != 1) {
                   1585:                        EC_GROUP_free(eg);
                   1586:                        return -1;
                   1587:                }
                   1588:        }
                   1589:        return nids[i];
                   1590: }
                   1591:
                   1592: static int
                   1593: ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
                   1594: {
                   1595:        EC_KEY *private;
                   1596:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1597:
                   1598:        if (nid == NULL || ecdsap == NULL ||
                   1599:            (*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
                   1600:                return SSH_ERR_INVALID_ARGUMENT;
                   1601:        *ecdsap = NULL;
                   1602:        if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
                   1603:                ret = SSH_ERR_ALLOC_FAIL;
                   1604:                goto out;
                   1605:        }
                   1606:        if (EC_KEY_generate_key(private) != 1) {
                   1607:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   1608:                goto out;
                   1609:        }
                   1610:        EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
                   1611:        *ecdsap = private;
                   1612:        private = NULL;
                   1613:        ret = 0;
                   1614:  out:
                   1615:        if (private != NULL)
                   1616:                EC_KEY_free(private);
                   1617:        return ret;
                   1618: }
                   1619: #endif /* WITH_OPENSSL */
                   1620:
                   1621: int
                   1622: sshkey_generate(int type, u_int bits, struct sshkey **keyp)
                   1623: {
                   1624:        struct sshkey *k;
                   1625:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1626:
                   1627:        if (keyp == NULL)
                   1628:                return SSH_ERR_INVALID_ARGUMENT;
                   1629:        *keyp = NULL;
                   1630:        if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
                   1631:                return SSH_ERR_ALLOC_FAIL;
                   1632:        switch (type) {
                   1633:        case KEY_ED25519:
                   1634:                if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
                   1635:                    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
                   1636:                        ret = SSH_ERR_ALLOC_FAIL;
                   1637:                        break;
                   1638:                }
                   1639:                crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
                   1640:                ret = 0;
                   1641:                break;
                   1642: #ifdef WITH_OPENSSL
                   1643:        case KEY_DSA:
                   1644:                ret = dsa_generate_private_key(bits, &k->dsa);
                   1645:                break;
                   1646:        case KEY_ECDSA:
                   1647:                ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
                   1648:                    &k->ecdsa);
                   1649:                break;
                   1650:        case KEY_RSA:
                   1651:        case KEY_RSA1:
                   1652:                ret = rsa_generate_private_key(bits, &k->rsa);
                   1653:                break;
                   1654: #endif /* WITH_OPENSSL */
                   1655:        default:
                   1656:                ret = SSH_ERR_INVALID_ARGUMENT;
                   1657:        }
                   1658:        if (ret == 0) {
                   1659:                k->type = type;
                   1660:                *keyp = k;
                   1661:        } else
                   1662:                sshkey_free(k);
                   1663:        return ret;
                   1664: }
                   1665:
                   1666: int
                   1667: sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
                   1668: {
                   1669:        u_int i;
                   1670:        const struct sshkey_cert *from;
                   1671:        struct sshkey_cert *to;
                   1672:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1673:
                   1674:        if (to_key->cert != NULL) {
                   1675:                cert_free(to_key->cert);
                   1676:                to_key->cert = NULL;
                   1677:        }
                   1678:
                   1679:        if ((from = from_key->cert) == NULL)
                   1680:                return SSH_ERR_INVALID_ARGUMENT;
                   1681:
                   1682:        if ((to = to_key->cert = cert_new()) == NULL)
                   1683:                return SSH_ERR_ALLOC_FAIL;
                   1684:
                   1685:        if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
                   1686:            (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
                   1687:            (ret = sshbuf_putb(to->extensions, from->extensions) != 0))
                   1688:                return ret;
                   1689:
                   1690:        to->serial = from->serial;
                   1691:        to->type = from->type;
                   1692:        if (from->key_id == NULL)
                   1693:                to->key_id = NULL;
                   1694:        else if ((to->key_id = strdup(from->key_id)) == NULL)
                   1695:                return SSH_ERR_ALLOC_FAIL;
                   1696:        to->valid_after = from->valid_after;
                   1697:        to->valid_before = from->valid_before;
                   1698:        if (from->signature_key == NULL)
                   1699:                to->signature_key = NULL;
                   1700:        else if ((ret = sshkey_from_private(from->signature_key,
                   1701:            &to->signature_key)) != 0)
                   1702:                return ret;
                   1703:
                   1704:        if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
                   1705:                return SSH_ERR_INVALID_ARGUMENT;
                   1706:        if (from->nprincipals > 0) {
                   1707:                if ((to->principals = calloc(from->nprincipals,
                   1708:                    sizeof(*to->principals))) == NULL)
                   1709:                        return SSH_ERR_ALLOC_FAIL;
                   1710:                for (i = 0; i < from->nprincipals; i++) {
                   1711:                        to->principals[i] = strdup(from->principals[i]);
                   1712:                        if (to->principals[i] == NULL) {
                   1713:                                to->nprincipals = i;
                   1714:                                return SSH_ERR_ALLOC_FAIL;
                   1715:                        }
                   1716:                }
                   1717:        }
                   1718:        to->nprincipals = from->nprincipals;
                   1719:        return 0;
                   1720: }
                   1721:
                   1722: int
                   1723: sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
                   1724: {
                   1725:        struct sshkey *n = NULL;
                   1726:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1727:
                   1728:        if (pkp != NULL)
                   1729:                *pkp = NULL;
                   1730:
                   1731:        switch (k->type) {
                   1732: #ifdef WITH_OPENSSL
                   1733:        case KEY_DSA:
                   1734:        case KEY_DSA_CERT:
                   1735:                if ((n = sshkey_new(k->type)) == NULL)
                   1736:                        return SSH_ERR_ALLOC_FAIL;
                   1737:                if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
                   1738:                    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
                   1739:                    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
                   1740:                    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
                   1741:                        sshkey_free(n);
                   1742:                        return SSH_ERR_ALLOC_FAIL;
                   1743:                }
                   1744:                break;
                   1745:        case KEY_ECDSA:
                   1746:        case KEY_ECDSA_CERT:
                   1747:                if ((n = sshkey_new(k->type)) == NULL)
                   1748:                        return SSH_ERR_ALLOC_FAIL;
                   1749:                n->ecdsa_nid = k->ecdsa_nid;
                   1750:                n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
                   1751:                if (n->ecdsa == NULL) {
                   1752:                        sshkey_free(n);
                   1753:                        return SSH_ERR_ALLOC_FAIL;
                   1754:                }
                   1755:                if (EC_KEY_set_public_key(n->ecdsa,
                   1756:                    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
                   1757:                        sshkey_free(n);
                   1758:                        return SSH_ERR_LIBCRYPTO_ERROR;
                   1759:                }
                   1760:                break;
                   1761:        case KEY_RSA:
                   1762:        case KEY_RSA1:
                   1763:        case KEY_RSA_CERT:
                   1764:                if ((n = sshkey_new(k->type)) == NULL)
                   1765:                        return SSH_ERR_ALLOC_FAIL;
                   1766:                if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
                   1767:                    (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
                   1768:                        sshkey_free(n);
                   1769:                        return SSH_ERR_ALLOC_FAIL;
                   1770:                }
                   1771:                break;
                   1772: #endif /* WITH_OPENSSL */
                   1773:        case KEY_ED25519:
                   1774:        case KEY_ED25519_CERT:
                   1775:                if ((n = sshkey_new(k->type)) == NULL)
                   1776:                        return SSH_ERR_ALLOC_FAIL;
                   1777:                if (k->ed25519_pk != NULL) {
                   1778:                        if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
                   1779:                                sshkey_free(n);
                   1780:                                return SSH_ERR_ALLOC_FAIL;
                   1781:                        }
                   1782:                        memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
                   1783:                }
                   1784:                break;
                   1785:        default:
                   1786:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   1787:        }
                   1788:        if (sshkey_is_cert(k)) {
                   1789:                if ((ret = sshkey_cert_copy(k, n)) != 0) {
                   1790:                        sshkey_free(n);
                   1791:                        return ret;
                   1792:                }
                   1793:        }
                   1794:        *pkp = n;
                   1795:        return 0;
                   1796: }
                   1797:
                   1798: static int
1.14      djm      1799: cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1.1       djm      1800: {
1.14      djm      1801:        struct sshbuf *principals = NULL, *crit = NULL;
                   1802:        struct sshbuf *exts = NULL, *ca = NULL;
                   1803:        u_char *sig = NULL;
                   1804:        size_t signed_len = 0, slen = 0, kidlen = 0;
1.1       djm      1805:        int ret = SSH_ERR_INTERNAL_ERROR;
                   1806:
                   1807:        /* Copy the entire key blob for verification and later serialisation */
1.14      djm      1808:        if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1.1       djm      1809:                return ret;
                   1810:
1.20    ! djm      1811:        /* Parse body of certificate up to signature */
        !          1812:        if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1.1       djm      1813:            (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
                   1814:            (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1.4       djm      1815:            (ret = sshbuf_froms(b, &principals)) != 0 ||
1.1       djm      1816:            (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
                   1817:            (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1.4       djm      1818:            (ret = sshbuf_froms(b, &crit)) != 0 ||
1.20    ! djm      1819:            (ret = sshbuf_froms(b, &exts)) != 0 ||
1.1       djm      1820:            (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1.14      djm      1821:            (ret = sshbuf_froms(b, &ca)) != 0) {
1.1       djm      1822:                /* XXX debug print error for ret */
                   1823:                ret = SSH_ERR_INVALID_FORMAT;
                   1824:                goto out;
                   1825:        }
                   1826:
                   1827:        /* Signature is left in the buffer so we can calculate this length */
                   1828:        signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
                   1829:
                   1830:        if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
                   1831:                ret = SSH_ERR_INVALID_FORMAT;
                   1832:                goto out;
                   1833:        }
                   1834:
                   1835:        if (key->cert->type != SSH2_CERT_TYPE_USER &&
                   1836:            key->cert->type != SSH2_CERT_TYPE_HOST) {
                   1837:                ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
                   1838:                goto out;
                   1839:        }
                   1840:
1.4       djm      1841:        /* Parse principals section */
                   1842:        while (sshbuf_len(principals) > 0) {
                   1843:                char *principal = NULL;
                   1844:                char **oprincipals = NULL;
                   1845:
1.1       djm      1846:                if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
                   1847:                        ret = SSH_ERR_INVALID_FORMAT;
                   1848:                        goto out;
                   1849:                }
1.4       djm      1850:                if ((ret = sshbuf_get_cstring(principals, &principal,
                   1851:                    NULL)) != 0) {
1.1       djm      1852:                        ret = SSH_ERR_INVALID_FORMAT;
                   1853:                        goto out;
                   1854:                }
                   1855:                oprincipals = key->cert->principals;
1.20    ! djm      1856:                key->cert->principals = reallocarray(key->cert->principals,
        !          1857:                    key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1.1       djm      1858:                if (key->cert->principals == NULL) {
                   1859:                        free(principal);
                   1860:                        key->cert->principals = oprincipals;
                   1861:                        ret = SSH_ERR_ALLOC_FAIL;
                   1862:                        goto out;
                   1863:                }
                   1864:                key->cert->principals[key->cert->nprincipals++] = principal;
                   1865:        }
                   1866:
1.4       djm      1867:        /*
                   1868:         * Stash a copies of the critical options and extensions sections
                   1869:         * for later use.
                   1870:         */
                   1871:        if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
                   1872:            (exts != NULL &&
                   1873:            (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1.1       djm      1874:                goto out;
                   1875:
1.4       djm      1876:        /*
                   1877:         * Validate critical options and extensions sections format.
                   1878:         */
                   1879:        while (sshbuf_len(crit) != 0) {
                   1880:                if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
                   1881:                    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
                   1882:                        sshbuf_reset(key->cert->critical);
1.1       djm      1883:                        ret = SSH_ERR_INVALID_FORMAT;
                   1884:                        goto out;
                   1885:                }
                   1886:        }
1.4       djm      1887:        while (exts != NULL && sshbuf_len(exts) != 0) {
                   1888:                if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
                   1889:                    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
                   1890:                        sshbuf_reset(key->cert->extensions);
1.1       djm      1891:                        ret = SSH_ERR_INVALID_FORMAT;
                   1892:                        goto out;
                   1893:                }
                   1894:        }
                   1895:
1.4       djm      1896:        /* Parse CA key and check signature */
1.14      djm      1897:        if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1.1       djm      1898:                ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
                   1899:                goto out;
                   1900:        }
                   1901:        if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
                   1902:                ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
                   1903:                goto out;
                   1904:        }
                   1905:        if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
                   1906:            sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
                   1907:                goto out;
1.4       djm      1908:
                   1909:        /* Success */
1.1       djm      1910:        ret = 0;
                   1911:  out:
1.14      djm      1912:        sshbuf_free(ca);
1.4       djm      1913:        sshbuf_free(crit);
                   1914:        sshbuf_free(exts);
                   1915:        sshbuf_free(principals);
1.1       djm      1916:        free(sig);
                   1917:        return ret;
                   1918: }
                   1919:
                   1920: static int
1.14      djm      1921: sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
                   1922:     int allow_cert)
1.1       djm      1923: {
1.12      djm      1924:        int type, ret = SSH_ERR_INTERNAL_ERROR;
1.1       djm      1925:        char *ktype = NULL, *curve = NULL;
                   1926:        struct sshkey *key = NULL;
                   1927:        size_t len;
                   1928:        u_char *pk = NULL;
1.14      djm      1929:        struct sshbuf *copy;
1.1       djm      1930: #ifdef WITH_OPENSSL
                   1931:        EC_POINT *q = NULL;
                   1932: #endif /* WITH_OPENSSL */
                   1933:
                   1934: #ifdef DEBUG_PK /* XXX */
1.14      djm      1935:        sshbuf_dump(b, stderr);
1.1       djm      1936: #endif
                   1937:        *keyp = NULL;
1.14      djm      1938:        if ((copy = sshbuf_fromb(b)) == NULL) {
                   1939:                ret = SSH_ERR_ALLOC_FAIL;
                   1940:                goto out;
                   1941:        }
1.1       djm      1942:        if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
                   1943:                ret = SSH_ERR_INVALID_FORMAT;
                   1944:                goto out;
                   1945:        }
                   1946:
                   1947:        type = sshkey_type_from_name(ktype);
                   1948:        if (!allow_cert && sshkey_type_is_cert(type)) {
                   1949:                ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
                   1950:                goto out;
                   1951:        }
                   1952:        switch (type) {
                   1953: #ifdef WITH_OPENSSL
                   1954:        case KEY_RSA_CERT:
1.14      djm      1955:                /* Skip nonce */
1.1       djm      1956:                if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
                   1957:                        ret = SSH_ERR_INVALID_FORMAT;
                   1958:                        goto out;
                   1959:                }
                   1960:                /* FALLTHROUGH */
                   1961:        case KEY_RSA:
                   1962:                if ((key = sshkey_new(type)) == NULL) {
                   1963:                        ret = SSH_ERR_ALLOC_FAIL;
                   1964:                        goto out;
                   1965:                }
1.16      djm      1966:                if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
                   1967:                    sshbuf_get_bignum2(b, key->rsa->n) != 0) {
1.1       djm      1968:                        ret = SSH_ERR_INVALID_FORMAT;
                   1969:                        goto out;
                   1970:                }
                   1971: #ifdef DEBUG_PK
                   1972:                RSA_print_fp(stderr, key->rsa, 8);
                   1973: #endif
                   1974:                break;
                   1975:        case KEY_DSA_CERT:
1.14      djm      1976:                /* Skip nonce */
1.1       djm      1977:                if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
                   1978:                        ret = SSH_ERR_INVALID_FORMAT;
                   1979:                        goto out;
                   1980:                }
                   1981:                /* FALLTHROUGH */
                   1982:        case KEY_DSA:
                   1983:                if ((key = sshkey_new(type)) == NULL) {
                   1984:                        ret = SSH_ERR_ALLOC_FAIL;
                   1985:                        goto out;
                   1986:                }
1.16      djm      1987:                if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
                   1988:                    sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
                   1989:                    sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
                   1990:                    sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
1.1       djm      1991:                        ret = SSH_ERR_INVALID_FORMAT;
                   1992:                        goto out;
                   1993:                }
                   1994: #ifdef DEBUG_PK
                   1995:                DSA_print_fp(stderr, key->dsa, 8);
                   1996: #endif
                   1997:                break;
                   1998:        case KEY_ECDSA_CERT:
1.14      djm      1999:                /* Skip nonce */
1.1       djm      2000:                if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
                   2001:                        ret = SSH_ERR_INVALID_FORMAT;
                   2002:                        goto out;
                   2003:                }
                   2004:                /* FALLTHROUGH */
                   2005:        case KEY_ECDSA:
                   2006:                if ((key = sshkey_new(type)) == NULL) {
                   2007:                        ret = SSH_ERR_ALLOC_FAIL;
                   2008:                        goto out;
                   2009:                }
1.12      djm      2010:                key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
1.1       djm      2011:                if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
                   2012:                        ret = SSH_ERR_INVALID_FORMAT;
                   2013:                        goto out;
                   2014:                }
                   2015:                if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
                   2016:                        ret = SSH_ERR_EC_CURVE_MISMATCH;
                   2017:                        goto out;
                   2018:                }
                   2019:                if (key->ecdsa != NULL)
                   2020:                        EC_KEY_free(key->ecdsa);
                   2021:                if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
                   2022:                    == NULL) {
                   2023:                        ret = SSH_ERR_EC_CURVE_INVALID;
                   2024:                        goto out;
                   2025:                }
                   2026:                if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
                   2027:                        ret = SSH_ERR_ALLOC_FAIL;
                   2028:                        goto out;
                   2029:                }
                   2030:                if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
                   2031:                        ret = SSH_ERR_INVALID_FORMAT;
                   2032:                        goto out;
                   2033:                }
                   2034:                if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
                   2035:                    q) != 0) {
                   2036:                        ret = SSH_ERR_KEY_INVALID_EC_VALUE;
                   2037:                        goto out;
                   2038:                }
                   2039:                if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
                   2040:                        /* XXX assume it is a allocation error */
                   2041:                        ret = SSH_ERR_ALLOC_FAIL;
                   2042:                        goto out;
                   2043:                }
                   2044: #ifdef DEBUG_PK
                   2045:                sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
                   2046: #endif
                   2047:                break;
                   2048: #endif /* WITH_OPENSSL */
                   2049:        case KEY_ED25519_CERT:
1.14      djm      2050:                /* Skip nonce */
1.1       djm      2051:                if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
                   2052:                        ret = SSH_ERR_INVALID_FORMAT;
                   2053:                        goto out;
                   2054:                }
                   2055:                /* FALLTHROUGH */
                   2056:        case KEY_ED25519:
                   2057:                if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
                   2058:                        goto out;
                   2059:                if (len != ED25519_PK_SZ) {
                   2060:                        ret = SSH_ERR_INVALID_FORMAT;
                   2061:                        goto out;
                   2062:                }
                   2063:                if ((key = sshkey_new(type)) == NULL) {
                   2064:                        ret = SSH_ERR_ALLOC_FAIL;
                   2065:                        goto out;
                   2066:                }
                   2067:                key->ed25519_pk = pk;
                   2068:                pk = NULL;
                   2069:                break;
                   2070:        case KEY_UNSPEC:
                   2071:                if ((key = sshkey_new(type)) == NULL) {
                   2072:                        ret = SSH_ERR_ALLOC_FAIL;
                   2073:                        goto out;
                   2074:                }
                   2075:                break;
                   2076:        default:
                   2077:                ret = SSH_ERR_KEY_TYPE_UNKNOWN;
                   2078:                goto out;
                   2079:        }
                   2080:
                   2081:        /* Parse certificate potion */
1.14      djm      2082:        if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
1.1       djm      2083:                goto out;
                   2084:
                   2085:        if (key != NULL && sshbuf_len(b) != 0) {
                   2086:                ret = SSH_ERR_INVALID_FORMAT;
                   2087:                goto out;
                   2088:        }
                   2089:        ret = 0;
                   2090:        *keyp = key;
                   2091:        key = NULL;
                   2092:  out:
1.14      djm      2093:        sshbuf_free(copy);
1.1       djm      2094:        sshkey_free(key);
                   2095:        free(ktype);
                   2096:        free(curve);
                   2097:        free(pk);
                   2098: #ifdef WITH_OPENSSL
                   2099:        if (q != NULL)
                   2100:                EC_POINT_free(q);
                   2101: #endif /* WITH_OPENSSL */
                   2102:        return ret;
                   2103: }
                   2104:
                   2105: int
                   2106: sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
                   2107: {
1.14      djm      2108:        struct sshbuf *b;
                   2109:        int r;
                   2110:
                   2111:        if ((b = sshbuf_from(blob, blen)) == NULL)
                   2112:                return SSH_ERR_ALLOC_FAIL;
                   2113:        r = sshkey_from_blob_internal(b, keyp, 1);
                   2114:        sshbuf_free(b);
                   2115:        return r;
                   2116: }
                   2117:
                   2118: int
                   2119: sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
                   2120: {
                   2121:        return sshkey_from_blob_internal(b, keyp, 1);
                   2122: }
                   2123:
                   2124: int
                   2125: sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
                   2126: {
                   2127:        struct sshbuf *b;
                   2128:        int r;
                   2129:
                   2130:        if ((r = sshbuf_froms(buf, &b)) != 0)
                   2131:                return r;
                   2132:        r = sshkey_from_blob_internal(b, keyp, 1);
                   2133:        sshbuf_free(b);
                   2134:        return r;
1.1       djm      2135: }
                   2136:
                   2137: int
                   2138: sshkey_sign(const struct sshkey *key,
                   2139:     u_char **sigp, size_t *lenp,
                   2140:     const u_char *data, size_t datalen, u_int compat)
                   2141: {
                   2142:        if (sigp != NULL)
                   2143:                *sigp = NULL;
                   2144:        if (lenp != NULL)
                   2145:                *lenp = 0;
                   2146:        if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
                   2147:                return SSH_ERR_INVALID_ARGUMENT;
                   2148:        switch (key->type) {
                   2149: #ifdef WITH_OPENSSL
                   2150:        case KEY_DSA_CERT:
                   2151:        case KEY_DSA:
                   2152:                return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
                   2153:        case KEY_ECDSA_CERT:
                   2154:        case KEY_ECDSA:
                   2155:                return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
                   2156:        case KEY_RSA_CERT:
                   2157:        case KEY_RSA:
                   2158:                return ssh_rsa_sign(key, sigp, lenp, data, datalen, compat);
                   2159: #endif /* WITH_OPENSSL */
                   2160:        case KEY_ED25519:
                   2161:        case KEY_ED25519_CERT:
                   2162:                return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
                   2163:        default:
                   2164:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   2165:        }
                   2166: }
                   2167:
                   2168: /*
                   2169:  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
                   2170:  */
                   2171: int
                   2172: sshkey_verify(const struct sshkey *key,
                   2173:     const u_char *sig, size_t siglen,
                   2174:     const u_char *data, size_t dlen, u_int compat)
                   2175: {
1.6       djm      2176:        if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
1.1       djm      2177:                return SSH_ERR_INVALID_ARGUMENT;
                   2178:        switch (key->type) {
                   2179: #ifdef WITH_OPENSSL
                   2180:        case KEY_DSA_CERT:
                   2181:        case KEY_DSA:
                   2182:                return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
                   2183:        case KEY_ECDSA_CERT:
                   2184:        case KEY_ECDSA:
                   2185:                return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
                   2186:        case KEY_RSA_CERT:
                   2187:        case KEY_RSA:
                   2188:                return ssh_rsa_verify(key, sig, siglen, data, dlen, compat);
                   2189: #endif /* WITH_OPENSSL */
                   2190:        case KEY_ED25519:
                   2191:        case KEY_ED25519_CERT:
                   2192:                return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
                   2193:        default:
                   2194:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   2195:        }
                   2196: }
                   2197:
                   2198: /* Converts a private to a public key */
                   2199: int
                   2200: sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
                   2201: {
                   2202:        struct sshkey *pk;
                   2203:        int ret = SSH_ERR_INTERNAL_ERROR;
                   2204:
                   2205:        if (dkp != NULL)
                   2206:                *dkp = NULL;
                   2207:
                   2208:        if ((pk = calloc(1, sizeof(*pk))) == NULL)
                   2209:                return SSH_ERR_ALLOC_FAIL;
                   2210:        pk->type = k->type;
                   2211:        pk->flags = k->flags;
                   2212:        pk->ecdsa_nid = k->ecdsa_nid;
                   2213:        pk->dsa = NULL;
                   2214:        pk->ecdsa = NULL;
                   2215:        pk->rsa = NULL;
                   2216:        pk->ed25519_pk = NULL;
                   2217:        pk->ed25519_sk = NULL;
                   2218:
                   2219:        switch (k->type) {
                   2220: #ifdef WITH_OPENSSL
                   2221:        case KEY_RSA_CERT:
                   2222:                if ((ret = sshkey_cert_copy(k, pk)) != 0)
                   2223:                        goto fail;
                   2224:                /* FALLTHROUGH */
                   2225:        case KEY_RSA1:
                   2226:        case KEY_RSA:
                   2227:                if ((pk->rsa = RSA_new()) == NULL ||
                   2228:                    (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
                   2229:                    (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
                   2230:                        ret = SSH_ERR_ALLOC_FAIL;
                   2231:                        goto fail;
                   2232:                        }
                   2233:                break;
                   2234:        case KEY_DSA_CERT:
                   2235:                if ((ret = sshkey_cert_copy(k, pk)) != 0)
                   2236:                        goto fail;
                   2237:                /* FALLTHROUGH */
                   2238:        case KEY_DSA:
                   2239:                if ((pk->dsa = DSA_new()) == NULL ||
                   2240:                    (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
                   2241:                    (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
                   2242:                    (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
                   2243:                    (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
                   2244:                        ret = SSH_ERR_ALLOC_FAIL;
                   2245:                        goto fail;
                   2246:                }
                   2247:                break;
                   2248:        case KEY_ECDSA_CERT:
                   2249:                if ((ret = sshkey_cert_copy(k, pk)) != 0)
                   2250:                        goto fail;
                   2251:                /* FALLTHROUGH */
                   2252:        case KEY_ECDSA:
                   2253:                pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
                   2254:                if (pk->ecdsa == NULL) {
                   2255:                        ret = SSH_ERR_ALLOC_FAIL;
                   2256:                        goto fail;
                   2257:                }
                   2258:                if (EC_KEY_set_public_key(pk->ecdsa,
                   2259:                    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
                   2260:                        ret = SSH_ERR_LIBCRYPTO_ERROR;
                   2261:                        goto fail;
                   2262:                }
                   2263:                break;
                   2264: #endif /* WITH_OPENSSL */
                   2265:        case KEY_ED25519_CERT:
                   2266:                if ((ret = sshkey_cert_copy(k, pk)) != 0)
                   2267:                        goto fail;
                   2268:                /* FALLTHROUGH */
                   2269:        case KEY_ED25519:
                   2270:                if (k->ed25519_pk != NULL) {
                   2271:                        if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
                   2272:                                ret = SSH_ERR_ALLOC_FAIL;
                   2273:                                goto fail;
                   2274:                        }
                   2275:                        memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
                   2276:                }
                   2277:                break;
                   2278:        default:
                   2279:                ret = SSH_ERR_KEY_TYPE_UNKNOWN;
                   2280:  fail:
                   2281:                sshkey_free(pk);
                   2282:                return ret;
                   2283:        }
                   2284:        *dkp = pk;
                   2285:        return 0;
                   2286: }
                   2287:
                   2288: /* Convert a plain key to their _CERT equivalent */
                   2289: int
1.20    ! djm      2290: sshkey_to_certified(struct sshkey *k)
1.1       djm      2291: {
                   2292:        int newtype;
                   2293:
                   2294:        switch (k->type) {
                   2295: #ifdef WITH_OPENSSL
                   2296:        case KEY_RSA:
1.20    ! djm      2297:                newtype = KEY_RSA_CERT;
1.1       djm      2298:                break;
                   2299:        case KEY_DSA:
1.20    ! djm      2300:                newtype = KEY_DSA_CERT;
1.1       djm      2301:                break;
                   2302:        case KEY_ECDSA:
                   2303:                newtype = KEY_ECDSA_CERT;
                   2304:                break;
                   2305: #endif /* WITH_OPENSSL */
                   2306:        case KEY_ED25519:
                   2307:                newtype = KEY_ED25519_CERT;
                   2308:                break;
                   2309:        default:
                   2310:                return SSH_ERR_INVALID_ARGUMENT;
                   2311:        }
                   2312:        if ((k->cert = cert_new()) == NULL)
                   2313:                return SSH_ERR_ALLOC_FAIL;
                   2314:        k->type = newtype;
                   2315:        return 0;
                   2316: }
                   2317:
                   2318: /* Convert a certificate to its raw key equivalent */
                   2319: int
                   2320: sshkey_drop_cert(struct sshkey *k)
                   2321: {
                   2322:        if (!sshkey_type_is_cert(k->type))
                   2323:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   2324:        cert_free(k->cert);
                   2325:        k->cert = NULL;
                   2326:        k->type = sshkey_type_plain(k->type);
                   2327:        return 0;
                   2328: }
                   2329:
                   2330: /* Sign a certified key, (re-)generating the signed certblob. */
                   2331: int
                   2332: sshkey_certify(struct sshkey *k, struct sshkey *ca)
                   2333: {
                   2334:        struct sshbuf *principals = NULL;
                   2335:        u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
                   2336:        size_t i, ca_len, sig_len;
                   2337:        int ret = SSH_ERR_INTERNAL_ERROR;
                   2338:        struct sshbuf *cert;
                   2339:
                   2340:        if (k == NULL || k->cert == NULL ||
                   2341:            k->cert->certblob == NULL || ca == NULL)
                   2342:                return SSH_ERR_INVALID_ARGUMENT;
                   2343:        if (!sshkey_is_cert(k))
                   2344:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   2345:        if (!sshkey_type_is_valid_ca(ca->type))
                   2346:                return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
                   2347:
                   2348:        if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
                   2349:                return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
                   2350:
                   2351:        cert = k->cert->certblob; /* for readability */
                   2352:        sshbuf_reset(cert);
                   2353:        if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
                   2354:                goto out;
                   2355:
                   2356:        /* -v01 certs put nonce first */
                   2357:        arc4random_buf(&nonce, sizeof(nonce));
1.20    ! djm      2358:        if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
        !          2359:                goto out;
1.1       djm      2360:
                   2361:        /* XXX this substantially duplicates to_blob(); refactor */
                   2362:        switch (k->type) {
                   2363: #ifdef WITH_OPENSSL
                   2364:        case KEY_DSA_CERT:
                   2365:                if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
                   2366:                    (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
                   2367:                    (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
                   2368:                    (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
                   2369:                        goto out;
                   2370:                break;
                   2371:        case KEY_ECDSA_CERT:
                   2372:                if ((ret = sshbuf_put_cstring(cert,
                   2373:                    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
                   2374:                    (ret = sshbuf_put_ec(cert,
                   2375:                    EC_KEY_get0_public_key(k->ecdsa),
                   2376:                    EC_KEY_get0_group(k->ecdsa))) != 0)
                   2377:                        goto out;
                   2378:                break;
                   2379:        case KEY_RSA_CERT:
                   2380:                if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
                   2381:                    (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
                   2382:                        goto out;
                   2383:                break;
                   2384: #endif /* WITH_OPENSSL */
                   2385:        case KEY_ED25519_CERT:
                   2386:                if ((ret = sshbuf_put_string(cert,
                   2387:                    k->ed25519_pk, ED25519_PK_SZ)) != 0)
                   2388:                        goto out;
                   2389:                break;
                   2390:        default:
                   2391:                ret = SSH_ERR_INVALID_ARGUMENT;
1.15      djm      2392:                goto out;
1.1       djm      2393:        }
                   2394:
1.20    ! djm      2395:        if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
        !          2396:            (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
1.1       djm      2397:            (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
                   2398:                goto out;
                   2399:
                   2400:        if ((principals = sshbuf_new()) == NULL) {
                   2401:                ret = SSH_ERR_ALLOC_FAIL;
                   2402:                goto out;
                   2403:        }
                   2404:        for (i = 0; i < k->cert->nprincipals; i++) {
                   2405:                if ((ret = sshbuf_put_cstring(principals,
                   2406:                    k->cert->principals[i])) != 0)
                   2407:                        goto out;
                   2408:        }
                   2409:        if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
                   2410:            (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
                   2411:            (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
1.20    ! djm      2412:            (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
        !          2413:            (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
        !          2414:            (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
1.1       djm      2415:            (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
                   2416:                goto out;
                   2417:
                   2418:        /* Sign the whole mess */
                   2419:        if ((ret = sshkey_sign(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
                   2420:            sshbuf_len(cert), 0)) != 0)
                   2421:                goto out;
                   2422:
                   2423:        /* Append signature and we are done */
                   2424:        if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
                   2425:                goto out;
                   2426:        ret = 0;
                   2427:  out:
                   2428:        if (ret != 0)
                   2429:                sshbuf_reset(cert);
                   2430:        if (sig_blob != NULL)
                   2431:                free(sig_blob);
                   2432:        if (ca_blob != NULL)
                   2433:                free(ca_blob);
                   2434:        if (principals != NULL)
                   2435:                sshbuf_free(principals);
                   2436:        return ret;
                   2437: }
                   2438:
                   2439: int
                   2440: sshkey_cert_check_authority(const struct sshkey *k,
                   2441:     int want_host, int require_principal,
                   2442:     const char *name, const char **reason)
                   2443: {
                   2444:        u_int i, principal_matches;
                   2445:        time_t now = time(NULL);
                   2446:
                   2447:        if (reason != NULL)
                   2448:                *reason = NULL;
                   2449:
                   2450:        if (want_host) {
                   2451:                if (k->cert->type != SSH2_CERT_TYPE_HOST) {
                   2452:                        *reason = "Certificate invalid: not a host certificate";
                   2453:                        return SSH_ERR_KEY_CERT_INVALID;
                   2454:                }
                   2455:        } else {
                   2456:                if (k->cert->type != SSH2_CERT_TYPE_USER) {
                   2457:                        *reason = "Certificate invalid: not a user certificate";
                   2458:                        return SSH_ERR_KEY_CERT_INVALID;
                   2459:                }
                   2460:        }
                   2461:        if (now < 0) {
                   2462:                /* yikes - system clock before epoch! */
                   2463:                *reason = "Certificate invalid: not yet valid";
                   2464:                return SSH_ERR_KEY_CERT_INVALID;
                   2465:        }
                   2466:        if ((u_int64_t)now < k->cert->valid_after) {
                   2467:                *reason = "Certificate invalid: not yet valid";
                   2468:                return SSH_ERR_KEY_CERT_INVALID;
                   2469:        }
                   2470:        if ((u_int64_t)now >= k->cert->valid_before) {
                   2471:                *reason = "Certificate invalid: expired";
                   2472:                return SSH_ERR_KEY_CERT_INVALID;
                   2473:        }
                   2474:        if (k->cert->nprincipals == 0) {
                   2475:                if (require_principal) {
                   2476:                        *reason = "Certificate lacks principal list";
                   2477:                        return SSH_ERR_KEY_CERT_INVALID;
                   2478:                }
                   2479:        } else if (name != NULL) {
                   2480:                principal_matches = 0;
                   2481:                for (i = 0; i < k->cert->nprincipals; i++) {
                   2482:                        if (strcmp(name, k->cert->principals[i]) == 0) {
                   2483:                                principal_matches = 1;
                   2484:                                break;
                   2485:                        }
                   2486:                }
                   2487:                if (!principal_matches) {
                   2488:                        *reason = "Certificate invalid: name is not a listed "
                   2489:                            "principal";
                   2490:                        return SSH_ERR_KEY_CERT_INVALID;
                   2491:                }
                   2492:        }
                   2493:        return 0;
                   2494: }
                   2495:
                   2496: int
                   2497: sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
                   2498: {
                   2499:        int r = SSH_ERR_INTERNAL_ERROR;
                   2500:
                   2501:        if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
                   2502:                goto out;
                   2503:        switch (key->type) {
                   2504: #ifdef WITH_OPENSSL
                   2505:        case KEY_RSA:
                   2506:                if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
                   2507:                    (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
                   2508:                    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
                   2509:                    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
                   2510:                    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
                   2511:                    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
                   2512:                        goto out;
                   2513:                break;
                   2514:        case KEY_RSA_CERT:
                   2515:                if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
                   2516:                        r = SSH_ERR_INVALID_ARGUMENT;
                   2517:                        goto out;
                   2518:                }
                   2519:                if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
                   2520:                    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
                   2521:                    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
                   2522:                    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
                   2523:                    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
                   2524:                        goto out;
                   2525:                break;
                   2526:        case KEY_DSA:
                   2527:                if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
                   2528:                    (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
                   2529:                    (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
                   2530:                    (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
                   2531:                    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
                   2532:                        goto out;
                   2533:                break;
                   2534:        case KEY_DSA_CERT:
                   2535:                if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
                   2536:                        r = SSH_ERR_INVALID_ARGUMENT;
                   2537:                        goto out;
                   2538:                }
                   2539:                if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
                   2540:                    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
                   2541:                        goto out;
                   2542:                break;
                   2543:        case KEY_ECDSA:
                   2544:                if ((r = sshbuf_put_cstring(b,
                   2545:                    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
                   2546:                    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
                   2547:                    (r = sshbuf_put_bignum2(b,
                   2548:                    EC_KEY_get0_private_key(key->ecdsa))) != 0)
                   2549:                        goto out;
                   2550:                break;
                   2551:        case KEY_ECDSA_CERT:
                   2552:                if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
                   2553:                        r = SSH_ERR_INVALID_ARGUMENT;
                   2554:                        goto out;
                   2555:                }
                   2556:                if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
                   2557:                    (r = sshbuf_put_bignum2(b,
                   2558:                    EC_KEY_get0_private_key(key->ecdsa))) != 0)
                   2559:                        goto out;
                   2560:                break;
                   2561: #endif /* WITH_OPENSSL */
                   2562:        case KEY_ED25519:
                   2563:                if ((r = sshbuf_put_string(b, key->ed25519_pk,
                   2564:                    ED25519_PK_SZ)) != 0 ||
                   2565:                    (r = sshbuf_put_string(b, key->ed25519_sk,
                   2566:                    ED25519_SK_SZ)) != 0)
                   2567:                        goto out;
                   2568:                break;
                   2569:        case KEY_ED25519_CERT:
                   2570:                if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
                   2571:                        r = SSH_ERR_INVALID_ARGUMENT;
                   2572:                        goto out;
                   2573:                }
                   2574:                if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
                   2575:                    (r = sshbuf_put_string(b, key->ed25519_pk,
                   2576:                    ED25519_PK_SZ)) != 0 ||
                   2577:                    (r = sshbuf_put_string(b, key->ed25519_sk,
                   2578:                    ED25519_SK_SZ)) != 0)
                   2579:                        goto out;
                   2580:                break;
                   2581:        default:
                   2582:                r = SSH_ERR_INVALID_ARGUMENT;
                   2583:                goto out;
                   2584:        }
                   2585:        /* success */
                   2586:        r = 0;
                   2587:  out:
                   2588:        return r;
                   2589: }
                   2590:
                   2591: int
                   2592: sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
                   2593: {
                   2594:        char *tname = NULL, *curve = NULL;
                   2595:        struct sshkey *k = NULL;
1.14      djm      2596:        size_t pklen = 0, sklen = 0;
1.1       djm      2597:        int type, r = SSH_ERR_INTERNAL_ERROR;
                   2598:        u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
                   2599: #ifdef WITH_OPENSSL
                   2600:        BIGNUM *exponent = NULL;
                   2601: #endif /* WITH_OPENSSL */
                   2602:
                   2603:        if (kp != NULL)
                   2604:                *kp = NULL;
                   2605:        if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
                   2606:                goto out;
                   2607:        type = sshkey_type_from_name(tname);
                   2608:        switch (type) {
                   2609: #ifdef WITH_OPENSSL
                   2610:        case KEY_DSA:
                   2611:                if ((k = sshkey_new_private(type)) == NULL) {
                   2612:                        r = SSH_ERR_ALLOC_FAIL;
                   2613:                        goto out;
                   2614:                }
                   2615:                if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
                   2616:                    (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
                   2617:                    (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
                   2618:                    (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
                   2619:                    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
                   2620:                        goto out;
                   2621:                break;
                   2622:        case KEY_DSA_CERT:
1.14      djm      2623:                if ((r = sshkey_froms(buf, &k)) != 0 ||
1.1       djm      2624:                    (r = sshkey_add_private(k)) != 0 ||
                   2625:                    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
                   2626:                        goto out;
                   2627:                break;
                   2628:        case KEY_ECDSA:
                   2629:                if ((k = sshkey_new_private(type)) == NULL) {
                   2630:                        r = SSH_ERR_ALLOC_FAIL;
                   2631:                        goto out;
                   2632:                }
                   2633:                if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
                   2634:                        r = SSH_ERR_INVALID_ARGUMENT;
                   2635:                        goto out;
                   2636:                }
                   2637:                if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
                   2638:                        goto out;
                   2639:                if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
                   2640:                        r = SSH_ERR_EC_CURVE_MISMATCH;
                   2641:                        goto out;
                   2642:                }
                   2643:                k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
                   2644:                if (k->ecdsa  == NULL || (exponent = BN_new()) == NULL) {
                   2645:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   2646:                        goto out;
                   2647:                }
                   2648:                if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
                   2649:                    (r = sshbuf_get_bignum2(buf, exponent)))
                   2650:                        goto out;
                   2651:                if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
                   2652:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   2653:                        goto out;
                   2654:                }
                   2655:                if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
                   2656:                    EC_KEY_get0_public_key(k->ecdsa)) != 0) ||
                   2657:                    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
                   2658:                        goto out;
                   2659:                break;
                   2660:        case KEY_ECDSA_CERT:
                   2661:                if ((exponent = BN_new()) == NULL) {
                   2662:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   2663:                        goto out;
                   2664:                }
1.14      djm      2665:                if ((r = sshkey_froms(buf, &k)) != 0 ||
1.1       djm      2666:                    (r = sshkey_add_private(k)) != 0 ||
                   2667:                    (r = sshbuf_get_bignum2(buf, exponent)) != 0)
                   2668:                        goto out;
                   2669:                if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
                   2670:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   2671:                        goto out;
                   2672:                }
                   2673:                if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
                   2674:                    EC_KEY_get0_public_key(k->ecdsa)) != 0) ||
                   2675:                    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
                   2676:                        goto out;
                   2677:                break;
                   2678:        case KEY_RSA:
                   2679:                if ((k = sshkey_new_private(type)) == NULL) {
                   2680:                        r = SSH_ERR_ALLOC_FAIL;
                   2681:                        goto out;
                   2682:                }
                   2683:                if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
                   2684:                    (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
                   2685:                    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
                   2686:                    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
                   2687:                    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
                   2688:                    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
                   2689:                    (r = rsa_generate_additional_parameters(k->rsa)) != 0)
                   2690:                        goto out;
                   2691:                break;
                   2692:        case KEY_RSA_CERT:
1.14      djm      2693:                if ((r = sshkey_froms(buf, &k)) != 0 ||
1.1       djm      2694:                    (r = sshkey_add_private(k)) != 0 ||
                   2695:                    (r = sshbuf_get_bignum2(buf, k->rsa->d) != 0) ||
                   2696:                    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp) != 0) ||
                   2697:                    (r = sshbuf_get_bignum2(buf, k->rsa->p) != 0) ||
                   2698:                    (r = sshbuf_get_bignum2(buf, k->rsa->q) != 0) ||
                   2699:                    (r = rsa_generate_additional_parameters(k->rsa)) != 0)
                   2700:                        goto out;
                   2701:                break;
                   2702: #endif /* WITH_OPENSSL */
                   2703:        case KEY_ED25519:
                   2704:                if ((k = sshkey_new_private(type)) == NULL) {
                   2705:                        r = SSH_ERR_ALLOC_FAIL;
                   2706:                        goto out;
                   2707:                }
                   2708:                if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
                   2709:                    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
                   2710:                        goto out;
                   2711:                if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
                   2712:                        r = SSH_ERR_INVALID_FORMAT;
                   2713:                        goto out;
                   2714:                }
                   2715:                k->ed25519_pk = ed25519_pk;
                   2716:                k->ed25519_sk = ed25519_sk;
                   2717:                ed25519_pk = ed25519_sk = NULL;
                   2718:                break;
                   2719:        case KEY_ED25519_CERT:
1.14      djm      2720:                if ((r = sshkey_froms(buf, &k)) != 0 ||
1.1       djm      2721:                    (r = sshkey_add_private(k)) != 0 ||
                   2722:                    (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
                   2723:                    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
                   2724:                        goto out;
                   2725:                if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
                   2726:                        r = SSH_ERR_INVALID_FORMAT;
                   2727:                        goto out;
                   2728:                }
                   2729:                k->ed25519_pk = ed25519_pk;
                   2730:                k->ed25519_sk = ed25519_sk;
                   2731:                ed25519_pk = ed25519_sk = NULL;
                   2732:                break;
                   2733:        default:
                   2734:                r = SSH_ERR_KEY_TYPE_UNKNOWN;
                   2735:                goto out;
                   2736:        }
                   2737: #ifdef WITH_OPENSSL
                   2738:        /* enable blinding */
                   2739:        switch (k->type) {
                   2740:        case KEY_RSA:
                   2741:        case KEY_RSA_CERT:
                   2742:        case KEY_RSA1:
                   2743:                if (RSA_blinding_on(k->rsa, NULL) != 1) {
                   2744:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   2745:                        goto out;
                   2746:                }
                   2747:                break;
                   2748:        }
                   2749: #endif /* WITH_OPENSSL */
                   2750:        /* success */
                   2751:        r = 0;
                   2752:        if (kp != NULL) {
                   2753:                *kp = k;
                   2754:                k = NULL;
                   2755:        }
                   2756:  out:
                   2757:        free(tname);
                   2758:        free(curve);
                   2759: #ifdef WITH_OPENSSL
                   2760:        if (exponent != NULL)
                   2761:                BN_clear_free(exponent);
                   2762: #endif /* WITH_OPENSSL */
                   2763:        sshkey_free(k);
                   2764:        if (ed25519_pk != NULL) {
                   2765:                explicit_bzero(ed25519_pk, pklen);
                   2766:                free(ed25519_pk);
                   2767:        }
                   2768:        if (ed25519_sk != NULL) {
                   2769:                explicit_bzero(ed25519_sk, sklen);
                   2770:                free(ed25519_sk);
                   2771:        }
                   2772:        return r;
                   2773: }
                   2774:
                   2775: #ifdef WITH_OPENSSL
                   2776: int
                   2777: sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
                   2778: {
                   2779:        BN_CTX *bnctx;
                   2780:        EC_POINT *nq = NULL;
                   2781:        BIGNUM *order, *x, *y, *tmp;
                   2782:        int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
                   2783:
                   2784:        if ((bnctx = BN_CTX_new()) == NULL)
                   2785:                return SSH_ERR_ALLOC_FAIL;
                   2786:        BN_CTX_start(bnctx);
                   2787:
                   2788:        /*
                   2789:         * We shouldn't ever hit this case because bignum_get_ecpoint()
                   2790:         * refuses to load GF2m points.
                   2791:         */
                   2792:        if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
                   2793:            NID_X9_62_prime_field)
                   2794:                goto out;
                   2795:
                   2796:        /* Q != infinity */
                   2797:        if (EC_POINT_is_at_infinity(group, public))
                   2798:                goto out;
                   2799:
                   2800:        if ((x = BN_CTX_get(bnctx)) == NULL ||
                   2801:            (y = BN_CTX_get(bnctx)) == NULL ||
                   2802:            (order = BN_CTX_get(bnctx)) == NULL ||
                   2803:            (tmp = BN_CTX_get(bnctx)) == NULL) {
                   2804:                ret = SSH_ERR_ALLOC_FAIL;
                   2805:                goto out;
                   2806:        }
                   2807:
                   2808:        /* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
                   2809:        if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
                   2810:            EC_POINT_get_affine_coordinates_GFp(group, public,
                   2811:            x, y, bnctx) != 1) {
                   2812:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   2813:                goto out;
                   2814:        }
                   2815:        if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
                   2816:            BN_num_bits(y) <= BN_num_bits(order) / 2)
                   2817:                goto out;
                   2818:
                   2819:        /* nQ == infinity (n == order of subgroup) */
                   2820:        if ((nq = EC_POINT_new(group)) == NULL) {
                   2821:                ret = SSH_ERR_ALLOC_FAIL;
                   2822:                goto out;
                   2823:        }
                   2824:        if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
                   2825:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   2826:                goto out;
                   2827:        }
                   2828:        if (EC_POINT_is_at_infinity(group, nq) != 1)
                   2829:                goto out;
                   2830:
                   2831:        /* x < order - 1, y < order - 1 */
                   2832:        if (!BN_sub(tmp, order, BN_value_one())) {
                   2833:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   2834:                goto out;
                   2835:        }
                   2836:        if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
                   2837:                goto out;
                   2838:        ret = 0;
                   2839:  out:
                   2840:        BN_CTX_free(bnctx);
                   2841:        if (nq != NULL)
                   2842:                EC_POINT_free(nq);
                   2843:        return ret;
                   2844: }
                   2845:
                   2846: int
                   2847: sshkey_ec_validate_private(const EC_KEY *key)
                   2848: {
                   2849:        BN_CTX *bnctx;
                   2850:        BIGNUM *order, *tmp;
                   2851:        int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
                   2852:
                   2853:        if ((bnctx = BN_CTX_new()) == NULL)
                   2854:                return SSH_ERR_ALLOC_FAIL;
                   2855:        BN_CTX_start(bnctx);
                   2856:
                   2857:        if ((order = BN_CTX_get(bnctx)) == NULL ||
                   2858:            (tmp = BN_CTX_get(bnctx)) == NULL) {
                   2859:                ret = SSH_ERR_ALLOC_FAIL;
                   2860:                goto out;
                   2861:        }
                   2862:
                   2863:        /* log2(private) > log2(order)/2 */
                   2864:        if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
                   2865:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   2866:                goto out;
                   2867:        }
                   2868:        if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
                   2869:            BN_num_bits(order) / 2)
                   2870:                goto out;
                   2871:
                   2872:        /* private < order - 1 */
                   2873:        if (!BN_sub(tmp, order, BN_value_one())) {
                   2874:                ret = SSH_ERR_LIBCRYPTO_ERROR;
                   2875:                goto out;
                   2876:        }
                   2877:        if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
                   2878:                goto out;
                   2879:        ret = 0;
                   2880:  out:
                   2881:        BN_CTX_free(bnctx);
                   2882:        return ret;
                   2883: }
                   2884:
                   2885: void
                   2886: sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
                   2887: {
                   2888:        BIGNUM *x, *y;
                   2889:        BN_CTX *bnctx;
                   2890:
                   2891:        if (point == NULL) {
                   2892:                fputs("point=(NULL)\n", stderr);
                   2893:                return;
                   2894:        }
                   2895:        if ((bnctx = BN_CTX_new()) == NULL) {
                   2896:                fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
                   2897:                return;
                   2898:        }
                   2899:        BN_CTX_start(bnctx);
                   2900:        if ((x = BN_CTX_get(bnctx)) == NULL ||
                   2901:            (y = BN_CTX_get(bnctx)) == NULL) {
                   2902:                fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
                   2903:                return;
                   2904:        }
                   2905:        if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
                   2906:            NID_X9_62_prime_field) {
                   2907:                fprintf(stderr, "%s: group is not a prime field\n", __func__);
                   2908:                return;
                   2909:        }
                   2910:        if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
                   2911:            bnctx) != 1) {
                   2912:                fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
                   2913:                    __func__);
                   2914:                return;
                   2915:        }
                   2916:        fputs("x=", stderr);
                   2917:        BN_print_fp(stderr, x);
                   2918:        fputs("\ny=", stderr);
                   2919:        BN_print_fp(stderr, y);
                   2920:        fputs("\n", stderr);
                   2921:        BN_CTX_free(bnctx);
                   2922: }
                   2923:
                   2924: void
                   2925: sshkey_dump_ec_key(const EC_KEY *key)
                   2926: {
                   2927:        const BIGNUM *exponent;
                   2928:
                   2929:        sshkey_dump_ec_point(EC_KEY_get0_group(key),
                   2930:            EC_KEY_get0_public_key(key));
                   2931:        fputs("exponent=", stderr);
                   2932:        if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
                   2933:                fputs("(NULL)", stderr);
                   2934:        else
                   2935:                BN_print_fp(stderr, EC_KEY_get0_private_key(key));
                   2936:        fputs("\n", stderr);
                   2937: }
                   2938: #endif /* WITH_OPENSSL */
                   2939:
                   2940: static int
                   2941: sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
                   2942:     const char *passphrase, const char *comment, const char *ciphername,
                   2943:     int rounds)
                   2944: {
1.4       djm      2945:        u_char *cp, *key = NULL, *pubkeyblob = NULL;
1.1       djm      2946:        u_char salt[SALT_LEN];
1.4       djm      2947:        char *b64 = NULL;
1.1       djm      2948:        size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
                   2949:        u_int check;
                   2950:        int r = SSH_ERR_INTERNAL_ERROR;
                   2951:        struct sshcipher_ctx ciphercontext;
                   2952:        const struct sshcipher *cipher;
                   2953:        const char *kdfname = KDFNAME;
                   2954:        struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
                   2955:
                   2956:        memset(&ciphercontext, 0, sizeof(ciphercontext));
                   2957:
                   2958:        if (rounds <= 0)
                   2959:                rounds = DEFAULT_ROUNDS;
                   2960:        if (passphrase == NULL || !strlen(passphrase)) {
                   2961:                ciphername = "none";
                   2962:                kdfname = "none";
                   2963:        } else if (ciphername == NULL)
                   2964:                ciphername = DEFAULT_CIPHERNAME;
                   2965:        else if (cipher_number(ciphername) != SSH_CIPHER_SSH2) {
                   2966:                r = SSH_ERR_INVALID_ARGUMENT;
                   2967:                goto out;
                   2968:        }
                   2969:        if ((cipher = cipher_by_name(ciphername)) == NULL) {
                   2970:                r = SSH_ERR_INTERNAL_ERROR;
                   2971:                goto out;
                   2972:        }
                   2973:
                   2974:        if ((kdf = sshbuf_new()) == NULL ||
                   2975:            (encoded = sshbuf_new()) == NULL ||
                   2976:            (encrypted = sshbuf_new()) == NULL) {
                   2977:                r = SSH_ERR_ALLOC_FAIL;
                   2978:                goto out;
                   2979:        }
                   2980:        blocksize = cipher_blocksize(cipher);
                   2981:        keylen = cipher_keylen(cipher);
                   2982:        ivlen = cipher_ivlen(cipher);
                   2983:        authlen = cipher_authlen(cipher);
                   2984:        if ((key = calloc(1, keylen + ivlen)) == NULL) {
                   2985:                r = SSH_ERR_ALLOC_FAIL;
                   2986:                goto out;
                   2987:        }
                   2988:        if (strcmp(kdfname, "bcrypt") == 0) {
                   2989:                arc4random_buf(salt, SALT_LEN);
                   2990:                if (bcrypt_pbkdf(passphrase, strlen(passphrase),
                   2991:                    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
                   2992:                        r = SSH_ERR_INVALID_ARGUMENT;
                   2993:                        goto out;
                   2994:                }
                   2995:                if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
                   2996:                    (r = sshbuf_put_u32(kdf, rounds)) != 0)
                   2997:                        goto out;
                   2998:        } else if (strcmp(kdfname, "none") != 0) {
                   2999:                /* Unsupported KDF type */
                   3000:                r = SSH_ERR_KEY_UNKNOWN_CIPHER;
                   3001:                goto out;
                   3002:        }
                   3003:        if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
                   3004:            key + keylen, ivlen, 1)) != 0)
                   3005:                goto out;
                   3006:
                   3007:        if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
                   3008:            (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
                   3009:            (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
                   3010:            (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
                   3011:            (r = sshbuf_put_u32(encoded, 1)) != 0 ||    /* number of keys */
                   3012:            (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
                   3013:            (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
                   3014:                goto out;
                   3015:
                   3016:        /* set up the buffer that will be encrypted */
                   3017:
                   3018:        /* Random check bytes */
                   3019:        check = arc4random();
                   3020:        if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
                   3021:            (r = sshbuf_put_u32(encrypted, check)) != 0)
                   3022:                goto out;
                   3023:
                   3024:        /* append private key and comment*/
                   3025:        if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
                   3026:            (r = sshbuf_put_cstring(encrypted, comment)) != 0)
                   3027:                goto out;
                   3028:
                   3029:        /* padding */
                   3030:        i = 0;
                   3031:        while (sshbuf_len(encrypted) % blocksize) {
                   3032:                if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
                   3033:                        goto out;
                   3034:        }
                   3035:
                   3036:        /* length in destination buffer */
                   3037:        if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
                   3038:                goto out;
                   3039:
                   3040:        /* encrypt */
                   3041:        if ((r = sshbuf_reserve(encoded,
                   3042:            sshbuf_len(encrypted) + authlen, &cp)) != 0)
                   3043:                goto out;
                   3044:        if ((r = cipher_crypt(&ciphercontext, 0, cp,
                   3045:            sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
                   3046:                goto out;
                   3047:
                   3048:        /* uuencode */
                   3049:        if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
                   3050:                r = SSH_ERR_ALLOC_FAIL;
                   3051:                goto out;
                   3052:        }
                   3053:
                   3054:        sshbuf_reset(blob);
                   3055:        if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
                   3056:                goto out;
                   3057:        for (i = 0; i < strlen(b64); i++) {
                   3058:                if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
                   3059:                        goto out;
                   3060:                /* insert line breaks */
                   3061:                if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
                   3062:                        goto out;
                   3063:        }
                   3064:        if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
                   3065:                goto out;
                   3066:        if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
                   3067:                goto out;
                   3068:
                   3069:        /* success */
                   3070:        r = 0;
                   3071:
                   3072:  out:
                   3073:        sshbuf_free(kdf);
                   3074:        sshbuf_free(encoded);
                   3075:        sshbuf_free(encrypted);
                   3076:        cipher_cleanup(&ciphercontext);
                   3077:        explicit_bzero(salt, sizeof(salt));
                   3078:        if (key != NULL) {
                   3079:                explicit_bzero(key, keylen + ivlen);
                   3080:                free(key);
                   3081:        }
                   3082:        if (pubkeyblob != NULL) {
                   3083:                explicit_bzero(pubkeyblob, pubkeylen);
                   3084:                free(pubkeyblob);
                   3085:        }
                   3086:        if (b64 != NULL) {
                   3087:                explicit_bzero(b64, strlen(b64));
                   3088:                free(b64);
                   3089:        }
                   3090:        return r;
                   3091: }
                   3092:
                   3093: static int
                   3094: sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
                   3095:     struct sshkey **keyp, char **commentp)
                   3096: {
                   3097:        char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
                   3098:        const struct sshcipher *cipher = NULL;
                   3099:        const u_char *cp;
                   3100:        int r = SSH_ERR_INTERNAL_ERROR;
                   3101:        size_t encoded_len;
1.18      djm      3102:        size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
1.1       djm      3103:        struct sshbuf *encoded = NULL, *decoded = NULL;
                   3104:        struct sshbuf *kdf = NULL, *decrypted = NULL;
                   3105:        struct sshcipher_ctx ciphercontext;
                   3106:        struct sshkey *k = NULL;
                   3107:        u_char *key = NULL, *salt = NULL, *dp, pad, last;
                   3108:        u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
                   3109:
                   3110:        memset(&ciphercontext, 0, sizeof(ciphercontext));
                   3111:        if (keyp != NULL)
                   3112:                *keyp = NULL;
                   3113:        if (commentp != NULL)
                   3114:                *commentp = NULL;
                   3115:
                   3116:        if ((encoded = sshbuf_new()) == NULL ||
                   3117:            (decoded = sshbuf_new()) == NULL ||
                   3118:            (decrypted = sshbuf_new()) == NULL) {
                   3119:                r = SSH_ERR_ALLOC_FAIL;
                   3120:                goto out;
                   3121:        }
                   3122:
                   3123:        /* check preamble */
                   3124:        cp = sshbuf_ptr(blob);
                   3125:        encoded_len = sshbuf_len(blob);
                   3126:        if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
                   3127:            memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
                   3128:                r = SSH_ERR_INVALID_FORMAT;
                   3129:                goto out;
                   3130:        }
                   3131:        cp += MARK_BEGIN_LEN;
                   3132:        encoded_len -= MARK_BEGIN_LEN;
                   3133:
                   3134:        /* Look for end marker, removing whitespace as we go */
                   3135:        while (encoded_len > 0) {
                   3136:                if (*cp != '\n' && *cp != '\r') {
                   3137:                        if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
                   3138:                                goto out;
                   3139:                }
                   3140:                last = *cp;
                   3141:                encoded_len--;
                   3142:                cp++;
                   3143:                if (last == '\n') {
                   3144:                        if (encoded_len >= MARK_END_LEN &&
                   3145:                            memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
                   3146:                                /* \0 terminate */
                   3147:                                if ((r = sshbuf_put_u8(encoded, 0)) != 0)
                   3148:                                        goto out;
                   3149:                                break;
                   3150:                        }
                   3151:                }
                   3152:        }
                   3153:        if (encoded_len == 0) {
                   3154:                r = SSH_ERR_INVALID_FORMAT;
                   3155:                goto out;
                   3156:        }
                   3157:
                   3158:        /* decode base64 */
1.4       djm      3159:        if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
1.1       djm      3160:                goto out;
                   3161:
                   3162:        /* check magic */
                   3163:        if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
                   3164:            memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
                   3165:                r = SSH_ERR_INVALID_FORMAT;
                   3166:                goto out;
                   3167:        }
                   3168:        /* parse public portion of key */
                   3169:        if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
                   3170:            (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
                   3171:            (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
                   3172:            (r = sshbuf_froms(decoded, &kdf)) != 0 ||
                   3173:            (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
                   3174:            (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
                   3175:            (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
                   3176:                goto out;
                   3177:
                   3178:        if ((cipher = cipher_by_name(ciphername)) == NULL) {
                   3179:                r = SSH_ERR_KEY_UNKNOWN_CIPHER;
                   3180:                goto out;
                   3181:        }
                   3182:        if ((passphrase == NULL || strlen(passphrase) == 0) &&
                   3183:            strcmp(ciphername, "none") != 0) {
                   3184:                /* passphrase required */
                   3185:                r = SSH_ERR_KEY_WRONG_PASSPHRASE;
                   3186:                goto out;
                   3187:        }
                   3188:        if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
                   3189:                r = SSH_ERR_KEY_UNKNOWN_CIPHER;
                   3190:                goto out;
                   3191:        }
                   3192:        if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
                   3193:                r = SSH_ERR_INVALID_FORMAT;
                   3194:                goto out;
                   3195:        }
                   3196:        if (nkeys != 1) {
                   3197:                /* XXX only one key supported */
                   3198:                r = SSH_ERR_INVALID_FORMAT;
                   3199:                goto out;
                   3200:        }
                   3201:
                   3202:        /* check size of encrypted key blob */
                   3203:        blocksize = cipher_blocksize(cipher);
                   3204:        if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
                   3205:                r = SSH_ERR_INVALID_FORMAT;
                   3206:                goto out;
                   3207:        }
                   3208:
                   3209:        /* setup key */
                   3210:        keylen = cipher_keylen(cipher);
                   3211:        ivlen = cipher_ivlen(cipher);
1.18      djm      3212:        authlen = cipher_authlen(cipher);
1.1       djm      3213:        if ((key = calloc(1, keylen + ivlen)) == NULL) {
                   3214:                r = SSH_ERR_ALLOC_FAIL;
                   3215:                goto out;
                   3216:        }
                   3217:        if (strcmp(kdfname, "bcrypt") == 0) {
                   3218:                if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
                   3219:                    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
                   3220:                        goto out;
                   3221:                if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
                   3222:                    key, keylen + ivlen, rounds) < 0) {
                   3223:                        r = SSH_ERR_INVALID_FORMAT;
                   3224:                        goto out;
                   3225:                }
                   3226:        }
                   3227:
1.18      djm      3228:        /* check that an appropriate amount of auth data is present */
                   3229:        if (sshbuf_len(decoded) < encrypted_len + authlen) {
                   3230:                r = SSH_ERR_INVALID_FORMAT;
                   3231:                goto out;
                   3232:        }
                   3233:
1.1       djm      3234:        /* decrypt private portion of key */
                   3235:        if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
                   3236:            (r = cipher_init(&ciphercontext, cipher, key, keylen,
                   3237:            key + keylen, ivlen, 0)) != 0)
                   3238:                goto out;
                   3239:        if ((r = cipher_crypt(&ciphercontext, 0, dp, sshbuf_ptr(decoded),
1.18      djm      3240:            encrypted_len, 0, authlen)) != 0) {
1.1       djm      3241:                /* an integrity error here indicates an incorrect passphrase */
                   3242:                if (r == SSH_ERR_MAC_INVALID)
                   3243:                        r = SSH_ERR_KEY_WRONG_PASSPHRASE;
                   3244:                goto out;
                   3245:        }
1.18      djm      3246:        if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
1.1       djm      3247:                goto out;
                   3248:        /* there should be no trailing data */
                   3249:        if (sshbuf_len(decoded) != 0) {
                   3250:                r = SSH_ERR_INVALID_FORMAT;
                   3251:                goto out;
                   3252:        }
                   3253:
                   3254:        /* check check bytes */
                   3255:        if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
                   3256:            (r = sshbuf_get_u32(decrypted, &check2)) != 0)
                   3257:                goto out;
                   3258:        if (check1 != check2) {
                   3259:                r = SSH_ERR_KEY_WRONG_PASSPHRASE;
                   3260:                goto out;
                   3261:        }
                   3262:
                   3263:        /* Load the private key and comment */
                   3264:        if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
                   3265:            (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
                   3266:                goto out;
                   3267:
                   3268:        /* Check deterministic padding */
                   3269:        i = 0;
                   3270:        while (sshbuf_len(decrypted)) {
                   3271:                if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
                   3272:                        goto out;
                   3273:                if (pad != (++i & 0xff)) {
                   3274:                        r = SSH_ERR_INVALID_FORMAT;
                   3275:                        goto out;
                   3276:                }
                   3277:        }
                   3278:
                   3279:        /* XXX decode pubkey and check against private */
                   3280:
                   3281:        /* success */
                   3282:        r = 0;
                   3283:        if (keyp != NULL) {
                   3284:                *keyp = k;
                   3285:                k = NULL;
                   3286:        }
                   3287:        if (commentp != NULL) {
                   3288:                *commentp = comment;
                   3289:                comment = NULL;
                   3290:        }
                   3291:  out:
                   3292:        pad = 0;
                   3293:        cipher_cleanup(&ciphercontext);
                   3294:        free(ciphername);
                   3295:        free(kdfname);
                   3296:        free(comment);
                   3297:        if (salt != NULL) {
                   3298:                explicit_bzero(salt, slen);
                   3299:                free(salt);
                   3300:        }
                   3301:        if (key != NULL) {
                   3302:                explicit_bzero(key, keylen + ivlen);
                   3303:                free(key);
                   3304:        }
                   3305:        sshbuf_free(encoded);
                   3306:        sshbuf_free(decoded);
                   3307:        sshbuf_free(kdf);
                   3308:        sshbuf_free(decrypted);
                   3309:        sshkey_free(k);
                   3310:        return r;
                   3311: }
                   3312:
                   3313: #if WITH_SSH1
                   3314: /*
                   3315:  * Serialises the authentication (private) key to a blob, encrypting it with
                   3316:  * passphrase.  The identification of the blob (lowest 64 bits of n) will
                   3317:  * precede the key to provide identification of the key without needing a
                   3318:  * passphrase.
                   3319:  */
                   3320: static int
                   3321: sshkey_private_rsa1_to_blob(struct sshkey *key, struct sshbuf *blob,
                   3322:     const char *passphrase, const char *comment)
                   3323: {
                   3324:        struct sshbuf *buffer = NULL, *encrypted = NULL;
                   3325:        u_char buf[8];
                   3326:        int r, cipher_num;
                   3327:        struct sshcipher_ctx ciphercontext;
                   3328:        const struct sshcipher *cipher;
                   3329:        u_char *cp;
                   3330:
                   3331:        /*
                   3332:         * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
                   3333:         * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
                   3334:         */
                   3335:        cipher_num = (strcmp(passphrase, "") == 0) ?
                   3336:            SSH_CIPHER_NONE : SSH_CIPHER_3DES;
                   3337:        if ((cipher = cipher_by_number(cipher_num)) == NULL)
                   3338:                return SSH_ERR_INTERNAL_ERROR;
                   3339:
                   3340:        /* This buffer is used to build the secret part of the private key. */
                   3341:        if ((buffer = sshbuf_new()) == NULL)
                   3342:                return SSH_ERR_ALLOC_FAIL;
                   3343:
                   3344:        /* Put checkbytes for checking passphrase validity. */
                   3345:        if ((r = sshbuf_reserve(buffer, 4, &cp)) != 0)
                   3346:                goto out;
                   3347:        arc4random_buf(cp, 2);
                   3348:        memcpy(cp + 2, cp, 2);
                   3349:
                   3350:        /*
                   3351:         * Store the private key (n and e will not be stored because they
                   3352:         * will be stored in plain text, and storing them also in encrypted
                   3353:         * format would just give known plaintext).
                   3354:         * Note: q and p are stored in reverse order to SSL.
                   3355:         */
                   3356:        if ((r = sshbuf_put_bignum1(buffer, key->rsa->d)) != 0 ||
                   3357:            (r = sshbuf_put_bignum1(buffer, key->rsa->iqmp)) != 0 ||
                   3358:            (r = sshbuf_put_bignum1(buffer, key->rsa->q)) != 0 ||
                   3359:            (r = sshbuf_put_bignum1(buffer, key->rsa->p)) != 0)
                   3360:                goto out;
                   3361:
                   3362:        /* Pad the part to be encrypted to a size that is a multiple of 8. */
                   3363:        explicit_bzero(buf, 8);
                   3364:        if ((r = sshbuf_put(buffer, buf, 8 - (sshbuf_len(buffer) % 8))) != 0)
                   3365:                goto out;
                   3366:
                   3367:        /* This buffer will be used to contain the data in the file. */
                   3368:        if ((encrypted = sshbuf_new()) == NULL) {
                   3369:                r = SSH_ERR_ALLOC_FAIL;
                   3370:                goto out;
                   3371:        }
                   3372:
                   3373:        /* First store keyfile id string. */
                   3374:        if ((r = sshbuf_put(encrypted, LEGACY_BEGIN,
                   3375:            sizeof(LEGACY_BEGIN))) != 0)
                   3376:                goto out;
                   3377:
                   3378:        /* Store cipher type and "reserved" field. */
                   3379:        if ((r = sshbuf_put_u8(encrypted, cipher_num)) != 0 ||
                   3380:            (r = sshbuf_put_u32(encrypted, 0)) != 0)
                   3381:                goto out;
                   3382:
                   3383:        /* Store public key.  This will be in plain text. */
                   3384:        if ((r = sshbuf_put_u32(encrypted, BN_num_bits(key->rsa->n))) != 0 ||
                   3385:            (r = sshbuf_put_bignum1(encrypted, key->rsa->n) != 0) ||
                   3386:            (r = sshbuf_put_bignum1(encrypted, key->rsa->e) != 0) ||
                   3387:            (r = sshbuf_put_cstring(encrypted, comment) != 0))
                   3388:                goto out;
                   3389:
                   3390:        /* Allocate space for the private part of the key in the buffer. */
                   3391:        if ((r = sshbuf_reserve(encrypted, sshbuf_len(buffer), &cp)) != 0)
                   3392:                goto out;
                   3393:
                   3394:        if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
                   3395:            CIPHER_ENCRYPT)) != 0)
                   3396:                goto out;
                   3397:        if ((r = cipher_crypt(&ciphercontext, 0, cp,
                   3398:            sshbuf_ptr(buffer), sshbuf_len(buffer), 0, 0)) != 0)
                   3399:                goto out;
                   3400:        if ((r = cipher_cleanup(&ciphercontext)) != 0)
                   3401:                goto out;
                   3402:
                   3403:        r = sshbuf_putb(blob, encrypted);
                   3404:
                   3405:  out:
                   3406:        explicit_bzero(&ciphercontext, sizeof(ciphercontext));
                   3407:        explicit_bzero(buf, sizeof(buf));
                   3408:        if (buffer != NULL)
                   3409:                sshbuf_free(buffer);
                   3410:        if (encrypted != NULL)
                   3411:                sshbuf_free(encrypted);
                   3412:
                   3413:        return r;
                   3414: }
                   3415: #endif /* WITH_SSH1 */
                   3416:
                   3417: #ifdef WITH_OPENSSL
                   3418: /* convert SSH v2 key in OpenSSL PEM format */
                   3419: static int
                   3420: sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
                   3421:     const char *_passphrase, const char *comment)
                   3422: {
                   3423:        int success, r;
                   3424:        int blen, len = strlen(_passphrase);
                   3425:        u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
                   3426:        const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
                   3427:        const u_char *bptr;
                   3428:        BIO *bio = NULL;
                   3429:
                   3430:        if (len > 0 && len <= 4)
                   3431:                return SSH_ERR_PASSPHRASE_TOO_SHORT;
                   3432:        if ((bio = BIO_new(BIO_s_mem())) == NULL)
                   3433:                return SSH_ERR_ALLOC_FAIL;
                   3434:
                   3435:        switch (key->type) {
                   3436:        case KEY_DSA:
                   3437:                success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
                   3438:                    cipher, passphrase, len, NULL, NULL);
                   3439:                break;
                   3440:        case KEY_ECDSA:
                   3441:                success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
                   3442:                    cipher, passphrase, len, NULL, NULL);
                   3443:                break;
                   3444:        case KEY_RSA:
                   3445:                success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
                   3446:                    cipher, passphrase, len, NULL, NULL);
                   3447:                break;
                   3448:        default:
                   3449:                success = 0;
                   3450:                break;
                   3451:        }
                   3452:        if (success == 0) {
                   3453:                r = SSH_ERR_LIBCRYPTO_ERROR;
                   3454:                goto out;
                   3455:        }
                   3456:        if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
                   3457:                r = SSH_ERR_INTERNAL_ERROR;
                   3458:                goto out;
                   3459:        }
                   3460:        if ((r = sshbuf_put(blob, bptr, blen)) != 0)
                   3461:                goto out;
                   3462:        r = 0;
                   3463:  out:
                   3464:        BIO_free(bio);
                   3465:        return r;
                   3466: }
                   3467: #endif /* WITH_OPENSSL */
                   3468:
                   3469: /* Serialise "key" to buffer "blob" */
                   3470: int
                   3471: sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
                   3472:     const char *passphrase, const char *comment,
                   3473:     int force_new_format, const char *new_format_cipher, int new_format_rounds)
                   3474: {
                   3475:        switch (key->type) {
1.9       markus   3476: #ifdef WITH_SSH1
1.1       djm      3477:        case KEY_RSA1:
                   3478:                return sshkey_private_rsa1_to_blob(key, blob,
                   3479:                    passphrase, comment);
1.9       markus   3480: #endif /* WITH_SSH1 */
                   3481: #ifdef WITH_OPENSSL
1.1       djm      3482:        case KEY_DSA:
                   3483:        case KEY_ECDSA:
                   3484:        case KEY_RSA:
                   3485:                if (force_new_format) {
                   3486:                        return sshkey_private_to_blob2(key, blob, passphrase,
                   3487:                            comment, new_format_cipher, new_format_rounds);
                   3488:                }
                   3489:                return sshkey_private_pem_to_blob(key, blob,
                   3490:                    passphrase, comment);
                   3491: #endif /* WITH_OPENSSL */
                   3492:        case KEY_ED25519:
                   3493:                return sshkey_private_to_blob2(key, blob, passphrase,
                   3494:                    comment, new_format_cipher, new_format_rounds);
                   3495:        default:
                   3496:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   3497:        }
                   3498: }
                   3499:
                   3500: #ifdef WITH_SSH1
                   3501: /*
                   3502:  * Parse the public, unencrypted portion of a RSA1 key.
                   3503:  */
                   3504: int
                   3505: sshkey_parse_public_rsa1_fileblob(struct sshbuf *blob,
                   3506:     struct sshkey **keyp, char **commentp)
                   3507: {
                   3508:        int r;
                   3509:        struct sshkey *pub = NULL;
                   3510:        struct sshbuf *copy = NULL;
                   3511:
                   3512:        if (keyp != NULL)
                   3513:                *keyp = NULL;
                   3514:        if (commentp != NULL)
                   3515:                *commentp = NULL;
                   3516:
                   3517:        /* Check that it is at least big enough to contain the ID string. */
                   3518:        if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
                   3519:                return SSH_ERR_INVALID_FORMAT;
                   3520:
                   3521:        /*
                   3522:         * Make sure it begins with the id string.  Consume the id string
                   3523:         * from the buffer.
                   3524:         */
                   3525:        if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
                   3526:                return SSH_ERR_INVALID_FORMAT;
                   3527:        /* Make a working copy of the keyblob and skip past the magic */
                   3528:        if ((copy = sshbuf_fromb(blob)) == NULL)
                   3529:                return SSH_ERR_ALLOC_FAIL;
                   3530:        if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
                   3531:                goto out;
                   3532:
                   3533:        /* Skip cipher type, reserved data and key bits. */
                   3534:        if ((r = sshbuf_get_u8(copy, NULL)) != 0 ||     /* cipher type */
                   3535:            (r = sshbuf_get_u32(copy, NULL)) != 0 ||    /* reserved */
                   3536:            (r = sshbuf_get_u32(copy, NULL)) != 0)      /* key bits */
                   3537:                goto out;
                   3538:
                   3539:        /* Read the public key from the buffer. */
                   3540:        if ((pub = sshkey_new(KEY_RSA1)) == NULL ||
                   3541:            (r = sshbuf_get_bignum1(copy, pub->rsa->n)) != 0 ||
                   3542:            (r = sshbuf_get_bignum1(copy, pub->rsa->e)) != 0)
                   3543:                goto out;
                   3544:
                   3545:        /* Finally, the comment */
                   3546:        if ((r = sshbuf_get_string(copy, (u_char**)commentp, NULL)) != 0)
                   3547:                goto out;
                   3548:
                   3549:        /* The encrypted private part is not parsed by this function. */
                   3550:
                   3551:        r = 0;
                   3552:        if (keyp != NULL)
                   3553:                *keyp = pub;
                   3554:        else
                   3555:                sshkey_free(pub);
                   3556:        pub = NULL;
                   3557:
                   3558:  out:
                   3559:        if (copy != NULL)
                   3560:                sshbuf_free(copy);
                   3561:        if (pub != NULL)
                   3562:                sshkey_free(pub);
                   3563:        return r;
                   3564: }
                   3565:
                   3566: static int
                   3567: sshkey_parse_private_rsa1(struct sshbuf *blob, const char *passphrase,
                   3568:     struct sshkey **keyp, char **commentp)
                   3569: {
                   3570:        int r;
                   3571:        u_int16_t check1, check2;
                   3572:        u_int8_t cipher_type;
                   3573:        struct sshbuf *decrypted = NULL, *copy = NULL;
                   3574:        u_char *cp;
                   3575:        char *comment = NULL;
                   3576:        struct sshcipher_ctx ciphercontext;
                   3577:        const struct sshcipher *cipher;
                   3578:        struct sshkey *prv = NULL;
                   3579:
                   3580:        *keyp = NULL;
                   3581:        if (commentp != NULL)
                   3582:                *commentp = NULL;
                   3583:
                   3584:        /* Check that it is at least big enough to contain the ID string. */
                   3585:        if (sshbuf_len(blob) < sizeof(LEGACY_BEGIN))
                   3586:                return SSH_ERR_INVALID_FORMAT;
                   3587:
                   3588:        /*
                   3589:         * Make sure it begins with the id string.  Consume the id string
                   3590:         * from the buffer.
                   3591:         */
                   3592:        if (memcmp(sshbuf_ptr(blob), LEGACY_BEGIN, sizeof(LEGACY_BEGIN)) != 0)
                   3593:                return SSH_ERR_INVALID_FORMAT;
                   3594:
                   3595:        if ((prv = sshkey_new_private(KEY_RSA1)) == NULL) {
                   3596:                r = SSH_ERR_ALLOC_FAIL;
                   3597:                goto out;
                   3598:        }
                   3599:        if ((copy = sshbuf_fromb(blob)) == NULL ||
                   3600:            (decrypted = sshbuf_new()) == NULL) {
                   3601:                r = SSH_ERR_ALLOC_FAIL;
                   3602:                goto out;
                   3603:        }
                   3604:        if ((r = sshbuf_consume(copy, sizeof(LEGACY_BEGIN))) != 0)
                   3605:                goto out;
                   3606:
                   3607:        /* Read cipher type. */
                   3608:        if ((r = sshbuf_get_u8(copy, &cipher_type)) != 0 ||
                   3609:            (r = sshbuf_get_u32(copy, NULL)) != 0)      /* reserved */
                   3610:                goto out;
                   3611:
                   3612:        /* Read the public key and comment from the buffer. */
                   3613:        if ((r = sshbuf_get_u32(copy, NULL)) != 0 ||    /* key bits */
                   3614:            (r = sshbuf_get_bignum1(copy, prv->rsa->n)) != 0 ||
                   3615:            (r = sshbuf_get_bignum1(copy, prv->rsa->e)) != 0 ||
                   3616:            (r = sshbuf_get_cstring(copy, &comment, NULL)) != 0)
                   3617:                goto out;
                   3618:
                   3619:        /* Check that it is a supported cipher. */
                   3620:        cipher = cipher_by_number(cipher_type);
                   3621:        if (cipher == NULL) {
                   3622:                r = SSH_ERR_KEY_UNKNOWN_CIPHER;
                   3623:                goto out;
                   3624:        }
                   3625:        /* Initialize space for decrypted data. */
                   3626:        if ((r = sshbuf_reserve(decrypted, sshbuf_len(copy), &cp)) != 0)
                   3627:                goto out;
                   3628:
                   3629:        /* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
                   3630:        if ((r = cipher_set_key_string(&ciphercontext, cipher, passphrase,
                   3631:            CIPHER_DECRYPT)) != 0)
                   3632:                goto out;
                   3633:        if ((r = cipher_crypt(&ciphercontext, 0, cp,
                   3634:            sshbuf_ptr(copy), sshbuf_len(copy), 0, 0)) != 0) {
                   3635:                cipher_cleanup(&ciphercontext);
                   3636:                goto out;
                   3637:        }
                   3638:        if ((r = cipher_cleanup(&ciphercontext)) != 0)
                   3639:                goto out;
                   3640:
                   3641:        if ((r = sshbuf_get_u16(decrypted, &check1)) != 0 ||
                   3642:            (r = sshbuf_get_u16(decrypted, &check2)) != 0)
                   3643:                goto out;
                   3644:        if (check1 != check2) {
                   3645:                r = SSH_ERR_KEY_WRONG_PASSPHRASE;
                   3646:                goto out;
                   3647:        }
                   3648:
                   3649:        /* Read the rest of the private key. */
                   3650:        if ((r = sshbuf_get_bignum1(decrypted, prv->rsa->d)) != 0 ||
                   3651:            (r = sshbuf_get_bignum1(decrypted, prv->rsa->iqmp)) != 0 ||
                   3652:            (r = sshbuf_get_bignum1(decrypted, prv->rsa->q)) != 0 ||
                   3653:            (r = sshbuf_get_bignum1(decrypted, prv->rsa->p)) != 0)
                   3654:                goto out;
                   3655:
                   3656:        /* calculate p-1 and q-1 */
                   3657:        if ((r = rsa_generate_additional_parameters(prv->rsa)) != 0)
                   3658:                goto out;
                   3659:
                   3660:        /* enable blinding */
                   3661:        if (RSA_blinding_on(prv->rsa, NULL) != 1) {
                   3662:                r = SSH_ERR_LIBCRYPTO_ERROR;
                   3663:                goto out;
                   3664:        }
                   3665:        r = 0;
                   3666:        *keyp = prv;
                   3667:        prv = NULL;
                   3668:        if (commentp != NULL) {
                   3669:                *commentp = comment;
                   3670:                comment = NULL;
                   3671:        }
                   3672:  out:
                   3673:        explicit_bzero(&ciphercontext, sizeof(ciphercontext));
                   3674:        if (comment != NULL)
                   3675:                free(comment);
                   3676:        if (prv != NULL)
                   3677:                sshkey_free(prv);
                   3678:        if (copy != NULL)
                   3679:                sshbuf_free(copy);
                   3680:        if (decrypted != NULL)
                   3681:                sshbuf_free(decrypted);
                   3682:        return r;
                   3683: }
                   3684: #endif /* WITH_SSH1 */
                   3685:
                   3686: #ifdef WITH_OPENSSL
1.8       djm      3687: static int
1.1       djm      3688: sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
1.8       djm      3689:     const char *passphrase, struct sshkey **keyp)
1.1       djm      3690: {
                   3691:        EVP_PKEY *pk = NULL;
                   3692:        struct sshkey *prv = NULL;
                   3693:        BIO *bio = NULL;
                   3694:        int r;
                   3695:
                   3696:        *keyp = NULL;
                   3697:
                   3698:        if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
                   3699:                return SSH_ERR_ALLOC_FAIL;
                   3700:        if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
                   3701:            (int)sshbuf_len(blob)) {
                   3702:                r = SSH_ERR_ALLOC_FAIL;
                   3703:                goto out;
                   3704:        }
                   3705:
                   3706:        if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
                   3707:            (char *)passphrase)) == NULL) {
                   3708:                r = SSH_ERR_KEY_WRONG_PASSPHRASE;
                   3709:                goto out;
                   3710:        }
                   3711:        if (pk->type == EVP_PKEY_RSA &&
                   3712:            (type == KEY_UNSPEC || type == KEY_RSA)) {
                   3713:                if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
                   3714:                        r = SSH_ERR_ALLOC_FAIL;
                   3715:                        goto out;
                   3716:                }
                   3717:                prv->rsa = EVP_PKEY_get1_RSA(pk);
                   3718:                prv->type = KEY_RSA;
                   3719: #ifdef DEBUG_PK
                   3720:                RSA_print_fp(stderr, prv->rsa, 8);
                   3721: #endif
                   3722:                if (RSA_blinding_on(prv->rsa, NULL) != 1) {
                   3723:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   3724:                        goto out;
                   3725:                }
                   3726:        } else if (pk->type == EVP_PKEY_DSA &&
                   3727:            (type == KEY_UNSPEC || type == KEY_DSA)) {
                   3728:                if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
                   3729:                        r = SSH_ERR_ALLOC_FAIL;
                   3730:                        goto out;
                   3731:                }
                   3732:                prv->dsa = EVP_PKEY_get1_DSA(pk);
                   3733:                prv->type = KEY_DSA;
                   3734: #ifdef DEBUG_PK
                   3735:                DSA_print_fp(stderr, prv->dsa, 8);
                   3736: #endif
                   3737:        } else if (pk->type == EVP_PKEY_EC &&
                   3738:            (type == KEY_UNSPEC || type == KEY_ECDSA)) {
                   3739:                if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
                   3740:                        r = SSH_ERR_ALLOC_FAIL;
                   3741:                        goto out;
                   3742:                }
                   3743:                prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
                   3744:                prv->type = KEY_ECDSA;
                   3745:                prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
                   3746:                if (prv->ecdsa_nid == -1 ||
                   3747:                    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
                   3748:                    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
                   3749:                    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
                   3750:                    sshkey_ec_validate_private(prv->ecdsa) != 0) {
                   3751:                        r = SSH_ERR_INVALID_FORMAT;
                   3752:                        goto out;
                   3753:                }
                   3754: #ifdef DEBUG_PK
                   3755:                if (prv != NULL && prv->ecdsa != NULL)
                   3756:                        sshkey_dump_ec_key(prv->ecdsa);
                   3757: #endif
                   3758:        } else {
                   3759:                r = SSH_ERR_INVALID_FORMAT;
                   3760:                goto out;
                   3761:        }
                   3762:        r = 0;
                   3763:        *keyp = prv;
                   3764:        prv = NULL;
                   3765:  out:
                   3766:        BIO_free(bio);
                   3767:        if (pk != NULL)
                   3768:                EVP_PKEY_free(pk);
                   3769:        if (prv != NULL)
                   3770:                sshkey_free(prv);
                   3771:        return r;
                   3772: }
                   3773: #endif /* WITH_OPENSSL */
                   3774:
                   3775: int
                   3776: sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
                   3777:     const char *passphrase, struct sshkey **keyp, char **commentp)
                   3778: {
                   3779:        int r;
                   3780:
                   3781:        *keyp = NULL;
                   3782:        if (commentp != NULL)
                   3783:                *commentp = NULL;
                   3784:
                   3785:        switch (type) {
1.9       markus   3786: #ifdef WITH_SSH1
1.1       djm      3787:        case KEY_RSA1:
                   3788:                return sshkey_parse_private_rsa1(blob, passphrase,
                   3789:                    keyp, commentp);
1.9       markus   3790: #endif /* WITH_SSH1 */
                   3791: #ifdef WITH_OPENSSL
1.1       djm      3792:        case KEY_DSA:
                   3793:        case KEY_ECDSA:
                   3794:        case KEY_RSA:
1.8       djm      3795:                return sshkey_parse_private_pem_fileblob(blob, type,
                   3796:                    passphrase, keyp);
1.1       djm      3797: #endif /* WITH_OPENSSL */
                   3798:        case KEY_ED25519:
                   3799:                return sshkey_parse_private2(blob, type, passphrase,
                   3800:                    keyp, commentp);
                   3801:        case KEY_UNSPEC:
                   3802:                if ((r = sshkey_parse_private2(blob, type, passphrase, keyp,
                   3803:                    commentp)) == 0)
                   3804:                        return 0;
                   3805: #ifdef WITH_OPENSSL
1.8       djm      3806:                return sshkey_parse_private_pem_fileblob(blob, type,
                   3807:                    passphrase, keyp);
1.1       djm      3808: #else
                   3809:                return SSH_ERR_INVALID_FORMAT;
                   3810: #endif /* WITH_OPENSSL */
                   3811:        default:
                   3812:                return SSH_ERR_KEY_TYPE_UNKNOWN;
                   3813:        }
                   3814: }
                   3815:
                   3816: int
                   3817: sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
                   3818:     const char *filename, struct sshkey **keyp, char **commentp)
                   3819: {
                   3820:        int r;
                   3821:
                   3822:        if (keyp != NULL)
                   3823:                *keyp = NULL;
                   3824:        if (commentp != NULL)
                   3825:                *commentp = NULL;
                   3826:
                   3827: #ifdef WITH_SSH1
                   3828:        /* it's a SSH v1 key if the public key part is readable */
                   3829:        if ((r = sshkey_parse_public_rsa1_fileblob(buffer, NULL, NULL)) == 0) {
                   3830:                return sshkey_parse_private_fileblob_type(buffer, KEY_RSA1,
                   3831:                    passphrase, keyp, commentp);
                   3832:        }
                   3833: #endif /* WITH_SSH1 */
1.2       markus   3834:        if ((r = sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
                   3835:            passphrase, keyp, commentp)) == 0)
                   3836:                return 0;
1.1       djm      3837:        return r;
                   3838: }