1 //== PutenvWithAutoChecker.cpp --------------------------------- -*- 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 // This file defines PutenvWithAutoChecker which finds calls of ``putenv``
10 // function with automatic variable as the argument.
11 // https://wiki.sei.cmu.edu/confluence/x/6NYxBQ
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "../AllocationState.h"
16 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 class PutenvWithAutoChecker : public Checker<check::PostCall> {
28 private:
29   BugType BT{this, "'putenv' function should not be called with auto variables",
30              categories::SecurityError};
31   const CallDescription Putenv{"putenv", 1};
32 
33 public:
34   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
35 };
36 
37 void PutenvWithAutoChecker::checkPostCall(const CallEvent &Call,
38                                           CheckerContext &C) const {
39   if (!Call.isCalled(Putenv))
40     return;
41 
42   SVal ArgV = Call.getArgSVal(0);
43   const Expr *ArgExpr = Call.getArgExpr(0);
44   const MemSpaceRegion *MSR = ArgV.getAsRegion()->getMemorySpace();
45 
46   if (!isa<StackSpaceRegion>(MSR))
47     return;
48 
49   StringRef ErrorMsg = "The 'putenv' function should not be called with "
50                        "arguments that have automatic storage";
51   ExplodedNode *N = C.generateErrorNode();
52   auto Report = std::make_unique<PathSensitiveBugReport>(BT, ErrorMsg, N);
53 
54   // Track the argument.
55   bugreporter::trackExpressionValue(Report->getErrorNode(), ArgExpr, *Report);
56 
57   C.emitReport(std::move(Report));
58 }
59 
60 void ento::registerPutenvWithAuto(CheckerManager &Mgr) {
61   Mgr.registerChecker<PutenvWithAutoChecker>();
62 }
63 
64 bool ento::shouldRegisterPutenvWithAuto(const LangOptions &) { return true; }
65