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