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