common.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include "common.h"
  2. #include <limits.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include "mbedtls/ctr_drbg.h"
  7. #if defined(MBEDTLS_PLATFORM_TIME_ALT)
  8. mbedtls_time_t dummy_constant_time(mbedtls_time_t *time)
  9. {
  10. (void) time;
  11. return 0x5af2a056;
  12. }
  13. #endif
  14. void dummy_init()
  15. {
  16. #if defined(MBEDTLS_PLATFORM_TIME_ALT)
  17. mbedtls_platform_set_time(dummy_constant_time);
  18. #else
  19. fprintf(stderr, "Warning: fuzzing without constant time\n");
  20. #endif
  21. }
  22. int dummy_send(void *ctx, const unsigned char *buf, size_t len)
  23. {
  24. //silence warning about unused parameter
  25. (void) ctx;
  26. (void) buf;
  27. //pretends we wrote everything ok
  28. if (len > INT_MAX) {
  29. return -1;
  30. }
  31. return (int) len;
  32. }
  33. int fuzz_recv(void *ctx, unsigned char *buf, size_t len)
  34. {
  35. //reads from the buffer from fuzzer
  36. fuzzBufferOffset_t *biomemfuzz = (fuzzBufferOffset_t *) ctx;
  37. if (biomemfuzz->Offset == biomemfuzz->Size) {
  38. //EOF
  39. return 0;
  40. }
  41. if (len > INT_MAX) {
  42. return -1;
  43. }
  44. if (len + biomemfuzz->Offset > biomemfuzz->Size) {
  45. //do not overflow
  46. len = biomemfuzz->Size - biomemfuzz->Offset;
  47. }
  48. memcpy(buf, biomemfuzz->Data + biomemfuzz->Offset, len);
  49. biomemfuzz->Offset += len;
  50. return (int) len;
  51. }
  52. int dummy_random(void *p_rng, unsigned char *output, size_t output_len)
  53. {
  54. int ret;
  55. size_t i;
  56. #if defined(MBEDTLS_CTR_DRBG_C)
  57. //mbedtls_ctr_drbg_random requires a valid mbedtls_ctr_drbg_context in p_rng
  58. if (p_rng != NULL) {
  59. //use mbedtls_ctr_drbg_random to find bugs in it
  60. ret = mbedtls_ctr_drbg_random(p_rng, output, output_len);
  61. } else {
  62. //fall through to pseudo-random
  63. ret = 0;
  64. }
  65. #else
  66. (void) p_rng;
  67. ret = 0;
  68. #endif
  69. for (i = 0; i < output_len; i++) {
  70. //replace result with pseudo random
  71. output[i] = (unsigned char) rand();
  72. }
  73. return ret;
  74. }
  75. int dummy_entropy(void *data, unsigned char *output, size_t len)
  76. {
  77. size_t i;
  78. (void) data;
  79. //use mbedtls_entropy_func to find bugs in it
  80. //test performance impact of entropy
  81. //ret = mbedtls_entropy_func(data, output, len);
  82. for (i = 0; i < len; i++) {
  83. //replace result with pseudo random
  84. output[i] = (unsigned char) rand();
  85. }
  86. return 0;
  87. }
  88. int fuzz_recv_timeout(void *ctx, unsigned char *buf, size_t len,
  89. uint32_t timeout)
  90. {
  91. (void) timeout;
  92. return fuzz_recv(ctx, buf, len);
  93. }