1 /* $OpenBSD: authfile.c,v 1.82 2010/08/04 05:49:22 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"
71 #include "pathnames.h"
73 /* Version identification string for SSH v1 identity files. */
74 static const char authfile_id_string[] =
75 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
78 * Saves the authentication (private) key in a file, encrypting it with
79 * passphrase. The identification of the file (lowest 64 bits of n) will
80 * precede the key to provide identification of the key without needing a
85 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
88 Buffer buffer, encrypted;
90 int fd, i, cipher_num;
91 CipherContext ciphercontext;
96 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
97 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
99 cipher_num = (strcmp(passphrase, "") == 0) ?
100 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
101 if ((cipher = cipher_by_number(cipher_num)) == NULL)
102 fatal("save_private_key_rsa: bad cipher");
104 /* This buffer is used to built the secret part of the private key. */
105 buffer_init(&buffer);
107 /* Put checkbytes for checking passphrase validity. */
110 buf[1] = (rnd >> 8) & 0xff;
113 buffer_append(&buffer, buf, 4);
116 * Store the private key (n and e will not be stored because they
117 * will be stored in plain text, and storing them also in encrypted
118 * format would just give known plaintext).
120 buffer_put_bignum(&buffer, key->rsa->d);
121 buffer_put_bignum(&buffer, key->rsa->iqmp);
122 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
123 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
125 /* Pad the part to be encrypted until its size is a multiple of 8. */
126 while (buffer_len(&buffer) % 8 != 0)
127 buffer_put_char(&buffer, 0);
129 /* This buffer will be used to contain the data in the file. */
130 buffer_init(&encrypted);
132 /* First store keyfile id string. */
133 for (i = 0; authfile_id_string[i]; i++)
134 buffer_put_char(&encrypted, authfile_id_string[i]);
135 buffer_put_char(&encrypted, 0);
137 /* Store cipher type. */
138 buffer_put_char(&encrypted, cipher_num);
139 buffer_put_int(&encrypted, 0); /* For future extension */
141 /* Store public key. This will be in plain text. */
142 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
143 buffer_put_bignum(&encrypted, key->rsa->n);
144 buffer_put_bignum(&encrypted, key->rsa->e);
145 buffer_put_cstring(&encrypted, comment);
147 /* Allocate space for the private part of the key in the buffer. */
148 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
150 cipher_set_key_string(&ciphercontext, cipher, passphrase,
152 cipher_crypt(&ciphercontext, cp,
153 buffer_ptr(&buffer), buffer_len(&buffer));
154 cipher_cleanup(&ciphercontext);
155 memset(&ciphercontext, 0, sizeof(ciphercontext));
157 /* Destroy temporary data. */
158 memset(buf, 0, sizeof(buf));
159 buffer_free(&buffer);
161 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
163 error("open %s failed: %s.", filename, strerror(errno));
164 buffer_free(&encrypted);
167 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
168 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
169 error("write to key file %s failed: %s", filename,
171 buffer_free(&encrypted);
177 buffer_free(&encrypted);
181 /* save SSH v2 key in OpenSSL PEM format */
183 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
189 int len = strlen(_passphrase);
190 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
191 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
192 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
194 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
197 if (len > 0 && len <= 4) {
198 error("passphrase too short: have %d bytes, need > 4", len);
201 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
203 error("open %s failed: %s.", filename, strerror(errno));
206 fp = fdopen(fd, "w");
208 error("fdopen %s failed: %s.", filename, strerror(errno));
214 success = PEM_write_DSAPrivateKey(fp, key->dsa,
215 cipher, passphrase, len, NULL, NULL);
218 success = PEM_write_RSAPrivateKey(fp, key->rsa,
219 cipher, passphrase, len, NULL, NULL);
227 key_save_private(Key *key, const char *filename, const char *passphrase,
232 return key_save_private_rsa1(key, filename, passphrase,
236 return key_save_private_pem(key, filename, passphrase,
241 error("key_save_private: cannot save key type %d", key->type);
246 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
247 * encountered (the file does not exist or is not readable), and the key
252 key_load_public_rsa1(int fd, const char *filename, char **commentp)
261 if (fstat(fd, &st) < 0) {
262 error("fstat for key file %.200s failed: %.100s",
263 filename, strerror(errno));
266 if (st.st_size > 1*1024*1024) {
267 error("key file %.200s too large", filename);
270 len = (size_t)st.st_size; /* truncated */
272 buffer_init(&buffer);
273 cp = buffer_append_space(&buffer, len);
275 if (atomicio(read, fd, cp, len) != len) {
276 debug("Read from key file %.200s failed: %.100s", filename,
278 buffer_free(&buffer);
282 /* Check that it is at least big enough to contain the ID string. */
283 if (len < sizeof(authfile_id_string)) {
284 debug3("Not a RSA1 key file %.200s.", filename);
285 buffer_free(&buffer);
289 * Make sure it begins with the id string. Consume the id string
292 for (i = 0; i < sizeof(authfile_id_string); i++)
293 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
294 debug3("Not a RSA1 key file %.200s.", filename);
295 buffer_free(&buffer);
298 /* Skip cipher type and reserved data. */
299 (void) buffer_get_char(&buffer); /* cipher type */
300 (void) buffer_get_int(&buffer); /* reserved */
302 /* Read the public key from the buffer. */
303 (void) buffer_get_int(&buffer);
304 pub = key_new(KEY_RSA1);
305 buffer_get_bignum(&buffer, pub->rsa->n);
306 buffer_get_bignum(&buffer, pub->rsa->e);
308 *commentp = buffer_get_string(&buffer, NULL);
309 /* The encrypted private part is not parsed by this function. */
311 buffer_free(&buffer);
315 /* load public key from private-key file, works only for SSH v1 */
317 key_load_public_type(int type, const char *filename, char **commentp)
322 if (type == KEY_RSA1) {
323 fd = open(filename, O_RDONLY);
326 pub = key_load_public_rsa1(fd, filename, commentp);
334 * Loads the private key from the file. Returns 0 if an error is encountered
335 * (file does not exist or is not readable, or passphrase is bad). This
336 * initializes the private key.
337 * Assumes we are called under uid of the owner of the file.
341 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
345 int check1, check2, cipher_type;
347 Buffer buffer, decrypted;
349 CipherContext ciphercontext;
354 if (fstat(fd, &st) < 0) {
355 error("fstat for key file %.200s failed: %.100s",
356 filename, strerror(errno));
360 if (st.st_size > 1*1024*1024) {
361 error("key file %.200s too large", filename);
365 len = (size_t)st.st_size; /* truncated */
367 buffer_init(&buffer);
368 cp = buffer_append_space(&buffer, len);
370 if (atomicio(read, fd, cp, len) != len) {
371 debug("Read from key file %.200s failed: %.100s", filename,
373 buffer_free(&buffer);
378 /* Check that it is at least big enough to contain the ID string. */
379 if (len < sizeof(authfile_id_string)) {
380 debug3("Not a RSA1 key file %.200s.", filename);
381 buffer_free(&buffer);
386 * Make sure it begins with the id string. Consume the id string
389 for (i = 0; i < sizeof(authfile_id_string); i++)
390 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
391 debug3("Not a RSA1 key file %.200s.", filename);
392 buffer_free(&buffer);
397 /* Read cipher type. */
398 cipher_type = buffer_get_char(&buffer);
399 (void) buffer_get_int(&buffer); /* Reserved data. */
401 /* Read the public key from the buffer. */
402 (void) buffer_get_int(&buffer);
403 prv = key_new_private(KEY_RSA1);
405 buffer_get_bignum(&buffer, prv->rsa->n);
406 buffer_get_bignum(&buffer, prv->rsa->e);
408 *commentp = buffer_get_string(&buffer, NULL);
410 xfree(buffer_get_string(&buffer, NULL));
412 /* Check that it is a supported cipher. */
413 cipher = cipher_by_number(cipher_type);
414 if (cipher == NULL) {
415 debug("Unsupported cipher %d used in key file %.200s.",
416 cipher_type, filename);
417 buffer_free(&buffer);
420 /* Initialize space for decrypted data. */
421 buffer_init(&decrypted);
422 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
424 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
425 cipher_set_key_string(&ciphercontext, cipher, passphrase,
427 cipher_crypt(&ciphercontext, cp,
428 buffer_ptr(&buffer), buffer_len(&buffer));
429 cipher_cleanup(&ciphercontext);
430 memset(&ciphercontext, 0, sizeof(ciphercontext));
431 buffer_free(&buffer);
433 check1 = buffer_get_char(&decrypted);
434 check2 = buffer_get_char(&decrypted);
435 if (check1 != buffer_get_char(&decrypted) ||
436 check2 != buffer_get_char(&decrypted)) {
437 if (strcmp(passphrase, "") != 0)
438 debug("Bad passphrase supplied for key file %.200s.",
440 /* Bad passphrase. */
441 buffer_free(&decrypted);
444 /* Read the rest of the private key. */
445 buffer_get_bignum(&decrypted, prv->rsa->d);
446 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
447 /* in SSL and SSH v1 p and q are exchanged */
448 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
449 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
451 /* calculate p-1 and q-1 */
452 rsa_generate_additional_parameters(prv->rsa);
454 buffer_free(&decrypted);
456 /* enable blinding */
457 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
458 error("key_load_private_rsa1: RSA_blinding_on failed");
473 key_load_private_pem(int fd, int type, const char *passphrase,
479 char *name = "<no key>";
481 fp = fdopen(fd, "r");
483 error("fdopen failed: %s", strerror(errno));
487 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
489 debug("PEM_read_PrivateKey failed");
490 (void)ERR_get_error();
491 } else if (pk->type == EVP_PKEY_RSA &&
492 (type == KEY_UNSPEC||type==KEY_RSA)) {
493 prv = key_new(KEY_UNSPEC);
494 prv->rsa = EVP_PKEY_get1_RSA(pk);
496 name = "rsa w/o comment";
498 RSA_print_fp(stderr, prv->rsa, 8);
500 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
501 error("key_load_private_pem: RSA_blinding_on failed");
505 } else if (pk->type == EVP_PKEY_DSA &&
506 (type == KEY_UNSPEC||type==KEY_DSA)) {
507 prv = key_new(KEY_UNSPEC);
508 prv->dsa = EVP_PKEY_get1_DSA(pk);
510 name = "dsa w/o comment";
512 DSA_print_fp(stderr, prv->dsa, 8);
515 error("PEM_read_PrivateKey: mismatch or "
516 "unknown EVP_PKEY save_type %d", pk->save_type);
521 if (prv != NULL && commentp)
522 *commentp = xstrdup(name);
523 debug("read PEM private key done: type %s",
524 prv ? key_type(prv) : "<unknown>");
529 key_perm_ok(int fd, const char *filename)
533 if (fstat(fd, &st) < 0)
536 * if a key owned by the user is accessed, then we check the
537 * permissions of the file. if the key owned by a different user,
538 * then we don't care.
541 if (check_ntsec(filename))
543 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
544 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
545 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
546 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
547 error("Permissions 0%3.3o for '%s' are too open.",
548 (u_int)st.st_mode & 0777, filename);
549 error("It is recommended that your private key files are NOT accessible by others.");
550 error("This private key will be ignored.");
557 key_load_private_type(int type, const char *filename, const char *passphrase,
558 char **commentp, int *perm_ok)
562 fd = open(filename, O_RDONLY);
564 debug("could not open key file '%s': %s", filename,
570 if (!key_perm_ok(fd, filename)) {
573 error("bad permissions: ignore key: %s", filename);
581 return key_load_private_rsa1(fd, filename, passphrase,
587 return key_load_private_pem(fd, type, passphrase, commentp);
597 key_load_private(const char *filename, const char *passphrase,
603 fd = open(filename, O_RDONLY);
605 debug("could not open key file '%s': %s", filename,
609 if (!key_perm_ok(fd, filename)) {
610 error("bad permissions: ignore key: %s", filename);
614 pub = key_load_public_rsa1(fd, filename, commentp);
615 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
618 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
619 /* use the filename as a comment for PEM */
621 *commentp = xstrdup(filename);
623 /* it's a SSH v1 key if the public key part is readable */
626 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
632 key_try_load_public(Key *k, const char *filename, char **commentp)
635 char line[SSH_MAX_PUBKEY_BYTES];
639 f = fopen(filename, "r");
641 while (read_keyfile_line(f, filename, line, sizeof(line),
650 /* Skip leading whitespace. */
651 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
654 if (key_read(k, &cp) == 1) {
656 *commentp=xstrdup(filename);
667 /* load public key from ssh v1 private or any pubkey file */
669 key_load_public(const char *filename, char **commentp)
672 char file[MAXPATHLEN];
674 /* try rsa1 private key */
675 pub = key_load_public_type(KEY_RSA1, filename, commentp);
679 /* try rsa1 public key */
680 pub = key_new(KEY_RSA1);
681 if (key_try_load_public(pub, filename, commentp) == 1)
685 /* try ssh2 public key */
686 pub = key_new(KEY_UNSPEC);
687 if (key_try_load_public(pub, filename, commentp) == 1)
689 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
690 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
691 (key_try_load_public(pub, file, commentp) == 1))
698 blacklist_filename(const Key *key)
702 xasprintf(&name, "%s.%s-%u",
703 _PATH_BLACKLIST, key_type(key), key_size(key));
707 /* Scan a blacklist of known-vulnerable keys. */
709 blacklisted_key(Key *key)
711 char *blacklist_file;
713 char *dgst_hex = NULL;
714 char *dgst_packed = NULL, *p;
719 off_t start, lower, upper;
722 blacklist_file = blacklist_filename(key);
723 debug("Checking blacklist file %s", blacklist_file);
724 fd = open(blacklist_file, O_RDONLY);
728 dgst_hex = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
729 /* Remove all colons */
730 dgst_packed = xcalloc(1, strlen(dgst_hex) + 1);
731 for (i = 0, p = dgst_packed; dgst_hex[i]; i++)
732 if (dgst_hex[i] != ':')
734 /* Only compare least-significant 80 bits (to keep the blacklist
737 line_len = strlen(dgst_packed + 12);
741 /* Skip leading comments */
747 r = atomicio(read, fd, buf, 256);
753 newline = memchr(buf, '\n', 256);
756 start += newline + 1 - buf;
757 if (lseek(fd, start, SEEK_SET) < 0)
761 /* Initialise binary search record numbers */
762 if (fstat(fd, &st) < 0)
765 upper = (st.st_size - start) / (line_len + 1);
767 while (lower != upper) {
772 cur = lower + (upper - lower) / 2;
774 /* Read this line and compare to digest; this is
775 * overflow-safe since cur < max(off_t) / (line_len + 1) */
776 if (lseek(fd, start + cur * (line_len + 1), SEEK_SET) < 0)
778 if (atomicio(read, fd, buf, line_len) != line_len)
780 cmp = memcmp(buf, dgst_packed + 12, line_len);
785 } else if (cmp > 0) {
790 debug("Found %s in blacklist", dgst_hex);
803 xfree(blacklist_file);
807 /* Load the certificate associated with the named private key */
809 key_load_cert(const char *filename)
814 pub = key_new(KEY_UNSPEC);
815 xasprintf(&file, "%s-cert.pub", filename);
816 if (key_try_load_public(pub, file, NULL) == 1) {
825 /* Load private key and certificate */
827 key_load_private_cert(int type, const char *filename, const char *passphrase,
837 error("%s: unsupported key type", __func__);
841 if ((key = key_load_private_type(type, filename,
842 passphrase, NULL, perm_ok)) == NULL)
845 if ((pub = key_load_cert(filename)) == NULL) {
850 /* Make sure the private key matches the certificate */
851 if (key_equal_public(key, pub) == 0) {
852 error("%s: certificate does not match private key %s",
854 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
855 error("%s: key_to_certified failed", __func__);
857 key_cert_copy(pub, key);
868 * Returns 1 if the specified "key" is listed in the file "filename",
869 * 0 if the key is not listed or -1 on error.
870 * If strict_type is set then the key type must match exactly,
871 * otherwise a comparison that ignores certficiate data is performed.
874 key_in_file(Key *key, const char *filename, int strict_type)
877 char line[SSH_MAX_PUBKEY_BYTES];
882 int (*key_compare)(const Key *, const Key *) = strict_type ?
883 key_equal : key_equal_public;
885 if ((f = fopen(filename, "r")) == NULL) {
886 if (errno == ENOENT) {
887 debug("%s: keyfile \"%s\" missing", __func__, filename);
890 error("%s: could not open keyfile \"%s\": %s", __func__,
891 filename, strerror(errno));
896 while (read_keyfile_line(f, filename, line, sizeof(line),
900 /* Skip leading whitespace. */
901 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
904 /* Skip comments and empty lines */
912 pub = key_new(KEY_UNSPEC);
913 if (key_read(pub, &cp) != 1) {
917 if (key_compare(key, pub)) {