CStringSyntaxChecker.cpp 9.8 KB

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