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