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