MacOSKeychainAPIChecker.cpp [plain text]
#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.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"
using namespace clang;
using namespace ento;
namespace {
class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
check::PreStmt<ReturnStmt>,
check::PostStmt<CallExpr>,
check::EndPath,
check::DeadSymbols> {
mutable OwningPtr<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 checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
void checkEndPath(CheckerContext &C) const;
private:
typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
typedef llvm::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("Improper use of SecKeychain API", "Mac OS API"));
}
void generateDeallocatorMismatchReport(const AllocationPair &AP,
const Expr *ArgExpr,
CheckerContext &C) const;
const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
CheckerContext &C) const;
BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
ExplodedNode *N,
CheckerContext &C) const;
bool definitelyReturnedError(SymbolRef RetSym,
ProgramStateRef State,
SValBuilder &Builder,
bool noError = false) const;
bool definitelyDidnotReturnError(SymbolRef RetSym,
ProgramStateRef State,
SValBuilder &Builder) const {
return definitelyReturnedError(RetSym, State, Builder, true);
}
void markInteresting(BugReport *R, const AllocationPair &AP) const {
R->markInteresting(AP.first);
R->markInteresting(AP.second->Region);
}
class SecKeychainBugVisitor
: public BugReporterVisitorImpl<SecKeychainBugVisitor> {
protected:
SymbolRef Sym;
public:
SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
virtual ~SecKeychainBugVisitor() {}
void Profile(llvm::FoldingSetNodeID &ID) const {
static int X = 0;
ID.AddPointer(&X);
ID.AddPointer(Sym);
}
PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
const ExplodedNode *PrevN,
BugReporterContext &BRC,
BugReport &BR);
};
};
}
typedef llvm::ImmutableMap<SymbolRef,
MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
namespace { struct AllocatedData {}; }
namespace clang { namespace ento {
template<> struct ProgramStateTrait<AllocatedData>
: public ProgramStatePartialTrait<AllocatedSetTy > {
static void *GDMIndex() { static int index = 0; return &index; }
};
}}
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>(VD) || isa<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;
if (isa<AllocaRegion>(Arg) ||
isa<BlockDataRegion>(Arg) ||
isa<TypedRegion>(Arg)) {
return true;
}
return false;
}
static SymbolRef getAsPointeeSymbol(const Expr *Expr,
CheckerContext &C) {
ProgramStateRef State = C.getState();
SVal ArgV = State->getSVal(Expr, C.getLocationContext());
if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
StoreManager& SM = C.getStoreManager();
SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
if (sym)
return sym;
}
return 0;
}
bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
ProgramStateRef State,
SValBuilder &Builder,
bool noError) const {
DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
Builder.getSymbolManager().getType(RetSym));
DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
nonloc::SymbolVal(RetSym));
ProgramStateRef ErrState = State->assume(NoErr, noError);
if (ErrState == State) {
return true;
}
return false;
}
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.addTransition(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.";
BugReport *Report = new BugReport(*BT, os.str(), N);
Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Report->addRange(ArgExpr->getSourceRange());
markInteresting(Report, AP);
C.EmitReport(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) {
const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
if (const AllocationState *AS = State->get<AllocatedData>(V)) {
if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
State = State->remove<AllocatedData>(V);
ExplodedNode *N = C.addTransition(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
<< "'.";
BugReport *Report = new BugReport(*BT, os.str(), N);
Report->addVisitor(new SecKeychainBugVisitor(V));
Report->addRange(ArgExpr->getSourceRange());
Report->markInteresting(AS->Region);
C.EmitReport(Report);
}
}
return;
}
idx = getTrackedFunctionIndex(funName, false);
if (idx == InvalidIdx)
return;
const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
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 && FunctionsToTrack[idx].Kind != ValidAPI) {
return;
}
if (!AS || RegionArgIsBad) {
if (isEnclosingFunctionParam(ArgExpr))
return;
ExplodedNode *N = C.addTransition(State);
if (!N)
return;
initBugType();
BugReport *Report = new BugReport(*BT,
"Trying to free data which has not been allocated.", N);
Report->addRange(ArgExpr->getSourceRange());
if (AS)
Report->markInteresting(AS->Region);
C.EmitReport(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") {
State = State->remove<AllocatedData>(ArgSM);
C.addTransition(State);
return;
}
}
}
return;
}
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;
}
if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
!definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
ExplodedNode *N = C.addTransition(State);
if (!N)
return;
initBugType();
BugReport *Report = new BugReport(*BT,
"Only call free if a valid (non-NULL) buffer was returned.", N);
Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Report->addRange(ArgExpr->getSourceRange());
Report->markInteresting(AS->Region);
C.EmitReport(Report);
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() == 0)
return;
if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
SymbolRef RetStatusSymbol =
State->getSVal(CE, C.getLocationContext()).getAsSymbol();
C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
RetStatusSymbol));
assert(State);
C.addTransition(State);
}
}
void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
CheckerContext &C) const {
const Expr *retExpr = S->getRetValue();
if (!retExpr)
return;
const LocationContext *LC = C.getLocationContext();
if (LC->getParent() != 0)
return;
ProgramStateRef state = C.getState();
SymbolRef sym = state->getSVal(retExpr, LC).getAsLocSymbol();
if (!sym)
return;
state = state->remove<AllocatedData>(sym);
C.addTransition(state);
}
const Stmt *
MacOSKeychainAPIChecker::getAllocationSite(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;
if (N->getLocationContext() == LeakContext)
AllocNode = N;
N = N->pred_empty() ? NULL : *(N->pred_begin());
}
ProgramPoint P = AllocNode->getLocation();
if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
return Exit->getCalleeContext()->getCallSite();
if (clang::PostStmt *PS = dyn_cast<clang::PostStmt>(&P))
return PS->getStmt();
return 0;
}
BugReport *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;
if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
C.getSourceManager(), N->getLocationContext());
BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
Report->addVisitor(new SecKeychainBugVisitor(AP.first));
markInteresting(Report, AP);
return Report;
}
void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
AllocatedSetTy ASet = State->get<AllocatedData>();
if (ASet.isEmpty())
return;
bool Changed = false;
AllocationPairVec Errors;
for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
if (SR.isLive(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() ||
definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
continue;
Errors.push_back(std::make_pair(I->first, &I->second));
}
if (!Changed) {
C.addTransition(State);
return;
}
static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
I != E; ++I) {
C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
}
C.addTransition(State, N);
}
void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
ProgramStateRef state = C.getState();
if (C.getLocationContext()->getParent() != 0)
return;
AllocatedSetTy AS = state->get<AllocatedData>();
if (AS.isEmpty())
return;
bool Changed = false;
AllocationPairVec Errors;
for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Changed = true;
state = state->remove<AllocatedData>(I->first);
ConstraintManager &CMgr = state->getConstraintManager();
ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
if (AllocFailed.isConstrainedTrue() ||
definitelyReturnedError(I->second.Region, state,
C.getSValBuilder())) {
continue;
}
Errors.push_back(std::make_pair(I->first, &I->second));
}
if (!Changed) {
C.addTransition(state);
return;
}
static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
I != E; ++I) {
C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
}
C.addTransition(state, N);
}
PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
const ExplodedNode *N,
const ExplodedNode *PrevN,
BugReporterContext &BRC,
BugReport &BR) {
const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
if (!AS)
return 0;
const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
if (ASPrev)
return 0;
const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
.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 new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
}
void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
mgr.registerChecker<MacOSKeychainAPIChecker>();
}