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