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