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