Coverage Report

Created: 2024-08-27 12:19

/src/mbedtls/library/pkparse.c
Line
Count
Source (jump to first uncovered line)
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
 */
61
int mbedtls_pk_load_file(const char *path, unsigned char **buf, size_t *n)
62
0
{
63
0
    FILE *f;
64
0
    long size;
65
66
0
    if ((f = fopen(path, "rb")) == NULL) {
67
0
        return MBEDTLS_ERR_PK_FILE_IO_ERROR;
68
0
    }
69
70
    /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
71
0
    mbedtls_setbuf(f, NULL);
72
73
0
    fseek(f, 0, SEEK_END);
74
0
    if ((size = ftell(f)) == -1) {
75
0
        fclose(f);
76
0
        return MBEDTLS_ERR_PK_FILE_IO_ERROR;
77
0
    }
78
0
    fseek(f, 0, SEEK_SET);
79
80
0
    *n = (size_t) size;
81
82
0
    if (*n + 1 == 0 ||
83
0
        (*buf = mbedtls_calloc(1, *n + 1)) == NULL) {
84
0
        fclose(f);
85
0
        return MBEDTLS_ERR_PK_ALLOC_FAILED;
86
0
    }
87
88
0
    if (fread(*buf, 1, *n, f) != *n) {
89
0
        fclose(f);
90
91
0
        mbedtls_platform_zeroize(*buf, *n);
92
0
        mbedtls_free(*buf);
93
94
0
        return MBEDTLS_ERR_PK_FILE_IO_ERROR;
95
0
    }
96
97
0
    fclose(f);
98
99
0
    (*buf)[*n] = '\0';
100
101
0
    if (strstr((const char *) *buf, "-----BEGIN ") != NULL) {
102
0
        ++*n;
103
0
    }
104
105
0
    return 0;
106
0
}
107
108
/*
109
 * Load and parse a private key
110
 */
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
0
{
115
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
116
0
    size_t n;
117
0
    unsigned char *buf;
118
119
0
    if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
120
0
        return ret;
121
0
    }
122
123
0
    if (pwd == NULL) {
124
0
        ret = mbedtls_pk_parse_key(ctx, buf, n, NULL, 0, f_rng, p_rng);
125
0
    } else {
126
0
        ret = mbedtls_pk_parse_key(ctx, buf, n,
127
0
                                   (const unsigned char *) pwd, strlen(pwd), f_rng, p_rng);
128
0
    }
129
130
0
    mbedtls_platform_zeroize(buf, n);
131
0
    mbedtls_free(buf);
132
133
0
    return ret;
134
0
}
135
136
/*
137
 * Load and parse a public key
138
 */
139
int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path)
140
0
{
141
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
142
0
    size_t n;
143
0
    unsigned char *buf;
144
145
0
    if ((ret = mbedtls_pk_load_file(path, &buf, &n)) != 0) {
146
0
        return ret;
147
0
    }
148
149
0
    ret = mbedtls_pk_parse_public_key(ctx, buf, n);
150
151
0
    mbedtls_platform_zeroize(buf, n);
152
0
    mbedtls_free(buf);
153
154
0
    return ret;
155
0
}
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
 */
167
static int pk_get_ecparams(unsigned char **p, const unsigned char *end,
168
                           mbedtls_asn1_buf *params)
169
0
{
170
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
171
172
0
    if (end - *p < 1) {
173
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
174
0
                                 MBEDTLS_ERR_ASN1_OUT_OF_DATA);
175
0
    }
176
177
    /* Tag may be either OID or SEQUENCE */
178
0
    params->tag = **p;
179
0
    if (params->tag != MBEDTLS_ASN1_OID
180
0
#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
181
0
        && params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)
182
0
#endif
183
0
        ) {
184
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
185
0
                                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
186
0
    }
187
188
0
    if ((ret = mbedtls_asn1_get_tag(p, end, &params->len, params->tag)) != 0) {
189
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
190
0
    }
191
192
0
    params->p = *p;
193
0
    *p += params->len;
194
195
0
    if (*p != end) {
196
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
197
0
                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
198
0
    }
199
200
0
    return 0;
201
0
}
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
 */
223
static int pk_group_from_specified(const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp)
224
6
{
225
6
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
226
6
    unsigned char *p = params->p;
227
6
    const unsigned char * const end = params->p + params->len;
228
6
    const unsigned char *end_field, *end_curve;
229
6
    size_t len;
230
6
    int ver;
231
232
    /* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */
233
6
    if ((ret = mbedtls_asn1_get_int(&p, end, &ver)) != 0) {
234
6
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
235
6
    }
236
237
0
    if (ver < 1 || ver > 3) {
238
0
        return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
239
0
    }
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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
248
0
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
249
0
        return ret;
250
0
    }
251
252
0
    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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end_field, &len, MBEDTLS_ASN1_OID)) != 0) {
263
0
        return ret;
264
0
    }
265
266
0
    if (len != MBEDTLS_OID_SIZE(MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD) ||
267
0
        memcmp(p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len) != 0) {
268
0
        return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
269
0
    }
270
271
0
    p += len;
272
273
    /* Prime-p ::= INTEGER -- Field of size p. */
274
0
    if ((ret = mbedtls_asn1_get_mpi(&p, end_field, &grp->P)) != 0) {
275
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
276
0
    }
277
278
0
    grp->pbits = mbedtls_mpi_bitlen(&grp->P);
279
280
0
    if (p != end_field) {
281
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
282
0
                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
283
0
    }
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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
295
0
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
296
0
        return ret;
297
0
    }
298
299
0
    end_curve = p + len;
300
301
    /*
302
     * FieldElement ::= OCTET STRING
303
     * containing an integer in the case of a prime field
304
     */
305
0
    if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0 ||
306
0
        (ret = mbedtls_mpi_read_binary(&grp->A, p, len)) != 0) {
307
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
308
0
    }
309
310
0
    p += len;
311
312
0
    if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0 ||
313
0
        (ret = mbedtls_mpi_read_binary(&grp->B, p, len)) != 0) {
314
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
315
0
    }
316
317
0
    p += len;
318
319
    /* Ignore seed BIT STRING OPTIONAL */
320
0
    if ((ret = mbedtls_asn1_get_tag(&p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING)) == 0) {
321
0
        p += len;
322
0
    }
323
324
0
    if (p != end_curve) {
325
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
326
0
                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
327
0
    }
328
329
    /*
330
     * ECPoint ::= OCTET STRING
331
     */
332
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
333
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
334
0
    }
335
336
0
    if ((ret = mbedtls_ecp_point_read_binary(grp, &grp->G,
337
0
                                             (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
0
        if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ||
343
0
            (p[0] != 0x02 && p[0] != 0x03) ||
344
0
            len != mbedtls_mpi_size(&grp->P) + 1 ||
345
0
            mbedtls_mpi_read_binary(&grp->G.X, p + 1, len - 1) != 0 ||
346
0
            mbedtls_mpi_lset(&grp->G.Y, p[0] - 2) != 0 ||
347
0
            mbedtls_mpi_lset(&grp->G.Z, 1) != 0) {
348
0
            return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
349
0
        }
350
0
    }
351
352
0
    p += len;
353
354
    /*
355
     * order INTEGER
356
     */
357
0
    if ((ret = mbedtls_asn1_get_mpi(&p, end, &grp->N)) != 0) {
358
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
359
0
    }
360
361
0
    grp->nbits = mbedtls_mpi_bitlen(&grp->N);
362
363
    /*
364
     * Allow optional elements by purposefully not enforcing p == end here.
365
     */
366
367
0
    return 0;
368
0
}
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
 */
374
static int pk_group_id_from_group(const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id)
375
0
{
376
0
    int ret = 0;
377
0
    mbedtls_ecp_group ref;
378
0
    const mbedtls_ecp_group_id *id;
379
380
0
    mbedtls_ecp_group_init(&ref);
381
382
0
    for (id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++) {
383
        /* Load the group associated to that id */
384
0
        mbedtls_ecp_group_free(&ref);
385
0
        MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&ref, *id));
386
387
        /* Compare to the group we were given, starting with easy tests */
388
0
        if (grp->pbits == ref.pbits && grp->nbits == ref.nbits &&
389
0
            mbedtls_mpi_cmp_mpi(&grp->P, &ref.P) == 0 &&
390
0
            mbedtls_mpi_cmp_mpi(&grp->A, &ref.A) == 0 &&
391
0
            mbedtls_mpi_cmp_mpi(&grp->B, &ref.B) == 0 &&
392
0
            mbedtls_mpi_cmp_mpi(&grp->N, &ref.N) == 0 &&
393
0
            mbedtls_mpi_cmp_mpi(&grp->G.X, &ref.G.X) == 0 &&
394
0
            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
0
            mbedtls_mpi_get_bit(&grp->G.Y, 0) == mbedtls_mpi_get_bit(&ref.G.Y, 0)) {
397
0
            break;
398
0
        }
399
400
0
    }
401
402
0
cleanup:
403
0
    mbedtls_ecp_group_free(&ref);
404
405
0
    *grp_id = *id;
406
407
0
    if (ret == 0 && *id == MBEDTLS_ECP_DP_NONE) {
408
0
        ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
409
0
    }
410
411
0
    return ret;
412
0
}
413
414
/*
415
 * Parse a SpecifiedECDomain (SEC 1 C.2) and find the associated group ID
416
 */
417
static int pk_group_id_from_specified(const mbedtls_asn1_buf *params,
418
                                      mbedtls_ecp_group_id *grp_id)
419
6
{
420
6
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
421
6
    mbedtls_ecp_group grp;
422
423
6
    mbedtls_ecp_group_init(&grp);
424
425
6
    if ((ret = pk_group_from_specified(params, &grp)) != 0) {
426
6
        goto cleanup;
427
6
    }
428
429
0
    ret = pk_group_id_from_group(&grp, grp_id);
430
431
6
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
6
    mbedtls_mpi_free(&grp.N);
440
6
    mbedtls_mpi_free(&grp.P);
441
6
    mbedtls_mpi_free(&grp.A);
442
6
    mbedtls_mpi_free(&grp.B);
443
6
    mbedtls_ecp_point_free(&grp.G);
444
445
6
    return ret;
446
0
}
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
 */
457
static int pk_use_ecparams(const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp)
458
2.42k
{
459
2.42k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
460
2.42k
    mbedtls_ecp_group_id grp_id;
461
462
2.42k
    if (params->tag == MBEDTLS_ASN1_OID) {
463
2.42k
        if (mbedtls_oid_get_ec_grp(params, &grp_id) != 0) {
464
10
            return MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE;
465
10
        }
466
2.42k
    } else {
467
6
#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
468
6
        if ((ret = pk_group_id_from_specified(params, &grp_id)) != 0) {
469
6
            return ret;
470
6
        }
471
#else
472
        return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
473
#endif
474
6
    }
475
476
    /*
477
     * grp may already be initialized; if so, make sure IDs match
478
     */
479
2.41k
    if (grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id) {
480
0
        return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
481
0
    }
482
483
2.41k
    if ((ret = mbedtls_ecp_group_load(grp, grp_id)) != 0) {
484
0
        return ret;
485
0
    }
486
487
2.41k
    return 0;
488
2.41k
}
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
 */
497
static int pk_get_ecpubkey(unsigned char **p, const unsigned char *end,
498
                           mbedtls_ecp_keypair *key)
499
2.41k
{
500
2.41k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
501
502
2.41k
    if ((ret = mbedtls_ecp_point_read_binary(&key->grp, &key->Q,
503
2.41k
                                             (const unsigned char *) *p, end - *p)) == 0) {
504
2.33k
        ret = mbedtls_ecp_check_pubkey(&key->grp, &key->Q);
505
2.33k
    }
506
507
    /*
508
     * We know mbedtls_ecp_point_read_binary consumed all bytes or failed
509
     */
510
2.41k
    *p = (unsigned char *) end;
511
512
2.41k
    return ret;
513
2.41k
}
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
 */
523
static int pk_get_rsapubkey(unsigned char **p,
524
                            const unsigned char *end,
525
                            mbedtls_rsa_context *rsa)
526
9.02k
{
527
9.02k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
528
9.02k
    size_t len;
529
530
9.02k
    if ((ret = mbedtls_asn1_get_tag(p, end, &len,
531
9.02k
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
532
7
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
533
7
    }
534
535
9.02k
    if (*p + len != end) {
536
11
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
537
11
                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
538
11
    }
539
540
    /* Import N */
541
9.00k
    if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
542
7
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
543
7
    }
544
545
9.00k
    if ((ret = mbedtls_rsa_import_raw(rsa, *p, len, NULL, 0, NULL, 0,
546
9.00k
                                      NULL, 0, NULL, 0)) != 0) {
547
0
        return MBEDTLS_ERR_PK_INVALID_PUBKEY;
548
0
    }
549
550
9.00k
    *p += len;
551
552
    /* Import E */
553
9.00k
    if ((ret = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
554
169
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
555
169
    }
556
557
8.83k
    if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
558
8.83k
                                      NULL, 0, *p, len)) != 0) {
559
0
        return MBEDTLS_ERR_PK_INVALID_PUBKEY;
560
0
    }
561
562
8.83k
    *p += len;
563
564
8.83k
    if (mbedtls_rsa_complete(rsa) != 0 ||
565
8.83k
        mbedtls_rsa_check_pubkey(rsa) != 0) {
566
69
        return MBEDTLS_ERR_PK_INVALID_PUBKEY;
567
69
    }
568
569
8.76k
    if (*p != end) {
570
1
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
571
1
                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
572
1
    }
573
574
8.76k
    return 0;
575
8.76k
}
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
 */
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
11.6k
{
588
11.6k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
589
11.6k
    mbedtls_asn1_buf alg_oid;
590
591
11.6k
    memset(params, 0, sizeof(mbedtls_asn1_buf));
592
593
11.6k
    if ((ret = mbedtls_asn1_get_alg(p, end, &alg_oid, params)) != 0) {
594
63
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_ALG, ret);
595
63
    }
596
597
11.5k
    if (mbedtls_oid_get_pk_alg(&alg_oid, pk_alg) != 0) {
598
38
        return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
599
38
    }
600
601
    /*
602
     * No parameters with RSA (only for EC)
603
     */
604
11.5k
    if (*pk_alg == MBEDTLS_PK_RSA &&
605
11.5k
        ((params->tag != MBEDTLS_ASN1_NULL && params->tag != 0) ||
606
9.07k
         params->len != 0)) {
607
10
        return MBEDTLS_ERR_PK_INVALID_ALG;
608
10
    }
609
610
11.5k
    return 0;
611
11.5k
}
612
613
/*
614
 *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
615
 *       algorithm            AlgorithmIdentifier,
616
 *       subjectPublicKey     BIT STRING }
617
 */
618
int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
619
                               mbedtls_pk_context *pk)
620
11.6k
{
621
11.6k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
622
11.6k
    size_t len;
623
11.6k
    mbedtls_asn1_buf alg_params;
624
11.6k
    mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
625
11.6k
    const mbedtls_pk_info_t *pk_info;
626
627
11.6k
    if ((ret = mbedtls_asn1_get_tag(p, end, &len,
628
11.6k
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
629
25
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
630
25
    }
631
632
11.6k
    end = *p + len;
633
634
11.6k
    if ((ret = pk_get_pk_alg(p, end, &pk_alg, &alg_params)) != 0) {
635
111
        return ret;
636
111
    }
637
638
11.5k
    if ((ret = mbedtls_asn1_get_bitstring_null(p, end, &len)) != 0) {
639
49
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY, ret);
640
49
    }
641
642
11.4k
    if (*p + len != end) {
643
7
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
644
7
                                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
645
7
    }
646
647
11.4k
    if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
648
0
        return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
649
0
    }
650
651
11.4k
    if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
652
0
        return ret;
653
0
    }
654
655
11.4k
#if defined(MBEDTLS_RSA_C)
656
11.4k
    if (pk_alg == MBEDTLS_PK_RSA) {
657
9.02k
        ret = pk_get_rsapubkey(p, end, mbedtls_pk_rsa(*pk));
658
9.02k
    } else
659
2.42k
#endif /* MBEDTLS_RSA_C */
660
2.42k
#if defined(MBEDTLS_ECP_C)
661
2.42k
    if (pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY) {
662
2.42k
        ret = pk_use_ecparams(&alg_params, &mbedtls_pk_ec(*pk)->grp);
663
2.42k
        if (ret == 0) {
664
2.41k
            ret = pk_get_ecpubkey(p, end, mbedtls_pk_ec(*pk));
665
2.41k
        }
666
2.42k
    } else
667
0
#endif /* MBEDTLS_ECP_C */
668
0
    ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
669
670
11.4k
    if (ret == 0 && *p != end) {
671
0
        ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
672
0
                                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
673
0
    }
674
675
11.4k
    if (ret != 0) {
676
1.00k
        mbedtls_pk_free(pk);
677
1.00k
    }
678
679
11.4k
    return ret;
680
11.4k
}
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
 */
693
static int asn1_get_nonzero_mpi(unsigned char **p,
694
                                const unsigned char *end,
695
                                mbedtls_mpi *X)
696
0
{
697
0
    int ret;
698
699
0
    ret = mbedtls_asn1_get_mpi(p, end, X);
700
0
    if (ret != 0) {
701
0
        return ret;
702
0
    }
703
704
0
    if (mbedtls_mpi_cmp_int(X, 0) == 0) {
705
0
        return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
706
0
    }
707
708
0
    return 0;
709
0
}
710
711
/*
712
 * Parse a PKCS#1 encoded private RSA key
713
 */
714
static int pk_parse_key_pkcs1_der(mbedtls_rsa_context *rsa,
715
                                  const unsigned char *key,
716
                                  size_t keylen)
717
0
{
718
0
    int ret, version;
719
0
    size_t len;
720
0
    unsigned char *p, *end;
721
722
0
    mbedtls_mpi T;
723
0
    mbedtls_mpi_init(&T);
724
725
0
    p = (unsigned char *) key;
726
0
    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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
745
0
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
746
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
747
0
    }
748
749
0
    end = p + len;
750
751
0
    if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
752
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
753
0
    }
754
755
0
    if (version != 0) {
756
0
        return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
757
0
    }
758
759
    /* Import N */
760
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
761
0
        (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
762
0
                                  NULL, NULL)) != 0) {
763
0
        goto cleanup;
764
0
    }
765
766
    /* Import E */
767
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
768
0
        (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
769
0
                                  NULL, &T)) != 0) {
770
0
        goto cleanup;
771
0
    }
772
773
    /* Import D */
774
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
775
0
        (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
776
0
                                  &T, NULL)) != 0) {
777
0
        goto cleanup;
778
0
    }
779
780
    /* Import P */
781
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
782
0
        (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
783
0
                                  NULL, NULL)) != 0) {
784
0
        goto cleanup;
785
0
    }
786
787
    /* Import Q */
788
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
789
0
        (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
790
0
                                  NULL, NULL)) != 0) {
791
0
        goto cleanup;
792
0
    }
793
794
0
#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
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
808
0
        (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
809
0
        goto cleanup;
810
0
    }
811
812
    /* Import DQ */
813
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
814
0
        (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
815
0
        goto cleanup;
816
0
    }
817
818
    /* Import QP */
819
0
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
820
0
        (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
821
0
        goto cleanup;
822
0
    }
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
0
    if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
843
0
        (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
844
0
        goto cleanup;
845
0
    }
846
847
0
    if (p != end) {
848
0
        ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
849
0
                                MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
850
0
    }
851
852
0
cleanup:
853
854
0
    mbedtls_mpi_free(&T);
855
856
0
    if (ret != 0) {
857
        /* Wrap error code if it's coming from a lower level */
858
0
        if ((ret & 0xff80) == 0) {
859
0
            ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
860
0
        } else {
861
0
            ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
862
0
        }
863
864
0
        mbedtls_rsa_free(rsa);
865
0
    }
866
867
0
    return ret;
868
0
}
869
#endif /* MBEDTLS_RSA_C */
870
871
#if defined(MBEDTLS_ECP_C)
872
/*
873
 * Parse a SEC1 encoded private EC key
874
 */
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
0
{
879
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
880
0
    int version, pubkey_done;
881
0
    size_t len;
882
0
    mbedtls_asn1_buf params = { 0, 0, NULL };
883
0
    unsigned char *p = (unsigned char *) key;
884
0
    unsigned char *end = p + keylen;
885
0
    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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
898
0
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
899
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
900
0
    }
901
902
0
    end = p + len;
903
904
0
    if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
905
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
906
0
    }
907
908
0
    if (version != 1) {
909
0
        return MBEDTLS_ERR_PK_KEY_INVALID_VERSION;
910
0
    }
911
912
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
913
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
914
0
    }
915
916
0
    if ((ret = mbedtls_mpi_read_binary(&eck->d, p, len)) != 0) {
917
0
        mbedtls_ecp_keypair_free(eck);
918
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
919
0
    }
920
921
0
    p += len;
922
923
0
    pubkey_done = 0;
924
0
    if (p != end) {
925
        /*
926
         * Is 'parameters' present?
927
         */
928
0
        if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
929
0
                                        MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
930
0
                                        0)) == 0) {
931
0
            if ((ret = pk_get_ecparams(&p, p + len, &params)) != 0 ||
932
0
                (ret = pk_use_ecparams(&params, &eck->grp)) != 0) {
933
0
                mbedtls_ecp_keypair_free(eck);
934
0
                return ret;
935
0
            }
936
0
        } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
937
0
            mbedtls_ecp_keypair_free(eck);
938
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
939
0
        }
940
0
    }
941
942
0
    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
0
        if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
948
0
                                        MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
949
0
                                        1)) == 0) {
950
0
            end2 = p + len;
951
952
0
            if ((ret = mbedtls_asn1_get_bitstring_null(&p, end2, &len)) != 0) {
953
0
                return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
954
0
            }
955
956
0
            if (p + len != end2) {
957
0
                return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
958
0
                                         MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
959
0
            }
960
961
0
            if ((ret = pk_get_ecpubkey(&p, end2, eck)) == 0) {
962
0
                pubkey_done = 1;
963
0
            } else {
964
                /*
965
                 * The only acceptable failure mode of pk_get_ecpubkey() above
966
                 * is if the point format is not recognized.
967
                 */
968
0
                if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) {
969
0
                    return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
970
0
                }
971
0
            }
972
0
        } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
973
0
            mbedtls_ecp_keypair_free(eck);
974
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
975
0
        }
976
0
    }
977
978
0
    if (!pubkey_done &&
979
0
        (ret = mbedtls_ecp_mul(&eck->grp, &eck->Q, &eck->d, &eck->grp.G,
980
0
                               f_rng, p_rng)) != 0) {
981
0
        mbedtls_ecp_keypair_free(eck);
982
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
983
0
    }
984
985
0
    if ((ret = mbedtls_ecp_check_privkey(&eck->grp, &eck->d)) != 0) {
986
0
        mbedtls_ecp_keypair_free(eck);
987
0
        return ret;
988
0
    }
989
990
0
    return 0;
991
0
}
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
 */
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
0
{
1012
0
    int ret, version;
1013
0
    size_t len;
1014
0
    mbedtls_asn1_buf params;
1015
0
    unsigned char *p = (unsigned char *) key;
1016
0
    unsigned char *end = p + keylen;
1017
0
    mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
1018
0
    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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1042
0
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1043
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1044
0
    }
1045
1046
0
    end = p + len;
1047
1048
0
    if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
1049
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1050
0
    }
1051
1052
0
    if (version != 0) {
1053
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_VERSION, ret);
1054
0
    }
1055
1056
0
    if ((ret = pk_get_pk_alg(&p, end, &pk_alg, &params)) != 0) {
1057
0
        return ret;
1058
0
    }
1059
1060
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1061
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1062
0
    }
1063
1064
0
    if (len < 1) {
1065
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
1066
0
                                 MBEDTLS_ERR_ASN1_OUT_OF_DATA);
1067
0
    }
1068
1069
0
    if ((pk_info = mbedtls_pk_info_from_type(pk_alg)) == NULL) {
1070
0
        return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1071
0
    }
1072
1073
0
    if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0) {
1074
0
        return ret;
1075
0
    }
1076
1077
0
#if defined(MBEDTLS_RSA_C)
1078
0
    if (pk_alg == MBEDTLS_PK_RSA) {
1079
0
        if ((ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), p, len)) != 0) {
1080
0
            mbedtls_pk_free(pk);
1081
0
            return ret;
1082
0
        }
1083
0
    } else
1084
0
#endif /* MBEDTLS_RSA_C */
1085
0
#if defined(MBEDTLS_ECP_C)
1086
0
    if (pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH) {
1087
0
        if ((ret = pk_use_ecparams(&params, &mbedtls_pk_ec(*pk)->grp)) != 0 ||
1088
0
            (ret = pk_parse_key_sec1_der(mbedtls_pk_ec(*pk), p, len, f_rng, p_rng)) != 0) {
1089
0
            mbedtls_pk_free(pk);
1090
0
            return ret;
1091
0
        }
1092
0
    } else
1093
0
#endif /* MBEDTLS_ECP_C */
1094
0
    return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1095
1096
0
    return 0;
1097
0
}
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)
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
0
{
1115
0
    int ret, decrypted = 0;
1116
0
    size_t len;
1117
0
    unsigned char *buf;
1118
0
    unsigned char *p, *end;
1119
0
    mbedtls_asn1_buf pbe_alg_oid, pbe_params;
1120
0
#if defined(MBEDTLS_PKCS12_C)
1121
0
    mbedtls_cipher_type_t cipher_alg;
1122
0
    mbedtls_md_type_t md_alg;
1123
0
#endif
1124
1125
0
    p = key;
1126
0
    end = p + keylen;
1127
1128
0
    if (pwdlen == 0) {
1129
0
        return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1130
0
    }
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
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1148
0
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1149
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1150
0
    }
1151
1152
0
    end = p + len;
1153
1154
0
    if ((ret = mbedtls_asn1_get_alg(&p, end, &pbe_alg_oid, &pbe_params)) != 0) {
1155
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1156
0
    }
1157
1158
0
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1159
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
1160
0
    }
1161
1162
0
    buf = p;
1163
1164
    /*
1165
     * Decrypt EncryptedData with appropriate PBE
1166
     */
1167
0
#if defined(MBEDTLS_PKCS12_C)
1168
0
    if (mbedtls_oid_get_pkcs12_pbe_alg(&pbe_alg_oid, &md_alg, &cipher_alg) == 0) {
1169
0
        if ((ret = mbedtls_pkcs12_pbe(&pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,
1170
0
                                      cipher_alg, md_alg,
1171
0
                                      pwd, pwdlen, p, len, buf)) != 0) {
1172
0
            if (ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) {
1173
0
                return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1174
0
            }
1175
1176
0
            return ret;
1177
0
        }
1178
1179
0
        decrypted = 1;
1180
0
    } else
1181
0
#endif /* MBEDTLS_PKCS12_C */
1182
0
#if defined(MBEDTLS_PKCS5_C)
1183
0
    if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid) == 0) {
1184
0
        if ((ret = mbedtls_pkcs5_pbes2(&pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,
1185
0
                                       p, len, buf)) != 0) {
1186
0
            if (ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) {
1187
0
                return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1188
0
            }
1189
1190
0
            return ret;
1191
0
        }
1192
1193
0
        decrypted = 1;
1194
0
    } else
1195
0
#endif /* MBEDTLS_PKCS5_C */
1196
0
    {
1197
0
        ((void) pwd);
1198
0
    }
1199
1200
0
    if (decrypted == 0) {
1201
0
        return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
1202
0
    }
1203
1204
0
    return pk_parse_key_pkcs8_unencrypted_der(pk, buf, len, f_rng, p_rng);
1205
0
}
1206
#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1207
1208
/*
1209
 * Parse a private key
1210
 */
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
0
{
1216
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1217
0
    const mbedtls_pk_info_t *pk_info;
1218
0
#if defined(MBEDTLS_PEM_PARSE_C)
1219
0
    size_t len;
1220
0
    mbedtls_pem_context pem;
1221
0
#endif
1222
1223
0
    if (keylen == 0) {
1224
0
        return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1225
0
    }
1226
1227
0
#if defined(MBEDTLS_PEM_PARSE_C)
1228
0
    mbedtls_pem_init(&pem);
1229
1230
0
#if defined(MBEDTLS_RSA_C)
1231
    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1232
0
    if (key[keylen - 1] != '\0') {
1233
0
        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1234
0
    } else {
1235
0
        ret = mbedtls_pem_read_buffer(&pem,
1236
0
                                      "-----BEGIN RSA PRIVATE KEY-----",
1237
0
                                      "-----END RSA PRIVATE KEY-----",
1238
0
                                      key, pwd, pwdlen, &len);
1239
0
    }
1240
1241
0
    if (ret == 0) {
1242
0
        pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1243
0
        if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1244
0
            (ret = pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk),
1245
0
                                          pem.buf, pem.buflen)) != 0) {
1246
0
            mbedtls_pk_free(pk);
1247
0
        }
1248
1249
0
        mbedtls_pem_free(&pem);
1250
0
        return ret;
1251
0
    } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1252
0
        return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1253
0
    } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1254
0
        return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1255
0
    } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1256
0
        return ret;
1257
0
    }
1258
0
#endif /* MBEDTLS_RSA_C */
1259
1260
0
#if defined(MBEDTLS_ECP_C)
1261
    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1262
0
    if (key[keylen - 1] != '\0') {
1263
0
        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1264
0
    } else {
1265
0
        ret = mbedtls_pem_read_buffer(&pem,
1266
0
                                      "-----BEGIN EC PRIVATE KEY-----",
1267
0
                                      "-----END EC PRIVATE KEY-----",
1268
0
                                      key, pwd, pwdlen, &len);
1269
0
    }
1270
0
    if (ret == 0) {
1271
0
        pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1272
1273
0
        if ((ret = mbedtls_pk_setup(pk, pk_info)) != 0 ||
1274
0
            (ret = pk_parse_key_sec1_der(mbedtls_pk_ec(*pk),
1275
0
                                         pem.buf, pem.buflen,
1276
0
                                         f_rng, p_rng)) != 0) {
1277
0
            mbedtls_pk_free(pk);
1278
0
        }
1279
1280
0
        mbedtls_pem_free(&pem);
1281
0
        return ret;
1282
0
    } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) {
1283
0
        return MBEDTLS_ERR_PK_PASSWORD_MISMATCH;
1284
0
    } else if (ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) {
1285
0
        return MBEDTLS_ERR_PK_PASSWORD_REQUIRED;
1286
0
    } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1287
0
        return ret;
1288
0
    }
1289
0
#endif /* MBEDTLS_ECP_C */
1290
1291
    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1292
0
    if (key[keylen - 1] != '\0') {
1293
0
        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1294
0
    } else {
1295
0
        ret = mbedtls_pem_read_buffer(&pem,
1296
0
                                      "-----BEGIN PRIVATE KEY-----",
1297
0
                                      "-----END PRIVATE KEY-----",
1298
0
                                      key, NULL, 0, &len);
1299
0
    }
1300
0
    if (ret == 0) {
1301
0
        if ((ret = pk_parse_key_pkcs8_unencrypted_der(pk,
1302
0
                                                      pem.buf, pem.buflen, f_rng, p_rng)) != 0) {
1303
0
            mbedtls_pk_free(pk);
1304
0
        }
1305
1306
0
        mbedtls_pem_free(&pem);
1307
0
        return ret;
1308
0
    } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1309
0
        return ret;
1310
0
    }
1311
1312
0
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1313
    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1314
0
    if (key[keylen - 1] != '\0') {
1315
0
        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1316
0
    } else {
1317
0
        ret = mbedtls_pem_read_buffer(&pem,
1318
0
                                      "-----BEGIN ENCRYPTED PRIVATE KEY-----",
1319
0
                                      "-----END ENCRYPTED PRIVATE KEY-----",
1320
0
                                      key, NULL, 0, &len);
1321
0
    }
1322
0
    if (ret == 0) {
1323
0
        if ((ret = pk_parse_key_pkcs8_encrypted_der(pk, pem.buf, pem.buflen,
1324
0
                                                    pwd, pwdlen, f_rng, p_rng)) != 0) {
1325
0
            mbedtls_pk_free(pk);
1326
0
        }
1327
1328
0
        mbedtls_pem_free(&pem);
1329
0
        return ret;
1330
0
    } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1331
0
        return ret;
1332
0
    }
1333
0
#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
0
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
1347
0
    if (pwdlen != 0) {
1348
0
        unsigned char *key_copy;
1349
1350
0
        if ((key_copy = mbedtls_calloc(1, keylen)) == NULL) {
1351
0
            return MBEDTLS_ERR_PK_ALLOC_FAILED;
1352
0
        }
1353
1354
0
        memcpy(key_copy, key, keylen);
1355
1356
0
        ret = pk_parse_key_pkcs8_encrypted_der(pk, key_copy, keylen,
1357
0
                                               pwd, pwdlen, f_rng, p_rng);
1358
1359
0
        mbedtls_platform_zeroize(key_copy, keylen);
1360
0
        mbedtls_free(key_copy);
1361
0
    }
1362
1363
0
    if (ret == 0) {
1364
0
        return 0;
1365
0
    }
1366
1367
0
    mbedtls_pk_free(pk);
1368
0
    mbedtls_pk_init(pk);
1369
1370
0
    if (ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH) {
1371
0
        return ret;
1372
0
    }
1373
0
#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
1374
1375
0
    ret = pk_parse_key_pkcs8_unencrypted_der(pk, key, keylen, f_rng, p_rng);
1376
0
    if (ret == 0) {
1377
0
        return 0;
1378
0
    }
1379
1380
0
    mbedtls_pk_free(pk);
1381
0
    mbedtls_pk_init(pk);
1382
1383
0
#if defined(MBEDTLS_RSA_C)
1384
1385
0
    pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
1386
0
    if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1387
0
        pk_parse_key_pkcs1_der(mbedtls_pk_rsa(*pk), key, keylen) == 0) {
1388
0
        return 0;
1389
0
    }
1390
1391
0
    mbedtls_pk_free(pk);
1392
0
    mbedtls_pk_init(pk);
1393
0
#endif /* MBEDTLS_RSA_C */
1394
1395
0
#if defined(MBEDTLS_ECP_C)
1396
0
    pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
1397
0
    if (mbedtls_pk_setup(pk, pk_info) == 0 &&
1398
0
        pk_parse_key_sec1_der(mbedtls_pk_ec(*pk),
1399
0
                              key, keylen, f_rng, p_rng) == 0) {
1400
0
        return 0;
1401
0
    }
1402
0
    mbedtls_pk_free(pk);
1403
0
#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
0
    return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1416
0
}
1417
1418
/*
1419
 * Parse a public key
1420
 */
1421
int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
1422
                                const unsigned char *key, size_t keylen)
1423
0
{
1424
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1425
0
    unsigned char *p;
1426
0
#if defined(MBEDTLS_RSA_C)
1427
0
    const mbedtls_pk_info_t *pk_info;
1428
0
#endif
1429
0
#if defined(MBEDTLS_PEM_PARSE_C)
1430
0
    size_t len;
1431
0
    mbedtls_pem_context pem;
1432
0
#endif
1433
1434
0
    if (keylen == 0) {
1435
0
        return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
1436
0
    }
1437
1438
0
#if defined(MBEDTLS_PEM_PARSE_C)
1439
0
    mbedtls_pem_init(&pem);
1440
0
#if defined(MBEDTLS_RSA_C)
1441
    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1442
0
    if (key[keylen - 1] != '\0') {
1443
0
        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1444
0
    } else {
1445
0
        ret = mbedtls_pem_read_buffer(&pem,
1446
0
                                      "-----BEGIN RSA PUBLIC KEY-----",
1447
0
                                      "-----END RSA PUBLIC KEY-----",
1448
0
                                      key, NULL, 0, &len);
1449
0
    }
1450
1451
0
    if (ret == 0) {
1452
0
        p = pem.buf;
1453
0
        if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1454
0
            mbedtls_pem_free(&pem);
1455
0
            return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1456
0
        }
1457
1458
0
        if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1459
0
            mbedtls_pem_free(&pem);
1460
0
            return ret;
1461
0
        }
1462
1463
0
        if ((ret = pk_get_rsapubkey(&p, p + pem.buflen, mbedtls_pk_rsa(*ctx))) != 0) {
1464
0
            mbedtls_pk_free(ctx);
1465
0
        }
1466
1467
0
        mbedtls_pem_free(&pem);
1468
0
        return ret;
1469
0
    } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1470
0
        mbedtls_pem_free(&pem);
1471
0
        return ret;
1472
0
    }
1473
0
#endif /* MBEDTLS_RSA_C */
1474
1475
    /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
1476
0
    if (key[keylen - 1] != '\0') {
1477
0
        ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
1478
0
    } else {
1479
0
        ret = mbedtls_pem_read_buffer(&pem,
1480
0
                                      "-----BEGIN PUBLIC KEY-----",
1481
0
                                      "-----END PUBLIC KEY-----",
1482
0
                                      key, NULL, 0, &len);
1483
0
    }
1484
1485
0
    if (ret == 0) {
1486
        /*
1487
         * Was PEM encoded
1488
         */
1489
0
        p = pem.buf;
1490
1491
0
        ret = mbedtls_pk_parse_subpubkey(&p,  p + pem.buflen, ctx);
1492
0
        mbedtls_pem_free(&pem);
1493
0
        return ret;
1494
0
    } else if (ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) {
1495
0
        mbedtls_pem_free(&pem);
1496
0
        return ret;
1497
0
    }
1498
0
    mbedtls_pem_free(&pem);
1499
0
#endif /* MBEDTLS_PEM_PARSE_C */
1500
1501
0
#if defined(MBEDTLS_RSA_C)
1502
0
    if ((pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)) == NULL) {
1503
0
        return MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
1504
0
    }
1505
1506
0
    if ((ret = mbedtls_pk_setup(ctx, pk_info)) != 0) {
1507
0
        return ret;
1508
0
    }
1509
1510
0
    p = (unsigned char *) key;
1511
0
    ret = pk_get_rsapubkey(&p, p + keylen, mbedtls_pk_rsa(*ctx));
1512
0
    if (ret == 0) {
1513
0
        return ret;
1514
0
    }
1515
0
    mbedtls_pk_free(ctx);
1516
0
    if (ret != (MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_INVALID_PUBKEY,
1517
0
                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG))) {
1518
0
        return ret;
1519
0
    }
1520
0
#endif /* MBEDTLS_RSA_C */
1521
0
    p = (unsigned char *) key;
1522
1523
0
    ret = mbedtls_pk_parse_subpubkey(&p, p + keylen, ctx);
1524
1525
0
    return ret;
1526
0
}
1527
1528
#endif /* MBEDTLS_PK_PARSE_C */