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