fuzz_pubkey.c 2.4 KB

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