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