1 /* $OpenBSD: authfile.c,v 1.87 2010/11/29 18:57:04 markus 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 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"
72 /* Version identification string for SSH v1 identity files. */
73 static const char authfile_id_string
[] =
74 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
77 * Serialises the authentication (private) key to a blob, encrypting it with
78 * passphrase. The identification of the blob (lowest 64 bits of n) will
79 * precede the key to provide identification of the key without needing a
83 key_private_rsa1_to_blob(Key
*key
, Buffer
*blob
, const char *passphrase
,
86 Buffer buffer
, encrypted
;
89 CipherContext ciphercontext
;
94 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
95 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
97 cipher_num
= (strcmp(passphrase
, "") == 0) ?
98 SSH_CIPHER_NONE
: SSH_AUTHFILE_CIPHER
;
99 if ((cipher
= cipher_by_number(cipher_num
)) == NULL
)
100 fatal("save_private_key_rsa: bad cipher");
102 /* This buffer is used to built the secret part of the private key. */
103 buffer_init(&buffer
);
105 /* Put checkbytes for checking passphrase validity. */
108 buf
[1] = (rnd
>> 8) & 0xff;
111 buffer_append(&buffer
, buf
, 4);
114 * Store the private key (n and e will not be stored because they
115 * will be stored in plain text, and storing them also in encrypted
116 * format would just give known plaintext).
118 buffer_put_bignum(&buffer
, key
->rsa
->d
);
119 buffer_put_bignum(&buffer
, key
->rsa
->iqmp
);
120 buffer_put_bignum(&buffer
, key
->rsa
->q
); /* reverse from SSL p */
121 buffer_put_bignum(&buffer
, key
->rsa
->p
); /* reverse from SSL q */
123 /* Pad the part to be encrypted until its size is a multiple of 8. */
124 while (buffer_len(&buffer
) % 8 != 0)
125 buffer_put_char(&buffer
, 0);
127 /* This buffer will be used to contain the data in the file. */
128 buffer_init(&encrypted
);
130 /* First store keyfile id string. */
131 for (i
= 0; authfile_id_string
[i
]; i
++)
132 buffer_put_char(&encrypted
, authfile_id_string
[i
]);
133 buffer_put_char(&encrypted
, 0);
135 /* Store cipher type. */
136 buffer_put_char(&encrypted
, cipher_num
);
137 buffer_put_int(&encrypted
, 0); /* For future extension */
139 /* Store public key. This will be in plain text. */
140 buffer_put_int(&encrypted
, BN_num_bits(key
->rsa
->n
));
141 buffer_put_bignum(&encrypted
, key
->rsa
->n
);
142 buffer_put_bignum(&encrypted
, key
->rsa
->e
);
143 buffer_put_cstring(&encrypted
, comment
);
145 /* Allocate space for the private part of the key in the buffer. */
146 cp
= buffer_append_space(&encrypted
, buffer_len(&buffer
));
148 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
150 cipher_crypt(&ciphercontext
, cp
,
151 buffer_ptr(&buffer
), buffer_len(&buffer
));
152 cipher_cleanup(&ciphercontext
);
153 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
155 /* Destroy temporary data. */
156 memset(buf
, 0, sizeof(buf
));
157 buffer_free(&buffer
);
159 buffer_append(blob
, buffer_ptr(&encrypted
), buffer_len(&encrypted
));
160 buffer_free(&encrypted
);
165 /* convert SSH v2 key in OpenSSL PEM format */
167 key_private_pem_to_blob(Key
*key
, Buffer
*blob
, const char *_passphrase
,
171 int blen
, len
= strlen(_passphrase
);
172 u_char
*passphrase
= (len
> 0) ? (u_char
*)_passphrase
: NULL
;
173 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
174 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_des_ede3_cbc() : NULL
;
176 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_aes_128_cbc() : NULL
;
181 if (len
> 0 && len
<= 4) {
182 error("passphrase too short: have %d bytes, need > 4", len
);
185 if ((bio
= BIO_new(BIO_s_mem())) == NULL
) {
186 error("%s: BIO_new failed", __func__
);
191 success
= PEM_write_bio_DSAPrivateKey(bio
, key
->dsa
,
192 cipher
, passphrase
, len
, NULL
, NULL
);
194 #ifdef OPENSSL_HAS_ECC
196 success
= PEM_write_bio_ECPrivateKey(bio
, key
->ecdsa
,
197 cipher
, passphrase
, len
, NULL
, NULL
);
201 success
= PEM_write_bio_RSAPrivateKey(bio
, key
->rsa
,
202 cipher
, passphrase
, len
, NULL
, NULL
);
206 if ((blen
= BIO_get_mem_data(bio
, &bptr
)) <= 0)
209 buffer_append(blob
, bptr
, blen
);
215 /* Save a key blob to a file */
217 key_save_private_blob(Buffer
*keybuf
, const char *filename
)
221 if ((fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600)) < 0) {
222 error("open %s failed: %s.", filename
, strerror(errno
));
225 if (atomicio(vwrite
, fd
, buffer_ptr(keybuf
),
226 buffer_len(keybuf
)) != buffer_len(keybuf
)) {
227 error("write to key file %s failed: %s", filename
,
237 /* Serialise "key" to buffer "blob" */
239 key_private_to_blob(Key
*key
, Buffer
*blob
, const char *passphrase
,
244 return key_private_rsa1_to_blob(key
, blob
, passphrase
, comment
);
248 return key_private_pem_to_blob(key
, blob
, passphrase
, comment
);
250 error("%s: cannot save key type %d", __func__
, key
->type
);
256 key_save_private(Key
*key
, const char *filename
, const char *passphrase
,
262 buffer_init(&keyblob
);
263 if (!key_private_to_blob(key
, &keyblob
, passphrase
, comment
))
265 if (!key_save_private_blob(&keyblob
, filename
))
269 buffer_free(&keyblob
);
274 * Parse the public, unencrypted portion of a RSA1 key.
277 key_parse_public_rsa1(Buffer
*blob
, char **commentp
)
281 /* Check that it is at least big enough to contain the ID string. */
282 if (buffer_len(blob
) < sizeof(authfile_id_string
)) {
283 debug3("Truncated RSA1 identifier");
288 * Make sure it begins with the id string. Consume the id string
291 if (memcmp(buffer_ptr(blob
), authfile_id_string
,
292 sizeof(authfile_id_string
)) != 0) {
293 debug3("Incorrect RSA1 identifier");
296 buffer_consume(blob
, sizeof(authfile_id_string
));
298 /* Skip cipher type and reserved data. */
299 (void) buffer_get_char(blob
); /* cipher type */
300 (void) buffer_get_int(blob
); /* reserved */
302 /* Read the public key from the buffer. */
303 (void) buffer_get_int(blob
);
304 pub
= key_new(KEY_RSA1
);
305 buffer_get_bignum(blob
, pub
->rsa
->n
);
306 buffer_get_bignum(blob
, pub
->rsa
->e
);
308 *commentp
= buffer_get_string(blob
, NULL
);
309 /* The encrypted private part is not parsed by this function. */
315 /* Load the contents of a key file into a buffer */
317 key_load_file(int fd
, const char *filename
, Buffer
*blob
)
323 if (fstat(fd
, &st
) < 0) {
324 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__
,
325 filename
== NULL
? "" : filename
,
326 filename
== NULL
? "" : " ",
331 if (st
.st_size
> 1*1024*1024) {
332 error("%s: key file %.200s%stoo large", __func__
,
333 filename
== NULL
? "" : filename
,
334 filename
== NULL
? "" : " ");
338 len
= (size_t)st
.st_size
; /* truncated */
341 cp
= buffer_append_space(blob
, len
);
343 if (atomicio(read
, fd
, cp
, len
) != len
) {
344 debug("%s: read from key file %.200s%sfailed: %.100s", __func__
,
345 filename
== NULL
? "" : filename
,
346 filename
== NULL
? "" : " ",
356 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
357 * encountered (the file does not exist or is not readable), and the key
361 key_load_public_rsa1(int fd
, const char *filename
, char **commentp
)
366 buffer_init(&buffer
);
367 if (!key_load_file(fd
, filename
, &buffer
)) {
368 buffer_free(&buffer
);
372 pub
= key_parse_public_rsa1(&buffer
, commentp
);
374 debug3("Could not load \"%s\" as a RSA1 public key", filename
);
375 buffer_free(&buffer
);
379 /* load public key from private-key file, works only for SSH v1 */
381 key_load_public_type(int type
, const char *filename
, char **commentp
)
386 if (type
== KEY_RSA1
) {
387 fd
= open(filename
, O_RDONLY
);
390 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
398 key_parse_private_rsa1(Buffer
*blob
, const char *passphrase
, char **commentp
)
400 int check1
, check2
, cipher_type
;
403 CipherContext ciphercontext
;
407 /* Check that it is at least big enough to contain the ID string. */
408 if (buffer_len(blob
) < sizeof(authfile_id_string
)) {
409 debug3("Truncated RSA1 identifier");
414 * Make sure it begins with the id string. Consume the id string
417 if (memcmp(buffer_ptr(blob
), authfile_id_string
,
418 sizeof(authfile_id_string
)) != 0) {
419 debug3("Incorrect RSA1 identifier");
422 buffer_consume(blob
, sizeof(authfile_id_string
));
424 /* Read cipher type. */
425 cipher_type
= buffer_get_char(blob
);
426 (void) buffer_get_int(blob
); /* Reserved data. */
428 /* Read the public key from the buffer. */
429 (void) buffer_get_int(blob
);
430 prv
= key_new_private(KEY_RSA1
);
432 buffer_get_bignum(blob
, prv
->rsa
->n
);
433 buffer_get_bignum(blob
, prv
->rsa
->e
);
435 *commentp
= buffer_get_string(blob
, NULL
);
437 (void)buffer_get_string_ptr(blob
, NULL
);
439 /* Check that it is a supported cipher. */
440 cipher
= cipher_by_number(cipher_type
);
441 if (cipher
== NULL
) {
442 debug("Unsupported RSA1 cipher %d", cipher_type
);
445 /* Initialize space for decrypted data. */
446 buffer_init(&decrypted
);
447 cp
= buffer_append_space(&decrypted
, buffer_len(blob
));
449 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
450 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
452 cipher_crypt(&ciphercontext
, cp
,
453 buffer_ptr(blob
), buffer_len(blob
));
454 cipher_cleanup(&ciphercontext
);
455 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
458 check1
= buffer_get_char(&decrypted
);
459 check2
= buffer_get_char(&decrypted
);
460 if (check1
!= buffer_get_char(&decrypted
) ||
461 check2
!= buffer_get_char(&decrypted
)) {
462 if (strcmp(passphrase
, "") != 0)
463 debug("Bad passphrase supplied for RSA1 key");
464 /* Bad passphrase. */
465 buffer_free(&decrypted
);
468 /* Read the rest of the private key. */
469 buffer_get_bignum(&decrypted
, prv
->rsa
->d
);
470 buffer_get_bignum(&decrypted
, prv
->rsa
->iqmp
); /* u */
471 /* in SSL and SSH v1 p and q are exchanged */
472 buffer_get_bignum(&decrypted
, prv
->rsa
->q
); /* p */
473 buffer_get_bignum(&decrypted
, prv
->rsa
->p
); /* q */
475 /* calculate p-1 and q-1 */
476 rsa_generate_additional_parameters(prv
->rsa
);
478 buffer_free(&decrypted
);
480 /* enable blinding */
481 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
482 error("%s: RSA_blinding_on failed", __func__
);
495 key_parse_private_pem(Buffer
*blob
, int type
, const char *passphrase
,
500 char *name
= "<no key>";
503 if ((bio
= BIO_new_mem_buf(buffer_ptr(blob
),
504 buffer_len(blob
))) == NULL
) {
505 error("%s: BIO_new_mem_buf failed", __func__
);
509 pk
= PEM_read_bio_PrivateKey(bio
, NULL
, NULL
, (char *)passphrase
);
512 debug("%s: PEM_read_PrivateKey failed", __func__
);
513 (void)ERR_get_error();
514 } else if (pk
->type
== EVP_PKEY_RSA
&&
515 (type
== KEY_UNSPEC
||type
==KEY_RSA
)) {
516 prv
= key_new(KEY_UNSPEC
);
517 prv
->rsa
= EVP_PKEY_get1_RSA(pk
);
519 name
= "rsa w/o comment";
521 RSA_print_fp(stderr
, prv
->rsa
, 8);
523 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
524 error("%s: RSA_blinding_on failed", __func__
);
528 } else if (pk
->type
== EVP_PKEY_DSA
&&
529 (type
== KEY_UNSPEC
||type
==KEY_DSA
)) {
530 prv
= key_new(KEY_UNSPEC
);
531 prv
->dsa
= EVP_PKEY_get1_DSA(pk
);
533 name
= "dsa w/o comment";
535 DSA_print_fp(stderr
, prv
->dsa
, 8);
537 #ifdef OPENSSL_HAS_ECC
538 } else if (pk
->type
== EVP_PKEY_EC
&&
539 (type
== KEY_UNSPEC
||type
==KEY_ECDSA
)) {
540 prv
= key_new(KEY_UNSPEC
);
541 prv
->ecdsa
= EVP_PKEY_get1_EC_KEY(pk
);
542 prv
->type
= KEY_ECDSA
;
543 if ((prv
->ecdsa_nid
= key_ecdsa_key_to_nid(prv
->ecdsa
)) == -1 ||
544 key_curve_nid_to_name(prv
->ecdsa_nid
) == NULL
||
545 key_ec_validate_public(EC_KEY_get0_group(prv
->ecdsa
),
546 EC_KEY_get0_public_key(prv
->ecdsa
)) != 0 ||
547 key_ec_validate_private(prv
->ecdsa
) != 0) {
548 error("%s: bad ECDSA key", __func__
);
552 name
= "ecdsa w/o comment";
554 if (prv
!= NULL
&& prv
->ecdsa
!= NULL
)
555 key_dump_ec_key(prv
->ecdsa
);
557 #endif /* OPENSSL_HAS_ECC */
559 error("%s: PEM_read_PrivateKey: mismatch or "
560 "unknown EVP_PKEY save_type %d", __func__
, pk
->save_type
);
564 if (prv
!= NULL
&& commentp
)
565 *commentp
= xstrdup(name
);
566 debug("read PEM private key done: type %s",
567 prv
? key_type(prv
) : "<unknown>");
572 key_load_private_pem(int fd
, int type
, const char *passphrase
,
578 buffer_init(&buffer
);
579 if (!key_load_file(fd
, NULL
, &buffer
)) {
580 buffer_free(&buffer
);
583 prv
= key_parse_private_pem(&buffer
, type
, passphrase
, commentp
);
584 buffer_free(&buffer
);
589 key_perm_ok(int fd
, const char *filename
)
593 if (fstat(fd
, &st
) < 0)
596 * if a key owned by the user is accessed, then we check the
597 * permissions of the file. if the key owned by a different user,
598 * then we don't care.
601 if (check_ntsec(filename
))
603 if ((st
.st_uid
== getuid()) && (st
.st_mode
& 077) != 0) {
604 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
605 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
606 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
607 error("Permissions 0%3.3o for '%s' are too open.",
608 (u_int
)st
.st_mode
& 0777, filename
);
609 error("It is recommended that your private key files are NOT accessible by others.");
610 error("This private key will be ignored.");
617 key_parse_private_type(Buffer
*blob
, int type
, const char *passphrase
,
622 return key_parse_private_rsa1(blob
, passphrase
, commentp
);
627 return key_parse_private_pem(blob
, type
, passphrase
, commentp
);
635 key_load_private_type(int type
, const char *filename
, const char *passphrase
,
636 char **commentp
, int *perm_ok
)
642 fd
= open(filename
, O_RDONLY
);
644 debug("could not open key file '%s': %s", filename
,
650 if (!key_perm_ok(fd
, filename
)) {
653 error("bad permissions: ignore key: %s", filename
);
660 buffer_init(&buffer
);
661 if (!key_load_file(fd
, filename
, &buffer
)) {
662 buffer_free(&buffer
);
667 ret
= key_parse_private_type(&buffer
, type
, passphrase
, commentp
);
668 buffer_free(&buffer
);
673 key_load_private(const char *filename
, const char *passphrase
,
677 Buffer buffer
, pubcopy
;
680 fd
= open(filename
, O_RDONLY
);
682 debug("could not open key file '%s': %s", filename
,
686 if (!key_perm_ok(fd
, filename
)) {
687 error("bad permissions: ignore key: %s", filename
);
692 buffer_init(&buffer
);
693 if (!key_load_file(fd
, filename
, &buffer
)) {
694 buffer_free(&buffer
);
700 buffer_init(&pubcopy
);
701 buffer_append(&pubcopy
, buffer_ptr(&buffer
), buffer_len(&buffer
));
702 /* it's a SSH v1 key if the public key part is readable */
703 pub
= key_parse_public_rsa1(&pubcopy
, commentp
);
704 buffer_free(&pubcopy
);
706 prv
= key_parse_private_type(&buffer
, KEY_UNSPEC
,
708 /* use the filename as a comment for PEM */
710 *commentp
= xstrdup(filename
);
713 /* key_parse_public_rsa1() has already loaded the comment */
714 prv
= key_parse_private_type(&buffer
, KEY_RSA1
, passphrase
,
717 buffer_free(&buffer
);
722 key_try_load_public(Key
*k
, const char *filename
, char **commentp
)
725 char line
[SSH_MAX_PUBKEY_BYTES
];
729 f
= fopen(filename
, "r");
731 while (read_keyfile_line(f
, filename
, line
, sizeof(line
),
740 /* Skip leading whitespace. */
741 for (; *cp
&& (*cp
== ' ' || *cp
== '\t'); cp
++)
744 if (key_read(k
, &cp
) == 1) {
746 *commentp
=xstrdup(filename
);
757 /* load public key from ssh v1 private or any pubkey file */
759 key_load_public(const char *filename
, char **commentp
)
762 char file
[MAXPATHLEN
];
764 /* try rsa1 private key */
765 pub
= key_load_public_type(KEY_RSA1
, filename
, commentp
);
769 /* try rsa1 public key */
770 pub
= key_new(KEY_RSA1
);
771 if (key_try_load_public(pub
, filename
, commentp
) == 1)
775 /* try ssh2 public key */
776 pub
= key_new(KEY_UNSPEC
);
777 if (key_try_load_public(pub
, filename
, commentp
) == 1)
779 if ((strlcpy(file
, filename
, sizeof file
) < sizeof(file
)) &&
780 (strlcat(file
, ".pub", sizeof file
) < sizeof(file
)) &&
781 (key_try_load_public(pub
, file
, commentp
) == 1))
787 /* Load the certificate associated with the named private key */
789 key_load_cert(const char *filename
)
794 pub
= key_new(KEY_UNSPEC
);
795 xasprintf(&file
, "%s-cert.pub", filename
);
796 if (key_try_load_public(pub
, file
, NULL
) == 1) {
805 /* Load private key and certificate */
807 key_load_private_cert(int type
, const char *filename
, const char *passphrase
,
818 error("%s: unsupported key type", __func__
);
822 if ((key
= key_load_private_type(type
, filename
,
823 passphrase
, NULL
, perm_ok
)) == NULL
)
826 if ((pub
= key_load_cert(filename
)) == NULL
) {
831 /* Make sure the private key matches the certificate */
832 if (key_equal_public(key
, pub
) == 0) {
833 error("%s: certificate does not match private key %s",
835 } else if (key_to_certified(key
, key_cert_is_legacy(pub
)) != 0) {
836 error("%s: key_to_certified failed", __func__
);
838 key_cert_copy(pub
, key
);
849 * Returns 1 if the specified "key" is listed in the file "filename",
850 * 0 if the key is not listed or -1 on error.
851 * If strict_type is set then the key type must match exactly,
852 * otherwise a comparison that ignores certficiate data is performed.
855 key_in_file(Key
*key
, const char *filename
, int strict_type
)
858 char line
[SSH_MAX_PUBKEY_BYTES
];
863 int (*key_compare
)(const Key
*, const Key
*) = strict_type
?
864 key_equal
: key_equal_public
;
866 if ((f
= fopen(filename
, "r")) == NULL
) {
867 if (errno
== ENOENT
) {
868 debug("%s: keyfile \"%s\" missing", __func__
, filename
);
871 error("%s: could not open keyfile \"%s\": %s", __func__
,
872 filename
, strerror(errno
));
877 while (read_keyfile_line(f
, filename
, line
, sizeof(line
),
881 /* Skip leading whitespace. */
882 for (; *cp
&& (*cp
== ' ' || *cp
== '\t'); cp
++)
885 /* Skip comments and empty lines */
893 pub
= key_new(KEY_UNSPEC
);
894 if (key_read(pub
, &cp
) != 1) {
898 if (key_compare(key
, pub
)) {