1 /* $OpenBSD: authfile.c,v 1.70 2006/07/17 01:31:09 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>
44 #include <openssl/err.h>
45 #include <openssl/evp.h>
46 #include <openssl/pem.h>
64 /* Version identification string for SSH v1 identity files. */
65 static const char authfile_id_string
[] =
66 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
69 * Saves the authentication (private) key in a file, encrypting it with
70 * passphrase. The identification of the file (lowest 64 bits of n) will
71 * precede the key to provide identification of the key without needing a
76 key_save_private_rsa1(Key
*key
, const char *filename
, const char *passphrase
,
79 Buffer buffer
, encrypted
;
81 int fd
, i
, cipher_num
;
82 CipherContext ciphercontext
;
87 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
88 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
90 cipher_num
= (strcmp(passphrase
, "") == 0) ?
91 SSH_CIPHER_NONE
: SSH_AUTHFILE_CIPHER
;
92 if ((cipher
= cipher_by_number(cipher_num
)) == NULL
)
93 fatal("save_private_key_rsa: bad cipher");
95 /* This buffer is used to built the secret part of the private key. */
98 /* Put checkbytes for checking passphrase validity. */
101 buf
[1] = (rnd
>> 8) & 0xff;
104 buffer_append(&buffer
, buf
, 4);
107 * Store the private key (n and e will not be stored because they
108 * will be stored in plain text, and storing them also in encrypted
109 * format would just give known plaintext).
111 buffer_put_bignum(&buffer
, key
->rsa
->d
);
112 buffer_put_bignum(&buffer
, key
->rsa
->iqmp
);
113 buffer_put_bignum(&buffer
, key
->rsa
->q
); /* reverse from SSL p */
114 buffer_put_bignum(&buffer
, key
->rsa
->p
); /* reverse from SSL q */
116 /* Pad the part to be encrypted until its size is a multiple of 8. */
117 while (buffer_len(&buffer
) % 8 != 0)
118 buffer_put_char(&buffer
, 0);
120 /* This buffer will be used to contain the data in the file. */
121 buffer_init(&encrypted
);
123 /* First store keyfile id string. */
124 for (i
= 0; authfile_id_string
[i
]; i
++)
125 buffer_put_char(&encrypted
, authfile_id_string
[i
]);
126 buffer_put_char(&encrypted
, 0);
128 /* Store cipher type. */
129 buffer_put_char(&encrypted
, cipher_num
);
130 buffer_put_int(&encrypted
, 0); /* For future extension */
132 /* Store public key. This will be in plain text. */
133 buffer_put_int(&encrypted
, BN_num_bits(key
->rsa
->n
));
134 buffer_put_bignum(&encrypted
, key
->rsa
->n
);
135 buffer_put_bignum(&encrypted
, key
->rsa
->e
);
136 buffer_put_cstring(&encrypted
, comment
);
138 /* Allocate space for the private part of the key in the buffer. */
139 cp
= buffer_append_space(&encrypted
, buffer_len(&buffer
));
141 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
143 cipher_crypt(&ciphercontext
, cp
,
144 buffer_ptr(&buffer
), buffer_len(&buffer
));
145 cipher_cleanup(&ciphercontext
);
146 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
148 /* Destroy temporary data. */
149 memset(buf
, 0, sizeof(buf
));
150 buffer_free(&buffer
);
152 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
154 error("open %s failed: %s.", filename
, strerror(errno
));
155 buffer_free(&encrypted
);
158 if (atomicio(vwrite
, fd
, buffer_ptr(&encrypted
),
159 buffer_len(&encrypted
)) != buffer_len(&encrypted
)) {
160 error("write to key file %s failed: %s", filename
,
162 buffer_free(&encrypted
);
168 buffer_free(&encrypted
);
172 /* save SSH v2 key in OpenSSL PEM format */
174 key_save_private_pem(Key
*key
, const char *filename
, const char *_passphrase
,
180 int len
= strlen(_passphrase
);
181 u_char
*passphrase
= (len
> 0) ? (u_char
*)_passphrase
: NULL
;
182 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_des_ede3_cbc() : NULL
;
184 if (len
> 0 && len
<= 4) {
185 error("passphrase too short: have %d bytes, need > 4", len
);
188 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
190 error("open %s failed: %s.", filename
, strerror(errno
));
193 fp
= fdopen(fd
, "w");
195 error("fdopen %s failed: %s.", filename
, strerror(errno
));
201 success
= PEM_write_DSAPrivateKey(fp
, key
->dsa
,
202 cipher
, passphrase
, len
, NULL
, NULL
);
205 success
= PEM_write_RSAPrivateKey(fp
, key
->rsa
,
206 cipher
, passphrase
, len
, NULL
, NULL
);
214 key_save_private(Key
*key
, const char *filename
, const char *passphrase
,
219 return key_save_private_rsa1(key
, filename
, passphrase
,
223 return key_save_private_pem(key
, filename
, passphrase
,
228 error("key_save_private: cannot save key type %d", key
->type
);
233 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
234 * encountered (the file does not exist or is not readable), and the key
239 key_load_public_rsa1(int fd
, const char *filename
, char **commentp
)
248 if (fstat(fd
, &st
) < 0) {
249 error("fstat for key file %.200s failed: %.100s",
250 filename
, strerror(errno
));
253 if (st
.st_size
> 1*1024*1024) {
254 error("key file %.200s too large", filename
);
257 len
= (size_t)st
.st_size
; /* truncated */
259 buffer_init(&buffer
);
260 cp
= buffer_append_space(&buffer
, len
);
262 if (atomicio(read
, fd
, cp
, len
) != len
) {
263 debug("Read from key file %.200s failed: %.100s", filename
,
265 buffer_free(&buffer
);
269 /* Check that it is at least big enough to contain the ID string. */
270 if (len
< sizeof(authfile_id_string
)) {
271 debug3("Not a RSA1 key file %.200s.", filename
);
272 buffer_free(&buffer
);
276 * Make sure it begins with the id string. Consume the id string
279 for (i
= 0; i
< sizeof(authfile_id_string
); i
++)
280 if (buffer_get_char(&buffer
) != authfile_id_string
[i
]) {
281 debug3("Not a RSA1 key file %.200s.", filename
);
282 buffer_free(&buffer
);
285 /* Skip cipher type and reserved data. */
286 (void) buffer_get_char(&buffer
); /* cipher type */
287 (void) buffer_get_int(&buffer
); /* reserved */
289 /* Read the public key from the buffer. */
290 (void) buffer_get_int(&buffer
);
291 pub
= key_new(KEY_RSA1
);
292 buffer_get_bignum(&buffer
, pub
->rsa
->n
);
293 buffer_get_bignum(&buffer
, pub
->rsa
->e
);
295 *commentp
= buffer_get_string(&buffer
, NULL
);
296 /* The encrypted private part is not parsed by this function. */
298 buffer_free(&buffer
);
302 /* load public key from private-key file, works only for SSH v1 */
304 key_load_public_type(int type
, const char *filename
, char **commentp
)
309 if (type
== KEY_RSA1
) {
310 fd
= open(filename
, O_RDONLY
);
313 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
321 * Loads the private key from the file. Returns 0 if an error is encountered
322 * (file does not exist or is not readable, or passphrase is bad). This
323 * initializes the private key.
324 * Assumes we are called under uid of the owner of the file.
328 key_load_private_rsa1(int fd
, const char *filename
, const char *passphrase
,
332 int check1
, check2
, cipher_type
;
334 Buffer buffer
, decrypted
;
336 CipherContext ciphercontext
;
341 if (fstat(fd
, &st
) < 0) {
342 error("fstat for key file %.200s failed: %.100s",
343 filename
, strerror(errno
));
347 if (st
.st_size
> 1*1024*1024) {
348 error("key file %.200s too large", filename
);
352 len
= (size_t)st
.st_size
; /* truncated */
354 buffer_init(&buffer
);
355 cp
= buffer_append_space(&buffer
, len
);
357 if (atomicio(read
, fd
, cp
, len
) != len
) {
358 debug("Read from key file %.200s failed: %.100s", filename
,
360 buffer_free(&buffer
);
365 /* Check that it is at least big enough to contain the ID string. */
366 if (len
< sizeof(authfile_id_string
)) {
367 debug3("Not a RSA1 key file %.200s.", filename
);
368 buffer_free(&buffer
);
373 * Make sure it begins with the id string. Consume the id string
376 for (i
= 0; i
< sizeof(authfile_id_string
); i
++)
377 if (buffer_get_char(&buffer
) != authfile_id_string
[i
]) {
378 debug3("Not a RSA1 key file %.200s.", filename
);
379 buffer_free(&buffer
);
384 /* Read cipher type. */
385 cipher_type
= buffer_get_char(&buffer
);
386 (void) buffer_get_int(&buffer
); /* Reserved data. */
388 /* Read the public key from the buffer. */
389 (void) buffer_get_int(&buffer
);
390 prv
= key_new_private(KEY_RSA1
);
392 buffer_get_bignum(&buffer
, prv
->rsa
->n
);
393 buffer_get_bignum(&buffer
, prv
->rsa
->e
);
395 *commentp
= buffer_get_string(&buffer
, NULL
);
397 xfree(buffer_get_string(&buffer
, NULL
));
399 /* Check that it is a supported cipher. */
400 cipher
= cipher_by_number(cipher_type
);
401 if (cipher
== NULL
) {
402 debug("Unsupported cipher %d used in key file %.200s.",
403 cipher_type
, filename
);
404 buffer_free(&buffer
);
407 /* Initialize space for decrypted data. */
408 buffer_init(&decrypted
);
409 cp
= buffer_append_space(&decrypted
, buffer_len(&buffer
));
411 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
412 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
414 cipher_crypt(&ciphercontext
, cp
,
415 buffer_ptr(&buffer
), buffer_len(&buffer
));
416 cipher_cleanup(&ciphercontext
);
417 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
418 buffer_free(&buffer
);
420 check1
= buffer_get_char(&decrypted
);
421 check2
= buffer_get_char(&decrypted
);
422 if (check1
!= buffer_get_char(&decrypted
) ||
423 check2
!= buffer_get_char(&decrypted
)) {
424 if (strcmp(passphrase
, "") != 0)
425 debug("Bad passphrase supplied for key file %.200s.",
427 /* Bad passphrase. */
428 buffer_free(&decrypted
);
431 /* Read the rest of the private key. */
432 buffer_get_bignum(&decrypted
, prv
->rsa
->d
);
433 buffer_get_bignum(&decrypted
, prv
->rsa
->iqmp
); /* u */
434 /* in SSL and SSH v1 p and q are exchanged */
435 buffer_get_bignum(&decrypted
, prv
->rsa
->q
); /* p */
436 buffer_get_bignum(&decrypted
, prv
->rsa
->p
); /* q */
438 /* calculate p-1 and q-1 */
439 rsa_generate_additional_parameters(prv
->rsa
);
441 buffer_free(&decrypted
);
443 /* enable blinding */
444 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
445 error("key_load_private_rsa1: RSA_blinding_on failed");
460 key_load_private_pem(int fd
, int type
, const char *passphrase
,
466 char *name
= "<no key>";
468 fp
= fdopen(fd
, "r");
470 error("fdopen failed: %s", strerror(errno
));
474 pk
= PEM_read_PrivateKey(fp
, NULL
, NULL
, (char *)passphrase
);
476 debug("PEM_read_PrivateKey failed");
477 (void)ERR_get_error();
478 } else if (pk
->type
== EVP_PKEY_RSA
&&
479 (type
== KEY_UNSPEC
||type
==KEY_RSA
)) {
480 prv
= key_new(KEY_UNSPEC
);
481 prv
->rsa
= EVP_PKEY_get1_RSA(pk
);
483 name
= "rsa w/o comment";
485 RSA_print_fp(stderr
, prv
->rsa
, 8);
487 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
488 error("key_load_private_pem: RSA_blinding_on failed");
492 } else if (pk
->type
== EVP_PKEY_DSA
&&
493 (type
== KEY_UNSPEC
||type
==KEY_DSA
)) {
494 prv
= key_new(KEY_UNSPEC
);
495 prv
->dsa
= EVP_PKEY_get1_DSA(pk
);
497 name
= "dsa w/o comment";
499 DSA_print_fp(stderr
, prv
->dsa
, 8);
502 error("PEM_read_PrivateKey: mismatch or "
503 "unknown EVP_PKEY save_type %d", pk
->save_type
);
508 if (prv
!= NULL
&& commentp
)
509 *commentp
= xstrdup(name
);
510 debug("read PEM private key done: type %s",
511 prv
? key_type(prv
) : "<unknown>");
516 key_perm_ok(int fd
, const char *filename
)
520 if (fstat(fd
, &st
) < 0)
523 * if a key owned by the user is accessed, then we check the
524 * permissions of the file. if the key owned by a different user,
525 * then we don't care.
528 if (check_ntsec(filename
))
530 if ((st
.st_uid
== getuid()) && (st
.st_mode
& 077) != 0) {
531 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
532 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
533 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
534 error("Permissions 0%3.3o for '%s' are too open.",
535 (u_int
)st
.st_mode
& 0777, filename
);
536 error("It is recommended that your private key files are NOT accessible by others.");
537 error("This private key will be ignored.");
544 key_load_private_type(int type
, const char *filename
, const char *passphrase
,
545 char **commentp
, int *perm_ok
)
549 fd
= open(filename
, O_RDONLY
);
552 if (!key_perm_ok(fd
, filename
)) {
555 error("bad permissions: ignore key: %s", filename
);
563 return key_load_private_rsa1(fd
, filename
, passphrase
,
569 return key_load_private_pem(fd
, type
, passphrase
, commentp
);
579 key_load_private(const char *filename
, const char *passphrase
,
585 fd
= open(filename
, O_RDONLY
);
588 if (!key_perm_ok(fd
, filename
)) {
589 error("bad permissions: ignore key: %s", filename
);
593 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
594 lseek(fd
, (off_t
) 0, SEEK_SET
); /* rewind */
597 prv
= key_load_private_pem(fd
, KEY_UNSPEC
, passphrase
, NULL
);
598 /* use the filename as a comment for PEM */
600 *commentp
= xstrdup(filename
);
602 /* it's a SSH v1 key if the public key part is readable */
605 prv
= key_load_private_rsa1(fd
, filename
, passphrase
, NULL
);
611 key_try_load_public(Key
*k
, const char *filename
, char **commentp
)
614 char line
[SSH_MAX_PUBKEY_BYTES
];
618 f
= fopen(filename
, "r");
620 while (read_keyfile_line(f
, filename
, line
, sizeof(line
),
629 /* Skip leading whitespace. */
630 for (; *cp
&& (*cp
== ' ' || *cp
== '\t'); cp
++)
633 if (key_read(k
, &cp
) == 1) {
635 *commentp
=xstrdup(filename
);
646 /* load public key from ssh v1 private or any pubkey file */
648 key_load_public(const char *filename
, char **commentp
)
651 char file
[MAXPATHLEN
];
653 /* try rsa1 private key */
654 pub
= key_load_public_type(KEY_RSA1
, filename
, commentp
);
658 /* try rsa1 public key */
659 pub
= key_new(KEY_RSA1
);
660 if (key_try_load_public(pub
, filename
, commentp
) == 1)
664 /* try ssh2 public key */
665 pub
= key_new(KEY_UNSPEC
);
666 if (key_try_load_public(pub
, filename
, commentp
) == 1)
668 if ((strlcpy(file
, filename
, sizeof file
) < sizeof(file
)) &&
669 (strlcat(file
, ".pub", sizeof file
) < sizeof(file
)) &&
670 (key_try_load_public(pub
, file
, commentp
) == 1))