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