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