#include "Yaml.h"
#include "clang/AST/Attr.h"
#include "clang/Basic/Builtins.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Checkers/Taint.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/YAMLTraits.h"
#include <limits>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#define DEBUG_TYPE "taint-checker"
using namespace clang;
using namespace ento;
using namespace taint;
using llvm::ImmutableSet;
namespace {
class GenericTaintChecker;
constexpr llvm::StringLiteral MsgUncontrolledFormatString =
"Untrusted data is used as a format string "
"(CWE-134: Uncontrolled Format String)";
constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
"Untrusted data is passed to a system call "
"(CERT/STR02-C. Sanitize data passed to complex subsystems)";
constexpr llvm::StringLiteral MsgCustomSink =
"Untrusted data is passed to a user-defined sink";
using ArgIdxTy = int;
using ArgVecTy = llvm::SmallVector<ArgIdxTy, 2>;
constexpr ArgIdxTy ReturnValueIndex{-1};
static ArgIdxTy fromArgumentCount(unsigned Count) {
assert(Count <=
static_cast<std::size_t>(std::numeric_limits<ArgIdxTy>::max()) &&
"ArgIdxTy is not large enough to represent the number of arguments.");
return Count;
}
bool isStdin(SVal Val, const ASTContext &ACtx) {
const auto *SymReg = dyn_cast_or_null<SymbolicRegion>(Val.getAsRegion());
if (!SymReg)
return false;
const auto *DeclReg =
dyn_cast_or_null<DeclRegion>(SymReg->getSymbol()->getOriginRegion());
if (!DeclReg)
return false;
if (const auto *D = dyn_cast_or_null<VarDecl>(DeclReg->getDecl())) {
D = D->getCanonicalDecl();
if (D->getName() == "stdin" && D->hasExternalStorage() && D->isExternC()) {
const QualType FILETy = ACtx.getFILEType().getCanonicalType();
const QualType Ty = D->getType().getCanonicalType();
if (Ty->isPointerType())
return Ty->getPointeeType() == FILETy;
}
}
return false;
}
SVal getPointeeOf(ProgramStateRef State, Loc LValue) {
const QualType ArgTy = LValue.getType(State->getStateManager().getContext());
if (!ArgTy->isPointerType() || !ArgTy->getPointeeType()->isVoidType())
return State->getSVal(LValue);
return State->getSVal(LValue, State->getStateManager().getContext().CharTy);
}
std::optional<SVal> getPointeeOf(ProgramStateRef State, SVal Arg) {
if (auto LValue = Arg.getAs<Loc>())
return getPointeeOf(State, *LValue);
return std::nullopt;
}
std::optional<SVal> getTaintedPointeeOrPointer(ProgramStateRef State,
SVal Arg) {
if (auto Pointee = getPointeeOf(State, Arg))
if (isTainted(State, *Pointee))
return Pointee;
if (isTainted(State, Arg))
return Arg;
return std::nullopt;
}
bool isTaintedOrPointsToTainted(ProgramStateRef State, SVal ExprSVal) {
return getTaintedPointeeOrPointer(State, ExprSVal).has_value();
}
const NoteTag *taintOriginTrackerTag(CheckerContext &C,
std::vector<SymbolRef> TaintedSymbols,
std::vector<ArgIdxTy> TaintedArgs,
const LocationContext *CallLocation) {
return C.getNoteTag([TaintedSymbols = std::move(TaintedSymbols),
TaintedArgs = std::move(TaintedArgs), CallLocation](
PathSensitiveBugReport &BR) -> std::string {
SmallString<256> Msg;
if (!BR.isInteresting(CallLocation) ||
BR.getBugType().getCategory() != categories::TaintedData) {
return "";
}
if (TaintedSymbols.empty())
return "Taint originated here";
for (auto Sym : TaintedSymbols) {
BR.markInteresting(Sym);
}
LLVM_DEBUG(for (auto Arg
: TaintedArgs) {
llvm::dbgs() << "Taint Propagated from argument " << Arg + 1 << "\n";
});
return "";
});
}
const NoteTag *taintPropagationExplainerTag(
CheckerContext &C, std::vector<SymbolRef> TaintedSymbols,
std::vector<ArgIdxTy> TaintedArgs, const LocationContext *CallLocation) {
assert(TaintedSymbols.size() == TaintedArgs.size());
return C.getNoteTag([TaintedSymbols = std::move(TaintedSymbols),
TaintedArgs = std::move(TaintedArgs), CallLocation](
PathSensitiveBugReport &BR) -> std::string {
SmallString<256> Msg;
llvm::raw_svector_ostream Out(Msg);
if (TaintedSymbols.empty() ||
BR.getBugType().getCategory() != categories::TaintedData) {
return "";
}
int nofTaintedArgs = 0;
for (auto [Idx, Sym] : llvm::enumerate(TaintedSymbols)) {
if (BR.isInteresting(Sym)) {
BR.markInteresting(CallLocation);
if (TaintedArgs[Idx] != ReturnValueIndex) {
LLVM_DEBUG(llvm::dbgs() << "Taint Propagated to argument "
<< TaintedArgs[Idx] + 1 << "\n");
if (nofTaintedArgs == 0)
Out << "Taint propagated to the ";
else
Out << ", ";
Out << TaintedArgs[Idx] + 1
<< llvm::getOrdinalSuffix(TaintedArgs[Idx] + 1) << " argument";
nofTaintedArgs++;
} else {
LLVM_DEBUG(llvm::dbgs() << "Taint Propagated to return value.\n");
Out << "Taint propagated to the return value";
}
}
}
return std::string(Out.str());
});
}
class ArgSet {
public:
ArgSet() = default;
ArgSet(ArgVecTy &&DiscreteArgs,
std::optional<ArgIdxTy> VariadicIndex = std::nullopt)
: DiscreteArgs(std::move(DiscreteArgs)),
VariadicIndex(std::move(VariadicIndex)) {}
bool contains(ArgIdxTy ArgIdx) const {
if (llvm::is_contained(DiscreteArgs, ArgIdx))
return true;
return VariadicIndex && ArgIdx >= *VariadicIndex;
}
bool isEmpty() const { return DiscreteArgs.empty() && !VariadicIndex; }
private:
ArgVecTy DiscreteArgs;
std::optional<ArgIdxTy> VariadicIndex;
};
class GenericTaintRule {
ArgSet SinkArgs;
ArgSet FilterArgs;
ArgSet PropSrcArgs;
ArgSet PropDstArgs;
std::optional<StringRef> SinkMsg;
GenericTaintRule() = default;
GenericTaintRule(ArgSet &&Sink, ArgSet &&Filter, ArgSet &&Src, ArgSet &&Dst,
std::optional<StringRef> SinkMsg = std::nullopt)
: SinkArgs(std::move(Sink)), FilterArgs(std::move(Filter)),
PropSrcArgs(std::move(Src)), PropDstArgs(std::move(Dst)),
SinkMsg(SinkMsg) {}
public:
static GenericTaintRule Sink(ArgSet &&SinkArgs,
std::optional<StringRef> Msg = std::nullopt) {
return {std::move(SinkArgs), {}, {}, {}, Msg};
}
static GenericTaintRule Filter(ArgSet &&FilterArgs) {
return {{}, std::move(FilterArgs), {}, {}};
}
static GenericTaintRule Source(ArgSet &&SourceArgs) {
return {{}, {}, {}, std::move(SourceArgs)};
}
static GenericTaintRule Prop(ArgSet &&SrcArgs, ArgSet &&DstArgs) {
return {{}, {}, std::move(SrcArgs), std::move(DstArgs)};
}
void process(const GenericTaintChecker &Checker, const CallEvent &Call,
CheckerContext &C) const;
static const Expr *GetArgExpr(ArgIdxTy ArgIdx, const CallEvent &Call) {
return ArgIdx == ReturnValueIndex ? Call.getOriginExpr()
: Call.getArgExpr(ArgIdx);
};
static bool UntrustedEnv(CheckerContext &C);
};
using RuleLookupTy = CallDescriptionMap<GenericTaintRule>;
struct TaintConfiguration {
using NameScopeArgs = std::tuple<std::string, std::string, ArgVecTy>;
enum class VariadicType { None, Src, Dst };
struct Common {
std::string Name;
std::string Scope;
};
struct Sink : Common {
ArgVecTy SinkArgs;
};
struct Filter : Common {
ArgVecTy FilterArgs;
};
struct Propagation : Common {
ArgVecTy SrcArgs;
ArgVecTy DstArgs;
VariadicType VarType;
ArgIdxTy VarIndex;
};
std::vector<Propagation> Propagations;
std::vector<Filter> Filters;
std::vector<Sink> Sinks;
TaintConfiguration() = default;
TaintConfiguration(const TaintConfiguration &) = default;
TaintConfiguration(TaintConfiguration &&) = default;
TaintConfiguration &operator=(const TaintConfiguration &) = default;
TaintConfiguration &operator=(TaintConfiguration &&) = default;
};
struct GenericTaintRuleParser {
GenericTaintRuleParser(CheckerManager &Mgr) : Mgr(Mgr) {}
using RulesContTy = std::vector<std::pair<CallDescription, GenericTaintRule>>;
RulesContTy parseConfiguration(const std::string &Option,
TaintConfiguration &&Config) const;
private:
using NamePartsTy = llvm::SmallVector<StringRef, 2>;
void validateArgVector(const std::string &Option, const ArgVecTy &Args) const;
template <typename Config> static NamePartsTy parseNameParts(const Config &C);
template <typename Config>
static void consumeRulesFromConfig(const Config &C, GenericTaintRule &&Rule,
RulesContTy &Rules);
void parseConfig(const std::string &Option, TaintConfiguration::Sink &&P,
RulesContTy &Rules) const;
void parseConfig(const std::string &Option, TaintConfiguration::Filter &&P,
RulesContTy &Rules) const;
void parseConfig(const std::string &Option,
TaintConfiguration::Propagation &&P,
RulesContTy &Rules) const;
CheckerManager &Mgr;
};
class GenericTaintChecker : public Checker<check::PreCall, check::PostCall> {
public:
void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
const char *Sep) const override;
bool generateReportIfTainted(const Expr *E, StringRef Msg,
CheckerContext &C) const;
bool isTaintReporterCheckerEnabled = false;
std::optional<BugType> BT;
private:
bool checkUncontrolledFormatString(const CallEvent &Call,
CheckerContext &C) const;
void taintUnsafeSocketProtocol(const CallEvent &Call,
CheckerContext &C) const;
void initTaintRules(CheckerContext &C) const;
mutable std::optional<RuleLookupTy> StaticTaintRules;
mutable std::optional<RuleLookupTy> DynamicTaintRules;
};
}
LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Sink)
LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Filter)
LLVM_YAML_IS_SEQUENCE_VECTOR(TaintConfiguration::Propagation)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<TaintConfiguration> {
static void mapping(IO &IO, TaintConfiguration &Config) {
IO.mapOptional("Propagations", Config.Propagations);
IO.mapOptional("Filters", Config.Filters);
IO.mapOptional("Sinks", Config.Sinks);
}
};
template <> struct MappingTraits<TaintConfiguration::Sink> {
static void mapping(IO &IO, TaintConfiguration::Sink &Sink) {
IO.mapRequired("Name", Sink.Name);
IO.mapOptional("Scope", Sink.Scope);
IO.mapRequired("Args", Sink.SinkArgs);
}
};
template <> struct MappingTraits<TaintConfiguration::Filter> {
static void mapping(IO &IO, TaintConfiguration::Filter &Filter) {
IO.mapRequired("Name", Filter.Name);
IO.mapOptional("Scope", Filter.Scope);
IO.mapRequired("Args", Filter.FilterArgs);
}
};
template <> struct MappingTraits<TaintConfiguration::Propagation> {
static void mapping(IO &IO, TaintConfiguration::Propagation &Propagation) {
IO.mapRequired("Name", Propagation.Name);
IO.mapOptional("Scope", Propagation.Scope);
IO.mapOptional("SrcArgs", Propagation.SrcArgs);
IO.mapOptional("DstArgs", Propagation.DstArgs);
IO.mapOptional("VariadicType", Propagation.VarType);
IO.mapOptional("VariadicIndex", Propagation.VarIndex);
}
};
template <> struct ScalarEnumerationTraits<TaintConfiguration::VariadicType> {
static void enumeration(IO &IO, TaintConfiguration::VariadicType &Value) {
IO.enumCase(Value, "None", TaintConfiguration::VariadicType::None);
IO.enumCase(Value, "Src", TaintConfiguration::VariadicType::Src);
IO.enumCase(Value, "Dst", TaintConfiguration::VariadicType::Dst);
}
};
}
}
REGISTER_MAP_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, const LocationContext *,
ImmutableSet<ArgIdxTy>)
REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ArgIdxFactory, ArgIdxTy)
void GenericTaintRuleParser::validateArgVector(const std::string &Option,
const ArgVecTy &Args) const {
for (ArgIdxTy Arg : Args) {
if (Arg < ReturnValueIndex) {
Mgr.reportInvalidCheckerOptionValue(
Mgr.getChecker<GenericTaintChecker>(), Option,
"an argument number for propagation rules greater or equal to -1");
}
}
}
template <typename Config>
GenericTaintRuleParser::NamePartsTy
GenericTaintRuleParser::parseNameParts(const Config &C) {
NamePartsTy NameParts;
if (!C.Scope.empty()) {
StringRef{C.Scope}.split(NameParts, "::", -1,
false);
}
NameParts.emplace_back(C.Name);
return NameParts;
}
template <typename Config>
void GenericTaintRuleParser::consumeRulesFromConfig(const Config &C,
GenericTaintRule &&Rule,
RulesContTy &Rules) {
NamePartsTy NameParts = parseNameParts(C);
Rules.emplace_back(CallDescription(CDM::Unspecified, NameParts),
std::move(Rule));
}
void GenericTaintRuleParser::parseConfig(const std::string &Option,
TaintConfiguration::Sink &&S,
RulesContTy &Rules) const {
validateArgVector(Option, S.SinkArgs);
consumeRulesFromConfig(S, GenericTaintRule::Sink(std::move(S.SinkArgs)),
Rules);
}
void GenericTaintRuleParser::parseConfig(const std::string &Option,
TaintConfiguration::Filter &&S,
RulesContTy &Rules) const {
validateArgVector(Option, S.FilterArgs);
consumeRulesFromConfig(S, GenericTaintRule::Filter(std::move(S.FilterArgs)),
Rules);
}
void GenericTaintRuleParser::parseConfig(const std::string &Option,
TaintConfiguration::Propagation &&P,
RulesContTy &Rules) const {
validateArgVector(Option, P.SrcArgs);
validateArgVector(Option, P.DstArgs);
bool IsSrcVariadic = P.VarType == TaintConfiguration::VariadicType::Src;
bool IsDstVariadic = P.VarType == TaintConfiguration::VariadicType::Dst;
std::optional<ArgIdxTy> JustVarIndex = P.VarIndex;
ArgSet SrcDesc(std::move(P.SrcArgs),
IsSrcVariadic ? JustVarIndex : std::nullopt);
ArgSet DstDesc(std::move(P.DstArgs),
IsDstVariadic ? JustVarIndex : std::nullopt);
consumeRulesFromConfig(
P, GenericTaintRule::Prop(std::move(SrcDesc), std::move(DstDesc)), Rules);
}
GenericTaintRuleParser::RulesContTy
GenericTaintRuleParser::parseConfiguration(const std::string &Option,
TaintConfiguration &&Config) const {
RulesContTy Rules;
for (auto &F : Config.Filters)
parseConfig(Option, std::move(F), Rules);
for (auto &S : Config.Sinks)
parseConfig(Option, std::move(S), Rules);
for (auto &P : Config.Propagations)
parseConfig(Option, std::move(P), Rules);
return Rules;
}
void GenericTaintChecker::initTaintRules(CheckerContext &C) const {
if (StaticTaintRules || DynamicTaintRules)
return;
using RulesConstructionTy =
std::vector<std::pair<CallDescription, GenericTaintRule>>;
using TR = GenericTaintRule;
RulesConstructionTy GlobalCRules{
{{CDM::CLibrary, {"fdopen"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"fopen"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"freopen"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"getch"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"getchar"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"getchar_unlocked"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"gets"}}, TR::Source({{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"gets_s"}}, TR::Source({{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"scanf"}}, TR::Source({{}, 1})},
{{CDM::CLibrary, {"scanf_s"}}, TR::Source({{}, 1})},
{{CDM::CLibrary, {"wgetch"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"_IO_getc"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"getcwd"}}, TR::Source({{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"getwd"}}, TR::Source({{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"readlink"}}, TR::Source({{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"readlinkat"}}, TR::Source({{2, ReturnValueIndex}})},
{{CDM::CLibrary, {"get_current_dir_name"}},
TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"gethostname"}}, TR::Source({{0}})},
{{CDM::CLibrary, {"getnameinfo"}}, TR::Source({{2, 4}})},
{{CDM::CLibrary, {"getseuserbyname"}}, TR::Source({{1, 2}})},
{{CDM::CLibrary, {"getgroups"}}, TR::Source({{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"getlogin"}}, TR::Source({{ReturnValueIndex}})},
{{CDM::CLibrary, {"getlogin_r"}}, TR::Source({{0}})},
{{CDM::CLibrary, {"accept"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"atoi"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"atol"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"atoll"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"fgetc"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"fgetln"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"fgets"}},
TR::Prop({{2}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"fgetws"}},
TR::Prop({{2}}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"fscanf"}}, TR::Prop({{0}}, {{}, 2})},
{{CDM::CLibrary, {"fscanf_s"}}, TR::Prop({{0}}, {{}, 2})},
{{CDM::CLibrary, {"sscanf"}}, TR::Prop({{0}}, {{}, 2})},
{{CDM::CLibrary, {"sscanf_s"}}, TR::Prop({{0}}, {{}, 2})},
{{CDM::CLibrary, {"getc"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"getc_unlocked"}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"getdelim"}}, TR::Prop({{3}}, {{0}})},
{{CDM::CLibrary, {"getline"}}, TR::Prop({{2}}, {{0}})},
{{CDM::CLibrary, {"getw"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"pread"}},
TR::Prop({{0, 1, 2, 3}}, {{1, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"read"}},
TR::Prop({{0, 2}}, {{1, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"fread"}},
TR::Prop({{3}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"recv"}},
TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"recvfrom"}},
TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"ttyname"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"ttyname_r"}},
TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"basename"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"dirname"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"fnmatch"}}, TR::Prop({{1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"mbtowc"}}, TR::Prop({{1}}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"wctomb"}}, TR::Prop({{1}}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"wcwidth"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"memcmp"}},
TR::Prop({{0, 1, 2}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"memcpy"}},
TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"memmove"}},
TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"bcopy"}}, TR::Prop({{0, 2}}, {{1}})},
{{CDM::CLibrary, {"memmem"}}, TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strstr"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strcasestr"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"memchr"}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"memrchr"}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"rawmemchr"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strchr"}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strrchr"}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strchrnul"}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"index"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"rindex"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"qsort"}}, TR::Prop({{0}}, {{0}})},
{{CDM::CLibrary, {"qsort_r"}}, TR::Prop({{0}}, {{0}})},
{{CDM::CLibrary, {"strcmp"}}, TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strcasecmp"}},
TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strncmp"}},
TR::Prop({{0, 1, 2}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strncasecmp"}},
TR::Prop({{0, 1, 2}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strspn"}}, TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strcspn"}}, TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strpbrk"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strndup"}}, TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strndupa"}}, TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strdup"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strdupa"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"wcsdup"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"strtol"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"strtoll"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"strtoul"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"strtoull"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
{{CDM::CLibrary, {"tolower"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"toupper"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isalnum"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isalpha"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isascii"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isblank"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"iscntrl"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isdigit"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isgraph"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"islower"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isprint"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"ispunct"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isspace"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isupper"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibrary, {"isxdigit"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strcpy"}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"stpcpy"}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strcat"}},
TR::Prop({{0, 1}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"wcsncat"}},
TR::Prop({{0, 1}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strncpy"}},
TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strncat"}},
TR::Prop({{0, 1, 2}}, {{0, ReturnValueIndex}})},
{{CDM::CLibraryMaybeHardened, {"strlcpy"}}, TR::Prop({{1, 2}}, {{0}})},
{{CDM::CLibraryMaybeHardened, {"strlcat"}}, TR::Prop({{0, 1, 2}}, {{0}})},
{{CDM::CLibrary, {"snprintf"}},
TR::Prop({{1, 2}, 3}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"sprintf"}},
TR::Prop({{1}, 2}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"__snprintf_chk"}},
TR::Prop({{1, 4}, 5}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"__sprintf_chk"}},
TR::Prop({{3}, 4}, {{0, ReturnValueIndex}})},
{{CDM::CLibrary, {"system"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"popen"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execl"}}, TR::Sink({{}, {0}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execle"}}, TR::Sink({{}, {0}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execlp"}}, TR::Sink({{}, {0}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execv"}}, TR::Sink({{0, 1}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execve"}},
TR::Sink({{0, 1, 2}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"fexecve"}},
TR::Sink({{0, 1, 2}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execvp"}}, TR::Sink({{0, 1}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"execvpe"}},
TR::Sink({{0, 1, 2}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"dlopen"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
{{CDM::CLibrary, {"setproctitle"}},
TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
{{CDM::CLibrary, {"setproctitle_fast"}},
TR::Sink({{0}, 1}, MsgUncontrolledFormatString)}};
if (TR::UntrustedEnv(C)) {
GlobalCRules.push_back({{CDM::CLibrary, {"setproctitle_init"}},
TR::Sink({{1, 2}}, MsgCustomSink)});
GlobalCRules.push_back(
{{CDM::CLibrary, {"getenv"}}, TR::Source({{ReturnValueIndex}})});
}
StaticTaintRules.emplace(std::make_move_iterator(GlobalCRules.begin()),
std::make_move_iterator(GlobalCRules.end()));
CheckerManager *Mgr = C.getAnalysisManager().getCheckerManager();
assert(Mgr);
GenericTaintRuleParser ConfigParser{*Mgr};
std::string Option{"Config"};
StringRef ConfigFile =
Mgr->getAnalyzerOptions().getCheckerStringOption(this, Option);
std::optional<TaintConfiguration> Config =
getConfiguration<TaintConfiguration>(*Mgr, this, Option, ConfigFile);
if (!Config) {
DynamicTaintRules = RuleLookupTy{};
return;
}
GenericTaintRuleParser::RulesContTy Rules{
ConfigParser.parseConfiguration(Option, std::move(*Config))};
DynamicTaintRules.emplace(std::make_move_iterator(Rules.begin()),
std::make_move_iterator(Rules.end()));
}
void GenericTaintChecker::checkPreCall(const CallEvent &Call,
CheckerContext &C) const {
initTaintRules(C);
if (const auto *Rule =
Call.isGlobalCFunction() ? StaticTaintRules->lookup(Call) : nullptr)
Rule->process(*this, Call, C);
else if (const auto *Rule = DynamicTaintRules->lookup(Call))
Rule->process(*this, Call, C);
checkUncontrolledFormatString(Call, C);
taintUnsafeSocketProtocol(Call, C);
}
void GenericTaintChecker::checkPostCall(const CallEvent &Call,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
const StackFrameContext *CurrentFrame = C.getStackFrame();
TaintArgsOnPostVisitTy TaintArgsMap = State->get<TaintArgsOnPostVisit>();
const ImmutableSet<ArgIdxTy> *TaintArgs = TaintArgsMap.lookup(CurrentFrame);
if (!TaintArgs)
return;
assert(!TaintArgs->isEmpty());
LLVM_DEBUG(for (ArgIdxTy I
: *TaintArgs) {
llvm::dbgs() << "PostCall<";
Call.dump(llvm::dbgs());
llvm::dbgs() << "> actually wants to taint arg index: " << I << '\n';
});
const NoteTag *InjectionTag = nullptr;
std::vector<SymbolRef> TaintedSymbols;
std::vector<ArgIdxTy> TaintedIndexes;
for (ArgIdxTy ArgNum : *TaintArgs) {
if (ArgNum == ReturnValueIndex) {
State = addTaint(State, Call.getReturnValue());
std::vector<SymbolRef> TaintedSyms =
getTaintedSymbols(State, Call.getReturnValue());
if (!TaintedSyms.empty()) {
TaintedSymbols.push_back(TaintedSyms[0]);
TaintedIndexes.push_back(ArgNum);
}
continue;
}
if (auto V = getPointeeOf(State, Call.getArgSVal(ArgNum))) {
State = addTaint(State, *V);
std::vector<SymbolRef> TaintedSyms = getTaintedSymbols(State, *V);
if (!TaintedSyms.empty()) {
TaintedSymbols.push_back(TaintedSyms[0]);
TaintedIndexes.push_back(ArgNum);
}
}
}
InjectionTag = taintPropagationExplainerTag(C, TaintedSymbols, TaintedIndexes,
Call.getCalleeStackFrame(0));
State = State->remove<TaintArgsOnPostVisit>(CurrentFrame);
C.addTransition(State, InjectionTag);
}
void GenericTaintChecker::printState(raw_ostream &Out, ProgramStateRef State,
const char *NL, const char *Sep) const {
printTaint(State, Out, NL, Sep);
}
void GenericTaintRule::process(const GenericTaintChecker &Checker,
const CallEvent &Call, CheckerContext &C) const {
ProgramStateRef State = C.getState();
const ArgIdxTy CallNumArgs = fromArgumentCount(Call.getNumArgs());
const auto ForEachCallArg = [&C, &Call, CallNumArgs](auto &&Fun) {
for (ArgIdxTy I = ReturnValueIndex; I < CallNumArgs; ++I) {
const Expr *E = GetArgExpr(I, Call);
Fun(I, E, C.getSVal(E));
}
};
ForEachCallArg([this, &Checker, &C, &State](ArgIdxTy I, const Expr *E, SVal) {
if (isStdin(C.getSVal(E), C.getASTContext())) {
State = addTaint(State, C.getSVal(E));
}
if (SinkArgs.contains(I) && isTaintedOrPointsToTainted(State, C.getSVal(E)))
Checker.generateReportIfTainted(E, SinkMsg.value_or(MsgCustomSink), C);
});
ForEachCallArg([this, &State](ArgIdxTy I, const Expr *E, SVal S) {
if (FilterArgs.contains(I)) {
State = removeTaint(State, S);
if (auto P = getPointeeOf(State, S))
State = removeTaint(State, *P);
}
});
bool IsMatching = PropSrcArgs.isEmpty();
std::vector<SymbolRef> TaintedSymbols;
std::vector<ArgIdxTy> TaintedIndexes;
ForEachCallArg([this, &C, &IsMatching, &State, &TaintedSymbols,
&TaintedIndexes](ArgIdxTy I, const Expr *E, SVal) {
std::optional<SVal> TaintedSVal =
getTaintedPointeeOrPointer(State, C.getSVal(E));
IsMatching =
IsMatching || (PropSrcArgs.contains(I) && TaintedSVal.has_value());
if (TaintedSVal && !isStdin(*TaintedSVal, C.getASTContext())) {
std::vector<SymbolRef> TaintedArgSyms =
getTaintedSymbols(State, *TaintedSVal);
if (!TaintedArgSyms.empty()) {
llvm::append_range(TaintedSymbols, TaintedArgSyms);
TaintedIndexes.push_back(I);
}
}
});
if (!IsMatching)
return;
const auto WouldEscape = [](SVal V, QualType Ty) -> bool {
if (!isa<Loc>(V))
return false;
const bool IsNonConstRef = Ty->isReferenceType() && !Ty.isConstQualified();
const bool IsNonConstPtr =
Ty->isPointerType() && !Ty->getPointeeType().isConstQualified();
return IsNonConstRef || IsNonConstPtr;
};
auto &F = State->getStateManager().get_context<ArgIdxFactory>();
ImmutableSet<ArgIdxTy> Result = F.getEmptySet();
ForEachCallArg(
[&](ArgIdxTy I, const Expr *E, SVal V) {
if (PropDstArgs.contains(I)) {
LLVM_DEBUG(llvm::dbgs() << "PreCall<"; Call.dump(llvm::dbgs());
llvm::dbgs()
<< "> prepares tainting arg index: " << I << '\n';);
Result = F.add(Result, I);
}
if (WouldEscape(V, E->getType()) && getTaintedPointeeOrPointer(State, V)) {
LLVM_DEBUG(if (!Result.contains(I)) {
llvm::dbgs() << "PreCall<";
Call.dump(llvm::dbgs());
llvm::dbgs() << "> prepares tainting arg index: " << I << '\n';
});
Result = F.add(Result, I);
}
});
if (!Result.isEmpty())
State = State->set<TaintArgsOnPostVisit>(C.getStackFrame(), Result);
const NoteTag *InjectionTag = taintOriginTrackerTag(
C, std::move(TaintedSymbols), std::move(TaintedIndexes),
Call.getCalleeStackFrame(0));
C.addTransition(State, InjectionTag);
}
bool GenericTaintRule::UntrustedEnv(CheckerContext &C) {
return !C.getAnalysisManager()
.getAnalyzerOptions()
.ShouldAssumeControlledEnvironment;
}
bool GenericTaintChecker::generateReportIfTainted(const Expr *E, StringRef Msg,
CheckerContext &C) const {
assert(E);
if (!isTaintReporterCheckerEnabled)
return false;
std::optional<SVal> TaintedSVal =
getTaintedPointeeOrPointer(C.getState(), C.getSVal(E));
if (!TaintedSVal)
return false;
assert(BT);
static CheckerProgramPointTag Tag(BT->getCheckerName(), Msg);
if (ExplodedNode *N = C.generateNonFatalErrorNode(C.getState(), &Tag)) {
auto report = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
report->addRange(E->getSourceRange());
for (auto TaintedSym : getTaintedSymbols(C.getState(), *TaintedSVal)) {
report->markInteresting(TaintedSym);
}
C.emitReport(std::move(report));
return true;
}
return false;
}
static bool getPrintfFormatArgumentNum(const CallEvent &Call,
const CheckerContext &C,
ArgIdxTy &ArgNum) {
const Decl *CallDecl = Call.getDecl();
if (!CallDecl)
return false;
const FunctionDecl *FDecl = CallDecl->getAsFunction();
if (!FDecl)
return false;
const ArgIdxTy CallNumArgs = fromArgumentCount(Call.getNumArgs());
for (const auto *Format : FDecl->specific_attrs<FormatAttr>()) {
ArgNum = Format->getFormatIdx() - 1;
if ((Format->getType()->getName() == "printf") && CallNumArgs > ArgNum)
return true;
}
return false;
}
bool GenericTaintChecker::checkUncontrolledFormatString(
const CallEvent &Call, CheckerContext &C) const {
ArgIdxTy ArgNum = 0;
if (!getPrintfFormatArgumentNum(Call, C, ArgNum))
return false;
return generateReportIfTainted(Call.getArgExpr(ArgNum),
MsgUncontrolledFormatString, C);
}
void GenericTaintChecker::taintUnsafeSocketProtocol(const CallEvent &Call,
CheckerContext &C) const {
if (Call.getNumArgs() < 1)
return;
const IdentifierInfo *ID = Call.getCalleeIdentifier();
if (!ID)
return;
if (ID->getName() != "socket")
return;
SourceLocation DomLoc = Call.getArgExpr(0)->getExprLoc();
StringRef DomName = C.getMacroNameOrSpelling(DomLoc);
bool SafeProtocol = DomName == "AF_SYSTEM" || DomName == "AF_LOCAL" ||
DomName == "AF_UNIX" || DomName == "AF_RESERVED_36";
if (SafeProtocol)
return;
ProgramStateRef State = C.getState();
auto &F = State->getStateManager().get_context<ArgIdxFactory>();
ImmutableSet<ArgIdxTy> Result = F.add(F.getEmptySet(), ReturnValueIndex);
State = State->set<TaintArgsOnPostVisit>(C.getStackFrame(), Result);
C.addTransition(State);
}
void ento::registerTaintPropagationChecker(CheckerManager &Mgr) {
Mgr.registerChecker<GenericTaintChecker>();
}
bool ento::shouldRegisterTaintPropagationChecker(const CheckerManager &mgr) {
return true;
}
void ento::registerGenericTaintChecker(CheckerManager &Mgr) {
GenericTaintChecker *checker = Mgr.getChecker<GenericTaintChecker>();
checker->isTaintReporterCheckerEnabled = true;
checker->BT.emplace(Mgr.getCurrentCheckerName(), "Use of Untrusted Data",
categories::TaintedData);
}
bool ento::shouldRegisterGenericTaintChecker(const CheckerManager &mgr) {
return true;
}