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