1 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
2
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include "mbedtls/pk.h"
7 #include "mbedtls/entropy.h"
8 #include "mbedtls/ctr_drbg.h"
9 #include "common.h"
10
11 //4 Kb should be enough for every bug ;-)
12 #define MAX_LEN 0x1000
13
14 #if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_CTR_DRBG_C) && defined(MBEDTLS_ENTROPY_C)
15 const char *pers = "fuzz_privkey";
16 #endif // MBEDTLS_PK_PARSE_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_ENTROPY_C
17
LLVMFuzzerTestOneInput(const uint8_t * Data,size_t Size)18 int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
19 {
20 #if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_CTR_DRBG_C) && defined(MBEDTLS_ENTROPY_C)
21 int ret;
22 mbedtls_pk_context pk;
23 mbedtls_ctr_drbg_context ctr_drbg;
24 mbedtls_entropy_context entropy;
25
26 if (Size > MAX_LEN) {
27 //only work on small inputs
28 Size = MAX_LEN;
29 }
30
31 mbedtls_ctr_drbg_init(&ctr_drbg);
32 mbedtls_entropy_init(&entropy);
33
34 if (mbedtls_ctr_drbg_seed(&ctr_drbg, dummy_entropy, &entropy,
35 (const unsigned char *) pers, strlen(pers)) != 0) {
36 return 1;
37 }
38
39 mbedtls_pk_init(&pk);
40 ret = mbedtls_pk_parse_key(&pk, Data, Size, NULL, 0,
41 dummy_random, &ctr_drbg);
42 if (ret == 0) {
43 #if defined(MBEDTLS_RSA_C)
44 if (mbedtls_pk_get_type(&pk) == MBEDTLS_PK_RSA) {
45 mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
46 mbedtls_rsa_context *rsa;
47
48 mbedtls_mpi_init(&N); mbedtls_mpi_init(&P); mbedtls_mpi_init(&Q);
49 mbedtls_mpi_init(&D); mbedtls_mpi_init(&E); mbedtls_mpi_init(&DP);
50 mbedtls_mpi_init(&DQ); mbedtls_mpi_init(&QP);
51
52 rsa = mbedtls_pk_rsa(pk);
53 if (mbedtls_rsa_export(rsa, &N, &P, &Q, &D, &E) != 0) {
54 abort();
55 }
56 if (mbedtls_rsa_export_crt(rsa, &DP, &DQ, &QP) != 0) {
57 abort();
58 }
59
60 mbedtls_mpi_free(&N); mbedtls_mpi_free(&P); mbedtls_mpi_free(&Q);
61 mbedtls_mpi_free(&D); mbedtls_mpi_free(&E); mbedtls_mpi_free(&DP);
62 mbedtls_mpi_free(&DQ); mbedtls_mpi_free(&QP);
63 } else
64 #endif
65 #if defined(MBEDTLS_ECP_C)
66 if (mbedtls_pk_get_type(&pk) == MBEDTLS_PK_ECKEY ||
67 mbedtls_pk_get_type(&pk) == MBEDTLS_PK_ECKEY_DH) {
68 mbedtls_ecp_keypair *ecp = mbedtls_pk_ec(pk);
69 mbedtls_ecp_group_id grp_id = ecp->grp.id;
70 const mbedtls_ecp_curve_info *curve_info =
71 mbedtls_ecp_curve_info_from_grp_id(grp_id);
72
73 /* If the curve is not supported, the key should not have been
74 * accepted. */
75 if (curve_info == NULL) {
76 abort();
77 }
78 } else
79 #endif
80 {
81 /* The key is valid but is not of a supported type.
82 * This should not happen. */
83 abort();
84 }
85 }
86 mbedtls_pk_free(&pk);
87 #else
88 (void) Data;
89 (void) Size;
90 #endif // MBEDTLS_PK_PARSE_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_ENTROPY_C
91
92 return 0;
93 }
94