1 /*
2 * Public Key layer for parsing key files and structures
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 */
7
8 #include "common.h"
9
10 #if defined(MBEDTLS_PK_PARSE_C)
11
12 #include "mbedtls/pk.h"
13 #include "mbedtls/asn1.h"
14 #include "mbedtls/oid.h"
15 #include "mbedtls/platform_util.h"
16 #include "mbedtls/error.h"
17 #include "pk_internal.h"
18
19 #include <string.h>
20
21 #if defined(MBEDTLS_RSA_C)
22 #include "mbedtls/rsa.h"
23 #endif
24 #include "mbedtls/ecp.h"
25 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
26 #include "pk_internal.h"
27 #endif
28 #if defined(MBEDTLS_ECDSA_C)
29 #include "mbedtls/ecdsa.h"
30 #endif
31 #if defined(MBEDTLS_PEM_PARSE_C)
32 #include "mbedtls/pem.h"
33 #endif
34 #if defined(MBEDTLS_PKCS5_C)
35 #include "mbedtls/pkcs5.h"
36 #endif
37 #if defined(MBEDTLS_PKCS12_C)
38 #include "mbedtls/pkcs12.h"
39 #endif
40
41 #if defined(MBEDTLS_PSA_CRYPTO_C)
42 #include "psa_util_internal.h"
43 #endif
44
45 #if defined(MBEDTLS_USE_PSA_CRYPTO)
46 #include "psa/crypto.h"
47 #endif
48
49 #include "mbedtls/platform.h"
50
51 /* Helper for Montgomery curves */
52 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS) && defined(MBEDTLS_PK_HAVE_RFC8410_CURVES)
53 #define MBEDTLS_PK_IS_RFC8410_GROUP_ID(id) \
54 ((id == MBEDTLS_ECP_DP_CURVE25519) || (id == MBEDTLS_ECP_DP_CURVE448))
55 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS && MBEDTLS_PK_HAVE_RFC8410_CURVES */
56
57 #if defined(MBEDTLS_FS_IO)
58 /*
59 * Load all data from a file into a given buffer.
60 *
61 * The file is expected to contain either PEM or DER encoded data.
62 * A terminating null byte is always appended. It is included in the announced
63 * length only if the data looks like it is PEM encoded.
64 */
mbedtls_pk_load_file(const char * path,unsigned char ** buf,size_t * n)65 int mbedtls_pk_load_file(const char *path, unsigned char **buf, size_t *n)
66 {
67 FILE *f;
68 long size;
69
70 if ((f = fopen(path, "rb")) == NULL) {
71 return MBEDTLS_ERR_PK_FILE_IO_ERROR;
72 }
73
74 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
75 mbedtls_setbuf(f, NULL);
76
77 fseek(f, 0, SEEK_END);
78 if ((size = ftell(f)) == -1) {
79 fclose(f);
80 return MBEDTLS_ERR_PK_FILE_IO_ERROR;
81 }
82 fseek(f, 0, SEEK_SET);
83
84 *n = (size_t) size;
85
86 if (*n + 1 == 0 ||
87 (*buf = mbedtls_calloc(1, *n + 1)) == NULL) {
88 fclose(f);
89 return MBEDTLS_ERR_PK_ALLOC_FAILED;
90 }
91
92 if (fread(*buf, 1, *n, f) != *n) {
93 fclose(f);
94
95 mbedtls_zeroize_and_free(*buf, *n);
96
97 return MBEDTLS_ERR_PK_FILE_IO_ERROR;
98 }
99
100 fclose(f);
101
102 (*buf)[*n] = '\0';
103
104 if (strstr((const char *) *buf, "-----BEGIN ") != NULL) {
105 ++*n;
106 }
107
108 return 0;
109 }
110
111 /*
112 * Load and parse a private key
113 */
mbedtls_pk_parse_keyfile(mbedtls_pk_context * ctx,const char * path,const char * pwd,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)114 int mbedtls_pk_parse_keyfile(mbedtls_pk_context *ctx,
115 const char *path, const char *pwd,
116 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
117 {
118 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
119 size_t n;
120 unsigned char *buf;
121
122 if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
123 return ret;
124 }
125
126 if (pwd == NULL) {
127 ret = mbedtls_pk_parse_key(ctx, buf, n, NULL, 0, f_rng, p_rng);
128 } else {
129 ret = mbedtls_pk_parse_key(ctx, buf, n,
130 (const unsigned char *) pwd, strlen(pwd), f_rng, p_rng);
131 }
132
133 mbedtls_zeroize_and_free(buf, n);
134
135 return ret;
136 }
137
138 /*
139 * Load and parse a public key
140 */
mbedtls_pk_parse_public_keyfile(mbedtls_pk_context * ctx,const char * path)141 int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path)
142 {
143 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
144 size_t n;
145 unsigned char *buf;
146
147 if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
148 return ret;
149 }
150
151 ret = mbedtls_pk_parse_public_key(ctx, buf, n);
152
153 mbedtls_zeroize_and_free(buf, n);
154
155 return ret;
156 }
157 #endif /* MBEDTLS_FS_IO */
158
159 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
160 /* Minimally parse an ECParameters buffer to and mbedtls_asn1_buf
161 *
162 * ECParameters ::= CHOICE {
163 * namedCurve OBJECT IDENTIFIER
164 * specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... }
165 * -- implicitCurve NULL
166 * }
167 */
pk_get_ecparams(unsigned char ** p,const unsigned char * end,mbedtls_asn1_buf * params)168 static int pk_get_ecparams(unsigned char **p, const unsigned char *end,
169 mbedtls_asn1_buf *params)
170 {
171 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
172
173 if (end - *p < 1) {
174 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
175 MBEDTLS_ERR_ASN1_OUT_OF_DATA);
176 }
177
178 /* Tag may be either OID or SEQUENCE */
179 params->tag = **p;
180 if (params->tag != MBEDTLS_ASN1_OID
181 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
182 && params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)
183 #endif
184 ) {
185 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
186 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
187 }
188
189 if ((ret = mbedtls_asn1_get_tag(p, end, ¶ms->len, params->tag)) != 0) {
190 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
191 }
192
193 params->p = *p;
194 *p += params->len;
195
196 if (*p != end) {
197 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
198 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
199 }
200
201 return 0;
202 }
203
204 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
205 /*
206 * Parse a SpecifiedECDomain (SEC 1 C.2) and (mostly) fill the group with it.
207 * WARNING: the resulting group should only be used with
208 * pk_group_id_from_specified(), since its base point may not be set correctly
209 * if it was encoded compressed.
210 *
211 * SpecifiedECDomain ::= SEQUENCE {
212 * version SpecifiedECDomainVersion(ecdpVer1 | ecdpVer2 | ecdpVer3, ...),
213 * fieldID FieldID {{FieldTypes}},
214 * curve Curve,
215 * base ECPoint,
216 * order INTEGER,
217 * cofactor INTEGER OPTIONAL,
218 * hash HashAlgorithm OPTIONAL,
219 * ...
220 * }
221 *
222 * We only support prime-field as field type, and ignore hash and cofactor.
223 */
pk_group_from_specified(const mbedtls_asn1_buf * params,mbedtls_ecp_group * grp)224 static int pk_group_from_specified(const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp)
225 {
226 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
227 unsigned char *p = params->p;
228 const unsigned char *const end = params->p + params->len;
229 const unsigned char *end_field, *end_curve;
230 size_t len;
231 int ver;
232
233 /* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */
234 if ((ret = mbedtls_asn1_get_int(&p, end, &ver)) != 0) {
235 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
236 }
237
238 if (ver < 1 || ver > 3) {
239 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
240 }
241
242 /*
243 * FieldID { FIELD-ID:IOSet } ::= SEQUENCE { -- Finite field
244 * fieldType FIELD-ID.&id({IOSet}),
245 * parameters FIELD-ID.&Type({IOSet}{@fieldType})
246 * }
247 */
248 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
249 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
250 return ret;
251 }
252
253 end_field = p + len;
254
255 /*
256 * FIELD-ID ::= TYPE-IDENTIFIER
257 * FieldTypes FIELD-ID ::= {
258 * { Prime-p IDENTIFIED BY prime-field } |
259 * { Characteristic-two IDENTIFIED BY characteristic-two-field }
260 * }
261 * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }
262 */
263 if ((ret = mbedtls_asn1_get_tag(&p, end_field, &len, MBEDTLS_ASN1_OID)) != 0) {
264 return ret;
265 }
266
267 if (len != MBEDTLS_OID_SIZE(MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD) ||
268 memcmp(p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len) != 0) {
269 return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
270 }
271
272 p += len;
273
274 /* Prime-p ::= INTEGER -- Field of size p. */
275 if ((ret = mbedtls_asn1_get_mpi(&p, end_field, &grp->P)) != 0) {
276 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
277 }
278
279 grp->pbits = mbedtls_mpi_bitlen(&grp->P);
280
281 if (p != end_field) {
282 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
283 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
284 }
285
286 /*
287 * Curve ::= SEQUENCE {
288 * a FieldElement,
289 * b FieldElement,
290 * seed BIT STRING OPTIONAL
291 * -- Shall be present if used in SpecifiedECDomain
292 * -- with version equal to ecdpVer2 or ecdpVer3
293 * }
294 */
295 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
296 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
297 return ret;
298 }
299
300 end_curve = p + len;
301
302 /*
303 * FieldElement ::= OCTET STRING
304 * containing an integer in the case of a prime field
305 */
306 if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0 ||
307 (ret = mbedtls_mpi_read_binary(&grp->A, p, len)) != 0) {
308 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
309 }
310
311 p += len;
312
313 if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0 ||
314 (ret = mbedtls_mpi_read_binary(&grp->B, p, len)) != 0) {
315 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
316 }
317
318 p += len;
319
320 /* Ignore seed BIT STRING OPTIONAL */
321 if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING)) == 0) {
322 p += len;
323 }
324
325 if (p != end_curve) {
326 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
327 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
328 }
329
330 /*
331 * ECPoint ::= OCTET STRING
332 */
333 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
334 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
335 }
336
337 if ((ret = mbedtls_ecp_point_read_binary(grp, &grp->G,
338 (const unsigned char *) p, len)) != 0) {
339 /*
340 * If we can't read the point because it's compressed, cheat by
341 * reading only the X coordinate and the parity bit of Y.
342 */
343 if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ||
344 (p[0] != 0x02 && p[0] != 0x03) ||
345 len != mbedtls_mpi_size(&grp->P) + 1 ||
346 mbedtls_mpi_read_binary(&grp->G.X, p + 1, len - 1) != 0 ||
347 mbedtls_mpi_lset(&grp->G.Y, p[0] - 2) != 0 ||
348 mbedtls_mpi_lset(&grp->G.Z, 1) != 0) {
349 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
350 }
351 }
352
353 p += len;
354
355 /*
356 * order INTEGER
357 */
358 if ((ret = mbedtls_asn1_get_mpi(&p, end, &grp->N)) != 0) {
359 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
360 }
361
362 grp->nbits = mbedtls_mpi_bitlen(&grp->N);
363
364 /*
365 * Allow optional elements by purposefully not enforcing p == end here.
366 */
367
368 return 0;
369 }
370
371 /*
372 * Find the group id associated with an (almost filled) group as generated by
373 * pk_group_from_specified(), or return an error if unknown.
374 */
pk_group_id_from_group(const mbedtls_ecp_group * grp,mbedtls_ecp_group_id * grp_id)375 static int pk_group_id_from_group(const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id)
376 {
377 int ret = 0;
378 mbedtls_ecp_group ref;
379 const mbedtls_ecp_group_id *id;
380
381 mbedtls_ecp_group_init(&ref);
382
383 for (id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++) {
384 /* Load the group associated to that id */
385 mbedtls_ecp_group_free(&ref);
386 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&ref, *id));
387
388 /* Compare to the group we were given, starting with easy tests */
389 if (grp->pbits == ref.pbits && grp->nbits == ref.nbits &&
390 mbedtls_mpi_cmp_mpi(&grp->P, &ref.P) == 0 &&
391 mbedtls_mpi_cmp_mpi(&grp->A, &ref.A) == 0 &&
392 mbedtls_mpi_cmp_mpi(&grp->B, &ref.B) == 0 &&
393 mbedtls_mpi_cmp_mpi(&grp->N, &ref.N) == 0 &&
394 mbedtls_mpi_cmp_mpi(&grp->G.X, &ref.G.X) == 0 &&
395 mbedtls_mpi_cmp_mpi(&grp->G.Z, &ref.G.Z) == 0 &&
396 /* For Y we may only know the parity bit, so compare only that */
397 mbedtls_mpi_get_bit(&grp->G.Y, 0) == mbedtls_mpi_get_bit(&ref.G.Y, 0)) {
398 break;
399 }
400 }
401
402 cleanup:
403 mbedtls_ecp_group_free(&ref);
404
405 *grp_id = *id;
406
407 if (ret == 0 && *id == MBEDTLS_ECP_DP_NONE) {
408 ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
409 }
410
411 return ret;
412 }
413
414 /*
415 * Parse a SpecifiedECDomain (SEC 1 C.2) and find the associated group ID
416 */
pk_group_id_from_specified(const mbedtls_asn1_buf * params,mbedtls_ecp_group_id * grp_id)417 static int pk_group_id_from_specified(const mbedtls_asn1_buf *params,
418 mbedtls_ecp_group_id *grp_id)
419 {
420 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
421 mbedtls_ecp_group grp;
422
423 mbedtls_ecp_group_init(&grp);
424
425 if ((ret = pk_group_from_specified(params, &grp)) != 0) {
426 goto cleanup;
427 }
428
429 ret = pk_group_id_from_group(&grp, grp_id);
430
431 cleanup:
432 /* The API respecting lifecycle for mbedtls_ecp_group struct is
433 * _init(), _load() and _free(). In pk_group_id_from_specified() the
434 * temporary grp breaks that flow and it's members are populated
435 * by pk_group_id_from_group(). As such mbedtls_ecp_group_free()
436 * which is assuming a group populated by _setup() may not clean-up
437 * properly -> Manually free it's members.
438 */
439 mbedtls_mpi_free(&grp.N);
440 mbedtls_mpi_free(&grp.P);
441 mbedtls_mpi_free(&grp.A);
442 mbedtls_mpi_free(&grp.B);
443 mbedtls_ecp_point_free(&grp.G);
444
445 return ret;
446 }
447 #endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */
448
449 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
450 /* Functions pk_use_ecparams() and pk_use_ecparams_rfc8410() update the
451 * ecp_keypair structure with proper group ID. The purpose of this helper
452 * function is to update ec_family and ec_bits accordingly. */
pk_update_psa_ecparams(mbedtls_pk_context * pk,mbedtls_ecp_group_id grp_id)453 static int pk_update_psa_ecparams(mbedtls_pk_context *pk,
454 mbedtls_ecp_group_id grp_id)
455 {
456 psa_ecc_family_t ec_family;
457 size_t bits;
458
459 ec_family = mbedtls_ecc_group_to_psa(grp_id, &bits);
460
461 if ((pk->ec_family != 0) && (pk->ec_family != ec_family)) {
462 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
463 }
464
465 pk->ec_family = ec_family;
466 pk->ec_bits = bits;
467
468 return 0;
469 }
470 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
471
472 /*
473 * Use EC parameters to initialise an EC group
474 *
475 * ECParameters ::= CHOICE {
476 * namedCurve OBJECT IDENTIFIER
477 * specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... }
478 * -- implicitCurve NULL
479 */
pk_use_ecparams(const mbedtls_asn1_buf * params,mbedtls_pk_context * pk)480 static int pk_use_ecparams(const mbedtls_asn1_buf *params, mbedtls_pk_context *pk)
481 {
482 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
483 mbedtls_ecp_group_id grp_id;
484
485 if (params->tag == MBEDTLS_ASN1_OID) {
486 if (mbedtls_oid_get_ec_grp(params, &grp_id) != 0) {
487 return MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE;
488 }
489 } else {
490 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
491 if ((ret = pk_group_id_from_specified(params, &grp_id)) != 0) {
492 return ret;
493 }
494 #else
495 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
496 #endif
497 }
498
499 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
500 ret = pk_update_psa_ecparams(pk, grp_id);
501 #else
502 /* grp may already be initialized; if so, make sure IDs match */
503 if (mbedtls_pk_ec_ro(*pk)->grp.id != MBEDTLS_ECP_DP_NONE &&
504 mbedtls_pk_ec_ro(*pk)->grp.id != grp_id) {
505 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
506 }
507
508 if ((ret = mbedtls_ecp_group_load(&(mbedtls_pk_ec_rw(*pk)->grp),
509 grp_id)) != 0) {
510 return ret;
511 }
512 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
513
514 return ret;
515 }
516
517 /*
518 * Helper function for deriving a public key from its private counterpart.
519 */
pk_derive_public_key(mbedtls_pk_context * pk,const unsigned char * d,size_t d_len,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)520 static int pk_derive_public_key(mbedtls_pk_context *pk,
521 const unsigned char *d, size_t d_len,
522 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
523 {
524 int ret;
525 #if defined(MBEDTLS_USE_PSA_CRYPTO)
526 psa_status_t status;
527 (void) f_rng;
528 (void) p_rng;
529 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
530 (void) d;
531 (void) d_len;
532
533 status = psa_export_public_key(pk->priv_id, pk->pub_raw, sizeof(pk->pub_raw),
534 &pk->pub_raw_len);
535 ret = psa_pk_status_to_mbedtls(status);
536 #else /* MBEDTLS_PK_USE_PSA_EC_DATA */
537 mbedtls_ecp_keypair *eck = (mbedtls_ecp_keypair *) pk->pk_ctx;
538 unsigned char key_buf[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH];
539 size_t key_len;
540 mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
541 psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
542 size_t curve_bits;
543 psa_ecc_family_t curve = mbedtls_ecc_group_to_psa(eck->grp.id, &curve_bits);
544 psa_status_t destruction_status;
545
546 psa_set_key_type(&key_attr, PSA_KEY_TYPE_ECC_KEY_PAIR(curve));
547 psa_set_key_usage_flags(&key_attr, PSA_KEY_USAGE_EXPORT);
548
549 status = psa_import_key(&key_attr, d, d_len, &key_id);
550 ret = psa_pk_status_to_mbedtls(status);
551 if (ret != 0) {
552 return ret;
553 }
554
555 status = psa_export_public_key(key_id, key_buf, sizeof(key_buf), &key_len);
556 ret = psa_pk_status_to_mbedtls(status);
557 destruction_status = psa_destroy_key(key_id);
558 if (ret != 0) {
559 return ret;
560 } else if (destruction_status != PSA_SUCCESS) {
561 return psa_pk_status_to_mbedtls(destruction_status);
562 }
563 ret = mbedtls_ecp_point_read_binary(&eck->grp, &eck->Q, key_buf, key_len);
564 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
565 #else /* MBEDTLS_USE_PSA_CRYPTO */
566 mbedtls_ecp_keypair *eck = (mbedtls_ecp_keypair *) pk->pk_ctx;
567 (void) d;
568 (void) d_len;
569
570 ret = mbedtls_ecp_mul(&eck->grp, &eck->Q, &eck->d, &eck->grp.G, f_rng, p_rng);
571 #endif /* MBEDTLS_USE_PSA_CRYPTO */
572 return ret;
573 }
574
575 #if defined(MBEDTLS_PK_HAVE_RFC8410_CURVES)
576
577 /*
578 * Load an RFC8410 EC key, which doesn't have any parameters
579 */
pk_use_ecparams_rfc8410(const mbedtls_asn1_buf * params,mbedtls_ecp_group_id grp_id,mbedtls_pk_context * pk)580 static int pk_use_ecparams_rfc8410(const mbedtls_asn1_buf *params,
581 mbedtls_ecp_group_id grp_id,
582 mbedtls_pk_context *pk)
583 {
584 int ret;
585
586 if (params->tag != 0 || params->len != 0) {
587 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
588 }
589
590 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
591 ret = pk_update_psa_ecparams(pk, grp_id);
592 #else
593 mbedtls_ecp_keypair *ecp = mbedtls_pk_ec_rw(*pk);
594 ret = mbedtls_ecp_group_load(&(ecp->grp), grp_id);
595 if (ret != 0) {
596 return ret;
597 }
598 #endif
599 return ret;
600 }
601
602 /*
603 * Parse an RFC 8410 encoded private EC key
604 *
605 * CurvePrivateKey ::= OCTET STRING
606 */
pk_parse_key_rfc8410_der(mbedtls_pk_context * pk,unsigned char * key,size_t keylen,const unsigned char * end,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)607 static int pk_parse_key_rfc8410_der(mbedtls_pk_context *pk,
608 unsigned char *key, size_t keylen, const unsigned char *end,
609 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
610 {
611 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
612 size_t len;
613
614 if ((ret = mbedtls_asn1_get_tag(&key, (key + keylen), &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
615 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
616 }
617
618 if (key + len != end) {
619 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
620 }
621
622 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
623 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
624 psa_status_t status;
625
626 psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(pk->ec_family));
627 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT |
628 PSA_KEY_USAGE_DERIVE);
629 psa_set_key_algorithm(&attributes, PSA_ALG_ECDH);
630
631 status = psa_import_key(&attributes, key, len, &pk->priv_id);
632 if (status != PSA_SUCCESS) {
633 ret = psa_pk_status_to_mbedtls(status);
634 return ret;
635 }
636 #else /* MBEDTLS_PK_USE_PSA_EC_DATA */
637 mbedtls_ecp_keypair *eck = mbedtls_pk_ec_rw(*pk);
638
639 if ((ret = mbedtls_ecp_read_key(eck->grp.id, eck, key, len)) != 0) {
640 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
641 }
642 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
643
644 /* pk_parse_key_pkcs8_unencrypted_der() only supports version 1 PKCS8 keys,
645 * which never contain a public key. As such, derive the public key
646 * unconditionally. */
647 if ((ret = pk_derive_public_key(pk, key, len, f_rng, p_rng)) != 0) {
648 return ret;
649 }
650
651 return 0;
652 }
653 #endif /* MBEDTLS_PK_HAVE_RFC8410_CURVES */
654
655 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA) && defined(MBEDTLS_PK_PARSE_EC_COMPRESSED)
656 /*
657 * Create a temporary ecp_keypair for converting an EC point in compressed
658 * format to an uncompressed one
659 */
pk_convert_compressed_ec(mbedtls_pk_context * pk,const unsigned char * in_start,size_t in_len,size_t * out_buf_len,unsigned char * out_buf,size_t out_buf_size)660 static int pk_convert_compressed_ec(mbedtls_pk_context *pk,
661 const unsigned char *in_start, size_t in_len,
662 size_t *out_buf_len, unsigned char *out_buf,
663 size_t out_buf_size)
664 {
665 mbedtls_ecp_keypair ecp_key;
666 mbedtls_ecp_group_id ecp_group_id;
667 int ret;
668
669 ecp_group_id = mbedtls_ecc_group_of_psa(pk->ec_family, pk->ec_bits, 0);
670
671 mbedtls_ecp_keypair_init(&ecp_key);
672 ret = mbedtls_ecp_group_load(&(ecp_key.grp), ecp_group_id);
673 if (ret != 0) {
674 return ret;
675 }
676 ret = mbedtls_ecp_point_read_binary(&(ecp_key.grp), &ecp_key.Q,
677 in_start, in_len);
678 if (ret != 0) {
679 goto exit;
680 }
681 ret = mbedtls_ecp_point_write_binary(&(ecp_key.grp), &ecp_key.Q,
682 MBEDTLS_ECP_PF_UNCOMPRESSED,
683 out_buf_len, out_buf, out_buf_size);
684
685 exit:
686 mbedtls_ecp_keypair_free(&ecp_key);
687 return ret;
688 }
689 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA && MBEDTLS_PK_PARSE_EC_COMPRESSED */
690
691 /*
692 * EC public key is an EC point
693 *
694 * The caller is responsible for clearing the structure upon failure if
695 * desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE
696 * return code of mbedtls_ecp_point_read_binary() and leave p in a usable state.
697 */
pk_get_ecpubkey(unsigned char ** p,const unsigned char * end,mbedtls_pk_context * pk)698 static int pk_get_ecpubkey(unsigned char **p, const unsigned char *end,
699 mbedtls_pk_context *pk)
700 {
701 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
702
703 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
704 mbedtls_svc_key_id_t key;
705 psa_key_attributes_t key_attrs = PSA_KEY_ATTRIBUTES_INIT;
706 size_t len = (end - *p);
707
708 if (len > PSA_EXPORT_PUBLIC_KEY_MAX_SIZE) {
709 return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
710 }
711
712 /* Compressed point format are not supported yet by PSA crypto. As a
713 * consequence ecp functions are used to "convert" the point to
714 * uncompressed format */
715 if ((**p == 0x02) || (**p == 0x03)) {
716 #if defined(MBEDTLS_PK_PARSE_EC_COMPRESSED)
717 ret = pk_convert_compressed_ec(pk, *p, len,
718 &(pk->pub_raw_len), pk->pub_raw,
719 PSA_EXPORT_PUBLIC_KEY_MAX_SIZE);
720 if (ret != 0) {
721 return ret;
722 }
723 #else /* MBEDTLS_PK_PARSE_EC_COMPRESSED */
724 return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
725 #endif /* MBEDTLS_PK_PARSE_EC_COMPRESSED */
726 } else {
727 /* Uncompressed format */
728 if ((size_t) (end - *p) > MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN) {
729 return MBEDTLS_ERR_PK_BUFFER_TOO_SMALL;
730 }
731 memcpy(pk->pub_raw, *p, (end - *p));
732 pk->pub_raw_len = end - *p;
733 }
734
735 /* Validate the key by trying to importing it */
736 psa_set_key_usage_flags(&key_attrs, 0);
737 psa_set_key_algorithm(&key_attrs, PSA_ALG_ECDSA_ANY);
738 psa_set_key_type(&key_attrs, PSA_KEY_TYPE_ECC_PUBLIC_KEY(pk->ec_family));
739 psa_set_key_bits(&key_attrs, pk->ec_bits);
740
741 if ((psa_import_key(&key_attrs, pk->pub_raw, pk->pub_raw_len,
742 &key) != PSA_SUCCESS) ||
743 (psa_destroy_key(key) != PSA_SUCCESS)) {
744 mbedtls_platform_zeroize(pk->pub_raw, MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN);
745 pk->pub_raw_len = 0;
746 return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
747 }
748 ret = 0;
749 #else /* MBEDTLS_PK_USE_PSA_EC_DATA */
750 mbedtls_ecp_keypair *ec_key = (mbedtls_ecp_keypair *) pk->pk_ctx;
751 if ((ret = mbedtls_ecp_point_read_binary(&ec_key->grp, &ec_key->Q,
752 (const unsigned char *) *p,
753 end - *p)) == 0) {
754 ret = mbedtls_ecp_check_pubkey(&ec_key->grp, &ec_key->Q);
755 }
756 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
757
758 /*
759 * We know mbedtls_ecp_point_read_binary consumed all bytes or failed
760 */
761 *p = (unsigned char *) end;
762
763 return ret;
764 }
765 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
766
767 #if defined(MBEDTLS_RSA_C)
768 /*
769 * RSAPublicKey ::= SEQUENCE {
770 * modulus INTEGER, -- n
771 * publicExponent INTEGER -- e
772 * }
773 */
pk_get_rsapubkey(unsigned char ** p,const unsigned char * end,mbedtls_rsa_context * rsa)774 static int pk_get_rsapubkey(unsigned char **p,
775 const unsigned char *end,
776 mbedtls_rsa_context *rsa)
777 {
778 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
779 size_t len;
780
781 if ((ret = mbedtls_asn1_get_tag(p, end, &len,
782 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
783 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
784 }
785
786 if (*p + len != end) {
787 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
788 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
789 }
790
791 /* Import N */
792 if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
793 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
794 }
795
796 if ((ret = mbedtls_rsa_import_raw(rsa, *p, len, NULL, 0, NULL, 0,
797 NULL, 0, NULL, 0)) != 0) {
798 return MBEDTLS_ERR_PK_INVALID_PUBKEY;
799 }
800
801 *p += len;
802
803 /* Import E */
804 if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
805 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
806 }
807
808 if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
809 NULL, 0, *p, len)) != 0) {
810 return MBEDTLS_ERR_PK_INVALID_PUBKEY;
811 }
812
813 *p += len;
814
815 if (mbedtls_rsa_complete(rsa) != 0 ||
816 mbedtls_rsa_check_pubkey(rsa) != 0) {
817 return MBEDTLS_ERR_PK_INVALID_PUBKEY;
818 }
819
820 if (*p != end) {
821 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
822 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
823 }
824
825 return 0;
826 }
827 #endif /* MBEDTLS_RSA_C */
828
829 /* Get a PK algorithm identifier
830 *
831 * AlgorithmIdentifier ::= SEQUENCE {
832 * algorithm OBJECT IDENTIFIER,
833 * parameters ANY DEFINED BY algorithm OPTIONAL }
834 */
pk_get_pk_alg(unsigned char ** p,const unsigned char * end,mbedtls_pk_type_t * pk_alg,mbedtls_asn1_buf * params,mbedtls_ecp_group_id * ec_grp_id)835 static int pk_get_pk_alg(unsigned char **p,
836 const unsigned char *end,
837 mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params,
838 mbedtls_ecp_group_id *ec_grp_id)
839 {
840 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
841 mbedtls_asn1_buf alg_oid;
842
843 memset(params, 0, sizeof(mbedtls_asn1_buf));
844
845 if ((ret = mbedtls_asn1_get_alg(p, end, &alg_oid, params)) != 0) {
846 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_ALG, ret);
847 }
848
849 ret = mbedtls_oid_get_pk_alg(&alg_oid, pk_alg);
850 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
851 if (ret == MBEDTLS_ERR_OID_NOT_FOUND) {
852 ret = mbedtls_oid_get_ec_grp_algid(&alg_oid, ec_grp_id);
853 if (ret == 0) {
854 *pk_alg = MBEDTLS_PK_ECKEY;
855 }
856 }
857 #else
858 (void) ec_grp_id;
859 #endif
860 if (ret != 0) {
861 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
862 }
863
864 /*
865 * No parameters with RSA (only for EC)
866 */
867 if (*pk_alg == MBEDTLS_PK_RSA &&
868 ((params->tag != MBEDTLS_ASN1_NULL && params->tag != 0) ||
869 params->len != 0)) {
870 return MBEDTLS_ERR_PK_INVALID_ALG;
871 }
872
873 return 0;
874 }
875
876 /*
877 * SubjectPublicKeyInfo ::= SEQUENCE {
878 * algorithm AlgorithmIdentifier,
879 * subjectPublicKey BIT STRING }
880 */
mbedtls_pk_parse_subpubkey(unsigned char ** p,const unsigned char * end,mbedtls_pk_context * pk)881 int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
882 mbedtls_pk_context *pk)
883 {
884 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
885 size_t len;
886 mbedtls_asn1_buf alg_params;
887 mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
888 mbedtls_ecp_group_id ec_grp_id = MBEDTLS_ECP_DP_NONE;
889 const mbedtls_pk_info_t *pk_info;
890
891 if ((ret = mbedtls_asn1_get_tag(p, end, &len,
892 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
893 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
894 }
895
896 end = *p + len;
897
898 if ((ret = pk_get_pk_alg(p, end, &pk_alg, &alg_params, &ec_grp_id)) != 0) {
899 return ret;
900 }
901
902 if ((ret = mbedtls_asn1_get_bitstring_null(p, end, &len)) != 0) {
903 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
904 }
905
906 if (*p + len != end) {
907 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
908 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
909 }
910
911 if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
912 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
913 }
914
915 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
916 return ret;
917 }
918
919 #if defined(MBEDTLS_RSA_C)
920 if (pk_alg == MBEDTLS_PK_RSA) {
921 ret = pk_get_rsapubkey(p, end, mbedtls_pk_rsa(*pk));
922 } else
923 #endif /* MBEDTLS_RSA_C */
924 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
925 if (pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY) {
926 #if defined(MBEDTLS_PK_HAVE_RFC8410_CURVES)
927 if (MBEDTLS_PK_IS_RFC8410_GROUP_ID(ec_grp_id)) {
928 ret = pk_use_ecparams_rfc8410(&alg_params, ec_grp_id, pk);
929 } else
930 #endif
931 {
932 ret = pk_use_ecparams(&alg_params, pk);
933 }
934 if (ret == 0) {
935 ret = pk_get_ecpubkey(p, end, pk);
936 }
937 } else
938 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
939 ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
940
941 if (ret == 0 && *p != end) {
942 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
943 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
944 }
945
946 if (ret != 0) {
947 mbedtls_pk_free(pk);
948 }
949
950 return ret;
951 }
952
953 #if defined(MBEDTLS_RSA_C)
954 /*
955 * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
956 *
957 * The value zero is:
958 * - never a valid value for an RSA parameter
959 * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
960 *
961 * Since values can't be omitted in PKCS#1, passing a zero value to
962 * rsa_complete() would be incorrect, so reject zero values early.
963 */
asn1_get_nonzero_mpi(unsigned char ** p,const unsigned char * end,mbedtls_mpi * X)964 static int asn1_get_nonzero_mpi(unsigned char **p,
965 const unsigned char *end,
966 mbedtls_mpi *X)
967 {
968 int ret;
969
970 ret = mbedtls_asn1_get_mpi(p, end, X);
971 if (ret != 0) {
972 return ret;
973 }
974
975 if (mbedtls_mpi_cmp_int(X, 0) == 0) {
976 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
977 }
978
979 return 0;
980 }
981
982 /*
983 * Parse a PKCS#1 encoded private RSA key
984 */
pk_parse_key_pkcs1_der(mbedtls_rsa_context * rsa,const unsigned char * key,size_t keylen)985 static int pk_parse_key_pkcs1_der(mbedtls_rsa_context *rsa,
986 const unsigned char *key,
987 size_t keylen)
988 {
989 int ret, version;
990 size_t len;
991 unsigned char *p, *end;
992
993 mbedtls_mpi T;
994 mbedtls_mpi_init(&T);
995
996 p = (unsigned char *) key;
997 end = p + keylen;
998
999 /*
1000 * This function parses the RSAPrivateKey (PKCS#1)
1001 *
1002 * RSAPrivateKey ::= SEQUENCE {
1003 * version Version,
1004 * modulus INTEGER, -- n
1005 * publicExponent INTEGER, -- e
1006 * privateExponent INTEGER, -- d
1007 * prime1 INTEGER, -- p
1008 * prime2 INTEGER, -- q
1009 * exponent1 INTEGER, -- d mod (p-1)
1010 * exponent2 INTEGER, -- d mod (q-1)
1011 * coefficient INTEGER, -- (inverse of q) mod p
1012 * otherPrimeInfos OtherPrimeInfos OPTIONAL
1013 * }
1014 */
1015 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1016 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1017 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1018 }
1019
1020 end = p + len;
1021
1022 if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
1023 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1024 }
1025
1026 if (version != 0) {
1027 return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
1028 }
1029
1030 /* Import N */
1031 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1032 (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
1033 NULL, NULL)) != 0) {
1034 goto cleanup;
1035 }
1036
1037 /* Import E */
1038 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1039 (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
1040 NULL, &T)) != 0) {
1041 goto cleanup;
1042 }
1043
1044 /* Import D */
1045 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1046 (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
1047 &T, NULL)) != 0) {
1048 goto cleanup;
1049 }
1050
1051 /* Import P */
1052 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1053 (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
1054 NULL, NULL)) != 0) {
1055 goto cleanup;
1056 }
1057
1058 /* Import Q */
1059 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1060 (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
1061 NULL, NULL)) != 0) {
1062 goto cleanup;
1063 }
1064
1065 #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
1066 /*
1067 * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
1068 * that they can be easily recomputed from D, P and Q. However by
1069 * parsing them from the PKCS1 structure it is possible to avoid
1070 * recalculating them which both reduces the overhead of loading
1071 * RSA private keys into memory and also avoids side channels which
1072 * can arise when computing those values, since all of D, P, and Q
1073 * are secret. See https://eprint.iacr.org/2020/055 for a
1074 * description of one such attack.
1075 */
1076
1077 /* Import DP */
1078 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1079 (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
1080 goto cleanup;
1081 }
1082
1083 /* Import DQ */
1084 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1085 (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
1086 goto cleanup;
1087 }
1088
1089 /* Import QP */
1090 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1091 (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
1092 goto cleanup;
1093 }
1094
1095 #else
1096 /* Verify existence of the CRT params */
1097 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1098 (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
1099 (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0) {
1100 goto cleanup;
1101 }
1102 #endif
1103
1104 /* rsa_complete() doesn't complete anything with the default
1105 * implementation but is still called:
1106 * - for the benefit of alternative implementation that may want to
1107 * pre-compute stuff beyond what's provided (eg Montgomery factors)
1108 * - as is also sanity-checks the key
1109 *
1110 * Furthermore, we also check the public part for consistency with
1111 * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
1112 */
1113 if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
1114 (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
1115 goto cleanup;
1116 }
1117
1118 if (p != end) {
1119 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1120 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1121 }
1122
1123 cleanup:
1124
1125 mbedtls_mpi_free(&T);
1126
1127 if (ret != 0) {
1128 /* Wrap error code if it's coming from a lower level */
1129 if ((ret & 0xff80) == 0) {
1130 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1131 } else {
1132 ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1133 }
1134
1135 mbedtls_rsa_free(rsa);
1136 }
1137
1138 return ret;
1139 }
1140 #endif /* MBEDTLS_RSA_C */
1141
1142 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
1143 /*
1144 * Parse a SEC1 encoded private EC key
1145 */
pk_parse_key_sec1_der(mbedtls_pk_context * pk,const unsigned char * key,size_t keylen,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1146 static int pk_parse_key_sec1_der(mbedtls_pk_context *pk,
1147 const unsigned char *key, size_t keylen,
1148 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1149 {
1150 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1151 int version, pubkey_done;
1152 size_t len, d_len;
1153 mbedtls_asn1_buf params = { 0, 0, NULL };
1154 unsigned char *p = (unsigned char *) key;
1155 unsigned char *d;
1156 unsigned char *end = p + keylen;
1157 unsigned char *end2;
1158 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
1159 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1160 psa_status_t status;
1161 #else /* MBEDTLS_PK_USE_PSA_EC_DATA */
1162 mbedtls_ecp_keypair *eck = mbedtls_pk_ec_rw(*pk);
1163 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
1164
1165 /*
1166 * RFC 5915, or SEC1 Appendix C.4
1167 *
1168 * ECPrivateKey ::= SEQUENCE {
1169 * version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
1170 * privateKey OCTET STRING,
1171 * parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
1172 * publicKey [1] BIT STRING OPTIONAL
1173 * }
1174 */
1175 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1176 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1177 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1178 }
1179
1180 end = p + len;
1181
1182 if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
1183 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1184 }
1185
1186 if (version != 1) {
1187 return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
1188 }
1189
1190 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1191 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1192 }
1193
1194 /* Keep a reference to the position fo the private key. It will be used
1195 * later in this function. */
1196 d = p;
1197 d_len = len;
1198
1199 p += len;
1200
1201 pubkey_done = 0;
1202 if (p != end) {
1203 /*
1204 * Is 'parameters' present?
1205 */
1206 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1207 MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
1208 0)) == 0) {
1209 if ((ret = pk_get_ecparams(&p, p + len, ¶ms)) != 0 ||
1210 (ret = pk_use_ecparams(¶ms, pk)) != 0) {
1211 return ret;
1212 }
1213 } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
1214 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1215 }
1216 }
1217
1218
1219 #if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
1220 if ((ret = mbedtls_ecp_read_key(eck->grp.id, eck, d, d_len)) != 0) {
1221 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1222 }
1223 #endif
1224
1225 if (p != end) {
1226 /*
1227 * Is 'publickey' present? If not, or if we can't read it (eg because it
1228 * is compressed), create it from the private key.
1229 */
1230 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1231 MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
1232 1)) == 0) {
1233 end2 = p + len;
1234
1235 if ((ret = mbedtls_asn1_get_bitstring_null(&p, end2, &len)) != 0) {
1236 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1237 }
1238
1239 if (p + len != end2) {
1240 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1241 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1242 }
1243
1244 if ((ret = pk_get_ecpubkey(&p, end2, pk)) == 0) {
1245 pubkey_done = 1;
1246 } else {
1247 /*
1248 * The only acceptable failure mode of pk_get_ecpubkey() above
1249 * is if the point format is not recognized.
1250 */
1251 if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) {
1252 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1253 }
1254 }
1255 } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
1256 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1257 }
1258 }
1259
1260 #if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
1261 psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(pk->ec_family));
1262 /* Setting largest masks for usage and key algorithms */
1263 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH |
1264 PSA_KEY_USAGE_SIGN_MESSAGE |
1265 PSA_KEY_USAGE_EXPORT | PSA_KEY_USAGE_DERIVE);
1266 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
1267 psa_set_key_algorithm(&attributes,
1268 PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_ANY_HASH));
1269 #else
1270 psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
1271 #endif
1272 psa_set_key_enrollment_algorithm(&attributes, PSA_ALG_ECDH);
1273
1274 status = psa_import_key(&attributes, d, d_len, &pk->priv_id);
1275 if (status != PSA_SUCCESS) {
1276 ret = psa_pk_status_to_mbedtls(status);
1277 return ret;
1278 }
1279 #endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
1280
1281 if (!pubkey_done) {
1282 if ((ret = pk_derive_public_key(pk, d, d_len, f_rng, p_rng)) != 0) {
1283 return ret;
1284 }
1285 }
1286
1287 return 0;
1288 }
1289 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
1290
1291 /*
1292 * Parse an unencrypted PKCS#8 encoded private key
1293 *
1294 * Notes:
1295 *
1296 * - This function does not own the key buffer. It is the
1297 * responsibility of the caller to take care of zeroizing
1298 * and freeing it after use.
1299 *
1300 * - The function is responsible for freeing the provided
1301 * PK context on failure.
1302 *
1303 */
pk_parse_key_pkcs8_unencrypted_der(mbedtls_pk_context * pk,const unsigned char * key,size_t keylen,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1304 static int pk_parse_key_pkcs8_unencrypted_der(
1305 mbedtls_pk_context *pk,
1306 const unsigned char *key, size_t keylen,
1307 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1308 {
1309 int ret, version;
1310 size_t len;
1311 mbedtls_asn1_buf params;
1312 unsigned char *p = (unsigned char *) key;
1313 unsigned char *end = p + keylen;
1314 mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
1315 mbedtls_ecp_group_id ec_grp_id = MBEDTLS_ECP_DP_NONE;
1316 const mbedtls_pk_info_t *pk_info;
1317
1318 #if !defined(MBEDTLS_PK_HAVE_ECC_KEYS)
1319 (void) f_rng;
1320 (void) p_rng;
1321 #endif
1322
1323 /*
1324 * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)
1325 *
1326 * PrivateKeyInfo ::= SEQUENCE {
1327 * version Version,
1328 * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
1329 * privateKey PrivateKey,
1330 * attributes [0] IMPLICIT Attributes OPTIONAL }
1331 *
1332 * Version ::= INTEGER
1333 * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
1334 * PrivateKey ::= OCTET STRING
1335 *
1336 * The PrivateKey OCTET STRING is a SEC1 ECPrivateKey
1337 */
1338
1339 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1340 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1341 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1342 }
1343
1344 end = p + len;
1345
1346 if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
1347 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1348 }
1349
1350 if (version != 0) {
1351 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_VERSION, ret);
1352 }
1353
1354 if ((ret = pk_get_pk_alg(&p, end, &pk_alg, ¶ms, &ec_grp_id)) != 0) {
1355 return ret;
1356 }
1357
1358 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1359 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1360 }
1361
1362 if (len < 1) {
1363 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1364 MBEDTLS_ERR_ASN1_OUT_OF_DATA);
1365 }
1366
1367 if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
1368 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1369 }
1370
1371 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
1372 return ret;
1373 }
1374
1375 #if defined(MBEDTLS_RSA_C)
1376 if (pk_alg == MBEDTLS_PK_RSA) {
1377 if ((ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), p, len)) != 0) {
1378 mbedtls_pk_free(pk);
1379 return ret;
1380 }
1381 } else
1382 #endif /* MBEDTLS_RSA_C */
1383 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
1384 if (pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH) {
1385 #if defined(MBEDTLS_PK_HAVE_RFC8410_CURVES)
1386 if (MBEDTLS_PK_IS_RFC8410_GROUP_ID(ec_grp_id)) {
1387 if ((ret =
1388 pk_use_ecparams_rfc8410(¶ms, ec_grp_id, pk)) != 0 ||
1389 (ret =
1390 pk_parse_key_rfc8410_der(pk, p, len, end, f_rng,
1391 p_rng)) != 0) {
1392 mbedtls_pk_free(pk);
1393 return ret;
1394 }
1395 } else
1396 #endif
1397 {
1398 if ((ret = pk_use_ecparams(¶ms, pk)) != 0 ||
1399 (ret = pk_parse_key_sec1_der(pk, p, len, f_rng, p_rng)) != 0) {
1400 mbedtls_pk_free(pk);
1401 return ret;
1402 }
1403 }
1404 } else
1405 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
1406 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1407
1408 end = p + len;
1409 if (end != (key + keylen)) {
1410 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1411 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1412 }
1413
1414 return 0;
1415 }
1416
1417 /*
1418 * Parse an encrypted PKCS#8 encoded private key
1419 *
1420 * To save space, the decryption happens in-place on the given key buffer.
1421 * Also, while this function may modify the keybuffer, it doesn't own it,
1422 * and instead it is the responsibility of the caller to zeroize and properly
1423 * free it after use.
1424 *
1425 */
1426 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
mbedtls_pk_parse_key_pkcs8_encrypted_der(mbedtls_pk_context * pk,unsigned char * key,size_t keylen,const unsigned char * pwd,size_t pwdlen,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1427 MBEDTLS_STATIC_TESTABLE int mbedtls_pk_parse_key_pkcs8_encrypted_der(
1428 mbedtls_pk_context *pk,
1429 unsigned char *key, size_t keylen,
1430 const unsigned char *pwd, size_t pwdlen,
1431 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1432 {
1433 int ret, decrypted = 0;
1434 size_t len;
1435 unsigned char *buf;
1436 unsigned char *p, *end;
1437 mbedtls_asn1_buf pbe_alg_oid, pbe_params;
1438 #if defined(MBEDTLS_PKCS12_C)
1439 mbedtls_cipher_type_t cipher_alg;
1440 mbedtls_md_type_t md_alg;
1441 #endif
1442 size_t outlen = 0;
1443
1444 p = key;
1445 end = p + keylen;
1446
1447 if (pwdlen == 0) {
1448 return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1449 }
1450
1451 /*
1452 * This function parses the EncryptedPrivateKeyInfo object (PKCS#8)
1453 *
1454 * EncryptedPrivateKeyInfo ::= SEQUENCE {
1455 * encryptionAlgorithm EncryptionAlgorithmIdentifier,
1456 * encryptedData EncryptedData
1457 * }
1458 *
1459 * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
1460 *
1461 * EncryptedData ::= OCTET STRING
1462 *
1463 * The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
1464 *
1465 */
1466 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1467 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1468 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1469 }
1470
1471 end = p + len;
1472
1473 if ((ret = mbedtls_asn1_get_alg(&p, end, &pbe_alg_oid, &pbe_params)) != 0) {
1474 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1475 }
1476
1477 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1478 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1479 }
1480
1481 buf = p;
1482
1483 /*
1484 * Decrypt EncryptedData with appropriate PBE
1485 */
1486 #if defined(MBEDTLS_PKCS12_C)
1487 if (mbedtls_oid_get_pkcs12_pbe_alg(&pbe_alg_oid, &md_alg, &cipher_alg) == 0) {
1488 if ((ret = mbedtls_pkcs12_pbe_ext(&pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,
1489 cipher_alg, md_alg,
1490 pwd, pwdlen, p, len, buf, len, &outlen)) != 0) {
1491 if (ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) {
1492 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1493 }
1494
1495 return ret;
1496 }
1497
1498 decrypted = 1;
1499 } else
1500 #endif /* MBEDTLS_PKCS12_C */
1501 #if defined(MBEDTLS_PKCS5_C)
1502 if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid) == 0) {
1503 if ((ret = mbedtls_pkcs5_pbes2_ext(&pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,
1504 p, len, buf, len, &outlen)) != 0) {
1505 if (ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) {
1506 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1507 }
1508
1509 return ret;
1510 }
1511
1512 decrypted = 1;
1513 } else
1514 #endif /* MBEDTLS_PKCS5_C */
1515 {
1516 ((void) pwd);
1517 }
1518
1519 if (decrypted == 0) {
1520 return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1521 }
1522 return pk_parse_key_pkcs8_unencrypted_der(pk, buf, outlen, f_rng, p_rng);
1523 }
1524 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1525
1526 /*
1527 * Parse a private key
1528 */
mbedtls_pk_parse_key(mbedtls_pk_context * pk,const unsigned char * key,size_t keylen,const unsigned char * pwd,size_t pwdlen,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1529 int mbedtls_pk_parse_key(mbedtls_pk_context *pk,
1530 const unsigned char *key, size_t keylen,
1531 const unsigned char *pwd, size_t pwdlen,
1532 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1533 {
1534 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1535 const mbedtls_pk_info_t *pk_info;
1536 #if defined(MBEDTLS_PEM_PARSE_C)
1537 size_t len;
1538 mbedtls_pem_context pem;
1539 #endif
1540
1541 if (keylen == 0) {
1542 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1543 }
1544
1545 #if defined(MBEDTLS_PEM_PARSE_C)
1546 mbedtls_pem_init(&pem);
1547
1548 #if defined(MBEDTLS_RSA_C)
1549 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1550 if (key[keylen - 1] != '\0') {
1551 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1552 } else {
1553 ret = mbedtls_pem_read_buffer(&pem,
1554 "-----BEGIN RSA PRIVATE KEY-----",
1555 "-----END RSA PRIVATE KEY-----",
1556 key, pwd, pwdlen, &len);
1557 }
1558
1559 if (ret == 0) {
1560 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1561 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1562 (ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk),
1563 pem.buf, pem.buflen)) != 0) {
1564 mbedtls_pk_free(pk);
1565 }
1566
1567 mbedtls_pem_free(&pem);
1568 return ret;
1569 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1570 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1571 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1572 return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1573 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1574 return ret;
1575 }
1576 #endif /* MBEDTLS_RSA_C */
1577
1578 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
1579 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1580 if (key[keylen - 1] != '\0') {
1581 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1582 } else {
1583 ret = mbedtls_pem_read_buffer(&pem,
1584 "-----BEGIN EC PRIVATE KEY-----",
1585 "-----END EC PRIVATE KEY-----",
1586 key, pwd, pwdlen, &len);
1587 }
1588 if (ret == 0) {
1589 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1590
1591 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1592 (ret = pk_parse_key_sec1_der(pk,
1593 pem.buf, pem.buflen,
1594 f_rng, p_rng)) != 0) {
1595 mbedtls_pk_free(pk);
1596 }
1597
1598 mbedtls_pem_free(&pem);
1599 return ret;
1600 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1601 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1602 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1603 return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1604 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1605 return ret;
1606 }
1607 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
1608
1609 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1610 if (key[keylen - 1] != '\0') {
1611 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1612 } else {
1613 ret = mbedtls_pem_read_buffer(&pem,
1614 "-----BEGIN PRIVATE KEY-----",
1615 "-----END PRIVATE KEY-----",
1616 key, NULL, 0, &len);
1617 }
1618 if (ret == 0) {
1619 if ((ret = pk_parse_key_pkcs8_unencrypted_der(pk,
1620 pem.buf, pem.buflen, f_rng, p_rng)) != 0) {
1621 mbedtls_pk_free(pk);
1622 }
1623
1624 mbedtls_pem_free(&pem);
1625 return ret;
1626 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1627 return ret;
1628 }
1629
1630 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1631 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1632 if (key[keylen - 1] != '\0') {
1633 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1634 } else {
1635 ret = mbedtls_pem_read_buffer(&pem,
1636 "-----BEGIN ENCRYPTED PRIVATE KEY-----",
1637 "-----END ENCRYPTED PRIVATE KEY-----",
1638 key, NULL, 0, &len);
1639 }
1640 if (ret == 0) {
1641 if ((ret = mbedtls_pk_parse_key_pkcs8_encrypted_der(pk, pem.buf, pem.buflen,
1642 pwd, pwdlen, f_rng, p_rng)) != 0) {
1643 mbedtls_pk_free(pk);
1644 }
1645
1646 mbedtls_pem_free(&pem);
1647 return ret;
1648 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1649 return ret;
1650 }
1651 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1652 #else
1653 ((void) pwd);
1654 ((void) pwdlen);
1655 #endif /* MBEDTLS_PEM_PARSE_C */
1656
1657 /*
1658 * At this point we only know it's not a PEM formatted key. Could be any
1659 * of the known DER encoded private key formats
1660 *
1661 * We try the different DER format parsers to see if one passes without
1662 * error
1663 */
1664 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1665 if (pwdlen != 0) {
1666 unsigned char *key_copy;
1667
1668 if ((key_copy = mbedtls_calloc(1, keylen)) == NULL) {
1669 return MBEDTLS_ERR_PK_ALLOC_FAILED;
1670 }
1671
1672 memcpy(key_copy, key, keylen);
1673
1674 ret = mbedtls_pk_parse_key_pkcs8_encrypted_der(pk, key_copy, keylen,
1675 pwd, pwdlen, f_rng, p_rng);
1676
1677 mbedtls_zeroize_and_free(key_copy, keylen);
1678 }
1679
1680 if (ret == 0) {
1681 return 0;
1682 }
1683
1684 mbedtls_pk_free(pk);
1685 mbedtls_pk_init(pk);
1686
1687 if (ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH) {
1688 return ret;
1689 }
1690 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1691
1692 ret = pk_parse_key_pkcs8_unencrypted_der(pk, key, keylen, f_rng, p_rng);
1693 if (ret == 0) {
1694 return 0;
1695 }
1696
1697 mbedtls_pk_free(pk);
1698 mbedtls_pk_init(pk);
1699
1700 #if defined(MBEDTLS_RSA_C)
1701
1702 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1703 if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1704 pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), key, keylen) == 0) {
1705 return 0;
1706 }
1707
1708 mbedtls_pk_free(pk);
1709 mbedtls_pk_init(pk);
1710 #endif /* MBEDTLS_RSA_C */
1711
1712 #if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
1713 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1714 if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1715 pk_parse_key_sec1_der(pk,
1716 key, keylen, f_rng, p_rng) == 0) {
1717 return 0;
1718 }
1719 mbedtls_pk_free(pk);
1720 #endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
1721
1722 /* If MBEDTLS_RSA_C is defined but MBEDTLS_PK_HAVE_ECC_KEYS isn't,
1723 * it is ok to leave the PK context initialized but not
1724 * freed: It is the caller's responsibility to call pk_init()
1725 * before calling this function, and to call pk_free()
1726 * when it fails. If MBEDTLS_PK_HAVE_ECC_KEYS is defined but MBEDTLS_RSA_C
1727 * isn't, this leads to mbedtls_pk_free() being called
1728 * twice, once here and once by the caller, but this is
1729 * also ok and in line with the mbedtls_pk_free() calls
1730 * on failed PEM parsing attempts. */
1731
1732 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1733 }
1734
1735 /*
1736 * Parse a public key
1737 */
mbedtls_pk_parse_public_key(mbedtls_pk_context * ctx,const unsigned char * key,size_t keylen)1738 int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
1739 const unsigned char *key, size_t keylen)
1740 {
1741 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1742 unsigned char *p;
1743 #if defined(MBEDTLS_RSA_C)
1744 const mbedtls_pk_info_t *pk_info;
1745 #endif
1746 #if defined(MBEDTLS_PEM_PARSE_C)
1747 size_t len;
1748 mbedtls_pem_context pem;
1749 #endif
1750
1751 if (keylen == 0) {
1752 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1753 }
1754
1755 #if defined(MBEDTLS_PEM_PARSE_C)
1756 mbedtls_pem_init(&pem);
1757 #if defined(MBEDTLS_RSA_C)
1758 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1759 if (key[keylen - 1] != '\0') {
1760 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1761 } else {
1762 ret = mbedtls_pem_read_buffer(&pem,
1763 "-----BEGIN RSA PUBLIC KEY-----",
1764 "-----END RSA PUBLIC KEY-----",
1765 key, NULL, 0, &len);
1766 }
1767
1768 if (ret == 0) {
1769 p = pem.buf;
1770 if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1771 mbedtls_pem_free(&pem);
1772 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1773 }
1774
1775 if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1776 mbedtls_pem_free(&pem);
1777 return ret;
1778 }
1779
1780 if ((ret = pk_get_rsapubkey(&p, p + pem.buflen, mbedtls_pk_rsa(*ctx))) != 0) {
1781 mbedtls_pk_free(ctx);
1782 }
1783
1784 mbedtls_pem_free(&pem);
1785 return ret;
1786 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1787 mbedtls_pem_free(&pem);
1788 return ret;
1789 }
1790 #endif /* MBEDTLS_RSA_C */
1791
1792 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1793 if (key[keylen - 1] != '\0') {
1794 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1795 } else {
1796 ret = mbedtls_pem_read_buffer(&pem,
1797 "-----BEGIN PUBLIC KEY-----",
1798 "-----END PUBLIC KEY-----",
1799 key, NULL, 0, &len);
1800 }
1801
1802 if (ret == 0) {
1803 /*
1804 * Was PEM encoded
1805 */
1806 p = pem.buf;
1807
1808 ret = mbedtls_pk_parse_subpubkey(&p, p + pem.buflen, ctx);
1809 mbedtls_pem_free(&pem);
1810 return ret;
1811 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1812 mbedtls_pem_free(&pem);
1813 return ret;
1814 }
1815 mbedtls_pem_free(&pem);
1816 #endif /* MBEDTLS_PEM_PARSE_C */
1817
1818 #if defined(MBEDTLS_RSA_C)
1819 if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1820 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1821 }
1822
1823 if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1824 return ret;
1825 }
1826
1827 p = (unsigned char *) key;
1828 ret = pk_get_rsapubkey(&p, p + keylen, mbedtls_pk_rsa(*ctx));
1829 if (ret == 0) {
1830 return ret;
1831 }
1832 mbedtls_pk_free(ctx);
1833 if (ret != (MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
1834 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG))) {
1835 return ret;
1836 }
1837 #endif /* MBEDTLS_RSA_C */
1838 p = (unsigned char *) key;
1839
1840 ret = mbedtls_pk_parse_subpubkey(&p, p + keylen, ctx);
1841
1842 return ret;
1843 }
1844
1845 #endif /* MBEDTLS_PK_PARSE_C */
1846