GenericTaintChecker.cpp 39 KB

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