blob: 81c10450c553d4fefa5782c93b0b6b3c1fe51a48 [file] [log] [blame]
Anna Zaks083fcb22011-08-04 17:28:06 +00001//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
Anna Zaksf57be282011-08-01 22:40:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This checker flags misuses of KeyChainAPI. In particular, the password data
10// allocated/returned by SecKeychainItemCopyContent,
11// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
12// to be freed using a call to SecKeychainItemFreeContent.
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
16#include "clang/StaticAnalyzer/Core/Checker.h"
17#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Anna Zaks03826aa2011-08-04 00:26:57 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaksf57be282011-08-01 22:40:01 +000019#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
22
23using namespace clang;
24using namespace ento;
25
26namespace {
27class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
28 check::PreStmt<ReturnStmt>,
29 check::PostStmt<CallExpr>,
30 check::EndPath > {
Anna Zaks03826aa2011-08-04 00:26:57 +000031 mutable llvm::OwningPtr<BugType> BT;
32
Anna Zaksf57be282011-08-01 22:40:01 +000033public:
34 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
35 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
36 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
37
38 void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
39
40private:
Anna Zaks083fcb22011-08-04 17:28:06 +000041 /// Stores the information about the allocator and deallocator functions -
42 /// these are the functions the checker is tracking.
43 struct ADFunctionInfo {
44 const char* Name;
45 unsigned int Param;
46 unsigned int DeallocatorIdx;
47 };
48 static const unsigned InvalidIdx = 100000;
49 static const unsigned FunctionsToTrackSize = 4;
50 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaksf57be282011-08-01 22:40:01 +000051
Anna Zaks083fcb22011-08-04 17:28:06 +000052 /// Given the function name, returns the index of the allocator/deallocator
53 /// function.
54 unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const;
Anna Zaks03826aa2011-08-04 00:26:57 +000055
56 inline void initBugType() const {
57 if (!BT)
58 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
59 }
Anna Zaksf57be282011-08-01 22:40:01 +000060};
61}
62
Anna Zaks083fcb22011-08-04 17:28:06 +000063/// AllocationState is a part of the checker specific state together with the
64/// MemRegion corresponding to the allocated data.
65struct AllocationState {
Anna Zaks03826aa2011-08-04 00:26:57 +000066 const Expr *Address;
Anna Zaks083fcb22011-08-04 17:28:06 +000067 /// The index of the allocator function.
68 unsigned int AllocatorIdx;
Anna Zaks03826aa2011-08-04 00:26:57 +000069
Anna Zaks083fcb22011-08-04 17:28:06 +000070 AllocationState(const Expr *E, unsigned int Idx) : Address(E),
71 AllocatorIdx(Idx) {}
72 bool operator==(const AllocationState &X) const {
Anna Zaks03826aa2011-08-04 00:26:57 +000073 return Address == X.Address;
74 }
75 void Profile(llvm::FoldingSetNodeID &ID) const {
76 ID.AddPointer(Address);
Anna Zaks083fcb22011-08-04 17:28:06 +000077 ID.AddInteger(AllocatorIdx);
Anna Zaks03826aa2011-08-04 00:26:57 +000078 }
79};
80
Anna Zaks083fcb22011-08-04 17:28:06 +000081/// GRState traits to store the currently allocated (and not yet freed) symbols.
82typedef llvm::ImmutableMap<const MemRegion*, AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +000083
84namespace { struct AllocatedData {}; }
85namespace clang { namespace ento {
86template<> struct GRStateTrait<AllocatedData>
87 : public GRStatePartialTrait<AllocatedSetTy > {
88 static void *GDMIndex() { static int index = 0; return &index; }
89};
90}}
91
Anna Zaks03826aa2011-08-04 00:26:57 +000092static bool isEnclosingFunctionParam(const Expr *E) {
93 E = E->IgnoreParenCasts();
94 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
95 const ValueDecl *VD = DRE->getDecl();
96 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
97 return true;
98 }
99 return false;
100}
101
Anna Zaks083fcb22011-08-04 17:28:06 +0000102const MacOSKeychainAPIChecker::ADFunctionInfo
103 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
104 {"SecKeychainItemCopyContent", 4, 3}, // 0
105 {"SecKeychainFindGenericPassword", 6, 3}, // 1
106 {"SecKeychainFindInternetPassword", 13, 3}, // 2
107 {"SecKeychainItemFreeContent", 1, InvalidIdx}, // 3
108};
109
110unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
111 bool IsAllocator) const {
112 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
113 ADFunctionInfo FI = FunctionsToTrack[I];
114 if (FI.Name != Name)
115 continue;
116 // Make sure the function is of the right type (allocator vs deallocator).
117 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
118 return InvalidIdx;
119 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
120 return InvalidIdx;
121
122 return I;
123 }
124 // The function is not tracked.
125 return InvalidIdx;
126}
127
Anna Zaksf57be282011-08-01 22:40:01 +0000128void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
129 CheckerContext &C) const {
130 const GRState *State = C.getState();
131 const Expr *Callee = CE->getCallee();
132 SVal L = State->getSVal(Callee);
133
134 const FunctionDecl *funDecl = L.getAsFunctionDecl();
135 if (!funDecl)
136 return;
137 IdentifierInfo *funI = funDecl->getIdentifier();
138 if (!funI)
139 return;
140 StringRef funName = funI->getName();
141
142 // If a value has been freed, remove from the list.
Anna Zaks083fcb22011-08-04 17:28:06 +0000143 unsigned idx = getTrackedFunctionIndex(funName, false);
144 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000145 return;
146
Anna Zaks083fcb22011-08-04 17:28:06 +0000147 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks08551b52011-08-04 00:31:38 +0000148 const MemRegion *Arg = State->getSVal(ArgExpr).getAsRegion();
149 if (!Arg)
150 return;
151
152 // If trying to free data which has not been allocated yet, report as bug.
Anna Zaks083fcb22011-08-04 17:28:06 +0000153 const AllocationState *AS = State->get<AllocatedData>(Arg);
154 if (!AS) {
Anna Zaks08551b52011-08-04 00:31:38 +0000155 // It is possible that this is a false positive - the argument might
156 // have entered as an enclosing function parameter.
157 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000158 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000159
Anna Zaks08551b52011-08-04 00:31:38 +0000160 ExplodedNode *N = C.generateNode(State);
161 if (!N)
162 return;
163 initBugType();
164 RangedBugReport *Report = new RangedBugReport(*BT,
165 "Trying to free data which has not been allocated.", N);
166 Report->addRange(ArgExpr->getSourceRange());
167 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000168 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000169 }
Anna Zaks08551b52011-08-04 00:31:38 +0000170
171 // Continue exploring from the new state.
Anna Zaks083fcb22011-08-04 17:28:06 +0000172 assert(FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx == idx &&
173 "Allocator should match the deallocator");
Anna Zaks08551b52011-08-04 00:31:38 +0000174 State = State->remove<AllocatedData>(Arg);
175 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000176}
177
178void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
179 CheckerContext &C) const {
180 const GRState *State = C.getState();
181 const Expr *Callee = CE->getCallee();
182 SVal L = State->getSVal(Callee);
183 StoreManager& SM = C.getStoreManager();
184
185 const FunctionDecl *funDecl = L.getAsFunctionDecl();
186 if (!funDecl)
187 return;
188 IdentifierInfo *funI = funDecl->getIdentifier();
189 if (!funI)
190 return;
191 StringRef funName = funI->getName();
192
193 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000194 unsigned idx = getTrackedFunctionIndex(funName, true);
195 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000196 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000197
Anna Zaks083fcb22011-08-04 17:28:06 +0000198 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
199 SVal Arg = State->getSVal(ArgExpr);
Anna Zaks08551b52011-08-04 00:31:38 +0000200 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&Arg)) {
201 // Add the symbolic value, which represents the location of the allocated
202 // data, to the set.
203 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
204 // If this is not a region, it can be:
205 // - unknown (cannot reason about it)
206 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000207 // - constant (null - should not be tracked,
208 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000209 // - goto (should be reported by other checker)
210 if (!V)
211 return;
Anna Zakse68b5f12011-08-02 17:11:03 +0000212
Anna Zaks083fcb22011-08-04 17:28:06 +0000213 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx));
Anna Zakse68b5f12011-08-02 17:11:03 +0000214
Anna Zaks08551b52011-08-04 00:31:38 +0000215 // We only need to track the value if the function returned noErr(0), so
216 // bind the return value of the function to 0.
217 SValBuilder &Builder = C.getSValBuilder();
218 SVal ZeroVal = Builder.makeZeroVal(Builder.getContext().CharTy);
219 State = State->BindExpr(CE, ZeroVal);
220 assert(State);
221
222 // Proceed from the new state.
223 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000224 }
225}
226
227void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
228 CheckerContext &C) const {
229 const Expr *retExpr = S->getRetValue();
230 if (!retExpr)
231 return;
232
233 // Check if the value is escaping through the return.
234 const GRState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000235 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000236 if (!V)
237 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000238 state = state->remove<AllocatedData>(V);
Anna Zaksf57be282011-08-01 22:40:01 +0000239
Anna Zaks03826aa2011-08-04 00:26:57 +0000240 // Proceed from the new state.
241 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000242}
243
244void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000245 ExprEngine &Eng) const {
Anna Zaksf57be282011-08-01 22:40:01 +0000246 const GRState *state = B.getState();
247 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks03826aa2011-08-04 00:26:57 +0000248 ExplodedNode *N = B.generateNode(state);
249 if (!N)
250 return;
251 initBugType();
Anna Zaksf57be282011-08-01 22:40:01 +0000252
253 // Anything which has been allocated but not freed (nor escaped) will be
254 // found here, so report it.
Anna Zaks03826aa2011-08-04 00:26:57 +0000255 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
256 RangedBugReport *Report = new RangedBugReport(*BT,
257 "Missing a call to SecKeychainItemFreeContent.", N);
258 // TODO: The report has to mention the expression which contains the
259 // allocated content as well as the point at which it has been allocated.
260 // Currently, the next line is useless.
261 Report->addRange(I->second.Address->getSourceRange());
262 Eng.getBugReporter().EmitReport(Report);
Anna Zaksf57be282011-08-01 22:40:01 +0000263 }
264}
265
266void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
267 mgr.registerChecker<MacOSKeychainAPIChecker>();
268}