xref: /openbsd/usr.bin/ssh/sshkey.c (revision 773a7280)
1 /* $OpenBSD: sshkey.c,v 1.148 2024/12/03 15:53:51 tb 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 	/* Q != infinity */
2669 	if (EC_POINT_is_at_infinity(group, public))
2670 		goto out;
2671 
2672 	if ((x = BN_new()) == NULL ||
2673 	    (y = BN_new()) == NULL ||
2674 	    (order = BN_new()) == NULL ||
2675 	    (tmp = BN_new()) == NULL) {
2676 		ret = SSH_ERR_ALLOC_FAIL;
2677 		goto out;
2678 	}
2679 
2680 	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2681 	if (EC_GROUP_get_order(group, order, NULL) != 1 ||
2682 	    EC_POINT_get_affine_coordinates_GFp(group, public,
2683 	    x, y, NULL) != 1) {
2684 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2685 		goto out;
2686 	}
2687 	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2688 	    BN_num_bits(y) <= BN_num_bits(order) / 2)
2689 		goto out;
2690 
2691 	/* nQ == infinity (n == order of subgroup) */
2692 	if ((nq = EC_POINT_new(group)) == NULL) {
2693 		ret = SSH_ERR_ALLOC_FAIL;
2694 		goto out;
2695 	}
2696 	if (EC_POINT_mul(group, nq, NULL, public, order, NULL) != 1) {
2697 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2698 		goto out;
2699 	}
2700 	if (EC_POINT_is_at_infinity(group, nq) != 1)
2701 		goto out;
2702 
2703 	/* x < order - 1, y < order - 1 */
2704 	if (!BN_sub(tmp, order, BN_value_one())) {
2705 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2706 		goto out;
2707 	}
2708 	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2709 		goto out;
2710 	ret = 0;
2711  out:
2712 	BN_clear_free(x);
2713 	BN_clear_free(y);
2714 	BN_clear_free(order);
2715 	BN_clear_free(tmp);
2716 	EC_POINT_free(nq);
2717 	return ret;
2718 }
2719 
2720 int
sshkey_ec_validate_private(const EC_KEY * key)2721 sshkey_ec_validate_private(const EC_KEY *key)
2722 {
2723 	BIGNUM *order = NULL, *tmp = NULL;
2724 	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2725 
2726 	if ((order = BN_new()) == NULL || (tmp = BN_new()) == NULL) {
2727 		ret = SSH_ERR_ALLOC_FAIL;
2728 		goto out;
2729 	}
2730 
2731 	/* log2(private) > log2(order)/2 */
2732 	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) {
2733 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2734 		goto out;
2735 	}
2736 	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2737 	    BN_num_bits(order) / 2)
2738 		goto out;
2739 
2740 	/* private < order - 1 */
2741 	if (!BN_sub(tmp, order, BN_value_one())) {
2742 		ret = SSH_ERR_LIBCRYPTO_ERROR;
2743 		goto out;
2744 	}
2745 	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2746 		goto out;
2747 	ret = 0;
2748  out:
2749 	BN_clear_free(order);
2750 	BN_clear_free(tmp);
2751 	return ret;
2752 }
2753 
2754 void
sshkey_dump_ec_point(const EC_GROUP * group,const EC_POINT * point)2755 sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2756 {
2757 	BIGNUM *x = NULL, *y = NULL;
2758 
2759 	if (point == NULL) {
2760 		fputs("point=(NULL)\n", stderr);
2761 		return;
2762 	}
2763 	if ((x = BN_new()) == NULL || (y = BN_new()) == NULL) {
2764 		fprintf(stderr, "%s: BN_new failed\n", __func__);
2765 		goto out;
2766 	}
2767 	if (EC_POINT_get_affine_coordinates_GFp(group, point,
2768 	    x, y, NULL) != 1) {
2769 		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
2770 		    __func__);
2771 		goto out;
2772 	}
2773 	fputs("x=", stderr);
2774 	BN_print_fp(stderr, x);
2775 	fputs("\ny=", stderr);
2776 	BN_print_fp(stderr, y);
2777 	fputs("\n", stderr);
2778  out:
2779 	BN_clear_free(x);
2780 	BN_clear_free(y);
2781 }
2782 
2783 void
sshkey_dump_ec_key(const EC_KEY * key)2784 sshkey_dump_ec_key(const EC_KEY *key)
2785 {
2786 	const BIGNUM *exponent;
2787 
2788 	sshkey_dump_ec_point(EC_KEY_get0_group(key),
2789 	    EC_KEY_get0_public_key(key));
2790 	fputs("exponent=", stderr);
2791 	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2792 		fputs("(NULL)", stderr);
2793 	else
2794 		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2795 	fputs("\n", stderr);
2796 }
2797 #endif /* WITH_OPENSSL */
2798 
2799 static int
sshkey_private_to_blob2(struct sshkey * prv,struct sshbuf * blob,const char * passphrase,const char * comment,const char * ciphername,int rounds)2800 sshkey_private_to_blob2(struct sshkey *prv, struct sshbuf *blob,
2801     const char *passphrase, const char *comment, const char *ciphername,
2802     int rounds)
2803 {
2804 	u_char *cp, *key = NULL, *pubkeyblob = NULL;
2805 	u_char salt[SALT_LEN];
2806 	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
2807 	u_int check;
2808 	int r = SSH_ERR_INTERNAL_ERROR;
2809 	struct sshcipher_ctx *ciphercontext = NULL;
2810 	const struct sshcipher *cipher;
2811 	const char *kdfname = KDFNAME;
2812 	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
2813 
2814 	if (rounds <= 0)
2815 		rounds = DEFAULT_ROUNDS;
2816 	if (passphrase == NULL || !strlen(passphrase)) {
2817 		ciphername = "none";
2818 		kdfname = "none";
2819 	} else if (ciphername == NULL)
2820 		ciphername = DEFAULT_CIPHERNAME;
2821 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
2822 		r = SSH_ERR_INVALID_ARGUMENT;
2823 		goto out;
2824 	}
2825 
2826 	if ((kdf = sshbuf_new()) == NULL ||
2827 	    (encoded = sshbuf_new()) == NULL ||
2828 	    (encrypted = sshbuf_new()) == NULL) {
2829 		r = SSH_ERR_ALLOC_FAIL;
2830 		goto out;
2831 	}
2832 	blocksize = cipher_blocksize(cipher);
2833 	keylen = cipher_keylen(cipher);
2834 	ivlen = cipher_ivlen(cipher);
2835 	authlen = cipher_authlen(cipher);
2836 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
2837 		r = SSH_ERR_ALLOC_FAIL;
2838 		goto out;
2839 	}
2840 	if (strcmp(kdfname, "bcrypt") == 0) {
2841 		arc4random_buf(salt, SALT_LEN);
2842 		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
2843 		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
2844 			r = SSH_ERR_INVALID_ARGUMENT;
2845 			goto out;
2846 		}
2847 		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
2848 		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
2849 			goto out;
2850 	} else if (strcmp(kdfname, "none") != 0) {
2851 		/* Unsupported KDF type */
2852 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2853 		goto out;
2854 	}
2855 	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
2856 	    key + keylen, ivlen, 1)) != 0)
2857 		goto out;
2858 
2859 	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
2860 	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
2861 	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
2862 	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
2863 	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
2864 	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
2865 	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
2866 		goto out;
2867 
2868 	/* set up the buffer that will be encrypted */
2869 
2870 	/* Random check bytes */
2871 	check = arc4random();
2872 	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
2873 	    (r = sshbuf_put_u32(encrypted, check)) != 0)
2874 		goto out;
2875 
2876 	/* append private key and comment*/
2877 	if ((r = sshkey_private_serialize_opt(prv, encrypted,
2878 	    SSHKEY_SERIALIZE_FULL)) != 0 ||
2879 	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
2880 		goto out;
2881 
2882 	/* padding */
2883 	i = 0;
2884 	while (sshbuf_len(encrypted) % blocksize) {
2885 		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
2886 			goto out;
2887 	}
2888 
2889 	/* length in destination buffer */
2890 	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
2891 		goto out;
2892 
2893 	/* encrypt */
2894 	if ((r = sshbuf_reserve(encoded,
2895 	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
2896 		goto out;
2897 	if ((r = cipher_crypt(ciphercontext, 0, cp,
2898 	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
2899 		goto out;
2900 
2901 	sshbuf_reset(blob);
2902 
2903 	/* assemble uuencoded key */
2904 	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0 ||
2905 	    (r = sshbuf_dtob64(encoded, blob, 1)) != 0 ||
2906 	    (r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
2907 		goto out;
2908 
2909 	/* success */
2910 	r = 0;
2911 
2912  out:
2913 	sshbuf_free(kdf);
2914 	sshbuf_free(encoded);
2915 	sshbuf_free(encrypted);
2916 	cipher_free(ciphercontext);
2917 	explicit_bzero(salt, sizeof(salt));
2918 	if (key != NULL)
2919 		freezero(key, keylen + ivlen);
2920 	if (pubkeyblob != NULL)
2921 		freezero(pubkeyblob, pubkeylen);
2922 	return r;
2923 }
2924 
2925 static int
private2_uudecode(struct sshbuf * blob,struct sshbuf ** decodedp)2926 private2_uudecode(struct sshbuf *blob, struct sshbuf **decodedp)
2927 {
2928 	const u_char *cp;
2929 	size_t encoded_len;
2930 	int r;
2931 	u_char last;
2932 	struct sshbuf *encoded = NULL, *decoded = NULL;
2933 
2934 	if (blob == NULL || decodedp == NULL)
2935 		return SSH_ERR_INVALID_ARGUMENT;
2936 
2937 	*decodedp = NULL;
2938 
2939 	if ((encoded = sshbuf_new()) == NULL ||
2940 	    (decoded = sshbuf_new()) == NULL) {
2941 		r = SSH_ERR_ALLOC_FAIL;
2942 		goto out;
2943 	}
2944 
2945 	/* check preamble */
2946 	cp = sshbuf_ptr(blob);
2947 	encoded_len = sshbuf_len(blob);
2948 	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
2949 	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
2950 		r = SSH_ERR_INVALID_FORMAT;
2951 		goto out;
2952 	}
2953 	cp += MARK_BEGIN_LEN;
2954 	encoded_len -= MARK_BEGIN_LEN;
2955 
2956 	/* Look for end marker, removing whitespace as we go */
2957 	while (encoded_len > 0) {
2958 		if (*cp != '\n' && *cp != '\r') {
2959 			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
2960 				goto out;
2961 		}
2962 		last = *cp;
2963 		encoded_len--;
2964 		cp++;
2965 		if (last == '\n') {
2966 			if (encoded_len >= MARK_END_LEN &&
2967 			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
2968 				/* \0 terminate */
2969 				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
2970 					goto out;
2971 				break;
2972 			}
2973 		}
2974 	}
2975 	if (encoded_len == 0) {
2976 		r = SSH_ERR_INVALID_FORMAT;
2977 		goto out;
2978 	}
2979 
2980 	/* decode base64 */
2981 	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
2982 		goto out;
2983 
2984 	/* check magic */
2985 	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
2986 	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
2987 		r = SSH_ERR_INVALID_FORMAT;
2988 		goto out;
2989 	}
2990 	/* success */
2991 	*decodedp = decoded;
2992 	decoded = NULL;
2993 	r = 0;
2994  out:
2995 	sshbuf_free(encoded);
2996 	sshbuf_free(decoded);
2997 	return r;
2998 }
2999 
3000 static int
private2_decrypt(struct sshbuf * decoded,const char * passphrase,struct sshbuf ** decryptedp,struct sshkey ** pubkeyp)3001 private2_decrypt(struct sshbuf *decoded, const char *passphrase,
3002     struct sshbuf **decryptedp, struct sshkey **pubkeyp)
3003 {
3004 	char *ciphername = NULL, *kdfname = NULL;
3005 	const struct sshcipher *cipher = NULL;
3006 	int r = SSH_ERR_INTERNAL_ERROR;
3007 	size_t keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3008 	struct sshbuf *kdf = NULL, *decrypted = NULL;
3009 	struct sshcipher_ctx *ciphercontext = NULL;
3010 	struct sshkey *pubkey = NULL;
3011 	u_char *key = NULL, *salt = NULL, *dp;
3012 	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3013 
3014 	if (decoded == NULL || decryptedp == NULL || pubkeyp == NULL)
3015 		return SSH_ERR_INVALID_ARGUMENT;
3016 
3017 	*decryptedp = NULL;
3018 	*pubkeyp = NULL;
3019 
3020 	if ((decrypted = sshbuf_new()) == NULL) {
3021 		r = SSH_ERR_ALLOC_FAIL;
3022 		goto out;
3023 	}
3024 
3025 	/* parse public portion of key */
3026 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3027 	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3028 	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3029 	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3030 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
3031 		goto out;
3032 
3033 	if (nkeys != 1) {
3034 		/* XXX only one key supported at present */
3035 		r = SSH_ERR_INVALID_FORMAT;
3036 		goto out;
3037 	}
3038 
3039 	if ((r = sshkey_froms(decoded, &pubkey)) != 0 ||
3040 	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3041 		goto out;
3042 
3043 	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3044 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3045 		goto out;
3046 	}
3047 	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3048 		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3049 		goto out;
3050 	}
3051 	if (strcmp(kdfname, "none") == 0 && strcmp(ciphername, "none") != 0) {
3052 		r = SSH_ERR_INVALID_FORMAT;
3053 		goto out;
3054 	}
3055 	if ((passphrase == NULL || strlen(passphrase) == 0) &&
3056 	    strcmp(kdfname, "none") != 0) {
3057 		/* passphrase required */
3058 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3059 		goto out;
3060 	}
3061 
3062 	/* check size of encrypted key blob */
3063 	blocksize = cipher_blocksize(cipher);
3064 	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3065 		r = SSH_ERR_INVALID_FORMAT;
3066 		goto out;
3067 	}
3068 
3069 	/* setup key */
3070 	keylen = cipher_keylen(cipher);
3071 	ivlen = cipher_ivlen(cipher);
3072 	authlen = cipher_authlen(cipher);
3073 	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3074 		r = SSH_ERR_ALLOC_FAIL;
3075 		goto out;
3076 	}
3077 	if (strcmp(kdfname, "bcrypt") == 0) {
3078 		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3079 		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3080 			goto out;
3081 		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3082 		    key, keylen + ivlen, rounds) < 0) {
3083 			r = SSH_ERR_INVALID_FORMAT;
3084 			goto out;
3085 		}
3086 	}
3087 
3088 	/* check that an appropriate amount of auth data is present */
3089 	if (sshbuf_len(decoded) < authlen ||
3090 	    sshbuf_len(decoded) - authlen < encrypted_len) {
3091 		r = SSH_ERR_INVALID_FORMAT;
3092 		goto out;
3093 	}
3094 
3095 	/* decrypt private portion of key */
3096 	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3097 	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
3098 	    key + keylen, ivlen, 0)) != 0)
3099 		goto out;
3100 	if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3101 	    encrypted_len, 0, authlen)) != 0) {
3102 		/* an integrity error here indicates an incorrect passphrase */
3103 		if (r == SSH_ERR_MAC_INVALID)
3104 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3105 		goto out;
3106 	}
3107 	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3108 		goto out;
3109 	/* there should be no trailing data */
3110 	if (sshbuf_len(decoded) != 0) {
3111 		r = SSH_ERR_INVALID_FORMAT;
3112 		goto out;
3113 	}
3114 
3115 	/* check check bytes */
3116 	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3117 	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3118 		goto out;
3119 	if (check1 != check2) {
3120 		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3121 		goto out;
3122 	}
3123 	/* success */
3124 	*decryptedp = decrypted;
3125 	decrypted = NULL;
3126 	*pubkeyp = pubkey;
3127 	pubkey = NULL;
3128 	r = 0;
3129  out:
3130 	cipher_free(ciphercontext);
3131 	free(ciphername);
3132 	free(kdfname);
3133 	sshkey_free(pubkey);
3134 	if (salt != NULL) {
3135 		explicit_bzero(salt, slen);
3136 		free(salt);
3137 	}
3138 	if (key != NULL) {
3139 		explicit_bzero(key, keylen + ivlen);
3140 		free(key);
3141 	}
3142 	sshbuf_free(kdf);
3143 	sshbuf_free(decrypted);
3144 	return r;
3145 }
3146 
3147 static int
sshkey_parse_private2(struct sshbuf * blob,int type,const char * passphrase,struct sshkey ** keyp,char ** commentp)3148 sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3149     struct sshkey **keyp, char **commentp)
3150 {
3151 	char *comment = NULL;
3152 	int r = SSH_ERR_INTERNAL_ERROR;
3153 	struct sshbuf *decoded = NULL, *decrypted = NULL;
3154 	struct sshkey *k = NULL, *pubkey = NULL;
3155 
3156 	if (keyp != NULL)
3157 		*keyp = NULL;
3158 	if (commentp != NULL)
3159 		*commentp = NULL;
3160 
3161 	/* Undo base64 encoding and decrypt the private section */
3162 	if ((r = private2_uudecode(blob, &decoded)) != 0 ||
3163 	    (r = private2_decrypt(decoded, passphrase,
3164 	    &decrypted, &pubkey)) != 0)
3165 		goto out;
3166 
3167 	if (type != KEY_UNSPEC &&
3168 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
3169 		r = SSH_ERR_KEY_TYPE_MISMATCH;
3170 		goto out;
3171 	}
3172 
3173 	/* Load the private key and comment */
3174 	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3175 	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3176 		goto out;
3177 
3178 	/* Check deterministic padding after private section */
3179 	if ((r = private2_check_padding(decrypted)) != 0)
3180 		goto out;
3181 
3182 	/* Check that the public key in the envelope matches the private key */
3183 	if (!sshkey_equal(pubkey, k)) {
3184 		r = SSH_ERR_INVALID_FORMAT;
3185 		goto out;
3186 	}
3187 
3188 	/* success */
3189 	r = 0;
3190 	if (keyp != NULL) {
3191 		*keyp = k;
3192 		k = NULL;
3193 	}
3194 	if (commentp != NULL) {
3195 		*commentp = comment;
3196 		comment = NULL;
3197 	}
3198  out:
3199 	free(comment);
3200 	sshbuf_free(decoded);
3201 	sshbuf_free(decrypted);
3202 	sshkey_free(k);
3203 	sshkey_free(pubkey);
3204 	return r;
3205 }
3206 
3207 static int
sshkey_parse_private2_pubkey(struct sshbuf * blob,int type,struct sshkey ** keyp)3208 sshkey_parse_private2_pubkey(struct sshbuf *blob, int type,
3209     struct sshkey **keyp)
3210 {
3211 	int r = SSH_ERR_INTERNAL_ERROR;
3212 	struct sshbuf *decoded = NULL;
3213 	struct sshkey *pubkey = NULL;
3214 	u_int nkeys = 0;
3215 
3216 	if (keyp != NULL)
3217 		*keyp = NULL;
3218 
3219 	if ((r = private2_uudecode(blob, &decoded)) != 0)
3220 		goto out;
3221 	/* parse public key from unencrypted envelope */
3222 	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3223 	    (r = sshbuf_skip_string(decoded)) != 0 || /* cipher */
3224 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF alg */
3225 	    (r = sshbuf_skip_string(decoded)) != 0 || /* KDF hint */
3226 	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0)
3227 		goto out;
3228 
3229 	if (nkeys != 1) {
3230 		/* XXX only one key supported at present */
3231 		r = SSH_ERR_INVALID_FORMAT;
3232 		goto out;
3233 	}
3234 
3235 	/* Parse the public key */
3236 	if ((r = sshkey_froms(decoded, &pubkey)) != 0)
3237 		goto out;
3238 
3239 	if (type != KEY_UNSPEC &&
3240 	    sshkey_type_plain(type) != sshkey_type_plain(pubkey->type)) {
3241 		r = SSH_ERR_KEY_TYPE_MISMATCH;
3242 		goto out;
3243 	}
3244 
3245 	/* success */
3246 	r = 0;
3247 	if (keyp != NULL) {
3248 		*keyp = pubkey;
3249 		pubkey = NULL;
3250 	}
3251  out:
3252 	sshbuf_free(decoded);
3253 	sshkey_free(pubkey);
3254 	return r;
3255 }
3256 
3257 #ifdef WITH_OPENSSL
3258 /* convert SSH v2 key to PEM or PKCS#8 format */
3259 static int
sshkey_private_to_blob_pem_pkcs8(struct sshkey * key,struct sshbuf * buf,int format,const char * _passphrase,const char * comment)3260 sshkey_private_to_blob_pem_pkcs8(struct sshkey *key, struct sshbuf *buf,
3261     int format, const char *_passphrase, const char *comment)
3262 {
3263 	int was_shielded = sshkey_is_shielded(key);
3264 	int success, r;
3265 	int blen, len = strlen(_passphrase);
3266 	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3267 	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3268 	char *bptr;
3269 	BIO *bio = NULL;
3270 	struct sshbuf *blob;
3271 	EVP_PKEY *pkey = NULL;
3272 
3273 	if (len > 0 && len <= 4)
3274 		return SSH_ERR_PASSPHRASE_TOO_SHORT;
3275 	if ((blob = sshbuf_new()) == NULL)
3276 		return SSH_ERR_ALLOC_FAIL;
3277 	if ((bio = BIO_new(BIO_s_mem())) == NULL) {
3278 		r = SSH_ERR_ALLOC_FAIL;
3279 		goto out;
3280 	}
3281 	if ((r = sshkey_unshield_private(key)) != 0)
3282 		goto out;
3283 
3284 	switch (key->type) {
3285 #ifdef WITH_DSA
3286 	case KEY_DSA:
3287 		if (format == SSHKEY_PRIVATE_PEM) {
3288 			success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3289 			    cipher, passphrase, len, NULL, NULL);
3290 		} else {
3291 			if ((pkey = EVP_PKEY_new()) == NULL) {
3292 				r = SSH_ERR_ALLOC_FAIL;
3293 				goto out;
3294 			}
3295 			success = EVP_PKEY_set1_DSA(pkey, key->dsa);
3296 		}
3297 		break;
3298 #endif
3299 	case KEY_ECDSA:
3300 		if (format == SSHKEY_PRIVATE_PEM) {
3301 			success = PEM_write_bio_ECPrivateKey(bio,
3302 			    EVP_PKEY_get0_EC_KEY(key->pkey),
3303 			    cipher, passphrase, len, NULL, NULL);
3304 		} else {
3305 			pkey = key->pkey;
3306 			EVP_PKEY_up_ref(key->pkey);
3307 			success = 1;
3308 		}
3309 		break;
3310 	case KEY_RSA:
3311 		if (format == SSHKEY_PRIVATE_PEM) {
3312 			success = PEM_write_bio_RSAPrivateKey(bio,
3313 			    EVP_PKEY_get0_RSA(key->pkey),
3314 			    cipher, passphrase, len, NULL, NULL);
3315 		} else {
3316 			pkey = key->pkey;
3317 			EVP_PKEY_up_ref(key->pkey);
3318 			success = 1;
3319 		}
3320 		break;
3321 	default:
3322 		success = 0;
3323 		break;
3324 	}
3325 	if (success == 0) {
3326 		r = SSH_ERR_LIBCRYPTO_ERROR;
3327 		goto out;
3328 	}
3329 	if (format == SSHKEY_PRIVATE_PKCS8) {
3330 		if ((success = PEM_write_bio_PrivateKey(bio, pkey, cipher,
3331 		    passphrase, len, NULL, NULL)) == 0) {
3332 			r = SSH_ERR_LIBCRYPTO_ERROR;
3333 			goto out;
3334 		}
3335 	}
3336 	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3337 		r = SSH_ERR_INTERNAL_ERROR;
3338 		goto out;
3339 	}
3340 	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3341 		goto out;
3342 	r = 0;
3343  out:
3344 	if (was_shielded)
3345 		r = sshkey_shield_private(key);
3346 	if (r == 0)
3347 		r = sshbuf_putb(buf, blob);
3348 
3349 	EVP_PKEY_free(pkey);
3350 	sshbuf_free(blob);
3351 	BIO_free(bio);
3352 	return r;
3353 }
3354 #endif /* WITH_OPENSSL */
3355 
3356 /* Serialise "key" to buffer "blob" */
3357 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)3358 sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3359     const char *passphrase, const char *comment,
3360     int format, const char *openssh_format_cipher, int openssh_format_rounds)
3361 {
3362 	switch (key->type) {
3363 #ifdef WITH_OPENSSL
3364 	case KEY_DSA:
3365 	case KEY_ECDSA:
3366 	case KEY_RSA:
3367 		break; /* see below */
3368 #endif /* WITH_OPENSSL */
3369 	case KEY_ED25519:
3370 	case KEY_ED25519_SK:
3371 #ifdef WITH_XMSS
3372 	case KEY_XMSS:
3373 #endif /* WITH_XMSS */
3374 #ifdef WITH_OPENSSL
3375 	case KEY_ECDSA_SK:
3376 #endif /* WITH_OPENSSL */
3377 		return sshkey_private_to_blob2(key, blob, passphrase,
3378 		    comment, openssh_format_cipher, openssh_format_rounds);
3379 	default:
3380 		return SSH_ERR_KEY_TYPE_UNKNOWN;
3381 	}
3382 
3383 #ifdef WITH_OPENSSL
3384 	switch (format) {
3385 	case SSHKEY_PRIVATE_OPENSSH:
3386 		return sshkey_private_to_blob2(key, blob, passphrase,
3387 		    comment, openssh_format_cipher, openssh_format_rounds);
3388 	case SSHKEY_PRIVATE_PEM:
3389 	case SSHKEY_PRIVATE_PKCS8:
3390 		return sshkey_private_to_blob_pem_pkcs8(key, blob,
3391 		    format, passphrase, comment);
3392 	default:
3393 		return SSH_ERR_INVALID_ARGUMENT;
3394 	}
3395 #endif /* WITH_OPENSSL */
3396 }
3397 
3398 #ifdef WITH_OPENSSL
3399 static int
translate_libcrypto_error(unsigned long pem_err)3400 translate_libcrypto_error(unsigned long pem_err)
3401 {
3402 	int pem_reason = ERR_GET_REASON(pem_err);
3403 
3404 	switch (ERR_GET_LIB(pem_err)) {
3405 	case ERR_LIB_PEM:
3406 		switch (pem_reason) {
3407 		case PEM_R_BAD_PASSWORD_READ:
3408 		case PEM_R_PROBLEMS_GETTING_PASSWORD:
3409 		case PEM_R_BAD_DECRYPT:
3410 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
3411 		default:
3412 			return SSH_ERR_INVALID_FORMAT;
3413 		}
3414 	case ERR_LIB_EVP:
3415 		switch (pem_reason) {
3416 		case EVP_R_BAD_DECRYPT:
3417 			return SSH_ERR_KEY_WRONG_PASSPHRASE;
3418 #ifdef EVP_R_BN_DECODE_ERROR
3419 		case EVP_R_BN_DECODE_ERROR:
3420 #endif
3421 		case EVP_R_DECODE_ERROR:
3422 #ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
3423 		case EVP_R_PRIVATE_KEY_DECODE_ERROR:
3424 #endif
3425 			return SSH_ERR_INVALID_FORMAT;
3426 		default:
3427 			return SSH_ERR_LIBCRYPTO_ERROR;
3428 		}
3429 	case ERR_LIB_ASN1:
3430 		return SSH_ERR_INVALID_FORMAT;
3431 	}
3432 	return SSH_ERR_LIBCRYPTO_ERROR;
3433 }
3434 
3435 static void
clear_libcrypto_errors(void)3436 clear_libcrypto_errors(void)
3437 {
3438 	while (ERR_get_error() != 0)
3439 		;
3440 }
3441 
3442 /*
3443  * Translate OpenSSL error codes to determine whether
3444  * passphrase is required/incorrect.
3445  */
3446 static int
convert_libcrypto_error(void)3447 convert_libcrypto_error(void)
3448 {
3449 	/*
3450 	 * Some password errors are reported at the beginning
3451 	 * of the error queue.
3452 	 */
3453 	if (translate_libcrypto_error(ERR_peek_error()) ==
3454 	    SSH_ERR_KEY_WRONG_PASSPHRASE)
3455 		return SSH_ERR_KEY_WRONG_PASSPHRASE;
3456 	return translate_libcrypto_error(ERR_peek_last_error());
3457 }
3458 
3459 static int
sshkey_parse_private_pem_fileblob(struct sshbuf * blob,int type,const char * passphrase,struct sshkey ** keyp)3460 sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3461     const char *passphrase, struct sshkey **keyp)
3462 {
3463 	EVP_PKEY *pk = NULL;
3464 	struct sshkey *prv = NULL;
3465 	BIO *bio = NULL;
3466 	int r;
3467 	RSA *rsa = NULL;
3468 	EC_KEY *ecdsa = NULL;
3469 
3470 	if (keyp != NULL)
3471 		*keyp = NULL;
3472 
3473 	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3474 		return SSH_ERR_ALLOC_FAIL;
3475 	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3476 	    (int)sshbuf_len(blob)) {
3477 		r = SSH_ERR_ALLOC_FAIL;
3478 		goto out;
3479 	}
3480 
3481 	clear_libcrypto_errors();
3482 	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3483 	    (char *)passphrase)) == NULL) {
3484 		/*
3485 		 * libcrypto may return various ASN.1 errors when attempting
3486 		 * to parse a key with an incorrect passphrase.
3487 		 * Treat all format errors as "incorrect passphrase" if a
3488 		 * passphrase was supplied.
3489 		 */
3490 		if (passphrase != NULL && *passphrase != '\0')
3491 			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3492 		else
3493 			r = convert_libcrypto_error();
3494 		goto out;
3495 	}
3496 	if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA &&
3497 	    (type == KEY_UNSPEC || type == KEY_RSA)) {
3498 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3499 			r = SSH_ERR_ALLOC_FAIL;
3500 			goto out;
3501 		}
3502 		if ((rsa = EVP_PKEY_get1_RSA(pk)) == NULL) {
3503 			r = SSH_ERR_LIBCRYPTO_ERROR;
3504 			goto out;
3505 		}
3506 		prv->type = KEY_RSA;
3507 #ifdef DEBUG_PK
3508 		RSA_print_fp(stderr, rsa, 8);
3509 #endif
3510 		if (RSA_blinding_on(rsa, NULL) != 1 ||
3511 		    EVP_PKEY_set1_RSA(pk, rsa) != 1) {
3512 			r = SSH_ERR_LIBCRYPTO_ERROR;
3513 			goto out;
3514 		}
3515 		EVP_PKEY_up_ref(pk);
3516 		prv->pkey = pk;
3517 		if ((r = sshkey_check_rsa_length(prv, 0)) != 0)
3518 			goto out;
3519 #ifdef WITH_DSA
3520 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_DSA &&
3521 	    (type == KEY_UNSPEC || type == KEY_DSA)) {
3522 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3523 			r = SSH_ERR_ALLOC_FAIL;
3524 			goto out;
3525 		}
3526 		prv->dsa = EVP_PKEY_get1_DSA(pk);
3527 		prv->type = KEY_DSA;
3528 #ifdef DEBUG_PK
3529 		DSA_print_fp(stderr, prv->dsa, 8);
3530 #endif
3531 #endif
3532 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_EC &&
3533 	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3534 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3535 			r = SSH_ERR_ALLOC_FAIL;
3536 			goto out;
3537 		}
3538 		if ((prv->ecdsa_nid = sshkey_ecdsa_fixup_group(pk)) == -1 ||
3539 		    (ecdsa = EVP_PKEY_get1_EC_KEY(pk)) == NULL) {
3540 			r = SSH_ERR_LIBCRYPTO_ERROR;
3541 			goto out;
3542 		}
3543 		prv->type = KEY_ECDSA;
3544 		if (sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3545 		    sshkey_ec_validate_public(EC_KEY_get0_group(ecdsa),
3546 		    EC_KEY_get0_public_key(ecdsa)) != 0 ||
3547 		    sshkey_ec_validate_private(ecdsa) != 0) {
3548 			r = SSH_ERR_INVALID_FORMAT;
3549 			goto out;
3550 		}
3551 		EVP_PKEY_up_ref(pk);
3552 		prv->pkey = pk;
3553 #ifdef DEBUG_PK
3554 		if (prv != NULL && prv->pkey != NULL)
3555 			sshkey_dump_ec_key(EVP_PKEY_get0_EC_KEY(prv->pkey));
3556 #endif
3557 	} else if (EVP_PKEY_base_id(pk) == EVP_PKEY_ED25519 &&
3558 	    (type == KEY_UNSPEC || type == KEY_ED25519)) {
3559 		size_t len;
3560 
3561 		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL ||
3562 		    (prv->ed25519_sk = calloc(1, ED25519_SK_SZ)) == NULL ||
3563 		    (prv->ed25519_pk = calloc(1, ED25519_PK_SZ)) == NULL) {
3564 			r = SSH_ERR_ALLOC_FAIL;
3565 			goto out;
3566 		}
3567 		prv->type = KEY_ED25519;
3568 		len = ED25519_PK_SZ;
3569 		if (!EVP_PKEY_get_raw_public_key(pk, prv->ed25519_pk, &len)) {
3570 			r = SSH_ERR_LIBCRYPTO_ERROR;
3571 			goto out;
3572 		}
3573 		if (len != ED25519_PK_SZ) {
3574 			r = SSH_ERR_INVALID_FORMAT;
3575 			goto out;
3576 		}
3577 		len = ED25519_SK_SZ - ED25519_PK_SZ;
3578 		if (!EVP_PKEY_get_raw_private_key(pk, prv->ed25519_sk, &len)) {
3579 			r = SSH_ERR_LIBCRYPTO_ERROR;
3580 			goto out;
3581 		}
3582 		if (len != ED25519_SK_SZ - ED25519_PK_SZ) {
3583 			r = SSH_ERR_INVALID_FORMAT;
3584 			goto out;
3585 		}
3586 		/* Append the public key to our private key */
3587 		memcpy(prv->ed25519_sk + (ED25519_SK_SZ - ED25519_PK_SZ),
3588 		    prv->ed25519_pk, ED25519_PK_SZ);
3589 #ifdef DEBUG_PK
3590 		sshbuf_dump_data(prv->ed25519_sk, ED25519_SK_SZ, stderr);
3591 #endif
3592 	} else {
3593 		r = SSH_ERR_INVALID_FORMAT;
3594 		goto out;
3595 	}
3596 	r = 0;
3597 	if (keyp != NULL) {
3598 		*keyp = prv;
3599 		prv = NULL;
3600 	}
3601  out:
3602 	BIO_free(bio);
3603 	EVP_PKEY_free(pk);
3604 	RSA_free(rsa);
3605 	EC_KEY_free(ecdsa);
3606 	sshkey_free(prv);
3607 	return r;
3608 }
3609 #endif /* WITH_OPENSSL */
3610 
3611 int
sshkey_parse_private_fileblob_type(struct sshbuf * blob,int type,const char * passphrase,struct sshkey ** keyp,char ** commentp)3612 sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3613     const char *passphrase, struct sshkey **keyp, char **commentp)
3614 {
3615 	int r = SSH_ERR_INTERNAL_ERROR;
3616 
3617 	if (keyp != NULL)
3618 		*keyp = NULL;
3619 	if (commentp != NULL)
3620 		*commentp = NULL;
3621 
3622 	switch (type) {
3623 	case KEY_XMSS:
3624 		/* No fallback for new-format-only keys */
3625 		return sshkey_parse_private2(blob, type, passphrase,
3626 		    keyp, commentp);
3627 	default:
3628 		r = sshkey_parse_private2(blob, type, passphrase, keyp,
3629 		    commentp);
3630 		/* Only fallback to PEM parser if a format error occurred. */
3631 		if (r != SSH_ERR_INVALID_FORMAT)
3632 			return r;
3633 #ifdef WITH_OPENSSL
3634 		return sshkey_parse_private_pem_fileblob(blob, type,
3635 		    passphrase, keyp);
3636 #else
3637 		return SSH_ERR_INVALID_FORMAT;
3638 #endif /* WITH_OPENSSL */
3639 	}
3640 }
3641 
3642 int
sshkey_parse_private_fileblob(struct sshbuf * buffer,const char * passphrase,struct sshkey ** keyp,char ** commentp)3643 sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3644     struct sshkey **keyp, char **commentp)
3645 {
3646 	if (keyp != NULL)
3647 		*keyp = NULL;
3648 	if (commentp != NULL)
3649 		*commentp = NULL;
3650 
3651 	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3652 	    passphrase, keyp, commentp);
3653 }
3654 
3655 void
sshkey_sig_details_free(struct sshkey_sig_details * details)3656 sshkey_sig_details_free(struct sshkey_sig_details *details)
3657 {
3658 	freezero(details, sizeof(*details));
3659 }
3660 
3661 int
sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf * blob,int type,struct sshkey ** pubkeyp)3662 sshkey_parse_pubkey_from_private_fileblob_type(struct sshbuf *blob, int type,
3663     struct sshkey **pubkeyp)
3664 {
3665 	int r = SSH_ERR_INTERNAL_ERROR;
3666 
3667 	if (pubkeyp != NULL)
3668 		*pubkeyp = NULL;
3669 	/* only new-format private keys bundle a public key inside */
3670 	if ((r = sshkey_parse_private2_pubkey(blob, type, pubkeyp)) != 0)
3671 		return r;
3672 	return 0;
3673 }
3674 
3675 #ifdef WITH_XMSS
3676 /*
3677  * serialize the key with the current state and forward the state
3678  * maxsign times.
3679  */
3680 int
sshkey_private_serialize_maxsign(struct sshkey * k,struct sshbuf * b,u_int32_t maxsign,int printerror)3681 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
3682     u_int32_t maxsign, int printerror)
3683 {
3684 	int r, rupdate;
3685 
3686 	if (maxsign == 0 ||
3687 	    sshkey_type_plain(k->type) != KEY_XMSS)
3688 		return sshkey_private_serialize_opt(k, b,
3689 		    SSHKEY_SERIALIZE_DEFAULT);
3690 	if ((r = sshkey_xmss_get_state(k, printerror)) != 0 ||
3691 	    (r = sshkey_private_serialize_opt(k, b,
3692 	    SSHKEY_SERIALIZE_STATE)) != 0 ||
3693 	    (r = sshkey_xmss_forward_state(k, maxsign)) != 0)
3694 		goto out;
3695 	r = 0;
3696 out:
3697 	if ((rupdate = sshkey_xmss_update_state(k, printerror)) != 0) {
3698 		if (r == 0)
3699 			r = rupdate;
3700 	}
3701 	return r;
3702 }
3703 
3704 u_int32_t
sshkey_signatures_left(const struct sshkey * k)3705 sshkey_signatures_left(const struct sshkey *k)
3706 {
3707 	if (sshkey_type_plain(k->type) == KEY_XMSS)
3708 		return sshkey_xmss_signatures_left(k);
3709 	return 0;
3710 }
3711 
3712 int
sshkey_enable_maxsign(struct sshkey * k,u_int32_t maxsign)3713 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
3714 {
3715 	if (sshkey_type_plain(k->type) != KEY_XMSS)
3716 		return SSH_ERR_INVALID_ARGUMENT;
3717 	return sshkey_xmss_enable_maxsign(k, maxsign);
3718 }
3719 
3720 int
sshkey_set_filename(struct sshkey * k,const char * filename)3721 sshkey_set_filename(struct sshkey *k, const char *filename)
3722 {
3723 	if (k == NULL)
3724 		return SSH_ERR_INVALID_ARGUMENT;
3725 	if (sshkey_type_plain(k->type) != KEY_XMSS)
3726 		return 0;
3727 	if (filename == NULL)
3728 		return SSH_ERR_INVALID_ARGUMENT;
3729 	if ((k->xmss_filename = strdup(filename)) == NULL)
3730 		return SSH_ERR_ALLOC_FAIL;
3731 	return 0;
3732 }
3733 #else
3734 int
sshkey_private_serialize_maxsign(struct sshkey * k,struct sshbuf * b,u_int32_t maxsign,int printerror)3735 sshkey_private_serialize_maxsign(struct sshkey *k, struct sshbuf *b,
3736     u_int32_t maxsign, int printerror)
3737 {
3738 	return sshkey_private_serialize_opt(k, b, SSHKEY_SERIALIZE_DEFAULT);
3739 }
3740 
3741 u_int32_t
sshkey_signatures_left(const struct sshkey * k)3742 sshkey_signatures_left(const struct sshkey *k)
3743 {
3744 	return 0;
3745 }
3746 
3747 int
sshkey_enable_maxsign(struct sshkey * k,u_int32_t maxsign)3748 sshkey_enable_maxsign(struct sshkey *k, u_int32_t maxsign)
3749 {
3750 	return SSH_ERR_INVALID_ARGUMENT;
3751 }
3752 
3753 int
sshkey_set_filename(struct sshkey * k,const char * filename)3754 sshkey_set_filename(struct sshkey *k, const char *filename)
3755 {
3756 	if (k == NULL)
3757 		return SSH_ERR_INVALID_ARGUMENT;
3758 	return 0;
3759 }
3760 #endif /* WITH_XMSS */
3761