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
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include "common.h"
21 
22 #if defined(MBEDTLS_PK_PARSE_C)
23 
24 #include "mbedtls/pk.h"
25 #include "mbedtls/asn1.h"
26 #include "mbedtls/oid.h"
27 #include "mbedtls/platform_util.h"
28 #include "mbedtls/error.h"
29 
30 #include <string.h>
31 
32 #if defined(MBEDTLS_RSA_C)
33 #include "mbedtls/rsa.h"
34 #endif
35 #if defined(MBEDTLS_ECP_C)
36 #include "mbedtls/ecp.h"
37 #endif
38 #if defined(MBEDTLS_ECDSA_C)
39 #include "mbedtls/ecdsa.h"
40 #endif
41 #if defined(MBEDTLS_PEM_PARSE_C)
42 #include "mbedtls/pem.h"
43 #endif
44 #if defined(MBEDTLS_PKCS5_C)
45 #include "mbedtls/pkcs5.h"
46 #endif
47 #if defined(MBEDTLS_PKCS12_C)
48 #include "mbedtls/pkcs12.h"
49 #endif
50 
51 #include "mbedtls/platform.h"
52 
53 #if defined(MBEDTLS_FS_IO)
54 /*
55  * Load all data from a file into a given buffer.
56  *
57  * The file is expected to contain either PEM or DER encoded data.
58  * A terminating null byte is always appended. It is included in the announced
59  * length only if the data looks like it is PEM encoded.
60  */
mbedtls_pk_load_file(const char * path,unsigned char ** buf,size_t * n)61 int mbedtls_pk_load_file(const char *path, unsigned char **buf, size_t *n)
62 {
63     FILE *f;
64     long size;
65 
66     if ((f = fopen(path, "rb")) == NULL) {
67         return MBEDTLS_ERR_PK_FILE_IO_ERROR;
68     }
69 
70     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
71     mbedtls_setbuf(f, NULL);
72 
73     fseek(f, 0, SEEK_END);
74     if ((size = ftell(f)) == -1) {
75         fclose(f);
76         return MBEDTLS_ERR_PK_FILE_IO_ERROR;
77     }
78     fseek(f, 0, SEEK_SET);
79 
80     *n = (size_t) size;
81 
82     if (*n + 1 == 0 ||
83         (*buf = mbedtls_calloc(1, *n + 1)) == NULL) {
84         fclose(f);
85         return MBEDTLS_ERR_PK_ALLOC_FAILED;
86     }
87 
88     if (fread(*buf, 1, *n, f) != *n) {
89         fclose(f);
90 
91         mbedtls_platform_zeroize(*buf, *n);
92         mbedtls_free(*buf);
93 
94         return MBEDTLS_ERR_PK_FILE_IO_ERROR;
95     }
96 
97     fclose(f);
98 
99     (*buf)[*n] = '\0';
100 
101     if (strstr((const char *) *buf, "-----BEGIN ") != NULL) {
102         ++*n;
103     }
104 
105     return 0;
106 }
107 
108 /*
109  * Load and parse a private key
110  */
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)111 int mbedtls_pk_parse_keyfile(mbedtls_pk_context *ctx,
112                              const char *path, const char *pwd,
113                              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
114 {
115     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
116     size_t n;
117     unsigned char *buf;
118 
119     if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
120         return ret;
121     }
122 
123     if (pwd == NULL) {
124         ret = mbedtls_pk_parse_key(ctx, buf, n, NULL, 0, f_rng, p_rng);
125     } else {
126         ret = mbedtls_pk_parse_key(ctx, buf, n,
127                                    (const unsigned char *) pwd, strlen(pwd), f_rng, p_rng);
128     }
129 
130     mbedtls_platform_zeroize(buf, n);
131     mbedtls_free(buf);
132 
133     return ret;
134 }
135 
136 /*
137  * Load and parse a public key
138  */
mbedtls_pk_parse_public_keyfile(mbedtls_pk_context * ctx,const char * path)139 int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path)
140 {
141     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
142     size_t n;
143     unsigned char *buf;
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, &params->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     /* 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 /*
450  * Use EC parameters to initialise an EC group
451  *
452  * ECParameters ::= CHOICE {
453  *   namedCurve         OBJECT IDENTIFIER
454  *   specifiedCurve     SpecifiedECDomain -- = SEQUENCE { ... }
455  *   -- implicitCurve   NULL
456  */
pk_use_ecparams(const mbedtls_asn1_buf * params,mbedtls_ecp_group * grp)457 static int pk_use_ecparams(const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp)
458 {
459     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
460     mbedtls_ecp_group_id grp_id;
461 
462     if (params->tag == MBEDTLS_ASN1_OID) {
463         if (mbedtls_oid_get_ec_grp(params, &grp_id) != 0) {
464             return MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE;
465         }
466     } else {
467 #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
468         if ((ret = pk_group_id_from_specified(params, &grp_id)) != 0) {
469             return ret;
470         }
471 #else
472         return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
473 #endif
474     }
475 
476     /*
477      * grp may already be initialized; if so, make sure IDs match
478      */
479     if (grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id) {
480         return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
481     }
482 
483     if ((ret = mbedtls_ecp_group_load(grp, grp_id)) != 0) {
484         return ret;
485     }
486 
487     return 0;
488 }
489 
490 /*
491  * EC public key is an EC point
492  *
493  * The caller is responsible for clearing the structure upon failure if
494  * desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE
495  * return code of mbedtls_ecp_point_read_binary() and leave p in a usable state.
496  */
pk_get_ecpubkey(unsigned char ** p,const unsigned char * end,mbedtls_ecp_keypair * key)497 static int pk_get_ecpubkey(unsigned char **p, const unsigned char *end,
498                            mbedtls_ecp_keypair *key)
499 {
500     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
501 
502     if ((ret = mbedtls_ecp_point_read_binary(&key->grp, &key->Q,
503                                              (const unsigned char *) *p, end - *p)) == 0) {
504         ret = mbedtls_ecp_check_pubkey(&key->grp, &key->Q);
505     }
506 
507     /*
508      * We know mbedtls_ecp_point_read_binary consumed all bytes or failed
509      */
510     *p = (unsigned char *) end;
511 
512     return ret;
513 }
514 #endif /* MBEDTLS_ECP_C */
515 
516 #if defined(MBEDTLS_RSA_C)
517 /*
518  *  RSAPublicKey ::= SEQUENCE {
519  *      modulus           INTEGER,  -- n
520  *      publicExponent    INTEGER   -- e
521  *  }
522  */
pk_get_rsapubkey(unsigned char ** p,const unsigned char * end,mbedtls_rsa_context * rsa)523 static int pk_get_rsapubkey(unsigned char **p,
524                             const unsigned char *end,
525                             mbedtls_rsa_context *rsa)
526 {
527     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
528     size_t len;
529 
530     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
531                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
532         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
533     }
534 
535     if (*p + len != end) {
536         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
537                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
538     }
539 
540     /* Import N */
541     if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
542         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
543     }
544 
545     if ((ret = mbedtls_rsa_import_raw(rsa, *p, len, NULL, 0, NULL, 0,
546                                       NULL, 0, NULL, 0)) != 0) {
547         return MBEDTLS_ERR_PK_INVALID_PUBKEY;
548     }
549 
550     *p += len;
551 
552     /* Import E */
553     if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
554         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
555     }
556 
557     if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
558                                       NULL, 0, *p, len)) != 0) {
559         return MBEDTLS_ERR_PK_INVALID_PUBKEY;
560     }
561 
562     *p += len;
563 
564     if (mbedtls_rsa_complete(rsa) != 0 ||
565         mbedtls_rsa_check_pubkey(rsa) != 0) {
566         return MBEDTLS_ERR_PK_INVALID_PUBKEY;
567     }
568 
569     if (*p != end) {
570         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
571                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
572     }
573 
574     return 0;
575 }
576 #endif /* MBEDTLS_RSA_C */
577 
578 /* Get a PK algorithm identifier
579  *
580  *  AlgorithmIdentifier  ::=  SEQUENCE  {
581  *       algorithm               OBJECT IDENTIFIER,
582  *       parameters              ANY DEFINED BY algorithm OPTIONAL  }
583  */
pk_get_pk_alg(unsigned char ** p,const unsigned char * end,mbedtls_pk_type_t * pk_alg,mbedtls_asn1_buf * params)584 static int pk_get_pk_alg(unsigned char **p,
585                          const unsigned char *end,
586                          mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params)
587 {
588     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
589     mbedtls_asn1_buf alg_oid;
590 
591     memset(params, 0, sizeof(mbedtls_asn1_buf));
592 
593     if ((ret = mbedtls_asn1_get_alg(p, end, &alg_oid, params)) != 0) {
594         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_ALG, ret);
595     }
596 
597     if (mbedtls_oid_get_pk_alg(&alg_oid, pk_alg) != 0) {
598         return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
599     }
600 
601     /*
602      * No parameters with RSA (only for EC)
603      */
604     if (*pk_alg == MBEDTLS_PK_RSA &&
605         ((params->tag != MBEDTLS_ASN1_NULL && params->tag != 0) ||
606          params->len != 0)) {
607         return MBEDTLS_ERR_PK_INVALID_ALG;
608     }
609 
610     return 0;
611 }
612 
613 /*
614  *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
615  *       algorithm            AlgorithmIdentifier,
616  *       subjectPublicKey     BIT STRING }
617  */
mbedtls_pk_parse_subpubkey(unsigned char ** p,const unsigned char * end,mbedtls_pk_context * pk)618 int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
619                                mbedtls_pk_context *pk)
620 {
621     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
622     size_t len;
623     mbedtls_asn1_buf alg_params;
624     mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
625     const mbedtls_pk_info_t *pk_info;
626 
627     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
628                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
629         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
630     }
631 
632     end = *p + len;
633 
634     if ((ret = pk_get_pk_alg(p, end, &pk_alg, &alg_params)) != 0) {
635         return ret;
636     }
637 
638     if ((ret = mbedtls_asn1_get_bitstring_null(p, end, &len)) != 0) {
639         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
640     }
641 
642     if (*p + len != end) {
643         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
644                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
645     }
646 
647     if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
648         return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
649     }
650 
651     if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
652         return ret;
653     }
654 
655 #if defined(MBEDTLS_RSA_C)
656     if (pk_alg == MBEDTLS_PK_RSA) {
657         ret = pk_get_rsapubkey(p, end, mbedtls_pk_rsa(*pk));
658     } else
659 #endif /* MBEDTLS_RSA_C */
660 #if defined(MBEDTLS_ECP_C)
661     if (pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY) {
662         ret = pk_use_ecparams(&alg_params, &mbedtls_pk_ec(*pk)->grp);
663         if (ret == 0) {
664             ret = pk_get_ecpubkey(p, end, mbedtls_pk_ec(*pk));
665         }
666     } else
667 #endif /* MBEDTLS_ECP_C */
668     ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
669 
670     if (ret == 0 && *p != end) {
671         ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
672                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
673     }
674 
675     if (ret != 0) {
676         mbedtls_pk_free(pk);
677     }
678 
679     return ret;
680 }
681 
682 #if defined(MBEDTLS_RSA_C)
683 /*
684  * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
685  *
686  * The value zero is:
687  * - never a valid value for an RSA parameter
688  * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
689  *
690  * Since values can't be omitted in PKCS#1, passing a zero value to
691  * rsa_complete() would be incorrect, so reject zero values early.
692  */
asn1_get_nonzero_mpi(unsigned char ** p,const unsigned char * end,mbedtls_mpi * X)693 static int asn1_get_nonzero_mpi(unsigned char **p,
694                                 const unsigned char *end,
695                                 mbedtls_mpi *X)
696 {
697     int ret;
698 
699     ret = mbedtls_asn1_get_mpi(p, end, X);
700     if (ret != 0) {
701         return ret;
702     }
703 
704     if (mbedtls_mpi_cmp_int(X, 0) == 0) {
705         return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
706     }
707 
708     return 0;
709 }
710 
711 /*
712  * Parse a PKCS#1 encoded private RSA key
713  */
pk_parse_key_pkcs1_der(mbedtls_rsa_context * rsa,const unsigned char * key,size_t keylen)714 static int pk_parse_key_pkcs1_der(mbedtls_rsa_context *rsa,
715                                   const unsigned char *key,
716                                   size_t keylen)
717 {
718     int ret, version;
719     size_t len;
720     unsigned char *p, *end;
721 
722     mbedtls_mpi T;
723     mbedtls_mpi_init(&T);
724 
725     p = (unsigned char *) key;
726     end = p + keylen;
727 
728     /*
729      * This function parses the RSAPrivateKey (PKCS#1)
730      *
731      *  RSAPrivateKey ::= SEQUENCE {
732      *      version           Version,
733      *      modulus           INTEGER,  -- n
734      *      publicExponent    INTEGER,  -- e
735      *      privateExponent   INTEGER,  -- d
736      *      prime1            INTEGER,  -- p
737      *      prime2            INTEGER,  -- q
738      *      exponent1         INTEGER,  -- d mod (p-1)
739      *      exponent2         INTEGER,  -- d mod (q-1)
740      *      coefficient       INTEGER,  -- (inverse of q) mod p
741      *      otherPrimeInfos   OtherPrimeInfos OPTIONAL
742      *  }
743      */
744     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
745                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
746         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
747     }
748 
749     end = p + len;
750 
751     if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
752         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
753     }
754 
755     if (version != 0) {
756         return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
757     }
758 
759     /* Import N */
760     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
761         (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
762                                   NULL, NULL)) != 0) {
763         goto cleanup;
764     }
765 
766     /* Import E */
767     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
768         (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
769                                   NULL, &T)) != 0) {
770         goto cleanup;
771     }
772 
773     /* Import D */
774     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
775         (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
776                                   &T, NULL)) != 0) {
777         goto cleanup;
778     }
779 
780     /* Import P */
781     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
782         (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
783                                   NULL, NULL)) != 0) {
784         goto cleanup;
785     }
786 
787     /* Import Q */
788     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
789         (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
790                                   NULL, NULL)) != 0) {
791         goto cleanup;
792     }
793 
794 #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
795     /*
796      * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
797      * that they can be easily recomputed from D, P and Q. However by
798      * parsing them from the PKCS1 structure it is possible to avoid
799      * recalculating them which both reduces the overhead of loading
800      * RSA private keys into memory and also avoids side channels which
801      * can arise when computing those values, since all of D, P, and Q
802      * are secret. See https://eprint.iacr.org/2020/055 for a
803      * description of one such attack.
804      */
805 
806     /* Import DP */
807     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
808         (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
809         goto cleanup;
810     }
811 
812     /* Import DQ */
813     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
814         (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
815         goto cleanup;
816     }
817 
818     /* Import QP */
819     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
820         (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
821         goto cleanup;
822     }
823 
824 #else
825     /* Verify existence of the CRT params */
826     if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
827         (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
828         (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0) {
829         goto cleanup;
830     }
831 #endif
832 
833     /* rsa_complete() doesn't complete anything with the default
834      * implementation but is still called:
835      * - for the benefit of alternative implementation that may want to
836      *   pre-compute stuff beyond what's provided (eg Montgomery factors)
837      * - as is also sanity-checks the key
838      *
839      * Furthermore, we also check the public part for consistency with
840      * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
841      */
842     if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
843         (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
844         goto cleanup;
845     }
846 
847     if (p != end) {
848         ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
849                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
850     }
851 
852 cleanup:
853 
854     mbedtls_mpi_free(&T);
855 
856     if (ret != 0) {
857         /* Wrap error code if it's coming from a lower level */
858         if ((ret & 0xff80) == 0) {
859             ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
860         } else {
861             ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
862         }
863 
864         mbedtls_rsa_free(rsa);
865     }
866 
867     return ret;
868 }
869 #endif /* MBEDTLS_RSA_C */
870 
871 #if defined(MBEDTLS_ECP_C)
872 /*
873  * Parse a SEC1 encoded private EC key
874  */
pk_parse_key_sec1_der(mbedtls_ecp_keypair * eck,const unsigned char * key,size_t keylen,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)875 static int pk_parse_key_sec1_der(mbedtls_ecp_keypair *eck,
876                                  const unsigned char *key, size_t keylen,
877                                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
878 {
879     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
880     int version, pubkey_done;
881     size_t len;
882     mbedtls_asn1_buf params = { 0, 0, NULL };
883     unsigned char *p = (unsigned char *) key;
884     unsigned char *end = p + keylen;
885     unsigned char *end2;
886 
887     /*
888      * RFC 5915, or SEC1 Appendix C.4
889      *
890      * ECPrivateKey ::= SEQUENCE {
891      *      version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
892      *      privateKey     OCTET STRING,
893      *      parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
894      *      publicKey  [1] BIT STRING OPTIONAL
895      *    }
896      */
897     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
898                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
899         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
900     }
901 
902     end = p + len;
903 
904     if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
905         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
906     }
907 
908     if (version != 1) {
909         return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
910     }
911 
912     if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
913         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
914     }
915 
916     if ((ret = mbedtls_mpi_read_binary(&eck->d, p, len)) != 0) {
917         mbedtls_ecp_keypair_free(eck);
918         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
919     }
920 
921     p += len;
922 
923     pubkey_done = 0;
924     if (p != end) {
925         /*
926          * Is 'parameters' present?
927          */
928         if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
929                                         MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
930                                         0)) == 0) {
931             if ((ret = pk_get_ecparams(&p, p + len, &params)) != 0 ||
932                 (ret = pk_use_ecparams(&params, &eck->grp)) != 0) {
933                 mbedtls_ecp_keypair_free(eck);
934                 return ret;
935             }
936         } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
937             mbedtls_ecp_keypair_free(eck);
938             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
939         }
940     }
941 
942     if (p != end) {
943         /*
944          * Is 'publickey' present? If not, or if we can't read it (eg because it
945          * is compressed), create it from the private key.
946          */
947         if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
948                                         MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
949                                         1)) == 0) {
950             end2 = p + len;
951 
952             if ((ret = mbedtls_asn1_get_bitstring_null(&p, end2, &len)) != 0) {
953                 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
954             }
955 
956             if (p + len != end2) {
957                 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
958                                          MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
959             }
960 
961             if ((ret = pk_get_ecpubkey(&p, end2, eck)) == 0) {
962                 pubkey_done = 1;
963             } else {
964                 /*
965                  * The only acceptable failure mode of pk_get_ecpubkey() above
966                  * is if the point format is not recognized.
967                  */
968                 if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) {
969                     return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
970                 }
971             }
972         } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
973             mbedtls_ecp_keypair_free(eck);
974             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
975         }
976     }
977 
978     if (!pubkey_done &&
979         (ret = mbedtls_ecp_mul(&eck->grp, &eck->Q, &eck->d, &eck->grp.G,
980                                f_rng, p_rng)) != 0) {
981         mbedtls_ecp_keypair_free(eck);
982         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
983     }
984 
985     if ((ret = mbedtls_ecp_check_privkey(&eck->grp, &eck->d)) != 0) {
986         mbedtls_ecp_keypair_free(eck);
987         return ret;
988     }
989 
990     return 0;
991 }
992 #endif /* MBEDTLS_ECP_C */
993 
994 /*
995  * Parse an unencrypted PKCS#8 encoded private key
996  *
997  * Notes:
998  *
999  * - This function does not own the key buffer. It is the
1000  *   responsibility of the caller to take care of zeroizing
1001  *   and freeing it after use.
1002  *
1003  * - The function is responsible for freeing the provided
1004  *   PK context on failure.
1005  *
1006  */
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)1007 static int pk_parse_key_pkcs8_unencrypted_der(
1008     mbedtls_pk_context *pk,
1009     const unsigned char *key, size_t keylen,
1010     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1011 {
1012     int ret, version;
1013     size_t len;
1014     mbedtls_asn1_buf params;
1015     unsigned char *p = (unsigned char *) key;
1016     unsigned char *end = p + keylen;
1017     mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
1018     const mbedtls_pk_info_t *pk_info;
1019 
1020 #if !defined(MBEDTLS_ECP_C)
1021     (void) f_rng;
1022     (void) p_rng;
1023 #endif
1024 
1025     /*
1026      * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)
1027      *
1028      *    PrivateKeyInfo ::= SEQUENCE {
1029      *      version                   Version,
1030      *      privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
1031      *      privateKey                PrivateKey,
1032      *      attributes           [0]  IMPLICIT Attributes OPTIONAL }
1033      *
1034      *    Version ::= INTEGER
1035      *    PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
1036      *    PrivateKey ::= OCTET STRING
1037      *
1038      *  The PrivateKey OCTET STRING is a SEC1 ECPrivateKey
1039      */
1040 
1041     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1042                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1043         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1044     }
1045 
1046     end = p + len;
1047 
1048     if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
1049         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1050     }
1051 
1052     if (version != 0) {
1053         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_VERSION, ret);
1054     }
1055 
1056     if ((ret = pk_get_pk_alg(&p, end, &pk_alg, &params)) != 0) {
1057         return ret;
1058     }
1059 
1060     if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1061         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1062     }
1063 
1064     if (len < 1) {
1065         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1066                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
1067     }
1068 
1069     if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
1070         return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1071     }
1072 
1073     if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
1074         return ret;
1075     }
1076 
1077 #if defined(MBEDTLS_RSA_C)
1078     if (pk_alg == MBEDTLS_PK_RSA) {
1079         if ((ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), p, len)) != 0) {
1080             mbedtls_pk_free(pk);
1081             return ret;
1082         }
1083     } else
1084 #endif /* MBEDTLS_RSA_C */
1085 #if defined(MBEDTLS_ECP_C)
1086     if (pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH) {
1087         if ((ret = pk_use_ecparams(&params, &mbedtls_pk_ec(*pk)->grp)) != 0 ||
1088             (ret = pk_parse_key_sec1_der(mbedtls_pk_ec(*pk), p, len, f_rng, p_rng)) != 0) {
1089             mbedtls_pk_free(pk);
1090             return ret;
1091         }
1092     } else
1093 #endif /* MBEDTLS_ECP_C */
1094     return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1095 
1096     return 0;
1097 }
1098 
1099 /*
1100  * Parse an encrypted PKCS#8 encoded private key
1101  *
1102  * To save space, the decryption happens in-place on the given key buffer.
1103  * Also, while this function may modify the keybuffer, it doesn't own it,
1104  * and instead it is the responsibility of the caller to zeroize and properly
1105  * free it after use.
1106  *
1107  */
1108 #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,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1109 static int pk_parse_key_pkcs8_encrypted_der(
1110     mbedtls_pk_context *pk,
1111     unsigned char *key, size_t keylen,
1112     const unsigned char *pwd, size_t pwdlen,
1113     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1114 {
1115     int ret, decrypted = 0;
1116     size_t len;
1117     unsigned char *buf;
1118     unsigned char *p, *end;
1119     mbedtls_asn1_buf pbe_alg_oid, pbe_params;
1120 #if defined(MBEDTLS_PKCS12_C)
1121     mbedtls_cipher_type_t cipher_alg;
1122     mbedtls_md_type_t md_alg;
1123 #endif
1124 
1125     p = key;
1126     end = p + keylen;
1127 
1128     if (pwdlen == 0) {
1129         return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1130     }
1131 
1132     /*
1133      * This function parses the EncryptedPrivateKeyInfo object (PKCS#8)
1134      *
1135      *  EncryptedPrivateKeyInfo ::= SEQUENCE {
1136      *    encryptionAlgorithm  EncryptionAlgorithmIdentifier,
1137      *    encryptedData        EncryptedData
1138      *  }
1139      *
1140      *  EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
1141      *
1142      *  EncryptedData ::= OCTET STRING
1143      *
1144      *  The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
1145      *
1146      */
1147     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1148                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1149         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1150     }
1151 
1152     end = p + len;
1153 
1154     if ((ret = mbedtls_asn1_get_alg(&p, end, &pbe_alg_oid, &pbe_params)) != 0) {
1155         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1156     }
1157 
1158     if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1159         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1160     }
1161 
1162     buf = p;
1163 
1164     /*
1165      * Decrypt EncryptedData with appropriate PBE
1166      */
1167 #if defined(MBEDTLS_PKCS12_C)
1168     if (mbedtls_oid_get_pkcs12_pbe_alg(&pbe_alg_oid, &md_alg, &cipher_alg) == 0) {
1169         if ((ret = mbedtls_pkcs12_pbe(&pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,
1170                                       cipher_alg, md_alg,
1171                                       pwd, pwdlen, p, len, buf)) != 0) {
1172             if (ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) {
1173                 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1174             }
1175 
1176             return ret;
1177         }
1178 
1179         decrypted = 1;
1180     } else
1181 #endif /* MBEDTLS_PKCS12_C */
1182 #if defined(MBEDTLS_PKCS5_C)
1183     if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid) == 0) {
1184         if ((ret = mbedtls_pkcs5_pbes2(&pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,
1185                                        p, len, buf)) != 0) {
1186             if (ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) {
1187                 return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1188             }
1189 
1190             return ret;
1191         }
1192 
1193         decrypted = 1;
1194     } else
1195 #endif /* MBEDTLS_PKCS5_C */
1196     {
1197         ((void) pwd);
1198     }
1199 
1200     if (decrypted == 0) {
1201         return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1202     }
1203 
1204     return pk_parse_key_pkcs8_unencrypted_der(pk, buf, len, f_rng, p_rng);
1205 }
1206 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1207 
1208 /*
1209  * Parse a private key
1210  */
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)1211 int mbedtls_pk_parse_key(mbedtls_pk_context *pk,
1212                          const unsigned char *key, size_t keylen,
1213                          const unsigned char *pwd, size_t pwdlen,
1214                          int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1215 {
1216     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1217     const mbedtls_pk_info_t *pk_info;
1218 #if defined(MBEDTLS_PEM_PARSE_C)
1219     size_t len;
1220     mbedtls_pem_context pem;
1221 #endif
1222 
1223     if (keylen == 0) {
1224         return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1225     }
1226 
1227 #if defined(MBEDTLS_PEM_PARSE_C)
1228     mbedtls_pem_init(&pem);
1229 
1230 #if defined(MBEDTLS_RSA_C)
1231     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1232     if (key[keylen - 1] != '\0') {
1233         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1234     } else {
1235         ret = mbedtls_pem_read_buffer(&pem,
1236                                       "-----BEGIN RSA PRIVATE KEY-----",
1237                                       "-----END RSA PRIVATE KEY-----",
1238                                       key, pwd, pwdlen, &len);
1239     }
1240 
1241     if (ret == 0) {
1242         pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1243         if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1244             (ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk),
1245                                           pem.buf, pem.buflen)) != 0) {
1246             mbedtls_pk_free(pk);
1247         }
1248 
1249         mbedtls_pem_free(&pem);
1250         return ret;
1251     } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1252         return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1253     } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1254         return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1255     } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1256         return ret;
1257     }
1258 #endif /* MBEDTLS_RSA_C */
1259 
1260 #if defined(MBEDTLS_ECP_C)
1261     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1262     if (key[keylen - 1] != '\0') {
1263         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1264     } else {
1265         ret = mbedtls_pem_read_buffer(&pem,
1266                                       "-----BEGIN EC PRIVATE KEY-----",
1267                                       "-----END EC PRIVATE KEY-----",
1268                                       key, pwd, pwdlen, &len);
1269     }
1270     if (ret == 0) {
1271         pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1272 
1273         if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1274             (ret = pk_parse_key_sec1_der(mbedtls_pk_ec(*pk),
1275                                          pem.buf, pem.buflen,
1276                                          f_rng, p_rng)) != 0) {
1277             mbedtls_pk_free(pk);
1278         }
1279 
1280         mbedtls_pem_free(&pem);
1281         return ret;
1282     } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1283         return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1284     } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1285         return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1286     } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1287         return ret;
1288     }
1289 #endif /* MBEDTLS_ECP_C */
1290 
1291     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1292     if (key[keylen - 1] != '\0') {
1293         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1294     } else {
1295         ret = mbedtls_pem_read_buffer(&pem,
1296                                       "-----BEGIN PRIVATE KEY-----",
1297                                       "-----END PRIVATE KEY-----",
1298                                       key, NULL, 0, &len);
1299     }
1300     if (ret == 0) {
1301         if ((ret = pk_parse_key_pkcs8_unencrypted_der(pk,
1302                                                       pem.buf, pem.buflen, f_rng, p_rng)) != 0) {
1303             mbedtls_pk_free(pk);
1304         }
1305 
1306         mbedtls_pem_free(&pem);
1307         return ret;
1308     } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1309         return ret;
1310     }
1311 
1312 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1313     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1314     if (key[keylen - 1] != '\0') {
1315         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1316     } else {
1317         ret = mbedtls_pem_read_buffer(&pem,
1318                                       "-----BEGIN ENCRYPTED PRIVATE KEY-----",
1319                                       "-----END ENCRYPTED PRIVATE KEY-----",
1320                                       key, NULL, 0, &len);
1321     }
1322     if (ret == 0) {
1323         if ((ret = pk_parse_key_pkcs8_encrypted_der(pk, pem.buf, pem.buflen,
1324                                                     pwd, pwdlen, f_rng, p_rng)) != 0) {
1325             mbedtls_pk_free(pk);
1326         }
1327 
1328         mbedtls_pem_free(&pem);
1329         return ret;
1330     } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1331         return ret;
1332     }
1333 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1334 #else
1335     ((void) pwd);
1336     ((void) pwdlen);
1337 #endif /* MBEDTLS_PEM_PARSE_C */
1338 
1339     /*
1340      * At this point we only know it's not a PEM formatted key. Could be any
1341      * of the known DER encoded private key formats
1342      *
1343      * We try the different DER format parsers to see if one passes without
1344      * error
1345      */
1346 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1347     if (pwdlen != 0) {
1348         unsigned char *key_copy;
1349 
1350         if ((key_copy = mbedtls_calloc(1, keylen)) == NULL) {
1351             return MBEDTLS_ERR_PK_ALLOC_FAILED;
1352         }
1353 
1354         memcpy(key_copy, key, keylen);
1355 
1356         ret = pk_parse_key_pkcs8_encrypted_der(pk, key_copy, keylen,
1357                                                pwd, pwdlen, f_rng, p_rng);
1358 
1359         mbedtls_platform_zeroize(key_copy, keylen);
1360         mbedtls_free(key_copy);
1361     }
1362 
1363     if (ret == 0) {
1364         return 0;
1365     }
1366 
1367     mbedtls_pk_free(pk);
1368     mbedtls_pk_init(pk);
1369 
1370     if (ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH) {
1371         return ret;
1372     }
1373 #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1374 
1375     ret = pk_parse_key_pkcs8_unencrypted_der(pk, key, keylen, f_rng, p_rng);
1376     if (ret == 0) {
1377         return 0;
1378     }
1379 
1380     mbedtls_pk_free(pk);
1381     mbedtls_pk_init(pk);
1382 
1383 #if defined(MBEDTLS_RSA_C)
1384 
1385     pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1386     if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1387         pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), key, keylen) == 0) {
1388         return 0;
1389     }
1390 
1391     mbedtls_pk_free(pk);
1392     mbedtls_pk_init(pk);
1393 #endif /* MBEDTLS_RSA_C */
1394 
1395 #if defined(MBEDTLS_ECP_C)
1396     pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1397     if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1398         pk_parse_key_sec1_der(mbedtls_pk_ec(*pk),
1399                               key, keylen, f_rng, p_rng) == 0) {
1400         return 0;
1401     }
1402     mbedtls_pk_free(pk);
1403 #endif /* MBEDTLS_ECP_C */
1404 
1405     /* If MBEDTLS_RSA_C is defined but MBEDTLS_ECP_C isn't,
1406      * it is ok to leave the PK context initialized but not
1407      * freed: It is the caller's responsibility to call pk_init()
1408      * before calling this function, and to call pk_free()
1409      * when it fails. If MBEDTLS_ECP_C is defined but MBEDTLS_RSA_C
1410      * isn't, this leads to mbedtls_pk_free() being called
1411      * twice, once here and once by the caller, but this is
1412      * also ok and in line with the mbedtls_pk_free() calls
1413      * on failed PEM parsing attempts. */
1414 
1415     return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1416 }
1417 
1418 /*
1419  * Parse a public key
1420  */
mbedtls_pk_parse_public_key(mbedtls_pk_context * ctx,const unsigned char * key,size_t keylen)1421 int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
1422                                 const unsigned char *key, size_t keylen)
1423 {
1424     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1425     unsigned char *p;
1426 #if defined(MBEDTLS_RSA_C)
1427     const mbedtls_pk_info_t *pk_info;
1428 #endif
1429 #if defined(MBEDTLS_PEM_PARSE_C)
1430     size_t len;
1431     mbedtls_pem_context pem;
1432 #endif
1433 
1434     if (keylen == 0) {
1435         return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1436     }
1437 
1438 #if defined(MBEDTLS_PEM_PARSE_C)
1439     mbedtls_pem_init(&pem);
1440 #if defined(MBEDTLS_RSA_C)
1441     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1442     if (key[keylen - 1] != '\0') {
1443         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1444     } else {
1445         ret = mbedtls_pem_read_buffer(&pem,
1446                                       "-----BEGIN RSA PUBLIC KEY-----",
1447                                       "-----END RSA PUBLIC KEY-----",
1448                                       key, NULL, 0, &len);
1449     }
1450 
1451     if (ret == 0) {
1452         p = pem.buf;
1453         if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1454             mbedtls_pem_free(&pem);
1455             return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1456         }
1457 
1458         if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1459             mbedtls_pem_free(&pem);
1460             return ret;
1461         }
1462 
1463         if ((ret = pk_get_rsapubkey(&p, p + pem.buflen, mbedtls_pk_rsa(*ctx))) != 0) {
1464             mbedtls_pk_free(ctx);
1465         }
1466 
1467         mbedtls_pem_free(&pem);
1468         return ret;
1469     } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1470         mbedtls_pem_free(&pem);
1471         return ret;
1472     }
1473 #endif /* MBEDTLS_RSA_C */
1474 
1475     /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1476     if (key[keylen - 1] != '\0') {
1477         ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1478     } else {
1479         ret = mbedtls_pem_read_buffer(&pem,
1480                                       "-----BEGIN PUBLIC KEY-----",
1481                                       "-----END PUBLIC KEY-----",
1482                                       key, NULL, 0, &len);
1483     }
1484 
1485     if (ret == 0) {
1486         /*
1487          * Was PEM encoded
1488          */
1489         p = pem.buf;
1490 
1491         ret = mbedtls_pk_parse_subpubkey(&p,  p + pem.buflen, ctx);
1492         mbedtls_pem_free(&pem);
1493         return ret;
1494     } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1495         mbedtls_pem_free(&pem);
1496         return ret;
1497     }
1498     mbedtls_pem_free(&pem);
1499 #endif /* MBEDTLS_PEM_PARSE_C */
1500 
1501 #if defined(MBEDTLS_RSA_C)
1502     if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1503         return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1504     }
1505 
1506     if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1507         return ret;
1508     }
1509 
1510     p = (unsigned char *) key;
1511     ret = pk_get_rsapubkey(&p, p + keylen, mbedtls_pk_rsa(*ctx));
1512     if (ret == 0) {
1513         return ret;
1514     }
1515     mbedtls_pk_free(ctx);
1516     if (ret != (MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
1517                                   MBEDTLS_ERR_ASN1_UNEXPECTED_TAG))) {
1518         return ret;
1519     }
1520 #endif /* MBEDTLS_RSA_C */
1521     p = (unsigned char *) key;
1522 
1523     ret = mbedtls_pk_parse_subpubkey(&p, p + keylen, ctx);
1524 
1525     return ret;
1526 }
1527 
1528 #endif /* MBEDTLS_PK_PARSE_C */
1529