xref: /NextBSD/crypto/openssh/key.c (revision 95f7c2f56c7268d6ed9c2a56d357aeeac260363b)
1 /* $OpenBSD: key.c,v 1.116 2014/02/02 03:44:31 djm Exp $ */
2 /*
3  * read_bignum():
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *
6  * As far as I am concerned, the code I have written for this software
7  * can be used freely for any purpose.  Any derived versions of this
8  * software must be clearly marked as such, and if the derived work is
9  * incompatible with the protocol description in the RFC file, it must be
10  * called by a name other than "ssh" or "Secure Shell".
11  *
12  *
13  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
14  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 
37 #include "includes.h"
38 
39 #include <sys/param.h>
40 #include <sys/types.h>
41 
42 #include "crypto_api.h"
43 
44 #include <openssl/evp.h>
45 #include <openbsd-compat/openssl-compat.h>
46 
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <string.h>
50 
51 #include "xmalloc.h"
52 #include "key.h"
53 #include "rsa.h"
54 #include "uuencode.h"
55 #include "buffer.h"
56 #include "log.h"
57 #include "misc.h"
58 #include "ssh2.h"
59 #include "digest.h"
60 
61 static int to_blob(const Key *, u_char **, u_int *, int);
62 static Key *key_from_blob2(const u_char *, u_int, int);
63 
64 static struct KeyCert *
cert_new(void)65 cert_new(void)
66 {
67 	struct KeyCert *cert;
68 
69 	cert = xcalloc(1, sizeof(*cert));
70 	buffer_init(&cert->certblob);
71 	buffer_init(&cert->critical);
72 	buffer_init(&cert->extensions);
73 	cert->key_id = NULL;
74 	cert->principals = NULL;
75 	cert->signature_key = NULL;
76 	return cert;
77 }
78 
79 Key *
key_new(int type)80 key_new(int type)
81 {
82 	Key *k;
83 	RSA *rsa;
84 	DSA *dsa;
85 	k = xcalloc(1, sizeof(*k));
86 	k->type = type;
87 	k->ecdsa = NULL;
88 	k->ecdsa_nid = -1;
89 	k->dsa = NULL;
90 	k->rsa = NULL;
91 	k->cert = NULL;
92 	k->ed25519_sk = NULL;
93 	k->ed25519_pk = NULL;
94 	switch (k->type) {
95 	case KEY_RSA1:
96 	case KEY_RSA:
97 	case KEY_RSA_CERT_V00:
98 	case KEY_RSA_CERT:
99 		if ((rsa = RSA_new()) == NULL)
100 			fatal("key_new: RSA_new failed");
101 		if ((rsa->n = BN_new()) == NULL)
102 			fatal("key_new: BN_new failed");
103 		if ((rsa->e = BN_new()) == NULL)
104 			fatal("key_new: BN_new failed");
105 		k->rsa = rsa;
106 		break;
107 	case KEY_DSA:
108 	case KEY_DSA_CERT_V00:
109 	case KEY_DSA_CERT:
110 		if ((dsa = DSA_new()) == NULL)
111 			fatal("key_new: DSA_new failed");
112 		if ((dsa->p = BN_new()) == NULL)
113 			fatal("key_new: BN_new failed");
114 		if ((dsa->q = BN_new()) == NULL)
115 			fatal("key_new: BN_new failed");
116 		if ((dsa->g = BN_new()) == NULL)
117 			fatal("key_new: BN_new failed");
118 		if ((dsa->pub_key = BN_new()) == NULL)
119 			fatal("key_new: BN_new failed");
120 		k->dsa = dsa;
121 		break;
122 #ifdef OPENSSL_HAS_ECC
123 	case KEY_ECDSA:
124 	case KEY_ECDSA_CERT:
125 		/* Cannot do anything until we know the group */
126 		break;
127 #endif
128 	case KEY_ED25519:
129 	case KEY_ED25519_CERT:
130 		/* no need to prealloc */
131 		break;
132 	case KEY_UNSPEC:
133 		break;
134 	default:
135 		fatal("key_new: bad key type %d", k->type);
136 		break;
137 	}
138 
139 	if (key_is_cert(k))
140 		k->cert = cert_new();
141 
142 	return k;
143 }
144 
145 void
key_add_private(Key * k)146 key_add_private(Key *k)
147 {
148 	switch (k->type) {
149 	case KEY_RSA1:
150 	case KEY_RSA:
151 	case KEY_RSA_CERT_V00:
152 	case KEY_RSA_CERT:
153 		if ((k->rsa->d = BN_new()) == NULL)
154 			fatal("key_new_private: BN_new failed");
155 		if ((k->rsa->iqmp = BN_new()) == NULL)
156 			fatal("key_new_private: BN_new failed");
157 		if ((k->rsa->q = BN_new()) == NULL)
158 			fatal("key_new_private: BN_new failed");
159 		if ((k->rsa->p = BN_new()) == NULL)
160 			fatal("key_new_private: BN_new failed");
161 		if ((k->rsa->dmq1 = BN_new()) == NULL)
162 			fatal("key_new_private: BN_new failed");
163 		if ((k->rsa->dmp1 = BN_new()) == NULL)
164 			fatal("key_new_private: BN_new failed");
165 		break;
166 	case KEY_DSA:
167 	case KEY_DSA_CERT_V00:
168 	case KEY_DSA_CERT:
169 		if ((k->dsa->priv_key = BN_new()) == NULL)
170 			fatal("key_new_private: BN_new failed");
171 		break;
172 	case KEY_ECDSA:
173 	case KEY_ECDSA_CERT:
174 		/* Cannot do anything until we know the group */
175 		break;
176 	case KEY_ED25519:
177 	case KEY_ED25519_CERT:
178 		/* no need to prealloc */
179 		break;
180 	case KEY_UNSPEC:
181 		break;
182 	default:
183 		break;
184 	}
185 }
186 
187 Key *
key_new_private(int type)188 key_new_private(int type)
189 {
190 	Key *k = key_new(type);
191 
192 	key_add_private(k);
193 	return k;
194 }
195 
196 static void
cert_free(struct KeyCert * cert)197 cert_free(struct KeyCert *cert)
198 {
199 	u_int i;
200 
201 	buffer_free(&cert->certblob);
202 	buffer_free(&cert->critical);
203 	buffer_free(&cert->extensions);
204 	free(cert->key_id);
205 	for (i = 0; i < cert->nprincipals; i++)
206 		free(cert->principals[i]);
207 	free(cert->principals);
208 	if (cert->signature_key != NULL)
209 		key_free(cert->signature_key);
210 	free(cert);
211 }
212 
213 void
key_free(Key * k)214 key_free(Key *k)
215 {
216 	if (k == NULL)
217 		fatal("key_free: key is NULL");
218 	switch (k->type) {
219 	case KEY_RSA1:
220 	case KEY_RSA:
221 	case KEY_RSA_CERT_V00:
222 	case KEY_RSA_CERT:
223 		if (k->rsa != NULL)
224 			RSA_free(k->rsa);
225 		k->rsa = NULL;
226 		break;
227 	case KEY_DSA:
228 	case KEY_DSA_CERT_V00:
229 	case KEY_DSA_CERT:
230 		if (k->dsa != NULL)
231 			DSA_free(k->dsa);
232 		k->dsa = NULL;
233 		break;
234 #ifdef OPENSSL_HAS_ECC
235 	case KEY_ECDSA:
236 	case KEY_ECDSA_CERT:
237 		if (k->ecdsa != NULL)
238 			EC_KEY_free(k->ecdsa);
239 		k->ecdsa = NULL;
240 		break;
241 #endif
242 	case KEY_ED25519:
243 	case KEY_ED25519_CERT:
244 		if (k->ed25519_pk) {
245 			explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
246 			free(k->ed25519_pk);
247 			k->ed25519_pk = NULL;
248 		}
249 		if (k->ed25519_sk) {
250 			explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
251 			free(k->ed25519_sk);
252 			k->ed25519_sk = NULL;
253 		}
254 		break;
255 	case KEY_UNSPEC:
256 		break;
257 	default:
258 		fatal("key_free: bad key type %d", k->type);
259 		break;
260 	}
261 	if (key_is_cert(k)) {
262 		if (k->cert != NULL)
263 			cert_free(k->cert);
264 		k->cert = NULL;
265 	}
266 
267 	free(k);
268 }
269 
270 static int
cert_compare(struct KeyCert * a,struct KeyCert * b)271 cert_compare(struct KeyCert *a, struct KeyCert *b)
272 {
273 	if (a == NULL && b == NULL)
274 		return 1;
275 	if (a == NULL || b == NULL)
276 		return 0;
277 	if (buffer_len(&a->certblob) != buffer_len(&b->certblob))
278 		return 0;
279 	if (timingsafe_bcmp(buffer_ptr(&a->certblob), buffer_ptr(&b->certblob),
280 	    buffer_len(&a->certblob)) != 0)
281 		return 0;
282 	return 1;
283 }
284 
285 /*
286  * Compare public portions of key only, allowing comparisons between
287  * certificates and plain keys too.
288  */
289 int
key_equal_public(const Key * a,const Key * b)290 key_equal_public(const Key *a, const Key *b)
291 {
292 #ifdef OPENSSL_HAS_ECC
293 	BN_CTX *bnctx;
294 #endif
295 
296 	if (a == NULL || b == NULL ||
297 	    key_type_plain(a->type) != key_type_plain(b->type))
298 		return 0;
299 
300 	switch (a->type) {
301 	case KEY_RSA1:
302 	case KEY_RSA_CERT_V00:
303 	case KEY_RSA_CERT:
304 	case KEY_RSA:
305 		return a->rsa != NULL && b->rsa != NULL &&
306 		    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
307 		    BN_cmp(a->rsa->n, b->rsa->n) == 0;
308 	case KEY_DSA_CERT_V00:
309 	case KEY_DSA_CERT:
310 	case KEY_DSA:
311 		return a->dsa != NULL && b->dsa != NULL &&
312 		    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
313 		    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
314 		    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
315 		    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
316 #ifdef OPENSSL_HAS_ECC
317 	case KEY_ECDSA_CERT:
318 	case KEY_ECDSA:
319 		if (a->ecdsa == NULL || b->ecdsa == NULL ||
320 		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
321 		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
322 			return 0;
323 		if ((bnctx = BN_CTX_new()) == NULL)
324 			fatal("%s: BN_CTX_new failed", __func__);
325 		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
326 		    EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
327 		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
328 		    EC_KEY_get0_public_key(a->ecdsa),
329 		    EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
330 			BN_CTX_free(bnctx);
331 			return 0;
332 		}
333 		BN_CTX_free(bnctx);
334 		return 1;
335 #endif /* OPENSSL_HAS_ECC */
336 	case KEY_ED25519:
337 	case KEY_ED25519_CERT:
338 		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
339 		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
340 	default:
341 		fatal("key_equal: bad key type %d", a->type);
342 	}
343 	/* NOTREACHED */
344 }
345 
346 int
key_equal(const Key * a,const Key * b)347 key_equal(const Key *a, const Key *b)
348 {
349 	if (a == NULL || b == NULL || a->type != b->type)
350 		return 0;
351 	if (key_is_cert(a)) {
352 		if (!cert_compare(a->cert, b->cert))
353 			return 0;
354 	}
355 	return key_equal_public(a, b);
356 }
357 
358 u_char*
key_fingerprint_raw(const Key * k,enum fp_type dgst_type,u_int * dgst_raw_length)359 key_fingerprint_raw(const Key *k, enum fp_type dgst_type,
360     u_int *dgst_raw_length)
361 {
362 	u_char *blob = NULL;
363 	u_char *retval = NULL;
364 	u_int len = 0;
365 	int nlen, elen, hash_alg = -1;
366 
367 	*dgst_raw_length = 0;
368 
369 	/* XXX switch to DIGEST_* directly? */
370 	switch (dgst_type) {
371 	case SSH_FP_MD5:
372 		hash_alg = SSH_DIGEST_MD5;
373 		break;
374 	case SSH_FP_SHA1:
375 		hash_alg = SSH_DIGEST_SHA1;
376 		break;
377 	case SSH_FP_SHA256:
378 		hash_alg = SSH_DIGEST_SHA256;
379 		break;
380 	default:
381 		fatal("%s: bad digest type %d", __func__, dgst_type);
382 	}
383 	switch (k->type) {
384 	case KEY_RSA1:
385 		nlen = BN_num_bytes(k->rsa->n);
386 		elen = BN_num_bytes(k->rsa->e);
387 		len = nlen + elen;
388 		blob = xmalloc(len);
389 		BN_bn2bin(k->rsa->n, blob);
390 		BN_bn2bin(k->rsa->e, blob + nlen);
391 		break;
392 	case KEY_DSA:
393 	case KEY_ECDSA:
394 	case KEY_RSA:
395 	case KEY_ED25519:
396 		key_to_blob(k, &blob, &len);
397 		break;
398 	case KEY_DSA_CERT_V00:
399 	case KEY_RSA_CERT_V00:
400 	case KEY_DSA_CERT:
401 	case KEY_ECDSA_CERT:
402 	case KEY_RSA_CERT:
403 	case KEY_ED25519_CERT:
404 		/* We want a fingerprint of the _key_ not of the cert */
405 		to_blob(k, &blob, &len, 1);
406 		break;
407 	case KEY_UNSPEC:
408 		return retval;
409 	default:
410 		fatal("%s: bad key type %d", __func__, k->type);
411 		break;
412 	}
413 	if (blob != NULL) {
414 		retval = xmalloc(SSH_DIGEST_MAX_LENGTH);
415 		if ((ssh_digest_memory(hash_alg, blob, len,
416 		    retval, SSH_DIGEST_MAX_LENGTH)) != 0)
417 			fatal("%s: digest_memory failed", __func__);
418 		explicit_bzero(blob, len);
419 		free(blob);
420 		*dgst_raw_length = ssh_digest_bytes(hash_alg);
421 	} else {
422 		fatal("%s: blob is null", __func__);
423 	}
424 	return retval;
425 }
426 
427 static char *
key_fingerprint_hex(u_char * dgst_raw,u_int dgst_raw_len)428 key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len)
429 {
430 	char *retval;
431 	u_int i;
432 
433 	retval = xcalloc(1, dgst_raw_len * 3 + 1);
434 	for (i = 0; i < dgst_raw_len; i++) {
435 		char hex[4];
436 		snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]);
437 		strlcat(retval, hex, dgst_raw_len * 3 + 1);
438 	}
439 
440 	/* Remove the trailing ':' character */
441 	retval[(dgst_raw_len * 3) - 1] = '\0';
442 	return retval;
443 }
444 
445 static char *
key_fingerprint_bubblebabble(u_char * dgst_raw,u_int dgst_raw_len)446 key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len)
447 {
448 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
449 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
450 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
451 	u_int i, j = 0, rounds, seed = 1;
452 	char *retval;
453 
454 	rounds = (dgst_raw_len / 2) + 1;
455 	retval = xcalloc((rounds * 6), sizeof(char));
456 	retval[j++] = 'x';
457 	for (i = 0; i < rounds; i++) {
458 		u_int idx0, idx1, idx2, idx3, idx4;
459 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
460 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
461 			    seed) % 6;
462 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
463 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
464 			    (seed / 6)) % 6;
465 			retval[j++] = vowels[idx0];
466 			retval[j++] = consonants[idx1];
467 			retval[j++] = vowels[idx2];
468 			if ((i + 1) < rounds) {
469 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
470 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
471 				retval[j++] = consonants[idx3];
472 				retval[j++] = '-';
473 				retval[j++] = consonants[idx4];
474 				seed = ((seed * 5) +
475 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
476 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
477 			}
478 		} else {
479 			idx0 = seed % 6;
480 			idx1 = 16;
481 			idx2 = seed / 6;
482 			retval[j++] = vowels[idx0];
483 			retval[j++] = consonants[idx1];
484 			retval[j++] = vowels[idx2];
485 		}
486 	}
487 	retval[j++] = 'x';
488 	retval[j++] = '\0';
489 	return retval;
490 }
491 
492 /*
493  * Draw an ASCII-Art representing the fingerprint so human brain can
494  * profit from its built-in pattern recognition ability.
495  * This technique is called "random art" and can be found in some
496  * scientific publications like this original paper:
497  *
498  * "Hash Visualization: a New Technique to improve Real-World Security",
499  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
500  * Techniques and E-Commerce (CrypTEC '99)
501  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
502  *
503  * The subject came up in a talk by Dan Kaminsky, too.
504  *
505  * If you see the picture is different, the key is different.
506  * If the picture looks the same, you still know nothing.
507  *
508  * The algorithm used here is a worm crawling over a discrete plane,
509  * leaving a trace (augmenting the field) everywhere it goes.
510  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
511  * makes the respective movement vector be ignored for this turn.
512  * Graphs are not unambiguous, because circles in graphs can be
513  * walked in either direction.
514  */
515 
516 /*
517  * Field sizes for the random art.  Have to be odd, so the starting point
518  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
519  * Else pictures would be too dense, and drawing the frame would
520  * fail, too, because the key type would not fit in anymore.
521  */
522 #define	FLDBASE		8
523 #define	FLDSIZE_Y	(FLDBASE + 1)
524 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
525 static char *
key_fingerprint_randomart(u_char * dgst_raw,u_int dgst_raw_len,const Key * k)526 key_fingerprint_randomart(u_char *dgst_raw, u_int dgst_raw_len, const Key *k)
527 {
528 	/*
529 	 * Chars to be used after each other every time the worm
530 	 * intersects with itself.  Matter of taste.
531 	 */
532 	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
533 	char	*retval, *p;
534 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
535 	u_int	 i, b;
536 	int	 x, y;
537 	size_t	 len = strlen(augmentation_string) - 1;
538 
539 	retval = xcalloc(1, (FLDSIZE_X + 3) * (FLDSIZE_Y + 2));
540 
541 	/* initialize field */
542 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
543 	x = FLDSIZE_X / 2;
544 	y = FLDSIZE_Y / 2;
545 
546 	/* process raw key */
547 	for (i = 0; i < dgst_raw_len; i++) {
548 		int input;
549 		/* each byte conveys four 2-bit move commands */
550 		input = dgst_raw[i];
551 		for (b = 0; b < 4; b++) {
552 			/* evaluate 2 bit, rest is shifted later */
553 			x += (input & 0x1) ? 1 : -1;
554 			y += (input & 0x2) ? 1 : -1;
555 
556 			/* assure we are still in bounds */
557 			x = MAX(x, 0);
558 			y = MAX(y, 0);
559 			x = MIN(x, FLDSIZE_X - 1);
560 			y = MIN(y, FLDSIZE_Y - 1);
561 
562 			/* augment the field */
563 			if (field[x][y] < len - 2)
564 				field[x][y]++;
565 			input = input >> 2;
566 		}
567 	}
568 
569 	/* mark starting point and end point*/
570 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
571 	field[x][y] = len;
572 
573 	/* fill in retval */
574 	snprintf(retval, FLDSIZE_X, "+--[%4s %4u]", key_type(k), key_size(k));
575 	p = strchr(retval, '\0');
576 
577 	/* output upper border */
578 	for (i = p - retval - 1; i < FLDSIZE_X; i++)
579 		*p++ = '-';
580 	*p++ = '+';
581 	*p++ = '\n';
582 
583 	/* output content */
584 	for (y = 0; y < FLDSIZE_Y; y++) {
585 		*p++ = '|';
586 		for (x = 0; x < FLDSIZE_X; x++)
587 			*p++ = augmentation_string[MIN(field[x][y], len)];
588 		*p++ = '|';
589 		*p++ = '\n';
590 	}
591 
592 	/* output lower border */
593 	*p++ = '+';
594 	for (i = 0; i < FLDSIZE_X; i++)
595 		*p++ = '-';
596 	*p++ = '+';
597 
598 	return retval;
599 }
600 
601 char *
key_fingerprint(const Key * k,enum fp_type dgst_type,enum fp_rep dgst_rep)602 key_fingerprint(const Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep)
603 {
604 	char *retval = NULL;
605 	u_char *dgst_raw;
606 	u_int dgst_raw_len;
607 
608 	dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len);
609 	if (!dgst_raw)
610 		fatal("key_fingerprint: null from key_fingerprint_raw()");
611 	switch (dgst_rep) {
612 	case SSH_FP_HEX:
613 		retval = key_fingerprint_hex(dgst_raw, dgst_raw_len);
614 		break;
615 	case SSH_FP_BUBBLEBABBLE:
616 		retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
617 		break;
618 	case SSH_FP_RANDOMART:
619 		retval = key_fingerprint_randomart(dgst_raw, dgst_raw_len, k);
620 		break;
621 	default:
622 		fatal("key_fingerprint: bad digest representation %d",
623 		    dgst_rep);
624 		break;
625 	}
626 	explicit_bzero(dgst_raw, dgst_raw_len);
627 	free(dgst_raw);
628 	return retval;
629 }
630 
631 /*
632  * Reads a multiple-precision integer in decimal from the buffer, and advances
633  * the pointer.  The integer must already be initialized.  This function is
634  * permitted to modify the buffer.  This leaves *cpp to point just beyond the
635  * last processed (and maybe modified) character.  Note that this may modify
636  * the buffer containing the number.
637  */
638 static int
read_bignum(char ** cpp,BIGNUM * value)639 read_bignum(char **cpp, BIGNUM * value)
640 {
641 	char *cp = *cpp;
642 	int old;
643 
644 	/* Skip any leading whitespace. */
645 	for (; *cp == ' ' || *cp == '\t'; cp++)
646 		;
647 
648 	/* Check that it begins with a decimal digit. */
649 	if (*cp < '0' || *cp > '9')
650 		return 0;
651 
652 	/* Save starting position. */
653 	*cpp = cp;
654 
655 	/* Move forward until all decimal digits skipped. */
656 	for (; *cp >= '0' && *cp <= '9'; cp++)
657 		;
658 
659 	/* Save the old terminating character, and replace it by \0. */
660 	old = *cp;
661 	*cp = 0;
662 
663 	/* Parse the number. */
664 	if (BN_dec2bn(&value, *cpp) == 0)
665 		return 0;
666 
667 	/* Restore old terminating character. */
668 	*cp = old;
669 
670 	/* Move beyond the number and return success. */
671 	*cpp = cp;
672 	return 1;
673 }
674 
675 static int
write_bignum(FILE * f,BIGNUM * num)676 write_bignum(FILE *f, BIGNUM *num)
677 {
678 	char *buf = BN_bn2dec(num);
679 	if (buf == NULL) {
680 		error("write_bignum: BN_bn2dec() failed");
681 		return 0;
682 	}
683 	fprintf(f, " %s", buf);
684 	OPENSSL_free(buf);
685 	return 1;
686 }
687 
688 /* returns 1 ok, -1 error */
689 int
key_read(Key * ret,char ** cpp)690 key_read(Key *ret, char **cpp)
691 {
692 	Key *k;
693 	int success = -1;
694 	char *cp, *space;
695 	int len, n, type;
696 	u_int bits;
697 	u_char *blob;
698 #ifdef OPENSSL_HAS_ECC
699 	int curve_nid = -1;
700 #endif
701 
702 	cp = *cpp;
703 
704 	switch (ret->type) {
705 	case KEY_RSA1:
706 		/* Get number of bits. */
707 		if (*cp < '0' || *cp > '9')
708 			return -1;	/* Bad bit count... */
709 		for (bits = 0; *cp >= '0' && *cp <= '9'; cp++)
710 			bits = 10 * bits + *cp - '0';
711 		if (bits == 0)
712 			return -1;
713 		*cpp = cp;
714 		/* Get public exponent, public modulus. */
715 		if (!read_bignum(cpp, ret->rsa->e))
716 			return -1;
717 		if (!read_bignum(cpp, ret->rsa->n))
718 			return -1;
719 		/* validate the claimed number of bits */
720 		if ((u_int)BN_num_bits(ret->rsa->n) != bits) {
721 			verbose("key_read: claimed key size %d does not match "
722 			   "actual %d", bits, BN_num_bits(ret->rsa->n));
723 			return -1;
724 		}
725 		success = 1;
726 		break;
727 	case KEY_UNSPEC:
728 	case KEY_RSA:
729 	case KEY_DSA:
730 	case KEY_ECDSA:
731 	case KEY_ED25519:
732 	case KEY_DSA_CERT_V00:
733 	case KEY_RSA_CERT_V00:
734 	case KEY_DSA_CERT:
735 	case KEY_ECDSA_CERT:
736 	case KEY_RSA_CERT:
737 	case KEY_ED25519_CERT:
738 		space = strchr(cp, ' ');
739 		if (space == NULL) {
740 			debug3("key_read: missing whitespace");
741 			return -1;
742 		}
743 		*space = '\0';
744 		type = key_type_from_name(cp);
745 #ifdef OPENSSL_HAS_ECC
746 		if (key_type_plain(type) == KEY_ECDSA &&
747 		    (curve_nid = key_ecdsa_nid_from_name(cp)) == -1) {
748 			debug("key_read: invalid curve");
749 			return -1;
750 		}
751 #endif
752 		*space = ' ';
753 		if (type == KEY_UNSPEC) {
754 			debug3("key_read: missing keytype");
755 			return -1;
756 		}
757 		cp = space+1;
758 		if (*cp == '\0') {
759 			debug3("key_read: short string");
760 			return -1;
761 		}
762 		if (ret->type == KEY_UNSPEC) {
763 			ret->type = type;
764 		} else if (ret->type != type) {
765 			/* is a key, but different type */
766 			debug3("key_read: type mismatch");
767 			return -1;
768 		}
769 		len = 2*strlen(cp);
770 		blob = xmalloc(len);
771 		n = uudecode(cp, blob, len);
772 		if (n < 0) {
773 			error("key_read: uudecode %s failed", cp);
774 			free(blob);
775 			return -1;
776 		}
777 		k = key_from_blob(blob, (u_int)n);
778 		free(blob);
779 		if (k == NULL) {
780 			error("key_read: key_from_blob %s failed", cp);
781 			return -1;
782 		}
783 		if (k->type != type) {
784 			error("key_read: type mismatch: encoding error");
785 			key_free(k);
786 			return -1;
787 		}
788 #ifdef OPENSSL_HAS_ECC
789 		if (key_type_plain(type) == KEY_ECDSA &&
790 		    curve_nid != k->ecdsa_nid) {
791 			error("key_read: type mismatch: EC curve mismatch");
792 			key_free(k);
793 			return -1;
794 		}
795 #endif
796 /*XXXX*/
797 		if (key_is_cert(ret)) {
798 			if (!key_is_cert(k)) {
799 				error("key_read: loaded key is not a cert");
800 				key_free(k);
801 				return -1;
802 			}
803 			if (ret->cert != NULL)
804 				cert_free(ret->cert);
805 			ret->cert = k->cert;
806 			k->cert = NULL;
807 		}
808 		if (key_type_plain(ret->type) == KEY_RSA) {
809 			if (ret->rsa != NULL)
810 				RSA_free(ret->rsa);
811 			ret->rsa = k->rsa;
812 			k->rsa = NULL;
813 #ifdef DEBUG_PK
814 			RSA_print_fp(stderr, ret->rsa, 8);
815 #endif
816 		}
817 		if (key_type_plain(ret->type) == KEY_DSA) {
818 			if (ret->dsa != NULL)
819 				DSA_free(ret->dsa);
820 			ret->dsa = k->dsa;
821 			k->dsa = NULL;
822 #ifdef DEBUG_PK
823 			DSA_print_fp(stderr, ret->dsa, 8);
824 #endif
825 		}
826 #ifdef OPENSSL_HAS_ECC
827 		if (key_type_plain(ret->type) == KEY_ECDSA) {
828 			if (ret->ecdsa != NULL)
829 				EC_KEY_free(ret->ecdsa);
830 			ret->ecdsa = k->ecdsa;
831 			ret->ecdsa_nid = k->ecdsa_nid;
832 			k->ecdsa = NULL;
833 			k->ecdsa_nid = -1;
834 #ifdef DEBUG_PK
835 			key_dump_ec_key(ret->ecdsa);
836 #endif
837 		}
838 #endif
839 		if (key_type_plain(ret->type) == KEY_ED25519) {
840 			free(ret->ed25519_pk);
841 			ret->ed25519_pk = k->ed25519_pk;
842 			k->ed25519_pk = NULL;
843 #ifdef DEBUG_PK
844 			/* XXX */
845 #endif
846 		}
847 		success = 1;
848 /*XXXX*/
849 		key_free(k);
850 		if (success != 1)
851 			break;
852 		/* advance cp: skip whitespace and data */
853 		while (*cp == ' ' || *cp == '\t')
854 			cp++;
855 		while (*cp != '\0' && *cp != ' ' && *cp != '\t')
856 			cp++;
857 		*cpp = cp;
858 		break;
859 	default:
860 		fatal("key_read: bad key type: %d", ret->type);
861 		break;
862 	}
863 	return success;
864 }
865 
866 int
key_write(const Key * key,FILE * f)867 key_write(const Key *key, FILE *f)
868 {
869 	int n, success = 0;
870 	u_int len, bits = 0;
871 	u_char *blob;
872 	char *uu;
873 
874 	if (key_is_cert(key)) {
875 		if (key->cert == NULL) {
876 			error("%s: no cert data", __func__);
877 			return 0;
878 		}
879 		if (buffer_len(&key->cert->certblob) == 0) {
880 			error("%s: no signed certificate blob", __func__);
881 			return 0;
882 		}
883 	}
884 
885 	switch (key->type) {
886 	case KEY_RSA1:
887 		if (key->rsa == NULL)
888 			return 0;
889 		/* size of modulus 'n' */
890 		bits = BN_num_bits(key->rsa->n);
891 		fprintf(f, "%u", bits);
892 		if (write_bignum(f, key->rsa->e) &&
893 		    write_bignum(f, key->rsa->n))
894 			return 1;
895 		error("key_write: failed for RSA key");
896 		return 0;
897 	case KEY_DSA:
898 	case KEY_DSA_CERT_V00:
899 	case KEY_DSA_CERT:
900 		if (key->dsa == NULL)
901 			return 0;
902 		break;
903 #ifdef OPENSSL_HAS_ECC
904 	case KEY_ECDSA:
905 	case KEY_ECDSA_CERT:
906 		if (key->ecdsa == NULL)
907 			return 0;
908 		break;
909 #endif
910 	case KEY_ED25519:
911 	case KEY_ED25519_CERT:
912 		if (key->ed25519_pk == NULL)
913 			return 0;
914 		break;
915 	case KEY_RSA:
916 	case KEY_RSA_CERT_V00:
917 	case KEY_RSA_CERT:
918 		if (key->rsa == NULL)
919 			return 0;
920 		break;
921 	default:
922 		return 0;
923 	}
924 
925 	key_to_blob(key, &blob, &len);
926 	uu = xmalloc(2*len);
927 	n = uuencode(blob, len, uu, 2*len);
928 	if (n > 0) {
929 		fprintf(f, "%s %s", key_ssh_name(key), uu);
930 		success = 1;
931 	}
932 	free(blob);
933 	free(uu);
934 
935 	return success;
936 }
937 
938 const char *
key_cert_type(const Key * k)939 key_cert_type(const Key *k)
940 {
941 	switch (k->cert->type) {
942 	case SSH2_CERT_TYPE_USER:
943 		return "user";
944 	case SSH2_CERT_TYPE_HOST:
945 		return "host";
946 	default:
947 		return "unknown";
948 	}
949 }
950 
951 struct keytype {
952 	char *name;
953 	char *shortname;
954 	int type;
955 	int nid;
956 	int cert;
957 };
958 static const struct keytype keytypes[] = {
959 	{ NULL, "RSA1", KEY_RSA1, 0, 0 },
960 	{ "ssh-rsa", "RSA", KEY_RSA, 0, 0 },
961 	{ "ssh-dss", "DSA", KEY_DSA, 0, 0 },
962 	{ "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0 },
963 #ifdef OPENSSL_HAS_ECC
964 	{ "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0 },
965 	{ "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0 },
966 # ifdef OPENSSL_HAS_NISTP521
967 	{ "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0 },
968 # endif
969 #endif /* OPENSSL_HAS_ECC */
970 	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1 },
971 	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1 },
972 #ifdef OPENSSL_HAS_ECC
973 	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
974 	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1 },
975 	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
976 	    KEY_ECDSA_CERT, NID_secp384r1, 1 },
977 # ifdef OPENSSL_HAS_NISTP521
978 	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
979 	    KEY_ECDSA_CERT, NID_secp521r1, 1 },
980 # endif
981 #endif /* OPENSSL_HAS_ECC */
982 	{ "ssh-rsa-cert-v00@openssh.com", "RSA-CERT-V00",
983 	    KEY_RSA_CERT_V00, 0, 1 },
984 	{ "ssh-dss-cert-v00@openssh.com", "DSA-CERT-V00",
985 	    KEY_DSA_CERT_V00, 0, 1 },
986 	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
987 	    KEY_ED25519_CERT, 0, 1 },
988 	{ NULL, NULL, -1, -1, 0 }
989 };
990 
991 const char *
key_type(const Key * k)992 key_type(const Key *k)
993 {
994 	const struct keytype *kt;
995 
996 	for (kt = keytypes; kt->type != -1; kt++) {
997 		if (kt->type == k->type)
998 			return kt->shortname;
999 	}
1000 	return "unknown";
1001 }
1002 
1003 static const char *
key_ssh_name_from_type_nid(int type,int nid)1004 key_ssh_name_from_type_nid(int type, int nid)
1005 {
1006 	const struct keytype *kt;
1007 
1008 	for (kt = keytypes; kt->type != -1; kt++) {
1009 		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
1010 			return kt->name;
1011 	}
1012 	return "ssh-unknown";
1013 }
1014 
1015 const char *
key_ssh_name(const Key * k)1016 key_ssh_name(const Key *k)
1017 {
1018 	return key_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
1019 }
1020 
1021 const char *
key_ssh_name_plain(const Key * k)1022 key_ssh_name_plain(const Key *k)
1023 {
1024 	return key_ssh_name_from_type_nid(key_type_plain(k->type),
1025 	    k->ecdsa_nid);
1026 }
1027 
1028 int
key_type_from_name(char * name)1029 key_type_from_name(char *name)
1030 {
1031 	const struct keytype *kt;
1032 
1033 	for (kt = keytypes; kt->type != -1; kt++) {
1034 		/* Only allow shortname matches for plain key types */
1035 		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
1036 		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
1037 			return kt->type;
1038 	}
1039 	debug2("key_type_from_name: unknown key type '%s'", name);
1040 	return KEY_UNSPEC;
1041 }
1042 
1043 int
key_ecdsa_nid_from_name(const char * name)1044 key_ecdsa_nid_from_name(const char *name)
1045 {
1046 	const struct keytype *kt;
1047 
1048 	for (kt = keytypes; kt->type != -1; kt++) {
1049 		if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
1050 			continue;
1051 		if (kt->name != NULL && strcmp(name, kt->name) == 0)
1052 			return kt->nid;
1053 	}
1054 	debug2("%s: unknown/non-ECDSA key type '%s'", __func__, name);
1055 	return -1;
1056 }
1057 
1058 char *
key_alg_list(int certs_only,int plain_only)1059 key_alg_list(int certs_only, int plain_only)
1060 {
1061 	char *ret = NULL;
1062 	size_t nlen, rlen = 0;
1063 	const struct keytype *kt;
1064 
1065 	for (kt = keytypes; kt->type != -1; kt++) {
1066 		if (kt->name == NULL)
1067 			continue;
1068 		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
1069 			continue;
1070 		if (ret != NULL)
1071 			ret[rlen++] = '\n';
1072 		nlen = strlen(kt->name);
1073 		ret = xrealloc(ret, 1, rlen + nlen + 2);
1074 		memcpy(ret + rlen, kt->name, nlen + 1);
1075 		rlen += nlen;
1076 	}
1077 	return ret;
1078 }
1079 
1080 int
key_type_is_cert(int type)1081 key_type_is_cert(int type)
1082 {
1083 	const struct keytype *kt;
1084 
1085 	for (kt = keytypes; kt->type != -1; kt++) {
1086 		if (kt->type == type)
1087 			return kt->cert;
1088 	}
1089 	return 0;
1090 }
1091 
1092 static int
key_type_is_valid_ca(int type)1093 key_type_is_valid_ca(int type)
1094 {
1095 	switch (type) {
1096 	case KEY_RSA:
1097 	case KEY_DSA:
1098 	case KEY_ECDSA:
1099 	case KEY_ED25519:
1100 		return 1;
1101 	default:
1102 		return 0;
1103 	}
1104 }
1105 
1106 u_int
key_size(const Key * k)1107 key_size(const Key *k)
1108 {
1109 	switch (k->type) {
1110 	case KEY_RSA1:
1111 	case KEY_RSA:
1112 	case KEY_RSA_CERT_V00:
1113 	case KEY_RSA_CERT:
1114 		return BN_num_bits(k->rsa->n);
1115 	case KEY_DSA:
1116 	case KEY_DSA_CERT_V00:
1117 	case KEY_DSA_CERT:
1118 		return BN_num_bits(k->dsa->p);
1119 	case KEY_ED25519:
1120 		return 256;	/* XXX */
1121 #ifdef OPENSSL_HAS_ECC
1122 	case KEY_ECDSA:
1123 	case KEY_ECDSA_CERT:
1124 		return key_curve_nid_to_bits(k->ecdsa_nid);
1125 #endif
1126 	}
1127 	return 0;
1128 }
1129 
1130 static RSA *
rsa_generate_private_key(u_int bits)1131 rsa_generate_private_key(u_int bits)
1132 {
1133 	RSA *private = RSA_new();
1134 	BIGNUM *f4 = BN_new();
1135 
1136 	if (private == NULL)
1137 		fatal("%s: RSA_new failed", __func__);
1138 	if (f4 == NULL)
1139 		fatal("%s: BN_new failed", __func__);
1140 	if (!BN_set_word(f4, RSA_F4))
1141 		fatal("%s: BN_new failed", __func__);
1142 	if (!RSA_generate_key_ex(private, bits, f4, NULL))
1143 		fatal("%s: key generation failed.", __func__);
1144 	BN_free(f4);
1145 	return private;
1146 }
1147 
1148 static DSA*
dsa_generate_private_key(u_int bits)1149 dsa_generate_private_key(u_int bits)
1150 {
1151 	DSA *private = DSA_new();
1152 
1153 	if (private == NULL)
1154 		fatal("%s: DSA_new failed", __func__);
1155 	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1156 	    NULL, NULL))
1157 		fatal("%s: DSA_generate_parameters failed", __func__);
1158 	if (!DSA_generate_key(private))
1159 		fatal("%s: DSA_generate_key failed.", __func__);
1160 	return private;
1161 }
1162 
1163 int
key_ecdsa_bits_to_nid(int bits)1164 key_ecdsa_bits_to_nid(int bits)
1165 {
1166 	switch (bits) {
1167 #ifdef OPENSSL_HAS_ECC
1168 	case 256:
1169 		return NID_X9_62_prime256v1;
1170 	case 384:
1171 		return NID_secp384r1;
1172 # ifdef OPENSSL_HAS_NISTP521
1173 	case 521:
1174 		return NID_secp521r1;
1175 # endif
1176 #endif
1177 	default:
1178 		return -1;
1179 	}
1180 }
1181 
1182 #ifdef OPENSSL_HAS_ECC
1183 int
key_ecdsa_key_to_nid(EC_KEY * k)1184 key_ecdsa_key_to_nid(EC_KEY *k)
1185 {
1186 	EC_GROUP *eg;
1187 	int nids[] = {
1188 		NID_X9_62_prime256v1,
1189 		NID_secp384r1,
1190 # ifdef OPENSSL_HAS_NISTP521
1191 		NID_secp521r1,
1192 # endif
1193 		-1
1194 	};
1195 	int nid;
1196 	u_int i;
1197 	BN_CTX *bnctx;
1198 	const EC_GROUP *g = EC_KEY_get0_group(k);
1199 
1200 	/*
1201 	 * The group may be stored in a ASN.1 encoded private key in one of two
1202 	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1203 	 * or explicit group parameters encoded into the key blob. Only the
1204 	 * "named group" case sets the group NID for us, but we can figure
1205 	 * it out for the other case by comparing against all the groups that
1206 	 * are supported.
1207 	 */
1208 	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1209 		return nid;
1210 	if ((bnctx = BN_CTX_new()) == NULL)
1211 		fatal("%s: BN_CTX_new() failed", __func__);
1212 	for (i = 0; nids[i] != -1; i++) {
1213 		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1214 			fatal("%s: EC_GROUP_new_by_curve_name failed",
1215 			    __func__);
1216 		if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1217 			break;
1218 		EC_GROUP_free(eg);
1219 	}
1220 	BN_CTX_free(bnctx);
1221 	debug3("%s: nid = %d", __func__, nids[i]);
1222 	if (nids[i] != -1) {
1223 		/* Use the group with the NID attached */
1224 		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1225 		if (EC_KEY_set_group(k, eg) != 1)
1226 			fatal("%s: EC_KEY_set_group", __func__);
1227 	}
1228 	return nids[i];
1229 }
1230 
1231 static EC_KEY*
ecdsa_generate_private_key(u_int bits,int * nid)1232 ecdsa_generate_private_key(u_int bits, int *nid)
1233 {
1234 	EC_KEY *private;
1235 
1236 	if ((*nid = key_ecdsa_bits_to_nid(bits)) == -1)
1237 		fatal("%s: invalid key length", __func__);
1238 	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL)
1239 		fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1240 	if (EC_KEY_generate_key(private) != 1)
1241 		fatal("%s: EC_KEY_generate_key failed", __func__);
1242 	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1243 	return private;
1244 }
1245 #endif /* OPENSSL_HAS_ECC */
1246 
1247 Key *
key_generate(int type,u_int bits)1248 key_generate(int type, u_int bits)
1249 {
1250 	Key *k = key_new(KEY_UNSPEC);
1251 	switch (type) {
1252 	case KEY_DSA:
1253 		k->dsa = dsa_generate_private_key(bits);
1254 		break;
1255 #ifdef OPENSSL_HAS_ECC
1256 	case KEY_ECDSA:
1257 		k->ecdsa = ecdsa_generate_private_key(bits, &k->ecdsa_nid);
1258 		break;
1259 #endif
1260 	case KEY_RSA:
1261 	case KEY_RSA1:
1262 		k->rsa = rsa_generate_private_key(bits);
1263 		break;
1264 	case KEY_ED25519:
1265 		k->ed25519_pk = xmalloc(ED25519_PK_SZ);
1266 		k->ed25519_sk = xmalloc(ED25519_SK_SZ);
1267 		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1268 		break;
1269 	case KEY_RSA_CERT_V00:
1270 	case KEY_DSA_CERT_V00:
1271 	case KEY_RSA_CERT:
1272 	case KEY_DSA_CERT:
1273 		fatal("key_generate: cert keys cannot be generated directly");
1274 	default:
1275 		fatal("key_generate: unknown type %d", type);
1276 	}
1277 	k->type = type;
1278 	return k;
1279 }
1280 
1281 void
key_cert_copy(const Key * from_key,struct Key * to_key)1282 key_cert_copy(const Key *from_key, struct Key *to_key)
1283 {
1284 	u_int i;
1285 	const struct KeyCert *from;
1286 	struct KeyCert *to;
1287 
1288 	if (to_key->cert != NULL) {
1289 		cert_free(to_key->cert);
1290 		to_key->cert = NULL;
1291 	}
1292 
1293 	if ((from = from_key->cert) == NULL)
1294 		return;
1295 
1296 	to = to_key->cert = cert_new();
1297 
1298 	buffer_append(&to->certblob, buffer_ptr(&from->certblob),
1299 	    buffer_len(&from->certblob));
1300 
1301 	buffer_append(&to->critical,
1302 	    buffer_ptr(&from->critical), buffer_len(&from->critical));
1303 	buffer_append(&to->extensions,
1304 	    buffer_ptr(&from->extensions), buffer_len(&from->extensions));
1305 
1306 	to->serial = from->serial;
1307 	to->type = from->type;
1308 	to->key_id = from->key_id == NULL ? NULL : xstrdup(from->key_id);
1309 	to->valid_after = from->valid_after;
1310 	to->valid_before = from->valid_before;
1311 	to->signature_key = from->signature_key == NULL ?
1312 	    NULL : key_from_private(from->signature_key);
1313 
1314 	to->nprincipals = from->nprincipals;
1315 	if (to->nprincipals > CERT_MAX_PRINCIPALS)
1316 		fatal("%s: nprincipals (%u) > CERT_MAX_PRINCIPALS (%u)",
1317 		    __func__, to->nprincipals, CERT_MAX_PRINCIPALS);
1318 	if (to->nprincipals > 0) {
1319 		to->principals = xcalloc(from->nprincipals,
1320 		    sizeof(*to->principals));
1321 		for (i = 0; i < to->nprincipals; i++)
1322 			to->principals[i] = xstrdup(from->principals[i]);
1323 	}
1324 }
1325 
1326 Key *
key_from_private(const Key * k)1327 key_from_private(const Key *k)
1328 {
1329 	Key *n = NULL;
1330 	switch (k->type) {
1331 	case KEY_DSA:
1332 	case KEY_DSA_CERT_V00:
1333 	case KEY_DSA_CERT:
1334 		n = key_new(k->type);
1335 		if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1336 		    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1337 		    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1338 		    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL))
1339 			fatal("key_from_private: BN_copy failed");
1340 		break;
1341 #ifdef OPENSSL_HAS_ECC
1342 	case KEY_ECDSA:
1343 	case KEY_ECDSA_CERT:
1344 		n = key_new(k->type);
1345 		n->ecdsa_nid = k->ecdsa_nid;
1346 		if ((n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid)) == NULL)
1347 			fatal("%s: EC_KEY_new_by_curve_name failed", __func__);
1348 		if (EC_KEY_set_public_key(n->ecdsa,
1349 		    EC_KEY_get0_public_key(k->ecdsa)) != 1)
1350 			fatal("%s: EC_KEY_set_public_key failed", __func__);
1351 		break;
1352 #endif
1353 	case KEY_RSA:
1354 	case KEY_RSA1:
1355 	case KEY_RSA_CERT_V00:
1356 	case KEY_RSA_CERT:
1357 		n = key_new(k->type);
1358 		if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1359 		    (BN_copy(n->rsa->e, k->rsa->e) == NULL))
1360 			fatal("key_from_private: BN_copy failed");
1361 		break;
1362 	case KEY_ED25519:
1363 	case KEY_ED25519_CERT:
1364 		n = key_new(k->type);
1365 		if (k->ed25519_pk != NULL) {
1366 			n->ed25519_pk = xmalloc(ED25519_PK_SZ);
1367 			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1368 		}
1369 		break;
1370 	default:
1371 		fatal("key_from_private: unknown type %d", k->type);
1372 		break;
1373 	}
1374 	if (key_is_cert(k))
1375 		key_cert_copy(k, n);
1376 	return n;
1377 }
1378 
1379 int
key_names_valid2(const char * names)1380 key_names_valid2(const char *names)
1381 {
1382 	char *s, *cp, *p;
1383 
1384 	if (names == NULL || strcmp(names, "") == 0)
1385 		return 0;
1386 	s = cp = xstrdup(names);
1387 	for ((p = strsep(&cp, ",")); p && *p != '\0';
1388 	    (p = strsep(&cp, ","))) {
1389 		switch (key_type_from_name(p)) {
1390 		case KEY_RSA1:
1391 		case KEY_UNSPEC:
1392 			free(s);
1393 			return 0;
1394 		}
1395 	}
1396 	debug3("key names ok: [%s]", names);
1397 	free(s);
1398 	return 1;
1399 }
1400 
1401 static int
cert_parse(Buffer * b,Key * key,const u_char * blob,u_int blen)1402 cert_parse(Buffer *b, Key *key, const u_char *blob, u_int blen)
1403 {
1404 	u_char *principals, *critical, *exts, *sig_key, *sig;
1405 	u_int signed_len, plen, clen, sklen, slen, kidlen, elen;
1406 	Buffer tmp;
1407 	char *principal;
1408 	int ret = -1;
1409 	int v00 = key->type == KEY_DSA_CERT_V00 ||
1410 	    key->type == KEY_RSA_CERT_V00;
1411 
1412 	buffer_init(&tmp);
1413 
1414 	/* Copy the entire key blob for verification and later serialisation */
1415 	buffer_append(&key->cert->certblob, blob, blen);
1416 
1417 	elen = 0; /* Not touched for v00 certs */
1418 	principals = exts = critical = sig_key = sig = NULL;
1419 	if ((!v00 && buffer_get_int64_ret(&key->cert->serial, b) != 0) ||
1420 	    buffer_get_int_ret(&key->cert->type, b) != 0 ||
1421 	    (key->cert->key_id = buffer_get_cstring_ret(b, &kidlen)) == NULL ||
1422 	    (principals = buffer_get_string_ret(b, &plen)) == NULL ||
1423 	    buffer_get_int64_ret(&key->cert->valid_after, b) != 0 ||
1424 	    buffer_get_int64_ret(&key->cert->valid_before, b) != 0 ||
1425 	    (critical = buffer_get_string_ret(b, &clen)) == NULL ||
1426 	    (!v00 && (exts = buffer_get_string_ret(b, &elen)) == NULL) ||
1427 	    (v00 && buffer_get_string_ptr_ret(b, NULL) == NULL) || /* nonce */
1428 	    buffer_get_string_ptr_ret(b, NULL) == NULL || /* reserved */
1429 	    (sig_key = buffer_get_string_ret(b, &sklen)) == NULL) {
1430 		error("%s: parse error", __func__);
1431 		goto out;
1432 	}
1433 
1434 	/* Signature is left in the buffer so we can calculate this length */
1435 	signed_len = buffer_len(&key->cert->certblob) - buffer_len(b);
1436 
1437 	if ((sig = buffer_get_string_ret(b, &slen)) == NULL) {
1438 		error("%s: parse error", __func__);
1439 		goto out;
1440 	}
1441 
1442 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
1443 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
1444 		error("Unknown certificate type %u", key->cert->type);
1445 		goto out;
1446 	}
1447 
1448 	buffer_append(&tmp, principals, plen);
1449 	while (buffer_len(&tmp) > 0) {
1450 		if (key->cert->nprincipals >= CERT_MAX_PRINCIPALS) {
1451 			error("%s: Too many principals", __func__);
1452 			goto out;
1453 		}
1454 		if ((principal = buffer_get_cstring_ret(&tmp, &plen)) == NULL) {
1455 			error("%s: Principals data invalid", __func__);
1456 			goto out;
1457 		}
1458 		key->cert->principals = xrealloc(key->cert->principals,
1459 		    key->cert->nprincipals + 1, sizeof(*key->cert->principals));
1460 		key->cert->principals[key->cert->nprincipals++] = principal;
1461 	}
1462 
1463 	buffer_clear(&tmp);
1464 
1465 	buffer_append(&key->cert->critical, critical, clen);
1466 	buffer_append(&tmp, critical, clen);
1467 	/* validate structure */
1468 	while (buffer_len(&tmp) != 0) {
1469 		if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1470 		    buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1471 			error("%s: critical option data invalid", __func__);
1472 			goto out;
1473 		}
1474 	}
1475 	buffer_clear(&tmp);
1476 
1477 	buffer_append(&key->cert->extensions, exts, elen);
1478 	buffer_append(&tmp, exts, elen);
1479 	/* validate structure */
1480 	while (buffer_len(&tmp) != 0) {
1481 		if (buffer_get_string_ptr_ret(&tmp, NULL) == NULL ||
1482 		    buffer_get_string_ptr_ret(&tmp, NULL) == NULL) {
1483 			error("%s: extension data invalid", __func__);
1484 			goto out;
1485 		}
1486 	}
1487 	buffer_clear(&tmp);
1488 
1489 	if ((key->cert->signature_key = key_from_blob2(sig_key, sklen, 0))
1490 	    == NULL) {
1491 		error("%s: Signature key invalid", __func__);
1492 		goto out;
1493 	}
1494 	if (!key_type_is_valid_ca(key->cert->signature_key->type)) {
1495 		error("%s: Invalid signature key type %s (%d)", __func__,
1496 		    key_type(key->cert->signature_key),
1497 		    key->cert->signature_key->type);
1498 		goto out;
1499 	}
1500 
1501 	switch (key_verify(key->cert->signature_key, sig, slen,
1502 	    buffer_ptr(&key->cert->certblob), signed_len)) {
1503 	case 1:
1504 		ret = 0;
1505 		break; /* Good signature */
1506 	case 0:
1507 		error("%s: Invalid signature on certificate", __func__);
1508 		goto out;
1509 	case -1:
1510 		error("%s: Certificate signature verification failed",
1511 		    __func__);
1512 		goto out;
1513 	}
1514 
1515  out:
1516 	buffer_free(&tmp);
1517 	free(principals);
1518 	free(critical);
1519 	free(exts);
1520 	free(sig_key);
1521 	free(sig);
1522 	return ret;
1523 }
1524 
1525 static Key *
key_from_blob2(const u_char * blob,u_int blen,int allow_cert)1526 key_from_blob2(const u_char *blob, u_int blen, int allow_cert)
1527 {
1528 	Buffer b;
1529 	int rlen, type;
1530 	u_int len;
1531 	char *ktype = NULL, *curve = NULL;
1532 	u_char *pk = NULL;
1533 	Key *key = NULL;
1534 #ifdef OPENSSL_HAS_ECC
1535 	EC_POINT *q = NULL;
1536 	int nid = -1;
1537 #endif
1538 
1539 #ifdef DEBUG_PK
1540 	dump_base64(stderr, blob, blen);
1541 #endif
1542 	buffer_init(&b);
1543 	buffer_append(&b, blob, blen);
1544 	if ((ktype = buffer_get_cstring_ret(&b, NULL)) == NULL) {
1545 		error("key_from_blob: can't read key type");
1546 		goto out;
1547 	}
1548 
1549 	type = key_type_from_name(ktype);
1550 #ifdef OPENSSL_HAS_ECC
1551 	if (key_type_plain(type) == KEY_ECDSA)
1552 		nid = key_ecdsa_nid_from_name(ktype);
1553 #endif
1554 	if (!allow_cert && key_type_is_cert(type)) {
1555 		error("key_from_blob: certificate not allowed in this context");
1556 		goto out;
1557 	}
1558 	switch (type) {
1559 	case KEY_RSA_CERT:
1560 		(void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1561 		/* FALLTHROUGH */
1562 	case KEY_RSA:
1563 	case KEY_RSA_CERT_V00:
1564 		key = key_new(type);
1565 		if (buffer_get_bignum2_ret(&b, key->rsa->e) == -1 ||
1566 		    buffer_get_bignum2_ret(&b, key->rsa->n) == -1) {
1567 			error("key_from_blob: can't read rsa key");
1568  badkey:
1569 			key_free(key);
1570 			key = NULL;
1571 			goto out;
1572 		}
1573 #ifdef DEBUG_PK
1574 		RSA_print_fp(stderr, key->rsa, 8);
1575 #endif
1576 		break;
1577 	case KEY_DSA_CERT:
1578 		(void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1579 		/* FALLTHROUGH */
1580 	case KEY_DSA:
1581 	case KEY_DSA_CERT_V00:
1582 		key = key_new(type);
1583 		if (buffer_get_bignum2_ret(&b, key->dsa->p) == -1 ||
1584 		    buffer_get_bignum2_ret(&b, key->dsa->q) == -1 ||
1585 		    buffer_get_bignum2_ret(&b, key->dsa->g) == -1 ||
1586 		    buffer_get_bignum2_ret(&b, key->dsa->pub_key) == -1) {
1587 			error("key_from_blob: can't read dsa key");
1588 			goto badkey;
1589 		}
1590 #ifdef DEBUG_PK
1591 		DSA_print_fp(stderr, key->dsa, 8);
1592 #endif
1593 		break;
1594 #ifdef OPENSSL_HAS_ECC
1595 	case KEY_ECDSA_CERT:
1596 		(void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1597 		/* FALLTHROUGH */
1598 	case KEY_ECDSA:
1599 		key = key_new(type);
1600 		key->ecdsa_nid = nid;
1601 		if ((curve = buffer_get_string_ret(&b, NULL)) == NULL) {
1602 			error("key_from_blob: can't read ecdsa curve");
1603 			goto badkey;
1604 		}
1605 		if (key->ecdsa_nid != key_curve_name_to_nid(curve)) {
1606 			error("key_from_blob: ecdsa curve doesn't match type");
1607 			goto badkey;
1608 		}
1609 		if (key->ecdsa != NULL)
1610 			EC_KEY_free(key->ecdsa);
1611 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
1612 		    == NULL)
1613 			fatal("key_from_blob: EC_KEY_new_by_curve_name failed");
1614 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL)
1615 			fatal("key_from_blob: EC_POINT_new failed");
1616 		if (buffer_get_ecpoint_ret(&b, EC_KEY_get0_group(key->ecdsa),
1617 		    q) == -1) {
1618 			error("key_from_blob: can't read ecdsa key point");
1619 			goto badkey;
1620 		}
1621 		if (key_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
1622 		    q) != 0)
1623 			goto badkey;
1624 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1)
1625 			fatal("key_from_blob: EC_KEY_set_public_key failed");
1626 #ifdef DEBUG_PK
1627 		key_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
1628 #endif
1629 		break;
1630 #endif /* OPENSSL_HAS_ECC */
1631 	case KEY_ED25519_CERT:
1632 		(void)buffer_get_string_ptr_ret(&b, NULL); /* Skip nonce */
1633 		/* FALLTHROUGH */
1634 	case KEY_ED25519:
1635 		if ((pk = buffer_get_string_ret(&b, &len)) == NULL) {
1636 			error("key_from_blob: can't read ed25519 key");
1637 			goto badkey;
1638 		}
1639 		if (len != ED25519_PK_SZ) {
1640 			error("key_from_blob: ed25519 len %d != %d",
1641 			    len, ED25519_PK_SZ);
1642 			goto badkey;
1643 		}
1644 		key = key_new(type);
1645 		key->ed25519_pk = pk;
1646 		pk = NULL;
1647 		break;
1648 	case KEY_UNSPEC:
1649 		key = key_new(type);
1650 		break;
1651 	default:
1652 		error("key_from_blob: cannot handle type %s", ktype);
1653 		goto out;
1654 	}
1655 	if (key_is_cert(key) && cert_parse(&b, key, blob, blen) == -1) {
1656 		error("key_from_blob: can't parse cert data");
1657 		goto badkey;
1658 	}
1659 	rlen = buffer_len(&b);
1660 	if (key != NULL && rlen != 0)
1661 		error("key_from_blob: remaining bytes in key blob %d", rlen);
1662  out:
1663 	free(ktype);
1664 	free(curve);
1665 	free(pk);
1666 #ifdef OPENSSL_HAS_ECC
1667 	if (q != NULL)
1668 		EC_POINT_free(q);
1669 #endif
1670 	buffer_free(&b);
1671 	return key;
1672 }
1673 
1674 Key *
key_from_blob(const u_char * blob,u_int blen)1675 key_from_blob(const u_char *blob, u_int blen)
1676 {
1677 	return key_from_blob2(blob, blen, 1);
1678 }
1679 
1680 static int
to_blob(const Key * key,u_char ** blobp,u_int * lenp,int force_plain)1681 to_blob(const Key *key, u_char **blobp, u_int *lenp, int force_plain)
1682 {
1683 	Buffer b;
1684 	int len, type;
1685 
1686 	if (blobp != NULL)
1687 		*blobp = NULL;
1688 	if (lenp != NULL)
1689 		*lenp = 0;
1690 	if (key == NULL) {
1691 		error("key_to_blob: key == NULL");
1692 		return 0;
1693 	}
1694 	buffer_init(&b);
1695 	type = force_plain ? key_type_plain(key->type) : key->type;
1696 	switch (type) {
1697 	case KEY_DSA_CERT_V00:
1698 	case KEY_RSA_CERT_V00:
1699 	case KEY_DSA_CERT:
1700 	case KEY_ECDSA_CERT:
1701 	case KEY_RSA_CERT:
1702 	case KEY_ED25519_CERT:
1703 		/* Use the existing blob */
1704 		buffer_append(&b, buffer_ptr(&key->cert->certblob),
1705 		    buffer_len(&key->cert->certblob));
1706 		break;
1707 	case KEY_DSA:
1708 		buffer_put_cstring(&b,
1709 		    key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1710 		buffer_put_bignum2(&b, key->dsa->p);
1711 		buffer_put_bignum2(&b, key->dsa->q);
1712 		buffer_put_bignum2(&b, key->dsa->g);
1713 		buffer_put_bignum2(&b, key->dsa->pub_key);
1714 		break;
1715 #ifdef OPENSSL_HAS_ECC
1716 	case KEY_ECDSA:
1717 		buffer_put_cstring(&b,
1718 		    key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1719 		buffer_put_cstring(&b, key_curve_nid_to_name(key->ecdsa_nid));
1720 		buffer_put_ecpoint(&b, EC_KEY_get0_group(key->ecdsa),
1721 		    EC_KEY_get0_public_key(key->ecdsa));
1722 		break;
1723 #endif
1724 	case KEY_RSA:
1725 		buffer_put_cstring(&b,
1726 		    key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1727 		buffer_put_bignum2(&b, key->rsa->e);
1728 		buffer_put_bignum2(&b, key->rsa->n);
1729 		break;
1730 	case KEY_ED25519:
1731 		buffer_put_cstring(&b,
1732 		    key_ssh_name_from_type_nid(type, key->ecdsa_nid));
1733 		buffer_put_string(&b, key->ed25519_pk, ED25519_PK_SZ);
1734 		break;
1735 	default:
1736 		error("key_to_blob: unsupported key type %d", key->type);
1737 		buffer_free(&b);
1738 		return 0;
1739 	}
1740 	len = buffer_len(&b);
1741 	if (lenp != NULL)
1742 		*lenp = len;
1743 	if (blobp != NULL) {
1744 		*blobp = xmalloc(len);
1745 		memcpy(*blobp, buffer_ptr(&b), len);
1746 	}
1747 	explicit_bzero(buffer_ptr(&b), len);
1748 	buffer_free(&b);
1749 	return len;
1750 }
1751 
1752 int
key_to_blob(const Key * key,u_char ** blobp,u_int * lenp)1753 key_to_blob(const Key *key, u_char **blobp, u_int *lenp)
1754 {
1755 	return to_blob(key, blobp, lenp, 0);
1756 }
1757 
1758 int
key_sign(const Key * key,u_char ** sigp,u_int * lenp,const u_char * data,u_int datalen)1759 key_sign(
1760     const Key *key,
1761     u_char **sigp, u_int *lenp,
1762     const u_char *data, u_int datalen)
1763 {
1764 	switch (key->type) {
1765 	case KEY_DSA_CERT_V00:
1766 	case KEY_DSA_CERT:
1767 	case KEY_DSA:
1768 		return ssh_dss_sign(key, sigp, lenp, data, datalen);
1769 #ifdef OPENSSL_HAS_ECC
1770 	case KEY_ECDSA_CERT:
1771 	case KEY_ECDSA:
1772 		return ssh_ecdsa_sign(key, sigp, lenp, data, datalen);
1773 #endif
1774 	case KEY_RSA_CERT_V00:
1775 	case KEY_RSA_CERT:
1776 	case KEY_RSA:
1777 		return ssh_rsa_sign(key, sigp, lenp, data, datalen);
1778 	case KEY_ED25519:
1779 	case KEY_ED25519_CERT:
1780 		return ssh_ed25519_sign(key, sigp, lenp, data, datalen);
1781 	default:
1782 		error("key_sign: invalid key type %d", key->type);
1783 		return -1;
1784 	}
1785 }
1786 
1787 /*
1788  * key_verify returns 1 for a correct signature, 0 for an incorrect signature
1789  * and -1 on error.
1790  */
1791 int
key_verify(const Key * key,const u_char * signature,u_int signaturelen,const u_char * data,u_int datalen)1792 key_verify(
1793     const Key *key,
1794     const u_char *signature, u_int signaturelen,
1795     const u_char *data, u_int datalen)
1796 {
1797 	if (signaturelen == 0)
1798 		return -1;
1799 
1800 	switch (key->type) {
1801 	case KEY_DSA_CERT_V00:
1802 	case KEY_DSA_CERT:
1803 	case KEY_DSA:
1804 		return ssh_dss_verify(key, signature, signaturelen, data, datalen);
1805 #ifdef OPENSSL_HAS_ECC
1806 	case KEY_ECDSA_CERT:
1807 	case KEY_ECDSA:
1808 		return ssh_ecdsa_verify(key, signature, signaturelen, data, datalen);
1809 #endif
1810 	case KEY_RSA_CERT_V00:
1811 	case KEY_RSA_CERT:
1812 	case KEY_RSA:
1813 		return ssh_rsa_verify(key, signature, signaturelen, data, datalen);
1814 	case KEY_ED25519:
1815 	case KEY_ED25519_CERT:
1816 		return ssh_ed25519_verify(key, signature, signaturelen, data, datalen);
1817 	default:
1818 		error("key_verify: invalid key type %d", key->type);
1819 		return -1;
1820 	}
1821 }
1822 
1823 /* Converts a private to a public key */
1824 Key *
key_demote(const Key * k)1825 key_demote(const Key *k)
1826 {
1827 	Key *pk;
1828 
1829 	pk = xcalloc(1, sizeof(*pk));
1830 	pk->type = k->type;
1831 	pk->flags = k->flags;
1832 	pk->ecdsa_nid = k->ecdsa_nid;
1833 	pk->dsa = NULL;
1834 	pk->ecdsa = NULL;
1835 	pk->rsa = NULL;
1836 	pk->ed25519_pk = NULL;
1837 	pk->ed25519_sk = NULL;
1838 
1839 	switch (k->type) {
1840 	case KEY_RSA_CERT_V00:
1841 	case KEY_RSA_CERT:
1842 		key_cert_copy(k, pk);
1843 		/* FALLTHROUGH */
1844 	case KEY_RSA1:
1845 	case KEY_RSA:
1846 		if ((pk->rsa = RSA_new()) == NULL)
1847 			fatal("key_demote: RSA_new failed");
1848 		if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL)
1849 			fatal("key_demote: BN_dup failed");
1850 		if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL)
1851 			fatal("key_demote: BN_dup failed");
1852 		break;
1853 	case KEY_DSA_CERT_V00:
1854 	case KEY_DSA_CERT:
1855 		key_cert_copy(k, pk);
1856 		/* FALLTHROUGH */
1857 	case KEY_DSA:
1858 		if ((pk->dsa = DSA_new()) == NULL)
1859 			fatal("key_demote: DSA_new failed");
1860 		if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL)
1861 			fatal("key_demote: BN_dup failed");
1862 		if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL)
1863 			fatal("key_demote: BN_dup failed");
1864 		if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL)
1865 			fatal("key_demote: BN_dup failed");
1866 		if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL)
1867 			fatal("key_demote: BN_dup failed");
1868 		break;
1869 #ifdef OPENSSL_HAS_ECC
1870 	case KEY_ECDSA_CERT:
1871 		key_cert_copy(k, pk);
1872 		/* FALLTHROUGH */
1873 	case KEY_ECDSA:
1874 		if ((pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid)) == NULL)
1875 			fatal("key_demote: EC_KEY_new_by_curve_name failed");
1876 		if (EC_KEY_set_public_key(pk->ecdsa,
1877 		    EC_KEY_get0_public_key(k->ecdsa)) != 1)
1878 			fatal("key_demote: EC_KEY_set_public_key failed");
1879 		break;
1880 #endif
1881 	case KEY_ED25519_CERT:
1882 		key_cert_copy(k, pk);
1883 		/* FALLTHROUGH */
1884 	case KEY_ED25519:
1885 		if (k->ed25519_pk != NULL) {
1886 			pk->ed25519_pk = xmalloc(ED25519_PK_SZ);
1887 			memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1888 		}
1889 		break;
1890 	default:
1891 		fatal("key_demote: bad key type %d", k->type);
1892 		break;
1893 	}
1894 
1895 	return (pk);
1896 }
1897 
1898 int
key_is_cert(const Key * k)1899 key_is_cert(const Key *k)
1900 {
1901 	if (k == NULL)
1902 		return 0;
1903 	return key_type_is_cert(k->type);
1904 }
1905 
1906 /* Return the cert-less equivalent to a certified key type */
1907 int
key_type_plain(int type)1908 key_type_plain(int type)
1909 {
1910 	switch (type) {
1911 	case KEY_RSA_CERT_V00:
1912 	case KEY_RSA_CERT:
1913 		return KEY_RSA;
1914 	case KEY_DSA_CERT_V00:
1915 	case KEY_DSA_CERT:
1916 		return KEY_DSA;
1917 	case KEY_ECDSA_CERT:
1918 		return KEY_ECDSA;
1919 	case KEY_ED25519_CERT:
1920 		return KEY_ED25519;
1921 	default:
1922 		return type;
1923 	}
1924 }
1925 
1926 /* Convert a plain key to their _CERT equivalent */
1927 int
key_to_certified(Key * k,int legacy)1928 key_to_certified(Key *k, int legacy)
1929 {
1930 	switch (k->type) {
1931 	case KEY_RSA:
1932 		k->cert = cert_new();
1933 		k->type = legacy ? KEY_RSA_CERT_V00 : KEY_RSA_CERT;
1934 		return 0;
1935 	case KEY_DSA:
1936 		k->cert = cert_new();
1937 		k->type = legacy ? KEY_DSA_CERT_V00 : KEY_DSA_CERT;
1938 		return 0;
1939 	case KEY_ECDSA:
1940 		if (legacy)
1941 			fatal("%s: legacy ECDSA certificates are not supported",
1942 			    __func__);
1943 		k->cert = cert_new();
1944 		k->type = KEY_ECDSA_CERT;
1945 		return 0;
1946 	case KEY_ED25519:
1947 		if (legacy)
1948 			fatal("%s: legacy ED25519 certificates are not "
1949 			    "supported", __func__);
1950 		k->cert = cert_new();
1951 		k->type = KEY_ED25519_CERT;
1952 		return 0;
1953 	default:
1954 		error("%s: key has incorrect type %s", __func__, key_type(k));
1955 		return -1;
1956 	}
1957 }
1958 
1959 /* Convert a certificate to its raw key equivalent */
1960 int
key_drop_cert(Key * k)1961 key_drop_cert(Key *k)
1962 {
1963 	if (!key_type_is_cert(k->type)) {
1964 		error("%s: key has incorrect type %s", __func__, key_type(k));
1965 		return -1;
1966 	}
1967 	cert_free(k->cert);
1968 	k->cert = NULL;
1969 	k->type = key_type_plain(k->type);
1970 	return 0;
1971 }
1972 
1973 /* Sign a certified key, (re-)generating the signed certblob. */
1974 int
key_certify(Key * k,Key * ca)1975 key_certify(Key *k, Key *ca)
1976 {
1977 	Buffer principals;
1978 	u_char *ca_blob, *sig_blob, nonce[32];
1979 	u_int i, ca_len, sig_len;
1980 
1981 	if (k->cert == NULL) {
1982 		error("%s: key lacks cert info", __func__);
1983 		return -1;
1984 	}
1985 
1986 	if (!key_is_cert(k)) {
1987 		error("%s: certificate has unknown type %d", __func__,
1988 		    k->cert->type);
1989 		return -1;
1990 	}
1991 
1992 	if (!key_type_is_valid_ca(ca->type)) {
1993 		error("%s: CA key has unsupported type %s", __func__,
1994 		    key_type(ca));
1995 		return -1;
1996 	}
1997 
1998 	key_to_blob(ca, &ca_blob, &ca_len);
1999 
2000 	buffer_clear(&k->cert->certblob);
2001 	buffer_put_cstring(&k->cert->certblob, key_ssh_name(k));
2002 
2003 	/* -v01 certs put nonce first */
2004 	arc4random_buf(&nonce, sizeof(nonce));
2005 	if (!key_cert_is_legacy(k))
2006 		buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
2007 
2008 	/* XXX this substantially duplicates to_blob(); refactor */
2009 	switch (k->type) {
2010 	case KEY_DSA_CERT_V00:
2011 	case KEY_DSA_CERT:
2012 		buffer_put_bignum2(&k->cert->certblob, k->dsa->p);
2013 		buffer_put_bignum2(&k->cert->certblob, k->dsa->q);
2014 		buffer_put_bignum2(&k->cert->certblob, k->dsa->g);
2015 		buffer_put_bignum2(&k->cert->certblob, k->dsa->pub_key);
2016 		break;
2017 #ifdef OPENSSL_HAS_ECC
2018 	case KEY_ECDSA_CERT:
2019 		buffer_put_cstring(&k->cert->certblob,
2020 		    key_curve_nid_to_name(k->ecdsa_nid));
2021 		buffer_put_ecpoint(&k->cert->certblob,
2022 		    EC_KEY_get0_group(k->ecdsa),
2023 		    EC_KEY_get0_public_key(k->ecdsa));
2024 		break;
2025 #endif
2026 	case KEY_RSA_CERT_V00:
2027 	case KEY_RSA_CERT:
2028 		buffer_put_bignum2(&k->cert->certblob, k->rsa->e);
2029 		buffer_put_bignum2(&k->cert->certblob, k->rsa->n);
2030 		break;
2031 	case KEY_ED25519_CERT:
2032 		buffer_put_string(&k->cert->certblob,
2033 		    k->ed25519_pk, ED25519_PK_SZ);
2034 		break;
2035 	default:
2036 		error("%s: key has incorrect type %s", __func__, key_type(k));
2037 		buffer_clear(&k->cert->certblob);
2038 		free(ca_blob);
2039 		return -1;
2040 	}
2041 
2042 	/* -v01 certs have a serial number next */
2043 	if (!key_cert_is_legacy(k))
2044 		buffer_put_int64(&k->cert->certblob, k->cert->serial);
2045 
2046 	buffer_put_int(&k->cert->certblob, k->cert->type);
2047 	buffer_put_cstring(&k->cert->certblob, k->cert->key_id);
2048 
2049 	buffer_init(&principals);
2050 	for (i = 0; i < k->cert->nprincipals; i++)
2051 		buffer_put_cstring(&principals, k->cert->principals[i]);
2052 	buffer_put_string(&k->cert->certblob, buffer_ptr(&principals),
2053 	    buffer_len(&principals));
2054 	buffer_free(&principals);
2055 
2056 	buffer_put_int64(&k->cert->certblob, k->cert->valid_after);
2057 	buffer_put_int64(&k->cert->certblob, k->cert->valid_before);
2058 	buffer_put_string(&k->cert->certblob,
2059 	    buffer_ptr(&k->cert->critical), buffer_len(&k->cert->critical));
2060 
2061 	/* -v01 certs have non-critical options here */
2062 	if (!key_cert_is_legacy(k)) {
2063 		buffer_put_string(&k->cert->certblob,
2064 		    buffer_ptr(&k->cert->extensions),
2065 		    buffer_len(&k->cert->extensions));
2066 	}
2067 
2068 	/* -v00 certs put the nonce at the end */
2069 	if (key_cert_is_legacy(k))
2070 		buffer_put_string(&k->cert->certblob, nonce, sizeof(nonce));
2071 
2072 	buffer_put_string(&k->cert->certblob, NULL, 0); /* reserved */
2073 	buffer_put_string(&k->cert->certblob, ca_blob, ca_len);
2074 	free(ca_blob);
2075 
2076 	/* Sign the whole mess */
2077 	if (key_sign(ca, &sig_blob, &sig_len, buffer_ptr(&k->cert->certblob),
2078 	    buffer_len(&k->cert->certblob)) != 0) {
2079 		error("%s: signature operation failed", __func__);
2080 		buffer_clear(&k->cert->certblob);
2081 		return -1;
2082 	}
2083 	/* Append signature and we are done */
2084 	buffer_put_string(&k->cert->certblob, sig_blob, sig_len);
2085 	free(sig_blob);
2086 
2087 	return 0;
2088 }
2089 
2090 int
key_cert_check_authority(const Key * k,int want_host,int require_principal,const char * name,const char ** reason)2091 key_cert_check_authority(const Key *k, int want_host, int require_principal,
2092     const char *name, const char **reason)
2093 {
2094 	u_int i, principal_matches;
2095 	time_t now = time(NULL);
2096 
2097 	if (want_host) {
2098 		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2099 			*reason = "Certificate invalid: not a host certificate";
2100 			return -1;
2101 		}
2102 	} else {
2103 		if (k->cert->type != SSH2_CERT_TYPE_USER) {
2104 			*reason = "Certificate invalid: not a user certificate";
2105 			return -1;
2106 		}
2107 	}
2108 	if (now < 0) {
2109 		error("%s: system clock lies before epoch", __func__);
2110 		*reason = "Certificate invalid: not yet valid";
2111 		return -1;
2112 	}
2113 	if ((u_int64_t)now < k->cert->valid_after) {
2114 		*reason = "Certificate invalid: not yet valid";
2115 		return -1;
2116 	}
2117 	if ((u_int64_t)now >= k->cert->valid_before) {
2118 		*reason = "Certificate invalid: expired";
2119 		return -1;
2120 	}
2121 	if (k->cert->nprincipals == 0) {
2122 		if (require_principal) {
2123 			*reason = "Certificate lacks principal list";
2124 			return -1;
2125 		}
2126 	} else if (name != NULL) {
2127 		principal_matches = 0;
2128 		for (i = 0; i < k->cert->nprincipals; i++) {
2129 			if (strcmp(name, k->cert->principals[i]) == 0) {
2130 				principal_matches = 1;
2131 				break;
2132 			}
2133 		}
2134 		if (!principal_matches) {
2135 			*reason = "Certificate invalid: name is not a listed "
2136 			    "principal";
2137 			return -1;
2138 		}
2139 	}
2140 	return 0;
2141 }
2142 
2143 int
key_cert_is_legacy(const Key * k)2144 key_cert_is_legacy(const Key *k)
2145 {
2146 	switch (k->type) {
2147 	case KEY_DSA_CERT_V00:
2148 	case KEY_RSA_CERT_V00:
2149 		return 1;
2150 	default:
2151 		return 0;
2152 	}
2153 }
2154 
2155 /* XXX: these are really begging for a table-driven approach */
2156 int
key_curve_name_to_nid(const char * name)2157 key_curve_name_to_nid(const char *name)
2158 {
2159 #ifdef OPENSSL_HAS_ECC
2160 	if (strcmp(name, "nistp256") == 0)
2161 		return NID_X9_62_prime256v1;
2162 	else if (strcmp(name, "nistp384") == 0)
2163 		return NID_secp384r1;
2164 # ifdef OPENSSL_HAS_NISTP521
2165 	else if (strcmp(name, "nistp521") == 0)
2166 		return NID_secp521r1;
2167 # endif
2168 #endif
2169 
2170 	debug("%s: unsupported EC curve name \"%.100s\"", __func__, name);
2171 	return -1;
2172 }
2173 
2174 u_int
key_curve_nid_to_bits(int nid)2175 key_curve_nid_to_bits(int nid)
2176 {
2177 	switch (nid) {
2178 #ifdef OPENSSL_HAS_ECC
2179 	case NID_X9_62_prime256v1:
2180 		return 256;
2181 	case NID_secp384r1:
2182 		return 384;
2183 # ifdef OPENSSL_HAS_NISTP521
2184 	case NID_secp521r1:
2185 		return 521;
2186 # endif
2187 #endif
2188 	default:
2189 		error("%s: unsupported EC curve nid %d", __func__, nid);
2190 		return 0;
2191 	}
2192 }
2193 
2194 const char *
key_curve_nid_to_name(int nid)2195 key_curve_nid_to_name(int nid)
2196 {
2197 #ifdef OPENSSL_HAS_ECC
2198 	if (nid == NID_X9_62_prime256v1)
2199 		return "nistp256";
2200 	else if (nid == NID_secp384r1)
2201 		return "nistp384";
2202 # ifdef OPENSSL_HAS_NISTP521
2203 	else if (nid == NID_secp521r1)
2204 		return "nistp521";
2205 # endif
2206 #endif
2207 	error("%s: unsupported EC curve nid %d", __func__, nid);
2208 	return NULL;
2209 }
2210 
2211 #ifdef OPENSSL_HAS_ECC
2212 int
key_ec_nid_to_hash_alg(int nid)2213 key_ec_nid_to_hash_alg(int nid)
2214 {
2215 	int kbits = key_curve_nid_to_bits(nid);
2216 
2217 	if (kbits == 0)
2218 		fatal("%s: invalid nid %d", __func__, nid);
2219 	/* RFC5656 section 6.2.1 */
2220 	if (kbits <= 256)
2221 		return SSH_DIGEST_SHA256;
2222 	else if (kbits <= 384)
2223 		return SSH_DIGEST_SHA384;
2224 	else
2225 		return SSH_DIGEST_SHA512;
2226 }
2227 
2228 int
key_ec_validate_public(const EC_GROUP * group,const EC_POINT * public)2229 key_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2230 {
2231 	BN_CTX *bnctx;
2232 	EC_POINT *nq = NULL;
2233 	BIGNUM *order, *x, *y, *tmp;
2234 	int ret = -1;
2235 
2236 	if ((bnctx = BN_CTX_new()) == NULL)
2237 		fatal("%s: BN_CTX_new failed", __func__);
2238 	BN_CTX_start(bnctx);
2239 
2240 	/*
2241 	 * We shouldn't ever hit this case because bignum_get_ecpoint()
2242 	 * refuses to load GF2m points.
2243 	 */
2244 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2245 	    NID_X9_62_prime_field) {
2246 		error("%s: group is not a prime field", __func__);
2247 		goto out;
2248 	}
2249 
2250 	/* Q != infinity */
2251 	if (EC_POINT_is_at_infinity(group, public)) {
2252 		error("%s: received degenerate public key (infinity)",
2253 		    __func__);
2254 		goto out;
2255 	}
2256 
2257 	if ((x = BN_CTX_get(bnctx)) == NULL ||
2258 	    (y = BN_CTX_get(bnctx)) == NULL ||
2259 	    (order = BN_CTX_get(bnctx)) == NULL ||
2260 	    (tmp = BN_CTX_get(bnctx)) == NULL)
2261 		fatal("%s: BN_CTX_get failed", __func__);
2262 
2263 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2264 	if (EC_GROUP_get_order(group, order, bnctx) != 1)
2265 		fatal("%s: EC_GROUP_get_order failed", __func__);
2266 	if (EC_POINT_get_affine_coordinates_GFp(group, public,
2267 	    x, y, bnctx) != 1)
2268 		fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2269 	if (BN_num_bits(x) <= BN_num_bits(order) / 2) {
2270 		error("%s: public key x coordinate too small: "
2271 		    "bits(x) = %d, bits(order)/2 = %d", __func__,
2272 		    BN_num_bits(x), BN_num_bits(order) / 2);
2273 		goto out;
2274 	}
2275 	if (BN_num_bits(y) <= BN_num_bits(order) / 2) {
2276 		error("%s: public key y coordinate too small: "
2277 		    "bits(y) = %d, bits(order)/2 = %d", __func__,
2278 		    BN_num_bits(x), BN_num_bits(order) / 2);
2279 		goto out;
2280 	}
2281 
2282 	/* nQ == infinity (n == order of subgroup) */
2283 	if ((nq = EC_POINT_new(group)) == NULL)
2284 		fatal("%s: BN_CTX_tmp failed", __func__);
2285 	if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1)
2286 		fatal("%s: EC_GROUP_mul failed", __func__);
2287 	if (EC_POINT_is_at_infinity(group, nq) != 1) {
2288 		error("%s: received degenerate public key (nQ != infinity)",
2289 		    __func__);
2290 		goto out;
2291 	}
2292 
2293 	/* x < order - 1, y < order - 1 */
2294 	if (!BN_sub(tmp, order, BN_value_one()))
2295 		fatal("%s: BN_sub failed", __func__);
2296 	if (BN_cmp(x, tmp) >= 0) {
2297 		error("%s: public key x coordinate >= group order - 1",
2298 		    __func__);
2299 		goto out;
2300 	}
2301 	if (BN_cmp(y, tmp) >= 0) {
2302 		error("%s: public key y coordinate >= group order - 1",
2303 		    __func__);
2304 		goto out;
2305 	}
2306 	ret = 0;
2307  out:
2308 	BN_CTX_free(bnctx);
2309 	EC_POINT_free(nq);
2310 	return ret;
2311 }
2312 
2313 int
key_ec_validate_private(const EC_KEY * key)2314 key_ec_validate_private(const EC_KEY *key)
2315 {
2316 	BN_CTX *bnctx;
2317 	BIGNUM *order, *tmp;
2318 	int ret = -1;
2319 
2320 	if ((bnctx = BN_CTX_new()) == NULL)
2321 		fatal("%s: BN_CTX_new failed", __func__);
2322 	BN_CTX_start(bnctx);
2323 
2324 	if ((order = BN_CTX_get(bnctx)) == NULL ||
2325 	    (tmp = BN_CTX_get(bnctx)) == NULL)
2326 		fatal("%s: BN_CTX_get failed", __func__);
2327 
2328 	/* log2(private) > log2(order)/2 */
2329 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1)
2330 		fatal("%s: EC_GROUP_get_order failed", __func__);
2331 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2332 	    BN_num_bits(order) / 2) {
2333 		error("%s: private key too small: "
2334 		    "bits(y) = %d, bits(order)/2 = %d", __func__,
2335 		    BN_num_bits(EC_KEY_get0_private_key(key)),
2336 		    BN_num_bits(order) / 2);
2337 		goto out;
2338 	}
2339 
2340 	/* private < order - 1 */
2341 	if (!BN_sub(tmp, order, BN_value_one()))
2342 		fatal("%s: BN_sub failed", __func__);
2343 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0) {
2344 		error("%s: private key >= group order - 1", __func__);
2345 		goto out;
2346 	}
2347 	ret = 0;
2348  out:
2349 	BN_CTX_free(bnctx);
2350 	return ret;
2351 }
2352 
2353 #if defined(DEBUG_KEXECDH) || defined(DEBUG_PK)
2354 void
key_dump_ec_point(const EC_GROUP * group,const EC_POINT * point)2355 key_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2356 {
2357 	BIGNUM *x, *y;
2358 	BN_CTX *bnctx;
2359 
2360 	if (point == NULL) {
2361 		fputs("point=(NULL)\n", stderr);
2362 		return;
2363 	}
2364 	if ((bnctx = BN_CTX_new()) == NULL)
2365 		fatal("%s: BN_CTX_new failed", __func__);
2366 	BN_CTX_start(bnctx);
2367 	if ((x = BN_CTX_get(bnctx)) == NULL || (y = BN_CTX_get(bnctx)) == NULL)
2368 		fatal("%s: BN_CTX_get failed", __func__);
2369 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2370 	    NID_X9_62_prime_field)
2371 		fatal("%s: group is not a prime field", __func__);
2372 	if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y, bnctx) != 1)
2373 		fatal("%s: EC_POINT_get_affine_coordinates_GFp", __func__);
2374 	fputs("x=", stderr);
2375 	BN_print_fp(stderr, x);
2376 	fputs("\ny=", stderr);
2377 	BN_print_fp(stderr, y);
2378 	fputs("\n", stderr);
2379 	BN_CTX_free(bnctx);
2380 }
2381 
2382 void
key_dump_ec_key(const EC_KEY * key)2383 key_dump_ec_key(const EC_KEY *key)
2384 {
2385 	const BIGNUM *exponent;
2386 
2387 	key_dump_ec_point(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key));
2388 	fputs("exponent=", stderr);
2389 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2390 		fputs("(NULL)", stderr);
2391 	else
2392 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2393 	fputs("\n", stderr);
2394 }
2395 #endif /* defined(DEBUG_KEXECDH) || defined(DEBUG_PK) */
2396 #endif /* OPENSSL_HAS_ECC */
2397 
2398 void
key_private_serialize(const Key * key,Buffer * b)2399 key_private_serialize(const Key *key, Buffer *b)
2400 {
2401 	buffer_put_cstring(b, key_ssh_name(key));
2402 	switch (key->type) {
2403 	case KEY_RSA:
2404 		buffer_put_bignum2(b, key->rsa->n);
2405 		buffer_put_bignum2(b, key->rsa->e);
2406 		buffer_put_bignum2(b, key->rsa->d);
2407 		buffer_put_bignum2(b, key->rsa->iqmp);
2408 		buffer_put_bignum2(b, key->rsa->p);
2409 		buffer_put_bignum2(b, key->rsa->q);
2410 		break;
2411 	case KEY_RSA_CERT_V00:
2412 	case KEY_RSA_CERT:
2413 		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
2414 			fatal("%s: no cert/certblob", __func__);
2415 		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
2416 		    buffer_len(&key->cert->certblob));
2417 		buffer_put_bignum2(b, key->rsa->d);
2418 		buffer_put_bignum2(b, key->rsa->iqmp);
2419 		buffer_put_bignum2(b, key->rsa->p);
2420 		buffer_put_bignum2(b, key->rsa->q);
2421 		break;
2422 	case KEY_DSA:
2423 		buffer_put_bignum2(b, key->dsa->p);
2424 		buffer_put_bignum2(b, key->dsa->q);
2425 		buffer_put_bignum2(b, key->dsa->g);
2426 		buffer_put_bignum2(b, key->dsa->pub_key);
2427 		buffer_put_bignum2(b, key->dsa->priv_key);
2428 		break;
2429 	case KEY_DSA_CERT_V00:
2430 	case KEY_DSA_CERT:
2431 		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
2432 			fatal("%s: no cert/certblob", __func__);
2433 		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
2434 		    buffer_len(&key->cert->certblob));
2435 		buffer_put_bignum2(b, key->dsa->priv_key);
2436 		break;
2437 #ifdef OPENSSL_HAS_ECC
2438 	case KEY_ECDSA:
2439 		buffer_put_cstring(b, key_curve_nid_to_name(key->ecdsa_nid));
2440 		buffer_put_ecpoint(b, EC_KEY_get0_group(key->ecdsa),
2441 		    EC_KEY_get0_public_key(key->ecdsa));
2442 		buffer_put_bignum2(b, EC_KEY_get0_private_key(key->ecdsa));
2443 		break;
2444 	case KEY_ECDSA_CERT:
2445 		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
2446 			fatal("%s: no cert/certblob", __func__);
2447 		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
2448 		    buffer_len(&key->cert->certblob));
2449 		buffer_put_bignum2(b, EC_KEY_get0_private_key(key->ecdsa));
2450 		break;
2451 #endif /* OPENSSL_HAS_ECC */
2452 	case KEY_ED25519:
2453 		buffer_put_string(b, key->ed25519_pk, ED25519_PK_SZ);
2454 		buffer_put_string(b, key->ed25519_sk, ED25519_SK_SZ);
2455 		break;
2456 	case KEY_ED25519_CERT:
2457 		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
2458 			fatal("%s: no cert/certblob", __func__);
2459 		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
2460 		    buffer_len(&key->cert->certblob));
2461 		buffer_put_string(b, key->ed25519_pk, ED25519_PK_SZ);
2462 		buffer_put_string(b, key->ed25519_sk, ED25519_SK_SZ);
2463 		break;
2464 	}
2465 }
2466 
2467 Key *
key_private_deserialize(Buffer * blob)2468 key_private_deserialize(Buffer *blob)
2469 {
2470 	char *type_name;
2471 	Key *k = NULL;
2472 	u_char *cert;
2473 	u_int len, pklen, sklen;
2474 	int type;
2475 #ifdef OPENSSL_HAS_ECC
2476 	char *curve;
2477 	BIGNUM *exponent;
2478 	EC_POINT *q;
2479 #endif
2480 
2481 	type_name = buffer_get_string(blob, NULL);
2482 	type = key_type_from_name(type_name);
2483 	switch (type) {
2484 	case KEY_DSA:
2485 		k = key_new_private(type);
2486 		buffer_get_bignum2(blob, k->dsa->p);
2487 		buffer_get_bignum2(blob, k->dsa->q);
2488 		buffer_get_bignum2(blob, k->dsa->g);
2489 		buffer_get_bignum2(blob, k->dsa->pub_key);
2490 		buffer_get_bignum2(blob, k->dsa->priv_key);
2491 		break;
2492 	case KEY_DSA_CERT_V00:
2493 	case KEY_DSA_CERT:
2494 		cert = buffer_get_string(blob, &len);
2495 		if ((k = key_from_blob(cert, len)) == NULL)
2496 			fatal("Certificate parse failed");
2497 		free(cert);
2498 		key_add_private(k);
2499 		buffer_get_bignum2(blob, k->dsa->priv_key);
2500 		break;
2501 #ifdef OPENSSL_HAS_ECC
2502 	case KEY_ECDSA:
2503 		k = key_new_private(type);
2504 		k->ecdsa_nid = key_ecdsa_nid_from_name(type_name);
2505 		curve = buffer_get_string(blob, NULL);
2506 		if (k->ecdsa_nid != key_curve_name_to_nid(curve))
2507 			fatal("%s: curve names mismatch", __func__);
2508 		free(curve);
2509 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2510 		if (k->ecdsa == NULL)
2511 			fatal("%s: EC_KEY_new_by_curve_name failed",
2512 			    __func__);
2513 		q = EC_POINT_new(EC_KEY_get0_group(k->ecdsa));
2514 		if (q == NULL)
2515 			fatal("%s: BN_new failed", __func__);
2516 		if ((exponent = BN_new()) == NULL)
2517 			fatal("%s: BN_new failed", __func__);
2518 		buffer_get_ecpoint(blob,
2519 			EC_KEY_get0_group(k->ecdsa), q);
2520 		buffer_get_bignum2(blob, exponent);
2521 		if (EC_KEY_set_public_key(k->ecdsa, q) != 1)
2522 			fatal("%s: EC_KEY_set_public_key failed",
2523 			    __func__);
2524 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
2525 			fatal("%s: EC_KEY_set_private_key failed",
2526 			    __func__);
2527 		if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2528 		    EC_KEY_get0_public_key(k->ecdsa)) != 0)
2529 			fatal("%s: bad ECDSA public key", __func__);
2530 		if (key_ec_validate_private(k->ecdsa) != 0)
2531 			fatal("%s: bad ECDSA private key", __func__);
2532 		BN_clear_free(exponent);
2533 		EC_POINT_free(q);
2534 		break;
2535 	case KEY_ECDSA_CERT:
2536 		cert = buffer_get_string(blob, &len);
2537 		if ((k = key_from_blob(cert, len)) == NULL)
2538 			fatal("Certificate parse failed");
2539 		free(cert);
2540 		key_add_private(k);
2541 		if ((exponent = BN_new()) == NULL)
2542 			fatal("%s: BN_new failed", __func__);
2543 		buffer_get_bignum2(blob, exponent);
2544 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1)
2545 			fatal("%s: EC_KEY_set_private_key failed",
2546 			    __func__);
2547 		if (key_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2548 		    EC_KEY_get0_public_key(k->ecdsa)) != 0 ||
2549 		    key_ec_validate_private(k->ecdsa) != 0)
2550 			fatal("%s: bad ECDSA key", __func__);
2551 		BN_clear_free(exponent);
2552 		break;
2553 #endif
2554 	case KEY_RSA:
2555 		k = key_new_private(type);
2556 		buffer_get_bignum2(blob, k->rsa->n);
2557 		buffer_get_bignum2(blob, k->rsa->e);
2558 		buffer_get_bignum2(blob, k->rsa->d);
2559 		buffer_get_bignum2(blob, k->rsa->iqmp);
2560 		buffer_get_bignum2(blob, k->rsa->p);
2561 		buffer_get_bignum2(blob, k->rsa->q);
2562 
2563 		/* Generate additional parameters */
2564 		rsa_generate_additional_parameters(k->rsa);
2565 		break;
2566 	case KEY_RSA_CERT_V00:
2567 	case KEY_RSA_CERT:
2568 		cert = buffer_get_string(blob, &len);
2569 		if ((k = key_from_blob(cert, len)) == NULL)
2570 			fatal("Certificate parse failed");
2571 		free(cert);
2572 		key_add_private(k);
2573 		buffer_get_bignum2(blob, k->rsa->d);
2574 		buffer_get_bignum2(blob, k->rsa->iqmp);
2575 		buffer_get_bignum2(blob, k->rsa->p);
2576 		buffer_get_bignum2(blob, k->rsa->q);
2577 		break;
2578 	case KEY_ED25519:
2579 		k = key_new_private(type);
2580 		k->ed25519_pk = buffer_get_string(blob, &pklen);
2581 		k->ed25519_sk = buffer_get_string(blob, &sklen);
2582 		if (pklen != ED25519_PK_SZ)
2583 			fatal("%s: ed25519 pklen %d != %d",
2584 			    __func__, pklen, ED25519_PK_SZ);
2585 		if (sklen != ED25519_SK_SZ)
2586 			fatal("%s: ed25519 sklen %d != %d",
2587 			    __func__, sklen, ED25519_SK_SZ);
2588 		break;
2589 	case KEY_ED25519_CERT:
2590 		cert = buffer_get_string(blob, &len);
2591 		if ((k = key_from_blob(cert, len)) == NULL)
2592 			fatal("Certificate parse failed");
2593 		free(cert);
2594 		key_add_private(k);
2595 		k->ed25519_pk = buffer_get_string(blob, &pklen);
2596 		k->ed25519_sk = buffer_get_string(blob, &sklen);
2597 		if (pklen != ED25519_PK_SZ)
2598 			fatal("%s: ed25519 pklen %d != %d",
2599 			    __func__, pklen, ED25519_PK_SZ);
2600 		if (sklen != ED25519_SK_SZ)
2601 			fatal("%s: ed25519 sklen %d != %d",
2602 			    __func__, sklen, ED25519_SK_SZ);
2603 		break;
2604 	default:
2605 		free(type_name);
2606 		buffer_clear(blob);
2607 		return NULL;
2608 	}
2609 	free(type_name);
2610 
2611 	/* enable blinding */
2612 	switch (k->type) {
2613 	case KEY_RSA:
2614 	case KEY_RSA_CERT_V00:
2615 	case KEY_RSA_CERT:
2616 	case KEY_RSA1:
2617 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
2618 			error("%s: RSA_blinding_on failed", __func__);
2619 			key_free(k);
2620 			return NULL;
2621 		}
2622 		break;
2623 	}
2624 	return k;
2625 }
2626