FuzzerTraceState.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //===- FuzzerTraceState.cpp - Trace-based fuzzer mutator ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // This file implements a mutation algorithm based on instruction traces and
  10. // on taint analysis feedback from DFSan.
  11. //
  12. // Instruction traces are special hooks inserted by the compiler around
  13. // interesting instructions. Currently supported traces:
  14. // * __sanitizer_cov_trace_cmp -- inserted before every ICMP instruction,
  15. // receives the type, size and arguments of ICMP.
  16. //
  17. // Every time a traced event is intercepted we analyse the data involved
  18. // in the event and suggest a mutation for future executions.
  19. // For example if 4 bytes of data that derive from input bytes {4,5,6,7}
  20. // are compared with a constant 12345,
  21. // we try to insert 12345, 12344, 12346 into bytes
  22. // {4,5,6,7} of the next fuzzed inputs.
  23. //
  24. // The fuzzer can work only with the traces, or with both traces and DFSan.
  25. //
  26. // DataFlowSanitizer (DFSan) is a tool for
  27. // generalised dynamic data flow (taint) analysis:
  28. // http://clang.llvm.org/docs/DataFlowSanitizer.html .
  29. //
  30. // The approach with DFSan-based fuzzing has some similarity to
  31. // "Taint-based Directed Whitebox Fuzzing"
  32. // by Vijay Ganesh & Tim Leek & Martin Rinard:
  33. // http://dspace.mit.edu/openaccess-disseminate/1721.1/59320,
  34. // but it uses a full blown LLVM IR taint analysis and separate instrumentation
  35. // to analyze all of the "attack points" at once.
  36. //
  37. // Workflow with DFSan:
  38. // * lib/Fuzzer/Fuzzer*.cpp is compiled w/o any instrumentation.
  39. // * The code under test is compiled with DFSan *and* with instruction traces.
  40. // * Every call to HOOK(a,b) is replaced by DFSan with
  41. // __dfsw_HOOK(a, b, label(a), label(b)) so that __dfsw_HOOK
  42. // gets all the taint labels for the arguments.
  43. // * At the Fuzzer startup we assign a unique DFSan label
  44. // to every byte of the input string (Fuzzer::CurrentUnit) so that for any
  45. // chunk of data we know which input bytes it has derived from.
  46. // * The __dfsw_* functions (implemented in this file) record the
  47. // parameters (i.e. the application data and the corresponding taint labels)
  48. // in a global state.
  49. // * Fuzzer::ApplyTraceBasedMutation() tries to use the data recorded
  50. // by __dfsw_* hooks to guide the fuzzing towards new application states.
  51. //
  52. // Parts of this code will not function when DFSan is not linked in.
  53. // Instead of using ifdefs and thus requiring a separate build of lib/Fuzzer
  54. // we redeclare the dfsan_* interface functions as weak and check if they
  55. // are nullptr before calling.
  56. // If this approach proves to be useful we may add attribute(weak) to the
  57. // dfsan declarations in dfsan_interface.h
  58. //
  59. // This module is in the "proof of concept" stage.
  60. // It is capable of solving only the simplest puzzles
  61. // like test/dfsan/DFSanSimpleCmpTest.cpp.
  62. //===----------------------------------------------------------------------===//
  63. /* Example of manual usage (-fsanitize=dataflow is optional):
  64. (
  65. cd $LLVM/lib/Fuzzer/
  66. clang -fPIC -c -g -O2 -std=c++11 Fuzzer*.cpp
  67. clang++ -O0 -std=c++11 -fsanitize-coverage=edge,trace-cmp \
  68. -fsanitize=dataflow \
  69. test/dfsan/DFSanSimpleCmpTest.cpp Fuzzer*.o
  70. ./a.out
  71. )
  72. */
  73. #include "FuzzerInternal.h"
  74. #include <sanitizer/dfsan_interface.h>
  75. #include <algorithm>
  76. #include <cstring>
  77. #include <unordered_map>
  78. extern "C" {
  79. __attribute__((weak))
  80. dfsan_label dfsan_create_label(const char *desc, void *userdata);
  81. __attribute__((weak))
  82. void dfsan_set_label(dfsan_label label, void *addr, size_t size);
  83. __attribute__((weak))
  84. void dfsan_add_label(dfsan_label label, void *addr, size_t size);
  85. __attribute__((weak))
  86. const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label);
  87. __attribute__((weak))
  88. dfsan_label dfsan_read_label(const void *addr, size_t size);
  89. } // extern "C"
  90. namespace fuzzer {
  91. static bool ReallyHaveDFSan() {
  92. return &dfsan_create_label != nullptr;
  93. }
  94. // These values are copied from include/llvm/IR/InstrTypes.h.
  95. // We do not include the LLVM headers here to remain independent.
  96. // If these values ever change, an assertion in ComputeCmp will fail.
  97. enum Predicate {
  98. ICMP_EQ = 32, ///< equal
  99. ICMP_NE = 33, ///< not equal
  100. ICMP_UGT = 34, ///< unsigned greater than
  101. ICMP_UGE = 35, ///< unsigned greater or equal
  102. ICMP_ULT = 36, ///< unsigned less than
  103. ICMP_ULE = 37, ///< unsigned less or equal
  104. ICMP_SGT = 38, ///< signed greater than
  105. ICMP_SGE = 39, ///< signed greater or equal
  106. ICMP_SLT = 40, ///< signed less than
  107. ICMP_SLE = 41, ///< signed less or equal
  108. };
  109. template <class U, class S>
  110. bool ComputeCmp(size_t CmpType, U Arg1, U Arg2) {
  111. switch(CmpType) {
  112. case ICMP_EQ : return Arg1 == Arg2;
  113. case ICMP_NE : return Arg1 != Arg2;
  114. case ICMP_UGT: return Arg1 > Arg2;
  115. case ICMP_UGE: return Arg1 >= Arg2;
  116. case ICMP_ULT: return Arg1 < Arg2;
  117. case ICMP_ULE: return Arg1 <= Arg2;
  118. case ICMP_SGT: return (S)Arg1 > (S)Arg2;
  119. case ICMP_SGE: return (S)Arg1 >= (S)Arg2;
  120. case ICMP_SLT: return (S)Arg1 < (S)Arg2;
  121. case ICMP_SLE: return (S)Arg1 <= (S)Arg2;
  122. default: assert(0 && "unsupported CmpType");
  123. }
  124. return false;
  125. }
  126. static bool ComputeCmp(size_t CmpSize, size_t CmpType, uint64_t Arg1,
  127. uint64_t Arg2) {
  128. if (CmpSize == 8) return ComputeCmp<uint64_t, int64_t>(CmpType, Arg1, Arg2);
  129. if (CmpSize == 4) return ComputeCmp<uint32_t, int32_t>(CmpType, Arg1, Arg2);
  130. if (CmpSize == 2) return ComputeCmp<uint16_t, int16_t>(CmpType, Arg1, Arg2);
  131. if (CmpSize == 1) return ComputeCmp<uint8_t, int8_t>(CmpType, Arg1, Arg2);
  132. assert(0 && "unsupported type size");
  133. return true;
  134. }
  135. // As a simplification we use the range of input bytes instead of a set of input
  136. // bytes.
  137. struct LabelRange {
  138. uint16_t Beg, End; // Range is [Beg, End), thus Beg==End is an empty range.
  139. LabelRange(uint16_t Beg = 0, uint16_t End = 0) : Beg(Beg), End(End) {}
  140. static LabelRange Join(LabelRange LR1, LabelRange LR2) {
  141. if (LR1.Beg == LR1.End) return LR2;
  142. if (LR2.Beg == LR2.End) return LR1;
  143. return {std::min(LR1.Beg, LR2.Beg), std::max(LR1.End, LR2.End)};
  144. }
  145. LabelRange &Join(LabelRange LR) {
  146. return *this = Join(*this, LR);
  147. }
  148. static LabelRange Singleton(const dfsan_label_info *LI) {
  149. uint16_t Idx = (uint16_t)(uintptr_t)LI->userdata;
  150. assert(Idx > 0);
  151. return {(uint16_t)(Idx - 1), Idx};
  152. }
  153. };
  154. // For now, very simple: put Size bytes of Data at position Pos.
  155. struct TraceBasedMutation {
  156. size_t Pos;
  157. size_t Size;
  158. uint64_t Data;
  159. };
  160. class TraceState {
  161. public:
  162. TraceState(const Fuzzer::FuzzingOptions &Options, const Unit &CurrentUnit)
  163. : Options(Options), CurrentUnit(CurrentUnit) {}
  164. LabelRange GetLabelRange(dfsan_label L);
  165. void DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
  166. uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
  167. dfsan_label L2);
  168. void TraceCmpCallback(size_t CmpSize, size_t CmpType, uint64_t Arg1,
  169. uint64_t Arg2);
  170. int TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
  171. size_t DataSize);
  172. void StartTraceRecording() {
  173. if (!Options.UseTraces) return;
  174. RecordingTraces = true;
  175. Mutations.clear();
  176. }
  177. size_t StopTraceRecording() {
  178. RecordingTraces = false;
  179. std::random_shuffle(Mutations.begin(), Mutations.end());
  180. return Mutations.size();
  181. }
  182. void ApplyTraceBasedMutation(size_t Idx, fuzzer::Unit *U);
  183. private:
  184. bool IsTwoByteData(uint64_t Data) {
  185. int64_t Signed = static_cast<int64_t>(Data);
  186. Signed >>= 16;
  187. return Signed == 0 || Signed == -1L;
  188. }
  189. bool RecordingTraces = false;
  190. std::vector<TraceBasedMutation> Mutations;
  191. LabelRange LabelRanges[1 << (sizeof(dfsan_label) * 8)] = {};
  192. const Fuzzer::FuzzingOptions &Options;
  193. const Unit &CurrentUnit;
  194. };
  195. LabelRange TraceState::GetLabelRange(dfsan_label L) {
  196. LabelRange &LR = LabelRanges[L];
  197. if (LR.Beg < LR.End || L == 0)
  198. return LR;
  199. const dfsan_label_info *LI = dfsan_get_label_info(L);
  200. if (LI->l1 || LI->l2)
  201. return LR = LabelRange::Join(GetLabelRange(LI->l1), GetLabelRange(LI->l2));
  202. return LR = LabelRange::Singleton(LI);
  203. }
  204. void TraceState::ApplyTraceBasedMutation(size_t Idx, fuzzer::Unit *U) {
  205. assert(Idx < Mutations.size());
  206. auto &M = Mutations[Idx];
  207. if (Options.Verbosity >= 3)
  208. Printf("TBM %zd %zd %zd\n", M.Pos, M.Size, M.Data);
  209. if (M.Pos + M.Size > U->size()) return;
  210. memcpy(U->data() + M.Pos, &M.Data, M.Size);
  211. }
  212. void TraceState::DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
  213. uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
  214. dfsan_label L2) {
  215. assert(ReallyHaveDFSan());
  216. if (!RecordingTraces) return;
  217. if (L1 == 0 && L2 == 0)
  218. return; // Not actionable.
  219. if (L1 != 0 && L2 != 0)
  220. return; // Probably still actionable.
  221. bool Res = ComputeCmp(CmpSize, CmpType, Arg1, Arg2);
  222. uint64_t Data = L1 ? Arg2 : Arg1;
  223. LabelRange LR = L1 ? GetLabelRange(L1) : GetLabelRange(L2);
  224. for (size_t Pos = LR.Beg; Pos + CmpSize <= LR.End; Pos++) {
  225. Mutations.push_back({Pos, CmpSize, Data});
  226. Mutations.push_back({Pos, CmpSize, Data + 1});
  227. Mutations.push_back({Pos, CmpSize, Data - 1});
  228. }
  229. if (CmpSize > LR.End - LR.Beg)
  230. Mutations.push_back({LR.Beg, (unsigned)(LR.End - LR.Beg), Data});
  231. if (Options.Verbosity >= 3)
  232. Printf("DFSAN: PC %lx S %zd T %zd A1 %llx A2 %llx R %d L1 %d L2 %d MU %zd\n",
  233. PC, CmpSize, CmpType, Arg1, Arg2, Res, L1, L2, Mutations.size());
  234. }
  235. int TraceState::TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
  236. size_t DataSize) {
  237. int Res = 0;
  238. const uint8_t *Beg = CurrentUnit.data();
  239. const uint8_t *End = Beg + CurrentUnit.size();
  240. for (const uint8_t *Cur = Beg; Cur < End; Cur += DataSize) {
  241. Cur = (uint8_t *)memmem(Cur, End - Cur, &PresentData, DataSize);
  242. if (!Cur)
  243. break;
  244. size_t Pos = Cur - Beg;
  245. assert(Pos < CurrentUnit.size());
  246. Mutations.push_back({Pos, DataSize, DesiredData});
  247. Mutations.push_back({Pos, DataSize, DesiredData + 1});
  248. Mutations.push_back({Pos, DataSize, DesiredData - 1});
  249. Cur += DataSize;
  250. Res++;
  251. }
  252. return Res;
  253. }
  254. void TraceState::TraceCmpCallback(size_t CmpSize, size_t CmpType, uint64_t Arg1,
  255. uint64_t Arg2) {
  256. if (!RecordingTraces) return;
  257. int Added = 0;
  258. if (Options.Verbosity >= 3)
  259. Printf("TraceCmp: %zd %zd\n", Arg1, Arg2);
  260. Added += TryToAddDesiredData(Arg1, Arg2, CmpSize);
  261. Added += TryToAddDesiredData(Arg2, Arg1, CmpSize);
  262. if (!Added && CmpSize == 4 && IsTwoByteData(Arg1) && IsTwoByteData(Arg2)) {
  263. Added += TryToAddDesiredData(Arg1, Arg2, 2);
  264. Added += TryToAddDesiredData(Arg2, Arg1, 2);
  265. }
  266. }
  267. static TraceState *TS;
  268. void Fuzzer::StartTraceRecording() {
  269. if (!TS) return;
  270. TS->StartTraceRecording();
  271. }
  272. size_t Fuzzer::StopTraceRecording() {
  273. if (!TS) return 0;
  274. return TS->StopTraceRecording();
  275. }
  276. void Fuzzer::ApplyTraceBasedMutation(size_t Idx, Unit *U) {
  277. assert(TS);
  278. TS->ApplyTraceBasedMutation(Idx, U);
  279. }
  280. void Fuzzer::InitializeTraceState() {
  281. if (!Options.UseTraces) return;
  282. TS = new TraceState(Options, CurrentUnit);
  283. CurrentUnit.resize(Options.MaxLen);
  284. // The rest really requires DFSan.
  285. if (!ReallyHaveDFSan()) return;
  286. for (size_t i = 0; i < static_cast<size_t>(Options.MaxLen); i++) {
  287. dfsan_label L = dfsan_create_label("input", (void*)(i + 1));
  288. // We assume that no one else has called dfsan_create_label before.
  289. assert(L == i + 1);
  290. dfsan_set_label(L, &CurrentUnit[i], 1);
  291. }
  292. }
  293. } // namespace fuzzer
  294. using fuzzer::TS;
  295. extern "C" {
  296. void __dfsw___sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
  297. uint64_t Arg2, dfsan_label L0,
  298. dfsan_label L1, dfsan_label L2) {
  299. if (!TS) return;
  300. assert(L0 == 0);
  301. uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
  302. uint64_t CmpSize = (SizeAndType >> 32) / 8;
  303. uint64_t Type = (SizeAndType << 32) >> 32;
  304. TS->DFSanCmpCallback(PC, CmpSize, Type, Arg1, Arg2, L1, L2);
  305. }
  306. void dfsan_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
  307. size_t n, dfsan_label s1_label,
  308. dfsan_label s2_label, dfsan_label n_label) {
  309. if (!TS) return;
  310. uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
  311. uint64_t S1 = 0, S2 = 0;
  312. // Simplification: handle only first 8 bytes.
  313. memcpy(&S1, s1, std::min(n, sizeof(S1)));
  314. memcpy(&S2, s2, std::min(n, sizeof(S2)));
  315. dfsan_label L1 = dfsan_read_label(s1, n);
  316. dfsan_label L2 = dfsan_read_label(s2, n);
  317. TS->DFSanCmpCallback(PC, n, fuzzer::ICMP_EQ, S1, S2, L1, L2);
  318. }
  319. void __sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
  320. uint64_t Arg2) {
  321. if (!TS) return;
  322. uint64_t CmpSize = (SizeAndType >> 32) / 8;
  323. uint64_t Type = (SizeAndType << 32) >> 32;
  324. TS->TraceCmpCallback(CmpSize, Type, Arg1, Arg2);
  325. }
  326. } // extern "C"