blob: 7e269dc0209111bd6f095e4a4aa6831ac346e5e9 [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;
Anna Zaks76cbb752011-08-04 21:53:01 +000049 static const unsigned FunctionsToTrackSize = 6;
Anna Zaks083fcb22011-08-04 17:28:06 +000050 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
Anna Zaks76cbb752011-08-04 21:53:01 +0000108 {"SecKeychainItemCopyAttributesAndData", 5, 5}, // 4
109 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx}, // 5
Anna Zaks083fcb22011-08-04 17:28:06 +0000110};
111
112unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
113 bool IsAllocator) const {
114 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
115 ADFunctionInfo FI = FunctionsToTrack[I];
116 if (FI.Name != Name)
117 continue;
118 // Make sure the function is of the right type (allocator vs deallocator).
119 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
120 return InvalidIdx;
121 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
122 return InvalidIdx;
123
124 return I;
125 }
126 // The function is not tracked.
127 return InvalidIdx;
128}
129
Anna Zaksf57be282011-08-01 22:40:01 +0000130void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
131 CheckerContext &C) const {
132 const GRState *State = C.getState();
133 const Expr *Callee = CE->getCallee();
134 SVal L = State->getSVal(Callee);
135
136 const FunctionDecl *funDecl = L.getAsFunctionDecl();
137 if (!funDecl)
138 return;
139 IdentifierInfo *funI = funDecl->getIdentifier();
140 if (!funI)
141 return;
142 StringRef funName = funI->getName();
143
144 // If a value has been freed, remove from the list.
Anna Zaks083fcb22011-08-04 17:28:06 +0000145 unsigned idx = getTrackedFunctionIndex(funName, false);
146 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000147 return;
148
Anna Zaks083fcb22011-08-04 17:28:06 +0000149 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks08551b52011-08-04 00:31:38 +0000150 const MemRegion *Arg = State->getSVal(ArgExpr).getAsRegion();
151 if (!Arg)
152 return;
153
154 // If trying to free data which has not been allocated yet, report as bug.
Anna Zaks083fcb22011-08-04 17:28:06 +0000155 const AllocationState *AS = State->get<AllocatedData>(Arg);
156 if (!AS) {
Anna Zaks08551b52011-08-04 00:31:38 +0000157 // It is possible that this is a false positive - the argument might
158 // have entered as an enclosing function parameter.
159 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000160 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000161
Anna Zaks08551b52011-08-04 00:31:38 +0000162 ExplodedNode *N = C.generateNode(State);
163 if (!N)
164 return;
165 initBugType();
166 RangedBugReport *Report = new RangedBugReport(*BT,
167 "Trying to free data which has not been allocated.", N);
168 Report->addRange(ArgExpr->getSourceRange());
169 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000170 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000171 }
Anna Zaks08551b52011-08-04 00:31:38 +0000172
Anna Zaks76cbb752011-08-04 21:53:01 +0000173 // Check if the proper deallocator is used.
174 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
175 if (PDeallocIdx != idx) {
176 ExplodedNode *N = C.generateSink(State);
177 if (!N)
178 return;
179 initBugType();
180
181 std::string sbuf;
182 llvm::raw_string_ostream os(sbuf);
183 os << "Allocator doesn't match the deallocator: '"
184 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
185 RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
186 Report->addRange(ArgExpr->getSourceRange());
187 C.EmitReport(Report);
188 return;
189 }
190
Anna Zaks08551b52011-08-04 00:31:38 +0000191 // Continue exploring from the new state.
192 State = State->remove<AllocatedData>(Arg);
193 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000194}
195
196void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
197 CheckerContext &C) const {
198 const GRState *State = C.getState();
199 const Expr *Callee = CE->getCallee();
200 SVal L = State->getSVal(Callee);
201 StoreManager& SM = C.getStoreManager();
202
203 const FunctionDecl *funDecl = L.getAsFunctionDecl();
204 if (!funDecl)
205 return;
206 IdentifierInfo *funI = funDecl->getIdentifier();
207 if (!funI)
208 return;
209 StringRef funName = funI->getName();
210
211 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000212 unsigned idx = getTrackedFunctionIndex(funName, true);
213 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000214 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000215
Anna Zaks083fcb22011-08-04 17:28:06 +0000216 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
217 SVal Arg = State->getSVal(ArgExpr);
Anna Zaks08551b52011-08-04 00:31:38 +0000218 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&Arg)) {
219 // Add the symbolic value, which represents the location of the allocated
220 // data, to the set.
221 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
222 // If this is not a region, it can be:
223 // - unknown (cannot reason about it)
224 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000225 // - constant (null - should not be tracked,
226 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000227 // - goto (should be reported by other checker)
228 if (!V)
229 return;
Anna Zakse68b5f12011-08-02 17:11:03 +0000230
Anna Zaks08551b52011-08-04 00:31:38 +0000231 // We only need to track the value if the function returned noErr(0), so
Anna Zaks76cbb752011-08-04 21:53:01 +0000232 // bind the return value of the function to 0 and proceed from the no error
233 // state.
Anna Zaks08551b52011-08-04 00:31:38 +0000234 SValBuilder &Builder = C.getSValBuilder();
Anna Zaks76cbb752011-08-04 21:53:01 +0000235 SVal ZeroVal = Builder.makeIntVal(0, CE->getCallReturnType());
236 const GRState *NoErr = State->BindExpr(CE, ZeroVal);
237 NoErr = NoErr->set<AllocatedData>(V, AllocationState(ArgExpr, idx));
238 assert(NoErr);
239 C.addTransition(NoErr);
Anna Zaks08551b52011-08-04 00:31:38 +0000240
Anna Zaks76cbb752011-08-04 21:53:01 +0000241 // Generate a transition to explore the state space when there is an error.
242 // In this case, we do not track the allocated data.
243 SVal ReturnedError = Builder.evalBinOpNN(State, BO_NE,
244 cast<NonLoc>(ZeroVal),
245 cast<NonLoc>(State->getSVal(CE)),
246 CE->getCallReturnType());
247 const GRState *Err = State->assume(cast<NonLoc>(ReturnedError), true);
248 assert(Err);
249 C.addTransition(Err);
Anna Zaksf57be282011-08-01 22:40:01 +0000250 }
251}
252
253void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
254 CheckerContext &C) const {
255 const Expr *retExpr = S->getRetValue();
256 if (!retExpr)
257 return;
258
259 // Check if the value is escaping through the return.
260 const GRState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000261 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000262 if (!V)
263 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000264 state = state->remove<AllocatedData>(V);
Anna Zaksf57be282011-08-01 22:40:01 +0000265
Anna Zaks03826aa2011-08-04 00:26:57 +0000266 // Proceed from the new state.
267 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000268}
269
270void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000271 ExprEngine &Eng) const {
Anna Zaksf57be282011-08-01 22:40:01 +0000272 const GRState *state = B.getState();
273 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks03826aa2011-08-04 00:26:57 +0000274 ExplodedNode *N = B.generateNode(state);
275 if (!N)
276 return;
277 initBugType();
Anna Zaksf57be282011-08-01 22:40:01 +0000278
279 // Anything which has been allocated but not freed (nor escaped) will be
280 // found here, so report it.
Anna Zaks03826aa2011-08-04 00:26:57 +0000281 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks76cbb752011-08-04 21:53:01 +0000282 const ADFunctionInfo &FI = FunctionsToTrack[I->second.AllocatorIdx];
283
284 std::string sbuf;
285 llvm::raw_string_ostream os(sbuf);
286 os << "Allocated data is not released: missing a call to '"
287 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
288 RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
Anna Zaks03826aa2011-08-04 00:26:57 +0000289 // TODO: The report has to mention the expression which contains the
290 // allocated content as well as the point at which it has been allocated.
291 // Currently, the next line is useless.
292 Report->addRange(I->second.Address->getSourceRange());
293 Eng.getBugReporter().EmitReport(Report);
Anna Zaksf57be282011-08-01 22:40:01 +0000294 }
295}
296
297void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
298 mgr.registerChecker<MacOSKeychainAPIChecker>();
299}