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