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