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