1 // Copyright 2019 The Chromium OS 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 <cstddef>
6 #include <cstdint>
7 #include <cstdio>
8 
9 #include <brillo/data_encoding.h>
10 
11 #include <base/logging.h>
12 #include <fuzzer/FuzzedDataProvider.h>
13 
14 namespace {
15 constexpr int kMaxStringLength = 256;
16 constexpr int kMaxParamsSize = 8;
17 
FuzzUrlEncodeDecode(FuzzedDataProvider * provider)18 void FuzzUrlEncodeDecode(FuzzedDataProvider* provider) {
19   brillo::data_encoding::UrlEncode(
20       provider->ConsumeRandomLengthString(kMaxStringLength).c_str(),
21       provider->ConsumeBool());
22 
23   brillo::data_encoding::UrlDecode(
24       provider->ConsumeRandomLengthString(kMaxStringLength).c_str());
25 }
26 
FuzzWebParamsEncodeDecode(FuzzedDataProvider * provider)27 void FuzzWebParamsEncodeDecode(FuzzedDataProvider* provider) {
28   brillo::data_encoding::WebParamList param_list;
29   const auto num_params = provider->ConsumeIntegralInRange(0, kMaxParamsSize);
30   for (auto i = 0; i < num_params; i++) {
31     param_list.push_back(std::pair<std::string, std::string>(
32         provider->ConsumeRandomLengthString(kMaxStringLength),
33         provider->ConsumeRandomLengthString(kMaxStringLength)));
34   }
35   brillo::data_encoding::WebParamsEncode(param_list, provider->ConsumeBool());
36 
37   brillo::data_encoding::WebParamsDecode(
38       provider->ConsumeRandomLengthString(kMaxStringLength));
39 }
40 
FuzzBase64EncodeDecode(FuzzedDataProvider * provider)41 void FuzzBase64EncodeDecode(FuzzedDataProvider* provider) {
42   brillo::data_encoding::Base64Encode(
43       provider->ConsumeRandomLengthString(kMaxStringLength));
44   brillo::Blob output;
45   brillo::data_encoding::Base64Decode(
46       provider->ConsumeRandomLengthString(kMaxStringLength), &output);
47 }
48 
IgnoreLogging(int,const char *,int,size_t,const std::string &)49 bool IgnoreLogging(int, const char*, int, size_t, const std::string&) {
50   return true;
51 }
52 
53 }  // namespace
54 
55 class Environment {
56  public:
Environment()57   Environment() {
58     // Disable logging. Normally this would be done with logging::SetMinLogLevel
59     // but that doesn't work for brillo::Error because it's not using the
60     // LOG(ERROR) macro which is where the actual log level check occurs.
61     logging::SetLogMessageHandler(&IgnoreLogging);
62   }
63 };
64 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)65 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
66   static Environment env;
67   FuzzedDataProvider data_provider(data, size);
68   FuzzUrlEncodeDecode(&data_provider);
69   FuzzWebParamsEncodeDecode(&data_provider);
70   FuzzBase64EncodeDecode(&data_provider);
71   return 0;
72 }
73