fuzz_privkey.c 2.2 KB

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