1 /* $OpenBSD: authfile.c,v 1.103 2014/02/02 03:44:31 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for reading and writing identity files, and
7 * for reading the passphrase from the user.
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".
16 * Copyright (c) 2000, 2013 Markus Friedl. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
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.
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.
41 #include <sys/types.h>
43 #include <sys/param.h>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/pem.h>
50 /* compatibility with old or broken OpenSSL versions */
51 #include "openbsd-compat/openssl-compat.h"
53 #include "crypto_api.h"
79 /* openssh private key file format */
80 #define MARK_BEGIN "-----BEGIN OPENSSH PRIVATE KEY-----\n"
81 #define MARK_END "-----END OPENSSH PRIVATE KEY-----\n"
82 #define KDFNAME "bcrypt"
83 #define AUTH_MAGIC "openssh-key-v1"
85 #define DEFAULT_CIPHERNAME "aes256-cbc"
86 #define DEFAULT_ROUNDS 16
88 #define MAX_KEY_FILE_SIZE (1024 * 1024)
90 /* Version identification string for SSH v1 identity files. */
91 static const char authfile_id_string[] =
92 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
95 key_private_to_blob2(Key *prv, Buffer *blob, const char *passphrase,
96 const char *comment, const char *ciphername, int rounds)
98 u_char *key, *cp, salt[SALT_LEN];
99 size_t keylen, ivlen, blocksize, authlen;
103 Buffer encoded, b, kdf;
105 const char *kdfname = KDFNAME;
108 rounds = DEFAULT_ROUNDS;
109 if (passphrase == NULL || !strlen(passphrase)) {
112 } else if (ciphername == NULL)
113 ciphername = DEFAULT_CIPHERNAME;
114 else if (cipher_number(ciphername) != SSH_CIPHER_SSH2)
115 fatal("invalid cipher");
117 if ((c = cipher_by_name(ciphername)) == NULL)
118 fatal("unknown cipher name");
120 blocksize = cipher_blocksize(c);
121 keylen = cipher_keylen(c);
122 ivlen = cipher_ivlen(c);
123 authlen = cipher_authlen(c);
124 key = xcalloc(1, keylen + ivlen);
125 if (strcmp(kdfname, "none") != 0) {
126 arc4random_buf(salt, SALT_LEN);
127 if (bcrypt_pbkdf(passphrase, strlen(passphrase),
128 salt, SALT_LEN, key, keylen + ivlen, rounds) < 0)
129 fatal("bcrypt_pbkdf failed");
130 buffer_put_string(&kdf, salt, SALT_LEN);
131 buffer_put_int(&kdf, rounds);
133 cipher_init(&ctx, c, key, keylen, key + keylen , ivlen, 1);
134 explicit_bzero(key, keylen + ivlen);
137 buffer_init(&encoded);
138 buffer_append(&encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC));
139 buffer_put_cstring(&encoded, ciphername);
140 buffer_put_cstring(&encoded, kdfname);
141 buffer_put_string(&encoded, buffer_ptr(&kdf), buffer_len(&kdf));
142 buffer_put_int(&encoded, 1); /* number of keys */
143 key_to_blob(prv, &cp, &len); /* public key */
144 buffer_put_string(&encoded, cp, len);
146 explicit_bzero(cp, len);
151 /* set up the buffer that will be encrypted */
154 /* Random check bytes */
155 check = arc4random();
156 buffer_put_int(&b, check);
157 buffer_put_int(&b, check);
159 /* append private key and comment*/
160 key_private_serialize(prv, &b);
161 buffer_put_cstring(&b, comment);
165 while (buffer_len(&b) % blocksize)
166 buffer_put_char(&b, ++i & 0xff);
169 buffer_put_int(&encoded, buffer_len(&b));
172 cp = buffer_append_space(&encoded, buffer_len(&b) + authlen);
173 if (cipher_crypt(&ctx, 0, cp, buffer_ptr(&b), buffer_len(&b), 0,
175 fatal("%s: cipher_crypt failed", __func__);
177 cipher_cleanup(&ctx);
180 len = 2 * buffer_len(&encoded);
182 n = uuencode(buffer_ptr(&encoded), buffer_len(&encoded),
185 fatal("%s: uuencode", __func__);
188 buffer_append(blob, MARK_BEGIN, sizeof(MARK_BEGIN) - 1);
189 for (i = 0; i < n; i++) {
190 buffer_put_char(blob, cp[i]);
192 buffer_put_char(blob, '\n');
195 buffer_put_char(blob, '\n');
196 buffer_append(blob, MARK_END, sizeof(MARK_END) - 1);
199 return buffer_len(blob);
203 key_parse_private2(Buffer *blob, int type, const char *passphrase,
206 u_char *key = NULL, *cp, *salt = NULL, pad, last;
207 char *comment = NULL, *ciphername = NULL, *kdfname = NULL, *kdfp;
208 u_int keylen = 0, ivlen, blocksize, slen, klen, len, rounds, nkeys;
209 u_int check1, check2, m1len, m2len;
212 Buffer b, encoded, copy, kdf;
219 buffer_init(&encoded);
223 m1len = sizeof(MARK_BEGIN) - 1;
224 m2len = sizeof(MARK_END) - 1;
225 cp = buffer_ptr(blob);
226 len = buffer_len(blob);
227 if (len < m1len || memcmp(cp, MARK_BEGIN, m1len)) {
228 debug("%s: missing begin marker", __func__);
234 if (*cp != '\n' && *cp != '\r')
235 buffer_put_char(&encoded, *cp);
240 if (len >= m2len && !memcmp(cp, MARK_END, m2len)) {
241 buffer_put_char(&encoded, '\0');
247 debug("%s: no end marker", __func__);
250 len = buffer_len(&encoded);
251 if ((cp = buffer_append_space(©, len)) == NULL) {
252 error("%s: buffer_append_space", __func__);
255 if ((dlen = uudecode(buffer_ptr(&encoded), cp, len)) < 0) {
256 error("%s: uudecode failed", __func__);
259 if ((u_int)dlen > len) {
260 error("%s: crazy uudecode length %d > %u", __func__, dlen, len);
263 buffer_consume_end(©, len - dlen);
264 if (buffer_len(©) < sizeof(AUTH_MAGIC) ||
265 memcmp(buffer_ptr(©), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
266 error("%s: bad magic", __func__);
269 buffer_consume(©, sizeof(AUTH_MAGIC));
271 ciphername = buffer_get_cstring_ret(©, NULL);
272 if (ciphername == NULL ||
273 (c = cipher_by_name(ciphername)) == NULL) {
274 error("%s: unknown cipher name", __func__);
277 if ((passphrase == NULL || !strlen(passphrase)) &&
278 strcmp(ciphername, "none") != 0) {
279 /* passphrase required */
282 kdfname = buffer_get_cstring_ret(©, NULL);
283 if (kdfname == NULL ||
284 (!strcmp(kdfname, "none") && !strcmp(kdfname, "bcrypt"))) {
285 error("%s: unknown kdf name", __func__);
288 if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
289 error("%s: cipher %s requires kdf", __func__, ciphername);
293 kdfp = buffer_get_string_ptr_ret(©, &klen);
295 error("%s: kdf options not set", __func__);
299 if ((cp = buffer_append_space(&kdf, klen)) == NULL) {
300 error("%s: kdf alloc failed", __func__);
303 memcpy(cp, kdfp, klen);
306 if (buffer_get_int_ret(&nkeys, ©) < 0) {
307 error("%s: key counter missing", __func__);
311 error("%s: only one key supported", __func__);
315 if ((cp = buffer_get_string_ret(©, &len)) == NULL) {
316 error("%s: pubkey not found", __func__);
319 free(cp); /* XXX check pubkey against decrypted private key */
321 /* size of encrypted key blob */
322 len = buffer_get_int(©);
323 blocksize = cipher_blocksize(c);
324 authlen = cipher_authlen(c);
325 if (len < blocksize) {
326 error("%s: encrypted data too small", __func__);
329 if (len % blocksize) {
330 error("%s: length not multiple of blocksize", __func__);
335 keylen = cipher_keylen(c);
336 ivlen = cipher_ivlen(c);
337 key = xcalloc(1, keylen + ivlen);
338 if (!strcmp(kdfname, "bcrypt")) {
339 if ((salt = buffer_get_string_ret(&kdf, &slen)) == NULL) {
340 error("%s: salt not set", __func__);
343 if (buffer_get_int_ret(&rounds, &kdf) < 0) {
344 error("%s: rounds not set", __func__);
347 if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
348 key, keylen + ivlen, rounds) < 0) {
349 error("%s: bcrypt_pbkdf failed", __func__);
354 cp = buffer_append_space(&b, len);
355 cipher_init(&ctx, c, key, keylen, key + keylen, ivlen, 0);
356 ret = cipher_crypt(&ctx, 0, cp, buffer_ptr(©), len, 0, authlen);
357 cipher_cleanup(&ctx);
358 buffer_consume(©, len);
360 /* fail silently on decryption errors */
362 debug("%s: decrypt failed", __func__);
366 if (buffer_len(©) != 0) {
367 error("%s: key blob has trailing data (len = %u)", __func__,
373 if (buffer_get_int_ret(&check1, &b) < 0 ||
374 buffer_get_int_ret(&check2, &b) < 0) {
375 error("check bytes missing");
378 if (check1 != check2) {
379 debug("%s: decrypt failed: 0x%08x != 0x%08x", __func__,
384 k = key_private_deserialize(&b);
387 comment = buffer_get_cstring_ret(&b, NULL);
390 while (buffer_len(&b)) {
391 if (buffer_get_char_ret(&pad, &b) == -1 ||
392 pad != (++i & 0xff)) {
393 error("%s: bad padding", __func__);
405 /* XXX decode pubkey and check against private */
412 explicit_bzero(key, keylen + ivlen);
414 buffer_free(&encoded);
422 * Serialises the authentication (private) key to a blob, encrypting it with
423 * passphrase. The identification of the blob (lowest 64 bits of n) will
424 * precede the key to provide identification of the key without needing a
428 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
431 Buffer buffer, encrypted;
432 u_char buf[100], *cp;
434 CipherContext ciphercontext;
435 const Cipher *cipher;
439 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
440 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
442 cipher_num = (strcmp(passphrase, "") == 0) ?
443 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
444 if ((cipher = cipher_by_number(cipher_num)) == NULL)
445 fatal("save_private_key_rsa: bad cipher");
447 /* This buffer is used to built the secret part of the private key. */
448 buffer_init(&buffer);
450 /* Put checkbytes for checking passphrase validity. */
453 buf[1] = (rnd >> 8) & 0xff;
456 buffer_append(&buffer, buf, 4);
459 * Store the private key (n and e will not be stored because they
460 * will be stored in plain text, and storing them also in encrypted
461 * format would just give known plaintext).
463 buffer_put_bignum(&buffer, key->rsa->d);
464 buffer_put_bignum(&buffer, key->rsa->iqmp);
465 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
466 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
468 /* Pad the part to be encrypted until its size is a multiple of 8. */
469 while (buffer_len(&buffer) % 8 != 0)
470 buffer_put_char(&buffer, 0);
472 /* This buffer will be used to contain the data in the file. */
473 buffer_init(&encrypted);
475 /* First store keyfile id string. */
476 for (i = 0; authfile_id_string[i]; i++)
477 buffer_put_char(&encrypted, authfile_id_string[i]);
478 buffer_put_char(&encrypted, 0);
480 /* Store cipher type. */
481 buffer_put_char(&encrypted, cipher_num);
482 buffer_put_int(&encrypted, 0); /* For future extension */
484 /* Store public key. This will be in plain text. */
485 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
486 buffer_put_bignum(&encrypted, key->rsa->n);
487 buffer_put_bignum(&encrypted, key->rsa->e);
488 buffer_put_cstring(&encrypted, comment);
490 /* Allocate space for the private part of the key in the buffer. */
491 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
493 cipher_set_key_string(&ciphercontext, cipher, passphrase,
495 if (cipher_crypt(&ciphercontext, 0, cp,
496 buffer_ptr(&buffer), buffer_len(&buffer), 0, 0) != 0)
497 fatal("%s: cipher_crypt failed", __func__);
498 cipher_cleanup(&ciphercontext);
499 explicit_bzero(&ciphercontext, sizeof(ciphercontext));
501 /* Destroy temporary data. */
502 explicit_bzero(buf, sizeof(buf));
503 buffer_free(&buffer);
505 buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
506 buffer_free(&encrypted);
511 /* convert SSH v2 key in OpenSSL PEM format */
513 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
517 int blen, len = strlen(_passphrase);
518 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
519 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
520 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
522 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
527 if (len > 0 && len <= 4) {
528 error("passphrase too short: have %d bytes, need > 4", len);
531 if ((bio = BIO_new(BIO_s_mem())) == NULL) {
532 error("%s: BIO_new failed", __func__);
537 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
538 cipher, passphrase, len, NULL, NULL);
540 #ifdef OPENSSL_HAS_ECC
542 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
543 cipher, passphrase, len, NULL, NULL);
547 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
548 cipher, passphrase, len, NULL, NULL);
552 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
555 buffer_append(blob, bptr, blen);
561 /* Save a key blob to a file */
563 key_save_private_blob(Buffer *keybuf, const char *filename)
567 if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
568 error("open %s failed: %s.", filename, strerror(errno));
571 if (atomicio(vwrite, fd, buffer_ptr(keybuf),
572 buffer_len(keybuf)) != buffer_len(keybuf)) {
573 error("write to key file %s failed: %s", filename,
583 /* Serialise "key" to buffer "blob" */
585 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
586 const char *comment, int force_new_format, const char *new_format_cipher,
587 int new_format_rounds)
591 return key_private_rsa1_to_blob(key, blob, passphrase, comment);
595 if (force_new_format) {
596 return key_private_to_blob2(key, blob, passphrase,
597 comment, new_format_cipher, new_format_rounds);
599 return key_private_pem_to_blob(key, blob, passphrase, comment);
601 return key_private_to_blob2(key, blob, passphrase,
602 comment, new_format_cipher, new_format_rounds);
604 error("%s: cannot save key type %d", __func__, key->type);
610 key_save_private(Key *key, const char *filename, const char *passphrase,
611 const char *comment, int force_new_format, const char *new_format_cipher,
612 int new_format_rounds)
617 buffer_init(&keyblob);
618 if (!key_private_to_blob(key, &keyblob, passphrase, comment,
619 force_new_format, new_format_cipher, new_format_rounds))
621 if (!key_save_private_blob(&keyblob, filename))
625 buffer_free(&keyblob);
630 * Parse the public, unencrypted portion of a RSA1 key.
633 key_parse_public_rsa1(Buffer *blob, char **commentp)
638 /* Check that it is at least big enough to contain the ID string. */
639 if (buffer_len(blob) < sizeof(authfile_id_string)) {
640 debug3("Truncated RSA1 identifier");
645 * Make sure it begins with the id string. Consume the id string
648 if (memcmp(buffer_ptr(blob), authfile_id_string,
649 sizeof(authfile_id_string)) != 0) {
650 debug3("Incorrect RSA1 identifier");
654 buffer_append(©, buffer_ptr(blob), buffer_len(blob));
655 buffer_consume(©, sizeof(authfile_id_string));
657 /* Skip cipher type and reserved data. */
658 (void) buffer_get_char(©); /* cipher type */
659 (void) buffer_get_int(©); /* reserved */
661 /* Read the public key from the buffer. */
662 (void) buffer_get_int(©);
663 pub = key_new(KEY_RSA1);
664 buffer_get_bignum(©, pub->rsa->n);
665 buffer_get_bignum(©, pub->rsa->e);
667 *commentp = buffer_get_string(©, NULL);
668 /* The encrypted private part is not parsed by this function. */
674 /* Load a key from a fd into a buffer */
676 key_load_file(int fd, const char *filename, Buffer *blob)
682 if (fstat(fd, &st) < 0) {
683 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
684 filename == NULL ? "" : filename,
685 filename == NULL ? "" : " ",
689 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
690 st.st_size > MAX_KEY_FILE_SIZE) {
692 error("%s: key file %.200s%stoo large", __func__,
693 filename == NULL ? "" : filename,
694 filename == NULL ? "" : " ");
699 if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
702 debug("%s: read from key file %.200s%sfailed: %.100s",
703 __func__, filename == NULL ? "" : filename,
704 filename == NULL ? "" : " ", strerror(errno));
706 explicit_bzero(buf, sizeof(buf));
709 buffer_append(blob, buf, len);
710 if (buffer_len(blob) > MAX_KEY_FILE_SIZE) {
712 explicit_bzero(buf, sizeof(buf));
716 explicit_bzero(buf, sizeof(buf));
717 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
718 st.st_size != buffer_len(blob)) {
719 debug("%s: key file %.200s%schanged size while reading",
720 __func__, filename == NULL ? "" : filename,
721 filename == NULL ? "" : " ");
730 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
731 * encountered (the file does not exist or is not readable), and the key
735 key_load_public_rsa1(int fd, const char *filename, char **commentp)
740 buffer_init(&buffer);
741 if (!key_load_file(fd, filename, &buffer)) {
742 buffer_free(&buffer);
746 pub = key_parse_public_rsa1(&buffer, commentp);
748 debug3("Could not load \"%s\" as a RSA1 public key", filename);
749 buffer_free(&buffer);
753 /* load public key from private-key file, works only for SSH v1 */
755 key_load_public_type(int type, const char *filename, char **commentp)
760 if (type == KEY_RSA1) {
761 fd = open(filename, O_RDONLY);
764 pub = key_load_public_rsa1(fd, filename, commentp);
772 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
774 int check1, check2, cipher_type;
777 CipherContext ciphercontext;
778 const Cipher *cipher;
782 /* Check that it is at least big enough to contain the ID string. */
783 if (buffer_len(blob) < sizeof(authfile_id_string)) {
784 debug3("Truncated RSA1 identifier");
789 * Make sure it begins with the id string. Consume the id string
792 if (memcmp(buffer_ptr(blob), authfile_id_string,
793 sizeof(authfile_id_string)) != 0) {
794 debug3("Incorrect RSA1 identifier");
798 buffer_append(©, buffer_ptr(blob), buffer_len(blob));
799 buffer_consume(©, sizeof(authfile_id_string));
801 /* Read cipher type. */
802 cipher_type = buffer_get_char(©);
803 (void) buffer_get_int(©); /* Reserved data. */
805 /* Read the public key from the buffer. */
806 (void) buffer_get_int(©);
807 prv = key_new_private(KEY_RSA1);
809 buffer_get_bignum(©, prv->rsa->n);
810 buffer_get_bignum(©, prv->rsa->e);
812 *commentp = buffer_get_string(©, NULL);
814 (void)buffer_get_string_ptr(©, NULL);
816 /* Check that it is a supported cipher. */
817 cipher = cipher_by_number(cipher_type);
818 if (cipher == NULL) {
819 debug("Unsupported RSA1 cipher %d", cipher_type);
823 /* Initialize space for decrypted data. */
824 buffer_init(&decrypted);
825 cp = buffer_append_space(&decrypted, buffer_len(©));
827 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
828 cipher_set_key_string(&ciphercontext, cipher, passphrase,
830 if (cipher_crypt(&ciphercontext, 0, cp,
831 buffer_ptr(©), buffer_len(©), 0, 0) != 0)
832 fatal("%s: cipher_crypt failed", __func__);
833 cipher_cleanup(&ciphercontext);
834 explicit_bzero(&ciphercontext, sizeof(ciphercontext));
837 check1 = buffer_get_char(&decrypted);
838 check2 = buffer_get_char(&decrypted);
839 if (check1 != buffer_get_char(&decrypted) ||
840 check2 != buffer_get_char(&decrypted)) {
841 if (strcmp(passphrase, "") != 0)
842 debug("Bad passphrase supplied for RSA1 key");
843 /* Bad passphrase. */
844 buffer_free(&decrypted);
847 /* Read the rest of the private key. */
848 buffer_get_bignum(&decrypted, prv->rsa->d);
849 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
850 /* in SSL and SSH v1 p and q are exchanged */
851 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
852 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
854 /* calculate p-1 and q-1 */
855 rsa_generate_additional_parameters(prv->rsa);
857 buffer_free(&decrypted);
859 /* enable blinding */
860 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
861 error("%s: RSA_blinding_on failed", __func__);
867 if (commentp != NULL)
874 key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
879 char *name = "<no key>";
882 if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
883 buffer_len(blob))) == NULL) {
884 error("%s: BIO_new_mem_buf failed", __func__);
888 pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
891 debug("%s: PEM_read_PrivateKey failed", __func__);
892 (void)ERR_get_error();
893 } else if (pk->type == EVP_PKEY_RSA &&
894 (type == KEY_UNSPEC||type==KEY_RSA)) {
895 prv = key_new(KEY_UNSPEC);
896 prv->rsa = EVP_PKEY_get1_RSA(pk);
898 name = "rsa w/o comment";
900 RSA_print_fp(stderr, prv->rsa, 8);
902 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
903 error("%s: RSA_blinding_on failed", __func__);
907 } else if (pk->type == EVP_PKEY_DSA &&
908 (type == KEY_UNSPEC||type==KEY_DSA)) {
909 prv = key_new(KEY_UNSPEC);
910 prv->dsa = EVP_PKEY_get1_DSA(pk);
912 name = "dsa w/o comment";
914 DSA_print_fp(stderr, prv->dsa, 8);
916 #ifdef OPENSSL_HAS_ECC
917 } else if (pk->type == EVP_PKEY_EC &&
918 (type == KEY_UNSPEC||type==KEY_ECDSA)) {
919 prv = key_new(KEY_UNSPEC);
920 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
921 prv->type = KEY_ECDSA;
922 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
923 key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
924 key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
925 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
926 key_ec_validate_private(prv->ecdsa) != 0) {
927 error("%s: bad ECDSA key", __func__);
931 name = "ecdsa w/o comment";
933 if (prv != NULL && prv->ecdsa != NULL)
934 key_dump_ec_key(prv->ecdsa);
936 #endif /* OPENSSL_HAS_ECC */
938 error("%s: PEM_read_PrivateKey: mismatch or "
939 "unknown EVP_PKEY save_type %d", __func__, pk->save_type);
943 if (prv != NULL && commentp)
944 *commentp = xstrdup(name);
945 debug("read PEM private key done: type %s",
946 prv ? key_type(prv) : "<unknown>");
951 key_load_private_pem(int fd, int type, const char *passphrase,
957 buffer_init(&buffer);
958 if (!key_load_file(fd, NULL, &buffer)) {
959 buffer_free(&buffer);
962 prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
963 buffer_free(&buffer);
968 key_perm_ok(int fd, const char *filename)
972 if (fstat(fd, &st) < 0)
975 * if a key owned by the user is accessed, then we check the
976 * permissions of the file. if the key owned by a different user,
977 * then we don't care.
980 if (check_ntsec(filename))
982 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
983 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
984 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
985 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
986 error("Permissions 0%3.3o for '%s' are too open.",
987 (u_int)st.st_mode & 0777, filename);
988 error("It is required that your private key files are NOT accessible by others.");
989 error("This private key will be ignored.");
996 key_parse_private_type(Buffer *blob, int type, const char *passphrase,
1003 return key_parse_private_rsa1(blob, passphrase, commentp);
1007 return key_parse_private_pem(blob, type, passphrase, commentp);
1009 return key_parse_private2(blob, type, passphrase, commentp);
1011 if ((k = key_parse_private2(blob, type, passphrase, commentp)))
1013 return key_parse_private_pem(blob, type, passphrase, commentp);
1015 error("%s: cannot parse key type %d", __func__, type);
1022 key_load_private_type(int type, const char *filename, const char *passphrase,
1023 char **commentp, int *perm_ok)
1029 fd = open(filename, O_RDONLY);
1031 debug("could not open key file '%s': %s", filename,
1033 if (perm_ok != NULL)
1037 if (!key_perm_ok(fd, filename)) {
1038 if (perm_ok != NULL)
1040 error("bad permissions: ignore key: %s", filename);
1044 if (perm_ok != NULL)
1047 buffer_init(&buffer);
1048 if (!key_load_file(fd, filename, &buffer)) {
1049 buffer_free(&buffer);
1054 ret = key_parse_private_type(&buffer, type, passphrase, commentp);
1055 buffer_free(&buffer);
1060 key_parse_private(Buffer *buffer, const char *filename,
1061 const char *passphrase, char **commentp)
1065 /* it's a SSH v1 key if the public key part is readable */
1066 pub = key_parse_public_rsa1(buffer, commentp);
1068 prv = key_parse_private_type(buffer, KEY_UNSPEC,
1070 /* use the filename as a comment for PEM */
1071 if (commentp && prv)
1072 *commentp = xstrdup(filename);
1075 /* key_parse_public_rsa1() has already loaded the comment */
1076 prv = key_parse_private_type(buffer, KEY_RSA1, passphrase,
1083 key_load_private(const char *filename, const char *passphrase,
1090 fd = open(filename, O_RDONLY);
1092 debug("could not open key file '%s': %s", filename,
1096 if (!key_perm_ok(fd, filename)) {
1097 error("bad permissions: ignore key: %s", filename);
1102 buffer_init(&buffer);
1103 if (!key_load_file(fd, filename, &buffer)) {
1104 buffer_free(&buffer);
1110 prv = key_parse_private(&buffer, filename, passphrase, commentp);
1111 buffer_free(&buffer);
1116 key_try_load_public(Key *k, const char *filename, char **commentp)
1119 char line[SSH_MAX_PUBKEY_BYTES];
1123 f = fopen(filename, "r");
1125 while (read_keyfile_line(f, filename, line, sizeof(line),
1134 /* Abort loading if this looks like a private key */
1135 if (strncmp(cp, "-----BEGIN", 10) == 0)
1137 /* Skip leading whitespace. */
1138 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
1141 if (key_read(k, &cp) == 1) {
1142 cp[strcspn(cp, "\r\n")] = '\0';
1144 *commentp = xstrdup(*cp ?
1157 /* load public key from ssh v1 private or any pubkey file */
1159 key_load_public(const char *filename, char **commentp)
1162 char file[MAXPATHLEN];
1164 /* try rsa1 private key */
1165 pub = key_load_public_type(KEY_RSA1, filename, commentp);
1169 /* try rsa1 public key */
1170 pub = key_new(KEY_RSA1);
1171 if (key_try_load_public(pub, filename, commentp) == 1)
1175 /* try ssh2 public key */
1176 pub = key_new(KEY_UNSPEC);
1177 if (key_try_load_public(pub, filename, commentp) == 1)
1179 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
1180 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
1181 (key_try_load_public(pub, file, commentp) == 1))
1187 /* Load the certificate associated with the named private key */
1189 key_load_cert(const char *filename)
1194 pub = key_new(KEY_UNSPEC);
1195 xasprintf(&file, "%s-cert.pub", filename);
1196 if (key_try_load_public(pub, file, NULL) == 1) {
1205 /* Load private key and certificate */
1207 key_load_private_cert(int type, const char *filename, const char *passphrase,
1219 error("%s: unsupported key type", __func__);
1223 if ((key = key_load_private_type(type, filename,
1224 passphrase, NULL, perm_ok)) == NULL)
1227 if ((pub = key_load_cert(filename)) == NULL) {
1232 /* Make sure the private key matches the certificate */
1233 if (key_equal_public(key, pub) == 0) {
1234 error("%s: certificate does not match private key %s",
1235 __func__, filename);
1236 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
1237 error("%s: key_to_certified failed", __func__);
1239 key_cert_copy(pub, key);
1250 * Returns 1 if the specified "key" is listed in the file "filename",
1251 * 0 if the key is not listed or -1 on error.
1252 * If strict_type is set then the key type must match exactly,
1253 * otherwise a comparison that ignores certficiate data is performed.
1256 key_in_file(Key *key, const char *filename, int strict_type)
1259 char line[SSH_MAX_PUBKEY_BYTES];
1264 int (*key_compare)(const Key *, const Key *) = strict_type ?
1265 key_equal : key_equal_public;
1267 if ((f = fopen(filename, "r")) == NULL) {
1268 if (errno == ENOENT) {
1269 debug("%s: keyfile \"%s\" missing", __func__, filename);
1272 error("%s: could not open keyfile \"%s\": %s", __func__,
1273 filename, strerror(errno));
1278 while (read_keyfile_line(f, filename, line, sizeof(line),
1282 /* Skip leading whitespace. */
1283 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
1286 /* Skip comments and empty lines */
1294 pub = key_new(KEY_UNSPEC);
1295 if (key_read(pub, &cp) != 1) {
1299 if (key_compare(key, pub)) {