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