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

Annotation of src/usr.bin/ssh/authfile.c, Revision 1.100

1.100   ! markus      1: /* $OpenBSD: authfile.c,v 1.99 2013/12/06 13:34:54 markus Exp $ */
1.1       deraadt     2: /*
1.9       deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * This file contains functions for reading and writing identity files, and
                      7:  * for reading the passphrase from the user.
1.14      markus      8:  *
1.19      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
                     14:  *
                     15:  *
1.99      markus     16:  * Copyright (c) 2000, 2013 Markus Friedl.  All rights reserved.
1.19      deraadt    17:  *
                     18:  * Redistribution and use in source and binary forms, with or without
                     19:  * modification, are permitted provided that the following conditions
                     20:  * are met:
                     21:  * 1. Redistributions of source code must retain the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer.
                     23:  * 2. Redistributions in binary form must reproduce the above copyright
                     24:  *    notice, this list of conditions and the following disclaimer in the
                     25:  *    documentation and/or other materials provided with the distribution.
                     26:  *
                     27:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     28:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     29:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     30:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     31:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     32:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     33:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     34:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     35:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     36:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.9       deraadt    37:  */
1.1       deraadt    38:
1.62      stevesk    39:
                     40: #include <sys/types.h>
                     41: #include <sys/stat.h>
1.72      stevesk    42: #include <sys/param.h>
1.76      deraadt    43: #include <sys/uio.h>
1.1       deraadt    44:
1.21      markus     45: #include <openssl/err.h>
1.25      markus     46: #include <openssl/evp.h>
1.15      markus     47: #include <openssl/pem.h>
1.68      stevesk    48:
1.100   ! markus     49: #include "crypto_api.h"
        !            50:
1.69      stevesk    51: #include <errno.h>
1.68      stevesk    52: #include <fcntl.h>
1.74      stevesk    53: #include <stdio.h>
1.73      stevesk    54: #include <stdlib.h>
1.71      stevesk    55: #include <string.h>
1.70      stevesk    56: #include <unistd.h>
1.15      markus     57:
1.99      markus     58: #include <util.h>
                     59:
1.76      deraadt    60: #include "xmalloc.h"
1.25      markus     61: #include "cipher.h"
1.1       deraadt    62: #include "buffer.h"
1.25      markus     63: #include "key.h"
1.1       deraadt    64: #include "ssh.h"
1.25      markus     65: #include "log.h"
1.27      itojun     66: #include "authfile.h"
1.44      markus     67: #include "rsa.h"
1.60      dtucker    68: #include "misc.h"
1.61      djm        69: #include "atomicio.h"
1.99      markus     70: #include "uuencode.h"
                     71:
                     72: /* openssh private key file format */
                     73: #define MARK_BEGIN             "-----BEGIN OPENSSH PRIVATE KEY-----\n"
                     74: #define MARK_END               "-----END OPENSSH PRIVATE KEY-----\n"
                     75: #define KDFNAME                        "bcrypt"
                     76: #define AUTH_MAGIC             "openssh-key-v1"
                     77: #define SALT_LEN               16
                     78: #define DEFAULT_CIPHERNAME     "aes256-cbc"
                     79: #define        DEFAULT_ROUNDS          16
1.1       deraadt    80:
1.88      djm        81: #define MAX_KEY_FILE_SIZE      (1024 * 1024)
                     82:
1.29      markus     83: /* Version identification string for SSH v1 identity files. */
1.26      stevesk    84: static const char authfile_id_string[] =
                     85:     "SSH PRIVATE KEY FILE FORMAT 1.1\n";
1.1       deraadt    86:
1.99      markus     87: static int
                     88: key_private_to_blob2(Key *prv, Buffer *blob, const char *passphrase,
                     89:     const char *comment, const char *ciphername, int rounds)
                     90: {
                     91:        u_char *key, *cp, salt[SALT_LEN];
                     92:        size_t keylen, ivlen, blocksize, authlen;
                     93:        u_int len, check;
                     94:        int i, n;
                     95:        const Cipher *c;
                     96:        Buffer encoded, b, kdf;
                     97:        CipherContext ctx;
                     98:        const char *kdfname = KDFNAME;
                     99:
                    100:        if (rounds <= 0)
                    101:                rounds = DEFAULT_ROUNDS;
                    102:        if (passphrase == NULL || !strlen(passphrase)) {
                    103:                ciphername = "none";
                    104:                kdfname = "none";
                    105:        } else if (ciphername == NULL)
                    106:                ciphername = DEFAULT_CIPHERNAME;
                    107:        else if (cipher_number(ciphername) != SSH_CIPHER_SSH2)
                    108:                fatal("invalid cipher");
                    109:
                    110:        if ((c = cipher_by_name(ciphername)) == NULL)
                    111:                fatal("unknown cipher name");
                    112:        buffer_init(&kdf);
                    113:        blocksize = cipher_blocksize(c);
                    114:        keylen = cipher_keylen(c);
                    115:        ivlen = cipher_ivlen(c);
                    116:        authlen = cipher_authlen(c);
                    117:        key = xcalloc(1, keylen + ivlen);
                    118:        if (strcmp(kdfname, "none") != 0) {
                    119:                arc4random_buf(salt, SALT_LEN);
                    120:                if (bcrypt_pbkdf(passphrase, strlen(passphrase),
                    121:                    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0)
                    122:                        fatal("bcrypt_pbkdf failed");
                    123:                buffer_put_string(&kdf, salt, SALT_LEN);
                    124:                buffer_put_int(&kdf, rounds);
                    125:        }
                    126:        cipher_init(&ctx, c, key, keylen, key + keylen , ivlen, 1);
                    127:        memset(key, 0, keylen + ivlen);
                    128:        free(key);
                    129:
                    130:        buffer_init(&encoded);
                    131:        buffer_append(&encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC));
                    132:        buffer_put_cstring(&encoded, ciphername);
                    133:        buffer_put_cstring(&encoded, kdfname);
                    134:        buffer_put_string(&encoded, buffer_ptr(&kdf), buffer_len(&kdf));
                    135:        buffer_put_int(&encoded, 1);                    /* number of keys */
                    136:        key_to_blob(prv, &cp, &len);                    /* public key */
                    137:        buffer_put_string(&encoded, cp, len);
                    138:
                    139:        memset(cp, 0, len);
                    140:        free(cp);
                    141:
                    142:        buffer_free(&kdf);
                    143:
                    144:        /* set up the buffer that will be encrypted */
                    145:        buffer_init(&b);
                    146:
                    147:        /* Random check bytes */
                    148:        check = arc4random();
                    149:        buffer_put_int(&b, check);
                    150:        buffer_put_int(&b, check);
                    151:
                    152:        /* append private key and comment*/
                    153:        key_private_serialize(prv, &b);
                    154:        buffer_put_cstring(&b, comment);
                    155:
                    156:        /* padding */
                    157:        i = 0;
                    158:        while (buffer_len(&b) % blocksize)
                    159:                buffer_put_char(&b, ++i & 0xff);
                    160:
                    161:        /* length */
                    162:        buffer_put_int(&encoded, buffer_len(&b));
                    163:
                    164:        /* encrypt */
                    165:        cp = buffer_append_space(&encoded, buffer_len(&b) + authlen);
                    166:        if (cipher_crypt(&ctx, 0, cp, buffer_ptr(&b), buffer_len(&b), 0,
                    167:            authlen) != 0)
                    168:                fatal("%s: cipher_crypt failed", __func__);
                    169:        buffer_free(&b);
                    170:        cipher_cleanup(&ctx);
                    171:
                    172:        /* uuencode */
                    173:        len = 2 * buffer_len(&encoded);
                    174:        cp = xmalloc(len);
                    175:        n = uuencode(buffer_ptr(&encoded), buffer_len(&encoded),
                    176:            (char *)cp, len);
                    177:        if (n < 0)
                    178:                fatal("%s: uuencode", __func__);
                    179:
                    180:        buffer_clear(blob);
                    181:        buffer_append(blob, MARK_BEGIN, sizeof(MARK_BEGIN) - 1);
                    182:        for (i = 0; i < n; i++) {
                    183:                buffer_put_char(blob, cp[i]);
                    184:                if (i % 70 == 69)
                    185:                        buffer_put_char(blob, '\n');
                    186:        }
                    187:        if (i % 70 != 69)
                    188:                buffer_put_char(blob, '\n');
                    189:        buffer_append(blob, MARK_END, sizeof(MARK_END) - 1);
                    190:        free(cp);
                    191:
                    192:        return buffer_len(blob);
                    193: }
                    194:
                    195: static Key *
                    196: key_parse_private2(Buffer *blob, int type, const char *passphrase,
                    197:     char **commentp)
                    198: {
                    199:        u_char *key = NULL, *cp, *salt = NULL, pad, last;
                    200:        char *comment = NULL, *ciphername = NULL, *kdfname = NULL, *kdfp;
                    201:        u_int keylen = 0, ivlen, blocksize, slen, klen, len, rounds, nkeys;
                    202:        u_int check1, check2, m1len, m2len;
                    203:        size_t authlen;
                    204:        const Cipher *c;
                    205:        Buffer b, encoded, copy, kdf;
                    206:        CipherContext ctx;
                    207:        Key *k = NULL;
                    208:        int dlen, ret, i;
                    209:
                    210:        buffer_init(&b);
                    211:        buffer_init(&kdf);
                    212:        buffer_init(&encoded);
                    213:        buffer_init(&copy);
                    214:
                    215:        /* uudecode */
                    216:        m1len = sizeof(MARK_BEGIN) - 1;
                    217:        m2len = sizeof(MARK_END) - 1;
                    218:        cp = buffer_ptr(blob);
                    219:        len = buffer_len(blob);
                    220:        if (len < m1len || memcmp(cp, MARK_BEGIN, m1len)) {
                    221:                debug("%s: missing begin marker", __func__);
                    222:                goto out;
                    223:        }
                    224:        cp += m1len;
                    225:        len -= m1len;
                    226:        while (len) {
                    227:                if (*cp != '\n' && *cp != '\r')
                    228:                        buffer_put_char(&encoded, *cp);
                    229:                last = *cp;
                    230:                len--;
                    231:                cp++;
                    232:                if (last == '\n') {
                    233:                        if (len >= m2len && !memcmp(cp, MARK_END, m2len)) {
                    234:                                buffer_put_char(&encoded, '\0');
                    235:                                break;
                    236:                        }
                    237:                }
                    238:        }
                    239:        if (!len) {
                    240:                debug("%s: no end marker", __func__);
                    241:                goto out;
                    242:        }
                    243:        len = buffer_len(&encoded);
                    244:        if ((cp = buffer_append_space(&copy, len)) == NULL) {
                    245:                error("%s: buffer_append_space", __func__);
                    246:                goto out;
                    247:        }
                    248:        if ((dlen = uudecode(buffer_ptr(&encoded), cp, len)) < 0) {
                    249:                error("%s: uudecode failed", __func__);
                    250:                goto out;
                    251:        }
                    252:        if ((u_int)dlen > len) {
                    253:                error("%s: crazy uudecode length %d > %u", __func__, dlen, len);
                    254:                goto out;
                    255:        }
                    256:        buffer_consume_end(&copy, len - dlen);
                    257:        if (buffer_len(&copy) < sizeof(AUTH_MAGIC) ||
                    258:            memcmp(buffer_ptr(&copy), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
                    259:                error("%s: bad magic", __func__);
                    260:                goto out;
                    261:        }
                    262:        buffer_consume(&copy, sizeof(AUTH_MAGIC));
                    263:
                    264:        ciphername = buffer_get_cstring_ret(&copy, NULL);
                    265:        if (ciphername == NULL ||
                    266:            (c = cipher_by_name(ciphername)) == NULL) {
                    267:                error("%s: unknown cipher name", __func__);
                    268:                goto out;
                    269:        }
                    270:        if ((passphrase == NULL || !strlen(passphrase)) &&
                    271:            strcmp(ciphername, "none") != 0) {
                    272:                /* passphrase required */
                    273:                goto out;
                    274:        }
                    275:        kdfname = buffer_get_cstring_ret(&copy, NULL);
                    276:        if (kdfname == NULL ||
                    277:            (!strcmp(kdfname, "none") && !strcmp(kdfname, "bcrypt"))) {
                    278:                error("%s: unknown kdf name", __func__);
                    279:                goto out;
                    280:        }
                    281:        if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
                    282:                error("%s: cipher %s requires kdf", __func__, ciphername);
                    283:                goto out;
                    284:        }
                    285:        /* kdf options */
                    286:        kdfp = buffer_get_string_ptr_ret(&copy, &klen);
                    287:        if (kdfp == NULL) {
                    288:                error("%s: kdf options not set", __func__);
                    289:                goto out;
                    290:        }
                    291:        if (klen > 0) {
                    292:                if ((cp = buffer_append_space(&kdf, klen)) == NULL) {
                    293:                        error("%s: kdf alloc failed", __func__);
                    294:                        goto out;
                    295:                }
                    296:                memcpy(cp, kdfp, klen);
                    297:        }
                    298:        /* number of keys */
                    299:        if (buffer_get_int_ret(&nkeys, &copy) < 0) {
                    300:                error("%s: key counter missing", __func__);
                    301:                goto out;
                    302:        }
                    303:        if (nkeys != 1) {
                    304:                error("%s: only one key supported", __func__);
                    305:                goto out;
                    306:        }
                    307:        /* pubkey */
                    308:        if ((cp = buffer_get_string_ret(&copy, &len)) == NULL) {
                    309:                error("%s: pubkey not found", __func__);
                    310:                goto out;
                    311:        }
                    312:        free(cp); /* XXX check pubkey against decrypted private key */
                    313:
                    314:        /* size of encrypted key blob */
                    315:        len = buffer_get_int(&copy);
                    316:        blocksize = cipher_blocksize(c);
                    317:        authlen = cipher_authlen(c);
                    318:        if (len < blocksize) {
                    319:                error("%s: encrypted data too small", __func__);
                    320:                goto out;
                    321:        }
                    322:        if (len % blocksize) {
                    323:                error("%s: length not multiple of blocksize", __func__);
                    324:                goto out;
                    325:        }
                    326:
                    327:        /* setup key */
                    328:        keylen = cipher_keylen(c);
                    329:        ivlen = cipher_ivlen(c);
                    330:        key = xcalloc(1, keylen + ivlen);
                    331:        if (!strcmp(kdfname, "bcrypt")) {
                    332:                if ((salt = buffer_get_string_ret(&kdf, &slen)) == NULL) {
                    333:                        error("%s: salt not set", __func__);
                    334:                        goto out;
                    335:                }
                    336:                if (buffer_get_int_ret(&rounds, &kdf) < 0) {
                    337:                        error("%s: rounds not set", __func__);
                    338:                        goto out;
                    339:                }
                    340:                if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
                    341:                    key, keylen + ivlen, rounds) < 0) {
                    342:                        error("%s: bcrypt_pbkdf failed", __func__);
                    343:                        goto out;
                    344:                }
                    345:        }
                    346:
                    347:        cp = buffer_append_space(&b, len);
                    348:        cipher_init(&ctx, c, key, keylen, key + keylen, ivlen, 0);
                    349:        ret = cipher_crypt(&ctx, 0, cp, buffer_ptr(&copy), len, 0, authlen);
                    350:        cipher_cleanup(&ctx);
                    351:        buffer_consume(&copy, len);
                    352:
                    353:        /* fail silently on decryption errors */
                    354:        if (ret != 0) {
                    355:                debug("%s: decrypt failed", __func__);
                    356:                goto out;
                    357:        }
                    358:
                    359:        if (buffer_len(&copy) != 0) {
                    360:                error("%s: key blob has trailing data (len = %u)", __func__,
                    361:                    buffer_len(&copy));
                    362:                goto out;
                    363:        }
                    364:
                    365:        /* check bytes */
                    366:        if (buffer_get_int_ret(&check1, &b) < 0 ||
                    367:            buffer_get_int_ret(&check2, &b) < 0) {
                    368:                error("check bytes missing");
                    369:                goto out;
                    370:        }
                    371:        if (check1 != check2) {
                    372:                debug("%s: decrypt failed: 0x%08x != 0x%08x", __func__,
                    373:                    check1, check2);
                    374:                goto out;
                    375:        }
                    376:
                    377:        k = key_private_deserialize(&b);
                    378:
                    379:        /* comment */
                    380:        comment = buffer_get_cstring_ret(&b, NULL);
                    381:
                    382:        i = 0;
                    383:        while (buffer_len(&b)) {
                    384:                if (buffer_get_char_ret(&pad, &b) == -1 ||
                    385:                    pad != (++i & 0xff)) {
                    386:                        error("%s: bad padding", __func__);
                    387:                        key_free(k);
                    388:                        k = NULL;
                    389:                        goto out;
                    390:                }
                    391:        }
                    392:
                    393:        if (k && commentp) {
                    394:                *commentp = comment;
                    395:                comment = NULL;
                    396:        }
                    397:
                    398:        /* XXX decode pubkey and check against private */
                    399:  out:
                    400:        free(ciphername);
                    401:        free(kdfname);
                    402:        free(salt);
                    403:        free(comment);
                    404:        if (key)
                    405:                memset(key, 0, keylen + ivlen);
                    406:        free(key);
                    407:        buffer_free(&encoded);
                    408:        buffer_free(&copy);
                    409:        buffer_free(&kdf);
                    410:        buffer_free(&b);
                    411:        return k;
                    412: }
                    413:
1.10      markus    414: /*
1.86      djm       415:  * Serialises the authentication (private) key to a blob, encrypting it with
                    416:  * passphrase.  The identification of the blob (lowest 64 bits of n) will
1.10      markus    417:  * precede the key to provide identification of the key without needing a
                    418:  * passphrase.
                    419:  */
1.37      itojun    420: static int
1.86      djm       421: key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
1.29      markus    422:     const char *comment)
1.1       deraadt   423: {
1.8       markus    424:        Buffer buffer, encrypted;
1.45      stevesk   425:        u_char buf[100], *cp;
1.86      djm       426:        int i, cipher_num;
1.20      markus    427:        CipherContext ciphercontext;
1.96      djm       428:        const Cipher *cipher;
1.57      avsm      429:        u_int32_t rnd;
1.8       markus    430:
1.10      markus    431:        /*
                    432:         * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
                    433:         * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
                    434:         */
1.46      markus    435:        cipher_num = (strcmp(passphrase, "") == 0) ?
                    436:            SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
                    437:        if ((cipher = cipher_by_number(cipher_num)) == NULL)
1.20      markus    438:                fatal("save_private_key_rsa: bad cipher");
1.8       markus    439:
                    440:        /* This buffer is used to built the secret part of the private key. */
                    441:        buffer_init(&buffer);
                    442:
                    443:        /* Put checkbytes for checking passphrase validity. */
1.57      avsm      444:        rnd = arc4random();
                    445:        buf[0] = rnd & 0xff;
                    446:        buf[1] = (rnd >> 8) & 0xff;
1.8       markus    447:        buf[2] = buf[0];
                    448:        buf[3] = buf[1];
                    449:        buffer_append(&buffer, buf, 4);
                    450:
1.10      markus    451:        /*
                    452:         * Store the private key (n and e will not be stored because they
                    453:         * will be stored in plain text, and storing them also in encrypted
                    454:         * format would just give known plaintext).
                    455:         */
1.29      markus    456:        buffer_put_bignum(&buffer, key->rsa->d);
                    457:        buffer_put_bignum(&buffer, key->rsa->iqmp);
                    458:        buffer_put_bignum(&buffer, key->rsa->q);        /* reverse from SSL p */
                    459:        buffer_put_bignum(&buffer, key->rsa->p);        /* reverse from SSL q */
1.8       markus    460:
                    461:        /* Pad the part to be encrypted until its size is a multiple of 8. */
                    462:        while (buffer_len(&buffer) % 8 != 0)
                    463:                buffer_put_char(&buffer, 0);
                    464:
                    465:        /* This buffer will be used to contain the data in the file. */
                    466:        buffer_init(&encrypted);
                    467:
                    468:        /* First store keyfile id string. */
1.26      stevesk   469:        for (i = 0; authfile_id_string[i]; i++)
                    470:                buffer_put_char(&encrypted, authfile_id_string[i]);
1.8       markus    471:        buffer_put_char(&encrypted, 0);
                    472:
                    473:        /* Store cipher type. */
1.46      markus    474:        buffer_put_char(&encrypted, cipher_num);
1.8       markus    475:        buffer_put_int(&encrypted, 0);  /* For future extension */
                    476:
                    477:        /* Store public key.  This will be in plain text. */
1.29      markus    478:        buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
                    479:        buffer_put_bignum(&encrypted, key->rsa->n);
                    480:        buffer_put_bignum(&encrypted, key->rsa->e);
1.36      markus    481:        buffer_put_cstring(&encrypted, comment);
1.8       markus    482:
                    483:        /* Allocate space for the private part of the key in the buffer. */
1.42      stevesk   484:        cp = buffer_append_space(&encrypted, buffer_len(&buffer));
1.8       markus    485:
1.46      markus    486:        cipher_set_key_string(&ciphercontext, cipher, passphrase,
                    487:            CIPHER_ENCRYPT);
1.99      markus    488:        if (cipher_crypt(&ciphercontext, 0, cp,
                    489:            buffer_ptr(&buffer), buffer_len(&buffer), 0, 0) != 0)
                    490:                fatal("%s: cipher_crypt failed", __func__);
1.46      markus    491:        cipher_cleanup(&ciphercontext);
1.20      markus    492:        memset(&ciphercontext, 0, sizeof(ciphercontext));
1.8       markus    493:
                    494:        /* Destroy temporary data. */
                    495:        memset(buf, 0, sizeof(buf));
                    496:        buffer_free(&buffer);
                    497:
1.86      djm       498:        buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
1.8       markus    499:        buffer_free(&encrypted);
1.86      djm       500:
1.8       markus    501:        return 1;
1.1       deraadt   502: }
                    503:
1.86      djm       504: /* convert SSH v2 key in OpenSSL PEM format */
1.37      itojun    505: static int
1.86      djm       506: key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
1.29      markus    507:     const char *comment)
1.15      markus    508: {
1.21      markus    509:        int success = 0;
1.86      djm       510:        int blen, len = strlen(_passphrase);
1.47      markus    511:        u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
1.77      djm       512:        const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
1.86      djm       513:        const u_char *bptr;
                    514:        BIO *bio;
1.15      markus    515:
                    516:        if (len > 0 && len <= 4) {
1.31      markus    517:                error("passphrase too short: have %d bytes, need > 4", len);
1.15      markus    518:                return 0;
                    519:        }
1.86      djm       520:        if ((bio = BIO_new(BIO_s_mem())) == NULL) {
                    521:                error("%s: BIO_new failed", __func__);
1.15      markus    522:                return 0;
                    523:        }
1.21      markus    524:        switch (key->type) {
1.30      markus    525:        case KEY_DSA:
1.86      djm       526:                success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
1.30      markus    527:                    cipher, passphrase, len, NULL, NULL);
                    528:                break;
1.83      djm       529:        case KEY_ECDSA:
1.86      djm       530:                success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
1.83      djm       531:                    cipher, passphrase, len, NULL, NULL);
                    532:                break;
1.30      markus    533:        case KEY_RSA:
1.86      djm       534:                success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
1.30      markus    535:                    cipher, passphrase, len, NULL, NULL);
                    536:                break;
1.15      markus    537:        }
1.86      djm       538:        if (success) {
                    539:                if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
                    540:                        success = 0;
                    541:                else
                    542:                        buffer_append(blob, bptr, blen);
                    543:        }
                    544:        BIO_free(bio);
1.15      markus    545:        return success;
                    546: }
                    547:
1.86      djm       548: /* Save a key blob to a file */
                    549: static int
                    550: key_save_private_blob(Buffer *keybuf, const char *filename)
                    551: {
                    552:        int fd;
                    553:
                    554:        if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
                    555:                error("open %s failed: %s.", filename, strerror(errno));
                    556:                return 0;
                    557:        }
                    558:        if (atomicio(vwrite, fd, buffer_ptr(keybuf),
                    559:            buffer_len(keybuf)) != buffer_len(keybuf)) {
                    560:                error("write to key file %s failed: %s", filename,
                    561:                    strerror(errno));
                    562:                close(fd);
                    563:                unlink(filename);
                    564:                return 0;
                    565:        }
                    566:        close(fd);
                    567:        return 1;
                    568: }
                    569:
                    570: /* Serialise "key" to buffer "blob" */
                    571: static int
                    572: key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
1.99      markus    573:     const char *comment, int force_new_format, const char *new_format_cipher,
                    574:     int new_format_rounds)
1.15      markus    575: {
                    576:        switch (key->type) {
1.21      markus    577:        case KEY_RSA1:
1.86      djm       578:                return key_private_rsa1_to_blob(key, blob, passphrase, comment);
1.15      markus    579:        case KEY_DSA:
1.83      djm       580:        case KEY_ECDSA:
1.21      markus    581:        case KEY_RSA:
1.99      markus    582:                if (force_new_format) {
                    583:                        return key_private_to_blob2(key, blob, passphrase,
                    584:                            comment, new_format_cipher, new_format_rounds);
                    585:                }
1.86      djm       586:                return key_private_pem_to_blob(key, blob, passphrase, comment);
1.100   ! markus    587:        case KEY_ED25519:
        !           588:                return key_private_to_blob2(key, blob, passphrase,
        !           589:                    comment, new_format_cipher, new_format_rounds);
1.15      markus    590:        default:
1.86      djm       591:                error("%s: cannot save key type %d", __func__, key->type);
                    592:                return 0;
1.15      markus    593:        }
1.86      djm       594: }
                    595:
                    596: int
                    597: key_save_private(Key *key, const char *filename, const char *passphrase,
1.99      markus    598:     const char *comment, int force_new_format, const char *new_format_cipher,
                    599:     int new_format_rounds)
1.86      djm       600: {
                    601:        Buffer keyblob;
                    602:        int success = 0;
                    603:
                    604:        buffer_init(&keyblob);
1.99      markus    605:        if (!key_private_to_blob(key, &keyblob, passphrase, comment,
                    606:            force_new_format, new_format_cipher, new_format_rounds))
1.86      djm       607:                goto out;
                    608:        if (!key_save_private_blob(&keyblob, filename))
                    609:                goto out;
                    610:        success = 1;
                    611:  out:
                    612:        buffer_free(&keyblob);
                    613:        return success;
1.15      markus    614: }
                    615:
1.10      markus    616: /*
1.86      djm       617:  * Parse the public, unencrypted portion of a RSA1 key.
1.10      markus    618:  */
1.37      itojun    619: static Key *
1.86      djm       620: key_parse_public_rsa1(Buffer *blob, char **commentp)
1.1       deraadt   621: {
1.29      markus    622:        Key *pub;
1.92      markus    623:        Buffer copy;
1.86      djm       624:
                    625:        /* Check that it is at least big enough to contain the ID string. */
                    626:        if (buffer_len(blob) < sizeof(authfile_id_string)) {
                    627:                debug3("Truncated RSA1 identifier");
                    628:                return NULL;
                    629:        }
                    630:
                    631:        /*
                    632:         * Make sure it begins with the id string.  Consume the id string
                    633:         * from the buffer.
                    634:         */
                    635:        if (memcmp(buffer_ptr(blob), authfile_id_string,
                    636:            sizeof(authfile_id_string)) != 0) {
                    637:                debug3("Incorrect RSA1 identifier");
                    638:                return NULL;
                    639:        }
1.92      markus    640:        buffer_init(&copy);
                    641:        buffer_append(&copy, buffer_ptr(blob), buffer_len(blob));
                    642:        buffer_consume(&copy, sizeof(authfile_id_string));
1.86      djm       643:
                    644:        /* Skip cipher type and reserved data. */
1.92      markus    645:        (void) buffer_get_char(&copy);          /* cipher type */
                    646:        (void) buffer_get_int(&copy);           /* reserved */
1.86      djm       647:
                    648:        /* Read the public key from the buffer. */
1.92      markus    649:        (void) buffer_get_int(&copy);
1.86      djm       650:        pub = key_new(KEY_RSA1);
1.92      markus    651:        buffer_get_bignum(&copy, pub->rsa->n);
                    652:        buffer_get_bignum(&copy, pub->rsa->e);
1.86      djm       653:        if (commentp)
1.92      markus    654:                *commentp = buffer_get_string(&copy, NULL);
1.86      djm       655:        /* The encrypted private part is not parsed by this function. */
1.92      markus    656:        buffer_free(&copy);
1.86      djm       657:
                    658:        return pub;
                    659: }
                    660:
1.88      djm       661: /* Load a key from a fd into a buffer */
                    662: int
1.86      djm       663: key_load_file(int fd, const char *filename, Buffer *blob)
                    664: {
1.88      djm       665:        u_char buf[1024];
1.86      djm       666:        size_t len;
1.51      fgsch     667:        struct stat st;
1.8       markus    668:
1.51      fgsch     669:        if (fstat(fd, &st) < 0) {
1.86      djm       670:                error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
                    671:                    filename == NULL ? "" : filename,
                    672:                    filename == NULL ? "" : " ",
                    673:                    strerror(errno));
                    674:                return 0;
1.51      fgsch     675:        }
1.88      djm       676:        if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
                    677:            st.st_size > MAX_KEY_FILE_SIZE) {
                    678:  toobig:
1.86      djm       679:                error("%s: key file %.200s%stoo large", __func__,
                    680:                    filename == NULL ? "" : filename,
                    681:                    filename == NULL ? "" : " ");
                    682:                return 0;
1.58      djm       683:        }
1.93      markus    684:        buffer_clear(blob);
1.88      djm       685:        for (;;) {
                    686:                if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
                    687:                        if (errno == EPIPE)
                    688:                                break;
                    689:                        debug("%s: read from key file %.200s%sfailed: %.100s",
                    690:                            __func__, filename == NULL ? "" : filename,
                    691:                            filename == NULL ? "" : " ", strerror(errno));
                    692:                        buffer_clear(blob);
                    693:                        bzero(buf, sizeof(buf));
                    694:                        return 0;
                    695:                }
                    696:                buffer_append(blob, buf, len);
                    697:                if (buffer_len(blob) > MAX_KEY_FILE_SIZE) {
                    698:                        buffer_clear(blob);
                    699:                        bzero(buf, sizeof(buf));
                    700:                        goto toobig;
                    701:                }
                    702:        }
                    703:        bzero(buf, sizeof(buf));
                    704:        if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
                    705:            st.st_size != buffer_len(blob)) {
                    706:                debug("%s: key file %.200s%schanged size while reading",
                    707:                    __func__, filename == NULL ? "" : filename,
                    708:                    filename == NULL ? "" : " ");
1.86      djm       709:                buffer_clear(blob);
                    710:                return 0;
1.8       markus    711:        }
1.88      djm       712:
1.86      djm       713:        return 1;
                    714: }
1.8       markus    715:
1.86      djm       716: /*
                    717:  * Loads the public part of the ssh v1 key file.  Returns NULL if an error was
                    718:  * encountered (the file does not exist or is not readable), and the key
                    719:  * otherwise.
                    720:  */
                    721: static Key *
                    722: key_load_public_rsa1(int fd, const char *filename, char **commentp)
                    723: {
                    724:        Buffer buffer;
                    725:        Key *pub;
                    726:
                    727:        buffer_init(&buffer);
                    728:        if (!key_load_file(fd, filename, &buffer)) {
1.8       markus    729:                buffer_free(&buffer);
1.29      markus    730:                return NULL;
1.8       markus    731:        }
                    732:
1.86      djm       733:        pub = key_parse_public_rsa1(&buffer, commentp);
                    734:        if (pub == NULL)
                    735:                debug3("Could not load \"%s\" as a RSA1 public key", filename);
1.1       deraadt   736:        buffer_free(&buffer);
1.29      markus    737:        return pub;
1.1       deraadt   738: }
                    739:
1.29      markus    740: /* load public key from private-key file, works only for SSH v1 */
                    741: Key *
                    742: key_load_public_type(int type, const char *filename, char **commentp)
1.15      markus    743: {
1.29      markus    744:        Key *pub;
                    745:        int fd;
                    746:
                    747:        if (type == KEY_RSA1) {
                    748:                fd = open(filename, O_RDONLY);
                    749:                if (fd < 0)
                    750:                        return NULL;
                    751:                pub = key_load_public_rsa1(fd, filename, commentp);
                    752:                close(fd);
                    753:                return pub;
1.15      markus    754:        }
1.29      markus    755:        return NULL;
1.15      markus    756: }
                    757:
1.37      itojun    758: static Key *
1.86      djm       759: key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
1.1       deraadt   760: {
1.61      djm       761:        int check1, check2, cipher_type;
1.86      djm       762:        Buffer decrypted;
1.45      stevesk   763:        u_char *cp;
1.20      markus    764:        CipherContext ciphercontext;
1.96      djm       765:        const Cipher *cipher;
1.29      markus    766:        Key *prv = NULL;
1.92      markus    767:        Buffer copy;
1.8       markus    768:
1.86      djm       769:        /* Check that it is at least big enough to contain the ID string. */
                    770:        if (buffer_len(blob) < sizeof(authfile_id_string)) {
                    771:                debug3("Truncated RSA1 identifier");
1.51      fgsch     772:                return NULL;
                    773:        }
1.8       markus    774:
1.10      markus    775:        /*
                    776:         * Make sure it begins with the id string.  Consume the id string
                    777:         * from the buffer.
                    778:         */
1.86      djm       779:        if (memcmp(buffer_ptr(blob), authfile_id_string,
                    780:            sizeof(authfile_id_string)) != 0) {
                    781:                debug3("Incorrect RSA1 identifier");
                    782:                return NULL;
                    783:        }
1.92      markus    784:        buffer_init(&copy);
                    785:        buffer_append(&copy, buffer_ptr(blob), buffer_len(blob));
                    786:        buffer_consume(&copy, sizeof(authfile_id_string));
1.28      deraadt   787:
1.8       markus    788:        /* Read cipher type. */
1.92      markus    789:        cipher_type = buffer_get_char(&copy);
                    790:        (void) buffer_get_int(&copy);   /* Reserved data. */
1.8       markus    791:
                    792:        /* Read the public key from the buffer. */
1.92      markus    793:        (void) buffer_get_int(&copy);
1.29      markus    794:        prv = key_new_private(KEY_RSA1);
                    795:
1.92      markus    796:        buffer_get_bignum(&copy, prv->rsa->n);
                    797:        buffer_get_bignum(&copy, prv->rsa->e);
1.29      markus    798:        if (commentp)
1.92      markus    799:                *commentp = buffer_get_string(&copy, NULL);
1.8       markus    800:        else
1.92      markus    801:                (void)buffer_get_string_ptr(&copy, NULL);
1.8       markus    802:
                    803:        /* Check that it is a supported cipher. */
1.20      markus    804:        cipher = cipher_by_number(cipher_type);
                    805:        if (cipher == NULL) {
1.86      djm       806:                debug("Unsupported RSA1 cipher %d", cipher_type);
1.92      markus    807:                buffer_free(&copy);
1.8       markus    808:                goto fail;
                    809:        }
                    810:        /* Initialize space for decrypted data. */
                    811:        buffer_init(&decrypted);
1.92      markus    812:        cp = buffer_append_space(&decrypted, buffer_len(&copy));
1.8       markus    813:
                    814:        /* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
1.46      markus    815:        cipher_set_key_string(&ciphercontext, cipher, passphrase,
                    816:            CIPHER_DECRYPT);
1.99      markus    817:        if (cipher_crypt(&ciphercontext, 0, cp,
                    818:            buffer_ptr(&copy), buffer_len(&copy), 0, 0) != 0)
                    819:                fatal("%s: cipher_crypt failed", __func__);
1.46      markus    820:        cipher_cleanup(&ciphercontext);
1.20      markus    821:        memset(&ciphercontext, 0, sizeof(ciphercontext));
1.92      markus    822:        buffer_free(&copy);
1.1       deraadt   823:
1.8       markus    824:        check1 = buffer_get_char(&decrypted);
                    825:        check2 = buffer_get_char(&decrypted);
                    826:        if (check1 != buffer_get_char(&decrypted) ||
                    827:            check2 != buffer_get_char(&decrypted)) {
                    828:                if (strcmp(passphrase, "") != 0)
1.86      djm       829:                        debug("Bad passphrase supplied for RSA1 key");
1.8       markus    830:                /* Bad passphrase. */
                    831:                buffer_free(&decrypted);
1.29      markus    832:                goto fail;
1.8       markus    833:        }
                    834:        /* Read the rest of the private key. */
1.29      markus    835:        buffer_get_bignum(&decrypted, prv->rsa->d);
                    836:        buffer_get_bignum(&decrypted, prv->rsa->iqmp);          /* u */
                    837:        /* in SSL and SSH v1 p and q are exchanged */
                    838:        buffer_get_bignum(&decrypted, prv->rsa->q);             /* p */
                    839:        buffer_get_bignum(&decrypted, prv->rsa->p);             /* q */
1.8       markus    840:
1.29      markus    841:        /* calculate p-1 and q-1 */
1.43      markus    842:        rsa_generate_additional_parameters(prv->rsa);
1.8       markus    843:
                    844:        buffer_free(&decrypted);
1.52      markus    845:
                    846:        /* enable blinding */
                    847:        if (RSA_blinding_on(prv->rsa, NULL) != 1) {
1.86      djm       848:                error("%s: RSA_blinding_on failed", __func__);
1.52      markus    849:                goto fail;
                    850:        }
1.29      markus    851:        return prv;
                    852:
                    853: fail:
1.97      djm       854:        if (commentp != NULL)
                    855:                free(*commentp);
1.29      markus    856:        key_free(prv);
                    857:        return NULL;
1.15      markus    858: }
                    859:
1.86      djm       860: static Key *
                    861: key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
1.29      markus    862:     char **commentp)
1.15      markus    863: {
1.21      markus    864:        EVP_PKEY *pk = NULL;
1.29      markus    865:        Key *prv = NULL;
1.21      markus    866:        char *name = "<no key>";
1.86      djm       867:        BIO *bio;
1.15      markus    868:
1.86      djm       869:        if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
                    870:            buffer_len(blob))) == NULL) {
                    871:                error("%s: BIO_new_mem_buf failed", __func__);
1.29      markus    872:                return NULL;
1.15      markus    873:        }
1.86      djm       874:
                    875:        pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
                    876:        BIO_free(bio);
1.21      markus    877:        if (pk == NULL) {
1.86      djm       878:                debug("%s: PEM_read_PrivateKey failed", __func__);
1.21      markus    879:                (void)ERR_get_error();
1.29      markus    880:        } else if (pk->type == EVP_PKEY_RSA &&
1.41      deraadt   881:            (type == KEY_UNSPEC||type==KEY_RSA)) {
1.29      markus    882:                prv = key_new(KEY_UNSPEC);
                    883:                prv->rsa = EVP_PKEY_get1_RSA(pk);
                    884:                prv->type = KEY_RSA;
                    885:                name = "rsa w/o comment";
1.21      markus    886: #ifdef DEBUG_PK
1.29      markus    887:                RSA_print_fp(stderr, prv->rsa, 8);
1.21      markus    888: #endif
1.52      markus    889:                if (RSA_blinding_on(prv->rsa, NULL) != 1) {
1.86      djm       890:                        error("%s: RSA_blinding_on failed", __func__);
1.52      markus    891:                        key_free(prv);
                    892:                        prv = NULL;
                    893:                }
1.29      markus    894:        } else if (pk->type == EVP_PKEY_DSA &&
1.41      deraadt   895:            (type == KEY_UNSPEC||type==KEY_DSA)) {
1.29      markus    896:                prv = key_new(KEY_UNSPEC);
                    897:                prv->dsa = EVP_PKEY_get1_DSA(pk);
                    898:                prv->type = KEY_DSA;
                    899:                name = "dsa w/o comment";
1.21      markus    900: #ifdef DEBUG_PK
1.29      markus    901:                DSA_print_fp(stderr, prv->dsa, 8);
1.21      markus    902: #endif
1.83      djm       903:        } else if (pk->type == EVP_PKEY_EC &&
                    904:            (type == KEY_UNSPEC||type==KEY_ECDSA)) {
                    905:                prv = key_new(KEY_UNSPEC);
                    906:                prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
                    907:                prv->type = KEY_ECDSA;
1.85      djm       908:                if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
                    909:                    key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
                    910:                    key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
1.83      djm       911:                    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
                    912:                    key_ec_validate_private(prv->ecdsa) != 0) {
                    913:                        error("%s: bad ECDSA key", __func__);
                    914:                        key_free(prv);
                    915:                        prv = NULL;
                    916:                }
1.84      djm       917:                name = "ecdsa w/o comment";
1.83      djm       918: #ifdef DEBUG_PK
1.85      djm       919:                if (prv != NULL && prv->ecdsa != NULL)
1.83      djm       920:                        key_dump_ec_key(prv->ecdsa);
                    921: #endif
1.15      markus    922:        } else {
1.86      djm       923:                error("%s: PEM_read_PrivateKey: mismatch or "
                    924:                    "unknown EVP_PKEY save_type %d", __func__, pk->save_type);
1.15      markus    925:        }
1.21      markus    926:        if (pk != NULL)
                    927:                EVP_PKEY_free(pk);
1.29      markus    928:        if (prv != NULL && commentp)
                    929:                *commentp = xstrdup(name);
                    930:        debug("read PEM private key done: type %s",
                    931:            prv ? key_type(prv) : "<unknown>");
                    932:        return prv;
1.15      markus    933: }
                    934:
1.86      djm       935: Key *
                    936: key_load_private_pem(int fd, int type, const char *passphrase,
                    937:     char **commentp)
                    938: {
                    939:        Buffer buffer;
                    940:        Key *prv;
                    941:
                    942:        buffer_init(&buffer);
                    943:        if (!key_load_file(fd, NULL, &buffer)) {
                    944:                buffer_free(&buffer);
                    945:                return NULL;
                    946:        }
                    947:        prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
                    948:        buffer_free(&buffer);
                    949:        return prv;
                    950: }
                    951:
1.63      dtucker   952: int
1.29      markus    953: key_perm_ok(int fd, const char *filename)
1.15      markus    954: {
                    955:        struct stat st;
                    956:
1.38      markus    957:        if (fstat(fd, &st) < 0)
                    958:                return 0;
                    959:        /*
                    960:         * if a key owned by the user is accessed, then we check the
                    961:         * permissions of the file. if the key owned by a different user,
                    962:         * then we don't care.
                    963:         */
                    964:        if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
1.15      markus    965:                error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    966:                error("@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @");
                    967:                error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1.38      markus    968:                error("Permissions 0%3.3o for '%s' are too open.",
1.54      djm       969:                    (u_int)st.st_mode & 0777, filename);
1.15      markus    970:                error("It is recommended that your private key files are NOT accessible by others.");
1.29      markus    971:                error("This private key will be ignored.");
1.15      markus    972:                return 0;
                    973:        }
1.29      markus    974:        return 1;
                    975: }
                    976:
1.86      djm       977: static Key *
                    978: key_parse_private_type(Buffer *blob, int type, const char *passphrase,
                    979:     char **commentp)
                    980: {
1.99      markus    981:        Key *k;
                    982:
1.86      djm       983:        switch (type) {
                    984:        case KEY_RSA1:
                    985:                return key_parse_private_rsa1(blob, passphrase, commentp);
                    986:        case KEY_DSA:
                    987:        case KEY_ECDSA:
                    988:        case KEY_RSA:
1.100   ! markus    989:                return key_parse_private_pem(blob, type, passphrase, commentp);
        !           990:        case KEY_ED25519:
        !           991:                return key_parse_private2(blob, type, passphrase, commentp);
1.86      djm       992:        case KEY_UNSPEC:
1.99      markus    993:                if ((k = key_parse_private2(blob, type, passphrase, commentp)))
                    994:                        return k;
1.86      djm       995:                return key_parse_private_pem(blob, type, passphrase, commentp);
                    996:        default:
1.90      djm       997:                error("%s: cannot parse key type %d", __func__, type);
1.86      djm       998:                break;
                    999:        }
                   1000:        return NULL;
                   1001: }
                   1002:
1.29      markus   1003: Key *
                   1004: key_load_private_type(int type, const char *filename, const char *passphrase,
1.67      dtucker  1005:     char **commentp, int *perm_ok)
1.29      markus   1006: {
                   1007:        int fd;
1.86      djm      1008:        Key *ret;
                   1009:        Buffer buffer;
1.29      markus   1010:
                   1011:        fd = open(filename, O_RDONLY);
1.78      dtucker  1012:        if (fd < 0) {
                   1013:                debug("could not open key file '%s': %s", filename,
                   1014:                    strerror(errno));
                   1015:                if (perm_ok != NULL)
                   1016:                        *perm_ok = 0;
1.79      dtucker  1017:                return NULL;
1.78      dtucker  1018:        }
1.29      markus   1019:        if (!key_perm_ok(fd, filename)) {
1.67      dtucker  1020:                if (perm_ok != NULL)
                   1021:                        *perm_ok = 0;
1.31      markus   1022:                error("bad permissions: ignore key: %s", filename);
1.29      markus   1023:                close(fd);
                   1024:                return NULL;
                   1025:        }
1.67      dtucker  1026:        if (perm_ok != NULL)
                   1027:                *perm_ok = 1;
1.86      djm      1028:
                   1029:        buffer_init(&buffer);
                   1030:        if (!key_load_file(fd, filename, &buffer)) {
                   1031:                buffer_free(&buffer);
1.28      deraadt  1032:                close(fd);
1.86      djm      1033:                return NULL;
1.15      markus   1034:        }
1.86      djm      1035:        close(fd);
                   1036:        ret = key_parse_private_type(&buffer, type, passphrase, commentp);
                   1037:        buffer_free(&buffer);
                   1038:        return ret;
1.29      markus   1039: }
                   1040:
                   1041: Key *
1.88      djm      1042: key_parse_private(Buffer *buffer, const char *filename,
                   1043:     const char *passphrase, char **commentp)
                   1044: {
                   1045:        Key *pub, *prv;
                   1046:
                   1047:        /* it's a SSH v1 key if the public key part is readable */
1.92      markus   1048:        pub = key_parse_public_rsa1(buffer, commentp);
1.88      djm      1049:        if (pub == NULL) {
                   1050:                prv = key_parse_private_type(buffer, KEY_UNSPEC,
                   1051:                    passphrase, NULL);
                   1052:                /* use the filename as a comment for PEM */
                   1053:                if (commentp && prv)
                   1054:                        *commentp = xstrdup(filename);
                   1055:        } else {
                   1056:                key_free(pub);
                   1057:                /* key_parse_public_rsa1() has already loaded the comment */
                   1058:                prv = key_parse_private_type(buffer, KEY_RSA1, passphrase,
                   1059:                    NULL);
                   1060:        }
                   1061:        return prv;
                   1062: }
                   1063:
                   1064: Key *
1.29      markus   1065: key_load_private(const char *filename, const char *passphrase,
                   1066:     char **commentp)
                   1067: {
1.88      djm      1068:        Key *prv;
                   1069:        Buffer buffer;
1.29      markus   1070:        int fd;
                   1071:
                   1072:        fd = open(filename, O_RDONLY);
1.78      dtucker  1073:        if (fd < 0) {
                   1074:                debug("could not open key file '%s': %s", filename,
                   1075:                    strerror(errno));
1.29      markus   1076:                return NULL;
1.78      dtucker  1077:        }
1.29      markus   1078:        if (!key_perm_ok(fd, filename)) {
1.31      markus   1079:                error("bad permissions: ignore key: %s", filename);
1.29      markus   1080:                close(fd);
                   1081:                return NULL;
                   1082:        }
1.86      djm      1083:
                   1084:        buffer_init(&buffer);
                   1085:        if (!key_load_file(fd, filename, &buffer)) {
                   1086:                buffer_free(&buffer);
                   1087:                close(fd);
                   1088:                return NULL;
                   1089:        }
                   1090:        close(fd);
                   1091:
1.88      djm      1092:        prv = key_parse_private(&buffer, filename, passphrase, commentp);
1.86      djm      1093:        buffer_free(&buffer);
1.34      markus   1094:        return prv;
1.18      markus   1095: }
                   1096:
1.37      itojun   1097: static int
1.29      markus   1098: key_try_load_public(Key *k, const char *filename, char **commentp)
1.18      markus   1099: {
                   1100:        FILE *f;
1.59      dtucker  1101:        char line[SSH_MAX_PUBKEY_BYTES];
1.18      markus   1102:        char *cp;
1.60      dtucker  1103:        u_long linenum = 0;
1.18      markus   1104:
                   1105:        f = fopen(filename, "r");
                   1106:        if (f != NULL) {
1.59      dtucker  1107:                while (read_keyfile_line(f, filename, line, sizeof(line),
                   1108:                            &linenum) != -1) {
1.18      markus   1109:                        cp = line;
1.40      deraadt  1110:                        switch (*cp) {
1.18      markus   1111:                        case '#':
                   1112:                        case '\n':
                   1113:                        case '\0':
                   1114:                                continue;
                   1115:                        }
1.89      djm      1116:                        /* Abort loading if this looks like a private key */
                   1117:                        if (strncmp(cp, "-----BEGIN", 10) == 0)
                   1118:                                break;
1.18      markus   1119:                        /* Skip leading whitespace. */
                   1120:                        for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
                   1121:                                ;
                   1122:                        if (*cp) {
1.21      markus   1123:                                if (key_read(k, &cp) == 1) {
1.91      djm      1124:                                        cp[strcspn(cp, "\r\n")] = '\0';
                   1125:                                        if (commentp) {
                   1126:                                                *commentp = xstrdup(*cp ?
                   1127:                                                    cp : filename);
                   1128:                                        }
1.18      markus   1129:                                        fclose(f);
                   1130:                                        return 1;
                   1131:                                }
                   1132:                        }
                   1133:                }
                   1134:                fclose(f);
                   1135:        }
                   1136:        return 0;
                   1137: }
                   1138:
1.29      markus   1139: /* load public key from ssh v1 private or any pubkey file */
                   1140: Key *
                   1141: key_load_public(const char *filename, char **commentp)
1.18      markus   1142: {
1.29      markus   1143:        Key *pub;
                   1144:        char file[MAXPATHLEN];
1.18      markus   1145:
1.53      markus   1146:        /* try rsa1 private key */
1.29      markus   1147:        pub = key_load_public_type(KEY_RSA1, filename, commentp);
                   1148:        if (pub != NULL)
                   1149:                return pub;
1.53      markus   1150:
                   1151:        /* try rsa1 public key */
                   1152:        pub = key_new(KEY_RSA1);
                   1153:        if (key_try_load_public(pub, filename, commentp) == 1)
                   1154:                return pub;
                   1155:        key_free(pub);
                   1156:
                   1157:        /* try ssh2 public key */
1.29      markus   1158:        pub = key_new(KEY_UNSPEC);
                   1159:        if (key_try_load_public(pub, filename, commentp) == 1)
                   1160:                return pub;
                   1161:        if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
                   1162:            (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
                   1163:            (key_try_load_public(pub, file, commentp) == 1))
                   1164:                return pub;
1.81      djm      1165:        key_free(pub);
                   1166:        return NULL;
                   1167: }
                   1168:
                   1169: /* Load the certificate associated with the named private key */
                   1170: Key *
                   1171: key_load_cert(const char *filename)
                   1172: {
                   1173:        Key *pub;
1.82      djm      1174:        char *file;
1.81      djm      1175:
                   1176:        pub = key_new(KEY_UNSPEC);
1.82      djm      1177:        xasprintf(&file, "%s-cert.pub", filename);
                   1178:        if (key_try_load_public(pub, file, NULL) == 1) {
1.97      djm      1179:                free(file);
1.81      djm      1180:                return pub;
1.82      djm      1181:        }
1.97      djm      1182:        free(file);
1.81      djm      1183:        key_free(pub);
                   1184:        return NULL;
                   1185: }
                   1186:
                   1187: /* Load private key and certificate */
                   1188: Key *
                   1189: key_load_private_cert(int type, const char *filename, const char *passphrase,
                   1190:     int *perm_ok)
                   1191: {
                   1192:        Key *key, *pub;
                   1193:
                   1194:        switch (type) {
                   1195:        case KEY_RSA:
                   1196:        case KEY_DSA:
1.83      djm      1197:        case KEY_ECDSA:
1.81      djm      1198:                break;
                   1199:        default:
                   1200:                error("%s: unsupported key type", __func__);
                   1201:                return NULL;
                   1202:        }
                   1203:
                   1204:        if ((key = key_load_private_type(type, filename,
                   1205:            passphrase, NULL, perm_ok)) == NULL)
                   1206:                return NULL;
                   1207:
                   1208:        if ((pub = key_load_cert(filename)) == NULL) {
                   1209:                key_free(key);
                   1210:                return NULL;
                   1211:        }
                   1212:
                   1213:        /* Make sure the private key matches the certificate */
                   1214:        if (key_equal_public(key, pub) == 0) {
                   1215:                error("%s: certificate does not match private key %s",
                   1216:                    __func__, filename);
                   1217:        } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
                   1218:                error("%s: key_to_certified failed", __func__);
                   1219:        } else {
                   1220:                key_cert_copy(pub, key);
                   1221:                key_free(pub);
                   1222:                return key;
                   1223:        }
                   1224:
                   1225:        key_free(key);
1.29      markus   1226:        key_free(pub);
                   1227:        return NULL;
1.1       deraadt  1228: }
1.80      djm      1229:
                   1230: /*
                   1231:  * Returns 1 if the specified "key" is listed in the file "filename",
                   1232:  * 0 if the key is not listed or -1 on error.
                   1233:  * If strict_type is set then the key type must match exactly,
                   1234:  * otherwise a comparison that ignores certficiate data is performed.
                   1235:  */
                   1236: int
                   1237: key_in_file(Key *key, const char *filename, int strict_type)
                   1238: {
                   1239:        FILE *f;
                   1240:        char line[SSH_MAX_PUBKEY_BYTES];
                   1241:        char *cp;
                   1242:        u_long linenum = 0;
                   1243:        int ret = 0;
                   1244:        Key *pub;
                   1245:        int (*key_compare)(const Key *, const Key *) = strict_type ?
                   1246:            key_equal : key_equal_public;
                   1247:
                   1248:        if ((f = fopen(filename, "r")) == NULL) {
                   1249:                if (errno == ENOENT) {
                   1250:                        debug("%s: keyfile \"%s\" missing", __func__, filename);
                   1251:                        return 0;
                   1252:                } else {
                   1253:                        error("%s: could not open keyfile \"%s\": %s", __func__,
                   1254:                            filename, strerror(errno));
                   1255:                        return -1;
                   1256:                }
                   1257:        }
                   1258:
                   1259:        while (read_keyfile_line(f, filename, line, sizeof(line),
                   1260:                    &linenum) != -1) {
                   1261:                cp = line;
                   1262:
                   1263:                /* Skip leading whitespace. */
                   1264:                for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
                   1265:                        ;
                   1266:
                   1267:                /* Skip comments and empty lines */
                   1268:                switch (*cp) {
                   1269:                case '#':
                   1270:                case '\n':
                   1271:                case '\0':
                   1272:                        continue;
                   1273:                }
                   1274:
                   1275:                pub = key_new(KEY_UNSPEC);
                   1276:                if (key_read(pub, &cp) != 1) {
                   1277:                        key_free(pub);
                   1278:                        continue;
                   1279:                }
                   1280:                if (key_compare(key, pub)) {
                   1281:                        ret = 1;
                   1282:                        key_free(pub);
                   1283:                        break;
                   1284:                }
                   1285:                key_free(pub);
                   1286:        }
                   1287:        fclose(f);
                   1288:        return ret;
                   1289: }