MacOSKeychainAPIChecker.cpp revision 76cbb75ff8c1c14ad0164b602176d5d4515eb06c
1//==--- 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"
18#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19#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 > {
31  mutable llvm::OwningPtr<BugType> BT;
32
33public:
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  /// 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 = 6;
50  static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
51
52  /// Given the function name, returns the index of the allocator/deallocator
53  /// function.
54  unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const;
55
56  inline void initBugType() const {
57    if (!BT)
58      BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
59  }
60};
61}
62
63/// AllocationState is a part of the checker specific state together with the
64/// MemRegion corresponding to the allocated data.
65struct AllocationState {
66  const Expr *Address;
67  /// The index of the allocator function.
68  unsigned int AllocatorIdx;
69
70  AllocationState(const Expr *E, unsigned int Idx) : Address(E),
71                                                     AllocatorIdx(Idx) {}
72  bool operator==(const AllocationState &X) const {
73    return Address == X.Address;
74  }
75  void Profile(llvm::FoldingSetNodeID &ID) const {
76    ID.AddPointer(Address);
77    ID.AddInteger(AllocatorIdx);
78  }
79};
80
81/// GRState traits to store the currently allocated (and not yet freed) symbols.
82typedef llvm::ImmutableMap<const MemRegion*, AllocationState> AllocatedSetTy;
83
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
92static 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
102const 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    {"SecKeychainItemCopyAttributesAndData", 5, 5},             // 4
109    {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx},    // 5
110};
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
130void 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.
145  unsigned idx = getTrackedFunctionIndex(funName, false);
146  if (idx == InvalidIdx)
147    return;
148
149  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
150  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.
155  const AllocationState *AS = State->get<AllocatedData>(Arg);
156  if (!AS) {
157    // It is possible that this is a false positive - the argument might
158    // have entered as an enclosing function parameter.
159    if (isEnclosingFunctionParam(ArgExpr))
160      return;
161
162    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);
170    return;
171  }
172
173  // 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
191  // Continue exploring from the new state.
192  State = State->remove<AllocatedData>(Arg);
193  C.addTransition(State);
194}
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.
212  unsigned idx = getTrackedFunctionIndex(funName, true);
213  if (idx == InvalidIdx)
214    return;
215
216  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
217  SVal Arg = State->getSVal(ArgExpr);
218  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)
225    //  - constant (null - should not be tracked,
226    //              other constant will generate a compiler warning)
227    //  - goto (should be reported by other checker)
228    if (!V)
229      return;
230
231    // We only need to track the value if the function returned noErr(0), so
232    // bind the return value of the function to 0 and proceed from the no error
233    // state.
234    SValBuilder &Builder = C.getSValBuilder();
235    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);
240
241    // 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);
250  }
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();
261  const MemRegion *V = state->getSVal(retExpr).getAsRegion();
262  if (!V)
263    return;
264  state = state->remove<AllocatedData>(V);
265
266  // Proceed from the new state.
267  C.addTransition(state);
268}
269
270void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
271                                           ExprEngine &Eng) const {
272  const GRState *state = B.getState();
273  AllocatedSetTy AS = state->get<AllocatedData>();
274  ExplodedNode *N = B.generateNode(state);
275  if (!N)
276    return;
277  initBugType();
278
279  // Anything which has been allocated but not freed (nor escaped) will be
280  // found here, so report it.
281  for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
282    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);
289    // 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);
294  }
295}
296
297void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
298  mgr.registerChecker<MacOSKeychainAPIChecker>();
299}
300