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