xref: /freebsd/crypto/openssh/sshkey.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /* $OpenBSD: sshkey.c,v 1.120 2022/01/06 22:05:42 djm Exp $ */
2 /*
3  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
5  * Copyright (c) 2010,2011 Damien Miller.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "includes.h"
29 
30 #include <sys/types.h>
31 #include <netinet/in.h>
32 
33 #ifdef WITH_OPENSSL
34 #include <openssl/evp.h>
35 #include <openssl/err.h>
36 #include <openssl/pem.h>
37 #endif
38 
39 #include "crypto_api.h"
40 
41 #include <errno.h>
42 #include <limits.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <resolv.h>
46 #include <time.h>
47 #ifdef HAVE_UTIL_H
48 #include <util.h>
49 #endif /* HAVE_UTIL_H */
50 
51 #include "ssh2.h"
52 #include "ssherr.h"
53 #include "misc.h"
54 #include "sshbuf.h"
55 #include "cipher.h"
56 #include "digest.h"
57 #define SSHKEY_INTERNAL
58 #include "sshkey.h"
59 #include "match.h"
60 #include "ssh-sk.h"
61 
62 #ifdef WITH_XMSS
63 #include "sshkey-xmss.h"
64 #include "xmss_fast.h"
65 #endif
66 
67 #include "openbsd-compat/openssl-compat.h"
68 
69 /* openssh private key file format */
70 #define MARK_BEGIN		"-----BEGIN OPENSSH PRIVATE KEY-----\n"
71 #define MARK_END		"-----END OPENSSH PRIVATE KEY-----\n"
72 #define MARK_BEGIN_LEN		(sizeof(MARK_BEGIN) - 1)
73 #define MARK_END_LEN		(sizeof(MARK_END) - 1)
74 #define KDFNAME			"bcrypt"
75 #define AUTH_MAGIC		"openssh-key-v1"
76 #define SALT_LEN		16
77 #define DEFAULT_CIPHERNAME	"aes256-ctr"
78 #define	DEFAULT_ROUNDS		16
79 
80 /* Version identification string for SSH v1 identity files. */
81 #define LEGACY_BEGIN		"SSH PRIVATE KEY FILE FORMAT 1.1\n"
82 
83 /*
84  * Constants relating to "shielding" support; protection of keys expected
85  * to remain in memory for long durations
86  */
87 #define SSHKEY_SHIELD_PREKEY_LEN	(16 * 1024)
88 #define SSHKEY_SHIELD_CIPHER		"aes256-ctr" /* XXX want AES-EME* */
89 #define SSHKEY_SHIELD_PREKEY_HASH	SSH_DIGEST_SHA512
90 
91 int	sshkey_private_serialize_opt(struct sshkey *key,
92     struct sshbuf *buf, enum sshkey_serialize_rep);
93 static int sshkey_from_blob_internal(struct sshbuf *buf,
94     struct sshkey **keyp, int allow_cert);
95 
96 /* Supported key types */
97 struct keytype {
98 	const char *name;
99 	const char *shortname;
100 	const char *sigalg;
101 	int type;
102 	int nid;
103 	int cert;
104 	int sigonly;
105 };
106 static const struct keytype keytypes[] = {
107 	{ "ssh-ed25519", "ED25519", NULL, KEY_ED25519, 0, 0, 0 },
108 	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT", NULL,
109 	    KEY_ED25519_CERT, 0, 1, 0 },
110 #ifdef ENABLE_SK
111 	{ "sk-ssh-ed25519@openssh.com", "ED25519-SK", NULL,
112 	    KEY_ED25519_SK, 0, 0, 0 },
113 	{ "sk-ssh-ed25519-cert-v01@openssh.com", "ED25519-SK-CERT", NULL,
114 	    KEY_ED25519_SK_CERT, 0, 1, 0 },
115 #endif
116 #ifdef WITH_XMSS
117 	{ "ssh-xmss@openssh.com", "XMSS", NULL, KEY_XMSS, 0, 0, 0 },
118 	{ "ssh-xmss-cert-v01@openssh.com", "XMSS-CERT", NULL,
119 	    KEY_XMSS_CERT, 0, 1, 0 },
120 #endif /* WITH_XMSS */
121 #ifdef WITH_OPENSSL
122 	{ "ssh-rsa", "RSA", NULL, KEY_RSA, 0, 0, 0 },
123 	{ "rsa-sha2-256", "RSA", NULL, KEY_RSA, 0, 0, 1 },
124 	{ "rsa-sha2-512", "RSA", NULL, KEY_RSA, 0, 0, 1 },
125 	{ "ssh-dss", "DSA", NULL, KEY_DSA, 0, 0, 0 },
126 # ifdef OPENSSL_HAS_ECC
127 	{ "ecdsa-sha2-nistp256", "ECDSA", NULL,
128 	    KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
129 	{ "ecdsa-sha2-nistp384", "ECDSA", NULL,
130 	    KEY_ECDSA, NID_secp384r1, 0, 0 },
131 #  ifdef OPENSSL_HAS_NISTP521
132 	{ "ecdsa-sha2-nistp521", "ECDSA", NULL,
133 	    KEY_ECDSA, NID_secp521r1, 0, 0 },
134 #  endif /* OPENSSL_HAS_NISTP521 */
135 #  ifdef ENABLE_SK
136 	{ "sk-ecdsa-sha2-nistp256@openssh.com", "ECDSA-SK", NULL,
137 	    KEY_ECDSA_SK, NID_X9_62_prime256v1, 0, 0 },
138 	{ "webauthn-sk-ecdsa-sha2-nistp256@openssh.com", "ECDSA-SK", NULL,
139 	    KEY_ECDSA_SK, NID_X9_62_prime256v1, 0, 1 },
140 #  endif /* ENABLE_SK */
141 # endif /* OPENSSL_HAS_ECC */
142 	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", NULL,
143 	    KEY_RSA_CERT, 0, 1, 0 },
144 	{ "rsa-sha2-256-cert-v01@openssh.com", "RSA-CERT",
145 	    "rsa-sha2-256", KEY_RSA_CERT, 0, 1, 1 },
146 	{ "rsa-sha2-512-cert-v01@openssh.com", "RSA-CERT",
147 	    "rsa-sha2-512", KEY_RSA_CERT, 0, 1, 1 },
148 	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", NULL,
149 	    KEY_DSA_CERT, 0, 1, 0 },
150 # ifdef OPENSSL_HAS_ECC
151 	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT", NULL,
152 	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
153 	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT", NULL,
154 	    KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
155 #  ifdef OPENSSL_HAS_NISTP521
156 	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT", NULL,
157 	    KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
158 #  endif /* OPENSSL_HAS_NISTP521 */
159 #  ifdef ENABLE_SK
160 	{ "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-SK-CERT", NULL,
161 	    KEY_ECDSA_SK_CERT, NID_X9_62_prime256v1, 1, 0 },
162 #  endif /* ENABLE_SK */
163 # endif /* OPENSSL_HAS_ECC */
164 #endif /* WITH_OPENSSL */
165 	{ NULL, NULL, NULL, -1, -1, 0, 0 }
166 };
167 
168 const char *
169 sshkey_type(const struct sshkey *k)
170 {
171 	const struct keytype *kt;
172 
173 	for (kt = keytypes; kt->type != -1; kt++) {
174 		if (kt->type == k->type)
175 			return kt->shortname;
176 	}
177 	return "unknown";
178 }
179 
180 static const char *
181 sshkey_ssh_name_from_type_nid(int type, int nid)
182 {
183 	const struct keytype *kt;
184 
185 	for (kt = keytypes; kt->type != -1; kt++) {
186 		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
187 			return kt->name;
188 	}
189 	return "ssh-unknown";
190 }
191 
192 int
193 sshkey_type_is_cert(int type)
194 {
195 	const struct keytype *kt;
196 
197 	for (kt = keytypes; kt->type != -1; kt++) {
198 		if (kt->type == type)
199 			return kt->cert;
200 	}
201 	return 0;
202 }
203 
204 const char *
205 sshkey_ssh_name(const struct sshkey *k)
206 {
207 	return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
208 }
209 
210 const char *
211 sshkey_ssh_name_plain(const struct sshkey *k)
212 {
213 	return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
214 	    k->ecdsa_nid);
215 }
216 
217 int
218 sshkey_type_from_name(const char *name)
219 {
220 	const struct keytype *kt;
221 
222 	for (kt = keytypes; kt->type != -1; kt++) {
223 		/* Only allow shortname matches for plain key types */
224 		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
225 		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
226 			return kt->type;
227 	}
228 	return KEY_UNSPEC;
229 }
230 
231 static int
232 key_type_is_ecdsa_variant(int type)
233 {
234 	switch (type) {
235 	case KEY_ECDSA:
236 	case KEY_ECDSA_CERT:
237 	case KEY_ECDSA_SK:
238 	case KEY_ECDSA_SK_CERT:
239 		return 1;
240 	}
241 	return 0;
242 }
243 
244 int
245 sshkey_ecdsa_nid_from_name(const char *name)
246 {
247 	const struct keytype *kt;
248 
249 	for (kt = keytypes; kt->type != -1; kt++) {
250 		if (!key_type_is_ecdsa_variant(kt->type))
251 			continue;
252 		if (kt->name != NULL && strcmp(name, kt->name) == 0)
253 			return kt->nid;
254 	}
255 	return -1;
256 }
257 
258 int
259 sshkey_match_keyname_to_sigalgs(const char *keyname, const char *sigalgs)
260 {
261 	int ktype;
262 
263 	if (sigalgs == NULL || *sigalgs == '\0' ||
264 	    (ktype = sshkey_type_from_name(keyname)) == KEY_UNSPEC)
265 		return 0;
266 	else if (ktype == KEY_RSA) {
267 		return match_pattern_list("ssh-rsa", sigalgs, 0) == 1 ||
268 		    match_pattern_list("rsa-sha2-256", sigalgs, 0) == 1 ||
269 		    match_pattern_list("rsa-sha2-512", sigalgs, 0) == 1;
270 	} else if (ktype == KEY_RSA_CERT) {
271 		return match_pattern_list("ssh-rsa-cert-v01@openssh.com",
272 		    sigalgs, 0) == 1 ||
273 		    match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
274 		    sigalgs, 0) == 1 ||
275 		    match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
276 		    sigalgs, 0) == 1;
277 	} else
278 		return match_pattern_list(keyname, sigalgs, 0) == 1;
279 }
280 
281 char *
282 sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
283 {
284 	char *tmp, *ret = NULL;
285 	size_t nlen, rlen = 0;
286 	const struct keytype *kt;
287 
288 	for (kt = keytypes; kt->type != -1; kt++) {
289 		if (kt->name == NULL)
290 			continue;
291 		if (!include_sigonly && kt->sigonly)
292 			continue;
293 		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
294 			continue;
295 		if (ret != NULL)
296 			ret[rlen++] = sep;
297 		nlen = strlen(kt->name);
298 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
299 			free(ret);
300 			return NULL;
301 		}
302 		ret = tmp;
303 		memcpy(ret + rlen, kt->name, nlen + 1);
304 		rlen += nlen;
305 	}
306 	return ret;
307 }
308 
309 int
310 sshkey_names_valid2(const char *names, int allow_wildcard)
311 {
312 	char *s, *cp, *p;
313 	const struct keytype *kt;
314 	int type;
315 
316 	if (names == NULL || strcmp(names, "") == 0)
317 		return 0;
318 	if ((s = cp = strdup(names)) == NULL)
319 		return 0;
320 	for ((p = strsep(&cp, ",")); p && *p != '\0';
321 	    (p = strsep(&cp, ","))) {
322 		type = sshkey_type_from_name(p);
323 		if (type == KEY_UNSPEC) {
324 			if (allow_wildcard) {
325 				/*
326 				 * Try matching key types against the string.
327 				 * If any has a positive or negative match then
328 				 * the component is accepted.
329 				 */
330 				for (kt = keytypes; kt->type != -1; kt++) {
331 					if (match_pattern_list(kt->name,
332 					    p, 0) != 0)
333 						break;
334 				}
335 				if (kt->type != -1)
336 					continue;
337 			}
338 			free(s);
339 			return 0;
340 		}
341 	}
342 	free(s);
343 	return 1;
344 }
345 
346 u_int
347 sshkey_size(const struct sshkey *k)
348 {
349 #ifdef WITH_OPENSSL
350 	const BIGNUM *rsa_n, *dsa_p;
351 #endif /* WITH_OPENSSL */
352 
353 	switch (k->type) {
354 #ifdef WITH_OPENSSL
355 	case KEY_RSA:
356 	case KEY_RSA_CERT:
357 		if (k->rsa == NULL)
358 			return 0;
359 		RSA_get0_key(k->rsa, &rsa_n, NULL, NULL);
360 		return BN_num_bits(rsa_n);
361 	case KEY_DSA:
362 	case KEY_DSA_CERT:
363 		if (k->dsa == NULL)
364 			return 0;
365 		DSA_get0_pqg(k->dsa, &dsa_p, NULL, NULL);
366 		return BN_num_bits(dsa_p);
367 	case KEY_ECDSA:
368 	case KEY_ECDSA_CERT:
369 	case KEY_ECDSA_SK:
370 	case KEY_ECDSA_SK_CERT:
371 		return sshkey_curve_nid_to_bits(k->ecdsa_nid);
372 #endif /* WITH_OPENSSL */
373 	case KEY_ED25519:
374 	case KEY_ED25519_CERT:
375 	case KEY_ED25519_SK:
376 	case KEY_ED25519_SK_CERT:
377 	case KEY_XMSS:
378 	case KEY_XMSS_CERT:
379 		return 256;	/* XXX */
380 	}
381 	return 0;
382 }
383 
384 static int
385 sshkey_type_is_valid_ca(int type)
386 {
387 	switch (type) {
388 	case KEY_RSA:
389 	case KEY_DSA:
390 	case KEY_ECDSA:
391 	case KEY_ECDSA_SK:
392 	case KEY_ED25519:
393 	case KEY_ED25519_SK:
394 	case KEY_XMSS:
395 		return 1;
396 	default:
397 		return 0;
398 	}
399 }
400 
401 int
402 sshkey_is_cert(const struct sshkey *k)
403 {
404 	if (k == NULL)
405 		return 0;
406 	return sshkey_type_is_cert(k->type);
407 }
408 
409 int
410 sshkey_is_sk(const struct sshkey *k)
411 {
412 	if (k == NULL)
413 		return 0;
414 	switch (sshkey_type_plain(k->type)) {
415 	case KEY_ECDSA_SK:
416 	case KEY_ED25519_SK:
417 		return 1;
418 	default:
419 		return 0;
420 	}
421 }
422 
423 /* Return the cert-less equivalent to a certified key type */
424 int
425 sshkey_type_plain(int type)
426 {
427 	switch (type) {
428 	case KEY_RSA_CERT:
429 		return KEY_RSA;
430 	case KEY_DSA_CERT:
431 		return KEY_DSA;
432 	case KEY_ECDSA_CERT:
433 		return KEY_ECDSA;
434 	case KEY_ECDSA_SK_CERT:
435 		return KEY_ECDSA_SK;
436 	case KEY_ED25519_CERT:
437 		return KEY_ED25519;
438 	case KEY_ED25519_SK_CERT:
439 		return KEY_ED25519_SK;
440 	case KEY_XMSS_CERT:
441 		return KEY_XMSS;
442 	default:
443 		return type;
444 	}
445 }
446 
447 #ifdef WITH_OPENSSL
448 /* XXX: these are really begging for a table-driven approach */
449 int
450 sshkey_curve_name_to_nid(const char *name)
451 {
452 	if (strcmp(name, "nistp256") == 0)
453 		return NID_X9_62_prime256v1;
454 	else if (strcmp(name, "nistp384") == 0)
455 		return NID_secp384r1;
456 # ifdef OPENSSL_HAS_NISTP521
457 	else if (strcmp(name, "nistp521") == 0)
458 		return NID_secp521r1;
459 # endif /* OPENSSL_HAS_NISTP521 */
460 	else
461 		return -1;
462 }
463 
464 u_int
465 sshkey_curve_nid_to_bits(int nid)
466 {
467 	switch (nid) {
468 	case NID_X9_62_prime256v1:
469 		return 256;
470 	case NID_secp384r1:
471 		return 384;
472 # ifdef OPENSSL_HAS_NISTP521
473 	case NID_secp521r1:
474 		return 521;
475 # endif /* OPENSSL_HAS_NISTP521 */
476 	default:
477 		return 0;
478 	}
479 }
480 
481 int
482 sshkey_ecdsa_bits_to_nid(int bits)
483 {
484 	switch (bits) {
485 	case 256:
486 		return NID_X9_62_prime256v1;
487 	case 384:
488 		return NID_secp384r1;
489 # ifdef OPENSSL_HAS_NISTP521
490 	case 521:
491 		return NID_secp521r1;
492 # endif /* OPENSSL_HAS_NISTP521 */
493 	default:
494 		return -1;
495 	}
496 }
497 
498 const char *
499 sshkey_curve_nid_to_name(int nid)
500 {
501 	switch (nid) {
502 	case NID_X9_62_prime256v1:
503 		return "nistp256";
504 	case NID_secp384r1:
505 		return "nistp384";
506 # ifdef OPENSSL_HAS_NISTP521
507 	case NID_secp521r1:
508 		return "nistp521";
509 # endif /* OPENSSL_HAS_NISTP521 */
510 	default:
511 		return NULL;
512 	}
513 }
514 
515 int
516 sshkey_ec_nid_to_hash_alg(int nid)
517 {
518 	int kbits = sshkey_curve_nid_to_bits(nid);
519 
520 	if (kbits <= 0)
521 		return -1;
522 
523 	/* RFC5656 section 6.2.1 */
524 	if (kbits <= 256)
525 		return SSH_DIGEST_SHA256;
526 	else if (kbits <= 384)
527 		return SSH_DIGEST_SHA384;
528 	else
529 		return SSH_DIGEST_SHA512;
530 }
531 #endif /* WITH_OPENSSL */
532 
533 static void
534 cert_free(struct sshkey_cert *cert)
535 {
536 	u_int i;
537 
538 	if (cert == NULL)
539 		return;
540 	sshbuf_free(cert->certblob);
541 	sshbuf_free(cert->critical);
542 	sshbuf_free(cert->extensions);
543 	free(cert->key_id);
544 	for (i = 0; i < cert->nprincipals; i++)
545 		free(cert->principals[i]);
546 	free(cert->principals);
547 	sshkey_free(cert->signature_key);
548 	free(cert->signature_type);
549 	freezero(cert, sizeof(*cert));
550 }
551 
552 static struct sshkey_cert *
553 cert_new(void)
554 {
555 	struct sshkey_cert *cert;
556 
557 	if ((cert = calloc(1, sizeof(*cert))) == NULL)
558 		return NULL;
559 	if ((cert->certblob = sshbuf_new()) == NULL ||
560 	    (cert->critical = sshbuf_new()) == NULL ||
561 	    (cert->extensions = sshbuf_new()) == NULL) {
562 		cert_free(cert);
563 		return NULL;
564 	}
565 	cert->key_id = NULL;
566 	cert->principals = NULL;
567 	cert->signature_key = NULL;
568 	cert->signature_type = NULL;
569 	return cert;
570 }
571 
572 struct sshkey *
573 sshkey_new(int type)
574 {
575 	struct sshkey *k;
576 #ifdef WITH_OPENSSL
577 	RSA *rsa;
578 	DSA *dsa;
579 #endif /* WITH_OPENSSL */
580 
581 	if ((k = calloc(1, sizeof(*k))) == NULL)
582 		return NULL;
583 	k->type = type;
584 	k->ecdsa = NULL;
585 	k->ecdsa_nid = -1;
586 	k->dsa = NULL;
587 	k->rsa = NULL;
588 	k->cert = NULL;
589 	k->ed25519_sk = NULL;
590 	k->ed25519_pk = NULL;
591 	k->xmss_sk = NULL;
592 	k->xmss_pk = NULL;
593 	switch (k->type) {
594 #ifdef WITH_OPENSSL
595 	case KEY_RSA:
596 	case KEY_RSA_CERT:
597 		if ((rsa = RSA_new()) == NULL) {
598 			free(k);
599 			return NULL;
600 		}
601 		k->rsa = rsa;
602 		break;
603 	case KEY_DSA:
604 	case KEY_DSA_CERT:
605 		if ((dsa = DSA_new()) == NULL) {
606 			free(k);
607 			return NULL;
608 		}
609 		k->dsa = dsa;
610 		break;
611 	case KEY_ECDSA:
612 	case KEY_ECDSA_CERT:
613 	case KEY_ECDSA_SK:
614 	case KEY_ECDSA_SK_CERT:
615 		/* Cannot do anything until we know the group */
616 		break;
617 #endif /* WITH_OPENSSL */
618 	case KEY_ED25519:
619 	case KEY_ED25519_CERT:
620 	case KEY_ED25519_SK:
621 	case KEY_ED25519_SK_CERT:
622 	case KEY_XMSS:
623 	case KEY_XMSS_CERT:
624 		/* no need to prealloc */
625 		break;
626 	case KEY_UNSPEC:
627 		break;
628 	default:
629 		free(k);
630 		return NULL;
631 	}
632 
633 	if (sshkey_is_cert(k)) {
634 		if ((k->cert = cert_new()) == NULL) {
635 			sshkey_free(k);
636 			return NULL;
637 		}
638 	}
639 
640 	return k;
641 }
642 
643 void
644 sshkey_free(struct sshkey *k)
645 {
646 	if (k == NULL)
647 		return;
648 	switch (k->type) {
649 #ifdef WITH_OPENSSL
650 	case KEY_RSA:
651 	case KEY_RSA_CERT:
652 		RSA_free(k->rsa);
653 		k->rsa = NULL;
654 		break;
655 	case KEY_DSA:
656 	case KEY_DSA_CERT:
657 		DSA_free(k->dsa);
658 		k->dsa = NULL;
659 		break;
660 # ifdef OPENSSL_HAS_ECC
661 	case KEY_ECDSA_SK:
662 	case KEY_ECDSA_SK_CERT:
663 		free(k->sk_application);
664 		sshbuf_free(k->sk_key_handle);
665 		sshbuf_free(k->sk_reserved);
666 		/* FALLTHROUGH */
667 	case KEY_ECDSA:
668 	case KEY_ECDSA_CERT:
669 		EC_KEY_free(k->ecdsa);
670 		k->ecdsa = NULL;
671 		break;
672 # endif /* OPENSSL_HAS_ECC */
673 #endif /* WITH_OPENSSL */
674 	case KEY_ED25519_SK:
675 	case KEY_ED25519_SK_CERT:
676 		free(k->sk_application);
677 		sshbuf_free(k->sk_key_handle);
678 		sshbuf_free(k->sk_reserved);
679 		/* FALLTHROUGH */
680 	case KEY_ED25519:
681 	case KEY_ED25519_CERT:
682 		freezero(k->ed25519_pk, ED25519_PK_SZ);
683 		k->ed25519_pk = NULL;
684 		freezero(k->ed25519_sk, ED25519_SK_SZ);
685 		k->ed25519_sk = NULL;
686 		break;
687 #ifdef WITH_XMSS
688 	case KEY_XMSS:
689 	case KEY_XMSS_CERT:
690 		freezero(k->xmss_pk, sshkey_xmss_pklen(k));
691 		k->xmss_pk = NULL;
692 		freezero(k->xmss_sk, sshkey_xmss_sklen(k));
693 		k->xmss_sk = NULL;
694 		sshkey_xmss_free_state(k);
695 		free(k->xmss_name);
696 		k->xmss_name = NULL;
697 		free(k->xmss_filename);
698 		k->xmss_filename = NULL;
699 		break;
700 #endif /* WITH_XMSS */
701 	case KEY_UNSPEC:
702 		break;
703 	default:
704 		break;
705 	}
706 	if (sshkey_is_cert(k))
707 		cert_free(k->cert);
708 	freezero(k->shielded_private, k->shielded_len);
709 	freezero(k->shield_prekey, k->shield_prekey_len);
710 	freezero(k, sizeof(*k));
711 }
712 
713 static int
714 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
715 {
716 	if (a == NULL && b == NULL)
717 		return 1;
718 	if (a == NULL || b == NULL)
719 		return 0;
720 	if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
721 		return 0;
722 	if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
723 	    sshbuf_len(a->certblob)) != 0)
724 		return 0;
725 	return 1;
726 }
727 
728 /*
729  * Compare public portions of key only, allowing comparisons between
730  * certificates and plain keys too.
731  */
732 int
733 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
734 {
735 #if defined(WITH_OPENSSL)
736 	const BIGNUM *rsa_e_a, *rsa_n_a;
737 	const BIGNUM *rsa_e_b, *rsa_n_b;
738 	const BIGNUM *dsa_p_a, *dsa_q_a, *dsa_g_a, *dsa_pub_key_a;
739 	const BIGNUM *dsa_p_b, *dsa_q_b, *dsa_g_b, *dsa_pub_key_b;
740 #endif /* WITH_OPENSSL */
741 
742 	if (a == NULL || b == NULL ||
743 	    sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
744 		return 0;
745 
746 	switch (a->type) {
747 #ifdef WITH_OPENSSL
748 	case KEY_RSA_CERT:
749 	case KEY_RSA:
750 		if (a->rsa == NULL || b->rsa == NULL)
751 			return 0;
752 		RSA_get0_key(a->rsa, &rsa_n_a, &rsa_e_a, NULL);
753 		RSA_get0_key(b->rsa, &rsa_n_b, &rsa_e_b, NULL);
754 		return BN_cmp(rsa_e_a, rsa_e_b) == 0 &&
755 		    BN_cmp(rsa_n_a, rsa_n_b) == 0;
756 	case KEY_DSA_CERT:
757 	case KEY_DSA:
758 		if (a->dsa == NULL || b->dsa == NULL)
759 			return 0;
760 		DSA_get0_pqg(a->dsa, &dsa_p_a, &dsa_q_a, &dsa_g_a);
761 		DSA_get0_pqg(b->dsa, &dsa_p_b, &dsa_q_b, &dsa_g_b);
762 		DSA_get0_key(a->dsa, &dsa_pub_key_a, NULL);
763 		DSA_get0_key(b->dsa, &dsa_pub_key_b, NULL);
764 		return BN_cmp(dsa_p_a, dsa_p_b) == 0 &&
765 		    BN_cmp(dsa_q_a, dsa_q_b) == 0 &&
766 		    BN_cmp(dsa_g_a, dsa_g_b) == 0 &&
767 		    BN_cmp(dsa_pub_key_a, dsa_pub_key_b) == 0;
768 # ifdef OPENSSL_HAS_ECC
769 	case KEY_ECDSA_SK:
770 	case KEY_ECDSA_SK_CERT:
771 		if (a->sk_application == NULL || b->sk_application == NULL)
772 			return 0;
773 		if (strcmp(a->sk_application, b->sk_application) != 0)
774 			return 0;
775 		/* FALLTHROUGH */
776 	case KEY_ECDSA_CERT:
777 	case KEY_ECDSA:
778 		if (a->ecdsa == NULL || b->ecdsa == NULL ||
779 		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
780 		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
781 			return 0;
782 		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
783 		    EC_KEY_get0_group(b->ecdsa), NULL) != 0 ||
784 		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
785 		    EC_KEY_get0_public_key(a->ecdsa),
786 		    EC_KEY_get0_public_key(b->ecdsa), NULL) != 0)
787 			return 0;
788 		return 1;
789 # endif /* OPENSSL_HAS_ECC */
790 #endif /* WITH_OPENSSL */
791 	case KEY_ED25519_SK:
792 	case KEY_ED25519_SK_CERT:
793 		if (a->sk_application == NULL || b->sk_application == NULL)
794 			return 0;
795 		if (strcmp(a->sk_application, b->sk_application) != 0)
796 			return 0;
797 		/* FALLTHROUGH */
798 	case KEY_ED25519:
799 	case KEY_ED25519_CERT:
800 		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
801 		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
802 #ifdef WITH_XMSS
803 	case KEY_XMSS:
804 	case KEY_XMSS_CERT:
805 		return a->xmss_pk != NULL && b->xmss_pk != NULL &&
806 		    sshkey_xmss_pklen(a) == sshkey_xmss_pklen(b) &&
807 		    memcmp(a->xmss_pk, b->xmss_pk, sshkey_xmss_pklen(a)) == 0;
808 #endif /* WITH_XMSS */
809 	default:
810 		return 0;
811 	}
812 	/* NOTREACHED */
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 static int
828 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain,
829   enum sshkey_serialize_rep opts)
830 {
831 	int type, ret = SSH_ERR_INTERNAL_ERROR;
832 	const char *typename;
833 #ifdef WITH_OPENSSL
834 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
835 #endif /* WITH_OPENSSL */
836 
837 	if (key == NULL)
838 		return SSH_ERR_INVALID_ARGUMENT;
839 
840 	if (sshkey_is_cert(key)) {
841 		if (key->cert == NULL)
842 			return SSH_ERR_EXPECTED_CERT;
843 		if (sshbuf_len(key->cert->certblob) == 0)
844 			return SSH_ERR_KEY_LACKS_CERTBLOB;
845 	}
846 	type = force_plain ? sshkey_type_plain(key->type) : key->type;
847 	typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
848 
849 	switch (type) {
850 #ifdef WITH_OPENSSL
851 	case KEY_DSA_CERT:
852 	case KEY_ECDSA_CERT:
853 	case KEY_ECDSA_SK_CERT:
854 	case KEY_RSA_CERT:
855 #endif /* WITH_OPENSSL */
856 	case KEY_ED25519_CERT:
857 	case KEY_ED25519_SK_CERT:
858 #ifdef WITH_XMSS
859 	case KEY_XMSS_CERT:
860 #endif /* WITH_XMSS */
861 		/* Use the existing blob */
862 		/* XXX modified flag? */
863 		if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
864 			return ret;
865 		break;
866 #ifdef WITH_OPENSSL
867 	case KEY_DSA:
868 		if (key->dsa == NULL)
869 			return SSH_ERR_INVALID_ARGUMENT;
870 		DSA_get0_pqg(key->dsa, &dsa_p, &dsa_q, &dsa_g);
871 		DSA_get0_key(key->dsa, &dsa_pub_key, NULL);
872 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
873 		    (ret = sshbuf_put_bignum2(b, dsa_p)) != 0 ||
874 		    (ret = sshbuf_put_bignum2(b, dsa_q)) != 0 ||
875 		    (ret = sshbuf_put_bignum2(b, dsa_g)) != 0 ||
876 		    (ret = sshbuf_put_bignum2(b, dsa_pub_key)) != 0)
877 			return ret;
878 		break;
879 # ifdef OPENSSL_HAS_ECC
880 	case KEY_ECDSA:
881 	case KEY_ECDSA_SK:
882 		if (key->ecdsa == NULL)
883 			return SSH_ERR_INVALID_ARGUMENT;
884 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
885 		    (ret = sshbuf_put_cstring(b,
886 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
887 		    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
888 			return ret;
889 		if (type == KEY_ECDSA_SK) {
890 			if ((ret = sshbuf_put_cstring(b,
891 			    key->sk_application)) != 0)
892 				return ret;
893 		}
894 		break;
895 # endif
896 	case KEY_RSA:
897 		if (key->rsa == NULL)
898 			return SSH_ERR_INVALID_ARGUMENT;
899 		RSA_get0_key(key->rsa, &rsa_n, &rsa_e, NULL);
900 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
901 		    (ret = sshbuf_put_bignum2(b, rsa_e)) != 0 ||
902 		    (ret = sshbuf_put_bignum2(b, rsa_n)) != 0)
903 			return ret;
904 		break;
905 #endif /* WITH_OPENSSL */
906 	case KEY_ED25519:
907 	case KEY_ED25519_SK:
908 		if (key->ed25519_pk == NULL)
909 			return SSH_ERR_INVALID_ARGUMENT;
910 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
911 		    (ret = sshbuf_put_string(b,
912 		    key->ed25519_pk, ED25519_PK_SZ)) != 0)
913 			return ret;
914 		if (type == KEY_ED25519_SK) {
915 			if ((ret = sshbuf_put_cstring(b,
916 			    key->sk_application)) != 0)
917 				return ret;
918 		}
919 		break;
920 #ifdef WITH_XMSS
921 	case KEY_XMSS:
922 		if (key->xmss_name == NULL || key->xmss_pk == NULL ||
923 		    sshkey_xmss_pklen(key) == 0)
924 			return SSH_ERR_INVALID_ARGUMENT;
925 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
926 		    (ret = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
927 		    (ret = sshbuf_put_string(b,
928 		    key->xmss_pk, sshkey_xmss_pklen(key))) != 0 ||
929 		    (ret = sshkey_xmss_serialize_pk_info(key, b, opts)) != 0)
930 			return ret;
931 		break;
932 #endif /* WITH_XMSS */
933 	default:
934 		return SSH_ERR_KEY_TYPE_UNKNOWN;
935 	}
936 	return 0;
937 }
938 
939 int
940 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
941 {
942 	return to_blob_buf(key, b, 0, SSHKEY_SERIALIZE_DEFAULT);
943 }
944 
945 int
946 sshkey_puts_opts(const struct sshkey *key, struct sshbuf *b,
947     enum sshkey_serialize_rep opts)
948 {
949 	struct sshbuf *tmp;
950 	int r;
951 
952 	if ((tmp = sshbuf_new()) == NULL)
953 		return SSH_ERR_ALLOC_FAIL;
954 	r = to_blob_buf(key, tmp, 0, opts);
955 	if (r == 0)
956 		r = sshbuf_put_stringb(b, tmp);
957 	sshbuf_free(tmp);
958 	return r;
959 }
960 
961 int
962 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
963 {
964 	return sshkey_puts_opts(key, b, SSHKEY_SERIALIZE_DEFAULT);
965 }
966 
967 int
968 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
969 {
970 	return to_blob_buf(key, b, 1, SSHKEY_SERIALIZE_DEFAULT);
971 }
972 
973 static int
974 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain,
975     enum sshkey_serialize_rep opts)
976 {
977 	int ret = SSH_ERR_INTERNAL_ERROR;
978 	size_t len;
979 	struct sshbuf *b = NULL;
980 
981 	if (lenp != NULL)
982 		*lenp = 0;
983 	if (blobp != NULL)
984 		*blobp = NULL;
985 	if ((b = sshbuf_new()) == NULL)
986 		return SSH_ERR_ALLOC_FAIL;
987 	if ((ret = to_blob_buf(key, b, force_plain, opts)) != 0)
988 		goto out;
989 	len = sshbuf_len(b);
990 	if (lenp != NULL)
991 		*lenp = len;
992 	if (blobp != NULL) {
993 		if ((*blobp = malloc(len)) == NULL) {
994 			ret = SSH_ERR_ALLOC_FAIL;
995 			goto out;
996 		}
997 		memcpy(*blobp, sshbuf_ptr(b), len);
998 	}
999 	ret = 0;
1000  out:
1001 	sshbuf_free(b);
1002 	return ret;
1003 }
1004 
1005 int
1006 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
1007 {
1008 	return to_blob(key, blobp, lenp, 0, SSHKEY_SERIALIZE_DEFAULT);
1009 }
1010 
1011 int
1012 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
1013 {
1014 	return to_blob(key, blobp, lenp, 1, SSHKEY_SERIALIZE_DEFAULT);
1015 }
1016 
1017 int
1018 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
1019     u_char **retp, size_t *lenp)
1020 {
1021 	u_char *blob = NULL, *ret = NULL;
1022 	size_t blob_len = 0;
1023 	int r = SSH_ERR_INTERNAL_ERROR;
1024 
1025 	if (retp != NULL)
1026 		*retp = NULL;
1027 	if (lenp != NULL)
1028 		*lenp = 0;
1029 	if (ssh_digest_bytes(dgst_alg) == 0) {
1030 		r = SSH_ERR_INVALID_ARGUMENT;
1031 		goto out;
1032 	}
1033 	if ((r = to_blob(k, &blob, &blob_len, 1, SSHKEY_SERIALIZE_DEFAULT))
1034 	    != 0)
1035 		goto out;
1036 	if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
1037 		r = SSH_ERR_ALLOC_FAIL;
1038 		goto out;
1039 	}
1040 	if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
1041 	    ret, SSH_DIGEST_MAX_LENGTH)) != 0)
1042 		goto out;
1043 	/* success */
1044 	if (retp != NULL) {
1045 		*retp = ret;
1046 		ret = NULL;
1047 	}
1048 	if (lenp != NULL)
1049 		*lenp = ssh_digest_bytes(dgst_alg);
1050 	r = 0;
1051  out:
1052 	free(ret);
1053 	if (blob != NULL)
1054 		freezero(blob, blob_len);
1055 	return r;
1056 }
1057 
1058 static char *
1059 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1060 {
1061 	char *ret;
1062 	size_t plen = strlen(alg) + 1;
1063 	size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
1064 
1065 	if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
1066 		return NULL;
1067 	strlcpy(ret, alg, rlen);
1068 	strlcat(ret, ":", rlen);
1069 	if (dgst_raw_len == 0)
1070 		return ret;
1071 	if (b64_ntop(dgst_raw, dgst_raw_len, ret + plen, rlen - plen) == -1) {
1072 		freezero(ret, rlen);
1073 		return NULL;
1074 	}
1075 	/* Trim padding characters from end */
1076 	ret[strcspn(ret, "=")] = '\0';
1077 	return ret;
1078 }
1079 
1080 static char *
1081 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1082 {
1083 	char *retval, hex[5];
1084 	size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
1085 
1086 	if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
1087 		return NULL;
1088 	strlcpy(retval, alg, rlen);
1089 	strlcat(retval, ":", rlen);
1090 	for (i = 0; i < dgst_raw_len; i++) {
1091 		snprintf(hex, sizeof(hex), "%s%02x",
1092 		    i > 0 ? ":" : "", dgst_raw[i]);
1093 		strlcat(retval, hex, rlen);
1094 	}
1095 	return retval;
1096 }
1097 
1098 static char *
1099 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
1100 {
1101 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
1102 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
1103 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
1104 	u_int i, j = 0, rounds, seed = 1;
1105 	char *retval;
1106 
1107 	rounds = (dgst_raw_len / 2) + 1;
1108 	if ((retval = calloc(rounds, 6)) == NULL)
1109 		return NULL;
1110 	retval[j++] = 'x';
1111 	for (i = 0; i < rounds; i++) {
1112 		u_int idx0, idx1, idx2, idx3, idx4;
1113 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
1114 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
1115 			    seed) % 6;
1116 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
1117 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
1118 			    (seed / 6)) % 6;
1119 			retval[j++] = vowels[idx0];
1120 			retval[j++] = consonants[idx1];
1121 			retval[j++] = vowels[idx2];
1122 			if ((i + 1) < rounds) {
1123 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
1124 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
1125 				retval[j++] = consonants[idx3];
1126 				retval[j++] = '-';
1127 				retval[j++] = consonants[idx4];
1128 				seed = ((seed * 5) +
1129 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
1130 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1131 			}
1132 		} else {
1133 			idx0 = seed % 6;
1134 			idx1 = 16;
1135 			idx2 = seed / 6;
1136 			retval[j++] = vowels[idx0];
1137 			retval[j++] = consonants[idx1];
1138 			retval[j++] = vowels[idx2];
1139 		}
1140 	}
1141 	retval[j++] = 'x';
1142 	retval[j++] = '\0';
1143 	return retval;
1144 }
1145 
1146 /*
1147  * Draw an ASCII-Art representing the fingerprint so human brain can
1148  * profit from its built-in pattern recognition ability.
1149  * This technique is called "random art" and can be found in some
1150  * scientific publications like this original paper:
1151  *
1152  * "Hash Visualization: a New Technique to improve Real-World Security",
1153  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1154  * Techniques and E-Commerce (CrypTEC '99)
1155  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1156  *
1157  * The subject came up in a talk by Dan Kaminsky, too.
1158  *
1159  * If you see the picture is different, the key is different.
1160  * If the picture looks the same, you still know nothing.
1161  *
1162  * The algorithm used here is a worm crawling over a discrete plane,
1163  * leaving a trace (augmenting the field) everywhere it goes.
1164  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
1165  * makes the respective movement vector be ignored for this turn.
1166  * Graphs are not unambiguous, because circles in graphs can be
1167  * walked in either direction.
1168  */
1169 
1170 /*
1171  * Field sizes for the random art.  Have to be odd, so the starting point
1172  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1173  * Else pictures would be too dense, and drawing the frame would
1174  * fail, too, because the key type would not fit in anymore.
1175  */
1176 #define	FLDBASE		8
1177 #define	FLDSIZE_Y	(FLDBASE + 1)
1178 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
1179 static char *
1180 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1181     const struct sshkey *k)
1182 {
1183 	/*
1184 	 * Chars to be used after each other every time the worm
1185 	 * intersects with itself.  Matter of taste.
1186 	 */
1187 	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
1188 	char	*retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1189 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
1190 	size_t	 i, tlen, hlen;
1191 	u_int	 b;
1192 	int	 x, y, r;
1193 	size_t	 len = strlen(augmentation_string) - 1;
1194 
1195 	if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1196 		return NULL;
1197 
1198 	/* initialize field */
1199 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1200 	x = FLDSIZE_X / 2;
1201 	y = FLDSIZE_Y / 2;
1202 
1203 	/* process raw key */
1204 	for (i = 0; i < dgst_raw_len; i++) {
1205 		int input;
1206 		/* each byte conveys four 2-bit move commands */
1207 		input = dgst_raw[i];
1208 		for (b = 0; b < 4; b++) {
1209 			/* evaluate 2 bit, rest is shifted later */
1210 			x += (input & 0x1) ? 1 : -1;
1211 			y += (input & 0x2) ? 1 : -1;
1212 
1213 			/* assure we are still in bounds */
1214 			x = MAXIMUM(x, 0);
1215 			y = MAXIMUM(y, 0);
1216 			x = MINIMUM(x, FLDSIZE_X - 1);
1217 			y = MINIMUM(y, FLDSIZE_Y - 1);
1218 
1219 			/* augment the field */
1220 			if (field[x][y] < len - 2)
1221 				field[x][y]++;
1222 			input = input >> 2;
1223 		}
1224 	}
1225 
1226 	/* mark starting point and end point*/
1227 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1228 	field[x][y] = len;
1229 
1230 	/* assemble title */
1231 	r = snprintf(title, sizeof(title), "[%s %u]",
1232 		sshkey_type(k), sshkey_size(k));
1233 	/* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1234 	if (r < 0 || r > (int)sizeof(title))
1235 		r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1236 	tlen = (r <= 0) ? 0 : strlen(title);
1237 
1238 	/* assemble hash ID. */
1239 	r = snprintf(hash, sizeof(hash), "[%s]", alg);
1240 	hlen = (r <= 0) ? 0 : strlen(hash);
1241 
1242 	/* output upper border */
1243 	p = retval;
1244 	*p++ = '+';
1245 	for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1246 		*p++ = '-';
1247 	memcpy(p, title, tlen);
1248 	p += tlen;
1249 	for (i += tlen; i < FLDSIZE_X; i++)
1250 		*p++ = '-';
1251 	*p++ = '+';
1252 	*p++ = '\n';
1253 
1254 	/* output content */
1255 	for (y = 0; y < FLDSIZE_Y; y++) {
1256 		*p++ = '|';
1257 		for (x = 0; x < FLDSIZE_X; x++)
1258 			*p++ = augmentation_string[MINIMUM(field[x][y], len)];
1259 		*p++ = '|';
1260 		*p++ = '\n';
1261 	}
1262 
1263 	/* output lower border */
1264 	*p++ = '+';
1265 	for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1266 		*p++ = '-';
1267 	memcpy(p, hash, hlen);
1268 	p += hlen;
1269 	for (i += hlen; i < FLDSIZE_X; i++)
1270 		*p++ = '-';
1271 	*p++ = '+';
1272 
1273 	return retval;
1274 }
1275 
1276 char *
1277 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1278     enum sshkey_fp_rep dgst_rep)
1279 {
1280 	char *retval = NULL;
1281 	u_char *dgst_raw;
1282 	size_t dgst_raw_len;
1283 
1284 	if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1285 		return NULL;
1286 	switch (dgst_rep) {
1287 	case SSH_FP_DEFAULT:
1288 		if (dgst_alg == SSH_DIGEST_MD5) {
1289 			retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1290 			    dgst_raw, dgst_raw_len);
1291 		} else {
1292 			retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1293 			    dgst_raw, dgst_raw_len);
1294 		}
1295 		break;
1296 	case SSH_FP_HEX:
1297 		retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1298 		    dgst_raw, dgst_raw_len);
1299 		break;
1300 	case SSH_FP_BASE64:
1301 		retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1302 		    dgst_raw, dgst_raw_len);
1303 		break;
1304 	case SSH_FP_BUBBLEBABBLE:
1305 		retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1306 		break;
1307 	case SSH_FP_RANDOMART:
1308 		retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1309 		    dgst_raw, dgst_raw_len, k);
1310 		break;
1311 	default:
1312 		freezero(dgst_raw, dgst_raw_len);
1313 		return NULL;
1314 	}
1315 	freezero(dgst_raw, dgst_raw_len);
1316 	return retval;
1317 }
1318 
1319 static int
1320 peek_type_nid(const char *s, size_t l, int *nid)
1321 {
1322 	const struct keytype *kt;
1323 
1324 	for (kt = keytypes; kt->type != -1; kt++) {
1325 		if (kt->name == NULL || strlen(kt->name) != l)
1326 			continue;
1327 		if (memcmp(s, kt->name, l) == 0) {
1328 			*nid = -1;
1329 			if (key_type_is_ecdsa_variant(kt->type))
1330 				*nid = kt->nid;
1331 			return kt->type;
1332 		}
1333 	}
1334 	return KEY_UNSPEC;
1335 }
1336 
1337 /* XXX this can now be made const char * */
1338 int
1339 sshkey_read(struct sshkey *ret, char **cpp)
1340 {
1341 	struct sshkey *k;
1342 	char *cp, *blobcopy;
1343 	size_t space;
1344 	int r, type, curve_nid = -1;
1345 	struct sshbuf *blob;
1346 
1347 	if (ret == NULL)
1348 		return SSH_ERR_INVALID_ARGUMENT;
1349 
1350 	switch (ret->type) {
1351 	case KEY_UNSPEC:
1352 	case KEY_RSA:
1353 	case KEY_DSA:
1354 	case KEY_ECDSA:
1355 	case KEY_ECDSA_SK:
1356 	case KEY_ED25519:
1357 	case KEY_ED25519_SK:
1358 	case KEY_DSA_CERT:
1359 	case KEY_ECDSA_CERT:
1360 	case KEY_ECDSA_SK_CERT:
1361 	case KEY_RSA_CERT:
1362 	case KEY_ED25519_CERT:
1363 	case KEY_ED25519_SK_CERT:
1364 #ifdef WITH_XMSS
1365 	case KEY_XMSS:
1366 	case KEY_XMSS_CERT:
1367 #endif /* WITH_XMSS */
1368 		break; /* ok */
1369 	default:
1370 		return SSH_ERR_INVALID_ARGUMENT;
1371 	}
1372 
1373 	/* Decode type */
1374 	cp = *cpp;
1375 	space = strcspn(cp, " \t");
1376 	if (space == strlen(cp))
1377 		return SSH_ERR_INVALID_FORMAT;
1378 	if ((type = peek_type_nid(cp, space, &curve_nid)) == KEY_UNSPEC)
1379 		return SSH_ERR_INVALID_FORMAT;
1380 
1381 	/* skip whitespace */
1382 	for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1383 		;
1384 	if (*cp == '\0')
1385 		return SSH_ERR_INVALID_FORMAT;
1386 	if (ret->type != KEY_UNSPEC && ret->type != type)
1387 		return SSH_ERR_KEY_TYPE_MISMATCH;
1388 	if ((blob = sshbuf_new()) == NULL)
1389 		return SSH_ERR_ALLOC_FAIL;
1390 
1391 	/* find end of keyblob and decode */
1392 	space = strcspn(cp, " \t");
1393 	if ((blobcopy = strndup(cp, space)) == NULL) {
1394 		sshbuf_free(blob);
1395 		return SSH_ERR_ALLOC_FAIL;
1396 	}
1397 	if ((r = sshbuf_b64tod(blob, blobcopy)) != 0) {
1398 		free(blobcopy);
1399 		sshbuf_free(blob);
1400 		return r;
1401 	}
1402 	free(blobcopy);
1403 	if ((r = sshkey_fromb(blob, &k)) != 0) {
1404 		sshbuf_free(blob);
1405 		return r;
1406 	}
1407 	sshbuf_free(blob);
1408 
1409 	/* skip whitespace and leave cp at start of comment */
1410 	for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1411 		;
1412 
1413 	/* ensure type of blob matches type at start of line */
1414 	if (k->type != type) {
1415 		sshkey_free(k);
1416 		return SSH_ERR_KEY_TYPE_MISMATCH;
1417 	}
1418 	if (key_type_is_ecdsa_variant(type) && curve_nid != k->ecdsa_nid) {
1419 		sshkey_free(k);
1420 		return SSH_ERR_EC_CURVE_MISMATCH;
1421 	}
1422 
1423 	/* Fill in ret from parsed key */
1424 	ret->type = type;
1425 	if (sshkey_is_cert(ret)) {
1426 		if (!sshkey_is_cert(k)) {
1427 			sshkey_free(k);
1428 			return SSH_ERR_EXPECTED_CERT;
1429 		}
1430 		if (ret->cert != NULL)
1431 			cert_free(ret->cert);
1432 		ret->cert = k->cert;
1433 		k->cert = NULL;
1434 	}
1435 	switch (sshkey_type_plain(ret->type)) {
1436 #ifdef WITH_OPENSSL
1437 	case KEY_RSA:
1438 		RSA_free(ret->rsa);
1439 		ret->rsa = k->rsa;
1440 		k->rsa = NULL;
1441 #ifdef DEBUG_PK
1442 		RSA_print_fp(stderr, ret->rsa, 8);
1443 #endif
1444 		break;
1445 	case KEY_DSA:
1446 		DSA_free(ret->dsa);
1447 		ret->dsa = k->dsa;
1448 		k->dsa = NULL;
1449 #ifdef DEBUG_PK
1450 		DSA_print_fp(stderr, ret->dsa, 8);
1451 #endif
1452 		break;
1453 # ifdef OPENSSL_HAS_ECC
1454 	case KEY_ECDSA:
1455 		EC_KEY_free(ret->ecdsa);
1456 		ret->ecdsa = k->ecdsa;
1457 		ret->ecdsa_nid = k->ecdsa_nid;
1458 		k->ecdsa = NULL;
1459 		k->ecdsa_nid = -1;
1460 #ifdef DEBUG_PK
1461 		sshkey_dump_ec_key(ret->ecdsa);
1462 #endif
1463 		break;
1464 	case KEY_ECDSA_SK:
1465 		EC_KEY_free(ret->ecdsa);
1466 		ret->ecdsa = k->ecdsa;
1467 		ret->ecdsa_nid = k->ecdsa_nid;
1468 		ret->sk_application = k->sk_application;
1469 		k->ecdsa = NULL;
1470 		k->ecdsa_nid = -1;
1471 		k->sk_application = NULL;
1472 #ifdef DEBUG_PK
1473 		sshkey_dump_ec_key(ret->ecdsa);
1474 		fprintf(stderr, "App: %s\n", ret->sk_application);
1475 #endif
1476 		break;
1477 # endif /* OPENSSL_HAS_ECC */
1478 #endif /* WITH_OPENSSL */
1479 	case KEY_ED25519:
1480 		freezero(ret->ed25519_pk, ED25519_PK_SZ);
1481 		ret->ed25519_pk = k->ed25519_pk;
1482 		k->ed25519_pk = NULL;
1483 #ifdef DEBUG_PK
1484 		/* XXX */
1485 #endif
1486 		break;
1487 	case KEY_ED25519_SK:
1488 		freezero(ret->ed25519_pk, ED25519_PK_SZ);
1489 		ret->ed25519_pk = k->ed25519_pk;
1490 		ret->sk_application = k->sk_application;
1491 		k->ed25519_pk = NULL;
1492 		k->sk_application = NULL;
1493 		break;
1494 #ifdef WITH_XMSS
1495 	case KEY_XMSS:
1496 		free(ret->xmss_pk);
1497 		ret->xmss_pk = k->xmss_pk;
1498 		k->xmss_pk = NULL;
1499 		free(ret->xmss_state);
1500 		ret->xmss_state = k->xmss_state;
1501 		k->xmss_state = NULL;
1502 		free(ret->xmss_name);
1503 		ret->xmss_name = k->xmss_name;
1504 		k->xmss_name = NULL;
1505 		free(ret->xmss_filename);
1506 		ret->xmss_filename = k->xmss_filename;
1507 		k->xmss_filename = NULL;
1508 #ifdef DEBUG_PK
1509 		/* XXX */
1510 #endif
1511 		break;
1512 #endif /* WITH_XMSS */
1513 	default:
1514 		sshkey_free(k);
1515 		return SSH_ERR_INTERNAL_ERROR;
1516 	}
1517 	sshkey_free(k);
1518 
1519 	/* success */
1520 	*cpp = cp;
1521 	return 0;
1522 }
1523 
1524 
1525 int
1526 sshkey_to_base64(const struct sshkey *key, char **b64p)
1527 {
1528 	int r = SSH_ERR_INTERNAL_ERROR;
1529 	struct sshbuf *b = NULL;
1530 	char *uu = NULL;
1531 
1532 	if (b64p != NULL)
1533 		*b64p = NULL;
1534 	if ((b = sshbuf_new()) == NULL)
1535 		return SSH_ERR_ALLOC_FAIL;
1536 	if ((r = sshkey_putb(key, b)) != 0)
1537 		goto out;
1538 	if ((uu = sshbuf_dtob64_string(b, 0)) == NULL) {
1539 		r = SSH_ERR_ALLOC_FAIL;
1540 		goto out;
1541 	}
1542 	/* Success */
1543 	if (b64p != NULL) {
1544 		*b64p = uu;
1545 		uu = NULL;
1546 	}
1547 	r = 0;
1548  out:
1549 	sshbuf_free(b);
1550 	free(uu);
1551 	return r;
1552 }
1553 
1554 int
1555 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1556 {
1557 	int r = SSH_ERR_INTERNAL_ERROR;
1558 	char *uu = NULL;
1559 
1560 	if ((r = sshkey_to_base64(key, &uu)) != 0)
1561 		goto out;
1562 	if ((r = sshbuf_putf(b, "%s %s",
1563 	    sshkey_ssh_name(key), uu)) != 0)
1564 		goto out;
1565 	r = 0;
1566  out:
1567 	free(uu);
1568 	return r;
1569 }
1570 
1571 int
1572 sshkey_write(const struct sshkey *key, FILE *f)
1573 {
1574 	struct sshbuf *b = NULL;
1575 	int r = SSH_ERR_INTERNAL_ERROR;
1576 
1577 	if ((b = sshbuf_new()) == NULL)
1578 		return SSH_ERR_ALLOC_FAIL;
1579 	if ((r = sshkey_format_text(key, b)) != 0)
1580 		goto out;
1581 	if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1582 		if (feof(f))
1583 			errno = EPIPE;
1584 		r = SSH_ERR_SYSTEM_ERROR;
1585 		goto out;
1586 	}
1587 	/* Success */
1588 	r = 0;
1589  out:
1590 	sshbuf_free(b);
1591 	return r;
1592 }
1593 
1594 const char *
1595 sshkey_cert_type(const struct sshkey *k)
1596 {
1597 	switch (k->cert->type) {
1598 	case SSH2_CERT_TYPE_USER:
1599 		return "user";
1600 	case SSH2_CERT_TYPE_HOST:
1601 		return "host";
1602 	default:
1603 		return "unknown";
1604 	}
1605 }
1606 
1607 #ifdef WITH_OPENSSL
1608 static int
1609 rsa_generate_private_key(u_int bits, RSA **rsap)
1610 {
1611 	RSA *private = NULL;
1612 	BIGNUM *f4 = NULL;
1613 	int ret = SSH_ERR_INTERNAL_ERROR;
1614 
1615 	if (rsap == NULL)
1616 		return SSH_ERR_INVALID_ARGUMENT;
1617 	if (bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1618 	    bits > SSHBUF_MAX_BIGNUM * 8)
1619 		return SSH_ERR_KEY_LENGTH;
1620 	*rsap = NULL;
1621 	if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1622 		ret = SSH_ERR_ALLOC_FAIL;
1623 		goto out;
1624 	}
1625 	if (!BN_set_word(f4, RSA_F4) ||
1626 	    !RSA_generate_key_ex(private, bits, f4, NULL)) {
1627 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1628 		goto out;
1629 	}
1630 	*rsap = private;
1631 	private = NULL;
1632 	ret = 0;
1633  out:
1634 	RSA_free(private);
1635 	BN_free(f4);
1636 	return ret;
1637 }
1638 
1639 static int
1640 dsa_generate_private_key(u_int bits, DSA **dsap)
1641 {
1642 	DSA *private;
1643 	int ret = SSH_ERR_INTERNAL_ERROR;
1644 
1645 	if (dsap == NULL)
1646 		return SSH_ERR_INVALID_ARGUMENT;
1647 	if (bits != 1024)
1648 		return SSH_ERR_KEY_LENGTH;
1649 	if ((private = DSA_new()) == NULL) {
1650 		ret = SSH_ERR_ALLOC_FAIL;
1651 		goto out;
1652 	}
1653 	*dsap = NULL;
1654 	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1655 	    NULL, NULL) || !DSA_generate_key(private)) {
1656 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1657 		goto out;
1658 	}
1659 	*dsap = private;
1660 	private = NULL;
1661 	ret = 0;
1662  out:
1663 	DSA_free(private);
1664 	return ret;
1665 }
1666 
1667 # ifdef OPENSSL_HAS_ECC
1668 int
1669 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1670 {
1671 	EC_GROUP *eg;
1672 	int nids[] = {
1673 		NID_X9_62_prime256v1,
1674 		NID_secp384r1,
1675 #  ifdef OPENSSL_HAS_NISTP521
1676 		NID_secp521r1,
1677 #  endif /* OPENSSL_HAS_NISTP521 */
1678 		-1
1679 	};
1680 	int nid;
1681 	u_int i;
1682 	const EC_GROUP *g = EC_KEY_get0_group(k);
1683 
1684 	/*
1685 	 * The group may be stored in a ASN.1 encoded private key in one of two
1686 	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1687 	 * or explicit group parameters encoded into the key blob. Only the
1688 	 * "named group" case sets the group NID for us, but we can figure
1689 	 * it out for the other case by comparing against all the groups that
1690 	 * are supported.
1691 	 */
1692 	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1693 		return nid;
1694 	for (i = 0; nids[i] != -1; i++) {
1695 		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1696 			return -1;
1697 		if (EC_GROUP_cmp(g, eg, NULL) == 0)
1698 			break;
1699 		EC_GROUP_free(eg);
1700 	}
1701 	if (nids[i] != -1) {
1702 		/* Use the group with the NID attached */
1703 		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1704 		if (EC_KEY_set_group(k, eg) != 1) {
1705 			EC_GROUP_free(eg);
1706 			return -1;
1707 		}
1708 	}
1709 	return nids[i];
1710 }
1711 
1712 static int
1713 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1714 {
1715 	EC_KEY *private;
1716 	int ret = SSH_ERR_INTERNAL_ERROR;
1717 
1718 	if (nid == NULL || ecdsap == NULL)
1719 		return SSH_ERR_INVALID_ARGUMENT;
1720 	if ((*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1721 		return SSH_ERR_KEY_LENGTH;
1722 	*ecdsap = NULL;
1723 	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1724 		ret = SSH_ERR_ALLOC_FAIL;
1725 		goto out;
1726 	}
1727 	if (EC_KEY_generate_key(private) != 1) {
1728 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1729 		goto out;
1730 	}
1731 	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1732 	*ecdsap = private;
1733 	private = NULL;
1734 	ret = 0;
1735  out:
1736 	EC_KEY_free(private);
1737 	return ret;
1738 }
1739 # endif /* OPENSSL_HAS_ECC */
1740 #endif /* WITH_OPENSSL */
1741 
1742 int
1743 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1744 {
1745 	struct sshkey *k;
1746 	int ret = SSH_ERR_INTERNAL_ERROR;
1747 
1748 	if (keyp == NULL)
1749 		return SSH_ERR_INVALID_ARGUMENT;
1750 	*keyp = NULL;
1751 	if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1752 		return SSH_ERR_ALLOC_FAIL;
1753 	switch (type) {
1754 	case KEY_ED25519:
1755 		if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1756 		    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1757 			ret = SSH_ERR_ALLOC_FAIL;
1758 			break;
1759 		}
1760 		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1761 		ret = 0;
1762 		break;
1763 #ifdef WITH_XMSS
1764 	case KEY_XMSS:
1765 		ret = sshkey_xmss_generate_private_key(k, bits);
1766 		break;
1767 #endif /* WITH_XMSS */
1768 #ifdef WITH_OPENSSL
1769 	case KEY_DSA:
1770 		ret = dsa_generate_private_key(bits, &k->dsa);
1771 		break;
1772 # ifdef OPENSSL_HAS_ECC
1773 	case KEY_ECDSA:
1774 		ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1775 		    &k->ecdsa);
1776 		break;
1777 # endif /* OPENSSL_HAS_ECC */
1778 	case KEY_RSA:
1779 		ret = rsa_generate_private_key(bits, &k->rsa);
1780 		break;
1781 #endif /* WITH_OPENSSL */
1782 	default:
1783 		ret = SSH_ERR_INVALID_ARGUMENT;
1784 	}
1785 	if (ret == 0) {
1786 		k->type = type;
1787 		*keyp = k;
1788 	} else
1789 		sshkey_free(k);
1790 	return ret;
1791 }
1792 
1793 int
1794 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1795 {
1796 	u_int i;
1797 	const struct sshkey_cert *from;
1798 	struct sshkey_cert *to;
1799 	int r = SSH_ERR_INTERNAL_ERROR;
1800 
1801 	if (to_key == NULL || (from = from_key->cert) == NULL)
1802 		return SSH_ERR_INVALID_ARGUMENT;
1803 
1804 	if ((to = cert_new()) == NULL)
1805 		return SSH_ERR_ALLOC_FAIL;
1806 
1807 	if ((r = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1808 	    (r = sshbuf_putb(to->critical, from->critical)) != 0 ||
1809 	    (r = sshbuf_putb(to->extensions, from->extensions)) != 0)
1810 		goto out;
1811 
1812 	to->serial = from->serial;
1813 	to->type = from->type;
1814 	if (from->key_id == NULL)
1815 		to->key_id = NULL;
1816 	else if ((to->key_id = strdup(from->key_id)) == NULL) {
1817 		r = SSH_ERR_ALLOC_FAIL;
1818 		goto out;
1819 	}
1820 	to->valid_after = from->valid_after;
1821 	to->valid_before = from->valid_before;
1822 	if (from->signature_key == NULL)
1823 		to->signature_key = NULL;
1824 	else if ((r = sshkey_from_private(from->signature_key,
1825 	    &to->signature_key)) != 0)
1826 		goto out;
1827 	if (from->signature_type != NULL &&
1828 	    (to->signature_type = strdup(from->signature_type)) == NULL) {
1829 		r = SSH_ERR_ALLOC_FAIL;
1830 		goto out;
1831 	}
1832 	if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS) {
1833 		r = SSH_ERR_INVALID_ARGUMENT;
1834 		goto out;
1835 	}
1836 	if (from->nprincipals > 0) {
1837 		if ((to->principals = calloc(from->nprincipals,
1838 		    sizeof(*to->principals))) == NULL) {
1839 			r = SSH_ERR_ALLOC_FAIL;
1840 			goto out;
1841 		}
1842 		for (i = 0; i < from->nprincipals; i++) {
1843 			to->principals[i] = strdup(from->principals[i]);
1844 			if (to->principals[i] == NULL) {
1845 				to->nprincipals = i;
1846 				r = SSH_ERR_ALLOC_FAIL;
1847 				goto out;
1848 			}
1849 		}
1850 	}
1851 	to->nprincipals = from->nprincipals;
1852 
1853 	/* success */
1854 	cert_free(to_key->cert);
1855 	to_key->cert = to;
1856 	to = NULL;
1857 	r = 0;
1858  out:
1859 	cert_free(to);
1860 	return r;
1861 }
1862 
1863 int
1864 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1865 {
1866 	struct sshkey *n = NULL;
1867 	int r = SSH_ERR_INTERNAL_ERROR;
1868 #ifdef WITH_OPENSSL
1869 	const BIGNUM *rsa_n, *rsa_e;
1870 	BIGNUM *rsa_n_dup = NULL, *rsa_e_dup = NULL;
1871 	const BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
1872 	BIGNUM *dsa_p_dup = NULL, *dsa_q_dup = NULL, *dsa_g_dup = NULL;
1873 	BIGNUM *dsa_pub_key_dup = NULL;
1874 #endif /* WITH_OPENSSL */
1875 
1876 	*pkp = NULL;
1877 	if ((n = sshkey_new(k->type)) == NULL) {
1878 		r = SSH_ERR_ALLOC_FAIL;
1879 		goto out;
1880 	}
1881 	switch (k->type) {
1882 #ifdef WITH_OPENSSL
1883 	case KEY_DSA:
1884 	case KEY_DSA_CERT:
1885 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
1886 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
1887 		if ((dsa_p_dup = BN_dup(dsa_p)) == NULL ||
1888 		    (dsa_q_dup = BN_dup(dsa_q)) == NULL ||
1889 		    (dsa_g_dup = BN_dup(dsa_g)) == NULL ||
1890 		    (dsa_pub_key_dup = BN_dup(dsa_pub_key)) == NULL) {
1891 			r = SSH_ERR_ALLOC_FAIL;
1892 			goto out;
1893 		}
1894 		if (!DSA_set0_pqg(n->dsa, dsa_p_dup, dsa_q_dup, dsa_g_dup)) {
1895 			r = SSH_ERR_LIBCRYPTO_ERROR;
1896 			goto out;
1897 		}
1898 		dsa_p_dup = dsa_q_dup = dsa_g_dup = NULL; /* transferred */
1899 		if (!DSA_set0_key(n->dsa, dsa_pub_key_dup, NULL)) {
1900 			r = SSH_ERR_LIBCRYPTO_ERROR;
1901 			goto out;
1902 		}
1903 		dsa_pub_key_dup = NULL; /* transferred */
1904 
1905 		break;
1906 # ifdef OPENSSL_HAS_ECC
1907 	case KEY_ECDSA:
1908 	case KEY_ECDSA_CERT:
1909 	case KEY_ECDSA_SK:
1910 	case KEY_ECDSA_SK_CERT:
1911 		n->ecdsa_nid = k->ecdsa_nid;
1912 		n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1913 		if (n->ecdsa == NULL) {
1914 			r = SSH_ERR_ALLOC_FAIL;
1915 			goto out;
1916 		}
1917 		if (EC_KEY_set_public_key(n->ecdsa,
1918 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1919 			r = SSH_ERR_LIBCRYPTO_ERROR;
1920 			goto out;
1921 		}
1922 		if (k->type != KEY_ECDSA_SK && k->type != KEY_ECDSA_SK_CERT)
1923 			break;
1924 		/* Append security-key application string */
1925 		if ((n->sk_application = strdup(k->sk_application)) == NULL)
1926 			goto out;
1927 		break;
1928 # endif /* OPENSSL_HAS_ECC */
1929 	case KEY_RSA:
1930 	case KEY_RSA_CERT:
1931 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
1932 		if ((rsa_n_dup = BN_dup(rsa_n)) == NULL ||
1933 		    (rsa_e_dup = BN_dup(rsa_e)) == NULL) {
1934 			r = SSH_ERR_ALLOC_FAIL;
1935 			goto out;
1936 		}
1937 		if (!RSA_set0_key(n->rsa, rsa_n_dup, rsa_e_dup, NULL)) {
1938 			r = SSH_ERR_LIBCRYPTO_ERROR;
1939 			goto out;
1940 		}
1941 		rsa_n_dup = rsa_e_dup = NULL; /* transferred */
1942 		break;
1943 #endif /* WITH_OPENSSL */
1944 	case KEY_ED25519:
1945 	case KEY_ED25519_CERT:
1946 	case KEY_ED25519_SK:
1947 	case KEY_ED25519_SK_CERT:
1948 		if (k->ed25519_pk != NULL) {
1949 			if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1950 				r = SSH_ERR_ALLOC_FAIL;
1951 				goto out;
1952 			}
1953 			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1954 		}
1955 		if (k->type != KEY_ED25519_SK &&
1956 		    k->type != KEY_ED25519_SK_CERT)
1957 			break;
1958 		/* Append security-key application string */
1959 		if ((n->sk_application = strdup(k->sk_application)) == NULL)
1960 			goto out;
1961 		break;
1962 #ifdef WITH_XMSS
1963 	case KEY_XMSS:
1964 	case KEY_XMSS_CERT:
1965 		if ((r = sshkey_xmss_init(n, k->xmss_name)) != 0)
1966 			goto out;
1967 		if (k->xmss_pk != NULL) {
1968 			u_int32_t left;
1969 			size_t pklen = sshkey_xmss_pklen(k);
1970 			if (pklen == 0 || sshkey_xmss_pklen(n) != pklen) {
1971 				r = SSH_ERR_INTERNAL_ERROR;
1972 				goto out;
1973 			}
1974 			if ((n->xmss_pk = malloc(pklen)) == NULL) {
1975 				r = SSH_ERR_ALLOC_FAIL;
1976 				goto out;
1977 			}
1978 			memcpy(n->xmss_pk, k->xmss_pk, pklen);
1979 			/* simulate number of signatures left on pubkey */
1980 			left = sshkey_xmss_signatures_left(k);
1981 			if (left)
1982 				sshkey_xmss_enable_maxsign(n, left);
1983 		}
1984 		break;
1985 #endif /* WITH_XMSS */
1986 	default:
1987 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
1988 		goto out;
1989 	}
1990 	if (sshkey_is_cert(k) && (r = sshkey_cert_copy(k, n)) != 0)
1991 		goto out;
1992 	/* success */
1993 	*pkp = n;
1994 	n = NULL;
1995 	r = 0;
1996  out:
1997 	sshkey_free(n);
1998 #ifdef WITH_OPENSSL
1999 	BN_clear_free(rsa_n_dup);
2000 	BN_clear_free(rsa_e_dup);
2001 	BN_clear_free(dsa_p_dup);
2002 	BN_clear_free(dsa_q_dup);
2003 	BN_clear_free(dsa_g_dup);
2004 	BN_clear_free(dsa_pub_key_dup);
2005 #endif
2006 
2007 	return r;
2008 }
2009 
2010 int
2011 sshkey_is_shielded(struct sshkey *k)
2012 {
2013 	return k != NULL && k->shielded_private != NULL;
2014 }
2015 
2016 int
2017 sshkey_shield_private(struct sshkey *k)
2018 {
2019 	struct sshbuf *prvbuf = NULL;
2020 	u_char *prekey = NULL, *enc = NULL, keyiv[SSH_DIGEST_MAX_LENGTH];
2021 	struct sshcipher_ctx *cctx = NULL;
2022 	const struct sshcipher *cipher;
2023 	size_t i, enclen = 0;
2024 	struct sshkey *kswap = NULL, tmp;
2025 	int r = SSH_ERR_INTERNAL_ERROR;
2026 
2027 #ifdef DEBUG_PK
2028 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
2029 #endif
2030 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2031 		r = SSH_ERR_INVALID_ARGUMENT;
2032 		goto out;
2033 	}
2034 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2035 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2036 		r = SSH_ERR_INTERNAL_ERROR;
2037 		goto out;
2038 	}
2039 
2040 	/* Prepare a random pre-key, and from it an ephemeral key */
2041 	if ((prekey = malloc(SSHKEY_SHIELD_PREKEY_LEN)) == NULL) {
2042 		r = SSH_ERR_ALLOC_FAIL;
2043 		goto out;
2044 	}
2045 	arc4random_buf(prekey, SSHKEY_SHIELD_PREKEY_LEN);
2046 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2047 	    prekey, SSHKEY_SHIELD_PREKEY_LEN,
2048 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2049 		goto out;
2050 #ifdef DEBUG_PK
2051 	fprintf(stderr, "%s: key+iv\n", __func__);
2052 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2053 	    stderr);
2054 #endif
2055 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2056 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 1)) != 0)
2057 		goto out;
2058 
2059 	/* Serialise and encrypt the private key using the ephemeral key */
2060 	if ((prvbuf = sshbuf_new()) == NULL) {
2061 		r = SSH_ERR_ALLOC_FAIL;
2062 		goto out;
2063 	}
2064 	if (sshkey_is_shielded(k) && (r = sshkey_unshield_private(k)) != 0)
2065 		goto out;
2066 	if ((r = sshkey_private_serialize_opt(k, prvbuf,
2067 	    SSHKEY_SERIALIZE_SHIELD)) != 0)
2068 		goto out;
2069 	/* pad to cipher blocksize */
2070 	i = 0;
2071 	while (sshbuf_len(prvbuf) % cipher_blocksize(cipher)) {
2072 		if ((r = sshbuf_put_u8(prvbuf, ++i & 0xff)) != 0)
2073 			goto out;
2074 	}
2075 #ifdef DEBUG_PK
2076 	fprintf(stderr, "%s: serialised\n", __func__);
2077 	sshbuf_dump(prvbuf, stderr);
2078 #endif
2079 	/* encrypt */
2080 	enclen = sshbuf_len(prvbuf);
2081 	if ((enc = malloc(enclen)) == NULL) {
2082 		r = SSH_ERR_ALLOC_FAIL;
2083 		goto out;
2084 	}
2085 	if ((r = cipher_crypt(cctx, 0, enc,
2086 	    sshbuf_ptr(prvbuf), sshbuf_len(prvbuf), 0, 0)) != 0)
2087 		goto out;
2088 #ifdef DEBUG_PK
2089 	fprintf(stderr, "%s: encrypted\n", __func__);
2090 	sshbuf_dump_data(enc, enclen, stderr);
2091 #endif
2092 
2093 	/* Make a scrubbed, public-only copy of our private key argument */
2094 	if ((r = sshkey_from_private(k, &kswap)) != 0)
2095 		goto out;
2096 
2097 	/* Swap the private key out (it will be destroyed below) */
2098 	tmp = *kswap;
2099 	*kswap = *k;
2100 	*k = tmp;
2101 
2102 	/* Insert the shielded key into our argument */
2103 	k->shielded_private = enc;
2104 	k->shielded_len = enclen;
2105 	k->shield_prekey = prekey;
2106 	k->shield_prekey_len = SSHKEY_SHIELD_PREKEY_LEN;
2107 	enc = prekey = NULL; /* transferred */
2108 	enclen = 0;
2109 
2110 	/* preserve key fields that are required for correct operation */
2111 	k->sk_flags = kswap->sk_flags;
2112 
2113 	/* success */
2114 	r = 0;
2115 
2116  out:
2117 	/* XXX behaviour on error - invalidate original private key? */
2118 	cipher_free(cctx);
2119 	explicit_bzero(keyiv, sizeof(keyiv));
2120 	explicit_bzero(&tmp, sizeof(tmp));
2121 	freezero(enc, enclen);
2122 	freezero(prekey, SSHKEY_SHIELD_PREKEY_LEN);
2123 	sshkey_free(kswap);
2124 	sshbuf_free(prvbuf);
2125 	return r;
2126 }
2127 
2128 int
2129 sshkey_unshield_private(struct sshkey *k)
2130 {
2131 	struct sshbuf *prvbuf = NULL;
2132 	u_char pad, *cp, keyiv[SSH_DIGEST_MAX_LENGTH];
2133 	struct sshcipher_ctx *cctx = NULL;
2134 	const struct sshcipher *cipher;
2135 	size_t i;
2136 	struct sshkey *kswap = NULL, tmp;
2137 	int r = SSH_ERR_INTERNAL_ERROR;
2138 
2139 #ifdef DEBUG_PK
2140 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
2141 #endif
2142 	if (!sshkey_is_shielded(k))
2143 		return 0; /* nothing to do */
2144 
2145 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2146 		r = SSH_ERR_INVALID_ARGUMENT;
2147 		goto out;
2148 	}
2149 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2150 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2151 		r = SSH_ERR_INTERNAL_ERROR;
2152 		goto out;
2153 	}
2154 	/* check size of shielded key blob */
2155 	if (k->shielded_len < cipher_blocksize(cipher) ||
2156 	    (k->shielded_len % cipher_blocksize(cipher)) != 0) {
2157 		r = SSH_ERR_INVALID_FORMAT;
2158 		goto out;
2159 	}
2160 
2161 	/* Calculate the ephemeral key from the prekey */
2162 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2163 	    k->shield_prekey, k->shield_prekey_len,
2164 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2165 		goto out;
2166 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2167 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0)) != 0)
2168 		goto out;
2169 #ifdef DEBUG_PK
2170 	fprintf(stderr, "%s: key+iv\n", __func__);
2171 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2172 	    stderr);
2173 #endif
2174 
2175 	/* Decrypt and parse the shielded private key using the ephemeral key */
2176 	if ((prvbuf = sshbuf_new()) == NULL) {
2177 		r = SSH_ERR_ALLOC_FAIL;
2178 		goto out;
2179 	}
2180 	if ((r = sshbuf_reserve(prvbuf, k->shielded_len, &cp)) != 0)
2181 		goto out;
2182 	/* decrypt */
2183 #ifdef DEBUG_PK
2184 	fprintf(stderr, "%s: encrypted\n", __func__);
2185 	sshbuf_dump_data(k->shielded_private, k->shielded_len, stderr);
2186 #endif
2187 	if ((r = cipher_crypt(cctx, 0, cp,
2188 	    k->shielded_private, k->shielded_len, 0, 0)) != 0)
2189 		goto out;
2190 #ifdef DEBUG_PK
2191 	fprintf(stderr, "%s: serialised\n", __func__);
2192 	sshbuf_dump(prvbuf, stderr);
2193 #endif
2194 	/* Parse private key */
2195 	if ((r = sshkey_private_deserialize(prvbuf, &kswap)) != 0)
2196 		goto out;
2197 	/* Check deterministic padding */
2198 	i = 0;
2199 	while (sshbuf_len(prvbuf)) {
2200 		if ((r = sshbuf_get_u8(prvbuf, &pad)) != 0)
2201 			goto out;
2202 		if (pad != (++i & 0xff)) {
2203 			r = SSH_ERR_INVALID_FORMAT;
2204 			goto out;
2205 		}
2206 	}
2207 
2208 	/* Swap the parsed key back into place */
2209 	tmp = *kswap;
2210 	*kswap = *k;
2211 	*k = tmp;
2212 
2213 	/* success */
2214 	r = 0;
2215 
2216  out:
2217 	cipher_free(cctx);
2218 	explicit_bzero(keyiv, sizeof(keyiv));
2219 	explicit_bzero(&tmp, sizeof(tmp));
2220 	sshkey_free(kswap);
2221 	sshbuf_free(prvbuf);
2222 	return r;
2223 }
2224 
2225 static int
2226 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
2227 {
2228 	struct sshbuf *principals = NULL, *crit = NULL;
2229 	struct sshbuf *exts = NULL, *ca = NULL;
2230 	u_char *sig = NULL;
2231 	size_t signed_len = 0, slen = 0, kidlen = 0;
2232 	int ret = SSH_ERR_INTERNAL_ERROR;
2233 
2234 	/* Copy the entire key blob for verification and later serialisation */
2235 	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
2236 		return ret;
2237 
2238 	/* Parse body of certificate up to signature */
2239 	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
2240 	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
2241 	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
2242 	    (ret = sshbuf_froms(b, &principals)) != 0 ||
2243 	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
2244 	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
2245 	    (ret = sshbuf_froms(b, &crit)) != 0 ||
2246 	    (ret = sshbuf_froms(b, &exts)) != 0 ||
2247 	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
2248 	    (ret = sshbuf_froms(b, &ca)) != 0) {
2249 		/* XXX debug print error for ret */
2250 		ret = SSH_ERR_INVALID_FORMAT;
2251 		goto out;
2252 	}
2253 
2254 	/* Signature is left in the buffer so we can calculate this length */
2255 	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
2256 
2257 	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
2258 		ret = SSH_ERR_INVALID_FORMAT;
2259 		goto out;
2260 	}
2261 
2262 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
2263 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
2264 		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
2265 		goto out;
2266 	}
2267 
2268 	/* Parse principals section */
2269 	while (sshbuf_len(principals) > 0) {
2270 		char *principal = NULL;
2271 		char **oprincipals = NULL;
2272 
2273 		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
2274 			ret = SSH_ERR_INVALID_FORMAT;
2275 			goto out;
2276 		}
2277 		if ((ret = sshbuf_get_cstring(principals, &principal,
2278 		    NULL)) != 0) {
2279 			ret = SSH_ERR_INVALID_FORMAT;
2280 			goto out;
2281 		}
2282 		oprincipals = key->cert->principals;
2283 		key->cert->principals = recallocarray(key->cert->principals,
2284 		    key->cert->nprincipals, key->cert->nprincipals + 1,
2285 		    sizeof(*key->cert->principals));
2286 		if (key->cert->principals == NULL) {
2287 			free(principal);
2288 			key->cert->principals = oprincipals;
2289 			ret = SSH_ERR_ALLOC_FAIL;
2290 			goto out;
2291 		}
2292 		key->cert->principals[key->cert->nprincipals++] = principal;
2293 	}
2294 
2295 	/*
2296 	 * Stash a copies of the critical options and extensions sections
2297 	 * for later use.
2298 	 */
2299 	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
2300 	    (exts != NULL &&
2301 	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
2302 		goto out;
2303 
2304 	/*
2305 	 * Validate critical options and extensions sections format.
2306 	 */
2307 	while (sshbuf_len(crit) != 0) {
2308 		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
2309 		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
2310 			sshbuf_reset(key->cert->critical);
2311 			ret = SSH_ERR_INVALID_FORMAT;
2312 			goto out;
2313 		}
2314 	}
2315 	while (exts != NULL && sshbuf_len(exts) != 0) {
2316 		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
2317 		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
2318 			sshbuf_reset(key->cert->extensions);
2319 			ret = SSH_ERR_INVALID_FORMAT;
2320 			goto out;
2321 		}
2322 	}
2323 
2324 	/* Parse CA key and check signature */
2325 	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
2326 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2327 		goto out;
2328 	}
2329 	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
2330 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2331 		goto out;
2332 	}
2333 	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
2334 	    sshbuf_ptr(key->cert->certblob), signed_len, NULL, 0, NULL)) != 0)
2335 		goto out;
2336 	if ((ret = sshkey_get_sigtype(sig, slen,
2337 	    &key->cert->signature_type)) != 0)
2338 		goto out;
2339 
2340 	/* Success */
2341 	ret = 0;
2342  out:
2343 	sshbuf_free(ca);
2344 	sshbuf_free(crit);
2345 	sshbuf_free(exts);
2346 	sshbuf_free(principals);
2347 	free(sig);
2348 	return ret;
2349 }
2350 
2351 #ifdef WITH_OPENSSL
2352 static int
2353 check_rsa_length(const RSA *rsa)
2354 {
2355 	const BIGNUM *rsa_n;
2356 
2357 	RSA_get0_key(rsa, &rsa_n, NULL, NULL);
2358 	if (BN_num_bits(rsa_n) < SSH_RSA_MINIMUM_MODULUS_SIZE)
2359 		return SSH_ERR_KEY_LENGTH;
2360 	return 0;
2361 }
2362 #endif
2363 
2364 static int
2365 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
2366     int allow_cert)
2367 {
2368 	int type, ret = SSH_ERR_INTERNAL_ERROR;
2369 	char *ktype = NULL, *curve = NULL, *xmss_name = NULL;
2370 	struct sshkey *key = NULL;
2371 	size_t len;
2372 	u_char *pk = NULL;
2373 	struct sshbuf *copy;
2374 #if defined(WITH_OPENSSL)
2375 	BIGNUM *rsa_n = NULL, *rsa_e = NULL;
2376 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL, *dsa_pub_key = NULL;
2377 # if defined(OPENSSL_HAS_ECC)
2378 	EC_POINT *q = NULL;
2379 # endif /* OPENSSL_HAS_ECC */
2380 #endif /* WITH_OPENSSL */
2381 
2382 #ifdef DEBUG_PK /* XXX */
2383 	sshbuf_dump(b, stderr);
2384 #endif
2385 	if (keyp != NULL)
2386 		*keyp = NULL;
2387 	if ((copy = sshbuf_fromb(b)) == NULL) {
2388 		ret = SSH_ERR_ALLOC_FAIL;
2389 		goto out;
2390 	}
2391 	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
2392 		ret = SSH_ERR_INVALID_FORMAT;
2393 		goto out;
2394 	}
2395 
2396 	type = sshkey_type_from_name(ktype);
2397 	if (!allow_cert && sshkey_type_is_cert(type)) {
2398 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2399 		goto out;
2400 	}
2401 	switch (type) {
2402 #ifdef WITH_OPENSSL
2403 	case KEY_RSA_CERT:
2404 		/* Skip nonce */
2405 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2406 			ret = SSH_ERR_INVALID_FORMAT;
2407 			goto out;
2408 		}
2409 		/* FALLTHROUGH */
2410 	case KEY_RSA:
2411 		if ((key = sshkey_new(type)) == NULL) {
2412 			ret = SSH_ERR_ALLOC_FAIL;
2413 			goto out;
2414 		}
2415 		if (sshbuf_get_bignum2(b, &rsa_e) != 0 ||
2416 		    sshbuf_get_bignum2(b, &rsa_n) != 0) {
2417 			ret = SSH_ERR_INVALID_FORMAT;
2418 			goto out;
2419 		}
2420 		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, NULL)) {
2421 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2422 			goto out;
2423 		}
2424 		rsa_n = rsa_e = NULL; /* transferred */
2425 		if ((ret = check_rsa_length(key->rsa)) != 0)
2426 			goto out;
2427 #ifdef DEBUG_PK
2428 		RSA_print_fp(stderr, key->rsa, 8);
2429 #endif
2430 		break;
2431 	case KEY_DSA_CERT:
2432 		/* Skip nonce */
2433 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2434 			ret = SSH_ERR_INVALID_FORMAT;
2435 			goto out;
2436 		}
2437 		/* FALLTHROUGH */
2438 	case KEY_DSA:
2439 		if ((key = sshkey_new(type)) == NULL) {
2440 			ret = SSH_ERR_ALLOC_FAIL;
2441 			goto out;
2442 		}
2443 		if (sshbuf_get_bignum2(b, &dsa_p) != 0 ||
2444 		    sshbuf_get_bignum2(b, &dsa_q) != 0 ||
2445 		    sshbuf_get_bignum2(b, &dsa_g) != 0 ||
2446 		    sshbuf_get_bignum2(b, &dsa_pub_key) != 0) {
2447 			ret = SSH_ERR_INVALID_FORMAT;
2448 			goto out;
2449 		}
2450 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g)) {
2451 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2452 			goto out;
2453 		}
2454 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
2455 		if (!DSA_set0_key(key->dsa, dsa_pub_key, NULL)) {
2456 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2457 			goto out;
2458 		}
2459 		dsa_pub_key = NULL; /* transferred */
2460 #ifdef DEBUG_PK
2461 		DSA_print_fp(stderr, key->dsa, 8);
2462 #endif
2463 		break;
2464 # ifdef OPENSSL_HAS_ECC
2465 	case KEY_ECDSA_CERT:
2466 	case KEY_ECDSA_SK_CERT:
2467 		/* Skip nonce */
2468 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2469 			ret = SSH_ERR_INVALID_FORMAT;
2470 			goto out;
2471 		}
2472 		/* FALLTHROUGH */
2473 	case KEY_ECDSA:
2474 	case KEY_ECDSA_SK:
2475 		if ((key = sshkey_new(type)) == NULL) {
2476 			ret = SSH_ERR_ALLOC_FAIL;
2477 			goto out;
2478 		}
2479 		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2480 		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2481 			ret = SSH_ERR_INVALID_FORMAT;
2482 			goto out;
2483 		}
2484 		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2485 			ret = SSH_ERR_EC_CURVE_MISMATCH;
2486 			goto out;
2487 		}
2488 		EC_KEY_free(key->ecdsa);
2489 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2490 		    == NULL) {
2491 			ret = SSH_ERR_EC_CURVE_INVALID;
2492 			goto out;
2493 		}
2494 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2495 			ret = SSH_ERR_ALLOC_FAIL;
2496 			goto out;
2497 		}
2498 		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2499 			ret = SSH_ERR_INVALID_FORMAT;
2500 			goto out;
2501 		}
2502 		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2503 		    q) != 0) {
2504 			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2505 			goto out;
2506 		}
2507 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2508 			/* XXX assume it is a allocation error */
2509 			ret = SSH_ERR_ALLOC_FAIL;
2510 			goto out;
2511 		}
2512 #ifdef DEBUG_PK
2513 		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2514 #endif
2515 		if (type == KEY_ECDSA_SK || type == KEY_ECDSA_SK_CERT) {
2516 			/* Parse additional security-key application string */
2517 			if (sshbuf_get_cstring(b, &key->sk_application,
2518 			    NULL) != 0) {
2519 				ret = SSH_ERR_INVALID_FORMAT;
2520 				goto out;
2521 			}
2522 #ifdef DEBUG_PK
2523 			fprintf(stderr, "App: %s\n", key->sk_application);
2524 #endif
2525 		}
2526 		break;
2527 # endif /* OPENSSL_HAS_ECC */
2528 #endif /* WITH_OPENSSL */
2529 	case KEY_ED25519_CERT:
2530 	case KEY_ED25519_SK_CERT:
2531 		/* Skip nonce */
2532 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2533 			ret = SSH_ERR_INVALID_FORMAT;
2534 			goto out;
2535 		}
2536 		/* FALLTHROUGH */
2537 	case KEY_ED25519:
2538 	case KEY_ED25519_SK:
2539 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2540 			goto out;
2541 		if (len != ED25519_PK_SZ) {
2542 			ret = SSH_ERR_INVALID_FORMAT;
2543 			goto out;
2544 		}
2545 		if ((key = sshkey_new(type)) == NULL) {
2546 			ret = SSH_ERR_ALLOC_FAIL;
2547 			goto out;
2548 		}
2549 		if (type == KEY_ED25519_SK || type == KEY_ED25519_SK_CERT) {
2550 			/* Parse additional security-key application string */
2551 			if (sshbuf_get_cstring(b, &key->sk_application,
2552 			    NULL) != 0) {
2553 				ret = SSH_ERR_INVALID_FORMAT;
2554 				goto out;
2555 			}
2556 #ifdef DEBUG_PK
2557 			fprintf(stderr, "App: %s\n", key->sk_application);
2558 #endif
2559 		}
2560 		key->ed25519_pk = pk;
2561 		pk = NULL;
2562 		break;
2563 #ifdef WITH_XMSS
2564 	case KEY_XMSS_CERT:
2565 		/* Skip nonce */
2566 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2567 			ret = SSH_ERR_INVALID_FORMAT;
2568 			goto out;
2569 		}
2570 		/* FALLTHROUGH */
2571 	case KEY_XMSS:
2572 		if ((ret = sshbuf_get_cstring(b, &xmss_name, NULL)) != 0)
2573 			goto out;
2574 		if ((key = sshkey_new(type)) == NULL) {
2575 			ret = SSH_ERR_ALLOC_FAIL;
2576 			goto out;
2577 		}
2578 		if ((ret = sshkey_xmss_init(key, xmss_name)) != 0)
2579 			goto out;
2580 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2581 			goto out;
2582 		if (len == 0 || len != sshkey_xmss_pklen(key)) {
2583 			ret = SSH_ERR_INVALID_FORMAT;
2584 			goto out;
2585 		}
2586 		key->xmss_pk = pk;
2587 		pk = NULL;
2588 		if (type != KEY_XMSS_CERT &&
2589 		    (ret = sshkey_xmss_deserialize_pk_info(key, b)) != 0)
2590 			goto out;
2591 		break;
2592 #endif /* WITH_XMSS */
2593 	case KEY_UNSPEC:
2594 	default:
2595 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2596 		goto out;
2597 	}
2598 
2599 	/* Parse certificate potion */
2600 	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2601 		goto out;
2602 
2603 	if (key != NULL && sshbuf_len(b) != 0) {
2604 		ret = SSH_ERR_INVALID_FORMAT;
2605 		goto out;
2606 	}
2607 	ret = 0;
2608 	if (keyp != NULL) {
2609 		*keyp = key;
2610 		key = NULL;
2611 	}
2612  out:
2613 	sshbuf_free(copy);
2614 	sshkey_free(key);
2615 	free(xmss_name);
2616 	free(ktype);
2617 	free(curve);
2618 	free(pk);
2619 #if defined(WITH_OPENSSL)
2620 	BN_clear_free(rsa_n);
2621 	BN_clear_free(rsa_e);
2622 	BN_clear_free(dsa_p);
2623 	BN_clear_free(dsa_q);
2624 	BN_clear_free(dsa_g);
2625 	BN_clear_free(dsa_pub_key);
2626 # if defined(OPENSSL_HAS_ECC)
2627 	EC_POINT_free(q);
2628 # endif /* OPENSSL_HAS_ECC */
2629 #endif /* WITH_OPENSSL */
2630 	return ret;
2631 }
2632 
2633 int
2634 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2635 {
2636 	struct sshbuf *b;
2637 	int r;
2638 
2639 	if ((b = sshbuf_from(blob, blen)) == NULL)
2640 		return SSH_ERR_ALLOC_FAIL;
2641 	r = sshkey_from_blob_internal(b, keyp, 1);
2642 	sshbuf_free(b);
2643 	return r;
2644 }
2645 
2646 int
2647 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2648 {
2649 	return sshkey_from_blob_internal(b, keyp, 1);
2650 }
2651 
2652 int
2653 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2654 {
2655 	struct sshbuf *b;
2656 	int r;
2657 
2658 	if ((r = sshbuf_froms(buf, &b)) != 0)
2659 		return r;
2660 	r = sshkey_from_blob_internal(b, keyp, 1);
2661 	sshbuf_free(b);
2662 	return r;
2663 }
2664 
2665 int
2666 sshkey_get_sigtype(const u_char *sig, size_t siglen, char **sigtypep)
2667 {
2668 	int r;
2669 	struct sshbuf *b = NULL;
2670 	char *sigtype = NULL;
2671 
2672 	if (sigtypep != NULL)
2673 		*sigtypep = NULL;
2674 	if ((b = sshbuf_from(sig, siglen)) == NULL)
2675 		return SSH_ERR_ALLOC_FAIL;
2676 	if ((r = sshbuf_get_cstring(b, &sigtype, NULL)) != 0)
2677 		goto out;
2678 	/* success */
2679 	if (sigtypep != NULL) {
2680 		*sigtypep = sigtype;
2681 		sigtype = NULL;
2682 	}
2683 	r = 0;
2684  out:
2685 	free(sigtype);
2686 	sshbuf_free(b);
2687 	return r;
2688 }
2689 
2690 /*
2691  *
2692  * Checks whether a certificate's signature type is allowed.
2693  * Returns 0 (success) if the certificate signature type appears in the
2694  * "allowed" pattern-list, or the key is not a certificate to begin with.
2695  * Otherwise returns a ssherr.h code.
2696  */
2697 int
2698 sshkey_check_cert_sigtype(const struct sshkey *key, const char *allowed)
2699 {
2700 	if (key == NULL || allowed == NULL)
2701 		return SSH_ERR_INVALID_ARGUMENT;
2702 	if (!sshkey_type_is_cert(key->type))
2703 		return 0;
2704 	if (key->cert == NULL || key->cert->signature_type == NULL)
2705 		return SSH_ERR_INVALID_ARGUMENT;
2706 	if (match_pattern_list(key->cert->signature_type, allowed, 0) != 1)
2707 		return SSH_ERR_SIGN_ALG_UNSUPPORTED;
2708 	return 0;
2709 }
2710 
2711 /*
2712  * Returns the expected signature algorithm for a given public key algorithm.
2713  */
2714 const char *
2715 sshkey_sigalg_by_name(const char *name)
2716 {
2717 	const struct keytype *kt;
2718 
2719 	for (kt = keytypes; kt->type != -1; kt++) {
2720 		if (strcmp(kt->name, name) != 0)
2721 			continue;
2722 		if (kt->sigalg != NULL)
2723 			return kt->sigalg;
2724 		if (!kt->cert)
2725 			return kt->name;
2726 		return sshkey_ssh_name_from_type_nid(
2727 		    sshkey_type_plain(kt->type), kt->nid);
2728 	}
2729 	return NULL;
2730 }
2731 
2732 /*
2733  * Verifies that the signature algorithm appearing inside the signature blob
2734  * matches that which was requested.
2735  */
2736 int
2737 sshkey_check_sigtype(const u_char *sig, size_t siglen,
2738     const char *requested_alg)
2739 {
2740 	const char *expected_alg;
2741 	char *sigtype = NULL;
2742 	int r;
2743 
2744 	if (requested_alg == NULL)
2745 		return 0;
2746 	if ((expected_alg = sshkey_sigalg_by_name(requested_alg)) == NULL)
2747 		return SSH_ERR_INVALID_ARGUMENT;
2748 	if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0)
2749 		return r;
2750 	r = strcmp(expected_alg, sigtype) == 0;
2751 	free(sigtype);
2752 	return r ? 0 : SSH_ERR_SIGN_ALG_UNSUPPORTED;
2753 }
2754 
2755 int
2756 sshkey_sign(struct sshkey *key,
2757     u_char **sigp, size_t *lenp,
2758     const u_char *data, size_t datalen,
2759     const char *alg, const char *sk_provider, const char *sk_pin, u_int compat)
2760 {
2761 	int was_shielded = sshkey_is_shielded(key);
2762 	int r2, r = SSH_ERR_INTERNAL_ERROR;
2763 
2764 	if (sigp != NULL)
2765 		*sigp = NULL;
2766 	if (lenp != NULL)
2767 		*lenp = 0;
2768 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2769 		return SSH_ERR_INVALID_ARGUMENT;
2770 	if ((r = sshkey_unshield_private(key)) != 0)
2771 		return r;
2772 	switch (key->type) {
2773 #ifdef WITH_OPENSSL
2774 	case KEY_DSA_CERT:
2775 	case KEY_DSA:
2776 		r = ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2777 		break;
2778 # ifdef OPENSSL_HAS_ECC
2779 	case KEY_ECDSA_CERT:
2780 	case KEY_ECDSA:
2781 		r = ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2782 		break;
2783 # endif /* OPENSSL_HAS_ECC */
2784 	case KEY_RSA_CERT:
2785 	case KEY_RSA:
2786 		r = ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2787 		break;
2788 #endif /* WITH_OPENSSL */
2789 	case KEY_ED25519:
2790 	case KEY_ED25519_CERT:
2791 		r = ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2792 		break;
2793 	case KEY_ED25519_SK:
2794 	case KEY_ED25519_SK_CERT:
2795 	case KEY_ECDSA_SK_CERT:
2796 	case KEY_ECDSA_SK:
2797 		r = sshsk_sign(sk_provider, key, sigp, lenp, data,
2798 		    datalen, compat, sk_pin);
2799 		break;
2800 #ifdef WITH_XMSS
2801 	case KEY_XMSS:
2802 	case KEY_XMSS_CERT:
2803 		r = ssh_xmss_sign(key, sigp, lenp, data, datalen, compat);
2804 		break;
2805 #endif /* WITH_XMSS */
2806 	default:
2807 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2808 		break;
2809 	}
2810 	if (was_shielded && (r2 = sshkey_shield_private(key)) != 0)
2811 		return r2;
2812 	return r;
2813 }
2814 
2815 /*
2816  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2817  * If "alg" specified, then the signature must use that algorithm.
2818  */
2819 int
2820 sshkey_verify(const struct sshkey *key,
2821     const u_char *sig, size_t siglen,
2822     const u_char *data, size_t dlen, const char *alg, u_int compat,
2823     struct sshkey_sig_details **detailsp)
2824 {
2825 	if (detailsp != NULL)
2826 		*detailsp = NULL;
2827 	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2828 		return SSH_ERR_INVALID_ARGUMENT;
2829 	switch (key->type) {
2830 #ifdef WITH_OPENSSL
2831 	case KEY_DSA_CERT:
2832 	case KEY_DSA:
2833 		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2834 # ifdef OPENSSL_HAS_ECC
2835 	case KEY_ECDSA_CERT:
2836 	case KEY_ECDSA:
2837 		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2838 	case KEY_ECDSA_SK_CERT:
2839 	case KEY_ECDSA_SK:
2840 		return ssh_ecdsa_sk_verify(key, sig, siglen, data, dlen,
2841 		    compat, detailsp);
2842 # endif /* OPENSSL_HAS_ECC */
2843 	case KEY_RSA_CERT:
2844 	case KEY_RSA:
2845 		return ssh_rsa_verify(key, sig, siglen, data, dlen, alg);
2846 #endif /* WITH_OPENSSL */
2847 	case KEY_ED25519:
2848 	case KEY_ED25519_CERT:
2849 		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2850 	case KEY_ED25519_SK:
2851 	case KEY_ED25519_SK_CERT:
2852 		return ssh_ed25519_sk_verify(key, sig, siglen, data, dlen,
2853 		    compat, detailsp);
2854 #ifdef WITH_XMSS
2855 	case KEY_XMSS:
2856 	case KEY_XMSS_CERT:
2857 		return ssh_xmss_verify(key, sig, siglen, data, dlen, compat);
2858 #endif /* WITH_XMSS */
2859 	default:
2860 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2861 	}
2862 }
2863 
2864 /* Convert a plain key to their _CERT equivalent */
2865 int
2866 sshkey_to_certified(struct sshkey *k)
2867 {
2868 	int newtype;
2869 
2870 	switch (k->type) {
2871 #ifdef WITH_OPENSSL
2872 	case KEY_RSA:
2873 		newtype = KEY_RSA_CERT;
2874 		break;
2875 	case KEY_DSA:
2876 		newtype = KEY_DSA_CERT;
2877 		break;
2878 	case KEY_ECDSA:
2879 		newtype = KEY_ECDSA_CERT;
2880 		break;
2881 	case KEY_ECDSA_SK:
2882 		newtype = KEY_ECDSA_SK_CERT;
2883 		break;
2884 #endif /* WITH_OPENSSL */
2885 	case KEY_ED25519_SK:
2886 		newtype = KEY_ED25519_SK_CERT;
2887 		break;
2888 	case KEY_ED25519:
2889 		newtype = KEY_ED25519_CERT;
2890 		break;
2891 #ifdef WITH_XMSS
2892 	case KEY_XMSS:
2893 		newtype = KEY_XMSS_CERT;
2894 		break;
2895 #endif /* WITH_XMSS */
2896 	default:
2897 		return SSH_ERR_INVALID_ARGUMENT;
2898 	}
2899 	if ((k->cert = cert_new()) == NULL)
2900 		return SSH_ERR_ALLOC_FAIL;
2901 	k->type = newtype;
2902 	return 0;
2903 }
2904 
2905 /* Convert a certificate to its raw key equivalent */
2906 int
2907 sshkey_drop_cert(struct sshkey *k)
2908 {
2909 	if (!sshkey_type_is_cert(k->type))
2910 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2911 	cert_free(k->cert);
2912 	k->cert = NULL;
2913 	k->type = sshkey_type_plain(k->type);
2914 	return 0;
2915 }
2916 
2917 /* Sign a certified key, (re-)generating the signed certblob. */
2918 int
2919 sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2920     const char *sk_provider, const char *sk_pin,
2921     sshkey_certify_signer *signer, void *signer_ctx)
2922 {
2923 	struct sshbuf *principals = NULL;
2924 	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2925 	size_t i, ca_len, sig_len;
2926 	int ret = SSH_ERR_INTERNAL_ERROR;
2927 	struct sshbuf *cert = NULL;
2928 	char *sigtype = NULL;
2929 #ifdef WITH_OPENSSL
2930 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
2931 #endif /* WITH_OPENSSL */
2932 
2933 	if (k == NULL || k->cert == NULL ||
2934 	    k->cert->certblob == NULL || ca == NULL)
2935 		return SSH_ERR_INVALID_ARGUMENT;
2936 	if (!sshkey_is_cert(k))
2937 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2938 	if (!sshkey_type_is_valid_ca(ca->type))
2939 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2940 
2941 	/*
2942 	 * If no alg specified as argument but a signature_type was set,
2943 	 * then prefer that. If both were specified, then they must match.
2944 	 */
2945 	if (alg == NULL)
2946 		alg = k->cert->signature_type;
2947 	else if (k->cert->signature_type != NULL &&
2948 	    strcmp(alg, k->cert->signature_type) != 0)
2949 		return SSH_ERR_INVALID_ARGUMENT;
2950 
2951 	/*
2952 	 * If no signing algorithm or signature_type was specified and we're
2953 	 * using a RSA key, then default to a good signature algorithm.
2954 	 */
2955 	if (alg == NULL && ca->type == KEY_RSA)
2956 		alg = "rsa-sha2-512";
2957 
2958 	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2959 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2960 
2961 	cert = k->cert->certblob; /* for readability */
2962 	sshbuf_reset(cert);
2963 	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2964 		goto out;
2965 
2966 	/* -v01 certs put nonce first */
2967 	arc4random_buf(&nonce, sizeof(nonce));
2968 	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2969 		goto out;
2970 
2971 	/* XXX this substantially duplicates to_blob(); refactor */
2972 	switch (k->type) {
2973 #ifdef WITH_OPENSSL
2974 	case KEY_DSA_CERT:
2975 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
2976 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
2977 		if ((ret = sshbuf_put_bignum2(cert, dsa_p)) != 0 ||
2978 		    (ret = sshbuf_put_bignum2(cert, dsa_q)) != 0 ||
2979 		    (ret = sshbuf_put_bignum2(cert, dsa_g)) != 0 ||
2980 		    (ret = sshbuf_put_bignum2(cert, dsa_pub_key)) != 0)
2981 			goto out;
2982 		break;
2983 # ifdef OPENSSL_HAS_ECC
2984 	case KEY_ECDSA_CERT:
2985 	case KEY_ECDSA_SK_CERT:
2986 		if ((ret = sshbuf_put_cstring(cert,
2987 		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2988 		    (ret = sshbuf_put_ec(cert,
2989 		    EC_KEY_get0_public_key(k->ecdsa),
2990 		    EC_KEY_get0_group(k->ecdsa))) != 0)
2991 			goto out;
2992 		if (k->type == KEY_ECDSA_SK_CERT) {
2993 			if ((ret = sshbuf_put_cstring(cert,
2994 			    k->sk_application)) != 0)
2995 				goto out;
2996 		}
2997 		break;
2998 # endif /* OPENSSL_HAS_ECC */
2999 	case KEY_RSA_CERT:
3000 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
3001 		if ((ret = sshbuf_put_bignum2(cert, rsa_e)) != 0 ||
3002 		    (ret = sshbuf_put_bignum2(cert, rsa_n)) != 0)
3003 			goto out;
3004 		break;
3005 #endif /* WITH_OPENSSL */
3006 	case KEY_ED25519_CERT:
3007 	case KEY_ED25519_SK_CERT:
3008 		if ((ret = sshbuf_put_string(cert,
3009 		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
3010 			goto out;
3011 		if (k->type == KEY_ED25519_SK_CERT) {
3012 			if ((ret = sshbuf_put_cstring(cert,
3013 			    k->sk_application)) != 0)
3014 				goto out;
3015 		}
3016 		break;
3017 #ifdef WITH_XMSS
3018 	case KEY_XMSS_CERT:
3019 		if (k->xmss_name == NULL) {
3020 			ret = SSH_ERR_INVALID_ARGUMENT;
3021 			goto out;
3022 		}
3023 		if ((ret = sshbuf_put_cstring(cert, k->xmss_name)) ||
3024 		    (ret = sshbuf_put_string(cert,
3025 		    k->xmss_pk, sshkey_xmss_pklen(k))) != 0)
3026 			goto out;
3027 		break;
3028 #endif /* WITH_XMSS */
3029 	default:
3030 		ret = SSH_ERR_INVALID_ARGUMENT;
3031 		goto out;
3032 	}
3033 
3034 	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
3035 	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
3036 	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
3037 		goto out;
3038 
3039 	if ((principals = sshbuf_new()) == NULL) {
3040 		ret = SSH_ERR_ALLOC_FAIL;
3041 		goto out;
3042 	}
3043 	for (i = 0; i < k->cert->nprincipals; i++) {
3044 		if ((ret = sshbuf_put_cstring(principals,
3045 		    k->cert->principals[i])) != 0)
3046 			goto out;
3047 	}
3048 	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
3049 	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
3050 	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
3051 	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
3052 	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
3053 	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
3054 	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
3055 		goto out;
3056 
3057 	/* Sign the whole mess */
3058 	if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
3059 	    sshbuf_len(cert), alg, sk_provider, sk_pin, 0, signer_ctx)) != 0)
3060 		goto out;
3061 	/* Check and update signature_type against what was actually used */
3062 	if ((ret = sshkey_get_sigtype(sig_blob, sig_len, &sigtype)) != 0)
3063 		goto out;
3064 	if (alg != NULL && strcmp(alg, sigtype) != 0) {
3065 		ret = SSH_ERR_SIGN_ALG_UNSUPPORTED;
3066 		goto out;
3067 	}
3068 	if (k->cert->signature_type == NULL) {
3069 		k->cert->signature_type = sigtype;
3070 		sigtype = NULL;
3071 	}
3072 	/* Append signature and we are done */
3073 	if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
3074 		goto out;
3075 	ret = 0;
3076  out:
3077 	if (ret != 0)
3078 		sshbuf_reset(cert);
3079 	free(sig_blob);
3080 	free(ca_blob);
3081 	free(sigtype);
3082 	sshbuf_free(principals);
3083 	return ret;
3084 }
3085 
3086 static int
3087 default_key_sign(struct sshkey *key, u_char **sigp, size_t *lenp,
3088     const u_char *data, size_t datalen,
3089     const char *alg, const char *sk_provider, const char *sk_pin,
3090     u_int compat, void *ctx)
3091 {
3092 	if (ctx != NULL)
3093 		return SSH_ERR_INVALID_ARGUMENT;
3094 	return sshkey_sign(key, sigp, lenp, data, datalen, alg,
3095 	    sk_provider, sk_pin, compat);
3096 }
3097 
3098 int
3099 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg,
3100     const char *sk_provider, const char *sk_pin)
3101 {
3102 	return sshkey_certify_custom(k, ca, alg, sk_provider, sk_pin,
3103 	    default_key_sign, NULL);
3104 }
3105 
3106 int
3107 sshkey_cert_check_authority(const struct sshkey *k,
3108     int want_host, int require_principal, int wildcard_pattern,
3109     uint64_t verify_time, const char *name, const char **reason)
3110 {
3111 	u_int i, principal_matches;
3112 
3113 	if (reason == NULL)
3114 		return SSH_ERR_INVALID_ARGUMENT;
3115 	if (!sshkey_is_cert(k)) {
3116 		*reason = "Key is not a certificate";
3117 		return SSH_ERR_KEY_CERT_INVALID;
3118 	}
3119 	if (want_host) {
3120 		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
3121 			*reason = "Certificate invalid: not a host certificate";
3122 			return SSH_ERR_KEY_CERT_INVALID;
3123 		}
3124 	} else {
3125 		if (k->cert->type != SSH2_CERT_TYPE_USER) {
3126 			*reason = "Certificate invalid: not a user certificate";
3127 			return SSH_ERR_KEY_CERT_INVALID;
3128 		}
3129 	}
3130 	if (verify_time < k->cert->valid_after) {
3131 		*reason = "Certificate invalid: not yet valid";
3132 		return SSH_ERR_KEY_CERT_INVALID;
3133 	}
3134 	if (verify_time >= k->cert->valid_before) {
3135 		*reason = "Certificate invalid: expired";
3136 		return SSH_ERR_KEY_CERT_INVALID;
3137 	}
3138 	if (k->cert->nprincipals == 0) {
3139 		if (require_principal) {
3140 			*reason = "Certificate lacks principal list";
3141 			return SSH_ERR_KEY_CERT_INVALID;
3142 		}
3143 	} else if (name != NULL) {
3144 		principal_matches = 0;
3145 		for (i = 0; i < k->cert->nprincipals; i++) {
3146 			if (wildcard_pattern) {
3147 				if (match_pattern(k->cert->principals[i],
3148 				    name)) {
3149 					principal_matches = 1;
3150 					break;
3151 				}
3152 			} else if (strcmp(name, k->cert->principals[i]) == 0) {
3153 				principal_matches = 1;
3154 				break;
3155 			}
3156 		}
3157 		if (!principal_matches) {
3158 			*reason = "Certificate invalid: name is not a listed "
3159 			    "principal";
3160 			return SSH_ERR_KEY_CERT_INVALID;
3161 		}
3162 	}
3163 	return 0;
3164 }
3165 
3166 int
3167 sshkey_cert_check_authority_now(const struct sshkey *k,
3168     int want_host, int require_principal, int wildcard_pattern,
3169     const char *name, const char **reason)
3170 {
3171 	time_t now;
3172 
3173 	if ((now = time(NULL)) < 0) {
3174 		/* yikes - system clock before epoch! */
3175 		*reason = "Certificate invalid: not yet valid";
3176 		return SSH_ERR_KEY_CERT_INVALID;
3177 	}
3178 	return sshkey_cert_check_authority(k, want_host, require_principal,
3179 	    wildcard_pattern, (uint64_t)now, name, reason);
3180 }
3181 
3182 int
3183 sshkey_cert_check_host(const struct sshkey *key, const char *host,
3184     int wildcard_principals, const char *ca_sign_algorithms,
3185     const char **reason)
3186 {
3187 	int r;
3188 
3189 	if ((r = sshkey_cert_check_authority_now(key, 1, 0, wildcard_principals,
3190 	    host, reason)) != 0)
3191 		return r;
3192 	if (sshbuf_len(key->cert->critical) != 0) {
3193 		*reason = "Certificate contains unsupported critical options";
3194 		return SSH_ERR_KEY_CERT_INVALID;
3195 	}
3196 	if (ca_sign_algorithms != NULL &&
3197 	    (r = sshkey_check_cert_sigtype(key, ca_sign_algorithms)) != 0) {
3198 		*reason = "Certificate signed with disallowed algorithm";
3199 		return SSH_ERR_KEY_CERT_INVALID;
3200 	}
3201 	return 0;
3202 }
3203 
3204 size_t
3205 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
3206 {
3207 	char from[32], to[32], ret[128];
3208 
3209 	*from = *to = '\0';
3210 	if (cert->valid_after == 0 &&
3211 	    cert->valid_before == 0xffffffffffffffffULL)
3212 		return strlcpy(s, "forever", l);
3213 
3214 	if (cert->valid_after != 0)
3215 		format_absolute_time(cert->valid_after, from, sizeof(from));
3216 	if (cert->valid_before != 0xffffffffffffffffULL)
3217 		format_absolute_time(cert->valid_before, to, sizeof(to));
3218 
3219 	if (cert->valid_after == 0)
3220 		snprintf(ret, sizeof(ret), "before %s", to);
3221 	else if (cert->valid_before == 0xffffffffffffffffULL)
3222 		snprintf(ret, sizeof(ret), "after %s", from);
3223 	else
3224 		snprintf(ret, sizeof(ret), "from %s to %s", from, to);
3225 
3226 	return strlcpy(s, ret, l);
3227 }
3228 
3229 int
3230 sshkey_private_serialize_opt(struct sshkey *key, struct sshbuf *buf,
3231     enum sshkey_serialize_rep opts)
3232 {
3233 	int r = SSH_ERR_INTERNAL_ERROR;
3234 	int was_shielded = sshkey_is_shielded(key);
3235 	struct sshbuf *b = NULL;
3236 #ifdef WITH_OPENSSL
3237 	const BIGNUM *rsa_n, *rsa_e, *rsa_d, *rsa_iqmp, *rsa_p, *rsa_q;
3238 	const BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key, *dsa_priv_key;
3239 #endif /* WITH_OPENSSL */
3240 
3241 	if ((r = sshkey_unshield_private(key)) != 0)
3242 		return r;
3243 	if ((b = sshbuf_new()) == NULL)
3244 		return SSH_ERR_ALLOC_FAIL;
3245 	if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
3246 		goto out;
3247 	switch (key->type) {
3248 #ifdef WITH_OPENSSL
3249 	case KEY_RSA:
3250 		RSA_get0_key(key->rsa, &rsa_n, &rsa_e, &rsa_d);
3251 		RSA_get0_factors(key->rsa, &rsa_p, &rsa_q);
3252 		RSA_get0_crt_params(key->rsa, NULL, NULL, &rsa_iqmp);
3253 		if ((r = sshbuf_put_bignum2(b, rsa_n)) != 0 ||
3254 		    (r = sshbuf_put_bignum2(b, rsa_e)) != 0 ||
3255 		    (r = sshbuf_put_bignum2(b, rsa_d)) != 0 ||
3256 		    (r = sshbuf_put_bignum2(b, rsa_iqmp)) != 0 ||
3257 		    (r = sshbuf_put_bignum2(b, rsa_p)) != 0 ||
3258 		    (r = sshbuf_put_bignum2(b, rsa_q)) != 0)
3259 			goto out;
3260 		break;
3261 	case KEY_RSA_CERT:
3262 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3263 			r = SSH_ERR_INVALID_ARGUMENT;
3264 			goto out;
3265 		}
3266 		RSA_get0_key(key->rsa, NULL, NULL, &rsa_d);
3267 		RSA_get0_factors(key->rsa, &rsa_p, &rsa_q);
3268 		RSA_get0_crt_params(key->rsa, NULL, NULL, &rsa_iqmp);
3269 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3270 		    (r = sshbuf_put_bignum2(b, rsa_d)) != 0 ||
3271 		    (r = sshbuf_put_bignum2(b, rsa_iqmp)) != 0 ||
3272 		    (r = sshbuf_put_bignum2(b, rsa_p)) != 0 ||
3273 		    (r = sshbuf_put_bignum2(b, rsa_q)) != 0)
3274 			goto out;
3275 		break;
3276 	case KEY_DSA:
3277 		DSA_get0_pqg(key->dsa, &dsa_p, &dsa_q, &dsa_g);
3278 		DSA_get0_key(key->dsa, &dsa_pub_key, &dsa_priv_key);
3279 		if ((r = sshbuf_put_bignum2(b, dsa_p)) != 0 ||
3280 		    (r = sshbuf_put_bignum2(b, dsa_q)) != 0 ||
3281 		    (r = sshbuf_put_bignum2(b, dsa_g)) != 0 ||
3282 		    (r = sshbuf_put_bignum2(b, dsa_pub_key)) != 0 ||
3283 		    (r = sshbuf_put_bignum2(b, dsa_priv_key)) != 0)
3284 			goto out;
3285 		break;
3286 	case KEY_DSA_CERT:
3287 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3288 			r = SSH_ERR_INVALID_ARGUMENT;
3289 			goto out;
3290 		}
3291 		DSA_get0_key(key->dsa, NULL, &dsa_priv_key);
3292 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3293 		    (r = sshbuf_put_bignum2(b, dsa_priv_key)) != 0)
3294 			goto out;
3295 		break;
3296 # ifdef OPENSSL_HAS_ECC
3297 	case KEY_ECDSA:
3298 		if ((r = sshbuf_put_cstring(b,
3299 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
3300 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
3301 		    (r = sshbuf_put_bignum2(b,
3302 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
3303 			goto out;
3304 		break;
3305 	case KEY_ECDSA_CERT:
3306 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3307 			r = SSH_ERR_INVALID_ARGUMENT;
3308 			goto out;
3309 		}
3310 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3311 		    (r = sshbuf_put_bignum2(b,
3312 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
3313 			goto out;
3314 		break;
3315 	case KEY_ECDSA_SK:
3316 		if ((r = sshbuf_put_cstring(b,
3317 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
3318 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
3319 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3320 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3321 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3322 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3323 			goto out;
3324 		break;
3325 	case KEY_ECDSA_SK_CERT:
3326 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3327 			r = SSH_ERR_INVALID_ARGUMENT;
3328 			goto out;
3329 		}
3330 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3331 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3332 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3333 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3334 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3335 			goto out;
3336 		break;
3337 # endif /* OPENSSL_HAS_ECC */
3338 #endif /* WITH_OPENSSL */
3339 	case KEY_ED25519:
3340 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
3341 		    ED25519_PK_SZ)) != 0 ||
3342 		    (r = sshbuf_put_string(b, key->ed25519_sk,
3343 		    ED25519_SK_SZ)) != 0)
3344 			goto out;
3345 		break;
3346 	case KEY_ED25519_CERT:
3347 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3348 			r = SSH_ERR_INVALID_ARGUMENT;
3349 			goto out;
3350 		}
3351 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3352 		    (r = sshbuf_put_string(b, key->ed25519_pk,
3353 		    ED25519_PK_SZ)) != 0 ||
3354 		    (r = sshbuf_put_string(b, key->ed25519_sk,
3355 		    ED25519_SK_SZ)) != 0)
3356 			goto out;
3357 		break;
3358 	case KEY_ED25519_SK:
3359 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
3360 		    ED25519_PK_SZ)) != 0 ||
3361 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3362 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3363 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3364 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3365 			goto out;
3366 		break;
3367 	case KEY_ED25519_SK_CERT:
3368 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3369 			r = SSH_ERR_INVALID_ARGUMENT;
3370 			goto out;
3371 		}
3372 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3373 		    (r = sshbuf_put_string(b, key->ed25519_pk,
3374 		    ED25519_PK_SZ)) != 0 ||
3375 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3376 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3377 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3378 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3379 			goto out;
3380 		break;
3381 #ifdef WITH_XMSS
3382 	case KEY_XMSS:
3383 		if (key->xmss_name == NULL) {
3384 			r = SSH_ERR_INVALID_ARGUMENT;
3385 			goto out;
3386 		}
3387 		if ((r = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
3388 		    (r = sshbuf_put_string(b, key->xmss_pk,
3389 		    sshkey_xmss_pklen(key))) != 0 ||
3390 		    (r = sshbuf_put_string(b, key->xmss_sk,
3391 		    sshkey_xmss_sklen(key))) != 0 ||
3392 		    (r = sshkey_xmss_serialize_state_opt(key, b, opts)) != 0)
3393 			goto out;
3394 		break;
3395 	case KEY_XMSS_CERT:
3396 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0 ||
3397 		    key->xmss_name == NULL) {
3398 			r = SSH_ERR_INVALID_ARGUMENT;
3399 			goto out;
3400 		}
3401 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3402 		    (r = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
3403 		    (r = sshbuf_put_string(b, key->xmss_pk,
3404 		    sshkey_xmss_pklen(key))) != 0 ||
3405 		    (r = sshbuf_put_string(b, key->xmss_sk,
3406 		    sshkey_xmss_sklen(key))) != 0 ||
3407 		    (r = sshkey_xmss_serialize_state_opt(key, b, opts)) != 0)
3408 			goto out;
3409 		break;
3410 #endif /* WITH_XMSS */
3411 	default:
3412 		r = SSH_ERR_INVALID_ARGUMENT;
3413 		goto out;
3414 	}
3415 	/*
3416 	 * success (but we still need to append the output to buf after
3417 	 * possibly re-shielding the private key)
3418 	 */
3419 	r = 0;
3420  out:
3421 	if (was_shielded)
3422 		r = sshkey_shield_private(key);
3423 	if (r == 0)
3424 		r = sshbuf_putb(buf, b);
3425 	sshbuf_free(b);
3426 
3427 	return r;
3428 }
3429 
3430 int
3431 sshkey_private_serialize(struct sshkey *key, struct sshbuf *b)
3432 {
3433 	return sshkey_private_serialize_opt(key, b,
3434 	    SSHKEY_SERIALIZE_DEFAULT);
3435 }
3436 
3437 int
3438 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
3439 {
3440 	char *tname = NULL, *curve = NULL, *xmss_name = NULL;
3441 	char *expect_sk_application = NULL;
3442 	struct sshkey *k = NULL;
3443 	size_t pklen = 0, sklen = 0;
3444 	int type, r = SSH_ERR_INTERNAL_ERROR;
3445 	u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
3446 	u_char *expect_ed25519_pk = NULL;
3447 	u_char *xmss_pk = NULL, *xmss_sk = NULL;
3448 #ifdef WITH_OPENSSL
3449 	BIGNUM *exponent = NULL;
3450 	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
3451 	BIGNUM *rsa_iqmp = NULL, *rsa_p = NULL, *rsa_q = NULL;
3452 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
3453 	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
3454 #endif /* WITH_OPENSSL */
3455 
3456 	if (kp != NULL)
3457 		*kp = NULL;
3458 	if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
3459 		goto out;
3460 	type = sshkey_type_from_name(tname);
3461 	if (sshkey_type_is_cert(type)) {
3462 		/*
3463 		 * Certificate key private keys begin with the certificate
3464 		 * itself. Make sure this matches the type of the enclosing
3465 		 * private key.
3466 		 */
3467 		if ((r = sshkey_froms(buf, &k)) != 0)
3468 			goto out;
3469 		if (k->type != type) {
3470 			r = SSH_ERR_KEY_CERT_MISMATCH;
3471 			goto out;
3472 		}
3473 		/* For ECDSA keys, the group must match too */
3474 		if (k->type == KEY_ECDSA &&
3475 		    k->ecdsa_nid != sshkey_ecdsa_nid_from_name(tname)) {
3476 			r = SSH_ERR_KEY_CERT_MISMATCH;
3477 			goto out;
3478 		}
3479 		/*
3480 		 * Several fields are redundant between certificate and
3481 		 * private key body, we require these to match.
3482 		 */
3483 		expect_sk_application = k->sk_application;
3484 		expect_ed25519_pk = k->ed25519_pk;
3485 		k->sk_application = NULL;
3486 		k->ed25519_pk = NULL;
3487 	} else {
3488 		if ((k = sshkey_new(type)) == NULL) {
3489 			r = SSH_ERR_ALLOC_FAIL;
3490 			goto out;
3491 		}
3492 	}
3493 	switch (type) {
3494 #ifdef WITH_OPENSSL
3495 	case KEY_DSA:
3496 		if ((r = sshbuf_get_bignum2(buf, &dsa_p)) != 0 ||
3497 		    (r = sshbuf_get_bignum2(buf, &dsa_q)) != 0 ||
3498 		    (r = sshbuf_get_bignum2(buf, &dsa_g)) != 0 ||
3499 		    (r = sshbuf_get_bignum2(buf, &dsa_pub_key)) != 0)
3500 			goto out;
3501 		if (!DSA_set0_pqg(k->dsa, dsa_p, dsa_q, dsa_g)) {
3502 			r = SSH_ERR_LIBCRYPTO_ERROR;
3503 			goto out;
3504 		}
3505 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
3506 		if (!DSA_set0_key(k->dsa, dsa_pub_key, NULL)) {
3507 			r = SSH_ERR_LIBCRYPTO_ERROR;
3508 			goto out;
3509 		}
3510 		dsa_pub_key = NULL; /* transferred */
3511 		/* FALLTHROUGH */
3512 	case KEY_DSA_CERT:
3513 		if ((r = sshbuf_get_bignum2(buf, &dsa_priv_key)) != 0)
3514 			goto out;
3515 		if (!DSA_set0_key(k->dsa, NULL, dsa_priv_key)) {
3516 			r = SSH_ERR_LIBCRYPTO_ERROR;
3517 			goto out;
3518 		}
3519 		dsa_priv_key = NULL; /* transferred */
3520 		break;
3521 # ifdef OPENSSL_HAS_ECC
3522 	case KEY_ECDSA:
3523 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
3524 			r = SSH_ERR_INVALID_ARGUMENT;
3525 			goto out;
3526 		}
3527 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
3528 			goto out;
3529 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
3530 			r = SSH_ERR_EC_CURVE_MISMATCH;
3531 			goto out;
3532 		}
3533 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
3534 		if (k->ecdsa  == NULL) {
3535 			r = SSH_ERR_LIBCRYPTO_ERROR;
3536 			goto out;
3537 		}
3538 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0)
3539 			goto out;
3540 		/* FALLTHROUGH */
3541 	case KEY_ECDSA_CERT:
3542 		if ((r = sshbuf_get_bignum2(buf, &exponent)) != 0)
3543 			goto out;
3544 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
3545 			r = SSH_ERR_LIBCRYPTO_ERROR;
3546 			goto out;
3547 		}
3548 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3549 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
3550 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
3551 			goto out;
3552 		break;
3553 	case KEY_ECDSA_SK:
3554 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
3555 			r = SSH_ERR_INVALID_ARGUMENT;
3556 			goto out;
3557 		}
3558 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
3559 			goto out;
3560 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
3561 			r = SSH_ERR_EC_CURVE_MISMATCH;
3562 			goto out;
3563 		}
3564 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3565 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3566 			r = SSH_ERR_ALLOC_FAIL;
3567 			goto out;
3568 		}
3569 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
3570 		if (k->ecdsa  == NULL) {
3571 			r = SSH_ERR_LIBCRYPTO_ERROR;
3572 			goto out;
3573 		}
3574 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
3575 		    (r = sshbuf_get_cstring(buf, &k->sk_application,
3576 		    NULL)) != 0 ||
3577 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3578 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3579 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3580 			goto out;
3581 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3582 		    EC_KEY_get0_public_key(k->ecdsa))) != 0)
3583 			goto out;
3584 		break;
3585 	case KEY_ECDSA_SK_CERT:
3586 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3587 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3588 			r = SSH_ERR_ALLOC_FAIL;
3589 			goto out;
3590 		}
3591 		if ((r = sshbuf_get_cstring(buf, &k->sk_application,
3592 		    NULL)) != 0 ||
3593 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3594 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3595 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3596 			goto out;
3597 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3598 		    EC_KEY_get0_public_key(k->ecdsa))) != 0)
3599 			goto out;
3600 		break;
3601 # endif /* OPENSSL_HAS_ECC */
3602 	case KEY_RSA:
3603 		if ((r = sshbuf_get_bignum2(buf, &rsa_n)) != 0 ||
3604 		    (r = sshbuf_get_bignum2(buf, &rsa_e)) != 0)
3605 			goto out;
3606 		if (!RSA_set0_key(k->rsa, rsa_n, rsa_e, NULL)) {
3607 			r = SSH_ERR_LIBCRYPTO_ERROR;
3608 			goto out;
3609 		}
3610 		rsa_n = rsa_e = NULL; /* transferred */
3611 		/* FALLTHROUGH */
3612 	case KEY_RSA_CERT:
3613 		if ((r = sshbuf_get_bignum2(buf, &rsa_d)) != 0 ||
3614 		    (r = sshbuf_get_bignum2(buf, &rsa_iqmp)) != 0 ||
3615 		    (r = sshbuf_get_bignum2(buf, &rsa_p)) != 0 ||
3616 		    (r = sshbuf_get_bignum2(buf, &rsa_q)) != 0)
3617 			goto out;
3618 		if (!RSA_set0_key(k->rsa, NULL, NULL, rsa_d)) {
3619 			r = SSH_ERR_LIBCRYPTO_ERROR;
3620 			goto out;
3621 		}
3622 		rsa_d = NULL; /* transferred */
3623 		if (!RSA_set0_factors(k->rsa, rsa_p, rsa_q)) {
3624 			r = SSH_ERR_LIBCRYPTO_ERROR;
3625 			goto out;
3626 		}
3627 		rsa_p = rsa_q = NULL; /* transferred */
3628 		if ((r = check_rsa_length(k->rsa)) != 0)
3629 			goto out;
3630 		if ((r = ssh_rsa_complete_crt_parameters(k, rsa_iqmp)) != 0)
3631 			goto out;
3632 		break;
3633 #endif /* WITH_OPENSSL */
3634 	case KEY_ED25519:
3635 	case KEY_ED25519_CERT:
3636 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
3637 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
3638 			goto out;
3639 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
3640 			r = SSH_ERR_INVALID_FORMAT;
3641 			goto out;
3642 		}
3643 		k->ed25519_pk = ed25519_pk;
3644 		k->ed25519_sk = ed25519_sk;
3645 		ed25519_pk = ed25519_sk = NULL; /* transferred */
3646 		break;
3647 	case KEY_ED25519_SK:
3648 	case KEY_ED25519_SK_CERT:
3649 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0)
3650 			goto out;
3651 		if (pklen != ED25519_PK_SZ) {
3652 			r = SSH_ERR_INVALID_FORMAT;
3653 			goto out;
3654 		}
3655 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3656 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3657 			r = SSH_ERR_ALLOC_FAIL;
3658 			goto out;
3659 		}
3660 		if ((r = sshbuf_get_cstring(buf, &k->sk_application,
3661 		    NULL)) != 0 ||
3662 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3663 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3664 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3665 			goto out;
3666 		k->ed25519_pk = ed25519_pk;
3667 		ed25519_pk = NULL; /* transferred */
3668 		break;
3669 #ifdef WITH_XMSS
3670 	case KEY_XMSS:
3671 	case KEY_XMSS_CERT:
3672 		if ((r = sshbuf_get_cstring(buf, &xmss_name, NULL)) != 0 ||
3673 		    (r = sshbuf_get_string(buf, &xmss_pk, &pklen)) != 0 ||
3674 		    (r = sshbuf_get_string(buf, &xmss_sk, &sklen)) != 0)
3675 			goto out;
3676 		if (type == KEY_XMSS &&
3677 		    (r = sshkey_xmss_init(k, xmss_name)) != 0)
3678 			goto out;
3679 		if (pklen != sshkey_xmss_pklen(k) ||
3680 		    sklen != sshkey_xmss_sklen(k)) {
3681 			r = SSH_ERR_INVALID_FORMAT;
3682 			goto out;
3683 		}
3684 		k->xmss_pk = xmss_pk;
3685 		k->xmss_sk = xmss_sk;
3686 		xmss_pk = xmss_sk = NULL;
3687 		/* optional internal state */
3688 		if ((r = sshkey_xmss_deserialize_state_opt(k, buf)) != 0)
3689 			goto out;
3690 		break;
3691 #endif /* WITH_XMSS */
3692 	default:
3693 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
3694 		goto out;
3695 	}
3696 #ifdef WITH_OPENSSL
3697 	/* enable blinding */
3698 	switch (k->type) {
3699 	case KEY_RSA:
3700 	case KEY_RSA_CERT:
3701 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
3702 			r = SSH_ERR_LIBCRYPTO_ERROR;
3703 			goto out;
3704 		}
3705 		break;
3706 	}
3707 #endif /* WITH_OPENSSL */
3708 	if ((expect_sk_application != NULL && (k->sk_application == NULL ||
3709 	    strcmp(expect_sk_application, k->sk_application) != 0)) ||
3710 	    (expect_ed25519_pk != NULL && (k->ed25519_pk == NULL ||
3711 	    memcmp(expect_ed25519_pk, k->ed25519_pk, ED25519_PK_SZ) != 0))) {
3712 		r = SSH_ERR_KEY_CERT_MISMATCH;
3713 		goto out;
3714 	}
3715 	/* success */
3716 	r = 0;
3717 	if (kp != NULL) {
3718 		*kp = k;
3719 		k = NULL;
3720 	}
3721  out:
3722 	free(tname);
3723 	free(curve);
3724 #ifdef WITH_OPENSSL
3725 	BN_clear_free(exponent);
3726 	BN_clear_free(dsa_p);
3727 	BN_clear_free(dsa_q);
3728 	BN_clear_free(dsa_g);
3729 	BN_clear_free(dsa_pub_key);
3730 	BN_clear_free(dsa_priv_key);
3731 	BN_clear_free(rsa_n);
3732 	BN_clear_free(rsa_e);
3733 	BN_clear_free(rsa_d);
3734 	BN_clear_free(rsa_p);
3735 	BN_clear_free(rsa_q);
3736 	BN_clear_free(rsa_iqmp);
3737 #endif /* WITH_OPENSSL */
3738 	sshkey_free(k);
3739 	freezero(ed25519_pk, pklen);
3740 	freezero(ed25519_sk, sklen);
3741 	free(xmss_name);
3742 	freezero(xmss_pk, pklen);
3743 	freezero(xmss_sk, sklen);
3744 	free(expect_sk_application);
3745 	free(expect_ed25519_pk);
3746 	return r;
3747 }
3748 
3749 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
3750 int
3751 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
3752 {
3753 	EC_POINT *nq = NULL;
3754 	BIGNUM *order = NULL, *x = NULL, *y = NULL, *tmp = NULL;
3755 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
3756 
3757 	/*
3758 	 * NB. This assumes OpenSSL has already verified that the public
3759 	 * point lies on the curve. This is done by EC_POINT_oct2point()
3760 	 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
3761 	 * reachable with public points not unmarshalled using
3762 	 * EC_POINT_oct2point then the caller will need to explicitly check.
3763 	 */
3764 
3765 	/*
3766 	 * We shouldn't ever hit this case because bignum_get_ecpoint()
3767 	 * refuses to load GF2m points.
3768 	 */
3769 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3770 	    NID_X9_62_prime_field)
3771 		goto out;
3772 
3773 	/* Q != infinity */
3774 	if (EC_POINT_is_at_infinity(group, public))
3775 		goto out;
3776 
3777 	if ((x = BN_new()) == NULL ||
3778 	    (y = BN_new()) == NULL ||
3779 	    (order = BN_new()) == NULL ||
3780 	    (tmp = BN_new()) == NULL) {
3781 		ret = SSH_ERR_ALLOC_FAIL;
3782 		goto out;
3783 	}
3784 
3785 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
3786 	if (EC_GROUP_get_order(group, order, NULL) != 1 ||
3787 	    EC_POINT_get_affine_coordinates_GFp(group, public,
3788 	    x, y, NULL) != 1) {
3789 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3790 		goto out;
3791 	}
3792 	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
3793 	    BN_num_bits(y) <= BN_num_bits(order) / 2)
3794 		goto out;
3795 
3796 	/* nQ == infinity (n == order of subgroup) */
3797 	if ((nq = EC_POINT_new(group)) == NULL) {
3798 		ret = SSH_ERR_ALLOC_FAIL;
3799 		goto out;
3800 	}
3801 	if (EC_POINT_mul(group, nq, NULL, public, order, NULL) != 1) {
3802 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3803 		goto out;
3804 	}
3805 	if (EC_POINT_is_at_infinity(group, nq) != 1)
3806 		goto out;
3807 
3808 	/* x < order - 1, y < order - 1 */
3809 	if (!BN_sub(tmp, order, BN_value_one())) {
3810 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3811 		goto out;
3812 	}
3813 	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
3814 		goto out;
3815 	ret = 0;
3816  out:
3817 	BN_clear_free(x);
3818 	BN_clear_free(y);
3819 	BN_clear_free(order);
3820 	BN_clear_free(tmp);
3821 	EC_POINT_free(nq);
3822 	return ret;
3823 }
3824 
3825 int
3826 sshkey_ec_validate_private(const EC_KEY *key)
3827 {
3828 	BIGNUM *order = NULL, *tmp = NULL;
3829 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
3830 
3831 	if ((order = BN_new()) == NULL || (tmp = BN_new()) == NULL) {
3832 		ret = SSH_ERR_ALLOC_FAIL;
3833 		goto out;
3834 	}
3835 
3836 	/* log2(private) > log2(order)/2 */
3837 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) {
3838 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3839 		goto out;
3840 	}
3841 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
3842 	    BN_num_bits(order) / 2)
3843 		goto out;
3844 
3845 	/* private < order - 1 */
3846 	if (!BN_sub(tmp, order, BN_value_one())) {
3847 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3848 		goto out;
3849 	}
3850 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
3851 		goto out;
3852 	ret = 0;
3853  out:
3854 	BN_clear_free(order);
3855 	BN_clear_free(tmp);
3856 	return ret;
3857 }
3858 
3859 void
3860 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
3861 {
3862 	BIGNUM *x = NULL, *y = NULL;
3863 
3864 	if (point == NULL) {
3865 		fputs("point=(NULL)\n", stderr);
3866 		return;
3867 	}
3868 	if ((x = BN_new()) == NULL || (y = BN_new()) == NULL) {
3869 		fprintf(stderr, "%s: BN_new failed\n", __func__);
3870 		goto out;
3871 	}
3872 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3873 	    NID_X9_62_prime_field) {
3874 		fprintf(stderr, "%s: group is not a prime field\n", __func__);
3875 		goto out;
3876 	}
3877 	if (EC_POINT_get_affine_coordinates_GFp(group, point,
3878 	    x, y, NULL) != 1) {
3879 		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
3880 		    __func__);
3881 		goto out;
3882 	}
3883 	fputs("x=", stderr);
3884 	BN_print_fp(stderr, x);
3885 	fputs("\ny=", stderr);
3886 	BN_print_fp(stderr, y);
3887 	fputs("\n", stderr);
3888  out:
3889 	BN_clear_free(x);
3890 	BN_clear_free(y);
3891 }
3892 
3893 void
3894 sshkey_dump_ec_key(const EC_KEY *key)
3895 {
3896 	const BIGNUM *exponent;
3897 
3898 	sshkey_dump_ec_point(EC_KEY_get0_group(key),
3899 	    EC_KEY_get0_public_key(key));
3900 	fputs("exponent=", stderr);
3901 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3902 		fputs("(NULL)", stderr);
3903 	else
3904 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3905 	fputs("\n", stderr);
3906 }
3907 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3908 
3909 static int
3910 sshkey_private_to_blob2(struct sshkey *prv, struct sshbuf *blob,
3911     const char *passphrase, const char *comment, const char *ciphername,
3912     int rounds)
3913 {
3914 	u_char *cp, *key = NULL, *pubkeyblob = NULL;
3915 	u_char salt[SALT_LEN];
3916 	char *b64 = NULL;
3917 	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3918 	u_int check;
3919 	int r = SSH_ERR_INTERNAL_ERROR;
3920 	struct sshcipher_ctx *ciphercontext = NULL;
3921 	const struct sshcipher *cipher;
3922 	const char *kdfname = KDFNAME;
3923 	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3924 
3925 	if (rounds <= 0)
3926 		rounds = DEFAULT_ROUNDS;
3927 	if (passphrase == NULL || !strlen(passphrase)) {
3928 		ciphername = "none";
3929 		kdfname = "none";
3930 	} else if (ciphername == NULL)
3931 		ciphername = DEFAULT_CIPHERNAME;
3932 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3933 		r = SSH_ERR_INVALID_ARGUMENT;
3934 		goto out;
3935 	}
3936 
3937 	if ((kdf = sshbuf_new()) == NULL ||
3938 	    (encoded = sshbuf_new()) == NULL ||
3939 	    (encrypted = sshbuf_new()) == NULL) {
3940 		r = SSH_ERR_ALLOC_FAIL;
3941 		goto out;
3942 	}
3943 	blocksize = cipher_blocksize(cipher);
3944 	keylen = cipher_keylen(cipher);
3945 	ivlen = cipher_ivlen(cipher);
3946 	authlen = cipher_authlen(cipher);
3947 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3948 		r = SSH_ERR_ALLOC_FAIL;
3949 		goto out;
3950 	}
3951 	if (strcmp(kdfname, "bcrypt") == 0) {
3952 		arc4random_buf(salt, SALT_LEN);
3953 		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3954 		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3955 			r = SSH_ERR_INVALID_ARGUMENT;
3956 			goto out;
3957 		}
3958 		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3959 		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
3960 			goto out;
3961 	} else if (strcmp(kdfname, "none") != 0) {
3962 		/* Unsupported KDF type */
3963 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3964 		goto out;
3965 	}
3966 	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3967 	    key + keylen, ivlen, 1)) != 0)
3968 		goto out;
3969 
3970 	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3971 	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3972 	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3973 	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3974 	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
3975 	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3976 	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
3977 		goto out;
3978 
3979 	/* set up the buffer that will be encrypted */
3980 
3981 	/* Random check bytes */
3982 	check = arc4random();
3983 	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
3984 	    (r = sshbuf_put_u32(encrypted, check)) != 0)
3985 		goto out;
3986 
3987 	/* append private key and comment*/
3988 	if ((r = sshkey_private_serialize_opt(prv, encrypted,
3989 	    SSHKEY_SERIALIZE_FULL)) != 0 ||
3990 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
3991 		goto out;
3992 
3993 	/* padding */
3994 	i = 0;
3995 	while (sshbuf_len(encrypted) % blocksize) {
3996 		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
3997 			goto out;
3998 	}
3999 
4000 	/* length in destination buffer */
4001 	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
4002 		goto out;
4003 
4004 	/* encrypt */
4005 	if ((r = sshbuf_reserve(encoded,
4006 	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
4007 		goto out;
4008 	if ((r = cipher_crypt(ciphercontext, 0, cp,
4009 	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
4010 		goto out;
4011 
4012 	sshbuf_reset(blob);
4013 
4014 	/* assemble uuencoded key */
4015 	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0 ||
4016 	    (r = sshbuf_dtob64(encoded, blob, 1)) != 0 ||
4017 	    (r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
4018 		goto out;
4019 
4020 	/* success */
4021 	r = 0;
4022 
4023  out:
4024 	sshbuf_free(kdf);
4025 	sshbuf_free(encoded);
4026 	sshbuf_free(encrypted);
4027 	cipher_free(ciphercontext);
4028 	explicit_bzero(salt, sizeof(salt));
4029 	if (key != NULL)
4030 		freezero(key, keylen + ivlen);
4031 	if (pubkeyblob != NULL)
4032 		freezero(pubkeyblob, pubkeylen);
4033 	if (b64 != NULL)
4034 		freezero(b64, strlen(b64));
4035 	return r;
4036 }
4037 
4038 static int
4039 private2_uudecode(struct sshbuf *blob, struct sshbuf **decodedp)
4040 {
4041 	const u_char *cp;
4042 	size_t encoded_len;
4043 	int r;
4044 	u_char last;
4045 	struct sshbuf *encoded = NULL, *decoded = NULL;
4046 
4047 	if (blob == NULL || decodedp == NULL)
4048 		return SSH_ERR_INVALID_ARGUMENT;
4049 
4050 	*decodedp = NULL;
4051 
4052 	if ((encoded = sshbuf_new()) == NULL ||
4053 	    (decoded = sshbuf_new()) == NULL) {
4054 		r = SSH_ERR_ALLOC_FAIL;
4055 		goto out;
4056 	}
4057 
4058 	/* check preamble */
4059 	cp = sshbuf_ptr(blob);
4060 	encoded_len = sshbuf_len(blob);
4061 	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
4062 	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
4063 		r = SSH_ERR_INVALID_FORMAT;
4064 		goto out;
4065 	}
4066 	cp += MARK_BEGIN_LEN;
4067 	encoded_len -= MARK_BEGIN_LEN;
4068 
4069 	/* Look for end marker, removing whitespace as we go */
4070 	while (encoded_len > 0) {
4071 		if (*cp != '\n' && *cp != '\r') {
4072 			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
4073 				goto out;
4074 		}
4075 		last = *cp;
4076 		encoded_len--;
4077 		cp++;
4078 		if (last == '\n') {
4079 			if (encoded_len >= MARK_END_LEN &&
4080 			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
4081 				/* \0 terminate */
4082 				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
4083 					goto out;
4084 				break;
4085 			}
4086 		}
4087 	}
4088 	if (encoded_len == 0) {
4089 		r = SSH_ERR_INVALID_FORMAT;
4090 		goto out;
4091 	}
4092 
4093 	/* decode base64 */
4094 	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
4095 		goto out;
4096 
4097 	/* check magic */
4098 	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
4099 	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
4100 		r = SSH_ERR_INVALID_FORMAT;
4101 		goto out;
4102 	}
4103 	/* success */
4104 	*decodedp = decoded;
4105 	decoded = NULL;
4106 	r = 0;
4107  out:
4108 	sshbuf_free(encoded);
4109 	sshbuf_free(decoded);
4110 	return r;
4111 }
4112 
4113 static int
4114 private2_decrypt(struct sshbuf *decoded, const char *passphrase,
4115     struct sshbuf **decryptedp, struct sshkey **pubkeyp)
4116 {
4117 	char *ciphername = NULL, *kdfname = NULL;
4118 	const struct sshcipher *cipher = NULL;
4119 	int r = SSH_ERR_INTERNAL_ERROR;
4120 	size_t keylen = 0, ivlen = 0, authlen = 0, slen = 0;
4121 	struct sshbuf *kdf = NULL, *decrypted = NULL;
4122 	struct sshcipher_ctx *ciphercontext = NULL;
4123 	struct sshkey *pubkey = NULL;
4124 	u_char *key = NULL, *salt = NULL, *dp;
4125 	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
4126 
4127 	if (decoded == NULL || decryptedp == NULL || pubkeyp == NULL)
4128 		return SSH_ERR_INVALID_ARGUMENT;
4129 
4130 	*decryptedp = NULL;
4131 	*pubkeyp = NULL;
4132 
4133 	if ((decrypted = sshbuf_new()) == NULL) {
4134 		r = SSH_ERR_ALLOC_FAIL;
4135 		goto out;
4136 	}
4137 
4138 	/* parse public portion of key */
4139 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
4140 	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
4141 	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
4142 	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
4143 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
4144 		goto out;
4145 
4146 	if (nkeys != 1) {
4147 		/* XXX only one key supported at present */
4148 		r = SSH_ERR_INVALID_FORMAT;
4149 		goto out;
4150 	}
4151 
4152 	if ((r = sshkey_froms(decoded, &pubkey)) != 0 ||
4153 	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
4154 		goto out;
4155 
4156 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
4157 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
4158 		goto out;
4159 	}
4160 	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
4161 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
4162 		goto out;
4163 	}
4164 	if (strcmp(kdfname, "none") == 0 && strcmp(ciphername, "none") != 0) {
4165 		r = SSH_ERR_INVALID_FORMAT;
4166 		goto out;
4167 	}
4168 	if ((passphrase == NULL || strlen(passphrase) == 0) &&
4169 	    strcmp(kdfname, "none") != 0) {
4170 		/* passphrase required */
4171 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4172 		goto out;
4173 	}
4174 
4175 	/* check size of encrypted key blob */
4176 	blocksize = cipher_blocksize(cipher);
4177 	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
4178 		r = SSH_ERR_INVALID_FORMAT;
4179 		goto out;
4180 	}
4181 
4182 	/* setup key */
4183 	keylen = cipher_keylen(cipher);
4184 	ivlen = cipher_ivlen(cipher);
4185 	authlen = cipher_authlen(cipher);
4186 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
4187 		r = SSH_ERR_ALLOC_FAIL;
4188 		goto out;
4189 	}
4190 	if (strcmp(kdfname, "bcrypt") == 0) {
4191 		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
4192 		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
4193 			goto out;
4194 		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
4195 		    key, keylen + ivlen, rounds) < 0) {
4196 			r = SSH_ERR_INVALID_FORMAT;
4197 			goto out;
4198 		}
4199 	}
4200 
4201 	/* check that an appropriate amount of auth data is present */
4202 	if (sshbuf_len(decoded) < authlen ||
4203 	    sshbuf_len(decoded) - authlen < encrypted_len) {
4204 		r = SSH_ERR_INVALID_FORMAT;
4205 		goto out;
4206 	}
4207 
4208 	/* decrypt private portion of key */
4209 	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
4210 	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
4211 	    key + keylen, ivlen, 0)) != 0)
4212 		goto out;
4213 	if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
4214 	    encrypted_len, 0, authlen)) != 0) {
4215 		/* an integrity error here indicates an incorrect passphrase */
4216 		if (r == SSH_ERR_MAC_INVALID)
4217 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4218 		goto out;
4219 	}
4220 	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
4221 		goto out;
4222 	/* there should be no trailing data */
4223 	if (sshbuf_len(decoded) != 0) {
4224 		r = SSH_ERR_INVALID_FORMAT;
4225 		goto out;
4226 	}
4227 
4228 	/* check check bytes */
4229 	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
4230 	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
4231 		goto out;
4232 	if (check1 != check2) {
4233 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4234 		goto out;
4235 	}
4236 	/* success */
4237 	*decryptedp = decrypted;
4238 	decrypted = NULL;
4239 	*pubkeyp = pubkey;
4240 	pubkey = NULL;
4241 	r = 0;
4242  out:
4243 	cipher_free(ciphercontext);
4244 	free(ciphername);
4245 	free(kdfname);
4246 	sshkey_free(pubkey);
4247 	if (salt != NULL) {
4248 		explicit_bzero(salt, slen);
4249 		free(salt);
4250 	}
4251 	if (key != NULL) {
4252 		explicit_bzero(key, keylen + ivlen);
4253 		free(key);
4254 	}
4255 	sshbuf_free(kdf);
4256 	sshbuf_free(decrypted);
4257 	return r;
4258 }
4259 
4260 /* Check deterministic padding after private key */
4261 static int
4262 private2_check_padding(struct sshbuf *decrypted)
4263 {
4264 	u_char pad;
4265 	size_t i;
4266 	int r = SSH_ERR_INTERNAL_ERROR;
4267 
4268 	i = 0;
4269 	while (sshbuf_len(decrypted)) {
4270 		if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
4271 			goto out;
4272 		if (pad != (++i & 0xff)) {
4273 			r = SSH_ERR_INVALID_FORMAT;
4274 			goto out;
4275 		}
4276 	}
4277 	/* success */
4278 	r = 0;
4279  out:
4280 	explicit_bzero(&pad, sizeof(pad));
4281 	explicit_bzero(&i, sizeof(i));
4282 	return r;
4283 }
4284 
4285 static int
4286 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
4287     struct sshkey **keyp, char **commentp)
4288 {
4289 	char *comment = NULL;
4290 	int r = SSH_ERR_INTERNAL_ERROR;
4291 	struct sshbuf *decoded = NULL, *decrypted = NULL;
4292 	struct sshkey *k = NULL, *pubkey = NULL;
4293 
4294 	if (keyp != NULL)
4295 		*keyp = NULL;
4296 	if (commentp != NULL)
4297 		*commentp = NULL;
4298 
4299 	/* Undo base64 encoding and decrypt the private section */
4300 	if ((r = private2_uudecode(blob, &decoded)) != 0 ||
4301 	    (r = private2_decrypt(decoded, passphrase,
4302 	    &decrypted, &pubkey)) != 0)
4303 		goto out;
4304 
4305 	if (type != KEY_UNSPEC &&
4306 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
4307 		r = SSH_ERR_KEY_TYPE_MISMATCH;
4308 		goto out;
4309 	}
4310 
4311 	/* Load the private key and comment */
4312 	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
4313 	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
4314 		goto out;
4315 
4316 	/* Check deterministic padding after private section */
4317 	if ((r = private2_check_padding(decrypted)) != 0)
4318 		goto out;
4319 
4320 	/* Check that the public key in the envelope matches the private key */
4321 	if (!sshkey_equal(pubkey, k)) {
4322 		r = SSH_ERR_INVALID_FORMAT;
4323 		goto out;
4324 	}
4325 
4326 	/* success */
4327 	r = 0;
4328 	if (keyp != NULL) {
4329 		*keyp = k;
4330 		k = NULL;
4331 	}
4332 	if (commentp != NULL) {
4333 		*commentp = comment;
4334 		comment = NULL;
4335 	}
4336  out:
4337 	free(comment);
4338 	sshbuf_free(decoded);
4339 	sshbuf_free(decrypted);
4340 	sshkey_free(k);
4341 	sshkey_free(pubkey);
4342 	return r;
4343 }
4344 
4345 static int
4346 sshkey_parse_private2_pubkey(struct sshbuf *blob, int type,
4347     struct sshkey **keyp)
4348 {
4349 	int r = SSH_ERR_INTERNAL_ERROR;
4350 	struct sshbuf *decoded = NULL;
4351 	struct sshkey *pubkey = NULL;
4352 	u_int nkeys = 0;
4353 
4354 	if (keyp != NULL)
4355 		*keyp = NULL;
4356 
4357 	if ((r = private2_uudecode(blob, &decoded)) != 0)
4358 		goto out;
4359 	/* parse public key from unencrypted envelope */
4360 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
4361 	    (r = sshbuf_skip_string(decoded)) != 0 || /* cipher */
4362 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF alg */
4363 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF hint */
4364 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
4365 		goto out;
4366 
4367 	if (nkeys != 1) {
4368 		/* XXX only one key supported at present */
4369 		r = SSH_ERR_INVALID_FORMAT;
4370 		goto out;
4371 	}
4372 
4373 	/* Parse the public key */
4374 	if ((r = sshkey_froms(decoded, &pubkey)) != 0)
4375 		goto out;
4376 
4377 	if (type != KEY_UNSPEC &&
4378 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
4379 		r = SSH_ERR_KEY_TYPE_MISMATCH;
4380 		goto out;
4381 	}
4382 
4383 	/* success */
4384 	r = 0;
4385 	if (keyp != NULL) {
4386 		*keyp = pubkey;
4387 		pubkey = NULL;
4388 	}
4389  out:
4390 	sshbuf_free(decoded);
4391 	sshkey_free(pubkey);
4392 	return r;
4393 }
4394 
4395 #ifdef WITH_OPENSSL
4396 /* convert SSH v2 key to PEM or PKCS#8 format */
4397 static int
4398 sshkey_private_to_blob_pem_pkcs8(struct sshkey *key, struct sshbuf *buf,
4399     int format, const char *_passphrase, const char *comment)
4400 {
4401 	int was_shielded = sshkey_is_shielded(key);
4402 	int success, r;
4403 	int blen, len = strlen(_passphrase);
4404 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
4405 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
4406 	char *bptr;
4407 	BIO *bio = NULL;
4408 	struct sshbuf *blob;
4409 	EVP_PKEY *pkey = NULL;
4410 
4411 	if (len > 0 && len <= 4)
4412 		return SSH_ERR_PASSPHRASE_TOO_SHORT;
4413 	if ((blob = sshbuf_new()) == NULL)
4414 		return SSH_ERR_ALLOC_FAIL;
4415 	if ((bio = BIO_new(BIO_s_mem())) == NULL) {
4416 		r = SSH_ERR_ALLOC_FAIL;
4417 		goto out;
4418 	}
4419 	if (format == SSHKEY_PRIVATE_PKCS8 && (pkey = EVP_PKEY_new()) == NULL) {
4420 		r = SSH_ERR_ALLOC_FAIL;
4421 		goto out;
4422 	}
4423 	if ((r = sshkey_unshield_private(key)) != 0)
4424 		goto out;
4425 
4426 	switch (key->type) {
4427 	case KEY_DSA:
4428 		if (format == SSHKEY_PRIVATE_PEM) {
4429 			success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
4430 			    cipher, passphrase, len, NULL, NULL);
4431 		} else {
4432 			success = EVP_PKEY_set1_DSA(pkey, key->dsa);
4433 		}
4434 		break;
4435 #ifdef OPENSSL_HAS_ECC
4436 	case KEY_ECDSA:
4437 		if (format == SSHKEY_PRIVATE_PEM) {
4438 			success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
4439 			    cipher, passphrase, len, NULL, NULL);
4440 		} else {
4441 			success = EVP_PKEY_set1_EC_KEY(pkey, key->ecdsa);
4442 		}
4443 		break;
4444 #endif
4445 	case KEY_RSA:
4446 		if (format == SSHKEY_PRIVATE_PEM) {
4447 			success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
4448 			    cipher, passphrase, len, NULL, NULL);
4449 		} else {
4450 			success = EVP_PKEY_set1_RSA(pkey, key->rsa);
4451 		}
4452 		break;
4453 	default:
4454 		success = 0;
4455 		break;
4456 	}
4457 	if (success == 0) {
4458 		r = SSH_ERR_LIBCRYPTO_ERROR;
4459 		goto out;
4460 	}
4461 	if (format == SSHKEY_PRIVATE_PKCS8) {
4462 		if ((success = PEM_write_bio_PrivateKey(bio, pkey, cipher,
4463 		    passphrase, len, NULL, NULL)) == 0) {
4464 			r = SSH_ERR_LIBCRYPTO_ERROR;
4465 			goto out;
4466 		}
4467 	}
4468 	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
4469 		r = SSH_ERR_INTERNAL_ERROR;
4470 		goto out;
4471 	}
4472 	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
4473 		goto out;
4474 	r = 0;
4475  out:
4476 	if (was_shielded)
4477 		r = sshkey_shield_private(key);
4478 	if (r == 0)
4479 		r = sshbuf_putb(buf, blob);
4480 
4481 	EVP_PKEY_free(pkey);
4482 	sshbuf_free(blob);
4483 	BIO_free(bio);
4484 	return r;
4485 }
4486 #endif /* WITH_OPENSSL */
4487 
4488 /* Serialise "key" to buffer "blob" */
4489 int
4490 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
4491     const char *passphrase, const char *comment,
4492     int format, const char *openssh_format_cipher, int openssh_format_rounds)
4493 {
4494 	switch (key->type) {
4495 #ifdef WITH_OPENSSL
4496 	case KEY_DSA:
4497 	case KEY_ECDSA:
4498 	case KEY_RSA:
4499 		break; /* see below */
4500 #endif /* WITH_OPENSSL */
4501 	case KEY_ED25519:
4502 	case KEY_ED25519_SK:
4503 #ifdef WITH_XMSS
4504 	case KEY_XMSS:
4505 #endif /* WITH_XMSS */
4506 #ifdef WITH_OPENSSL
4507 	case KEY_ECDSA_SK:
4508 #endif /* WITH_OPENSSL */
4509 		return sshkey_private_to_blob2(key, blob, passphrase,
4510 		    comment, openssh_format_cipher, openssh_format_rounds);
4511 	default:
4512 		return SSH_ERR_KEY_TYPE_UNKNOWN;
4513 	}
4514 
4515 #ifdef WITH_OPENSSL
4516 	switch (format) {
4517 	case SSHKEY_PRIVATE_OPENSSH:
4518 		return sshkey_private_to_blob2(key, blob, passphrase,
4519 		    comment, openssh_format_cipher, openssh_format_rounds);
4520 	case SSHKEY_PRIVATE_PEM:
4521 	case SSHKEY_PRIVATE_PKCS8:
4522 		return sshkey_private_to_blob_pem_pkcs8(key, blob,
4523 		    format, passphrase, comment);
4524 	default:
4525 		return SSH_ERR_INVALID_ARGUMENT;
4526 	}
4527 #endif /* WITH_OPENSSL */
4528 }
4529 
4530 #ifdef WITH_OPENSSL
4531 static int
4532 translate_libcrypto_error(unsigned long pem_err)
4533 {
4534 	int pem_reason = ERR_GET_REASON(pem_err);
4535 
4536 	switch (ERR_GET_LIB(pem_err)) {
4537 	case ERR_LIB_PEM:
4538 		switch (pem_reason) {
4539 		case PEM_R_BAD_PASSWORD_READ:
4540 		case PEM_R_PROBLEMS_GETTING_PASSWORD:
4541 		case PEM_R_BAD_DECRYPT:
4542 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
4543 		default:
4544 			return SSH_ERR_INVALID_FORMAT;
4545 		}
4546 	case ERR_LIB_EVP:
4547 		switch (pem_reason) {
4548 		case EVP_R_BAD_DECRYPT:
4549 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
4550 #ifdef EVP_R_BN_DECODE_ERROR
4551 		case EVP_R_BN_DECODE_ERROR:
4552 #endif
4553 		case EVP_R_DECODE_ERROR:
4554 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
4555 		case EVP_R_PRIVATE_KEY_DECODE_ERROR:
4556 #endif
4557 			return SSH_ERR_INVALID_FORMAT;
4558 		default:
4559 			return SSH_ERR_LIBCRYPTO_ERROR;
4560 		}
4561 	case ERR_LIB_ASN1:
4562 		return SSH_ERR_INVALID_FORMAT;
4563 	}
4564 	return SSH_ERR_LIBCRYPTO_ERROR;
4565 }
4566 
4567 static void
4568 clear_libcrypto_errors(void)
4569 {
4570 	while (ERR_get_error() != 0)
4571 		;
4572 }
4573 
4574 /*
4575  * Translate OpenSSL error codes to determine whether
4576  * passphrase is required/incorrect.
4577  */
4578 static int
4579 convert_libcrypto_error(void)
4580 {
4581 	/*
4582 	 * Some password errors are reported at the beginning
4583 	 * of the error queue.
4584 	 */
4585 	if (translate_libcrypto_error(ERR_peek_error()) ==
4586 	    SSH_ERR_KEY_WRONG_PASSPHRASE)
4587 		return SSH_ERR_KEY_WRONG_PASSPHRASE;
4588 	return translate_libcrypto_error(ERR_peek_last_error());
4589 }
4590 
4591 static int
4592 pem_passphrase_cb(char *buf, int size, int rwflag, void *u)
4593 {
4594 	char *p = (char *)u;
4595 	size_t len;
4596 
4597 	if (p == NULL || (len = strlen(p)) == 0)
4598 		return -1;
4599 	if (size < 0 || len > (size_t)size)
4600 		return -1;
4601 	memcpy(buf, p, len);
4602 	return (int)len;
4603 }
4604 
4605 static int
4606 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
4607     const char *passphrase, struct sshkey **keyp)
4608 {
4609 	EVP_PKEY *pk = NULL;
4610 	struct sshkey *prv = NULL;
4611 	BIO *bio = NULL;
4612 	int r;
4613 
4614 	if (keyp != NULL)
4615 		*keyp = NULL;
4616 
4617 	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
4618 		return SSH_ERR_ALLOC_FAIL;
4619 	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
4620 	    (int)sshbuf_len(blob)) {
4621 		r = SSH_ERR_ALLOC_FAIL;
4622 		goto out;
4623 	}
4624 
4625 	clear_libcrypto_errors();
4626 	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, pem_passphrase_cb,
4627 	    (char *)passphrase)) == NULL) {
4628 		/*
4629 		 * libcrypto may return various ASN.1 errors when attempting
4630 		 * to parse a key with an incorrect passphrase.
4631 		 * Treat all format errors as "incorrect passphrase" if a
4632 		 * passphrase was supplied.
4633 		 */
4634 		if (passphrase != NULL && *passphrase != '\0')
4635 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4636 		else
4637 			r = convert_libcrypto_error();
4638 		goto out;
4639 	}
4640 	if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA &&
4641 	    (type == KEY_UNSPEC || type == KEY_RSA)) {
4642 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4643 			r = SSH_ERR_ALLOC_FAIL;
4644 			goto out;
4645 		}
4646 		prv->rsa = EVP_PKEY_get1_RSA(pk);
4647 		prv->type = KEY_RSA;
4648 #ifdef DEBUG_PK
4649 		RSA_print_fp(stderr, prv->rsa, 8);
4650 #endif
4651 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
4652 			r = SSH_ERR_LIBCRYPTO_ERROR;
4653 			goto out;
4654 		}
4655 		if ((r = check_rsa_length(prv->rsa)) != 0)
4656 			goto out;
4657 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_DSA &&
4658 	    (type == KEY_UNSPEC || type == KEY_DSA)) {
4659 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4660 			r = SSH_ERR_ALLOC_FAIL;
4661 			goto out;
4662 		}
4663 		prv->dsa = EVP_PKEY_get1_DSA(pk);
4664 		prv->type = KEY_DSA;
4665 #ifdef DEBUG_PK
4666 		DSA_print_fp(stderr, prv->dsa, 8);
4667 #endif
4668 #ifdef OPENSSL_HAS_ECC
4669 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_EC &&
4670 	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
4671 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4672 			r = SSH_ERR_ALLOC_FAIL;
4673 			goto out;
4674 		}
4675 		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
4676 		prv->type = KEY_ECDSA;
4677 		prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
4678 		if (prv->ecdsa_nid == -1 ||
4679 		    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
4680 		    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
4681 		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
4682 		    sshkey_ec_validate_private(prv->ecdsa) != 0) {
4683 			r = SSH_ERR_INVALID_FORMAT;
4684 			goto out;
4685 		}
4686 # ifdef DEBUG_PK
4687 		if (prv != NULL && prv->ecdsa != NULL)
4688 			sshkey_dump_ec_key(prv->ecdsa);
4689 # endif
4690 #endif /* OPENSSL_HAS_ECC */
4691 	} else {
4692 		r = SSH_ERR_INVALID_FORMAT;
4693 		goto out;
4694 	}
4695 	r = 0;
4696 	if (keyp != NULL) {
4697 		*keyp = prv;
4698 		prv = NULL;
4699 	}
4700  out:
4701 	BIO_free(bio);
4702 	EVP_PKEY_free(pk);
4703 	sshkey_free(prv);
4704 	return r;
4705 }
4706 #endif /* WITH_OPENSSL */
4707 
4708 int
4709 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
4710     const char *passphrase, struct sshkey **keyp, char **commentp)
4711 {
4712 	int r = SSH_ERR_INTERNAL_ERROR;
4713 
4714 	if (keyp != NULL)
4715 		*keyp = NULL;
4716 	if (commentp != NULL)
4717 		*commentp = NULL;
4718 
4719 	switch (type) {
4720 	case KEY_ED25519:
4721 	case KEY_XMSS:
4722 		/* No fallback for new-format-only keys */
4723 		return sshkey_parse_private2(blob, type, passphrase,
4724 		    keyp, commentp);
4725 	default:
4726 		r = sshkey_parse_private2(blob, type, passphrase, keyp,
4727 		    commentp);
4728 		/* Only fallback to PEM parser if a format error occurred. */
4729 		if (r != SSH_ERR_INVALID_FORMAT)
4730 			return r;
4731 #ifdef WITH_OPENSSL
4732 		return sshkey_parse_private_pem_fileblob(blob, type,
4733 		    passphrase, keyp);
4734 #else
4735 		return SSH_ERR_INVALID_FORMAT;
4736 #endif /* WITH_OPENSSL */
4737 	}
4738 }
4739 
4740 int
4741 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
4742     struct sshkey **keyp, char **commentp)
4743 {
4744 	if (keyp != NULL)
4745 		*keyp = NULL;
4746 	if (commentp != NULL)
4747 		*commentp = NULL;
4748 
4749 	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
4750 	    passphrase, keyp, commentp);
4751 }
4752 
4753 void
4754 sshkey_sig_details_free(struct sshkey_sig_details *details)
4755 {
4756 	freezero(details, sizeof(*details));
4757 }
4758 
4759 int
4760 sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf *blob, int type,
4761     struct sshkey **pubkeyp)
4762 {
4763 	int r = SSH_ERR_INTERNAL_ERROR;
4764 
4765 	if (pubkeyp != NULL)
4766 		*pubkeyp = NULL;
4767 	/* only new-format private keys bundle a public key inside */
4768 	if ((r = sshkey_parse_private2_pubkey(blob, type, pubkeyp)) != 0)
4769 		return r;
4770 	return 0;
4771 }
4772 
4773 #ifdef WITH_XMSS
4774 /*
4775  * serialize the key with the current state and forward the state
4776  * maxsign times.
4777  */
4778 int
4779 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
4780     u_int32_t maxsign, int printerror)
4781 {
4782 	int r, rupdate;
4783 
4784 	if (maxsign == 0 ||
4785 	    sshkey_type_plain(k->type) != KEY_XMSS)
4786 		return sshkey_private_serialize_opt(k, b,
4787 		    SSHKEY_SERIALIZE_DEFAULT);
4788 	if ((r = sshkey_xmss_get_state(k, printerror)) != 0 ||
4789 	    (r = sshkey_private_serialize_opt(k, b,
4790 	    SSHKEY_SERIALIZE_STATE)) != 0 ||
4791 	    (r = sshkey_xmss_forward_state(k, maxsign)) != 0)
4792 		goto out;
4793 	r = 0;
4794 out:
4795 	if ((rupdate = sshkey_xmss_update_state(k, printerror)) != 0) {
4796 		if (r == 0)
4797 			r = rupdate;
4798 	}
4799 	return r;
4800 }
4801 
4802 u_int32_t
4803 sshkey_signatures_left(const struct sshkey *k)
4804 {
4805 	if (sshkey_type_plain(k->type) == KEY_XMSS)
4806 		return sshkey_xmss_signatures_left(k);
4807 	return 0;
4808 }
4809 
4810 int
4811 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
4812 {
4813 	if (sshkey_type_plain(k->type) != KEY_XMSS)
4814 		return SSH_ERR_INVALID_ARGUMENT;
4815 	return sshkey_xmss_enable_maxsign(k, maxsign);
4816 }
4817 
4818 int
4819 sshkey_set_filename(struct sshkey *k, const char *filename)
4820 {
4821 	if (k == NULL)
4822 		return SSH_ERR_INVALID_ARGUMENT;
4823 	if (sshkey_type_plain(k->type) != KEY_XMSS)
4824 		return 0;
4825 	if (filename == NULL)
4826 		return SSH_ERR_INVALID_ARGUMENT;
4827 	if ((k->xmss_filename = strdup(filename)) == NULL)
4828 		return SSH_ERR_ALLOC_FAIL;
4829 	return 0;
4830 }
4831 #else
4832 int
4833 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
4834     u_int32_t maxsign, int printerror)
4835 {
4836 	return sshkey_private_serialize_opt(k, b, SSHKEY_SERIALIZE_DEFAULT);
4837 }
4838 
4839 u_int32_t
4840 sshkey_signatures_left(const struct sshkey *k)
4841 {
4842 	return 0;
4843 }
4844 
4845 int
4846 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
4847 {
4848 	return SSH_ERR_INVALID_ARGUMENT;
4849 }
4850 
4851 int
4852 sshkey_set_filename(struct sshkey *k, const char *filename)
4853 {
4854 	if (k == NULL)
4855 		return SSH_ERR_INVALID_ARGUMENT;
4856 	return 0;
4857 }
4858 #endif /* WITH_XMSS */
4859