xref: /openssh-portable/sshkey.c (revision e3fa6249)
1 /* $OpenBSD: sshkey.c,v 1.110 2020/06/24 15:07:33 markus Exp $ */
2 /*
3  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2008 Alexander von Gernler.  All rights reserved.
5  * Copyright (c) 2010,2011 Damien Miller.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "includes.h"
29 
30 #include <sys/types.h>
31 #include <netinet/in.h>
32 
33 #ifdef WITH_OPENSSL
34 #include <openssl/evp.h>
35 #include <openssl/err.h>
36 #include <openssl/pem.h>
37 #endif
38 
39 #include "crypto_api.h"
40 
41 #include <errno.h>
42 #include <limits.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <resolv.h>
46 #include <time.h>
47 #ifdef HAVE_UTIL_H
48 #include <util.h>
49 #endif /* HAVE_UTIL_H */
50 
51 #include "ssh2.h"
52 #include "ssherr.h"
53 #include "misc.h"
54 #include "sshbuf.h"
55 #include "cipher.h"
56 #include "digest.h"
57 #define SSHKEY_INTERNAL
58 #include "sshkey.h"
59 #include "match.h"
60 #include "ssh-sk.h"
61 
62 #ifdef WITH_XMSS
63 #include "sshkey-xmss.h"
64 #include "xmss_fast.h"
65 #endif
66 
67 #include "openbsd-compat/openssl-compat.h"
68 
69 /* openssh private key file format */
70 #define MARK_BEGIN		"-----BEGIN OPENSSH PRIVATE KEY-----\n"
71 #define MARK_END		"-----END OPENSSH PRIVATE KEY-----\n"
72 #define MARK_BEGIN_LEN		(sizeof(MARK_BEGIN) - 1)
73 #define MARK_END_LEN		(sizeof(MARK_END) - 1)
74 #define KDFNAME			"bcrypt"
75 #define AUTH_MAGIC		"openssh-key-v1"
76 #define SALT_LEN		16
77 #define DEFAULT_CIPHERNAME	"aes256-ctr"
78 #define	DEFAULT_ROUNDS		16
79 
80 /* Version identification string for SSH v1 identity files. */
81 #define LEGACY_BEGIN		"SSH PRIVATE KEY FILE FORMAT 1.1\n"
82 
83 /*
84  * Constants relating to "shielding" support; protection of keys expected
85  * to remain in memory for long durations
86  */
87 #define SSHKEY_SHIELD_PREKEY_LEN	(16 * 1024)
88 #define SSHKEY_SHIELD_CIPHER		"aes256-ctr" /* XXX want AES-EME* */
89 #define SSHKEY_SHIELD_PREKEY_HASH	SSH_DIGEST_SHA512
90 
91 int	sshkey_private_serialize_opt(struct sshkey *key,
92     struct sshbuf *buf, enum sshkey_serialize_rep);
93 static int sshkey_from_blob_internal(struct sshbuf *buf,
94     struct sshkey **keyp, int allow_cert);
95 
96 /* Supported key types */
97 struct keytype {
98 	const char *name;
99 	const char *shortname;
100 	const char *sigalg;
101 	int type;
102 	int nid;
103 	int cert;
104 	int sigonly;
105 };
106 static const struct keytype keytypes[] = {
107 	{ "ssh-ed25519", "ED25519", NULL, KEY_ED25519, 0, 0, 0 },
108 	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT", NULL,
109 	    KEY_ED25519_CERT, 0, 1, 0 },
110 	{ "sk-ssh-ed25519@openssh.com", "ED25519-SK", NULL,
111 	    KEY_ED25519_SK, 0, 0, 0 },
112 	{ "sk-ssh-ed25519-cert-v01@openssh.com", "ED25519-SK-CERT", NULL,
113 	    KEY_ED25519_SK_CERT, 0, 1, 0 },
114 #ifdef WITH_XMSS
115 	{ "ssh-xmss@openssh.com", "XMSS", NULL, KEY_XMSS, 0, 0, 0 },
116 	{ "ssh-xmss-cert-v01@openssh.com", "XMSS-CERT", NULL,
117 	    KEY_XMSS_CERT, 0, 1, 0 },
118 #endif /* WITH_XMSS */
119 #ifdef WITH_OPENSSL
120 	{ "ssh-rsa", "RSA", NULL, KEY_RSA, 0, 0, 0 },
121 	{ "rsa-sha2-256", "RSA", NULL, KEY_RSA, 0, 0, 1 },
122 	{ "rsa-sha2-512", "RSA", NULL, KEY_RSA, 0, 0, 1 },
123 	{ "ssh-dss", "DSA", NULL, KEY_DSA, 0, 0, 0 },
124 # ifdef OPENSSL_HAS_ECC
125 	{ "ecdsa-sha2-nistp256", "ECDSA", NULL,
126 	    KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
127 	{ "ecdsa-sha2-nistp384", "ECDSA", NULL,
128 	    KEY_ECDSA, NID_secp384r1, 0, 0 },
129 #  ifdef OPENSSL_HAS_NISTP521
130 	{ "ecdsa-sha2-nistp521", "ECDSA", NULL,
131 	    KEY_ECDSA, NID_secp521r1, 0, 0 },
132 #  endif /* OPENSSL_HAS_NISTP521 */
133 	{ "sk-ecdsa-sha2-nistp256@openssh.com", "ECDSA-SK", NULL,
134 	    KEY_ECDSA_SK, NID_X9_62_prime256v1, 0, 0 },
135 	{ "webauthn-sk-ecdsa-sha2-nistp256@openssh.com", "ECDSA-SK", NULL,
136 	    KEY_ECDSA_SK, NID_X9_62_prime256v1, 0, 1 },
137 # endif /* OPENSSL_HAS_ECC */
138 	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", NULL,
139 	    KEY_RSA_CERT, 0, 1, 0 },
140 	{ "rsa-sha2-256-cert-v01@openssh.com", "RSA-CERT",
141 	    "rsa-sha2-256", KEY_RSA_CERT, 0, 1, 1 },
142 	{ "rsa-sha2-512-cert-v01@openssh.com", "RSA-CERT",
143 	    "rsa-sha2-512", KEY_RSA_CERT, 0, 1, 1 },
144 	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", NULL,
145 	    KEY_DSA_CERT, 0, 1, 0 },
146 # ifdef OPENSSL_HAS_ECC
147 	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT", NULL,
148 	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
149 	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT", NULL,
150 	    KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
151 #  ifdef OPENSSL_HAS_NISTP521
152 	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT", NULL,
153 	   KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
154 #  endif /* OPENSSL_HAS_NISTP521 */
155 	{ "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-SK-CERT", NULL,
156 	    KEY_ECDSA_SK_CERT, NID_X9_62_prime256v1, 1, 0 },
157 # endif /* OPENSSL_HAS_ECC */
158 #endif /* WITH_OPENSSL */
159 	{ NULL, NULL, NULL, -1, -1, 0, 0 }
160 };
161 
162 const char *
163 sshkey_type(const struct sshkey *k)
164 {
165 	const struct keytype *kt;
166 
167 	for (kt = keytypes; kt->type != -1; kt++) {
168 		if (kt->type == k->type)
169 			return kt->shortname;
170 	}
171 	return "unknown";
172 }
173 
174 static const char *
175 sshkey_ssh_name_from_type_nid(int type, int nid)
176 {
177 	const struct keytype *kt;
178 
179 	for (kt = keytypes; kt->type != -1; kt++) {
180 		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
181 			return kt->name;
182 	}
183 	return "ssh-unknown";
184 }
185 
186 int
187 sshkey_type_is_cert(int type)
188 {
189 	const struct keytype *kt;
190 
191 	for (kt = keytypes; kt->type != -1; kt++) {
192 		if (kt->type == type)
193 			return kt->cert;
194 	}
195 	return 0;
196 }
197 
198 const char *
199 sshkey_ssh_name(const struct sshkey *k)
200 {
201 	return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
202 }
203 
204 const char *
205 sshkey_ssh_name_plain(const struct sshkey *k)
206 {
207 	return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
208 	    k->ecdsa_nid);
209 }
210 
211 int
212 sshkey_type_from_name(const char *name)
213 {
214 	const struct keytype *kt;
215 
216 	for (kt = keytypes; kt->type != -1; kt++) {
217 		/* Only allow shortname matches for plain key types */
218 		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
219 		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
220 			return kt->type;
221 	}
222 	return KEY_UNSPEC;
223 }
224 
225 static int
226 key_type_is_ecdsa_variant(int type)
227 {
228 	switch (type) {
229 	case KEY_ECDSA:
230 	case KEY_ECDSA_CERT:
231 	case KEY_ECDSA_SK:
232 	case KEY_ECDSA_SK_CERT:
233 		return 1;
234 	}
235 	return 0;
236 }
237 
238 int
239 sshkey_ecdsa_nid_from_name(const char *name)
240 {
241 	const struct keytype *kt;
242 
243 	for (kt = keytypes; kt->type != -1; kt++) {
244 		if (!key_type_is_ecdsa_variant(kt->type))
245 			continue;
246 		if (kt->name != NULL && strcmp(name, kt->name) == 0)
247 			return kt->nid;
248 	}
249 	return -1;
250 }
251 
252 char *
253 sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
254 {
255 	char *tmp, *ret = NULL;
256 	size_t nlen, rlen = 0;
257 	const struct keytype *kt;
258 
259 	for (kt = keytypes; kt->type != -1; kt++) {
260 		if (kt->name == NULL)
261 			continue;
262 		if (!include_sigonly && kt->sigonly)
263 			continue;
264 		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
265 			continue;
266 		if (ret != NULL)
267 			ret[rlen++] = sep;
268 		nlen = strlen(kt->name);
269 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
270 			free(ret);
271 			return NULL;
272 		}
273 		ret = tmp;
274 		memcpy(ret + rlen, kt->name, nlen + 1);
275 		rlen += nlen;
276 	}
277 	return ret;
278 }
279 
280 int
281 sshkey_names_valid2(const char *names, int allow_wildcard)
282 {
283 	char *s, *cp, *p;
284 	const struct keytype *kt;
285 	int type;
286 
287 	if (names == NULL || strcmp(names, "") == 0)
288 		return 0;
289 	if ((s = cp = strdup(names)) == NULL)
290 		return 0;
291 	for ((p = strsep(&cp, ",")); p && *p != '\0';
292 	    (p = strsep(&cp, ","))) {
293 		type = sshkey_type_from_name(p);
294 		if (type == KEY_UNSPEC) {
295 			if (allow_wildcard) {
296 				/*
297 				 * Try matching key types against the string.
298 				 * If any has a positive or negative match then
299 				 * the component is accepted.
300 				 */
301 				for (kt = keytypes; kt->type != -1; kt++) {
302 					if (match_pattern_list(kt->name,
303 					    p, 0) != 0)
304 						break;
305 				}
306 				if (kt->type != -1)
307 					continue;
308 			}
309 			free(s);
310 			return 0;
311 		}
312 	}
313 	free(s);
314 	return 1;
315 }
316 
317 u_int
318 sshkey_size(const struct sshkey *k)
319 {
320 #ifdef WITH_OPENSSL
321 	const BIGNUM *rsa_n, *dsa_p;
322 #endif /* WITH_OPENSSL */
323 
324 	switch (k->type) {
325 #ifdef WITH_OPENSSL
326 	case KEY_RSA:
327 	case KEY_RSA_CERT:
328 		if (k->rsa == NULL)
329 			return 0;
330 		RSA_get0_key(k->rsa, &rsa_n, NULL, NULL);
331 		return BN_num_bits(rsa_n);
332 	case KEY_DSA:
333 	case KEY_DSA_CERT:
334 		if (k->dsa == NULL)
335 			return 0;
336 		DSA_get0_pqg(k->dsa, &dsa_p, NULL, NULL);
337 		return BN_num_bits(dsa_p);
338 	case KEY_ECDSA:
339 	case KEY_ECDSA_CERT:
340 	case KEY_ECDSA_SK:
341 	case KEY_ECDSA_SK_CERT:
342 		return sshkey_curve_nid_to_bits(k->ecdsa_nid);
343 #endif /* WITH_OPENSSL */
344 	case KEY_ED25519:
345 	case KEY_ED25519_CERT:
346 	case KEY_ED25519_SK:
347 	case KEY_ED25519_SK_CERT:
348 	case KEY_XMSS:
349 	case KEY_XMSS_CERT:
350 		return 256;	/* XXX */
351 	}
352 	return 0;
353 }
354 
355 static int
356 sshkey_type_is_valid_ca(int type)
357 {
358 	switch (type) {
359 	case KEY_RSA:
360 	case KEY_DSA:
361 	case KEY_ECDSA:
362 	case KEY_ECDSA_SK:
363 	case KEY_ED25519:
364 	case KEY_ED25519_SK:
365 	case KEY_XMSS:
366 		return 1;
367 	default:
368 		return 0;
369 	}
370 }
371 
372 int
373 sshkey_is_cert(const struct sshkey *k)
374 {
375 	if (k == NULL)
376 		return 0;
377 	return sshkey_type_is_cert(k->type);
378 }
379 
380 int
381 sshkey_is_sk(const struct sshkey *k)
382 {
383 	if (k == NULL)
384 		return 0;
385 	switch (sshkey_type_plain(k->type)) {
386 	case KEY_ECDSA_SK:
387 	case KEY_ED25519_SK:
388 		return 1;
389 	default:
390 		return 0;
391 	}
392 }
393 
394 /* Return the cert-less equivalent to a certified key type */
395 int
396 sshkey_type_plain(int type)
397 {
398 	switch (type) {
399 	case KEY_RSA_CERT:
400 		return KEY_RSA;
401 	case KEY_DSA_CERT:
402 		return KEY_DSA;
403 	case KEY_ECDSA_CERT:
404 		return KEY_ECDSA;
405 	case KEY_ECDSA_SK_CERT:
406 		return KEY_ECDSA_SK;
407 	case KEY_ED25519_CERT:
408 		return KEY_ED25519;
409 	case KEY_ED25519_SK_CERT:
410 		return KEY_ED25519_SK;
411 	case KEY_XMSS_CERT:
412 		return KEY_XMSS;
413 	default:
414 		return type;
415 	}
416 }
417 
418 #ifdef WITH_OPENSSL
419 /* XXX: these are really begging for a table-driven approach */
420 int
421 sshkey_curve_name_to_nid(const char *name)
422 {
423 	if (strcmp(name, "nistp256") == 0)
424 		return NID_X9_62_prime256v1;
425 	else if (strcmp(name, "nistp384") == 0)
426 		return NID_secp384r1;
427 # ifdef OPENSSL_HAS_NISTP521
428 	else if (strcmp(name, "nistp521") == 0)
429 		return NID_secp521r1;
430 # endif /* OPENSSL_HAS_NISTP521 */
431 	else
432 		return -1;
433 }
434 
435 u_int
436 sshkey_curve_nid_to_bits(int nid)
437 {
438 	switch (nid) {
439 	case NID_X9_62_prime256v1:
440 		return 256;
441 	case NID_secp384r1:
442 		return 384;
443 # ifdef OPENSSL_HAS_NISTP521
444 	case NID_secp521r1:
445 		return 521;
446 # endif /* OPENSSL_HAS_NISTP521 */
447 	default:
448 		return 0;
449 	}
450 }
451 
452 int
453 sshkey_ecdsa_bits_to_nid(int bits)
454 {
455 	switch (bits) {
456 	case 256:
457 		return NID_X9_62_prime256v1;
458 	case 384:
459 		return NID_secp384r1;
460 # ifdef OPENSSL_HAS_NISTP521
461 	case 521:
462 		return NID_secp521r1;
463 # endif /* OPENSSL_HAS_NISTP521 */
464 	default:
465 		return -1;
466 	}
467 }
468 
469 const char *
470 sshkey_curve_nid_to_name(int nid)
471 {
472 	switch (nid) {
473 	case NID_X9_62_prime256v1:
474 		return "nistp256";
475 	case NID_secp384r1:
476 		return "nistp384";
477 # ifdef OPENSSL_HAS_NISTP521
478 	case NID_secp521r1:
479 		return "nistp521";
480 # endif /* OPENSSL_HAS_NISTP521 */
481 	default:
482 		return NULL;
483 	}
484 }
485 
486 int
487 sshkey_ec_nid_to_hash_alg(int nid)
488 {
489 	int kbits = sshkey_curve_nid_to_bits(nid);
490 
491 	if (kbits <= 0)
492 		return -1;
493 
494 	/* RFC5656 section 6.2.1 */
495 	if (kbits <= 256)
496 		return SSH_DIGEST_SHA256;
497 	else if (kbits <= 384)
498 		return SSH_DIGEST_SHA384;
499 	else
500 		return SSH_DIGEST_SHA512;
501 }
502 #endif /* WITH_OPENSSL */
503 
504 static void
505 cert_free(struct sshkey_cert *cert)
506 {
507 	u_int i;
508 
509 	if (cert == NULL)
510 		return;
511 	sshbuf_free(cert->certblob);
512 	sshbuf_free(cert->critical);
513 	sshbuf_free(cert->extensions);
514 	free(cert->key_id);
515 	for (i = 0; i < cert->nprincipals; i++)
516 		free(cert->principals[i]);
517 	free(cert->principals);
518 	sshkey_free(cert->signature_key);
519 	free(cert->signature_type);
520 	freezero(cert, sizeof(*cert));
521 }
522 
523 static struct sshkey_cert *
524 cert_new(void)
525 {
526 	struct sshkey_cert *cert;
527 
528 	if ((cert = calloc(1, sizeof(*cert))) == NULL)
529 		return NULL;
530 	if ((cert->certblob = sshbuf_new()) == NULL ||
531 	    (cert->critical = sshbuf_new()) == NULL ||
532 	    (cert->extensions = sshbuf_new()) == NULL) {
533 		cert_free(cert);
534 		return NULL;
535 	}
536 	cert->key_id = NULL;
537 	cert->principals = NULL;
538 	cert->signature_key = NULL;
539 	cert->signature_type = NULL;
540 	return cert;
541 }
542 
543 struct sshkey *
544 sshkey_new(int type)
545 {
546 	struct sshkey *k;
547 #ifdef WITH_OPENSSL
548 	RSA *rsa;
549 	DSA *dsa;
550 #endif /* WITH_OPENSSL */
551 
552 	if ((k = calloc(1, sizeof(*k))) == NULL)
553 		return NULL;
554 	k->type = type;
555 	k->ecdsa = NULL;
556 	k->ecdsa_nid = -1;
557 	k->dsa = NULL;
558 	k->rsa = NULL;
559 	k->cert = NULL;
560 	k->ed25519_sk = NULL;
561 	k->ed25519_pk = NULL;
562 	k->xmss_sk = NULL;
563 	k->xmss_pk = NULL;
564 	switch (k->type) {
565 #ifdef WITH_OPENSSL
566 	case KEY_RSA:
567 	case KEY_RSA_CERT:
568 		if ((rsa = RSA_new()) == NULL) {
569 			free(k);
570 			return NULL;
571 		}
572 		k->rsa = rsa;
573 		break;
574 	case KEY_DSA:
575 	case KEY_DSA_CERT:
576 		if ((dsa = DSA_new()) == NULL) {
577 			free(k);
578 			return NULL;
579 		}
580 		k->dsa = dsa;
581 		break;
582 	case KEY_ECDSA:
583 	case KEY_ECDSA_CERT:
584 	case KEY_ECDSA_SK:
585 	case KEY_ECDSA_SK_CERT:
586 		/* Cannot do anything until we know the group */
587 		break;
588 #endif /* WITH_OPENSSL */
589 	case KEY_ED25519:
590 	case KEY_ED25519_CERT:
591 	case KEY_ED25519_SK:
592 	case KEY_ED25519_SK_CERT:
593 	case KEY_XMSS:
594 	case KEY_XMSS_CERT:
595 		/* no need to prealloc */
596 		break;
597 	case KEY_UNSPEC:
598 		break;
599 	default:
600 		free(k);
601 		return NULL;
602 	}
603 
604 	if (sshkey_is_cert(k)) {
605 		if ((k->cert = cert_new()) == NULL) {
606 			sshkey_free(k);
607 			return NULL;
608 		}
609 	}
610 
611 	return k;
612 }
613 
614 void
615 sshkey_free(struct sshkey *k)
616 {
617 	if (k == NULL)
618 		return;
619 	switch (k->type) {
620 #ifdef WITH_OPENSSL
621 	case KEY_RSA:
622 	case KEY_RSA_CERT:
623 		RSA_free(k->rsa);
624 		k->rsa = NULL;
625 		break;
626 	case KEY_DSA:
627 	case KEY_DSA_CERT:
628 		DSA_free(k->dsa);
629 		k->dsa = NULL;
630 		break;
631 # ifdef OPENSSL_HAS_ECC
632 	case KEY_ECDSA_SK:
633 	case KEY_ECDSA_SK_CERT:
634 		free(k->sk_application);
635 		sshbuf_free(k->sk_key_handle);
636 		sshbuf_free(k->sk_reserved);
637 		/* FALLTHROUGH */
638 	case KEY_ECDSA:
639 	case KEY_ECDSA_CERT:
640 		EC_KEY_free(k->ecdsa);
641 		k->ecdsa = NULL;
642 		break;
643 # endif /* OPENSSL_HAS_ECC */
644 #endif /* WITH_OPENSSL */
645 	case KEY_ED25519_SK:
646 	case KEY_ED25519_SK_CERT:
647 		free(k->sk_application);
648 		sshbuf_free(k->sk_key_handle);
649 		sshbuf_free(k->sk_reserved);
650 		/* FALLTHROUGH */
651 	case KEY_ED25519:
652 	case KEY_ED25519_CERT:
653 		freezero(k->ed25519_pk, ED25519_PK_SZ);
654 		k->ed25519_pk = NULL;
655 		freezero(k->ed25519_sk, ED25519_SK_SZ);
656 		k->ed25519_sk = NULL;
657 		break;
658 #ifdef WITH_XMSS
659 	case KEY_XMSS:
660 	case KEY_XMSS_CERT:
661 		freezero(k->xmss_pk, sshkey_xmss_pklen(k));
662 		k->xmss_pk = NULL;
663 		freezero(k->xmss_sk, sshkey_xmss_sklen(k));
664 		k->xmss_sk = NULL;
665 		sshkey_xmss_free_state(k);
666 		free(k->xmss_name);
667 		k->xmss_name = NULL;
668 		free(k->xmss_filename);
669 		k->xmss_filename = NULL;
670 		break;
671 #endif /* WITH_XMSS */
672 	case KEY_UNSPEC:
673 		break;
674 	default:
675 		break;
676 	}
677 	if (sshkey_is_cert(k))
678 		cert_free(k->cert);
679 	freezero(k->shielded_private, k->shielded_len);
680 	freezero(k->shield_prekey, k->shield_prekey_len);
681 	freezero(k, sizeof(*k));
682 }
683 
684 static int
685 cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
686 {
687 	if (a == NULL && b == NULL)
688 		return 1;
689 	if (a == NULL || b == NULL)
690 		return 0;
691 	if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
692 		return 0;
693 	if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
694 	    sshbuf_len(a->certblob)) != 0)
695 		return 0;
696 	return 1;
697 }
698 
699 /*
700  * Compare public portions of key only, allowing comparisons between
701  * certificates and plain keys too.
702  */
703 int
704 sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
705 {
706 #if defined(WITH_OPENSSL)
707 	const BIGNUM *rsa_e_a, *rsa_n_a;
708 	const BIGNUM *rsa_e_b, *rsa_n_b;
709 	const BIGNUM *dsa_p_a, *dsa_q_a, *dsa_g_a, *dsa_pub_key_a;
710 	const BIGNUM *dsa_p_b, *dsa_q_b, *dsa_g_b, *dsa_pub_key_b;
711 #endif /* WITH_OPENSSL */
712 
713 	if (a == NULL || b == NULL ||
714 	    sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
715 		return 0;
716 
717 	switch (a->type) {
718 #ifdef WITH_OPENSSL
719 	case KEY_RSA_CERT:
720 	case KEY_RSA:
721 		if (a->rsa == NULL || b->rsa == NULL)
722 			return 0;
723 		RSA_get0_key(a->rsa, &rsa_n_a, &rsa_e_a, NULL);
724 		RSA_get0_key(b->rsa, &rsa_n_b, &rsa_e_b, NULL);
725 		return BN_cmp(rsa_e_a, rsa_e_b) == 0 &&
726 		    BN_cmp(rsa_n_a, rsa_n_b) == 0;
727 	case KEY_DSA_CERT:
728 	case KEY_DSA:
729 		if (a->dsa == NULL || b->dsa == NULL)
730 			return 0;
731 		DSA_get0_pqg(a->dsa, &dsa_p_a, &dsa_q_a, &dsa_g_a);
732 		DSA_get0_pqg(b->dsa, &dsa_p_b, &dsa_q_b, &dsa_g_b);
733 		DSA_get0_key(a->dsa, &dsa_pub_key_a, NULL);
734 		DSA_get0_key(b->dsa, &dsa_pub_key_b, NULL);
735 		return BN_cmp(dsa_p_a, dsa_p_b) == 0 &&
736 		    BN_cmp(dsa_q_a, dsa_q_b) == 0 &&
737 		    BN_cmp(dsa_g_a, dsa_g_b) == 0 &&
738 		    BN_cmp(dsa_pub_key_a, dsa_pub_key_b) == 0;
739 # ifdef OPENSSL_HAS_ECC
740 	case KEY_ECDSA_SK:
741 	case KEY_ECDSA_SK_CERT:
742 		if (a->sk_application == NULL || b->sk_application == NULL)
743 			return 0;
744 		if (strcmp(a->sk_application, b->sk_application) != 0)
745 			return 0;
746 		/* FALLTHROUGH */
747 	case KEY_ECDSA_CERT:
748 	case KEY_ECDSA:
749 		if (a->ecdsa == NULL || b->ecdsa == NULL ||
750 		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
751 		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
752 			return 0;
753 		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
754 		    EC_KEY_get0_group(b->ecdsa), NULL) != 0 ||
755 		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
756 		    EC_KEY_get0_public_key(a->ecdsa),
757 		    EC_KEY_get0_public_key(b->ecdsa), NULL) != 0)
758 			return 0;
759 		return 1;
760 # endif /* OPENSSL_HAS_ECC */
761 #endif /* WITH_OPENSSL */
762 	case KEY_ED25519_SK:
763 	case KEY_ED25519_SK_CERT:
764 		if (a->sk_application == NULL || b->sk_application == NULL)
765 			return 0;
766 		if (strcmp(a->sk_application, b->sk_application) != 0)
767 			return 0;
768 		/* FALLTHROUGH */
769 	case KEY_ED25519:
770 	case KEY_ED25519_CERT:
771 		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
772 		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
773 #ifdef WITH_XMSS
774 	case KEY_XMSS:
775 	case KEY_XMSS_CERT:
776 		return a->xmss_pk != NULL && b->xmss_pk != NULL &&
777 		    sshkey_xmss_pklen(a) == sshkey_xmss_pklen(b) &&
778 		    memcmp(a->xmss_pk, b->xmss_pk, sshkey_xmss_pklen(a)) == 0;
779 #endif /* WITH_XMSS */
780 	default:
781 		return 0;
782 	}
783 	/* NOTREACHED */
784 }
785 
786 int
787 sshkey_equal(const struct sshkey *a, const struct sshkey *b)
788 {
789 	if (a == NULL || b == NULL || a->type != b->type)
790 		return 0;
791 	if (sshkey_is_cert(a)) {
792 		if (!cert_compare(a->cert, b->cert))
793 			return 0;
794 	}
795 	return sshkey_equal_public(a, b);
796 }
797 
798 static int
799 to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain,
800   enum sshkey_serialize_rep opts)
801 {
802 	int type, ret = SSH_ERR_INTERNAL_ERROR;
803 	const char *typename;
804 #ifdef WITH_OPENSSL
805 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
806 #endif /* WITH_OPENSSL */
807 
808 	if (key == NULL)
809 		return SSH_ERR_INVALID_ARGUMENT;
810 
811 	if (sshkey_is_cert(key)) {
812 		if (key->cert == NULL)
813 			return SSH_ERR_EXPECTED_CERT;
814 		if (sshbuf_len(key->cert->certblob) == 0)
815 			return SSH_ERR_KEY_LACKS_CERTBLOB;
816 	}
817 	type = force_plain ? sshkey_type_plain(key->type) : key->type;
818 	typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
819 
820 	switch (type) {
821 #ifdef WITH_OPENSSL
822 	case KEY_DSA_CERT:
823 	case KEY_ECDSA_CERT:
824 	case KEY_ECDSA_SK_CERT:
825 	case KEY_RSA_CERT:
826 #endif /* WITH_OPENSSL */
827 	case KEY_ED25519_CERT:
828 	case KEY_ED25519_SK_CERT:
829 #ifdef WITH_XMSS
830 	case KEY_XMSS_CERT:
831 #endif /* WITH_XMSS */
832 		/* Use the existing blob */
833 		/* XXX modified flag? */
834 		if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
835 			return ret;
836 		break;
837 #ifdef WITH_OPENSSL
838 	case KEY_DSA:
839 		if (key->dsa == NULL)
840 			return SSH_ERR_INVALID_ARGUMENT;
841 		DSA_get0_pqg(key->dsa, &dsa_p, &dsa_q, &dsa_g);
842 		DSA_get0_key(key->dsa, &dsa_pub_key, NULL);
843 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
844 		    (ret = sshbuf_put_bignum2(b, dsa_p)) != 0 ||
845 		    (ret = sshbuf_put_bignum2(b, dsa_q)) != 0 ||
846 		    (ret = sshbuf_put_bignum2(b, dsa_g)) != 0 ||
847 		    (ret = sshbuf_put_bignum2(b, dsa_pub_key)) != 0)
848 			return ret;
849 		break;
850 # ifdef OPENSSL_HAS_ECC
851 	case KEY_ECDSA:
852 	case KEY_ECDSA_SK:
853 		if (key->ecdsa == NULL)
854 			return SSH_ERR_INVALID_ARGUMENT;
855 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
856 		    (ret = sshbuf_put_cstring(b,
857 		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
858 		    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
859 			return ret;
860 		if (type == KEY_ECDSA_SK) {
861 			if ((ret = sshbuf_put_cstring(b,
862 			    key->sk_application)) != 0)
863 				return ret;
864 		}
865 		break;
866 # endif
867 	case KEY_RSA:
868 		if (key->rsa == NULL)
869 			return SSH_ERR_INVALID_ARGUMENT;
870 		RSA_get0_key(key->rsa, &rsa_n, &rsa_e, NULL);
871 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
872 		    (ret = sshbuf_put_bignum2(b, rsa_e)) != 0 ||
873 		    (ret = sshbuf_put_bignum2(b, rsa_n)) != 0)
874 			return ret;
875 		break;
876 #endif /* WITH_OPENSSL */
877 	case KEY_ED25519:
878 	case KEY_ED25519_SK:
879 		if (key->ed25519_pk == NULL)
880 			return SSH_ERR_INVALID_ARGUMENT;
881 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
882 		    (ret = sshbuf_put_string(b,
883 		    key->ed25519_pk, ED25519_PK_SZ)) != 0)
884 			return ret;
885 		if (type == KEY_ED25519_SK) {
886 			if ((ret = sshbuf_put_cstring(b,
887 			    key->sk_application)) != 0)
888 				return ret;
889 		}
890 		break;
891 #ifdef WITH_XMSS
892 	case KEY_XMSS:
893 		if (key->xmss_name == NULL || key->xmss_pk == NULL ||
894 		    sshkey_xmss_pklen(key) == 0)
895 			return SSH_ERR_INVALID_ARGUMENT;
896 		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
897 		    (ret = sshbuf_put_cstring(b, key->xmss_name)) != 0 ||
898 		    (ret = sshbuf_put_string(b,
899 		    key->xmss_pk, sshkey_xmss_pklen(key))) != 0 ||
900 		    (ret = sshkey_xmss_serialize_pk_info(key, b, opts)) != 0)
901 			return ret;
902 		break;
903 #endif /* WITH_XMSS */
904 	default:
905 		return SSH_ERR_KEY_TYPE_UNKNOWN;
906 	}
907 	return 0;
908 }
909 
910 int
911 sshkey_putb(const struct sshkey *key, struct sshbuf *b)
912 {
913 	return to_blob_buf(key, b, 0, SSHKEY_SERIALIZE_DEFAULT);
914 }
915 
916 int
917 sshkey_puts_opts(const struct sshkey *key, struct sshbuf *b,
918     enum sshkey_serialize_rep opts)
919 {
920 	struct sshbuf *tmp;
921 	int r;
922 
923 	if ((tmp = sshbuf_new()) == NULL)
924 		return SSH_ERR_ALLOC_FAIL;
925 	r = to_blob_buf(key, tmp, 0, opts);
926 	if (r == 0)
927 		r = sshbuf_put_stringb(b, tmp);
928 	sshbuf_free(tmp);
929 	return r;
930 }
931 
932 int
933 sshkey_puts(const struct sshkey *key, struct sshbuf *b)
934 {
935 	return sshkey_puts_opts(key, b, SSHKEY_SERIALIZE_DEFAULT);
936 }
937 
938 int
939 sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
940 {
941 	return to_blob_buf(key, b, 1, SSHKEY_SERIALIZE_DEFAULT);
942 }
943 
944 static int
945 to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain,
946     enum sshkey_serialize_rep opts)
947 {
948 	int ret = SSH_ERR_INTERNAL_ERROR;
949 	size_t len;
950 	struct sshbuf *b = NULL;
951 
952 	if (lenp != NULL)
953 		*lenp = 0;
954 	if (blobp != NULL)
955 		*blobp = NULL;
956 	if ((b = sshbuf_new()) == NULL)
957 		return SSH_ERR_ALLOC_FAIL;
958 	if ((ret = to_blob_buf(key, b, force_plain, opts)) != 0)
959 		goto out;
960 	len = sshbuf_len(b);
961 	if (lenp != NULL)
962 		*lenp = len;
963 	if (blobp != NULL) {
964 		if ((*blobp = malloc(len)) == NULL) {
965 			ret = SSH_ERR_ALLOC_FAIL;
966 			goto out;
967 		}
968 		memcpy(*blobp, sshbuf_ptr(b), len);
969 	}
970 	ret = 0;
971  out:
972 	sshbuf_free(b);
973 	return ret;
974 }
975 
976 int
977 sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
978 {
979 	return to_blob(key, blobp, lenp, 0, SSHKEY_SERIALIZE_DEFAULT);
980 }
981 
982 int
983 sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
984 {
985 	return to_blob(key, blobp, lenp, 1, SSHKEY_SERIALIZE_DEFAULT);
986 }
987 
988 int
989 sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
990     u_char **retp, size_t *lenp)
991 {
992 	u_char *blob = NULL, *ret = NULL;
993 	size_t blob_len = 0;
994 	int r = SSH_ERR_INTERNAL_ERROR;
995 
996 	if (retp != NULL)
997 		*retp = NULL;
998 	if (lenp != NULL)
999 		*lenp = 0;
1000 	if (ssh_digest_bytes(dgst_alg) == 0) {
1001 		r = SSH_ERR_INVALID_ARGUMENT;
1002 		goto out;
1003 	}
1004 	if ((r = to_blob(k, &blob, &blob_len, 1, SSHKEY_SERIALIZE_DEFAULT))
1005 	    != 0)
1006 		goto out;
1007 	if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
1008 		r = SSH_ERR_ALLOC_FAIL;
1009 		goto out;
1010 	}
1011 	if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
1012 	    ret, SSH_DIGEST_MAX_LENGTH)) != 0)
1013 		goto out;
1014 	/* success */
1015 	if (retp != NULL) {
1016 		*retp = ret;
1017 		ret = NULL;
1018 	}
1019 	if (lenp != NULL)
1020 		*lenp = ssh_digest_bytes(dgst_alg);
1021 	r = 0;
1022  out:
1023 	free(ret);
1024 	if (blob != NULL)
1025 		freezero(blob, blob_len);
1026 	return r;
1027 }
1028 
1029 static char *
1030 fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1031 {
1032 	char *ret;
1033 	size_t plen = strlen(alg) + 1;
1034 	size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
1035 
1036 	if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
1037 		return NULL;
1038 	strlcpy(ret, alg, rlen);
1039 	strlcat(ret, ":", rlen);
1040 	if (dgst_raw_len == 0)
1041 		return ret;
1042 	if (b64_ntop(dgst_raw, dgst_raw_len, ret + plen, rlen - plen) == -1) {
1043 		freezero(ret, rlen);
1044 		return NULL;
1045 	}
1046 	/* Trim padding characters from end */
1047 	ret[strcspn(ret, "=")] = '\0';
1048 	return ret;
1049 }
1050 
1051 static char *
1052 fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
1053 {
1054 	char *retval, hex[5];
1055 	size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
1056 
1057 	if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
1058 		return NULL;
1059 	strlcpy(retval, alg, rlen);
1060 	strlcat(retval, ":", rlen);
1061 	for (i = 0; i < dgst_raw_len; i++) {
1062 		snprintf(hex, sizeof(hex), "%s%02x",
1063 		    i > 0 ? ":" : "", dgst_raw[i]);
1064 		strlcat(retval, hex, rlen);
1065 	}
1066 	return retval;
1067 }
1068 
1069 static char *
1070 fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
1071 {
1072 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
1073 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
1074 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
1075 	u_int i, j = 0, rounds, seed = 1;
1076 	char *retval;
1077 
1078 	rounds = (dgst_raw_len / 2) + 1;
1079 	if ((retval = calloc(rounds, 6)) == NULL)
1080 		return NULL;
1081 	retval[j++] = 'x';
1082 	for (i = 0; i < rounds; i++) {
1083 		u_int idx0, idx1, idx2, idx3, idx4;
1084 		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
1085 			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
1086 			    seed) % 6;
1087 			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
1088 			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
1089 			    (seed / 6)) % 6;
1090 			retval[j++] = vowels[idx0];
1091 			retval[j++] = consonants[idx1];
1092 			retval[j++] = vowels[idx2];
1093 			if ((i + 1) < rounds) {
1094 				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
1095 				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
1096 				retval[j++] = consonants[idx3];
1097 				retval[j++] = '-';
1098 				retval[j++] = consonants[idx4];
1099 				seed = ((seed * 5) +
1100 				    ((((u_int)(dgst_raw[2 * i])) * 7) +
1101 				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
1102 			}
1103 		} else {
1104 			idx0 = seed % 6;
1105 			idx1 = 16;
1106 			idx2 = seed / 6;
1107 			retval[j++] = vowels[idx0];
1108 			retval[j++] = consonants[idx1];
1109 			retval[j++] = vowels[idx2];
1110 		}
1111 	}
1112 	retval[j++] = 'x';
1113 	retval[j++] = '\0';
1114 	return retval;
1115 }
1116 
1117 /*
1118  * Draw an ASCII-Art representing the fingerprint so human brain can
1119  * profit from its built-in pattern recognition ability.
1120  * This technique is called "random art" and can be found in some
1121  * scientific publications like this original paper:
1122  *
1123  * "Hash Visualization: a New Technique to improve Real-World Security",
1124  * Perrig A. and Song D., 1999, International Workshop on Cryptographic
1125  * Techniques and E-Commerce (CrypTEC '99)
1126  * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
1127  *
1128  * The subject came up in a talk by Dan Kaminsky, too.
1129  *
1130  * If you see the picture is different, the key is different.
1131  * If the picture looks the same, you still know nothing.
1132  *
1133  * The algorithm used here is a worm crawling over a discrete plane,
1134  * leaving a trace (augmenting the field) everywhere it goes.
1135  * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
1136  * makes the respective movement vector be ignored for this turn.
1137  * Graphs are not unambiguous, because circles in graphs can be
1138  * walked in either direction.
1139  */
1140 
1141 /*
1142  * Field sizes for the random art.  Have to be odd, so the starting point
1143  * can be in the exact middle of the picture, and FLDBASE should be >=8 .
1144  * Else pictures would be too dense, and drawing the frame would
1145  * fail, too, because the key type would not fit in anymore.
1146  */
1147 #define	FLDBASE		8
1148 #define	FLDSIZE_Y	(FLDBASE + 1)
1149 #define	FLDSIZE_X	(FLDBASE * 2 + 1)
1150 static char *
1151 fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
1152     const struct sshkey *k)
1153 {
1154 	/*
1155 	 * Chars to be used after each other every time the worm
1156 	 * intersects with itself.  Matter of taste.
1157 	 */
1158 	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
1159 	char	*retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1160 	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
1161 	size_t	 i, tlen, hlen;
1162 	u_int	 b;
1163 	int	 x, y, r;
1164 	size_t	 len = strlen(augmentation_string) - 1;
1165 
1166 	if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1167 		return NULL;
1168 
1169 	/* initialize field */
1170 	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1171 	x = FLDSIZE_X / 2;
1172 	y = FLDSIZE_Y / 2;
1173 
1174 	/* process raw key */
1175 	for (i = 0; i < dgst_raw_len; i++) {
1176 		int input;
1177 		/* each byte conveys four 2-bit move commands */
1178 		input = dgst_raw[i];
1179 		for (b = 0; b < 4; b++) {
1180 			/* evaluate 2 bit, rest is shifted later */
1181 			x += (input & 0x1) ? 1 : -1;
1182 			y += (input & 0x2) ? 1 : -1;
1183 
1184 			/* assure we are still in bounds */
1185 			x = MAXIMUM(x, 0);
1186 			y = MAXIMUM(y, 0);
1187 			x = MINIMUM(x, FLDSIZE_X - 1);
1188 			y = MINIMUM(y, FLDSIZE_Y - 1);
1189 
1190 			/* augment the field */
1191 			if (field[x][y] < len - 2)
1192 				field[x][y]++;
1193 			input = input >> 2;
1194 		}
1195 	}
1196 
1197 	/* mark starting point and end point*/
1198 	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1199 	field[x][y] = len;
1200 
1201 	/* assemble title */
1202 	r = snprintf(title, sizeof(title), "[%s %u]",
1203 		sshkey_type(k), sshkey_size(k));
1204 	/* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1205 	if (r < 0 || r > (int)sizeof(title))
1206 		r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1207 	tlen = (r <= 0) ? 0 : strlen(title);
1208 
1209 	/* assemble hash ID. */
1210 	r = snprintf(hash, sizeof(hash), "[%s]", alg);
1211 	hlen = (r <= 0) ? 0 : strlen(hash);
1212 
1213 	/* output upper border */
1214 	p = retval;
1215 	*p++ = '+';
1216 	for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1217 		*p++ = '-';
1218 	memcpy(p, title, tlen);
1219 	p += tlen;
1220 	for (i += tlen; i < FLDSIZE_X; i++)
1221 		*p++ = '-';
1222 	*p++ = '+';
1223 	*p++ = '\n';
1224 
1225 	/* output content */
1226 	for (y = 0; y < FLDSIZE_Y; y++) {
1227 		*p++ = '|';
1228 		for (x = 0; x < FLDSIZE_X; x++)
1229 			*p++ = augmentation_string[MINIMUM(field[x][y], len)];
1230 		*p++ = '|';
1231 		*p++ = '\n';
1232 	}
1233 
1234 	/* output lower border */
1235 	*p++ = '+';
1236 	for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1237 		*p++ = '-';
1238 	memcpy(p, hash, hlen);
1239 	p += hlen;
1240 	for (i += hlen; i < FLDSIZE_X; i++)
1241 		*p++ = '-';
1242 	*p++ = '+';
1243 
1244 	return retval;
1245 }
1246 
1247 char *
1248 sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1249     enum sshkey_fp_rep dgst_rep)
1250 {
1251 	char *retval = NULL;
1252 	u_char *dgst_raw;
1253 	size_t dgst_raw_len;
1254 
1255 	if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1256 		return NULL;
1257 	switch (dgst_rep) {
1258 	case SSH_FP_DEFAULT:
1259 		if (dgst_alg == SSH_DIGEST_MD5) {
1260 			retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1261 			    dgst_raw, dgst_raw_len);
1262 		} else {
1263 			retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1264 			    dgst_raw, dgst_raw_len);
1265 		}
1266 		break;
1267 	case SSH_FP_HEX:
1268 		retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1269 		    dgst_raw, dgst_raw_len);
1270 		break;
1271 	case SSH_FP_BASE64:
1272 		retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1273 		    dgst_raw, dgst_raw_len);
1274 		break;
1275 	case SSH_FP_BUBBLEBABBLE:
1276 		retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1277 		break;
1278 	case SSH_FP_RANDOMART:
1279 		retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1280 		    dgst_raw, dgst_raw_len, k);
1281 		break;
1282 	default:
1283 		freezero(dgst_raw, dgst_raw_len);
1284 		return NULL;
1285 	}
1286 	freezero(dgst_raw, dgst_raw_len);
1287 	return retval;
1288 }
1289 
1290 static int
1291 peek_type_nid(const char *s, size_t l, int *nid)
1292 {
1293 	const struct keytype *kt;
1294 
1295 	for (kt = keytypes; kt->type != -1; kt++) {
1296 		if (kt->name == NULL || strlen(kt->name) != l)
1297 			continue;
1298 		if (memcmp(s, kt->name, l) == 0) {
1299 			*nid = -1;
1300 			if (key_type_is_ecdsa_variant(kt->type))
1301 				*nid = kt->nid;
1302 			return kt->type;
1303 		}
1304 	}
1305 	return KEY_UNSPEC;
1306 }
1307 
1308 /* XXX this can now be made const char * */
1309 int
1310 sshkey_read(struct sshkey *ret, char **cpp)
1311 {
1312 	struct sshkey *k;
1313 	char *cp, *blobcopy;
1314 	size_t space;
1315 	int r, type, curve_nid = -1;
1316 	struct sshbuf *blob;
1317 
1318 	if (ret == NULL)
1319 		return SSH_ERR_INVALID_ARGUMENT;
1320 
1321 	switch (ret->type) {
1322 	case KEY_UNSPEC:
1323 	case KEY_RSA:
1324 	case KEY_DSA:
1325 	case KEY_ECDSA:
1326 	case KEY_ECDSA_SK:
1327 	case KEY_ED25519:
1328 	case KEY_ED25519_SK:
1329 	case KEY_DSA_CERT:
1330 	case KEY_ECDSA_CERT:
1331 	case KEY_ECDSA_SK_CERT:
1332 	case KEY_RSA_CERT:
1333 	case KEY_ED25519_CERT:
1334 	case KEY_ED25519_SK_CERT:
1335 #ifdef WITH_XMSS
1336 	case KEY_XMSS:
1337 	case KEY_XMSS_CERT:
1338 #endif /* WITH_XMSS */
1339 		break; /* ok */
1340 	default:
1341 		return SSH_ERR_INVALID_ARGUMENT;
1342 	}
1343 
1344 	/* Decode type */
1345 	cp = *cpp;
1346 	space = strcspn(cp, " \t");
1347 	if (space == strlen(cp))
1348 		return SSH_ERR_INVALID_FORMAT;
1349 	if ((type = peek_type_nid(cp, space, &curve_nid)) == KEY_UNSPEC)
1350 		return SSH_ERR_INVALID_FORMAT;
1351 
1352 	/* skip whitespace */
1353 	for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1354 		;
1355 	if (*cp == '\0')
1356 		return SSH_ERR_INVALID_FORMAT;
1357 	if (ret->type != KEY_UNSPEC && ret->type != type)
1358 		return SSH_ERR_KEY_TYPE_MISMATCH;
1359 	if ((blob = sshbuf_new()) == NULL)
1360 		return SSH_ERR_ALLOC_FAIL;
1361 
1362 	/* find end of keyblob and decode */
1363 	space = strcspn(cp, " \t");
1364 	if ((blobcopy = strndup(cp, space)) == NULL) {
1365 		sshbuf_free(blob);
1366 		return SSH_ERR_ALLOC_FAIL;
1367 	}
1368 	if ((r = sshbuf_b64tod(blob, blobcopy)) != 0) {
1369 		free(blobcopy);
1370 		sshbuf_free(blob);
1371 		return r;
1372 	}
1373 	free(blobcopy);
1374 	if ((r = sshkey_fromb(blob, &k)) != 0) {
1375 		sshbuf_free(blob);
1376 		return r;
1377 	}
1378 	sshbuf_free(blob);
1379 
1380 	/* skip whitespace and leave cp at start of comment */
1381 	for (cp += space; *cp == ' ' || *cp == '\t'; cp++)
1382 		;
1383 
1384 	/* ensure type of blob matches type at start of line */
1385 	if (k->type != type) {
1386 		sshkey_free(k);
1387 		return SSH_ERR_KEY_TYPE_MISMATCH;
1388 	}
1389 	if (key_type_is_ecdsa_variant(type) && curve_nid != k->ecdsa_nid) {
1390 		sshkey_free(k);
1391 		return SSH_ERR_EC_CURVE_MISMATCH;
1392 	}
1393 
1394 	/* Fill in ret from parsed key */
1395 	ret->type = type;
1396 	if (sshkey_is_cert(ret)) {
1397 		if (!sshkey_is_cert(k)) {
1398 			sshkey_free(k);
1399 			return SSH_ERR_EXPECTED_CERT;
1400 		}
1401 		if (ret->cert != NULL)
1402 			cert_free(ret->cert);
1403 		ret->cert = k->cert;
1404 		k->cert = NULL;
1405 	}
1406 	switch (sshkey_type_plain(ret->type)) {
1407 #ifdef WITH_OPENSSL
1408 	case KEY_RSA:
1409 		RSA_free(ret->rsa);
1410 		ret->rsa = k->rsa;
1411 		k->rsa = NULL;
1412 #ifdef DEBUG_PK
1413 		RSA_print_fp(stderr, ret->rsa, 8);
1414 #endif
1415 		break;
1416 	case KEY_DSA:
1417 		DSA_free(ret->dsa);
1418 		ret->dsa = k->dsa;
1419 		k->dsa = NULL;
1420 #ifdef DEBUG_PK
1421 		DSA_print_fp(stderr, ret->dsa, 8);
1422 #endif
1423 		break;
1424 # ifdef OPENSSL_HAS_ECC
1425 	case KEY_ECDSA:
1426 		EC_KEY_free(ret->ecdsa);
1427 		ret->ecdsa = k->ecdsa;
1428 		ret->ecdsa_nid = k->ecdsa_nid;
1429 		k->ecdsa = NULL;
1430 		k->ecdsa_nid = -1;
1431 #ifdef DEBUG_PK
1432 		sshkey_dump_ec_key(ret->ecdsa);
1433 #endif
1434 		break;
1435 	case KEY_ECDSA_SK:
1436 		EC_KEY_free(ret->ecdsa);
1437 		ret->ecdsa = k->ecdsa;
1438 		ret->ecdsa_nid = k->ecdsa_nid;
1439 		ret->sk_application = k->sk_application;
1440 		k->ecdsa = NULL;
1441 		k->ecdsa_nid = -1;
1442 		k->sk_application = NULL;
1443 #ifdef DEBUG_PK
1444 		sshkey_dump_ec_key(ret->ecdsa);
1445 		fprintf(stderr, "App: %s\n", ret->sk_application);
1446 #endif
1447 		break;
1448 # endif /* OPENSSL_HAS_ECC */
1449 #endif /* WITH_OPENSSL */
1450 	case KEY_ED25519:
1451 		freezero(ret->ed25519_pk, ED25519_PK_SZ);
1452 		ret->ed25519_pk = k->ed25519_pk;
1453 		k->ed25519_pk = NULL;
1454 #ifdef DEBUG_PK
1455 		/* XXX */
1456 #endif
1457 		break;
1458 	case KEY_ED25519_SK:
1459 		freezero(ret->ed25519_pk, ED25519_PK_SZ);
1460 		ret->ed25519_pk = k->ed25519_pk;
1461 		ret->sk_application = k->sk_application;
1462 		k->ed25519_pk = NULL;
1463 		k->sk_application = NULL;
1464 		break;
1465 #ifdef WITH_XMSS
1466 	case KEY_XMSS:
1467 		free(ret->xmss_pk);
1468 		ret->xmss_pk = k->xmss_pk;
1469 		k->xmss_pk = NULL;
1470 		free(ret->xmss_state);
1471 		ret->xmss_state = k->xmss_state;
1472 		k->xmss_state = NULL;
1473 		free(ret->xmss_name);
1474 		ret->xmss_name = k->xmss_name;
1475 		k->xmss_name = NULL;
1476 		free(ret->xmss_filename);
1477 		ret->xmss_filename = k->xmss_filename;
1478 		k->xmss_filename = NULL;
1479 #ifdef DEBUG_PK
1480 		/* XXX */
1481 #endif
1482 		break;
1483 #endif /* WITH_XMSS */
1484 	default:
1485 		sshkey_free(k);
1486 		return SSH_ERR_INTERNAL_ERROR;
1487 	}
1488 	sshkey_free(k);
1489 
1490 	/* success */
1491 	*cpp = cp;
1492 	return 0;
1493 }
1494 
1495 
1496 int
1497 sshkey_to_base64(const struct sshkey *key, char **b64p)
1498 {
1499 	int r = SSH_ERR_INTERNAL_ERROR;
1500 	struct sshbuf *b = NULL;
1501 	char *uu = NULL;
1502 
1503 	if (b64p != NULL)
1504 		*b64p = NULL;
1505 	if ((b = sshbuf_new()) == NULL)
1506 		return SSH_ERR_ALLOC_FAIL;
1507 	if ((r = sshkey_putb(key, b)) != 0)
1508 		goto out;
1509 	if ((uu = sshbuf_dtob64_string(b, 0)) == NULL) {
1510 		r = SSH_ERR_ALLOC_FAIL;
1511 		goto out;
1512 	}
1513 	/* Success */
1514 	if (b64p != NULL) {
1515 		*b64p = uu;
1516 		uu = NULL;
1517 	}
1518 	r = 0;
1519  out:
1520 	sshbuf_free(b);
1521 	free(uu);
1522 	return r;
1523 }
1524 
1525 int
1526 sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1527 {
1528 	int r = SSH_ERR_INTERNAL_ERROR;
1529 	char *uu = NULL;
1530 
1531 	if ((r = sshkey_to_base64(key, &uu)) != 0)
1532 		goto out;
1533 	if ((r = sshbuf_putf(b, "%s %s",
1534 	    sshkey_ssh_name(key), uu)) != 0)
1535 		goto out;
1536 	r = 0;
1537  out:
1538 	free(uu);
1539 	return r;
1540 }
1541 
1542 int
1543 sshkey_write(const struct sshkey *key, FILE *f)
1544 {
1545 	struct sshbuf *b = NULL;
1546 	int r = SSH_ERR_INTERNAL_ERROR;
1547 
1548 	if ((b = sshbuf_new()) == NULL)
1549 		return SSH_ERR_ALLOC_FAIL;
1550 	if ((r = sshkey_format_text(key, b)) != 0)
1551 		goto out;
1552 	if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1553 		if (feof(f))
1554 			errno = EPIPE;
1555 		r = SSH_ERR_SYSTEM_ERROR;
1556 		goto out;
1557 	}
1558 	/* Success */
1559 	r = 0;
1560  out:
1561 	sshbuf_free(b);
1562 	return r;
1563 }
1564 
1565 const char *
1566 sshkey_cert_type(const struct sshkey *k)
1567 {
1568 	switch (k->cert->type) {
1569 	case SSH2_CERT_TYPE_USER:
1570 		return "user";
1571 	case SSH2_CERT_TYPE_HOST:
1572 		return "host";
1573 	default:
1574 		return "unknown";
1575 	}
1576 }
1577 
1578 #ifdef WITH_OPENSSL
1579 static int
1580 rsa_generate_private_key(u_int bits, RSA **rsap)
1581 {
1582 	RSA *private = NULL;
1583 	BIGNUM *f4 = NULL;
1584 	int ret = SSH_ERR_INTERNAL_ERROR;
1585 
1586 	if (rsap == NULL)
1587 		return SSH_ERR_INVALID_ARGUMENT;
1588 	if (bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1589 	    bits > SSHBUF_MAX_BIGNUM * 8)
1590 		return SSH_ERR_KEY_LENGTH;
1591 	*rsap = NULL;
1592 	if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1593 		ret = SSH_ERR_ALLOC_FAIL;
1594 		goto out;
1595 	}
1596 	if (!BN_set_word(f4, RSA_F4) ||
1597 	    !RSA_generate_key_ex(private, bits, f4, NULL)) {
1598 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1599 		goto out;
1600 	}
1601 	*rsap = private;
1602 	private = NULL;
1603 	ret = 0;
1604  out:
1605 	RSA_free(private);
1606 	BN_free(f4);
1607 	return ret;
1608 }
1609 
1610 static int
1611 dsa_generate_private_key(u_int bits, DSA **dsap)
1612 {
1613 	DSA *private;
1614 	int ret = SSH_ERR_INTERNAL_ERROR;
1615 
1616 	if (dsap == NULL)
1617 		return SSH_ERR_INVALID_ARGUMENT;
1618 	if (bits != 1024)
1619 		return SSH_ERR_KEY_LENGTH;
1620 	if ((private = DSA_new()) == NULL) {
1621 		ret = SSH_ERR_ALLOC_FAIL;
1622 		goto out;
1623 	}
1624 	*dsap = NULL;
1625 	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1626 	    NULL, NULL) || !DSA_generate_key(private)) {
1627 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1628 		goto out;
1629 	}
1630 	*dsap = private;
1631 	private = NULL;
1632 	ret = 0;
1633  out:
1634 	DSA_free(private);
1635 	return ret;
1636 }
1637 
1638 # ifdef OPENSSL_HAS_ECC
1639 int
1640 sshkey_ecdsa_key_to_nid(EC_KEY *k)
1641 {
1642 	EC_GROUP *eg;
1643 	int nids[] = {
1644 		NID_X9_62_prime256v1,
1645 		NID_secp384r1,
1646 #  ifdef OPENSSL_HAS_NISTP521
1647 		NID_secp521r1,
1648 #  endif /* OPENSSL_HAS_NISTP521 */
1649 		-1
1650 	};
1651 	int nid;
1652 	u_int i;
1653 	const EC_GROUP *g = EC_KEY_get0_group(k);
1654 
1655 	/*
1656 	 * The group may be stored in a ASN.1 encoded private key in one of two
1657 	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1658 	 * or explicit group parameters encoded into the key blob. Only the
1659 	 * "named group" case sets the group NID for us, but we can figure
1660 	 * it out for the other case by comparing against all the groups that
1661 	 * are supported.
1662 	 */
1663 	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1664 		return nid;
1665 	for (i = 0; nids[i] != -1; i++) {
1666 		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL)
1667 			return -1;
1668 		if (EC_GROUP_cmp(g, eg, NULL) == 0)
1669 			break;
1670 		EC_GROUP_free(eg);
1671 	}
1672 	if (nids[i] != -1) {
1673 		/* Use the group with the NID attached */
1674 		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1675 		if (EC_KEY_set_group(k, eg) != 1) {
1676 			EC_GROUP_free(eg);
1677 			return -1;
1678 		}
1679 	}
1680 	return nids[i];
1681 }
1682 
1683 static int
1684 ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1685 {
1686 	EC_KEY *private;
1687 	int ret = SSH_ERR_INTERNAL_ERROR;
1688 
1689 	if (nid == NULL || ecdsap == NULL)
1690 		return SSH_ERR_INVALID_ARGUMENT;
1691 	if ((*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1692 		return SSH_ERR_KEY_LENGTH;
1693 	*ecdsap = NULL;
1694 	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1695 		ret = SSH_ERR_ALLOC_FAIL;
1696 		goto out;
1697 	}
1698 	if (EC_KEY_generate_key(private) != 1) {
1699 		ret = SSH_ERR_LIBCRYPTO_ERROR;
1700 		goto out;
1701 	}
1702 	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1703 	*ecdsap = private;
1704 	private = NULL;
1705 	ret = 0;
1706  out:
1707 	EC_KEY_free(private);
1708 	return ret;
1709 }
1710 # endif /* OPENSSL_HAS_ECC */
1711 #endif /* WITH_OPENSSL */
1712 
1713 int
1714 sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1715 {
1716 	struct sshkey *k;
1717 	int ret = SSH_ERR_INTERNAL_ERROR;
1718 
1719 	if (keyp == NULL)
1720 		return SSH_ERR_INVALID_ARGUMENT;
1721 	*keyp = NULL;
1722 	if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1723 		return SSH_ERR_ALLOC_FAIL;
1724 	switch (type) {
1725 	case KEY_ED25519:
1726 		if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1727 		    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1728 			ret = SSH_ERR_ALLOC_FAIL;
1729 			break;
1730 		}
1731 		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1732 		ret = 0;
1733 		break;
1734 #ifdef WITH_XMSS
1735 	case KEY_XMSS:
1736 		ret = sshkey_xmss_generate_private_key(k, bits);
1737 		break;
1738 #endif /* WITH_XMSS */
1739 #ifdef WITH_OPENSSL
1740 	case KEY_DSA:
1741 		ret = dsa_generate_private_key(bits, &k->dsa);
1742 		break;
1743 # ifdef OPENSSL_HAS_ECC
1744 	case KEY_ECDSA:
1745 		ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1746 		    &k->ecdsa);
1747 		break;
1748 # endif /* OPENSSL_HAS_ECC */
1749 	case KEY_RSA:
1750 		ret = rsa_generate_private_key(bits, &k->rsa);
1751 		break;
1752 #endif /* WITH_OPENSSL */
1753 	default:
1754 		ret = SSH_ERR_INVALID_ARGUMENT;
1755 	}
1756 	if (ret == 0) {
1757 		k->type = type;
1758 		*keyp = k;
1759 	} else
1760 		sshkey_free(k);
1761 	return ret;
1762 }
1763 
1764 int
1765 sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1766 {
1767 	u_int i;
1768 	const struct sshkey_cert *from;
1769 	struct sshkey_cert *to;
1770 	int r = SSH_ERR_INTERNAL_ERROR;
1771 
1772 	if (to_key == NULL || (from = from_key->cert) == NULL)
1773 		return SSH_ERR_INVALID_ARGUMENT;
1774 
1775 	if ((to = cert_new()) == NULL)
1776 		return SSH_ERR_ALLOC_FAIL;
1777 
1778 	if ((r = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1779 	    (r = sshbuf_putb(to->critical, from->critical)) != 0 ||
1780 	    (r = sshbuf_putb(to->extensions, from->extensions)) != 0)
1781 		goto out;
1782 
1783 	to->serial = from->serial;
1784 	to->type = from->type;
1785 	if (from->key_id == NULL)
1786 		to->key_id = NULL;
1787 	else if ((to->key_id = strdup(from->key_id)) == NULL) {
1788 		r = SSH_ERR_ALLOC_FAIL;
1789 		goto out;
1790 	}
1791 	to->valid_after = from->valid_after;
1792 	to->valid_before = from->valid_before;
1793 	if (from->signature_key == NULL)
1794 		to->signature_key = NULL;
1795 	else if ((r = sshkey_from_private(from->signature_key,
1796 	    &to->signature_key)) != 0)
1797 		goto out;
1798 	if (from->signature_type != NULL &&
1799 	    (to->signature_type = strdup(from->signature_type)) == NULL) {
1800 		r = SSH_ERR_ALLOC_FAIL;
1801 		goto out;
1802 	}
1803 	if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS) {
1804 		r = SSH_ERR_INVALID_ARGUMENT;
1805 		goto out;
1806 	}
1807 	if (from->nprincipals > 0) {
1808 		if ((to->principals = calloc(from->nprincipals,
1809 		    sizeof(*to->principals))) == NULL) {
1810 			r = SSH_ERR_ALLOC_FAIL;
1811 			goto out;
1812 		}
1813 		for (i = 0; i < from->nprincipals; i++) {
1814 			to->principals[i] = strdup(from->principals[i]);
1815 			if (to->principals[i] == NULL) {
1816 				to->nprincipals = i;
1817 				r = SSH_ERR_ALLOC_FAIL;
1818 				goto out;
1819 			}
1820 		}
1821 	}
1822 	to->nprincipals = from->nprincipals;
1823 
1824 	/* success */
1825 	cert_free(to_key->cert);
1826 	to_key->cert = to;
1827 	to = NULL;
1828 	r = 0;
1829  out:
1830 	cert_free(to);
1831 	return r;
1832 }
1833 
1834 int
1835 sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1836 {
1837 	struct sshkey *n = NULL;
1838 	int r = SSH_ERR_INTERNAL_ERROR;
1839 #ifdef WITH_OPENSSL
1840 	const BIGNUM *rsa_n, *rsa_e;
1841 	BIGNUM *rsa_n_dup = NULL, *rsa_e_dup = NULL;
1842 	const BIGNUM *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
1843 	BIGNUM *dsa_p_dup = NULL, *dsa_q_dup = NULL, *dsa_g_dup = NULL;
1844 	BIGNUM *dsa_pub_key_dup = NULL;
1845 #endif /* WITH_OPENSSL */
1846 
1847 	*pkp = NULL;
1848 	if ((n = sshkey_new(k->type)) == NULL) {
1849 		r = SSH_ERR_ALLOC_FAIL;
1850 		goto out;
1851 	}
1852 	switch (k->type) {
1853 #ifdef WITH_OPENSSL
1854 	case KEY_DSA:
1855 	case KEY_DSA_CERT:
1856 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
1857 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
1858 		if ((dsa_p_dup = BN_dup(dsa_p)) == NULL ||
1859 		    (dsa_q_dup = BN_dup(dsa_q)) == NULL ||
1860 		    (dsa_g_dup = BN_dup(dsa_g)) == NULL ||
1861 		    (dsa_pub_key_dup = BN_dup(dsa_pub_key)) == NULL) {
1862 			r = SSH_ERR_ALLOC_FAIL;
1863 			goto out;
1864 		}
1865 		if (!DSA_set0_pqg(n->dsa, dsa_p_dup, dsa_q_dup, dsa_g_dup)) {
1866 			r = SSH_ERR_LIBCRYPTO_ERROR;
1867 			goto out;
1868 		}
1869 		dsa_p_dup = dsa_q_dup = dsa_g_dup = NULL; /* transferred */
1870 		if (!DSA_set0_key(n->dsa, dsa_pub_key_dup, NULL)) {
1871 			r = SSH_ERR_LIBCRYPTO_ERROR;
1872 			goto out;
1873 		}
1874 		dsa_pub_key_dup = NULL; /* transferred */
1875 
1876 		break;
1877 # ifdef OPENSSL_HAS_ECC
1878 	case KEY_ECDSA:
1879 	case KEY_ECDSA_CERT:
1880 	case KEY_ECDSA_SK:
1881 	case KEY_ECDSA_SK_CERT:
1882 		n->ecdsa_nid = k->ecdsa_nid;
1883 		n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1884 		if (n->ecdsa == NULL) {
1885 			r = SSH_ERR_ALLOC_FAIL;
1886 			goto out;
1887 		}
1888 		if (EC_KEY_set_public_key(n->ecdsa,
1889 		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1890 			r = SSH_ERR_LIBCRYPTO_ERROR;
1891 			goto out;
1892 		}
1893 		if (k->type != KEY_ECDSA_SK && k->type != KEY_ECDSA_SK_CERT)
1894 			break;
1895 		/* Append security-key application string */
1896 		if ((n->sk_application = strdup(k->sk_application)) == NULL)
1897 			goto out;
1898 		break;
1899 # endif /* OPENSSL_HAS_ECC */
1900 	case KEY_RSA:
1901 	case KEY_RSA_CERT:
1902 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
1903 		if ((rsa_n_dup = BN_dup(rsa_n)) == NULL ||
1904 		    (rsa_e_dup = BN_dup(rsa_e)) == NULL) {
1905 			r = SSH_ERR_ALLOC_FAIL;
1906 			goto out;
1907 		}
1908 		if (!RSA_set0_key(n->rsa, rsa_n_dup, rsa_e_dup, NULL)) {
1909 			r = SSH_ERR_LIBCRYPTO_ERROR;
1910 			goto out;
1911 		}
1912 		rsa_n_dup = rsa_e_dup = NULL; /* transferred */
1913 		break;
1914 #endif /* WITH_OPENSSL */
1915 	case KEY_ED25519:
1916 	case KEY_ED25519_CERT:
1917 	case KEY_ED25519_SK:
1918 	case KEY_ED25519_SK_CERT:
1919 		if (k->ed25519_pk != NULL) {
1920 			if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1921 				r = SSH_ERR_ALLOC_FAIL;
1922 				goto out;
1923 			}
1924 			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1925 		}
1926 		if (k->type != KEY_ED25519_SK &&
1927 		    k->type != KEY_ED25519_SK_CERT)
1928 			break;
1929 		/* Append security-key application string */
1930 		if ((n->sk_application = strdup(k->sk_application)) == NULL)
1931 			goto out;
1932 		break;
1933 #ifdef WITH_XMSS
1934 	case KEY_XMSS:
1935 	case KEY_XMSS_CERT:
1936 		if ((r = sshkey_xmss_init(n, k->xmss_name)) != 0)
1937 			goto out;
1938 		if (k->xmss_pk != NULL) {
1939 			u_int32_t left;
1940 			size_t pklen = sshkey_xmss_pklen(k);
1941 			if (pklen == 0 || sshkey_xmss_pklen(n) != pklen) {
1942 				r = SSH_ERR_INTERNAL_ERROR;
1943 				goto out;
1944 			}
1945 			if ((n->xmss_pk = malloc(pklen)) == NULL) {
1946 				r = SSH_ERR_ALLOC_FAIL;
1947 				goto out;
1948 			}
1949 			memcpy(n->xmss_pk, k->xmss_pk, pklen);
1950 			/* simulate number of signatures left on pubkey */
1951 			left = sshkey_xmss_signatures_left(k);
1952 			if (left)
1953 				sshkey_xmss_enable_maxsign(n, left);
1954 		}
1955 		break;
1956 #endif /* WITH_XMSS */
1957 	default:
1958 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
1959 		goto out;
1960 	}
1961 	if (sshkey_is_cert(k) && (r = sshkey_cert_copy(k, n)) != 0)
1962 		goto out;
1963 	/* success */
1964 	*pkp = n;
1965 	n = NULL;
1966 	r = 0;
1967  out:
1968 	sshkey_free(n);
1969 #ifdef WITH_OPENSSL
1970 	BN_clear_free(rsa_n_dup);
1971 	BN_clear_free(rsa_e_dup);
1972 	BN_clear_free(dsa_p_dup);
1973 	BN_clear_free(dsa_q_dup);
1974 	BN_clear_free(dsa_g_dup);
1975 	BN_clear_free(dsa_pub_key_dup);
1976 #endif
1977 
1978 	return r;
1979 }
1980 
1981 int
1982 sshkey_is_shielded(struct sshkey *k)
1983 {
1984 	return k != NULL && k->shielded_private != NULL;
1985 }
1986 
1987 int
1988 sshkey_shield_private(struct sshkey *k)
1989 {
1990 	struct sshbuf *prvbuf = NULL;
1991 	u_char *prekey = NULL, *enc = NULL, keyiv[SSH_DIGEST_MAX_LENGTH];
1992 	struct sshcipher_ctx *cctx = NULL;
1993 	const struct sshcipher *cipher;
1994 	size_t i, enclen = 0;
1995 	struct sshkey *kswap = NULL, tmp;
1996 	int r = SSH_ERR_INTERNAL_ERROR;
1997 
1998 #ifdef DEBUG_PK
1999 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
2000 #endif
2001 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2002 		r = SSH_ERR_INVALID_ARGUMENT;
2003 		goto out;
2004 	}
2005 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2006 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2007 		r = SSH_ERR_INTERNAL_ERROR;
2008 		goto out;
2009 	}
2010 
2011 	/* Prepare a random pre-key, and from it an ephemeral key */
2012 	if ((prekey = malloc(SSHKEY_SHIELD_PREKEY_LEN)) == NULL) {
2013 		r = SSH_ERR_ALLOC_FAIL;
2014 		goto out;
2015 	}
2016 	arc4random_buf(prekey, SSHKEY_SHIELD_PREKEY_LEN);
2017 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2018 	    prekey, SSHKEY_SHIELD_PREKEY_LEN,
2019 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2020 		goto out;
2021 #ifdef DEBUG_PK
2022 	fprintf(stderr, "%s: key+iv\n", __func__);
2023 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2024 	    stderr);
2025 #endif
2026 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2027 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 1)) != 0)
2028 		goto out;
2029 
2030 	/* Serialise and encrypt the private key using the ephemeral key */
2031 	if ((prvbuf = sshbuf_new()) == NULL) {
2032 		r = SSH_ERR_ALLOC_FAIL;
2033 		goto out;
2034 	}
2035 	if (sshkey_is_shielded(k) && (r = sshkey_unshield_private(k)) != 0)
2036 		goto out;
2037 	if ((r = sshkey_private_serialize_opt(k, prvbuf,
2038 	     SSHKEY_SERIALIZE_SHIELD)) != 0)
2039 		goto out;
2040 	/* pad to cipher blocksize */
2041 	i = 0;
2042 	while (sshbuf_len(prvbuf) % cipher_blocksize(cipher)) {
2043 		if ((r = sshbuf_put_u8(prvbuf, ++i & 0xff)) != 0)
2044 			goto out;
2045 	}
2046 #ifdef DEBUG_PK
2047 	fprintf(stderr, "%s: serialised\n", __func__);
2048 	sshbuf_dump(prvbuf, stderr);
2049 #endif
2050 	/* encrypt */
2051 	enclen = sshbuf_len(prvbuf);
2052 	if ((enc = malloc(enclen)) == NULL) {
2053 		r = SSH_ERR_ALLOC_FAIL;
2054 		goto out;
2055 	}
2056 	if ((r = cipher_crypt(cctx, 0, enc,
2057 	    sshbuf_ptr(prvbuf), sshbuf_len(prvbuf), 0, 0)) != 0)
2058 		goto out;
2059 #ifdef DEBUG_PK
2060 	fprintf(stderr, "%s: encrypted\n", __func__);
2061 	sshbuf_dump_data(enc, enclen, stderr);
2062 #endif
2063 
2064 	/* Make a scrubbed, public-only copy of our private key argument */
2065 	if ((r = sshkey_from_private(k, &kswap)) != 0)
2066 		goto out;
2067 
2068 	/* Swap the private key out (it will be destroyed below) */
2069 	tmp = *kswap;
2070 	*kswap = *k;
2071 	*k = tmp;
2072 
2073 	/* Insert the shielded key into our argument */
2074 	k->shielded_private = enc;
2075 	k->shielded_len = enclen;
2076 	k->shield_prekey = prekey;
2077 	k->shield_prekey_len = SSHKEY_SHIELD_PREKEY_LEN;
2078 	enc = prekey = NULL; /* transferred */
2079 	enclen = 0;
2080 
2081 	/* preserve key fields that are required for correct operation */
2082 	k->sk_flags = kswap->sk_flags;
2083 
2084 	/* success */
2085 	r = 0;
2086 
2087  out:
2088 	/* XXX behaviour on error - invalidate original private key? */
2089 	cipher_free(cctx);
2090 	explicit_bzero(keyiv, sizeof(keyiv));
2091 	explicit_bzero(&tmp, sizeof(tmp));
2092 	freezero(enc, enclen);
2093 	freezero(prekey, SSHKEY_SHIELD_PREKEY_LEN);
2094 	sshkey_free(kswap);
2095 	sshbuf_free(prvbuf);
2096 	return r;
2097 }
2098 
2099 int
2100 sshkey_unshield_private(struct sshkey *k)
2101 {
2102 	struct sshbuf *prvbuf = NULL;
2103 	u_char pad, *cp, keyiv[SSH_DIGEST_MAX_LENGTH];
2104 	struct sshcipher_ctx *cctx = NULL;
2105 	const struct sshcipher *cipher;
2106 	size_t i;
2107 	struct sshkey *kswap = NULL, tmp;
2108 	int r = SSH_ERR_INTERNAL_ERROR;
2109 
2110 #ifdef DEBUG_PK
2111 	fprintf(stderr, "%s: entering for %s\n", __func__, sshkey_ssh_name(k));
2112 #endif
2113 	if (!sshkey_is_shielded(k))
2114 		return 0; /* nothing to do */
2115 
2116 	if ((cipher = cipher_by_name(SSHKEY_SHIELD_CIPHER)) == NULL) {
2117 		r = SSH_ERR_INVALID_ARGUMENT;
2118 		goto out;
2119 	}
2120 	if (cipher_keylen(cipher) + cipher_ivlen(cipher) >
2121 	    ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH)) {
2122 		r = SSH_ERR_INTERNAL_ERROR;
2123 		goto out;
2124 	}
2125 	/* check size of shielded key blob */
2126 	if (k->shielded_len < cipher_blocksize(cipher) ||
2127 	    (k->shielded_len % cipher_blocksize(cipher)) != 0) {
2128 		r = SSH_ERR_INVALID_FORMAT;
2129 		goto out;
2130 	}
2131 
2132 	/* Calculate the ephemeral key from the prekey */
2133 	if ((r = ssh_digest_memory(SSHKEY_SHIELD_PREKEY_HASH,
2134 	    k->shield_prekey, k->shield_prekey_len,
2135 	    keyiv, SSH_DIGEST_MAX_LENGTH)) != 0)
2136 		goto out;
2137 	if ((r = cipher_init(&cctx, cipher, keyiv, cipher_keylen(cipher),
2138 	    keyiv + cipher_keylen(cipher), cipher_ivlen(cipher), 0)) != 0)
2139 		goto out;
2140 #ifdef DEBUG_PK
2141 	fprintf(stderr, "%s: key+iv\n", __func__);
2142 	sshbuf_dump_data(keyiv, ssh_digest_bytes(SSHKEY_SHIELD_PREKEY_HASH),
2143 	    stderr);
2144 #endif
2145 
2146 	/* Decrypt and parse the shielded private key using the ephemeral key */
2147 	if ((prvbuf = sshbuf_new()) == NULL) {
2148 		r = SSH_ERR_ALLOC_FAIL;
2149 		goto out;
2150 	}
2151 	if ((r = sshbuf_reserve(prvbuf, k->shielded_len, &cp)) != 0)
2152 		goto out;
2153 	/* decrypt */
2154 #ifdef DEBUG_PK
2155 	fprintf(stderr, "%s: encrypted\n", __func__);
2156 	sshbuf_dump_data(k->shielded_private, k->shielded_len, stderr);
2157 #endif
2158 	if ((r = cipher_crypt(cctx, 0, cp,
2159 	    k->shielded_private, k->shielded_len, 0, 0)) != 0)
2160 		goto out;
2161 #ifdef DEBUG_PK
2162 	fprintf(stderr, "%s: serialised\n", __func__);
2163 	sshbuf_dump(prvbuf, stderr);
2164 #endif
2165 	/* Parse private key */
2166 	if ((r = sshkey_private_deserialize(prvbuf, &kswap)) != 0)
2167 		goto out;
2168 	/* Check deterministic padding */
2169 	i = 0;
2170 	while (sshbuf_len(prvbuf)) {
2171 		if ((r = sshbuf_get_u8(prvbuf, &pad)) != 0)
2172 			goto out;
2173 		if (pad != (++i & 0xff)) {
2174 			r = SSH_ERR_INVALID_FORMAT;
2175 			goto out;
2176 		}
2177 	}
2178 
2179 	/* Swap the parsed key back into place */
2180 	tmp = *kswap;
2181 	*kswap = *k;
2182 	*k = tmp;
2183 
2184 	/* success */
2185 	r = 0;
2186 
2187  out:
2188 	cipher_free(cctx);
2189 	explicit_bzero(keyiv, sizeof(keyiv));
2190 	explicit_bzero(&tmp, sizeof(tmp));
2191 	sshkey_free(kswap);
2192 	sshbuf_free(prvbuf);
2193 	return r;
2194 }
2195 
2196 static int
2197 cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
2198 {
2199 	struct sshbuf *principals = NULL, *crit = NULL;
2200 	struct sshbuf *exts = NULL, *ca = NULL;
2201 	u_char *sig = NULL;
2202 	size_t signed_len = 0, slen = 0, kidlen = 0;
2203 	int ret = SSH_ERR_INTERNAL_ERROR;
2204 
2205 	/* Copy the entire key blob for verification and later serialisation */
2206 	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
2207 		return ret;
2208 
2209 	/* Parse body of certificate up to signature */
2210 	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
2211 	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
2212 	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
2213 	    (ret = sshbuf_froms(b, &principals)) != 0 ||
2214 	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
2215 	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
2216 	    (ret = sshbuf_froms(b, &crit)) != 0 ||
2217 	    (ret = sshbuf_froms(b, &exts)) != 0 ||
2218 	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
2219 	    (ret = sshbuf_froms(b, &ca)) != 0) {
2220 		/* XXX debug print error for ret */
2221 		ret = SSH_ERR_INVALID_FORMAT;
2222 		goto out;
2223 	}
2224 
2225 	/* Signature is left in the buffer so we can calculate this length */
2226 	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
2227 
2228 	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
2229 		ret = SSH_ERR_INVALID_FORMAT;
2230 		goto out;
2231 	}
2232 
2233 	if (key->cert->type != SSH2_CERT_TYPE_USER &&
2234 	    key->cert->type != SSH2_CERT_TYPE_HOST) {
2235 		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
2236 		goto out;
2237 	}
2238 
2239 	/* Parse principals section */
2240 	while (sshbuf_len(principals) > 0) {
2241 		char *principal = NULL;
2242 		char **oprincipals = NULL;
2243 
2244 		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
2245 			ret = SSH_ERR_INVALID_FORMAT;
2246 			goto out;
2247 		}
2248 		if ((ret = sshbuf_get_cstring(principals, &principal,
2249 		    NULL)) != 0) {
2250 			ret = SSH_ERR_INVALID_FORMAT;
2251 			goto out;
2252 		}
2253 		oprincipals = key->cert->principals;
2254 		key->cert->principals = recallocarray(key->cert->principals,
2255 		    key->cert->nprincipals, key->cert->nprincipals + 1,
2256 		    sizeof(*key->cert->principals));
2257 		if (key->cert->principals == NULL) {
2258 			free(principal);
2259 			key->cert->principals = oprincipals;
2260 			ret = SSH_ERR_ALLOC_FAIL;
2261 			goto out;
2262 		}
2263 		key->cert->principals[key->cert->nprincipals++] = principal;
2264 	}
2265 
2266 	/*
2267 	 * Stash a copies of the critical options and extensions sections
2268 	 * for later use.
2269 	 */
2270 	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
2271 	    (exts != NULL &&
2272 	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
2273 		goto out;
2274 
2275 	/*
2276 	 * Validate critical options and extensions sections format.
2277 	 */
2278 	while (sshbuf_len(crit) != 0) {
2279 		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
2280 		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
2281 			sshbuf_reset(key->cert->critical);
2282 			ret = SSH_ERR_INVALID_FORMAT;
2283 			goto out;
2284 		}
2285 	}
2286 	while (exts != NULL && sshbuf_len(exts) != 0) {
2287 		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
2288 		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
2289 			sshbuf_reset(key->cert->extensions);
2290 			ret = SSH_ERR_INVALID_FORMAT;
2291 			goto out;
2292 		}
2293 	}
2294 
2295 	/* Parse CA key and check signature */
2296 	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
2297 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2298 		goto out;
2299 	}
2300 	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
2301 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2302 		goto out;
2303 	}
2304 	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
2305 	    sshbuf_ptr(key->cert->certblob), signed_len, NULL, 0, NULL)) != 0)
2306 		goto out;
2307 	if ((ret = sshkey_get_sigtype(sig, slen,
2308 	    &key->cert->signature_type)) != 0)
2309 		goto out;
2310 
2311 	/* Success */
2312 	ret = 0;
2313  out:
2314 	sshbuf_free(ca);
2315 	sshbuf_free(crit);
2316 	sshbuf_free(exts);
2317 	sshbuf_free(principals);
2318 	free(sig);
2319 	return ret;
2320 }
2321 
2322 #ifdef WITH_OPENSSL
2323 static int
2324 check_rsa_length(const RSA *rsa)
2325 {
2326 	const BIGNUM *rsa_n;
2327 
2328 	RSA_get0_key(rsa, &rsa_n, NULL, NULL);
2329 	if (BN_num_bits(rsa_n) < SSH_RSA_MINIMUM_MODULUS_SIZE)
2330 		return SSH_ERR_KEY_LENGTH;
2331 	return 0;
2332 }
2333 #endif
2334 
2335 static int
2336 sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
2337     int allow_cert)
2338 {
2339 	int type, ret = SSH_ERR_INTERNAL_ERROR;
2340 	char *ktype = NULL, *curve = NULL, *xmss_name = NULL;
2341 	struct sshkey *key = NULL;
2342 	size_t len;
2343 	u_char *pk = NULL;
2344 	struct sshbuf *copy;
2345 #if defined(WITH_OPENSSL)
2346 	BIGNUM *rsa_n = NULL, *rsa_e = NULL;
2347 	BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL, *dsa_pub_key = NULL;
2348 # if defined(OPENSSL_HAS_ECC)
2349 	EC_POINT *q = NULL;
2350 # endif /* OPENSSL_HAS_ECC */
2351 #endif /* WITH_OPENSSL */
2352 
2353 #ifdef DEBUG_PK /* XXX */
2354 	sshbuf_dump(b, stderr);
2355 #endif
2356 	if (keyp != NULL)
2357 		*keyp = NULL;
2358 	if ((copy = sshbuf_fromb(b)) == NULL) {
2359 		ret = SSH_ERR_ALLOC_FAIL;
2360 		goto out;
2361 	}
2362 	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
2363 		ret = SSH_ERR_INVALID_FORMAT;
2364 		goto out;
2365 	}
2366 
2367 	type = sshkey_type_from_name(ktype);
2368 	if (!allow_cert && sshkey_type_is_cert(type)) {
2369 		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2370 		goto out;
2371 	}
2372 	switch (type) {
2373 #ifdef WITH_OPENSSL
2374 	case KEY_RSA_CERT:
2375 		/* Skip nonce */
2376 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2377 			ret = SSH_ERR_INVALID_FORMAT;
2378 			goto out;
2379 		}
2380 		/* FALLTHROUGH */
2381 	case KEY_RSA:
2382 		if ((key = sshkey_new(type)) == NULL) {
2383 			ret = SSH_ERR_ALLOC_FAIL;
2384 			goto out;
2385 		}
2386 		if (sshbuf_get_bignum2(b, &rsa_e) != 0 ||
2387 		    sshbuf_get_bignum2(b, &rsa_n) != 0) {
2388 			ret = SSH_ERR_INVALID_FORMAT;
2389 			goto out;
2390 		}
2391 		if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, NULL)) {
2392 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2393 			goto out;
2394 		}
2395 		rsa_n = rsa_e = NULL; /* transferred */
2396 		if ((ret = check_rsa_length(key->rsa)) != 0)
2397 			goto out;
2398 #ifdef DEBUG_PK
2399 		RSA_print_fp(stderr, key->rsa, 8);
2400 #endif
2401 		break;
2402 	case KEY_DSA_CERT:
2403 		/* Skip nonce */
2404 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2405 			ret = SSH_ERR_INVALID_FORMAT;
2406 			goto out;
2407 		}
2408 		/* FALLTHROUGH */
2409 	case KEY_DSA:
2410 		if ((key = sshkey_new(type)) == NULL) {
2411 			ret = SSH_ERR_ALLOC_FAIL;
2412 			goto out;
2413 		}
2414 		if (sshbuf_get_bignum2(b, &dsa_p) != 0 ||
2415 		    sshbuf_get_bignum2(b, &dsa_q) != 0 ||
2416 		    sshbuf_get_bignum2(b, &dsa_g) != 0 ||
2417 		    sshbuf_get_bignum2(b, &dsa_pub_key) != 0) {
2418 			ret = SSH_ERR_INVALID_FORMAT;
2419 			goto out;
2420 		}
2421 		if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g)) {
2422 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2423 			goto out;
2424 		}
2425 		dsa_p = dsa_q = dsa_g = NULL; /* transferred */
2426 		if (!DSA_set0_key(key->dsa, dsa_pub_key, NULL)) {
2427 			ret = SSH_ERR_LIBCRYPTO_ERROR;
2428 			goto out;
2429 		}
2430 		dsa_pub_key = NULL; /* transferred */
2431 #ifdef DEBUG_PK
2432 		DSA_print_fp(stderr, key->dsa, 8);
2433 #endif
2434 		break;
2435 # ifdef OPENSSL_HAS_ECC
2436 	case KEY_ECDSA_CERT:
2437 	case KEY_ECDSA_SK_CERT:
2438 		/* Skip nonce */
2439 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2440 			ret = SSH_ERR_INVALID_FORMAT;
2441 			goto out;
2442 		}
2443 		/* FALLTHROUGH */
2444 	case KEY_ECDSA:
2445 	case KEY_ECDSA_SK:
2446 		if ((key = sshkey_new(type)) == NULL) {
2447 			ret = SSH_ERR_ALLOC_FAIL;
2448 			goto out;
2449 		}
2450 		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
2451 		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
2452 			ret = SSH_ERR_INVALID_FORMAT;
2453 			goto out;
2454 		}
2455 		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2456 			ret = SSH_ERR_EC_CURVE_MISMATCH;
2457 			goto out;
2458 		}
2459 		EC_KEY_free(key->ecdsa);
2460 		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
2461 		    == NULL) {
2462 			ret = SSH_ERR_EC_CURVE_INVALID;
2463 			goto out;
2464 		}
2465 		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
2466 			ret = SSH_ERR_ALLOC_FAIL;
2467 			goto out;
2468 		}
2469 		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
2470 			ret = SSH_ERR_INVALID_FORMAT;
2471 			goto out;
2472 		}
2473 		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
2474 		    q) != 0) {
2475 			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2476 			goto out;
2477 		}
2478 		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
2479 			/* XXX assume it is a allocation error */
2480 			ret = SSH_ERR_ALLOC_FAIL;
2481 			goto out;
2482 		}
2483 #ifdef DEBUG_PK
2484 		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
2485 #endif
2486 		if (type == KEY_ECDSA_SK || type == KEY_ECDSA_SK_CERT) {
2487 			/* Parse additional security-key application string */
2488 			if (sshbuf_get_cstring(b, &key->sk_application,
2489 			    NULL) != 0) {
2490 				ret = SSH_ERR_INVALID_FORMAT;
2491 				goto out;
2492 			}
2493 #ifdef DEBUG_PK
2494 			fprintf(stderr, "App: %s\n", key->sk_application);
2495 #endif
2496 		}
2497 		break;
2498 # endif /* OPENSSL_HAS_ECC */
2499 #endif /* WITH_OPENSSL */
2500 	case KEY_ED25519_CERT:
2501 	case KEY_ED25519_SK_CERT:
2502 		/* Skip nonce */
2503 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2504 			ret = SSH_ERR_INVALID_FORMAT;
2505 			goto out;
2506 		}
2507 		/* FALLTHROUGH */
2508 	case KEY_ED25519:
2509 	case KEY_ED25519_SK:
2510 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2511 			goto out;
2512 		if (len != ED25519_PK_SZ) {
2513 			ret = SSH_ERR_INVALID_FORMAT;
2514 			goto out;
2515 		}
2516 		if ((key = sshkey_new(type)) == NULL) {
2517 			ret = SSH_ERR_ALLOC_FAIL;
2518 			goto out;
2519 		}
2520 		if (type == KEY_ED25519_SK || type == KEY_ED25519_SK_CERT) {
2521 			/* Parse additional security-key application string */
2522 			if (sshbuf_get_cstring(b, &key->sk_application,
2523 			    NULL) != 0) {
2524 				ret = SSH_ERR_INVALID_FORMAT;
2525 				goto out;
2526 			}
2527 #ifdef DEBUG_PK
2528 			fprintf(stderr, "App: %s\n", key->sk_application);
2529 #endif
2530 		}
2531 		key->ed25519_pk = pk;
2532 		pk = NULL;
2533 		break;
2534 #ifdef WITH_XMSS
2535 	case KEY_XMSS_CERT:
2536 		/* Skip nonce */
2537 		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
2538 			ret = SSH_ERR_INVALID_FORMAT;
2539 			goto out;
2540 		}
2541 		/* FALLTHROUGH */
2542 	case KEY_XMSS:
2543 		if ((ret = sshbuf_get_cstring(b, &xmss_name, NULL)) != 0)
2544 			goto out;
2545 		if ((key = sshkey_new(type)) == NULL) {
2546 			ret = SSH_ERR_ALLOC_FAIL;
2547 			goto out;
2548 		}
2549 		if ((ret = sshkey_xmss_init(key, xmss_name)) != 0)
2550 			goto out;
2551 		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
2552 			goto out;
2553 		if (len == 0 || len != sshkey_xmss_pklen(key)) {
2554 			ret = SSH_ERR_INVALID_FORMAT;
2555 			goto out;
2556 		}
2557 		key->xmss_pk = pk;
2558 		pk = NULL;
2559 		if (type != KEY_XMSS_CERT &&
2560 		    (ret = sshkey_xmss_deserialize_pk_info(key, b)) != 0)
2561 			goto out;
2562 		break;
2563 #endif /* WITH_XMSS */
2564 	case KEY_UNSPEC:
2565 	default:
2566 		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2567 		goto out;
2568 	}
2569 
2570 	/* Parse certificate potion */
2571 	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
2572 		goto out;
2573 
2574 	if (key != NULL && sshbuf_len(b) != 0) {
2575 		ret = SSH_ERR_INVALID_FORMAT;
2576 		goto out;
2577 	}
2578 	ret = 0;
2579 	if (keyp != NULL) {
2580 		*keyp = key;
2581 		key = NULL;
2582 	}
2583  out:
2584 	sshbuf_free(copy);
2585 	sshkey_free(key);
2586 	free(xmss_name);
2587 	free(ktype);
2588 	free(curve);
2589 	free(pk);
2590 #if defined(WITH_OPENSSL)
2591 	BN_clear_free(rsa_n);
2592 	BN_clear_free(rsa_e);
2593 	BN_clear_free(dsa_p);
2594 	BN_clear_free(dsa_q);
2595 	BN_clear_free(dsa_g);
2596 	BN_clear_free(dsa_pub_key);
2597 # if defined(OPENSSL_HAS_ECC)
2598 	EC_POINT_free(q);
2599 # endif /* OPENSSL_HAS_ECC */
2600 #endif /* WITH_OPENSSL */
2601 	return ret;
2602 }
2603 
2604 int
2605 sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
2606 {
2607 	struct sshbuf *b;
2608 	int r;
2609 
2610 	if ((b = sshbuf_from(blob, blen)) == NULL)
2611 		return SSH_ERR_ALLOC_FAIL;
2612 	r = sshkey_from_blob_internal(b, keyp, 1);
2613 	sshbuf_free(b);
2614 	return r;
2615 }
2616 
2617 int
2618 sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
2619 {
2620 	return sshkey_from_blob_internal(b, keyp, 1);
2621 }
2622 
2623 int
2624 sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2625 {
2626 	struct sshbuf *b;
2627 	int r;
2628 
2629 	if ((r = sshbuf_froms(buf, &b)) != 0)
2630 		return r;
2631 	r = sshkey_from_blob_internal(b, keyp, 1);
2632 	sshbuf_free(b);
2633 	return r;
2634 }
2635 
2636 int
2637 sshkey_get_sigtype(const u_char *sig, size_t siglen, char **sigtypep)
2638 {
2639 	int r;
2640 	struct sshbuf *b = NULL;
2641 	char *sigtype = NULL;
2642 
2643 	if (sigtypep != NULL)
2644 		*sigtypep = NULL;
2645 	if ((b = sshbuf_from(sig, siglen)) == NULL)
2646 		return SSH_ERR_ALLOC_FAIL;
2647 	if ((r = sshbuf_get_cstring(b, &sigtype, NULL)) != 0)
2648 		goto out;
2649 	/* success */
2650 	if (sigtypep != NULL) {
2651 		*sigtypep = sigtype;
2652 		sigtype = NULL;
2653 	}
2654 	r = 0;
2655  out:
2656 	free(sigtype);
2657 	sshbuf_free(b);
2658 	return r;
2659 }
2660 
2661 /*
2662  *
2663  * Checks whether a certificate's signature type is allowed.
2664  * Returns 0 (success) if the certificate signature type appears in the
2665  * "allowed" pattern-list, or the key is not a certificate to begin with.
2666  * Otherwise returns a ssherr.h code.
2667  */
2668 int
2669 sshkey_check_cert_sigtype(const struct sshkey *key, const char *allowed)
2670 {
2671 	if (key == NULL || allowed == NULL)
2672 		return SSH_ERR_INVALID_ARGUMENT;
2673 	if (!sshkey_type_is_cert(key->type))
2674 		return 0;
2675 	if (key->cert == NULL || key->cert->signature_type == NULL)
2676 		return SSH_ERR_INVALID_ARGUMENT;
2677 	if (match_pattern_list(key->cert->signature_type, allowed, 0) != 1)
2678 		return SSH_ERR_SIGN_ALG_UNSUPPORTED;
2679 	return 0;
2680 }
2681 
2682 /*
2683  * Returns the expected signature algorithm for a given public key algorithm.
2684  */
2685 const char *
2686 sshkey_sigalg_by_name(const char *name)
2687 {
2688 	const struct keytype *kt;
2689 
2690 	for (kt = keytypes; kt->type != -1; kt++) {
2691 		if (strcmp(kt->name, name) != 0)
2692 			continue;
2693 		if (kt->sigalg != NULL)
2694 			return kt->sigalg;
2695 		if (!kt->cert)
2696 			return kt->name;
2697 		return sshkey_ssh_name_from_type_nid(
2698 		    sshkey_type_plain(kt->type), kt->nid);
2699 	}
2700 	return NULL;
2701 }
2702 
2703 /*
2704  * Verifies that the signature algorithm appearing inside the signature blob
2705  * matches that which was requested.
2706  */
2707 int
2708 sshkey_check_sigtype(const u_char *sig, size_t siglen,
2709     const char *requested_alg)
2710 {
2711 	const char *expected_alg;
2712 	char *sigtype = NULL;
2713 	int r;
2714 
2715 	if (requested_alg == NULL)
2716 		return 0;
2717 	if ((expected_alg = sshkey_sigalg_by_name(requested_alg)) == NULL)
2718 		return SSH_ERR_INVALID_ARGUMENT;
2719 	if ((r = sshkey_get_sigtype(sig, siglen, &sigtype)) != 0)
2720 		return r;
2721 	r = strcmp(expected_alg, sigtype) == 0;
2722 	free(sigtype);
2723 	return r ? 0 : SSH_ERR_SIGN_ALG_UNSUPPORTED;
2724 }
2725 
2726 int
2727 sshkey_sign(struct sshkey *key,
2728     u_char **sigp, size_t *lenp,
2729     const u_char *data, size_t datalen,
2730     const char *alg, const char *sk_provider, u_int compat)
2731 {
2732 	int was_shielded = sshkey_is_shielded(key);
2733 	int r2, r = SSH_ERR_INTERNAL_ERROR;
2734 
2735 	if (sigp != NULL)
2736 		*sigp = NULL;
2737 	if (lenp != NULL)
2738 		*lenp = 0;
2739 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2740 		return SSH_ERR_INVALID_ARGUMENT;
2741 	if ((r = sshkey_unshield_private(key)) != 0)
2742 		return r;
2743 	switch (key->type) {
2744 #ifdef WITH_OPENSSL
2745 	case KEY_DSA_CERT:
2746 	case KEY_DSA:
2747 		r = ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2748 		break;
2749 # ifdef OPENSSL_HAS_ECC
2750 	case KEY_ECDSA_CERT:
2751 	case KEY_ECDSA:
2752 		r = ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2753 		break;
2754 # endif /* OPENSSL_HAS_ECC */
2755 	case KEY_RSA_CERT:
2756 	case KEY_RSA:
2757 		r = ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2758 		break;
2759 #endif /* WITH_OPENSSL */
2760 	case KEY_ED25519:
2761 	case KEY_ED25519_CERT:
2762 		r = ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2763 		break;
2764 	case KEY_ED25519_SK:
2765 	case KEY_ED25519_SK_CERT:
2766 	case KEY_ECDSA_SK_CERT:
2767 	case KEY_ECDSA_SK:
2768 		r = sshsk_sign(sk_provider, key, sigp, lenp, data,
2769 		    datalen, compat, /* XXX PIN */ NULL);
2770 		break;
2771 #ifdef WITH_XMSS
2772 	case KEY_XMSS:
2773 	case KEY_XMSS_CERT:
2774 		r = ssh_xmss_sign(key, sigp, lenp, data, datalen, compat);
2775 		break;
2776 #endif /* WITH_XMSS */
2777 	default:
2778 		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2779 		break;
2780 	}
2781 	if (was_shielded && (r2 = sshkey_shield_private(key)) != 0)
2782 		return r2;
2783 	return r;
2784 }
2785 
2786 /*
2787  * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2788  * If "alg" specified, then the signature must use that algorithm.
2789  */
2790 int
2791 sshkey_verify(const struct sshkey *key,
2792     const u_char *sig, size_t siglen,
2793     const u_char *data, size_t dlen, const char *alg, u_int compat,
2794     struct sshkey_sig_details **detailsp)
2795 {
2796 	if (detailsp != NULL)
2797 		*detailsp = NULL;
2798 	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2799 		return SSH_ERR_INVALID_ARGUMENT;
2800 	switch (key->type) {
2801 #ifdef WITH_OPENSSL
2802 	case KEY_DSA_CERT:
2803 	case KEY_DSA:
2804 		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2805 # ifdef OPENSSL_HAS_ECC
2806 	case KEY_ECDSA_CERT:
2807 	case KEY_ECDSA:
2808 		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2809 	case KEY_ECDSA_SK_CERT:
2810 	case KEY_ECDSA_SK:
2811 		return ssh_ecdsa_sk_verify(key, sig, siglen, data, dlen,
2812 		    compat, detailsp);
2813 # endif /* OPENSSL_HAS_ECC */
2814 	case KEY_RSA_CERT:
2815 	case KEY_RSA:
2816 		return ssh_rsa_verify(key, sig, siglen, data, dlen, alg);
2817 #endif /* WITH_OPENSSL */
2818 	case KEY_ED25519:
2819 	case KEY_ED25519_CERT:
2820 		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2821 	case KEY_ED25519_SK:
2822 	case KEY_ED25519_SK_CERT:
2823 		return ssh_ed25519_sk_verify(key, sig, siglen, data, dlen,
2824 		    compat, detailsp);
2825 #ifdef WITH_XMSS
2826 	case KEY_XMSS:
2827 	case KEY_XMSS_CERT:
2828 		return ssh_xmss_verify(key, sig, siglen, data, dlen, compat);
2829 #endif /* WITH_XMSS */
2830 	default:
2831 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2832 	}
2833 }
2834 
2835 /* Convert a plain key to their _CERT equivalent */
2836 int
2837 sshkey_to_certified(struct sshkey *k)
2838 {
2839 	int newtype;
2840 
2841 	switch (k->type) {
2842 #ifdef WITH_OPENSSL
2843 	case KEY_RSA:
2844 		newtype = KEY_RSA_CERT;
2845 		break;
2846 	case KEY_DSA:
2847 		newtype = KEY_DSA_CERT;
2848 		break;
2849 	case KEY_ECDSA:
2850 		newtype = KEY_ECDSA_CERT;
2851 		break;
2852 	case KEY_ECDSA_SK:
2853 		newtype = KEY_ECDSA_SK_CERT;
2854 		break;
2855 #endif /* WITH_OPENSSL */
2856 	case KEY_ED25519_SK:
2857 		newtype = KEY_ED25519_SK_CERT;
2858 		break;
2859 	case KEY_ED25519:
2860 		newtype = KEY_ED25519_CERT;
2861 		break;
2862 #ifdef WITH_XMSS
2863 	case KEY_XMSS:
2864 		newtype = KEY_XMSS_CERT;
2865 		break;
2866 #endif /* WITH_XMSS */
2867 	default:
2868 		return SSH_ERR_INVALID_ARGUMENT;
2869 	}
2870 	if ((k->cert = cert_new()) == NULL)
2871 		return SSH_ERR_ALLOC_FAIL;
2872 	k->type = newtype;
2873 	return 0;
2874 }
2875 
2876 /* Convert a certificate to its raw key equivalent */
2877 int
2878 sshkey_drop_cert(struct sshkey *k)
2879 {
2880 	if (!sshkey_type_is_cert(k->type))
2881 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2882 	cert_free(k->cert);
2883 	k->cert = NULL;
2884 	k->type = sshkey_type_plain(k->type);
2885 	return 0;
2886 }
2887 
2888 /* Sign a certified key, (re-)generating the signed certblob. */
2889 int
2890 sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2891     const char *sk_provider, sshkey_certify_signer *signer, void *signer_ctx)
2892 {
2893 	struct sshbuf *principals = NULL;
2894 	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2895 	size_t i, ca_len, sig_len;
2896 	int ret = SSH_ERR_INTERNAL_ERROR;
2897 	struct sshbuf *cert = NULL;
2898 	char *sigtype = NULL;
2899 #ifdef WITH_OPENSSL
2900 	const BIGNUM *rsa_n, *rsa_e, *dsa_p, *dsa_q, *dsa_g, *dsa_pub_key;
2901 #endif /* WITH_OPENSSL */
2902 
2903 	if (k == NULL || k->cert == NULL ||
2904 	    k->cert->certblob == NULL || ca == NULL)
2905 		return SSH_ERR_INVALID_ARGUMENT;
2906 	if (!sshkey_is_cert(k))
2907 		return SSH_ERR_KEY_TYPE_UNKNOWN;
2908 	if (!sshkey_type_is_valid_ca(ca->type))
2909 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2910 
2911 	/*
2912 	 * If no alg specified as argument but a signature_type was set,
2913 	 * then prefer that. If both were specified, then they must match.
2914 	 */
2915 	if (alg == NULL)
2916 		alg = k->cert->signature_type;
2917 	else if (k->cert->signature_type != NULL &&
2918 	    strcmp(alg, k->cert->signature_type) != 0)
2919 		return SSH_ERR_INVALID_ARGUMENT;
2920 
2921 	/*
2922 	 * If no signing algorithm or signature_type was specified and we're
2923 	 * using a RSA key, then default to a good signature algorithm.
2924 	 */
2925 	if (alg == NULL && ca->type == KEY_RSA)
2926 		alg = "rsa-sha2-512";
2927 
2928 	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2929 		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2930 
2931 	cert = k->cert->certblob; /* for readability */
2932 	sshbuf_reset(cert);
2933 	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2934 		goto out;
2935 
2936 	/* -v01 certs put nonce first */
2937 	arc4random_buf(&nonce, sizeof(nonce));
2938 	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2939 		goto out;
2940 
2941 	/* XXX this substantially duplicates to_blob(); refactor */
2942 	switch (k->type) {
2943 #ifdef WITH_OPENSSL
2944 	case KEY_DSA_CERT:
2945 		DSA_get0_pqg(k->dsa, &dsa_p, &dsa_q, &dsa_g);
2946 		DSA_get0_key(k->dsa, &dsa_pub_key, NULL);
2947 		if ((ret = sshbuf_put_bignum2(cert, dsa_p)) != 0 ||
2948 		    (ret = sshbuf_put_bignum2(cert, dsa_q)) != 0 ||
2949 		    (ret = sshbuf_put_bignum2(cert, dsa_g)) != 0 ||
2950 		    (ret = sshbuf_put_bignum2(cert, dsa_pub_key)) != 0)
2951 			goto out;
2952 		break;
2953 # ifdef OPENSSL_HAS_ECC
2954 	case KEY_ECDSA_CERT:
2955 	case KEY_ECDSA_SK_CERT:
2956 		if ((ret = sshbuf_put_cstring(cert,
2957 		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2958 		    (ret = sshbuf_put_ec(cert,
2959 		    EC_KEY_get0_public_key(k->ecdsa),
2960 		    EC_KEY_get0_group(k->ecdsa))) != 0)
2961 			goto out;
2962 		if (k->type == KEY_ECDSA_SK_CERT) {
2963 			if ((ret = sshbuf_put_cstring(cert,
2964 			    k->sk_application)) != 0)
2965 				goto out;
2966 		}
2967 		break;
2968 # endif /* OPENSSL_HAS_ECC */
2969 	case KEY_RSA_CERT:
2970 		RSA_get0_key(k->rsa, &rsa_n, &rsa_e, NULL);
2971 		if ((ret = sshbuf_put_bignum2(cert, rsa_e)) != 0 ||
2972 		    (ret = sshbuf_put_bignum2(cert, rsa_n)) != 0)
2973 			goto out;
2974 		break;
2975 #endif /* WITH_OPENSSL */
2976 	case KEY_ED25519_CERT:
2977 	case KEY_ED25519_SK_CERT:
2978 		if ((ret = sshbuf_put_string(cert,
2979 		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
2980 			goto out;
2981 		if (k->type == KEY_ED25519_SK_CERT) {
2982 			if ((ret = sshbuf_put_cstring(cert,
2983 			    k->sk_application)) != 0)
2984 				goto out;
2985 		}
2986 		break;
2987 #ifdef WITH_XMSS
2988 	case KEY_XMSS_CERT:
2989 		if (k->xmss_name == NULL) {
2990 			ret = SSH_ERR_INVALID_ARGUMENT;
2991 			goto out;
2992 		}
2993 		if ((ret = sshbuf_put_cstring(cert, k->xmss_name)) ||
2994 		    (ret = sshbuf_put_string(cert,
2995 		    k->xmss_pk, sshkey_xmss_pklen(k))) != 0)
2996 			goto out;
2997 		break;
2998 #endif /* WITH_XMSS */
2999 	default:
3000 		ret = SSH_ERR_INVALID_ARGUMENT;
3001 		goto out;
3002 	}
3003 
3004 	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
3005 	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
3006 	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
3007 		goto out;
3008 
3009 	if ((principals = sshbuf_new()) == NULL) {
3010 		ret = SSH_ERR_ALLOC_FAIL;
3011 		goto out;
3012 	}
3013 	for (i = 0; i < k->cert->nprincipals; i++) {
3014 		if ((ret = sshbuf_put_cstring(principals,
3015 		    k->cert->principals[i])) != 0)
3016 			goto out;
3017 	}
3018 	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
3019 	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
3020 	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
3021 	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
3022 	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
3023 	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
3024 	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
3025 		goto out;
3026 
3027 	/* Sign the whole mess */
3028 	if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
3029 	    sshbuf_len(cert), alg, sk_provider, 0, signer_ctx)) != 0)
3030 		goto out;
3031 	/* Check and update signature_type against what was actually used */
3032 	if ((ret = sshkey_get_sigtype(