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