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