1 /* $OpenBSD: authfile.c,v 1.75 2006/08/01 23:36:11 stevesk 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>
45 #include <openssl/err.h>
46 #include <openssl/evp.h>
47 #include <openssl/pem.h>
68 /* Version identification string for SSH v1 identity files. */
69 static const char authfile_id_string[] =
70 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
73 * Saves the authentication (private) key in a file, encrypting it with
74 * passphrase. The identification of the file (lowest 64 bits of n) will
75 * precede the key to provide identification of the key without needing a
80 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
83 Buffer buffer, encrypted;
85 int fd, i, cipher_num;
86 CipherContext ciphercontext;
91 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
92 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
94 cipher_num = (strcmp(passphrase, "") == 0) ?
95 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
96 if ((cipher = cipher_by_number(cipher_num)) == NULL)
97 fatal("save_private_key_rsa: bad cipher");
99 /* This buffer is used to built the secret part of the private key. */
100 buffer_init(&buffer);
102 /* Put checkbytes for checking passphrase validity. */
105 buf[1] = (rnd >> 8) & 0xff;
108 buffer_append(&buffer, buf, 4);
111 * Store the private key (n and e will not be stored because they
112 * will be stored in plain text, and storing them also in encrypted
113 * format would just give known plaintext).
115 buffer_put_bignum(&buffer, key->rsa->d);
116 buffer_put_bignum(&buffer, key->rsa->iqmp);
117 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
118 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
120 /* Pad the part to be encrypted until its size is a multiple of 8. */
121 while (buffer_len(&buffer) % 8 != 0)
122 buffer_put_char(&buffer, 0);
124 /* This buffer will be used to contain the data in the file. */
125 buffer_init(&encrypted);
127 /* First store keyfile id string. */
128 for (i = 0; authfile_id_string[i]; i++)
129 buffer_put_char(&encrypted, authfile_id_string[i]);
130 buffer_put_char(&encrypted, 0);
132 /* Store cipher type. */
133 buffer_put_char(&encrypted, cipher_num);
134 buffer_put_int(&encrypted, 0); /* For future extension */
136 /* Store public key. This will be in plain text. */
137 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
138 buffer_put_bignum(&encrypted, key->rsa->n);
139 buffer_put_bignum(&encrypted, key->rsa->e);
140 buffer_put_cstring(&encrypted, comment);
142 /* Allocate space for the private part of the key in the buffer. */
143 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
145 cipher_set_key_string(&ciphercontext, cipher, passphrase,
147 cipher_crypt(&ciphercontext, cp,
148 buffer_ptr(&buffer), buffer_len(&buffer));
149 cipher_cleanup(&ciphercontext);
150 memset(&ciphercontext, 0, sizeof(ciphercontext));
152 /* Destroy temporary data. */
153 memset(buf, 0, sizeof(buf));
154 buffer_free(&buffer);
156 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
158 error("open %s failed: %s.", filename, strerror(errno));
159 buffer_free(&encrypted);
162 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
163 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
164 error("write to key file %s failed: %s", filename,
166 buffer_free(&encrypted);
172 buffer_free(&encrypted);
176 /* save SSH v2 key in OpenSSL PEM format */
178 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
184 int len = strlen(_passphrase);
185 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
186 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
188 if (len > 0 && len <= 4) {
189 error("passphrase too short: have %d bytes, need > 4", len);
192 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
194 error("open %s failed: %s.", filename, strerror(errno));
197 fp = fdopen(fd, "w");
199 error("fdopen %s failed: %s.", filename, strerror(errno));
205 success = PEM_write_DSAPrivateKey(fp, key->dsa,
206 cipher, passphrase, len, NULL, NULL);
209 success = PEM_write_RSAPrivateKey(fp, key->rsa,
210 cipher, passphrase, len, NULL, NULL);
218 key_save_private(Key *key, const char *filename, const char *passphrase,
223 return key_save_private_rsa1(key, filename, passphrase,
227 return key_save_private_pem(key, filename, passphrase,
232 error("key_save_private: cannot save key type %d", key->type);
237 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
238 * encountered (the file does not exist or is not readable), and the key
243 key_load_public_rsa1(int fd, const char *filename, char **commentp)
252 if (fstat(fd, &st) < 0) {
253 error("fstat for key file %.200s failed: %.100s",
254 filename, strerror(errno));
257 if (st.st_size > 1*1024*1024) {
258 error("key file %.200s too large", filename);
261 len = (size_t)st.st_size; /* truncated */
263 buffer_init(&buffer);
264 cp = buffer_append_space(&buffer, len);
266 if (atomicio(read, fd, cp, len) != len) {
267 debug("Read from key file %.200s failed: %.100s", filename,
269 buffer_free(&buffer);
273 /* Check that it is at least big enough to contain the ID string. */
274 if (len < sizeof(authfile_id_string)) {
275 debug3("Not a RSA1 key file %.200s.", filename);
276 buffer_free(&buffer);
280 * Make sure it begins with the id string. Consume the id string
283 for (i = 0; i < sizeof(authfile_id_string); i++)
284 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
285 debug3("Not a RSA1 key file %.200s.", filename);
286 buffer_free(&buffer);
289 /* Skip cipher type and reserved data. */
290 (void) buffer_get_char(&buffer); /* cipher type */
291 (void) buffer_get_int(&buffer); /* reserved */
293 /* Read the public key from the buffer. */
294 (void) buffer_get_int(&buffer);
295 pub = key_new(KEY_RSA1);
296 buffer_get_bignum(&buffer, pub->rsa->n);
297 buffer_get_bignum(&buffer, pub->rsa->e);
299 *commentp = buffer_get_string(&buffer, NULL);
300 /* The encrypted private part is not parsed by this function. */
302 buffer_free(&buffer);
306 /* load public key from private-key file, works only for SSH v1 */
308 key_load_public_type(int type, const char *filename, char **commentp)
313 if (type == KEY_RSA1) {
314 fd = open(filename, O_RDONLY);
317 pub = key_load_public_rsa1(fd, filename, commentp);
325 * Loads the private key from the file. Returns 0 if an error is encountered
326 * (file does not exist or is not readable, or passphrase is bad). This
327 * initializes the private key.
328 * Assumes we are called under uid of the owner of the file.
332 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
336 int check1, check2, cipher_type;
338 Buffer buffer, decrypted;
340 CipherContext ciphercontext;
345 if (fstat(fd, &st) < 0) {
346 error("fstat for key file %.200s failed: %.100s",
347 filename, strerror(errno));
351 if (st.st_size > 1*1024*1024) {
352 error("key file %.200s too large", filename);
356 len = (size_t)st.st_size; /* truncated */
358 buffer_init(&buffer);
359 cp = buffer_append_space(&buffer, len);
361 if (atomicio(read, fd, cp, len) != len) {
362 debug("Read from key file %.200s failed: %.100s", filename,
364 buffer_free(&buffer);
369 /* Check that it is at least big enough to contain the ID string. */
370 if (len < sizeof(authfile_id_string)) {
371 debug3("Not a RSA1 key file %.200s.", filename);
372 buffer_free(&buffer);
377 * Make sure it begins with the id string. Consume the id string
380 for (i = 0; i < sizeof(authfile_id_string); i++)
381 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
382 debug3("Not a RSA1 key file %.200s.", filename);
383 buffer_free(&buffer);
388 /* Read cipher type. */
389 cipher_type = buffer_get_char(&buffer);
390 (void) buffer_get_int(&buffer); /* Reserved data. */
392 /* Read the public key from the buffer. */
393 (void) buffer_get_int(&buffer);
394 prv = key_new_private(KEY_RSA1);
396 buffer_get_bignum(&buffer, prv->rsa->n);
397 buffer_get_bignum(&buffer, prv->rsa->e);
399 *commentp = buffer_get_string(&buffer, NULL);
401 xfree(buffer_get_string(&buffer, NULL));
403 /* Check that it is a supported cipher. */
404 cipher = cipher_by_number(cipher_type);
405 if (cipher == NULL) {
406 debug("Unsupported cipher %d used in key file %.200s.",
407 cipher_type, filename);
408 buffer_free(&buffer);
411 /* Initialize space for decrypted data. */
412 buffer_init(&decrypted);
413 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
415 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
416 cipher_set_key_string(&ciphercontext, cipher, passphrase,
418 cipher_crypt(&ciphercontext, cp,
419 buffer_ptr(&buffer), buffer_len(&buffer));
420 cipher_cleanup(&ciphercontext);
421 memset(&ciphercontext, 0, sizeof(ciphercontext));
422 buffer_free(&buffer);
424 check1 = buffer_get_char(&decrypted);
425 check2 = buffer_get_char(&decrypted);
426 if (check1 != buffer_get_char(&decrypted) ||
427 check2 != buffer_get_char(&decrypted)) {
428 if (strcmp(passphrase, "") != 0)
429 debug("Bad passphrase supplied for key file %.200s.",
431 /* Bad passphrase. */
432 buffer_free(&decrypted);
435 /* Read the rest of the private key. */
436 buffer_get_bignum(&decrypted, prv->rsa->d);
437 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
438 /* in SSL and SSH v1 p and q are exchanged */
439 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
440 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
442 /* calculate p-1 and q-1 */
443 rsa_generate_additional_parameters(prv->rsa);
445 buffer_free(&decrypted);
447 /* enable blinding */
448 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
449 error("key_load_private_rsa1: RSA_blinding_on failed");
464 key_load_private_pem(int fd, int type, const char *passphrase,
470 char *name = "<no key>";
472 fp = fdopen(fd, "r");
474 error("fdopen failed: %s", strerror(errno));
478 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
480 debug("PEM_read_PrivateKey failed");
481 (void)ERR_get_error();
482 } else if (pk->type == EVP_PKEY_RSA &&
483 (type == KEY_UNSPEC||type==KEY_RSA)) {
484 prv = key_new(KEY_UNSPEC);
485 prv->rsa = EVP_PKEY_get1_RSA(pk);
487 name = "rsa w/o comment";
489 RSA_print_fp(stderr, prv->rsa, 8);
491 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
492 error("key_load_private_pem: RSA_blinding_on failed");
496 } else if (pk->type == EVP_PKEY_DSA &&
497 (type == KEY_UNSPEC||type==KEY_DSA)) {
498 prv = key_new(KEY_UNSPEC);
499 prv->dsa = EVP_PKEY_get1_DSA(pk);
501 name = "dsa w/o comment";
503 DSA_print_fp(stderr, prv->dsa, 8);
506 error("PEM_read_PrivateKey: mismatch or "
507 "unknown EVP_PKEY save_type %d", pk->save_type);
512 if (prv != NULL && commentp)
513 *commentp = xstrdup(name);
514 debug("read PEM private key done: type %s",
515 prv ? key_type(prv) : "<unknown>");
520 key_perm_ok(int fd, const char *filename)
524 if (fstat(fd, &st) < 0)
527 * if a key owned by the user is accessed, then we check the
528 * permissions of the file. if the key owned by a different user,
529 * then we don't care.
532 if (check_ntsec(filename))
534 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
535 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
536 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
537 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
538 error("Permissions 0%3.3o for '%s' are too open.",
539 (u_int)st.st_mode & 0777, filename);
540 error("It is recommended that your private key files are NOT accessible by others.");
541 error("This private key will be ignored.");
548 key_load_private_type(int type, const char *filename, const char *passphrase,
549 char **commentp, int *perm_ok)
553 fd = open(filename, O_RDONLY);
556 if (!key_perm_ok(fd, filename)) {
559 error("bad permissions: ignore key: %s", filename);
567 return key_load_private_rsa1(fd, filename, passphrase,
573 return key_load_private_pem(fd, type, passphrase, commentp);
583 key_load_private(const char *filename, const char *passphrase,
589 fd = open(filename, O_RDONLY);
592 if (!key_perm_ok(fd, filename)) {
593 error("bad permissions: ignore key: %s", filename);
597 pub = key_load_public_rsa1(fd, filename, commentp);
598 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
601 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
602 /* use the filename as a comment for PEM */
604 *commentp = xstrdup(filename);
606 /* it's a SSH v1 key if the public key part is readable */
609 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
615 key_try_load_public(Key *k, const char *filename, char **commentp)
618 char line[SSH_MAX_PUBKEY_BYTES];
622 f = fopen(filename, "r");
624 while (read_keyfile_line(f, filename, line, sizeof(line),
633 /* Skip leading whitespace. */
634 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
637 if (key_read(k, &cp) == 1) {
639 *commentp=xstrdup(filename);
650 /* load public key from ssh v1 private or any pubkey file */
652 key_load_public(const char *filename, char **commentp)
655 char file[MAXPATHLEN];
657 /* try rsa1 private key */
658 pub = key_load_public_type(KEY_RSA1, filename, commentp);
662 /* try rsa1 public key */
663 pub = key_new(KEY_RSA1);
664 if (key_try_load_public(pub, filename, commentp) == 1)
668 /* try ssh2 public key */
669 pub = key_new(KEY_UNSPEC);
670 if (key_try_load_public(pub, filename, commentp) == 1)
672 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
673 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
674 (key_try_load_public(pub, file, commentp) == 1))