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.26 2001/01/28 22:27:05 stevesk Exp $");
41 #include <openssl/err.h>
42 #include <openssl/evp.h>
43 #include <openssl/pem.h>
53 /* Version identification string for identity files. */
54 static const char authfile_id_string[] =
55 "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_rsa1(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 for (i = 0; authfile_id_string[i]; i++)
116 buffer_put_char(&encrypted, authfile_id_string[i]);
117 buffer_put_char(&encrypted, 0);
119 /* Store cipher type. */
120 buffer_put_char(&encrypted, cipher->number);
121 buffer_put_int(&encrypted, 0); /* For future extension */
123 /* Store public key. This will be in plain text. */
124 buffer_put_int(&encrypted, BN_num_bits(key->n));
125 buffer_put_bignum(&encrypted, key->n);
126 buffer_put_bignum(&encrypted, key->e);
127 buffer_put_string(&encrypted, comment, strlen(comment));
129 /* Allocate space for the private part of the key in the buffer. */
130 buffer_append_space(&encrypted, &cp, buffer_len(&buffer));
132 cipher_set_key_string(&ciphercontext, cipher, passphrase);
133 cipher_encrypt(&ciphercontext, (u_char *) cp,
134 (u_char *) buffer_ptr(&buffer), buffer_len(&buffer));
135 memset(&ciphercontext, 0, sizeof(ciphercontext));
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 SSH2 key in OpenSSL PEM format */
160 save_private_key_ssh2(const char *filename, const char *_passphrase,
161 Key *key, const char *comment)
166 int len = strlen(_passphrase);
167 char *passphrase = (len > 0) ? (char *)_passphrase : NULL;
168 EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
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);
188 success = PEM_write_DSAPrivateKey(fp, key->dsa,
189 cipher, passphrase, len, NULL, NULL);
192 success = PEM_write_RSAPrivateKey(fp, key->rsa,
193 cipher, passphrase, len, NULL, NULL);
201 save_private_key(const char *filename, const char *passphrase, Key *key,
206 return save_private_key_rsa1(filename, passphrase, key->rsa, comment);
210 return save_private_key_ssh2(filename, passphrase, key, comment);
219 * Loads the public part of the key file. Returns 0 if an error was
220 * encountered (the file does not exist or is not readable), and non-zero
225 load_public_key_rsa(const char *filename, RSA * pub, char **comment_return)
232 fd = open(filename, O_RDONLY);
235 len = lseek(fd, (off_t) 0, SEEK_END);
236 lseek(fd, (off_t) 0, SEEK_SET);
238 buffer_init(&buffer);
239 buffer_append_space(&buffer, &cp, len);
241 if (read(fd, cp, (size_t) len) != (size_t) len) {
242 debug("Read from key file %.200s failed: %.100s", filename,
244 buffer_free(&buffer);
250 /* Check that it is at least big enough to contain the ID string. */
251 if (len < sizeof(authfile_id_string)) {
252 debug3("Bad RSA1 key file %.200s.", filename);
253 buffer_free(&buffer);
257 * Make sure it begins with the id string. Consume the id string
260 for (i = 0; i < sizeof(authfile_id_string); i++)
261 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
262 debug3("Bad RSA1 key file %.200s.", filename);
263 buffer_free(&buffer);
266 /* Skip cipher type and reserved data. */
267 (void) buffer_get_char(&buffer); /* cipher type */
268 (void) buffer_get_int(&buffer); /* reserved */
270 /* Read the public key from the buffer. */
271 buffer_get_int(&buffer);
275 buffer_get_bignum(&buffer, pub->n);
279 buffer_get_bignum(&buffer, pub->e);
281 *comment_return = buffer_get_string(&buffer, NULL);
282 /* The encrypted private part is not parsed by this function. */
284 buffer_free(&buffer);
289 /* load public key from private-key file */
291 load_public_key(const char *filename, Key * key, char **comment_return)
295 return load_public_key_rsa(filename, key->rsa, comment_return);
306 * Loads the private key from the file. Returns 0 if an error is encountered
307 * (file does not exist or is not readable, or passphrase is bad). This
308 * initializes the private key.
309 * Assumes we are called under uid of the owner of the file.
313 load_private_key_rsa1(int fd, const char *filename,
314 const char *passphrase, RSA * prv, char **comment_return)
316 int i, check1, check2, cipher_type;
318 Buffer buffer, decrypted;
320 CipherContext ciphercontext;
325 len = lseek(fd, (off_t) 0, SEEK_END);
326 lseek(fd, (off_t) 0, SEEK_SET);
328 buffer_init(&buffer);
329 buffer_append_space(&buffer, &cp, len);
331 if (read(fd, cp, (size_t) len) != (size_t) len) {
332 debug("Read from key file %.200s failed: %.100s", filename,
334 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);
347 * Make sure it begins with the id string. Consume the id string
350 for (i = 0; i < sizeof(authfile_id_string); i++)
351 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
352 debug3("Bad RSA1 key file %.200s.", filename);
353 buffer_free(&buffer);
356 /* Read cipher type. */
357 cipher_type = buffer_get_char(&buffer);
358 (void) buffer_get_int(&buffer); /* Reserved data. */
360 /* Read the public key from the buffer. */
361 buffer_get_int(&buffer);
363 buffer_get_bignum(&buffer, prv->n);
365 buffer_get_bignum(&buffer, prv->e);
367 *comment_return = buffer_get_string(&buffer, NULL);
369 xfree(buffer_get_string(&buffer, NULL));
371 /* Check that it is a supported cipher. */
372 cipher = cipher_by_number(cipher_type);
373 if (cipher == NULL) {
374 debug("Unsupported cipher %d used in key file %.200s.",
375 cipher_type, filename);
376 buffer_free(&buffer);
379 /* Initialize space for decrypted data. */
380 buffer_init(&decrypted);
381 buffer_append_space(&decrypted, &cp, buffer_len(&buffer));
383 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
384 cipher_set_key_string(&ciphercontext, cipher, passphrase);
385 cipher_decrypt(&ciphercontext, (u_char *) cp,
386 (u_char *) buffer_ptr(&buffer), buffer_len(&buffer));
387 memset(&ciphercontext, 0, sizeof(ciphercontext));
388 buffer_free(&buffer);
390 check1 = buffer_get_char(&decrypted);
391 check2 = buffer_get_char(&decrypted);
392 if (check1 != buffer_get_char(&decrypted) ||
393 check2 != buffer_get_char(&decrypted)) {
394 if (strcmp(passphrase, "") != 0)
395 debug("Bad passphrase supplied for key file %.200s.", filename);
396 /* Bad passphrase. */
397 buffer_free(&decrypted);
399 BN_clear_free(prv->n);
401 BN_clear_free(prv->e);
404 xfree(*comment_return);
407 /* Read the rest of the private key. */
409 buffer_get_bignum(&decrypted, prv->d);
410 prv->iqmp = BN_new();
411 buffer_get_bignum(&decrypted, prv->iqmp); /* u */
412 /* in SSL and SSH p and q are exchanged */
414 buffer_get_bignum(&decrypted, prv->q); /* p */
416 buffer_get_bignum(&decrypted, prv->p); /* q */
421 BN_sub(aux, prv->q, BN_value_one());
422 prv->dmq1 = BN_new();
423 BN_mod(prv->dmq1, prv->d, aux, ctx);
425 BN_sub(aux, prv->p, BN_value_one());
426 prv->dmp1 = BN_new();
427 BN_mod(prv->dmp1, prv->d, aux, ctx);
432 buffer_free(&decrypted);
438 load_private_key_ssh2(int fd, const char *passphrase, Key *k, char **comment_return)
443 char *name = "<no key>";
445 fp = fdopen(fd, "r");
447 error("fdopen failed");
450 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
452 debug("PEM_read_PrivateKey failed");
453 (void)ERR_get_error();
454 } else if (pk->type == EVP_PKEY_RSA) {
455 /* replace k->rsa with loaded key */
456 if (k->type == KEY_RSA || k->type == KEY_UNSPEC) {
459 k->rsa = EVP_PKEY_get1_RSA(pk);
461 name = "rsa w/o comment";
464 RSA_print_fp(stderr, k->rsa, 8);
467 } else if (pk->type == EVP_PKEY_DSA) {
468 /* replace k->dsa with loaded key */
469 if (k->type == KEY_DSA || k->type == KEY_UNSPEC) {
472 k->dsa = EVP_PKEY_get1_DSA(pk);
474 name = "dsa w/o comment";
476 DSA_print_fp(stderr, k->dsa, 8);
481 error("PEM_read_PrivateKey: mismatch or "
482 "unknown EVP_PKEY save_type %d", pk->save_type);
487 if (success && comment_return)
488 *comment_return = xstrdup(name);
489 debug("read SSH2 private key done: name %s success %d", name, success);
494 load_private_key(const char *filename, const char *passphrase, Key *key,
495 char **comment_return)
501 fd = open(filename, O_RDONLY);
505 /* check owner and modes */
507 if (check_ntsec(filename))
509 if (fstat(fd, &st) < 0 ||
510 (st.st_uid != 0 && getuid() != 0 && st.st_uid != getuid()) ||
511 (st.st_mode & 077) != 0) {
513 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
514 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
515 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
516 error("Bad ownership or mode(0%3.3o) for '%s'.",
517 st.st_mode & 0777, filename);
518 error("It is recommended that your private key files are NOT accessible by others.");
523 if (key->rsa->e != NULL) {
524 BN_clear_free(key->rsa->e);
527 if (key->rsa->n != NULL) {
528 BN_clear_free(key->rsa->n);
531 ret = load_private_key_rsa1(fd, filename, passphrase,
532 key->rsa, comment_return);
537 ret = load_private_key_ssh2(fd, passphrase, key, comment_return);
546 do_load_public_key(const char *filename, Key *k, char **commentp)
552 f = fopen(filename, "r");
554 while (fgets(line, sizeof(line), f)) {
555 line[sizeof(line)-1] = '\0';
563 /* Skip leading whitespace. */
564 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
567 if (key_read(k, &cp) == 1) {
569 *commentp=xstrdup(filename);
580 /* load public key from pubkey file */
582 try_load_public_key(const char *filename, Key *k, char **commentp)
584 char pub[MAXPATHLEN];
586 if (do_load_public_key(filename, k, commentp) == 1)
588 if (strlcpy(pub, filename, sizeof pub) >= MAXPATHLEN)
590 if (strlcat(pub, ".pub", sizeof pub) >= MAXPATHLEN)
592 if (do_load_public_key(pub, k, commentp) == 1)