1 /* $OpenBSD: authfile.c,v 1.93 2012/01/25 19:36:31 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 #define MAX_KEY_FILE_SIZE (1024 * 1024)
74 /* Version identification string for SSH v1 identity files. */
75 static const char authfile_id_string[] =
76 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
79 * Serialises the authentication (private) key to a blob, encrypting it with
80 * passphrase. The identification of the blob (lowest 64 bits of n) will
81 * precede the key to provide identification of the key without needing a
85 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
88 Buffer buffer, encrypted;
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 buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
162 buffer_free(&encrypted);
167 /* convert SSH v2 key in OpenSSL PEM format */
169 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
173 int blen, len = strlen(_passphrase);
174 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
175 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
176 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
178 const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
183 if (len > 0 && len <= 4) {
184 error("passphrase too short: have %d bytes, need > 4", len);
187 if ((bio = BIO_new(BIO_s_mem())) == NULL) {
188 error("%s: BIO_new failed", __func__);
193 success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
194 cipher, passphrase, len, NULL, NULL);
196 #ifdef OPENSSL_HAS_ECC
198 success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
199 cipher, passphrase, len, NULL, NULL);
203 success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
204 cipher, passphrase, len, NULL, NULL);
208 if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
211 buffer_append(blob, bptr, blen);
217 /* Save a key blob to a file */
219 key_save_private_blob(Buffer *keybuf, const char *filename)
223 if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
224 error("open %s failed: %s.", filename, strerror(errno));
227 if (atomicio(vwrite, fd, buffer_ptr(keybuf),
228 buffer_len(keybuf)) != buffer_len(keybuf)) {
229 error("write to key file %s failed: %s", filename,
239 /* Serialise "key" to buffer "blob" */
241 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
246 return key_private_rsa1_to_blob(key, blob, passphrase, comment);
250 return key_private_pem_to_blob(key, blob, passphrase, comment);
252 error("%s: cannot save key type %d", __func__, key->type);
258 key_save_private(Key *key, const char *filename, const char *passphrase,
264 buffer_init(&keyblob);
265 if (!key_private_to_blob(key, &keyblob, passphrase, comment))
267 if (!key_save_private_blob(&keyblob, filename))
271 buffer_free(&keyblob);
276 * Parse the public, unencrypted portion of a RSA1 key.
279 key_parse_public_rsa1(Buffer *blob, char **commentp)
284 /* Check that it is at least big enough to contain the ID string. */
285 if (buffer_len(blob) < sizeof(authfile_id_string)) {
286 debug3("Truncated RSA1 identifier");
291 * Make sure it begins with the id string. Consume the id string
294 if (memcmp(buffer_ptr(blob), authfile_id_string,
295 sizeof(authfile_id_string)) != 0) {
296 debug3("Incorrect RSA1 identifier");
300 buffer_append(©, buffer_ptr(blob), buffer_len(blob));
301 buffer_consume(©, sizeof(authfile_id_string));
303 /* Skip cipher type and reserved data. */
304 (void) buffer_get_char(©); /* cipher type */
305 (void) buffer_get_int(©); /* reserved */
307 /* Read the public key from the buffer. */
308 (void) buffer_get_int(©);
309 pub = key_new(KEY_RSA1);
310 buffer_get_bignum(©, pub->rsa->n);
311 buffer_get_bignum(©, pub->rsa->e);
313 *commentp = buffer_get_string(©, NULL);
314 /* The encrypted private part is not parsed by this function. */
320 /* Load a key from a fd into a buffer */
322 key_load_file(int fd, const char *filename, Buffer *blob)
328 if (fstat(fd, &st) < 0) {
329 error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
330 filename == NULL ? "" : filename,
331 filename == NULL ? "" : " ",
335 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
336 st.st_size > MAX_KEY_FILE_SIZE) {
338 error("%s: key file %.200s%stoo large", __func__,
339 filename == NULL ? "" : filename,
340 filename == NULL ? "" : " ");
345 if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
348 debug("%s: read from key file %.200s%sfailed: %.100s",
349 __func__, filename == NULL ? "" : filename,
350 filename == NULL ? "" : " ", strerror(errno));
352 bzero(buf, sizeof(buf));
355 buffer_append(blob, buf, len);
356 if (buffer_len(blob) > MAX_KEY_FILE_SIZE) {
358 bzero(buf, sizeof(buf));
362 bzero(buf, sizeof(buf));
363 if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
364 st.st_size != buffer_len(blob)) {
365 debug("%s: key file %.200s%schanged size while reading",
366 __func__, filename == NULL ? "" : filename,
367 filename == NULL ? "" : " ");
376 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
377 * encountered (the file does not exist or is not readable), and the key
381 key_load_public_rsa1(int fd, const char *filename, char **commentp)
386 buffer_init(&buffer);
387 if (!key_load_file(fd, filename, &buffer)) {
388 buffer_free(&buffer);
392 pub = key_parse_public_rsa1(&buffer, commentp);
394 debug3("Could not load \"%s\" as a RSA1 public key", filename);
395 buffer_free(&buffer);
399 /* load public key from private-key file, works only for SSH v1 */
401 key_load_public_type(int type, const char *filename, char **commentp)
406 if (type == KEY_RSA1) {
407 fd = open(filename, O_RDONLY);
410 pub = key_load_public_rsa1(fd, filename, commentp);
418 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
420 int check1, check2, cipher_type;
423 CipherContext ciphercontext;
428 /* Check that it is at least big enough to contain the ID string. */
429 if (buffer_len(blob) < sizeof(authfile_id_string)) {
430 debug3("Truncated RSA1 identifier");
435 * Make sure it begins with the id string. Consume the id string
438 if (memcmp(buffer_ptr(blob), authfile_id_string,
439 sizeof(authfile_id_string)) != 0) {
440 debug3("Incorrect RSA1 identifier");
444 buffer_append(©, buffer_ptr(blob), buffer_len(blob));
445 buffer_consume(©, sizeof(authfile_id_string));
447 /* Read cipher type. */
448 cipher_type = buffer_get_char(©);
449 (void) buffer_get_int(©); /* Reserved data. */
451 /* Read the public key from the buffer. */
452 (void) buffer_get_int(©);
453 prv = key_new_private(KEY_RSA1);
455 buffer_get_bignum(©, prv->rsa->n);
456 buffer_get_bignum(©, prv->rsa->e);
458 *commentp = buffer_get_string(©, NULL);
460 (void)buffer_get_string_ptr(©, NULL);
462 /* Check that it is a supported cipher. */
463 cipher = cipher_by_number(cipher_type);
464 if (cipher == NULL) {
465 debug("Unsupported RSA1 cipher %d", cipher_type);
469 /* Initialize space for decrypted data. */
470 buffer_init(&decrypted);
471 cp = buffer_append_space(&decrypted, buffer_len(©));
473 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
474 cipher_set_key_string(&ciphercontext, cipher, passphrase,
476 cipher_crypt(&ciphercontext, cp,
477 buffer_ptr(©), buffer_len(©));
478 cipher_cleanup(&ciphercontext);
479 memset(&ciphercontext, 0, sizeof(ciphercontext));
482 check1 = buffer_get_char(&decrypted);
483 check2 = buffer_get_char(&decrypted);
484 if (check1 != buffer_get_char(&decrypted) ||
485 check2 != buffer_get_char(&decrypted)) {
486 if (strcmp(passphrase, "") != 0)
487 debug("Bad passphrase supplied for RSA1 key");
488 /* Bad passphrase. */
489 buffer_free(&decrypted);
492 /* Read the rest of the private key. */
493 buffer_get_bignum(&decrypted, prv->rsa->d);
494 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
495 /* in SSL and SSH v1 p and q are exchanged */
496 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
497 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
499 /* calculate p-1 and q-1 */
500 rsa_generate_additional_parameters(prv->rsa);
502 buffer_free(&decrypted);
504 /* enable blinding */
505 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
506 error("%s: RSA_blinding_on failed", __func__);
519 key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
524 char *name = "<no key>";
527 if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
528 buffer_len(blob))) == NULL) {
529 error("%s: BIO_new_mem_buf failed", __func__);
533 pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
536 debug("%s: PEM_read_PrivateKey failed", __func__);
537 (void)ERR_get_error();
538 } else if (pk->type == EVP_PKEY_RSA &&
539 (type == KEY_UNSPEC||type==KEY_RSA)) {
540 prv = key_new(KEY_UNSPEC);
541 prv->rsa = EVP_PKEY_get1_RSA(pk);
543 name = "rsa w/o comment";
545 RSA_print_fp(stderr, prv->rsa, 8);
547 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
548 error("%s: RSA_blinding_on failed", __func__);
552 } else if (pk->type == EVP_PKEY_DSA &&
553 (type == KEY_UNSPEC||type==KEY_DSA)) {
554 prv = key_new(KEY_UNSPEC);
555 prv->dsa = EVP_PKEY_get1_DSA(pk);
557 name = "dsa w/o comment";
559 DSA_print_fp(stderr, prv->dsa, 8);
561 #ifdef OPENSSL_HAS_ECC
562 } else if (pk->type == EVP_PKEY_EC &&
563 (type == KEY_UNSPEC||type==KEY_ECDSA)) {
564 prv = key_new(KEY_UNSPEC);
565 prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
566 prv->type = KEY_ECDSA;
567 if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
568 key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
569 key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
570 EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
571 key_ec_validate_private(prv->ecdsa) != 0) {
572 error("%s: bad ECDSA key", __func__);
576 name = "ecdsa w/o comment";
578 if (prv != NULL && prv->ecdsa != NULL)
579 key_dump_ec_key(prv->ecdsa);
581 #endif /* OPENSSL_HAS_ECC */
583 error("%s: PEM_read_PrivateKey: mismatch or "
584 "unknown EVP_PKEY save_type %d", __func__, pk->save_type);
588 if (prv != NULL && commentp)
589 *commentp = xstrdup(name);
590 debug("read PEM private key done: type %s",
591 prv ? key_type(prv) : "<unknown>");
596 key_load_private_pem(int fd, int type, const char *passphrase,
602 buffer_init(&buffer);
603 if (!key_load_file(fd, NULL, &buffer)) {
604 buffer_free(&buffer);
607 prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
608 buffer_free(&buffer);
613 key_perm_ok(int fd, const char *filename)
617 if (fstat(fd, &st) < 0)
620 * if a key owned by the user is accessed, then we check the
621 * permissions of the file. if the key owned by a different user,
622 * then we don't care.
625 if (check_ntsec(filename))
627 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
628 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
629 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
630 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
631 error("Permissions 0%3.3o for '%s' are too open.",
632 (u_int)st.st_mode & 0777, filename);
633 error("It is required that your private key files are NOT accessible by others.");
634 error("This private key will be ignored.");
641 key_parse_private_type(Buffer *blob, int type, const char *passphrase,
646 return key_parse_private_rsa1(blob, passphrase, commentp);
651 return key_parse_private_pem(blob, type, passphrase, commentp);
653 error("%s: cannot parse key type %d", __func__, type);
660 key_load_private_type(int type, const char *filename, const char *passphrase,
661 char **commentp, int *perm_ok)
667 fd = open(filename, O_RDONLY);
669 debug("could not open key file '%s': %s", filename,
675 if (!key_perm_ok(fd, filename)) {
678 error("bad permissions: ignore key: %s", filename);
685 buffer_init(&buffer);
686 if (!key_load_file(fd, filename, &buffer)) {
687 buffer_free(&buffer);
692 ret = key_parse_private_type(&buffer, type, passphrase, commentp);
693 buffer_free(&buffer);
698 key_parse_private(Buffer *buffer, const char *filename,
699 const char *passphrase, char **commentp)
703 /* it's a SSH v1 key if the public key part is readable */
704 pub = key_parse_public_rsa1(buffer, commentp);
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,
721 key_load_private(const char *filename, const char *passphrase,
728 fd = open(filename, O_RDONLY);
730 debug("could not open key file '%s': %s", filename,
734 if (!key_perm_ok(fd, filename)) {
735 error("bad permissions: ignore key: %s", filename);
740 buffer_init(&buffer);
741 if (!key_load_file(fd, filename, &buffer)) {
742 buffer_free(&buffer);
748 prv = key_parse_private(&buffer, filename, passphrase, commentp);
749 buffer_free(&buffer);
754 key_try_load_public(Key *k, const char *filename, char **commentp)
757 char line[SSH_MAX_PUBKEY_BYTES];
761 f = fopen(filename, "r");
763 while (read_keyfile_line(f, filename, line, sizeof(line),
772 /* Abort loading if this looks like a private key */
773 if (strncmp(cp, "-----BEGIN", 10) == 0)
775 /* Skip leading whitespace. */
776 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
779 if (key_read(k, &cp) == 1) {
780 cp[strcspn(cp, "\r\n")] = '\0';
782 *commentp = xstrdup(*cp ?
795 /* load public key from ssh v1 private or any pubkey file */
797 key_load_public(const char *filename, char **commentp)
800 char file[MAXPATHLEN];
802 /* try rsa1 private key */
803 pub = key_load_public_type(KEY_RSA1, filename, commentp);
807 /* try rsa1 public key */
808 pub = key_new(KEY_RSA1);
809 if (key_try_load_public(pub, filename, commentp) == 1)
813 /* try ssh2 public key */
814 pub = key_new(KEY_UNSPEC);
815 if (key_try_load_public(pub, filename, commentp) == 1)
817 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
818 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
819 (key_try_load_public(pub, file, commentp) == 1))
825 /* Load the certificate associated with the named private key */
827 key_load_cert(const char *filename)
832 pub = key_new(KEY_UNSPEC);
833 xasprintf(&file, "%s-cert.pub", filename);
834 if (key_try_load_public(pub, file, NULL) == 1) {
843 /* Load private key and certificate */
845 key_load_private_cert(int type, const char *filename, const char *passphrase,
856 error("%s: unsupported key type", __func__);
860 if ((key = key_load_private_type(type, filename,
861 passphrase, NULL, perm_ok)) == NULL)
864 if ((pub = key_load_cert(filename)) == NULL) {
869 /* Make sure the private key matches the certificate */
870 if (key_equal_public(key, pub) == 0) {
871 error("%s: certificate does not match private key %s",
873 } else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
874 error("%s: key_to_certified failed", __func__);
876 key_cert_copy(pub, key);
887 * Returns 1 if the specified "key" is listed in the file "filename",
888 * 0 if the key is not listed or -1 on error.
889 * If strict_type is set then the key type must match exactly,
890 * otherwise a comparison that ignores certficiate data is performed.
893 key_in_file(Key *key, const char *filename, int strict_type)
896 char line[SSH_MAX_PUBKEY_BYTES];
901 int (*key_compare)(const Key *, const Key *) = strict_type ?
902 key_equal : key_equal_public;
904 if ((f = fopen(filename, "r")) == NULL) {
905 if (errno == ENOENT) {
906 debug("%s: keyfile \"%s\" missing", __func__, filename);
909 error("%s: could not open keyfile \"%s\": %s", __func__,
910 filename, strerror(errno));
915 while (read_keyfile_line(f, filename, line, sizeof(line),
919 /* Skip leading whitespace. */
920 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
923 /* Skip comments and empty lines */
931 pub = key_new(KEY_UNSPEC);
932 if (key_read(pub, &cp) != 1) {
936 if (key_compare(key, pub)) {