1 /* $OpenBSD: authfile.c,v 1.77 2009/10/22 22:26:13 djm 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>
50 /* compatibility with old or broken OpenSSL versions */
51 #include "openbsd-compat/openssl-compat.h"
72 /* Version identification string for SSH v1 identity files. */
73 static const char authfile_id_string
[] =
74 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
77 * Saves the authentication (private) key in a file, encrypting it with
78 * passphrase. The identification of the file (lowest 64 bits of n) will
79 * precede the key to provide identification of the key without needing a
84 key_save_private_rsa1(Key
*key
, const char *filename
, const char *passphrase
,
87 Buffer buffer
, encrypted
;
89 int fd
, i
, cipher_num
;
90 CipherContext ciphercontext
;
95 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
96 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
98 cipher_num
= (strcmp(passphrase
, "") == 0) ?
99 SSH_CIPHER_NONE
: SSH_AUTHFILE_CIPHER
;
100 if ((cipher
= cipher_by_number(cipher_num
)) == NULL
)
101 fatal("save_private_key_rsa: bad cipher");
103 /* This buffer is used to built the secret part of the private key. */
104 buffer_init(&buffer
);
106 /* Put checkbytes for checking passphrase validity. */
109 buf
[1] = (rnd
>> 8) & 0xff;
112 buffer_append(&buffer
, buf
, 4);
115 * Store the private key (n and e will not be stored because they
116 * will be stored in plain text, and storing them also in encrypted
117 * format would just give known plaintext).
119 buffer_put_bignum(&buffer
, key
->rsa
->d
);
120 buffer_put_bignum(&buffer
, key
->rsa
->iqmp
);
121 buffer_put_bignum(&buffer
, key
->rsa
->q
); /* reverse from SSL p */
122 buffer_put_bignum(&buffer
, key
->rsa
->p
); /* reverse from SSL q */
124 /* Pad the part to be encrypted until its size is a multiple of 8. */
125 while (buffer_len(&buffer
) % 8 != 0)
126 buffer_put_char(&buffer
, 0);
128 /* This buffer will be used to contain the data in the file. */
129 buffer_init(&encrypted
);
131 /* First store keyfile id string. */
132 for (i
= 0; authfile_id_string
[i
]; i
++)
133 buffer_put_char(&encrypted
, authfile_id_string
[i
]);
134 buffer_put_char(&encrypted
, 0);
136 /* Store cipher type. */
137 buffer_put_char(&encrypted
, cipher_num
);
138 buffer_put_int(&encrypted
, 0); /* For future extension */
140 /* Store public key. This will be in plain text. */
141 buffer_put_int(&encrypted
, BN_num_bits(key
->rsa
->n
));
142 buffer_put_bignum(&encrypted
, key
->rsa
->n
);
143 buffer_put_bignum(&encrypted
, key
->rsa
->e
);
144 buffer_put_cstring(&encrypted
, comment
);
146 /* Allocate space for the private part of the key in the buffer. */
147 cp
= buffer_append_space(&encrypted
, buffer_len(&buffer
));
149 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
151 cipher_crypt(&ciphercontext
, cp
,
152 buffer_ptr(&buffer
), buffer_len(&buffer
));
153 cipher_cleanup(&ciphercontext
);
154 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
156 /* Destroy temporary data. */
157 memset(buf
, 0, sizeof(buf
));
158 buffer_free(&buffer
);
160 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
162 error("open %s failed: %s.", filename
, strerror(errno
));
163 buffer_free(&encrypted
);
166 if (atomicio(vwrite
, fd
, buffer_ptr(&encrypted
),
167 buffer_len(&encrypted
)) != buffer_len(&encrypted
)) {
168 error("write to key file %s failed: %s", filename
,
170 buffer_free(&encrypted
);
176 buffer_free(&encrypted
);
180 /* save SSH v2 key in OpenSSL PEM format */
182 key_save_private_pem(Key
*key
, const char *filename
, const char *_passphrase
,
188 int len
= strlen(_passphrase
);
189 u_char
*passphrase
= (len
> 0) ? (u_char
*)_passphrase
: NULL
;
190 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
191 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_des_ede3_cbc() : NULL
;
193 const EVP_CIPHER
*cipher
= (len
> 0) ? EVP_aes_128_cbc() : NULL
;
196 if (len
> 0 && len
<= 4) {
197 error("passphrase too short: have %d bytes, need > 4", len
);
200 fd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
202 error("open %s failed: %s.", filename
, strerror(errno
));
205 fp
= fdopen(fd
, "w");
207 error("fdopen %s failed: %s.", filename
, strerror(errno
));
213 success
= PEM_write_DSAPrivateKey(fp
, key
->dsa
,
214 cipher
, passphrase
, len
, NULL
, NULL
);
217 success
= PEM_write_RSAPrivateKey(fp
, key
->rsa
,
218 cipher
, passphrase
, len
, NULL
, NULL
);
226 key_save_private(Key
*key
, const char *filename
, const char *passphrase
,
231 return key_save_private_rsa1(key
, filename
, passphrase
,
235 return key_save_private_pem(key
, filename
, passphrase
,
240 error("key_save_private: cannot save key type %d", key
->type
);
245 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
246 * encountered (the file does not exist or is not readable), and the key
251 key_load_public_rsa1(int fd
, const char *filename
, char **commentp
)
260 if (fstat(fd
, &st
) < 0) {
261 error("fstat for key file %.200s failed: %.100s",
262 filename
, strerror(errno
));
265 if (st
.st_size
> 1*1024*1024) {
266 error("key file %.200s too large", filename
);
269 len
= (size_t)st
.st_size
; /* truncated */
271 buffer_init(&buffer
);
272 cp
= buffer_append_space(&buffer
, len
);
274 if (atomicio(read
, fd
, cp
, len
) != len
) {
275 debug("Read from key file %.200s failed: %.100s", filename
,
277 buffer_free(&buffer
);
281 /* Check that it is at least big enough to contain the ID string. */
282 if (len
< sizeof(authfile_id_string
)) {
283 debug3("Not a RSA1 key file %.200s.", filename
);
284 buffer_free(&buffer
);
288 * Make sure it begins with the id string. Consume the id string
291 for (i
= 0; i
< sizeof(authfile_id_string
); i
++)
292 if (buffer_get_char(&buffer
) != authfile_id_string
[i
]) {
293 debug3("Not a RSA1 key file %.200s.", filename
);
294 buffer_free(&buffer
);
297 /* Skip cipher type and reserved data. */
298 (void) buffer_get_char(&buffer
); /* cipher type */
299 (void) buffer_get_int(&buffer
); /* reserved */
301 /* Read the public key from the buffer. */
302 (void) buffer_get_int(&buffer
);
303 pub
= key_new(KEY_RSA1
);
304 buffer_get_bignum(&buffer
, pub
->rsa
->n
);
305 buffer_get_bignum(&buffer
, pub
->rsa
->e
);
307 *commentp
= buffer_get_string(&buffer
, NULL
);
308 /* The encrypted private part is not parsed by this function. */
310 buffer_free(&buffer
);
314 /* load public key from private-key file, works only for SSH v1 */
316 key_load_public_type(int type
, const char *filename
, char **commentp
)
321 if (type
== KEY_RSA1
) {
322 fd
= open(filename
, O_RDONLY
);
325 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
333 * Loads the private key from the file. Returns 0 if an error is encountered
334 * (file does not exist or is not readable, or passphrase is bad). This
335 * initializes the private key.
336 * Assumes we are called under uid of the owner of the file.
340 key_load_private_rsa1(int fd
, const char *filename
, const char *passphrase
,
344 int check1
, check2
, cipher_type
;
346 Buffer buffer
, decrypted
;
348 CipherContext ciphercontext
;
353 if (fstat(fd
, &st
) < 0) {
354 error("fstat for key file %.200s failed: %.100s",
355 filename
, strerror(errno
));
359 if (st
.st_size
> 1*1024*1024) {
360 error("key file %.200s too large", filename
);
364 len
= (size_t)st
.st_size
; /* truncated */
366 buffer_init(&buffer
);
367 cp
= buffer_append_space(&buffer
, len
);
369 if (atomicio(read
, fd
, cp
, len
) != len
) {
370 debug("Read from key file %.200s failed: %.100s", filename
,
372 buffer_free(&buffer
);
377 /* Check that it is at least big enough to contain the ID string. */
378 if (len
< sizeof(authfile_id_string
)) {
379 debug3("Not a RSA1 key file %.200s.", filename
);
380 buffer_free(&buffer
);
385 * Make sure it begins with the id string. Consume the id string
388 for (i
= 0; i
< sizeof(authfile_id_string
); i
++)
389 if (buffer_get_char(&buffer
) != authfile_id_string
[i
]) {
390 debug3("Not a RSA1 key file %.200s.", filename
);
391 buffer_free(&buffer
);
396 /* Read cipher type. */
397 cipher_type
= buffer_get_char(&buffer
);
398 (void) buffer_get_int(&buffer
); /* Reserved data. */
400 /* Read the public key from the buffer. */
401 (void) buffer_get_int(&buffer
);
402 prv
= key_new_private(KEY_RSA1
);
404 buffer_get_bignum(&buffer
, prv
->rsa
->n
);
405 buffer_get_bignum(&buffer
, prv
->rsa
->e
);
407 *commentp
= buffer_get_string(&buffer
, NULL
);
409 xfree(buffer_get_string(&buffer
, NULL
));
411 /* Check that it is a supported cipher. */
412 cipher
= cipher_by_number(cipher_type
);
413 if (cipher
== NULL
) {
414 debug("Unsupported cipher %d used in key file %.200s.",
415 cipher_type
, filename
);
416 buffer_free(&buffer
);
419 /* Initialize space for decrypted data. */
420 buffer_init(&decrypted
);
421 cp
= buffer_append_space(&decrypted
, buffer_len(&buffer
));
423 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
424 cipher_set_key_string(&ciphercontext
, cipher
, passphrase
,
426 cipher_crypt(&ciphercontext
, cp
,
427 buffer_ptr(&buffer
), buffer_len(&buffer
));
428 cipher_cleanup(&ciphercontext
);
429 memset(&ciphercontext
, 0, sizeof(ciphercontext
));
430 buffer_free(&buffer
);
432 check1
= buffer_get_char(&decrypted
);
433 check2
= buffer_get_char(&decrypted
);
434 if (check1
!= buffer_get_char(&decrypted
) ||
435 check2
!= buffer_get_char(&decrypted
)) {
436 if (strcmp(passphrase
, "") != 0)
437 debug("Bad passphrase supplied for key file %.200s.",
439 /* Bad passphrase. */
440 buffer_free(&decrypted
);
443 /* Read the rest of the private key. */
444 buffer_get_bignum(&decrypted
, prv
->rsa
->d
);
445 buffer_get_bignum(&decrypted
, prv
->rsa
->iqmp
); /* u */
446 /* in SSL and SSH v1 p and q are exchanged */
447 buffer_get_bignum(&decrypted
, prv
->rsa
->q
); /* p */
448 buffer_get_bignum(&decrypted
, prv
->rsa
->p
); /* q */
450 /* calculate p-1 and q-1 */
451 rsa_generate_additional_parameters(prv
->rsa
);
453 buffer_free(&decrypted
);
455 /* enable blinding */
456 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
457 error("key_load_private_rsa1: RSA_blinding_on failed");
472 key_load_private_pem(int fd
, int type
, const char *passphrase
,
478 char *name
= "<no key>";
480 fp
= fdopen(fd
, "r");
482 error("fdopen failed: %s", strerror(errno
));
486 pk
= PEM_read_PrivateKey(fp
, NULL
, NULL
, (char *)passphrase
);
488 debug("PEM_read_PrivateKey failed");
489 (void)ERR_get_error();
490 } else if (pk
->type
== EVP_PKEY_RSA
&&
491 (type
== KEY_UNSPEC
||type
==KEY_RSA
)) {
492 prv
= key_new(KEY_UNSPEC
);
493 prv
->rsa
= EVP_PKEY_get1_RSA(pk
);
495 name
= "rsa w/o comment";
497 RSA_print_fp(stderr
, prv
->rsa
, 8);
499 if (RSA_blinding_on(prv
->rsa
, NULL
) != 1) {
500 error("key_load_private_pem: RSA_blinding_on failed");
504 } else if (pk
->type
== EVP_PKEY_DSA
&&
505 (type
== KEY_UNSPEC
||type
==KEY_DSA
)) {
506 prv
= key_new(KEY_UNSPEC
);
507 prv
->dsa
= EVP_PKEY_get1_DSA(pk
);
509 name
= "dsa w/o comment";
511 DSA_print_fp(stderr
, prv
->dsa
, 8);
514 error("PEM_read_PrivateKey: mismatch or "
515 "unknown EVP_PKEY save_type %d", pk
->save_type
);
520 if (prv
!= NULL
&& commentp
)
521 *commentp
= xstrdup(name
);
522 debug("read PEM private key done: type %s",
523 prv
? key_type(prv
) : "<unknown>");
528 key_perm_ok(int fd
, const char *filename
)
532 if (fstat(fd
, &st
) < 0)
535 * if a key owned by the user is accessed, then we check the
536 * permissions of the file. if the key owned by a different user,
537 * then we don't care.
540 if (check_ntsec(filename
))
542 if ((st
.st_uid
== getuid()) && (st
.st_mode
& 077) != 0) {
543 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
544 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
545 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
546 error("Permissions 0%3.3o for '%s' are too open.",
547 (u_int
)st
.st_mode
& 0777, filename
);
548 error("It is recommended that your private key files are NOT accessible by others.");
549 error("This private key will be ignored.");
556 key_load_private_type(int type
, const char *filename
, const char *passphrase
,
557 char **commentp
, int *perm_ok
)
561 fd
= open(filename
, O_RDONLY
);
564 if (!key_perm_ok(fd
, filename
)) {
567 error("bad permissions: ignore key: %s", filename
);
575 return key_load_private_rsa1(fd
, filename
, passphrase
,
581 return key_load_private_pem(fd
, type
, passphrase
, commentp
);
591 key_load_private(const char *filename
, const char *passphrase
,
597 fd
= open(filename
, O_RDONLY
);
600 if (!key_perm_ok(fd
, filename
)) {
601 error("bad permissions: ignore key: %s", filename
);
605 pub
= key_load_public_rsa1(fd
, filename
, commentp
);
606 lseek(fd
, (off_t
) 0, SEEK_SET
); /* rewind */
609 prv
= key_load_private_pem(fd
, KEY_UNSPEC
, passphrase
, NULL
);
610 /* use the filename as a comment for PEM */
612 *commentp
= xstrdup(filename
);
614 /* it's a SSH v1 key if the public key part is readable */
617 prv
= key_load_private_rsa1(fd
, filename
, passphrase
, NULL
);
623 key_try_load_public(Key
*k
, const char *filename
, char **commentp
)
626 char line
[SSH_MAX_PUBKEY_BYTES
];
630 f
= fopen(filename
, "r");
632 while (read_keyfile_line(f
, filename
, line
, sizeof(line
),
641 /* Skip leading whitespace. */
642 for (; *cp
&& (*cp
== ' ' || *cp
== '\t'); cp
++)
645 if (key_read(k
, &cp
) == 1) {
647 *commentp
=xstrdup(filename
);
658 /* load public key from ssh v1 private or any pubkey file */
660 key_load_public(const char *filename
, char **commentp
)
663 char file
[MAXPATHLEN
];
665 /* try rsa1 private key */
666 pub
= key_load_public_type(KEY_RSA1
, filename
, commentp
);
670 /* try rsa1 public key */
671 pub
= key_new(KEY_RSA1
);
672 if (key_try_load_public(pub
, filename
, commentp
) == 1)
676 /* try ssh2 public key */
677 pub
= key_new(KEY_UNSPEC
);
678 if (key_try_load_public(pub
, filename
, commentp
) == 1)
680 if ((strlcpy(file
, filename
, sizeof file
) < sizeof(file
)) &&
681 (strlcat(file
, ".pub", sizeof file
) < sizeof(file
)) &&
682 (key_try_load_public(pub
, file
, commentp
) == 1))