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.28 2001/02/21 09:05:54 deraadt Exp $");
41 #include <openssl/err.h>
42 #include <openssl/evp.h>
43 #include <openssl/pem.h>
54 /* Version identification string for identity files. */
55 static const char authfile_id_string[] =
56 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
59 * Saves the authentication (private) key in a file, encrypting it with
60 * passphrase. The identification of the file (lowest 64 bits of n) will
61 * precede the key to provide identification of the key without needing a
66 save_private_key_rsa1(const char *filename, const char *passphrase,
67 RSA *key, const char *comment)
69 Buffer buffer, encrypted;
72 CipherContext ciphercontext;
77 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
78 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
80 if (strcmp(passphrase, "") == 0)
81 cipher = cipher_by_number(SSH_CIPHER_NONE);
83 cipher = cipher_by_number(SSH_AUTHFILE_CIPHER);
85 fatal("save_private_key_rsa: bad cipher");
87 /* This buffer is used to built the secret part of the private key. */
90 /* Put checkbytes for checking passphrase validity. */
93 buf[1] = (rand >> 8) & 0xff;
96 buffer_append(&buffer, buf, 4);
99 * Store the private key (n and e will not be stored because they
100 * will be stored in plain text, and storing them also in encrypted
101 * format would just give known plaintext).
103 buffer_put_bignum(&buffer, key->d);
104 buffer_put_bignum(&buffer, key->iqmp);
105 buffer_put_bignum(&buffer, key->q); /* reverse from SSL p */
106 buffer_put_bignum(&buffer, key->p); /* reverse from SSL q */
108 /* Pad the part to be encrypted until its size is a multiple of 8. */
109 while (buffer_len(&buffer) % 8 != 0)
110 buffer_put_char(&buffer, 0);
112 /* This buffer will be used to contain the data in the file. */
113 buffer_init(&encrypted);
115 /* First store keyfile id string. */
116 for (i = 0; authfile_id_string[i]; i++)
117 buffer_put_char(&encrypted, authfile_id_string[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, (u_char *) cp,
135 (u_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 SSH2 key in OpenSSL PEM format */
161 save_private_key_ssh2(const char *filename, const char *_passphrase,
162 Key *key, const char *comment)
167 int len = strlen(_passphrase);
168 char *passphrase = (len > 0) ? (char *)_passphrase : NULL;
169 EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
171 if (len > 0 && len <= 4) {
172 error("passphrase too short: %d bytes", len);
176 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
178 debug("open %s failed", filename);
181 fp = fdopen(fd, "w");
183 debug("fdopen %s failed", filename);
189 success = PEM_write_DSAPrivateKey(fp, key->dsa,
190 cipher, passphrase, len, NULL, NULL);
193 success = PEM_write_RSAPrivateKey(fp, key->rsa,
194 cipher, passphrase, len, NULL, NULL);
202 save_private_key(const char *filename, const char *passphrase, Key *key,
207 return save_private_key_rsa1(filename, passphrase, key->rsa, comment);
211 return save_private_key_ssh2(filename, passphrase, key, comment);
220 * Loads the public part of the key file. Returns 0 if an error was
221 * encountered (the file does not exist or is not readable), and non-zero
226 load_public_key_rsa(const char *filename, RSA * pub, char **comment_return)
233 fd = open(filename, O_RDONLY);
236 len = lseek(fd, (off_t) 0, SEEK_END);
237 lseek(fd, (off_t) 0, SEEK_SET);
239 buffer_init(&buffer);
240 buffer_append_space(&buffer, &cp, len);
242 if (read(fd, cp, (size_t) len) != (size_t) len) {
243 debug("Read from key file %.200s failed: %.100s", filename,
245 buffer_free(&buffer);
251 /* Check that it is at least big enough to contain the ID string. */
252 if (len < sizeof(authfile_id_string)) {
253 debug3("Bad RSA1 key file %.200s.", filename);
254 buffer_free(&buffer);
258 * Make sure it begins with the id string. Consume the id string
261 for (i = 0; i < sizeof(authfile_id_string); i++)
262 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
263 debug3("Bad RSA1 key file %.200s.", filename);
264 buffer_free(&buffer);
267 /* Skip cipher type and reserved data. */
268 (void) buffer_get_char(&buffer); /* cipher type */
269 (void) buffer_get_int(&buffer); /* reserved */
271 /* Read the public key from the buffer. */
272 buffer_get_int(&buffer);
276 buffer_get_bignum(&buffer, pub->n);
280 buffer_get_bignum(&buffer, pub->e);
282 *comment_return = buffer_get_string(&buffer, NULL);
283 /* The encrypted private part is not parsed by this function. */
285 buffer_free(&buffer);
290 /* load public key from private-key file */
292 load_public_key(const char *filename, Key * key, char **comment_return)
296 return load_public_key_rsa(filename, key->rsa, comment_return);
307 * Loads the private key from the file. Returns 0 if an error is encountered
308 * (file does not exist or is not readable, or passphrase is bad). This
309 * initializes the private key.
310 * Assumes we are called under uid of the owner of the file.
314 load_private_key_rsa1(int fd, const char *filename,
315 const char *passphrase, RSA * prv, char **comment_return)
317 int i, check1, check2, cipher_type;
319 Buffer buffer, decrypted;
321 CipherContext ciphercontext;
326 len = lseek(fd, (off_t) 0, SEEK_END);
327 lseek(fd, (off_t) 0, SEEK_SET);
329 buffer_init(&buffer);
330 buffer_append_space(&buffer, &cp, len);
332 if (read(fd, cp, (size_t) len) != (size_t) len) {
333 debug("Read from key file %.200s failed: %.100s", filename,
335 buffer_free(&buffer);
340 /* Check that it is at least big enough to contain the ID string. */
341 if (len < sizeof(authfile_id_string)) {
342 debug3("Bad RSA1 key file %.200s.", filename);
343 buffer_free(&buffer);
348 * Make sure it begins with the id string. Consume the id string
351 for (i = 0; i < sizeof(authfile_id_string); i++)
352 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
353 debug3("Bad RSA1 key file %.200s.", filename);
354 buffer_free(&buffer);
359 /* Read cipher type. */
360 cipher_type = buffer_get_char(&buffer);
361 (void) buffer_get_int(&buffer); /* Reserved data. */
363 /* Read the public key from the buffer. */
364 buffer_get_int(&buffer);
366 buffer_get_bignum(&buffer, prv->n);
368 buffer_get_bignum(&buffer, prv->e);
370 *comment_return = buffer_get_string(&buffer, NULL);
372 xfree(buffer_get_string(&buffer, NULL));
374 /* Check that it is a supported cipher. */
375 cipher = cipher_by_number(cipher_type);
376 if (cipher == NULL) {
377 debug("Unsupported cipher %d used in key file %.200s.",
378 cipher_type, filename);
379 buffer_free(&buffer);
382 /* Initialize space for decrypted data. */
383 buffer_init(&decrypted);
384 buffer_append_space(&decrypted, &cp, buffer_len(&buffer));
386 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
387 cipher_set_key_string(&ciphercontext, cipher, passphrase);
388 cipher_decrypt(&ciphercontext, (u_char *) cp,
389 (u_char *) buffer_ptr(&buffer), buffer_len(&buffer));
390 memset(&ciphercontext, 0, sizeof(ciphercontext));
391 buffer_free(&buffer);
393 check1 = buffer_get_char(&decrypted);
394 check2 = buffer_get_char(&decrypted);
395 if (check1 != buffer_get_char(&decrypted) ||
396 check2 != buffer_get_char(&decrypted)) {
397 if (strcmp(passphrase, "") != 0)
398 debug("Bad passphrase supplied for key file %.200s.", filename);
399 /* Bad passphrase. */
400 buffer_free(&decrypted);
402 BN_clear_free(prv->n);
404 BN_clear_free(prv->e);
407 xfree(*comment_return);
411 /* Read the rest of the private key. */
413 buffer_get_bignum(&decrypted, prv->d);
414 prv->iqmp = BN_new();
415 buffer_get_bignum(&decrypted, prv->iqmp); /* u */
416 /* in SSL and SSH p and q are exchanged */
418 buffer_get_bignum(&decrypted, prv->q); /* p */
420 buffer_get_bignum(&decrypted, prv->p); /* q */
425 BN_sub(aux, prv->q, BN_value_one());
426 prv->dmq1 = BN_new();
427 BN_mod(prv->dmq1, prv->d, aux, ctx);
429 BN_sub(aux, prv->p, BN_value_one());
430 prv->dmp1 = BN_new();
431 BN_mod(prv->dmp1, prv->d, aux, ctx);
436 buffer_free(&decrypted);
442 load_private_key_ssh2(int fd, const char *passphrase, Key *k, char **comment_return)
447 char *name = "<no key>";
449 fp = fdopen(fd, "r");
451 error("fdopen failed");
455 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
457 debug("PEM_read_PrivateKey failed");
458 (void)ERR_get_error();
459 } else if (pk->type == EVP_PKEY_RSA) {
460 /* replace k->rsa with loaded key */
461 if (k->type == KEY_RSA || k->type == KEY_UNSPEC) {
464 k->rsa = EVP_PKEY_get1_RSA(pk);
466 name = "rsa w/o comment";
469 RSA_print_fp(stderr, k->rsa, 8);
472 } else if (pk->type == EVP_PKEY_DSA) {
473 /* replace k->dsa with loaded key */
474 if (k->type == KEY_DSA || k->type == KEY_UNSPEC) {
477 k->dsa = EVP_PKEY_get1_DSA(pk);
479 name = "dsa w/o comment";
481 DSA_print_fp(stderr, k->dsa, 8);
486 error("PEM_read_PrivateKey: mismatch or "
487 "unknown EVP_PKEY save_type %d", pk->save_type);
492 if (success && comment_return)
493 *comment_return = xstrdup(name);
494 debug("read SSH2 private key done: name %s success %d", name, success);
499 load_private_key(const char *filename, const char *passphrase, Key *key,
500 char **comment_return)
506 fd = open(filename, O_RDONLY);
510 /* check owner and modes */
512 if (check_ntsec(filename))
514 if (fstat(fd, &st) < 0 ||
515 (st.st_uid != 0 && getuid() != 0 && st.st_uid != getuid()) ||
516 (st.st_mode & 077) != 0) {
518 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
519 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
520 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
521 error("Bad ownership or mode(0%3.3o) for '%s'.",
522 st.st_mode & 0777, filename);
523 error("It is recommended that your private key files are NOT accessible by others.");
528 if (key->rsa->e != NULL) {
529 BN_clear_free(key->rsa->e);
532 if (key->rsa->n != NULL) {
533 BN_clear_free(key->rsa->n);
536 ret = load_private_key_rsa1(fd, filename, passphrase,
537 key->rsa, comment_return); /* closes fd */
543 ret = load_private_key_ssh2(fd, passphrase, key,
544 comment_return); /* closes fd */
554 do_load_public_key(const char *filename, Key *k, char **commentp)
560 f = fopen(filename, "r");
562 while (fgets(line, sizeof(line), f)) {
563 line[sizeof(line)-1] = '\0';
571 /* Skip leading whitespace. */
572 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
575 if (key_read(k, &cp) == 1) {
577 *commentp=xstrdup(filename);
588 /* load public key from pubkey file */
590 try_load_public_key(const char *filename, Key *k, char **commentp)
592 char pub[MAXPATHLEN];
594 if (do_load_public_key(filename, k, commentp) == 1)
596 if (strlcpy(pub, filename, sizeof pub) >= MAXPATHLEN)
598 if (strlcat(pub, ".pub", sizeof pub) >= MAXPATHLEN)
600 if (do_load_public_key(pub, k, commentp) == 1)