2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This file contains functions for reading and writing identity files, and
6 * for reading the passphrase from the user.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 2000 Markus Friedl. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 RCSID("$OpenBSD: authfile.c,v 1.19 2000/09/07 20:27:49 deraadt Exp $");
41 #include <openssl/bn.h>
42 #include <openssl/dsa.h>
43 #include <openssl/rsa.h>
44 #include <openssl/pem.h>
45 #include <openssl/evp.h>
54 /* Version identification string for identity files. */
55 #define AUTHFILE_ID_STRING "SSH PRIVATE KEY FILE FORMAT 1.1\n"
58 * Saves the authentication (private) key in a file, encrypting it with
59 * passphrase. The identification of the file (lowest 64 bits of n) will
60 * precede the key to provide identification of the key without needing a
65 save_private_key_rsa(const char *filename, const char *passphrase,
66 RSA *key, const char *comment)
68 Buffer buffer, encrypted;
76 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
77 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
79 if (strcmp(passphrase, "") == 0)
80 cipher_type = SSH_CIPHER_NONE;
82 cipher_type = SSH_AUTHFILE_CIPHER;
84 /* This buffer is used to built the secret part of the private key. */
87 /* Put checkbytes for checking passphrase validity. */
90 buf[1] = (rand >> 8) & 0xff;
93 buffer_append(&buffer, buf, 4);
96 * Store the private key (n and e will not be stored because they
97 * will be stored in plain text, and storing them also in encrypted
98 * format would just give known plaintext).
100 buffer_put_bignum(&buffer, key->d);
101 buffer_put_bignum(&buffer, key->iqmp);
102 buffer_put_bignum(&buffer, key->q); /* reverse from SSL p */
103 buffer_put_bignum(&buffer, key->p); /* reverse from SSL q */
105 /* Pad the part to be encrypted until its size is a multiple of 8. */
106 while (buffer_len(&buffer) % 8 != 0)
107 buffer_put_char(&buffer, 0);
109 /* This buffer will be used to contain the data in the file. */
110 buffer_init(&encrypted);
112 /* First store keyfile id string. */
113 cp = AUTHFILE_ID_STRING;
114 for (i = 0; cp[i]; i++)
115 buffer_put_char(&encrypted, cp[i]);
116 buffer_put_char(&encrypted, 0);
118 /* Store cipher type. */
119 buffer_put_char(&encrypted, cipher_type);
120 buffer_put_int(&encrypted, 0); /* For future extension */
122 /* Store public key. This will be in plain text. */
123 buffer_put_int(&encrypted, BN_num_bits(key->n));
124 buffer_put_bignum(&encrypted, key->n);
125 buffer_put_bignum(&encrypted, key->e);
126 buffer_put_string(&encrypted, comment, strlen(comment));
128 /* Allocate space for the private part of the key in the buffer. */
129 buffer_append_space(&encrypted, &cp, buffer_len(&buffer));
131 cipher_set_key_string(&cipher, cipher_type, passphrase);
132 cipher_encrypt(&cipher, (unsigned char *) cp,
133 (unsigned char *) buffer_ptr(&buffer),
134 buffer_len(&buffer));
135 memset(&cipher, 0, sizeof(cipher));
137 /* Destroy temporary data. */
138 memset(buf, 0, sizeof(buf));
139 buffer_free(&buffer);
141 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
144 if (write(fd, buffer_ptr(&encrypted), buffer_len(&encrypted)) !=
145 buffer_len(&encrypted)) {
146 debug("Write to key file %.200s failed: %.100s", filename,
148 buffer_free(&encrypted);
154 buffer_free(&encrypted);
158 /* save DSA key in OpenSSL PEM format */
161 save_private_key_dsa(const char *filename, const char *passphrase,
162 DSA *dsa, const char *comment)
167 int len = strlen(passphrase);
169 if (len > 0 && len <= 4) {
170 error("passphrase too short: %d bytes", len);
174 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
176 debug("open %s failed", filename);
179 fp = fdopen(fd, "w");
181 debug("fdopen %s failed", filename);
186 if (!PEM_write_DSAPrivateKey(fp, dsa, EVP_des_ede3_cbc(),
187 (char *)passphrase, strlen(passphrase), NULL, NULL))
190 if (!PEM_write_DSAPrivateKey(fp, dsa, NULL,
191 NULL, 0, NULL, NULL))
199 save_private_key(const char *filename, const char *passphrase, Key *key,
204 return save_private_key_rsa(filename, passphrase, key->rsa, comment);
207 return save_private_key_dsa(filename, passphrase, key->dsa, comment);
216 * Loads the public part of the key file. Returns 0 if an error was
217 * encountered (the file does not exist or is not readable), and non-zero
222 load_public_key_rsa(const char *filename, RSA * pub, char **comment_return)
229 fd = open(filename, O_RDONLY);
232 len = lseek(fd, (off_t) 0, SEEK_END);
233 lseek(fd, (off_t) 0, SEEK_SET);
235 buffer_init(&buffer);
236 buffer_append_space(&buffer, &cp, len);
238 if (read(fd, cp, (size_t) len) != (size_t) len) {
239 debug("Read from key file %.200s failed: %.100s", filename,
241 buffer_free(&buffer);
247 /* Check that it is at least big enought to contain the ID string. */
248 if (len < strlen(AUTHFILE_ID_STRING) + 1) {
249 debug("Bad key file %.200s.", filename);
250 buffer_free(&buffer);
254 * Make sure it begins with the id string. Consume the id string
257 for (i = 0; i < (unsigned int) strlen(AUTHFILE_ID_STRING) + 1; i++)
258 if (buffer_get_char(&buffer) != (u_char) AUTHFILE_ID_STRING[i]) {
259 debug("Bad key file %.200s.", filename);
260 buffer_free(&buffer);
263 /* Skip cipher type and reserved data. */
264 (void) buffer_get_char(&buffer); /* cipher type */
265 (void) buffer_get_int(&buffer); /* reserved */
267 /* Read the public key from the buffer. */
268 buffer_get_int(&buffer);
272 buffer_get_bignum(&buffer, pub->n);
276 buffer_get_bignum(&buffer, pub->e);
278 *comment_return = buffer_get_string(&buffer, NULL);
279 /* The encrypted private part is not parsed by this function. */
281 buffer_free(&buffer);
286 /* load public key from private-key file */
288 load_public_key(const char *filename, Key * key, char **comment_return)
292 return load_public_key_rsa(filename, key->rsa, comment_return);
302 * Loads the private key from the file. Returns 0 if an error is encountered
303 * (file does not exist or is not readable, or passphrase is bad). This
304 * initializes the private key.
305 * Assumes we are called under uid of the owner of the file.
309 load_private_key_rsa(int fd, const char *filename,
310 const char *passphrase, RSA * prv, char **comment_return)
312 int i, check1, check2, cipher_type;
314 Buffer buffer, decrypted;
316 CipherContext cipher;
320 len = lseek(fd, (off_t) 0, SEEK_END);
321 lseek(fd, (off_t) 0, SEEK_SET);
323 buffer_init(&buffer);
324 buffer_append_space(&buffer, &cp, len);
326 if (read(fd, cp, (size_t) len) != (size_t) len) {
327 debug("Read from key file %.200s failed: %.100s", filename,
329 buffer_free(&buffer);
335 /* Check that it is at least big enought to contain the ID string. */
336 if (len < strlen(AUTHFILE_ID_STRING) + 1) {
337 debug("Bad key file %.200s.", filename);
338 buffer_free(&buffer);
342 * Make sure it begins with the id string. Consume the id string
345 for (i = 0; i < (unsigned int) strlen(AUTHFILE_ID_STRING) + 1; i++)
346 if (buffer_get_char(&buffer) != (unsigned char) AUTHFILE_ID_STRING[i]) {
347 debug("Bad key file %.200s.", filename);
348 buffer_free(&buffer);
351 /* Read cipher type. */
352 cipher_type = buffer_get_char(&buffer);
353 (void) buffer_get_int(&buffer); /* Reserved data. */
355 /* Read the public key from the buffer. */
356 buffer_get_int(&buffer);
358 buffer_get_bignum(&buffer, prv->n);
360 buffer_get_bignum(&buffer, prv->e);
362 *comment_return = buffer_get_string(&buffer, NULL);
364 xfree(buffer_get_string(&buffer, NULL));
366 /* Check that it is a supported cipher. */
367 if (((cipher_mask1() | SSH_CIPHER_NONE | SSH_AUTHFILE_CIPHER) &
368 (1 << cipher_type)) == 0) {
369 debug("Unsupported cipher %.100s used in key file %.200s.",
370 cipher_name(cipher_type), filename);
371 buffer_free(&buffer);
374 /* Initialize space for decrypted data. */
375 buffer_init(&decrypted);
376 buffer_append_space(&decrypted, &cp, buffer_len(&buffer));
378 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
379 cipher_set_key_string(&cipher, cipher_type, passphrase);
380 cipher_decrypt(&cipher, (unsigned char *) cp,
381 (unsigned char *) buffer_ptr(&buffer),
382 buffer_len(&buffer));
384 buffer_free(&buffer);
386 check1 = buffer_get_char(&decrypted);
387 check2 = buffer_get_char(&decrypted);
388 if (check1 != buffer_get_char(&decrypted) ||
389 check2 != buffer_get_char(&decrypted)) {
390 if (strcmp(passphrase, "") != 0)
391 debug("Bad passphrase supplied for key file %.200s.", filename);
392 /* Bad passphrase. */
393 buffer_free(&decrypted);
395 BN_clear_free(prv->n);
397 BN_clear_free(prv->e);
400 xfree(*comment_return);
403 /* Read the rest of the private key. */
405 buffer_get_bignum(&decrypted, prv->d);
406 prv->iqmp = BN_new();
407 buffer_get_bignum(&decrypted, prv->iqmp); /* u */
408 /* in SSL and SSH p and q are exchanged */
410 buffer_get_bignum(&decrypted, prv->q); /* p */
412 buffer_get_bignum(&decrypted, prv->p); /* q */
417 BN_sub(aux, prv->q, BN_value_one());
418 prv->dmq1 = BN_new();
419 BN_mod(prv->dmq1, prv->d, aux, ctx);
421 BN_sub(aux, prv->p, BN_value_one());
422 prv->dmp1 = BN_new();
423 BN_mod(prv->dmp1, prv->d, aux, ctx);
428 buffer_free(&decrypted);
434 load_private_key_dsa(int fd, const char *passphrase, Key *k, char **comment_return)
440 in = BIO_new(BIO_s_file());
442 error("BIO_new failed");
445 fp = fdopen(fd, "r");
447 error("fdopen failed");
450 BIO_set_fp(in, fp, BIO_NOCLOSE);
451 dsa = PEM_read_bio_DSAPrivateKey(in, NULL, NULL, (char *)passphrase);
453 debug("PEM_read_bio_DSAPrivateKey failed");
455 /* replace k->dsa with loaded key */
462 *comment_return = xstrdup("dsa w/o comment");
463 debug("read DSA private key done");
465 DSA_print_fp(stderr, dsa, 8);
467 return dsa != NULL ? 1 : 0;
471 load_private_key(const char *filename, const char *passphrase, Key *key,
472 char **comment_return)
478 fd = open(filename, O_RDONLY);
484 * check owner and modes.
485 * This won't work on Windows under all circumstances so we drop
486 * that check for now.
488 if (fstat(fd, &st) < 0 ||
489 (st.st_uid != 0 && st.st_uid != getuid()) ||
490 (st.st_mode & 077) != 0) {
492 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
493 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
494 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
495 error("Bad ownership or mode(0%3.3o) for '%s'.",
496 st.st_mode & 0777, filename);
497 error("It is recommended that your private key files are NOT accessible by others.");
503 if (key->rsa->e != NULL) {
504 BN_clear_free(key->rsa->e);
507 if (key->rsa->n != NULL) {
508 BN_clear_free(key->rsa->n);
511 ret = load_private_key_rsa(fd, filename, passphrase,
512 key->rsa, comment_return);
515 ret = load_private_key_dsa(fd, passphrase, key, comment_return);
524 do_load_public_key(const char *filename, Key *k, char **commentp)
531 f = fopen(filename, "r");
533 while (fgets(line, sizeof(line), f)) {
534 line[sizeof(line)-1] = '\0';
542 /* Skip leading whitespace. */
543 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
546 bits = key_read(k, &cp);
549 *commentp=xstrdup(filename);
560 /* load public key from pubkey file */
562 try_load_public_key(const char *filename, Key *k, char **commentp)
564 char pub[MAXPATHLEN];
566 if (do_load_public_key(filename, k, commentp) == 1)
568 if (strlcpy(pub, filename, sizeof pub) >= MAXPATHLEN)
570 if (strlcat(pub, ".pub", sizeof pub) >= MAXPATHLEN)
572 if (do_load_public_key(pub, k, commentp) == 1)