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
17#include "Yaml.h"
18#include "clang/AST/Attr.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/ADT/StringExtras.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/Support/YAMLTraits.h"
31
32#include <limits>
33#include <memory>
34#include <optional>
35#include <utility>
36#include <vector>
37
38#define DEBUG_TYPE "taint-checker"
39
40using namespace clang;
41using namespace ento;
42using namespace taint;
43
44using llvm::ImmutableSet;
45
46namespace {
47
48class GenericTaintChecker;
49
50/// Check for CWE-134: Uncontrolled Format String.
51constexpr llvm::StringLiteral MsgUncontrolledFormatString =
52 "Untrusted data is used as a format string "
53 "(CWE-134: Uncontrolled Format String)";
54
55/// Check for:
56/// CERT/STR02-C. "Sanitize data passed to complex subsystems"
57/// CWE-78, "Failure to Sanitize Data into an OS Command"
58constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
59 "Untrusted data is passed to a system call "
60 "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
61
62/// Check if tainted data is used as a custom sink's parameter.
63constexpr llvm::StringLiteral MsgCustomSink =
64 "Untrusted data is passed to a user-defined sink";
65
66using ArgIdxTy = int;
67using ArgVecTy = llvm::SmallVector<ArgIdxTy, 2>;
68
69/// Denotes the return value.
70constexpr ArgIdxTy ReturnValueIndex{-1};
71
72static ArgIdxTy fromArgumentCount(unsigned Count) {
73 assert(Count <=
74 static_cast<std::size_t>(std::numeric_limits<ArgIdxTy>::max()) &&
75 "ArgIdxTy is not large enough to represent the number of arguments.");
76 return Count;
77}
78
79/// Check if the region the expression evaluates to is the standard input,
80/// and thus, is tainted.
81/// FIXME: Move this to Taint.cpp.
82bool isStdin(SVal Val, const ASTContext &ACtx) {
83 // FIXME: What if Val is NonParamVarRegion?
84
85 // The region should be symbolic, we do not know it's value.
86 const auto *SymReg = dyn_cast_or_null<SymbolicRegion>(Val: Val.getAsRegion());
87 if (!SymReg)
88 return false;
89
90 // Get it's symbol and find the declaration region it's pointing to.
91 const auto *DeclReg =
92 dyn_cast_or_null<DeclRegion>(Val: SymReg->getSymbol()->getOriginRegion());
93 if (!DeclReg)
94 return false;
95
96 // This region corresponds to a declaration, find out if it's a global/extern
97 // variable named stdin with the proper type.
98 if (const auto *D = dyn_cast_or_null<VarDecl>(Val: DeclReg->getDecl())) {
99 D = D->getCanonicalDecl();
100 if (D->getName() == "stdin" && D->hasExternalStorage() && D->isExternC()) {
101 const QualType FILETy = ACtx.getFILEType().getCanonicalType();
102 const QualType Ty = D->getType().getCanonicalType();
103
104 if (Ty->isPointerType())
105 return Ty->getPointeeType() == FILETy;
106 }
107 }
108 return false;
109}
110
111SVal getPointeeOf(ProgramStateRef State, Loc LValue) {
112 const QualType ArgTy = LValue.getType(State->getStateManager().getContext());
113 if (!ArgTy->isPointerType() || !ArgTy->getPointeeType()->isVoidType())
114 return State->getSVal(LV: LValue);
115
116 // Do not dereference void pointers. Treat them as byte pointers instead.
117 // FIXME: we might want to consider more than just the first byte.
118 return State->getSVal(LV: LValue, T: State->getStateManager().getContext().CharTy);
119}
120
121/// Given a pointer/reference argument, return the value it refers to.
122std::optional<SVal> getPointeeOf(ProgramStateRef State, SVal Arg) {
123 if (auto LValue = Arg.getAs<Loc>())
124 return getPointeeOf(State, LValue: *LValue);
125 return std::nullopt;
126}
127
128/// Given a pointer, return the SVal of its pointee or if it is tainted,
129/// otherwise return the pointer's SVal if tainted.
130/// Also considers stdin as a taint source.
131std::optional<SVal> getTaintedPointeeOrPointer(ProgramStateRef State,
132 SVal Arg) {
133 if (auto Pointee = getPointeeOf(State, Arg))
134 if (isTainted(State, V: *Pointee)) // FIXME: isTainted(...) ? Pointee : None;
135 return Pointee;
136
137 if (isTainted(State, V: Arg))
138 return Arg;
139 return std::nullopt;
140}
141
142bool isTaintedOrPointsToTainted(ProgramStateRef State, SVal ExprSVal) {
143 return getTaintedPointeeOrPointer(State, Arg: ExprSVal).has_value();
144}
145
146/// Helps in printing taint diagnostics.
147/// Marks the incoming parameters of a function interesting (to be printed)
148/// when the return value, or the outgoing parameters are tainted.
149const NoteTag *taintOriginTrackerTag(CheckerContext &C,
150 std::vector<SymbolRef> TaintedSymbols,
151 std::vector<ArgIdxTy> TaintedArgs,
152 const LocationContext *CallLocation) {
153 return C.getNoteTag(Cb: [TaintedSymbols = std::move(TaintedSymbols),
154 TaintedArgs = std::move(TaintedArgs), CallLocation](
155 PathSensitiveBugReport &BR) -> std::string {
156 // We give diagnostics only for taint related reports
157 if (!BR.isInteresting(LC: CallLocation) ||
158 BR.getBugType().getCategory() != categories::TaintedData) {
159 return "";
160 }
161 if (TaintedSymbols.empty())
162 return "Taint originated here";
163
164 for (auto Sym : TaintedSymbols) {
165 BR.markInteresting(sym: Sym);
166 }
167 LLVM_DEBUG(for (auto Arg
168 : TaintedArgs) {
169 llvm::dbgs() << "Taint Propagated from argument " << Arg + 1 << "\n";
170 });
171 return "";
172 });
173}
174
175/// Helps in printing taint diagnostics.
176/// Marks the function interesting (to be printed)
177/// when the return value, or the outgoing parameters are tainted.
178const NoteTag *taintPropagationExplainerTag(
179 CheckerContext &C, std::vector<SymbolRef> TaintedSymbols,
180 std::vector<ArgIdxTy> TaintedArgs, const LocationContext *CallLocation) {
181 assert(TaintedSymbols.size() == TaintedArgs.size());
182 return C.getNoteTag(Cb: [TaintedSymbols = std::move(TaintedSymbols),
183 TaintedArgs = std::move(TaintedArgs), CallLocation](
184 PathSensitiveBugReport &BR) -> std::string {
185 SmallString<256> Msg;
186 llvm::raw_svector_ostream Out(Msg);
187 // We give diagnostics only for taint related reports
188 if (TaintedSymbols.empty() ||
189 BR.getBugType().getCategory() != categories::TaintedData) {
190 return "";
191 }
192 int nofTaintedArgs = 0;
193 for (auto [Idx, Sym] : llvm::enumerate(First: TaintedSymbols)) {
194 if (BR.isInteresting(sym: Sym)) {
195 BR.markInteresting(LC: CallLocation);
196 if (TaintedArgs[Idx] != ReturnValueIndex) {
197 LLVM_DEBUG(llvm::dbgs() << "Taint Propagated to argument "
198 << TaintedArgs[Idx] + 1 << "\n");
199 if (nofTaintedArgs == 0)
200 Out << "Taint propagated to the ";
201 else
202 Out << ", ";
203 Out << TaintedArgs[Idx] + 1
204 << llvm::getOrdinalSuffix(Val: TaintedArgs[Idx] + 1) << " argument";
205 nofTaintedArgs++;
206 } else {
207 LLVM_DEBUG(llvm::dbgs() << "Taint Propagated to return value.\n");
208 Out << "Taint propagated to the return value";
209 }
210 }
211 }
212 return std::string(Out.str());
213 });
214}
215
216/// ArgSet is used to describe arguments relevant for taint detection or
217/// taint application. A discrete set of argument indexes and a variadic
218/// argument list signified by a starting index are supported.
219class ArgSet {
220public:
221 ArgSet() = default;
222 ArgSet(ArgVecTy &&DiscreteArgs,
223 std::optional<ArgIdxTy> VariadicIndex = std::nullopt)
224 : DiscreteArgs(std::move(DiscreteArgs)),
225 VariadicIndex(std::move(VariadicIndex)) {}
226
227 bool contains(ArgIdxTy ArgIdx) const {
228 if (llvm::is_contained(Range: DiscreteArgs, Element: ArgIdx))
229 return true;
230
231 return VariadicIndex && ArgIdx >= *VariadicIndex;
232 }
233
234 bool isEmpty() const { return DiscreteArgs.empty() && !VariadicIndex; }
235
236private:
237 ArgVecTy DiscreteArgs;
238 std::optional<ArgIdxTy> VariadicIndex;
239};
240
241/// A struct used to specify taint propagation rules for a function.
242///
243/// If any of the possible taint source arguments is tainted, all of the
244/// destination arguments should also be tainted. If ReturnValueIndex is added
245/// to the dst list, the return value will be tainted.
246class GenericTaintRule {
247 /// Arguments which are taints sinks and should be checked, and a report
248 /// should be emitted if taint reaches these.
249 ArgSet SinkArgs;
250 /// Arguments which should be sanitized on function return.
251 ArgSet FilterArgs;
252 /// Arguments which can participate in taint propagation. If any of the
253 /// arguments in PropSrcArgs is tainted, all arguments in PropDstArgs should
254 /// be tainted.
255 ArgSet PropSrcArgs;
256 ArgSet PropDstArgs;
257
258 /// A message that explains why the call is sensitive to taint.
259 std::optional<StringRef> SinkMsg;
260
261 GenericTaintRule() = default;
262
263 GenericTaintRule(ArgSet &&Sink, ArgSet &&Filter, ArgSet &&Src, ArgSet &&Dst,
264 std::optional<StringRef> SinkMsg = std::nullopt)
265 : SinkArgs(std::move(Sink)), FilterArgs(std::move(Filter)),
266 PropSrcArgs(std::move(Src)), PropDstArgs(std::move(Dst)),
267 SinkMsg(SinkMsg) {}
268
269public:
270 /// Make a rule that reports a warning if taint reaches any of \p FilterArgs
271 /// arguments.
272 static GenericTaintRule Sink(ArgSet &&SinkArgs,
273 std::optional<StringRef> Msg = std::nullopt) {
274 return {std::move(SinkArgs), {}, {}, {}, Msg};
275 }
276
277 /// Make a rule that sanitizes all FilterArgs arguments.
278 static GenericTaintRule Filter(ArgSet &&FilterArgs) {
279 return {{}, std::move(FilterArgs), {}, {}};
280 }
281
282 /// Make a rule that unconditionally taints all Args.
283 /// If Func is provided, it must also return true for taint to propagate.
284 static GenericTaintRule Source(ArgSet &&SourceArgs) {
285 return {{}, {}, {}, std::move(SourceArgs)};
286 }
287
288 /// Make a rule that taints all PropDstArgs if any of PropSrcArgs is tainted.
289 static GenericTaintRule Prop(ArgSet &&SrcArgs, ArgSet &&DstArgs) {
290 return {{}, {}, std::move(SrcArgs), std::move(DstArgs)};
291 }
292
293 /// Process a function which could either be a taint source, a taint sink, a
294 /// taint filter or a taint propagator.
295 void process(const GenericTaintChecker &Checker, const CallEvent &Call,
296 CheckerContext &C) const;
297
298 /// Handles the resolution of indexes of type ArgIdxTy to Expr*-s.
299 static const Expr *GetArgExpr(ArgIdxTy ArgIdx, const CallEvent &Call) {
300 return ArgIdx == ReturnValueIndex ? Call.getOriginExpr()
301 : Call.getArgExpr(Index: ArgIdx);
302 };
303
304 /// Functions for custom taintedness propagation.
305 static bool UntrustedEnv(CheckerContext &C);
306};
307
308using RuleLookupTy = CallDescriptionMap<GenericTaintRule>;
309
310/// Used to parse the configuration file.
311struct TaintConfiguration {
312 using NameScopeArgs = std::tuple<std::string, std::string, ArgVecTy>;
313 enum class VariadicType { None, Src, Dst };
314
315 struct Common {
316 std::string Name;
317 std::string Scope;
318 };
319
320 struct Sink : Common {
321 ArgVecTy SinkArgs;
322 };
323
324 struct Filter : Common {
325 ArgVecTy FilterArgs;
326 };
327
328 struct Propagation : Common {
329 ArgVecTy SrcArgs;
330 ArgVecTy DstArgs;
331 VariadicType VarType;
332 ArgIdxTy VarIndex;
333 };
334
335 std::vector<Propagation> Propagations;
336 std::vector<Filter> Filters;
337 std::vector<Sink> Sinks;
338
339 TaintConfiguration() = default;
340 TaintConfiguration(const TaintConfiguration &) = default;
341 TaintConfiguration(TaintConfiguration &&) = default;
342 TaintConfiguration &operator=(const TaintConfiguration &) = default;
343 TaintConfiguration &operator=(TaintConfiguration &&) = default;
344};
345
346struct GenericTaintRuleParser {
347 GenericTaintRuleParser(CheckerManager &Mgr) : Mgr(Mgr) {}
348 /// Container type used to gather call identification objects grouped into
349 /// pairs with their corresponding taint rules. It is temporary as it is used
350 /// to finally initialize RuleLookupTy, which is considered to be immutable.
351 using RulesContTy = std::vector<std::pair<CallDescription, GenericTaintRule>>;
352 RulesContTy parseConfiguration(const std::string &Option,
353 TaintConfiguration &&Config) const;
354
355private:
356 using NamePartsTy = llvm::SmallVector<StringRef, 2>;
357
358 /// Validate part of the configuration, which contains a list of argument
359 /// indexes.
360 void validateArgVector(const std::string &Option, const ArgVecTy &Args) const;
361
362 template <typename Config> static NamePartsTy parseNameParts(const Config &C);
363
364 // Takes the config and creates a CallDescription for it and associates a Rule
365 // with that.
366 template <typename Config>
367 static void consumeRulesFromConfig(const Config &C, GenericTaintRule &&Rule,
368 RulesContTy &Rules);
369
370 void parseConfig(const std::string &Option, TaintConfiguration::Sink &&P,
371 RulesContTy &Rules) const;
372 void parseConfig(const std::string &Option, TaintConfiguration::Filter &&P,
373 RulesContTy &Rules) const;
374 void parseConfig(const std::string &Option,
375 TaintConfiguration::Propagation &&P,
376 RulesContTy &Rules) const;
377
378 CheckerManager &Mgr;
379};
380
381class GenericTaintChecker
382 : public Checker<check::PreCall, check::PostCall, check::BeginFunction> {
383public:
384 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
385 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
386 void checkBeginFunction(CheckerContext &C) const;
387
388 void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
389 const char *Sep) const override;
390
391 /// Generate a report if the expression is tainted or points to tainted data.
392 bool generateReportIfTainted(const Expr *E, StringRef Msg,
393 CheckerContext &C) const;
394
395 bool isTaintReporterCheckerEnabled = false;
396 std::optional<BugType> BT;
397
398private:
399 bool checkUncontrolledFormatString(const CallEvent &Call,
400 CheckerContext &C) const;
401
402 void taintUnsafeSocketProtocol(const CallEvent &Call,
403 CheckerContext &C) const;
404
405 /// The taint rules are initalized with the help of a CheckerContext to
406 /// access user-provided configuration.
407 void initTaintRules(CheckerContext &C) const;
408
409 // TODO: The two separate `CallDescriptionMap`s were introduced when
410 // `CallDescription` was unable to restrict matches to the global namespace
411 // only. This limitation no longer exists, so the following two maps should
412 // be unified.
413 mutable std::optional<RuleLookupTy> StaticTaintRules;
414 mutable std::optional<RuleLookupTy> DynamicTaintRules;
415};
416} // end of anonymous namespace
417
418/// YAML serialization mapping.
419LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Sink)
420LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Filter)
421LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Propagation)
422
423namespace llvm {
424namespace yaml {
425template <> struct MappingTraits<TaintConfiguration> {
426 static void mapping(IO &IO, TaintConfiguration &Config) {
427 IO.mapOptional(Key: "Propagations", Val&: Config.Propagations);
428 IO.mapOptional(Key: "Filters", Val&: Config.Filters);
429 IO.mapOptional(Key: "Sinks", Val&: Config.Sinks);
430 }
431};
432
433template <> struct MappingTraits<TaintConfiguration::Sink> {
434 static void mapping(IO &IO, TaintConfiguration::Sink &Sink) {
435 IO.mapRequired(Key: "Name", Val&: Sink.Name);
436 IO.mapOptional(Key: "Scope", Val&: Sink.Scope);
437 IO.mapRequired(Key: "Args", Val&: Sink.SinkArgs);
438 }
439};
440
441template <> struct MappingTraits<TaintConfiguration::Filter> {
442 static void mapping(IO &IO, TaintConfiguration::Filter &Filter) {
443 IO.mapRequired(Key: "Name", Val&: Filter.Name);
444 IO.mapOptional(Key: "Scope", Val&: Filter.Scope);
445 IO.mapRequired(Key: "Args", Val&: Filter.FilterArgs);
446 }
447};
448
449template <> struct MappingTraits<TaintConfiguration::Propagation> {
450 static void mapping(IO &IO, TaintConfiguration::Propagation &Propagation) {
451 IO.mapRequired(Key: "Name", Val&: Propagation.Name);
452 IO.mapOptional(Key: "Scope", Val&: Propagation.Scope);
453 IO.mapOptional(Key: "SrcArgs", Val&: Propagation.SrcArgs);
454 IO.mapOptional(Key: "DstArgs", Val&: Propagation.DstArgs);
455 IO.mapOptional(Key: "VariadicType", Val&: Propagation.VarType);
456 IO.mapOptional(Key: "VariadicIndex", Val&: Propagation.VarIndex);
457 }
458};
459
460template <> struct ScalarEnumerationTraits<TaintConfiguration::VariadicType> {
461 static void enumeration(IO &IO, TaintConfiguration::VariadicType &Value) {
462 IO.enumCase(Val&: Value, Str: "None", ConstVal: TaintConfiguration::VariadicType::None);
463 IO.enumCase(Val&: Value, Str: "Src", ConstVal: TaintConfiguration::VariadicType::Src);
464 IO.enumCase(Val&: Value, Str: "Dst", ConstVal: TaintConfiguration::VariadicType::Dst);
465 }
466};
467} // namespace yaml
468} // namespace llvm
469
470/// A set which is used to pass information from call pre-visit instruction
471/// to the call post-visit. The values are signed integers, which are either
472/// ReturnValueIndex, or indexes of the pointer/reference argument, which
473/// points to data, which should be tainted on return.
474REGISTER_MAP_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, const LocationContext *,
475 ImmutableSet<ArgIdxTy>)
476REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ArgIdxFactory, ArgIdxTy)
477
478void GenericTaintRuleParser::validateArgVector(const std::string &Option,
479 const ArgVecTy &Args) const {
480 for (ArgIdxTy Arg : Args) {
481 if (Arg < ReturnValueIndex) {
482 Mgr.reportInvalidCheckerOptionValue(
483 Checker: Mgr.getChecker<GenericTaintChecker>(), OptionName: Option,
484 ExpectedValueDesc: "an argument number for propagation rules greater or equal to -1");
485 }
486 }
487}
488
489template <typename Config>
490GenericTaintRuleParser::NamePartsTy
491GenericTaintRuleParser::parseNameParts(const Config &C) {
492 NamePartsTy NameParts;
493 if (!C.Scope.empty()) {
494 // If the Scope argument contains multiple "::" parts, those are considered
495 // namespace identifiers.
496 StringRef{C.Scope}.split(A&: NameParts, Separator: "::", /*MaxSplit*/ -1,
497 /*KeepEmpty*/ false);
498 }
499 NameParts.emplace_back(C.Name);
500 return NameParts;
501}
502
503template <typename Config>
504void GenericTaintRuleParser::consumeRulesFromConfig(const Config &C,
505 GenericTaintRule &&Rule,
506 RulesContTy &Rules) {
507 NamePartsTy NameParts = parseNameParts(C);
508 Rules.emplace_back(args: CallDescription(CDM::Unspecified, NameParts),
509 args: std::move(Rule));
510}
511
512void GenericTaintRuleParser::parseConfig(const std::string &Option,
513 TaintConfiguration::Sink &&S,
514 RulesContTy &Rules) const {
515 validateArgVector(Option, Args: S.SinkArgs);
516 consumeRulesFromConfig(C: S, Rule: GenericTaintRule::Sink(SinkArgs: std::move(S.SinkArgs)),
517 Rules);
518}
519
520void GenericTaintRuleParser::parseConfig(const std::string &Option,
521 TaintConfiguration::Filter &&S,
522 RulesContTy &Rules) const {
523 validateArgVector(Option, Args: S.FilterArgs);
524 consumeRulesFromConfig(C: S, Rule: GenericTaintRule::Filter(FilterArgs: std::move(S.FilterArgs)),
525 Rules);
526}
527
528void GenericTaintRuleParser::parseConfig(const std::string &Option,
529 TaintConfiguration::Propagation &&P,
530 RulesContTy &Rules) const {
531 validateArgVector(Option, Args: P.SrcArgs);
532 validateArgVector(Option, Args: P.DstArgs);
533 bool IsSrcVariadic = P.VarType == TaintConfiguration::VariadicType::Src;
534 bool IsDstVariadic = P.VarType == TaintConfiguration::VariadicType::Dst;
535 std::optional<ArgIdxTy> JustVarIndex = P.VarIndex;
536
537 ArgSet SrcDesc(std::move(P.SrcArgs),
538 IsSrcVariadic ? JustVarIndex : std::nullopt);
539 ArgSet DstDesc(std::move(P.DstArgs),
540 IsDstVariadic ? JustVarIndex : std::nullopt);
541
542 consumeRulesFromConfig(
543 C: P, Rule: GenericTaintRule::Prop(SrcArgs: std::move(SrcDesc), DstArgs: std::move(DstDesc)), Rules);
544}
545
546GenericTaintRuleParser::RulesContTy
547GenericTaintRuleParser::parseConfiguration(const std::string &Option,
548 TaintConfiguration &&Config) const {
549
550 RulesContTy Rules;
551
552 for (auto &F : Config.Filters)
553 parseConfig(Option, S: std::move(F), Rules);
554
555 for (auto &S : Config.Sinks)
556 parseConfig(Option, S: std::move(S), Rules);
557
558 for (auto &P : Config.Propagations)
559 parseConfig(Option, P: std::move(P), Rules);
560
561 return Rules;
562}
563
564void GenericTaintChecker::initTaintRules(CheckerContext &C) const {
565 // Check for exact name match for functions without builtin substitutes.
566 // Use qualified name, because these are C functions without namespace.
567
568 if (StaticTaintRules || DynamicTaintRules)
569 return;
570
571 using RulesConstructionTy =
572 std::vector<std::pair<CallDescription, GenericTaintRule>>;
573 using TR = GenericTaintRule;
574
575 RulesConstructionTy GlobalCRules{
576 // Sources
577 {{CDM::CLibrary, {"fdopen"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
578 {{CDM::CLibrary, {"fopen"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
579 {{CDM::CLibrary, {"freopen"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
580 {{CDM::CLibrary, {"getch"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
581 {{CDM::CLibrary, {"getchar"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
582 {{CDM::CLibrary, {"getchar_unlocked"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
583 {{CDM::CLibrary, {"gets"}}, TR::Source(SourceArgs: {{0, ReturnValueIndex}})},
584 {{CDM::CLibrary, {"gets_s"}}, TR::Source(SourceArgs: {{0, ReturnValueIndex}})},
585 {{CDM::CLibrary, {"scanf"}}, TR::Source(SourceArgs: {{}, 1})},
586 {{CDM::CLibrary, {"scanf_s"}}, TR::Source(SourceArgs: {{}, 1})},
587 {{CDM::CLibrary, {"wgetch"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
588 // Sometimes the line between taint sources and propagators is blurry.
589 // _IO_getc is choosen to be a source, but could also be a propagator.
590 // This way it is simpler, as modeling it as a propagator would require
591 // to model the possible sources of _IO_FILE * values, which the _IO_getc
592 // function takes as parameters.
593 {{CDM::CLibrary, {"_IO_getc"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
594 {{CDM::CLibrary, {"getcwd"}}, TR::Source(SourceArgs: {{0, ReturnValueIndex}})},
595 {{CDM::CLibrary, {"getwd"}}, TR::Source(SourceArgs: {{0, ReturnValueIndex}})},
596 {{CDM::CLibrary, {"readlink"}}, TR::Source(SourceArgs: {{1, ReturnValueIndex}})},
597 {{CDM::CLibrary, {"readlinkat"}}, TR::Source(SourceArgs: {{2, ReturnValueIndex}})},
598 {{CDM::CLibrary, {"get_current_dir_name"}},
599 TR::Source(SourceArgs: {{ReturnValueIndex}})},
600 {{CDM::CLibrary, {"gethostname"}}, TR::Source(SourceArgs: {{0}})},
601 {{CDM::CLibrary, {"getnameinfo"}}, TR::Source(SourceArgs: {{2, 4}})},
602 {{CDM::CLibrary, {"getseuserbyname"}}, TR::Source(SourceArgs: {{1, 2}})},
603 {{CDM::CLibrary, {"getgroups"}}, TR::Source(SourceArgs: {{1, ReturnValueIndex}})},
604 {{CDM::CLibrary, {"getlogin"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})},
605 {{CDM::CLibrary, {"getlogin_r"}}, TR::Source(SourceArgs: {{0}})},
606
607 // Props
608 {{CDM::CLibrary, {"accept"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
609 {{CDM::CLibrary, {"atoi"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
610 {{CDM::CLibrary, {"atol"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
611 {{CDM::CLibrary, {"atoll"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
612 {{CDM::CLibrary, {"fgetc"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
613 {{CDM::CLibrary, {"fgetln"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
614 {{CDM::CLibraryMaybeHardened, {"fgets"}},
615 TR::Prop(SrcArgs: {{2}}, DstArgs: {{0, ReturnValueIndex}})},
616 {{CDM::CLibraryMaybeHardened, {"fgetws"}},
617 TR::Prop(SrcArgs: {{2}}, DstArgs: {{0, ReturnValueIndex}})},
618 {{CDM::CLibrary, {"fscanf"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{}, 2})},
619 {{CDM::CLibrary, {"fscanf_s"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{}, 2})},
620 {{CDM::CLibrary, {"sscanf"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{}, 2})},
621 {{CDM::CLibrary, {"sscanf_s"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{}, 2})},
622
623 {{CDM::CLibrary, {"getc"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
624 {{CDM::CLibrary, {"getc_unlocked"}},
625 TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
626 {{CDM::CLibrary, {"getdelim"}}, TR::Prop(SrcArgs: {{3}}, DstArgs: {{0}})},
627 // TODO: this intends to match the C function `getline()`, but the call
628 // description also matches the C++ function `std::getline()`; it should
629 // be ruled out by some additional logic.
630 {{CDM::CLibrary, {"getline"}}, TR::Prop(SrcArgs: {{2}}, DstArgs: {{0}})},
631 {{CDM::CLibrary, {"getw"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
632 {{CDM::CLibraryMaybeHardened, {"pread"}},
633 TR::Prop(SrcArgs: {{0, 1, 2, 3}}, DstArgs: {{1, ReturnValueIndex}})},
634 {{CDM::CLibraryMaybeHardened, {"read"}},
635 TR::Prop(SrcArgs: {{0, 2}}, DstArgs: {{1, ReturnValueIndex}})},
636 {{CDM::CLibraryMaybeHardened, {"fread"}},
637 TR::Prop(SrcArgs: {{3}}, DstArgs: {{0, ReturnValueIndex}})},
638 {{CDM::CLibraryMaybeHardened, {"recv"}},
639 TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
640 {{CDM::CLibraryMaybeHardened, {"recvfrom"}},
641 TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
642
643 {{CDM::CLibrary, {"ttyname"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
644 {{CDM::CLibrary, {"ttyname_r"}},
645 TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
646
647 {{CDM::CLibrary, {"basename"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
648 {{CDM::CLibrary, {"dirname"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
649 {{CDM::CLibrary, {"fnmatch"}}, TR::Prop(SrcArgs: {{1}}, DstArgs: {{ReturnValueIndex}})},
650
651 {{CDM::CLibrary, {"mbtowc"}}, TR::Prop(SrcArgs: {{1}}, DstArgs: {{0, ReturnValueIndex}})},
652 {{CDM::CLibrary, {"wctomb"}}, TR::Prop(SrcArgs: {{1}}, DstArgs: {{0, ReturnValueIndex}})},
653 {{CDM::CLibrary, {"wcwidth"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
654
655 {{CDM::CLibrary, {"memcmp"}},
656 TR::Prop(SrcArgs: {{0, 1, 2}}, DstArgs: {{ReturnValueIndex}})},
657 {{CDM::CLibraryMaybeHardened, {"memcpy"}},
658 TR::Prop(SrcArgs: {{1, 2}}, DstArgs: {{0, ReturnValueIndex}})},
659 {{CDM::CLibraryMaybeHardened, {"memmove"}},
660 TR::Prop(SrcArgs: {{1, 2}}, DstArgs: {{0, ReturnValueIndex}})},
661 {{CDM::CLibraryMaybeHardened, {"bcopy"}}, TR::Prop(SrcArgs: {{0, 2}}, DstArgs: {{1}})},
662
663 // Note: "memmem" and its variants search for a byte sequence ("needle")
664 // in a larger area ("haystack"). Currently we only propagate taint from
665 // the haystack to the result, but in theory tampering with the needle
666 // could also produce incorrect results.
667 {{CDM::CLibrary, {"memmem"}}, TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
668 {{CDM::CLibrary, {"strstr"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
669 {{CDM::CLibrary, {"strcasestr"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
670
671 // Analogously, the following functions search for a byte within a buffer
672 // and we only propagate taint from the buffer to the result.
673 {{CDM::CLibraryMaybeHardened, {"memchr"}},
674 TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
675 {{CDM::CLibraryMaybeHardened, {"memrchr"}},
676 TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
677 {{CDM::CLibrary, {"rawmemchr"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
678 {{CDM::CLibraryMaybeHardened, {"strchr"}},
679 TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
680 {{CDM::CLibraryMaybeHardened, {"strrchr"}},
681 TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
682 {{CDM::CLibraryMaybeHardened, {"strchrnul"}},
683 TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
684 {{CDM::CLibrary, {"index"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
685 {{CDM::CLibrary, {"rindex"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
686
687 // FIXME: In case of arrays, only the first element of the array gets
688 // tainted.
689 {{CDM::CLibrary, {"qsort"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{0}})},
690 {{CDM::CLibrary, {"qsort_r"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{0}})},
691
692 {{CDM::CLibrary, {"strcmp"}}, TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
693 {{CDM::CLibrary, {"strcasecmp"}},
694 TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
695 {{CDM::CLibrary, {"strncmp"}},
696 TR::Prop(SrcArgs: {{0, 1, 2}}, DstArgs: {{ReturnValueIndex}})},
697 {{CDM::CLibrary, {"strncasecmp"}},
698 TR::Prop(SrcArgs: {{0, 1, 2}}, DstArgs: {{ReturnValueIndex}})},
699 {{CDM::CLibrary, {"strspn"}}, TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
700 {{CDM::CLibrary, {"strcspn"}}, TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
701 {{CDM::CLibrary, {"strpbrk"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
702
703 {{CDM::CLibrary, {"strndup"}}, TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
704 {{CDM::CLibrary, {"strndupa"}}, TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{ReturnValueIndex}})},
705 {{CDM::CLibrary, {"strdup"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
706 {{CDM::CLibrary, {"strdupa"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
707 {{CDM::CLibrary, {"wcsdup"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
708
709 // strlen, wcslen, strnlen and alike intentionally don't propagate taint.
710 // See the details here: https://github.com/llvm/llvm-project/pull/66086
711
712 {{CDM::CLibrary, {"strtol"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
713 {{CDM::CLibrary, {"strtoll"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
714 {{CDM::CLibrary, {"strtoul"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
715 {{CDM::CLibrary, {"strtoull"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{1, ReturnValueIndex}})},
716
717 {{CDM::CLibrary, {"tolower"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
718 {{CDM::CLibrary, {"toupper"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
719
720 {{CDM::CLibrary, {"isalnum"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
721 {{CDM::CLibrary, {"isalpha"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
722 {{CDM::CLibrary, {"isascii"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
723 {{CDM::CLibrary, {"isblank"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
724 {{CDM::CLibrary, {"iscntrl"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
725 {{CDM::CLibrary, {"isdigit"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
726 {{CDM::CLibrary, {"isgraph"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
727 {{CDM::CLibrary, {"islower"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
728 {{CDM::CLibrary, {"isprint"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
729 {{CDM::CLibrary, {"ispunct"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
730 {{CDM::CLibrary, {"isspace"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
731 {{CDM::CLibrary, {"isupper"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
732 {{CDM::CLibrary, {"isxdigit"}}, TR::Prop(SrcArgs: {{0}}, DstArgs: {{ReturnValueIndex}})},
733
734 {{CDM::CLibraryMaybeHardened, {"strcpy"}},
735 TR::Prop(SrcArgs: {{1}}, DstArgs: {{0, ReturnValueIndex}})},
736 {{CDM::CLibraryMaybeHardened, {"stpcpy"}},
737 TR::Prop(SrcArgs: {{1}}, DstArgs: {{0, ReturnValueIndex}})},
738 {{CDM::CLibraryMaybeHardened, {"strcat"}},
739 TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{0, ReturnValueIndex}})},
740 {{CDM::CLibraryMaybeHardened, {"wcsncat"}},
741 TR::Prop(SrcArgs: {{0, 1}}, DstArgs: {{0, ReturnValueIndex}})},
742 {{CDM::CLibraryMaybeHardened, {"strncpy"}},
743 TR::Prop(SrcArgs: {{1, 2}}, DstArgs: {{0, ReturnValueIndex}})},
744 {{CDM::CLibraryMaybeHardened, {"strncat"}},
745 TR::Prop(SrcArgs: {{0, 1, 2}}, DstArgs: {{0, ReturnValueIndex}})},
746 {{CDM::CLibraryMaybeHardened, {"strlcpy"}}, TR::Prop(SrcArgs: {{1, 2}}, DstArgs: {{0}})},
747 {{CDM::CLibraryMaybeHardened, {"strlcat"}}, TR::Prop(SrcArgs: {{0, 1, 2}}, DstArgs: {{0}})},
748
749 // Usually the matching mode `CDM::CLibraryMaybeHardened` is sufficient
750 // for unified handling of a function `FOO()` and its hardened variant
751 // `__FOO_chk()`, but in the "sprintf" family the extra parameters of the
752 // hardened variants are inserted into the middle of the parameter list,
753 // so that would not work in their case.
754 // int snprintf(char * str, size_t maxlen, const char * format, ...);
755 {{CDM::CLibrary, {"snprintf"}},
756 TR::Prop(SrcArgs: {{1, 2}, 3}, DstArgs: {{0, ReturnValueIndex}})},
757 // int sprintf(char * str, const char * format, ...);
758 {{CDM::CLibrary, {"sprintf"}},
759 TR::Prop(SrcArgs: {{1}, 2}, DstArgs: {{0, ReturnValueIndex}})},
760 // int __snprintf_chk(char * str, size_t maxlen, int flag, size_t strlen,
761 // const char * format, ...);
762 {{CDM::CLibrary, {"__snprintf_chk"}},
763 TR::Prop(SrcArgs: {{1, 4}, 5}, DstArgs: {{0, ReturnValueIndex}})},
764 // int __sprintf_chk(char * str, int flag, size_t strlen, const char *
765 // format, ...);
766 {{CDM::CLibrary, {"__sprintf_chk"}},
767 TR::Prop(SrcArgs: {{3}, 4}, DstArgs: {{0, ReturnValueIndex}})},
768
769 // Sinks
770 {{CDM::CLibrary, {"system"}}, TR::Sink(SinkArgs: {{0}}, Msg: MsgSanitizeSystemArgs)},
771 {{CDM::CLibrary, {"popen"}}, TR::Sink(SinkArgs: {{0}}, Msg: MsgSanitizeSystemArgs)},
772 {{CDM::CLibrary, {"execl"}}, TR::Sink(SinkArgs: {{}, {0}}, Msg: MsgSanitizeSystemArgs)},
773 {{CDM::CLibrary, {"execle"}}, TR::Sink(SinkArgs: {{}, {0}}, Msg: MsgSanitizeSystemArgs)},
774 {{CDM::CLibrary, {"execlp"}}, TR::Sink(SinkArgs: {{}, {0}}, Msg: MsgSanitizeSystemArgs)},
775 {{CDM::CLibrary, {"execv"}}, TR::Sink(SinkArgs: {{0, 1}}, Msg: MsgSanitizeSystemArgs)},
776 {{CDM::CLibrary, {"execve"}},
777 TR::Sink(SinkArgs: {{0, 1, 2}}, Msg: MsgSanitizeSystemArgs)},
778 {{CDM::CLibrary, {"fexecve"}},
779 TR::Sink(SinkArgs: {{0, 1, 2}}, Msg: MsgSanitizeSystemArgs)},
780 {{CDM::CLibrary, {"execvp"}}, TR::Sink(SinkArgs: {{0, 1}}, Msg: MsgSanitizeSystemArgs)},
781 {{CDM::CLibrary, {"execvpe"}},
782 TR::Sink(SinkArgs: {{0, 1, 2}}, Msg: MsgSanitizeSystemArgs)},
783 {{CDM::CLibrary, {"dlopen"}}, TR::Sink(SinkArgs: {{0}}, Msg: MsgSanitizeSystemArgs)},
784
785 // malloc, calloc, alloca, realloc, memccpy
786 // are intentionally not marked as taint sinks because unconditional
787 // reporting for these functions generates many false positives.
788 // These taint sinks should be implemented in other checkers with more
789 // sophisticated sanitation heuristics.
790
791 {{CDM::CLibrary, {"setproctitle"}},
792 TR::Sink(SinkArgs: {{0}, 1}, Msg: MsgUncontrolledFormatString)},
793 {{CDM::CLibrary, {"setproctitle_fast"}},
794 TR::Sink(SinkArgs: {{0}, 1}, Msg: MsgUncontrolledFormatString)}};
795
796 if (TR::UntrustedEnv(C)) {
797 // void setproctitle_init(int argc, char *argv[], char *envp[])
798 // TODO: replace `MsgCustomSink` with a message that fits this situation.
799 GlobalCRules.push_back(x: {{CDM::CLibrary, {"setproctitle_init"}},
800 TR::Sink(SinkArgs: {{1, 2}}, Msg: MsgCustomSink)});
801
802 // `getenv` returns taint only in untrusted environments.
803 GlobalCRules.push_back(
804 x: {{CDM::CLibrary, {"getenv"}}, TR::Source(SourceArgs: {{ReturnValueIndex}})});
805 }
806 CheckerManager *Mgr = C.getAnalysisManager().getCheckerManager();
807
808 StaticTaintRules = RuleLookupTy{};
809 if (Mgr->getAnalyzerOptions().getCheckerBooleanOption(C: this,
810 OptionName: "EnableDefaultConfig"))
811 StaticTaintRules.emplace(args: std::make_move_iterator(i: GlobalCRules.begin()),
812 args: std::make_move_iterator(i: GlobalCRules.end()));
813
814 // User-provided taint configuration.
815 const GenericTaintRuleParser ConfigParser{*Mgr};
816 std::string Option{"Config"};
817 StringRef ConfigFile =
818 Mgr->getAnalyzerOptions().getCheckerStringOption(C: this, OptionName: Option);
819 std::optional<TaintConfiguration> Config =
820 getConfiguration<TaintConfiguration>(Mgr&: *Mgr, Chk: this, Option, ConfigFile);
821 if (!Config) {
822 // We don't have external taint config, no parsing required.
823 DynamicTaintRules = RuleLookupTy{};
824 return;
825 }
826
827 GenericTaintRuleParser::RulesContTy Rules{
828 ConfigParser.parseConfiguration(Option, Config: std::move(*Config))};
829
830 DynamicTaintRules.emplace(args: std::make_move_iterator(i: Rules.begin()),
831 args: std::make_move_iterator(i: Rules.end()));
832}
833
834bool isPointerToCharArray(const QualType &QT) {
835 if (!QT->isPointerType())
836 return false;
837 QualType PointeeType = QT->getPointeeType();
838 return PointeeType->isPointerType() &&
839 PointeeType->getPointeeType()->isCharType();
840}
841
842// The incoming parameters of the main function get tainted
843// if the program called in an untrusted environment.
844void GenericTaintChecker::checkBeginFunction(CheckerContext &C) const {
845 if (!C.inTopFrame() || C.getAnalysisManager()
846 .getAnalyzerOptions()
847 .ShouldAssumeControlledEnvironment)
848 return;
849
850 const auto *FD = dyn_cast<FunctionDecl>(Val: C.getLocationContext()->getDecl());
851 if (!FD || !FD->isMain() || FD->param_size() < 2)
852 return;
853
854 if (!FD->parameters()[0]->getType()->isIntegerType())
855 return;
856
857 if (!isPointerToCharArray(QT: FD->parameters()[1]->getType()))
858 return;
859 ProgramStateRef State = C.getState();
860
861 const MemRegion *ArgcReg =
862 State->getRegion(D: FD->parameters()[0], LC: C.getLocationContext());
863 SVal ArgcSVal = State->getSVal(R: ArgcReg);
864 State = addTaint(State, V: ArgcSVal);
865 StringRef ArgcName = FD->parameters()[0]->getName();
866 if (auto N = ArgcSVal.getAs<NonLoc>()) {
867 ConstraintManager &CM = C.getConstraintManager();
868 // The upper bound is the ARG_MAX on an arbitrary Linux
869 // to model that is is typically smaller than INT_MAX.
870 State = CM.assumeInclusiveRange(State, Value: *N, From: llvm::APSInt::getUnsigned(X: 1),
871 To: llvm::APSInt::getUnsigned(X: 2097152), InBound: true);
872 }
873
874 const MemRegion *ArgvReg =
875 State->getRegion(D: FD->parameters()[1], LC: C.getLocationContext());
876 SVal ArgvSVal = State->getSVal(R: ArgvReg);
877 State = addTaint(State, V: ArgvSVal);
878 StringRef ArgvName = FD->parameters()[1]->getName();
879
880 bool HaveEnvp = FD->param_size() > 2;
881 SVal EnvpSVal;
882 StringRef EnvpName;
883 if (HaveEnvp && !isPointerToCharArray(QT: FD->parameters()[2]->getType()))
884 return;
885 if (HaveEnvp) {
886 const MemRegion *EnvPReg =
887 State->getRegion(D: FD->parameters()[2], LC: C.getLocationContext());
888 EnvpSVal = State->getSVal(R: EnvPReg);
889 EnvpName = FD->parameters()[2]->getName();
890 State = addTaint(State, V: EnvpSVal);
891 }
892
893 const NoteTag *OriginatingTag =
894 C.getNoteTag(Cb: [ArgvSVal, ArgcSVal, ArgcName, ArgvName, EnvpSVal,
895 EnvpName](PathSensitiveBugReport &BR) -> std::string {
896 if ((!BR.isInteresting(V: ArgcSVal) && !BR.isInteresting(V: ArgvSVal) &&
897 !BR.isInteresting(V: EnvpSVal)))
898 return "";
899 if (BR.getBugType().getCategory() != categories::TaintedData)
900 return "";
901 std::string Message = "";
902 if (BR.isInteresting(V: ArgvSVal))
903 Message += "'" + ArgvName.str() + "'";
904 if (BR.isInteresting(V: ArgcSVal)) {
905 if (Message.size() > 0)
906 Message += ", ";
907 Message += "'" + ArgcName.str() + "'";
908 }
909 if (BR.isInteresting(V: EnvpSVal)) {
910 if (Message.size() > 0)
911 Message += ", ";
912 Message += "'" + EnvpName.str() + "'";
913 }
914 return "Taint originated in " + Message;
915 });
916 C.addTransition(State, Tag: OriginatingTag);
917}
918
919void GenericTaintChecker::checkPreCall(const CallEvent &Call,
920 CheckerContext &C) const {
921
922 initTaintRules(C);
923
924 // FIXME: this should be much simpler.
925 if (const auto *Rule =
926 Call.isGlobalCFunction() ? StaticTaintRules->lookup(Call) : nullptr)
927 Rule->process(Checker: *this, Call, C);
928 else if (const auto *Rule = DynamicTaintRules->lookup(Call))
929 Rule->process(Checker: *this, Call, C);
930
931 // FIXME: These edge cases are to be eliminated from here eventually.
932 //
933 // Additional check that is not supported by CallDescription.
934 // TODO: Make CallDescription be able to match attributes such as printf-like
935 // arguments.
936 checkUncontrolledFormatString(Call, C);
937
938 // TODO: Modeling sockets should be done in a specific checker.
939 // Socket is a source, which taints the return value.
940 taintUnsafeSocketProtocol(Call, C);
941}
942
943void GenericTaintChecker::checkPostCall(const CallEvent &Call,
944 CheckerContext &C) const {
945 // Set the marked values as tainted. The return value only accessible from
946 // checkPostStmt.
947 ProgramStateRef State = C.getState();
948 const StackFrameContext *CurrentFrame = C.getStackFrame();
949
950 // Depending on what was tainted at pre-visit, we determined a set of
951 // arguments which should be tainted after the function returns. These are
952 // stored in the state as TaintArgsOnPostVisit set.
953 TaintArgsOnPostVisitTy TaintArgsMap = State->get<TaintArgsOnPostVisit>();
954
955 const ImmutableSet<ArgIdxTy> *TaintArgs = TaintArgsMap.lookup(K: CurrentFrame);
956 if (!TaintArgs)
957 return;
958 assert(!TaintArgs->isEmpty());
959
960 LLVM_DEBUG(for (ArgIdxTy I
961 : *TaintArgs) {
962 llvm::dbgs() << "PostCall<";
963 Call.dump(llvm::dbgs());
964 llvm::dbgs() << "> actually wants to taint arg index: " << I << '\n';
965 });
966
967 const NoteTag *InjectionTag = nullptr;
968 std::vector<SymbolRef> TaintedSymbols;
969 std::vector<ArgIdxTy> TaintedIndexes;
970 for (ArgIdxTy ArgNum : *TaintArgs) {
971 // Special handling for the tainted return value.
972 if (ArgNum == ReturnValueIndex) {
973 State = addTaint(State, V: Call.getReturnValue());
974 std::vector<SymbolRef> TaintedSyms =
975 getTaintedSymbols(State, V: Call.getReturnValue());
976 if (!TaintedSyms.empty()) {
977 TaintedSymbols.push_back(x: TaintedSyms[0]);
978 TaintedIndexes.push_back(x: ArgNum);
979 }
980 continue;
981 }
982 // The arguments are pointer arguments. The data they are pointing at is
983 // tainted after the call.
984 if (auto V = getPointeeOf(State, Arg: Call.getArgSVal(Index: ArgNum))) {
985 State = addTaint(State, V: *V);
986 std::vector<SymbolRef> TaintedSyms = getTaintedSymbols(State, V: *V);
987 if (!TaintedSyms.empty()) {
988 TaintedSymbols.push_back(x: TaintedSyms[0]);
989 TaintedIndexes.push_back(x: ArgNum);
990 }
991 }
992 }
993 // Create a NoteTag callback, which prints to the user where the taintedness
994 // was propagated to.
995 InjectionTag = taintPropagationExplainerTag(C, TaintedSymbols, TaintedArgs: TaintedIndexes,
996 CallLocation: Call.getCalleeStackFrame(BlockCount: 0));
997 // Clear up the taint info from the state.
998 State = State->remove<TaintArgsOnPostVisit>(K: CurrentFrame);
999 C.addTransition(State, Tag: InjectionTag);
1000}
1001
1002void GenericTaintChecker::printState(raw_ostream &Out, ProgramStateRef State,
1003 const char *NL, const char *Sep) const {
1004 printTaint(State, Out, nl: NL, sep: Sep);
1005}
1006
1007void GenericTaintRule::process(const GenericTaintChecker &Checker,
1008 const CallEvent &Call, CheckerContext &C) const {
1009 ProgramStateRef State = C.getState();
1010 const ArgIdxTy CallNumArgs = fromArgumentCount(Count: Call.getNumArgs());
1011
1012 /// Iterate every call argument, and get their corresponding Expr and SVal.
1013 const auto ForEachCallArg = [&C, &Call, CallNumArgs](auto &&Fun) {
1014 for (ArgIdxTy I = ReturnValueIndex; I < CallNumArgs; ++I) {
1015 const Expr *E = GetArgExpr(ArgIdx: I, Call);
1016 Fun(I, E, C.getSVal(S: E));
1017 }
1018 };
1019
1020 /// Check for taint sinks.
1021 ForEachCallArg([this, &Checker, &C, &State](ArgIdxTy I, const Expr *E, SVal) {
1022 // Add taintedness to stdin parameters
1023 if (isStdin(Val: C.getSVal(S: E), ACtx: C.getASTContext())) {
1024 State = addTaint(State, V: C.getSVal(S: E));
1025 }
1026 if (SinkArgs.contains(ArgIdx: I) && isTaintedOrPointsToTainted(State, ExprSVal: C.getSVal(S: E)))
1027 Checker.generateReportIfTainted(E, Msg: SinkMsg.value_or(u: MsgCustomSink), C);
1028 });
1029
1030 /// Check for taint filters.
1031 ForEachCallArg([this, &State](ArgIdxTy I, const Expr *E, SVal S) {
1032 if (FilterArgs.contains(ArgIdx: I)) {
1033 State = removeTaint(State, V: S);
1034 if (auto P = getPointeeOf(State, Arg: S))
1035 State = removeTaint(State, V: *P);
1036 }
1037 });
1038
1039 /// Check for taint propagation sources.
1040 /// A rule will make the destination variables tainted if PropSrcArgs
1041 /// is empty (taints the destination
1042 /// arguments unconditionally), or if any of its signified
1043 /// args are tainted in context of the current CallEvent.
1044 bool IsMatching = PropSrcArgs.isEmpty();
1045 std::vector<SymbolRef> TaintedSymbols;
1046 std::vector<ArgIdxTy> TaintedIndexes;
1047 ForEachCallArg([this, &C, &IsMatching, &State, &TaintedSymbols,
1048 &TaintedIndexes](ArgIdxTy I, const Expr *E, SVal) {
1049 std::optional<SVal> TaintedSVal =
1050 getTaintedPointeeOrPointer(State, Arg: C.getSVal(S: E));
1051 IsMatching =
1052 IsMatching || (PropSrcArgs.contains(ArgIdx: I) && TaintedSVal.has_value());
1053
1054 // We track back tainted arguments except for stdin
1055 if (TaintedSVal && !isStdin(Val: *TaintedSVal, ACtx: C.getASTContext())) {
1056 std::vector<SymbolRef> TaintedArgSyms =
1057 getTaintedSymbols(State, V: *TaintedSVal);
1058 if (!TaintedArgSyms.empty()) {
1059 llvm::append_range(C&: TaintedSymbols, R&: TaintedArgSyms);
1060 TaintedIndexes.push_back(x: I);
1061 }
1062 }
1063 });
1064
1065 // Early return for propagation rules which dont match.
1066 // Matching propagations, Sinks and Filters will pass this point.
1067 if (!IsMatching)
1068 return;
1069
1070 const auto WouldEscape = [](SVal V, QualType Ty) -> bool {
1071 if (!isa<Loc>(Val: V))
1072 return false;
1073
1074 const bool IsNonConstRef = Ty->isReferenceType() && !Ty.isConstQualified();
1075 const bool IsNonConstPtr =
1076 Ty->isPointerType() && !Ty->getPointeeType().isConstQualified();
1077
1078 return IsNonConstRef || IsNonConstPtr;
1079 };
1080
1081 /// Propagate taint where it is necessary.
1082 auto &F = State->getStateManager().get_context<ArgIdxFactory>();
1083 ImmutableSet<ArgIdxTy> Result = F.getEmptySet();
1084 ForEachCallArg(
1085 [&](ArgIdxTy I, const Expr *E, SVal V) {
1086 if (PropDstArgs.contains(ArgIdx: I)) {
1087 LLVM_DEBUG(llvm::dbgs() << "PreCall<"; Call.dump(llvm::dbgs());
1088 llvm::dbgs()
1089 << "> prepares tainting arg index: " << I << '\n';);
1090 Result = F.add(Old: Result, V: I);
1091 }
1092
1093 // Taint property gets lost if the variable is passed as a
1094 // non-const pointer or reference to a function which is
1095 // not inlined. For matching rules we want to preserve the taintedness.
1096 // TODO: We should traverse all reachable memory regions via the
1097 // escaping parameter. Instead of doing that we simply mark only the
1098 // referred memory region as tainted.
1099 if (WouldEscape(V, E->getType()) && getTaintedPointeeOrPointer(State, Arg: V)) {
1100 LLVM_DEBUG(if (!Result.contains(I)) {
1101 llvm::dbgs() << "PreCall<";
1102 Call.dump(llvm::dbgs());
1103 llvm::dbgs() << "> prepares tainting arg index: " << I << '\n';
1104 });
1105 Result = F.add(Old: Result, V: I);
1106 }
1107 });
1108
1109 if (!Result.isEmpty())
1110 State = State->set<TaintArgsOnPostVisit>(K: C.getStackFrame(), E: Result);
1111 const NoteTag *InjectionTag = taintOriginTrackerTag(
1112 C, TaintedSymbols: std::move(TaintedSymbols), TaintedArgs: std::move(TaintedIndexes),
1113 CallLocation: Call.getCalleeStackFrame(BlockCount: 0));
1114 C.addTransition(State, Tag: InjectionTag);
1115}
1116
1117bool GenericTaintRule::UntrustedEnv(CheckerContext &C) {
1118 return !C.getAnalysisManager()
1119 .getAnalyzerOptions()
1120 .ShouldAssumeControlledEnvironment;
1121}
1122
1123bool GenericTaintChecker::generateReportIfTainted(const Expr *E, StringRef Msg,
1124 CheckerContext &C) const {
1125 assert(E);
1126 if (!isTaintReporterCheckerEnabled)
1127 return false;
1128 std::optional<SVal> TaintedSVal =
1129 getTaintedPointeeOrPointer(State: C.getState(), Arg: C.getSVal(S: E));
1130
1131 if (!TaintedSVal)
1132 return false;
1133
1134 // Generate diagnostic.
1135 assert(BT);
1136 if (ExplodedNode *N = C.generateNonFatalErrorNode(State: C.getState())) {
1137 auto report = std::make_unique<PathSensitiveBugReport>(args: *BT, args&: Msg, args&: N);
1138 report->addRange(R: E->getSourceRange());
1139 for (auto TaintedSym : getTaintedSymbols(State: C.getState(), V: *TaintedSVal)) {
1140 report->markInteresting(sym: TaintedSym);
1141 }
1142 C.emitReport(R: std::move(report));
1143 return true;
1144 }
1145 return false;
1146}
1147
1148/// TODO: remove checking for printf format attributes and socket whitelisting
1149/// from GenericTaintChecker, and that means the following functions:
1150/// getPrintfFormatArgumentNum,
1151/// GenericTaintChecker::checkUncontrolledFormatString,
1152/// GenericTaintChecker::taintUnsafeSocketProtocol
1153
1154static bool getPrintfFormatArgumentNum(const CallEvent &Call,
1155 const CheckerContext &C,
1156 ArgIdxTy &ArgNum) {
1157 // Find if the function contains a format string argument.
1158 // Handles: fprintf, printf, sprintf, snprintf, vfprintf, vprintf, vsprintf,
1159 // vsnprintf, syslog, custom annotated functions.
1160 const Decl *CallDecl = Call.getDecl();
1161 if (!CallDecl)
1162 return false;
1163 const FunctionDecl *FDecl = CallDecl->getAsFunction();
1164 if (!FDecl)
1165 return false;
1166
1167 const ArgIdxTy CallNumArgs = fromArgumentCount(Count: Call.getNumArgs());
1168
1169 for (const auto *Format : FDecl->specific_attrs<FormatAttr>()) {
1170 // The format attribute uses 1-based parameter indexing, for example
1171 // plain `printf(const char *fmt, ...)` would be annotated with
1172 // `__format__(__printf__, 1, 2)`, so we need to subtract 1 to get a
1173 // 0-based index. (This checker uses 0-based parameter indices.)
1174 ArgNum = Format->getFormatIdx() - 1;
1175 // The format attribute also counts the implicit `this` parameter of
1176 // methods, so e.g. in `SomeClass::method(const char *fmt, ...)` could be
1177 // annotated with `__format__(__printf__, 2, 3)`. This checker doesn't
1178 // count the implicit `this` parameter, so in this case we need to subtract
1179 // one again.
1180 // FIXME: Apparently the implementation of the format attribute doesn't
1181 // support methods with an explicit object parameter, so we cannot
1182 // implement proper support for that rare case either.
1183 const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl);
1184 if (MDecl && !MDecl->isStatic())
1185 ArgNum--;
1186
1187 if ((Format->getType()->getName() == "printf") && CallNumArgs > ArgNum)
1188 return true;
1189 }
1190
1191 return false;
1192}
1193
1194bool GenericTaintChecker::checkUncontrolledFormatString(
1195 const CallEvent &Call, CheckerContext &C) const {
1196 // Check if the function contains a format string argument.
1197 ArgIdxTy ArgNum = 0;
1198 if (!getPrintfFormatArgumentNum(Call, C, ArgNum))
1199 return false;
1200
1201 // If either the format string content or the pointer itself are tainted,
1202 // warn.
1203 return generateReportIfTainted(E: Call.getArgExpr(Index: ArgNum),
1204 Msg: MsgUncontrolledFormatString, C);
1205}
1206
1207void GenericTaintChecker::taintUnsafeSocketProtocol(const CallEvent &Call,
1208 CheckerContext &C) const {
1209 if (Call.getNumArgs() < 1)
1210 return;
1211 const IdentifierInfo *ID = Call.getCalleeIdentifier();
1212 if (!ID)
1213 return;
1214 if (ID->getName() != "socket")
1215 return;
1216
1217 SourceLocation DomLoc = Call.getArgExpr(Index: 0)->getExprLoc();
1218 StringRef DomName = C.getMacroNameOrSpelling(Loc&: DomLoc);
1219 // Allow internal communication protocols.
1220 bool SafeProtocol = DomName == "AF_SYSTEM" || DomName == "AF_LOCAL" ||
1221 DomName == "AF_UNIX" || DomName == "AF_RESERVED_36";
1222 if (SafeProtocol)
1223 return;
1224
1225 ProgramStateRef State = C.getState();
1226 auto &F = State->getStateManager().get_context<ArgIdxFactory>();
1227 ImmutableSet<ArgIdxTy> Result = F.add(Old: F.getEmptySet(), V: ReturnValueIndex);
1228 State = State->set<TaintArgsOnPostVisit>(K: C.getStackFrame(), E: Result);
1229 C.addTransition(State);
1230}
1231
1232/// Checker registration
1233void ento::registerTaintPropagationChecker(CheckerManager &Mgr) {
1234 Mgr.registerChecker<GenericTaintChecker>();
1235}
1236
1237bool ento::shouldRegisterTaintPropagationChecker(const CheckerManager &mgr) {
1238 return true;
1239}
1240
1241void ento::registerGenericTaintChecker(CheckerManager &Mgr) {
1242 GenericTaintChecker *checker = Mgr.getChecker<GenericTaintChecker>();
1243 checker->isTaintReporterCheckerEnabled = true;
1244 checker->BT.emplace(args: Mgr.getCurrentCheckerName(), args: "Use of Untrusted Data",
1245 args: categories::TaintedData);
1246}
1247
1248bool ento::shouldRegisterGenericTaintChecker(const CheckerManager &mgr) {
1249 return true;
1250}
1251