1 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
2
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include "mbedtls/pk.h"
6
LLVMFuzzerTestOneInput(const uint8_t * Data,size_t Size)7 int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
8 {
9 #ifdef MBEDTLS_PK_PARSE_C
10 int ret;
11 mbedtls_pk_context pk;
12
13 mbedtls_pk_init(&pk);
14 #if defined(MBEDTLS_USE_PSA_CRYPTO)
15 psa_status_t status = psa_crypto_init();
16 if (status != PSA_SUCCESS) {
17 goto exit;
18 }
19 #endif /* MBEDTLS_USE_PSA_CRYPTO */
20 ret = mbedtls_pk_parse_public_key(&pk, Data, Size);
21 if (ret == 0) {
22 #if defined(MBEDTLS_RSA_C)
23 if (mbedtls_pk_get_type(&pk) == MBEDTLS_PK_RSA) {
24 mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
25 mbedtls_rsa_context *rsa;
26
27 mbedtls_mpi_init(&N); mbedtls_mpi_init(&P); mbedtls_mpi_init(&Q);
28 mbedtls_mpi_init(&D); mbedtls_mpi_init(&E); mbedtls_mpi_init(&DP);
29 mbedtls_mpi_init(&DQ); mbedtls_mpi_init(&QP);
30
31 rsa = mbedtls_pk_rsa(pk);
32 if (mbedtls_rsa_export(rsa, &N, NULL, NULL, NULL, &E) != 0) {
33 abort();
34 }
35 if (mbedtls_rsa_export(rsa, &N, &P, &Q, &D, &E) != MBEDTLS_ERR_RSA_BAD_INPUT_DATA) {
36 abort();
37 }
38 if (mbedtls_rsa_export_crt(rsa, &DP, &DQ, &QP) != MBEDTLS_ERR_RSA_BAD_INPUT_DATA) {
39 abort();
40 }
41
42 mbedtls_mpi_free(&N); mbedtls_mpi_free(&P); mbedtls_mpi_free(&Q);
43 mbedtls_mpi_free(&D); mbedtls_mpi_free(&E); mbedtls_mpi_free(&DP);
44 mbedtls_mpi_free(&DQ); mbedtls_mpi_free(&QP);
45
46 } else
47 #endif
48 #if defined(MBEDTLS_ECP_C)
49 if (mbedtls_pk_get_type(&pk) == MBEDTLS_PK_ECKEY ||
50 mbedtls_pk_get_type(&pk) == MBEDTLS_PK_ECKEY_DH) {
51 mbedtls_ecp_keypair *ecp = mbedtls_pk_ec(pk);
52 mbedtls_ecp_group_id grp_id = ecp->grp.id;
53 const mbedtls_ecp_curve_info *curve_info =
54 mbedtls_ecp_curve_info_from_grp_id(grp_id);
55
56 /* If the curve is not supported, the key should not have been
57 * accepted. */
58 if (curve_info == NULL) {
59 abort();
60 }
61
62 /* It's a public key, so the private value should not have
63 * been changed from its initialization to 0. */
64 if (mbedtls_mpi_cmp_int(&ecp->d, 0) != 0) {
65 abort();
66 }
67 } else
68 #endif
69 {
70 /* The key is valid but is not of a supported type.
71 * This should not happen. */
72 abort();
73 }
74 }
75 #if defined(MBEDTLS_USE_PSA_CRYPTO)
76 exit:
77 mbedtls_psa_crypto_free();
78 #endif /* MBEDTLS_USE_PSA_CRYPTO */
79 mbedtls_pk_free(&pk);
80 #else
81 (void) Data;
82 (void) Size;
83 #endif //MBEDTLS_PK_PARSE_C
84
85 return 0;
86 }
87