xref: /freebsd/crypto/openssh/sshkey.c (revision 657729a89dd578d8cfc70d6616f5c65a48a8b33a)
1 /* $OpenBSD: sshkey.c,v 1.122 2022/09/17 10:30:45 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 /* Check deterministic padding after private key */
2129 static int
2130 private2_check_padding(struct sshbuf *decrypted)
2131 {
2132 	u_char pad;
2133 	size_t i;
2134 	int r;
2135 
2136 	i = 0;
2137 	while (sshbuf_len(decrypted)) {
2138 		if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
2139 			goto out;
2140 		if (pad != (++i & 0xff)) {
2141 			r = SSH_ERR_INVALID_FORMAT;
2142 			goto out;
2143 		}
2144 	}
2145 	/* success */
2146 	r = 0;
2147  out:
2148 	explicit_bzero(&pad, sizeof(pad));
2149 	explicit_bzero(&i, sizeof(i));
2150 	return r;
2151 }
2152 
2153 int
2154 sshkey_unshield_private(struct sshkey *k)
2155 {
2156 	struct sshbuf *prvbuf = NULL;
2157 	u_char *cp, keyiv[SSH_DIGEST_MAX_LENGTH];
2158 	struct sshcipher_ctx *cctx = NULL;
2159 	const struct sshcipher *cipher;
2160 	struct sshkey *kswap = NULL, tmp;
2161 	int r = SSH_ERR_INTERNAL_ERROR;
2162 
2163 #ifdef DEBUG_PK
2164 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
2165 #endif
2166 	if (!sshkey_is_shielded(k))
2167 		return 0; /* nothing to do */
2168 
2169 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2170 		r = SSH_ERR_INVALID_ARGUMENT;
2171 		goto out;
2172 	}
2173 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2174 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2175 		r = SSH_ERR_INTERNAL_ERROR;
2176 		goto out;
2177 	}
2178 	/* check size of shielded key blob */
2179 	if (k->shielded_len < cipher_blocksize(cipher) ||
2180 	    (k->shielded_len % cipher_blocksize(cipher)) != 0) {
2181 		r = SSH_ERR_INVALID_FORMAT;
2182 		goto out;
2183 	}
2184 
2185 	/* Calculate the ephemeral key from the prekey */
2186 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2187 	    k->shield_prekey, k->shield_prekey_len,
2188 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2189 		goto out;
2190 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2191 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0)) != 0)
2192 		goto out;
2193 #ifdef DEBUG_PK
2194 	fprintf(stderr, "%s: key+iv\n", __func__);
2195 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2196 	    stderr);
2197 #endif
2198 
2199 	/* Decrypt and parse the shielded private key using the ephemeral key */
2200 	if ((prvbuf = sshbuf_new()) == NULL) {
2201 		r = SSH_ERR_ALLOC_FAIL;
2202 		goto out;
2203 	}
2204 	if ((r = sshbuf_reserve(prvbuf, k->shielded_len, &cp)) != 0)
2205 		goto out;
2206 	/* decrypt */
2207 #ifdef DEBUG_PK
2208 	fprintf(stderr, "%s: encrypted\n", __func__);
2209 	sshbuf_dump_data(k->shielded_private, k->shielded_len, stderr);
2210 #endif
2211 	if ((r = cipher_crypt(cctx, 0, cp,
2212 	    k->shielded_private, k->shielded_len, 0, 0)) != 0)
2213 		goto out;
2214 #ifdef DEBUG_PK
2215 	fprintf(stderr, "%s: serialised\n", __func__);
2216 	sshbuf_dump(prvbuf, stderr);
2217 #endif
2218 	/* Parse private key */
2219 	if ((r = sshkey_private_deserialize(prvbuf, &kswap)) != 0)
2220 		goto out;
2221 
2222 	if ((r = private2_check_padding(prvbuf)) != 0)
2223 		goto out;
2224 
2225 	/* Swap the parsed key back into place */
2226 	tmp = *kswap;
2227 	*kswap = *k;
2228 	*k = tmp;
2229 
2230 	/* success */
2231 	r = 0;
2232 
2233  out:
2234 	cipher_free(cctx);
2235 	explicit_bzero(keyiv, sizeof(keyiv));
2236 	explicit_bzero(&tmp, sizeof(tmp));
2237 	sshkey_free(kswap);
2238 	sshbuf_free(prvbuf);
2239 	return r;
2240 }
2241 
2242 static int
2243 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
2244 {
2245 	struct sshbuf *principals = NULL, *crit = NULL;
2246 	struct sshbuf *exts = NULL, *ca = NULL;
2247 	u_char *sig = NULL;
2248 	size_t signed_len = 0, slen = 0, kidlen = 0;
2249 	int ret = SSH_ERR_INTERNAL_ERROR;
2250 
2251 	/* Copy the entire key blob for verification and later serialisation */
2252 	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
2253 		return ret;
2254 
2255 	/* Parse body of certificate up to signature */
2256 	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
2257 	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
2258 	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
2259 	    (ret = sshbuf_froms(b, &principals)) != 0 ||
2260 	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
2261 	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
2262 	    (ret = sshbuf_froms(b, &crit)) != 0 ||
2263 	    (ret = sshbuf_froms(b, &exts)) != 0 ||
2264 	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
2265 	    (ret = sshbuf_froms(b, &ca)) != 0) {
2266 		/* XXX debug print error for ret */
2267 		ret = SSH_ERR_INVALID_FORMAT;
2268 		goto out;
2269 	}
2270 
2271 	/* Signature is left in the buffer so we can calculate this length */
2272 	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
2273 
2274 	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
2275 		ret = SSH_ERR_INVALID_FORMAT;
2276 		goto out;
2277 	}
2278 
2279 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
2280 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
2281 		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
2282 		goto out;
2283 	}
2284 
2285 	/* Parse principals section */
2286 	while (sshbuf_len(principals) > 0) {
2287 		char *principal = NULL;
2288 		char **oprincipals = NULL;
2289 
2290 		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
2291 			ret = SSH_ERR_INVALID_FORMAT;
2292 			goto out;
2293 		}
2294 		if ((ret = sshbuf_get_cstring(principals, &principal,
2295 		    NULL)) != 0) {
2296 			ret = SSH_ERR_INVALID_FORMAT;
2297 			goto out;
2298 		}
2299 		oprincipals = key->cert->principals;
2300 		key->cert->principals = recallocarray(key->cert->principals,
2301 		    key->cert->nprincipals, key->cert->nprincipals + 1,
2302 		    sizeof(*key->cert->principals));
2303 		if (key->cert->principals == NULL) {
2304 			free(principal);
2305 			key->cert->principals = oprincipals;
2306 			ret = SSH_ERR_ALLOC_FAIL;
2307 			goto out;
2308 		}
2309 		key->cert->principals[key->cert->nprincipals++] = principal;
2310 	}
2311 
2312 	/*
2313 	 * Stash a copies of the critical options and extensions sections
2314 	 * for later use.
2315 	 */
2316 	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
2317 	    (exts != NULL &&
2318 	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
2319 		goto out;
2320 
2321 	/*
2322 	 * Validate critical options and extensions sections format.
2323 	 */
2324 	while (sshbuf_len(crit) != 0) {
2325 		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
2326 		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
2327 			sshbuf_reset(key->cert->critical);
2328 			ret = SSH_ERR_INVALID_FORMAT;
2329 			goto out;
2330 		}
2331 	}
2332 	while (exts != NULL && sshbuf_len(exts) != 0) {
2333 		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
2334 		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
2335 			sshbuf_reset(key->cert->extensions);
2336 			ret = SSH_ERR_INVALID_FORMAT;
2337 			goto out;
2338 		}
2339 	}
2340 
2341 	/* Parse CA key and check signature */
2342 	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
2343 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2344 		goto out;
2345 	}
2346 	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
2347 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2348 		goto out;
2349 	}
2350 	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
2351 	    sshbuf_ptr(key->cert->certblob), signed_len, NULL, 0, NULL)) != 0)
2352 		goto out;
2353 	if ((ret = sshkey_get_sigtype(sig, slen,
2354 	    &key->cert->signature_type)) != 0)
2355 		goto out;
2356 
2357 	/* Success */
2358 	ret = 0;
2359  out:
2360 	sshbuf_free(ca);
2361 	sshbuf_free(crit);
2362 	sshbuf_free(exts);
2363 	sshbuf_free(principals);
2364 	free(sig);
2365 	return ret;
2366 }
2367 
2368 int
2369 sshkey_check_rsa_length(const struct sshkey *k, int min_size)
2370 {
2371 #ifdef WITH_OPENSSL
2372 	const BIGNUM *rsa_n;
2373 	int nbits;
2374 
2375 	if (k == NULL || k->rsa == NULL ||
2376 	    (k->type != KEY_RSA && k->type != KEY_RSA_CERT))
2377 		return 0;
2378 	RSA_get0_key(k->rsa, &rsa_n, NULL, NULL);
2379 	nbits = BN_num_bits(rsa_n);
2380 	if (nbits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
2381 	    (min_size > 0 && nbits < min_size))
2382 		return SSH_ERR_KEY_LENGTH;
2383 #endif /* WITH_OPENSSL */
2384 	return 0;
2385 }
2386 
2387 static int
2388 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
2389     int allow_cert)
2390 {
2391 	int type, ret = SSH_ERR_INTERNAL_ERROR;
2392 	char *ktype = NULL, *curve = NULL, *xmss_name = NULL;
2393 	struct sshkey *key = NULL;
2394 	size_t len;
2395 	u_char *pk = NULL;
2396 	struct sshbuf *copy;
2397 #if defined(WITH_OPENSSL)
2398 	BIGNUM *rsa_n = NULL, *rsa_e = NULL;
2399 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL, *dsa_pub_key = NULL;
2400 # if defined(OPENSSL_HAS_ECC)
2401 	EC_POINT *q = NULL;
2402 # endif /* OPENSSL_HAS_ECC */
2403 #endif /* WITH_OPENSSL */
2404 
2405 #ifdef DEBUG_PK /* XXX */
2406 	sshbuf_dump(b, stderr);
2407 #endif
2408 	if (keyp != NULL)
2409 		*keyp = NULL;
2410 	if ((copy = sshbuf_fromb(b)) == NULL) {
2411 		ret = SSH_ERR_ALLOC_FAIL;
2412 		goto out;
2413 	}
2414 	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
2415 		ret = SSH_ERR_INVALID_FORMAT;
2416 		goto out;
2417 	}
2418 
2419 	type = sshkey_type_from_name(ktype);
2420 	if (!allow_cert && sshkey_type_is_cert(type)) {
2421 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2422 		goto out;
2423 	}
2424 	switch (type) {
2425 #ifdef WITH_OPENSSL
2426 	case KEY_RSA_CERT:
2427 		/* Skip nonce */
2428 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2429 			ret = SSH_ERR_INVALID_FORMAT;
2430 			goto out;
2431 		}
2432 		/* FALLTHROUGH */
2433 	case KEY_RSA:
2434 		if ((key = sshkey_new(type)) == NULL) {
2435 			ret = SSH_ERR_ALLOC_FAIL;
2436 			goto out;
2437 		}
2438 		if (sshbuf_get_bignum2(b, &rsa_e) != 0 ||
2439 		    sshbuf_get_bignum2(b, &rsa_n) != 0) {
2440 			ret = SSH_ERR_INVALID_FORMAT;
2441 			goto out;
2442 		}
2443 		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, NULL)) {
2444 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2445 			goto out;
2446 		}
2447 		rsa_n = rsa_e = NULL; /* transferred */
2448 		if ((ret = sshkey_check_rsa_length(key, 0)) != 0)
2449 			goto out;
2450 #ifdef DEBUG_PK
2451 		RSA_print_fp(stderr, key->rsa, 8);
2452 #endif
2453 		break;
2454 	case KEY_DSA_CERT:
2455 		/* Skip nonce */
2456 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2457 			ret = SSH_ERR_INVALID_FORMAT;
2458 			goto out;
2459 		}
2460 		/* FALLTHROUGH */
2461 	case KEY_DSA:
2462 		if ((key = sshkey_new(type)) == NULL) {
2463 			ret = SSH_ERR_ALLOC_FAIL;
2464 			goto out;
2465 		}
2466 		if (sshbuf_get_bignum2(b, &dsa_p) != 0 ||
2467 		    sshbuf_get_bignum2(b, &dsa_q) != 0 ||
2468 		    sshbuf_get_bignum2(b, &dsa_g) != 0 ||
2469 		    sshbuf_get_bignum2(b, &dsa_pub_key) != 0) {
2470 			ret = SSH_ERR_INVALID_FORMAT;
2471 			goto out;
2472 		}
2473 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g)) {
2474 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2475 			goto out;
2476 		}
2477 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
2478 		if (!DSA_set0_key(key->dsa, dsa_pub_key, NULL)) {
2479 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2480 			goto out;
2481 		}
2482 		dsa_pub_key = NULL; /* transferred */
2483 #ifdef DEBUG_PK
2484 		DSA_print_fp(stderr, key->dsa, 8);
2485 #endif
2486 		break;
2487 # ifdef OPENSSL_HAS_ECC
2488 	case KEY_ECDSA_CERT:
2489 	case KEY_ECDSA_SK_CERT:
2490 		/* Skip nonce */
2491 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2492 			ret = SSH_ERR_INVALID_FORMAT;
2493 			goto out;
2494 		}
2495 		/* FALLTHROUGH */
2496 	case KEY_ECDSA:
2497 	case KEY_ECDSA_SK:
2498 		if ((key = sshkey_new(type)) == NULL) {
2499 			ret = SSH_ERR_ALLOC_FAIL;
2500 			goto out;
2501 		}
2502 		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2503 		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2504 			ret = SSH_ERR_INVALID_FORMAT;
2505 			goto out;
2506 		}
2507 		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2508 			ret = SSH_ERR_EC_CURVE_MISMATCH;
2509 			goto out;
2510 		}
2511 		EC_KEY_free(key->ecdsa);
2512 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2513 		    == NULL) {
2514 			ret = SSH_ERR_EC_CURVE_INVALID;
2515 			goto out;
2516 		}
2517 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2518 			ret = SSH_ERR_ALLOC_FAIL;
2519 			goto out;
2520 		}
2521 		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2522 			ret = SSH_ERR_INVALID_FORMAT;
2523 			goto out;
2524 		}
2525 		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2526 		    q) != 0) {
2527 			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2528 			goto out;
2529 		}
2530 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2531 			/* XXX assume it is a allocation error */
2532 			ret = SSH_ERR_ALLOC_FAIL;
2533 			goto out;
2534 		}
2535 #ifdef DEBUG_PK
2536 		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2537 #endif
2538 		if (type == KEY_ECDSA_SK || type == KEY_ECDSA_SK_CERT) {
2539 			/* Parse additional security-key application string */
2540 			if (sshbuf_get_cstring(b, &key->sk_application,
2541 			    NULL) != 0) {
2542 				ret = SSH_ERR_INVALID_FORMAT;
2543 				goto out;
2544 			}
2545 #ifdef DEBUG_PK
2546 			fprintf(stderr, "App: %s\n", key->sk_application);
2547 #endif
2548 		}
2549 		break;
2550 # endif /* OPENSSL_HAS_ECC */
2551 #endif /* WITH_OPENSSL */
2552 	case KEY_ED25519_CERT:
2553 	case KEY_ED25519_SK_CERT:
2554 		/* Skip nonce */
2555 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2556 			ret = SSH_ERR_INVALID_FORMAT;
2557 			goto out;
2558 		}
2559 		/* FALLTHROUGH */
2560 	case KEY_ED25519:
2561 	case KEY_ED25519_SK:
2562 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2563 			goto out;
2564 		if (len != ED25519_PK_SZ) {
2565 			ret = SSH_ERR_INVALID_FORMAT;
2566 			goto out;
2567 		}
2568 		if ((key = sshkey_new(type)) == NULL) {
2569 			ret = SSH_ERR_ALLOC_FAIL;
2570 			goto out;
2571 		}
2572 		if (type == KEY_ED25519_SK || type == KEY_ED25519_SK_CERT) {
2573 			/* Parse additional security-key application string */
2574 			if (sshbuf_get_cstring(b, &key->sk_application,
2575 			    NULL) != 0) {
2576 				ret = SSH_ERR_INVALID_FORMAT;
2577 				goto out;
2578 			}
2579 #ifdef DEBUG_PK
2580 			fprintf(stderr, "App: %s\n", key->sk_application);
2581 #endif
2582 		}
2583 		key->ed25519_pk = pk;
2584 		pk = NULL;
2585 		break;
2586 #ifdef WITH_XMSS
2587 	case KEY_XMSS_CERT:
2588 		/* Skip nonce */
2589 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2590 			ret = SSH_ERR_INVALID_FORMAT;
2591 			goto out;
2592 		}
2593 		/* FALLTHROUGH */
2594 	case KEY_XMSS:
2595 		if ((ret = sshbuf_get_cstring(b, &xmss_name, NULL)) != 0)
2596 			goto out;
2597 		if ((key = sshkey_new(type)) == NULL) {
2598 			ret = SSH_ERR_ALLOC_FAIL;
2599 			goto out;
2600 		}
2601 		if ((ret = sshkey_xmss_init(key, xmss_name)) != 0)
2602 			goto out;
2603 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2604 			goto out;
2605 		if (len == 0 || len != sshkey_xmss_pklen(key)) {
2606 			ret = SSH_ERR_INVALID_FORMAT;
2607 			goto out;
2608 		}
2609 		key->xmss_pk = pk;
2610 		pk = NULL;
2611 		if (type != KEY_XMSS_CERT &&
2612 		    (ret = sshkey_xmss_deserialize_pk_info(key, b)) != 0)
2613 			goto out;
2614 		break;
2615 #endif /* WITH_XMSS */
2616 	case KEY_UNSPEC:
2617 	default:
2618 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2619 		goto out;
2620 	}
2621 
2622 	/* Parse certificate potion */
2623 	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2624 		goto out;
2625 
2626 	if (key != NULL && sshbuf_len(b) != 0) {
2627 		ret = SSH_ERR_INVALID_FORMAT;
2628 		goto out;
2629 	}
2630 	ret = 0;
2631 	if (keyp != NULL) {
2632 		*keyp = key;
2633 		key = NULL;
2634 	}
2635  out:
2636 	sshbuf_free(copy);
2637 	sshkey_free(key);
2638 	free(xmss_name);
2639 	free(ktype);
2640 	free(curve);
2641 	free(pk);
2642 #if defined(WITH_OPENSSL)
2643 	BN_clear_free(rsa_n);
2644 	BN_clear_free(rsa_e);
2645 	BN_clear_free(dsa_p);
2646 	BN_clear_free(dsa_q);
2647 	BN_clear_free(dsa_g);
2648 	BN_clear_free(dsa_pub_key);
2649 # if defined(OPENSSL_HAS_ECC)
2650 	EC_POINT_free(q);
2651 # endif /* OPENSSL_HAS_ECC */
2652 #endif /* WITH_OPENSSL */
2653 	return ret;
2654 }
2655 
2656 int
2657 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2658 {
2659 	struct sshbuf *b;
2660 	int r;
2661 
2662 	if ((b = sshbuf_from(blob, blen)) == NULL)
2663 		return SSH_ERR_ALLOC_FAIL;
2664 	r = sshkey_from_blob_internal(b, keyp, 1);
2665 	sshbuf_free(b);
2666 	return r;
2667 }
2668 
2669 int
2670 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2671 {
2672 	return sshkey_from_blob_internal(b, keyp, 1);
2673 }
2674 
2675 int
2676 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2677 {
2678 	struct sshbuf *b;
2679 	int r;
2680 
2681 	if ((r = sshbuf_froms(buf, &b)) != 0)
2682 		return r;
2683 	r = sshkey_from_blob_internal(b, keyp, 1);
2684 	sshbuf_free(b);
2685 	return r;
2686 }
2687 
2688 int
2689 sshkey_get_sigtype(const u_char *sig, size_t siglen, char **sigtypep)
2690 {
2691 	int r;
2692 	struct sshbuf *b = NULL;
2693 	char *sigtype = NULL;
2694 
2695 	if (sigtypep != NULL)
2696 		*sigtypep = NULL;
2697 	if ((b = sshbuf_from(sig, siglen)) == NULL)
2698 		return SSH_ERR_ALLOC_FAIL;
2699 	if ((r = sshbuf_get_cstring(b, &sigtype, NULL)) != 0)
2700 		goto out;
2701 	/* success */
2702 	if (sigtypep != NULL) {
2703 		*sigtypep = sigtype;
2704 		sigtype = NULL;
2705 	}
2706 	r = 0;
2707  out:
2708 	free(sigtype);
2709 	sshbuf_free(b);
2710 	return r;
2711 }
2712 
2713 /*
2714  *
2715  * Checks whether a certificate's signature type is allowed.
2716  * Returns 0 (success) if the certificate signature type appears in the
2717  * "allowed" pattern-list, or the key is not a certificate to begin with.
2718  * Otherwise returns a ssherr.h code.
2719  */
2720 int
2721 sshkey_check_cert_sigtype(const struct sshkey *key, const char *allowed)
2722 {
2723 	if (key == NULL || allowed == NULL)
2724 		return SSH_ERR_INVALID_ARGUMENT;
2725 	if (!sshkey_type_is_cert(key->type))
2726 		return 0;
2727 	if (key->cert == NULL || key->cert->signature_type == NULL)
2728 		return SSH_ERR_INVALID_ARGUMENT;
2729 	if (match_pattern_list(key->cert->signature_type, allowed, 0) != 1)
2730 		return SSH_ERR_SIGN_ALG_UNSUPPORTED;
2731 	return 0;
2732 }
2733 
2734 /*
2735  * Returns the expected signature algorithm for a given public key algorithm.
2736  */
2737 const char *
2738 sshkey_sigalg_by_name(const char *name)
2739 {
2740 	const struct keytype *kt;
2741 
2742 	for (kt = keytypes; kt->type != -1; kt++) {
2743 		if (strcmp(kt->name, name) != 0)
2744 			continue;
2745 		if (kt->sigalg != NULL)
2746 			return kt->sigalg;
2747 		if (!kt->cert)
2748 			return kt->name;
2749 		return sshkey_ssh_name_from_type_nid(
2750 		    sshkey_type_plain(kt->type), kt->nid);
2751 	}
2752 	return NULL;
2753 }
2754 
2755 /*
2756  * Verifies that the signature algorithm appearing inside the signature blob
2757  * matches that which was requested.
2758  */
2759 int
2760 sshkey_check_sigtype(const u_char *sig, size_t siglen,
2761     const char *requested_alg)
2762 {
2763 	const char *expected_alg;
2764 	char *sigtype = NULL;
2765 	int r;
2766 
2767 	if (requested_alg == NULL)
2768 		return 0;
2769 	if ((expected_alg = sshkey_sigalg_by_name(requested_alg)) == NULL)
2770 		return SSH_ERR_INVALID_ARGUMENT;
2771 	if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0)
2772 		return r;
2773 	r = strcmp(expected_alg, sigtype) == 0;
2774 	free(sigtype);
2775 	return r ? 0 : SSH_ERR_SIGN_ALG_UNSUPPORTED;
2776 }
2777 
2778 int
2779 sshkey_sign(struct sshkey *key,
2780     u_char **sigp, size_t *lenp,
2781     const u_char *data, size_t datalen,
2782     const char *alg, const char *sk_provider, const char *sk_pin, u_int compat)
2783 {
2784 	int was_shielded = sshkey_is_shielded(key);
2785 	int r2, r = SSH_ERR_INTERNAL_ERROR;
2786 
2787 	if (sigp != NULL)
2788 		*sigp = NULL;
2789 	if (lenp != NULL)
2790 		*lenp = 0;
2791 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2792 		return SSH_ERR_INVALID_ARGUMENT;
2793 	if ((r = sshkey_unshield_private(key)) != 0)
2794 		return r;
2795 	switch (key->type) {
2796 #ifdef WITH_OPENSSL
2797 	case KEY_DSA_CERT:
2798 	case KEY_DSA:
2799 		r = ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2800 		break;
2801 # ifdef OPENSSL_HAS_ECC
2802 	case KEY_ECDSA_CERT:
2803 	case KEY_ECDSA:
2804 		r = ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2805 		break;
2806 # endif /* OPENSSL_HAS_ECC */
2807 	case KEY_RSA_CERT:
2808 	case KEY_RSA:
2809 		r = ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2810 		break;
2811 #endif /* WITH_OPENSSL */
2812 	case KEY_ED25519:
2813 	case KEY_ED25519_CERT:
2814 		r = ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2815 		break;
2816 	case KEY_ED25519_SK:
2817 	case KEY_ED25519_SK_CERT:
2818 	case KEY_ECDSA_SK_CERT:
2819 	case KEY_ECDSA_SK:
2820 		r = sshsk_sign(sk_provider, key, sigp, lenp, data,
2821 		    datalen, compat, sk_pin);
2822 		break;
2823 #ifdef WITH_XMSS
2824 	case KEY_XMSS:
2825 	case KEY_XMSS_CERT:
2826 		r = ssh_xmss_sign(key, sigp, lenp, data, datalen, compat);
2827 		break;
2828 #endif /* WITH_XMSS */
2829 	default:
2830 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2831 		break;
2832 	}
2833 	if (was_shielded && (r2 = sshkey_shield_private(key)) != 0)
2834 		return r2;
2835 	return r;
2836 }
2837 
2838 /*
2839  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2840  * If "alg" specified, then the signature must use that algorithm.
2841  */
2842 int
2843 sshkey_verify(const struct sshkey *key,
2844     const u_char *sig, size_t siglen,
2845     const u_char *data, size_t dlen, const char *alg, u_int compat,
2846     struct sshkey_sig_details **detailsp)
2847 {
2848 	if (detailsp != NULL)
2849 		*detailsp = NULL;
2850 	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2851 		return SSH_ERR_INVALID_ARGUMENT;
2852 	switch (key->type) {
2853 #ifdef WITH_OPENSSL
2854 	case KEY_DSA_CERT:
2855 	case KEY_DSA:
2856 		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2857 # ifdef OPENSSL_HAS_ECC
2858 	case KEY_ECDSA_CERT:
2859 	case KEY_ECDSA:
2860 		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2861 	case KEY_ECDSA_SK_CERT:
2862 	case KEY_ECDSA_SK:
2863 		return ssh_ecdsa_sk_verify(key, sig, siglen, data, dlen,
2864 		    compat, detailsp);
2865 # endif /* OPENSSL_HAS_ECC */
2866 	case KEY_RSA_CERT:
2867 	case KEY_RSA:
2868 		return ssh_rsa_verify(key, sig, siglen, data, dlen, alg);
2869 #endif /* WITH_OPENSSL */
2870 	case KEY_ED25519:
2871 	case KEY_ED25519_CERT:
2872 		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2873 	case KEY_ED25519_SK:
2874 	case KEY_ED25519_SK_CERT:
2875 		return ssh_ed25519_sk_verify(key, sig, siglen, data, dlen,
2876 		    compat, detailsp);
2877 #ifdef WITH_XMSS
2878 	case KEY_XMSS:
2879 	case KEY_XMSS_CERT:
2880 		return ssh_xmss_verify(key, sig, siglen, data, dlen, compat);
2881 #endif /* WITH_XMSS */
2882 	default:
2883 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2884 	}
2885 }
2886 
2887 /* Convert a plain key to their _CERT equivalent */
2888 int
2889 sshkey_to_certified(struct sshkey *k)
2890 {
2891 	int newtype;
2892 
2893 	switch (k->type) {
2894 #ifdef WITH_OPENSSL
2895 	case KEY_RSA:
2896 		newtype = KEY_RSA_CERT;
2897 		break;
2898 	case KEY_DSA:
2899 		newtype = KEY_DSA_CERT;
2900 		break;
2901 	case KEY_ECDSA:
2902 		newtype = KEY_ECDSA_CERT;
2903 		break;
2904 	case KEY_ECDSA_SK:
2905 		newtype = KEY_ECDSA_SK_CERT;
2906 		break;
2907 #endif /* WITH_OPENSSL */
2908 	case KEY_ED25519_SK:
2909 		newtype = KEY_ED25519_SK_CERT;
2910 		break;
2911 	case KEY_ED25519:
2912 		newtype = KEY_ED25519_CERT;
2913 		break;
2914 #ifdef WITH_XMSS
2915 	case KEY_XMSS:
2916 		newtype = KEY_XMSS_CERT;
2917 		break;
2918 #endif /* WITH_XMSS */
2919 	default:
2920 		return SSH_ERR_INVALID_ARGUMENT;
2921 	}
2922 	if ((k->cert = cert_new()) == NULL)
2923 		return SSH_ERR_ALLOC_FAIL;
2924 	k->type = newtype;
2925 	return 0;
2926 }
2927 
2928 /* Convert a certificate to its raw key equivalent */
2929 int
2930 sshkey_drop_cert(struct sshkey *k)
2931 {
2932 	if (!sshkey_type_is_cert(k->type))
2933 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2934 	cert_free(k->cert);
2935 	k->cert = NULL;
2936 	k->type = sshkey_type_plain(k->type);
2937 	return 0;
2938 }
2939 
2940 /* Sign a certified key, (re-)generating the signed certblob. */
2941 int
2942 sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2943     const char *sk_provider, const char *sk_pin,
2944     sshkey_certify_signer *signer, void *signer_ctx)
2945 {
2946 	struct sshbuf *principals = NULL;
2947 	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2948 	size_t i, ca_len, sig_len;
2949 	int ret = SSH_ERR_INTERNAL_ERROR;
2950 	struct sshbuf *cert = NULL;
2951 	char *sigtype = NULL;
2952 #ifdef WITH_OPENSSL
2953 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
2954 #endif /* WITH_OPENSSL */
2955 
2956 	if (k == NULL || k->cert == NULL ||
2957 	    k->cert->certblob == NULL || ca == NULL)
2958 		return SSH_ERR_INVALID_ARGUMENT;
2959 	if (!sshkey_is_cert(k))
2960 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2961 	if (!sshkey_type_is_valid_ca(ca->type))
2962 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2963 
2964 	/*
2965 	 * If no alg specified as argument but a signature_type was set,
2966 	 * then prefer that. If both were specified, then they must match.
2967 	 */
2968 	if (alg == NULL)
2969 		alg = k->cert->signature_type;
2970 	else if (k->cert->signature_type != NULL &&
2971 	    strcmp(alg, k->cert->signature_type) != 0)
2972 		return SSH_ERR_INVALID_ARGUMENT;
2973 
2974 	/*
2975 	 * If no signing algorithm or signature_type was specified and we're
2976 	 * using a RSA key, then default to a good signature algorithm.
2977 	 */
2978 	if (alg == NULL && ca->type == KEY_RSA)
2979 		alg = "rsa-sha2-512";
2980 
2981 	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2982 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2983 
2984 	cert = k->cert->certblob; /* for readability */
2985 	sshbuf_reset(cert);
2986 	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2987 		goto out;
2988 
2989 	/* -v01 certs put nonce first */
2990 	arc4random_buf(&nonce, sizeof(nonce));
2991 	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2992 		goto out;
2993 
2994 	/* XXX this substantially duplicates to_blob(); refactor */
2995 	switch (k->type) {
2996 #ifdef WITH_OPENSSL
2997 	case KEY_DSA_CERT:
2998 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
2999 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
3000 		if ((ret = sshbuf_put_bignum2(cert, dsa_p)) != 0 ||
3001 		    (ret = sshbuf_put_bignum2(cert, dsa_q)) != 0 ||
3002 		    (ret = sshbuf_put_bignum2(cert, dsa_g)) != 0 ||
3003 		    (ret = sshbuf_put_bignum2(cert, dsa_pub_key)) != 0)
3004 			goto out;
3005 		break;
3006 # ifdef OPENSSL_HAS_ECC
3007 	case KEY_ECDSA_CERT:
3008 	case KEY_ECDSA_SK_CERT:
3009 		if ((ret = sshbuf_put_cstring(cert,
3010 		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
3011 		    (ret = sshbuf_put_ec(cert,
3012 		    EC_KEY_get0_public_key(k->ecdsa),
3013 		    EC_KEY_get0_group(k->ecdsa))) != 0)
3014 			goto out;
3015 		if (k->type == KEY_ECDSA_SK_CERT) {
3016 			if ((ret = sshbuf_put_cstring(cert,
3017 			    k->sk_application)) != 0)
3018 				goto out;
3019 		}
3020 		break;
3021 # endif /* OPENSSL_HAS_ECC */
3022 	case KEY_RSA_CERT:
3023 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
3024 		if ((ret = sshbuf_put_bignum2(cert, rsa_e)) != 0 ||
3025 		    (ret = sshbuf_put_bignum2(cert, rsa_n)) != 0)
3026 			goto out;
3027 		break;
3028 #endif /* WITH_OPENSSL */
3029 	case KEY_ED25519_CERT:
3030 	case KEY_ED25519_SK_CERT:
3031 		if ((ret = sshbuf_put_string(cert,
3032 		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
3033 			goto out;
3034 		if (k->type == KEY_ED25519_SK_CERT) {
3035 			if ((ret = sshbuf_put_cstring(cert,
3036 			    k->sk_application)) != 0)
3037 				goto out;
3038 		}
3039 		break;
3040 #ifdef WITH_XMSS
3041 	case KEY_XMSS_CERT:
3042 		if (k->xmss_name == NULL) {
3043 			ret = SSH_ERR_INVALID_ARGUMENT;
3044 			goto out;
3045 		}
3046 		if ((ret = sshbuf_put_cstring(cert, k->xmss_name)) ||
3047 		    (ret = sshbuf_put_string(cert,
3048 		    k->xmss_pk, sshkey_xmss_pklen(k))) != 0)
3049 			goto out;
3050 		break;
3051 #endif /* WITH_XMSS */
3052 	default:
3053 		ret = SSH_ERR_INVALID_ARGUMENT;
3054 		goto out;
3055 	}
3056 
3057 	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
3058 	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
3059 	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
3060 		goto out;
3061 
3062 	if ((principals = sshbuf_new()) == NULL) {
3063 		ret = SSH_ERR_ALLOC_FAIL;
3064 		goto out;
3065 	}
3066 	for (i = 0; i < k->cert->nprincipals; i++) {
3067 		if ((ret = sshbuf_put_cstring(principals,
3068 		    k->cert->principals[i])) != 0)
3069 			goto out;
3070 	}
3071 	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
3072 	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
3073 	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
3074 	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
3075 	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
3076 	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
3077 	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
3078 		goto out;
3079 
3080 	/* Sign the whole mess */
3081 	if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
3082 	    sshbuf_len(cert), alg, sk_provider, sk_pin, 0, signer_ctx)) != 0)
3083 		goto out;
3084 	/* Check and update signature_type against what was actually used */
3085 	if ((ret = sshkey_get_sigtype(sig_blob, sig_len, &sigtype)) != 0)
3086 		goto out;
3087 	if (alg != NULL && strcmp(alg, sigtype) != 0) {
3088 		ret = SSH_ERR_SIGN_ALG_UNSUPPORTED;
3089 		goto out;
3090 	}
3091 	if (k->cert->signature_type == NULL) {
3092 		k->cert->signature_type = sigtype;
3093 		sigtype = NULL;
3094 	}
3095 	/* Append signature and we are done */
3096 	if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
3097 		goto out;
3098 	ret = 0;
3099  out:
3100 	if (ret != 0)
3101 		sshbuf_reset(cert);
3102 	free(sig_blob);
3103 	free(ca_blob);
3104 	free(sigtype);
3105 	sshbuf_free(principals);
3106 	return ret;
3107 }
3108 
3109 static int
3110 default_key_sign(struct sshkey *key, u_char **sigp, size_t *lenp,
3111     const u_char *data, size_t datalen,
3112     const char *alg, const char *sk_provider, const char *sk_pin,
3113     u_int compat, void *ctx)
3114 {
3115 	if (ctx != NULL)
3116 		return SSH_ERR_INVALID_ARGUMENT;
3117 	return sshkey_sign(key, sigp, lenp, data, datalen, alg,
3118 	    sk_provider, sk_pin, compat);
3119 }
3120 
3121 int
3122 sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg,
3123     const char *sk_provider, const char *sk_pin)
3124 {
3125 	return sshkey_certify_custom(k, ca, alg, sk_provider, sk_pin,
3126 	    default_key_sign, NULL);
3127 }
3128 
3129 int
3130 sshkey_cert_check_authority(const struct sshkey *k,
3131     int want_host, int require_principal, int wildcard_pattern,
3132     uint64_t verify_time, const char *name, const char **reason)
3133 {
3134 	u_int i, principal_matches;
3135 
3136 	if (reason == NULL)
3137 		return SSH_ERR_INVALID_ARGUMENT;
3138 	if (!sshkey_is_cert(k)) {
3139 		*reason = "Key is not a certificate";
3140 		return SSH_ERR_KEY_CERT_INVALID;
3141 	}
3142 	if (want_host) {
3143 		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
3144 			*reason = "Certificate invalid: not a host certificate";
3145 			return SSH_ERR_KEY_CERT_INVALID;
3146 		}
3147 	} else {
3148 		if (k->cert->type != SSH2_CERT_TYPE_USER) {
3149 			*reason = "Certificate invalid: not a user certificate";
3150 			return SSH_ERR_KEY_CERT_INVALID;
3151 		}
3152 	}
3153 	if (verify_time < k->cert->valid_after) {
3154 		*reason = "Certificate invalid: not yet valid";
3155 		return SSH_ERR_KEY_CERT_INVALID;
3156 	}
3157 	if (verify_time >= k->cert->valid_before) {
3158 		*reason = "Certificate invalid: expired";
3159 		return SSH_ERR_KEY_CERT_INVALID;
3160 	}
3161 	if (k->cert->nprincipals == 0) {
3162 		if (require_principal) {
3163 			*reason = "Certificate lacks principal list";
3164 			return SSH_ERR_KEY_CERT_INVALID;
3165 		}
3166 	} else if (name != NULL) {
3167 		principal_matches = 0;
3168 		for (i = 0; i < k->cert->nprincipals; i++) {
3169 			if (wildcard_pattern) {
3170 				if (match_pattern(k->cert->principals[i],
3171 				    name)) {
3172 					principal_matches = 1;
3173 					break;
3174 				}
3175 			} else if (strcmp(name, k->cert->principals[i]) == 0) {
3176 				principal_matches = 1;
3177 				break;
3178 			}
3179 		}
3180 		if (!principal_matches) {
3181 			*reason = "Certificate invalid: name is not a listed "
3182 			    "principal";
3183 			return SSH_ERR_KEY_CERT_INVALID;
3184 		}
3185 	}
3186 	return 0;
3187 }
3188 
3189 int
3190 sshkey_cert_check_authority_now(const struct sshkey *k,
3191     int want_host, int require_principal, int wildcard_pattern,
3192     const char *name, const char **reason)
3193 {
3194 	time_t now;
3195 
3196 	if ((now = time(NULL)) < 0) {
3197 		/* yikes - system clock before epoch! */
3198 		*reason = "Certificate invalid: not yet valid";
3199 		return SSH_ERR_KEY_CERT_INVALID;
3200 	}
3201 	return sshkey_cert_check_authority(k, want_host, require_principal,
3202 	    wildcard_pattern, (uint64_t)now, name, reason);
3203 }
3204 
3205 int
3206 sshkey_cert_check_host(const struct sshkey *key, const char *host,
3207     int wildcard_principals, const char *ca_sign_algorithms,
3208     const char **reason)
3209 {
3210 	int r;
3211 
3212 	if ((r = sshkey_cert_check_authority_now(key, 1, 0, wildcard_principals,
3213 	    host, reason)) != 0)
3214 		return r;
3215 	if (sshbuf_len(key->cert->critical) != 0) {
3216 		*reason = "Certificate contains unsupported critical options";
3217 		return SSH_ERR_KEY_CERT_INVALID;
3218 	}
3219 	if (ca_sign_algorithms != NULL &&
3220 	    (r = sshkey_check_cert_sigtype(key, ca_sign_algorithms)) != 0) {
3221 		*reason = "Certificate signed with disallowed algorithm";
3222 		return SSH_ERR_KEY_CERT_INVALID;
3223 	}
3224 	return 0;
3225 }
3226 
3227 size_t
3228 sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
3229 {
3230 	char from[32], to[32], ret[128];
3231 
3232 	*from = *to = '\0';
3233 	if (cert->valid_after == 0 &&
3234 	    cert->valid_before == 0xffffffffffffffffULL)
3235 		return strlcpy(s, "forever", l);
3236 
3237 	if (cert->valid_after != 0)
3238 		format_absolute_time(cert->valid_after, from, sizeof(from));
3239 	if (cert->valid_before != 0xffffffffffffffffULL)
3240 		format_absolute_time(cert->valid_before, to, sizeof(to));
3241 
3242 	if (cert->valid_after == 0)
3243 		snprintf(ret, sizeof(ret), "before %s", to);
3244 	else if (cert->valid_before == 0xffffffffffffffffULL)
3245 		snprintf(ret, sizeof(ret), "after %s", from);
3246 	else
3247 		snprintf(ret, sizeof(ret), "from %s to %s", from, to);
3248 
3249 	return strlcpy(s, ret, l);
3250 }
3251 
3252 int
3253 sshkey_private_serialize_opt(struct sshkey *key, struct sshbuf *buf,
3254     enum sshkey_serialize_rep opts)
3255 {
3256 	int r = SSH_ERR_INTERNAL_ERROR;
3257 	int was_shielded = sshkey_is_shielded(key);
3258 	struct sshbuf *b = NULL;
3259 #ifdef WITH_OPENSSL
3260 	const BIGNUM *rsa_n, *rsa_e, *rsa_d, *rsa_iqmp, *rsa_p, *rsa_q;
3261 	const BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key, *dsa_priv_key;
3262 #endif /* WITH_OPENSSL */
3263 
3264 	if ((r = sshkey_unshield_private(key)) != 0)
3265 		return r;
3266 	if ((b = sshbuf_new()) == NULL)
3267 		return SSH_ERR_ALLOC_FAIL;
3268 	if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
3269 		goto out;
3270 	switch (key->type) {
3271 #ifdef WITH_OPENSSL
3272 	case KEY_RSA:
3273 		RSA_get0_key(key->rsa, &rsa_n, &rsa_e, &rsa_d);
3274 		RSA_get0_factors(key->rsa, &rsa_p, &rsa_q);
3275 		RSA_get0_crt_params(key->rsa, NULL, NULL, &rsa_iqmp);
3276 		if ((r = sshbuf_put_bignum2(b, rsa_n)) != 0 ||
3277 		    (r = sshbuf_put_bignum2(b, rsa_e)) != 0 ||
3278 		    (r = sshbuf_put_bignum2(b, rsa_d)) != 0 ||
3279 		    (r = sshbuf_put_bignum2(b, rsa_iqmp)) != 0 ||
3280 		    (r = sshbuf_put_bignum2(b, rsa_p)) != 0 ||
3281 		    (r = sshbuf_put_bignum2(b, rsa_q)) != 0)
3282 			goto out;
3283 		break;
3284 	case KEY_RSA_CERT:
3285 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3286 			r = SSH_ERR_INVALID_ARGUMENT;
3287 			goto out;
3288 		}
3289 		RSA_get0_key(key->rsa, NULL, NULL, &rsa_d);
3290 		RSA_get0_factors(key->rsa, &rsa_p, &rsa_q);
3291 		RSA_get0_crt_params(key->rsa, NULL, NULL, &rsa_iqmp);
3292 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3293 		    (r = sshbuf_put_bignum2(b, rsa_d)) != 0 ||
3294 		    (r = sshbuf_put_bignum2(b, rsa_iqmp)) != 0 ||
3295 		    (r = sshbuf_put_bignum2(b, rsa_p)) != 0 ||
3296 		    (r = sshbuf_put_bignum2(b, rsa_q)) != 0)
3297 			goto out;
3298 		break;
3299 	case KEY_DSA:
3300 		DSA_get0_pqg(key->dsa, &dsa_p, &dsa_q, &dsa_g);
3301 		DSA_get0_key(key->dsa, &dsa_pub_key, &dsa_priv_key);
3302 		if ((r = sshbuf_put_bignum2(b, dsa_p)) != 0 ||
3303 		    (r = sshbuf_put_bignum2(b, dsa_q)) != 0 ||
3304 		    (r = sshbuf_put_bignum2(b, dsa_g)) != 0 ||
3305 		    (r = sshbuf_put_bignum2(b, dsa_pub_key)) != 0 ||
3306 		    (r = sshbuf_put_bignum2(b, dsa_priv_key)) != 0)
3307 			goto out;
3308 		break;
3309 	case KEY_DSA_CERT:
3310 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3311 			r = SSH_ERR_INVALID_ARGUMENT;
3312 			goto out;
3313 		}
3314 		DSA_get0_key(key->dsa, NULL, &dsa_priv_key);
3315 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3316 		    (r = sshbuf_put_bignum2(b, dsa_priv_key)) != 0)
3317 			goto out;
3318 		break;
3319 # ifdef OPENSSL_HAS_ECC
3320 	case KEY_ECDSA:
3321 		if ((r = sshbuf_put_cstring(b,
3322 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
3323 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
3324 		    (r = sshbuf_put_bignum2(b,
3325 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
3326 			goto out;
3327 		break;
3328 	case KEY_ECDSA_CERT:
3329 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3330 			r = SSH_ERR_INVALID_ARGUMENT;
3331 			goto out;
3332 		}
3333 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3334 		    (r = sshbuf_put_bignum2(b,
3335 		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
3336 			goto out;
3337 		break;
3338 	case KEY_ECDSA_SK:
3339 		if ((r = sshbuf_put_cstring(b,
3340 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
3341 		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
3342 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3343 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3344 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3345 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3346 			goto out;
3347 		break;
3348 	case KEY_ECDSA_SK_CERT:
3349 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3350 			r = SSH_ERR_INVALID_ARGUMENT;
3351 			goto out;
3352 		}
3353 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3354 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3355 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3356 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3357 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3358 			goto out;
3359 		break;
3360 # endif /* OPENSSL_HAS_ECC */
3361 #endif /* WITH_OPENSSL */
3362 	case KEY_ED25519:
3363 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
3364 		    ED25519_PK_SZ)) != 0 ||
3365 		    (r = sshbuf_put_string(b, key->ed25519_sk,
3366 		    ED25519_SK_SZ)) != 0)
3367 			goto out;
3368 		break;
3369 	case KEY_ED25519_CERT:
3370 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3371 			r = SSH_ERR_INVALID_ARGUMENT;
3372 			goto out;
3373 		}
3374 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3375 		    (r = sshbuf_put_string(b, key->ed25519_pk,
3376 		    ED25519_PK_SZ)) != 0 ||
3377 		    (r = sshbuf_put_string(b, key->ed25519_sk,
3378 		    ED25519_SK_SZ)) != 0)
3379 			goto out;
3380 		break;
3381 	case KEY_ED25519_SK:
3382 		if ((r = sshbuf_put_string(b, key->ed25519_pk,
3383 		    ED25519_PK_SZ)) != 0 ||
3384 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3385 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3386 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3387 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3388 			goto out;
3389 		break;
3390 	case KEY_ED25519_SK_CERT:
3391 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
3392 			r = SSH_ERR_INVALID_ARGUMENT;
3393 			goto out;
3394 		}
3395 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3396 		    (r = sshbuf_put_string(b, key->ed25519_pk,
3397 		    ED25519_PK_SZ)) != 0 ||
3398 		    (r = sshbuf_put_cstring(b, key->sk_application)) != 0 ||
3399 		    (r = sshbuf_put_u8(b, key->sk_flags)) != 0 ||
3400 		    (r = sshbuf_put_stringb(b, key->sk_key_handle)) != 0 ||
3401 		    (r = sshbuf_put_stringb(b, key->sk_reserved)) != 0)
3402 			goto out;
3403 		break;
3404 #ifdef WITH_XMSS
3405 	case KEY_XMSS:
3406 		if (key->xmss_name == NULL) {
3407 			r = SSH_ERR_INVALID_ARGUMENT;
3408 			goto out;
3409 		}
3410 		if ((r = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
3411 		    (r = sshbuf_put_string(b, key->xmss_pk,
3412 		    sshkey_xmss_pklen(key))) != 0 ||
3413 		    (r = sshbuf_put_string(b, key->xmss_sk,
3414 		    sshkey_xmss_sklen(key))) != 0 ||
3415 		    (r = sshkey_xmss_serialize_state_opt(key, b, opts)) != 0)
3416 			goto out;
3417 		break;
3418 	case KEY_XMSS_CERT:
3419 		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0 ||
3420 		    key->xmss_name == NULL) {
3421 			r = SSH_ERR_INVALID_ARGUMENT;
3422 			goto out;
3423 		}
3424 		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
3425 		    (r = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
3426 		    (r = sshbuf_put_string(b, key->xmss_pk,
3427 		    sshkey_xmss_pklen(key))) != 0 ||
3428 		    (r = sshbuf_put_string(b, key->xmss_sk,
3429 		    sshkey_xmss_sklen(key))) != 0 ||
3430 		    (r = sshkey_xmss_serialize_state_opt(key, b, opts)) != 0)
3431 			goto out;
3432 		break;
3433 #endif /* WITH_XMSS */
3434 	default:
3435 		r = SSH_ERR_INVALID_ARGUMENT;
3436 		goto out;
3437 	}
3438 	/*
3439 	 * success (but we still need to append the output to buf after
3440 	 * possibly re-shielding the private key)
3441 	 */
3442 	r = 0;
3443  out:
3444 	if (was_shielded)
3445 		r = sshkey_shield_private(key);
3446 	if (r == 0)
3447 		r = sshbuf_putb(buf, b);
3448 	sshbuf_free(b);
3449 
3450 	return r;
3451 }
3452 
3453 int
3454 sshkey_private_serialize(struct sshkey *key, struct sshbuf *b)
3455 {
3456 	return sshkey_private_serialize_opt(key, b,
3457 	    SSHKEY_SERIALIZE_DEFAULT);
3458 }
3459 
3460 int
3461 sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
3462 {
3463 	char *tname = NULL, *curve = NULL, *xmss_name = NULL;
3464 	char *expect_sk_application = NULL;
3465 	struct sshkey *k = NULL;
3466 	size_t pklen = 0, sklen = 0;
3467 	int type, r = SSH_ERR_INTERNAL_ERROR;
3468 	u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
3469 	u_char *expect_ed25519_pk = NULL;
3470 	u_char *xmss_pk = NULL, *xmss_sk = NULL;
3471 #ifdef WITH_OPENSSL
3472 	BIGNUM *exponent = NULL;
3473 	BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
3474 	BIGNUM *rsa_iqmp = NULL, *rsa_p = NULL, *rsa_q = NULL;
3475 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
3476 	BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
3477 #endif /* WITH_OPENSSL */
3478 
3479 	if (kp != NULL)
3480 		*kp = NULL;
3481 	if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
3482 		goto out;
3483 	type = sshkey_type_from_name(tname);
3484 	if (sshkey_type_is_cert(type)) {
3485 		/*
3486 		 * Certificate key private keys begin with the certificate
3487 		 * itself. Make sure this matches the type of the enclosing
3488 		 * private key.
3489 		 */
3490 		if ((r = sshkey_froms(buf, &k)) != 0)
3491 			goto out;
3492 		if (k->type != type) {
3493 			r = SSH_ERR_KEY_CERT_MISMATCH;
3494 			goto out;
3495 		}
3496 		/* For ECDSA keys, the group must match too */
3497 		if (k->type == KEY_ECDSA &&
3498 		    k->ecdsa_nid != sshkey_ecdsa_nid_from_name(tname)) {
3499 			r = SSH_ERR_KEY_CERT_MISMATCH;
3500 			goto out;
3501 		}
3502 		/*
3503 		 * Several fields are redundant between certificate and
3504 		 * private key body, we require these to match.
3505 		 */
3506 		expect_sk_application = k->sk_application;
3507 		expect_ed25519_pk = k->ed25519_pk;
3508 		k->sk_application = NULL;
3509 		k->ed25519_pk = NULL;
3510 	} else {
3511 		if ((k = sshkey_new(type)) == NULL) {
3512 			r = SSH_ERR_ALLOC_FAIL;
3513 			goto out;
3514 		}
3515 	}
3516 	switch (type) {
3517 #ifdef WITH_OPENSSL
3518 	case KEY_DSA:
3519 		if ((r = sshbuf_get_bignum2(buf, &dsa_p)) != 0 ||
3520 		    (r = sshbuf_get_bignum2(buf, &dsa_q)) != 0 ||
3521 		    (r = sshbuf_get_bignum2(buf, &dsa_g)) != 0 ||
3522 		    (r = sshbuf_get_bignum2(buf, &dsa_pub_key)) != 0)
3523 			goto out;
3524 		if (!DSA_set0_pqg(k->dsa, dsa_p, dsa_q, dsa_g)) {
3525 			r = SSH_ERR_LIBCRYPTO_ERROR;
3526 			goto out;
3527 		}
3528 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
3529 		if (!DSA_set0_key(k->dsa, dsa_pub_key, NULL)) {
3530 			r = SSH_ERR_LIBCRYPTO_ERROR;
3531 			goto out;
3532 		}
3533 		dsa_pub_key = NULL; /* transferred */
3534 		/* FALLTHROUGH */
3535 	case KEY_DSA_CERT:
3536 		if ((r = sshbuf_get_bignum2(buf, &dsa_priv_key)) != 0)
3537 			goto out;
3538 		if (!DSA_set0_key(k->dsa, NULL, dsa_priv_key)) {
3539 			r = SSH_ERR_LIBCRYPTO_ERROR;
3540 			goto out;
3541 		}
3542 		dsa_priv_key = NULL; /* transferred */
3543 		break;
3544 # ifdef OPENSSL_HAS_ECC
3545 	case KEY_ECDSA:
3546 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
3547 			r = SSH_ERR_INVALID_ARGUMENT;
3548 			goto out;
3549 		}
3550 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
3551 			goto out;
3552 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
3553 			r = SSH_ERR_EC_CURVE_MISMATCH;
3554 			goto out;
3555 		}
3556 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
3557 		if (k->ecdsa  == NULL) {
3558 			r = SSH_ERR_LIBCRYPTO_ERROR;
3559 			goto out;
3560 		}
3561 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0)
3562 			goto out;
3563 		/* FALLTHROUGH */
3564 	case KEY_ECDSA_CERT:
3565 		if ((r = sshbuf_get_bignum2(buf, &exponent)) != 0)
3566 			goto out;
3567 		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
3568 			r = SSH_ERR_LIBCRYPTO_ERROR;
3569 			goto out;
3570 		}
3571 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3572 		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
3573 		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
3574 			goto out;
3575 		break;
3576 	case KEY_ECDSA_SK:
3577 		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
3578 			r = SSH_ERR_INVALID_ARGUMENT;
3579 			goto out;
3580 		}
3581 		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
3582 			goto out;
3583 		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
3584 			r = SSH_ERR_EC_CURVE_MISMATCH;
3585 			goto out;
3586 		}
3587 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3588 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3589 			r = SSH_ERR_ALLOC_FAIL;
3590 			goto out;
3591 		}
3592 		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
3593 		if (k->ecdsa  == NULL) {
3594 			r = SSH_ERR_LIBCRYPTO_ERROR;
3595 			goto out;
3596 		}
3597 		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
3598 		    (r = sshbuf_get_cstring(buf, &k->sk_application,
3599 		    NULL)) != 0 ||
3600 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3601 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3602 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3603 			goto out;
3604 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3605 		    EC_KEY_get0_public_key(k->ecdsa))) != 0)
3606 			goto out;
3607 		break;
3608 	case KEY_ECDSA_SK_CERT:
3609 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3610 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3611 			r = SSH_ERR_ALLOC_FAIL;
3612 			goto out;
3613 		}
3614 		if ((r = sshbuf_get_cstring(buf, &k->sk_application,
3615 		    NULL)) != 0 ||
3616 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3617 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3618 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3619 			goto out;
3620 		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
3621 		    EC_KEY_get0_public_key(k->ecdsa))) != 0)
3622 			goto out;
3623 		break;
3624 # endif /* OPENSSL_HAS_ECC */
3625 	case KEY_RSA:
3626 		if ((r = sshbuf_get_bignum2(buf, &rsa_n)) != 0 ||
3627 		    (r = sshbuf_get_bignum2(buf, &rsa_e)) != 0)
3628 			goto out;
3629 		if (!RSA_set0_key(k->rsa, rsa_n, rsa_e, NULL)) {
3630 			r = SSH_ERR_LIBCRYPTO_ERROR;
3631 			goto out;
3632 		}
3633 		rsa_n = rsa_e = NULL; /* transferred */
3634 		/* FALLTHROUGH */
3635 	case KEY_RSA_CERT:
3636 		if ((r = sshbuf_get_bignum2(buf, &rsa_d)) != 0 ||
3637 		    (r = sshbuf_get_bignum2(buf, &rsa_iqmp)) != 0 ||
3638 		    (r = sshbuf_get_bignum2(buf, &rsa_p)) != 0 ||
3639 		    (r = sshbuf_get_bignum2(buf, &rsa_q)) != 0)
3640 			goto out;
3641 		if (!RSA_set0_key(k->rsa, NULL, NULL, rsa_d)) {
3642 			r = SSH_ERR_LIBCRYPTO_ERROR;
3643 			goto out;
3644 		}
3645 		rsa_d = NULL; /* transferred */
3646 		if (!RSA_set0_factors(k->rsa, rsa_p, rsa_q)) {
3647 			r = SSH_ERR_LIBCRYPTO_ERROR;
3648 			goto out;
3649 		}
3650 		rsa_p = rsa_q = NULL; /* transferred */
3651 		if ((r = sshkey_check_rsa_length(k, 0)) != 0)
3652 			goto out;
3653 		if ((r = ssh_rsa_complete_crt_parameters(k, rsa_iqmp)) != 0)
3654 			goto out;
3655 		break;
3656 #endif /* WITH_OPENSSL */
3657 	case KEY_ED25519:
3658 	case KEY_ED25519_CERT:
3659 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
3660 		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
3661 			goto out;
3662 		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
3663 			r = SSH_ERR_INVALID_FORMAT;
3664 			goto out;
3665 		}
3666 		k->ed25519_pk = ed25519_pk;
3667 		k->ed25519_sk = ed25519_sk;
3668 		ed25519_pk = ed25519_sk = NULL; /* transferred */
3669 		break;
3670 	case KEY_ED25519_SK:
3671 	case KEY_ED25519_SK_CERT:
3672 		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0)
3673 			goto out;
3674 		if (pklen != ED25519_PK_SZ) {
3675 			r = SSH_ERR_INVALID_FORMAT;
3676 			goto out;
3677 		}
3678 		if ((k->sk_key_handle = sshbuf_new()) == NULL ||
3679 		    (k->sk_reserved = sshbuf_new()) == NULL) {
3680 			r = SSH_ERR_ALLOC_FAIL;
3681 			goto out;
3682 		}
3683 		if ((r = sshbuf_get_cstring(buf, &k->sk_application,
3684 		    NULL)) != 0 ||
3685 		    (r = sshbuf_get_u8(buf, &k->sk_flags)) != 0 ||
3686 		    (r = sshbuf_get_stringb(buf, k->sk_key_handle)) != 0 ||
3687 		    (r = sshbuf_get_stringb(buf, k->sk_reserved)) != 0)
3688 			goto out;
3689 		k->ed25519_pk = ed25519_pk;
3690 		ed25519_pk = NULL; /* transferred */
3691 		break;
3692 #ifdef WITH_XMSS
3693 	case KEY_XMSS:
3694 	case KEY_XMSS_CERT:
3695 		if ((r = sshbuf_get_cstring(buf, &xmss_name, NULL)) != 0 ||
3696 		    (r = sshbuf_get_string(buf, &xmss_pk, &pklen)) != 0 ||
3697 		    (r = sshbuf_get_string(buf, &xmss_sk, &sklen)) != 0)
3698 			goto out;
3699 		if (type == KEY_XMSS &&
3700 		    (r = sshkey_xmss_init(k, xmss_name)) != 0)
3701 			goto out;
3702 		if (pklen != sshkey_xmss_pklen(k) ||
3703 		    sklen != sshkey_xmss_sklen(k)) {
3704 			r = SSH_ERR_INVALID_FORMAT;
3705 			goto out;
3706 		}
3707 		k->xmss_pk = xmss_pk;
3708 		k->xmss_sk = xmss_sk;
3709 		xmss_pk = xmss_sk = NULL;
3710 		/* optional internal state */
3711 		if ((r = sshkey_xmss_deserialize_state_opt(k, buf)) != 0)
3712 			goto out;
3713 		break;
3714 #endif /* WITH_XMSS */
3715 	default:
3716 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
3717 		goto out;
3718 	}
3719 #ifdef WITH_OPENSSL
3720 	/* enable blinding */
3721 	switch (k->type) {
3722 	case KEY_RSA:
3723 	case KEY_RSA_CERT:
3724 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
3725 			r = SSH_ERR_LIBCRYPTO_ERROR;
3726 			goto out;
3727 		}
3728 		break;
3729 	}
3730 #endif /* WITH_OPENSSL */
3731 	if ((expect_sk_application != NULL && (k->sk_application == NULL ||
3732 	    strcmp(expect_sk_application, k->sk_application) != 0)) ||
3733 	    (expect_ed25519_pk != NULL && (k->ed25519_pk == NULL ||
3734 	    memcmp(expect_ed25519_pk, k->ed25519_pk, ED25519_PK_SZ) != 0))) {
3735 		r = SSH_ERR_KEY_CERT_MISMATCH;
3736 		goto out;
3737 	}
3738 	/* success */
3739 	r = 0;
3740 	if (kp != NULL) {
3741 		*kp = k;
3742 		k = NULL;
3743 	}
3744  out:
3745 	free(tname);
3746 	free(curve);
3747 #ifdef WITH_OPENSSL
3748 	BN_clear_free(exponent);
3749 	BN_clear_free(dsa_p);
3750 	BN_clear_free(dsa_q);
3751 	BN_clear_free(dsa_g);
3752 	BN_clear_free(dsa_pub_key);
3753 	BN_clear_free(dsa_priv_key);
3754 	BN_clear_free(rsa_n);
3755 	BN_clear_free(rsa_e);
3756 	BN_clear_free(rsa_d);
3757 	BN_clear_free(rsa_p);
3758 	BN_clear_free(rsa_q);
3759 	BN_clear_free(rsa_iqmp);
3760 #endif /* WITH_OPENSSL */
3761 	sshkey_free(k);
3762 	freezero(ed25519_pk, pklen);
3763 	freezero(ed25519_sk, sklen);
3764 	free(xmss_name);
3765 	freezero(xmss_pk, pklen);
3766 	freezero(xmss_sk, sklen);
3767 	free(expect_sk_application);
3768 	free(expect_ed25519_pk);
3769 	return r;
3770 }
3771 
3772 #if defined(WITH_OPENSSL) && defined(OPENSSL_HAS_ECC)
3773 int
3774 sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
3775 {
3776 	EC_POINT *nq = NULL;
3777 	BIGNUM *order = NULL, *x = NULL, *y = NULL, *tmp = NULL;
3778 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
3779 
3780 	/*
3781 	 * NB. This assumes OpenSSL has already verified that the public
3782 	 * point lies on the curve. This is done by EC_POINT_oct2point()
3783 	 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
3784 	 * reachable with public points not unmarshalled using
3785 	 * EC_POINT_oct2point then the caller will need to explicitly check.
3786 	 */
3787 
3788 	/*
3789 	 * We shouldn't ever hit this case because bignum_get_ecpoint()
3790 	 * refuses to load GF2m points.
3791 	 */
3792 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3793 	    NID_X9_62_prime_field)
3794 		goto out;
3795 
3796 	/* Q != infinity */
3797 	if (EC_POINT_is_at_infinity(group, public))
3798 		goto out;
3799 
3800 	if ((x = BN_new()) == NULL ||
3801 	    (y = BN_new()) == NULL ||
3802 	    (order = BN_new()) == NULL ||
3803 	    (tmp = BN_new()) == NULL) {
3804 		ret = SSH_ERR_ALLOC_FAIL;
3805 		goto out;
3806 	}
3807 
3808 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
3809 	if (EC_GROUP_get_order(group, order, NULL) != 1 ||
3810 	    EC_POINT_get_affine_coordinates_GFp(group, public,
3811 	    x, y, NULL) != 1) {
3812 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3813 		goto out;
3814 	}
3815 	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
3816 	    BN_num_bits(y) <= BN_num_bits(order) / 2)
3817 		goto out;
3818 
3819 	/* nQ == infinity (n == order of subgroup) */
3820 	if ((nq = EC_POINT_new(group)) == NULL) {
3821 		ret = SSH_ERR_ALLOC_FAIL;
3822 		goto out;
3823 	}
3824 	if (EC_POINT_mul(group, nq, NULL, public, order, NULL) != 1) {
3825 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3826 		goto out;
3827 	}
3828 	if (EC_POINT_is_at_infinity(group, nq) != 1)
3829 		goto out;
3830 
3831 	/* x < order - 1, y < order - 1 */
3832 	if (!BN_sub(tmp, order, BN_value_one())) {
3833 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3834 		goto out;
3835 	}
3836 	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
3837 		goto out;
3838 	ret = 0;
3839  out:
3840 	BN_clear_free(x);
3841 	BN_clear_free(y);
3842 	BN_clear_free(order);
3843 	BN_clear_free(tmp);
3844 	EC_POINT_free(nq);
3845 	return ret;
3846 }
3847 
3848 int
3849 sshkey_ec_validate_private(const EC_KEY *key)
3850 {
3851 	BIGNUM *order = NULL, *tmp = NULL;
3852 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
3853 
3854 	if ((order = BN_new()) == NULL || (tmp = BN_new()) == NULL) {
3855 		ret = SSH_ERR_ALLOC_FAIL;
3856 		goto out;
3857 	}
3858 
3859 	/* log2(private) > log2(order)/2 */
3860 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) {
3861 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3862 		goto out;
3863 	}
3864 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
3865 	    BN_num_bits(order) / 2)
3866 		goto out;
3867 
3868 	/* private < order - 1 */
3869 	if (!BN_sub(tmp, order, BN_value_one())) {
3870 		ret = SSH_ERR_LIBCRYPTO_ERROR;
3871 		goto out;
3872 	}
3873 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
3874 		goto out;
3875 	ret = 0;
3876  out:
3877 	BN_clear_free(order);
3878 	BN_clear_free(tmp);
3879 	return ret;
3880 }
3881 
3882 void
3883 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
3884 {
3885 	BIGNUM *x = NULL, *y = NULL;
3886 
3887 	if (point == NULL) {
3888 		fputs("point=(NULL)\n", stderr);
3889 		return;
3890 	}
3891 	if ((x = BN_new()) == NULL || (y = BN_new()) == NULL) {
3892 		fprintf(stderr, "%s: BN_new failed\n", __func__);
3893 		goto out;
3894 	}
3895 	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
3896 	    NID_X9_62_prime_field) {
3897 		fprintf(stderr, "%s: group is not a prime field\n", __func__);
3898 		goto out;
3899 	}
3900 	if (EC_POINT_get_affine_coordinates_GFp(group, point,
3901 	    x, y, NULL) != 1) {
3902 		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
3903 		    __func__);
3904 		goto out;
3905 	}
3906 	fputs("x=", stderr);
3907 	BN_print_fp(stderr, x);
3908 	fputs("\ny=", stderr);
3909 	BN_print_fp(stderr, y);
3910 	fputs("\n", stderr);
3911  out:
3912 	BN_clear_free(x);
3913 	BN_clear_free(y);
3914 }
3915 
3916 void
3917 sshkey_dump_ec_key(const EC_KEY *key)
3918 {
3919 	const BIGNUM *exponent;
3920 
3921 	sshkey_dump_ec_point(EC_KEY_get0_group(key),
3922 	    EC_KEY_get0_public_key(key));
3923 	fputs("exponent=", stderr);
3924 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
3925 		fputs("(NULL)", stderr);
3926 	else
3927 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
3928 	fputs("\n", stderr);
3929 }
3930 #endif /* WITH_OPENSSL && OPENSSL_HAS_ECC */
3931 
3932 static int
3933 sshkey_private_to_blob2(struct sshkey *prv, struct sshbuf *blob,
3934     const char *passphrase, const char *comment, const char *ciphername,
3935     int rounds)
3936 {
3937 	u_char *cp, *key = NULL, *pubkeyblob = NULL;
3938 	u_char salt[SALT_LEN];
3939 	char *b64 = NULL;
3940 	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
3941 	u_int check;
3942 	int r = SSH_ERR_INTERNAL_ERROR;
3943 	struct sshcipher_ctx *ciphercontext = NULL;
3944 	const struct sshcipher *cipher;
3945 	const char *kdfname = KDFNAME;
3946 	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
3947 
3948 	if (rounds <= 0)
3949 		rounds = DEFAULT_ROUNDS;
3950 	if (passphrase == NULL || !strlen(passphrase)) {
3951 		ciphername = "none";
3952 		kdfname = "none";
3953 	} else if (ciphername == NULL)
3954 		ciphername = DEFAULT_CIPHERNAME;
3955 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3956 		r = SSH_ERR_INVALID_ARGUMENT;
3957 		goto out;
3958 	}
3959 
3960 	if ((kdf = sshbuf_new()) == NULL ||
3961 	    (encoded = sshbuf_new()) == NULL ||
3962 	    (encrypted = sshbuf_new()) == NULL) {
3963 		r = SSH_ERR_ALLOC_FAIL;
3964 		goto out;
3965 	}
3966 	blocksize = cipher_blocksize(cipher);
3967 	keylen = cipher_keylen(cipher);
3968 	ivlen = cipher_ivlen(cipher);
3969 	authlen = cipher_authlen(cipher);
3970 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3971 		r = SSH_ERR_ALLOC_FAIL;
3972 		goto out;
3973 	}
3974 	if (strcmp(kdfname, "bcrypt") == 0) {
3975 		arc4random_buf(salt, SALT_LEN);
3976 		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
3977 		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
3978 			r = SSH_ERR_INVALID_ARGUMENT;
3979 			goto out;
3980 		}
3981 		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
3982 		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
3983 			goto out;
3984 	} else if (strcmp(kdfname, "none") != 0) {
3985 		/* Unsupported KDF type */
3986 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3987 		goto out;
3988 	}
3989 	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
3990 	    key + keylen, ivlen, 1)) != 0)
3991 		goto out;
3992 
3993 	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
3994 	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
3995 	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
3996 	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
3997 	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
3998 	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
3999 	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
4000 		goto out;
4001 
4002 	/* set up the buffer that will be encrypted */
4003 
4004 	/* Random check bytes */
4005 	check = arc4random();
4006 	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
4007 	    (r = sshbuf_put_u32(encrypted, check)) != 0)
4008 		goto out;
4009 
4010 	/* append private key and comment*/
4011 	if ((r = sshkey_private_serialize_opt(prv, encrypted,
4012 	    SSHKEY_SERIALIZE_FULL)) != 0 ||
4013 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
4014 		goto out;
4015 
4016 	/* padding */
4017 	i = 0;
4018 	while (sshbuf_len(encrypted) % blocksize) {
4019 		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
4020 			goto out;
4021 	}
4022 
4023 	/* length in destination buffer */
4024 	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
4025 		goto out;
4026 
4027 	/* encrypt */
4028 	if ((r = sshbuf_reserve(encoded,
4029 	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
4030 		goto out;
4031 	if ((r = cipher_crypt(ciphercontext, 0, cp,
4032 	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
4033 		goto out;
4034 
4035 	sshbuf_reset(blob);
4036 
4037 	/* assemble uuencoded key */
4038 	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0 ||
4039 	    (r = sshbuf_dtob64(encoded, blob, 1)) != 0 ||
4040 	    (r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
4041 		goto out;
4042 
4043 	/* success */
4044 	r = 0;
4045 
4046  out:
4047 	sshbuf_free(kdf);
4048 	sshbuf_free(encoded);
4049 	sshbuf_free(encrypted);
4050 	cipher_free(ciphercontext);
4051 	explicit_bzero(salt, sizeof(salt));
4052 	if (key != NULL)
4053 		freezero(key, keylen + ivlen);
4054 	if (pubkeyblob != NULL)
4055 		freezero(pubkeyblob, pubkeylen);
4056 	if (b64 != NULL)
4057 		freezero(b64, strlen(b64));
4058 	return r;
4059 }
4060 
4061 static int
4062 private2_uudecode(struct sshbuf *blob, struct sshbuf **decodedp)
4063 {
4064 	const u_char *cp;
4065 	size_t encoded_len;
4066 	int r;
4067 	u_char last;
4068 	struct sshbuf *encoded = NULL, *decoded = NULL;
4069 
4070 	if (blob == NULL || decodedp == NULL)
4071 		return SSH_ERR_INVALID_ARGUMENT;
4072 
4073 	*decodedp = NULL;
4074 
4075 	if ((encoded = sshbuf_new()) == NULL ||
4076 	    (decoded = sshbuf_new()) == NULL) {
4077 		r = SSH_ERR_ALLOC_FAIL;
4078 		goto out;
4079 	}
4080 
4081 	/* check preamble */
4082 	cp = sshbuf_ptr(blob);
4083 	encoded_len = sshbuf_len(blob);
4084 	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
4085 	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
4086 		r = SSH_ERR_INVALID_FORMAT;
4087 		goto out;
4088 	}
4089 	cp += MARK_BEGIN_LEN;
4090 	encoded_len -= MARK_BEGIN_LEN;
4091 
4092 	/* Look for end marker, removing whitespace as we go */
4093 	while (encoded_len > 0) {
4094 		if (*cp != '\n' && *cp != '\r') {
4095 			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
4096 				goto out;
4097 		}
4098 		last = *cp;
4099 		encoded_len--;
4100 		cp++;
4101 		if (last == '\n') {
4102 			if (encoded_len >= MARK_END_LEN &&
4103 			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
4104 				/* \0 terminate */
4105 				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
4106 					goto out;
4107 				break;
4108 			}
4109 		}
4110 	}
4111 	if (encoded_len == 0) {
4112 		r = SSH_ERR_INVALID_FORMAT;
4113 		goto out;
4114 	}
4115 
4116 	/* decode base64 */
4117 	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
4118 		goto out;
4119 
4120 	/* check magic */
4121 	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
4122 	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
4123 		r = SSH_ERR_INVALID_FORMAT;
4124 		goto out;
4125 	}
4126 	/* success */
4127 	*decodedp = decoded;
4128 	decoded = NULL;
4129 	r = 0;
4130  out:
4131 	sshbuf_free(encoded);
4132 	sshbuf_free(decoded);
4133 	return r;
4134 }
4135 
4136 static int
4137 private2_decrypt(struct sshbuf *decoded, const char *passphrase,
4138     struct sshbuf **decryptedp, struct sshkey **pubkeyp)
4139 {
4140 	char *ciphername = NULL, *kdfname = NULL;
4141 	const struct sshcipher *cipher = NULL;
4142 	int r = SSH_ERR_INTERNAL_ERROR;
4143 	size_t keylen = 0, ivlen = 0, authlen = 0, slen = 0;
4144 	struct sshbuf *kdf = NULL, *decrypted = NULL;
4145 	struct sshcipher_ctx *ciphercontext = NULL;
4146 	struct sshkey *pubkey = NULL;
4147 	u_char *key = NULL, *salt = NULL, *dp;
4148 	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
4149 
4150 	if (decoded == NULL || decryptedp == NULL || pubkeyp == NULL)
4151 		return SSH_ERR_INVALID_ARGUMENT;
4152 
4153 	*decryptedp = NULL;
4154 	*pubkeyp = NULL;
4155 
4156 	if ((decrypted = sshbuf_new()) == NULL) {
4157 		r = SSH_ERR_ALLOC_FAIL;
4158 		goto out;
4159 	}
4160 
4161 	/* parse public portion of key */
4162 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
4163 	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
4164 	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
4165 	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
4166 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
4167 		goto out;
4168 
4169 	if (nkeys != 1) {
4170 		/* XXX only one key supported at present */
4171 		r = SSH_ERR_INVALID_FORMAT;
4172 		goto out;
4173 	}
4174 
4175 	if ((r = sshkey_froms(decoded, &pubkey)) != 0 ||
4176 	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
4177 		goto out;
4178 
4179 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
4180 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
4181 		goto out;
4182 	}
4183 	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
4184 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
4185 		goto out;
4186 	}
4187 	if (strcmp(kdfname, "none") == 0 && strcmp(ciphername, "none") != 0) {
4188 		r = SSH_ERR_INVALID_FORMAT;
4189 		goto out;
4190 	}
4191 	if ((passphrase == NULL || strlen(passphrase) == 0) &&
4192 	    strcmp(kdfname, "none") != 0) {
4193 		/* passphrase required */
4194 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4195 		goto out;
4196 	}
4197 
4198 	/* check size of encrypted key blob */
4199 	blocksize = cipher_blocksize(cipher);
4200 	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
4201 		r = SSH_ERR_INVALID_FORMAT;
4202 		goto out;
4203 	}
4204 
4205 	/* setup key */
4206 	keylen = cipher_keylen(cipher);
4207 	ivlen = cipher_ivlen(cipher);
4208 	authlen = cipher_authlen(cipher);
4209 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
4210 		r = SSH_ERR_ALLOC_FAIL;
4211 		goto out;
4212 	}
4213 	if (strcmp(kdfname, "bcrypt") == 0) {
4214 		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
4215 		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
4216 			goto out;
4217 		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
4218 		    key, keylen + ivlen, rounds) < 0) {
4219 			r = SSH_ERR_INVALID_FORMAT;
4220 			goto out;
4221 		}
4222 	}
4223 
4224 	/* check that an appropriate amount of auth data is present */
4225 	if (sshbuf_len(decoded) < authlen ||
4226 	    sshbuf_len(decoded) - authlen < encrypted_len) {
4227 		r = SSH_ERR_INVALID_FORMAT;
4228 		goto out;
4229 	}
4230 
4231 	/* decrypt private portion of key */
4232 	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
4233 	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
4234 	    key + keylen, ivlen, 0)) != 0)
4235 		goto out;
4236 	if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
4237 	    encrypted_len, 0, authlen)) != 0) {
4238 		/* an integrity error here indicates an incorrect passphrase */
4239 		if (r == SSH_ERR_MAC_INVALID)
4240 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4241 		goto out;
4242 	}
4243 	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
4244 		goto out;
4245 	/* there should be no trailing data */
4246 	if (sshbuf_len(decoded) != 0) {
4247 		r = SSH_ERR_INVALID_FORMAT;
4248 		goto out;
4249 	}
4250 
4251 	/* check check bytes */
4252 	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
4253 	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
4254 		goto out;
4255 	if (check1 != check2) {
4256 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4257 		goto out;
4258 	}
4259 	/* success */
4260 	*decryptedp = decrypted;
4261 	decrypted = NULL;
4262 	*pubkeyp = pubkey;
4263 	pubkey = NULL;
4264 	r = 0;
4265  out:
4266 	cipher_free(ciphercontext);
4267 	free(ciphername);
4268 	free(kdfname);
4269 	sshkey_free(pubkey);
4270 	if (salt != NULL) {
4271 		explicit_bzero(salt, slen);
4272 		free(salt);
4273 	}
4274 	if (key != NULL) {
4275 		explicit_bzero(key, keylen + ivlen);
4276 		free(key);
4277 	}
4278 	sshbuf_free(kdf);
4279 	sshbuf_free(decrypted);
4280 	return r;
4281 }
4282 
4283 static int
4284 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
4285     struct sshkey **keyp, char **commentp)
4286 {
4287 	char *comment = NULL;
4288 	int r = SSH_ERR_INTERNAL_ERROR;
4289 	struct sshbuf *decoded = NULL, *decrypted = NULL;
4290 	struct sshkey *k = NULL, *pubkey = NULL;
4291 
4292 	if (keyp != NULL)
4293 		*keyp = NULL;
4294 	if (commentp != NULL)
4295 		*commentp = NULL;
4296 
4297 	/* Undo base64 encoding and decrypt the private section */
4298 	if ((r = private2_uudecode(blob, &decoded)) != 0 ||
4299 	    (r = private2_decrypt(decoded, passphrase,
4300 	    &decrypted, &pubkey)) != 0)
4301 		goto out;
4302 
4303 	if (type != KEY_UNSPEC &&
4304 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
4305 		r = SSH_ERR_KEY_TYPE_MISMATCH;
4306 		goto out;
4307 	}
4308 
4309 	/* Load the private key and comment */
4310 	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
4311 	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
4312 		goto out;
4313 
4314 	/* Check deterministic padding after private section */
4315 	if ((r = private2_check_padding(decrypted)) != 0)
4316 		goto out;
4317 
4318 	/* Check that the public key in the envelope matches the private key */
4319 	if (!sshkey_equal(pubkey, k)) {
4320 		r = SSH_ERR_INVALID_FORMAT;
4321 		goto out;
4322 	}
4323 
4324 	/* success */
4325 	r = 0;
4326 	if (keyp != NULL) {
4327 		*keyp = k;
4328 		k = NULL;
4329 	}
4330 	if (commentp != NULL) {
4331 		*commentp = comment;
4332 		comment = NULL;
4333 	}
4334  out:
4335 	free(comment);
4336 	sshbuf_free(decoded);
4337 	sshbuf_free(decrypted);
4338 	sshkey_free(k);
4339 	sshkey_free(pubkey);
4340 	return r;
4341 }
4342 
4343 static int
4344 sshkey_parse_private2_pubkey(struct sshbuf *blob, int type,
4345     struct sshkey **keyp)
4346 {
4347 	int r = SSH_ERR_INTERNAL_ERROR;
4348 	struct sshbuf *decoded = NULL;
4349 	struct sshkey *pubkey = NULL;
4350 	u_int nkeys = 0;
4351 
4352 	if (keyp != NULL)
4353 		*keyp = NULL;
4354 
4355 	if ((r = private2_uudecode(blob, &decoded)) != 0)
4356 		goto out;
4357 	/* parse public key from unencrypted envelope */
4358 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
4359 	    (r = sshbuf_skip_string(decoded)) != 0 || /* cipher */
4360 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF alg */
4361 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF hint */
4362 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
4363 		goto out;
4364 
4365 	if (nkeys != 1) {
4366 		/* XXX only one key supported at present */
4367 		r = SSH_ERR_INVALID_FORMAT;
4368 		goto out;
4369 	}
4370 
4371 	/* Parse the public key */
4372 	if ((r = sshkey_froms(decoded, &pubkey)) != 0)
4373 		goto out;
4374 
4375 	if (type != KEY_UNSPEC &&
4376 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
4377 		r = SSH_ERR_KEY_TYPE_MISMATCH;
4378 		goto out;
4379 	}
4380 
4381 	/* success */
4382 	r = 0;
4383 	if (keyp != NULL) {
4384 		*keyp = pubkey;
4385 		pubkey = NULL;
4386 	}
4387  out:
4388 	sshbuf_free(decoded);
4389 	sshkey_free(pubkey);
4390 	return r;
4391 }
4392 
4393 #ifdef WITH_OPENSSL
4394 /* convert SSH v2 key to PEM or PKCS#8 format */
4395 static int
4396 sshkey_private_to_blob_pem_pkcs8(struct sshkey *key, struct sshbuf *buf,
4397     int format, const char *_passphrase, const char *comment)
4398 {
4399 	int was_shielded = sshkey_is_shielded(key);
4400 	int success, r;
4401 	int blen, len = strlen(_passphrase);
4402 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
4403 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
4404 	char *bptr;
4405 	BIO *bio = NULL;
4406 	struct sshbuf *blob;
4407 	EVP_PKEY *pkey = NULL;
4408 
4409 	if (len > 0 && len <= 4)
4410 		return SSH_ERR_PASSPHRASE_TOO_SHORT;
4411 	if ((blob = sshbuf_new()) == NULL)
4412 		return SSH_ERR_ALLOC_FAIL;
4413 	if ((bio = BIO_new(BIO_s_mem())) == NULL) {
4414 		r = SSH_ERR_ALLOC_FAIL;
4415 		goto out;
4416 	}
4417 	if (format == SSHKEY_PRIVATE_PKCS8 && (pkey = EVP_PKEY_new()) == NULL) {
4418 		r = SSH_ERR_ALLOC_FAIL;
4419 		goto out;
4420 	}
4421 	if ((r = sshkey_unshield_private(key)) != 0)
4422 		goto out;
4423 
4424 	switch (key->type) {
4425 	case KEY_DSA:
4426 		if (format == SSHKEY_PRIVATE_PEM) {
4427 			success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
4428 			    cipher, passphrase, len, NULL, NULL);
4429 		} else {
4430 			success = EVP_PKEY_set1_DSA(pkey, key->dsa);
4431 		}
4432 		break;
4433 #ifdef OPENSSL_HAS_ECC
4434 	case KEY_ECDSA:
4435 		if (format == SSHKEY_PRIVATE_PEM) {
4436 			success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
4437 			    cipher, passphrase, len, NULL, NULL);
4438 		} else {
4439 			success = EVP_PKEY_set1_EC_KEY(pkey, key->ecdsa);
4440 		}
4441 		break;
4442 #endif
4443 	case KEY_RSA:
4444 		if (format == SSHKEY_PRIVATE_PEM) {
4445 			success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
4446 			    cipher, passphrase, len, NULL, NULL);
4447 		} else {
4448 			success = EVP_PKEY_set1_RSA(pkey, key->rsa);
4449 		}
4450 		break;
4451 	default:
4452 		success = 0;
4453 		break;
4454 	}
4455 	if (success == 0) {
4456 		r = SSH_ERR_LIBCRYPTO_ERROR;
4457 		goto out;
4458 	}
4459 	if (format == SSHKEY_PRIVATE_PKCS8) {
4460 		if ((success = PEM_write_bio_PrivateKey(bio, pkey, cipher,
4461 		    passphrase, len, NULL, NULL)) == 0) {
4462 			r = SSH_ERR_LIBCRYPTO_ERROR;
4463 			goto out;
4464 		}
4465 	}
4466 	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
4467 		r = SSH_ERR_INTERNAL_ERROR;
4468 		goto out;
4469 	}
4470 	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
4471 		goto out;
4472 	r = 0;
4473  out:
4474 	if (was_shielded)
4475 		r = sshkey_shield_private(key);
4476 	if (r == 0)
4477 		r = sshbuf_putb(buf, blob);
4478 
4479 	EVP_PKEY_free(pkey);
4480 	sshbuf_free(blob);
4481 	BIO_free(bio);
4482 	return r;
4483 }
4484 #endif /* WITH_OPENSSL */
4485 
4486 /* Serialise "key" to buffer "blob" */
4487 int
4488 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
4489     const char *passphrase, const char *comment,
4490     int format, const char *openssh_format_cipher, int openssh_format_rounds)
4491 {
4492 	switch (key->type) {
4493 #ifdef WITH_OPENSSL
4494 	case KEY_DSA:
4495 	case KEY_ECDSA:
4496 	case KEY_RSA:
4497 		break; /* see below */
4498 #endif /* WITH_OPENSSL */
4499 	case KEY_ED25519:
4500 	case KEY_ED25519_SK:
4501 #ifdef WITH_XMSS
4502 	case KEY_XMSS:
4503 #endif /* WITH_XMSS */
4504 #ifdef WITH_OPENSSL
4505 	case KEY_ECDSA_SK:
4506 #endif /* WITH_OPENSSL */
4507 		return sshkey_private_to_blob2(key, blob, passphrase,
4508 		    comment, openssh_format_cipher, openssh_format_rounds);
4509 	default:
4510 		return SSH_ERR_KEY_TYPE_UNKNOWN;
4511 	}
4512 
4513 #ifdef WITH_OPENSSL
4514 	switch (format) {
4515 	case SSHKEY_PRIVATE_OPENSSH:
4516 		return sshkey_private_to_blob2(key, blob, passphrase,
4517 		    comment, openssh_format_cipher, openssh_format_rounds);
4518 	case SSHKEY_PRIVATE_PEM:
4519 	case SSHKEY_PRIVATE_PKCS8:
4520 		return sshkey_private_to_blob_pem_pkcs8(key, blob,
4521 		    format, passphrase, comment);
4522 	default:
4523 		return SSH_ERR_INVALID_ARGUMENT;
4524 	}
4525 #endif /* WITH_OPENSSL */
4526 }
4527 
4528 #ifdef WITH_OPENSSL
4529 static int
4530 translate_libcrypto_error(unsigned long pem_err)
4531 {
4532 	int pem_reason = ERR_GET_REASON(pem_err);
4533 
4534 	switch (ERR_GET_LIB(pem_err)) {
4535 	case ERR_LIB_PEM:
4536 		switch (pem_reason) {
4537 		case PEM_R_BAD_PASSWORD_READ:
4538 		case PEM_R_PROBLEMS_GETTING_PASSWORD:
4539 		case PEM_R_BAD_DECRYPT:
4540 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
4541 		default:
4542 			return SSH_ERR_INVALID_FORMAT;
4543 		}
4544 	case ERR_LIB_EVP:
4545 		switch (pem_reason) {
4546 		case EVP_R_BAD_DECRYPT:
4547 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
4548 #ifdef EVP_R_BN_DECODE_ERROR
4549 		case EVP_R_BN_DECODE_ERROR:
4550 #endif
4551 		case EVP_R_DECODE_ERROR:
4552 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
4553 		case EVP_R_PRIVATE_KEY_DECODE_ERROR:
4554 #endif
4555 			return SSH_ERR_INVALID_FORMAT;
4556 		default:
4557 			return SSH_ERR_LIBCRYPTO_ERROR;
4558 		}
4559 	case ERR_LIB_ASN1:
4560 		return SSH_ERR_INVALID_FORMAT;
4561 	}
4562 	return SSH_ERR_LIBCRYPTO_ERROR;
4563 }
4564 
4565 static void
4566 clear_libcrypto_errors(void)
4567 {
4568 	while (ERR_get_error() != 0)
4569 		;
4570 }
4571 
4572 /*
4573  * Translate OpenSSL error codes to determine whether
4574  * passphrase is required/incorrect.
4575  */
4576 static int
4577 convert_libcrypto_error(void)
4578 {
4579 	/*
4580 	 * Some password errors are reported at the beginning
4581 	 * of the error queue.
4582 	 */
4583 	if (translate_libcrypto_error(ERR_peek_error()) ==
4584 	    SSH_ERR_KEY_WRONG_PASSPHRASE)
4585 		return SSH_ERR_KEY_WRONG_PASSPHRASE;
4586 	return translate_libcrypto_error(ERR_peek_last_error());
4587 }
4588 
4589 static int
4590 pem_passphrase_cb(char *buf, int size, int rwflag, void *u)
4591 {
4592 	char *p = (char *)u;
4593 	size_t len;
4594 
4595 	if (p == NULL || (len = strlen(p)) == 0)
4596 		return -1;
4597 	if (size < 0 || len > (size_t)size)
4598 		return -1;
4599 	memcpy(buf, p, len);
4600 	return (int)len;
4601 }
4602 
4603 static int
4604 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
4605     const char *passphrase, struct sshkey **keyp)
4606 {
4607 	EVP_PKEY *pk = NULL;
4608 	struct sshkey *prv = NULL;
4609 	BIO *bio = NULL;
4610 	int r;
4611 
4612 	if (keyp != NULL)
4613 		*keyp = NULL;
4614 
4615 	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
4616 		return SSH_ERR_ALLOC_FAIL;
4617 	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
4618 	    (int)sshbuf_len(blob)) {
4619 		r = SSH_ERR_ALLOC_FAIL;
4620 		goto out;
4621 	}
4622 
4623 	clear_libcrypto_errors();
4624 	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, pem_passphrase_cb,
4625 	    (char *)passphrase)) == NULL) {
4626 		/*
4627 		 * libcrypto may return various ASN.1 errors when attempting
4628 		 * to parse a key with an incorrect passphrase.
4629 		 * Treat all format errors as "incorrect passphrase" if a
4630 		 * passphrase was supplied.
4631 		 */
4632 		if (passphrase != NULL && *passphrase != '\0')
4633 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
4634 		else
4635 			r = convert_libcrypto_error();
4636 		goto out;
4637 	}
4638 	if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA &&
4639 	    (type == KEY_UNSPEC || type == KEY_RSA)) {
4640 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4641 			r = SSH_ERR_ALLOC_FAIL;
4642 			goto out;
4643 		}
4644 		prv->rsa = EVP_PKEY_get1_RSA(pk);
4645 		prv->type = KEY_RSA;
4646 #ifdef DEBUG_PK
4647 		RSA_print_fp(stderr, prv->rsa, 8);
4648 #endif
4649 		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
4650 			r = SSH_ERR_LIBCRYPTO_ERROR;
4651 			goto out;
4652 		}
4653 		if ((r = sshkey_check_rsa_length(prv, 0)) != 0)
4654 			goto out;
4655 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_DSA &&
4656 	    (type == KEY_UNSPEC || type == KEY_DSA)) {
4657 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4658 			r = SSH_ERR_ALLOC_FAIL;
4659 			goto out;
4660 		}
4661 		prv->dsa = EVP_PKEY_get1_DSA(pk);
4662 		prv->type = KEY_DSA;
4663 #ifdef DEBUG_PK
4664 		DSA_print_fp(stderr, prv->dsa, 8);
4665 #endif
4666 #ifdef OPENSSL_HAS_ECC
4667 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_EC &&
4668 	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
4669 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
4670 			r = SSH_ERR_ALLOC_FAIL;
4671 			goto out;
4672 		}
4673 		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
4674 		prv->type = KEY_ECDSA;
4675 		prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
4676 		if (prv->ecdsa_nid == -1 ||
4677 		    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
4678 		    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
4679 		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
4680 		    sshkey_ec_validate_private(prv->ecdsa) != 0) {
4681 			r = SSH_ERR_INVALID_FORMAT;
4682 			goto out;
4683 		}
4684 # ifdef DEBUG_PK
4685 		if (prv != NULL && prv->ecdsa != NULL)
4686 			sshkey_dump_ec_key(prv->ecdsa);
4687 # endif
4688 #endif /* OPENSSL_HAS_ECC */
4689 	} else {
4690 		r = SSH_ERR_INVALID_FORMAT;
4691 		goto out;
4692 	}
4693 	r = 0;
4694 	if (keyp != NULL) {
4695 		*keyp = prv;
4696 		prv = NULL;
4697 	}
4698  out:
4699 	BIO_free(bio);
4700 	EVP_PKEY_free(pk);
4701 	sshkey_free(prv);
4702 	return r;
4703 }
4704 #endif /* WITH_OPENSSL */
4705 
4706 int
4707 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
4708     const char *passphrase, struct sshkey **keyp, char **commentp)
4709 {
4710 	int r = SSH_ERR_INTERNAL_ERROR;
4711 
4712 	if (keyp != NULL)
4713 		*keyp = NULL;
4714 	if (commentp != NULL)
4715 		*commentp = NULL;
4716 
4717 	switch (type) {
4718 	case KEY_ED25519:
4719 	case KEY_XMSS:
4720 		/* No fallback for new-format-only keys */
4721 		return sshkey_parse_private2(blob, type, passphrase,
4722 		    keyp, commentp);
4723 	default:
4724 		r = sshkey_parse_private2(blob, type, passphrase, keyp,
4725 		    commentp);
4726 		/* Only fallback to PEM parser if a format error occurred. */
4727 		if (r != SSH_ERR_INVALID_FORMAT)
4728 			return r;
4729 #ifdef WITH_OPENSSL
4730 		return sshkey_parse_private_pem_fileblob(blob, type,
4731 		    passphrase, keyp);
4732 #else
4733 		return SSH_ERR_INVALID_FORMAT;
4734 #endif /* WITH_OPENSSL */
4735 	}
4736 }
4737 
4738 int
4739 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
4740     struct sshkey **keyp, char **commentp)
4741 {
4742 	if (keyp != NULL)
4743 		*keyp = NULL;
4744 	if (commentp != NULL)
4745 		*commentp = NULL;
4746 
4747 	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
4748 	    passphrase, keyp, commentp);
4749 }
4750 
4751 void
4752 sshkey_sig_details_free(struct sshkey_sig_details *details)
4753 {
4754 	freezero(details, sizeof(*details));
4755 }
4756 
4757 int
4758 sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf *blob, int type,
4759     struct sshkey **pubkeyp)
4760 {
4761 	int r = SSH_ERR_INTERNAL_ERROR;
4762 
4763 	if (pubkeyp != NULL)
4764 		*pubkeyp = NULL;
4765 	/* only new-format private keys bundle a public key inside */
4766 	if ((r = sshkey_parse_private2_pubkey(blob, type, pubkeyp)) != 0)
4767 		return r;
4768 	return 0;
4769 }
4770 
4771 #ifdef WITH_XMSS
4772 /*
4773  * serialize the key with the current state and forward the state
4774  * maxsign times.
4775  */
4776 int
4777 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
4778     u_int32_t maxsign, int printerror)
4779 {
4780 	int r, rupdate;
4781 
4782 	if (maxsign == 0 ||
4783 	    sshkey_type_plain(k->type) != KEY_XMSS)
4784 		return sshkey_private_serialize_opt(k, b,
4785 		    SSHKEY_SERIALIZE_DEFAULT);
4786 	if ((r = sshkey_xmss_get_state(k, printerror)) != 0 ||
4787 	    (r = sshkey_private_serialize_opt(k, b,
4788 	    SSHKEY_SERIALIZE_STATE)) != 0 ||
4789 	    (r = sshkey_xmss_forward_state(k, maxsign)) != 0)
4790 		goto out;
4791 	r = 0;
4792 out:
4793 	if ((rupdate = sshkey_xmss_update_state(k, printerror)) != 0) {
4794 		if (r == 0)
4795 			r = rupdate;
4796 	}
4797 	return r;
4798 }
4799 
4800 u_int32_t
4801 sshkey_signatures_left(const struct sshkey *k)
4802 {
4803 	if (sshkey_type_plain(k->type) == KEY_XMSS)
4804 		return sshkey_xmss_signatures_left(k);
4805 	return 0;
4806 }
4807 
4808 int
4809 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
4810 {
4811 	if (sshkey_type_plain(k->type) != KEY_XMSS)
4812 		return SSH_ERR_INVALID_ARGUMENT;
4813 	return sshkey_xmss_enable_maxsign(k, maxsign);
4814 }
4815 
4816 int
4817 sshkey_set_filename(struct sshkey *k, const char *filename)
4818 {
4819 	if (k == NULL)
4820 		return SSH_ERR_INVALID_ARGUMENT;
4821 	if (sshkey_type_plain(k->type) != KEY_XMSS)
4822 		return 0;
4823 	if (filename == NULL)
4824 		return SSH_ERR_INVALID_ARGUMENT;
4825 	if ((k->xmss_filename = strdup(filename)) == NULL)
4826 		return SSH_ERR_ALLOC_FAIL;
4827 	return 0;
4828 }
4829 #else
4830 int
4831 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
4832     u_int32_t maxsign, int printerror)
4833 {
4834 	return sshkey_private_serialize_opt(k, b, SSHKEY_SERIALIZE_DEFAULT);
4835 }
4836 
4837 u_int32_t
4838 sshkey_signatures_left(const struct sshkey *k)
4839 {
4840 	return 0;
4841 }
4842 
4843 int
4844 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
4845 {
4846 	return SSH_ERR_INVALID_ARGUMENT;
4847 }
4848 
4849 int
4850 sshkey_set_filename(struct sshkey *k, const char *filename)
4851 {
4852 	if (k == NULL)
4853 		return SSH_ERR_INVALID_ARGUMENT;
4854 	return 0;
4855 }
4856 #endif /* WITH_XMSS */
4857