GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/ssh/lib/../sshkey.c Lines: 869 1699 51.1 %
Date: 2017-11-07 Branches: 492 1585 31.0 %

Line Branch Exec Source
1
/* $OpenBSD: sshkey.c,v 1.56 2017/08/12 06:42:52 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 <sys/types.h>
29
#include <netinet/in.h>
30
31
#ifdef WITH_OPENSSL
32
#include <openssl/evp.h>
33
#include <openssl/err.h>
34
#include <openssl/pem.h>
35
#endif
36
37
#include "crypto_api.h"
38
39
#include <errno.h>
40
#include <stdio.h>
41
#include <string.h>
42
#include <util.h>
43
#include <limits.h>
44
#include <resolv.h>
45
46
#include "ssh2.h"
47
#include "ssherr.h"
48
#include "misc.h"
49
#include "sshbuf.h"
50
#include "cipher.h"
51
#include "digest.h"
52
#define SSHKEY_INTERNAL
53
#include "sshkey.h"
54
#include "match.h"
55
56
/* openssh private key file format */
57
#define MARK_BEGIN		"-----BEGIN OPENSSH PRIVATE KEY-----\n"
58
#define MARK_END		"-----END OPENSSH PRIVATE KEY-----\n"
59
#define MARK_BEGIN_LEN		(sizeof(MARK_BEGIN) - 1)
60
#define MARK_END_LEN		(sizeof(MARK_END) - 1)
61
#define KDFNAME			"bcrypt"
62
#define AUTH_MAGIC		"openssh-key-v1"
63
#define SALT_LEN		16
64
#define DEFAULT_CIPHERNAME	"aes256-ctr"
65
#define	DEFAULT_ROUNDS		16
66
67
/* Version identification string for SSH v1 identity files. */
68
#define LEGACY_BEGIN		"SSH PRIVATE KEY FILE FORMAT 1.1\n"
69
70
static int sshkey_from_blob_internal(struct sshbuf *buf,
71
    struct sshkey **keyp, int allow_cert);
72
73
/* Supported key types */
74
struct keytype {
75
	const char *name;
76
	const char *shortname;
77
	int type;
78
	int nid;
79
	int cert;
80
	int sigonly;
81
};
82
static const struct keytype keytypes[] = {
83
	{ "ssh-ed25519", "ED25519", KEY_ED25519, 0, 0, 0 },
84
	{ "ssh-ed25519-cert-v01@openssh.com", "ED25519-CERT",
85
	    KEY_ED25519_CERT, 0, 1, 0 },
86
#ifdef WITH_OPENSSL
87
	{ "ssh-rsa", "RSA", KEY_RSA, 0, 0, 0 },
88
	{ "rsa-sha2-256", "RSA", KEY_RSA, 0, 0, 1 },
89
	{ "rsa-sha2-512", "RSA", KEY_RSA, 0, 0, 1 },
90
	{ "ssh-dss", "DSA", KEY_DSA, 0, 0, 0 },
91
	{ "ecdsa-sha2-nistp256", "ECDSA", KEY_ECDSA, NID_X9_62_prime256v1, 0, 0 },
92
	{ "ecdsa-sha2-nistp384", "ECDSA", KEY_ECDSA, NID_secp384r1, 0, 0 },
93
	{ "ecdsa-sha2-nistp521", "ECDSA", KEY_ECDSA, NID_secp521r1, 0, 0 },
94
	{ "ssh-rsa-cert-v01@openssh.com", "RSA-CERT", KEY_RSA_CERT, 0, 1, 0 },
95
	{ "ssh-dss-cert-v01@openssh.com", "DSA-CERT", KEY_DSA_CERT, 0, 1, 0 },
96
	{ "ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA-CERT",
97
	    KEY_ECDSA_CERT, NID_X9_62_prime256v1, 1, 0 },
98
	{ "ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA-CERT",
99
	    KEY_ECDSA_CERT, NID_secp384r1, 1, 0 },
100
	{ "ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA-CERT",
101
	    KEY_ECDSA_CERT, NID_secp521r1, 1, 0 },
102
#endif /* WITH_OPENSSL */
103
	{ NULL, NULL, -1, -1, 0, 0 }
104
};
105
106
const char *
107
sshkey_type(const struct sshkey *k)
108
{
109
	const struct keytype *kt;
110
111
858
	for (kt = keytypes; kt->type != -1; kt++) {
112
378
		if (kt->type == k->type)
113
102
			return kt->shortname;
114
	}
115
	return "unknown";
116
102
}
117
118
static const char *
119
sshkey_ssh_name_from_type_nid(int type, int nid)
120
{
121
	const struct keytype *kt;
122
123
1901
	for (kt = keytypes; kt->type != -1; kt++) {
124

1107
		if (kt->type == type && (kt->nid == 0 || kt->nid == nid))
125
259
			return kt->name;
126
	}
127
	return "ssh-unknown";
128
259
}
129
130
int
131
sshkey_type_is_cert(int type)
132
{
133
	const struct keytype *kt;
134
135
15657
	for (kt = keytypes; kt->type != -1; kt++) {
136
6991
		if (kt->type == type)
137
643
			return kt->cert;
138
	}
139
344
	return 0;
140
987
}
141
142
const char *
143
sshkey_ssh_name(const struct sshkey *k)
144
{
145
156
	return sshkey_ssh_name_from_type_nid(k->type, k->ecdsa_nid);
146
}
147
148
const char *
149
sshkey_ssh_name_plain(const struct sshkey *k)
150
{
151
3
	return sshkey_ssh_name_from_type_nid(sshkey_type_plain(k->type),
152
1
	    k->ecdsa_nid);
153
}
154
155
int
156
sshkey_type_from_name(const char *name)
157
{
158
	const struct keytype *kt;
159
160
1456
	for (kt = keytypes; kt->type != -1; kt++) {
161
		/* Only allow shortname matches for plain key types */
162

1596
		if ((kt->name != NULL && strcmp(name, kt->name) == 0) ||
163
787
		    (!kt->cert && strcasecmp(kt->shortname, name) == 0))
164
188
			return kt->type;
165
	}
166
	return KEY_UNSPEC;
167
188
}
168
169
int
170
sshkey_ecdsa_nid_from_name(const char *name)
171
{
172
	const struct keytype *kt;
173
174
332
	for (kt = keytypes; kt->type != -1; kt++) {
175

284
		if (kt->type != KEY_ECDSA && kt->type != KEY_ECDSA_CERT)
176
			continue;
177

60
		if (kt->name != NULL && strcmp(name, kt->name) == 0)
178
18
			return kt->nid;
179
	}
180
2
	return -1;
181
20
}
182
183
char *
184
sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
185
{
186
	char *tmp, *ret = NULL;
187
	size_t nlen, rlen = 0;
188
	const struct keytype *kt;
189
190
	for (kt = keytypes; kt->type != -1; kt++) {
191
		if (kt->name == NULL)
192
			continue;
193
		if (!include_sigonly && kt->sigonly)
194
			continue;
195
		if ((certs_only && !kt->cert) || (plain_only && kt->cert))
196
			continue;
197
		if (ret != NULL)
198
			ret[rlen++] = sep;
199
		nlen = strlen(kt->name);
200
		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
201
			free(ret);
202
			return NULL;
203
		}
204
		ret = tmp;
205
		memcpy(ret + rlen, kt->name, nlen + 1);
206
		rlen += nlen;
207
	}
208
	return ret;
209
}
210
211
int
212
sshkey_names_valid2(const char *names, int allow_wildcard)
213
{
214
	char *s, *cp, *p;
215
	const struct keytype *kt;
216
	int type;
217
218
	if (names == NULL || strcmp(names, "") == 0)
219
		return 0;
220
	if ((s = cp = strdup(names)) == NULL)
221
		return 0;
222
	for ((p = strsep(&cp, ",")); p && *p != '\0';
223
	    (p = strsep(&cp, ","))) {
224
		type = sshkey_type_from_name(p);
225
		if (type == KEY_UNSPEC) {
226
			if (allow_wildcard) {
227
				/*
228
				 * Try matching key types against the string.
229
				 * If any has a positive or negative match then
230
				 * the component is accepted.
231
				 */
232
				for (kt = keytypes; kt->type != -1; kt++) {
233
					if (match_pattern_list(kt->name,
234
					    p, 0) != 0)
235
						break;
236
				}
237
				if (kt->type != -1)
238
					continue;
239
			}
240
			free(s);
241
			return 0;
242
		}
243
	}
244
	free(s);
245
	return 1;
246
}
247
248
u_int
249
sshkey_size(const struct sshkey *k)
250
{
251


202
	switch (k->type) {
252
#ifdef WITH_OPENSSL
253
	case KEY_RSA:
254
	case KEY_RSA_CERT:
255
44
		return BN_num_bits(k->rsa->n);
256
	case KEY_DSA:
257
	case KEY_DSA_CERT:
258
16
		return BN_num_bits(k->dsa->p);
259
	case KEY_ECDSA:
260
	case KEY_ECDSA_CERT:
261
17
		return sshkey_curve_nid_to_bits(k->ecdsa_nid);
262
#endif /* WITH_OPENSSL */
263
	case KEY_ED25519:
264
	case KEY_ED25519_CERT:
265
24
		return 256;	/* XXX */
266
	}
267
	return 0;
268
101
}
269
270
static int
271
sshkey_type_is_valid_ca(int type)
272
{
273
	switch (type) {
274
	case KEY_RSA:
275
	case KEY_DSA:
276
	case KEY_ECDSA:
277
	case KEY_ED25519:
278
		return 1;
279
	default:
280
		return 0;
281
	}
282
}
283
284
int
285
sshkey_is_cert(const struct sshkey *k)
286
{
287
2034
	if (k == NULL)
288
30
		return 0;
289
987
	return sshkey_type_is_cert(k->type);
290
1017
}
291
292
/* Return the cert-less equivalent to a certified key type */
293
int
294
sshkey_type_plain(int type)
295
{
296

794
	switch (type) {
297
	case KEY_RSA_CERT:
298
1
		return KEY_RSA;
299
	case KEY_DSA_CERT:
300
		return KEY_DSA;
301
	case KEY_ECDSA_CERT:
302
3
		return KEY_ECDSA;
303
	case KEY_ED25519_CERT:
304
1
		return KEY_ED25519;
305
	default:
306
392
		return type;
307
	}
308
397
}
309
310
#ifdef WITH_OPENSSL
311
/* XXX: these are really begging for a table-driven approach */
312
int
313
sshkey_curve_name_to_nid(const char *name)
314
{
315
18
	if (strcmp(name, "nistp256") == 0)
316
9
		return NID_X9_62_prime256v1;
317
	else if (strcmp(name, "nistp384") == 0)
318
		return NID_secp384r1;
319
	else if (strcmp(name, "nistp521") == 0)
320
		return NID_secp521r1;
321
	else
322
		return -1;
323
9
}
324
325
u_int
326
sshkey_curve_nid_to_bits(int nid)
327
{
328

40
	switch (nid) {
329
	case NID_X9_62_prime256v1:
330
18
		return 256;
331
	case NID_secp384r1:
332
		return 384;
333
	case NID_secp521r1:
334
		return 521;
335
	default:
336
2
		return 0;
337
	}
338
20
}
339
340
int
341
sshkey_ecdsa_bits_to_nid(int bits)
342
{
343

8
	switch (bits) {
344
	case 256:
345
4
		return NID_X9_62_prime256v1;
346
	case 384:
347
		return NID_secp384r1;
348
	case 521:
349
		return NID_secp521r1;
350
	default:
351
		return -1;
352
	}
353
4
}
354
355
const char *
356
sshkey_curve_nid_to_name(int nid)
357
{
358

44
	switch (nid) {
359
	case NID_X9_62_prime256v1:
360
22
		return "nistp256";
361
	case NID_secp384r1:
362
		return "nistp384";
363
	case NID_secp521r1:
364
		return "nistp521";
365
	default:
366
		return NULL;
367
	}
368
22
}
369
370
int
371
sshkey_ec_nid_to_hash_alg(int nid)
372
{
373
2
	int kbits = sshkey_curve_nid_to_bits(nid);
374
375
1
	if (kbits <= 0)
376
		return -1;
377
378
	/* RFC5656 section 6.2.1 */
379
1
	if (kbits <= 256)
380
1
		return SSH_DIGEST_SHA256;
381
	else if (kbits <= 384)
382
		return SSH_DIGEST_SHA384;
383
	else
384
		return SSH_DIGEST_SHA512;
385
1
}
386
#endif /* WITH_OPENSSL */
387
388
static void
389
cert_free(struct sshkey_cert *cert)
390
{
391
	u_int i;
392
393
	if (cert == NULL)
394
		return;
395
	sshbuf_free(cert->certblob);
396
	sshbuf_free(cert->critical);
397
	sshbuf_free(cert->extensions);
398
	free(cert->key_id);
399
	for (i = 0; i < cert->nprincipals; i++)
400
		free(cert->principals[i]);
401
	free(cert->principals);
402
	sshkey_free(cert->signature_key);
403
	explicit_bzero(cert, sizeof(*cert));
404
	free(cert);
405
}
406
407
static struct sshkey_cert *
408
cert_new(void)
409
{
410
	struct sshkey_cert *cert;
411
412
	if ((cert = calloc(1, sizeof(*cert))) == NULL)
413
		return NULL;
414
	if ((cert->certblob = sshbuf_new()) == NULL ||
415
	    (cert->critical = sshbuf_new()) == NULL ||
416
	    (cert->extensions = sshbuf_new()) == NULL) {
417
		cert_free(cert);
418
		return NULL;
419
	}
420
	cert->key_id = NULL;
421
	cert->principals = NULL;
422
	cert->signature_key = NULL;
423
	return cert;
424
}
425
426
struct sshkey *
427
sshkey_new(int type)
428
{
429
	struct sshkey *k;
430
#ifdef WITH_OPENSSL
431
	RSA *rsa;
432
	DSA *dsa;
433
#endif /* WITH_OPENSSL */
434
435
704
	if ((k = calloc(1, sizeof(*k))) == NULL)
436
		return NULL;
437
421
	k->type = type;
438
421
	k->ecdsa = NULL;
439
421
	k->ecdsa_nid = -1;
440
421
	k->dsa = NULL;
441
421
	k->rsa = NULL;
442
421
	k->cert = NULL;
443
421
	k->ed25519_sk = NULL;
444
421
	k->ed25519_pk = NULL;
445


421
	switch (k->type) {
446
#ifdef WITH_OPENSSL
447
	case KEY_RSA:
448
	case KEY_RSA_CERT:
449

102
		if ((rsa = RSA_new()) == NULL ||
450
51
		    (rsa->n = BN_new()) == NULL ||
451
51
		    (rsa->e = BN_new()) == NULL) {
452
			if (rsa != NULL)
453
				RSA_free(rsa);
454
			free(k);
455
			return NULL;
456
		}
457
51
		k->rsa = rsa;
458
51
		break;
459
	case KEY_DSA:
460
	case KEY_DSA_CERT:
461

36
		if ((dsa = DSA_new()) == NULL ||
462
18
		    (dsa->p = BN_new()) == NULL ||
463
18
		    (dsa->q = BN_new()) == NULL ||
464
18
		    (dsa->g = BN_new()) == NULL ||
465
18
		    (dsa->pub_key = BN_new()) == NULL) {
466
			if (dsa != NULL)
467
				DSA_free(dsa);
468
			free(k);
469
			return NULL;
470
		}
471
18
		k->dsa = dsa;
472
18
		break;
473
	case KEY_ECDSA:
474
	case KEY_ECDSA_CERT:
475
		/* Cannot do anything until we know the group */
476
		break;
477
#endif /* WITH_OPENSSL */
478
	case KEY_ED25519:
479
	case KEY_ED25519_CERT:
480
		/* no need to prealloc */
481
		break;
482
	case KEY_UNSPEC:
483
		break;
484
	default:
485
		free(k);
486
		return NULL;
487
	}
488
489
352
	if (sshkey_is_cert(k)) {
490
		if ((k->cert = cert_new()) == NULL) {
491
			sshkey_free(k);
492
			return NULL;
493
		}
494
	}
495
496
352
	return k;
497
352
}
498
499
int
500
sshkey_add_private(struct sshkey *k)
501
{
502


90
	switch (k->type) {
503
#ifdef WITH_OPENSSL
504
	case KEY_RSA:
505
	case KEY_RSA_CERT:
506
#define bn_maybe_alloc_failed(p) (p == NULL && (p = BN_new()) == NULL)
507

36
		if (bn_maybe_alloc_failed(k->rsa->d) ||
508

24
		    bn_maybe_alloc_failed(k->rsa->iqmp) ||
509

24
		    bn_maybe_alloc_failed(k->rsa->q) ||
510

24
		    bn_maybe_alloc_failed(k->rsa->p) ||
511

24
		    bn_maybe_alloc_failed(k->rsa->dmq1) ||
512
24
		    bn_maybe_alloc_failed(k->rsa->dmp1))
513
			return SSH_ERR_ALLOC_FAIL;
514
		break;
515
	case KEY_DSA:
516
	case KEY_DSA_CERT:
517

8
		if (bn_maybe_alloc_failed(k->dsa->priv_key))
518
			return SSH_ERR_ALLOC_FAIL;
519
		break;
520
#undef bn_maybe_alloc_failed
521
	case KEY_ECDSA:
522
	case KEY_ECDSA_CERT:
523
		/* Cannot do anything until we know the group */
524
		break;
525
#endif /* WITH_OPENSSL */
526
	case KEY_ED25519:
527
	case KEY_ED25519_CERT:
528
		/* no need to prealloc */
529
		break;
530
	case KEY_UNSPEC:
531
		break;
532
	default:
533
		return SSH_ERR_INVALID_ARGUMENT;
534
	}
535
37
	return 0;
536
37
}
537
538
struct sshkey *
539
sshkey_new_private(int type)
540
{
541
74
	struct sshkey *k = sshkey_new(type);
542
543
37
	if (k == NULL)
544
		return NULL;
545
37
	if (sshkey_add_private(k) != 0) {
546
		sshkey_free(k);
547
		return NULL;
548
	}
549
37
	return k;
550
37
}
551
552
void
553
sshkey_free(struct sshkey *k)
554
{
555
1052
	if (k == NULL)
556
		return;
557


472
	switch (k->type) {
558
#ifdef WITH_OPENSSL
559
	case KEY_RSA:
560
	case KEY_RSA_CERT:
561
83
		if (k->rsa != NULL)
562
52
			RSA_free(k->rsa);
563
83
		k->rsa = NULL;
564
83
		break;
565
	case KEY_DSA:
566
	case KEY_DSA_CERT:
567
32
		if (k->dsa != NULL)
568
24
			DSA_free(k->dsa);
569
32
		k->dsa = NULL;
570
32
		break;
571
	case KEY_ECDSA:
572
	case KEY_ECDSA_CERT:
573
21
		if (k->ecdsa != NULL)
574
13
			EC_KEY_free(k->ecdsa);
575
21
		k->ecdsa = NULL;
576
21
		break;
577
#endif /* WITH_OPENSSL */
578
	case KEY_ED25519:
579
	case KEY_ED25519_CERT:
580
41
		if (k->ed25519_pk) {
581
22
			explicit_bzero(k->ed25519_pk, ED25519_PK_SZ);
582
22
			free(k->ed25519_pk);
583
22
			k->ed25519_pk = NULL;
584
22
		}
585
41
		if (k->ed25519_sk) {
586
5
			explicit_bzero(k->ed25519_sk, ED25519_SK_SZ);
587
5
			free(k->ed25519_sk);
588
5
			k->ed25519_sk = NULL;
589
5
		}
590
		break;
591
	case KEY_UNSPEC:
592
		break;
593
	default:
594
		break;
595
	}
596
295
	if (sshkey_is_cert(k))
597
		cert_free(k->cert);
598
295
	explicit_bzero(k, sizeof(*k));
599
295
	free(k);
600
821
}
601
602
static int
603
cert_compare(struct sshkey_cert *a, struct sshkey_cert *b)
604
{
605
	if (a == NULL && b == NULL)
606
		return 1;
607
	if (a == NULL || b == NULL)
608
		return 0;
609
	if (sshbuf_len(a->certblob) != sshbuf_len(b->certblob))
610
		return 0;
611
	if (timingsafe_bcmp(sshbuf_ptr(a->certblob), sshbuf_ptr(b->certblob),
612
	    sshbuf_len(a->certblob)) != 0)
613
		return 0;
614
	return 1;
615
}
616
617
/*
618
 * Compare public portions of key only, allowing comparisons between
619
 * certificates and plain keys too.
620
 */
621
int
622
sshkey_equal_public(const struct sshkey *a, const struct sshkey *b)
623
{
624
#ifdef WITH_OPENSSL
625
	BN_CTX *bnctx;
626
#endif /* WITH_OPENSSL */
627
628
	if (a == NULL || b == NULL ||
629
	    sshkey_type_plain(a->type) != sshkey_type_plain(b->type))
630
		return 0;
631
632
	switch (a->type) {
633
#ifdef WITH_OPENSSL
634
	case KEY_RSA_CERT:
635
	case KEY_RSA:
636
		return a->rsa != NULL && b->rsa != NULL &&
637
		    BN_cmp(a->rsa->e, b->rsa->e) == 0 &&
638
		    BN_cmp(a->rsa->n, b->rsa->n) == 0;
639
	case KEY_DSA_CERT:
640
	case KEY_DSA:
641
		return a->dsa != NULL && b->dsa != NULL &&
642
		    BN_cmp(a->dsa->p, b->dsa->p) == 0 &&
643
		    BN_cmp(a->dsa->q, b->dsa->q) == 0 &&
644
		    BN_cmp(a->dsa->g, b->dsa->g) == 0 &&
645
		    BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0;
646
	case KEY_ECDSA_CERT:
647
	case KEY_ECDSA:
648
		if (a->ecdsa == NULL || b->ecdsa == NULL ||
649
		    EC_KEY_get0_public_key(a->ecdsa) == NULL ||
650
		    EC_KEY_get0_public_key(b->ecdsa) == NULL)
651
			return 0;
652
		if ((bnctx = BN_CTX_new()) == NULL)
653
			return 0;
654
		if (EC_GROUP_cmp(EC_KEY_get0_group(a->ecdsa),
655
		    EC_KEY_get0_group(b->ecdsa), bnctx) != 0 ||
656
		    EC_POINT_cmp(EC_KEY_get0_group(a->ecdsa),
657
		    EC_KEY_get0_public_key(a->ecdsa),
658
		    EC_KEY_get0_public_key(b->ecdsa), bnctx) != 0) {
659
			BN_CTX_free(bnctx);
660
			return 0;
661
		}
662
		BN_CTX_free(bnctx);
663
		return 1;
664
#endif /* WITH_OPENSSL */
665
	case KEY_ED25519:
666
	case KEY_ED25519_CERT:
667
		return a->ed25519_pk != NULL && b->ed25519_pk != NULL &&
668
		    memcmp(a->ed25519_pk, b->ed25519_pk, ED25519_PK_SZ) == 0;
669
	default:
670
		return 0;
671
	}
672
	/* NOTREACHED */
673
}
674
675
int
676
sshkey_equal(const struct sshkey *a, const struct sshkey *b)
677
{
678

2
	if (a == NULL || b == NULL || a->type != b->type)
679
1
		return 0;
680
	if (sshkey_is_cert(a)) {
681
		if (!cert_compare(a->cert, b->cert))
682
			return 0;
683
	}
684
	return sshkey_equal_public(a, b);
685
1
}
686
687
static int
688
to_blob_buf(const struct sshkey *key, struct sshbuf *b, int force_plain)
689
{
690
	int type, ret = SSH_ERR_INTERNAL_ERROR;
691
	const char *typename;
692
693
360
	if (key == NULL)
694
		return SSH_ERR_INVALID_ARGUMENT;
695
696
180
	if (sshkey_is_cert(key)) {
697
		if (key->cert == NULL)
698
			return SSH_ERR_EXPECTED_CERT;
699
		if (sshbuf_len(key->cert->certblob) == 0)
700
			return SSH_ERR_KEY_LACKS_CERTBLOB;
701
	}
702
501
	type = force_plain ? sshkey_type_plain(key->type) : key->type;
703
180
	typename = sshkey_ssh_name_from_type_nid(type, key->ecdsa_nid);
704
705


180
	switch (type) {
706
#ifdef WITH_OPENSSL
707
	case KEY_DSA_CERT:
708
	case KEY_ECDSA_CERT:
709
	case KEY_RSA_CERT:
710
#endif /* WITH_OPENSSL */
711
	case KEY_ED25519_CERT:
712
		/* Use the existing blob */
713
		/* XXX modified flag? */
714
		if ((ret = sshbuf_putb(b, key->cert->certblob)) != 0)
715
			return ret;
716
		break;
717
#ifdef WITH_OPENSSL
718
	case KEY_DSA:
719
26
		if (key->dsa == NULL)
720
			return SSH_ERR_INVALID_ARGUMENT;
721

52
		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
722
26
		    (ret = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
723
26
		    (ret = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
724
26
		    (ret = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
725
26
		    (ret = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0)
726
			return ret;
727
		break;
728
	case KEY_ECDSA:
729
22
		if (key->ecdsa == NULL)
730
			return SSH_ERR_INVALID_ARGUMENT;
731

44
		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
732
22
		    (ret = sshbuf_put_cstring(b,
733
44
		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
734
22
		    (ret = sshbuf_put_eckey(b, key->ecdsa)) != 0)
735
			return ret;
736
		break;
737
	case KEY_RSA:
738
77
		if (key->rsa == NULL)
739
			return SSH_ERR_INVALID_ARGUMENT;
740

154
		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
741
77
		    (ret = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
742
77
		    (ret = sshbuf_put_bignum2(b, key->rsa->n)) != 0)
743
			return ret;
744
		break;
745
#endif /* WITH_OPENSSL */
746
	case KEY_ED25519:
747
55
		if (key->ed25519_pk == NULL)
748
			return SSH_ERR_INVALID_ARGUMENT;
749

110
		if ((ret = sshbuf_put_cstring(b, typename)) != 0 ||
750
55
		    (ret = sshbuf_put_string(b,
751
110
		    key->ed25519_pk, ED25519_PK_SZ)) != 0)
752
			return ret;
753
		break;
754
	default:
755
		return SSH_ERR_KEY_TYPE_UNKNOWN;
756
	}
757
180
	return 0;
758
180
}
759
760
int
761
sshkey_putb(const struct sshkey *key, struct sshbuf *b)
762
{
763
60
	return to_blob_buf(key, b, 0);
764
}
765
766
int
767
sshkey_puts(const struct sshkey *key, struct sshbuf *b)
768
{
769
	struct sshbuf *tmp;
770
	int r;
771
772
	if ((tmp = sshbuf_new()) == NULL)
773
		return SSH_ERR_ALLOC_FAIL;
774
	r = to_blob_buf(key, tmp, 0);
775
	if (r == 0)
776
		r = sshbuf_put_stringb(b, tmp);
777
	sshbuf_free(tmp);
778
	return r;
779
}
780
781
int
782
sshkey_putb_plain(const struct sshkey *key, struct sshbuf *b)
783
{
784
	return to_blob_buf(key, b, 1);
785
}
786
787
static int
788
to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp, int force_plain)
789
{
790
	int ret = SSH_ERR_INTERNAL_ERROR;
791
	size_t len;
792
	struct sshbuf *b = NULL;
793
794
300
	if (lenp != NULL)
795
150
		*lenp = 0;
796
150
	if (blobp != NULL)
797
150
		*blobp = NULL;
798
150
	if ((b = sshbuf_new()) == NULL)
799
		return SSH_ERR_ALLOC_FAIL;
800
150
	if ((ret = to_blob_buf(key, b, force_plain)) != 0)
801
		goto out;
802
150
	len = sshbuf_len(b);
803
150
	if (lenp != NULL)
804
150
		*lenp = len;
805
150
	if (blobp != NULL) {
806
150
		if ((*blobp = malloc(len)) == NULL) {
807
			ret = SSH_ERR_ALLOC_FAIL;
808
			goto out;
809
		}
810
150
		memcpy(*blobp, sshbuf_ptr(b), len);
811
150
	}
812
150
	ret = 0;
813
 out:
814
150
	sshbuf_free(b);
815
150
	return ret;
816
150
}
817
818
int
819
sshkey_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
820
{
821
18
	return to_blob(key, blobp, lenp, 0);
822
}
823
824
int
825
sshkey_plain_to_blob(const struct sshkey *key, u_char **blobp, size_t *lenp)
826
{
827
	return to_blob(key, blobp, lenp, 1);
828
}
829
830
int
831
sshkey_fingerprint_raw(const struct sshkey *k, int dgst_alg,
832
    u_char **retp, size_t *lenp)
833
{
834
282
	u_char *blob = NULL, *ret = NULL;
835
141
	size_t blob_len = 0;
836
	int r = SSH_ERR_INTERNAL_ERROR;
837
838
141
	if (retp != NULL)
839
141
		*retp = NULL;
840
141
	if (lenp != NULL)
841
141
		*lenp = 0;
842
141
	if (ssh_digest_bytes(dgst_alg) == 0) {
843
		r = SSH_ERR_INVALID_ARGUMENT;
844
		goto out;
845
	}
846
141
	if ((r = to_blob(k, &blob, &blob_len, 1)) != 0)
847
		goto out;
848
141
	if ((ret = calloc(1, SSH_DIGEST_MAX_LENGTH)) == NULL) {
849
		r = SSH_ERR_ALLOC_FAIL;
850
		goto out;
851
	}
852
282
	if ((r = ssh_digest_memory(dgst_alg, blob, blob_len,
853
141
	    ret, SSH_DIGEST_MAX_LENGTH)) != 0)
854
		goto out;
855
	/* success */
856
141
	if (retp != NULL) {
857
141
		*retp = ret;
858
		ret = NULL;
859
141
	}
860
141
	if (lenp != NULL)
861
141
		*lenp = ssh_digest_bytes(dgst_alg);
862
141
	r = 0;
863
 out:
864
141
	free(ret);
865
141
	if (blob != NULL) {
866
141
		explicit_bzero(blob, blob_len);
867
141
		free(blob);
868
141
	}
869
141
	return r;
870
141
}
871
872
static char *
873
fingerprint_b64(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
874
{
875
	char *ret;
876
136
	size_t plen = strlen(alg) + 1;
877
68
	size_t rlen = ((dgst_raw_len + 2) / 3) * 4 + plen + 1;
878
	int r;
879
880

136
	if (dgst_raw_len > 65536 || (ret = calloc(1, rlen)) == NULL)
881
		return NULL;
882
68
	strlcpy(ret, alg, rlen);
883
68
	strlcat(ret, ":", rlen);
884
68
	if (dgst_raw_len == 0)
885
		return ret;
886
136
	if ((r = b64_ntop(dgst_raw, dgst_raw_len,
887
136
	    ret + plen, rlen - plen)) == -1) {
888
		explicit_bzero(ret, rlen);
889
		free(ret);
890
		return NULL;
891
	}
892
	/* Trim padding characters from end */
893
68
	ret[strcspn(ret, "=")] = '\0';
894
68
	return ret;
895
68
}
896
897
static char *
898
fingerprint_hex(const char *alg, u_char *dgst_raw, size_t dgst_raw_len)
899
{
900
8
	char *retval, hex[5];
901
4
	size_t i, rlen = dgst_raw_len * 3 + strlen(alg) + 2;
902
903

8
	if (dgst_raw_len > 65536 || (retval = calloc(1, rlen)) == NULL)
904
		return NULL;
905
4
	strlcpy(retval, alg, rlen);
906
4
	strlcat(retval, ":", rlen);
907
136
	for (i = 0; i < dgst_raw_len; i++) {
908
128
		snprintf(hex, sizeof(hex), "%s%02x",
909
64
		    i > 0 ? ":" : "", dgst_raw[i]);
910
64
		strlcat(retval, hex, rlen);
911
	}
912
4
	return retval;
913
4
}
914
915
static char *
916
fingerprint_bubblebabble(u_char *dgst_raw, size_t dgst_raw_len)
917
{
918
40
	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
919
20
	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
920
	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
921
	u_int i, j = 0, rounds, seed = 1;
922
	char *retval;
923
924
20
	rounds = (dgst_raw_len / 2) + 1;
925
20
	if ((retval = calloc(rounds, 6)) == NULL)
926
		return NULL;
927
20
	retval[j++] = 'x';
928
480
	for (i = 0; i < rounds; i++) {
929
		u_int idx0, idx1, idx2, idx3, idx4;
930

240
		if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) {
931
200
			idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) +
932
200
			    seed) % 6;
933
200
			idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15;
934
400
			idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) +
935
400
			    (seed / 6)) % 6;
936
200
			retval[j++] = vowels[idx0];
937
200
			retval[j++] = consonants[idx1];
938
200
			retval[j++] = vowels[idx2];
939
200
			if ((i + 1) < rounds) {
940
200
				idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15;
941
200
				idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15;
942
200
				retval[j++] = consonants[idx3];
943
200
				retval[j++] = '-';
944
200
				retval[j++] = consonants[idx4];
945
400
				seed = ((seed * 5) +
946
400
				    ((((u_int)(dgst_raw[2 * i])) * 7) +
947
400
				    ((u_int)(dgst_raw[(2 * i) + 1])))) % 36;
948
200
			}
949
		} else {
950
20
			idx0 = seed % 6;
951
			idx1 = 16;
952
20
			idx2 = seed / 6;
953
20
			retval[j++] = vowels[idx0];
954
20
			retval[j++] = consonants[idx1];
955
20
			retval[j++] = vowels[idx2];
956
		}
957
	}
958
20
	retval[j++] = 'x';
959
20
	retval[j++] = '\0';
960
20
	return retval;
961
20
}
962
963
/*
964
 * Draw an ASCII-Art representing the fingerprint so human brain can
965
 * profit from its built-in pattern recognition ability.
966
 * This technique is called "random art" and can be found in some
967
 * scientific publications like this original paper:
968
 *
969
 * "Hash Visualization: a New Technique to improve Real-World Security",
970
 * Perrig A. and Song D., 1999, International Workshop on Cryptographic
971
 * Techniques and E-Commerce (CrypTEC '99)
972
 * sparrow.ece.cmu.edu/~adrian/projects/validation/validation.pdf
973
 *
974
 * The subject came up in a talk by Dan Kaminsky, too.
975
 *
976
 * If you see the picture is different, the key is different.
977
 * If the picture looks the same, you still know nothing.
978
 *
979
 * The algorithm used here is a worm crawling over a discrete plane,
980
 * leaving a trace (augmenting the field) everywhere it goes.
981
 * Movement is taken from dgst_raw 2bit-wise.  Bumping into walls
982
 * makes the respective movement vector be ignored for this turn.
983
 * Graphs are not unambiguous, because circles in graphs can be
984
 * walked in either direction.
985
 */
986
987
/*
988
 * Field sizes for the random art.  Have to be odd, so the starting point
989
 * can be in the exact middle of the picture, and FLDBASE should be >=8 .
990
 * Else pictures would be too dense, and drawing the frame would
991
 * fail, too, because the key type would not fit in anymore.
992
 */
993
#define	FLDBASE		8
994
#define	FLDSIZE_Y	(FLDBASE + 1)
995
#define	FLDSIZE_X	(FLDBASE * 2 + 1)
996
static char *
997
fingerprint_randomart(const char *alg, u_char *dgst_raw, size_t dgst_raw_len,
998
    const struct sshkey *k)
999
{
1000
	/*
1001
	 * Chars to be used after each other every time the worm
1002
	 * intersects with itself.  Matter of taste.
1003
	 */
1004
	char	*augmentation_string = " .o+=*BOX@%&#/^SE";
1005
98
	char	*retval, *p, title[FLDSIZE_X], hash[FLDSIZE_X];
1006
49
	u_char	 field[FLDSIZE_X][FLDSIZE_Y];
1007
	size_t	 i, tlen, hlen;
1008
	u_int	 b;
1009
	int	 x, y, r;
1010
49
	size_t	 len = strlen(augmentation_string) - 1;
1011
1012
49
	if ((retval = calloc((FLDSIZE_X + 3), (FLDSIZE_Y + 2))) == NULL)
1013
		return NULL;
1014
1015
	/* initialize field */
1016
49
	memset(field, 0, FLDSIZE_X * FLDSIZE_Y * sizeof(char));
1017
	x = FLDSIZE_X / 2;
1018
	y = FLDSIZE_Y / 2;
1019
1020
	/* process raw key */
1021
3106
	for (i = 0; i < dgst_raw_len; i++) {
1022
		int input;
1023
		/* each byte conveys four 2-bit move commands */
1024
1504
		input = dgst_raw[i];
1025
15040
		for (b = 0; b < 4; b++) {
1026
			/* evaluate 2 bit, rest is shifted later */
1027
6016
			x += (input & 0x1) ? 1 : -1;
1028
6016
			y += (input & 0x2) ? 1 : -1;
1029
1030
			/* assure we are still in bounds */
1031
6016
			x = MAXIMUM(x, 0);
1032
6016
			y = MAXIMUM(y, 0);
1033
6016
			x = MINIMUM(x, FLDSIZE_X - 1);
1034
6016
			y = MINIMUM(y, FLDSIZE_Y - 1);
1035
1036
			/* augment the field */
1037
6016
			if (field[x][y] < len - 2)
1038
6016
				field[x][y]++;
1039
6016
			input = input >> 2;
1040
		}
1041
	}
1042
1043
	/* mark starting point and end point*/
1044
49
	field[FLDSIZE_X / 2][FLDSIZE_Y / 2] = len - 1;
1045
49
	field[x][y] = len;
1046
1047
	/* assemble title */
1048
98
	r = snprintf(title, sizeof(title), "[%s %u]",
1049
49
		sshkey_type(k), sshkey_size(k));
1050
	/* If [type size] won't fit, then try [type]; fits "[ED25519-CERT]" */
1051
49
	if (r < 0 || r > (int)sizeof(title))
1052
		r = snprintf(title, sizeof(title), "[%s]", sshkey_type(k));
1053
147
	tlen = (r <= 0) ? 0 : strlen(title);
1054
1055
	/* assemble hash ID. */
1056
49
	r = snprintf(hash, sizeof(hash), "[%s]", alg);
1057
147
	hlen = (r <= 0) ? 0 : strlen(hash);
1058
1059
	/* output upper border */
1060
	p = retval;
1061
49
	*p++ = '+';
1062
368
	for (i = 0; i < (FLDSIZE_X - tlen) / 2; i++)
1063
135
		*p++ = '-';
1064
49
	memcpy(p, title, tlen);
1065
49
	p += tlen;
1066
424
	for (i += tlen; i < FLDSIZE_X; i++)
1067
163
		*p++ = '-';
1068
49
	*p++ = '+';
1069
49
	*p++ = '\n';
1070
1071
	/* output content */
1072
980
	for (y = 0; y < FLDSIZE_Y; y++) {
1073
441
		*p++ = '|';
1074
15876
		for (x = 0; x < FLDSIZE_X; x++)
1075
22491
			*p++ = augmentation_string[MINIMUM(field[x][y], len)];
1076
441
		*p++ = '|';
1077
441
		*p++ = '\n';
1078
	}
1079
1080
	/* output lower border */
1081
49
	*p++ = '+';
1082
506
	for (i = 0; i < (FLDSIZE_X - hlen) / 2; i++)
1083
204
		*p++ = '-';
1084
49
	memcpy(p, hash, hlen);
1085
49
	p += hlen;
1086
596
	for (i += hlen; i < FLDSIZE_X; i++)
1087
249
		*p++ = '-';
1088
49
	*p++ = '+';
1089
1090
49
	return retval;
1091
49
}
1092
1093
char *
1094
sshkey_fingerprint(const struct sshkey *k, int dgst_alg,
1095
    enum sshkey_fp_rep dgst_rep)
1096
{
1097
	char *retval = NULL;
1098
282
	u_char *dgst_raw;
1099
141
	size_t dgst_raw_len;
1100
1101
141
	if (sshkey_fingerprint_raw(k, dgst_alg, &dgst_raw, &dgst_raw_len) != 0)
1102
		return NULL;
1103

141
	switch (dgst_rep) {
1104
	case SSH_FP_DEFAULT:
1105
144
		if (dgst_alg == SSH_DIGEST_MD5) {
1106
76
			retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1107
			    dgst_raw, dgst_raw_len);
1108
4
		} else {
1109
68
			retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1110
			    dgst_raw, dgst_raw_len);
1111
		}
1112
		break;
1113
	case SSH_FP_HEX:
1114
		retval = fingerprint_hex(ssh_digest_alg_name(dgst_alg),
1115
		    dgst_raw, dgst_raw_len);
1116
		break;
1117
	case SSH_FP_BASE64:
1118
		retval = fingerprint_b64(ssh_digest_alg_name(dgst_alg),
1119
		    dgst_raw, dgst_raw_len);
1120
		break;
1121
	case SSH_FP_BUBBLEBABBLE:
1122
20
		retval = fingerprint_bubblebabble(dgst_raw, dgst_raw_len);
1123
20
		break;
1124
	case SSH_FP_RANDOMART:
1125
98
		retval = fingerprint_randomart(ssh_digest_alg_name(dgst_alg),
1126
49
		    dgst_raw, dgst_raw_len, k);
1127
49
		break;
1128
	default:
1129
		explicit_bzero(dgst_raw, dgst_raw_len);
1130
		free(dgst_raw);
1131
		return NULL;
1132
	}
1133
141
	explicit_bzero(dgst_raw, dgst_raw_len);
1134
141
	free(dgst_raw);
1135
141
	return retval;
1136
141
}
1137
1138
1139
/* returns 0 ok, and < 0 error */
1140
int
1141
sshkey_read(struct sshkey *ret, char **cpp)
1142
{
1143
132
	struct sshkey *k;
1144
	int retval = SSH_ERR_INVALID_FORMAT;
1145
	char *ep, *cp, *space;
1146
	int r, type, curve_nid = -1;
1147
	struct sshbuf *blob;
1148
1149
66
	if (ret == NULL)
1150
		return SSH_ERR_INVALID_ARGUMENT;
1151
1152
66
	cp = *cpp;
1153
1154
66
	switch (ret->type) {
1155
	case KEY_UNSPEC:
1156
	case KEY_RSA:
1157
	case KEY_DSA:
1158
	case KEY_ECDSA:
1159
	case KEY_ED25519:
1160
	case KEY_DSA_CERT:
1161
	case KEY_ECDSA_CERT:
1162
	case KEY_RSA_CERT:
1163
	case KEY_ED25519_CERT:
1164
66
		space = strchr(cp, ' ');
1165
66
		if (space == NULL)
1166
			return SSH_ERR_INVALID_FORMAT;
1167
66
		*space = '\0';
1168
66
		type = sshkey_type_from_name(cp);
1169

74
		if (sshkey_type_plain(type) == KEY_ECDSA &&
1170
8
		    (curve_nid = sshkey_ecdsa_nid_from_name(cp)) == -1)
1171
			return SSH_ERR_EC_CURVE_INVALID;
1172
66
		*space = ' ';
1173
66
		if (type == KEY_UNSPEC)
1174
			return SSH_ERR_INVALID_FORMAT;
1175
66
		cp = space+1;
1176
66
		if (*cp == '\0')
1177
			return SSH_ERR_INVALID_FORMAT;
1178

66
		if (ret->type != KEY_UNSPEC && ret->type != type)
1179
			return SSH_ERR_KEY_TYPE_MISMATCH;
1180
66
		if ((blob = sshbuf_new()) == NULL)
1181
			return SSH_ERR_ALLOC_FAIL;
1182
		/* trim comment */
1183
66
		space = strchr(cp, ' ');
1184
66
		if (space) {
1185
			/* advance 'space': skip whitespace */
1186
50
			*space++ = '\0';
1187

200
			while (*space == ' ' || *space == '\t')
1188
				space++;
1189
			ep = space;
1190
50
		} else
1191
16
			ep = cp + strlen(cp);
1192
66
		if ((r = sshbuf_b64tod(blob, cp)) != 0) {
1193
			sshbuf_free(blob);
1194
			return r;
1195
		}
1196
198
		if ((r = sshkey_from_blob(sshbuf_ptr(blob),
1197
132
		    sshbuf_len(blob), &k)) != 0) {
1198
66
			sshbuf_free(blob);
1199
			return r;
1200
		}
1201
		sshbuf_free(blob);
1202
66
		if (k->type != type) {
1203
			sshkey_free(k);
1204
			return SSH_ERR_KEY_TYPE_MISMATCH;
1205
		}
1206

74
		if (sshkey_type_plain(type) == KEY_ECDSA &&
1207
8
		    curve_nid != k->ecdsa_nid) {
1208
			sshkey_free(k);
1209
			return SSH_ERR_EC_CURVE_MISMATCH;
1210
		}
1211
66
		ret->type = type;
1212
66
		if (sshkey_is_cert(ret)) {
1213
			if (!sshkey_is_cert(k)) {
1214
				sshkey_free(k);
1215
				return SSH_ERR_EXPECTED_CERT;
1216
			}
1217
			if (ret->cert != NULL)
1218
				cert_free(ret->cert);
1219
			ret->cert = k->cert;
1220
			k->cert = NULL;
1221
		}
1222

132
		switch (sshkey_type_plain(ret->type)) {
1223
#ifdef WITH_OPENSSL
1224
		case KEY_RSA:
1225
31
			if (ret->rsa != NULL)
1226
				RSA_free(ret->rsa);
1227
31
			ret->rsa = k->rsa;
1228
31
			k->rsa = NULL;
1229
#ifdef DEBUG_PK
1230
			RSA_print_fp(stderr, ret->rsa, 8);
1231
#endif
1232
31
			break;
1233
		case KEY_DSA:
1234
8
			if (ret->dsa != NULL)
1235
				DSA_free(ret->dsa);
1236
8
			ret->dsa = k->dsa;
1237
8
			k->dsa = NULL;
1238
#ifdef DEBUG_PK
1239
			DSA_print_fp(stderr, ret->dsa, 8);
1240
#endif
1241
8
			break;
1242
		case KEY_ECDSA:
1243
8
			if (ret->ecdsa != NULL)
1244
				EC_KEY_free(ret->ecdsa);
1245
8
			ret->ecdsa = k->ecdsa;
1246
8
			ret->ecdsa_nid = k->ecdsa_nid;
1247
8
			k->ecdsa = NULL;
1248
8
			k->ecdsa_nid = -1;
1249
#ifdef DEBUG_PK
1250
			sshkey_dump_ec_key(ret->ecdsa);
1251
#endif
1252
8
			break;
1253
#endif /* WITH_OPENSSL */
1254
		case KEY_ED25519:
1255
19
			free(ret->ed25519_pk);
1256
19
			ret->ed25519_pk = k->ed25519_pk;
1257
19
			k->ed25519_pk = NULL;
1258
#ifdef DEBUG_PK
1259
			/* XXX */
1260
#endif
1261
19
			break;
1262
		}
1263
66
		*cpp = ep;
1264
		retval = 0;
1265
/*XXXX*/
1266
66
		sshkey_free(k);
1267
		if (retval != 0)
1268
			break;
1269
		break;
1270
	default:
1271
		return SSH_ERR_INVALID_ARGUMENT;
1272
	}
1273
66
	return retval;
1274
66
}
1275
1276
int
1277
sshkey_to_base64(const struct sshkey *key, char **b64p)
1278
{
1279
	int r = SSH_ERR_INTERNAL_ERROR;
1280
	struct sshbuf *b = NULL;
1281
	char *uu = NULL;
1282
1283
60
	if (b64p != NULL)
1284
30
		*b64p = NULL;
1285
30
	if ((b = sshbuf_new()) == NULL)
1286
		return SSH_ERR_ALLOC_FAIL;
1287
30
	if ((r = sshkey_putb(key, b)) != 0)
1288
		goto out;
1289
30
	if ((uu = sshbuf_dtob64(b)) == NULL) {
1290
		r = SSH_ERR_ALLOC_FAIL;
1291
		goto out;
1292
	}
1293
	/* Success */
1294
30
	if (b64p != NULL) {
1295
30
		*b64p = uu;
1296
		uu = NULL;
1297
30
	}
1298
30
	r = 0;
1299
 out:
1300
30
	sshbuf_free(b);
1301
30
	free(uu);
1302
30
	return r;
1303
30
}
1304
1305
int
1306
sshkey_format_text(const struct sshkey *key, struct sshbuf *b)
1307
{
1308
	int r = SSH_ERR_INTERNAL_ERROR;
1309
60
	char *uu = NULL;
1310
1311
30
	if ((r = sshkey_to_base64(key, &uu)) != 0)
1312
		goto out;
1313
60
	if ((r = sshbuf_putf(b, "%s %s",
1314
60
	    sshkey_ssh_name(key), uu)) != 0)
1315
		goto out;
1316
	r = 0;
1317
 out:
1318
30
	free(uu);
1319
30
	return r;
1320
30
}
1321
1322
int
1323
sshkey_write(const struct sshkey *key, FILE *f)
1324
{
1325
	struct sshbuf *b = NULL;
1326
	int r = SSH_ERR_INTERNAL_ERROR;
1327
1328
60
	if ((b = sshbuf_new()) == NULL)
1329
		return SSH_ERR_ALLOC_FAIL;
1330
30
	if ((r = sshkey_format_text(key, b)) != 0)
1331
		goto out;
1332
30
	if (fwrite(sshbuf_ptr(b), sshbuf_len(b), 1, f) != 1) {
1333
		if (feof(f))
1334
			errno = EPIPE;
1335
		r = SSH_ERR_SYSTEM_ERROR;
1336
		goto out;
1337
	}
1338
	/* Success */
1339
30
	r = 0;
1340
 out:
1341
30
	sshbuf_free(b);
1342
30
	return r;
1343
30
}
1344
1345
const char *
1346
sshkey_cert_type(const struct sshkey *k)
1347
{
1348
	switch (k->cert->type) {
1349
	case SSH2_CERT_TYPE_USER:
1350
		return "user";
1351
	case SSH2_CERT_TYPE_HOST:
1352
		return "host";
1353
	default:
1354
		return "unknown";
1355
	}
1356
}
1357
1358
#ifdef WITH_OPENSSL
1359
static int
1360
rsa_generate_private_key(u_int bits, RSA **rsap)
1361
{
1362
	RSA *private = NULL;
1363
	BIGNUM *f4 = NULL;
1364
	int ret = SSH_ERR_INTERNAL_ERROR;
1365
1366
8
	if (rsap == NULL)
1367
		return SSH_ERR_INVALID_ARGUMENT;
1368
8
	if (bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1369
4
	    bits > SSHBUF_MAX_BIGNUM * 8)
1370
		return SSH_ERR_KEY_LENGTH;
1371
4
	*rsap = NULL;
1372

8
	if ((private = RSA_new()) == NULL || (f4 = BN_new()) == NULL) {
1373
		ret = SSH_ERR_ALLOC_FAIL;
1374
		goto out;
1375
	}
1376

8
	if (!BN_set_word(f4, RSA_F4) ||
1377
4
	    !RSA_generate_key_ex(private, bits, f4, NULL)) {
1378
		ret = SSH_ERR_LIBCRYPTO_ERROR;
1379
		goto out;
1380
	}
1381
4
	*rsap = private;
1382
	private = NULL;
1383
4
	ret = 0;
1384
 out:
1385
4
	if (private != NULL)
1386
		RSA_free(private);
1387
4
	if (f4 != NULL)
1388
4
		BN_free(f4);
1389
4
	return ret;
1390
4
}
1391
1392
static int
1393
dsa_generate_private_key(u_int bits, DSA **dsap)
1394
{
1395
	DSA *private;
1396
	int ret = SSH_ERR_INTERNAL_ERROR;
1397
1398
4
	if (dsap == NULL)
1399
		return SSH_ERR_INVALID_ARGUMENT;
1400
2
	if (bits != 1024)
1401
		return SSH_ERR_KEY_LENGTH;
1402
2
	if ((private = DSA_new()) == NULL) {
1403
		ret = SSH_ERR_ALLOC_FAIL;
1404
		goto out;
1405
	}
1406
2
	*dsap = NULL;
1407
4
	if (!DSA_generate_parameters_ex(private, bits, NULL, 0, NULL,
1408
4
	    NULL, NULL) || !DSA_generate_key(private)) {
1409
		ret = SSH_ERR_LIBCRYPTO_ERROR;
1410
		goto out;
1411
	}
1412
2
	*dsap = private;
1413
	private = NULL;
1414
2
	ret = 0;
1415
 out:
1416
2
	if (private != NULL)
1417
		DSA_free(private);
1418
2
	return ret;
1419
2
}
1420
1421
int
1422
sshkey_ecdsa_key_to_nid(EC_KEY *k)
1423
{
1424
	EC_GROUP *eg;
1425
	int nids[] = {
1426
		NID_X9_62_prime256v1,
1427
		NID_secp384r1,
1428
		NID_secp521r1,
1429
		-1
1430
	};
1431
	int nid;
1432
	u_int i;
1433
	BN_CTX *bnctx;
1434
	const EC_GROUP *g = EC_KEY_get0_group(k);
1435
1436
	/*
1437
	 * The group may be stored in a ASN.1 encoded private key in one of two
1438
	 * ways: as a "named group", which is reconstituted by ASN.1 object ID
1439
	 * or explicit group parameters encoded into the key blob. Only the
1440
	 * "named group" case sets the group NID for us, but we can figure
1441
	 * it out for the other case by comparing against all the groups that
1442
	 * are supported.
1443
	 */
1444
	if ((nid = EC_GROUP_get_curve_name(g)) > 0)
1445
		return nid;
1446
	if ((bnctx = BN_CTX_new()) == NULL)
1447
		return -1;
1448
	for (i = 0; nids[i] != -1; i++) {
1449
		if ((eg = EC_GROUP_new_by_curve_name(nids[i])) == NULL) {
1450
			BN_CTX_free(bnctx);
1451
			return -1;
1452
		}
1453
		if (EC_GROUP_cmp(g, eg, bnctx) == 0)
1454
			break;
1455
		EC_GROUP_free(eg);
1456
	}
1457
	BN_CTX_free(bnctx);
1458
	if (nids[i] != -1) {
1459
		/* Use the group with the NID attached */
1460
		EC_GROUP_set_asn1_flag(eg, OPENSSL_EC_NAMED_CURVE);
1461
		if (EC_KEY_set_group(k, eg) != 1) {
1462
			EC_GROUP_free(eg);
1463
			return -1;
1464
		}
1465
	}
1466
	return nids[i];
1467
}
1468
1469
static int
1470
ecdsa_generate_private_key(u_int bits, int *nid, EC_KEY **ecdsap)
1471
{
1472
	EC_KEY *private;
1473
	int ret = SSH_ERR_INTERNAL_ERROR;
1474
1475
4
	if (nid == NULL || ecdsap == NULL)
1476
		return SSH_ERR_INVALID_ARGUMENT;
1477
2
	if ((*nid = sshkey_ecdsa_bits_to_nid(bits)) == -1)
1478
		return SSH_ERR_KEY_LENGTH;
1479
2
	*ecdsap = NULL;
1480
2
	if ((private = EC_KEY_new_by_curve_name(*nid)) == NULL) {
1481
		ret = SSH_ERR_ALLOC_FAIL;
1482
		goto out;
1483
	}
1484
2
	if (EC_KEY_generate_key(private) != 1) {
1485
		ret = SSH_ERR_LIBCRYPTO_ERROR;
1486
		goto out;
1487
	}
1488
2
	EC_KEY_set_asn1_flag(private, OPENSSL_EC_NAMED_CURVE);
1489
2
	*ecdsap = private;
1490
	private = NULL;
1491
2
	ret = 0;
1492
 out:
1493
2
	if (private != NULL)
1494
		EC_KEY_free(private);
1495
2
	return ret;
1496
2
}
1497
#endif /* WITH_OPENSSL */
1498
1499
int
1500
sshkey_generate(int type, u_int bits, struct sshkey **keyp)
1501
{
1502
	struct sshkey *k;
1503
	int ret = SSH_ERR_INTERNAL_ERROR;
1504
1505
26
	if (keyp == NULL)
1506
		return SSH_ERR_INVALID_ARGUMENT;
1507
13
	*keyp = NULL;
1508
13
	if ((k = sshkey_new(KEY_UNSPEC)) == NULL)
1509
		return SSH_ERR_ALLOC_FAIL;
1510

13
	switch (type) {
1511
	case KEY_ED25519:
1512

10
		if ((k->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL ||
1513
5
		    (k->ed25519_sk = malloc(ED25519_SK_SZ)) == NULL) {
1514
			ret = SSH_ERR_ALLOC_FAIL;
1515
			break;
1516
		}
1517
5
		crypto_sign_ed25519_keypair(k->ed25519_pk, k->ed25519_sk);
1518
		ret = 0;
1519
5
		break;
1520
#ifdef WITH_OPENSSL
1521
	case KEY_DSA:
1522
2
		ret = dsa_generate_private_key(bits, &k->dsa);
1523
2
		break;
1524
	case KEY_ECDSA:
1525
4
		ret = ecdsa_generate_private_key(bits, &k->ecdsa_nid,
1526
2
		    &k->ecdsa);
1527
2
		break;
1528
	case KEY_RSA:
1529
4
		ret = rsa_generate_private_key(bits, &k->rsa);
1530
4
		break;
1531
#endif /* WITH_OPENSSL */
1532
	default:
1533
		ret = SSH_ERR_INVALID_ARGUMENT;
1534
	}
1535
13
	if (ret == 0) {
1536
13
		k->type = type;
1537
13
		*keyp = k;
1538
13
	} else
1539
		sshkey_free(k);
1540
13
	return ret;
1541
13
}
1542
1543
int
1544
sshkey_cert_copy(const struct sshkey *from_key, struct sshkey *to_key)
1545
{
1546
	u_int i;
1547
	const struct sshkey_cert *from;
1548
	struct sshkey_cert *to;
1549
	int ret = SSH_ERR_INTERNAL_ERROR;
1550
1551
	if (to_key->cert != NULL) {
1552
		cert_free(to_key->cert);
1553
		to_key->cert = NULL;
1554
	}
1555
1556
	if ((from = from_key->cert) == NULL)
1557
		return SSH_ERR_INVALID_ARGUMENT;
1558
1559
	if ((to = to_key->cert = cert_new()) == NULL)
1560
		return SSH_ERR_ALLOC_FAIL;
1561
1562
	if ((ret = sshbuf_putb(to->certblob, from->certblob)) != 0 ||
1563
	    (ret = sshbuf_putb(to->critical, from->critical)) != 0 ||
1564
	    (ret = sshbuf_putb(to->extensions, from->extensions)) != 0)
1565
		return ret;
1566
1567
	to->serial = from->serial;
1568
	to->type = from->type;
1569
	if (from->key_id == NULL)
1570
		to->key_id = NULL;
1571
	else if ((to->key_id = strdup(from->key_id)) == NULL)
1572
		return SSH_ERR_ALLOC_FAIL;
1573
	to->valid_after = from->valid_after;
1574
	to->valid_before = from->valid_before;
1575
	if (from->signature_key == NULL)
1576
		to->signature_key = NULL;
1577
	else if ((ret = sshkey_from_private(from->signature_key,
1578
	    &to->signature_key)) != 0)
1579
		return ret;
1580
1581
	if (from->nprincipals > SSHKEY_CERT_MAX_PRINCIPALS)
1582
		return SSH_ERR_INVALID_ARGUMENT;
1583
	if (from->nprincipals > 0) {
1584
		if ((to->principals = calloc(from->nprincipals,
1585
		    sizeof(*to->principals))) == NULL)
1586
			return SSH_ERR_ALLOC_FAIL;
1587
		for (i = 0; i < from->nprincipals; i++) {
1588
			to->principals[i] = strdup(from->principals[i]);
1589
			if (to->principals[i] == NULL) {
1590
				to->nprincipals = i;
1591
				return SSH_ERR_ALLOC_FAIL;
1592
			}
1593
		}
1594
	}
1595
	to->nprincipals = from->nprincipals;
1596
	return 0;
1597
}
1598
1599
int
1600
sshkey_from_private(const struct sshkey *k, struct sshkey **pkp)
1601
{
1602
	struct sshkey *n = NULL;
1603
	int ret = SSH_ERR_INTERNAL_ERROR;
1604
1605
28
	*pkp = NULL;
1606


14
	switch (k->type) {
1607
#ifdef WITH_OPENSSL
1608
	case KEY_DSA:
1609
	case KEY_DSA_CERT:
1610
2
		if ((n = sshkey_new(k->type)) == NULL)
1611
			return SSH_ERR_ALLOC_FAIL;
1612

4
		if ((BN_copy(n->dsa->p, k->dsa->p) == NULL) ||
1613
2
		    (BN_copy(n->dsa->q, k->dsa->q) == NULL) ||
1614
2
		    (BN_copy(n->dsa->g, k->dsa->g) == NULL) ||
1615
2
		    (BN_copy(n->dsa->pub_key, k->dsa->pub_key) == NULL)) {
1616
			sshkey_free(n);
1617
			return SSH_ERR_ALLOC_FAIL;
1618
		}
1619
		break;
1620
	case KEY_ECDSA:
1621
	case KEY_ECDSA_CERT:
1622
3
		if ((n = sshkey_new(k->type)) == NULL)
1623
			return SSH_ERR_ALLOC_FAIL;
1624
3
		n->ecdsa_nid = k->ecdsa_nid;
1625
3
		n->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
1626
3
		if (n->ecdsa == NULL) {
1627
			sshkey_free(n);
1628
			return SSH_ERR_ALLOC_FAIL;
1629
		}
1630
6
		if (EC_KEY_set_public_key(n->ecdsa,
1631
6
		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
1632
			sshkey_free(n);
1633
			return SSH_ERR_LIBCRYPTO_ERROR;
1634
		}
1635
		break;
1636
	case KEY_RSA:
1637
	case KEY_RSA_CERT:
1638
4
		if ((n = sshkey_new(k->type)) == NULL)
1639
			return SSH_ERR_ALLOC_FAIL;
1640

8
		if ((BN_copy(n->rsa->n, k->rsa->n) == NULL) ||
1641
4
		    (BN_copy(n->rsa->e, k->rsa->e) == NULL)) {
1642
			sshkey_free(n);
1643
			return SSH_ERR_ALLOC_FAIL;
1644
		}
1645
		break;
1646
#endif /* WITH_OPENSSL */
1647
	case KEY_ED25519:
1648
	case KEY_ED25519_CERT:
1649
5
		if ((n = sshkey_new(k->type)) == NULL)
1650
			return SSH_ERR_ALLOC_FAIL;
1651
5
		if (k->ed25519_pk != NULL) {
1652
5
			if ((n->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
1653
				sshkey_free(n);
1654
				return SSH_ERR_ALLOC_FAIL;
1655
			}
1656
5
			memcpy(n->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
1657
5
		}
1658
		break;
1659
	default:
1660
		return SSH_ERR_KEY_TYPE_UNKNOWN;
1661
	}
1662
14
	if (sshkey_is_cert(k)) {
1663
		if ((ret = sshkey_cert_copy(k, n)) != 0) {
1664
			sshkey_free(n);
1665
			return ret;
1666
		}
1667
	}
1668
14
	*pkp = n;
1669
14
	return 0;
1670
14
}
1671
1672
static int
1673
cert_parse(struct sshbuf *b, struct sshkey *key, struct sshbuf *certbuf)
1674
{
1675
	struct sshbuf *principals = NULL, *crit = NULL;
1676
	struct sshbuf *exts = NULL, *ca = NULL;
1677
	u_char *sig = NULL;
1678
	size_t signed_len = 0, slen = 0, kidlen = 0;
1679
	int ret = SSH_ERR_INTERNAL_ERROR;
1680
1681
	/* Copy the entire key blob for verification and later serialisation */
1682
	if ((ret = sshbuf_putb(key->cert->certblob, certbuf)) != 0)
1683
		return ret;
1684
1685
	/* Parse body of certificate up to signature */
1686
	if ((ret = sshbuf_get_u64(b, &key->cert->serial)) != 0 ||
1687
	    (ret = sshbuf_get_u32(b, &key->cert->type)) != 0 ||
1688
	    (ret = sshbuf_get_cstring(b, &key->cert->key_id, &kidlen)) != 0 ||
1689
	    (ret = sshbuf_froms(b, &principals)) != 0 ||
1690
	    (ret = sshbuf_get_u64(b, &key->cert->valid_after)) != 0 ||
1691
	    (ret = sshbuf_get_u64(b, &key->cert->valid_before)) != 0 ||
1692
	    (ret = sshbuf_froms(b, &crit)) != 0 ||
1693
	    (ret = sshbuf_froms(b, &exts)) != 0 ||
1694
	    (ret = sshbuf_get_string_direct(b, NULL, NULL)) != 0 ||
1695
	    (ret = sshbuf_froms(b, &ca)) != 0) {
1696
		/* XXX debug print error for ret */
1697
		ret = SSH_ERR_INVALID_FORMAT;
1698
		goto out;
1699
	}
1700
1701
	/* Signature is left in the buffer so we can calculate this length */
1702
	signed_len = sshbuf_len(key->cert->certblob) - sshbuf_len(b);
1703
1704
	if ((ret = sshbuf_get_string(b, &sig, &slen)) != 0) {
1705
		ret = SSH_ERR_INVALID_FORMAT;
1706
		goto out;
1707
	}
1708
1709
	if (key->cert->type != SSH2_CERT_TYPE_USER &&
1710
	    key->cert->type != SSH2_CERT_TYPE_HOST) {
1711
		ret = SSH_ERR_KEY_CERT_UNKNOWN_TYPE;
1712
		goto out;
1713
	}
1714
1715
	/* Parse principals section */
1716
	while (sshbuf_len(principals) > 0) {
1717
		char *principal = NULL;
1718
		char **oprincipals = NULL;
1719
1720
		if (key->cert->nprincipals >= SSHKEY_CERT_MAX_PRINCIPALS) {
1721
			ret = SSH_ERR_INVALID_FORMAT;
1722
			goto out;
1723
		}
1724
		if ((ret = sshbuf_get_cstring(principals, &principal,
1725
		    NULL)) != 0) {
1726
			ret = SSH_ERR_INVALID_FORMAT;
1727
			goto out;
1728
		}
1729
		oprincipals = key->cert->principals;
1730
		key->cert->principals = recallocarray(key->cert->principals,
1731
		    key->cert->nprincipals, key->cert->nprincipals + 1,
1732
		    sizeof(*key->cert->principals));
1733
		if (key->cert->principals == NULL) {
1734
			free(principal);
1735
			key->cert->principals = oprincipals;
1736
			ret = SSH_ERR_ALLOC_FAIL;
1737
			goto out;
1738
		}
1739
		key->cert->principals[key->cert->nprincipals++] = principal;
1740
	}
1741
1742
	/*
1743
	 * Stash a copies of the critical options and extensions sections
1744
	 * for later use.
1745
	 */
1746
	if ((ret = sshbuf_putb(key->cert->critical, crit)) != 0 ||
1747
	    (exts != NULL &&
1748
	    (ret = sshbuf_putb(key->cert->extensions, exts)) != 0))
1749
		goto out;
1750
1751
	/*
1752
	 * Validate critical options and extensions sections format.
1753
	 */
1754
	while (sshbuf_len(crit) != 0) {
1755
		if ((ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0 ||
1756
		    (ret = sshbuf_get_string_direct(crit, NULL, NULL)) != 0) {
1757
			sshbuf_reset(key->cert->critical);
1758
			ret = SSH_ERR_INVALID_FORMAT;
1759
			goto out;
1760
		}
1761
	}
1762
	while (exts != NULL && sshbuf_len(exts) != 0) {
1763
		if ((ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0 ||
1764
		    (ret = sshbuf_get_string_direct(exts, NULL, NULL)) != 0) {
1765
			sshbuf_reset(key->cert->extensions);
1766
			ret = SSH_ERR_INVALID_FORMAT;
1767
			goto out;
1768
		}
1769
	}
1770
1771
	/* Parse CA key and check signature */
1772
	if (sshkey_from_blob_internal(ca, &key->cert->signature_key, 0) != 0) {
1773
		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1774
		goto out;
1775
	}
1776
	if (!sshkey_type_is_valid_ca(key->cert->signature_key->type)) {
1777
		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1778
		goto out;
1779
	}
1780
	if ((ret = sshkey_verify(key->cert->signature_key, sig, slen,
1781
	    sshbuf_ptr(key->cert->certblob), signed_len, 0)) != 0)
1782
		goto out;
1783
1784
	/* Success */
1785
	ret = 0;
1786
 out:
1787
	sshbuf_free(ca);
1788
	sshbuf_free(crit);
1789
	sshbuf_free(exts);
1790
	sshbuf_free(principals);
1791
	free(sig);
1792
	return ret;
1793
}
1794
1795
static int
1796
sshkey_from_blob_internal(struct sshbuf *b, struct sshkey **keyp,
1797
    int allow_cert)
1798
{
1799
	int type, ret = SSH_ERR_INTERNAL_ERROR;
1800
150
	char *ktype = NULL, *curve = NULL;
1801
	struct sshkey *key = NULL;
1802
75
	size_t len;
1803
75
	u_char *pk = NULL;
1804
	struct sshbuf *copy;
1805
#ifdef WITH_OPENSSL
1806
	EC_POINT *q = NULL;
1807
#endif /* WITH_OPENSSL */
1808
1809
#ifdef DEBUG_PK /* XXX */
1810
	sshbuf_dump(b, stderr);
1811
#endif
1812
75
	if (keyp != NULL)
1813
75
		*keyp = NULL;
1814
75
	if ((copy = sshbuf_fromb(b)) == NULL) {
1815
		ret = SSH_ERR_ALLOC_FAIL;
1816
		goto out;
1817
	}
1818
75
	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
1819
		ret = SSH_ERR_INVALID_FORMAT;
1820
		goto out;
1821
	}
1822
1823
75
	type = sshkey_type_from_name(ktype);
1824

75
	if (!allow_cert && sshkey_type_is_cert(type)) {
1825
		ret = SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
1826
		goto out;
1827
	}
1828


75
	switch (type) {
1829
#ifdef WITH_OPENSSL
1830
	case KEY_RSA_CERT:
1831
		/* Skip nonce */
1832
		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1833
			ret = SSH_ERR_INVALID_FORMAT;
1834
			goto out;
1835
		}
1836
		/* FALLTHROUGH */
1837
	case KEY_RSA:
1838
35
		if ((key = sshkey_new(type)) == NULL) {
1839
			ret = SSH_ERR_ALLOC_FAIL;
1840
			goto out;
1841
		}
1842

70
		if (sshbuf_get_bignum2(b, key->rsa->e) != 0 ||
1843
35
		    sshbuf_get_bignum2(b, key->rsa->n) != 0) {
1844
			ret = SSH_ERR_INVALID_FORMAT;
1845
			goto out;
1846
		}
1847
35
		if (BN_num_bits(key->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
1848
			ret = SSH_ERR_KEY_LENGTH;
1849
			goto out;
1850
		}
1851
#ifdef DEBUG_PK
1852
		RSA_print_fp(stderr, key->rsa, 8);
1853
#endif
1854
		break;
1855
	case KEY_DSA_CERT:
1856
		/* Skip nonce */
1857
		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1858
			ret = SSH_ERR_INVALID_FORMAT;
1859
			goto out;
1860
		}
1861
		/* FALLTHROUGH */
1862
	case KEY_DSA:
1863
12
		if ((key = sshkey_new(type)) == NULL) {
1864
			ret = SSH_ERR_ALLOC_FAIL;
1865
			goto out;
1866
		}
1867

24
		if (sshbuf_get_bignum2(b, key->dsa->p) != 0 ||
1868
12
		    sshbuf_get_bignum2(b, key->dsa->q) != 0 ||
1869
12
		    sshbuf_get_bignum2(b, key->dsa->g) != 0 ||
1870
12
		    sshbuf_get_bignum2(b, key->dsa->pub_key) != 0) {
1871
			ret = SSH_ERR_INVALID_FORMAT;
1872
			goto out;
1873
		}
1874
#ifdef DEBUG_PK
1875
		DSA_print_fp(stderr, key->dsa, 8);
1876
#endif
1877
		break;
1878
	case KEY_ECDSA_CERT:
1879
		/* Skip nonce */
1880
		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1881
			ret = SSH_ERR_INVALID_FORMAT;
1882
			goto out;
1883
		}
1884
		/* FALLTHROUGH */
1885
	case KEY_ECDSA:
1886
9
		if ((key = sshkey_new(type)) == NULL) {
1887
			ret = SSH_ERR_ALLOC_FAIL;
1888
			goto out;
1889
		}
1890
9
		key->ecdsa_nid = sshkey_ecdsa_nid_from_name(ktype);
1891
9
		if (sshbuf_get_cstring(b, &curve, NULL) != 0) {
1892
			ret = SSH_ERR_INVALID_FORMAT;
1893
			goto out;
1894
		}
1895
9
		if (key->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
1896
			ret = SSH_ERR_EC_CURVE_MISMATCH;
1897
			goto out;
1898
		}
1899
9
		if (key->ecdsa != NULL)
1900
			EC_KEY_free(key->ecdsa);
1901
18
		if ((key->ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid))
1902
9
		    == NULL) {
1903
			ret = SSH_ERR_EC_CURVE_INVALID;
1904
			goto out;
1905
		}
1906
9
		if ((q = EC_POINT_new(EC_KEY_get0_group(key->ecdsa))) == NULL) {
1907
			ret = SSH_ERR_ALLOC_FAIL;
1908
			goto out;
1909
		}
1910
9
		if (sshbuf_get_ec(b, q, EC_KEY_get0_group(key->ecdsa)) != 0) {
1911
			ret = SSH_ERR_INVALID_FORMAT;
1912
			goto out;
1913
		}
1914
18
		if (sshkey_ec_validate_public(EC_KEY_get0_group(key->ecdsa),
1915
9
		    q) != 0) {
1916
			ret = SSH_ERR_KEY_INVALID_EC_VALUE;
1917
			goto out;
1918
		}
1919
9
		if (EC_KEY_set_public_key(key->ecdsa, q) != 1) {
1920
			/* XXX assume it is a allocation error */
1921
			ret = SSH_ERR_ALLOC_FAIL;
1922
			goto out;
1923
		}
1924
#ifdef DEBUG_PK
1925
		sshkey_dump_ec_point(EC_KEY_get0_group(key->ecdsa), q);
1926
#endif
1927
		break;
1928
#endif /* WITH_OPENSSL */
1929
	case KEY_ED25519_CERT:
1930
		/* Skip nonce */
1931
		if (sshbuf_get_string_direct(b, NULL, NULL) != 0) {
1932
			ret = SSH_ERR_INVALID_FORMAT;
1933
			goto out;
1934
		}
1935
		/* FALLTHROUGH */
1936
	case KEY_ED25519:
1937
19
		if ((ret = sshbuf_get_string(b, &pk, &len)) != 0)
1938
			goto out;
1939
19
		if (len != ED25519_PK_SZ) {
1940
			ret = SSH_ERR_INVALID_FORMAT;
1941
			goto out;
1942
		}
1943
19
		if ((key = sshkey_new(type)) == NULL) {
1944
			ret = SSH_ERR_ALLOC_FAIL;
1945
			goto out;
1946
		}
1947
19
		key->ed25519_pk = pk;
1948
19
		pk = NULL;
1949
19
		break;
1950
	case KEY_UNSPEC:
1951
	default:
1952
		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
1953
		goto out;
1954
	}
1955
1956
	/* Parse certificate potion */
1957

75
	if (sshkey_is_cert(key) && (ret = cert_parse(b, key, copy)) != 0)
1958
		goto out;
1959
1960

150
	if (key != NULL && sshbuf_len(b) != 0) {
1961
		ret = SSH_ERR_INVALID_FORMAT;
1962
		goto out;
1963
	}
1964
	ret = 0;
1965
75
	if (keyp != NULL) {
1966
75
		*keyp = key;
1967
		key = NULL;
1968
75
	}
1969
 out:
1970
75
	sshbuf_free(copy);
1971
75
	sshkey_free(key);
1972
75
	free(ktype);
1973
75
	free(curve);
1974
75
	free(pk);
1975
#ifdef WITH_OPENSSL
1976
75
	if (q != NULL)
1977
9
		EC_POINT_free(q);
1978
#endif /* WITH_OPENSSL */
1979
75
	return ret;
1980
75
}
1981
1982
int
1983
sshkey_from_blob(const u_char *blob, size_t blen, struct sshkey **keyp)
1984
{
1985
	struct sshbuf *b;
1986
	int r;
1987
1988
150
	if ((b = sshbuf_from(blob, blen)) == NULL)
1989
		return SSH_ERR_ALLOC_FAIL;
1990
75
	r = sshkey_from_blob_internal(b, keyp, 1);
1991
75
	sshbuf_free(b);
1992
75
	return r;
1993
75
}
1994
1995
int
1996
sshkey_fromb(struct sshbuf *b, struct sshkey **keyp)
1997
{
1998
	return sshkey_from_blob_internal(b, keyp, 1);
1999
}
2000
2001
int
2002
sshkey_froms(struct sshbuf *buf, struct sshkey **keyp)
2003
{
2004
	struct sshbuf *b;
2005
	int r;
2006
2007
	if ((r = sshbuf_froms(buf, &b)) != 0)
2008
		return r;
2009
	r = sshkey_from_blob_internal(b, keyp, 1);
2010
	sshbuf_free(b);
2011
	return r;
2012
}
2013
2014
int
2015
sshkey_sign(const struct sshkey *key,
2016
    u_char **sigp, size_t *lenp,
2017
    const u_char *data, size_t datalen, const char *alg, u_int compat)
2018
{
2019
32
	if (sigp != NULL)
2020
16
		*sigp = NULL;
2021
16
	if (lenp != NULL)
2022
16
		*lenp = 0;
2023
16
	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2024
		return SSH_ERR_INVALID_ARGUMENT;
2025


16
	switch (key->type) {
2026
#ifdef WITH_OPENSSL
2027
	case KEY_DSA_CERT:
2028
	case KEY_DSA:
2029
4
		return ssh_dss_sign(key, sigp, lenp, data, datalen, compat);
2030
	case KEY_ECDSA_CERT:
2031
	case KEY_ECDSA:
2032
		return ssh_ecdsa_sign(key, sigp, lenp, data, datalen, compat);
2033
	case KEY_RSA_CERT:
2034
	case KEY_RSA:
2035
12
		return ssh_rsa_sign(key, sigp, lenp, data, datalen, alg);
2036
#endif /* WITH_OPENSSL */
2037
	case KEY_ED25519:
2038
	case KEY_ED25519_CERT:
2039
		return ssh_ed25519_sign(key, sigp, lenp, data, datalen, compat);
2040
	default:
2041
		return SSH_ERR_KEY_TYPE_UNKNOWN;
2042
	}
2043
16
}
2044
2045
/*
2046
 * ssh_key_verify returns 0 for a correct signature  and < 0 on error.
2047
 */
2048
int
2049
sshkey_verify(const struct sshkey *key,
2050
    const u_char *sig, size_t siglen,
2051
    const u_char *data, size_t dlen, u_int compat)
2052
{
2053
34
	if (siglen == 0 || dlen > SSH_KEY_MAX_SIGN_DATA_SIZE)
2054
		return SSH_ERR_INVALID_ARGUMENT;
2055


17
	switch (key->type) {
2056
#ifdef WITH_OPENSSL
2057
	case KEY_DSA_CERT:
2058
	case KEY_DSA:
2059
4
		return ssh_dss_verify(key, sig, siglen, data, dlen, compat);
2060
	case KEY_ECDSA_CERT:
2061
	case KEY_ECDSA:
2062
1
		return ssh_ecdsa_verify(key, sig, siglen, data, dlen, compat);
2063
	case KEY_RSA_CERT:
2064
	case KEY_RSA:
2065
12
		return ssh_rsa_verify(key, sig, siglen, data, dlen);
2066
#endif /* WITH_OPENSSL */
2067
	case KEY_ED25519:
2068
	case KEY_ED25519_CERT:
2069
		return ssh_ed25519_verify(key, sig, siglen, data, dlen, compat);
2070
	default:
2071
		return SSH_ERR_KEY_TYPE_UNKNOWN;
2072
	}
2073
17
}
2074
2075
/* Converts a private to a public key */
2076
int
2077
sshkey_demote(const struct sshkey *k, struct sshkey **dkp)
2078
{
2079
	struct sshkey *pk;
2080
	int ret = SSH_ERR_INTERNAL_ERROR;
2081
2082
56
	*dkp = NULL;
2083
28
	if ((pk = calloc(1, sizeof(*pk))) == NULL)
2084
		return SSH_ERR_ALLOC_FAIL;
2085
28
	pk->type = k->type;
2086
28
	pk->flags = k->flags;
2087
28
	pk->ecdsa_nid = k->ecdsa_nid;
2088
28
	pk->dsa = NULL;
2089
28
	pk->ecdsa = NULL;
2090
28
	pk->rsa = NULL;
2091
28
	pk->ed25519_pk = NULL;
2092
28
	pk->ed25519_sk = NULL;
2093
2094


28
	switch (k->type) {
2095
#ifdef WITH_OPENSSL
2096
	case KEY_RSA_CERT:
2097
		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2098
			goto fail;
2099
		/* FALLTHROUGH */
2100
	case KEY_RSA:
2101

28
		if ((pk->rsa = RSA_new()) == NULL ||
2102
14
		    (pk->rsa->e = BN_dup(k->rsa->e)) == NULL ||
2103
14
		    (pk->rsa->n = BN_dup(k->rsa->n)) == NULL) {
2104
			ret = SSH_ERR_ALLOC_FAIL;
2105
			goto fail;
2106
			}
2107
		break;
2108
	case KEY_DSA_CERT:
2109
		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2110
			goto fail;
2111
		/* FALLTHROUGH */
2112
	case KEY_DSA:
2113
		if ((pk->dsa = DSA_new()) == NULL ||
2114
		    (pk->dsa->p = BN_dup(k->dsa->p)) == NULL ||
2115
		    (pk->dsa->q = BN_dup(k->dsa->q)) == NULL ||
2116
		    (pk->dsa->g = BN_dup(k->dsa->g)) == NULL ||
2117
		    (pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) {
2118
			ret = SSH_ERR_ALLOC_FAIL;
2119
			goto fail;
2120
		}
2121
		break;
2122
	case KEY_ECDSA_CERT:
2123
		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2124
			goto fail;
2125
		/* FALLTHROUGH */
2126
	case KEY_ECDSA:
2127
		pk->ecdsa = EC_KEY_new_by_curve_name(pk->ecdsa_nid);
2128
		if (pk->ecdsa == NULL) {
2129
			ret = SSH_ERR_ALLOC_FAIL;
2130
			goto fail;
2131
		}
2132
		if (EC_KEY_set_public_key(pk->ecdsa,
2133
		    EC_KEY_get0_public_key(k->ecdsa)) != 1) {
2134
			ret = SSH_ERR_LIBCRYPTO_ERROR;
2135
			goto fail;
2136
		}
2137
		break;
2138
#endif /* WITH_OPENSSL */
2139
	case KEY_ED25519_CERT:
2140
		if ((ret = sshkey_cert_copy(k, pk)) != 0)
2141
			goto fail;
2142
		/* FALLTHROUGH */
2143
	case KEY_ED25519:
2144
14
		if (k->ed25519_pk != NULL) {
2145
14
			if ((pk->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
2146
				ret = SSH_ERR_ALLOC_FAIL;
2147
				goto fail;
2148
			}
2149
14
			memcpy(pk->ed25519_pk, k->ed25519_pk, ED25519_PK_SZ);
2150
14
		}
2151
		break;
2152
	default:
2153
		ret = SSH_ERR_KEY_TYPE_UNKNOWN;
2154
 fail:
2155
		sshkey_free(pk);
2156
		return ret;
2157
	}
2158
28
	*dkp = pk;
2159
28
	return 0;
2160
28
}
2161
2162
/* Convert a plain key to their _CERT equivalent */
2163
int
2164
sshkey_to_certified(struct sshkey *k)
2165
{
2166
	int newtype;
2167
2168
	switch (k->type) {
2169
#ifdef WITH_OPENSSL
2170
	case KEY_RSA:
2171
		newtype = KEY_RSA_CERT;
2172
		break;
2173
	case KEY_DSA:
2174
		newtype = KEY_DSA_CERT;
2175
		break;
2176
	case KEY_ECDSA:
2177
		newtype = KEY_ECDSA_CERT;
2178
		break;
2179
#endif /* WITH_OPENSSL */
2180
	case KEY_ED25519:
2181
		newtype = KEY_ED25519_CERT;
2182
		break;
2183
	default:
2184
		return SSH_ERR_INVALID_ARGUMENT;
2185
	}
2186
	if ((k->cert = cert_new()) == NULL)
2187
		return SSH_ERR_ALLOC_FAIL;
2188
	k->type = newtype;
2189
	return 0;
2190
}
2191
2192
/* Convert a certificate to its raw key equivalent */
2193
int
2194
sshkey_drop_cert(struct sshkey *k)
2195
{
2196
	if (!sshkey_type_is_cert(k->type))
2197
		return SSH_ERR_KEY_TYPE_UNKNOWN;
2198
	cert_free(k->cert);
2199
	k->cert = NULL;
2200
	k->type = sshkey_type_plain(k->type);
2201
	return 0;
2202
}
2203
2204
/* Sign a certified key, (re-)generating the signed certblob. */
2205
int
2206
sshkey_certify_custom(struct sshkey *k, struct sshkey *ca, const char *alg,
2207
    sshkey_certify_signer *signer, void *signer_ctx)
2208
{
2209
	struct sshbuf *principals = NULL;
2210
	u_char *ca_blob = NULL, *sig_blob = NULL, nonce[32];
2211
	size_t i, ca_len, sig_len;
2212
	int ret = SSH_ERR_INTERNAL_ERROR;
2213
	struct sshbuf *cert;
2214
2215
	if (k == NULL || k->cert == NULL ||
2216
	    k->cert->certblob == NULL || ca == NULL)
2217
		return SSH_ERR_INVALID_ARGUMENT;
2218
	if (!sshkey_is_cert(k))
2219
		return SSH_ERR_KEY_TYPE_UNKNOWN;
2220
	if (!sshkey_type_is_valid_ca(ca->type))
2221
		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2222
2223
	if ((ret = sshkey_to_blob(ca, &ca_blob, &ca_len)) != 0)
2224
		return SSH_ERR_KEY_CERT_INVALID_SIGN_KEY;
2225
2226
	cert = k->cert->certblob; /* for readability */
2227
	sshbuf_reset(cert);
2228
	if ((ret = sshbuf_put_cstring(cert, sshkey_ssh_name(k))) != 0)
2229
		goto out;
2230
2231
	/* -v01 certs put nonce first */
2232
	arc4random_buf(&nonce, sizeof(nonce));
2233
	if ((ret = sshbuf_put_string(cert, nonce, sizeof(nonce))) != 0)
2234
		goto out;
2235
2236
	/* XXX this substantially duplicates to_blob(); refactor */
2237
	switch (k->type) {
2238
#ifdef WITH_OPENSSL
2239
	case KEY_DSA_CERT:
2240
		if ((ret = sshbuf_put_bignum2(cert, k->dsa->p)) != 0 ||
2241
		    (ret = sshbuf_put_bignum2(cert, k->dsa->q)) != 0 ||
2242
		    (ret = sshbuf_put_bignum2(cert, k->dsa->g)) != 0 ||
2243
		    (ret = sshbuf_put_bignum2(cert, k->dsa->pub_key)) != 0)
2244
			goto out;
2245
		break;
2246
	case KEY_ECDSA_CERT:
2247
		if ((ret = sshbuf_put_cstring(cert,
2248
		    sshkey_curve_nid_to_name(k->ecdsa_nid))) != 0 ||
2249
		    (ret = sshbuf_put_ec(cert,
2250
		    EC_KEY_get0_public_key(k->ecdsa),
2251
		    EC_KEY_get0_group(k->ecdsa))) != 0)
2252
			goto out;
2253
		break;
2254
	case KEY_RSA_CERT:
2255
		if ((ret = sshbuf_put_bignum2(cert, k->rsa->e)) != 0 ||
2256
		    (ret = sshbuf_put_bignum2(cert, k->rsa->n)) != 0)
2257
			goto out;
2258
		break;
2259
#endif /* WITH_OPENSSL */
2260
	case KEY_ED25519_CERT:
2261
		if ((ret = sshbuf_put_string(cert,
2262
		    k->ed25519_pk, ED25519_PK_SZ)) != 0)
2263
			goto out;
2264
		break;
2265
	default:
2266
		ret = SSH_ERR_INVALID_ARGUMENT;
2267
		goto out;
2268
	}
2269
2270
	if ((ret = sshbuf_put_u64(cert, k->cert->serial)) != 0 ||
2271
	    (ret = sshbuf_put_u32(cert, k->cert->type)) != 0 ||
2272
	    (ret = sshbuf_put_cstring(cert, k->cert->key_id)) != 0)
2273
		goto out;
2274
2275
	if ((principals = sshbuf_new()) == NULL) {
2276
		ret = SSH_ERR_ALLOC_FAIL;
2277
		goto out;
2278
	}
2279
	for (i = 0; i < k->cert->nprincipals; i++) {
2280
		if ((ret = sshbuf_put_cstring(principals,
2281
		    k->cert->principals[i])) != 0)
2282
			goto out;
2283
	}
2284
	if ((ret = sshbuf_put_stringb(cert, principals)) != 0 ||
2285
	    (ret = sshbuf_put_u64(cert, k->cert->valid_after)) != 0 ||
2286
	    (ret = sshbuf_put_u64(cert, k->cert->valid_before)) != 0 ||
2287
	    (ret = sshbuf_put_stringb(cert, k->cert->critical)) != 0 ||
2288
	    (ret = sshbuf_put_stringb(cert, k->cert->extensions)) != 0 ||
2289
	    (ret = sshbuf_put_string(cert, NULL, 0)) != 0 || /* Reserved */
2290
	    (ret = sshbuf_put_string(cert, ca_blob, ca_len)) != 0)
2291
		goto out;
2292
2293
	/* Sign the whole mess */
2294
	if ((ret = signer(ca, &sig_blob, &sig_len, sshbuf_ptr(cert),
2295
	    sshbuf_len(cert), alg, 0, signer_ctx)) != 0)
2296
		goto out;
2297
2298
	/* Append signature and we are done */
2299
	if ((ret = sshbuf_put_string(cert, sig_blob, sig_len)) != 0)
2300
		goto out;
2301
	ret = 0;
2302
 out:
2303
	if (ret != 0)
2304
		sshbuf_reset(cert);
2305
	free(sig_blob);
2306
	free(ca_blob);
2307
	sshbuf_free(principals);
2308
	return ret;
2309
}
2310
2311
static int
2312
default_key_sign(const struct sshkey *key, u_char **sigp, size_t *lenp,
2313
    const u_char *data, size_t datalen,
2314
    const char *alg, u_int compat, void *ctx)
2315
{
2316
	if (ctx != NULL)
2317
		return SSH_ERR_INVALID_ARGUMENT;
2318
	return sshkey_sign(key, sigp, lenp, data, datalen, alg, compat);
2319
}
2320
2321
int
2322
sshkey_certify(struct sshkey *k, struct sshkey *ca, const char *alg)
2323
{
2324
	return sshkey_certify_custom(k, ca, alg, default_key_sign, NULL);
2325
}
2326
2327
int
2328
sshkey_cert_check_authority(const struct sshkey *k,
2329
    int want_host, int require_principal,
2330
    const char *name, const char **reason)
2331
{
2332
	u_int i, principal_matches;
2333
	time_t now = time(NULL);
2334
2335
	if (reason != NULL)
2336
		*reason = NULL;
2337
2338
	if (want_host) {
2339
		if (k->cert->type != SSH2_CERT_TYPE_HOST) {
2340
			*reason = "Certificate invalid: not a host certificate";
2341
			return SSH_ERR_KEY_CERT_INVALID;
2342
		}
2343
	} else {
2344
		if (k->cert->type != SSH2_CERT_TYPE_USER) {
2345
			*reason = "Certificate invalid: not a user certificate";
2346
			return SSH_ERR_KEY_CERT_INVALID;
2347
		}
2348
	}
2349
	if (now < 0) {
2350
		/* yikes - system clock before epoch! */
2351
		*reason = "Certificate invalid: not yet valid";
2352
		return SSH_ERR_KEY_CERT_INVALID;
2353
	}
2354
	if ((u_int64_t)now < k->cert->valid_after) {
2355
		*reason = "Certificate invalid: not yet valid";
2356
		return SSH_ERR_KEY_CERT_INVALID;
2357
	}
2358
	if ((u_int64_t)now >= k->cert->valid_before) {
2359
		*reason = "Certificate invalid: expired";
2360
		return SSH_ERR_KEY_CERT_INVALID;
2361
	}
2362
	if (k->cert->nprincipals == 0) {
2363
		if (require_principal) {
2364
			*reason = "Certificate lacks principal list";
2365
			return SSH_ERR_KEY_CERT_INVALID;
2366
		}
2367
	} else if (name != NULL) {
2368
		principal_matches = 0;
2369
		for (i = 0; i < k->cert->nprincipals; i++) {
2370
			if (strcmp(name, k->cert->principals[i]) == 0) {
2371
				principal_matches = 1;
2372
				break;
2373
			}
2374
		}
2375
		if (!principal_matches) {
2376
			*reason = "Certificate invalid: name is not a listed "
2377
			    "principal";
2378
			return SSH_ERR_KEY_CERT_INVALID;
2379
		}
2380
	}
2381
	return 0;
2382
}
2383
2384
size_t
2385
sshkey_format_cert_validity(const struct sshkey_cert *cert, char *s, size_t l)
2386
{
2387
	char from[32], to[32], ret[64];
2388
	time_t tt;
2389
	struct tm *tm;
2390
2391
	*from = *to = '\0';
2392
	if (cert->valid_after == 0 &&
2393
	    cert->valid_before == 0xffffffffffffffffULL)
2394
		return strlcpy(s, "forever", l);
2395
2396
	if (cert->valid_after != 0) {
2397
		/* XXX revisit INT_MAX in 2038 :) */
2398
		tt = cert->valid_after > INT_MAX ?
2399
		    INT_MAX : cert->valid_after;
2400
		tm = localtime(&tt);
2401
		strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
2402
	}
2403
	if (cert->valid_before != 0xffffffffffffffffULL) {
2404
		/* XXX revisit INT_MAX in 2038 :) */
2405
		tt = cert->valid_before > INT_MAX ?
2406
		    INT_MAX : cert->valid_before;
2407
		tm = localtime(&tt);
2408
		strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
2409
	}
2410
2411
	if (cert->valid_after == 0)
2412
		snprintf(ret, sizeof(ret), "before %s", to);
2413
	else if (cert->valid_before == 0xffffffffffffffffULL)
2414
		snprintf(ret, sizeof(ret), "after %s", from);
2415
	else
2416
		snprintf(ret, sizeof(ret), "from %s to %s", from, to);
2417
2418
	return strlcpy(s, ret, l);
2419
}
2420
2421
int
2422
sshkey_private_serialize(const struct sshkey *key, struct sshbuf *b)
2423
{
2424
	int r = SSH_ERR_INTERNAL_ERROR;
2425
2426
10
	if ((r = sshbuf_put_cstring(b, sshkey_ssh_name(key))) != 0)
2427
		goto out;
2428


5
	switch (key->type) {
2429
#ifdef WITH_OPENSSL
2430
	case KEY_RSA:
2431
		if ((r = sshbuf_put_bignum2(b, key->rsa->n)) != 0 ||
2432
		    (r = sshbuf_put_bignum2(b, key->rsa->e)) != 0 ||
2433
		    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2434
		    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2435
		    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2436
		    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2437
			goto out;
2438
		break;
2439
	case KEY_RSA_CERT:
2440
		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2441
			r = SSH_ERR_INVALID_ARGUMENT;
2442
			goto out;
2443
		}
2444
		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2445
		    (r = sshbuf_put_bignum2(b, key->rsa->d)) != 0 ||
2446
		    (r = sshbuf_put_bignum2(b, key->rsa->iqmp)) != 0 ||
2447
		    (r = sshbuf_put_bignum2(b, key->rsa->p)) != 0 ||
2448
		    (r = sshbuf_put_bignum2(b, key->rsa->q)) != 0)
2449
			goto out;
2450
		break;
2451
	case KEY_DSA:
2452
		if ((r = sshbuf_put_bignum2(b, key->dsa->p)) != 0 ||
2453
		    (r = sshbuf_put_bignum2(b, key->dsa->q)) != 0 ||
2454
		    (r = sshbuf_put_bignum2(b, key->dsa->g)) != 0 ||
2455
		    (r = sshbuf_put_bignum2(b, key->dsa->pub_key)) != 0 ||
2456
		    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2457
			goto out;
2458
		break;
2459
	case KEY_DSA_CERT:
2460
		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2461
			r = SSH_ERR_INVALID_ARGUMENT;
2462
			goto out;
2463
		}
2464
		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2465
		    (r = sshbuf_put_bignum2(b, key->dsa->priv_key)) != 0)
2466
			goto out;
2467
		break;
2468
	case KEY_ECDSA:
2469
		if ((r = sshbuf_put_cstring(b,
2470
		    sshkey_curve_nid_to_name(key->ecdsa_nid))) != 0 ||
2471
		    (r = sshbuf_put_eckey(b, key->ecdsa)) != 0 ||
2472
		    (r = sshbuf_put_bignum2(b,
2473
		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
2474
			goto out;
2475
		break;
2476
	case KEY_ECDSA_CERT:
2477
		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2478
			r = SSH_ERR_INVALID_ARGUMENT;
2479
			goto out;
2480
		}
2481
		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2482
		    (r = sshbuf_put_bignum2(b,
2483
		    EC_KEY_get0_private_key(key->ecdsa))) != 0)
2484
			goto out;
2485
		break;
2486
#endif /* WITH_OPENSSL */
2487
	case KEY_ED25519:
2488
10
		if ((r = sshbuf_put_string(b, key->ed25519_pk,
2489
5
		    ED25519_PK_SZ)) != 0 ||
2490
5
		    (r = sshbuf_put_string(b, key->ed25519_sk,
2491
5
		    ED25519_SK_SZ)) != 0)
2492
			goto out;
2493
		break;
2494
	case KEY_ED25519_CERT:
2495
		if (key->cert == NULL || sshbuf_len(key->cert->certblob) == 0) {
2496
			r = SSH_ERR_INVALID_ARGUMENT;
2497
			goto out;
2498
		}
2499
		if ((r = sshbuf_put_stringb(b, key->cert->certblob)) != 0 ||
2500
		    (r = sshbuf_put_string(b, key->ed25519_pk,
2501
		    ED25519_PK_SZ)) != 0 ||
2502
		    (r = sshbuf_put_string(b, key->ed25519_sk,
2503
		    ED25519_SK_SZ)) != 0)
2504
			goto out;
2505
		break;
2506
	default:
2507
		r = SSH_ERR_INVALID_ARGUMENT;
2508
		goto out;
2509
	}
2510
	/* success */
2511
5
	r = 0;
2512
 out:
2513
5
	return r;
2514
}
2515
2516
int
2517
sshkey_private_deserialize(struct sshbuf *buf, struct sshkey **kp)
2518
{
2519
42
	char *tname = NULL, *curve = NULL;
2520
21
	struct sshkey *k = NULL;
2521
21
	size_t pklen = 0, sklen = 0;
2522
	int type, r = SSH_ERR_INTERNAL_ERROR;
2523
21
	u_char *ed25519_pk = NULL, *ed25519_sk = NULL;
2524
#ifdef WITH_OPENSSL
2525
	BIGNUM *exponent = NULL;
2526
#endif /* WITH_OPENSSL */
2527
2528
21
	if (kp != NULL)
2529
21
		*kp = NULL;
2530
21
	if ((r = sshbuf_get_cstring(buf, &tname, NULL)) != 0)
2531
		goto out;
2532
21
	type = sshkey_type_from_name(tname);
2533


21
	switch (type) {
2534
#ifdef WITH_OPENSSL
2535
	case KEY_DSA:
2536
		if ((k = sshkey_new_private(type)) == NULL) {
2537
			r = SSH_ERR_ALLOC_FAIL;
2538
			goto out;
2539
		}
2540
		if ((r = sshbuf_get_bignum2(buf, k->dsa->p)) != 0 ||
2541
		    (r = sshbuf_get_bignum2(buf, k->dsa->q)) != 0 ||
2542
		    (r = sshbuf_get_bignum2(buf, k->dsa->g)) != 0 ||
2543
		    (r = sshbuf_get_bignum2(buf, k->dsa->pub_key)) != 0 ||
2544
		    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2545
			goto out;
2546
		break;
2547
	case KEY_DSA_CERT:
2548
		if ((r = sshkey_froms(buf, &k)) != 0 ||
2549
		    (r = sshkey_add_private(k)) != 0 ||
2550
		    (r = sshbuf_get_bignum2(buf, k->dsa->priv_key)) != 0)
2551
			goto out;
2552
		break;
2553
	case KEY_ECDSA:
2554
		if ((k = sshkey_new_private(type)) == NULL) {
2555
			r = SSH_ERR_ALLOC_FAIL;
2556
			goto out;
2557
		}
2558
		if ((k->ecdsa_nid = sshkey_ecdsa_nid_from_name(tname)) == -1) {
2559
			r = SSH_ERR_INVALID_ARGUMENT;
2560
			goto out;
2561
		}
2562
		if ((r = sshbuf_get_cstring(buf, &curve, NULL)) != 0)
2563
			goto out;
2564
		if (k->ecdsa_nid != sshkey_curve_name_to_nid(curve)) {
2565
			r = SSH_ERR_EC_CURVE_MISMATCH;
2566
			goto out;
2567
		}
2568
		k->ecdsa = EC_KEY_new_by_curve_name(k->ecdsa_nid);
2569
		if (k->ecdsa  == NULL || (exponent = BN_new()) == NULL) {
2570
			r = SSH_ERR_LIBCRYPTO_ERROR;
2571
			goto out;
2572
		}
2573
		if ((r = sshbuf_get_eckey(buf, k->ecdsa)) != 0 ||
2574
		    (r = sshbuf_get_bignum2(buf, exponent)))
2575
			goto out;
2576
		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2577
			r = SSH_ERR_LIBCRYPTO_ERROR;
2578
			goto out;
2579
		}
2580
		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2581
		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2582
		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2583
			goto out;
2584
		break;
2585
	case KEY_ECDSA_CERT:
2586
		if ((exponent = BN_new()) == NULL) {
2587
			r = SSH_ERR_LIBCRYPTO_ERROR;
2588
			goto out;
2589
		}
2590
		if ((r = sshkey_froms(buf, &k)) != 0 ||
2591
		    (r = sshkey_add_private(k)) != 0 ||
2592
		    (r = sshbuf_get_bignum2(buf, exponent)) != 0)
2593
			goto out;
2594
		if (EC_KEY_set_private_key(k->ecdsa, exponent) != 1) {
2595
			r = SSH_ERR_LIBCRYPTO_ERROR;
2596
			goto out;
2597
		}
2598
		if ((r = sshkey_ec_validate_public(EC_KEY_get0_group(k->ecdsa),
2599
		    EC_KEY_get0_public_key(k->ecdsa))) != 0 ||
2600
		    (r = sshkey_ec_validate_private(k->ecdsa)) != 0)
2601
			goto out;
2602
		break;
2603
	case KEY_RSA:
2604
		if ((k = sshkey_new_private(type)) == NULL) {
2605
			r = SSH_ERR_ALLOC_FAIL;
2606
			goto out;
2607
		}
2608
		if ((r = sshbuf_get_bignum2(buf, k->rsa->n)) != 0 ||
2609
		    (r = sshbuf_get_bignum2(buf, k->rsa->e)) != 0 ||
2610
		    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2611
		    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2612
		    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2613
		    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2614
		    (r = ssh_rsa_generate_additional_parameters(k)) != 0)
2615
			goto out;
2616
		if (BN_num_bits(k->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
2617
			r = SSH_ERR_KEY_LENGTH;
2618
			goto out;
2619
		}
2620
		break;
2621
	case KEY_RSA_CERT:
2622
		if ((r = sshkey_froms(buf, &k)) != 0 ||
2623
		    (r = sshkey_add_private(k)) != 0 ||
2624
		    (r = sshbuf_get_bignum2(buf, k->rsa->d)) != 0 ||
2625
		    (r = sshbuf_get_bignum2(buf, k->rsa->iqmp)) != 0 ||
2626
		    (r = sshbuf_get_bignum2(buf, k->rsa->p)) != 0 ||
2627
		    (r = sshbuf_get_bignum2(buf, k->rsa->q)) != 0 ||
2628
		    (r = ssh_rsa_generate_additional_parameters(k)) != 0)
2629
			goto out;
2630
		if (BN_num_bits(k->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
2631
			r = SSH_ERR_KEY_LENGTH;
2632
			goto out;
2633
		}
2634
		break;
2635
#endif /* WITH_OPENSSL */
2636
	case KEY_ED25519:
2637
21
		if ((k = sshkey_new_private(type)) == NULL) {
2638
			r = SSH_ERR_ALLOC_FAIL;
2639
			goto out;
2640
		}
2641

42
		if ((r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2642
21
		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2643
			goto out;
2644
21
		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2645
			r = SSH_ERR_INVALID_FORMAT;
2646
			goto out;
2647
		}
2648
21
		k->ed25519_pk = ed25519_pk;
2649
21
		k->ed25519_sk = ed25519_sk;
2650
21
		ed25519_pk = ed25519_sk = NULL;
2651
21
		break;
2652
	case KEY_ED25519_CERT:
2653
		if ((r = sshkey_froms(buf, &k)) != 0 ||
2654
		    (r = sshkey_add_private(k)) != 0 ||
2655
		    (r = sshbuf_get_string(buf, &ed25519_pk, &pklen)) != 0 ||
2656
		    (r = sshbuf_get_string(buf, &ed25519_sk, &sklen)) != 0)
2657
			goto out;
2658
		if (pklen != ED25519_PK_SZ || sklen != ED25519_SK_SZ) {
2659
			r = SSH_ERR_INVALID_FORMAT;
2660
			goto out;
2661
		}
2662
		k->ed25519_pk = ed25519_pk;
2663
		k->ed25519_sk = ed25519_sk;
2664
		ed25519_pk = ed25519_sk = NULL;
2665
		break;
2666
	default:
2667
		r = SSH_ERR_KEY_TYPE_UNKNOWN;
2668
		goto out;
2669
	}
2670
#ifdef WITH_OPENSSL
2671
	/* enable blinding */
2672
21
	switch (k->type) {
2673
	case KEY_RSA:
2674
	case KEY_RSA_CERT:
2675
		if (RSA_blinding_on(k->rsa, NULL) != 1) {
2676
			r = SSH_ERR_LIBCRYPTO_ERROR;
2677
			goto out;
2678
		}
2679
		break;
2680
	}
2681
#endif /* WITH_OPENSSL */
2682
	/* success */
2683
	r = 0;
2684
21
	if (kp != NULL) {
2685
21
		*kp = k;
2686
21
		k = NULL;
2687
21
	}
2688
 out:
2689
21
	free(tname);
2690
21
	free(curve);
2691
#ifdef WITH_OPENSSL
2692
21
	if (exponent != NULL)
2693
		BN_clear_free(exponent);
2694
#endif /* WITH_OPENSSL */
2695
21
	sshkey_free(k);
2696
21
	if (ed25519_pk != NULL) {
2697
		explicit_bzero(ed25519_pk, pklen);
2698
		free(ed25519_pk);
2699
	}
2700
21
	if (ed25519_sk != NULL) {
2701
		explicit_bzero(ed25519_sk, sklen);
2702
		free(ed25519_sk);
2703
	}
2704
21
	return r;
2705
21
}
2706
2707
#ifdef WITH_OPENSSL
2708
int
2709
sshkey_ec_validate_public(const EC_GROUP *group, const EC_POINT *public)
2710
{
2711
	BN_CTX *bnctx;
2712
	EC_POINT *nq = NULL;
2713
	BIGNUM *order, *x, *y, *tmp;
2714
	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2715
2716
	/*
2717
	 * NB. This assumes OpenSSL has already verified that the public
2718
	 * point lies on the curve. This is done by EC_POINT_oct2point()
2719
	 * implicitly calling EC_POINT_is_on_curve(). If this code is ever
2720
	 * reachable with public points not unmarshalled using
2721
	 * EC_POINT_oct2point then the caller will need to explicitly check.
2722
	 */
2723
2724
18
	if ((bnctx = BN_CTX_new()) == NULL)
2725
		return SSH_ERR_ALLOC_FAIL;
2726
9
	BN_CTX_start(bnctx);
2727
2728
	/*
2729
	 * We shouldn't ever hit this case because bignum_get_ecpoint()
2730
	 * refuses to load GF2m points.
2731
	 */
2732
9
	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2733
	    NID_X9_62_prime_field)
2734
		goto out;
2735
2736
	/* Q != infinity */
2737
9
	if (EC_POINT_is_at_infinity(group, public))
2738
		goto out;
2739
2740

18
	if ((x = BN_CTX_get(bnctx)) == NULL ||
2741
9
	    (y = BN_CTX_get(bnctx)) == NULL ||
2742
9
	    (order = BN_CTX_get(bnctx)) == NULL ||
2743
9
	    (tmp = BN_CTX_get(bnctx)) == NULL) {
2744
		ret = SSH_ERR_ALLOC_FAIL;
2745
		goto out;
2746
	}
2747
2748
	/* log2(x) > log2(order)/2, log2(y) > log2(order)/2 */
2749

18
	if (EC_GROUP_get_order(group, order, bnctx) != 1 ||
2750
9
	    EC_POINT_get_affine_coordinates_GFp(group, public,
2751
9
	    x, y, bnctx) != 1) {
2752
		ret = SSH_ERR_LIBCRYPTO_ERROR;
2753
		goto out;
2754
	}
2755

18
	if (BN_num_bits(x) <= BN_num_bits(order) / 2 ||
2756
9
	    BN_num_bits(y) <= BN_num_bits(order) / 2)
2757
		goto out;
2758
2759
	/* nQ == infinity (n == order of subgroup) */
2760
9
	if ((nq = EC_POINT_new(group)) == NULL) {
2761
		ret = SSH_ERR_ALLOC_FAIL;
2762
		goto out;
2763
	}
2764
9
	if (EC_POINT_mul(group, nq, NULL, public, order, bnctx) != 1) {
2765
		ret = SSH_ERR_LIBCRYPTO_ERROR;
2766
		goto out;
2767
	}
2768
9
	if (EC_POINT_is_at_infinity(group, nq) != 1)
2769
		goto out;
2770
2771
	/* x < order - 1, y < order - 1 */
2772
9
	if (!BN_sub(tmp, order, BN_value_one())) {
2773
		ret = SSH_ERR_LIBCRYPTO_ERROR;
2774
		goto out;
2775
	}
2776

18
	if (BN_cmp(x, tmp) >= 0 || BN_cmp(y, tmp) >= 0)
2777
		goto out;
2778
9
	ret = 0;
2779
 out:
2780
9
	BN_CTX_free(bnctx);
2781
9
	if (nq != NULL)
2782
9
		EC_POINT_free(nq);
2783
9
	return ret;
2784
9
}
2785
2786
int
2787
sshkey_ec_validate_private(const EC_KEY *key)
2788
{
2789
	BN_CTX *bnctx;
2790
	BIGNUM *order, *tmp;
2791
	int ret = SSH_ERR_KEY_INVALID_EC_VALUE;
2792
2793
	if ((bnctx = BN_CTX_new()) == NULL)
2794
		return SSH_ERR_ALLOC_FAIL;
2795
	BN_CTX_start(bnctx);
2796
2797
	if ((order = BN_CTX_get(bnctx)) == NULL ||
2798
	    (tmp = BN_CTX_get(bnctx)) == NULL) {
2799
		ret = SSH_ERR_ALLOC_FAIL;
2800
		goto out;
2801
	}
2802
2803
	/* log2(private) > log2(order)/2 */
2804
	if (EC_GROUP_get_order(EC_KEY_get0_group(key), order, bnctx) != 1) {
2805
		ret = SSH_ERR_LIBCRYPTO_ERROR;
2806
		goto out;
2807
	}
2808
	if (BN_num_bits(EC_KEY_get0_private_key(key)) <=
2809
	    BN_num_bits(order) / 2)
2810
		goto out;
2811
2812
	/* private < order - 1 */
2813
	if (!BN_sub(tmp, order, BN_value_one())) {
2814
		ret = SSH_ERR_LIBCRYPTO_ERROR;
2815
		goto out;
2816
	}
2817
	if (BN_cmp(EC_KEY_get0_private_key(key), tmp) >= 0)
2818
		goto out;
2819
	ret = 0;
2820
 out:
2821
	BN_CTX_free(bnctx);
2822
	return ret;
2823
}
2824
2825
void
2826
sshkey_dump_ec_point(const EC_GROUP *group, const EC_POINT *point)
2827
{
2828
	BIGNUM *x, *y;
2829
	BN_CTX *bnctx;
2830
2831
	if (point == NULL) {
2832
		fputs("point=(NULL)\n", stderr);
2833
		return;
2834
	}
2835
	if ((bnctx = BN_CTX_new()) == NULL) {
2836
		fprintf(stderr, "%s: BN_CTX_new failed\n", __func__);
2837
		return;
2838
	}
2839
	BN_CTX_start(bnctx);
2840
	if ((x = BN_CTX_get(bnctx)) == NULL ||
2841
	    (y = BN_CTX_get(bnctx)) == NULL) {
2842
		fprintf(stderr, "%s: BN_CTX_get failed\n", __func__);
2843
		return;
2844
	}
2845
	if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
2846
	    NID_X9_62_prime_field) {
2847
		fprintf(stderr, "%s: group is not a prime field\n", __func__);
2848
		return;
2849
	}
2850
	if (EC_POINT_get_affine_coordinates_GFp(group, point, x, y,
2851
	    bnctx) != 1) {
2852
		fprintf(stderr, "%s: EC_POINT_get_affine_coordinates_GFp\n",
2853
		    __func__);
2854
		return;
2855
	}
2856
	fputs("x=", stderr);
2857
	BN_print_fp(stderr, x);
2858
	fputs("\ny=", stderr);
2859
	BN_print_fp(stderr, y);
2860
	fputs("\n", stderr);
2861
	BN_CTX_free(bnctx);
2862
}
2863
2864
void
2865
sshkey_dump_ec_key(const EC_KEY *key)
2866
{
2867
	const BIGNUM *exponent;
2868
2869
	sshkey_dump_ec_point(EC_KEY_get0_group(key),
2870
	    EC_KEY_get0_public_key(key));
2871
	fputs("exponent=", stderr);
2872
	if ((exponent = EC_KEY_get0_private_key(key)) == NULL)
2873
		fputs("(NULL)", stderr);
2874
	else
2875
		BN_print_fp(stderr, EC_KEY_get0_private_key(key));
2876
	fputs("\n", stderr);
2877
}
2878
#endif /* WITH_OPENSSL */
2879
2880
static int
2881
sshkey_private_to_blob2(const struct sshkey *prv, struct sshbuf *blob,
2882
    const char *passphrase, const char *comment, const char *ciphername,
2883
    int rounds)
2884
{
2885
10
	u_char *cp, *key = NULL, *pubkeyblob = NULL;
2886
5
	u_char salt[SALT_LEN];
2887
	char *b64 = NULL;
2888
5
	size_t i, pubkeylen, keylen, ivlen, blocksize, authlen;
2889
	u_int check;
2890
	int r = SSH_ERR_INTERNAL_ERROR;
2891
5
	struct sshcipher_ctx *ciphercontext = NULL;
2892
	const struct sshcipher *cipher;
2893
	const char *kdfname = KDFNAME;
2894
	struct sshbuf *encoded = NULL, *encrypted = NULL, *kdf = NULL;
2895
2896
5
	if (rounds <= 0)
2897
5
		rounds = DEFAULT_ROUNDS;
2898

10
	if (passphrase == NULL || !strlen(passphrase)) {
2899
		ciphername = "none";
2900
		kdfname = "none";
2901
5
	} else if (ciphername == NULL)
2902
		ciphername = DEFAULT_CIPHERNAME;
2903
5
	if ((cipher = cipher_by_name(ciphername)) == NULL) {
2904
		r = SSH_ERR_INVALID_ARGUMENT;
2905
		goto out;
2906
	}
2907
2908

10
	if ((kdf = sshbuf_new()) == NULL ||
2909
5
	    (encoded = sshbuf_new()) == NULL ||
2910
5
	    (encrypted = sshbuf_new()) == NULL) {
2911
		r = SSH_ERR_ALLOC_FAIL;
2912
		goto out;
2913
	}
2914
5
	blocksize = cipher_blocksize(cipher);
2915
5
	keylen = cipher_keylen(cipher);
2916
5
	ivlen = cipher_ivlen(cipher);
2917
5
	authlen = cipher_authlen(cipher);
2918
5
	if ((key = calloc(1, keylen + ivlen)) == NULL) {
2919
		r = SSH_ERR_ALLOC_FAIL;
2920
		goto out;
2921
	}
2922
5
	if (strcmp(kdfname, "bcrypt") == 0) {
2923
		arc4random_buf(salt, SALT_LEN);
2924
		if (bcrypt_pbkdf(passphrase, strlen(passphrase),
2925
		    salt, SALT_LEN, key, keylen + ivlen, rounds) < 0) {
2926
			r = SSH_ERR_INVALID_ARGUMENT;
2927
			goto out;
2928
		}
2929
		if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
2930
		    (r = sshbuf_put_u32(kdf, rounds)) != 0)
2931
			goto out;
2932
5
	} else if (strcmp(kdfname, "none") != 0) {
2933
		/* Unsupported KDF type */
2934
		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
2935
		goto out;
2936
	}
2937
10
	if ((r = cipher_init(&ciphercontext, cipher, key, keylen,
2938
10
	    key + keylen, ivlen, 1)) != 0)
2939
		goto out;
2940
2941

10
	if ((r = sshbuf_put(encoded, AUTH_MAGIC, sizeof(AUTH_MAGIC))) != 0 ||
2942
5
	    (r = sshbuf_put_cstring(encoded, ciphername)) != 0 ||
2943
5
	    (r = sshbuf_put_cstring(encoded, kdfname)) != 0 ||
2944
5
	    (r = sshbuf_put_stringb(encoded, kdf)) != 0 ||
2945
5
	    (r = sshbuf_put_u32(encoded, 1)) != 0 ||	/* number of keys */
2946
5
	    (r = sshkey_to_blob(prv, &pubkeyblob, &pubkeylen)) != 0 ||
2947
5
	    (r = sshbuf_put_string(encoded, pubkeyblob, pubkeylen)) != 0)
2948
		goto out;
2949
2950
	/* set up the buffer that will be encrypted */
2951
2952
	/* Random check bytes */
2953
5
	check = arc4random();
2954

10
	if ((r = sshbuf_put_u32(encrypted, check)) != 0 ||
2955
5
	    (r = sshbuf_put_u32(encrypted, check)) != 0)
2956
		goto out;
2957
2958
	/* append private key and comment*/
2959

10
	if ((r = sshkey_private_serialize(prv, encrypted)) != 0 ||
2960
5
	    (r = sshbuf_put_cstring(encrypted, comment)) != 0)
2961
		goto out;
2962
2963
	/* padding */
2964
	i = 0;
2965
24
	while (sshbuf_len(encrypted) % blocksize) {
2966
14
		if ((r = sshbuf_put_u8(encrypted, ++i & 0xff)) != 0)
2967
			goto out;
2968
	}
2969
2970
	/* length in destination buffer */
2971
5
	if ((r = sshbuf_put_u32(encoded, sshbuf_len(encrypted))) != 0)
2972
		goto out;
2973
2974
	/* encrypt */
2975
10
	if ((r = sshbuf_reserve(encoded,
2976
10
	    sshbuf_len(encrypted) + authlen, &cp)) != 0)
2977
		goto out;
2978
15
	if ((r = cipher_crypt(ciphercontext, 0, cp,
2979
10
	    sshbuf_ptr(encrypted), sshbuf_len(encrypted), 0, authlen)) != 0)
2980
		goto out;
2981
2982
	/* uuencode */
2983
5
	if ((b64 = sshbuf_dtob64(encoded)) == NULL) {
2984
		r = SSH_ERR_ALLOC_FAIL;
2985
		goto out;
2986
	}
2987
2988
5
	sshbuf_reset(blob);
2989
5
	if ((r = sshbuf_put(blob, MARK_BEGIN, MARK_BEGIN_LEN)) != 0)
2990
		goto out;
2991
3370
	for (i = 0; i < strlen(b64); i++) {
2992
1680
		if ((r = sshbuf_put_u8(blob, b64[i])) != 0)
2993
			goto out;
2994
		/* insert line breaks */
2995

1700
		if (i % 70 == 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
2996
			goto out;
2997
	}
2998

10
	if (i % 70 != 69 && (r = sshbuf_put_u8(blob, '\n')) != 0)
2999
		goto out;
3000
5
	if ((r = sshbuf_put(blob, MARK_END, MARK_END_LEN)) != 0)
3001
		goto out;
3002
3003
	/* success */
3004
	r = 0;
3005
3006
 out:
3007
5
	sshbuf_free(kdf);
3008
5
	sshbuf_free(encoded);
3009
5
	sshbuf_free(encrypted);
3010
5
	cipher_free(ciphercontext);
3011
5
	explicit_bzero(salt, sizeof(salt));
3012
5
	if (key != NULL) {
3013
5
		explicit_bzero(key, keylen + ivlen);
3014
5
		free(key);
3015
5
	}
3016
5
	if (pubkeyblob != NULL) {
3017
5
		explicit_bzero(pubkeyblob, pubkeylen);
3018
5
		free(pubkeyblob);
3019
5
	}
3020
5
	if (b64 != NULL) {
3021
5
		explicit_bzero(b64, strlen(b64));
3022
5
		free(b64);
3023
5
	}
3024
5
	return r;
3025
5
}
3026
3027
static int
3028
sshkey_parse_private2(struct sshbuf *blob, int type, const char *passphrase,
3029
    struct sshkey **keyp, char **commentp)
3030
{
3031
100
	char *comment = NULL, *ciphername = NULL, *kdfname = NULL;
3032
	const struct sshcipher *cipher = NULL;
3033
	const u_char *cp;
3034
	int r = SSH_ERR_INTERNAL_ERROR;
3035
	size_t encoded_len;
3036
50
	size_t i, keylen = 0, ivlen = 0, authlen = 0, slen = 0;
3037
	struct sshbuf *encoded = NULL, *decoded = NULL;
3038
50
	struct sshbuf *kdf = NULL, *decrypted = NULL;
3039
50
	struct sshcipher_ctx *ciphercontext = NULL;
3040
50
	struct sshkey *k = NULL;
3041
50
	u_char *key = NULL, *salt = NULL, *dp, pad, last;
3042
50
	u_int blocksize, rounds, nkeys, encrypted_len, check1, check2;
3043
3044
50
	if (keyp != NULL)
3045
50
		*keyp = NULL;
3046
50
	if (commentp != NULL)
3047
		*commentp = NULL;
3048
3049

100
	if ((encoded = sshbuf_new()) == NULL ||
3050
50
	    (decoded = sshbuf_new()) == NULL ||
3051
50
	    (decrypted = sshbuf_new()) == NULL) {
3052
		r = SSH_ERR_ALLOC_FAIL;
3053
		goto out;
3054
	}
3055
3056
	/* check preamble */
3057
50
	cp = sshbuf_ptr(blob);
3058
50
	encoded_len = sshbuf_len(blob);
3059

100
	if (encoded_len < (MARK_BEGIN_LEN + MARK_END_LEN) ||
3060
50
	    memcmp(cp, MARK_BEGIN, MARK_BEGIN_LEN) != 0) {
3061
		r = SSH_ERR_INVALID_FORMAT;
3062
29
		goto out;
3063
	}
3064
21
	cp += MARK_BEGIN_LEN;
3065
21
	encoded_len -= MARK_BEGIN_LEN;
3066
3067
	/* Look for end marker, removing whitespace as we go */
3068
7182
	while (encoded_len > 0) {
3069

14217
		if (*cp != '\n' && *cp != '\r') {
3070
7056
			if ((r = sshbuf_put_u8(encoded, *cp)) != 0)
3071
				goto out;
3072
		}
3073
7161
		last = *cp;
3074
7161
		encoded_len--;
3075
7161
		cp++;
3076
14322
		if (last == '\n') {
3077
7266
			if (encoded_len >= MARK_END_LEN &&
3078
105
			    memcmp(cp, MARK_END, MARK_END_LEN) == 0) {
3079
				/* \0 terminate */
3080
21
				if ((r = sshbuf_put_u8(encoded, 0)) != 0)
3081
					goto out;
3082
				break;
3083
			}
3084
		}
3085
	}
3086
21
	if (encoded_len == 0) {
3087
		r = SSH_ERR_INVALID_FORMAT;
3088
		goto out;
3089
	}
3090
3091
	/* decode base64 */
3092
21
	if ((r = sshbuf_b64tod(decoded, (char *)sshbuf_ptr(encoded))) != 0)
3093
		goto out;
3094
3095
	/* check magic */
3096

42
	if (sshbuf_len(decoded) < sizeof(AUTH_MAGIC) ||
3097
21
	    memcmp(sshbuf_ptr(decoded), AUTH_MAGIC, sizeof(AUTH_MAGIC))) {
3098
		r = SSH_ERR_INVALID_FORMAT;
3099
		goto out;
3100
	}
3101
	/* parse public portion of key */
3102

42
	if ((r = sshbuf_consume(decoded, sizeof(AUTH_MAGIC))) != 0 ||
3103
21
	    (r = sshbuf_get_cstring(decoded, &ciphername, NULL)) != 0 ||
3104
21
	    (r = sshbuf_get_cstring(decoded, &kdfname, NULL)) != 0 ||
3105
21
	    (r = sshbuf_froms(decoded, &kdf)) != 0 ||
3106
21
	    (r = sshbuf_get_u32(decoded, &nkeys)) != 0 ||
3107
21
	    (r = sshbuf_skip_string(decoded)) != 0 || /* pubkey */
3108
21
	    (r = sshbuf_get_u32(decoded, &encrypted_len)) != 0)
3109
		goto out;
3110
3111
21
	if ((cipher = cipher_by_name(ciphername)) == NULL) {
3112
		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3113
		goto out;
3114
	}
3115

63
	if ((passphrase == NULL || strlen(passphrase) == 0) &&
3116
21
	    strcmp(ciphername, "none") != 0) {
3117
		/* passphrase required */
3118
		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3119
		goto out;
3120
	}
3121

21
	if (strcmp(kdfname, "none") != 0 && strcmp(kdfname, "bcrypt") != 0) {
3122
		r = SSH_ERR_KEY_UNKNOWN_CIPHER;
3123
		goto out;
3124
	}
3125

42
	if (!strcmp(kdfname, "none") && strcmp(ciphername, "none") != 0) {
3126
		r = SSH_ERR_INVALID_FORMAT;
3127
		goto out;
3128
	}
3129
21
	if (nkeys != 1) {
3130
		/* XXX only one key supported */
3131
		r = SSH_ERR_INVALID_FORMAT;
3132
		goto out;
3133
	}
3134
3135
	/* check size of encrypted key blob */
3136
21
	blocksize = cipher_blocksize(cipher);
3137

42
	if (encrypted_len < blocksize || (encrypted_len % blocksize) != 0) {
3138
		r = SSH_ERR_INVALID_FORMAT;
3139
		goto out;
3140
	}
3141
3142
	/* setup key */
3143
21
	keylen = cipher_keylen(cipher);
3144
21
	ivlen = cipher_ivlen(cipher);
3145
21
	authlen = cipher_authlen(cipher);
3146
21
	if ((key = calloc(1, keylen + ivlen)) == NULL) {
3147
		r = SSH_ERR_ALLOC_FAIL;
3148
		goto out;
3149
	}
3150
21
	if (strcmp(kdfname, "bcrypt") == 0) {
3151
		if ((r = sshbuf_get_string(kdf, &salt, &slen)) != 0 ||
3152
		    (r = sshbuf_get_u32(kdf, &rounds)) != 0)
3153
			goto out;
3154
		if (bcrypt_pbkdf(passphrase, strlen(passphrase), salt, slen,
3155
		    key, keylen + ivlen, rounds) < 0) {
3156
			r = SSH_ERR_INVALID_FORMAT;
3157
			goto out;
3158
		}
3159
	}
3160
3161
	/* check that an appropriate amount of auth data is present */
3162
21
	if (sshbuf_len(decoded) < encrypted_len + authlen) {
3163
		r = SSH_ERR_INVALID_FORMAT;
3164
		goto out;
3165
	}
3166
3167
	/* decrypt private portion of key */
3168

42
	if ((r = sshbuf_reserve(decrypted, encrypted_len, &dp)) != 0 ||
3169
21
	    (r = cipher_init(&ciphercontext, cipher, key, keylen,
3170
42
	    key + keylen, ivlen, 0)) != 0)
3171
		goto out;
3172
63
	if ((r = cipher_crypt(ciphercontext, 0, dp, sshbuf_ptr(decoded),
3173
42
	    encrypted_len, 0, authlen)) != 0) {
3174
		/* an integrity error here indicates an incorrect passphrase */
3175
		if (r == SSH_ERR_MAC_INVALID)
3176
			r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3177
		goto out;
3178
	}
3179
21
	if ((r = sshbuf_consume(decoded, encrypted_len + authlen)) != 0)
3180
		goto out;
3181
	/* there should be no trailing data */
3182
21
	if (sshbuf_len(decoded) != 0) {
3183
		r = SSH_ERR_INVALID_FORMAT;
3184
		goto out;
3185
	}
3186
3187
	/* check check bytes */
3188

42
	if ((r = sshbuf_get_u32(decrypted, &check1)) != 0 ||
3189
21
	    (r = sshbuf_get_u32(decrypted, &check2)) != 0)
3190
		goto out;
3191
21
	if (check1 != check2) {
3192
		r = SSH_ERR_KEY_WRONG_PASSPHRASE;
3193
		goto out;
3194
	}
3195
3196
	/* Load the private key and comment */
3197

42
	if ((r = sshkey_private_deserialize(decrypted, &k)) != 0 ||
3198
21
	    (r = sshbuf_get_cstring(decrypted, &comment, NULL)) != 0)
3199
		goto out;
3200
3201
	/* Check deterministic padding */
3202
	i = 0;
3203
84
	while (sshbuf_len(decrypted)) {
3204
42
		if ((r = sshbuf_get_u8(decrypted, &pad)) != 0)
3205
			goto out;
3206
42
		if (pad != (++i & 0xff)) {
3207
			r = SSH_ERR_INVALID_FORMAT;
3208
			goto out;
3209
		}
3210
	}
3211
3212
	/* XXX decode pubkey and check against private */
3213
3214
	/* success */
3215
	r = 0;
3216
21
	if (keyp != NULL) {
3217
21
		*keyp = k;
3218
21
		k = NULL;
3219
21
	}
3220
21
	if (commentp != NULL) {
3221
		*commentp = comment;
3222
		comment = NULL;
3223
	}
3224
 out:
3225
50
	pad = 0;
3226
50
	cipher_free(ciphercontext);
3227
50
	free(ciphername);
3228
50
	free(kdfname);
3229
50
	free(comment);
3230
50
	if (salt != NULL) {
3231
		explicit_bzero(salt, slen);
3232
		free(salt);
3233
	}
3234
50
	if (key != NULL) {
3235
21
		explicit_bzero(key, keylen + ivlen);
3236
21
		free(key);
3237
21
	}
3238
50
	sshbuf_free(encoded);
3239
50
	sshbuf_free(decoded);
3240
50
	sshbuf_free(kdf);
3241
50
	sshbuf_free(decrypted);
3242
50
	sshkey_free(k);
3243
50
	return r;
3244
50
}
3245
3246
3247
#ifdef WITH_OPENSSL
3248
/* convert SSH v2 key in OpenSSL PEM format */
3249
static int
3250
sshkey_private_pem_to_blob(struct sshkey *key, struct sshbuf *blob,
3251
    const char *_passphrase, const char *comment)
3252
{
3253
	int success, r;
3254
16
	int blen, len = strlen(_passphrase);
3255
8
	u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
3256
16
	const EVP_CIPHER *cipher = (len > 0) ? EVP_aes_128_cbc() : NULL;
3257
8
	const u_char *bptr;
3258
	BIO *bio = NULL;
3259
3260
8
	if (len > 0 && len <= 4)
3261
		return SSH_ERR_PASSPHRASE_TOO_SHORT;
3262
8
	if ((bio = BIO_new(BIO_s_mem())) == NULL)
3263
		return SSH_ERR_ALLOC_FAIL;
3264
3265

8
	switch (key->type) {
3266
	case KEY_DSA:
3267
2
		success = PEM_write_bio_DSAPrivateKey(bio, key->dsa,
3268
		    cipher, passphrase, len, NULL, NULL);
3269
2
		break;
3270
	case KEY_ECDSA:
3271
2
		success = PEM_write_bio_ECPrivateKey(bio, key->ecdsa,
3272
		    cipher, passphrase, len, NULL, NULL);
3273
2
		break;
3274
	case KEY_RSA:
3275
4
		success = PEM_write_bio_RSAPrivateKey(bio, key->rsa,
3276
		    cipher, passphrase, len, NULL, NULL);
3277
4
		break;
3278
	default:
3279
		success = 0;
3280
		break;
3281
	}
3282
8
	if (success == 0) {
3283
		r = SSH_ERR_LIBCRYPTO_ERROR;
3284
		goto out;
3285
	}
3286
8
	if ((blen = BIO_get_mem_data(bio, &bptr)) <= 0) {
3287
		r = SSH_ERR_INTERNAL_ERROR;
3288
		goto out;
3289
	}
3290
8
	if ((r = sshbuf_put(blob, bptr, blen)) != 0)
3291
		goto out;
3292
	r = 0;
3293
 out:
3294
8
	BIO_free(bio);
3295
8
	return r;
3296
8
}
3297
#endif /* WITH_OPENSSL */
3298
3299
/* Serialise "key" to buffer "blob" */
3300
int
3301
sshkey_private_to_fileblob(struct sshkey *key, struct sshbuf *blob,
3302
    const char *passphrase, const char *comment,
3303
    int force_new_format, const char *new_format_cipher, int new_format_rounds)
3304
{
3305

26
	switch (key->type) {
3306
#ifdef WITH_OPENSSL
3307
	case KEY_DSA:
3308
	case KEY_ECDSA:
3309
	case KEY_RSA:
3310
8
		if (force_new_format) {
3311
			return sshkey_private_to_blob2(key, blob, passphrase,
3312
			    comment, new_format_cipher, new_format_rounds);
3313
		}
3314
8
		return sshkey_private_pem_to_blob(key, blob,
3315
		    passphrase, comment);
3316
#endif /* WITH_OPENSSL */
3317
	case KEY_ED25519:
3318
5
		return sshkey_private_to_blob2(key, blob, passphrase,
3319
		    comment, new_format_cipher, new_format_rounds);
3320
	default:
3321
		return SSH_ERR_KEY_TYPE_UNKNOWN;
3322
	}
3323
13
}
3324
3325
3326
#ifdef WITH_OPENSSL
3327
static int
3328
translate_libcrypto_error(unsigned long pem_err)
3329
{
3330
	int pem_reason = ERR_GET_REASON(pem_err);
3331
3332
	switch (ERR_GET_LIB(pem_err)) {
3333
	case ERR_LIB_PEM:
3334
		switch (pem_reason) {
3335
		case PEM_R_BAD_PASSWORD_READ:
3336
		case PEM_R_PROBLEMS_GETTING_PASSWORD:
3337
		case PEM_R_BAD_DECRYPT:
3338
			return SSH_ERR_KEY_WRONG_PASSPHRASE;
3339
		default:
3340
			return SSH_ERR_INVALID_FORMAT;
3341
		}
3342
	case ERR_LIB_EVP:
3343
		switch (pem_reason) {
3344
		case EVP_R_BAD_DECRYPT:
3345
			return SSH_ERR_KEY_WRONG_PASSPHRASE;
3346
		case EVP_R_BN_DECODE_ERROR:
3347
		case EVP_R_DECODE_ERROR:
3348
#ifdef EVP_R_PRIVATE_KEY_DECODE_ERROR
3349
		case EVP_R_PRIVATE_KEY_DECODE_ERROR:
3350
#endif
3351
			return SSH_ERR_INVALID_FORMAT;
3352
		default:
3353
			return SSH_ERR_LIBCRYPTO_ERROR;
3354
		}
3355
	case ERR_LIB_ASN1:
3356
		return SSH_ERR_INVALID_FORMAT;
3357
	}
3358
	return SSH_ERR_LIBCRYPTO_ERROR;
3359
}
3360
3361
static void
3362
clear_libcrypto_errors(void)
3363
{
3364
87
	while (ERR_get_error() != 0)
3365
		;
3366
29
}
3367
3368
/*
3369
 * Translate OpenSSL error codes to determine whether
3370
 * passphrase is required/incorrect.
3371
 */
3372
static int
3373
convert_libcrypto_error(void)
3374
{
3375
	/*
3376
	 * Some password errors are reported at the beginning
3377
	 * of the error queue.
3378
	 */
3379
	if (translate_libcrypto_error(ERR_peek_error()) ==
3380
	    SSH_ERR_KEY_WRONG_PASSPHRASE)
3381
		return SSH_ERR_KEY_WRONG_PASSPHRASE;
3382
	return translate_libcrypto_error(ERR_peek_last_error());
3383
}
3384
3385
static int
3386
sshkey_parse_private_pem_fileblob(struct sshbuf *blob, int type,
3387
    const char *passphrase, struct sshkey **keyp)
3388
{
3389
	EVP_PKEY *pk = NULL;
3390
	struct sshkey *prv = NULL;
3391
	BIO *bio = NULL;
3392
	int r;
3393
3394
58
	if (keyp != NULL)
3395
29
		*keyp = NULL;
3396
3397

58
	if ((bio = BIO_new(BIO_s_mem())) == NULL || sshbuf_len(blob) > INT_MAX)
3398
		return SSH_ERR_ALLOC_FAIL;
3399
58
	if (BIO_write(bio, sshbuf_ptr(blob), sshbuf_len(blob)) !=
3400
29
	    (int)sshbuf_len(blob)) {
3401
		r = SSH_ERR_ALLOC_FAIL;
3402
		goto out;
3403
	}
3404
3405
29
	clear_libcrypto_errors();
3406
58
	if ((pk = PEM_read_bio_PrivateKey(bio, NULL, NULL,
3407
29
	    (char *)passphrase)) == NULL) {
3408
		r = convert_libcrypto_error();
3409
		goto out;
3410
	}
3411
29
	if (pk->type == EVP_PKEY_RSA &&
3412
25
	    (type == KEY_UNSPEC || type == KEY_RSA)) {
3413
25
		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3414
			r = SSH_ERR_ALLOC_FAIL;
3415
			goto out;
3416
		}
3417
25
		prv->rsa = EVP_PKEY_get1_RSA(pk);
3418
25
		prv->type = KEY_RSA;
3419
#ifdef DEBUG_PK
3420
		RSA_print_fp(stderr, prv->rsa, 8);
3421
#endif
3422
25
		if (RSA_blinding_on(prv->rsa, NULL) != 1) {
3423
			r = SSH_ERR_LIBCRYPTO_ERROR;
3424
			goto out;
3425
		}
3426
25
		if (BN_num_bits(prv->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
3427
			r = SSH_ERR_KEY_LENGTH;
3428
			goto out;
3429
		}
3430
4
	} else if (pk->type == EVP_PKEY_DSA &&
3431
4
	    (type == KEY_UNSPEC || type == KEY_DSA)) {
3432
4
		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3433
			r = SSH_ERR_ALLOC_FAIL;
3434
			goto out;
3435
		}
3436
4
		prv->dsa = EVP_PKEY_get1_DSA(pk);
3437
4
		prv->type = KEY_DSA;
3438
#ifdef DEBUG_PK
3439
		DSA_print_fp(stderr, prv->dsa, 8);
3440
#endif
3441
4
	} else if (pk->type == EVP_PKEY_EC &&
3442
	    (type == KEY_UNSPEC || type == KEY_ECDSA)) {
3443
		if ((prv = sshkey_new(KEY_UNSPEC)) == NULL) {
3444
			r = SSH_ERR_ALLOC_FAIL;
3445
			goto out;
3446
		}
3447
		prv->ecdsa = EVP_PKEY_get1_EC_KEY(pk);
3448
		prv->type = KEY_ECDSA;
3449
		prv->ecdsa_nid = sshkey_ecdsa_key_to_nid(prv->ecdsa);
3450
		if (prv->ecdsa_nid == -1 ||
3451
		    sshkey_curve_nid_to_name(prv->ecdsa_nid) == NULL ||
3452
		    sshkey_ec_validate_public(EC_KEY_get0_group(prv->ecdsa),
3453
		    EC_KEY_get0_public_key(prv->ecdsa)) != 0 ||
3454
		    sshkey_ec_validate_private(prv->ecdsa) != 0) {
3455
			r = SSH_ERR_INVALID_FORMAT;
3456
			goto out;
3457
		}
3458
#ifdef DEBUG_PK
3459
		if (prv != NULL && prv->ecdsa != NULL)
3460
			sshkey_dump_ec_key(prv->ecdsa);
3461
#endif
3462
	} else {
3463
		r = SSH_ERR_INVALID_FORMAT;
3464
		goto out;
3465
	}
3466
	r = 0;
3467
29
	if (keyp != NULL) {
3468
29
		*keyp = prv;
3469
		prv = NULL;
3470
29
	}
3471
 out:
3472
29
	BIO_free(bio);
3473
29
	if (pk != NULL)
3474
29
		EVP_PKEY_free(pk);
3475
29
	sshkey_free(prv);
3476
29
	return r;
3477
29
}
3478
#endif /* WITH_OPENSSL */
3479
3480
int
3481
sshkey_parse_private_fileblob_type(struct sshbuf *blob, int type,
3482
    const char *passphrase, struct sshkey **keyp, char **commentp)
3483
{
3484
	int r = SSH_ERR_INTERNAL_ERROR;
3485
3486
100
	if (keyp != NULL)
3487
50
		*keyp = NULL;
3488
50
	if (commentp != NULL)
3489
		*commentp = NULL;
3490
3491

50
	switch (type) {
3492
#ifdef WITH_OPENSSL
3493
	case KEY_DSA:
3494
	case KEY_ECDSA:
3495
	case KEY_RSA:
3496
		return sshkey_parse_private_pem_fileblob(blob, type,
3497
		    passphrase, keyp);
3498
#endif /* WITH_OPENSSL */
3499
	case KEY_ED25519:
3500
		return sshkey_parse_private2(blob, type, passphrase,
3501
		    keyp, commentp);
3502
	case KEY_UNSPEC:
3503
50
		r = sshkey_parse_private2(blob, type, passphrase, keyp,
3504
		    commentp);
3505
		/* Do not fallback to PEM parser if only passphrase is wrong. */
3506
50
		if (r == 0 || r == SSH_ERR_KEY_WRONG_PASSPHRASE)
3507
21
			return r;
3508
#ifdef WITH_OPENSSL
3509
29
		return sshkey_parse_private_pem_fileblob(blob, type,
3510
		    passphrase, keyp);
3511
#else
3512
		return SSH_ERR_INVALID_FORMAT;
3513
#endif /* WITH_OPENSSL */
3514
	default:
3515
		return SSH_ERR_KEY_TYPE_UNKNOWN;
3516
	}
3517
50
}
3518
3519
int
3520
sshkey_parse_private_fileblob(struct sshbuf *buffer, const char *passphrase,
3521
    struct sshkey **keyp, char **commentp)
3522
{
3523
100
	if (keyp != NULL)
3524
50
		*keyp = NULL;
3525
50
	if (commentp != NULL)
3526
		*commentp = NULL;
3527
3528
50
	return sshkey_parse_private_fileblob_type(buffer, KEY_UNSPEC,
3529
	    passphrase, keyp, commentp);
3530
}