decoder.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright 2023-2024 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. * https://www.openssl.org/source/license.html
  8. * or in the file LICENSE in the source distribution.
  9. */
  10. #include <openssl/decoder.h>
  11. #include <openssl/err.h>
  12. #include <openssl/rand.h>
  13. #include "fuzzer.h"
  14. static ASN1_PCTX *pctx;
  15. int FuzzerInitialize(int *argc, char ***argv)
  16. {
  17. FuzzerSetRand();
  18. OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS
  19. | OPENSSL_INIT_ADD_ALL_CIPHERS
  20. | OPENSSL_INIT_ADD_ALL_DIGESTS,
  21. NULL);
  22. pctx = ASN1_PCTX_new();
  23. ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT | ASN1_PCTX_FLAGS_SHOW_SEQUENCE | ASN1_PCTX_FLAGS_SHOW_SSOF | ASN1_PCTX_FLAGS_SHOW_TYPE | ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME);
  24. ASN1_PCTX_set_str_flags(pctx, ASN1_STRFLGS_UTF8_CONVERT | ASN1_STRFLGS_SHOW_TYPE | ASN1_STRFLGS_DUMP_ALL);
  25. ERR_clear_error();
  26. CRYPTO_free_ex_index(0, -1);
  27. return 1;
  28. }
  29. int FuzzerTestOneInput(const uint8_t *buf, size_t len)
  30. {
  31. OSSL_DECODER_CTX *dctx;
  32. EVP_PKEY *pkey = NULL;
  33. EVP_PKEY_CTX *ctx = NULL;
  34. BIO *bio;
  35. bio = BIO_new(BIO_s_null());
  36. dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, NULL, NULL, NULL, 0, NULL,
  37. NULL);
  38. if (dctx == NULL) {
  39. return 0;
  40. }
  41. if (OSSL_DECODER_from_data(dctx, &buf, &len)) {
  42. EVP_PKEY *pkey2;
  43. EVP_PKEY_print_public(bio, pkey, 1, pctx);
  44. EVP_PKEY_print_private(bio, pkey, 1, pctx);
  45. EVP_PKEY_print_params(bio, pkey, 1, pctx);
  46. pkey2 = EVP_PKEY_dup(pkey);
  47. OPENSSL_assert(pkey2 != NULL);
  48. EVP_PKEY_eq(pkey, pkey2);
  49. EVP_PKEY_free(pkey2);
  50. ctx = EVP_PKEY_CTX_new(pkey, NULL);
  51. /*
  52. * Param check will take too long time on large DH parameters.
  53. * Skip it.
  54. */
  55. if ((!EVP_PKEY_is_a(pkey, "DH") && !EVP_PKEY_is_a(pkey, "DHX"))
  56. || EVP_PKEY_get_bits(pkey) <= 2048)
  57. EVP_PKEY_param_check(ctx);
  58. EVP_PKEY_public_check(ctx);
  59. /* Private and pairwise checks are unbounded, skip for large keys. */
  60. if (EVP_PKEY_get_bits(pkey) <= 4096) {
  61. EVP_PKEY_private_check(ctx);
  62. EVP_PKEY_pairwise_check(ctx);
  63. }
  64. OPENSSL_assert(ctx != NULL);
  65. EVP_PKEY_CTX_free(ctx);
  66. EVP_PKEY_free(pkey);
  67. }
  68. OSSL_DECODER_CTX_free(dctx);
  69. BIO_free(bio);
  70. ERR_clear_error();
  71. return 0;
  72. }
  73. void FuzzerCleanup(void)
  74. {
  75. ASN1_PCTX_free(pctx);
  76. FuzzerClearRand();
  77. }