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