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