yawanng updated this revision to Diff 101279.
yawanng added a comment.

Format changes.


https://reviews.llvm.org/D33304

Files:
  clang-tidy/CMakeLists.txt
  clang-tidy/android/AndroidTidyModule.cpp
  clang-tidy/android/CMakeLists.txt
  clang-tidy/android/FileOpenFlagCheck.cpp
  clang-tidy/android/FileOpenFlagCheck.h
  clang-tidy/plugin/CMakeLists.txt
  clang-tidy/tool/CMakeLists.txt
  clang-tidy/tool/ClangTidyMain.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/android-file-open-flag.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/index.rst
  test/clang-tidy/android-file-open-flag.cpp
  unittests/clang-tidy/CMakeLists.txt

Index: unittests/clang-tidy/CMakeLists.txt
===================================================================
--- unittests/clang-tidy/CMakeLists.txt
+++ unittests/clang-tidy/CMakeLists.txt
@@ -25,6 +25,7 @@
   clangFrontend
   clangLex
   clangTidy
+  clangTidyAndroidModule
   clangTidyGoogleModule
   clangTidyLLVMModule
   clangTidyMiscModule
Index: test/clang-tidy/android-file-open-flag.cpp
===================================================================
--- /dev/null
+++ test/clang-tidy/android-file-open-flag.cpp
@@ -0,0 +1,104 @@
+// RUN: %check_clang_tidy %s android-file-open-flag %t
+
+#define O_RDWR 1
+#define O_EXCL 2
+#define __O_CLOEXEC 3
+#define O_CLOEXEC __O_CLOEXEC
+
+extern "C" int open(const char *fn, int flags, ...);
+extern "C" int open64(const char *fn, int flags, ...);
+extern "C" int openat(int dirfd, const char *pathname, int flags, ...);
+
+void a() {
+  open("filename", O_RDWR);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: open should use O_CLOEXEC where possible. [android-file-open-flag]
+  // CHECK-FIXES: O_RDWR | O_CLOEXEC
+  open("filename", O_RDWR | O_EXCL);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: open should use O_CLOEXEC where
+  // CHECK-FIXES: O_RDWR | O_EXCL | O_CLOEXEC
+}
+
+void b() {
+  open64("filename", O_RDWR);
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: open64 should use O_CLOEXEC where possible. [android-file-open-flag]
+  // CHECK-FIXES: O_RDWR | O_CLOEXEC
+  open64("filename", O_RDWR | O_EXCL);
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: open64 should use O_CLOEXEC where
+  // CHECK-FIXES: O_RDWR | O_EXCL | O_CLOEXEC
+}
+
+void c() {
+  openat(0, "filename", O_RDWR);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: openat should use O_CLOEXEC where possible. [android-file-open-flag]
+  // CHECK-FIXES: O_RDWR | O_CLOEXEC
+  openat(0, "filename", O_RDWR | O_EXCL);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: openat should use O_CLOEXEC where
+  // CHECK-FIXES: O_RDWR | O_EXCL | O_CLOEXEC
+}
+
+void f() {
+  open("filename", 3);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: open should use O_CLOEXEC where possible. [android-file-open-flag]
+  // CHECK-FIXES: 3 | O_CLOEXEC
+  open64("filename", 3);
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: open64 should use O_CLOEXEC where possible. [android-file-open-flag]
+  // CHECK-FIXES: 3 | O_CLOEXEC
+  openat(0, "filename", 3);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: openat should use O_CLOEXEC where possible. [android-file-open-flag]
+  // CHECK-FIXES: 3 | O_CLOEXEC
+
+  int flag = 3;
+  open("filename", flag);
+  // CHECK-MESSAGES-NOT: warning:
+  open64("filename", flag);
+  // CHECK-MESSAGES-NOT: warning:
+  openat(0, "filename", flag);
+  // CHECK-MESSAGES-NOT: warning:
+}
+
+namespace i {
+int open(const char *pathname, int flags, ...);
+int open64(const char *pathname, int flags, ...);
+int openat(int dirfd, const char *pathname, int flags, ...);
+
+void d() {
+  open("filename", O_RDWR);
+  // CHECK-MESSAGES-NOT: warning:
+  open64("filename", O_RDWR);
+  // CHECK-MESSAGES-NOT: warning:
+  openat(0, "filename", O_RDWR);
+  // CHECK-MESSAGES-NOT: warning:
+}
+
+} // namespace i
+
+void e() {
+  open("filename", O_CLOEXEC);
+  // CHECK-MESSAGES-NOT: warning:
+  open("filename", O_RDWR | O_CLOEXEC);
+  // CHECK-MESSAGES-NOT: warning:
+  open64("filename", O_CLOEXEC);
+  // CHECK-MESSAGES-NOT: warning:
+  open64("filename", O_RDWR | O_CLOEXEC);
+  // CHECK-MESSAGES-NOT: warning:
+  openat(0, "filename", O_CLOEXEC);
+  // CHECK-MESSAGES-NOT: warning:
+  openat(0, "filename", O_RDWR | O_CLOEXEC);
+  // CHECK-MESSAGES-NOT: warning:
+}
+
+class G {
+public:
+  int open(const char *pathname, int flags, ...);
+  int open64(const char *pathname, int flags, ...);
+  int openat(int dirfd, const char *pathname, int flags, ...);
+
+  void h() {
+    open("filename", O_RDWR);
+    // CHECK-MESSAGES-NOT: warning:
+    open64("filename", O_RDWR);
+    // CHECK-MESSAGES-NOT: warning:
+    openat(0, "filename", O_RDWR);
+    // CHECK-MESSAGES-NOT: warning:
+  }
+};
Index: docs/clang-tidy/index.rst
===================================================================
--- docs/clang-tidy/index.rst
+++ docs/clang-tidy/index.rst
@@ -55,6 +55,7 @@
 ====================== =========================================================
 Name prefix            Description
 ====================== =========================================================
+``android``
 ``boost-``             Checks related to Boost library.
 ``cert-``              Checks related to CERT Secure Coding Guidelines.
 ``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
Index: docs/clang-tidy/checks/list.rst
===================================================================
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -4,6 +4,7 @@
 =================
 
 .. toctree::
+   android-file-open-flag
    boost-use-to-string
    cert-dcl03-c (redirects to misc-static-assert) <cert-dcl03-c>
    cert-dcl21-cpp
Index: docs/clang-tidy/checks/android-file-open-flag.rst
===================================================================
--- /dev/null
+++ docs/clang-tidy/checks/android-file-open-flag.rst
@@ -0,0 +1,24 @@
+.. title:: clang-tidy - android-file-open-flag
+
+android-file-open-flag
+======================
+
+A common source of security bugs has been code that opens file without using
+the ``O_CLOEXEC`` flag.  Without that flag, an opened sensitive file would
+remain open across a fork+exec to a lower-privileged SELinux domain, leaking
+that sensitive data Functions including ``open()``, ``openat()``, and
+``open64()`` must include ``O_CLOEXEC`` in their flags argument.
+
+Examples:
+
+.. code-block:: c++
+
+  open("filename", O_RDWR);
+  open64("filename", O_RDWR);
+  openat(0, "filename", O_RDWR);
+
+  // becomes
+
+  open("filename", O_RDWR | O_CLOEXEC);
+  open64("filename", O_RDWR | O_CLOEXEC);
+  openat(0, "filename", O_RDWR | O_CLOEXEC);
Index: docs/ReleaseNotes.rst
===================================================================
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -57,6 +57,12 @@
 Improvements to clang-tidy
 --------------------------
 
+- New `android-file-open-flag
+    <http://clang.llvm.org/extra/clang-tidy/checks/android-file-open-flag>`_ check
+
+  Checks if the required file flag ``O_CLOEXEC`` exists in ``open()``,
+  ``open64()`` and ``openat()``.
+
 - New `cert-dcl21-cpp
   <http://clang.llvm.org/extra/clang-tidy/checks/cert-dcl21-cpp.html>`_ check
 
Index: clang-tidy/tool/ClangTidyMain.cpp
===================================================================
--- clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tidy/tool/ClangTidyMain.cpp
@@ -477,6 +477,11 @@
 static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination =
     GoogleModuleAnchorSource;
 
+// This anchor is used to force the linker to link the AndroidModule.
+extern volatile int AndroidModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
+    AndroidModuleAnchorSource;
+
 // This anchor is used to force the linker to link the MiscModule.
 extern volatile int MiscModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination =
Index: clang-tidy/tool/CMakeLists.txt
===================================================================
--- clang-tidy/tool/CMakeLists.txt
+++ clang-tidy/tool/CMakeLists.txt
@@ -13,6 +13,7 @@
   clangASTMatchers
   clangBasic
   clangTidy
+  clangTidyAndroidModule
   clangTidyBoostModule
   clangTidyCERTModule
   clangTidyCppCoreGuidelinesModule
Index: clang-tidy/plugin/CMakeLists.txt
===================================================================
--- clang-tidy/plugin/CMakeLists.txt
+++ clang-tidy/plugin/CMakeLists.txt
@@ -8,6 +8,7 @@
   clangFrontend
   clangSema
   clangTidy
+  clangTidyAndroidModule
   clangTidyBoostModule
   clangTidyCERTModule
   clangTidyCppCoreGuidelinesModule
Index: clang-tidy/android/FileOpenFlagCheck.h
===================================================================
--- /dev/null
+++ clang-tidy/android/FileOpenFlagCheck.h
@@ -0,0 +1,45 @@
+//===--- FileOpenFlagCheck.h - clang-tidy----------------------------------===//
+//
+//                      The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FILE_OPEN_FLAG_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FILE_OPEN_FLAG_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+/// Finds code that opens file without using the O_CLOEXEC flag.
+///
+/// open(), openat(), and open64() had better to include O_CLOEXEC in their
+/// flags argument. Only consider simple cases that the corresponding argument
+/// is constant or binary operation OR among constants like 'O_CLOEXEC' or
+/// 'O_CLOEXEC | O_RDONLY'. No constant propagation is performed.
+///
+/// Only the symbolic 'O_CLOEXEC' macro definition is checked, not the concrete
+/// value.
+class FileOpenFlagCheck : public ClangTidyCheck {
+public:
+  FileOpenFlagCheck(StringRef Name, ClangTidyContext *Context)
+      : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  bool checkFlags(const Expr *Flags, const SourceManager &SM);
+
+  static constexpr const char *O_CLOEXEC = "O_CLOEXEC";
+};
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FILE_OPEN_FLAG_H
Index: clang-tidy/android/FileOpenFlagCheck.cpp
===================================================================
--- /dev/null
+++ clang-tidy/android/FileOpenFlagCheck.cpp
@@ -0,0 +1,111 @@
+//===--- FileOpenFlagCheck.cpp - clang-tidy--------------------------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "FileOpenFlagCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+void FileOpenFlagCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
+
+  Finder->addMatcher(
+      callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
+                                   hasParameter(0, CharPointerType),
+                                   hasParameter(1, hasType(isInteger())),
+                                   hasAnyName("open", "open64"))
+                          .bind("funcDecl")))
+          .bind("openFn"),
+      this);
+  Finder->addMatcher(
+      callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
+                                   hasParameter(0, hasType(isInteger())),
+                                   hasParameter(1, CharPointerType),
+                                   hasParameter(2, hasType(isInteger())),
+                                   hasName("openat"))
+                          .bind("funcDecl")))
+          .bind("openatFn"),
+      this);
+}
+
+void FileOpenFlagCheck::check(const MatchFinder::MatchResult &Result) {
+  const CallExpr *MatchedCall;
+  const Expr *FlagArg;
+  if ((MatchedCall = Result.Nodes.getNodeAs<CallExpr>("openFn")))
+    FlagArg = MatchedCall->getArg(1);
+  else if ((MatchedCall = Result.Nodes.getNodeAs<CallExpr>("openatFn")))
+    FlagArg = MatchedCall->getArg(2);
+  else
+    return;
+
+  const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl");
+
+  // Check the required flag.
+  SourceManager &SM = *Result.SourceManager;
+  if (checkFlags(FlagArg->IgnoreParenCasts(), SM))
+    return;
+
+  LangOptions LangOpts = getLangOpts();
+  SourceRange FlagsRange(FlagArg->getLocStart(), FlagArg->getLocEnd());
+  StringRef FlagsText = Lexer::getSourceText(
+      CharSourceRange::getTokenRange(FlagsRange), SM, LangOpts);
+  std::string ReplacementText =
+      (llvm::Twine(FlagsText) + " | " + O_CLOEXEC).str();
+  diag(FlagArg->getLocStart(), "%0 should use %1 where possible.")
+      << FD->getName() << O_CLOEXEC
+      << FixItHint::CreateReplacement(FlagsRange, ReplacementText);
+}
+
+bool FileOpenFlagCheck::checkFlags(const Expr *Flags, const SourceManager &SM) {
+  bool IsFlagIn;
+  // If the Flag is an integer constant, check it.
+  if (isa<IntegerLiteral>(Flags)) {
+    SourceLocation SL = Flags->getLocStart();
+
+    if (!SM.isMacroBodyExpansion(SL))
+      return false;
+
+    // Get the Marco name.
+    LangOptions LangOpts = getLangOpts();
+    auto Loc = SM.getFileLoc(SL);
+    std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
+    unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
+    StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
+    auto MacroName =
+        ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
+
+    IsFlagIn = (MacroName == O_CLOEXEC);
+
+  }
+  // If it's a binary OR operation.
+  else if ((isa<BinaryOperator>(Flags)) &&
+           (cast<BinaryOperator>(Flags)->getOpcode() ==
+            clang::BinaryOperatorKind::BO_Or)) {
+    IsFlagIn =
+        checkFlags(cast<BinaryOperator>(Flags)->getLHS()->IgnoreParenCasts(),
+                   SM) ||
+        checkFlags(cast<BinaryOperator>(Flags)->getRHS()->IgnoreParenCasts(),
+                   SM);
+  }
+  // Otherwise, we assume it has the flag to avoid false positive.
+  else
+    IsFlagIn = true;
+
+  return IsFlagIn;
+}
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/android/CMakeLists.txt
===================================================================
--- /dev/null
+++ clang-tidy/android/CMakeLists.txt
@@ -0,0 +1,14 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_library(clangTidyAndroidModule
+  AndroidTidyModule.cpp
+  FileOpenFlagCheck.cpp
+
+  LINK_LIBS
+  clangAST
+  clangASTMatchers
+  clangBasic
+  clangLex
+  clangTidy
+  clangTidyUtils
+  )
Index: clang-tidy/android/AndroidTidyModule.cpp
===================================================================
--- /dev/null
+++ clang-tidy/android/AndroidTidyModule.cpp
@@ -0,0 +1,40 @@
+//===--- AndroidTidyModule.cpp - clang-tidy--------------------------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "../ClangTidy.h"
+#include "../ClangTidyModule.h"
+#include "../ClangTidyModuleRegistry.h"
+#include "FileOpenFlagCheck.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+/// This module is for Android specific checks.
+class AndroidModule : public ClangTidyModule {
+public:
+  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
+    CheckFactories.registerCheck<FileOpenFlagCheck>("android-file-open-flag");
+  }
+};
+
+// Register the AndroidTidyModule using this statically initialized variable.
+static ClangTidyModuleRegistry::Add<AndroidModule>
+    X("android-module", "Adds Android platform checks.");
+
+} // namespace android
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the AndroidModule.
+volatile int AndroidModuleAnchorSource = 0;
+
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/CMakeLists.txt
===================================================================
--- clang-tidy/CMakeLists.txt
+++ clang-tidy/CMakeLists.txt
@@ -26,6 +26,7 @@
   clangToolingCore
   )
 
+add_subdirectory(android)
 add_subdirectory(boost)
 add_subdirectory(cert)
 add_subdirectory(cppcoreguidelines)
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to