1 /* $OpenBSD: authfile.c,v 1.76 2006/08/03 03:34:41 deraadt 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>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/pem.h>
69 /* Version identification string for SSH v1 identity files. */
70 static const char authfile_id_string[] =
71 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
74 * Saves the authentication (private) key in a file, encrypting it with
75 * passphrase. The identification of the file (lowest 64 bits of n) will
76 * precede the key to provide identification of the key without needing a
81 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
84 Buffer buffer, encrypted;
86 int fd, i, cipher_num;
87 CipherContext ciphercontext;
92 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
93 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
95 cipher_num = (strcmp(passphrase, "") == 0) ?
96 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
97 if ((cipher = cipher_by_number(cipher_num)) == NULL)
98 fatal("save_private_key_rsa: bad cipher");
100 /* This buffer is used to built the secret part of the private key. */
101 buffer_init(&buffer);
103 /* Put checkbytes for checking passphrase validity. */
106 buf[1] = (rnd >> 8) & 0xff;
109 buffer_append(&buffer, buf, 4);
112 * Store the private key (n and e will not be stored because they
113 * will be stored in plain text, and storing them also in encrypted
114 * format would just give known plaintext).
116 buffer_put_bignum(&buffer, key->rsa->d);
117 buffer_put_bignum(&buffer, key->rsa->iqmp);
118 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
119 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
121 /* Pad the part to be encrypted until its size is a multiple of 8. */
122 while (buffer_len(&buffer) % 8 != 0)
123 buffer_put_char(&buffer, 0);
125 /* This buffer will be used to contain the data in the file. */
126 buffer_init(&encrypted);
128 /* First store keyfile id string. */
129 for (i = 0; authfile_id_string[i]; i++)
130 buffer_put_char(&encrypted, authfile_id_string[i]);
131 buffer_put_char(&encrypted, 0);
133 /* Store cipher type. */
134 buffer_put_char(&encrypted, cipher_num);
135 buffer_put_int(&encrypted, 0); /* For future extension */
137 /* Store public key. This will be in plain text. */
138 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
139 buffer_put_bignum(&encrypted, key->rsa->n);
140 buffer_put_bignum(&encrypted, key->rsa->e);
141 buffer_put_cstring(&encrypted, comment);
143 /* Allocate space for the private part of the key in the buffer. */
144 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
146 cipher_set_key_string(&ciphercontext, cipher, passphrase,
148 cipher_crypt(&ciphercontext, cp,
149 buffer_ptr(&buffer), buffer_len(&buffer));
150 cipher_cleanup(&ciphercontext);
151 memset(&ciphercontext, 0, sizeof(ciphercontext));
153 /* Destroy temporary data. */
154 memset(buf, 0, sizeof(buf));
155 buffer_free(&buffer);
157 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
159 error("open %s failed: %s.", filename, strerror(errno));
160 buffer_free(&encrypted);
163 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
164 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
165 error("write to key file %s failed: %s", filename,
167 buffer_free(&encrypted);
173 buffer_free(&encrypted);
177 /* save SSH v2 key in OpenSSL PEM format */
179 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
185 int len = strlen(_passphrase);
186 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
187 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
189 if (len > 0 && len <= 4) {
190 error("passphrase too short: have %d bytes, need > 4", len);
193 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
195 error("open %s failed: %s.", filename, strerror(errno));
198 fp = fdopen(fd, "w");
200 error("fdopen %s failed: %s.", filename, strerror(errno));
206 success = PEM_write_DSAPrivateKey(fp, key->dsa,
207 cipher, passphrase, len, NULL, NULL);
210 success = PEM_write_RSAPrivateKey(fp, key->rsa,
211 cipher, passphrase, len, NULL, NULL);
219 key_save_private(Key *key, const char *filename, const char *passphrase,
224 return key_save_private_rsa1(key, filename, passphrase,
228 return key_save_private_pem(key, filename, passphrase,
233 error("key_save_private: cannot save key type %d", key->type);
238 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
239 * encountered (the file does not exist or is not readable), and the key
244 key_load_public_rsa1(int fd, const char *filename, char **commentp)
253 if (fstat(fd, &st) < 0) {
254 error("fstat for key file %.200s failed: %.100s",
255 filename, strerror(errno));
258 if (st.st_size > 1*1024*1024) {
259 error("key file %.200s too large", filename);
262 len = (size_t)st.st_size; /* truncated */
264 buffer_init(&buffer);
265 cp = buffer_append_space(&buffer, len);
267 if (atomicio(read, fd, cp, len) != len) {
268 debug("Read from key file %.200s failed: %.100s", filename,
270 buffer_free(&buffer);
274 /* Check that it is at least big enough to contain the ID string. */
275 if (len < sizeof(authfile_id_string)) {
276 debug3("Not a RSA1 key file %.200s.", filename);
277 buffer_free(&buffer);
281 * Make sure it begins with the id string. Consume the id string
284 for (i = 0; i < sizeof(authfile_id_string); i++)
285 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
286 debug3("Not a RSA1 key file %.200s.", filename);
287 buffer_free(&buffer);
290 /* Skip cipher type and reserved data. */
291 (void) buffer_get_char(&buffer); /* cipher type */
292 (void) buffer_get_int(&buffer); /* reserved */
294 /* Read the public key from the buffer. */
295 (void) buffer_get_int(&buffer);
296 pub = key_new(KEY_RSA1);
297 buffer_get_bignum(&buffer, pub->rsa->n);
298 buffer_get_bignum(&buffer, pub->rsa->e);
300 *commentp = buffer_get_string(&buffer, NULL);
301 /* The encrypted private part is not parsed by this function. */
303 buffer_free(&buffer);
307 /* load public key from private-key file, works only for SSH v1 */
309 key_load_public_type(int type, const char *filename, char **commentp)
314 if (type == KEY_RSA1) {
315 fd = open(filename, O_RDONLY);
318 pub = key_load_public_rsa1(fd, filename, commentp);
326 * Loads the private key from the file. Returns 0 if an error is encountered
327 * (file does not exist or is not readable, or passphrase is bad). This
328 * initializes the private key.
329 * Assumes we are called under uid of the owner of the file.
333 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
337 int check1, check2, cipher_type;
339 Buffer buffer, decrypted;
341 CipherContext ciphercontext;
346 if (fstat(fd, &st) < 0) {
347 error("fstat for key file %.200s failed: %.100s",
348 filename, strerror(errno));
352 if (st.st_size > 1*1024*1024) {
353 error("key file %.200s too large", filename);
357 len = (size_t)st.st_size; /* truncated */
359 buffer_init(&buffer);
360 cp = buffer_append_space(&buffer, len);
362 if (atomicio(read, fd, cp, len) != len) {
363 debug("Read from key file %.200s failed: %.100s", filename,
365 buffer_free(&buffer);
370 /* Check that it is at least big enough to contain the ID string. */
371 if (len < sizeof(authfile_id_string)) {
372 debug3("Not a RSA1 key file %.200s.", filename);
373 buffer_free(&buffer);
378 * Make sure it begins with the id string. Consume the id string
381 for (i = 0; i < sizeof(authfile_id_string); i++)
382 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
383 debug3("Not a RSA1 key file %.200s.", filename);
384 buffer_free(&buffer);
389 /* Read cipher type. */
390 cipher_type = buffer_get_char(&buffer);
391 (void) buffer_get_int(&buffer); /* Reserved data. */
393 /* Read the public key from the buffer. */
394 (void) buffer_get_int(&buffer);
395 prv = key_new_private(KEY_RSA1);
397 buffer_get_bignum(&buffer, prv->rsa->n);
398 buffer_get_bignum(&buffer, prv->rsa->e);
400 *commentp = buffer_get_string(&buffer, NULL);
402 xfree(buffer_get_string(&buffer, NULL));
404 /* Check that it is a supported cipher. */
405 cipher = cipher_by_number(cipher_type);
406 if (cipher == NULL) {
407 debug("Unsupported cipher %d used in key file %.200s.",
408 cipher_type, filename);
409 buffer_free(&buffer);
412 /* Initialize space for decrypted data. */
413 buffer_init(&decrypted);
414 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
416 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
417 cipher_set_key_string(&ciphercontext, cipher, passphrase,
419 cipher_crypt(&ciphercontext, cp,
420 buffer_ptr(&buffer), buffer_len(&buffer));
421 cipher_cleanup(&ciphercontext);
422 memset(&ciphercontext, 0, sizeof(ciphercontext));
423 buffer_free(&buffer);
425 check1 = buffer_get_char(&decrypted);
426 check2 = buffer_get_char(&decrypted);
427 if (check1 != buffer_get_char(&decrypted) ||
428 check2 != buffer_get_char(&decrypted)) {
429 if (strcmp(passphrase, "") != 0)
430 debug("Bad passphrase supplied for key file %.200s.",
432 /* Bad passphrase. */
433 buffer_free(&decrypted);
436 /* Read the rest of the private key. */
437 buffer_get_bignum(&decrypted, prv->rsa->d);
438 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
439 /* in SSL and SSH v1 p and q are exchanged */
440 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
441 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
443 /* calculate p-1 and q-1 */
444 rsa_generate_additional_parameters(prv->rsa);
446 buffer_free(&decrypted);
448 /* enable blinding */
449 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
450 error("key_load_private_rsa1: RSA_blinding_on failed");
465 key_load_private_pem(int fd, int type, const char *passphrase,
471 char *name = "<no key>";
473 fp = fdopen(fd, "r");
475 error("fdopen failed: %s", strerror(errno));
479 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
481 debug("PEM_read_PrivateKey failed");
482 (void)ERR_get_error();
483 } else if (pk->type == EVP_PKEY_RSA &&
484 (type == KEY_UNSPEC||type==KEY_RSA)) {
485 prv = key_new(KEY_UNSPEC);
486 prv->rsa = EVP_PKEY_get1_RSA(pk);
488 name = "rsa w/o comment";
490 RSA_print_fp(stderr, prv->rsa, 8);
492 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
493 error("key_load_private_pem: RSA_blinding_on failed");
497 } else if (pk->type == EVP_PKEY_DSA &&
498 (type == KEY_UNSPEC||type==KEY_DSA)) {
499 prv = key_new(KEY_UNSPEC);
500 prv->dsa = EVP_PKEY_get1_DSA(pk);
502 name = "dsa w/o comment";
504 DSA_print_fp(stderr, prv->dsa, 8);
507 error("PEM_read_PrivateKey: mismatch or "
508 "unknown EVP_PKEY save_type %d", pk->save_type);
513 if (prv != NULL && commentp)
514 *commentp = xstrdup(name);
515 debug("read PEM private key done: type %s",
516 prv ? key_type(prv) : "<unknown>");
521 key_perm_ok(int fd, const char *filename)
525 if (fstat(fd, &st) < 0)
528 * if a key owned by the user is accessed, then we check the
529 * permissions of the file. if the key owned by a different user,
530 * then we don't care.
533 if (check_ntsec(filename))
535 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
536 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
537 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
538 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
539 error("Permissions 0%3.3o for '%s' are too open.",
540 (u_int)st.st_mode & 0777, filename);
541 error("It is recommended that your private key files are NOT accessible by others.");
542 error("This private key will be ignored.");
549 key_load_private_type(int type, const char *filename, const char *passphrase,
550 char **commentp, int *perm_ok)
554 fd = open(filename, O_RDONLY);
557 if (!key_perm_ok(fd, filename)) {
560 error("bad permissions: ignore key: %s", filename);
568 return key_load_private_rsa1(fd, filename, passphrase,
574 return key_load_private_pem(fd, type, passphrase, commentp);
584 key_load_private(const char *filename, const char *passphrase,
590 fd = open(filename, O_RDONLY);
593 if (!key_perm_ok(fd, filename)) {
594 error("bad permissions: ignore key: %s", filename);
598 pub = key_load_public_rsa1(fd, filename, commentp);
599 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
602 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
603 /* use the filename as a comment for PEM */
605 *commentp = xstrdup(filename);
607 /* it's a SSH v1 key if the public key part is readable */
610 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
616 key_try_load_public(Key *k, const char *filename, char **commentp)
619 char line[SSH_MAX_PUBKEY_BYTES];
623 f = fopen(filename, "r");
625 while (read_keyfile_line(f, filename, line, sizeof(line),
634 /* Skip leading whitespace. */
635 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
638 if (key_read(k, &cp) == 1) {
640 *commentp=xstrdup(filename);
651 /* load public key from ssh v1 private or any pubkey file */
653 key_load_public(const char *filename, char **commentp)
656 char file[MAXPATHLEN];
658 /* try rsa1 private key */
659 pub = key_load_public_type(KEY_RSA1, filename, commentp);
663 /* try rsa1 public key */
664 pub = key_new(KEY_RSA1);
665 if (key_try_load_public(pub, filename, commentp) == 1)
669 /* try ssh2 public key */
670 pub = key_new(KEY_UNSPEC);
671 if (key_try_load_public(pub, filename, commentp) == 1)
673 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
674 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
675 (key_try_load_public(pub, file, commentp) == 1))