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