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
18 #include <string.h>
19
20 #if defined(MBEDTLS_RSA_C)
21 #include "mbedtls/rsa.h"
22 #endif
23 #if defined(MBEDTLS_ECP_C)
24 #include "mbedtls/ecp.h"
25 #endif
26 #if defined(MBEDTLS_ECDSA_C)
27 #include "mbedtls/ecdsa.h"
28 #endif
29 #if defined(MBEDTLS_PEM_PARSE_C)
30 #include "mbedtls/pem.h"
31 #endif
32 #if defined(MBEDTLS_PKCS5_C)
33 #include "mbedtls/pkcs5.h"
34 #endif
35 #if defined(MBEDTLS_PKCS12_C)
36 #include "mbedtls/pkcs12.h"
37 #endif
38
39 #include "mbedtls/platform.h"
40
41 /* Parameter validation macros based on platform_util.h */
42 #define PK_VALIDATE_RET(cond) \
43 MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA)
44 #define PK_VALIDATE(cond) \
45 MBEDTLS_INTERNAL_VALIDATE(cond)
46
47 #if defined(MBEDTLS_FS_IO)
48 /*
49 * Load all data from a file into a given buffer.
50 *
51 * The file is expected to contain either PEM or DER encoded data.
52 * A terminating null byte is always appended. It is included in the announced
53 * length only if the data looks like it is PEM encoded.
54 */
mbedtls_pk_load_file(const char * path,unsigned char ** buf,size_t * n)55 int mbedtls_pk_load_file(const char *path, unsigned char **buf, size_t *n)
56 {
57 FILE *f;
58 long size;
59
60 PK_VALIDATE_RET(path != NULL);
61 PK_VALIDATE_RET(buf != NULL);
62 PK_VALIDATE_RET(n != NULL);
63
64 if ((f = fopen(path, "rb")) == NULL) {
65 return MBEDTLS_ERR_PK_FILE_IO_ERROR;
66 }
67
68 fseek(f, 0, SEEK_END);
69 if ((size = ftell(f)) == -1) {
70 fclose(f);
71 return MBEDTLS_ERR_PK_FILE_IO_ERROR;
72 }
73 fseek(f, 0, SEEK_SET);
74
75 *n = (size_t) size;
76
77 if (*n + 1 == 0 ||
78 (*buf = mbedtls_calloc(1, *n + 1)) == NULL) {
79 fclose(f);
80 return MBEDTLS_ERR_PK_ALLOC_FAILED;
81 }
82
83 if (fread(*buf, 1, *n, f) != *n) {
84 fclose(f);
85
86 mbedtls_platform_zeroize(*buf, *n);
87 mbedtls_free(*buf);
88
89 return MBEDTLS_ERR_PK_FILE_IO_ERROR;
90 }
91
92 fclose(f);
93
94 (*buf)[*n] = '\0';
95
96 if (strstr((const char *) *buf, "-----BEGIN ") != NULL) {
97 ++*n;
98 }
99
100 return 0;
101 }
102
103 /*
104 * Load and parse a private key
105 */
mbedtls_pk_parse_keyfile(mbedtls_pk_context * ctx,const char * path,const char * pwd)106 int mbedtls_pk_parse_keyfile(mbedtls_pk_context *ctx,
107 const char *path, const char *pwd)
108 {
109 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
110 size_t n;
111 unsigned char *buf;
112
113 PK_VALIDATE_RET(ctx != NULL);
114 PK_VALIDATE_RET(path != NULL);
115
116 if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
117 return ret;
118 }
119
120 if (pwd == NULL) {
121 ret = mbedtls_pk_parse_key(ctx, buf, n, NULL, 0);
122 } else {
123 ret = mbedtls_pk_parse_key(ctx, buf, n,
124 (const unsigned char *) pwd, strlen(pwd));
125 }
126
127 mbedtls_platform_zeroize(buf, n);
128 mbedtls_free(buf);
129
130 return ret;
131 }
132
133 /*
134 * Load and parse a public key
135 */
mbedtls_pk_parse_public_keyfile(mbedtls_pk_context * ctx,const char * path)136 int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path)
137 {
138 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
139 size_t n;
140 unsigned char *buf;
141
142 PK_VALIDATE_RET(ctx != NULL);
143 PK_VALIDATE_RET(path != NULL);
144
145 if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
146 return ret;
147 }
148
149 ret = mbedtls_pk_parse_public_key(ctx, buf, n);
150
151 mbedtls_platform_zeroize(buf, n);
152 mbedtls_free(buf);
153
154 return ret;
155 }
156 #endif /* MBEDTLS_FS_IO */
157
158 #if defined(MBEDTLS_ECP_C)
159 /* Minimally parse an ECParameters buffer to and mbedtls_asn1_buf
160 *
161 * ECParameters ::= CHOICE {
162 * namedCurve OBJECT IDENTIFIER
163 * specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... }
164 * -- implicitCurve NULL
165 * }
166 */
pk_get_ecparams(unsigned char ** p,const unsigned char * end,mbedtls_asn1_buf * params)167 static int pk_get_ecparams(unsigned char **p, const unsigned char *end,
168 mbedtls_asn1_buf *params)
169 {
170 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
171
172 if (end - *p < 1) {
173 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
174 MBEDTLS_ERR_ASN1_OUT_OF_DATA);
175 }
176
177 /* Tag may be either OID or SEQUENCE */
178 params->tag = **p;
179 if (params->tag != MBEDTLS_ASN1_OID
180 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
181 && params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)
182 #endif
183 ) {
184 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
185 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
186 }
187
188 if ((ret = mbedtls_asn1_get_tag(p, end, ¶ms->len, params->tag)) != 0) {
189 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
190 }
191
192 params->p = *p;
193 *p += params->len;
194
195 if (*p != end) {
196 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
197 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
198 }
199
200 return 0;
201 }
202
203 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
204 /*
205 * Parse a SpecifiedECDomain (SEC 1 C.2) and (mostly) fill the group with it.
206 * WARNING: the resulting group should only be used with
207 * pk_group_id_from_specified(), since its base point may not be set correctly
208 * if it was encoded compressed.
209 *
210 * SpecifiedECDomain ::= SEQUENCE {
211 * version SpecifiedECDomainVersion(ecdpVer1 | ecdpVer2 | ecdpVer3, ...),
212 * fieldID FieldID {{FieldTypes}},
213 * curve Curve,
214 * base ECPoint,
215 * order INTEGER,
216 * cofactor INTEGER OPTIONAL,
217 * hash HashAlgorithm OPTIONAL,
218 * ...
219 * }
220 *
221 * We only support prime-field as field type, and ignore hash and cofactor.
222 */
pk_group_from_specified(const mbedtls_asn1_buf * params,mbedtls_ecp_group * grp)223 static int pk_group_from_specified(const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp)
224 {
225 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
226 unsigned char *p = params->p;
227 const unsigned char * const end = params->p + params->len;
228 const unsigned char *end_field, *end_curve;
229 size_t len;
230 int ver;
231
232 /* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */
233 if ((ret = mbedtls_asn1_get_int(&p, end, &ver)) != 0) {
234 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
235 }
236
237 if (ver < 1 || ver > 3) {
238 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
239 }
240
241 /*
242 * FieldID { FIELD-ID:IOSet } ::= SEQUENCE { -- Finite field
243 * fieldType FIELD-ID.&id({IOSet}),
244 * parameters FIELD-ID.&Type({IOSet}{@fieldType})
245 * }
246 */
247 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
248 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
249 return ret;
250 }
251
252 end_field = p + len;
253
254 /*
255 * FIELD-ID ::= TYPE-IDENTIFIER
256 * FieldTypes FIELD-ID ::= {
257 * { Prime-p IDENTIFIED BY prime-field } |
258 * { Characteristic-two IDENTIFIED BY characteristic-two-field }
259 * }
260 * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }
261 */
262 if ((ret = mbedtls_asn1_get_tag(&p, end_field, &len, MBEDTLS_ASN1_OID)) != 0) {
263 return ret;
264 }
265
266 if (len != MBEDTLS_OID_SIZE(MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD) ||
267 memcmp(p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len) != 0) {
268 return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
269 }
270
271 p += len;
272
273 /* Prime-p ::= INTEGER -- Field of size p. */
274 if ((ret = mbedtls_asn1_get_mpi(&p, end_field, &grp->P)) != 0) {
275 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
276 }
277
278 grp->pbits = mbedtls_mpi_bitlen(&grp->P);
279
280 if (p != end_field) {
281 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
282 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
283 }
284
285 /*
286 * Curve ::= SEQUENCE {
287 * a FieldElement,
288 * b FieldElement,
289 * seed BIT STRING OPTIONAL
290 * -- Shall be present if used in SpecifiedECDomain
291 * -- with version equal to ecdpVer2 or ecdpVer3
292 * }
293 */
294 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
295 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
296 return ret;
297 }
298
299 end_curve = p + len;
300
301 /*
302 * FieldElement ::= OCTET STRING
303 * containing an integer in the case of a prime field
304 */
305 if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0 ||
306 (ret = mbedtls_mpi_read_binary(&grp->A, p, len)) != 0) {
307 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
308 }
309
310 p += len;
311
312 if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0 ||
313 (ret = mbedtls_mpi_read_binary(&grp->B, p, len)) != 0) {
314 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
315 }
316
317 p += len;
318
319 /* Ignore seed BIT STRING OPTIONAL */
320 if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING)) == 0) {
321 p += len;
322 }
323
324 if (p != end_curve) {
325 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
326 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
327 }
328
329 /*
330 * ECPoint ::= OCTET STRING
331 */
332 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
333 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
334 }
335
336 if ((ret = mbedtls_ecp_point_read_binary(grp, &grp->G,
337 (const unsigned char *) p, len)) != 0) {
338 /*
339 * If we can't read the point because it's compressed, cheat by
340 * reading only the X coordinate and the parity bit of Y.
341 */
342 if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ||
343 (p[0] != 0x02 && p[0] != 0x03) ||
344 len != mbedtls_mpi_size(&grp->P) + 1 ||
345 mbedtls_mpi_read_binary(&grp->G.X, p + 1, len - 1) != 0 ||
346 mbedtls_mpi_lset(&grp->G.Y, p[0] - 2) != 0 ||
347 mbedtls_mpi_lset(&grp->G.Z, 1) != 0) {
348 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
349 }
350 }
351
352 p += len;
353
354 /*
355 * order INTEGER
356 */
357 if ((ret = mbedtls_asn1_get_mpi(&p, end, &grp->N)) != 0) {
358 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
359 }
360
361 grp->nbits = mbedtls_mpi_bitlen(&grp->N);
362
363 /*
364 * Allow optional elements by purposefully not enforcing p == end here.
365 */
366
367 return 0;
368 }
369
370 /*
371 * Find the group id associated with an (almost filled) group as generated by
372 * pk_group_from_specified(), or return an error if unknown.
373 */
pk_group_id_from_group(const mbedtls_ecp_group * grp,mbedtls_ecp_group_id * grp_id)374 static int pk_group_id_from_group(const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id)
375 {
376 int ret = 0;
377 mbedtls_ecp_group ref;
378 const mbedtls_ecp_group_id *id;
379
380 mbedtls_ecp_group_init(&ref);
381
382 for (id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++) {
383 /* Load the group associated to that id */
384 mbedtls_ecp_group_free(&ref);
385 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&ref, *id));
386
387 /* Compare to the group we were given, starting with easy tests */
388 if (grp->pbits == ref.pbits && grp->nbits == ref.nbits &&
389 mbedtls_mpi_cmp_mpi(&grp->P, &ref.P) == 0 &&
390 mbedtls_mpi_cmp_mpi(&grp->A, &ref.A) == 0 &&
391 mbedtls_mpi_cmp_mpi(&grp->B, &ref.B) == 0 &&
392 mbedtls_mpi_cmp_mpi(&grp->N, &ref.N) == 0 &&
393 mbedtls_mpi_cmp_mpi(&grp->G.X, &ref.G.X) == 0 &&
394 mbedtls_mpi_cmp_mpi(&grp->G.Z, &ref.G.Z) == 0 &&
395 /* For Y we may only know the parity bit, so compare only that */
396 mbedtls_mpi_get_bit(&grp->G.Y, 0) == mbedtls_mpi_get_bit(&ref.G.Y, 0)) {
397 break;
398 }
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 mbedtls_ecp_group_free(&grp);
433
434 return ret;
435 }
436 #endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */
437
438 /*
439 * Use EC parameters to initialise an EC group
440 *
441 * ECParameters ::= CHOICE {
442 * namedCurve OBJECT IDENTIFIER
443 * specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... }
444 * -- implicitCurve NULL
445 */
pk_use_ecparams(const mbedtls_asn1_buf * params,mbedtls_ecp_group * grp)446 static int pk_use_ecparams(const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp)
447 {
448 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
449 mbedtls_ecp_group_id grp_id;
450
451 if (params->tag == MBEDTLS_ASN1_OID) {
452 if (mbedtls_oid_get_ec_grp(params, &grp_id) != 0) {
453 return MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE;
454 }
455 } else {
456 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
457 if ((ret = pk_group_id_from_specified(params, &grp_id)) != 0) {
458 return ret;
459 }
460 #else
461 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
462 #endif
463 }
464
465 /*
466 * grp may already be initialized; if so, make sure IDs match
467 */
468 if (grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id) {
469 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
470 }
471
472 if ((ret = mbedtls_ecp_group_load(grp, grp_id)) != 0) {
473 return ret;
474 }
475
476 return 0;
477 }
478
479 /*
480 * EC public key is an EC point
481 *
482 * The caller is responsible for clearing the structure upon failure if
483 * desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE
484 * return code of mbedtls_ecp_point_read_binary() and leave p in a usable state.
485 */
pk_get_ecpubkey(unsigned char ** p,const unsigned char * end,mbedtls_ecp_keypair * key)486 static int pk_get_ecpubkey(unsigned char **p, const unsigned char *end,
487 mbedtls_ecp_keypair *key)
488 {
489 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
490
491 if ((ret = mbedtls_ecp_point_read_binary(&key->grp, &key->Q,
492 (const unsigned char *) *p, end - *p)) == 0) {
493 ret = mbedtls_ecp_check_pubkey(&key->grp, &key->Q);
494 }
495
496 /*
497 * We know mbedtls_ecp_point_read_binary consumed all bytes or failed
498 */
499 *p = (unsigned char *) end;
500
501 return ret;
502 }
503 #endif /* MBEDTLS_ECP_C */
504
505 #if defined(MBEDTLS_RSA_C)
506 /*
507 * RSAPublicKey ::= SEQUENCE {
508 * modulus INTEGER, -- n
509 * publicExponent INTEGER -- e
510 * }
511 */
pk_get_rsapubkey(unsigned char ** p,const unsigned char * end,mbedtls_rsa_context * rsa)512 static int pk_get_rsapubkey(unsigned char **p,
513 const unsigned char *end,
514 mbedtls_rsa_context *rsa)
515 {
516 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
517 size_t len;
518
519 if ((ret = mbedtls_asn1_get_tag(p, end, &len,
520 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
521 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
522 }
523
524 if (*p + len != end) {
525 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
526 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
527 }
528
529 /* Import N */
530 if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
531 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
532 }
533
534 if ((ret = mbedtls_rsa_import_raw(rsa, *p, len, NULL, 0, NULL, 0,
535 NULL, 0, NULL, 0)) != 0) {
536 return MBEDTLS_ERR_PK_INVALID_PUBKEY;
537 }
538
539 *p += len;
540
541 /* Import E */
542 if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
543 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
544 }
545
546 if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
547 NULL, 0, *p, len)) != 0) {
548 return MBEDTLS_ERR_PK_INVALID_PUBKEY;
549 }
550
551 *p += len;
552
553 if (mbedtls_rsa_complete(rsa) != 0 ||
554 mbedtls_rsa_check_pubkey(rsa) != 0) {
555 return MBEDTLS_ERR_PK_INVALID_PUBKEY;
556 }
557
558 if (*p != end) {
559 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
560 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
561 }
562
563 return 0;
564 }
565 #endif /* MBEDTLS_RSA_C */
566
567 /* Get a PK algorithm identifier
568 *
569 * AlgorithmIdentifier ::= SEQUENCE {
570 * algorithm OBJECT IDENTIFIER,
571 * parameters ANY DEFINED BY algorithm OPTIONAL }
572 */
pk_get_pk_alg(unsigned char ** p,const unsigned char * end,mbedtls_pk_type_t * pk_alg,mbedtls_asn1_buf * params)573 static int pk_get_pk_alg(unsigned char **p,
574 const unsigned char *end,
575 mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params)
576 {
577 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
578 mbedtls_asn1_buf alg_oid;
579
580 memset(params, 0, sizeof(mbedtls_asn1_buf));
581
582 if ((ret = mbedtls_asn1_get_alg(p, end, &alg_oid, params)) != 0) {
583 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_ALG, ret);
584 }
585
586 if (mbedtls_oid_get_pk_alg(&alg_oid, pk_alg) != 0) {
587 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
588 }
589
590 /*
591 * No parameters with RSA (only for EC)
592 */
593 if (*pk_alg == MBEDTLS_PK_RSA &&
594 ((params->tag != MBEDTLS_ASN1_NULL && params->tag != 0) ||
595 params->len != 0)) {
596 return MBEDTLS_ERR_PK_INVALID_ALG;
597 }
598
599 return 0;
600 }
601
602 /*
603 * SubjectPublicKeyInfo ::= SEQUENCE {
604 * algorithm AlgorithmIdentifier,
605 * subjectPublicKey BIT STRING }
606 */
mbedtls_pk_parse_subpubkey(unsigned char ** p,const unsigned char * end,mbedtls_pk_context * pk)607 int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
608 mbedtls_pk_context *pk)
609 {
610 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
611 size_t len;
612 mbedtls_asn1_buf alg_params;
613 mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
614 const mbedtls_pk_info_t *pk_info;
615
616 PK_VALIDATE_RET(p != NULL);
617 PK_VALIDATE_RET(*p != NULL);
618 PK_VALIDATE_RET(end != NULL);
619 PK_VALIDATE_RET(pk != NULL);
620
621 if ((ret = mbedtls_asn1_get_tag(p, end, &len,
622 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
623 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
624 }
625
626 end = *p + len;
627
628 if ((ret = pk_get_pk_alg(p, end, &pk_alg, &alg_params)) != 0) {
629 return ret;
630 }
631
632 if ((ret = mbedtls_asn1_get_bitstring_null(p, end, &len)) != 0) {
633 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
634 }
635
636 if (*p + len != end) {
637 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
638 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
639 }
640
641 if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
642 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
643 }
644
645 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
646 return ret;
647 }
648
649 #if defined(MBEDTLS_RSA_C)
650 if (pk_alg == MBEDTLS_PK_RSA) {
651 ret = pk_get_rsapubkey(p, end, mbedtls_pk_rsa(*pk));
652 } else
653 #endif /* MBEDTLS_RSA_C */
654 #if defined(MBEDTLS_ECP_C)
655 if (pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY) {
656 ret = pk_use_ecparams(&alg_params, &mbedtls_pk_ec(*pk)->grp);
657 if (ret == 0) {
658 ret = pk_get_ecpubkey(p, end, mbedtls_pk_ec(*pk));
659 }
660 } else
661 #endif /* MBEDTLS_ECP_C */
662 ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
663
664 if (ret == 0 && *p != end) {
665 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
666 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
667 }
668
669 if (ret != 0) {
670 mbedtls_pk_free(pk);
671 }
672
673 return ret;
674 }
675
676 #if defined(MBEDTLS_RSA_C)
677 /*
678 * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
679 *
680 * The value zero is:
681 * - never a valid value for an RSA parameter
682 * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
683 *
684 * Since values can't be omitted in PKCS#1, passing a zero value to
685 * rsa_complete() would be incorrect, so reject zero values early.
686 */
asn1_get_nonzero_mpi(unsigned char ** p,const unsigned char * end,mbedtls_mpi * X)687 static int asn1_get_nonzero_mpi(unsigned char **p,
688 const unsigned char *end,
689 mbedtls_mpi *X)
690 {
691 int ret;
692
693 ret = mbedtls_asn1_get_mpi(p, end, X);
694 if (ret != 0) {
695 return ret;
696 }
697
698 if (mbedtls_mpi_cmp_int(X, 0) == 0) {
699 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
700 }
701
702 return 0;
703 }
704
705 /*
706 * Parse a PKCS#1 encoded private RSA key
707 */
pk_parse_key_pkcs1_der(mbedtls_rsa_context * rsa,const unsigned char * key,size_t keylen)708 static int pk_parse_key_pkcs1_der(mbedtls_rsa_context *rsa,
709 const unsigned char *key,
710 size_t keylen)
711 {
712 int ret, version;
713 size_t len;
714 unsigned char *p, *end;
715
716 mbedtls_mpi T;
717 mbedtls_mpi_init(&T);
718
719 p = (unsigned char *) key;
720 end = p + keylen;
721
722 /*
723 * This function parses the RSAPrivateKey (PKCS#1)
724 *
725 * RSAPrivateKey ::= SEQUENCE {
726 * version Version,
727 * modulus INTEGER, -- n
728 * publicExponent INTEGER, -- e
729 * privateExponent INTEGER, -- d
730 * prime1 INTEGER, -- p
731 * prime2 INTEGER, -- q
732 * exponent1 INTEGER, -- d mod (p-1)
733 * exponent2 INTEGER, -- d mod (q-1)
734 * coefficient INTEGER, -- (inverse of q) mod p
735 * otherPrimeInfos OtherPrimeInfos OPTIONAL
736 * }
737 */
738 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
739 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
740 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
741 }
742
743 end = p + len;
744
745 if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
746 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
747 }
748
749 if (version != 0) {
750 return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
751 }
752
753 /* Import N */
754 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
755 (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
756 NULL, NULL)) != 0) {
757 goto cleanup;
758 }
759
760 /* Import E */
761 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
762 (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
763 NULL, &T)) != 0) {
764 goto cleanup;
765 }
766
767 /* Import D */
768 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
769 (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
770 &T, NULL)) != 0) {
771 goto cleanup;
772 }
773
774 /* Import P */
775 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
776 (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
777 NULL, NULL)) != 0) {
778 goto cleanup;
779 }
780
781 /* Import Q */
782 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
783 (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
784 NULL, NULL)) != 0) {
785 goto cleanup;
786 }
787
788 #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
789 /*
790 * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
791 * that they can be easily recomputed from D, P and Q. However by
792 * parsing them from the PKCS1 structure it is possible to avoid
793 * recalculating them which both reduces the overhead of loading
794 * RSA private keys into memory and also avoids side channels which
795 * can arise when computing those values, since all of D, P, and Q
796 * are secret. See https://eprint.iacr.org/2020/055 for a
797 * description of one such attack.
798 */
799
800 /* Import DP */
801 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
802 (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
803 goto cleanup;
804 }
805
806 /* Import DQ */
807 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
808 (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
809 goto cleanup;
810 }
811
812 /* Import QP */
813 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
814 (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
815 goto cleanup;
816 }
817
818 #else
819 /* Verify existence of the CRT params */
820 if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
821 (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
822 (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0) {
823 goto cleanup;
824 }
825 #endif
826
827 /* rsa_complete() doesn't complete anything with the default
828 * implementation but is still called:
829 * - for the benefit of alternative implementation that may want to
830 * pre-compute stuff beyond what's provided (eg Montgomery factors)
831 * - as is also sanity-checks the key
832 *
833 * Furthermore, we also check the public part for consistency with
834 * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
835 */
836 if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
837 (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
838 goto cleanup;
839 }
840
841 if (p != end) {
842 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
843 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
844 }
845
846 cleanup:
847
848 mbedtls_mpi_free(&T);
849
850 if (ret != 0) {
851 /* Wrap error code if it's coming from a lower level */
852 if ((ret & 0xff80) == 0) {
853 ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
854 } else {
855 ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
856 }
857
858 mbedtls_rsa_free(rsa);
859 }
860
861 return ret;
862 }
863 #endif /* MBEDTLS_RSA_C */
864
865 #if defined(MBEDTLS_ECP_C)
866 /*
867 * Parse a SEC1 encoded private EC key
868 */
pk_parse_key_sec1_der(mbedtls_ecp_keypair * eck,const unsigned char * key,size_t keylen)869 static int pk_parse_key_sec1_der(mbedtls_ecp_keypair *eck,
870 const unsigned char *key,
871 size_t keylen)
872 {
873 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
874 int version, pubkey_done;
875 size_t len;
876 mbedtls_asn1_buf params;
877 unsigned char *p = (unsigned char *) key;
878 unsigned char *end = p + keylen;
879 unsigned char *end2;
880
881 /*
882 * RFC 5915, or SEC1 Appendix C.4
883 *
884 * ECPrivateKey ::= SEQUENCE {
885 * version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
886 * privateKey OCTET STRING,
887 * parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
888 * publicKey [1] BIT STRING OPTIONAL
889 * }
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 = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
899 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
900 }
901
902 if (version != 1) {
903 return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
904 }
905
906 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
907 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
908 }
909
910 if ((ret = mbedtls_mpi_read_binary(&eck->d, p, len)) != 0) {
911 mbedtls_ecp_keypair_free(eck);
912 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
913 }
914
915 p += len;
916
917 pubkey_done = 0;
918 if (p != end) {
919 /*
920 * Is 'parameters' present?
921 */
922 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
923 MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
924 0)) == 0) {
925 if ((ret = pk_get_ecparams(&p, p + len, ¶ms)) != 0 ||
926 (ret = pk_use_ecparams(¶ms, &eck->grp)) != 0) {
927 mbedtls_ecp_keypair_free(eck);
928 return ret;
929 }
930 } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
931 mbedtls_ecp_keypair_free(eck);
932 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
933 }
934 }
935
936 if (p != end) {
937 /*
938 * Is 'publickey' present? If not, or if we can't read it (eg because it
939 * is compressed), create it from the private key.
940 */
941 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
942 MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
943 1)) == 0) {
944 end2 = p + len;
945
946 if ((ret = mbedtls_asn1_get_bitstring_null(&p, end2, &len)) != 0) {
947 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
948 }
949
950 if (p + len != end2) {
951 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
952 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
953 }
954
955 if ((ret = pk_get_ecpubkey(&p, end2, eck)) == 0) {
956 pubkey_done = 1;
957 } else {
958 /*
959 * The only acceptable failure mode of pk_get_ecpubkey() above
960 * is if the point format is not recognized.
961 */
962 if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) {
963 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
964 }
965 }
966 } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
967 mbedtls_ecp_keypair_free(eck);
968 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
969 }
970 }
971
972 if (!pubkey_done &&
973 (ret = mbedtls_ecp_mul(&eck->grp, &eck->Q, &eck->d, &eck->grp.G,
974 NULL, NULL)) != 0) {
975 mbedtls_ecp_keypair_free(eck);
976 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
977 }
978
979 if ((ret = mbedtls_ecp_check_privkey(&eck->grp, &eck->d)) != 0) {
980 mbedtls_ecp_keypair_free(eck);
981 return ret;
982 }
983
984 return 0;
985 }
986 #endif /* MBEDTLS_ECP_C */
987
988 /*
989 * Parse an unencrypted PKCS#8 encoded private key
990 *
991 * Notes:
992 *
993 * - This function does not own the key buffer. It is the
994 * responsibility of the caller to take care of zeroizing
995 * and freeing it after use.
996 *
997 * - The function is responsible for freeing the provided
998 * PK context on failure.
999 *
1000 */
pk_parse_key_pkcs8_unencrypted_der(mbedtls_pk_context * pk,const unsigned char * key,size_t keylen)1001 static int pk_parse_key_pkcs8_unencrypted_der(
1002 mbedtls_pk_context *pk,
1003 const unsigned char *key,
1004 size_t keylen)
1005 {
1006 int ret, version;
1007 size_t len;
1008 mbedtls_asn1_buf params;
1009 unsigned char *p = (unsigned char *) key;
1010 unsigned char *end = p + keylen;
1011 mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
1012 const mbedtls_pk_info_t *pk_info;
1013
1014 /*
1015 * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)
1016 *
1017 * PrivateKeyInfo ::= SEQUENCE {
1018 * version Version,
1019 * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
1020 * privateKey PrivateKey,
1021 * attributes [0] IMPLICIT Attributes OPTIONAL }
1022 *
1023 * Version ::= INTEGER
1024 * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
1025 * PrivateKey ::= OCTET STRING
1026 *
1027 * The PrivateKey OCTET STRING is a SEC1 ECPrivateKey
1028 */
1029
1030 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1031 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1032 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1033 }
1034
1035 end = p + len;
1036
1037 if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
1038 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1039 }
1040
1041 if (version != 0) {
1042 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_VERSION, ret);
1043 }
1044
1045 if ((ret = pk_get_pk_alg(&p, end, &pk_alg, ¶ms)) != 0) {
1046 return ret;
1047 }
1048
1049 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1050 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1051 }
1052
1053 if (len < 1) {
1054 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1055 MBEDTLS_ERR_ASN1_OUT_OF_DATA);
1056 }
1057
1058 if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
1059 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1060 }
1061
1062 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
1063 return ret;
1064 }
1065
1066 #if defined(MBEDTLS_RSA_C)
1067 if (pk_alg == MBEDTLS_PK_RSA) {
1068 if ((ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), p, len)) != 0) {
1069 mbedtls_pk_free(pk);
1070 return ret;
1071 }
1072 } else
1073 #endif /* MBEDTLS_RSA_C */
1074 #if defined(MBEDTLS_ECP_C)
1075 if (pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH) {
1076 if ((ret = pk_use_ecparams(¶ms, &mbedtls_pk_ec(*pk)->grp)) != 0 ||
1077 (ret = pk_parse_key_sec1_der(mbedtls_pk_ec(*pk), p, len)) != 0) {
1078 mbedtls_pk_free(pk);
1079 return ret;
1080 }
1081 } else
1082 #endif /* MBEDTLS_ECP_C */
1083 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1084
1085 return 0;
1086 }
1087
1088 /*
1089 * Parse an encrypted PKCS#8 encoded private key
1090 *
1091 * To save space, the decryption happens in-place on the given key buffer.
1092 * Also, while this function may modify the keybuffer, it doesn't own it,
1093 * and instead it is the responsibility of the caller to zeroize and properly
1094 * free it after use.
1095 *
1096 */
1097 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
pk_parse_key_pkcs8_encrypted_der(mbedtls_pk_context * pk,unsigned char * key,size_t keylen,const unsigned char * pwd,size_t pwdlen)1098 static int pk_parse_key_pkcs8_encrypted_der(
1099 mbedtls_pk_context *pk,
1100 unsigned char *key, size_t keylen,
1101 const unsigned char *pwd, size_t pwdlen)
1102 {
1103 int ret, decrypted = 0;
1104 size_t len;
1105 unsigned char *buf;
1106 unsigned char *p, *end;
1107 mbedtls_asn1_buf pbe_alg_oid, pbe_params;
1108 #if defined(MBEDTLS_PKCS12_C)
1109 mbedtls_cipher_type_t cipher_alg;
1110 mbedtls_md_type_t md_alg;
1111 #endif
1112
1113 p = key;
1114 end = p + keylen;
1115
1116 if (pwdlen == 0) {
1117 return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1118 }
1119
1120 /*
1121 * This function parses the EncryptedPrivateKeyInfo object (PKCS#8)
1122 *
1123 * EncryptedPrivateKeyInfo ::= SEQUENCE {
1124 * encryptionAlgorithm EncryptionAlgorithmIdentifier,
1125 * encryptedData EncryptedData
1126 * }
1127 *
1128 * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
1129 *
1130 * EncryptedData ::= OCTET STRING
1131 *
1132 * The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
1133 *
1134 */
1135 if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1136 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1137 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1138 }
1139
1140 end = p + len;
1141
1142 if ((ret = mbedtls_asn1_get_alg(&p, end, &pbe_alg_oid, &pbe_params)) != 0) {
1143 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1144 }
1145
1146 if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1147 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1148 }
1149
1150 buf = p;
1151
1152 /*
1153 * Decrypt EncryptedData with appropriate PBE
1154 */
1155 #if defined(MBEDTLS_PKCS12_C)
1156 if (mbedtls_oid_get_pkcs12_pbe_alg(&pbe_alg_oid, &md_alg, &cipher_alg) == 0) {
1157 if ((ret = mbedtls_pkcs12_pbe(&pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,
1158 cipher_alg, md_alg,
1159 pwd, pwdlen, p, len, buf)) != 0) {
1160 if (ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) {
1161 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1162 }
1163
1164 return ret;
1165 }
1166
1167 decrypted = 1;
1168 } else if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid) == 0) {
1169 if ((ret = mbedtls_pkcs12_pbe_sha1_rc4_128(&pbe_params,
1170 MBEDTLS_PKCS12_PBE_DECRYPT,
1171 pwd, pwdlen,
1172 p, len, buf)) != 0) {
1173 return ret;
1174 }
1175
1176 // Best guess for password mismatch when using RC4. If first tag is
1177 // not MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
1178 //
1179 if (*buf != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
1180 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1181 }
1182
1183 decrypted = 1;
1184 } else
1185 #endif /* MBEDTLS_PKCS12_C */
1186 #if defined(MBEDTLS_PKCS5_C)
1187 if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid) == 0) {
1188 if ((ret = mbedtls_pkcs5_pbes2(&pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,
1189 p, len, buf)) != 0) {
1190 if (ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) {
1191 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1192 }
1193
1194 return ret;
1195 }
1196
1197 decrypted = 1;
1198 } else
1199 #endif /* MBEDTLS_PKCS5_C */
1200 {
1201 ((void) pwd);
1202 }
1203
1204 if (decrypted == 0) {
1205 return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1206 }
1207
1208 return pk_parse_key_pkcs8_unencrypted_der(pk, buf, len);
1209 }
1210 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1211
1212 /*
1213 * Parse a private key
1214 */
mbedtls_pk_parse_key(mbedtls_pk_context * pk,const unsigned char * key,size_t keylen,const unsigned char * pwd,size_t pwdlen)1215 int mbedtls_pk_parse_key(mbedtls_pk_context *pk,
1216 const unsigned char *key, size_t keylen,
1217 const unsigned char *pwd, size_t pwdlen)
1218 {
1219 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1220 const mbedtls_pk_info_t *pk_info;
1221 #if defined(MBEDTLS_PEM_PARSE_C)
1222 size_t len;
1223 mbedtls_pem_context pem;
1224 #endif
1225
1226 (void) pk_info;
1227
1228 PK_VALIDATE_RET(pk != NULL);
1229 if (keylen == 0) {
1230 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1231 }
1232 PK_VALIDATE_RET(key != NULL);
1233
1234 #if defined(MBEDTLS_PEM_PARSE_C)
1235 mbedtls_pem_init(&pem);
1236
1237 #if defined(MBEDTLS_RSA_C)
1238 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1239 if (key[keylen - 1] != '\0') {
1240 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1241 } else {
1242 ret = mbedtls_pem_read_buffer(&pem,
1243 "-----BEGIN RSA PRIVATE KEY-----",
1244 "-----END RSA PRIVATE KEY-----",
1245 key, pwd, pwdlen, &len);
1246 }
1247
1248 if (ret == 0) {
1249 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1250 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1251 (ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk),
1252 pem.buf, pem.buflen)) != 0) {
1253 mbedtls_pk_free(pk);
1254 }
1255
1256 mbedtls_pem_free(&pem);
1257 return ret;
1258 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1259 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1260 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1261 return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1262 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1263 return ret;
1264 }
1265 #endif /* MBEDTLS_RSA_C */
1266
1267 #if defined(MBEDTLS_ECP_C)
1268 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1269 if (key[keylen - 1] != '\0') {
1270 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1271 } else {
1272 ret = mbedtls_pem_read_buffer(&pem,
1273 "-----BEGIN EC PRIVATE KEY-----",
1274 "-----END EC PRIVATE KEY-----",
1275 key, pwd, pwdlen, &len);
1276 }
1277 if (ret == 0) {
1278 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1279
1280 if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1281 (ret = pk_parse_key_sec1_der(mbedtls_pk_ec(*pk),
1282 pem.buf, pem.buflen)) != 0) {
1283 mbedtls_pk_free(pk);
1284 }
1285
1286 mbedtls_pem_free(&pem);
1287 return ret;
1288 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1289 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1290 } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1291 return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1292 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1293 return ret;
1294 }
1295 #endif /* MBEDTLS_ECP_C */
1296
1297 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1298 if (key[keylen - 1] != '\0') {
1299 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1300 } else {
1301 ret = mbedtls_pem_read_buffer(&pem,
1302 "-----BEGIN PRIVATE KEY-----",
1303 "-----END PRIVATE KEY-----",
1304 key, NULL, 0, &len);
1305 }
1306 if (ret == 0) {
1307 if ((ret = pk_parse_key_pkcs8_unencrypted_der(pk,
1308 pem.buf, pem.buflen)) != 0) {
1309 mbedtls_pk_free(pk);
1310 }
1311
1312 mbedtls_pem_free(&pem);
1313 return ret;
1314 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1315 return ret;
1316 }
1317
1318 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1319 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1320 if (key[keylen - 1] != '\0') {
1321 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1322 } else {
1323 ret = mbedtls_pem_read_buffer(&pem,
1324 "-----BEGIN ENCRYPTED PRIVATE KEY-----",
1325 "-----END ENCRYPTED PRIVATE KEY-----",
1326 key, NULL, 0, &len);
1327 }
1328 if (ret == 0) {
1329 if ((ret = pk_parse_key_pkcs8_encrypted_der(pk,
1330 pem.buf, pem.buflen,
1331 pwd, pwdlen)) != 0) {
1332 mbedtls_pk_free(pk);
1333 }
1334
1335 mbedtls_pem_free(&pem);
1336 return ret;
1337 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1338 return ret;
1339 }
1340 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1341 #else
1342 ((void) pwd);
1343 ((void) pwdlen);
1344 #endif /* MBEDTLS_PEM_PARSE_C */
1345
1346 /*
1347 * At this point we only know it's not a PEM formatted key. Could be any
1348 * of the known DER encoded private key formats
1349 *
1350 * We try the different DER format parsers to see if one passes without
1351 * error
1352 */
1353 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1354 {
1355 unsigned char *key_copy;
1356
1357 if ((key_copy = mbedtls_calloc(1, keylen)) == NULL) {
1358 return MBEDTLS_ERR_PK_ALLOC_FAILED;
1359 }
1360
1361 memcpy(key_copy, key, keylen);
1362
1363 ret = pk_parse_key_pkcs8_encrypted_der(pk, key_copy, keylen,
1364 pwd, pwdlen);
1365
1366 mbedtls_platform_zeroize(key_copy, keylen);
1367 mbedtls_free(key_copy);
1368 }
1369
1370 if (ret == 0) {
1371 return 0;
1372 }
1373
1374 mbedtls_pk_free(pk);
1375 mbedtls_pk_init(pk);
1376
1377 if (ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH) {
1378 return ret;
1379 }
1380 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1381
1382 ret = pk_parse_key_pkcs8_unencrypted_der(pk, key, keylen);
1383 if (ret == 0) {
1384 return 0;
1385 }
1386
1387 mbedtls_pk_free(pk);
1388 mbedtls_pk_init(pk);
1389
1390 #if defined(MBEDTLS_RSA_C)
1391
1392 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1393 if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1394 pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), key, keylen) == 0) {
1395 return 0;
1396 }
1397
1398 mbedtls_pk_free(pk);
1399 mbedtls_pk_init(pk);
1400 #endif /* MBEDTLS_RSA_C */
1401
1402 #if defined(MBEDTLS_ECP_C)
1403 pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1404 if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1405 pk_parse_key_sec1_der(mbedtls_pk_ec(*pk),
1406 key, keylen) == 0) {
1407 return 0;
1408 }
1409 mbedtls_pk_free(pk);
1410 #endif /* MBEDTLS_ECP_C */
1411
1412 /* If MBEDTLS_RSA_C is defined but MBEDTLS_ECP_C isn't,
1413 * it is ok to leave the PK context initialized but not
1414 * freed: It is the caller's responsibility to call pk_init()
1415 * before calling this function, and to call pk_free()
1416 * when it fails. If MBEDTLS_ECP_C is defined but MBEDTLS_RSA_C
1417 * isn't, this leads to mbedtls_pk_free() being called
1418 * twice, once here and once by the caller, but this is
1419 * also ok and in line with the mbedtls_pk_free() calls
1420 * on failed PEM parsing attempts. */
1421
1422 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1423 }
1424
1425 /*
1426 * Parse a public key
1427 */
mbedtls_pk_parse_public_key(mbedtls_pk_context * ctx,const unsigned char * key,size_t keylen)1428 int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
1429 const unsigned char *key, size_t keylen)
1430 {
1431 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1432 unsigned char *p;
1433 #if defined(MBEDTLS_RSA_C)
1434 const mbedtls_pk_info_t *pk_info;
1435 #endif
1436 #if defined(MBEDTLS_PEM_PARSE_C)
1437 size_t len;
1438 mbedtls_pem_context pem;
1439 #endif
1440
1441 PK_VALIDATE_RET(ctx != NULL);
1442 if (keylen == 0) {
1443 return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1444 }
1445 PK_VALIDATE_RET(key != NULL || keylen == 0);
1446
1447 #if defined(MBEDTLS_PEM_PARSE_C)
1448 mbedtls_pem_init(&pem);
1449 #if defined(MBEDTLS_RSA_C)
1450 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1451 if (key[keylen - 1] != '\0') {
1452 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1453 } else {
1454 ret = mbedtls_pem_read_buffer(&pem,
1455 "-----BEGIN RSA PUBLIC KEY-----",
1456 "-----END RSA PUBLIC KEY-----",
1457 key, NULL, 0, &len);
1458 }
1459
1460 if (ret == 0) {
1461 p = pem.buf;
1462 if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1463 mbedtls_pem_free(&pem);
1464 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1465 }
1466
1467 if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1468 mbedtls_pem_free(&pem);
1469 return ret;
1470 }
1471
1472 if ((ret = pk_get_rsapubkey(&p, p + pem.buflen, mbedtls_pk_rsa(*ctx))) != 0) {
1473 mbedtls_pk_free(ctx);
1474 }
1475
1476 mbedtls_pem_free(&pem);
1477 return ret;
1478 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1479 mbedtls_pem_free(&pem);
1480 return ret;
1481 }
1482 #endif /* MBEDTLS_RSA_C */
1483
1484 /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1485 if (key[keylen - 1] != '\0') {
1486 ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1487 } else {
1488 ret = mbedtls_pem_read_buffer(&pem,
1489 "-----BEGIN PUBLIC KEY-----",
1490 "-----END PUBLIC KEY-----",
1491 key, NULL, 0, &len);
1492 }
1493
1494 if (ret == 0) {
1495 /*
1496 * Was PEM encoded
1497 */
1498 p = pem.buf;
1499
1500 ret = mbedtls_pk_parse_subpubkey(&p, p + pem.buflen, ctx);
1501 mbedtls_pem_free(&pem);
1502 return ret;
1503 } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1504 mbedtls_pem_free(&pem);
1505 return ret;
1506 }
1507 mbedtls_pem_free(&pem);
1508 #endif /* MBEDTLS_PEM_PARSE_C */
1509
1510 #if defined(MBEDTLS_RSA_C)
1511 if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1512 return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1513 }
1514
1515 if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1516 return ret;
1517 }
1518
1519 p = (unsigned char *) key;
1520 ret = pk_get_rsapubkey(&p, p + keylen, mbedtls_pk_rsa(*ctx));
1521 if (ret == 0) {
1522 return ret;
1523 }
1524 mbedtls_pk_free(ctx);
1525 if (ret != (MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
1526 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG))) {
1527 return ret;
1528 }
1529 #endif /* MBEDTLS_RSA_C */
1530 p = (unsigned char *) key;
1531
1532 ret = mbedtls_pk_parse_subpubkey(&p, p + keylen, ctx);
1533
1534 return ret;
1535 }
1536
1537 #endif /* MBEDTLS_PK_PARSE_C */
1538