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