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