#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace ento;
namespace {
class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
check::PostStmt<CallExpr>,
check::DeadSymbols,
check::PointerEscape,
eval::Assume> {
mutable std::unique_ptr<BugType> BT;
public:
struct AllocationState {
unsigned int AllocatorIdx;
SymbolRef Region;
AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
AllocatorIdx(Idx),
Region(R) {}
bool operator==(const AllocationState &X) const {
return (AllocatorIdx == X.AllocatorIdx &&
Region == X.Region);
}
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(AllocatorIdx);
ID.AddPointer(Region);
}
};
void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
ProgramStateRef checkPointerEscape(ProgramStateRef State,
const InvalidatedSymbols &Escaped,
const CallEvent *Call,
PointerEscapeKind Kind) const;
ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
bool Assumption) const;
void printState(raw_ostream &Out, ProgramStateRef State,
const char *NL, const char *Sep) const override;
private:
typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
typedef SmallVector<AllocationPair, 2> AllocationPairVec;
enum APIKind {
ValidAPI = 0,
ErrorAPI = 1,
PossibleAPI = 2
};
struct ADFunctionInfo {
const char* Name;
unsigned int Param;
unsigned int DeallocatorIdx;
APIKind Kind;
};
static const unsigned InvalidIdx = 100000;
static const unsigned FunctionsToTrackSize = 8;
static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
static const unsigned NoErr = 0;
static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
inline void initBugType() const {
if (!BT)
BT.reset(new BugType(this, "Improper use of SecKeychain API",
"API Misuse (Apple)"));
}
void generateDeallocatorMismatchReport(const AllocationPair &AP,
const Expr *ArgExpr,
CheckerContext &C) const;
const ExplodedNode *getAllocationNode(const ExplodedNode *N, SymbolRef Sym,
CheckerContext &C) const;
std::unique_ptr<PathSensitiveBugReport>
generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
ExplodedNode *N,
CheckerContext &C) const;
void markInteresting(PathSensitiveBugReport *R,
const AllocationPair &AP) const {
R->markInteresting(AP.first);
R->markInteresting(AP.second->Region);
}
class SecKeychainBugVisitor : public BugReporterVisitor {
protected:
SymbolRef Sym;
public:
SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int X = 0;
ID.AddPointer(&X);
ID.AddPointer(Sym);
}
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override;
};
};
}
REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
SymbolRef,
MacOSKeychainAPIChecker::AllocationState)
static bool isEnclosingFunctionParam(const Expr *E) {
E = E->IgnoreParenCasts();
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
const ValueDecl *VD = DRE->getDecl();
if (isa<ImplicitParamDecl, ParmVarDecl>(VD))
return true;
}
return false;
}
const MacOSKeychainAPIChecker::ADFunctionInfo
MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
{"SecKeychainItemCopyContent", 4, 3, ValidAPI}, {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, {"free", 0, InvalidIdx, ErrorAPI}, {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, };
unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
bool IsAllocator) {
for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
ADFunctionInfo FI = FunctionsToTrack[I];
if (FI.Name != Name)
continue;
if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
return InvalidIdx;
if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
return InvalidIdx;
return I;
}
return InvalidIdx;
}
static bool isBadDeallocationArgument(const MemRegion *Arg) {
if (!Arg)
return false;
return isa<AllocaRegion, BlockDataRegion, TypedRegion>(Arg);
}
static SymbolRef getAsPointeeSymbol(const Expr *Expr,
CheckerContext &C) {
ProgramStateRef State = C.getState();
SVal ArgV = C.getSVal(Expr);
if (Optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) {
StoreManager& SM = C.getStoreManager();
SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
if (sym)
return sym;
}
return nullptr;
}
void MacOSKeychainAPIChecker::
generateDeallocatorMismatchReport(const AllocationPair &AP,
const Expr *ArgExpr,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
State = State->remove<AllocatedData>(AP.first);
ExplodedNode *N = C.generateNonFatalErrorNode(State);
if (!N)
return;
initBugType();
SmallString<80> sbuf;
llvm::raw_svector_ostream os(sbuf);
unsigned int PDeallocIdx =
FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
os << "Deallocator doesn't match the allocator: '"
<< FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
auto Report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
Report->addVisitor(std::make_unique<SecKeychainBugVisitor>(AP.first));
Report->addRange(ArgExpr->getSourceRange());
markInteresting(Report.get(), AP);
C.emitReport(std::move(Report));
}
void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
CheckerContext &C) const {
unsigned idx = InvalidIdx;
ProgramStateRef State = C.getState();
const FunctionDecl *FD = C.getCalleeDecl(CE);
if (!FD || FD->getKind() != Decl::Function)
return;
StringRef funName = C.getCalleeName(FD);
if (funName.empty())
return;
idx = getTrackedFunctionIndex(funName, true);
if (idx != InvalidIdx) {
unsigned paramIdx = FunctionsToTrack[idx].Param;
if (CE->getNumArgs() <= paramIdx)
return;
const Expr *ArgExpr = CE->getArg(paramIdx);
if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
if (const AllocationState *AS = State->get<AllocatedData>(V)) {
State = State->remove<AllocatedData>(V);
ExplodedNode *N = C.generateNonFatalErrorNode(State);
if (!N)
return;
initBugType();
SmallString<128> sbuf;
llvm::raw_svector_ostream os(sbuf);
unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
os << "Allocated data should be released before another call to "
<< "the allocator: missing a call to '"
<< FunctionsToTrack[DIdx].Name
<< "'.";
auto Report =
std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
Report->addVisitor(std::make_unique<SecKeychainBugVisitor>(V));
Report->addRange(ArgExpr->getSourceRange());
Report->markInteresting(AS->Region);
C.emitReport(std::move(Report));
}
return;
}
idx = getTrackedFunctionIndex(funName, false);
if (idx == InvalidIdx)
return;
unsigned paramIdx = FunctionsToTrack[idx].Param;
if (CE->getNumArgs() <= paramIdx)
return;
const Expr *ArgExpr = CE->getArg(paramIdx);
SVal ArgSVal = C.getSVal(ArgExpr);
if (ArgSVal.isUndef())
return;
SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
bool RegionArgIsBad = false;
if (!ArgSM) {
if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
return;
RegionArgIsBad = true;
}
const AllocationState *AS = State->get<AllocatedData>(ArgSM);
if (!AS)
return;
if (RegionArgIsBad) {
if (isEnclosingFunctionParam(ArgExpr))
return;
ExplodedNode *N = C.generateNonFatalErrorNode(State);
if (!N)
return;
initBugType();
auto Report = std::make_unique<PathSensitiveBugReport>(
*BT, "Trying to free data which has not been allocated.", N);
Report->addRange(ArgExpr->getSourceRange());
if (AS)
Report->markInteresting(AS->Region);
C.emitReport(std::move(Report));
return;
}
if (FunctionsToTrack[idx].Kind == PossibleAPI) {
if (funName == "CFStringCreateWithBytesNoCopy") {
const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
Expr::NPC_ValueDependentIsNotNull)) {
const AllocationPair AP = std::make_pair(ArgSM, AS);
generateDeallocatorMismatchReport(AP, ArgExpr, C);
return;
}
if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
StringRef DeallocatorName = DE->getFoundDecl()->getName();
if (DeallocatorName == "kCFAllocatorDefault" ||
DeallocatorName == "kCFAllocatorSystemDefault" ||
DeallocatorName == "kCFAllocatorMalloc") {
const AllocationPair AP = std::make_pair(ArgSM, AS);
generateDeallocatorMismatchReport(AP, ArgExpr, C);
return;
}
if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
return;
}
State = State->remove<AllocatedData>(ArgSM);
C.addTransition(State);
return;
}
llvm_unreachable("We know of no other possible APIs.");
}
State = State->remove<AllocatedData>(ArgSM);
unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
const AllocationPair AP = std::make_pair(ArgSM, AS);
generateDeallocatorMismatchReport(AP, ArgExpr, C);
return;
}
C.addTransition(State);
}
void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
const FunctionDecl *FD = C.getCalleeDecl(CE);
if (!FD || FD->getKind() != Decl::Function)
return;
StringRef funName = C.getCalleeName(FD);
unsigned idx = getTrackedFunctionIndex(funName, true);
if (idx == InvalidIdx)
return;
const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
if (isEnclosingFunctionParam(ArgExpr) &&
C.getLocationContext()->getParent() == nullptr)
return;
if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
SymbolRef RetStatusSymbol = C.getSVal(CE).getAsSymbol();
C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
RetStatusSymbol));
assert(State);
C.addTransition(State);
}
}
const ExplodedNode *
MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
SymbolRef Sym,
CheckerContext &C) const {
const LocationContext *LeakContext = N->getLocationContext();
const ExplodedNode *AllocNode = N;
while (N) {
if (!N->getState()->get<AllocatedData>(Sym))
break;
const LocationContext *NContext = N->getLocationContext();
if (NContext == LeakContext ||
NContext->isParentOf(LeakContext))
AllocNode = N;
N = N->pred_empty() ? nullptr : *(N->pred_begin());
}
return AllocNode;
}
std::unique_ptr<PathSensitiveBugReport>
MacOSKeychainAPIChecker::generateAllocatedDataNotReleasedReport(
const AllocationPair &AP, ExplodedNode *N, CheckerContext &C) const {
const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
initBugType();
SmallString<70> sbuf;
llvm::raw_svector_ostream os(sbuf);
os << "Allocated data is not released: missing a call to '"
<< FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
PathDiagnosticLocation LocUsedForUniqueing;
const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
const Stmt *AllocStmt = AllocNode->getStmtForDiagnostics();
if (AllocStmt)
LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
C.getSourceManager(),
AllocNode->getLocationContext());
auto Report = std::make_unique<PathSensitiveBugReport>(
*BT, os.str(), N, LocUsedForUniqueing,
AllocNode->getLocationContext()->getDecl());
Report->addVisitor(std::make_unique<SecKeychainBugVisitor>(AP.first));
markInteresting(Report.get(), AP);
return Report;
}
ProgramStateRef MacOSKeychainAPIChecker::evalAssume(ProgramStateRef State,
SVal Cond,
bool Assumption) const {
AllocatedDataTy AMap = State->get<AllocatedData>();
if (AMap.isEmpty())
return State;
auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymbol());
if (!CondBSE)
return State;
BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
if (OpCode != BO_EQ && OpCode != BO_NE)
return State;
SymbolRef ReturnSymbol = nullptr;
if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
const llvm::APInt &RHS = SIE->getRHS();
bool ErrorIsReturned = (OpCode == BO_EQ && RHS != NoErr) ||
(OpCode == BO_NE && RHS == NoErr);
if (!Assumption)
ErrorIsReturned = !ErrorIsReturned;
if (ErrorIsReturned)
ReturnSymbol = SIE->getLHS();
}
if (ReturnSymbol)
for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
if (ReturnSymbol == I->second.Region)
State = State->remove<AllocatedData>(I->first);
}
return State;
}
void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
AllocatedDataTy AMap = State->get<AllocatedData>();
if (AMap.isEmpty())
return;
bool Changed = false;
AllocationPairVec Errors;
for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
if (!SR.isDead(I->first))
continue;
Changed = true;
State = State->remove<AllocatedData>(I->first);
ConstraintManager &CMgr = State->getConstraintManager();
ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
if (AllocFailed.isConstrainedTrue())
continue;
Errors.push_back(std::make_pair(I->first, &I->second));
}
if (!Changed) {
C.addTransition(State);
return;
}
static CheckerProgramPointTag Tag(this, "DeadSymbolsLeak");
ExplodedNode *N = C.generateNonFatalErrorNode(C.getState(), &Tag);
if (!N)
return;
for (const auto &P : Errors)
C.emitReport(generateAllocatedDataNotReleasedReport(P, N, C));
C.addTransition(State, N);
}
ProgramStateRef MacOSKeychainAPIChecker::checkPointerEscape(
ProgramStateRef State, const InvalidatedSymbols &Escaped,
const CallEvent *Call, PointerEscapeKind Kind) const {
if (!Call || Call->getDecl())
return State;
for (auto I : State->get<AllocatedData>()) {
SymbolRef Sym = I.first;
if (Escaped.count(Sym))
State = State->remove<AllocatedData>(Sym);
if (const auto *SD = dyn_cast<SymbolDerived>(Sym)) {
SymbolRef ParentSym = SD->getParentSymbol();
if (Escaped.count(ParentSym))
State = State->remove<AllocatedData>(Sym);
}
}
return State;
}
PathDiagnosticPieceRef
MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
const ExplodedNode *N, BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
if (!AS)
return nullptr;
const AllocationState *ASPrev =
N->getFirstPred()->getState()->get<AllocatedData>(Sym);
if (ASPrev)
return nullptr;
const CallExpr *CE =
cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
const FunctionDecl *funDecl = CE->getDirectCallee();
assert(funDecl && "We do not support indirect function calls as of now.");
StringRef funName = funDecl->getName();
unsigned Idx = getTrackedFunctionIndex(funName, true);
assert(Idx != InvalidIdx && "This should be a call to an allocator.");
const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
N->getLocationContext());
return std::make_shared<PathDiagnosticEventPiece>(Pos,
"Data is allocated here.");
}
void MacOSKeychainAPIChecker::printState(raw_ostream &Out,
ProgramStateRef State,
const char *NL,
const char *Sep) const {
AllocatedDataTy AMap = State->get<AllocatedData>();
if (!AMap.isEmpty()) {
Out << Sep << "KeychainAPIChecker :" << NL;
for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
I.getKey()->dumpToStream(Out);
}
}
}
void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
mgr.registerChecker<MacOSKeychainAPIChecker>();
}
bool ento::shouldRegisterMacOSKeychainAPIChecker(const CheckerManager &mgr) {
return true;
}