xref: /dragonfly/crypto/openssh/sshkey.c (revision a3127495)
1 /* $OpenBSD: sshkey.c,v 1.56 2017/08/12 06:42:52 djm Exp $ */
2 /*
3  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
5  * Copyright (c) 2010,2011 Damien Miller.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "includes.h"
29 
30 #include <sys/types.h>
31 #include <netinet/in.h>
32 
33 #ifdef WITH_OPENSSL
34 #include <openssl/evp.h>
35 #include <openssl/err.h>
36 #include <openssl/pem.h>
37 #endif
38 
39 #include "crypto_api.h"
40 
41 #include <errno.h>
42 #include <limits.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <resolv.h>
46 #ifdef HAVE_UTIL_H
47 #include <util.h>
48 #endif /* HAVE_UTIL_H */
49 
50 #include "ssh2.h"
51 #include "ssherr.h"
52 #include "misc.h"
53 #include "sshbuf.h"
54 #include "cipher.h"
55 #include "digest.h"
56 #define SSHKEY_INTERNAL
57 #include "sshkey.h"
58 #include "match.h"
59 
60 /* openssh private key file format */
61 #define MARK_BEGIN		"-----BEGIN OPENSSH PRIVATE KEY-----\n"
62 #define MARK_END		"-----END OPENSSH PRIVATE KEY-----\n"
63 #define MARK_BEGIN_LEN		(sizeof(MARK_BEGIN) - 1)
64 #define MARK_END_LEN		(sizeof(MARK_END) - 1)
65 #define KDFNAME			"bcrypt"
66 #define AUTH_MAGIC		"openssh-key-v1"
67 #define SALT_LEN		16
68 #define DEFAULT_CIPHERNAME	"aes256-ctr"
69 #define	DEFAULT_ROUNDS		16
70 
71 /* Version identification string for SSH v1 identity files. */
72 #define LEGACY_BEGIN		"SSH PRIVATE KEY FILE FORMAT 1.1\n"
73 
74 static int sshkey_from_blob_internal(struct sshbuf *buf,
75     struct sshkey **keyp, int allow_cert);
76 
77 /* Supported key types */
78 struct keytype {
79 	const char *name;
80 	const char *shortname;
81 	int type;
82 	int nid;
83 	int cert;
84 	int sigonly;
85 };
86 static const struct keytype keytypes[] = {
87 	{ "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0, 0 },
88 	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
89 	    KEY_ED25519_CERT, 0, 1, 0 },
90 #ifdef WITH_OPENSSL
91 	{ "ssh-rsa", "RSA", KEY_RSA, 0, 0, 0 },
92 	{ "rsa-sha2-256", "RSA", KEY_RSA, 0, 0, 1 },
93 	{ "rsa-sha2-512", "RSA", KEY_RSA, 0, 0, 1 },
94 	{ "ssh-dss", "DSA", KEY_DSA, 0, 0, 0 },
95 # ifdef OPENSSL_HAS_ECC
96 	{ "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
97 	{ "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0, 0 },
98 #  ifdef OPENSSL_HAS_NISTP521
99 	{ "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0, 0 },
100 #  endif /* OPENSSL_HAS_NISTP521 */
101 # endif /* OPENSSL_HAS_ECC */
102 	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1, 0 },
103 	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1, 0 },
104 # ifdef OPENSSL_HAS_ECC
105 	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
106 	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
107 	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
108 	    KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
109 #  ifdef OPENSSL_HAS_NISTP521
110 	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
111 	    KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
112 #  endif /* OPENSSL_HAS_NISTP521 */
113 # endif /* OPENSSL_HAS_ECC */
114 #endif /* WITH_OPENSSL */
115 	{ NULL, NULL, -1, -1, 0, 0 }
116 };
117 
118 const char *
119 sshkey_type(const struct sshkey *k)
120 {
121 	const struct keytype *kt;
122 
123 	for (kt = keytypes; kt->type != -1; kt++) {
124 		if (kt->type == k->type)
125 			return kt->shortname;
126 	}
127 	return "unknown";
128 }
129 
130 static const char *
131 sshkey_ssh_name_from_type_nid(int type, int nid)
132 {
133 	const struct keytype *kt;
134 
135 	for (kt = keytypes; kt->type != -1; kt++) {
136 		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
137 			return kt->name;
138 	}
139 	return "ssh-unknown";
140 }
141 
142 int
143 sshkey_type_is_cert(int type)
144 {
145 	const struct keytype *kt;
146 
147 	for (kt = keytypes; kt->type != -1; kt++) {
148 		if (kt->type == type)
149 			return kt->cert;
150 	}
151 	return 0;
152 }
153 
154 const char *
155 sshkey_ssh_name(const struct sshkey *k)
156 {
157 	return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
158 }
159 
160 const char *
161 sshkey_ssh_name_plain(const struct sshkey *k)
162 {
163 	return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
164 	    k->ecdsa_nid);
165 }
166 
167 int
168 sshkey_type_from_name(const char *name)
169 {
170 	const struct keytype *kt;
171 
172 	for (kt = keytypes; kt->type != -1; kt++) {
173 		/* Only allow shortname matches for plain key types */
174 		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
175 		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
176 			return kt->type;
177 	}
178 	return KEY_UNSPEC;
179 }
180 
181 int
182 sshkey_ecdsa_nid_from_name(const char *name)
183 {
184 	const struct keytype *kt;
185 
186 	for (kt = keytypes; kt->type != -1; kt++) {
187 		if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
188 			continue;
189 		if (kt->name != NULL && strcmp(name, kt->name) == 0)
190 			return kt->nid;
191 	}
192 	return -1;
193 }
194 
195 char *
196 sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
197 {
198 	char *tmp, *ret = NULL;
199 	size_t nlen, rlen = 0;
200 	const struct keytype *kt;
201 
202 	for (kt = keytypes; kt->type != -1; kt++) {
203 		if (kt->name == NULL)
204 			continue;
205 		if (!include_sigonly && kt->sigonly)
206 			continue;
207 		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
208 			continue;
209 		if (ret != NULL)
210 			ret[rlen++] = sep;
211 		nlen = strlen(kt->name);
212 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
213 			free(ret);
214 			return NULL;
215 		}
216 		ret = tmp;
217 		memcpy(ret + rlen, kt->name, nlen + 1);
218 		rlen += nlen;
219 	}
220 	return ret;
221 }
222 
223 int
224 sshkey_names_valid2(const char *names, int allow_wildcard)
225 {
226 	char *s, *cp, *p;
227 	const struct keytype *kt;
228 	int type;
229 
230 	if (names == NULL || strcmp(names, "") == 0)
231 		return 0;
232 	if ((s = cp = strdup(names)) == NULL)
233 		return 0;
234 	for ((p = strsep(&cp, ",")); p && *p != '\0';
235 	    (p = strsep(&cp, ","))) {
236 		type = sshkey_type_from_name(p);
237 		if (type == KEY_UNSPEC) {
238 			if (allow_wildcard) {
239 				/*
240 				 * Try matching key types against the string.
241 				 * If any has a positive or negative match then
242 				 * the component is accepted.
243 				 */
244 				for (kt = keytypes; kt->type != -1; kt++) {
245 					if (match_pattern_list(kt->name,
246 					    p, 0) != 0)
247 						break;
248 				}
249 				if (kt->type != -1)
250 					continue;
251 			}
252 			free(s);
253 			return 0;
254 		}
255 	}
256 	free(s);
257 	return 1;
258 }
259 
260 u_int
261 sshkey_size(const struct sshkey *k)
262 {
263 	switch (k->type) {
264 #ifdef WITH_OPENSSL
265 	case KEY_RSA:
266 	case KEY_RSA_CERT:
267 		return BN_num_bits(k->rsa->n);
268 	case KEY_DSA:
269 	case KEY_DSA_CERT:
270 		return BN_num_bits(k->dsa->p);
271 	case KEY_ECDSA:
272 	case KEY_ECDSA_CERT:
273 		return sshkey_curve_nid_to_bits(k->ecdsa_nid);
274 #endif /* WITH_OPENSSL */
275 	case KEY_ED25519:
276 	case KEY_ED25519_CERT:
277 		return 256;	/* XXX */
278 	}
279 	return 0;
280 }
281 
282 static int
283 sshkey_type_is_valid_ca(int type)
284 {
285 	switch (type) {
286 	case KEY_RSA:
287 	case KEY_DSA:
288 	case KEY_ECDSA:
289 	case KEY_ED25519:
290 		return 1;
291 	default:
292 		return 0;
293 	}
294 }
295 
296 int
297 sshkey_is_cert(const struct sshkey *k)
298 {
299 	if (k == NULL)
300 		return 0;
301 	return sshkey_type_is_cert(k->type);
302 }
303 
304 /* Return the cert-less equivalent to a certified key type */
305 int
306 sshkey_type_plain(int type)
307 {
308 	switch (type) {
309 	case KEY_RSA_CERT:
310 		return KEY_RSA;
311 	case KEY_DSA_CERT:
312 		return KEY_DSA;
313 	case KEY_ECDSA_CERT:
314 		return KEY_ECDSA;
315 	case KEY_ED25519_CERT:
316 		return KEY_ED25519;
317 	default:
318 		return type;
319 	}
320 }
321 
322 #ifdef WITH_OPENSSL
323 /* XXX: these are really begging for a table-driven approach */
324 int
325 sshkey_curve_name_to_nid(const char *name)
326 {
327 	if (strcmp(name, "nistp256") == 0)
328 		return NID_X9_62_prime256v1;
329 	else if (strcmp(name, "nistp384") == 0)
330 		return NID_secp384r1;
331 # ifdef OPENSSL_HAS_NISTP521
332 	else if (strcmp(name, "nistp521") == 0)
333 		return NID_secp521r1;
334 # endif /* OPENSSL_HAS_NISTP521 */
335 	else
336 		return -1;
337 }
338 
339 u_int
340 sshkey_curve_nid_to_bits(int nid)
341 {
342 	switch (nid) {
343 	case NID_X9_62_prime256v1:
344 		return 256;
345 	case NID_secp384r1:
346 		return 384;
347 # ifdef OPENSSL_HAS_NISTP521
348 	case NID_secp521r1:
349 		return 521;
350 # endif /* OPENSSL_HAS_NISTP521 */
351 	default:
352 		return 0;
353 	}
354 }
355 
356 int
357 sshkey_ecdsa_bits_to_nid(int bits)
358 {
359 	switch (bits) {
360 	case 256:
361 		return NID_X9_62_prime256v1;
362 	case 384:
363 		return NID_secp384r1;
364 # ifdef OPENSSL_HAS_NISTP521
365 	case 521:
366 		return NID_secp521r1;
367 # endif /* OPENSSL_HAS_NISTP521 */
368 	default:
369 		return -1;
370 	}
371 }
372 
373 const char *
374 sshkey_curve_nid_to_name(int nid)
375 {
376 	switch (nid) {
377 	case NID_X9_62_prime256v1:
378 		return "nistp256";
379 	case NID_secp384r1:
380 		return "nistp384";
381 # ifdef OPENSSL_HAS_NISTP521
382 	case NID_secp521r1:
383 		return "nistp521";
384 # endif /* OPENSSL_HAS_NISTP521 */
385 	default:
386 		return NULL;
387 	}
388 }
389 
390 int
391 sshkey_ec_nid_to_hash_alg(int nid)
392 {
393 	int kbits = sshkey_curve_nid_to_bits(nid);
394 
395 	if (kbits <= 0)
396 		return -1;
397 
398 	/* RFC5656 section 6.2.1 */
399 	if (kbits <= 256)
400 		return SSH_DIGEST_SHA256;
401 	else if (kbits <= 384)
402 		return SSH_DIGEST_SHA384;
403 	else
404 		return SSH_DIGEST_SHA512;
405 }
406 #endif /* WITH_OPENSSL */
407 
408 static void
409 cert_free(struct sshkey_cert *cert)
410 {
411 	u_int i;
412 
413 	if (cert == NULL)
414 		return;
415 	sshbuf_free(cert->certblob);
416 	sshbuf_free(cert->critical);
417 	sshbuf_free(cert->extensions);
418 	free(cert->key_id);
419 	for (i = 0; i < cert->nprincipals; i++)
420 		free(cert->principals[i]);
421 	free(cert->principals);
422 	sshkey_free(cert->signature_key);
423 	explicit_bzero(cert, sizeof(*cert));
424 	free(cert);
425 }
426 
427 static struct sshkey_cert *
428 cert_new(void)
429 {
430 	struct sshkey_cert *cert;
431 
432 	if ((cert = calloc(1, sizeof(*cert))) == NULL)
433 		return NULL;
434 	if ((cert->certblob = sshbuf_new()) == NULL ||
435 	    (cert->critical = sshbuf_new()) == NULL ||
436 	    (cert->extensions = sshbuf_new()) == NULL) {
437 		cert_free(cert);
438 		return NULL;
439 	}
440 	cert->key_id = NULL;
441 	cert->principals = NULL;
442 	cert->signature_key = NULL;
443 	return cert;
444 }
445 
446 struct sshkey *
447 sshkey_new(int type)
448 {
449 	struct sshkey *k;
450 #ifdef WITH_OPENSSL
451 	RSA *rsa;
452 	DSA *dsa;
453 #endif /* WITH_OPENSSL */
454 
455 	if ((k = calloc(1, sizeof(*k))) == NULL)
456 		return NULL;
457 	k->type = type;
458 	k->ecdsa = NULL;
459 	k->ecdsa_nid = -1;
460 	k->dsa = NULL;
461 	k->rsa = NULL;
462 	k->cert = NULL;
463 	k->ed25519_sk = NULL;
464 	k->ed25519_pk = NULL;
465 	switch (k->type) {
466 #ifdef WITH_OPENSSL
467 	case KEY_RSA:
468 	case KEY_RSA_CERT:
469 		if ((rsa = RSA_new()) == NULL ||
470 		    (rsa->n = BN_new()) == NULL ||
471 		    (rsa->e = BN_new()) == NULL) {
472 			if (rsa != NULL)
473 				RSA_free(rsa);
474 			free(k);
475 			return NULL;
476 		}
477 		k->rsa = rsa;
478 		break;
479 	case KEY_DSA:
480 	case KEY_DSA_CERT:
481 		if ((dsa = DSA_new()) == NULL ||
482 		    (dsa->p = BN_new()) == NULL ||
483 		    (dsa->q = BN_new()) == NULL ||
484 		    (dsa->g = BN_new()) == NULL ||
485 		    (dsa->pub_key = BN_new()) == NULL) {
486 			if (dsa != NULL)
487 				DSA_free(dsa);
488 			free(k);
489 			return NULL;
490 		}
491 		k->dsa = dsa;
492 		break;
493 	case KEY_ECDSA:
494 	case KEY_ECDSA_CERT:
495 		/* Cannot do anything until we know the group */
496 		break;
497 #endif /* WITH_OPENSSL */
498 	case KEY_ED25519:
499 	case KEY_ED25519_CERT:
500 		/* no need to prealloc */
501 		break;
502 	case KEY_UNSPEC:
503 		break;
504 	default:
505 		free(k);
506 		return NULL;
507 	}
508 
509 	if (sshkey_is_cert(k)) {
510 		if ((k->cert = cert_new()) == NULL) {
511 			sshkey_free(k);
512 			return NULL;
513 		}
514 	}
515 
516 	return k;
517 }
518 
519 int
520 sshkey_add_private(struct sshkey *k)
521 {
522 	switch (k->type) {
523 #ifdef WITH_OPENSSL
524 	case KEY_RSA:
525 	case KEY_RSA_CERT:
526 #define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
527 		if (bn_maybe_alloc_failed(k->rsa->d) ||
528 		    bn_maybe_alloc_failed(k->rsa->iqmp) ||
529 		    bn_maybe_alloc_failed(k->rsa->q) ||
530 		    bn_maybe_alloc_failed(k->rsa->p) ||
531 		    bn_maybe_alloc_failed(k->rsa->dmq1) ||
532 		    bn_maybe_alloc_failed(k->rsa->dmp1))
533 			return SSH_ERR_ALLOC_FAIL;
534 		break;
535 	case KEY_DSA:
536 	case KEY_DSA_CERT:
537 		if (bn_maybe_alloc_failed(k->dsa->priv_key))
538 			return SSH_ERR_ALLOC_FAIL;
539 		break;
540 #undef bn_maybe_alloc_failed
541 	case KEY_ECDSA:
542 	case KEY_ECDSA_CERT:
543 		/* Cannot do anything until we know the group */
544 		break;
545 #endif /* WITH_OPENSSL */
546 	case KEY_ED25519:
547 	case KEY_ED25519_CERT:
548 		/* no need to prealloc */
549 		break;
550 	case KEY_UNSPEC:
551 		break;
552 	default:
553 		return SSH_ERR_INVALID_ARGUMENT;
554 	}
555 	return 0;
556 }
557 
558 struct sshkey *
559 sshkey_new_private(int type)
560 {
561 	struct sshkey *k = sshkey_new(type);
562 
563 	if (k == NULL)
564 		return NULL;
565 	if (sshkey_add_private(k) != 0) {
566 		sshkey_free(k);
567 		return NULL;
568 	}
569 	return k;
570 }
571 
572 void
573 sshkey_free(struct sshkey *k)
574 {
575 	if (k == NULL)
576 		return;
577 	switch (k->type) {
578 #ifdef WITH_OPENSSL
579 	case KEY_RSA:
580 	case KEY_RSA_CERT:
581 		if (k->rsa != NULL)
582 			RSA_free(k->rsa);
583 		k->rsa = NULL;
584 		break;
585 	case KEY_DSA:
586 	case KEY_DSA_CERT:
587 		if (k->dsa != NULL)
588 			DSA_free(k->dsa);
589 		k->dsa = NULL;
590 		break;
591 # ifdef OPENSSL_HAS_ECC
592 	case KEY_ECDSA:
593 	case KEY_ECDSA_CERT:
594 		if (k->ecdsa != NULL)
595 			EC_KEY_free(k->ecdsa);
596 		k->ecdsa = NULL;
597 		break;
598 # endif /* OPENSSL_HAS_ECC */
599 #endif /* WITH_OPENSSL */
600 	case KEY_ED25519:
601 	case KEY_ED25519_CERT:
602 		if (k->ed25519_pk) {
603 			explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
604 			free(k->ed25519_pk);
605 			k->ed25519_pk = NULL;
606 		}
607 		if (k->ed25519_sk) {
608 			explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
609 			free(k->ed25519_sk);
610 			k->ed25519_sk = NULL;
611 		}
612 		break;
613 	case KEY_UNSPEC:
614 		break;
615 	default:
616 		break;
617 	}
618 	if (sshkey_is_cert(k))
619 		cert_free(k->cert);
620 	explicit_bzero(k, sizeof(*k));
621 	free(k);
622 }
623 
624 static int
625 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
626 {
627 	if (a == NULL && b == NULL)
628 		return 1;
629 	if (a == NULL || b == NULL)
630 		return 0;
631 	if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
632 		return 0;
633 	if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
634 	    sshbuf_len(a->certblob)) != 0)
635 		return 0;
636 	return 1;
637 }
638 
639 /*
640  * Compare public portions of key only, allowing comparisons between
641  * certificates and plain keys too.
642  */
643 int
644 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
645 {
646 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
647 	BN_CTX *bnctx;
648 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
649 
650 	if (a == NULL || b == NULL ||
651 	    sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
652 		return 0;
653 
654 	switch (a->type) {
655 #ifdef WITH_OPENSSL
656 	case KEY_RSA_CERT:
657 	case KEY_RSA:
658 		return a->rsa != NULL && b->rsa != NULL &&
659 		    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
660 		    BN_cmp(a->rsa->n, b->rsa->n) == 0;
661 	case KEY_DSA_CERT:
662 	case KEY_DSA:
663 		return a->dsa != NULL && b->dsa != NULL &&
664 		    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
665 		    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
666 		    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
667 		    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
668 # ifdef OPENSSL_HAS_ECC
669 	case KEY_ECDSA_CERT:
670 	case KEY_ECDSA:
671 		if (a->ecdsa == NULL || b->ecdsa == NULL ||
672 		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
673 		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
674 			return 0;
675 		if ((bnctx = BN_CTX_new()) == NULL)
676 			return 0;
677 		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
678 		    EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
679 		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
680 		    EC_KEY_get0_public_key(a->ecdsa),
681 		    EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
682 			BN_CTX_free(bnctx);
683 			return 0;
684 		}
685 		BN_CTX_free(bnctx);
686 		return 1;
687 # endif /* OPENSSL_HAS_ECC */
688 #endif /* WITH_OPENSSL */
689 	case KEY_ED25519:
690 	case KEY_ED25519_CERT:
691 		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
692 		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
693 	default:
694 		return 0;
695 	}
696 	/* NOTREACHED */
697 }
698 
699 int
700 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
701 {
702 	if (a == NULL || b == NULL || a->type != b->type)
703 		return 0;
704 	if (sshkey_is_cert(a)) {
705 		if (!cert_compare(a->cert, b->cert))
706 			return 0;
707 	}
708 	return sshkey_equal_public(a, b);
709 }
710 
711 static int
712 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
713 {
714 	int type, ret = SSH_ERR_INTERNAL_ERROR;
715 	const char *typename;
716 
717 	if (key == NULL)
718 		return SSH_ERR_INVALID_ARGUMENT;
719 
720 	if (sshkey_is_cert(key)) {
721 		if (key->cert == NULL)
722 			return SSH_ERR_EXPECTED_CERT;
723 		if (sshbuf_len(key->cert->certblob) == 0)
724 			return SSH_ERR_KEY_LACKS_CERTBLOB;
725 	}
726 	type = force_plain ? sshkey_type_plain(key->type) : key->type;
727 	typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
728 
729 	switch (type) {
730 #ifdef WITH_OPENSSL
731 	case KEY_DSA_CERT:
732 	case KEY_ECDSA_CERT:
733 	case KEY_RSA_CERT:
734 #endif /* WITH_OPENSSL */
735 	case KEY_ED25519_CERT:
736 		/* Use the existing blob */
737 		/* XXX modified flag? */
738 		if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
739 			return ret;
740 		break;
741 #ifdef WITH_OPENSSL
742 	case KEY_DSA:
743 		if (key->dsa == NULL)
744 			return SSH_ERR_INVALID_ARGUMENT;
745 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
746 		    (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
747 		    (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
748 		    (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
749 		    (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
750 			return ret;
751 		break;
752 # ifdef OPENSSL_HAS_ECC
753 	case KEY_ECDSA:
754 		if (key->ecdsa == NULL)
755 			return SSH_ERR_INVALID_ARGUMENT;
756 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
757 		    (ret = sshbuf_put_cstring(b,
758 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
759 		    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
760 			return ret;
761 		break;
762 # endif
763 	case KEY_RSA:
764 		if (key->rsa == NULL)
765 			return SSH_ERR_INVALID_ARGUMENT;
766 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
767 		    (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
768 		    (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
769 			return ret;
770 		break;
771 #endif /* WITH_OPENSSL */
772 	case KEY_ED25519:
773 		if (key->ed25519_pk == NULL)
774 			return SSH_ERR_INVALID_ARGUMENT;
775 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
776 		    (ret = sshbuf_put_string(b,
777 		    key->ed25519_pk, ED25519_PK_SZ)) != 0)
778 			return ret;
779 		break;
780 	default:
781 		return SSH_ERR_KEY_TYPE_UNKNOWN;
782 	}
783 	return 0;
784 }
785 
786 int
787 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
788 {
789 	return to_blob_buf(key, b, 0);
790 }
791 
792 int
793 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
794 {
795 	struct sshbuf *tmp;
796 	int r;
797 
798 	if ((tmp = sshbuf_new()) == NULL)
799 		return SSH_ERR_ALLOC_FAIL;
800 	r = to_blob_buf(key, tmp, 0);
801 	if (r == 0)
802 		r = sshbuf_put_stringb(b, tmp);
803 	sshbuf_free(tmp);
804 	return r;
805 }
806 
807 int
808 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
809 {
810 	return to_blob_buf(key, b, 1);
811 }
812 
813 static int
814 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
815 {
816 	int ret = SSH_ERR_INTERNAL_ERROR;
817 	size_t len;
818 	struct sshbuf *b = NULL;
819 
820 	if (lenp != NULL)
821 		*lenp = 0;
822 	if (blobp != NULL)
823 		*blobp = NULL;
824 	if ((b = sshbuf_new()) == NULL)
825 		return SSH_ERR_ALLOC_FAIL;
826 	if ((ret = to_blob_buf(key, b, force_plain)) != 0)
827 		goto out;
828 	len = sshbuf_len(b);
829 	if (lenp != NULL)
830 		*lenp = len;
831 	if (blobp != NULL) {
832 		if ((*blobp = malloc(len)) == NULL) {
833 			ret = SSH_ERR_ALLOC_FAIL;
834 			goto out;
835 		}
836 		memcpy(*blobp, sshbuf_ptr(b), len);
837 	}
838 	ret = 0;
839  out:
840 	sshbuf_free(b);
841 	return ret;
842 }
843 
844 int
845 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
846 {
847 	return to_blob(key, blobp, lenp, 0);
848 }
849 
850 int
851 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
852 {
853 	return to_blob(key, blobp, lenp, 1);
854 }
855 
856 int
857 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
858     u_char **retp, size_t *lenp)
859 {
860 	u_char *blob = NULL, *ret = NULL;
861 	size_t blob_len = 0;
862 	int r = SSH_ERR_INTERNAL_ERROR;
863 
864 	if (retp != NULL)
865 		*retp = NULL;
866 	if (lenp != NULL)
867 		*lenp = 0;
868 	if (ssh_digest_bytes(dgst_alg) == 0) {
869 		r = SSH_ERR_INVALID_ARGUMENT;
870 		goto out;
871 	}
872 	if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
873 		goto out;
874 	if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
875 		r = SSH_ERR_ALLOC_FAIL;
876 		goto out;
877 	}
878 	if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
879 	    ret, SSH_DIGEST_MAX_LENGTH)) != 0)
880 		goto out;
881 	/* success */
882 	if (retp != NULL) {
883 		*retp = ret;
884 		ret = NULL;
885 	}
886 	if (lenp != NULL)
887 		*lenp = ssh_digest_bytes(dgst_alg);
888 	r = 0;
889  out:
890 	free(ret);
891 	if (blob != NULL) {
892 		explicit_bzero(blob, blob_len);
893 		free(blob);
894 	}
895 	return r;
896 }
897 
898 static char *
899 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
900 {
901 	char *ret;
902 	size_t plen = strlen(alg) + 1;
903 	size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
904 	int r;
905 
906 	if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
907 		return NULL;
908 	strlcpy(ret, alg, rlen);
909 	strlcat(ret, ":", rlen);
910 	if (dgst_raw_len == 0)
911 		return ret;
912 	if ((r = b64_ntop(dgst_raw, dgst_raw_len,
913 	    ret + plen, rlen - plen)) == -1) {
914 		explicit_bzero(ret, rlen);
915 		free(ret);
916 		return NULL;
917 	}
918 	/* Trim padding characters from end */
919 	ret[strcspn(ret, "=")] = '\0';
920 	return ret;
921 }
922 
923 static char *
924 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
925 {
926 	char *retval, hex[5];
927 	size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
928 
929 	if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
930 		return NULL;
931 	strlcpy(retval, alg, rlen);
932 	strlcat(retval, ":", rlen);
933 	for (i = 0; i < dgst_raw_len; i++) {
934 		snprintf(hex, sizeof(hex), "%s%02x",
935 		    i > 0 ? ":" : "", dgst_raw[i]);
936 		strlcat(retval, hex, rlen);
937 	}
938 	return retval;
939 }
940 
941 static char *
942 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
943 {
944 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
945 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
946 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
947 	u_int i, j = 0, rounds, seed = 1;
948 	char *retval;
949 
950 	rounds = (dgst_raw_len / 2) + 1;
951 	if ((retval = calloc(rounds, 6)) == NULL)
952 		return NULL;
953 	retval[j++] = 'x';
954 	for (i = 0; i < rounds; i++) {
955 		u_int idx0, idx1, idx2, idx3, idx4;
956 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
957 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
958 			    seed) % 6;
959 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
960 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
961 			    (seed / 6)) % 6;
962 			retval[j++] = vowels[idx0];
963 			retval[j++] = consonants[idx1];
964 			retval[j++] = vowels[idx2];
965 			if ((i + 1) < rounds) {
966 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
967 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
968 				retval[j++] = consonants[idx3];
969 				retval[j++] = '-';
970 				retval[j++] = consonants[idx4];
971 				seed = ((seed * 5) +
972 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
973 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
974 			}
975 		} else {
976 			idx0 = seed % 6;
977 			idx1 = 16;
978 			idx2 = seed / 6;
979 			retval[j++] = vowels[idx0];
980 			retval[j++] = consonants[idx1];
981 			retval[j++] = vowels[idx2];
982 		}
983 	}
984 	retval[j++] = 'x';
985 	retval[j++] = '\0';
986 	return retval;
987 }
988 
989 /*
990  * Draw an ASCII-Art representing the fingerprint so human brain can
991  * profit from its built-in pattern recognition ability.
992  * This technique is called "random art" and can be found in some
993  * scientific publications like this original paper:
994  *
995  * "Hash Visualization: a New Technique to improve Real-World Security",
996  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
997  * Techniques and E-Commerce (CrypTEC '99)
998  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
999  *
1000  * The subject came up in a talk by Dan Kaminsky, too.
1001  *
1002  * If you see the picture is different, the key is different.
1003  * If the picture looks the same, you still know nothing.
1004  *
1005  * The algorithm used here is a worm crawling over a discrete plane,
1006  * leaving a trace (augmenting the field) everywhere it goes.
1007  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
1008  * makes the respective movement vector be ignored for this turn.
1009  * Graphs are not unambiguous, because circles in graphs can be
1010  * walked in either direction.
1011  */
1012 
1013 /*
1014  * Field sizes for the random art.  Have to be odd, so the starting point
1015  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1016  * Else pictures would be too dense, and drawing the frame would
1017  * fail, too, because the key type would not fit in anymore.
1018  */
1019 #define	FLDBASE		8
1020 #define	FLDSIZE_Y	(FLDBASE + 1)
1021 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
1022 static char *
1023 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1024     const struct sshkey *k)
1025 {
1026 	/*
1027 	 * Chars to be used after each other every time the worm
1028 	 * intersects with itself.  Matter of taste.
1029 	 */
1030 	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
1031 	char	*retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1032 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
1033 	size_t	 i, tlen, hlen;
1034 	u_int	 b;
1035 	int	 x, y, r;
1036 	size_t	 len = strlen(augmentation_string) - 1;
1037 
1038 	if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1039 		return NULL;
1040 
1041 	/* initialize field */
1042 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1043 	x = FLDSIZE_X / 2;
1044 	y = FLDSIZE_Y / 2;
1045 
1046 	/* process raw key */
1047 	for (i = 0; i < dgst_raw_len; i++) {
1048 		int input;
1049 		/* each byte conveys four 2-bit move commands */
1050 		input = dgst_raw[i];
1051 		for (b = 0; b < 4; b++) {
1052 			/* evaluate 2 bit, rest is shifted later */
1053 			x += (input & 0x1) ? 1 : -1;
1054 			y += (input & 0x2) ? 1 : -1;
1055 
1056 			/* assure we are still in bounds */
1057 			x = MAXIMUM(x, 0);
1058 			y = MAXIMUM(y, 0);
1059 			x = MINIMUM(x, FLDSIZE_X - 1);
1060 			y = MINIMUM(y, FLDSIZE_Y - 1);
1061 
1062 			/* augment the field */
1063 			if (field[x][y] < len - 2)
1064 				field[x][y]++;
1065 			input = input >> 2;
1066 		}
1067 	}
1068 
1069 	/* mark starting point and end point*/
1070 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1071 	field[x][y] = len;
1072 
1073 	/* assemble title */
1074 	r = snprintf(title, sizeof(title), "[%s %u]",
1075 		sshkey_type(k), sshkey_size(k));
1076 	/* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1077 	if (r < 0 || r > (int)sizeof(title))
1078 		r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1079 	tlen = (r <= 0) ? 0 : strlen(title);
1080 
1081 	/* assemble hash ID. */
1082 	r = snprintf(hash, sizeof(hash), "[%s]", alg);
1083 	hlen = (r <= 0) ? 0 : strlen(hash);
1084 
1085 	/* output upper border */
1086 	p = retval;
1087 	*p++ = '+';
1088 	for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1089 		*p++ = '-';
1090 	memcpy(p, title, tlen);
1091 	p += tlen;
1092 	for (i += tlen; i < FLDSIZE_X; i++)
1093 		*p++ = '-';
1094 	*p++ = '+';
1095 	*p++ = '\n';
1096 
1097 	/* output content */
1098 	for (y = 0; y < FLDSIZE_Y; y++) {
1099 		*p++ = '|';
1100 		for (x = 0; x < FLDSIZE_X; x++)
1101 			*p++ = augmentation_string[MINIMUM(field[x][y], len)];
1102 		*p++ = '|';
1103 		*p++ = '\n';
1104 	}
1105 
1106 	/* output lower border */
1107 	*p++ = '+';
1108 	for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1109 		*p++ = '-';
1110 	memcpy(p, hash, hlen);
1111 	p += hlen;
1112 	for (i += hlen; i < FLDSIZE_X; i++)
1113 		*p++ = '-';
1114 	*p++ = '+';
1115 
1116 	return retval;
1117 }
1118 
1119 char *
1120 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1121     enum sshkey_fp_rep dgst_rep)
1122 {
1123 	char *retval = NULL;
1124 	u_char *dgst_raw;
1125 	size_t dgst_raw_len;
1126 
1127 	if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1128 		return NULL;
1129 	switch (dgst_rep) {
1130 	case SSH_FP_DEFAULT:
1131 		if (dgst_alg == SSH_DIGEST_MD5) {
1132 			retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1133 			    dgst_raw, dgst_raw_len);
1134 		} else {
1135 			retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1136 			    dgst_raw, dgst_raw_len);
1137 		}
1138 		break;
1139 	case SSH_FP_HEX:
1140 		retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1141 		    dgst_raw, dgst_raw_len);
1142 		break;
1143 	case SSH_FP_BASE64:
1144 		retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1145 		    dgst_raw, dgst_raw_len);
1146 		break;
1147 	case SSH_FP_BUBBLEBABBLE:
1148 		retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1149 		break;
1150 	case SSH_FP_RANDOMART:
1151 		retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1152 		    dgst_raw, dgst_raw_len, k);
1153 		break;
1154 	default:
1155 		explicit_bzero(dgst_raw, dgst_raw_len);
1156 		free(dgst_raw);
1157 		return NULL;
1158 	}
1159 	explicit_bzero(dgst_raw, dgst_raw_len);
1160 	free(dgst_raw);
1161 	return retval;
1162 }
1163 
1164 
1165 /* returns 0 ok, and < 0 error */
1166 int
1167 sshkey_read(struct sshkey *ret, char **cpp)
1168 {
1169 	struct sshkey *k;
1170 	int retval = SSH_ERR_INVALID_FORMAT;
1171 	char *ep, *cp, *space;
1172 	int r, type, curve_nid = -1;
1173 	struct sshbuf *blob;
1174 
1175 	if (ret == NULL)
1176 		return SSH_ERR_INVALID_ARGUMENT;
1177 
1178 	cp = *cpp;
1179 
1180 	switch (ret->type) {
1181 	case KEY_UNSPEC:
1182 	case KEY_RSA:
1183 	case KEY_DSA:
1184 	case KEY_ECDSA:
1185 	case KEY_ED25519:
1186 	case KEY_DSA_CERT:
1187 	case KEY_ECDSA_CERT:
1188 	case KEY_RSA_CERT:
1189 	case KEY_ED25519_CERT:
1190 		space = strchr(cp, ' ');
1191 		if (space == NULL)
1192 			return SSH_ERR_INVALID_FORMAT;
1193 		*space = '\0';
1194 		type = sshkey_type_from_name(cp);
1195 		if (sshkey_type_plain(type) == KEY_ECDSA &&
1196 		    (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1197 			return SSH_ERR_EC_CURVE_INVALID;
1198 		*space = ' ';
1199 		if (type == KEY_UNSPEC)
1200 			return SSH_ERR_INVALID_FORMAT;
1201 		cp = space+1;
1202 		if (*cp == '\0')
1203 			return SSH_ERR_INVALID_FORMAT;
1204 		if (ret->type != KEY_UNSPEC && ret->type != type)
1205 			return SSH_ERR_KEY_TYPE_MISMATCH;
1206 		if ((blob = sshbuf_new()) == NULL)
1207 			return SSH_ERR_ALLOC_FAIL;
1208 		/* trim comment */
1209 		space = strchr(cp, ' ');
1210 		if (space) {
1211 			/* advance 'space': skip whitespace */
1212 			*space++ = '\0';
1213 			while (*space == ' ' || *space == '\t')
1214 				space++;
1215 			ep = space;
1216 		} else
1217 			ep = cp + strlen(cp);
1218 		if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1219 			sshbuf_free(blob);
1220 			return r;
1221 		}
1222 		if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1223 		    sshbuf_len(blob), &k)) != 0) {
1224 			sshbuf_free(blob);
1225 			return r;
1226 		}
1227 		sshbuf_free(blob);
1228 		if (k->type != type) {
1229 			sshkey_free(k);
1230 			return SSH_ERR_KEY_TYPE_MISMATCH;
1231 		}
1232 		if (sshkey_type_plain(type) == KEY_ECDSA &&
1233 		    curve_nid != k->ecdsa_nid) {
1234 			sshkey_free(k);
1235 			return SSH_ERR_EC_CURVE_MISMATCH;
1236 		}
1237 		ret->type = type;
1238 		if (sshkey_is_cert(ret)) {
1239 			if (!sshkey_is_cert(k)) {
1240 				sshkey_free(k);
1241 				return SSH_ERR_EXPECTED_CERT;
1242 			}
1243 			if (ret->cert != NULL)
1244 				cert_free(ret->cert);
1245 			ret->cert = k->cert;
1246 			k->cert = NULL;
1247 		}
1248 		switch (sshkey_type_plain(ret->type)) {
1249 #ifdef WITH_OPENSSL
1250 		case KEY_RSA:
1251 			if (ret->rsa != NULL)
1252 				RSA_free(ret->rsa);
1253 			ret->rsa = k->rsa;
1254 			k->rsa = NULL;
1255 #ifdef DEBUG_PK
1256 			RSA_print_fp(stderr, ret->rsa, 8);
1257 #endif
1258 			break;
1259 		case KEY_DSA:
1260 			if (ret->dsa != NULL)
1261 				DSA_free(ret->dsa);
1262 			ret->dsa = k->dsa;
1263 			k->dsa = NULL;
1264 #ifdef DEBUG_PK
1265 			DSA_print_fp(stderr, ret->dsa, 8);
1266 #endif
1267 			break;
1268 # ifdef OPENSSL_HAS_ECC
1269 		case KEY_ECDSA:
1270 			if (ret->ecdsa != NULL)
1271 				EC_KEY_free(ret->ecdsa);
1272 			ret->ecdsa = k->ecdsa;
1273 			ret->ecdsa_nid = k->ecdsa_nid;
1274 			k->ecdsa = NULL;
1275 			k->ecdsa_nid = -1;
1276 #ifdef DEBUG_PK
1277 			sshkey_dump_ec_key(ret->ecdsa);
1278 #endif
1279 			break;
1280 # endif /* OPENSSL_HAS_ECC */
1281 #endif /* WITH_OPENSSL */
1282 		case KEY_ED25519:
1283 			free(ret->ed25519_pk);
1284 			ret->ed25519_pk = k->ed25519_pk;
1285 			k->ed25519_pk = NULL;
1286 #ifdef DEBUG_PK
1287 			/* XXX */
1288 #endif
1289 			break;
1290 		}
1291 		*cpp = ep;
1292 		retval = 0;
1293 /*XXXX*/
1294 		sshkey_free(k);
1295 		if (retval != 0)
1296 			break;
1297 		break;
1298 	default:
1299 		return SSH_ERR_INVALID_ARGUMENT;
1300 	}
1301 	return retval;
1302 }
1303 
1304 int
1305 sshkey_to_base64(const struct sshkey *key, char **b64p)
1306 {
1307 	int r = SSH_ERR_INTERNAL_ERROR;
1308 	struct sshbuf *b = NULL;
1309 	char *uu = NULL;
1310 
1311 	if (b64p != NULL)
1312 		*b64p = NULL;
1313 	if ((b = sshbuf_new()) == NULL)
1314 		return SSH_ERR_ALLOC_FAIL;
1315 	if ((r = sshkey_putb(key, b)) != 0)
1316 		goto out;
1317 	if ((uu = sshbuf_dtob64(b)) == NULL) {
1318 		r = SSH_ERR_ALLOC_FAIL;
1319 		goto out;
1320 	}
1321 	/* Success */
1322 	if (b64p != NULL) {
1323 		*b64p = uu;
1324 		uu = NULL;
1325 	}
1326 	r = 0;
1327  out:
1328 	sshbuf_free(b);
1329 	free(uu);
1330 	return r;
1331 }
1332 
1333 int
1334 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1335 {
1336 	int r = SSH_ERR_INTERNAL_ERROR;
1337 	char *uu = NULL;
1338 
1339 	if ((r = sshkey_to_base64(key, &uu)) != 0)
1340 		goto out;
1341 	if ((r = sshbuf_putf(b, "%s %s",
1342 	    sshkey_ssh_name(key), uu)) != 0)
1343 		goto out;
1344 	r = 0;
1345  out:
1346 	free(uu);
1347 	return r;
1348 }
1349 
1350 int
1351 sshkey_write(const struct sshkey *key, FILE *f)
1352 {
1353 	struct sshbuf *b = NULL;
1354 	int r = SSH_ERR_INTERNAL_ERROR;
1355 
1356 	if ((b = sshbuf_new()) == NULL)
1357 		return SSH_ERR_ALLOC_FAIL;
1358 	if ((r = sshkey_format_text(key, b)) != 0)
1359 		goto out;
1360 	if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1361 		if (feof(f))
1362 			errno = EPIPE;
1363 		r = SSH_ERR_SYSTEM_ERROR;
1364 		goto out;
1365 	}
1366 	/* Success */
1367 	r = 0;
1368  out:
1369 	sshbuf_free(b);
1370 	return r;
1371 }
1372 
1373 const char *
1374 sshkey_cert_type(const struct sshkey *k)
1375 {
1376 	switch (k->cert->type) {
1377 	case SSH2_CERT_TYPE_USER:
1378 		return "user";
1379 	case SSH2_CERT_TYPE_HOST:
1380 		return "host";
1381 	default:
1382 		return "unknown";
1383 	}
1384 }
1385 
1386 #ifdef WITH_OPENSSL
1387 static int
1388 rsa_generate_private_key(u_int bits, RSA **rsap)
1389 {
1390 	RSA *private = NULL;
1391 	BIGNUM *f4 = NULL;
1392 	int ret = SSH_ERR_INTERNAL_ERROR;
1393 
1394 	if (rsap == NULL)
1395 		return SSH_ERR_INVALID_ARGUMENT;
1396 	if (bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1397 	    bits > SSHBUF_MAX_BIGNUM * 8)
1398 		return SSH_ERR_KEY_LENGTH;
1399 	*rsap = NULL;
1400 	if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1401 		ret = SSH_ERR_ALLOC_FAIL;
1402 		goto out;
1403 	}
1404 	if (!BN_set_word(f4, RSA_F4) ||
1405 	    !RSA_generate_key_ex(private, bits, f4, NULL)) {
1406 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1407 		goto out;
1408 	}
1409 	*rsap = private;
1410 	private = NULL;
1411 	ret = 0;
1412  out:
1413 	if (private != NULL)
1414 		RSA_free(private);
1415 	if (f4 != NULL)
1416 		BN_free(f4);
1417 	return ret;
1418 }
1419 
1420 static int
1421 dsa_generate_private_key(u_int bits, DSA **dsap)
1422 {
1423 	DSA *private;
1424 	int ret = SSH_ERR_INTERNAL_ERROR;
1425 
1426 	if (dsap == NULL)
1427 		return SSH_ERR_INVALID_ARGUMENT;
1428 	if (bits != 1024)
1429 		return SSH_ERR_KEY_LENGTH;
1430 	if ((private = DSA_new()) == NULL) {
1431 		ret = SSH_ERR_ALLOC_FAIL;
1432 		goto out;
1433 	}
1434 	*dsap = NULL;
1435 	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1436 	    NULL, NULL) || !DSA_generate_key(private)) {
1437 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1438 		goto out;
1439 	}
1440 	*dsap = private;
1441 	private = NULL;
1442 	ret = 0;
1443  out:
1444 	if (private != NULL)
1445 		DSA_free(private);
1446 	return ret;
1447 }
1448 
1449 # ifdef OPENSSL_HAS_ECC
1450 int
1451 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1452 {
1453 	EC_GROUP *eg;
1454 	int nids[] = {
1455 		NID_X9_62_prime256v1,
1456 		NID_secp384r1,
1457 #  ifdef OPENSSL_HAS_NISTP521
1458 		NID_secp521r1,
1459 #  endif /* OPENSSL_HAS_NISTP521 */
1460 		-1
1461 	};
1462 	int nid;
1463 	u_int i;
1464 	BN_CTX *bnctx;
1465 	const EC_GROUP *g = EC_KEY_get0_group(k);
1466 
1467 	/*
1468 	 * The group may be stored in a ASN.1 encoded private key in one of two
1469 	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1470 	 * or explicit group parameters encoded into the key blob. Only the
1471 	 * "named group" case sets the group NID for us, but we can figure
1472 	 * it out for the other case by comparing against all the groups that
1473 	 * are supported.
1474 	 */
1475 	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1476 		return nid;
1477 	if ((bnctx = BN_CTX_new()) == NULL)
1478 		return -1;
1479 	for (i = 0; nids[i] != -1; i++) {
1480 		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1481 			BN_CTX_free(bnctx);
1482 			return -1;
1483 		}
1484 		if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1485 			break;
1486 		EC_GROUP_free(eg);
1487 	}
1488 	BN_CTX_free(bnctx);
1489 	if (nids[i] != -1) {
1490 		/* Use the group with the NID attached */
1491 		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1492 		if (EC_KEY_set_group(k, eg) != 1) {
1493 			EC_GROUP_free(eg);
1494 			return -1;
1495 		}
1496 	}
1497 	return nids[i];
1498 }
1499 
1500 static int
1501 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1502 {
1503 	EC_KEY *private;
1504 	int ret = SSH_ERR_INTERNAL_ERROR;
1505 
1506 	if (nid == NULL || ecdsap == NULL)
1507 		return SSH_ERR_INVALID_ARGUMENT;
1508 	if ((*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1509 		return SSH_ERR_KEY_LENGTH;
1510 	*ecdsap = NULL;
1511 	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1512 		ret = SSH_ERR_ALLOC_FAIL;
1513 		goto out;
1514 	}
1515 	if (EC_KEY_generate_key(private) != 1) {
1516 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1517 		goto out;
1518 	}
1519 	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1520 	*ecdsap = private;
1521 	private = NULL;
1522 	ret = 0;
1523  out:
1524 	if (private != NULL)
1525 		EC_KEY_free(private);
1526 	return ret;
1527 }
1528 # endif /* OPENSSL_HAS_ECC */
1529 #endif /* WITH_OPENSSL */
1530 
1531 int
1532 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1533 {
1534 	struct sshkey *k;
1535 	int ret = SSH_ERR_INTERNAL_ERROR;
1536 
1537 	if (keyp == NULL)
1538 		return SSH_ERR_INVALID_ARGUMENT;
1539 	*keyp = NULL;
1540 	if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1541 		return SSH_ERR_ALLOC_FAIL;
1542 	switch (type) {
1543 	case KEY_ED25519:
1544 		if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1545 		    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1546 			ret = SSH_ERR_ALLOC_FAIL;
1547 			break;
1548 		}
1549 		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1550 		ret = 0;
1551 		break;
1552 #ifdef WITH_OPENSSL
1553 	case KEY_DSA:
1554 		ret = dsa_generate_private_key(bits, &k->dsa);
1555 		break;
1556 # ifdef OPENSSL_HAS_ECC
1557 	case KEY_ECDSA:
1558 		ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1559 		    &k->ecdsa);
1560 		break;
1561 # endif /* OPENSSL_HAS_ECC */
1562 	case KEY_RSA:
1563 		ret = rsa_generate_private_key(bits, &k->rsa);
1564 		break;
1565 #endif /* WITH_OPENSSL */
1566 	default:
1567 		ret = SSH_ERR_INVALID_ARGUMENT;
1568 	}
1569 	if (ret == 0) {
1570 		k->type = type;
1571 		*keyp = k;
1572 	} else
1573 		sshkey_free(k);
1574 	return ret;
1575 }
1576 
1577 int
1578 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1579 {
1580 	u_int i;
1581 	const struct sshkey_cert *from;
1582 	struct sshkey_cert *to;
1583 	int ret = SSH_ERR_INTERNAL_ERROR;
1584 
1585 	if (to_key->cert != NULL) {
1586 		cert_free(to_key->cert);
1587 		to_key->cert = NULL;
1588 	}
1589 
1590 	if ((from = from_key->cert) == NULL)
1591 		return SSH_ERR_INVALID_ARGUMENT;
1592 
1593 	if ((to = to_key->cert = cert_new()) == NULL)
1594 		return SSH_ERR_ALLOC_FAIL;
1595 
1596 	if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1597 	    (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1598 	    (ret = sshbuf_putb(to->extensions, from->extensions)) != 0)
1599 		return ret;
1600 
1601 	to->serial = from->serial;
1602 	to->type = from->type;
1603 	if (from->key_id == NULL)
1604 		to->key_id = NULL;
1605 	else if ((to->key_id = strdup(from->key_id)) == NULL)
1606 		return SSH_ERR_ALLOC_FAIL;
1607 	to->valid_after = from->valid_after;
1608 	to->valid_before = from->valid_before;
1609 	if (from->signature_key == NULL)
1610 		to->signature_key = NULL;
1611 	else if ((ret = sshkey_from_private(from->signature_key,
1612 	    &to->signature_key)) != 0)
1613 		return ret;
1614 
1615 	if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1616 		return SSH_ERR_INVALID_ARGUMENT;
1617 	if (from->nprincipals > 0) {
1618 		if ((to->principals = calloc(from->nprincipals,
1619 		    sizeof(*to->principals))) == NULL)
1620 			return SSH_ERR_ALLOC_FAIL;
1621 		for (i = 0; i < from->nprincipals; i++) {
1622 			to->principals[i] = strdup(from->principals[i]);
1623 			if (to->principals[i] == NULL) {
1624 				to->nprincipals = i;
1625 				return SSH_ERR_ALLOC_FAIL;
1626 			}
1627 		}
1628 	}
1629 	to->nprincipals = from->nprincipals;
1630 	return 0;
1631 }
1632 
1633 int
1634 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1635 {
1636 	struct sshkey *n = NULL;
1637 	int ret = SSH_ERR_INTERNAL_ERROR;
1638 
1639 	*pkp = NULL;
1640 	switch (k->type) {
1641 #ifdef WITH_OPENSSL
1642 	case KEY_DSA:
1643 	case KEY_DSA_CERT:
1644 		if ((n = sshkey_new(k->type)) == NULL)
1645 			return SSH_ERR_ALLOC_FAIL;
1646 		if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1647 		    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1648 		    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1649 		    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1650 			sshkey_free(n);
1651 			return SSH_ERR_ALLOC_FAIL;
1652 		}
1653 		break;
1654 # ifdef OPENSSL_HAS_ECC
1655 	case KEY_ECDSA:
1656 	case KEY_ECDSA_CERT:
1657 		if ((n = sshkey_new(k->type)) == NULL)
1658 			return SSH_ERR_ALLOC_FAIL;
1659 		n->ecdsa_nid = k->ecdsa_nid;
1660 		n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1661 		if (n->ecdsa == NULL) {
1662 			sshkey_free(n);
1663 			return SSH_ERR_ALLOC_FAIL;
1664 		}
1665 		if (EC_KEY_set_public_key(n->ecdsa,
1666 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1667 			sshkey_free(n);
1668 			return SSH_ERR_LIBCRYPTO_ERROR;
1669 		}
1670 		break;
1671 # endif /* OPENSSL_HAS_ECC */
1672 	case KEY_RSA:
1673 	case KEY_RSA_CERT:
1674 		if ((n = sshkey_new(k->type)) == NULL)
1675 			return SSH_ERR_ALLOC_FAIL;
1676 		if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1677 		    (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1678 			sshkey_free(n);
1679 			return SSH_ERR_ALLOC_FAIL;
1680 		}
1681 		break;
1682 #endif /* WITH_OPENSSL */
1683 	case KEY_ED25519:
1684 	case KEY_ED25519_CERT:
1685 		if ((n = sshkey_new(k->type)) == NULL)
1686 			return SSH_ERR_ALLOC_FAIL;
1687 		if (k->ed25519_pk != NULL) {
1688 			if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1689 				sshkey_free(n);
1690 				return SSH_ERR_ALLOC_FAIL;
1691 			}
1692 			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1693 		}
1694 		break;
1695 	default:
1696 		return SSH_ERR_KEY_TYPE_UNKNOWN;
1697 	}
1698 	if (sshkey_is_cert(k)) {
1699 		if ((ret = sshkey_cert_copy(k, n)) != 0) {
1700 			sshkey_free(n);
1701 			return ret;
1702 		}
1703 	}
1704 	*pkp = n;
1705 	return 0;
1706 }
1707 
1708 static int
1709 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1710 {
1711 	struct sshbuf *principals = NULL, *crit = NULL;
1712 	struct sshbuf *exts = NULL, *ca = NULL;
1713 	u_char *sig = NULL;
1714 	size_t signed_len = 0, slen = 0, kidlen = 0;
1715 	int ret = SSH_ERR_INTERNAL_ERROR;
1716 
1717 	/* Copy the entire key blob for verification and later serialisation */
1718 	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1719 		return ret;
1720 
1721 	/* Parse body of certificate up to signature */
1722 	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1723 	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1724 	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1725 	    (ret = sshbuf_froms(b, &principals)) != 0 ||
1726 	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1727 	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1728 	    (ret = sshbuf_froms(b, &crit)) != 0 ||
1729 	    (ret = sshbuf_froms(b, &exts)) != 0 ||
1730 	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1731 	    (ret = sshbuf_froms(b, &ca)) != 0) {
1732 		/* XXX debug print error for ret */
1733 		ret = SSH_ERR_INVALID_FORMAT;
1734 		goto out;
1735 	}
1736 
1737 	/* Signature is left in the buffer so we can calculate this length */
1738 	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1739 
1740 	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1741 		ret = SSH_ERR_INVALID_FORMAT;
1742 		goto out;
1743 	}
1744 
1745 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
1746 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
1747 		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1748 		goto out;
1749 	}
1750 
1751 	/* Parse principals section */
1752 	while (sshbuf_len(principals) > 0) {
1753 		char *principal = NULL;
1754 		char **oprincipals = NULL;
1755 
1756 		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1757 			ret = SSH_ERR_INVALID_FORMAT;
1758 			goto out;
1759 		}
1760 		if ((ret = sshbuf_get_cstring(principals, &principal,
1761 		    NULL)) != 0) {
1762 			ret = SSH_ERR_INVALID_FORMAT;
1763 			goto out;
1764 		}
1765 		oprincipals = key->cert->principals;
1766 		key->cert->principals = recallocarray(key->cert->principals,
1767 		    key->cert->nprincipals, key->cert->nprincipals + 1,
1768 		    sizeof(*key->cert->principals));
1769 		if (key->cert->principals == NULL) {
1770 			free(principal);
1771 			key->cert->principals = oprincipals;
1772 			ret = SSH_ERR_ALLOC_FAIL;
1773 			goto out;
1774 		}
1775 		key->cert->principals[key->cert->nprincipals++] = principal;
1776 	}
1777 
1778 	/*
1779 	 * Stash a copies of the critical options and extensions sections
1780 	 * for later use.
1781 	 */
1782 	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1783 	    (exts != NULL &&
1784 	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1785 		goto out;
1786 
1787 	/*
1788 	 * Validate critical options and extensions sections format.
1789 	 */
1790 	while (sshbuf_len(crit) != 0) {
1791 		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1792 		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1793 			sshbuf_reset(key->cert->critical);
1794 			ret = SSH_ERR_INVALID_FORMAT;
1795 			goto out;
1796 		}
1797 	}
1798 	while (exts != NULL && sshbuf_len(exts) != 0) {
1799 		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1800 		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1801 			sshbuf_reset(key->cert->extensions);
1802 			ret = SSH_ERR_INVALID_FORMAT;
1803 			goto out;
1804 		}
1805 	}
1806 
1807 	/* Parse CA key and check signature */
1808 	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1809 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1810 		goto out;
1811 	}
1812 	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1813 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1814 		goto out;
1815 	}
1816 	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1817 	    sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1818 		goto out;
1819 
1820 	/* Success */
1821 	ret = 0;
1822  out:
1823 	sshbuf_free(ca);
1824 	sshbuf_free(crit);
1825 	sshbuf_free(exts);
1826 	sshbuf_free(principals);
1827 	free(sig);
1828 	return ret;
1829 }
1830 
1831 static int
1832 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1833     int allow_cert)
1834 {
1835 	int type, ret = SSH_ERR_INTERNAL_ERROR;
1836 	char *ktype = NULL, *curve = NULL;
1837 	struct sshkey *key = NULL;
1838 	size_t len;
1839 	u_char *pk = NULL;
1840 	struct sshbuf *copy;
1841 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
1842 	EC_POINT *q = NULL;
1843 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
1844 
1845 #ifdef DEBUG_PK /* XXX */
1846 	sshbuf_dump(b, stderr);
1847 #endif
1848 	if (keyp != NULL)
1849 		*keyp = NULL;
1850 	if ((copy = sshbuf_fromb(b)) == NULL) {
1851 		ret = SSH_ERR_ALLOC_FAIL;
1852 		goto out;
1853 	}
1854 	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1855 		ret = SSH_ERR_INVALID_FORMAT;
1856 		goto out;
1857 	}
1858 
1859 	type = sshkey_type_from_name(ktype);
1860 	if (!allow_cert && sshkey_type_is_cert(type)) {
1861 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1862 		goto out;
1863 	}
1864 	switch (type) {
1865 #ifdef WITH_OPENSSL
1866 	case KEY_RSA_CERT:
1867 		/* Skip nonce */
1868 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1869 			ret = SSH_ERR_INVALID_FORMAT;
1870 			goto out;
1871 		}
1872 		/* FALLTHROUGH */
1873 	case KEY_RSA:
1874 		if ((key = sshkey_new(type)) == NULL) {
1875 			ret = SSH_ERR_ALLOC_FAIL;
1876 			goto out;
1877 		}
1878 		if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
1879 		    sshbuf_get_bignum2(b, key->rsa->n) != 0) {
1880 			ret = SSH_ERR_INVALID_FORMAT;
1881 			goto out;
1882 		}
1883 		if (BN_num_bits(key->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
1884 			ret = SSH_ERR_KEY_LENGTH;
1885 			goto out;
1886 		}
1887 #ifdef DEBUG_PK
1888 		RSA_print_fp(stderr, key->rsa, 8);
1889 #endif
1890 		break;
1891 	case KEY_DSA_CERT:
1892 		/* Skip nonce */
1893 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1894 			ret = SSH_ERR_INVALID_FORMAT;
1895 			goto out;
1896 		}
1897 		/* FALLTHROUGH */
1898 	case KEY_DSA:
1899 		if ((key = sshkey_new(type)) == NULL) {
1900 			ret = SSH_ERR_ALLOC_FAIL;
1901 			goto out;
1902 		}
1903 		if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
1904 		    sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
1905 		    sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
1906 		    sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
1907 			ret = SSH_ERR_INVALID_FORMAT;
1908 			goto out;
1909 		}
1910 #ifdef DEBUG_PK
1911 		DSA_print_fp(stderr, key->dsa, 8);
1912 #endif
1913 		break;
1914 	case KEY_ECDSA_CERT:
1915 		/* Skip nonce */
1916 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1917 			ret = SSH_ERR_INVALID_FORMAT;
1918 			goto out;
1919 		}
1920 		/* FALLTHROUGH */
1921 # ifdef OPENSSL_HAS_ECC
1922 	case KEY_ECDSA:
1923 		if ((key = sshkey_new(type)) == NULL) {
1924 			ret = SSH_ERR_ALLOC_FAIL;
1925 			goto out;
1926 		}
1927 		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
1928 		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
1929 			ret = SSH_ERR_INVALID_FORMAT;
1930 			goto out;
1931 		}
1932 		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
1933 			ret = SSH_ERR_EC_CURVE_MISMATCH;
1934 			goto out;
1935 		}
1936 		if (key->ecdsa != NULL)
1937 			EC_KEY_free(key->ecdsa);
1938 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
1939 		    == NULL) {
1940 			ret = SSH_ERR_EC_CURVE_INVALID;
1941 			goto out;
1942 		}
1943 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
1944 			ret = SSH_ERR_ALLOC_FAIL;
1945 			goto out;
1946 		}
1947 		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
1948 			ret = SSH_ERR_INVALID_FORMAT;
1949 			goto out;
1950 		}
1951 		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
1952 		    q) != 0) {
1953 			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
1954 			goto out;
1955 		}
1956 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
1957 			/* XXX assume it is a allocation error */
1958 			ret = SSH_ERR_ALLOC_FAIL;
1959 			goto out;
1960 		}
1961 #ifdef DEBUG_PK
1962 		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
1963 #endif
1964 		break;
1965 # endif /* OPENSSL_HAS_ECC */
1966 #endif /* WITH_OPENSSL */
1967 	case KEY_ED25519_CERT:
1968 		/* Skip nonce */
1969 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1970 			ret = SSH_ERR_INVALID_FORMAT;
1971 			goto out;
1972 		}
1973 		/* FALLTHROUGH */
1974 	case KEY_ED25519:
1975 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
1976 			goto out;
1977 		if (len != ED25519_PK_SZ) {
1978 			ret = SSH_ERR_INVALID_FORMAT;
1979 			goto out;
1980 		}
1981 		if ((key = sshkey_new(type)) == NULL) {
1982 			ret = SSH_ERR_ALLOC_FAIL;
1983 			goto out;
1984 		}
1985 		key->ed25519_pk = pk;
1986 		pk = NULL;
1987 		break;
1988 	case KEY_UNSPEC:
1989 	default:
1990 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
1991 		goto out;
1992 	}
1993 
1994 	/* Parse certificate potion */
1995 	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
1996 		goto out;
1997 
1998 	if (key != NULL && sshbuf_len(b) != 0) {
1999 		ret = SSH_ERR_INVALID_FORMAT;
2000 		goto out;
2001 	}
2002 	ret = 0;
2003 	if (keyp != NULL) {
2004 		*keyp = key;
2005 		key = NULL;
2006 	}
2007  out:
2008 	sshbuf_free(copy);
2009 	sshkey_free(key);
2010 	free(ktype);
2011 	free(curve);
2012 	free(pk);
2013 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2014 	if (q != NULL)
2015 		EC_POINT_free(q);
2016 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2017 	return ret;
2018 }
2019 
2020 int
2021 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2022 {
2023 	struct sshbuf *b;
2024 	int r;
2025 
2026 	if ((b = sshbuf_from(blob, blen)) == NULL)
2027 		return SSH_ERR_ALLOC_FAIL;
2028 	r = sshkey_from_blob_internal(b, keyp, 1);
2029 	sshbuf_free(b);
2030 	return r;
2031 }
2032 
2033 int
2034 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2035 {
2036 	return sshkey_from_blob_internal(b, keyp, 1);
2037 }
2038 
2039 int
2040 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2041 {
2042 	struct sshbuf *b;
2043 	int r;
2044 
2045 	if ((r = sshbuf_froms(buf, &b)) != 0)
2046 		return r;
2047 	r = sshkey_from_blob_internal(b, keyp, 1);
2048 	sshbuf_free(b);
2049 	return r;
2050 }
2051 
2052 int
2053 sshkey_sign(const struct sshkey *key,
2054     u_char **sigp, size_t *lenp,
2055     const u_char *data, size_t datalen, const char *alg, u_int compat)
2056 {
2057 	if (sigp != NULL)
2058 		*sigp = NULL;
2059 	if (lenp != NULL)
2060 		*lenp = 0;
2061 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2062 		return SSH_ERR_INVALID_ARGUMENT;
2063 	switch (key->type) {
2064 #ifdef WITH_OPENSSL
2065 	case KEY_DSA_CERT:
2066 	case KEY_DSA:
2067 		return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2068 # ifdef OPENSSL_HAS_ECC
2069 	case KEY_ECDSA_CERT:
2070 	case KEY_ECDSA:
2071 		return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2072 # endif /* OPENSSL_HAS_ECC */
2073 	case KEY_RSA_CERT:
2074 	case KEY_RSA:
2075 		return ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2076 #endif /* WITH_OPENSSL */
2077 	case KEY_ED25519:
2078 	case KEY_ED25519_CERT:
2079 		return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2080 	default:
2081 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2082 	}
2083 }
2084 
2085 /*
2086  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2087  */
2088 int
2089 sshkey_verify(const struct sshkey *key,
2090     const u_char *sig, size_t siglen,
2091     const u_char *data, size_t dlen, u_int compat)
2092 {
2093 	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2094 		return SSH_ERR_INVALID_ARGUMENT;
2095 	switch (key->type) {
2096 #ifdef WITH_OPENSSL
2097 	case KEY_DSA_CERT:
2098 	case KEY_DSA:
2099 		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2100 # ifdef OPENSSL_HAS_ECC
2101 	case KEY_ECDSA_CERT:
2102 	case KEY_ECDSA:
2103 		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2104 # endif /* OPENSSL_HAS_ECC */
2105 	case KEY_RSA_CERT:
2106 	case KEY_RSA:
2107 		return ssh_rsa_verify(key, sig, siglen, data, dlen);
2108 #endif /* WITH_OPENSSL */
2109 	case KEY_ED25519:
2110 	case KEY_ED25519_CERT:
2111 		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2112 	default:
2113 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2114 	}
2115 }
2116 
2117 /* Converts a private to a public key */
2118 int
2119 sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2120 {
2121 	struct sshkey *pk;
2122 	int ret = SSH_ERR_INTERNAL_ERROR;
2123 
2124 	*dkp = NULL;
2125 	if ((pk = calloc(1, sizeof(*pk))) == NULL)
2126 		return SSH_ERR_ALLOC_FAIL;
2127 	pk->type = k->type;
2128 	pk->flags = k->flags;
2129 	pk->ecdsa_nid = k->ecdsa_nid;
2130 	pk->dsa = NULL;
2131 	pk->ecdsa = NULL;
2132 	pk->rsa = NULL;
2133 	pk->ed25519_pk = NULL;
2134 	pk->ed25519_sk = NULL;
2135 
2136 	switch (k->type) {
2137 #ifdef WITH_OPENSSL
2138 	case KEY_RSA_CERT:
2139 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2140 			goto fail;
2141 		/* FALLTHROUGH */
2142 	case KEY_RSA:
2143 		if ((pk->rsa = RSA_new()) == NULL ||
2144 		    (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2145 		    (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2146 			ret = SSH_ERR_ALLOC_FAIL;
2147 			goto fail;
2148 			}
2149 		break;
2150 	case KEY_DSA_CERT:
2151 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2152 			goto fail;
2153 		/* FALLTHROUGH */
2154 	case KEY_DSA:
2155 		if ((pk->dsa = DSA_new()) == NULL ||
2156 		    (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2157 		    (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2158 		    (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2159 		    (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2160 			ret = SSH_ERR_ALLOC_FAIL;
2161 			goto fail;
2162 		}
2163 		break;
2164 	case KEY_ECDSA_CERT:
2165 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2166 			goto fail;
2167 		/* FALLTHROUGH */
2168 # ifdef OPENSSL_HAS_ECC
2169 	case KEY_ECDSA:
2170 		pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2171 		if (pk->ecdsa == NULL) {
2172 			ret = SSH_ERR_ALLOC_FAIL;
2173 			goto fail;
2174 		}
2175 		if (EC_KEY_set_public_key(pk->ecdsa,
2176 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2177 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2178 			goto fail;
2179 		}
2180 		break;
2181 # endif /* OPENSSL_HAS_ECC */
2182 #endif /* WITH_OPENSSL */
2183 	case KEY_ED25519_CERT:
2184 		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2185 			goto fail;
2186 		/* FALLTHROUGH */
2187 	case KEY_ED25519:
2188 		if (k->ed25519_pk != NULL) {
2189 			if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2190 				ret = SSH_ERR_ALLOC_FAIL;
2191 				goto fail;
2192 			}
2193 			memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2194 		}
2195 		break;
2196 	default:
2197 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2198  fail:
2199 		sshkey_free(pk);
2200 		return ret;
2201 	}
2202 	*dkp = pk;
2203 	return 0;
2204 }
2205 
2206 /* Convert a plain key to their _CERT equivalent */
2207 int
2208 sshkey_to_certified(struct sshkey *k)
2209 {
2210 	int newtype;
2211 
2212 	switch (k->type) {
2213 #ifdef WITH_OPENSSL
2214 	case KEY_RSA:
2215 		newtype = KEY_RSA_CERT;
2216 		break;
2217 	case KEY_DSA:
2218 		newtype = KEY_DSA_CERT;
2219 		break;
2220 	case KEY_ECDSA:
2221 		newtype = KEY_ECDSA_CERT;
2222 		break;
2223 #endif /* WITH_OPENSSL */
2224 	case KEY_ED25519:
2225 		newtype = KEY_ED25519_CERT;
2226 		break;
2227 	default:
2228 		return SSH_ERR_INVALID_ARGUMENT;
2229 	}
2230 	if ((k->cert = cert_new()) == NULL)
2231 		return SSH_ERR_ALLOC_FAIL;
2232 	k->type = newtype;
2233 	return 0;
2234 }
2235 
2236 /* Convert a certificate to its raw key equivalent */
2237 int
2238 sshkey_drop_cert(struct sshkey *k)
2239 {
2240 	if (!sshkey_type_is_cert(k->type))
2241 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2242 	cert_free(k->cert);
2243 	k->cert = NULL;
2244 	k->type = sshkey_type_plain(k->type);
2245 	return 0;
2246 }
2247 
2248 /* Sign a certified key, (re-)generating the signed certblob. */
2249 int
2250 sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2251     sshkey_certify_signer *signer, void *signer_ctx)
2252 {
2253 	struct sshbuf *principals = NULL;
2254 	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2255 	size_t i, ca_len, sig_len;
2256 	int ret = SSH_ERR_INTERNAL_ERROR;
2257 	struct sshbuf *cert;
2258 
2259 	if (k == NULL || k->cert == NULL ||
2260 	    k->cert->certblob == NULL || ca == NULL)
2261 		return SSH_ERR_INVALID_ARGUMENT;
2262 	if (!sshkey_is_cert(k))
2263 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2264 	if (!sshkey_type_is_valid_ca(ca->type))
2265 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2266 
2267 	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2268 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2269 
2270 	cert = k->cert->certblob; /* for readability */
2271 	sshbuf_reset(cert);
2272 	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2273 		goto out;
2274 
2275 	/* -v01 certs put nonce first */
2276 	arc4random_buf(&nonce, sizeof(nonce));
2277 	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2278 		goto out;
2279 
2280 	/* XXX this substantially duplicates to_blob(); refactor */
2281 	switch (k->type) {
2282 #ifdef WITH_OPENSSL
2283 	case KEY_DSA_CERT:
2284 		if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2285 		    (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2286 		    (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2287 		    (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2288 			goto out;
2289 		break;
2290 # ifdef OPENSSL_HAS_ECC
2291 	case KEY_ECDSA_CERT:
2292 		if ((ret = sshbuf_put_cstring(cert,
2293 		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2294 		    (ret = sshbuf_put_ec(cert,
2295 		    EC_KEY_get0_public_key(k->ecdsa),
2296 		    EC_KEY_get0_group(k->ecdsa))) != 0)
2297 			goto out;
2298 		break;
2299 # endif /* OPENSSL_HAS_ECC */
2300 	case KEY_RSA_CERT:
2301 		if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2302 		    (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2303 			goto out;
2304 		break;
2305 #endif /* WITH_OPENSSL */
2306 	case KEY_ED25519_CERT:
2307 		if ((ret = sshbuf_put_string(cert,
2308 		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
2309 			goto out;
2310 		break;
2311 	default:
2312 		ret = SSH_ERR_INVALID_ARGUMENT;
2313 		goto out;
2314 	}
2315 
2316 	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2317 	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2318 	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2319 		goto out;
2320 
2321 	if ((principals = sshbuf_new()) == NULL) {
2322 		ret = SSH_ERR_ALLOC_FAIL;
2323 		goto out;
2324 	}
2325 	for (i = 0; i < k->cert->nprincipals; i++) {
2326 		if ((ret = sshbuf_put_cstring(principals,
2327 		    k->cert->principals[i])) != 0)
2328 			goto out;
2329 	}
2330 	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2331 	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2332 	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2333 	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2334 	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2335 	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2336 	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2337 		goto out;
2338 
2339 	/* Sign the whole mess */
2340 	if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2341 	    sshbuf_len(cert), alg, 0, signer_ctx)) != 0)
2342 		goto out;
2343 
2344 	/* Append signature and we are done */
2345 	if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2346 		goto out;
2347 	ret = 0;
2348  out:
2349 	if (ret != 0)
2350 		sshbuf_reset(cert);
2351 	free(sig_blob);
2352 	free(ca_blob);
2353 	sshbuf_free(principals);
2354 	return ret;
2355 }
2356 
2357 static int
2358 default_key_sign(const struct sshkey *key, u_char **sigp, size_t *lenp,
2359     const u_char *data, size_t datalen,
2360     const char *alg, u_int compat, void *ctx)
2361 {
2362 	if (ctx != NULL)
2363 		return SSH_ERR_INVALID_ARGUMENT;
2364 	return sshkey_sign(key, sigp, lenp, data, datalen, alg, compat);
2365 }
2366 
2367 int
2368 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg)
2369 {
2370 	return sshkey_certify_custom(k, ca, alg, default_key_sign, NULL);
2371 }
2372 
2373 int
2374 sshkey_cert_check_authority(const struct sshkey *k,
2375     int want_host, int require_principal,
2376     const char *name, const char **reason)
2377 {
2378 	u_int i, principal_matches;
2379 	time_t now = time(NULL);
2380 
2381 	if (reason != NULL)
2382 		*reason = NULL;
2383 
2384 	if (want_host) {
2385 		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2386 			*reason = "Certificate invalid: not a host certificate";
2387 			return SSH_ERR_KEY_CERT_INVALID;
2388 		}
2389 	} else {
2390 		if (k->cert->type != SSH2_CERT_TYPE_USER) {
2391 			*reason = "Certificate invalid: not a user certificate";
2392 			return SSH_ERR_KEY_CERT_INVALID;
2393 		}
2394 	}
2395 	if (now < 0) {
2396 		/* yikes - system clock before epoch! */
2397 		*reason = "Certificate invalid: not yet valid";
2398 		return SSH_ERR_KEY_CERT_INVALID;
2399 	}
2400 	if ((u_int64_t)now < k->cert->valid_after) {
2401 		*reason = "Certificate invalid: not yet valid";
2402 		return SSH_ERR_KEY_CERT_INVALID;
2403 	}
2404 	if ((u_int64_t)now >= k->cert->valid_before) {
2405 		*reason = "Certificate invalid: expired";
2406 		return SSH_ERR_KEY_CERT_INVALID;
2407 	}
2408 	if (k->cert->nprincipals == 0) {
2409 		if (require_principal) {
2410 			*reason = "Certificate lacks principal list";
2411 			return SSH_ERR_KEY_CERT_INVALID;
2412 		}
2413 	} else if (name != NULL) {
2414 		principal_matches = 0;
2415 		for (i = 0; i < k->cert->nprincipals; i++) {
2416 			if (strcmp(name, k->cert->principals[i]) == 0) {
2417 				principal_matches = 1;
2418 				break;
2419 			}
2420 		}
2421 		if (!principal_matches) {
2422 			*reason = "Certificate invalid: name is not a listed "
2423 			    "principal";
2424 			return SSH_ERR_KEY_CERT_INVALID;
2425 		}
2426 	}
2427 	return 0;
2428 }
2429 
2430 size_t
2431 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2432 {
2433 	char from[32], to[32], ret[64];
2434 	time_t tt;
2435 	struct tm *tm;
2436 
2437 	*from = *to = '\0';
2438 	if (cert->valid_after == 0 &&
2439 	    cert->valid_before == 0xffffffffffffffffULL)
2440 		return strlcpy(s, "forever", l);
2441 
2442 	if (cert->valid_after != 0) {
2443 		/* XXX revisit INT_MAX in 2038 :) */
2444 		tt = cert->valid_after > INT_MAX ?
2445 		    INT_MAX : cert->valid_after;
2446 		tm = localtime(&tt);
2447 		strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
2448 	}
2449 	if (cert->valid_before != 0xffffffffffffffffULL) {
2450 		/* XXX revisit INT_MAX in 2038 :) */
2451 		tt = cert->valid_before > INT_MAX ?
2452 		    INT_MAX : cert->valid_before;
2453 		tm = localtime(&tt);
2454 		strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
2455 	}
2456 
2457 	if (cert->valid_after == 0)
2458 		snprintf(ret, sizeof(ret), "before %s", to);
2459 	else if (cert->valid_before == 0xffffffffffffffffULL)
2460 		snprintf(ret, sizeof(ret), "after %s", from);
2461 	else
2462 		snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2463 
2464 	return strlcpy(s, ret, l);
2465 }
2466 
2467 int
2468 sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2469 {
2470 	int r = SSH_ERR_INTERNAL_ERROR;
2471 
2472 	if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2473 		goto out;
2474 	switch (key->type) {
2475 #ifdef WITH_OPENSSL
2476 	case KEY_RSA:
2477 		if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2478 		    (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2479 		    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2480 		    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2481 		    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2482 		    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2483 			goto out;
2484 		break;
2485 	case KEY_RSA_CERT:
2486 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2487 			r = SSH_ERR_INVALID_ARGUMENT;
2488 			goto out;
2489 		}
2490 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2491 		    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2492 		    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2493 		    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2494 		    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2495 			goto out;
2496 		break;
2497 	case KEY_DSA:
2498 		if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2499 		    (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2500 		    (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2501 		    (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2502 		    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2503 			goto out;
2504 		break;
2505 	case KEY_DSA_CERT:
2506 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2507 			r = SSH_ERR_INVALID_ARGUMENT;
2508 			goto out;
2509 		}
2510 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2511 		    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2512 			goto out;
2513 		break;
2514 # ifdef OPENSSL_HAS_ECC
2515 	case KEY_ECDSA:
2516 		if ((r = sshbuf_put_cstring(b,
2517 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2518 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2519 		    (r = sshbuf_put_bignum2(b,
2520 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
2521 			goto out;
2522 		break;
2523 	case KEY_ECDSA_CERT:
2524 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2525 			r = SSH_ERR_INVALID_ARGUMENT;
2526 			goto out;
2527 		}
2528 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2529 		    (r = sshbuf_put_bignum2(b,
2530 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
2531 			goto out;
2532 		break;
2533 # endif /* OPENSSL_HAS_ECC */
2534 #endif /* WITH_OPENSSL */
2535 	case KEY_ED25519:
2536 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
2537 		    ED25519_PK_SZ)) != 0 ||
2538 		    (r = sshbuf_put_string(b, key->ed25519_sk,
2539 		    ED25519_SK_SZ)) != 0)
2540 			goto out;
2541 		break;
2542 	case KEY_ED25519_CERT:
2543 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2544 			r = SSH_ERR_INVALID_ARGUMENT;
2545 			goto out;
2546 		}
2547 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2548 		    (r = sshbuf_put_string(b, key->ed25519_pk,
2549 		    ED25519_PK_SZ)) != 0 ||
2550 		    (r = sshbuf_put_string(b, key->ed25519_sk,
2551 		    ED25519_SK_SZ)) != 0)
2552 			goto out;
2553 		break;
2554 	default:
2555 		r = SSH_ERR_INVALID_ARGUMENT;
2556 		goto out;
2557 	}
2558 	/* success */
2559 	r = 0;
2560  out:
2561 	return r;
2562 }
2563 
2564 int
2565 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2566 {
2567 	char *tname = NULL, *curve = NULL;
2568 	struct sshkey *k = NULL;
2569 	size_t pklen = 0, sklen = 0;
2570 	int type, r = SSH_ERR_INTERNAL_ERROR;
2571 	u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2572 #ifdef WITH_OPENSSL
2573 	BIGNUM *exponent = NULL;
2574 #endif /* WITH_OPENSSL */
2575 
2576 	if (kp != NULL)
2577 		*kp = NULL;
2578 	if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2579 		goto out;
2580 	type = sshkey_type_from_name(tname);
2581 	switch (type) {
2582 #ifdef WITH_OPENSSL
2583 	case KEY_DSA:
2584 		if ((k = sshkey_new_private(type)) == NULL) {
2585 			r = SSH_ERR_ALLOC_FAIL;
2586 			goto out;
2587 		}
2588 		if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2589 		    (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2590 		    (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2591 		    (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2592 		    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2593 			goto out;
2594 		break;
2595 	case KEY_DSA_CERT:
2596 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2597 		    (r = sshkey_add_private(k)) != 0 ||
2598 		    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2599 			goto out;
2600 		break;
2601 # ifdef OPENSSL_HAS_ECC
2602 	case KEY_ECDSA:
2603 		if ((k = sshkey_new_private(type)) == NULL) {
2604 			r = SSH_ERR_ALLOC_FAIL;
2605 			goto out;
2606 		}
2607 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2608 			r = SSH_ERR_INVALID_ARGUMENT;
2609 			goto out;
2610 		}
2611 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2612 			goto out;
2613 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2614 			r = SSH_ERR_EC_CURVE_MISMATCH;
2615 			goto out;
2616 		}
2617 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2618 		if (k->ecdsa  == NULL || (exponent = BN_new()) == NULL) {
2619 			r = SSH_ERR_LIBCRYPTO_ERROR;
2620 			goto out;
2621 		}
2622 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2623 		    (r = sshbuf_get_bignum2(buf, exponent)))
2624 			goto out;
2625 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2626 			r = SSH_ERR_LIBCRYPTO_ERROR;
2627 			goto out;
2628 		}
2629 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2630 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2631 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2632 			goto out;
2633 		break;
2634 	case KEY_ECDSA_CERT:
2635 		if ((exponent = BN_new()) == NULL) {
2636 			r = SSH_ERR_LIBCRYPTO_ERROR;
2637 			goto out;
2638 		}
2639 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2640 		    (r = sshkey_add_private(k)) != 0 ||
2641 		    (r = sshbuf_get_bignum2(buf, exponent)) != 0)
2642 			goto out;
2643 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2644 			r = SSH_ERR_LIBCRYPTO_ERROR;
2645 			goto out;
2646 		}
2647 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2648 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2649 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2650 			goto out;
2651 		break;
2652 # endif /* OPENSSL_HAS_ECC */
2653 	case KEY_RSA:
2654 		if ((k = sshkey_new_private(type)) == NULL) {
2655 			r = SSH_ERR_ALLOC_FAIL;
2656 			goto out;
2657 		}
2658 		if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2659 		    (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2660 		    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2661 		    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2662 		    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2663 		    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2664 		    (r = ssh_rsa_generate_additional_parameters(k)) != 0)
2665 			goto out;
2666 		if (BN_num_bits(k->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
2667 			r = SSH_ERR_KEY_LENGTH;
2668 			goto out;
2669 		}
2670 		break;
2671 	case KEY_RSA_CERT:
2672 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2673 		    (r = sshkey_add_private(k)) != 0 ||
2674 		    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2675 		    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2676 		    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2677 		    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2678 		    (r = ssh_rsa_generate_additional_parameters(k)) != 0)
2679 			goto out;
2680 		if (BN_num_bits(k->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
2681 			r = SSH_ERR_KEY_LENGTH;
2682 			goto out;
2683 		}
2684 		break;
2685 #endif /* WITH_OPENSSL */
2686 	case KEY_ED25519:
2687 		if ((k = sshkey_new_private(type)) == NULL) {
2688 			r = SSH_ERR_ALLOC_FAIL;
2689 			goto out;
2690 		}
2691 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2692 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2693 			goto out;
2694 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2695 			r = SSH_ERR_INVALID_FORMAT;
2696 			goto out;
2697 		}
2698 		k->ed25519_pk = ed25519_pk;
2699 		k->ed25519_sk = ed25519_sk;
2700 		ed25519_pk = ed25519_sk = NULL;
2701 		break;
2702 	case KEY_ED25519_CERT:
2703 		if ((r = sshkey_froms(buf, &k)) != 0 ||
2704 		    (r = sshkey_add_private(k)) != 0 ||
2705 		    (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2706 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2707 			goto out;
2708 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2709 			r = SSH_ERR_INVALID_FORMAT;
2710 			goto out;
2711 		}
2712 		k->ed25519_pk = ed25519_pk;
2713 		k->ed25519_sk = ed25519_sk;
2714 		ed25519_pk = ed25519_sk = NULL;
2715 		break;
2716 	default:
2717 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2718 		goto out;
2719 	}
2720 #ifdef WITH_OPENSSL
2721 	/* enable blinding */
2722 	switch (k->type) {
2723 	case KEY_RSA:
2724 	case KEY_RSA_CERT:
2725 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
2726 			r = SSH_ERR_LIBCRYPTO_ERROR;
2727 			goto out;
2728 		}
2729 		break;
2730 	}
2731 #endif /* WITH_OPENSSL */
2732 	/* success */
2733 	r = 0;
2734 	if (kp != NULL) {
2735 		*kp = k;
2736 		k = NULL;
2737 	}
2738  out:
2739 	free(tname);
2740 	free(curve);
2741 #ifdef WITH_OPENSSL
2742 	if (exponent != NULL)
2743 		BN_clear_free(exponent);
2744 #endif /* WITH_OPENSSL */
2745 	sshkey_free(k);
2746 	if (ed25519_pk != NULL) {
2747 		explicit_bzero(ed25519_pk, pklen);
2748 		free(ed25519_pk);
2749 	}
2750 	if (ed25519_sk != NULL) {
2751 		explicit_bzero(ed25519_sk, sklen);
2752 		free(ed25519_sk);
2753 	}
2754 	return r;
2755 }
2756 
2757 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
2758 int
2759 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2760 {
2761 	BN_CTX *bnctx;
2762 	EC_POINT *nq = NULL;
2763 	BIGNUM *order, *x, *y, *tmp;
2764 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2765 
2766 	/*
2767 	 * NB. This assumes OpenSSL has already verified that the public
2768 	 * point lies on the curve. This is done by EC_POINT_oct2point()
2769 	 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
2770 	 * reachable with public points not unmarshalled using
2771 	 * EC_POINT_oct2point then the caller will need to explicitly check.
2772 	 */
2773 
2774 	if ((bnctx = BN_CTX_new()) == NULL)
2775 		return SSH_ERR_ALLOC_FAIL;
2776 	BN_CTX_start(bnctx);
2777 
2778 	/*
2779 	 * We shouldn't ever hit this case because bignum_get_ecpoint()
2780 	 * refuses to load GF2m points.
2781 	 */
2782 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2783 	    NID_X9_62_prime_field)
2784 		goto out;
2785 
2786 	/* Q != infinity */
2787 	if (EC_POINT_is_at_infinity(group, public))
2788 		goto out;
2789 
2790 	if ((x = BN_CTX_get(bnctx)) == NULL ||
2791 	    (y = BN_CTX_get(bnctx)) == NULL ||
2792 	    (order = BN_CTX_get(bnctx)) == NULL ||
2793 	    (tmp = BN_CTX_get(bnctx)) == NULL) {
2794 		ret = SSH_ERR_ALLOC_FAIL;
2795 		goto out;
2796 	}
2797 
2798 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2799 	if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2800 	    EC_POINT_get_affine_coordinates_GFp(group, public,
2801 	    x, y, bnctx) != 1) {
2802 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2803 		goto out;
2804 	}
2805 	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2806 	    BN_num_bits(y) <= BN_num_bits(order) / 2)
2807 		goto out;
2808 
2809 	/* nQ == infinity (n == order of subgroup) */
2810 	if ((nq = EC_POINT_new(group)) == NULL) {
2811 		ret = SSH_ERR_ALLOC_FAIL;
2812 		goto out;
2813 	}
2814 	if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2815 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2816 		goto out;
2817 	}
2818 	if (EC_POINT_is_at_infinity(group, nq) != 1)
2819 		goto out;
2820 
2821 	/* x < order - 1, y < order - 1 */
2822 	if (!BN_sub(tmp, order, BN_value_one())) {
2823 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2824 		goto out;
2825 	}
2826 	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2827 		goto out;
2828 	ret = 0;
2829  out:
2830 	BN_CTX_free(bnctx);
2831 	if (nq != NULL)
2832 		EC_POINT_free(nq);
2833 	return ret;
2834 }
2835 
2836 int
2837 sshkey_ec_validate_private(const EC_KEY *key)
2838 {
2839 	BN_CTX *bnctx;
2840 	BIGNUM *order, *tmp;
2841 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2842 
2843 	if ((bnctx = BN_CTX_new()) == NULL)
2844 		return SSH_ERR_ALLOC_FAIL;
2845 	BN_CTX_start(bnctx);
2846 
2847 	if ((order = BN_CTX_get(bnctx)) == NULL ||
2848 	    (tmp = BN_CTX_get(bnctx)) == NULL) {
2849 		ret = SSH_ERR_ALLOC_FAIL;
2850 		goto out;
2851 	}
2852 
2853 	/* log2(private) > log2(order)/2 */
2854 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2855 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2856 		goto out;
2857 	}
2858 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2859 	    BN_num_bits(order) / 2)
2860 		goto out;
2861 
2862 	/* private < order - 1 */
2863 	if (!BN_sub(tmp, order, BN_value_one())) {
2864 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2865 		goto out;
2866 	}
2867 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2868 		goto out;
2869 	ret = 0;
2870  out:
2871 	BN_CTX_free(bnctx);
2872 	return ret;
2873 }
2874 
2875 void
2876 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2877 {
2878 	BIGNUM *x, *y;
2879 	BN_CTX *bnctx;
2880 
2881 	if (point == NULL) {
2882 		fputs("point=(NULL)\n", stderr);
2883 		return;
2884 	}
2885 	if ((bnctx = BN_CTX_new()) == NULL) {
2886 		fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
2887 		return;
2888 	}
2889 	BN_CTX_start(bnctx);
2890 	if ((x = BN_CTX_get(bnctx)) == NULL ||
2891 	    (y = BN_CTX_get(bnctx)) == NULL) {
2892 		fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
2893 		return;
2894 	}
2895 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2896 	    NID_X9_62_prime_field) {
2897 		fprintf(stderr, "%s: group is not a prime field\n", __func__);
2898 		return;
2899 	}
2900 	if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
2901 	    bnctx) != 1) {
2902 		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
2903 		    __func__);
2904 		return;
2905 	}
2906 	fputs("x=", stderr);
2907 	BN_print_fp(stderr, x);
2908 	fputs("\ny=", stderr);
2909 	BN_print_fp(stderr, y);
2910 	fputs("\n", stderr);
2911 	BN_CTX_free(bnctx);
2912 }
2913 
2914 void
2915 sshkey_dump_ec_key(const EC_KEY *key)
2916 {
2917 	const BIGNUM *exponent;
2918 
2919 	sshkey_dump_ec_point(EC_KEY_get0_group(key),
2920 	    EC_KEY_get0_public_key(key));
2921 	fputs("exponent=", stderr);
2922 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2923 		fputs("(NULL)", stderr);
2924 	else
2925 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2926 	fputs("\n", stderr);
2927 }
2928 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
2929 
2930 static int
2931 sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
2932     const char *passphrase, const char *comment, const char *ciphername,
2933     int rounds)
2934 {
2935 	u_char *cp, *key = NULL, *pubkeyblob = NULL;
2936 	u_char salt[SALT_LEN];
2937 	char *b64 = NULL;
2938 	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
2939 	u_int check;
2940 	int r = SSH_ERR_INTERNAL_ERROR;
2941 	struct sshcipher_ctx *ciphercontext = NULL;
2942 	const struct sshcipher *cipher;
2943 	const char *kdfname = KDFNAME;
2944 	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
2945 
2946 	if (rounds <= 0)
2947 		rounds = DEFAULT_ROUNDS;
2948 	if (passphrase == NULL || !strlen(passphrase)) {
2949 		ciphername = "none";
2950 		kdfname = "none";
2951 	} else if (ciphername == NULL)
2952 		ciphername = DEFAULT_CIPHERNAME;
2953 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
2954 		r = SSH_ERR_INVALID_ARGUMENT;
2955 		goto out;
2956 	}
2957 
2958 	if ((kdf = sshbuf_new()) == NULL ||
2959 	    (encoded = sshbuf_new()) == NULL ||
2960 	    (encrypted = sshbuf_new()) == NULL) {
2961 		r = SSH_ERR_ALLOC_FAIL;
2962 		goto out;
2963 	}
2964 	blocksize = cipher_blocksize(cipher);
2965 	keylen = cipher_keylen(cipher);
2966 	ivlen = cipher_ivlen(cipher);
2967 	authlen = cipher_authlen(cipher);
2968 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
2969 		r = SSH_ERR_ALLOC_FAIL;
2970 		goto out;
2971 	}
2972 	if (strcmp(kdfname, "bcrypt") == 0) {
2973 		arc4random_buf(salt, SALT_LEN);
2974 		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
2975 		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
2976 			r = SSH_ERR_INVALID_ARGUMENT;
2977 			goto out;
2978 		}
2979 		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
2980 		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
2981 			goto out;
2982 	} else if (strcmp(kdfname, "none") != 0) {
2983 		/* Unsupported KDF type */
2984 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2985 		goto out;
2986 	}
2987 	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
2988 	    key + keylen, ivlen, 1)) != 0)
2989 		goto out;
2990 
2991 	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
2992 	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
2993 	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
2994 	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
2995 	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
2996 	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
2997 	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
2998 		goto out;
2999 
3000 	/* set up the buffer that will be encrypted */
3001 
3002 	/* Random check bytes */
3003 	check = arc4random();
3004 	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3005 	    (r = sshbuf_put_u32(encrypted, check)) != 0)
3006 		goto out;
3007 
3008 	/* append private key and comment*/
3009 	if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
3010 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3011 		goto out;
3012 
3013 	/* padding */
3014 	i = 0;
3015 	while (sshbuf_len(encrypted) % blocksize) {
3016 		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3017 			goto out;
3018 	}
3019 
3020 	/* length in destination buffer */
3021 	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
3022 		goto out;
3023 
3024 	/* encrypt */
3025 	if ((r = sshbuf_reserve(encoded,
3026 	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
3027 		goto out;
3028 	if ((r = cipher_crypt(ciphercontext, 0, cp,
3029 	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
3030 		goto out;
3031 
3032 	/* uuencode */
3033 	if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
3034 		r = SSH_ERR_ALLOC_FAIL;
3035 		goto out;
3036 	}
3037 
3038 	sshbuf_reset(blob);
3039 	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
3040 		goto out;
3041 	for (i = 0; i < strlen(b64); i++) {
3042 		if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
3043 			goto out;
3044 		/* insert line breaks */
3045 		if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3046 			goto out;
3047 	}
3048 	if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
3049 		goto out;
3050 	if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3051 		goto out;
3052 
3053 	/* success */
3054 	r = 0;
3055 
3056  out:
3057 	sshbuf_free(kdf);
3058 	sshbuf_free(encoded);
3059 	sshbuf_free(encrypted);
3060 	cipher_free(ciphercontext);
3061 	explicit_bzero(salt, sizeof(salt));
3062 	if (key != NULL) {
3063 		explicit_bzero(key, keylen + ivlen);
3064 		free(key);
3065 	}
3066 	if (pubkeyblob != NULL) {
3067 		explicit_bzero(pubkeyblob, pubkeylen);
3068 		free(pubkeyblob);
3069 	}
3070 	if (b64 != NULL) {
3071 		explicit_bzero(b64, strlen(b64));
3072 		free(b64);
3073 	}
3074 	return r;
3075 }
3076 
3077 static int
3078 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3079     struct sshkey **keyp, char **commentp)
3080 {
3081 	char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3082 	const struct sshcipher *cipher = NULL;
3083 	const u_char *cp;
3084 	int r = SSH_ERR_INTERNAL_ERROR;
3085 	size_t encoded_len;
3086 	size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3087 	struct sshbuf *encoded = NULL, *decoded = NULL;
3088 	struct sshbuf *kdf = NULL, *decrypted = NULL;
3089 	struct sshcipher_ctx *ciphercontext = NULL;
3090 	struct sshkey *k = NULL;
3091 	u_char *key = NULL, *salt = NULL, *dp, pad, last;
3092 	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3093 
3094 	if (keyp != NULL)
3095 		*keyp = NULL;
3096 	if (commentp != NULL)
3097 		*commentp = NULL;
3098 
3099 	if ((encoded = sshbuf_new()) == NULL ||
3100 	    (decoded = sshbuf_new()) == NULL ||
3101 	    (decrypted = sshbuf_new()) == NULL) {
3102 		r = SSH_ERR_ALLOC_FAIL;
3103 		goto out;
3104 	}
3105 
3106 	/* check preamble */
3107 	cp = sshbuf_ptr(blob);
3108 	encoded_len = sshbuf_len(blob);
3109 	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3110 	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3111 		r = SSH_ERR_INVALID_FORMAT;
3112 		goto out;
3113 	}
3114 	cp += MARK_BEGIN_LEN;
3115 	encoded_len -= MARK_BEGIN_LEN;
3116 
3117 	/* Look for end marker, removing whitespace as we go */
3118 	while (encoded_len > 0) {
3119 		if (*cp != '\n' && *cp != '\r') {
3120 			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3121 				goto out;
3122 		}
3123 		last = *cp;
3124 		encoded_len--;
3125 		cp++;
3126 		if (last == '\n') {
3127 			if (encoded_len >= MARK_END_LEN &&
3128 			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3129 				/* \0 terminate */
3130 				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3131 					goto out;
3132 				break;
3133 			}
3134 		}
3135 	}
3136 	if (encoded_len == 0) {
3137 		r = SSH_ERR_INVALID_FORMAT;
3138 		goto out;
3139 	}
3140 
3141 	/* decode base64 */
3142 	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3143 		goto out;
3144 
3145 	/* check magic */
3146 	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3147 	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3148 		r = SSH_ERR_INVALID_FORMAT;
3149 		goto out;
3150 	}
3151 	/* parse public portion of key */
3152 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3153 	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3154 	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3155 	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3156 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3157 	    (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3158 	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3159 		goto out;
3160 
3161 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3162 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3163 		goto out;
3164 	}
3165 	if ((passphrase == NULL || strlen(passphrase) == 0) &&
3166 	    strcmp(ciphername, "none") != 0) {
3167 		/* passphrase required */
3168 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3169 		goto out;
3170 	}
3171 	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3172 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3173 		goto out;
3174 	}
3175 	if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3176 		r = SSH_ERR_INVALID_FORMAT;
3177 		goto out;
3178 	}
3179 	if (nkeys != 1) {
3180 		/* XXX only one key supported */
3181 		r = SSH_ERR_INVALID_FORMAT;
3182 		goto out;
3183 	}
3184 
3185 	/* check size of encrypted key blob */
3186 	blocksize = cipher_blocksize(cipher);
3187 	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3188 		r = SSH_ERR_INVALID_FORMAT;
3189 		goto out;
3190 	}
3191 
3192 	/* setup key */
3193 	keylen = cipher_keylen(cipher);
3194 	ivlen = cipher_ivlen(cipher);
3195 	authlen = cipher_authlen(cipher);
3196 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3197 		r = SSH_ERR_ALLOC_FAIL;
3198 		goto out;
3199 	}
3200 	if (strcmp(kdfname, "bcrypt") == 0) {
3201 		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3202 		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3203 			goto out;
3204 		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3205 		    key, keylen + ivlen, rounds) < 0) {
3206 			r = SSH_ERR_INVALID_FORMAT;
3207 			goto out;
3208 		}
3209 	}
3210 
3211 	/* check that an appropriate amount of auth data is present */
3212 	if (sshbuf_len(decoded) < encrypted_len + authlen) {
3213 		r = SSH_ERR_INVALID_FORMAT;
3214 		goto out;
3215 	}
3216 
3217 	/* decrypt private portion of key */
3218 	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3219 	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
3220 	    key + keylen, ivlen, 0)) != 0)
3221 		goto out;
3222 	if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3223 	    encrypted_len, 0, authlen)) != 0) {
3224 		/* an integrity error here indicates an incorrect passphrase */
3225 		if (r == SSH_ERR_MAC_INVALID)
3226 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3227 		goto out;
3228 	}
3229 	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3230 		goto out;
3231 	/* there should be no trailing data */
3232 	if (sshbuf_len(decoded) != 0) {
3233 		r = SSH_ERR_INVALID_FORMAT;
3234 		goto out;
3235 	}
3236 
3237 	/* check check bytes */
3238 	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3239 	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3240 		goto out;
3241 	if (check1 != check2) {
3242 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3243 		goto out;
3244 	}
3245 
3246 	/* Load the private key and comment */
3247 	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3248 	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3249 		goto out;
3250 
3251 	/* Check deterministic padding */
3252 	i = 0;
3253 	while (sshbuf_len(decrypted)) {
3254 		if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3255 			goto out;
3256 		if (pad != (++i & 0xff)) {
3257 			r = SSH_ERR_INVALID_FORMAT;
3258 			goto out;
3259 		}
3260 	}
3261 
3262 	/* XXX decode pubkey and check against private */
3263 
3264 	/* success */
3265 	r = 0;
3266 	if (keyp != NULL) {
3267 		*keyp = k;
3268 		k = NULL;
3269 	}
3270 	if (commentp != NULL) {
3271 		*commentp = comment;
3272 		comment = NULL;
3273 	}
3274  out:
3275 	pad = 0;
3276 	cipher_free(ciphercontext);
3277 	free(ciphername);
3278 	free(kdfname);
3279 	free(comment);
3280 	if (salt != NULL) {
3281 		explicit_bzero(salt, slen);
3282 		free(salt);
3283 	}
3284 	if (key != NULL) {
3285 		explicit_bzero(key, keylen + ivlen);
3286 		free(key);
3287 	}
3288 	sshbuf_free(encoded);
3289 	sshbuf_free(decoded);
3290 	sshbuf_free(kdf);
3291 	sshbuf_free(decrypted);
3292 	sshkey_free(k);
3293 	return r;
3294 }
3295 
3296 
3297 #ifdef WITH_OPENSSL
3298 /* convert SSH v2 key in OpenSSL PEM format */
3299 static int
3300 sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3301     const char *_passphrase, const char *comment)
3302 {
3303 	int success, r;
3304 	int blen, len = strlen(_passphrase);
3305 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3306 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3307 	const u_char *bptr;
3308 	BIO *bio = NULL;
3309 
3310 	if (len > 0 && len <= 4)
3311 		return SSH_ERR_PASSPHRASE_TOO_SHORT;
3312 	if ((bio = BIO_new(BIO_s_mem())) == NULL)
3313 		return SSH_ERR_ALLOC_FAIL;
3314 
3315 	switch (key->type) {
3316 	case KEY_DSA:
3317 		success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3318 		    cipher, passphrase, len, NULL, NULL);
3319 		break;
3320 #ifdef OPENSSL_HAS_ECC
3321 	case KEY_ECDSA:
3322 		success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3323 		    cipher, passphrase, len, NULL, NULL);
3324 		break;
3325 #endif
3326 	case KEY_RSA:
3327 		success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3328 		    cipher, passphrase, len, NULL, NULL);
3329 		break;
3330 	default:
3331 		success = 0;
3332 		break;
3333 	}
3334 	if (success == 0) {
3335 		r = SSH_ERR_LIBCRYPTO_ERROR;
3336 		goto out;
3337 	}
3338 	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3339 		r = SSH_ERR_INTERNAL_ERROR;
3340 		goto out;
3341 	}
3342 	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3343 		goto out;
3344 	r = 0;
3345  out:
3346 	BIO_free(bio);
3347 	return r;
3348 }
3349 #endif /* WITH_OPENSSL */
3350 
3351 /* Serialise "key" to buffer "blob" */
3352 int
3353 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3354     const char *passphrase, const char *comment,
3355     int force_new_format, const char *new_format_cipher, int new_format_rounds)
3356 {
3357 	switch (key->type) {
3358 #ifdef WITH_OPENSSL
3359 	case KEY_DSA:
3360 	case KEY_ECDSA:
3361 	case KEY_RSA:
3362 		if (force_new_format) {
3363 			return sshkey_private_to_blob2(key, blob, passphrase,
3364 			    comment, new_format_cipher, new_format_rounds);
3365 		}
3366 		return sshkey_private_pem_to_blob(key, blob,
3367 		    passphrase, comment);
3368 #endif /* WITH_OPENSSL */
3369 	case KEY_ED25519:
3370 		return sshkey_private_to_blob2(key, blob, passphrase,
3371 		    comment, new_format_cipher, new_format_rounds);
3372 	default:
3373 		return SSH_ERR_KEY_TYPE_UNKNOWN;
3374 	}
3375 }
3376 
3377 
3378 #ifdef WITH_OPENSSL
3379 static int
3380 translate_libcrypto_error(unsigned long pem_err)
3381 {
3382 	int pem_reason = ERR_GET_REASON(pem_err);
3383 
3384 	switch (ERR_GET_LIB(pem_err)) {
3385 	case ERR_LIB_PEM:
3386 		switch (pem_reason) {
3387 		case PEM_R_BAD_PASSWORD_READ:
3388 		case PEM_R_PROBLEMS_GETTING_PASSWORD:
3389 		case PEM_R_BAD_DECRYPT:
3390 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
3391 		default:
3392 			return SSH_ERR_INVALID_FORMAT;
3393 		}
3394 	case ERR_LIB_EVP:
3395 		switch (pem_reason) {
3396 		case EVP_R_BAD_DECRYPT:
3397 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
3398 		case EVP_R_BN_DECODE_ERROR:
3399 		case EVP_R_DECODE_ERROR:
3400 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
3401 		case EVP_R_PRIVATE_KEY_DECODE_ERROR:
3402 #endif
3403 			return SSH_ERR_INVALID_FORMAT;
3404 		default:
3405 			return SSH_ERR_LIBCRYPTO_ERROR;
3406 		}
3407 	case ERR_LIB_ASN1:
3408 		return SSH_ERR_INVALID_FORMAT;
3409 	}
3410 	return SSH_ERR_LIBCRYPTO_ERROR;
3411 }
3412 
3413 static void
3414 clear_libcrypto_errors(void)
3415 {
3416 	while (ERR_get_error() != 0)
3417 		;
3418 }
3419 
3420 /*
3421  * Translate OpenSSL error codes to determine whether
3422  * passphrase is required/incorrect.
3423  */
3424 static int
3425 convert_libcrypto_error(void)
3426 {
3427 	/*
3428 	 * Some password errors are reported at the beginning
3429 	 * of the error queue.
3430 	 */
3431 	if (translate_libcrypto_error(ERR_peek_error()) ==
3432 	    SSH_ERR_KEY_WRONG_PASSPHRASE)
3433 		return SSH_ERR_KEY_WRONG_PASSPHRASE;
3434 	return translate_libcrypto_error(ERR_peek_last_error());
3435 }
3436 
3437 static int
3438 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3439     const char *passphrase, struct sshkey **keyp)
3440 {
3441 	EVP_PKEY *pk = NULL;
3442 	struct sshkey *prv = NULL;
3443 	BIO *bio = NULL;
3444 	int r;
3445 
3446 	if (keyp != NULL)
3447 		*keyp = NULL;
3448 
3449 	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3450 		return SSH_ERR_ALLOC_FAIL;
3451 	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3452 	    (int)sshbuf_len(blob)) {
3453 		r = SSH_ERR_ALLOC_FAIL;
3454 		goto out;
3455 	}
3456 
3457 	clear_libcrypto_errors();
3458 	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3459 	    (char *)passphrase)) == NULL) {
3460 		r = convert_libcrypto_error();
3461 		goto out;
3462 	}
3463 	if (pk->type == EVP_PKEY_RSA &&
3464 	    (type == KEY_UNSPEC || type == KEY_RSA)) {
3465 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3466 			r = SSH_ERR_ALLOC_FAIL;
3467 			goto out;
3468 		}
3469 		prv->rsa = EVP_PKEY_get1_RSA(pk);
3470 		prv->type = KEY_RSA;
3471 #ifdef DEBUG_PK
3472 		RSA_print_fp(stderr, prv->rsa, 8);
3473 #endif
3474 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3475 			r = SSH_ERR_LIBCRYPTO_ERROR;
3476 			goto out;
3477 		}
3478 		if (BN_num_bits(prv->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
3479 			r = SSH_ERR_KEY_LENGTH;
3480 			goto out;
3481 		}
3482 	} else if (pk->type == EVP_PKEY_DSA &&
3483 	    (type == KEY_UNSPEC || type == KEY_DSA)) {
3484 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3485 			r = SSH_ERR_ALLOC_FAIL;
3486 			goto out;
3487 		}
3488 		prv->dsa = EVP_PKEY_get1_DSA(pk);
3489 		prv->type = KEY_DSA;
3490 #ifdef DEBUG_PK
3491 		DSA_print_fp(stderr, prv->dsa, 8);
3492 #endif
3493 #ifdef OPENSSL_HAS_ECC
3494 	} else if (pk->type == EVP_PKEY_EC &&
3495 	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3496 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3497 			r = SSH_ERR_ALLOC_FAIL;
3498 			goto out;
3499 		}
3500 		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3501 		prv->type = KEY_ECDSA;
3502 		prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3503 		if (prv->ecdsa_nid == -1 ||
3504 		    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3505 		    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3506 		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3507 		    sshkey_ec_validate_private(prv->ecdsa) != 0) {
3508 			r = SSH_ERR_INVALID_FORMAT;
3509 			goto out;
3510 		}
3511 # ifdef DEBUG_PK
3512 		if (prv != NULL && prv->ecdsa != NULL)
3513 			sshkey_dump_ec_key(prv->ecdsa);
3514 # endif
3515 #endif /* OPENSSL_HAS_ECC */
3516 	} else {
3517 		r = SSH_ERR_INVALID_FORMAT;
3518 		goto out;
3519 	}
3520 	r = 0;
3521 	if (keyp != NULL) {
3522 		*keyp = prv;
3523 		prv = NULL;
3524 	}
3525  out:
3526 	BIO_free(bio);
3527 	if (pk != NULL)
3528 		EVP_PKEY_free(pk);
3529 	sshkey_free(prv);
3530 	return r;
3531 }
3532 #endif /* WITH_OPENSSL */
3533 
3534 int
3535 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3536     const char *passphrase, struct sshkey **keyp, char **commentp)
3537 {
3538 	int r = SSH_ERR_INTERNAL_ERROR;
3539 
3540 	if (keyp != NULL)
3541 		*keyp = NULL;
3542 	if (commentp != NULL)
3543 		*commentp = NULL;
3544 
3545 	switch (type) {
3546 #ifdef WITH_OPENSSL
3547 	case KEY_DSA:
3548 	case KEY_ECDSA:
3549 	case KEY_RSA:
3550 		return sshkey_parse_private_pem_fileblob(blob, type,
3551 		    passphrase, keyp);
3552 #endif /* WITH_OPENSSL */
3553 	case KEY_ED25519:
3554 		return sshkey_parse_private2(blob, type, passphrase,
3555 		    keyp, commentp);
3556 	case KEY_UNSPEC:
3557 		r = sshkey_parse_private2(blob, type, passphrase, keyp,
3558 		    commentp);
3559 		/* Do not fallback to PEM parser if only passphrase is wrong. */
3560 		if (r == 0 || r == SSH_ERR_KEY_WRONG_PASSPHRASE)
3561 			return r;
3562 #ifdef WITH_OPENSSL
3563 		return sshkey_parse_private_pem_fileblob(blob, type,
3564 		    passphrase, keyp);
3565 #else
3566 		return SSH_ERR_INVALID_FORMAT;
3567 #endif /* WITH_OPENSSL */
3568 	default:
3569 		return SSH_ERR_KEY_TYPE_UNKNOWN;
3570 	}
3571 }
3572 
3573 int
3574 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3575     struct sshkey **keyp, char **commentp)
3576 {
3577 	if (keyp != NULL)
3578 		*keyp = NULL;
3579 	if (commentp != NULL)
3580 		*commentp = NULL;
3581 
3582 	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3583 	    passphrase, keyp, commentp);
3584 }
3585