mime_sniffer_fuzzer.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/base/mime_sniffer.h"
  5. #include <stddef.h>
  6. #include <string>
  7. #include <fuzzer/FuzzedDataProvider.h>
  8. #include "url/gurl.h"
  9. // Fuzzer for the two main mime sniffing functions:
  10. // SniffMimeType and SniffMimeTypeFromLocalData.
  11. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  12. // net::SniffMimeType DCHECKs if passed an input buffer that's too large,
  13. // since it's meant to be used only on the first chunk of a file that's being
  14. // fed into a stream. Set a max size of the input to avoid running into that
  15. // DCHECK. Use 64k because that's twice the size of a typical read attempt.
  16. constexpr size_t kMaxSniffLength = 64 * 1024;
  17. static_assert(kMaxSniffLength >= net::kMaxBytesToSniff,
  18. "kMaxSniffLength is too small.");
  19. FuzzedDataProvider data_provider(data, size);
  20. // Divide up the input. It's important not to pass |url_string| to the GURL
  21. // constructor until after the length check, to prevent the fuzzer from
  22. // exploring GURL space with invalid inputs.
  23. //
  24. // Max lengths of URL and type hint are arbitrary.
  25. std::string url_string = data_provider.ConsumeRandomLengthString(4 * 1024);
  26. std::string mime_type_hint = data_provider.ConsumeRandomLengthString(1024);
  27. net::ForceSniffFileUrlsForHtml force_sniff_file_urls_for_html =
  28. data_provider.ConsumeBool() ? net::ForceSniffFileUrlsForHtml::kDisabled
  29. : net::ForceSniffFileUrlsForHtml::kEnabled;
  30. // Do nothing if remaining input is too long. An early exit prevents the
  31. // fuzzer from exploring needlessly long inputs with interesting prefixes.
  32. if (data_provider.remaining_bytes() > kMaxSniffLength)
  33. return 0;
  34. std::string input = data_provider.ConsumeRemainingBytesAsString();
  35. std::string result;
  36. net::SniffMimeType(input, GURL(url_string), mime_type_hint,
  37. force_sniff_file_urls_for_html, &result);
  38. net::SniffMimeTypeFromLocalData(input, &result);
  39. return 0;
  40. }