summaryrefslogtreecommitdiffstats
path: root/tools/fuzzing/messagemanager/MessageManagerFuzzer.cpp
blob: 6a4475641f3616b4e23d4d90d64329d4b1313b9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <climits>
#include <cmath>
#include "FuzzingTraits.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/CharacterEncoding.h"
#include "js/Exception.h"
#include "js/PropertyAndElement.h"  // JS_Enumerate, JS_GetProperty, JS_GetPropertyById, JS_SetProperty, JS_SetPropertyById
#include "prenv.h"
#include "MessageManagerFuzzer.h"
#include "mozilla/ErrorResult.h"
#include "nsComponentManagerUtils.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsFrameMessageManager.h"
#include "nsJSUtils.h"
#include "nsXULAppAPI.h"
#include "nsNetCID.h"
#include "nsString.h"
#include "nsUnicharUtils.h"
#include "nsIFile.h"
#include "nsIFileStreams.h"
#include "nsILineInputStream.h"
#include "nsLocalFile.h"
#include "nsTArray.h"

#ifdef IsLoggingEnabled
// This is defined in the Windows SDK urlmon.h
#  undef IsLoggingEnabled
#endif

#define MESSAGEMANAGER_FUZZER_DEFAULT_MUTATION_PROBABILITY 2
#define MSGMGR_FUZZER_LOG(fmt, args...)                        \
  if (MessageManagerFuzzer::IsLoggingEnabled()) {              \
    printf_stderr("[MessageManagerFuzzer] " fmt "\n", ##args); \
  }

namespace mozilla {
namespace dom {

using namespace fuzzing;
using namespace ipc;

/* static */
void MessageManagerFuzzer::ReadFile(const char* path,
                                    nsTArray<nsCString>& aArray) {
  nsCOMPtr<nsIFile> file;
  nsresult rv =
      NS_NewLocalFile(NS_ConvertUTF8toUTF16(path), true, getter_AddRefs(file));
  NS_ENSURE_SUCCESS_VOID(rv);

  bool exists = false;
  rv = file->Exists(&exists);
  if (NS_FAILED(rv) || !exists) {
    return;
  }

  nsCOMPtr<nsIFileInputStream> fileStream(
      do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS_VOID(rv);

  rv = fileStream->Init(file, -1, -1, false);
  NS_ENSURE_SUCCESS_VOID(rv);

  nsCOMPtr<nsILineInputStream> lineStream(do_QueryInterface(fileStream, &rv));
  NS_ENSURE_SUCCESS_VOID(rv);

  nsAutoCString line;
  bool more = true;
  do {
    rv = lineStream->ReadLine(line, &more);
    NS_ENSURE_SUCCESS_VOID(rv);
    aArray.AppendElement(line);
  } while (more);
}

/* static */
bool MessageManagerFuzzer::IsMessageNameBlacklisted(
    const nsAString& aMessageName) {
  static bool sFileLoaded = false;
  static nsTArray<nsCString> valuesInFile;

  if (!sFileLoaded) {
    ReadFile(PR_GetEnv("MESSAGEMANAGER_FUZZER_BLACKLIST"), valuesInFile);
    sFileLoaded = true;
  }

  if (valuesInFile.Length() == 0) {
    return false;
  }

  return valuesInFile.Contains(NS_ConvertUTF16toUTF8(aMessageName).get());
}

/* static */
nsCString MessageManagerFuzzer::GetFuzzValueFromFile() {
  static bool sFileLoaded = false;
  static nsTArray<nsCString> valuesInFile;

  if (!sFileLoaded) {
    ReadFile(PR_GetEnv("MESSAGEMANAGER_FUZZER_STRINGSFILE"), valuesInFile);
    sFileLoaded = true;
  }

  // If something goes wrong with importing the file we return an empty string.
  if (valuesInFile.Length() == 0) {
    return nsCString();
  }

  unsigned randIdx = RandomIntegerRange<unsigned>(0, valuesInFile.Length());
  return valuesInFile.ElementAt(randIdx);
}

/* static */
void MessageManagerFuzzer::MutateObject(JSContext* aCx,
                                        JS::Handle<JS::Value> aValue,
                                        unsigned short int aRecursionCounter) {
  JS::Rooted<JSObject*> object(aCx, &aValue.toObject());
  JS::Rooted<JS::IdVector> ids(aCx, JS::IdVector(aCx));

  if (!JS_Enumerate(aCx, object, &ids)) {
    return;
  }

  for (size_t i = 0, n = ids.length(); i < n; i++) {
    // Retrieve Property name.
    nsAutoJSString propName;
    if (!propName.init(aCx, ids[i])) {
      continue;
    }
    MSGMGR_FUZZER_LOG("%*s- Property: %s", aRecursionCounter * 4, "",
                      NS_ConvertUTF16toUTF8(propName).get());

    // The likelihood when a value gets fuzzed of this object.
    if (!FuzzingTraits::Sometimes(DefaultMutationProbability())) {
      continue;
    }

    // Retrieve Property value.
    JS::Rooted<JS::Value> propertyValue(aCx);
    JS_GetPropertyById(aCx, object, ids[i], &propertyValue);

    JS::Rooted<JS::Value> newPropValue(aCx);
    MutateValue(aCx, propertyValue, &newPropValue, aRecursionCounter);

    JS_SetPropertyById(aCx, object, ids[i], newPropValue);
  }
}

/* static */
bool MessageManagerFuzzer::MutateValue(
    JSContext* aCx, JS::Handle<JS::Value> aValue,
    JS::MutableHandle<JS::Value> aOutMutationValue,
    unsigned short int aRecursionCounter) {
  if (aValue.isInt32()) {
    if (FuzzingTraits::Sometimes(DefaultMutationProbability() * 2)) {
      aOutMutationValue.set(JS::Int32Value(RandomNumericLimit<int>()));
    } else {
      aOutMutationValue.set(JS::Int32Value(RandomInteger<int>()));
    }
    MSGMGR_FUZZER_LOG("%*s! Mutated value of type |int32|: '%d' to '%d'",
                      aRecursionCounter * 4, "", aValue.toInt32(),
                      aOutMutationValue.toInt32());
    return true;
  }

  if (aValue.isDouble()) {
    aOutMutationValue.set(JS::DoubleValue(RandomFloatingPoint<double>()));
    MSGMGR_FUZZER_LOG("%*s! Mutated value of type |double|: '%f' to '%f'",
                      aRecursionCounter * 4, "", aValue.toDouble(),
                      aOutMutationValue.toDouble());
    return true;
  }

  if (aValue.isBoolean()) {
    aOutMutationValue.set(JS::BooleanValue(bool(RandomIntegerRange(0, 2))));
    MSGMGR_FUZZER_LOG("%*s! Mutated value of type |boolean|: '%d' to '%d'",
                      aRecursionCounter * 4, "", aValue.toBoolean(),
                      aOutMutationValue.toBoolean());
    return true;
  }

  if (aValue.isString()) {
    nsCString x = GetFuzzValueFromFile();
    if (x.IsEmpty()) {
      return false;
    }
    JSString* str = JS_NewStringCopyZ(aCx, x.get());
    aOutMutationValue.set(JS::StringValue(str));
    JS::Rooted<JSString*> rootedValue(aCx, aValue.toString());
    JS::UniqueChars valueChars = JS_EncodeStringToUTF8(aCx, rootedValue);
    MSGMGR_FUZZER_LOG("%*s! Mutated value of type |string|: '%s' to '%s'",
                      aRecursionCounter * 4, "", valueChars.get(), x.get());
    return true;
  }

  if (aValue.isObject()) {
    aRecursionCounter++;
    MSGMGR_FUZZER_LOG("%*s<Enumerating found object>", aRecursionCounter * 4,
                      "");
    MutateObject(aCx, aValue, aRecursionCounter);
    aOutMutationValue.set(aValue);
    return true;
  }

  return false;
}

/* static */
bool MessageManagerFuzzer::Mutate(JSContext* aCx, const nsAString& aMessageName,
                                  ipc::StructuredCloneData* aData,
                                  const JS::Value& aTransfer) {
  MSGMGR_FUZZER_LOG("Message: %s in process: %d",
                    NS_ConvertUTF16toUTF8(aMessageName).get(),
                    XRE_GetProcessType());

  unsigned short int aRecursionCounter = 0;
  ErrorResult rv;
  JS::Rooted<JS::Value> t(aCx, aTransfer);

  /* Read original StructuredCloneData. */
  JS::Rooted<JS::Value> scdContent(aCx);
  aData->Read(aCx, &scdContent, rv);
  if (NS_WARN_IF(rv.Failed())) {
    rv.SuppressException();
    JS_ClearPendingException(aCx);
    return false;
  }

  JS::Rooted<JS::Value> scdMutationContent(aCx);
  bool isMutated =
      MutateValue(aCx, scdContent, &scdMutationContent, aRecursionCounter);

  /* Write mutated StructuredCloneData. */
  ipc::StructuredCloneData mutatedStructuredCloneData;
  mutatedStructuredCloneData.Write(aCx, scdMutationContent, t,
                                   JS::CloneDataPolicy(), rv);
  if (NS_WARN_IF(rv.Failed())) {
    rv.SuppressException();
    JS_ClearPendingException(aCx);
    return false;
  }

  // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1346040
  aData->Copy(mutatedStructuredCloneData);

  /* Mutated and successfully written to StructuredCloneData object. */
  if (isMutated) {
    JS::Rooted<JSString*> str(aCx, JS_ValueToSource(aCx, scdMutationContent));
    JS::UniqueChars strChars = JS_EncodeStringToUTF8(aCx, str);
    MSGMGR_FUZZER_LOG("Mutated '%s' Message: %s",
                      NS_ConvertUTF16toUTF8(aMessageName).get(),
                      strChars.get());
  }

  return true;
}

/* static */
unsigned int MessageManagerFuzzer::DefaultMutationProbability() {
  static unsigned long sPropValue =
      MESSAGEMANAGER_FUZZER_DEFAULT_MUTATION_PROBABILITY;
  static bool sInitialized = false;

  if (sInitialized) {
    return sPropValue;
  }
  sInitialized = true;

  // Defines the likelihood of fuzzing a message.
  const char* probability =
      PR_GetEnv("MESSAGEMANAGER_FUZZER_MUTATION_PROBABILITY");
  if (probability) {
    long n = std::strtol(probability, nullptr, 10);
    if (n != 0) {
      sPropValue = n;
      return sPropValue;
    }
  }

  return sPropValue;
}

/* static */
bool MessageManagerFuzzer::IsLoggingEnabled() {
  static bool sInitialized = false;
  static bool sIsLoggingEnabled = false;

  if (!sInitialized) {
    sIsLoggingEnabled = !!PR_GetEnv("MESSAGEMANAGER_FUZZER_ENABLE_LOGGING");
    sInitialized = true;
  }

  return sIsLoggingEnabled;
}

/* static */
bool MessageManagerFuzzer::IsEnabled() {
  return !!PR_GetEnv("MESSAGEMANAGER_FUZZER_ENABLE") && XRE_IsContentProcess();
}

/* static */
void MessageManagerFuzzer::TryMutate(JSContext* aCx,
                                     const nsAString& aMessageName,
                                     ipc::StructuredCloneData* aData,
                                     const JS::Value& aTransfer) {
  if (!IsEnabled()) {
    return;
  }

  if (IsMessageNameBlacklisted(aMessageName)) {
    MSGMGR_FUZZER_LOG("Blacklisted message: %s",
                      NS_ConvertUTF16toUTF8(aMessageName).get());
    return;
  }

  Mutate(aCx, aMessageName, aData, aTransfer);
}

}  // namespace dom
}  // namespace mozilla