decoder.c 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright 2023 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, NULL);
  21. pctx = ASN1_PCTX_new();
  22. ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT
  23. | ASN1_PCTX_FLAGS_SHOW_SEQUENCE
  24. | ASN1_PCTX_FLAGS_SHOW_SSOF
  25. | ASN1_PCTX_FLAGS_SHOW_TYPE
  26. | ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME);
  27. ASN1_PCTX_set_str_flags(pctx, ASN1_STRFLGS_UTF8_CONVERT
  28. | ASN1_STRFLGS_SHOW_TYPE
  29. | ASN1_STRFLGS_DUMP_ALL);
  30. ERR_clear_error();
  31. CRYPTO_free_ex_index(0, -1);
  32. return 1;
  33. }
  34. int FuzzerTestOneInput(const uint8_t *buf, size_t len)
  35. {
  36. OSSL_DECODER_CTX *dctx;
  37. EVP_PKEY *pkey = NULL;
  38. EVP_PKEY_CTX *ctx = NULL;
  39. BIO *bio;
  40. bio = BIO_new(BIO_s_null());
  41. dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, NULL, NULL, NULL, 0, NULL,
  42. NULL);
  43. if (dctx == NULL) {
  44. return 0;
  45. }
  46. if (OSSL_DECODER_from_data(dctx, &buf, &len)) {
  47. EVP_PKEY *pkey2;
  48. EVP_PKEY_print_public(bio, pkey, 1, pctx);
  49. EVP_PKEY_print_private(bio, pkey, 1, pctx);
  50. EVP_PKEY_print_params(bio, pkey, 1, pctx);
  51. pkey2 = EVP_PKEY_dup(pkey);
  52. OPENSSL_assert(pkey2 != NULL);
  53. EVP_PKEY_eq(pkey, pkey2);
  54. EVP_PKEY_free(pkey2);
  55. ctx = EVP_PKEY_CTX_new(pkey, NULL);
  56. /*
  57. * Param check will take too long time on large DH parameters.
  58. * Skip it.
  59. */
  60. if ((!EVP_PKEY_is_a(pkey, "DH") && !EVP_PKEY_is_a(pkey, "DHX"))
  61. || EVP_PKEY_get_bits(pkey) <= 8192)
  62. EVP_PKEY_param_check(ctx);
  63. EVP_PKEY_public_check(ctx);
  64. /* Private and pairwise checks are unbounded, skip for large keys. */
  65. if (EVP_PKEY_get_bits(pkey) <= 16384) {
  66. EVP_PKEY_private_check(ctx);
  67. EVP_PKEY_pairwise_check(ctx);
  68. }
  69. OPENSSL_assert(ctx != NULL);
  70. EVP_PKEY_CTX_free(ctx);
  71. EVP_PKEY_free(pkey);
  72. }
  73. OSSL_DECODER_CTX_free(dctx);
  74. BIO_free(bio);
  75. ERR_clear_error();
  76. return 0;
  77. }
  78. void FuzzerCleanup(void)
  79. {
  80. ASN1_PCTX_free(pctx);
  81. FuzzerClearRand();
  82. }