xref: /netbsd-src/crypto/external/bsd/openssh/dist/authfile.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: authfile.c,v 1.3 2010/11/21 18:29:48 adam Exp $	*/
2 /* $OpenBSD: authfile.c,v 1.82 2010/08/04 05:49:22 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.3 2010/11/21 18:29:48 adam 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 /* Version identification string for SSH v1 identity files. */
70 static const char authfile_id_string[] =
71     "SSH PRIVATE KEY FILE FORMAT 1.1\n";
72 
73 /*
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
77  * passphrase.
78  */
79 
80 static int
81 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
82     const char *comment)
83 {
84 	Buffer buffer, encrypted;
85 	u_char buf[100], *cp;
86 	int fd, i, cipher_num;
87 	CipherContext ciphercontext;
88 	Cipher *cipher;
89 	u_int32_t rnd;
90 
91 	/*
92 	 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
93 	 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
94 	 */
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");
99 
100 	/* This buffer is used to built the secret part of the private key. */
101 	buffer_init(&buffer);
102 
103 	/* Put checkbytes for checking passphrase validity. */
104 	rnd = arc4random();
105 	buf[0] = rnd & 0xff;
106 	buf[1] = (rnd >> 8) & 0xff;
107 	buf[2] = buf[0];
108 	buf[3] = buf[1];
109 	buffer_append(&buffer, buf, 4);
110 
111 	/*
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).
115 	 */
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 */
120 
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);
124 
125 	/* This buffer will be used to contain the data in the file. */
126 	buffer_init(&encrypted);
127 
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);
132 
133 	/* Store cipher type. */
134 	buffer_put_char(&encrypted, cipher_num);
135 	buffer_put_int(&encrypted, 0);	/* For future extension */
136 
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);
142 
143 	/* Allocate space for the private part of the key in the buffer. */
144 	cp = buffer_append_space(&encrypted, buffer_len(&buffer));
145 
146 	cipher_set_key_string(&ciphercontext, cipher, passphrase,
147 	    CIPHER_ENCRYPT);
148 	cipher_crypt(&ciphercontext, cp,
149 	    buffer_ptr(&buffer), buffer_len(&buffer));
150 	cipher_cleanup(&ciphercontext);
151 	memset(&ciphercontext, 0, sizeof(ciphercontext));
152 
153 	/* Destroy temporary data. */
154 	memset(buf, 0, sizeof(buf));
155 	buffer_free(&buffer);
156 
157 	fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
158 	if (fd < 0) {
159 		error("open %s failed: %s.", filename, strerror(errno));
160 		buffer_free(&encrypted);
161 		return 0;
162 	}
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,
166 		    strerror(errno));
167 		buffer_free(&encrypted);
168 		close(fd);
169 		unlink(filename);
170 		return 0;
171 	}
172 	close(fd);
173 	buffer_free(&encrypted);
174 	return 1;
175 }
176 
177 /* save SSH v2 key in OpenSSL PEM format */
178 static int
179 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
180     const char *comment)
181 {
182 	FILE *fp;
183 	int fd;
184 	int success = 0;
185 	int len = strlen(_passphrase);
186 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
187 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
188 
189 	if (len > 0 && len <= 4) {
190 		error("passphrase too short: have %d bytes, need > 4", len);
191 		return 0;
192 	}
193 	fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
194 	if (fd < 0) {
195 		error("open %s failed: %s.", filename, strerror(errno));
196 		return 0;
197 	}
198 	fp = fdopen(fd, "w");
199 	if (fp == NULL) {
200 		error("fdopen %s failed: %s.", filename, strerror(errno));
201 		close(fd);
202 		return 0;
203 	}
204 	switch (key->type) {
205 	case KEY_DSA:
206 		success = PEM_write_DSAPrivateKey(fp, key->dsa,
207 		    cipher, passphrase, len, NULL, NULL);
208 		break;
209 	case KEY_RSA:
210 		success = PEM_write_RSAPrivateKey(fp, key->rsa,
211 		    cipher, passphrase, len, NULL, NULL);
212 		break;
213 	}
214 	fclose(fp);
215 	return success;
216 }
217 
218 int
219 key_save_private(Key *key, const char *filename, const char *passphrase,
220     const char *comment)
221 {
222 	switch (key->type) {
223 	case KEY_RSA1:
224 		return key_save_private_rsa1(key, filename, passphrase,
225 		    comment);
226 	case KEY_DSA:
227 	case KEY_RSA:
228 		return key_save_private_pem(key, filename, passphrase,
229 		    comment);
230 	default:
231 		break;
232 	}
233 	error("key_save_private: cannot save key type %d", key->type);
234 	return 0;
235 }
236 
237 /*
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
240  * otherwise.
241  */
242 
243 static Key *
244 key_load_public_rsa1(int fd, const char *filename, char **commentp)
245 {
246 	Buffer buffer;
247 	Key *pub;
248 	struct stat st;
249 	char *cp;
250 	u_int i;
251 	size_t len;
252 
253 	if (fstat(fd, &st) < 0) {
254 		error("fstat for key file %.200s failed: %.100s",
255 		    filename, strerror(errno));
256 		return NULL;
257 	}
258 	if (st.st_size > 1*1024*1024) {
259 		error("key file %.200s too large", filename);
260 		return NULL;
261 	}
262 	len = (size_t)st.st_size;		/* truncated */
263 
264 	buffer_init(&buffer);
265 	cp = buffer_append_space(&buffer, len);
266 
267 	if (atomicio(read, fd, cp, len) != len) {
268 		debug("Read from key file %.200s failed: %.100s", filename,
269 		    strerror(errno));
270 		buffer_free(&buffer);
271 		return NULL;
272 	}
273 
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);
278 		return NULL;
279 	}
280 	/*
281 	 * Make sure it begins with the id string.  Consume the id string
282 	 * from the buffer.
283 	 */
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);
288 			return NULL;
289 		}
290 	/* Skip cipher type and reserved data. */
291 	(void) buffer_get_char(&buffer);	/* cipher type */
292 	(void) buffer_get_int(&buffer);		/* reserved */
293 
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);
299 	if (commentp)
300 		*commentp = buffer_get_string(&buffer, NULL);
301 	/* The encrypted private part is not parsed by this function. */
302 
303 	buffer_free(&buffer);
304 	return pub;
305 }
306 
307 /* load public key from private-key file, works only for SSH v1 */
308 Key *
309 key_load_public_type(int type, const char *filename, char **commentp)
310 {
311 	Key *pub;
312 	int fd;
313 
314 	if (type == KEY_RSA1) {
315 		fd = open(filename, O_RDONLY);
316 		if (fd < 0)
317 			return NULL;
318 		pub = key_load_public_rsa1(fd, filename, commentp);
319 		close(fd);
320 		return pub;
321 	}
322 	return NULL;
323 }
324 
325 /*
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.
330  */
331 
332 static Key *
333 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
334     char **commentp)
335 {
336 	u_int i;
337 	int check1, check2, cipher_type;
338 	size_t len;
339 	Buffer buffer, decrypted;
340 	u_char *cp;
341 	CipherContext ciphercontext;
342 	Cipher *cipher;
343 	Key *prv = NULL;
344 	struct stat st;
345 
346 	if (fstat(fd, &st) < 0) {
347 		error("fstat for key file %.200s failed: %.100s",
348 		    filename, strerror(errno));
349 		close(fd);
350 		return NULL;
351 	}
352 	if (st.st_size > 1*1024*1024) {
353 		error("key file %.200s too large", filename);
354 		close(fd);
355 		return (NULL);
356 	}
357 	len = (size_t)st.st_size;		/* truncated */
358 
359 	buffer_init(&buffer);
360 	cp = buffer_append_space(&buffer, len);
361 
362 	if (atomicio(read, fd, cp, len) != len) {
363 		debug("Read from key file %.200s failed: %.100s", filename,
364 		    strerror(errno));
365 		buffer_free(&buffer);
366 		close(fd);
367 		return NULL;
368 	}
369 
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);
374 		close(fd);
375 		return NULL;
376 	}
377 	/*
378 	 * Make sure it begins with the id string.  Consume the id string
379 	 * from the buffer.
380 	 */
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);
385 			close(fd);
386 			return NULL;
387 		}
388 
389 	/* Read cipher type. */
390 	cipher_type = buffer_get_char(&buffer);
391 	(void) buffer_get_int(&buffer);	/* Reserved data. */
392 
393 	/* Read the public key from the buffer. */
394 	(void) buffer_get_int(&buffer);
395 	prv = key_new_private(KEY_RSA1);
396 
397 	buffer_get_bignum(&buffer, prv->rsa->n);
398 	buffer_get_bignum(&buffer, prv->rsa->e);
399 	if (commentp)
400 		*commentp = buffer_get_string(&buffer, NULL);
401 	else
402 		xfree(buffer_get_string(&buffer, NULL));
403 
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);
410 		goto fail;
411 	}
412 	/* Initialize space for decrypted data. */
413 	buffer_init(&decrypted);
414 	cp = buffer_append_space(&decrypted, buffer_len(&buffer));
415 
416 	/* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
417 	cipher_set_key_string(&ciphercontext, cipher, passphrase,
418 	    CIPHER_DECRYPT);
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);
424 
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.",
431 			    filename);
432 		/* Bad passphrase. */
433 		buffer_free(&decrypted);
434 		goto fail;
435 	}
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 */
442 
443 	/* calculate p-1 and q-1 */
444 	rsa_generate_additional_parameters(prv->rsa);
445 
446 	buffer_free(&decrypted);
447 
448 	/* enable blinding */
449 	if (RSA_blinding_on(prv->rsa, NULL) != 1) {
450 		error("key_load_private_rsa1: RSA_blinding_on failed");
451 		goto fail;
452 	}
453 	close(fd);
454 	return prv;
455 
456 fail:
457 	if (commentp)
458 		xfree(*commentp);
459 	close(fd);
460 	key_free(prv);
461 	return NULL;
462 }
463 
464 Key *
465 key_load_private_pem(int fd, int type, const char *passphrase,
466     char **commentp)
467 {
468 	FILE *fp;
469 	EVP_PKEY *pk = NULL;
470 	Key *prv = NULL;
471 	char *name = "<no key>";
472 
473 	fp = fdopen(fd, "r");
474 	if (fp == NULL) {
475 		error("fdopen failed: %s", strerror(errno));
476 		close(fd);
477 		return NULL;
478 	}
479 	pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
480 	if (pk == NULL) {
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);
487 		prv->type = KEY_RSA;
488 		name = "rsa w/o comment";
489 #ifdef DEBUG_PK
490 		RSA_print_fp(stderr, prv->rsa, 8);
491 #endif
492 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
493 			error("key_load_private_pem: RSA_blinding_on failed");
494 			key_free(prv);
495 			prv = NULL;
496 		}
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);
501 		prv->type = KEY_DSA;
502 		name = "dsa w/o comment";
503 #ifdef DEBUG_PK
504 		DSA_print_fp(stderr, prv->dsa, 8);
505 #endif
506 	} else {
507 		error("PEM_read_PrivateKey: mismatch or "
508 		    "unknown EVP_PKEY save_type %d", pk->save_type);
509 	}
510 	fclose(fp);
511 	if (pk != NULL)
512 		EVP_PKEY_free(pk);
513 	if (prv != NULL && commentp)
514 		*commentp = xstrdup(name);
515 	debug("read PEM private key done: type %s",
516 	    prv ? key_type(prv) : "<unknown>");
517 	return prv;
518 }
519 
520 int
521 key_perm_ok(int fd, const char *filename)
522 {
523 	struct stat st;
524 
525 	if (fstat(fd, &st) < 0)
526 		return 0;
527 	/*
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.
531 	 */
532 	if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
533 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
534 		error("@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @");
535 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
536 		error("Permissions 0%3.3o for '%s' are too open.",
537 		    (u_int)st.st_mode & 0777, filename);
538 		error("It is recommended that your private key files are NOT accessible by others.");
539 		error("This private key will be ignored.");
540 		return 0;
541 	}
542 	return 1;
543 }
544 
545 Key *
546 key_load_private_type(int type, const char *filename, const char *passphrase,
547     char **commentp, int *perm_ok)
548 {
549 	int fd;
550 
551 	fd = open(filename, O_RDONLY);
552 	if (fd < 0) {
553 		debug("could not open key file '%s': %s", filename,
554 		    strerror(errno));
555 		if (perm_ok != NULL)
556 			*perm_ok = 0;
557 		return NULL;
558 	}
559 	if (!key_perm_ok(fd, filename)) {
560 		if (perm_ok != NULL)
561 			*perm_ok = 0;
562 		error("bad permissions: ignore key: %s", filename);
563 		close(fd);
564 		return NULL;
565 	}
566 	if (perm_ok != NULL)
567 		*perm_ok = 1;
568 	switch (type) {
569 	case KEY_RSA1:
570 		return key_load_private_rsa1(fd, filename, passphrase,
571 		    commentp);
572 		/* closes fd */
573 	case KEY_DSA:
574 	case KEY_RSA:
575 	case KEY_UNSPEC:
576 		return key_load_private_pem(fd, type, passphrase, commentp);
577 		/* closes fd */
578 	default:
579 		close(fd);
580 		break;
581 	}
582 	return NULL;
583 }
584 
585 Key *
586 key_load_private(const char *filename, const char *passphrase,
587     char **commentp)
588 {
589 	Key *pub, *prv;
590 	int fd;
591 
592 	fd = open(filename, O_RDONLY);
593 	if (fd < 0) {
594 		debug("could not open key file '%s': %s", filename,
595 		    strerror(errno));
596 		return NULL;
597 	}
598 	if (!key_perm_ok(fd, filename)) {
599 		error("bad permissions: ignore key: %s", filename);
600 		close(fd);
601 		return NULL;
602 	}
603 	pub = key_load_public_rsa1(fd, filename, commentp);
604 	lseek(fd, (off_t) 0, SEEK_SET);		/* rewind */
605 	if (pub == NULL) {
606 		/* closes fd */
607 		prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
608 		/* use the filename as a comment for PEM */
609 		if (commentp && prv)
610 			*commentp = xstrdup(filename);
611 	} else {
612 		/* it's a SSH v1 key if the public key part is readable */
613 		key_free(pub);
614 		/* closes fd */
615 		prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
616 	}
617 	return prv;
618 }
619 
620 static int
621 key_try_load_public(Key *k, const char *filename, char **commentp)
622 {
623 	FILE *f;
624 	char line[SSH_MAX_PUBKEY_BYTES];
625 	char *cp;
626 	u_long linenum = 0;
627 
628 	f = fopen(filename, "r");
629 	if (f != NULL) {
630 		while (read_keyfile_line(f, filename, line, sizeof(line),
631 			    &linenum) != -1) {
632 			cp = line;
633 			switch (*cp) {
634 			case '#':
635 			case '\n':
636 			case '\0':
637 				continue;
638 			}
639 			/* Skip leading whitespace. */
640 			for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
641 				;
642 			if (*cp) {
643 				if (key_read(k, &cp) == 1) {
644 					if (commentp)
645 						*commentp=xstrdup(filename);
646 					fclose(f);
647 					return 1;
648 				}
649 			}
650 		}
651 		fclose(f);
652 	}
653 	return 0;
654 }
655 
656 /* load public key from ssh v1 private or any pubkey file */
657 Key *
658 key_load_public(const char *filename, char **commentp)
659 {
660 	Key *pub;
661 	char file[MAXPATHLEN];
662 
663 	/* try rsa1 private key */
664 	pub = key_load_public_type(KEY_RSA1, filename, commentp);
665 	if (pub != NULL)
666 		return pub;
667 
668 	/* try rsa1 public key */
669 	pub = key_new(KEY_RSA1);
670 	if (key_try_load_public(pub, filename, commentp) == 1)
671 		return pub;
672 	key_free(pub);
673 
674 	/* try ssh2 public key */
675 	pub = key_new(KEY_UNSPEC);
676 	if (key_try_load_public(pub, filename, commentp) == 1)
677 		return pub;
678 	if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
679 	    (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
680 	    (key_try_load_public(pub, file, commentp) == 1))
681 		return pub;
682 	key_free(pub);
683 	return NULL;
684 }
685 
686 /* Load the certificate associated with the named private key */
687 Key *
688 key_load_cert(const char *filename)
689 {
690 	Key *pub;
691 	char *file;
692 
693 	pub = key_new(KEY_UNSPEC);
694 	xasprintf(&file, "%s-cert.pub", filename);
695 	if (key_try_load_public(pub, file, NULL) == 1) {
696 		xfree(file);
697 		return pub;
698 	}
699 	xfree(file);
700 	key_free(pub);
701 	return NULL;
702 }
703 
704 /* Load private key and certificate */
705 Key *
706 key_load_private_cert(int type, const char *filename, const char *passphrase,
707     int *perm_ok)
708 {
709 	Key *key, *pub;
710 
711 	switch (type) {
712 	case KEY_RSA:
713 	case KEY_DSA:
714 		break;
715 	default:
716 		error("%s: unsupported key type", __func__);
717 		return NULL;
718 	}
719 
720 	if ((key = key_load_private_type(type, filename,
721 	    passphrase, NULL, perm_ok)) == NULL)
722 		return NULL;
723 
724 	if ((pub = key_load_cert(filename)) == NULL) {
725 		key_free(key);
726 		return NULL;
727 	}
728 
729 	/* Make sure the private key matches the certificate */
730 	if (key_equal_public(key, pub) == 0) {
731 		error("%s: certificate does not match private key %s",
732 		    __func__, filename);
733 	} else if (key_to_certified(key, key_cert_is_legacy(pub)) != 0) {
734 		error("%s: key_to_certified failed", __func__);
735 	} else {
736 		key_cert_copy(pub, key);
737 		key_free(pub);
738 		return key;
739 	}
740 
741 	key_free(key);
742 	key_free(pub);
743 	return NULL;
744 }
745 
746 /*
747  * Returns 1 if the specified "key" is listed in the file "filename",
748  * 0 if the key is not listed or -1 on error.
749  * If strict_type is set then the key type must match exactly,
750  * otherwise a comparison that ignores certficiate data is performed.
751  */
752 int
753 key_in_file(Key *key, const char *filename, int strict_type)
754 {
755 	FILE *f;
756 	char line[SSH_MAX_PUBKEY_BYTES];
757 	char *cp;
758 	u_long linenum = 0;
759 	int ret = 0;
760 	Key *pub;
761 	int (*key_compare)(const Key *, const Key *) = strict_type ?
762 	    key_equal : key_equal_public;
763 
764 	if ((f = fopen(filename, "r")) == NULL) {
765 		if (errno == ENOENT) {
766 			debug("%s: keyfile \"%s\" missing", __func__, filename);
767 			return 0;
768 		} else {
769 			error("%s: could not open keyfile \"%s\": %s", __func__,
770 			    filename, strerror(errno));
771 			return -1;
772 		}
773 	}
774 
775 	while (read_keyfile_line(f, filename, line, sizeof(line),
776 		    &linenum) != -1) {
777 		cp = line;
778 
779 		/* Skip leading whitespace. */
780 		for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
781 			;
782 
783 		/* Skip comments and empty lines */
784 		switch (*cp) {
785 		case '#':
786 		case '\n':
787 		case '\0':
788 			continue;
789 		}
790 
791 		pub = key_new(KEY_UNSPEC);
792 		if (key_read(pub, &cp) != 1) {
793 			key_free(pub);
794 			continue;
795 		}
796 		if (key_compare(key, pub)) {
797 			ret = 1;
798 			key_free(pub);
799 			break;
800 		}
801 		key_free(pub);
802 	}
803 	fclose(f);
804 	return ret;
805 }
806 
807