GenericTaintChecker.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. //== GenericTaintChecker.cpp ----------------------------------- -*- C++ -*--=//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This checker defines the attack surface for generic taint propagation.
  10. //
  11. // The taint information produced by it might be useful to other checkers. For
  12. // example, checkers should report errors which involve tainted data more
  13. // aggressively, even if the involved symbols are under constrained.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "Taint.h"
  17. #include "Yaml.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/Basic/Builtins.h"
  20. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  21. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  22. #include "clang/StaticAnalyzer/Core/Checker.h"
  23. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  28. #include "llvm/Support/YAMLTraits.h"
  29. #include <limits>
  30. #include <memory>
  31. #include <utility>
  32. using namespace clang;
  33. using namespace ento;
  34. using namespace taint;
  35. namespace {
  36. class GenericTaintChecker;
  37. /// Check for CWE-134: Uncontrolled Format String.
  38. constexpr llvm::StringLiteral MsgUncontrolledFormatString =
  39. "Untrusted data is used as a format string "
  40. "(CWE-134: Uncontrolled Format String)";
  41. /// Check for:
  42. /// CERT/STR02-C. "Sanitize data passed to complex subsystems"
  43. /// CWE-78, "Failure to Sanitize Data into an OS Command"
  44. constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
  45. "Untrusted data is passed to a system call "
  46. "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
  47. /// Check if tainted data is used as a buffer size in strn.. functions,
  48. /// and allocators.
  49. constexpr llvm::StringLiteral MsgTaintedBufferSize =
  50. "Untrusted data is used to specify the buffer size "
  51. "(CERT/STR31-C. Guarantee that storage for strings has sufficient space "
  52. "for character data and the null terminator)";
  53. /// Check if tainted data is used as a custom sink's parameter.
  54. constexpr llvm::StringLiteral MsgCustomSink =
  55. "Untrusted data is passed to a user-defined sink";
  56. using ArgIdxTy = int;
  57. using ArgVecTy = llvm::SmallVector<ArgIdxTy, 2>;
  58. /// Denotes the return value.
  59. constexpr ArgIdxTy ReturnValueIndex{-1};
  60. static ArgIdxTy fromArgumentCount(unsigned Count) {
  61. assert(Count <=
  62. static_cast<std::size_t>(std::numeric_limits<ArgIdxTy>::max()) &&
  63. "ArgIdxTy is not large enough to represent the number of arguments.");
  64. return Count;
  65. }
  66. /// Check if the region the expression evaluates to is the standard input,
  67. /// and thus, is tainted.
  68. /// FIXME: Move this to Taint.cpp.
  69. bool isStdin(SVal Val, const ASTContext &ACtx) {
  70. // FIXME: What if Val is NonParamVarRegion?
  71. // The region should be symbolic, we do not know it's value.
  72. const auto *SymReg = dyn_cast_or_null<SymbolicRegion>(Val.getAsRegion());
  73. if (!SymReg)
  74. return false;
  75. // Get it's symbol and find the declaration region it's pointing to.
  76. const auto *Sm = dyn_cast<SymbolRegionValue>(SymReg->getSymbol());
  77. if (!Sm)
  78. return false;
  79. const auto *DeclReg = dyn_cast<DeclRegion>(Sm->getRegion());
  80. if (!DeclReg)
  81. return false;
  82. // This region corresponds to a declaration, find out if it's a global/extern
  83. // variable named stdin with the proper type.
  84. if (const auto *D = dyn_cast_or_null<VarDecl>(DeclReg->getDecl())) {
  85. D = D->getCanonicalDecl();
  86. // FIXME: This should look for an exact match.
  87. if (D->getName().contains("stdin") && D->isExternC()) {
  88. const QualType FILETy = ACtx.getFILEType().getCanonicalType();
  89. const QualType Ty = D->getType().getCanonicalType();
  90. if (Ty->isPointerType())
  91. return Ty->getPointeeType() == FILETy;
  92. }
  93. }
  94. return false;
  95. }
  96. SVal getPointeeOf(const CheckerContext &C, Loc LValue) {
  97. const QualType ArgTy = LValue.getType(C.getASTContext());
  98. if (!ArgTy->isPointerType() || !ArgTy->getPointeeType()->isVoidType())
  99. return C.getState()->getSVal(LValue);
  100. // Do not dereference void pointers. Treat them as byte pointers instead.
  101. // FIXME: we might want to consider more than just the first byte.
  102. return C.getState()->getSVal(LValue, C.getASTContext().CharTy);
  103. }
  104. /// Given a pointer/reference argument, return the value it refers to.
  105. Optional<SVal> getPointeeOf(const CheckerContext &C, SVal Arg) {
  106. if (auto LValue = Arg.getAs<Loc>())
  107. return getPointeeOf(C, *LValue);
  108. return None;
  109. }
  110. /// Given a pointer, return the SVal of its pointee or if it is tainted,
  111. /// otherwise return the pointer's SVal if tainted.
  112. /// Also considers stdin as a taint source.
  113. Optional<SVal> getTaintedPointeeOrPointer(const CheckerContext &C, SVal Arg) {
  114. const ProgramStateRef State = C.getState();
  115. if (auto Pointee = getPointeeOf(C, Arg))
  116. if (isTainted(State, *Pointee)) // FIXME: isTainted(...) ? Pointee : None;
  117. return Pointee;
  118. if (isTainted(State, Arg))
  119. return Arg;
  120. // FIXME: This should be done by the isTainted() API.
  121. if (isStdin(Arg, C.getASTContext()))
  122. return Arg;
  123. return None;
  124. }
  125. bool isTaintedOrPointsToTainted(const Expr *E, const ProgramStateRef &State,
  126. CheckerContext &C) {
  127. return getTaintedPointeeOrPointer(C, C.getSVal(E)).hasValue();
  128. }
  129. /// ArgSet is used to describe arguments relevant for taint detection or
  130. /// taint application. A discrete set of argument indexes and a variadic
  131. /// argument list signified by a starting index are supported.
  132. class ArgSet {
  133. public:
  134. ArgSet() = default;
  135. ArgSet(ArgVecTy &&DiscreteArgs, Optional<ArgIdxTy> VariadicIndex = None)
  136. : DiscreteArgs(std::move(DiscreteArgs)),
  137. VariadicIndex(std::move(VariadicIndex)) {}
  138. bool contains(ArgIdxTy ArgIdx) const {
  139. if (llvm::is_contained(DiscreteArgs, ArgIdx))
  140. return true;
  141. return VariadicIndex && ArgIdx >= *VariadicIndex;
  142. }
  143. bool isEmpty() const { return DiscreteArgs.empty() && !VariadicIndex; }
  144. ArgVecTy ArgsUpTo(ArgIdxTy LastArgIdx) const {
  145. ArgVecTy Args;
  146. for (ArgIdxTy I = ReturnValueIndex; I <= LastArgIdx; ++I) {
  147. if (contains(I))
  148. Args.push_back(I);
  149. }
  150. return Args;
  151. }
  152. private:
  153. ArgVecTy DiscreteArgs;
  154. Optional<ArgIdxTy> VariadicIndex;
  155. };
  156. /// A struct used to specify taint propagation rules for a function.
  157. ///
  158. /// If any of the possible taint source arguments is tainted, all of the
  159. /// destination arguments should also be tainted. If ReturnValueIndex is added
  160. /// to the dst list, the return value will be tainted.
  161. class GenericTaintRule {
  162. /// Arguments which are taints sinks and should be checked, and a report
  163. /// should be emitted if taint reaches these.
  164. ArgSet SinkArgs;
  165. /// Arguments which should be sanitized on function return.
  166. ArgSet FilterArgs;
  167. /// Arguments which can participate in taint propagationa. If any of the
  168. /// arguments in PropSrcArgs is tainted, all arguments in PropDstArgs should
  169. /// be tainted.
  170. ArgSet PropSrcArgs;
  171. ArgSet PropDstArgs;
  172. /// A message that explains why the call is sensitive to taint.
  173. Optional<StringRef> SinkMsg;
  174. GenericTaintRule() = default;
  175. GenericTaintRule(ArgSet &&Sink, ArgSet &&Filter, ArgSet &&Src, ArgSet &&Dst,
  176. Optional<StringRef> SinkMsg = None)
  177. : SinkArgs(std::move(Sink)), FilterArgs(std::move(Filter)),
  178. PropSrcArgs(std::move(Src)), PropDstArgs(std::move(Dst)),
  179. SinkMsg(SinkMsg) {}
  180. public:
  181. /// Make a rule that reports a warning if taint reaches any of \p FilterArgs
  182. /// arguments.
  183. static GenericTaintRule Sink(ArgSet &&SinkArgs,
  184. Optional<StringRef> Msg = None) {
  185. return {std::move(SinkArgs), {}, {}, {}, Msg};
  186. }
  187. /// Make a rule that sanitizes all FilterArgs arguments.
  188. static GenericTaintRule Filter(ArgSet &&FilterArgs) {
  189. return {{}, std::move(FilterArgs), {}, {}};
  190. }
  191. /// Make a rule that unconditionally taints all Args.
  192. /// If Func is provided, it must also return true for taint to propagate.
  193. static GenericTaintRule Source(ArgSet &&SourceArgs) {
  194. return {{}, {}, {}, std::move(SourceArgs)};
  195. }
  196. /// Make a rule that taints all PropDstArgs if any of PropSrcArgs is tainted.
  197. static GenericTaintRule Prop(ArgSet &&SrcArgs, ArgSet &&DstArgs) {
  198. return {{}, {}, std::move(SrcArgs), std::move(DstArgs)};
  199. }
  200. /// Make a rule that taints all PropDstArgs if any of PropSrcArgs is tainted.
  201. static GenericTaintRule SinkProp(ArgSet &&SinkArgs, ArgSet &&SrcArgs,
  202. ArgSet &&DstArgs,
  203. Optional<StringRef> Msg = None) {
  204. return {
  205. std::move(SinkArgs), {}, std::move(SrcArgs), std::move(DstArgs), Msg};
  206. }
  207. /// Process a function which could either be a taint source, a taint sink, a
  208. /// taint filter or a taint propagator.
  209. void process(const GenericTaintChecker &Checker, const CallEvent &Call,
  210. CheckerContext &C) const;
  211. /// Handles the resolution of indexes of type ArgIdxTy to Expr*-s.
  212. static const Expr *GetArgExpr(ArgIdxTy ArgIdx, const CallEvent &Call) {
  213. return ArgIdx == ReturnValueIndex ? Call.getOriginExpr()
  214. : Call.getArgExpr(ArgIdx);
  215. };
  216. /// Functions for custom taintedness propagation.
  217. static bool UntrustedEnv(CheckerContext &C);
  218. };
  219. using RuleLookupTy = CallDescriptionMap<GenericTaintRule>;
  220. /// Used to parse the configuration file.
  221. struct TaintConfiguration {
  222. using NameScopeArgs = std::tuple<std::string, std::string, ArgVecTy>;
  223. enum class VariadicType { None, Src, Dst };
  224. struct Common {
  225. std::string Name;
  226. std::string Scope;
  227. };
  228. struct Sink : Common {
  229. ArgVecTy SinkArgs;
  230. };
  231. struct Filter : Common {
  232. ArgVecTy FilterArgs;
  233. };
  234. struct Propagation : Common {
  235. ArgVecTy SrcArgs;
  236. ArgVecTy DstArgs;
  237. VariadicType VarType;
  238. ArgIdxTy VarIndex;
  239. };
  240. std::vector<Propagation> Propagations;
  241. std::vector<Filter> Filters;
  242. std::vector<Sink> Sinks;
  243. TaintConfiguration() = default;
  244. TaintConfiguration(const TaintConfiguration &) = default;
  245. TaintConfiguration(TaintConfiguration &&) = default;
  246. TaintConfiguration &operator=(const TaintConfiguration &) = default;
  247. TaintConfiguration &operator=(TaintConfiguration &&) = default;
  248. };
  249. struct GenericTaintRuleParser {
  250. GenericTaintRuleParser(CheckerManager &Mgr) : Mgr(Mgr) {}
  251. /// Container type used to gather call identification objects grouped into
  252. /// pairs with their corresponding taint rules. It is temporary as it is used
  253. /// to finally initialize RuleLookupTy, which is considered to be immutable.
  254. using RulesContTy = std::vector<std::pair<CallDescription, GenericTaintRule>>;
  255. RulesContTy parseConfiguration(const std::string &Option,
  256. TaintConfiguration &&Config) const;
  257. private:
  258. using NamePartsTy = llvm::SmallVector<SmallString<32>, 2>;
  259. /// Validate part of the configuration, which contains a list of argument
  260. /// indexes.
  261. void validateArgVector(const std::string &Option, const ArgVecTy &Args) const;
  262. template <typename Config> static NamePartsTy parseNameParts(const Config &C);
  263. // Takes the config and creates a CallDescription for it and associates a Rule
  264. // with that.
  265. template <typename Config>
  266. static void consumeRulesFromConfig(const Config &C, GenericTaintRule &&Rule,
  267. RulesContTy &Rules);
  268. void parseConfig(const std::string &Option, TaintConfiguration::Sink &&P,
  269. RulesContTy &Rules) const;
  270. void parseConfig(const std::string &Option, TaintConfiguration::Filter &&P,
  271. RulesContTy &Rules) const;
  272. void parseConfig(const std::string &Option,
  273. TaintConfiguration::Propagation &&P,
  274. RulesContTy &Rules) const;
  275. CheckerManager &Mgr;
  276. };
  277. class GenericTaintChecker : public Checker<check::PreCall, check::PostCall> {
  278. public:
  279. static void *getTag() {
  280. static int Tag;
  281. return &Tag;
  282. }
  283. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  284. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  285. void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
  286. const char *Sep) const override;
  287. /// Generate a report if the expression is tainted or points to tainted data.
  288. bool generateReportIfTainted(const Expr *E, StringRef Msg,
  289. CheckerContext &C) const;
  290. private:
  291. const BugType BT{this, "Use of Untrusted Data", "Untrusted Data"};
  292. bool checkUncontrolledFormatString(const CallEvent &Call,
  293. CheckerContext &C) const;
  294. void taintUnsafeSocketProtocol(const CallEvent &Call,
  295. CheckerContext &C) const;
  296. /// Default taint rules are initilized with the help of a CheckerContext to
  297. /// access the names of built-in functions like memcpy.
  298. void initTaintRules(CheckerContext &C) const;
  299. /// CallDescription currently cannot restrict matches to the global namespace
  300. /// only, which is why multiple CallDescriptionMaps are used, as we want to
  301. /// disambiguate global C functions from functions inside user-defined
  302. /// namespaces.
  303. // TODO: Remove separation to simplify matching logic once CallDescriptions
  304. // are more expressive.
  305. mutable Optional<RuleLookupTy> StaticTaintRules;
  306. mutable Optional<RuleLookupTy> DynamicTaintRules;
  307. };
  308. } // end of anonymous namespace
  309. /// YAML serialization mapping.
  310. LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Sink)
  311. LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Filter)
  312. LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Propagation)
  313. namespace llvm {
  314. namespace yaml {
  315. template <> struct MappingTraits<TaintConfiguration> {
  316. static void mapping(IO &IO, TaintConfiguration &Config) {
  317. IO.mapOptional("Propagations", Config.Propagations);
  318. IO.mapOptional("Filters", Config.Filters);
  319. IO.mapOptional("Sinks", Config.Sinks);
  320. }
  321. };
  322. template <> struct MappingTraits<TaintConfiguration::Sink> {
  323. static void mapping(IO &IO, TaintConfiguration::Sink &Sink) {
  324. IO.mapRequired("Name", Sink.Name);
  325. IO.mapOptional("Scope", Sink.Scope);
  326. IO.mapRequired("Args", Sink.SinkArgs);
  327. }
  328. };
  329. template <> struct MappingTraits<TaintConfiguration::Filter> {
  330. static void mapping(IO &IO, TaintConfiguration::Filter &Filter) {
  331. IO.mapRequired("Name", Filter.Name);
  332. IO.mapOptional("Scope", Filter.Scope);
  333. IO.mapRequired("Args", Filter.FilterArgs);
  334. }
  335. };
  336. template <> struct MappingTraits<TaintConfiguration::Propagation> {
  337. static void mapping(IO &IO, TaintConfiguration::Propagation &Propagation) {
  338. IO.mapRequired("Name", Propagation.Name);
  339. IO.mapOptional("Scope", Propagation.Scope);
  340. IO.mapOptional("SrcArgs", Propagation.SrcArgs);
  341. IO.mapOptional("DstArgs", Propagation.DstArgs);
  342. IO.mapOptional("VariadicType", Propagation.VarType);
  343. IO.mapOptional("VariadicIndex", Propagation.VarIndex);
  344. }
  345. };
  346. template <> struct ScalarEnumerationTraits<TaintConfiguration::VariadicType> {
  347. static void enumeration(IO &IO, TaintConfiguration::VariadicType &Value) {
  348. IO.enumCase(Value, "None", TaintConfiguration::VariadicType::None);
  349. IO.enumCase(Value, "Src", TaintConfiguration::VariadicType::Src);
  350. IO.enumCase(Value, "Dst", TaintConfiguration::VariadicType::Dst);
  351. }
  352. };
  353. } // namespace yaml
  354. } // namespace llvm
  355. /// A set which is used to pass information from call pre-visit instruction
  356. /// to the call post-visit. The values are signed integers, which are either
  357. /// ReturnValueIndex, or indexes of the pointer/reference argument, which
  358. /// points to data, which should be tainted on return.
  359. REGISTER_SET_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, ArgIdxTy)
  360. void GenericTaintRuleParser::validateArgVector(const std::string &Option,
  361. const ArgVecTy &Args) const {
  362. for (ArgIdxTy Arg : Args) {
  363. if (Arg < ReturnValueIndex) {
  364. Mgr.reportInvalidCheckerOptionValue(
  365. Mgr.getChecker<GenericTaintChecker>(), Option,
  366. "an argument number for propagation rules greater or equal to -1");
  367. }
  368. }
  369. }
  370. template <typename Config>
  371. GenericTaintRuleParser::NamePartsTy
  372. GenericTaintRuleParser::parseNameParts(const Config &C) {
  373. NamePartsTy NameParts;
  374. if (!C.Scope.empty()) {
  375. // If the Scope argument contains multiple "::" parts, those are considered
  376. // namespace identifiers.
  377. llvm::SmallVector<StringRef, 2> NSParts;
  378. StringRef{C.Scope}.split(NSParts, "::", /*MaxSplit*/ -1,
  379. /*KeepEmpty*/ false);
  380. NameParts.append(NSParts.begin(), NSParts.end());
  381. }
  382. NameParts.emplace_back(C.Name);
  383. return NameParts;
  384. }
  385. template <typename Config>
  386. void GenericTaintRuleParser::consumeRulesFromConfig(const Config &C,
  387. GenericTaintRule &&Rule,
  388. RulesContTy &Rules) {
  389. NamePartsTy NameParts = parseNameParts(C);
  390. llvm::SmallVector<const char *, 2> CallDescParts{NameParts.size()};
  391. llvm::transform(NameParts, CallDescParts.begin(),
  392. [](SmallString<32> &S) { return S.c_str(); });
  393. Rules.emplace_back(CallDescription(CallDescParts), std::move(Rule));
  394. }
  395. void GenericTaintRuleParser::parseConfig(const std::string &Option,
  396. TaintConfiguration::Sink &&S,
  397. RulesContTy &Rules) const {
  398. validateArgVector(Option, S.SinkArgs);
  399. consumeRulesFromConfig(S, GenericTaintRule::Sink(std::move(S.SinkArgs)),
  400. Rules);
  401. }
  402. void GenericTaintRuleParser::parseConfig(const std::string &Option,
  403. TaintConfiguration::Filter &&S,
  404. RulesContTy &Rules) const {
  405. validateArgVector(Option, S.FilterArgs);
  406. consumeRulesFromConfig(S, GenericTaintRule::Filter(std::move(S.FilterArgs)),
  407. Rules);
  408. }
  409. void GenericTaintRuleParser::parseConfig(const std::string &Option,
  410. TaintConfiguration::Propagation &&P,
  411. RulesContTy &Rules) const {
  412. validateArgVector(Option, P.SrcArgs);
  413. validateArgVector(Option, P.DstArgs);
  414. bool IsSrcVariadic = P.VarType == TaintConfiguration::VariadicType::Src;
  415. bool IsDstVariadic = P.VarType == TaintConfiguration::VariadicType::Dst;
  416. Optional<ArgIdxTy> JustVarIndex = P.VarIndex;
  417. ArgSet SrcDesc(std::move(P.SrcArgs), IsSrcVariadic ? JustVarIndex : None);
  418. ArgSet DstDesc(std::move(P.DstArgs), IsDstVariadic ? JustVarIndex : None);
  419. consumeRulesFromConfig(
  420. P, GenericTaintRule::Prop(std::move(SrcDesc), std::move(DstDesc)), Rules);
  421. }
  422. GenericTaintRuleParser::RulesContTy
  423. GenericTaintRuleParser::parseConfiguration(const std::string &Option,
  424. TaintConfiguration &&Config) const {
  425. RulesContTy Rules;
  426. for (auto &F : Config.Filters)
  427. parseConfig(Option, std::move(F), Rules);
  428. for (auto &S : Config.Sinks)
  429. parseConfig(Option, std::move(S), Rules);
  430. for (auto &P : Config.Propagations)
  431. parseConfig(Option, std::move(P), Rules);
  432. return Rules;
  433. }
  434. void GenericTaintChecker::initTaintRules(CheckerContext &C) const {
  435. // Check for exact name match for functions without builtin substitutes.
  436. // Use qualified name, because these are C functions without namespace.
  437. if (StaticTaintRules || DynamicTaintRules)
  438. return;
  439. using RulesConstructionTy =
  440. std::vector<std::pair<CallDescription, GenericTaintRule>>;
  441. using TR = GenericTaintRule;
  442. const Builtin::Context &BI = C.getASTContext().BuiltinInfo;
  443. RulesConstructionTy GlobalCRules{
  444. // Sources
  445. {{"fdopen"}, TR::Source({{ReturnValueIndex}})},
  446. {{"fopen"}, TR::Source({{ReturnValueIndex}})},
  447. {{"freopen"}, TR::Source({{ReturnValueIndex}})},
  448. {{"getch"}, TR::Source({{ReturnValueIndex}})},
  449. {{"getchar"}, TR::Source({{ReturnValueIndex}})},
  450. {{"getchar_unlocked"}, TR::Source({{ReturnValueIndex}})},
  451. {{"gets"}, TR::Source({{0}, ReturnValueIndex})},
  452. {{"scanf"}, TR::Source({{}, 1})},
  453. {{"wgetch"}, TR::Source({{}, ReturnValueIndex})},
  454. // Props
  455. {{"atoi"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  456. {{"atol"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  457. {{"atoll"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  458. {{"fgetc"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  459. {{"fgetln"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  460. {{"fgets"}, TR::Prop({{2}}, {{0}, ReturnValueIndex})},
  461. {{"fscanf"}, TR::Prop({{0}}, {{}, 2})},
  462. {{"sscanf"}, TR::Prop({{0}}, {{}, 2})},
  463. {{"getc"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  464. {{"getc_unlocked"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  465. {{"getdelim"}, TR::Prop({{3}}, {{0}})},
  466. {{"getline"}, TR::Prop({{2}}, {{0}})},
  467. {{"getw"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  468. {{"pread"}, TR::Prop({{0, 1, 2, 3}}, {{1, ReturnValueIndex}})},
  469. {{"read"}, TR::Prop({{0, 2}}, {{1, ReturnValueIndex}})},
  470. {{"strchr"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  471. {{"strrchr"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  472. {{"tolower"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  473. {{"toupper"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  474. {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrncat)}},
  475. TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
  476. {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrlcpy)}},
  477. TR::Prop({{1, 2}}, {{0}})},
  478. {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrlcat)}},
  479. TR::Prop({{1, 2}}, {{0}})},
  480. {{CDF_MaybeBuiltin, {"snprintf"}},
  481. TR::Prop({{1}, 3}, {{0, ReturnValueIndex}})},
  482. {{CDF_MaybeBuiltin, {"sprintf"}},
  483. TR::Prop({{1}, 2}, {{0, ReturnValueIndex}})},
  484. {{CDF_MaybeBuiltin, {"strcpy"}},
  485. TR::Prop({{1}}, {{0, ReturnValueIndex}})},
  486. {{CDF_MaybeBuiltin, {"stpcpy"}},
  487. TR::Prop({{1}}, {{0, ReturnValueIndex}})},
  488. {{CDF_MaybeBuiltin, {"strcat"}},
  489. TR::Prop({{1}}, {{0, ReturnValueIndex}})},
  490. {{CDF_MaybeBuiltin, {"strdup"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  491. {{CDF_MaybeBuiltin, {"strdupa"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  492. {{CDF_MaybeBuiltin, {"wcsdup"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
  493. // Sinks
  494. {{"system"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  495. {{"popen"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  496. {{"execl"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  497. {{"execle"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  498. {{"execlp"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  499. {{"execvp"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  500. {{"execvP"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  501. {{"execve"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  502. {{"dlopen"}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
  503. {{CDF_MaybeBuiltin, {"malloc"}}, TR::Sink({{0}}, MsgTaintedBufferSize)},
  504. {{CDF_MaybeBuiltin, {"calloc"}}, TR::Sink({{0}}, MsgTaintedBufferSize)},
  505. {{CDF_MaybeBuiltin, {"alloca"}}, TR::Sink({{0}}, MsgTaintedBufferSize)},
  506. {{CDF_MaybeBuiltin, {"memccpy"}}, TR::Sink({{3}}, MsgTaintedBufferSize)},
  507. {{CDF_MaybeBuiltin, {"realloc"}}, TR::Sink({{1}}, MsgTaintedBufferSize)},
  508. {{{"setproctitle"}}, TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
  509. {{{"setproctitle_fast"}},
  510. TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
  511. // SinkProps
  512. {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
  513. TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
  514. MsgTaintedBufferSize)},
  515. {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
  516. TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
  517. MsgTaintedBufferSize)},
  518. {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrncpy)}},
  519. TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
  520. MsgTaintedBufferSize)},
  521. {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrndup)}},
  522. TR::SinkProp({{1}}, {{0, 1}}, {{ReturnValueIndex}},
  523. MsgTaintedBufferSize)},
  524. {{CDF_MaybeBuiltin, {"bcopy"}},
  525. TR::SinkProp({{2}}, {{0, 2}}, {{1}}, MsgTaintedBufferSize)}};
  526. // `getenv` returns taint only in untrusted environments.
  527. if (TR::UntrustedEnv(C)) {
  528. // void setproctitle_init(int argc, char *argv[], char *envp[])
  529. GlobalCRules.push_back(
  530. {{{"setproctitle_init"}}, TR::Sink({{2}}, MsgCustomSink)});
  531. GlobalCRules.push_back({{"getenv"}, TR::Source({{ReturnValueIndex}})});
  532. }
  533. StaticTaintRules.emplace(std::make_move_iterator(GlobalCRules.begin()),
  534. std::make_move_iterator(GlobalCRules.end()));
  535. // User-provided taint configuration.
  536. CheckerManager *Mgr = C.getAnalysisManager().getCheckerManager();
  537. assert(Mgr);
  538. GenericTaintRuleParser ConfigParser{*Mgr};
  539. std::string Option{"Config"};
  540. StringRef ConfigFile =
  541. Mgr->getAnalyzerOptions().getCheckerStringOption(this, Option);
  542. llvm::Optional<TaintConfiguration> Config =
  543. getConfiguration<TaintConfiguration>(*Mgr, this, Option, ConfigFile);
  544. if (!Config) {
  545. // We don't have external taint config, no parsing required.
  546. DynamicTaintRules = RuleLookupTy{};
  547. return;
  548. }
  549. GenericTaintRuleParser::RulesContTy Rules{
  550. ConfigParser.parseConfiguration(Option, std::move(Config.getValue()))};
  551. DynamicTaintRules.emplace(std::make_move_iterator(Rules.begin()),
  552. std::make_move_iterator(Rules.end()));
  553. }
  554. void GenericTaintChecker::checkPreCall(const CallEvent &Call,
  555. CheckerContext &C) const {
  556. initTaintRules(C);
  557. // FIXME: this should be much simpler.
  558. if (const auto *Rule =
  559. Call.isGlobalCFunction() ? StaticTaintRules->lookup(Call) : nullptr)
  560. Rule->process(*this, Call, C);
  561. else if (const auto *Rule = DynamicTaintRules->lookup(Call))
  562. Rule->process(*this, Call, C);
  563. // FIXME: These edge cases are to be eliminated from here eventually.
  564. //
  565. // Additional check that is not supported by CallDescription.
  566. // TODO: Make CallDescription be able to match attributes such as printf-like
  567. // arguments.
  568. checkUncontrolledFormatString(Call, C);
  569. // TODO: Modeling sockets should be done in a specific checker.
  570. // Socket is a source, which taints the return value.
  571. taintUnsafeSocketProtocol(Call, C);
  572. }
  573. void GenericTaintChecker::checkPostCall(const CallEvent &Call,
  574. CheckerContext &C) const {
  575. // Set the marked values as tainted. The return value only accessible from
  576. // checkPostStmt.
  577. ProgramStateRef State = C.getState();
  578. // Depending on what was tainted at pre-visit, we determined a set of
  579. // arguments which should be tainted after the function returns. These are
  580. // stored in the state as TaintArgsOnPostVisit set.
  581. TaintArgsOnPostVisitTy TaintArgs = State->get<TaintArgsOnPostVisit>();
  582. if (TaintArgs.isEmpty())
  583. return;
  584. for (ArgIdxTy ArgNum : TaintArgs) {
  585. // Special handling for the tainted return value.
  586. if (ArgNum == ReturnValueIndex) {
  587. State = addTaint(State, Call.getReturnValue());
  588. continue;
  589. }
  590. // The arguments are pointer arguments. The data they are pointing at is
  591. // tainted after the call.
  592. if (auto V = getPointeeOf(C, Call.getArgSVal(ArgNum)))
  593. State = addTaint(State, *V);
  594. }
  595. // Clear up the taint info from the state.
  596. State = State->remove<TaintArgsOnPostVisit>();
  597. C.addTransition(State);
  598. }
  599. void GenericTaintChecker::printState(raw_ostream &Out, ProgramStateRef State,
  600. const char *NL, const char *Sep) const {
  601. printTaint(State, Out, NL, Sep);
  602. }
  603. void GenericTaintRule::process(const GenericTaintChecker &Checker,
  604. const CallEvent &Call, CheckerContext &C) const {
  605. ProgramStateRef State = C.getState();
  606. const ArgIdxTy CallNumArgs = fromArgumentCount(Call.getNumArgs());
  607. /// Iterate every call argument, and get their corresponding Expr and SVal.
  608. const auto ForEachCallArg = [&C, &Call, CallNumArgs](auto &&Fun) {
  609. for (ArgIdxTy I = ReturnValueIndex; I < CallNumArgs; ++I) {
  610. const Expr *E = GetArgExpr(I, Call);
  611. Fun(I, E, C.getSVal(E));
  612. }
  613. };
  614. /// Check for taint sinks.
  615. ForEachCallArg([this, &Checker, &C, &State](ArgIdxTy I, const Expr *E, SVal) {
  616. if (SinkArgs.contains(I) && isTaintedOrPointsToTainted(E, State, C))
  617. Checker.generateReportIfTainted(E, SinkMsg.getValueOr(MsgCustomSink), C);
  618. });
  619. /// Check for taint filters.
  620. ForEachCallArg([this, &C, &State](ArgIdxTy I, const Expr *E, SVal S) {
  621. if (FilterArgs.contains(I)) {
  622. State = removeTaint(State, S);
  623. if (auto P = getPointeeOf(C, S))
  624. State = removeTaint(State, *P);
  625. }
  626. });
  627. /// Check for taint propagation sources.
  628. /// A rule is relevant if PropSrcArgs is empty, or if any of its signified
  629. /// args are tainted in context of the current CallEvent.
  630. bool IsMatching = PropSrcArgs.isEmpty();
  631. ForEachCallArg(
  632. [this, &C, &IsMatching, &State](ArgIdxTy I, const Expr *E, SVal) {
  633. IsMatching = IsMatching || (PropSrcArgs.contains(I) &&
  634. isTaintedOrPointsToTainted(E, State, C));
  635. });
  636. if (!IsMatching)
  637. return;
  638. const auto WouldEscape = [](SVal V, QualType Ty) -> bool {
  639. if (!V.getAs<Loc>())
  640. return false;
  641. const bool IsNonConstRef = Ty->isReferenceType() && !Ty.isConstQualified();
  642. const bool IsNonConstPtr =
  643. Ty->isPointerType() && !Ty->getPointeeType().isConstQualified();
  644. return IsNonConstRef || IsNonConstPtr;
  645. };
  646. /// Propagate taint where it is necessary.
  647. ForEachCallArg(
  648. [this, &State, WouldEscape](ArgIdxTy I, const Expr *E, SVal V) {
  649. if (PropDstArgs.contains(I))
  650. State = State->add<TaintArgsOnPostVisit>(I);
  651. // TODO: We should traverse all reachable memory regions via the
  652. // escaping parameter. Instead of doing that we simply mark only the
  653. // referred memory region as tainted.
  654. if (WouldEscape(V, E->getType()))
  655. State = State->add<TaintArgsOnPostVisit>(I);
  656. });
  657. C.addTransition(State);
  658. }
  659. bool GenericTaintRule::UntrustedEnv(CheckerContext &C) {
  660. return !C.getAnalysisManager()
  661. .getAnalyzerOptions()
  662. .ShouldAssumeControlledEnvironment;
  663. }
  664. bool GenericTaintChecker::generateReportIfTainted(const Expr *E, StringRef Msg,
  665. CheckerContext &C) const {
  666. assert(E);
  667. Optional<SVal> TaintedSVal{getTaintedPointeeOrPointer(C, C.getSVal(E))};
  668. if (!TaintedSVal)
  669. return false;
  670. // Generate diagnostic.
  671. if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
  672. auto report = std::make_unique<PathSensitiveBugReport>(BT, Msg, N);
  673. report->addRange(E->getSourceRange());
  674. report->addVisitor(std::make_unique<TaintBugVisitor>(*TaintedSVal));
  675. C.emitReport(std::move(report));
  676. return true;
  677. }
  678. return false;
  679. }
  680. /// TODO: remove checking for printf format attributes and socket whitelisting
  681. /// from GenericTaintChecker, and that means the following functions:
  682. /// getPrintfFormatArgumentNum,
  683. /// GenericTaintChecker::checkUncontrolledFormatString,
  684. /// GenericTaintChecker::taintUnsafeSocketProtocol
  685. static bool getPrintfFormatArgumentNum(const CallEvent &Call,
  686. const CheckerContext &C,
  687. ArgIdxTy &ArgNum) {
  688. // Find if the function contains a format string argument.
  689. // Handles: fprintf, printf, sprintf, snprintf, vfprintf, vprintf, vsprintf,
  690. // vsnprintf, syslog, custom annotated functions.
  691. const Decl *CallDecl = Call.getDecl();
  692. if (!CallDecl)
  693. return false;
  694. const FunctionDecl *FDecl = CallDecl->getAsFunction();
  695. if (!FDecl)
  696. return false;
  697. const ArgIdxTy CallNumArgs = fromArgumentCount(Call.getNumArgs());
  698. for (const auto *Format : FDecl->specific_attrs<FormatAttr>()) {
  699. ArgNum = Format->getFormatIdx() - 1;
  700. if ((Format->getType()->getName() == "printf") && CallNumArgs > ArgNum)
  701. return true;
  702. }
  703. return false;
  704. }
  705. bool GenericTaintChecker::checkUncontrolledFormatString(
  706. const CallEvent &Call, CheckerContext &C) const {
  707. // Check if the function contains a format string argument.
  708. ArgIdxTy ArgNum = 0;
  709. if (!getPrintfFormatArgumentNum(Call, C, ArgNum))
  710. return false;
  711. // If either the format string content or the pointer itself are tainted,
  712. // warn.
  713. return generateReportIfTainted(Call.getArgExpr(ArgNum),
  714. MsgUncontrolledFormatString, C);
  715. }
  716. void GenericTaintChecker::taintUnsafeSocketProtocol(const CallEvent &Call,
  717. CheckerContext &C) const {
  718. if (Call.getNumArgs() < 1)
  719. return;
  720. const IdentifierInfo *ID = Call.getCalleeIdentifier();
  721. if (!ID)
  722. return;
  723. if (!ID->getName().equals("socket"))
  724. return;
  725. SourceLocation DomLoc = Call.getArgExpr(0)->getExprLoc();
  726. StringRef DomName = C.getMacroNameOrSpelling(DomLoc);
  727. // Allow internal communication protocols.
  728. bool SafeProtocol = DomName.equals("AF_SYSTEM") ||
  729. DomName.equals("AF_LOCAL") || DomName.equals("AF_UNIX") ||
  730. DomName.equals("AF_RESERVED_36");
  731. if (SafeProtocol)
  732. return;
  733. C.addTransition(C.getState()->add<TaintArgsOnPostVisit>(ReturnValueIndex));
  734. }
  735. /// Checker registration
  736. void ento::registerGenericTaintChecker(CheckerManager &Mgr) {
  737. Mgr.registerChecker<GenericTaintChecker>();
  738. }
  739. bool ento::shouldRegisterGenericTaintChecker(const CheckerManager &mgr) {
  740. return true;
  741. }