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