1 /* $OpenBSD: authfile.c,v 1.76 2006/08/03 03:34:41 deraadt 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>
68 #include "pathnames.h"
70 /* Version identification string for SSH v1 identity files. */
71 static const char authfile_id_string[] =
72 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
75 * Saves the authentication (private) key in a file, encrypting it with
76 * passphrase. The identification of the file (lowest 64 bits of n) will
77 * precede the key to provide identification of the key without needing a
82 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
85 Buffer buffer, encrypted;
87 int fd, i, cipher_num;
88 CipherContext ciphercontext;
93 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
94 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
96 cipher_num = (strcmp(passphrase, "") == 0) ?
97 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
98 if ((cipher = cipher_by_number(cipher_num)) == NULL)
99 fatal("save_private_key_rsa: bad cipher");
101 /* This buffer is used to built the secret part of the private key. */
102 buffer_init(&buffer);
104 /* Put checkbytes for checking passphrase validity. */
107 buf[1] = (rnd >> 8) & 0xff;
110 buffer_append(&buffer, buf, 4);
113 * Store the private key (n and e will not be stored because they
114 * will be stored in plain text, and storing them also in encrypted
115 * format would just give known plaintext).
117 buffer_put_bignum(&buffer, key->rsa->d);
118 buffer_put_bignum(&buffer, key->rsa->iqmp);
119 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
120 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
122 /* Pad the part to be encrypted until its size is a multiple of 8. */
123 while (buffer_len(&buffer) % 8 != 0)
124 buffer_put_char(&buffer, 0);
126 /* This buffer will be used to contain the data in the file. */
127 buffer_init(&encrypted);
129 /* First store keyfile id string. */
130 for (i = 0; authfile_id_string[i]; i++)
131 buffer_put_char(&encrypted, authfile_id_string[i]);
132 buffer_put_char(&encrypted, 0);
134 /* Store cipher type. */
135 buffer_put_char(&encrypted, cipher_num);
136 buffer_put_int(&encrypted, 0); /* For future extension */
138 /* Store public key. This will be in plain text. */
139 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
140 buffer_put_bignum(&encrypted, key->rsa->n);
141 buffer_put_bignum(&encrypted, key->rsa->e);
142 buffer_put_cstring(&encrypted, comment);
144 /* Allocate space for the private part of the key in the buffer. */
145 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
147 cipher_set_key_string(&ciphercontext, cipher, passphrase,
149 cipher_crypt(&ciphercontext, cp,
150 buffer_ptr(&buffer), buffer_len(&buffer));
151 cipher_cleanup(&ciphercontext);
152 memset(&ciphercontext, 0, sizeof(ciphercontext));
154 /* Destroy temporary data. */
155 memset(buf, 0, sizeof(buf));
156 buffer_free(&buffer);
158 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
160 error("open %s failed: %s.", filename, strerror(errno));
161 buffer_free(&encrypted);
164 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
165 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
166 error("write to key file %s failed: %s", filename,
168 buffer_free(&encrypted);
174 buffer_free(&encrypted);
178 /* save SSH v2 key in OpenSSL PEM format */
180 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
186 int len = strlen(_passphrase);
187 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
188 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
190 if (len > 0 && len <= 4) {
191 error("passphrase too short: have %d bytes, need > 4", len);
194 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
196 error("open %s failed: %s.", filename, strerror(errno));
199 fp = fdopen(fd, "w");
201 error("fdopen %s failed: %s.", filename, strerror(errno));
207 success = PEM_write_DSAPrivateKey(fp, key->dsa,
208 cipher, passphrase, len, NULL, NULL);
211 success = PEM_write_RSAPrivateKey(fp, key->rsa,
212 cipher, passphrase, len, NULL, NULL);
220 key_save_private(Key *key, const char *filename, const char *passphrase,
225 return key_save_private_rsa1(key, filename, passphrase,
229 return key_save_private_pem(key, filename, passphrase,
234 error("key_save_private: cannot save key type %d", key->type);
239 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
240 * encountered (the file does not exist or is not readable), and the key
245 key_load_public_rsa1(int fd, const char *filename, char **commentp)
254 if (fstat(fd, &st) < 0) {
255 error("fstat for key file %.200s failed: %.100s",
256 filename, strerror(errno));
259 if (st.st_size > 1*1024*1024) {
260 error("key file %.200s too large", filename);
263 len = (size_t)st.st_size; /* truncated */
265 buffer_init(&buffer);
266 cp = buffer_append_space(&buffer, len);
268 if (atomicio(read, fd, cp, len) != len) {
269 debug("Read from key file %.200s failed: %.100s", filename,
271 buffer_free(&buffer);
275 /* Check that it is at least big enough to contain the ID string. */
276 if (len < sizeof(authfile_id_string)) {
277 debug3("Not a RSA1 key file %.200s.", filename);
278 buffer_free(&buffer);
282 * Make sure it begins with the id string. Consume the id string
285 for (i = 0; i < sizeof(authfile_id_string); i++)
286 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
287 debug3("Not a RSA1 key file %.200s.", filename);
288 buffer_free(&buffer);
291 /* Skip cipher type and reserved data. */
292 (void) buffer_get_char(&buffer); /* cipher type */
293 (void) buffer_get_int(&buffer); /* reserved */
295 /* Read the public key from the buffer. */
296 (void) buffer_get_int(&buffer);
297 pub = key_new(KEY_RSA1);
298 buffer_get_bignum(&buffer, pub->rsa->n);
299 buffer_get_bignum(&buffer, pub->rsa->e);
301 *commentp = buffer_get_string(&buffer, NULL);
302 /* The encrypted private part is not parsed by this function. */
304 buffer_free(&buffer);
308 /* load public key from private-key file, works only for SSH v1 */
310 key_load_public_type(int type, const char *filename, char **commentp)
315 if (type == KEY_RSA1) {
316 fd = open(filename, O_RDONLY);
319 pub = key_load_public_rsa1(fd, filename, commentp);
327 * Loads the private key from the file. Returns 0 if an error is encountered
328 * (file does not exist or is not readable, or passphrase is bad). This
329 * initializes the private key.
330 * Assumes we are called under uid of the owner of the file.
334 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
338 int check1, check2, cipher_type;
340 Buffer buffer, decrypted;
342 CipherContext ciphercontext;
347 if (fstat(fd, &st) < 0) {
348 error("fstat for key file %.200s failed: %.100s",
349 filename, strerror(errno));
353 if (st.st_size > 1*1024*1024) {
354 error("key file %.200s too large", filename);
358 len = (size_t)st.st_size; /* truncated */
360 buffer_init(&buffer);
361 cp = buffer_append_space(&buffer, len);
363 if (atomicio(read, fd, cp, len) != len) {
364 debug("Read from key file %.200s failed: %.100s", filename,
366 buffer_free(&buffer);
371 /* Check that it is at least big enough to contain the ID string. */
372 if (len < sizeof(authfile_id_string)) {
373 debug3("Not a RSA1 key file %.200s.", filename);
374 buffer_free(&buffer);
379 * Make sure it begins with the id string. Consume the id string
382 for (i = 0; i < sizeof(authfile_id_string); i++)
383 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
384 debug3("Not a RSA1 key file %.200s.", filename);
385 buffer_free(&buffer);
390 /* Read cipher type. */
391 cipher_type = buffer_get_char(&buffer);
392 (void) buffer_get_int(&buffer); /* Reserved data. */
394 /* Read the public key from the buffer. */
395 (void) buffer_get_int(&buffer);
396 prv = key_new_private(KEY_RSA1);
398 buffer_get_bignum(&buffer, prv->rsa->n);
399 buffer_get_bignum(&buffer, prv->rsa->e);
401 *commentp = buffer_get_string(&buffer, NULL);
403 xfree(buffer_get_string(&buffer, NULL));
405 /* Check that it is a supported cipher. */
406 cipher = cipher_by_number(cipher_type);
407 if (cipher == NULL) {
408 debug("Unsupported cipher %d used in key file %.200s.",
409 cipher_type, filename);
410 buffer_free(&buffer);
413 /* Initialize space for decrypted data. */
414 buffer_init(&decrypted);
415 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
417 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
418 cipher_set_key_string(&ciphercontext, cipher, passphrase,
420 cipher_crypt(&ciphercontext, cp,
421 buffer_ptr(&buffer), buffer_len(&buffer));
422 cipher_cleanup(&ciphercontext);
423 memset(&ciphercontext, 0, sizeof(ciphercontext));
424 buffer_free(&buffer);
426 check1 = buffer_get_char(&decrypted);
427 check2 = buffer_get_char(&decrypted);
428 if (check1 != buffer_get_char(&decrypted) ||
429 check2 != buffer_get_char(&decrypted)) {
430 if (strcmp(passphrase, "") != 0)
431 debug("Bad passphrase supplied for key file %.200s.",
433 /* Bad passphrase. */
434 buffer_free(&decrypted);
437 /* Read the rest of the private key. */
438 buffer_get_bignum(&decrypted, prv->rsa->d);
439 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
440 /* in SSL and SSH v1 p and q are exchanged */
441 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
442 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
444 /* calculate p-1 and q-1 */
445 rsa_generate_additional_parameters(prv->rsa);
447 buffer_free(&decrypted);
449 /* enable blinding */
450 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
451 error("key_load_private_rsa1: RSA_blinding_on failed");
466 key_load_private_pem(int fd, int type, const char *passphrase,
472 char *name = "<no key>";
474 fp = fdopen(fd, "r");
476 error("fdopen failed: %s", strerror(errno));
480 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
482 debug("PEM_read_PrivateKey failed");
483 (void)ERR_get_error();
484 } else if (pk->type == EVP_PKEY_RSA &&
485 (type == KEY_UNSPEC||type==KEY_RSA)) {
486 prv = key_new(KEY_UNSPEC);
487 prv->rsa = EVP_PKEY_get1_RSA(pk);
489 name = "rsa w/o comment";
491 RSA_print_fp(stderr, prv->rsa, 8);
493 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
494 error("key_load_private_pem: RSA_blinding_on failed");
498 } else if (pk->type == EVP_PKEY_DSA &&
499 (type == KEY_UNSPEC||type==KEY_DSA)) {
500 prv = key_new(KEY_UNSPEC);
501 prv->dsa = EVP_PKEY_get1_DSA(pk);
503 name = "dsa w/o comment";
505 DSA_print_fp(stderr, prv->dsa, 8);
508 error("PEM_read_PrivateKey: mismatch or "
509 "unknown EVP_PKEY save_type %d", pk->save_type);
514 if (prv != NULL && commentp)
515 *commentp = xstrdup(name);
516 debug("read PEM private key done: type %s",
517 prv ? key_type(prv) : "<unknown>");
522 key_perm_ok(int fd, const char *filename)
526 if (fstat(fd, &st) < 0)
529 * if a key owned by the user is accessed, then we check the
530 * permissions of the file. if the key owned by a different user,
531 * then we don't care.
534 if (check_ntsec(filename))
536 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
537 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
538 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
539 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
540 error("Permissions 0%3.3o for '%s' are too open.",
541 (u_int)st.st_mode & 0777, filename);
542 error("It is recommended that your private key files are NOT accessible by others.");
543 error("This private key will be ignored.");
550 key_load_private_type(int type, const char *filename, const char *passphrase,
551 char **commentp, int *perm_ok)
555 fd = open(filename, O_RDONLY);
558 if (!key_perm_ok(fd, filename)) {
561 error("bad permissions: ignore key: %s", filename);
569 return key_load_private_rsa1(fd, filename, passphrase,
575 return key_load_private_pem(fd, type, passphrase, commentp);
585 key_load_private(const char *filename, const char *passphrase,
591 fd = open(filename, O_RDONLY);
594 if (!key_perm_ok(fd, filename)) {
595 error("bad permissions: ignore key: %s", filename);
599 pub = key_load_public_rsa1(fd, filename, commentp);
600 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
603 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
604 /* use the filename as a comment for PEM */
606 *commentp = xstrdup(filename);
608 /* it's a SSH v1 key if the public key part is readable */
611 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
617 key_try_load_public(Key *k, const char *filename, char **commentp)
620 char line[SSH_MAX_PUBKEY_BYTES];
624 f = fopen(filename, "r");
626 while (read_keyfile_line(f, filename, line, sizeof(line),
635 /* Skip leading whitespace. */
636 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
639 if (key_read(k, &cp) == 1) {
641 *commentp=xstrdup(filename);
652 /* load public key from ssh v1 private or any pubkey file */
654 key_load_public(const char *filename, char **commentp)
657 char file[MAXPATHLEN];
659 /* try rsa1 private key */
660 pub = key_load_public_type(KEY_RSA1, filename, commentp);
664 /* try rsa1 public key */
665 pub = key_new(KEY_RSA1);
666 if (key_try_load_public(pub, filename, commentp) == 1)
670 /* try ssh2 public key */
671 pub = key_new(KEY_UNSPEC);
672 if (key_try_load_public(pub, filename, commentp) == 1)
674 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
675 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
676 (key_try_load_public(pub, file, commentp) == 1))
683 blacklist_filename(const Key *key)
687 xasprintf(&name, "%s.%s-%u",
688 _PATH_BLACKLIST, key_type(key), key_size(key));
692 /* Scan a blacklist of known-vulnerable keys. */
694 blacklisted_key(const Key *key)
696 char *blacklist_file;
698 char *dgst_hex = NULL;
699 char *dgst_packed = NULL, *p;
704 off_t start, lower, upper;
707 blacklist_file = blacklist_filename(key);
708 debug("Checking blacklist file %s", blacklist_file);
709 fd = open(blacklist_file, O_RDONLY);
713 dgst_hex = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
714 /* Remove all colons */
715 dgst_packed = xcalloc(1, strlen(dgst_hex) + 1);
716 for (i = 0, p = dgst_packed; dgst_hex[i]; i++)
717 if (dgst_hex[i] != ':')
719 /* Only compare least-significant 80 bits (to keep the blacklist
722 line_len = strlen(dgst_packed + 12);
726 /* Skip leading comments */
732 r = atomicio(read, fd, buf, 256);
738 newline = memchr(buf, '\n', 256);
741 start += newline + 1 - buf;
742 if (lseek(fd, start, SEEK_SET) < 0)
746 /* Initialise binary search record numbers */
747 if (fstat(fd, &st) < 0)
750 upper = (st.st_size - start) / (line_len + 1);
752 while (lower != upper) {
757 cur = lower + (upper - lower) / 2;
759 /* Read this line and compare to digest; this is
760 * overflow-safe since cur < max(off_t) / (line_len + 1) */
761 if (lseek(fd, start + cur * (line_len + 1), SEEK_SET) < 0)
763 if (atomicio(read, fd, buf, line_len) != line_len)
765 cmp = memcmp(buf, dgst_packed + 12, line_len);
770 } else if (cmp > 0) {
775 debug("Found %s in blacklist", dgst_hex);
788 xfree(blacklist_file);