blob: 7fd0e516072260fa173352f9134c644315631d7e [file] [log] [blame]
Anna Zaksf57be282011-08-01 22:40:01 +00001//==--- MacOSKeychainAPIChecker.cpp -----------------------------------*- C++ -*-==//
2//
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:
41 static const unsigned InvalidParamVal = 100000;
42
43 /// Given the function name, returns the index of the parameter which will
44 /// be allocated as a result of the call.
45 unsigned getAllocatingFunctionParam(StringRef Name) const {
46 if (Name == "SecKeychainItemCopyContent")
47 return 4;
48 if (Name == "SecKeychainFindGenericPassword")
49 return 6;
50 if (Name == "SecKeychainFindInternetPassword")
51 return 13;
52 return InvalidParamVal;
53 }
54
55 /// Given the function name, returns the index of the parameter which will
56 /// be freed by the function.
57 unsigned getDeallocatingFunctionParam(StringRef Name) const {
58 if (Name == "SecKeychainItemFreeContent")
59 return 1;
60 return InvalidParamVal;
61 }
Anna Zaks03826aa2011-08-04 00:26:57 +000062
63 inline void initBugType() const {
64 if (!BT)
65 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
66 }
Anna Zaksf57be282011-08-01 22:40:01 +000067};
68}
69
Anna Zaks03826aa2011-08-04 00:26:57 +000070struct AllocationInfo {
71 const Expr *Address;
72
73 AllocationInfo(const Expr *E) : Address(E) {}
74 bool operator==(const AllocationInfo &X) const {
75 return Address == X.Address;
76 }
77 void Profile(llvm::FoldingSetNodeID &ID) const {
78 ID.AddPointer(Address);
79 }
80};
81
Anna Zaksf57be282011-08-01 22:40:01 +000082// GRState traits to store the currently allocated (and not yet freed) symbols.
Anna Zaks03826aa2011-08-04 00:26:57 +000083typedef llvm::ImmutableMap<const MemRegion*, AllocationInfo> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +000084
85namespace { struct AllocatedData {}; }
86namespace clang { namespace ento {
87template<> struct GRStateTrait<AllocatedData>
88 : public GRStatePartialTrait<AllocatedSetTy > {
89 static void *GDMIndex() { static int index = 0; return &index; }
90};
91}}
92
Anna Zaks03826aa2011-08-04 00:26:57 +000093static bool isEnclosingFunctionParam(const Expr *E) {
94 E = E->IgnoreParenCasts();
95 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
96 const ValueDecl *VD = DRE->getDecl();
97 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
98 return true;
99 }
100 return false;
101}
102
Anna Zaksf57be282011-08-01 22:40:01 +0000103void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
104 CheckerContext &C) const {
105 const GRState *State = C.getState();
106 const Expr *Callee = CE->getCallee();
107 SVal L = State->getSVal(Callee);
108
109 const FunctionDecl *funDecl = L.getAsFunctionDecl();
110 if (!funDecl)
111 return;
112 IdentifierInfo *funI = funDecl->getIdentifier();
113 if (!funI)
114 return;
115 StringRef funName = funI->getName();
116
117 // If a value has been freed, remove from the list.
118 unsigned idx = getDeallocatingFunctionParam(funName);
119 if (idx != InvalidParamVal) {
Anna Zaks03826aa2011-08-04 00:26:57 +0000120 const Expr *ArgExpr = CE->getArg(idx);
121 const MemRegion *Arg = State->getSVal(ArgExpr).getAsRegion();
122 if (!Arg)
Anna Zaksf57be282011-08-01 22:40:01 +0000123 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000124
125 // If trying to free data which has not been allocated yet, report as bug.
126 if (State->get<AllocatedData>(Arg) == 0) {
127 // It is possible that this is a false positive - the argument might
128 // have entered as an enclosing function parameter.
129 if (isEnclosingFunctionParam(ArgExpr))
130 return;
131
132 ExplodedNode *N = C.generateNode(State);
133 if (!N)
134 return;
135 initBugType();
136 RangedBugReport *Report = new RangedBugReport(*BT,
137 "Trying to free data which has not been allocated.", N);
138 Report->addRange(ArgExpr->getSourceRange());
139 C.EmitReport(Report);
Anna Zaksf57be282011-08-01 22:40:01 +0000140 }
Anna Zaks03826aa2011-08-04 00:26:57 +0000141
142 // Continue exploring from the new state.
143 State = State->remove<AllocatedData>(Arg);
Anna Zaksf57be282011-08-01 22:40:01 +0000144 C.addTransition(State);
145 }
146}
147
148void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
149 CheckerContext &C) const {
150 const GRState *State = C.getState();
151 const Expr *Callee = CE->getCallee();
152 SVal L = State->getSVal(Callee);
153 StoreManager& SM = C.getStoreManager();
154
155 const FunctionDecl *funDecl = L.getAsFunctionDecl();
156 if (!funDecl)
157 return;
158 IdentifierInfo *funI = funDecl->getIdentifier();
159 if (!funI)
160 return;
161 StringRef funName = funI->getName();
162
163 // If a value has been allocated, add it to the set for tracking.
164 unsigned idx = getAllocatingFunctionParam(funName);
165 if (idx != InvalidParamVal) {
Anna Zaks03826aa2011-08-04 00:26:57 +0000166 SVal Arg = State->getSVal(CE->getArg(idx));
167 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&Arg)) {
Anna Zakse68b5f12011-08-02 17:11:03 +0000168 // Add the symbolic value, which represents the location of the allocated
169 // data, to the set.
Anna Zaks03826aa2011-08-04 00:26:57 +0000170 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
171 // If this is not a region, it can be:
172 // - unknown (cannot reason about it)
173 // - undefined (already reported by other checker)
174 // - constant (null - should not be tracked, other - report a warning?)
175 // - goto (should be reported by other checker)
Anna Zaksf57be282011-08-01 22:40:01 +0000176 if (!V)
177 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000178
179 State = State->set<AllocatedData>(V, AllocationInfo(CE->getArg(idx)));
Anna Zakse68b5f12011-08-02 17:11:03 +0000180
181 // We only need to track the value if the function returned noErr(0), so
182 // bind the return value of the function to 0.
183 SValBuilder &Builder = C.getSValBuilder();
184 SVal ZeroVal = Builder.makeZeroVal(Builder.getContext().CharTy);
185 State = State->BindExpr(CE, ZeroVal);
186 assert(State);
187
188 // Proceed from the new state.
Anna Zaksf57be282011-08-01 22:40:01 +0000189 C.addTransition(State);
190 }
191 }
192}
193
194void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
195 CheckerContext &C) const {
196 const Expr *retExpr = S->getRetValue();
197 if (!retExpr)
198 return;
199
200 // Check if the value is escaping through the return.
201 const GRState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000202 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000203 if (!V)
204 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000205 state = state->remove<AllocatedData>(V);
Anna Zaksf57be282011-08-01 22:40:01 +0000206
Anna Zaks03826aa2011-08-04 00:26:57 +0000207 // Proceed from the new state.
208 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000209}
210
211void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000212 ExprEngine &Eng) const {
Anna Zaksf57be282011-08-01 22:40:01 +0000213 const GRState *state = B.getState();
214 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks03826aa2011-08-04 00:26:57 +0000215 ExplodedNode *N = B.generateNode(state);
216 if (!N)
217 return;
218 initBugType();
Anna Zaksf57be282011-08-01 22:40:01 +0000219
220 // Anything which has been allocated but not freed (nor escaped) will be
221 // found here, so report it.
Anna Zaks03826aa2011-08-04 00:26:57 +0000222 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
223 RangedBugReport *Report = new RangedBugReport(*BT,
224 "Missing a call to SecKeychainItemFreeContent.", N);
225 // TODO: The report has to mention the expression which contains the
226 // allocated content as well as the point at which it has been allocated.
227 // Currently, the next line is useless.
228 Report->addRange(I->second.Address->getSourceRange());
229 Eng.getBugReporter().EmitReport(Report);
Anna Zaksf57be282011-08-01 22:40:01 +0000230 }
231}
232
233void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
234 mgr.registerChecker<MacOSKeychainAPIChecker>();
235}