1 /* $OpenBSD: authfile.c,v 1.85 2010/10/28 11:22:09 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 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 * Saves the authentication (private) key in a file, encrypting it with
78 * passphrase. The identification of the file (lowest 64 bits of n) will
79 * precede the key to provide identification of the key without needing a
84 key_save_private_rsa1(Key
*key
, const char *filename
, const char *passphrase
,
87 Buffer buffer
, encrypted
;
89 int fd
, i
, cipher_num
;
90 CipherContext ciphercontext
;
95 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
96 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
98 cipher_num
= (strcmp(passphrase
, "") == 0) ?
99 SSH_CIPHER_NONE
: SSH_AUTHFILE_CIPHER
;
100 if ((cipher
= cipher_by_number(cipher_num
)) == NULL
)
101 fatal("save_private_key_rsa: bad cipher");
103 /* This buffer is used to built the secret part of the private key. */
104 buffer_init(&buffer
);
106 /* Put checkbytes for checking passphrase validity. */
109 buf
[1] = (rnd
>> 8) & 0xff;
112 buffer_append(&buffer
, buf
, 4);
115 * Store the private key (n and e will not be stored because they
116 * will be stored in plain text, and storing them also in encrypted
117 * format would just give known plaintext).
119 buffer_put_bignum(&buffer
, key
->rsa
->d
);
120 buffer_put_bignum(&buffer
, key
->rsa
->iqmp
);
121 buffer_put_bignum(&buffer
, key
->rsa
->q
); /* reverse from SSL p */
122 buffer_put_bignum(&buffer
, key
->rsa
->p
); /* reverse from SSL q */
124 /* Pad the part to be encrypted until its size is a multiple of 8. */
125 while (buffer_len(&buffer
) % 8 != 0)
126 buffer_put_char(&buffer
, 0);
128 /* This buffer will be used to contain the data in the file. */
129 buffer_init(&encrypted
);
131 /* First store keyfile id string. */
132 for (i
= 0; authfile_id_string
[i
]; i
++)
133 buffer_put_char(&encrypted
, authfile_id_string
[i
]);
134 buffer_put_char(&encrypted
, 0);
136 /* Store cipher type. */
137 buffer_put_char(&encrypted
, cipher_num
);
138 buffer_put_int(&encrypted
, 0); /* For future extension */
140 /* Store public key. This will be in plain text. */
141 buffer_put_int(&encrypted
, BN_num_bits(key
->rsa
->n
));
142 buffer_put_bignum(&encrypted
, key
->rsa
->n
);
143 buffer_put_bignum(&encrypted
, key
->rsa
->e
);
144 buffer_put_cstring(&encrypted
, comment
);
146 /* Allocate space for the private part of the key in the buffer. */
147 cp
= buffer_append_space(&encrypted
, buffer_len(&buffer
));
149 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
151 cipher_crypt(&ciphercontext
, cp
,
152 buffer_ptr(&buffer
), buffer_len(&buffer
));
153 cipher_cleanup(&ciphercontext
);
154 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
156 /* Destroy temporary data. */
157 memset(buf
, 0, sizeof(buf
));
158 buffer_free(&buffer
);
160 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
162 error("open %s failed: %s.", filename
, strerror(errno
));
163 buffer_free(&encrypted
);
166 if (atomicio(vwrite
, fd
, buffer_ptr(&encrypted
),
167 buffer_len(&encrypted
)) != buffer_len(&encrypted
)) {
168 error("write to key file %s failed: %s", filename
,
170 buffer_free(&encrypted
);
176 buffer_free(&encrypted
);
180 /* save SSH v2 key in OpenSSL PEM format */
182 key_save_private_pem(Key
*key
, const char *filename
, const char *_passphrase
,
188 int len
= strlen(_passphrase
);
189 u_char
*passphrase
= (len
> 0) ? (u_char
*)_passphrase
: NULL
;
190 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
191 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_des_ede3_cbc() : NULL
;
193 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_aes_128_cbc() : NULL
;
196 if (len
> 0 && len
<= 4) {
197 error("passphrase too short: have %d bytes, need > 4", len
);
200 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
202 error("open %s failed: %s.", filename
, strerror(errno
));
205 fp
= fdopen(fd
, "w");
207 error("fdopen %s failed: %s.", filename
, strerror(errno
));
213 success
= PEM_write_DSAPrivateKey(fp
, key
->dsa
,
214 cipher
, passphrase
, len
, NULL
, NULL
);
216 #ifdef OPENSSL_HAS_ECC
218 success
= PEM_write_ECPrivateKey(fp
, key
->ecdsa
,
219 cipher
, passphrase
, len
, NULL
, NULL
);
223 success
= PEM_write_RSAPrivateKey(fp
, key
->rsa
,
224 cipher
, passphrase
, len
, NULL
, NULL
);
232 key_save_private(Key
*key
, const char *filename
, const char *passphrase
,
237 return key_save_private_rsa1(key
, filename
, passphrase
,
242 return key_save_private_pem(key
, filename
, passphrase
,
247 error("key_save_private: cannot save key type %d", key
->type
);
252 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
253 * encountered (the file does not exist or is not readable), and the key
258 key_load_public_rsa1(int fd
, const char *filename
, char **commentp
)
267 if (fstat(fd
, &st
) < 0) {
268 error("fstat for key file %.200s failed: %.100s",
269 filename
, strerror(errno
));
272 if (st
.st_size
> 1*1024*1024) {
273 error("key file %.200s too large", filename
);
276 len
= (size_t)st
.st_size
; /* truncated */
278 buffer_init(&buffer
);
279 cp
= buffer_append_space(&buffer
, len
);
281 if (atomicio(read
, fd
, cp
, len
) != len
) {
282 debug("Read from key file %.200s failed: %.100s", filename
,
284 buffer_free(&buffer
);
288 /* Check that it is at least big enough to contain the ID string. */
289 if (len
< sizeof(authfile_id_string
)) {
290 debug3("Not a RSA1 key file %.200s.", filename
);
291 buffer_free(&buffer
);
295 * Make sure it begins with the id string. Consume the id string
298 for (i
= 0; i
< sizeof(authfile_id_string
); i
++)
299 if (buffer_get_char(&buffer
) != authfile_id_string
[i
]) {
300 debug3("Not a RSA1 key file %.200s.", filename
);
301 buffer_free(&buffer
);
304 /* Skip cipher type and reserved data. */
305 (void) buffer_get_char(&buffer
); /* cipher type */
306 (void) buffer_get_int(&buffer
); /* reserved */
308 /* Read the public key from the buffer. */
309 (void) buffer_get_int(&buffer
);
310 pub
= key_new(KEY_RSA1
);
311 buffer_get_bignum(&buffer
, pub
->rsa
->n
);
312 buffer_get_bignum(&buffer
, pub
->rsa
->e
);
314 *commentp
= buffer_get_string(&buffer
, NULL
);
315 /* The encrypted private part is not parsed by this function. */
317 buffer_free(&buffer
);
321 /* load public key from private-key file, works only for SSH v1 */
323 key_load_public_type(int type
, const char *filename
, char **commentp
)
328 if (type
== KEY_RSA1
) {
329 fd
= open(filename
, O_RDONLY
);
332 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
340 * Loads the private key from the file. Returns 0 if an error is encountered
341 * (file does not exist or is not readable, or passphrase is bad). This
342 * initializes the private key.
343 * Assumes we are called under uid of the owner of the file.
347 key_load_private_rsa1(int fd
, const char *filename
, const char *passphrase
,
351 int check1
, check2
, cipher_type
;
353 Buffer buffer
, decrypted
;
355 CipherContext ciphercontext
;
360 if (fstat(fd
, &st
) < 0) {
361 error("fstat for key file %.200s failed: %.100s",
362 filename
, strerror(errno
));
366 if (st
.st_size
> 1*1024*1024) {
367 error("key file %.200s too large", filename
);
371 len
= (size_t)st
.st_size
; /* truncated */
373 buffer_init(&buffer
);
374 cp
= buffer_append_space(&buffer
, len
);
376 if (atomicio(read
, fd
, cp
, len
) != len
) {
377 debug("Read from key file %.200s failed: %.100s", filename
,
379 buffer_free(&buffer
);
384 /* Check that it is at least big enough to contain the ID string. */
385 if (len
< sizeof(authfile_id_string
)) {
386 debug3("Not a RSA1 key file %.200s.", filename
);
387 buffer_free(&buffer
);
392 * Make sure it begins with the id string. Consume the id string
395 for (i
= 0; i
< sizeof(authfile_id_string
); i
++)
396 if (buffer_get_char(&buffer
) != authfile_id_string
[i
]) {
397 debug3("Not a RSA1 key file %.200s.", filename
);
398 buffer_free(&buffer
);
403 /* Read cipher type. */
404 cipher_type
= buffer_get_char(&buffer
);
405 (void) buffer_get_int(&buffer
); /* Reserved data. */
407 /* Read the public key from the buffer. */
408 (void) buffer_get_int(&buffer
);
409 prv
= key_new_private(KEY_RSA1
);
411 buffer_get_bignum(&buffer
, prv
->rsa
->n
);
412 buffer_get_bignum(&buffer
, prv
->rsa
->e
);
414 *commentp
= buffer_get_string(&buffer
, NULL
);
416 xfree(buffer_get_string(&buffer
, NULL
));
418 /* Check that it is a supported cipher. */
419 cipher
= cipher_by_number(cipher_type
);
420 if (cipher
== NULL
) {
421 debug("Unsupported cipher %d used in key file %.200s.",
422 cipher_type
, filename
);
423 buffer_free(&buffer
);
426 /* Initialize space for decrypted data. */
427 buffer_init(&decrypted
);
428 cp
= buffer_append_space(&decrypted
, buffer_len(&buffer
));
430 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
431 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
433 cipher_crypt(&ciphercontext
, cp
,
434 buffer_ptr(&buffer
), buffer_len(&buffer
));
435 cipher_cleanup(&ciphercontext
);
436 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
437 buffer_free(&buffer
);
439 check1
= buffer_get_char(&decrypted
);
440 check2
= buffer_get_char(&decrypted
);
441 if (check1
!= buffer_get_char(&decrypted
) ||
442 check2
!= buffer_get_char(&decrypted
)) {
443 if (strcmp(passphrase
, "") != 0)
444 debug("Bad passphrase supplied for key file %.200s.",
446 /* Bad passphrase. */
447 buffer_free(&decrypted
);
450 /* Read the rest of the private key. */
451 buffer_get_bignum(&decrypted
, prv
->rsa
->d
);
452 buffer_get_bignum(&decrypted
, prv
->rsa
->iqmp
); /* u */
453 /* in SSL and SSH v1 p and q are exchanged */
454 buffer_get_bignum(&decrypted
, prv
->rsa
->q
); /* p */
455 buffer_get_bignum(&decrypted
, prv
->rsa
->p
); /* q */
457 /* calculate p-1 and q-1 */
458 rsa_generate_additional_parameters(prv
->rsa
);
460 buffer_free(&decrypted
);
462 /* enable blinding */
463 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
464 error("key_load_private_rsa1: RSA_blinding_on failed");
479 key_load_private_pem(int fd
, int type
, const char *passphrase
,
485 char *name
= "<no key>";
487 fp
= fdopen(fd
, "r");
489 error("fdopen failed: %s", strerror(errno
));
493 pk
= PEM_read_PrivateKey(fp
, NULL
, NULL
, (char *)passphrase
);
495 debug("PEM_read_PrivateKey failed");
496 (void)ERR_get_error();
497 } else if (pk
->type
== EVP_PKEY_RSA
&&
498 (type
== KEY_UNSPEC
||type
==KEY_RSA
)) {
499 prv
= key_new(KEY_UNSPEC
);
500 prv
->rsa
= EVP_PKEY_get1_RSA(pk
);
502 name
= "rsa w/o comment";
504 RSA_print_fp(stderr
, prv
->rsa
, 8);
506 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
507 error("key_load_private_pem: RSA_blinding_on failed");
511 } else if (pk
->type
== EVP_PKEY_DSA
&&
512 (type
== KEY_UNSPEC
||type
==KEY_DSA
)) {
513 prv
= key_new(KEY_UNSPEC
);
514 prv
->dsa
= EVP_PKEY_get1_DSA(pk
);
516 name
= "dsa w/o comment";
518 DSA_print_fp(stderr
, prv
->dsa
, 8);
520 #ifdef OPENSSL_HAS_ECC
521 } else if (pk
->type
== EVP_PKEY_EC
&&
522 (type
== KEY_UNSPEC
||type
==KEY_ECDSA
)) {
523 prv
= key_new(KEY_UNSPEC
);
524 prv
->ecdsa
= EVP_PKEY_get1_EC_KEY(pk
);
525 prv
->type
= KEY_ECDSA
;
526 if ((prv
->ecdsa_nid
= key_ecdsa_key_to_nid(prv
->ecdsa
)) == -1 ||
527 key_curve_nid_to_name(prv
->ecdsa_nid
) == NULL
||
528 key_ec_validate_public(EC_KEY_get0_group(prv
->ecdsa
),
529 EC_KEY_get0_public_key(prv
->ecdsa
)) != 0 ||
530 key_ec_validate_private(prv
->ecdsa
) != 0) {
531 error("%s: bad ECDSA key", __func__
);
535 name
= "ecdsa w/o comment";
537 if (prv
!= NULL
&& prv
->ecdsa
!= NULL
)
538 key_dump_ec_key(prv
->ecdsa
);
540 #endif /* OPENSSL_HAS_ECC */
542 error("PEM_read_PrivateKey: mismatch or "
543 "unknown EVP_PKEY save_type %d", pk
->save_type
);
548 if (prv
!= NULL
&& commentp
)
549 *commentp
= xstrdup(name
);
550 debug("read PEM private key done: type %s",
551 prv
? key_type(prv
) : "<unknown>");
556 key_perm_ok(int fd
, const char *filename
)
560 if (fstat(fd
, &st
) < 0)
563 * if a key owned by the user is accessed, then we check the
564 * permissions of the file. if the key owned by a different user,
565 * then we don't care.
568 if (check_ntsec(filename
))
570 if ((st
.st_uid
== getuid()) && (st
.st_mode
& 077) != 0) {
571 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
572 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
573 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
574 error("Permissions 0%3.3o for '%s' are too open.",
575 (u_int
)st
.st_mode
& 0777, filename
);
576 error("It is recommended that your private key files are NOT accessible by others.");
577 error("This private key will be ignored.");
584 key_load_private_type(int type
, const char *filename
, const char *passphrase
,
585 char **commentp
, int *perm_ok
)
589 fd
= open(filename
, O_RDONLY
);
591 debug("could not open key file '%s': %s", filename
,
597 if (!key_perm_ok(fd
, filename
)) {
600 error("bad permissions: ignore key: %s", filename
);
608 return key_load_private_rsa1(fd
, filename
, passphrase
,
615 return key_load_private_pem(fd
, type
, passphrase
, commentp
);
625 key_load_private(const char *filename
, const char *passphrase
,
631 fd
= open(filename
, O_RDONLY
);
633 debug("could not open key file '%s': %s", filename
,
637 if (!key_perm_ok(fd
, filename
)) {
638 error("bad permissions: ignore key: %s", filename
);
642 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
643 lseek(fd
, (off_t
) 0, SEEK_SET
); /* rewind */
646 prv
= key_load_private_pem(fd
, KEY_UNSPEC
, passphrase
, NULL
);
647 /* use the filename as a comment for PEM */
649 *commentp
= xstrdup(filename
);
651 /* it's a SSH v1 key if the public key part is readable */
654 prv
= key_load_private_rsa1(fd
, filename
, passphrase
, NULL
);
660 key_try_load_public(Key
*k
, const char *filename
, char **commentp
)
663 char line
[SSH_MAX_PUBKEY_BYTES
];
667 f
= fopen(filename
, "r");
669 while (read_keyfile_line(f
, filename
, line
, sizeof(line
),
678 /* Skip leading whitespace. */
679 for (; *cp
&& (*cp
== ' ' || *cp
== '\t'); cp
++)
682 if (key_read(k
, &cp
) == 1) {
684 *commentp
=xstrdup(filename
);
695 /* load public key from ssh v1 private or any pubkey file */
697 key_load_public(const char *filename
, char **commentp
)
700 char file
[MAXPATHLEN
];
702 /* try rsa1 private key */
703 pub
= key_load_public_type(KEY_RSA1
, filename
, commentp
);
707 /* try rsa1 public key */
708 pub
= key_new(KEY_RSA1
);
709 if (key_try_load_public(pub
, filename
, commentp
) == 1)
713 /* try ssh2 public key */
714 pub
= key_new(KEY_UNSPEC
);
715 if (key_try_load_public(pub
, filename
, commentp
) == 1)
717 if ((strlcpy(file
, filename
, sizeof file
) < sizeof(file
)) &&
718 (strlcat(file
, ".pub", sizeof file
) < sizeof(file
)) &&
719 (key_try_load_public(pub
, file
, commentp
) == 1))
725 /* Load the certificate associated with the named private key */
727 key_load_cert(const char *filename
)
732 pub
= key_new(KEY_UNSPEC
);
733 xasprintf(&file
, "%s-cert.pub", filename
);
734 if (key_try_load_public(pub
, file
, NULL
) == 1) {
743 /* Load private key and certificate */
745 key_load_private_cert(int type
, const char *filename
, const char *passphrase
,
756 error("%s: unsupported key type", __func__
);
760 if ((key
= key_load_private_type(type
, filename
,
761 passphrase
, NULL
, perm_ok
)) == NULL
)
764 if ((pub
= key_load_cert(filename
)) == NULL
) {
769 /* Make sure the private key matches the certificate */
770 if (key_equal_public(key
, pub
) == 0) {
771 error("%s: certificate does not match private key %s",
773 } else if (key_to_certified(key
, key_cert_is_legacy(pub
)) != 0) {
774 error("%s: key_to_certified failed", __func__
);
776 key_cert_copy(pub
, key
);
787 * Returns 1 if the specified "key" is listed in the file "filename",
788 * 0 if the key is not listed or -1 on error.
789 * If strict_type is set then the key type must match exactly,
790 * otherwise a comparison that ignores certficiate data is performed.
793 key_in_file(Key
*key
, const char *filename
, int strict_type
)
796 char line
[SSH_MAX_PUBKEY_BYTES
];
801 int (*key_compare
)(const Key
*, const Key
*) = strict_type
?
802 key_equal
: key_equal_public
;
804 if ((f
= fopen(filename
, "r")) == NULL
) {
805 if (errno
== ENOENT
) {
806 debug("%s: keyfile \"%s\" missing", __func__
, filename
);
809 error("%s: could not open keyfile \"%s\": %s", __func__
,
810 filename
, strerror(errno
));
815 while (read_keyfile_line(f
, filename
, line
, sizeof(line
),
819 /* Skip leading whitespace. */
820 for (; *cp
&& (*cp
== ' ' || *cp
== '\t'); cp
++)
823 /* Skip comments and empty lines */
831 pub
= key_new(KEY_UNSPEC
);
832 if (key_read(pub
, &cp
) != 1) {
836 if (key_compare(key
, pub
)) {