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