xref: /freebsd/crypto/openssh/authfile.c (revision 595e514d0df2bac5b813d35f83e32875dbf16a83)
1 /* $OpenBSD: authfile.c,v 1.95 2013/01/08 18:49:04 markus Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains functions for reading and writing identity files, and
7  * for reading the passphrase from the user.
8  *
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".
14  *
15  *
16  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
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.
26  *
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.
37  */
38 
39 #include "includes.h"
40 
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <sys/param.h>
44 #include <sys/uio.h>
45 
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/pem.h>
49 
50 /* compatibility with old or broken OpenSSL versions */
51 #include "openbsd-compat/openssl-compat.h"
52 
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdarg.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #include "xmalloc.h"
62 #include "cipher.h"
63 #include "buffer.h"
64 #include "key.h"
65 #include "ssh.h"
66 #include "log.h"
67 #include "authfile.h"
68 #include "rsa.h"
69 #include "misc.h"
70 #include "atomicio.h"
71 
72 #define MAX_KEY_FILE_SIZE	(1024 * 1024)
73 
74 /* Version identification string for SSH v1 identity files. */
75 static const char authfile_id_string[] =
76     "SSH PRIVATE KEY FILE FORMAT 1.1\n";
77 
78 /*
79  * Serialises the authentication (private) key to a blob, encrypting it with
80  * passphrase.  The identification of the blob (lowest 64 bits of n) will
81  * precede the key to provide identification of the key without needing a
82  * passphrase.
83  */
84 static int
85 key_private_rsa1_to_blob(Key *key, Buffer *blob, const char *passphrase,
86     const char *comment)
87 {
88 	Buffer buffer, encrypted;
89 	u_char buf[100], *cp;
90 	int i, cipher_num;
91 	CipherContext ciphercontext;
92 	Cipher *cipher;
93 	u_int32_t rnd;
94 
95 	/*
96 	 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
97 	 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
98 	 */
99 	cipher_num = (strcmp(passphrase, "") == 0) ?
100 	    SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
101 	if ((cipher = cipher_by_number(cipher_num)) == NULL)
102 		fatal("save_private_key_rsa: bad cipher");
103 
104 	/* This buffer is used to built the secret part of the private key. */
105 	buffer_init(&buffer);
106 
107 	/* Put checkbytes for checking passphrase validity. */
108 	rnd = arc4random();
109 	buf[0] = rnd & 0xff;
110 	buf[1] = (rnd >> 8) & 0xff;
111 	buf[2] = buf[0];
112 	buf[3] = buf[1];
113 	buffer_append(&buffer, buf, 4);
114 
115 	/*
116 	 * Store the private key (n and e will not be stored because they
117 	 * will be stored in plain text, and storing them also in encrypted
118 	 * format would just give known plaintext).
119 	 */
120 	buffer_put_bignum(&buffer, key->rsa->d);
121 	buffer_put_bignum(&buffer, key->rsa->iqmp);
122 	buffer_put_bignum(&buffer, key->rsa->q);	/* reverse from SSL p */
123 	buffer_put_bignum(&buffer, key->rsa->p);	/* reverse from SSL q */
124 
125 	/* Pad the part to be encrypted until its size is a multiple of 8. */
126 	while (buffer_len(&buffer) % 8 != 0)
127 		buffer_put_char(&buffer, 0);
128 
129 	/* This buffer will be used to contain the data in the file. */
130 	buffer_init(&encrypted);
131 
132 	/* First store keyfile id string. */
133 	for (i = 0; authfile_id_string[i]; i++)
134 		buffer_put_char(&encrypted, authfile_id_string[i]);
135 	buffer_put_char(&encrypted, 0);
136 
137 	/* Store cipher type. */
138 	buffer_put_char(&encrypted, cipher_num);
139 	buffer_put_int(&encrypted, 0);	/* For future extension */
140 
141 	/* Store public key.  This will be in plain text. */
142 	buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
143 	buffer_put_bignum(&encrypted, key->rsa->n);
144 	buffer_put_bignum(&encrypted, key->rsa->e);
145 	buffer_put_cstring(&encrypted, comment);
146 
147 	/* Allocate space for the private part of the key in the buffer. */
148 	cp = buffer_append_space(&encrypted, buffer_len(&buffer));
149 
150 	cipher_set_key_string(&ciphercontext, cipher, passphrase,
151 	    CIPHER_ENCRYPT);
152 	cipher_crypt(&ciphercontext, cp,
153 	    buffer_ptr(&buffer), buffer_len(&buffer), 0, 0);
154 	cipher_cleanup(&ciphercontext);
155 	memset(&ciphercontext, 0, sizeof(ciphercontext));
156 
157 	/* Destroy temporary data. */
158 	memset(buf, 0, sizeof(buf));
159 	buffer_free(&buffer);
160 
161 	buffer_append(blob, buffer_ptr(&encrypted), buffer_len(&encrypted));
162 	buffer_free(&encrypted);
163 
164 	return 1;
165 }
166 
167 /* convert SSH v2 key in OpenSSL PEM format */
168 static int
169 key_private_pem_to_blob(Key *key, Buffer *blob, const char *_passphrase,
170     const char *comment)
171 {
172 	int success = 0;
173 	int blen, len = strlen(_passphrase);
174 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
175 #if (OPENSSL_VERSION_NUMBER < 0x00907000L)
176 	const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
177 #else
178 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
179 #endif
180 	const u_char *bptr;
181 	BIO *bio;
182 
183 	if (len > 0 && len <= 4) {
184 		error("passphrase too short: have %d bytes, need > 4", len);
185 		return 0;
186 	}
187 	if ((bio = BIO_new(BIO_s_mem())) == NULL) {
188 		error("%s: BIO_new failed", __func__);
189 		return 0;
190 	}
191 	switch (key->type) {
192 	case KEY_DSA:
193 		success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
194 		    cipher, passphrase, len, NULL, NULL);
195 		break;
196 #ifdef OPENSSL_HAS_ECC
197 	case KEY_ECDSA:
198 		success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
199 		    cipher, passphrase, len, NULL, NULL);
200 		break;
201 #endif
202 	case KEY_RSA:
203 		success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
204 		    cipher, passphrase, len, NULL, NULL);
205 		break;
206 	}
207 	if (success) {
208 		if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0)
209 			success = 0;
210 		else
211 			buffer_append(blob, bptr, blen);
212 	}
213 	BIO_free(bio);
214 	return success;
215 }
216 
217 /* Save a key blob to a file */
218 static int
219 key_save_private_blob(Buffer *keybuf, const char *filename)
220 {
221 	int fd;
222 
223 	if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0) {
224 		error("open %s failed: %s.", filename, strerror(errno));
225 		return 0;
226 	}
227 	if (atomicio(vwrite, fd, buffer_ptr(keybuf),
228 	    buffer_len(keybuf)) != buffer_len(keybuf)) {
229 		error("write to key file %s failed: %s", filename,
230 		    strerror(errno));
231 		close(fd);
232 		unlink(filename);
233 		return 0;
234 	}
235 	close(fd);
236 	return 1;
237 }
238 
239 /* Serialise "key" to buffer "blob" */
240 static int
241 key_private_to_blob(Key *key, Buffer *blob, const char *passphrase,
242     const char *comment)
243 {
244 	switch (key->type) {
245 	case KEY_RSA1:
246 		return key_private_rsa1_to_blob(key, blob, passphrase, comment);
247 	case KEY_DSA:
248 	case KEY_ECDSA:
249 	case KEY_RSA:
250 		return key_private_pem_to_blob(key, blob, passphrase, comment);
251 	default:
252 		error("%s: cannot save key type %d", __func__, key->type);
253 		return 0;
254 	}
255 }
256 
257 int
258 key_save_private(Key *key, const char *filename, const char *passphrase,
259     const char *comment)
260 {
261 	Buffer keyblob;
262 	int success = 0;
263 
264 	buffer_init(&keyblob);
265 	if (!key_private_to_blob(key, &keyblob, passphrase, comment))
266 		goto out;
267 	if (!key_save_private_blob(&keyblob, filename))
268 		goto out;
269 	success = 1;
270  out:
271 	buffer_free(&keyblob);
272 	return success;
273 }
274 
275 /*
276  * Parse the public, unencrypted portion of a RSA1 key.
277  */
278 static Key *
279 key_parse_public_rsa1(Buffer *blob, char **commentp)
280 {
281 	Key *pub;
282 	Buffer copy;
283 
284 	/* Check that it is at least big enough to contain the ID string. */
285 	if (buffer_len(blob) < sizeof(authfile_id_string)) {
286 		debug3("Truncated RSA1 identifier");
287 		return NULL;
288 	}
289 
290 	/*
291 	 * Make sure it begins with the id string.  Consume the id string
292 	 * from the buffer.
293 	 */
294 	if (memcmp(buffer_ptr(blob), authfile_id_string,
295 	    sizeof(authfile_id_string)) != 0) {
296 		debug3("Incorrect RSA1 identifier");
297 		return NULL;
298 	}
299 	buffer_init(&copy);
300 	buffer_append(&copy, buffer_ptr(blob), buffer_len(blob));
301 	buffer_consume(&copy, sizeof(authfile_id_string));
302 
303 	/* Skip cipher type and reserved data. */
304 	(void) buffer_get_char(&copy);		/* cipher type */
305 	(void) buffer_get_int(&copy);		/* reserved */
306 
307 	/* Read the public key from the buffer. */
308 	(void) buffer_get_int(&copy);
309 	pub = key_new(KEY_RSA1);
310 	buffer_get_bignum(&copy, pub->rsa->n);
311 	buffer_get_bignum(&copy, pub->rsa->e);
312 	if (commentp)
313 		*commentp = buffer_get_string(&copy, NULL);
314 	/* The encrypted private part is not parsed by this function. */
315 	buffer_free(&copy);
316 
317 	return pub;
318 }
319 
320 /* Load a key from a fd into a buffer */
321 int
322 key_load_file(int fd, const char *filename, Buffer *blob)
323 {
324 	u_char buf[1024];
325 	size_t len;
326 	struct stat st;
327 
328 	if (fstat(fd, &st) < 0) {
329 		error("%s: fstat of key file %.200s%sfailed: %.100s", __func__,
330 		    filename == NULL ? "" : filename,
331 		    filename == NULL ? "" : " ",
332 		    strerror(errno));
333 		return 0;
334 	}
335 	if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
336 	    st.st_size > MAX_KEY_FILE_SIZE) {
337  toobig:
338 		error("%s: key file %.200s%stoo large", __func__,
339 		    filename == NULL ? "" : filename,
340 		    filename == NULL ? "" : " ");
341 		return 0;
342 	}
343 	buffer_clear(blob);
344 	for (;;) {
345 		if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
346 			if (errno == EPIPE)
347 				break;
348 			debug("%s: read from key file %.200s%sfailed: %.100s",
349 			    __func__, filename == NULL ? "" : filename,
350 			    filename == NULL ? "" : " ", strerror(errno));
351 			buffer_clear(blob);
352 			bzero(buf, sizeof(buf));
353 			return 0;
354 		}
355 		buffer_append(blob, buf, len);
356 		if (buffer_len(blob) > MAX_KEY_FILE_SIZE) {
357 			buffer_clear(blob);
358 			bzero(buf, sizeof(buf));
359 			goto toobig;
360 		}
361 	}
362 	bzero(buf, sizeof(buf));
363 	if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
364 	    st.st_size != buffer_len(blob)) {
365 		debug("%s: key file %.200s%schanged size while reading",
366 		    __func__, filename == NULL ? "" : filename,
367 		    filename == NULL ? "" : " ");
368 		buffer_clear(blob);
369 		return 0;
370 	}
371 
372 	return 1;
373 }
374 
375 /*
376  * Loads the public part of the ssh v1 key file.  Returns NULL if an error was
377  * encountered (the file does not exist or is not readable), and the key
378  * otherwise.
379  */
380 static Key *
381 key_load_public_rsa1(int fd, const char *filename, char **commentp)
382 {
383 	Buffer buffer;
384 	Key *pub;
385 
386 	buffer_init(&buffer);
387 	if (!key_load_file(fd, filename, &buffer)) {
388 		buffer_free(&buffer);
389 		return NULL;
390 	}
391 
392 	pub = key_parse_public_rsa1(&buffer, commentp);
393 	if (pub == NULL)
394 		debug3("Could not load \"%s\" as a RSA1 public key", filename);
395 	buffer_free(&buffer);
396 	return pub;
397 }
398 
399 /* load public key from private-key file, works only for SSH v1 */
400 Key *
401 key_load_public_type(int type, const char *filename, char **commentp)
402 {
403 	Key *pub;
404 	int fd;
405 
406 	if (type == KEY_RSA1) {
407 		fd = open(filename, O_RDONLY);
408 		if (fd < 0)
409 			return NULL;
410 		pub = key_load_public_rsa1(fd, filename, commentp);
411 		close(fd);
412 		return pub;
413 	}
414 	return NULL;
415 }
416 
417 static Key *
418 key_parse_private_rsa1(Buffer *blob, const char *passphrase, char **commentp)
419 {
420 	int check1, check2, cipher_type;
421 	Buffer decrypted;
422 	u_char *cp;
423 	CipherContext ciphercontext;
424 	Cipher *cipher;
425 	Key *prv = NULL;
426 	Buffer copy;
427 
428 	/* Check that it is at least big enough to contain the ID string. */
429 	if (buffer_len(blob) < sizeof(authfile_id_string)) {
430 		debug3("Truncated RSA1 identifier");
431 		return NULL;
432 	}
433 
434 	/*
435 	 * Make sure it begins with the id string.  Consume the id string
436 	 * from the buffer.
437 	 */
438 	if (memcmp(buffer_ptr(blob), authfile_id_string,
439 	    sizeof(authfile_id_string)) != 0) {
440 		debug3("Incorrect RSA1 identifier");
441 		return NULL;
442 	}
443 	buffer_init(&copy);
444 	buffer_append(&copy, buffer_ptr(blob), buffer_len(blob));
445 	buffer_consume(&copy, sizeof(authfile_id_string));
446 
447 	/* Read cipher type. */
448 	cipher_type = buffer_get_char(&copy);
449 	(void) buffer_get_int(&copy);	/* Reserved data. */
450 
451 	/* Read the public key from the buffer. */
452 	(void) buffer_get_int(&copy);
453 	prv = key_new_private(KEY_RSA1);
454 
455 	buffer_get_bignum(&copy, prv->rsa->n);
456 	buffer_get_bignum(&copy, prv->rsa->e);
457 	if (commentp)
458 		*commentp = buffer_get_string(&copy, NULL);
459 	else
460 		(void)buffer_get_string_ptr(&copy, NULL);
461 
462 	/* Check that it is a supported cipher. */
463 	cipher = cipher_by_number(cipher_type);
464 	if (cipher == NULL) {
465 		debug("Unsupported RSA1 cipher %d", cipher_type);
466 		buffer_free(&copy);
467 		goto fail;
468 	}
469 	/* Initialize space for decrypted data. */
470 	buffer_init(&decrypted);
471 	cp = buffer_append_space(&decrypted, buffer_len(&copy));
472 
473 	/* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
474 	cipher_set_key_string(&ciphercontext, cipher, passphrase,
475 	    CIPHER_DECRYPT);
476 	cipher_crypt(&ciphercontext, cp,
477 	    buffer_ptr(&copy), buffer_len(&copy), 0, 0);
478 	cipher_cleanup(&ciphercontext);
479 	memset(&ciphercontext, 0, sizeof(ciphercontext));
480 	buffer_free(&copy);
481 
482 	check1 = buffer_get_char(&decrypted);
483 	check2 = buffer_get_char(&decrypted);
484 	if (check1 != buffer_get_char(&decrypted) ||
485 	    check2 != buffer_get_char(&decrypted)) {
486 		if (strcmp(passphrase, "") != 0)
487 			debug("Bad passphrase supplied for RSA1 key");
488 		/* Bad passphrase. */
489 		buffer_free(&decrypted);
490 		goto fail;
491 	}
492 	/* Read the rest of the private key. */
493 	buffer_get_bignum(&decrypted, prv->rsa->d);
494 	buffer_get_bignum(&decrypted, prv->rsa->iqmp);		/* u */
495 	/* in SSL and SSH v1 p and q are exchanged */
496 	buffer_get_bignum(&decrypted, prv->rsa->q);		/* p */
497 	buffer_get_bignum(&decrypted, prv->rsa->p);		/* q */
498 
499 	/* calculate p-1 and q-1 */
500 	rsa_generate_additional_parameters(prv->rsa);
501 
502 	buffer_free(&decrypted);
503 
504 	/* enable blinding */
505 	if (RSA_blinding_on(prv->rsa, NULL) != 1) {
506 		error("%s: RSA_blinding_on failed", __func__);
507 		goto fail;
508 	}
509 	return prv;
510 
511 fail:
512 	if (commentp)
513 		xfree(*commentp);
514 	key_free(prv);
515 	return NULL;
516 }
517 
518 static Key *
519 key_parse_private_pem(Buffer *blob, int type, const char *passphrase,
520     char **commentp)
521 {
522 	EVP_PKEY *pk = NULL;
523 	Key *prv = NULL;
524 	char *name = "<no key>";
525 	BIO *bio;
526 
527 	if ((bio = BIO_new_mem_buf(buffer_ptr(blob),
528 	    buffer_len(blob))) == NULL) {
529 		error("%s: BIO_new_mem_buf failed", __func__);
530 		return NULL;
531 	}
532 
533 	pk = PEM_read_bio_PrivateKey(bio, NULL, NULL, (char *)passphrase);
534 	BIO_free(bio);
535 	if (pk == NULL) {
536 		debug("%s: PEM_read_PrivateKey failed", __func__);
537 		(void)ERR_get_error();
538 	} else if (pk->type == EVP_PKEY_RSA &&
539 	    (type == KEY_UNSPEC||type==KEY_RSA)) {
540 		prv = key_new(KEY_UNSPEC);
541 		prv->rsa = EVP_PKEY_get1_RSA(pk);
542 		prv->type = KEY_RSA;
543 		name = "rsa w/o comment";
544 #ifdef DEBUG_PK
545 		RSA_print_fp(stderr, prv->rsa, 8);
546 #endif
547 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
548 			error("%s: RSA_blinding_on failed", __func__);
549 			key_free(prv);
550 			prv = NULL;
551 		}
552 	} else if (pk->type == EVP_PKEY_DSA &&
553 	    (type == KEY_UNSPEC||type==KEY_DSA)) {
554 		prv = key_new(KEY_UNSPEC);
555 		prv->dsa = EVP_PKEY_get1_DSA(pk);
556 		prv->type = KEY_DSA;
557 		name = "dsa w/o comment";
558 #ifdef DEBUG_PK
559 		DSA_print_fp(stderr, prv->dsa, 8);
560 #endif
561 #ifdef OPENSSL_HAS_ECC
562 	} else if (pk->type == EVP_PKEY_EC &&
563 	    (type == KEY_UNSPEC||type==KEY_ECDSA)) {
564 		prv = key_new(KEY_UNSPEC);
565 		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
566 		prv->type = KEY_ECDSA;
567 		if ((prv->ecdsa_nid = key_ecdsa_key_to_nid(prv->ecdsa)) == -1 ||
568 		    key_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
569 		    key_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
570 		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
571 		    key_ec_validate_private(prv->ecdsa) != 0) {
572 			error("%s: bad ECDSA key", __func__);
573 			key_free(prv);
574 			prv = NULL;
575 		}
576 		name = "ecdsa w/o comment";
577 #ifdef DEBUG_PK
578 		if (prv != NULL && prv->ecdsa != NULL)
579 			key_dump_ec_key(prv->ecdsa);
580 #endif
581 #endif /* OPENSSL_HAS_ECC */
582 	} else {
583 		error("%s: PEM_read_PrivateKey: mismatch or "
584 		    "unknown EVP_PKEY save_type %d", __func__, pk->save_type);
585 	}
586 	if (pk != NULL)
587 		EVP_PKEY_free(pk);
588 	if (prv != NULL && commentp)
589 		*commentp = xstrdup(name);
590 	debug("read PEM private key done: type %s",
591 	    prv ? key_type(prv) : "<unknown>");
592 	return prv;
593 }
594 
595 Key *
596 key_load_private_pem(int fd, int type, const char *passphrase,
597     char **commentp)
598 {
599 	Buffer buffer;
600 	Key *prv;
601 
602 	buffer_init(&buffer);
603 	if (!key_load_file(fd, NULL, &buffer)) {
604 		buffer_free(&buffer);
605 		return NULL;
606 	}
607 	prv = key_parse_private_pem(&buffer, type, passphrase, commentp);
608 	buffer_free(&buffer);
609 	return prv;
610 }
611 
612 int
613 key_perm_ok(int fd, const char *filename)
614 {
615 	struct stat st;
616 
617 	if (fstat(fd, &st) < 0)
618 		return 0;
619 	/*
620 	 * if a key owned by the user is accessed, then we check the
621 	 * permissions of the file. if the key owned by a different user,
622 	 * then we don't care.
623 	 */
624 #ifdef HAVE_CYGWIN
625 	if (check_ntsec(filename))
626 #endif
627 	if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
628 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
629 		error("@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @");
630 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
631 		error("Permissions 0%3.3o for '%s' are too open.",
632 		    (u_int)st.st_mode & 0777, filename);
633 		error("It is required that your private key files are NOT accessible by others.");
634 		error("This private key will be ignored.");
635 		return 0;
636 	}
637 	return 1;
638 }
639 
640 static Key *
641 key_parse_private_type(Buffer *blob, int type, const char *passphrase,
642     char **commentp)
643 {
644 	switch (type) {
645 	case KEY_RSA1:
646 		return key_parse_private_rsa1(blob, passphrase, commentp);
647 	case KEY_DSA:
648 	case KEY_ECDSA:
649 	case KEY_RSA:
650 	case KEY_UNSPEC:
651 		return key_parse_private_pem(blob, type, passphrase, commentp);
652 	default:
653 		error("%s: cannot parse key type %d", __func__, type);
654 		break;
655 	}
656 	return NULL;
657 }
658 
659 Key *
660 key_load_private_type(int type, const char *filename, const char *passphrase,
661     char **commentp, int *perm_ok)
662 {
663 	int fd;
664 	Key *ret;
665 	Buffer buffer;
666 
667 	fd = open(filename, O_RDONLY);
668 	if (fd < 0) {
669 		debug("could not open key file '%s': %s", filename,
670 		    strerror(errno));
671 		if (perm_ok != NULL)
672 			*perm_ok = 0;
673 		return NULL;
674 	}
675 	if (!key_perm_ok(fd, filename)) {
676 		if (perm_ok != NULL)
677 			*perm_ok = 0;
678 		error("bad permissions: ignore key: %s", filename);
679 		close(fd);
680 		return NULL;
681 	}
682 	if (perm_ok != NULL)
683 		*perm_ok = 1;
684 
685 	buffer_init(&buffer);
686 	if (!key_load_file(fd, filename, &buffer)) {
687 		buffer_free(&buffer);
688 		close(fd);
689 		return NULL;
690 	}
691 	close(fd);
692 	ret = key_parse_private_type(&buffer, type, passphrase, commentp);
693 	buffer_free(&buffer);
694 	return ret;
695 }
696 
697 Key *
698 key_parse_private(Buffer *buffer, const char *filename,
699     const char *passphrase, char **commentp)
700 {
701 	Key *pub, *prv;
702 
703 	/* it's a SSH v1 key if the public key part is readable */
704 	pub = key_parse_public_rsa1(buffer, commentp);
705 	if (pub == NULL) {
706 		prv = key_parse_private_type(buffer, KEY_UNSPEC,
707 		    passphrase, NULL);
708 		/* use the filename as a comment for PEM */
709 		if (commentp && prv)
710 			*commentp = xstrdup(filename);
711 	} else {
712 		key_free(pub);
713 		/* key_parse_public_rsa1() has already loaded the comment */
714 		prv = key_parse_private_type(buffer, KEY_RSA1, passphrase,
715 		    NULL);
716 	}
717 	return prv;
718 }
719 
720 Key *
721 key_load_private(const char *filename, const char *passphrase,
722     char **commentp)
723 {
724 	Key *prv;
725 	Buffer buffer;
726 	int fd;
727 
728 	fd = open(filename, O_RDONLY);
729 	if (fd < 0) {
730 		debug("could not open key file '%s': %s", filename,
731 		    strerror(errno));
732 		return NULL;
733 	}
734 	if (!key_perm_ok(fd, filename)) {
735 		error("bad permissions: ignore key: %s", filename);
736 		close(fd);
737 		return NULL;
738 	}
739 
740 	buffer_init(&buffer);
741 	if (!key_load_file(fd, filename, &buffer)) {
742 		buffer_free(&buffer);
743 		close(fd);
744 		return NULL;
745 	}
746 	close(fd);
747 
748 	prv = key_parse_private(&buffer, filename, passphrase, commentp);
749 	buffer_free(&buffer);
750 	return prv;
751 }
752 
753 static int
754 key_try_load_public(Key *k, const char *filename, char **commentp)
755 {
756 	FILE *f;
757 	char line[SSH_MAX_PUBKEY_BYTES];
758 	char *cp;
759 	u_long linenum = 0;
760 
761 	f = fopen(filename, "r");
762 	if (f != NULL) {
763 		while (read_keyfile_line(f, filename, line, sizeof(line),
764 			    &linenum) != -1) {
765 			cp = line;
766 			switch (*cp) {
767 			case '#':
768 			case '\n':
769 			case '\0':
770 				continue;
771 			}
772 			/* Abort loading if this looks like a private key */
773 			if (strncmp(cp, "-----BEGIN", 10) == 0)
774 				break;
775 			/* Skip leading whitespace. */
776 			for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
777 				;
778 			if (*cp) {
779 				if (key_read(k, &cp) == 1) {
780 					cp[strcspn(cp, "\r\n")] = '\0';
781 					if (commentp) {
782 						*commentp = xstrdup(*cp ?
783 						    cp : filename);
784 					}
785 					fclose(f);
786 					return 1;
787 				}
788 			}
789 		}
790 		fclose(f);
791 	}
792 	return 0;
793 }
794 
795 /* load public key from ssh v1 private or any pubkey file */
796 Key *
797 key_load_public(const char *filename, char **commentp)
798 {
799 	Key *pub;
800 	char file[MAXPATHLEN];
801 
802 	/* try rsa1 private key */
803 	pub = key_load_public_type(KEY_RSA1, filename, commentp);
804 	if (pub != NULL)
805 		return pub;
806 
807 	/* try rsa1 public key */
808 	pub = key_new(KEY_RSA1);
809 	if (key_try_load_public(pub, filename, commentp) == 1)
810 		return pub;
811 	key_free(pub);
812 
813 	/* try ssh2 public key */
814 	pub = key_new(KEY_UNSPEC);
815 	if (key_try_load_public(pub, filename, commentp) == 1)
816 		return pub;
817 	if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
818 	    (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
819 	    (key_try_load_public(pub, file, commentp) == 1))
820 		return pub;
821 	key_free(pub);
822 	return NULL;
823 }
824 
825 /* Load the certificate associated with the named private key */
826 Key *
827 key_load_cert(const char *filename)
828 {
829 	Key *pub;
830 	char *file;
831 
832 	pub = key_new(KEY_UNSPEC);
833 	xasprintf(&file, "%s-cert.pub", filename);
834 	if (key_try_load_public(pub, file, NULL) == 1) {
835 		xfree(file);
836 		return pub;
837 	}
838 	xfree(file);
839 	key_free(pub);
840 	return NULL;
841 }
842 
843 /* Load private key and certificate */
844 Key *
845 key_load_private_cert(int type, const char *filename, const char *passphrase,
846     int *perm_ok)
847 {
848 	Key *key, *pub;
849 
850 	switch (type) {
851 	case KEY_RSA:
852 	case KEY_DSA:
853 	case KEY_ECDSA:
854 		break;
855 	default:
856 		error("%s: unsupported key type", __func__);
857 		return NULL;
858 	}
859 
860 	if ((key = key_load_private_type(type, filename,
861 	    passphrase, NULL, perm_ok)) == NULL)
862 		return NULL;
863 
864 	if ((pub = key_load_cert(filename)) == NULL) {
865 		key_free(key);
866 		return NULL;
867 	}
868 
869 	/* Make sure the private key matches the certificate */
870 	if (key_equal_public(key, pub) == 0) {
871 		error("%s: certificate does not match private key %s",
872 		    __func__, filename);
873 	} else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
874 		error("%s: key_to_certified failed", __func__);
875 	} else {
876 		key_cert_copy(pub, key);
877 		key_free(pub);
878 		return key;
879 	}
880 
881 	key_free(key);
882 	key_free(pub);
883 	return NULL;
884 }
885 
886 /*
887  * Returns 1 if the specified "key" is listed in the file "filename",
888  * 0 if the key is not listed or -1 on error.
889  * If strict_type is set then the key type must match exactly,
890  * otherwise a comparison that ignores certficiate data is performed.
891  */
892 int
893 key_in_file(Key *key, const char *filename, int strict_type)
894 {
895 	FILE *f;
896 	char line[SSH_MAX_PUBKEY_BYTES];
897 	char *cp;
898 	u_long linenum = 0;
899 	int ret = 0;
900 	Key *pub;
901 	int (*key_compare)(const Key *, const Key *) = strict_type ?
902 	    key_equal : key_equal_public;
903 
904 	if ((f = fopen(filename, "r")) == NULL) {
905 		if (errno == ENOENT) {
906 			debug("%s: keyfile \"%s\" missing", __func__, filename);
907 			return 0;
908 		} else {
909 			error("%s: could not open keyfile \"%s\": %s", __func__,
910 			    filename, strerror(errno));
911 			return -1;
912 		}
913 	}
914 
915 	while (read_keyfile_line(f, filename, line, sizeof(line),
916 		    &linenum) != -1) {
917 		cp = line;
918 
919 		/* Skip leading whitespace. */
920 		for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
921 			;
922 
923 		/* Skip comments and empty lines */
924 		switch (*cp) {
925 		case '#':
926 		case '\n':
927 		case '\0':
928 			continue;
929 		}
930 
931 		pub = key_new(KEY_UNSPEC);
932 		if (key_read(pub, &cp) != 1) {
933 			key_free(pub);
934 			continue;
935 		}
936 		if (key_compare(key, pub)) {
937 			ret = 1;
938 			key_free(pub);
939 			break;
940 		}
941 		key_free(pub);
942 	}
943 	fclose(f);
944 	return ret;
945 }
946 
947