1*0b57cec5SDimitry Andric //== CStringSyntaxChecker.cpp - CoreFoundation containers API *- C++ -*-==//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // An AST checker that looks for common pitfalls when using C string APIs.
10*0b57cec5SDimitry Andric //  - Identifies erroneous patterns in the last argument to strncat - the number
11*0b57cec5SDimitry Andric //    of bytes to copy.
12*0b57cec5SDimitry Andric //
13*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15*0b57cec5SDimitry Andric #include "clang/AST/Expr.h"
16*0b57cec5SDimitry Andric #include "clang/AST/OperationKinds.h"
17*0b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
18*0b57cec5SDimitry Andric #include "clang/Analysis/AnalysisDeclContext.h"
19*0b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
20*0b57cec5SDimitry Andric #include "clang/Basic/TypeTraits.h"
21*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
22*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
23*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
24*0b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
26*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
27*0b57cec5SDimitry Andric 
28*0b57cec5SDimitry Andric using namespace clang;
29*0b57cec5SDimitry Andric using namespace ento;
30*0b57cec5SDimitry Andric 
31*0b57cec5SDimitry Andric namespace {
32*0b57cec5SDimitry Andric class WalkAST: public StmtVisitor<WalkAST> {
33*0b57cec5SDimitry Andric   const CheckerBase *Checker;
34*0b57cec5SDimitry Andric   BugReporter &BR;
35*0b57cec5SDimitry Andric   AnalysisDeclContext* AC;
36*0b57cec5SDimitry Andric 
37*0b57cec5SDimitry Andric   /// Check if two expressions refer to the same declaration.
sameDecl(const Expr * A1,const Expr * A2)38*0b57cec5SDimitry Andric   bool sameDecl(const Expr *A1, const Expr *A2) {
39*0b57cec5SDimitry Andric     if (const auto *D1 = dyn_cast<DeclRefExpr>(A1->IgnoreParenCasts()))
40*0b57cec5SDimitry Andric       if (const auto *D2 = dyn_cast<DeclRefExpr>(A2->IgnoreParenCasts()))
41*0b57cec5SDimitry Andric         return D1->getDecl() == D2->getDecl();
42*0b57cec5SDimitry Andric     return false;
43*0b57cec5SDimitry Andric   }
44*0b57cec5SDimitry Andric 
45*0b57cec5SDimitry Andric   /// Check if the expression E is a sizeof(WithArg).
isSizeof(const Expr * E,const Expr * WithArg)46*0b57cec5SDimitry Andric   bool isSizeof(const Expr *E, const Expr *WithArg) {
47*0b57cec5SDimitry Andric     if (const auto *UE = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
48*0b57cec5SDimitry Andric       if (UE->getKind() == UETT_SizeOf && !UE->isArgumentType())
49*0b57cec5SDimitry Andric         return sameDecl(UE->getArgumentExpr(), WithArg);
50*0b57cec5SDimitry Andric     return false;
51*0b57cec5SDimitry Andric   }
52*0b57cec5SDimitry Andric 
53*0b57cec5SDimitry Andric   /// Check if the expression E is a strlen(WithArg).
isStrlen(const Expr * E,const Expr * WithArg)54*0b57cec5SDimitry Andric   bool isStrlen(const Expr *E, const Expr *WithArg) {
55*0b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<CallExpr>(E)) {
56*0b57cec5SDimitry Andric       const FunctionDecl *FD = CE->getDirectCallee();
57*0b57cec5SDimitry Andric       if (!FD)
58*0b57cec5SDimitry Andric         return false;
59*0b57cec5SDimitry Andric       return (CheckerContext::isCLibraryFunction(FD, "strlen") &&
60*0b57cec5SDimitry Andric               sameDecl(CE->getArg(0), WithArg));
61*0b57cec5SDimitry Andric     }
62*0b57cec5SDimitry Andric     return false;
63*0b57cec5SDimitry Andric   }
64*0b57cec5SDimitry Andric 
65*0b57cec5SDimitry Andric   /// Check if the expression is an integer literal with value 1.
isOne(const Expr * E)66*0b57cec5SDimitry Andric   bool isOne(const Expr *E) {
67*0b57cec5SDimitry Andric     if (const auto *IL = dyn_cast<IntegerLiteral>(E))
68*0b57cec5SDimitry Andric       return (IL->getValue().isIntN(1));
69*0b57cec5SDimitry Andric     return false;
70*0b57cec5SDimitry Andric   }
71*0b57cec5SDimitry Andric 
getPrintableName(const Expr * E)72*0b57cec5SDimitry Andric   StringRef getPrintableName(const Expr *E) {
73*0b57cec5SDimitry Andric     if (const auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
74*0b57cec5SDimitry Andric       return D->getDecl()->getName();
75*0b57cec5SDimitry Andric     return StringRef();
76*0b57cec5SDimitry Andric   }
77*0b57cec5SDimitry Andric 
78*0b57cec5SDimitry Andric   /// Identify erroneous patterns in the last argument to strncat - the number
79*0b57cec5SDimitry Andric   /// of bytes to copy.
80*0b57cec5SDimitry Andric   bool containsBadStrncatPattern(const CallExpr *CE);
81*0b57cec5SDimitry Andric 
82*0b57cec5SDimitry Andric   /// Identify erroneous patterns in the last argument to strlcpy - the number
83*0b57cec5SDimitry Andric   /// of bytes to copy.
84*0b57cec5SDimitry Andric   /// The bad pattern checked is when the size is known
85*0b57cec5SDimitry Andric   /// to be larger than the destination can handle.
86*0b57cec5SDimitry Andric   ///   char dst[2];
87*0b57cec5SDimitry Andric   ///   size_t cpy = 4;
88*0b57cec5SDimitry Andric   ///   strlcpy(dst, "abcd", sizeof("abcd") - 1);
89*0b57cec5SDimitry Andric   ///   strlcpy(dst, "abcd", 4);
90*0b57cec5SDimitry Andric   ///   strlcpy(dst + 3, "abcd", 2);
91*0b57cec5SDimitry Andric   ///   strlcpy(dst, "abcd", cpy);
92*0b57cec5SDimitry Andric   /// Identify erroneous patterns in the last argument to strlcat - the number
93*0b57cec5SDimitry Andric   /// of bytes to copy.
94*0b57cec5SDimitry Andric   /// The bad pattern checked is when the last argument is basically
95*0b57cec5SDimitry Andric   /// pointing to the destination buffer size or argument larger or
96*0b57cec5SDimitry Andric   /// equal to.
97*0b57cec5SDimitry Andric   ///   char dst[2];
98*0b57cec5SDimitry Andric   ///   strlcat(dst, src2, sizeof(dst));
99*0b57cec5SDimitry Andric   ///   strlcat(dst, src2, 2);
100*0b57cec5SDimitry Andric   ///   strlcat(dst, src2, 10);
101*0b57cec5SDimitry Andric   bool containsBadStrlcpyStrlcatPattern(const CallExpr *CE);
102*0b57cec5SDimitry Andric 
103*0b57cec5SDimitry Andric public:
WalkAST(const CheckerBase * Checker,BugReporter & BR,AnalysisDeclContext * AC)104*0b57cec5SDimitry Andric   WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
105*0b57cec5SDimitry Andric       : Checker(Checker), BR(BR), AC(AC) {}
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric   // Statement visitor methods.
108*0b57cec5SDimitry Andric   void VisitChildren(Stmt *S);
VisitStmt(Stmt * S)109*0b57cec5SDimitry Andric   void VisitStmt(Stmt *S) {
110*0b57cec5SDimitry Andric     VisitChildren(S);
111*0b57cec5SDimitry Andric   }
112*0b57cec5SDimitry Andric   void VisitCallExpr(CallExpr *CE);
113*0b57cec5SDimitry Andric };
114*0b57cec5SDimitry Andric } // end anonymous namespace
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric // The correct size argument should look like following:
117*0b57cec5SDimitry Andric //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
118*0b57cec5SDimitry Andric // We look for the following anti-patterns:
119*0b57cec5SDimitry Andric //   - strncat(dst, src, sizeof(dst) - strlen(dst));
120*0b57cec5SDimitry Andric //   - strncat(dst, src, sizeof(dst) - 1);
121*0b57cec5SDimitry Andric //   - strncat(dst, src, sizeof(dst));
containsBadStrncatPattern(const CallExpr * CE)122*0b57cec5SDimitry Andric bool WalkAST::containsBadStrncatPattern(const CallExpr *CE) {
123*0b57cec5SDimitry Andric   if (CE->getNumArgs() != 3)
124*0b57cec5SDimitry Andric     return false;
125*0b57cec5SDimitry Andric   const Expr *DstArg = CE->getArg(0);
126*0b57cec5SDimitry Andric   const Expr *SrcArg = CE->getArg(1);
127*0b57cec5SDimitry Andric   const Expr *LenArg = CE->getArg(2);
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric   // Identify wrong size expressions, which are commonly used instead.
130*0b57cec5SDimitry Andric   if (const auto *BE = dyn_cast<BinaryOperator>(LenArg->IgnoreParenCasts())) {
131*0b57cec5SDimitry Andric     // - sizeof(dst) - strlen(dst)
132*0b57cec5SDimitry Andric     if (BE->getOpcode() == BO_Sub) {
133*0b57cec5SDimitry Andric       const Expr *L = BE->getLHS();
134*0b57cec5SDimitry Andric       const Expr *R = BE->getRHS();
135*0b57cec5SDimitry Andric       if (isSizeof(L, DstArg) && isStrlen(R, DstArg))
136*0b57cec5SDimitry Andric         return true;
137*0b57cec5SDimitry Andric 
138*0b57cec5SDimitry Andric       // - sizeof(dst) - 1
139*0b57cec5SDimitry Andric       if (isSizeof(L, DstArg) && isOne(R->IgnoreParenCasts()))
140*0b57cec5SDimitry Andric         return true;
141*0b57cec5SDimitry Andric     }
142*0b57cec5SDimitry Andric   }
143*0b57cec5SDimitry Andric   // - sizeof(dst)
144*0b57cec5SDimitry Andric   if (isSizeof(LenArg, DstArg))
145*0b57cec5SDimitry Andric     return true;
146*0b57cec5SDimitry Andric 
147*0b57cec5SDimitry Andric   // - sizeof(src)
148*0b57cec5SDimitry Andric   if (isSizeof(LenArg, SrcArg))
149*0b57cec5SDimitry Andric     return true;
150*0b57cec5SDimitry Andric   return false;
151*0b57cec5SDimitry Andric }
152*0b57cec5SDimitry Andric 
containsBadStrlcpyStrlcatPattern(const CallExpr * CE)153*0b57cec5SDimitry Andric bool WalkAST::containsBadStrlcpyStrlcatPattern(const CallExpr *CE) {
154*0b57cec5SDimitry Andric   if (CE->getNumArgs() != 3)
155*0b57cec5SDimitry Andric     return false;
156*0b57cec5SDimitry Andric   const Expr *DstArg = CE->getArg(0);
157*0b57cec5SDimitry Andric   const Expr *LenArg = CE->getArg(2);
158*0b57cec5SDimitry Andric 
159*0b57cec5SDimitry Andric   const auto *DstArgDRE = dyn_cast<DeclRefExpr>(DstArg->IgnoreParenImpCasts());
160*0b57cec5SDimitry Andric   const auto *LenArgDRE =
161*0b57cec5SDimitry Andric       dyn_cast<DeclRefExpr>(LenArg->IgnoreParenLValueCasts());
162*0b57cec5SDimitry Andric   uint64_t DstOff = 0;
163*0b57cec5SDimitry Andric   if (isSizeof(LenArg, DstArg))
164*0b57cec5SDimitry Andric     return false;
165*0b57cec5SDimitry Andric 
166*0b57cec5SDimitry Andric   // - size_t dstlen = sizeof(dst)
167*0b57cec5SDimitry Andric   if (LenArgDRE) {
168*0b57cec5SDimitry Andric     const auto *LenArgVal = dyn_cast<VarDecl>(LenArgDRE->getDecl());
169*0b57cec5SDimitry Andric     // If it's an EnumConstantDecl instead, then we're missing out on something.
170*0b57cec5SDimitry Andric     if (!LenArgVal) {
171*0b57cec5SDimitry Andric       assert(isa<EnumConstantDecl>(LenArgDRE->getDecl()));
172*0b57cec5SDimitry Andric       return false;
173*0b57cec5SDimitry Andric     }
174*0b57cec5SDimitry Andric     if (LenArgVal->getInit())
175*0b57cec5SDimitry Andric       LenArg = LenArgVal->getInit();
176*0b57cec5SDimitry Andric   }
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   // - integral value
179*0b57cec5SDimitry Andric   // We try to figure out if the last argument is possibly longer
180*0b57cec5SDimitry Andric   // than the destination can possibly handle if its size can be defined.
181*0b57cec5SDimitry Andric   if (const auto *IL = dyn_cast<IntegerLiteral>(LenArg->IgnoreParenImpCasts())) {
182*0b57cec5SDimitry Andric     uint64_t ILRawVal = IL->getValue().getZExtValue();
183*0b57cec5SDimitry Andric 
184*0b57cec5SDimitry Andric     // Case when there is pointer arithmetic on the destination buffer
185*0b57cec5SDimitry Andric     // especially when we offset from the base decreasing the
186*0b57cec5SDimitry Andric     // buffer length accordingly.
187*0b57cec5SDimitry Andric     if (!DstArgDRE) {
188*0b57cec5SDimitry Andric       if (const auto *BE =
189*0b57cec5SDimitry Andric               dyn_cast<BinaryOperator>(DstArg->IgnoreParenImpCasts())) {
190*0b57cec5SDimitry Andric         DstArgDRE = dyn_cast<DeclRefExpr>(BE->getLHS()->IgnoreParenImpCasts());
191*0b57cec5SDimitry Andric         if (BE->getOpcode() == BO_Add) {
192*0b57cec5SDimitry Andric           if ((IL = dyn_cast<IntegerLiteral>(BE->getRHS()->IgnoreParenImpCasts()))) {
193*0b57cec5SDimitry Andric             DstOff = IL->getValue().getZExtValue();
194*0b57cec5SDimitry Andric           }
195*0b57cec5SDimitry Andric         }
196*0b57cec5SDimitry Andric       }
197*0b57cec5SDimitry Andric     }
198*0b57cec5SDimitry Andric     if (DstArgDRE) {
199*0b57cec5SDimitry Andric       if (const auto *Buffer =
200*0b57cec5SDimitry Andric               dyn_cast<ConstantArrayType>(DstArgDRE->getType())) {
201*0b57cec5SDimitry Andric         ASTContext &C = BR.getContext();
202*0b57cec5SDimitry Andric         uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
203*0b57cec5SDimitry Andric         auto RemainingBufferLen = BufferLen - DstOff;
204*0b57cec5SDimitry Andric         if (RemainingBufferLen < ILRawVal)
205*0b57cec5SDimitry Andric           return true;
206*0b57cec5SDimitry Andric       }
207*0b57cec5SDimitry Andric     }
208*0b57cec5SDimitry Andric   }
209*0b57cec5SDimitry Andric 
210*0b57cec5SDimitry Andric   return false;
211*0b57cec5SDimitry Andric }
212*0b57cec5SDimitry Andric 
VisitCallExpr(CallExpr * CE)213*0b57cec5SDimitry Andric void WalkAST::VisitCallExpr(CallExpr *CE) {
214*0b57cec5SDimitry Andric   const FunctionDecl *FD = CE->getDirectCallee();
215*0b57cec5SDimitry Andric   if (!FD)
216*0b57cec5SDimitry Andric     return;
217*0b57cec5SDimitry Andric 
218*0b57cec5SDimitry Andric   if (CheckerContext::isCLibraryFunction(FD, "strncat")) {
219*0b57cec5SDimitry Andric     if (containsBadStrncatPattern(CE)) {
220*0b57cec5SDimitry Andric       const Expr *DstArg = CE->getArg(0);
221*0b57cec5SDimitry Andric       const Expr *LenArg = CE->getArg(2);
222*0b57cec5SDimitry Andric       PathDiagnosticLocation Loc =
223*0b57cec5SDimitry Andric         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
224*0b57cec5SDimitry Andric 
225*0b57cec5SDimitry Andric       StringRef DstName = getPrintableName(DstArg);
226*0b57cec5SDimitry Andric 
227*0b57cec5SDimitry Andric       SmallString<256> S;
228*0b57cec5SDimitry Andric       llvm::raw_svector_ostream os(S);
229*0b57cec5SDimitry Andric       os << "Potential buffer overflow. ";
230*0b57cec5SDimitry Andric       if (!DstName.empty()) {
231*0b57cec5SDimitry Andric         os << "Replace with 'sizeof(" << DstName << ") "
232*0b57cec5SDimitry Andric               "- strlen(" << DstName <<") - 1'";
233*0b57cec5SDimitry Andric         os << " or u";
234*0b57cec5SDimitry Andric       } else
235*0b57cec5SDimitry Andric         os << "U";
236*0b57cec5SDimitry Andric       os << "se a safer 'strlcat' API";
237*0b57cec5SDimitry Andric 
238*0b57cec5SDimitry Andric       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
239*0b57cec5SDimitry Andric                          "C String API", os.str(), Loc,
240*0b57cec5SDimitry Andric                          LenArg->getSourceRange());
241*0b57cec5SDimitry Andric     }
242*0b57cec5SDimitry Andric   } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy") ||
243*0b57cec5SDimitry Andric              CheckerContext::isCLibraryFunction(FD, "strlcat")) {
244*0b57cec5SDimitry Andric     if (containsBadStrlcpyStrlcatPattern(CE)) {
245*0b57cec5SDimitry Andric       const Expr *DstArg = CE->getArg(0);
246*0b57cec5SDimitry Andric       const Expr *LenArg = CE->getArg(2);
247*0b57cec5SDimitry Andric       PathDiagnosticLocation Loc =
248*0b57cec5SDimitry Andric         PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
249*0b57cec5SDimitry Andric 
250*0b57cec5SDimitry Andric       StringRef DstName = getPrintableName(DstArg);
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric       SmallString<256> S;
253*0b57cec5SDimitry Andric       llvm::raw_svector_ostream os(S);
254*0b57cec5SDimitry Andric       os << "The third argument allows to potentially copy more bytes than it should. ";
255*0b57cec5SDimitry Andric       os << "Replace with the value ";
256*0b57cec5SDimitry Andric       if (!DstName.empty())
257*0b57cec5SDimitry Andric           os << "sizeof(" << DstName << ")";
258*0b57cec5SDimitry Andric       else
259*0b57cec5SDimitry Andric           os << "sizeof(<destination buffer>)";
260*0b57cec5SDimitry Andric       os << " or lower";
261*0b57cec5SDimitry Andric 
262*0b57cec5SDimitry Andric       BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
263*0b57cec5SDimitry Andric               "C String API", os.str(), Loc,
264*0b57cec5SDimitry Andric               LenArg->getSourceRange());
265*0b57cec5SDimitry Andric     }
266*0b57cec5SDimitry Andric   }
267*0b57cec5SDimitry Andric 
268*0b57cec5SDimitry Andric   // Recurse and check children.
269*0b57cec5SDimitry Andric   VisitChildren(CE);
270*0b57cec5SDimitry Andric }
271*0b57cec5SDimitry Andric 
VisitChildren(Stmt * S)272*0b57cec5SDimitry Andric void WalkAST::VisitChildren(Stmt *S) {
273*0b57cec5SDimitry Andric   for (Stmt *Child : S->children())
274*0b57cec5SDimitry Andric     if (Child)
275*0b57cec5SDimitry Andric       Visit(Child);
276*0b57cec5SDimitry Andric }
277*0b57cec5SDimitry Andric 
278*0b57cec5SDimitry Andric namespace {
279*0b57cec5SDimitry Andric class CStringSyntaxChecker: public Checker<check::ASTCodeBody> {
280*0b57cec5SDimitry Andric public:
281*0b57cec5SDimitry Andric 
checkASTCodeBody(const Decl * D,AnalysisManager & Mgr,BugReporter & BR) const282*0b57cec5SDimitry Andric   void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
283*0b57cec5SDimitry Andric       BugReporter &BR) const {
284*0b57cec5SDimitry Andric     WalkAST walker(this, BR, Mgr.getAnalysisDeclContext(D));
285*0b57cec5SDimitry Andric     walker.Visit(D->getBody());
286*0b57cec5SDimitry Andric   }
287*0b57cec5SDimitry Andric };
288 }
289 
registerCStringSyntaxChecker(CheckerManager & mgr)290 void ento::registerCStringSyntaxChecker(CheckerManager &mgr) {
291   mgr.registerChecker<CStringSyntaxChecker>();
292 }
293 
shouldRegisterCStringSyntaxChecker(const CheckerManager & mgr)294 bool ento::shouldRegisterCStringSyntaxChecker(const CheckerManager &mgr) {
295   return true;
296 }
297