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

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