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.20 2000/10/11 20:27:23 markus Exp $");
42 #include <openssl/bn.h>
43 #include <openssl/dsa.h>
44 #include <openssl/rsa.h>
45 #include <openssl/pem.h>
46 #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;
71 CipherContext ciphercontext;
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 = cipher_by_number(SSH_CIPHER_NONE);
82 cipher = cipher_by_number(SSH_AUTHFILE_CIPHER);
84 fatal("save_private_key_rsa: bad cipher");
86 /* This buffer is used to built the secret part of the private key. */
89 /* Put checkbytes for checking passphrase validity. */
92 buf[1] = (rand >> 8) & 0xff;
95 buffer_append(&buffer, buf, 4);
98 * Store the private key (n and e will not be stored because they
99 * will be stored in plain text, and storing them also in encrypted
100 * format would just give known plaintext).
102 buffer_put_bignum(&buffer, key->d);
103 buffer_put_bignum(&buffer, key->iqmp);
104 buffer_put_bignum(&buffer, key->q); /* reverse from SSL p */
105 buffer_put_bignum(&buffer, key->p); /* reverse from SSL q */
107 /* Pad the part to be encrypted until its size is a multiple of 8. */
108 while (buffer_len(&buffer) % 8 != 0)
109 buffer_put_char(&buffer, 0);
111 /* This buffer will be used to contain the data in the file. */
112 buffer_init(&encrypted);
114 /* First store keyfile id string. */
115 cp = AUTHFILE_ID_STRING;
116 for (i = 0; cp[i]; i++)
117 buffer_put_char(&encrypted, cp[i]);
118 buffer_put_char(&encrypted, 0);
120 /* Store cipher type. */
121 buffer_put_char(&encrypted, cipher->number);
122 buffer_put_int(&encrypted, 0); /* For future extension */
124 /* Store public key. This will be in plain text. */
125 buffer_put_int(&encrypted, BN_num_bits(key->n));
126 buffer_put_bignum(&encrypted, key->n);
127 buffer_put_bignum(&encrypted, key->e);
128 buffer_put_string(&encrypted, comment, strlen(comment));
130 /* Allocate space for the private part of the key in the buffer. */
131 buffer_append_space(&encrypted, &cp, buffer_len(&buffer));
133 cipher_set_key_string(&ciphercontext, cipher, passphrase);
134 cipher_encrypt(&ciphercontext, (unsigned char *) cp,
135 (unsigned char *) buffer_ptr(&buffer), buffer_len(&buffer));
136 memset(&ciphercontext, 0, sizeof(ciphercontext));
138 /* Destroy temporary data. */
139 memset(buf, 0, sizeof(buf));
140 buffer_free(&buffer);
142 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
145 if (write(fd, buffer_ptr(&encrypted), buffer_len(&encrypted)) !=
146 buffer_len(&encrypted)) {
147 debug("Write to key file %.200s failed: %.100s", filename,
149 buffer_free(&encrypted);
155 buffer_free(&encrypted);
159 /* save DSA key in OpenSSL PEM format */
162 save_private_key_dsa(const char *filename, const char *passphrase,
163 DSA *dsa, const char *comment)
168 int len = strlen(passphrase);
170 if (len > 0 && len <= 4) {
171 error("passphrase too short: %d bytes", len);
175 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
177 debug("open %s failed", filename);
180 fp = fdopen(fd, "w");
182 debug("fdopen %s failed", filename);
187 if (!PEM_write_DSAPrivateKey(fp, dsa, EVP_des_ede3_cbc(),
188 (char *)passphrase, strlen(passphrase), NULL, NULL))
191 if (!PEM_write_DSAPrivateKey(fp, dsa, NULL,
192 NULL, 0, NULL, NULL))
200 save_private_key(const char *filename, const char *passphrase, Key *key,
205 return save_private_key_rsa(filename, passphrase, key->rsa, comment);
208 return save_private_key_dsa(filename, passphrase, key->dsa, comment);
217 * Loads the public part of the key file. Returns 0 if an error was
218 * encountered (the file does not exist or is not readable), and non-zero
223 load_public_key_rsa(const char *filename, RSA * pub, char **comment_return)
230 fd = open(filename, O_RDONLY);
233 len = lseek(fd, (off_t) 0, SEEK_END);
234 lseek(fd, (off_t) 0, SEEK_SET);
236 buffer_init(&buffer);
237 buffer_append_space(&buffer, &cp, len);
239 if (read(fd, cp, (size_t) len) != (size_t) len) {
240 debug("Read from key file %.200s failed: %.100s", filename,
242 buffer_free(&buffer);
248 /* Check that it is at least big enought to contain the ID string. */
249 if (len < strlen(AUTHFILE_ID_STRING) + 1) {
250 debug("Bad key file %.200s.", filename);
251 buffer_free(&buffer);
255 * Make sure it begins with the id string. Consume the id string
258 for (i = 0; i < (unsigned int) strlen(AUTHFILE_ID_STRING) + 1; i++)
259 if (buffer_get_char(&buffer) != (u_char) AUTHFILE_ID_STRING[i]) {
260 debug("Bad key file %.200s.", filename);
261 buffer_free(&buffer);
264 /* Skip cipher type and reserved data. */
265 (void) buffer_get_char(&buffer); /* cipher type */
266 (void) buffer_get_int(&buffer); /* reserved */
268 /* Read the public key from the buffer. */
269 buffer_get_int(&buffer);
273 buffer_get_bignum(&buffer, pub->n);
277 buffer_get_bignum(&buffer, pub->e);
279 *comment_return = buffer_get_string(&buffer, NULL);
280 /* The encrypted private part is not parsed by this function. */
282 buffer_free(&buffer);
287 /* load public key from private-key file */
289 load_public_key(const char *filename, Key * key, char **comment_return)
293 return load_public_key_rsa(filename, key->rsa, comment_return);
303 * Loads the private key from the file. Returns 0 if an error is encountered
304 * (file does not exist or is not readable, or passphrase is bad). This
305 * initializes the private key.
306 * Assumes we are called under uid of the owner of the file.
310 load_private_key_rsa(int fd, const char *filename,
311 const char *passphrase, RSA * prv, char **comment_return)
313 int i, check1, check2, cipher_type;
315 Buffer buffer, decrypted;
317 CipherContext ciphercontext;
322 len = lseek(fd, (off_t) 0, SEEK_END);
323 lseek(fd, (off_t) 0, SEEK_SET);
325 buffer_init(&buffer);
326 buffer_append_space(&buffer, &cp, len);
328 if (read(fd, cp, (size_t) len) != (size_t) len) {
329 debug("Read from key file %.200s failed: %.100s", filename,
331 buffer_free(&buffer);
337 /* Check that it is at least big enought to contain the ID string. */
338 if (len < strlen(AUTHFILE_ID_STRING) + 1) {
339 debug("Bad key file %.200s.", filename);
340 buffer_free(&buffer);
344 * Make sure it begins with the id string. Consume the id string
347 for (i = 0; i < (unsigned int) strlen(AUTHFILE_ID_STRING) + 1; i++)
348 if (buffer_get_char(&buffer) != (unsigned char) AUTHFILE_ID_STRING[i]) {
349 debug("Bad key file %.200s.", filename);
350 buffer_free(&buffer);
353 /* Read cipher type. */
354 cipher_type = buffer_get_char(&buffer);
355 (void) buffer_get_int(&buffer); /* Reserved data. */
357 /* Read the public key from the buffer. */
358 buffer_get_int(&buffer);
360 buffer_get_bignum(&buffer, prv->n);
362 buffer_get_bignum(&buffer, prv->e);
364 *comment_return = buffer_get_string(&buffer, NULL);
366 xfree(buffer_get_string(&buffer, NULL));
368 /* Check that it is a supported cipher. */
369 cipher = cipher_by_number(cipher_type);
370 if (cipher == NULL) {
371 debug("Unsupported cipher %d used in key file %.200s.",
372 cipher_type, filename);
373 buffer_free(&buffer);
376 /* Initialize space for decrypted data. */
377 buffer_init(&decrypted);
378 buffer_append_space(&decrypted, &cp, buffer_len(&buffer));
380 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
381 cipher_set_key_string(&ciphercontext, cipher, passphrase);
382 cipher_decrypt(&ciphercontext, (unsigned char *) cp,
383 (unsigned char *) buffer_ptr(&buffer), buffer_len(&buffer));
384 memset(&ciphercontext, 0, sizeof(ciphercontext));
385 buffer_free(&buffer);
387 check1 = buffer_get_char(&decrypted);
388 check2 = buffer_get_char(&decrypted);
389 if (check1 != buffer_get_char(&decrypted) ||
390 check2 != buffer_get_char(&decrypted)) {
391 if (strcmp(passphrase, "") != 0)
392 debug("Bad passphrase supplied for key file %.200s.", filename);
393 /* Bad passphrase. */
394 buffer_free(&decrypted);
396 BN_clear_free(prv->n);
398 BN_clear_free(prv->e);
401 xfree(*comment_return);
404 /* Read the rest of the private key. */
406 buffer_get_bignum(&decrypted, prv->d);
407 prv->iqmp = BN_new();
408 buffer_get_bignum(&decrypted, prv->iqmp); /* u */
409 /* in SSL and SSH p and q are exchanged */
411 buffer_get_bignum(&decrypted, prv->q); /* p */
413 buffer_get_bignum(&decrypted, prv->p); /* q */
418 BN_sub(aux, prv->q, BN_value_one());
419 prv->dmq1 = BN_new();
420 BN_mod(prv->dmq1, prv->d, aux, ctx);
422 BN_sub(aux, prv->p, BN_value_one());
423 prv->dmp1 = BN_new();
424 BN_mod(prv->dmp1, prv->d, aux, ctx);
429 buffer_free(&decrypted);
435 load_private_key_dsa(int fd, const char *passphrase, Key *k, char **comment_return)
441 in = BIO_new(BIO_s_file());
443 error("BIO_new failed");
446 fp = fdopen(fd, "r");
448 error("fdopen failed");
451 BIO_set_fp(in, fp, BIO_NOCLOSE);
452 dsa = PEM_read_bio_DSAPrivateKey(in, NULL, NULL, (char *)passphrase);
454 debug("PEM_read_bio_DSAPrivateKey failed");
456 /* replace k->dsa with loaded key */
463 *comment_return = xstrdup("dsa w/o comment");
464 debug("read DSA private key done");
466 DSA_print_fp(stderr, dsa, 8);
468 return dsa != NULL ? 1 : 0;
472 load_private_key(const char *filename, const char *passphrase, Key *key,
473 char **comment_return)
479 fd = open(filename, O_RDONLY);
483 /* check owner and modes */
484 if (fstat(fd, &st) < 0 ||
485 (st.st_uid != 0 && st.st_uid != getuid()) ||
486 (st.st_mode & 077) != 0) {
488 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
489 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
490 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
491 error("Bad ownership or mode(0%3.3o) for '%s'.",
492 st.st_mode & 0777, filename);
493 error("It is recommended that your private key files are NOT accessible by others.");
498 if (key->rsa->e != NULL) {
499 BN_clear_free(key->rsa->e);
502 if (key->rsa->n != NULL) {
503 BN_clear_free(key->rsa->n);
506 ret = load_private_key_rsa(fd, filename, passphrase,
507 key->rsa, comment_return);
510 ret = load_private_key_dsa(fd, passphrase, key, comment_return);
519 do_load_public_key(const char *filename, Key *k, char **commentp)
526 f = fopen(filename, "r");
528 while (fgets(line, sizeof(line), f)) {
529 line[sizeof(line)-1] = '\0';
537 /* Skip leading whitespace. */
538 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
541 bits = key_read(k, &cp);
544 *commentp=xstrdup(filename);
555 /* load public key from pubkey file */
557 try_load_public_key(const char *filename, Key *k, char **commentp)
559 char pub[MAXPATHLEN];
561 if (do_load_public_key(filename, k, commentp) == 1)
563 if (strlcpy(pub, filename, sizeof pub) >= MAXPATHLEN)
565 if (strlcat(pub, ".pub", sizeof pub) >= MAXPATHLEN)
567 if (do_load_public_key(pub, k, commentp) == 1)