1 //==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- 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 // This file defines a set of flow-insensitive security checks.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ClangSACheckers.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "clang/Analysis/AnalysisContext.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/raw_ostream.h"
24
25 using namespace clang;
26 using namespace ento;
27
isArc4RandomAvailable(const ASTContext & Ctx)28 static bool isArc4RandomAvailable(const ASTContext &Ctx) {
29 const llvm::Triple &T = Ctx.getTargetInfo().getTriple();
30 return T.getVendor() == llvm::Triple::Apple ||
31 T.getOS() == llvm::Triple::CloudABI ||
32 T.getOS() == llvm::Triple::FreeBSD ||
33 T.getOS() == llvm::Triple::NetBSD ||
34 T.getOS() == llvm::Triple::OpenBSD ||
35 T.getOS() == llvm::Triple::Bitrig ||
36 T.getOS() == llvm::Triple::DragonFly;
37 }
38
39 namespace {
40 struct ChecksFilter {
41 DefaultBool check_gets;
42 DefaultBool check_getpw;
43 DefaultBool check_mktemp;
44 DefaultBool check_mkstemp;
45 DefaultBool check_strcpy;
46 DefaultBool check_rand;
47 DefaultBool check_vfork;
48 DefaultBool check_FloatLoopCounter;
49 DefaultBool check_UncheckedReturn;
50
51 CheckName checkName_gets;
52 CheckName checkName_getpw;
53 CheckName checkName_mktemp;
54 CheckName checkName_mkstemp;
55 CheckName checkName_strcpy;
56 CheckName checkName_rand;
57 CheckName checkName_vfork;
58 CheckName checkName_FloatLoopCounter;
59 CheckName checkName_UncheckedReturn;
60 };
61
62 class WalkAST : public StmtVisitor<WalkAST> {
63 BugReporter &BR;
64 AnalysisDeclContext* AC;
65 enum { num_setids = 6 };
66 IdentifierInfo *II_setid[num_setids];
67
68 const bool CheckRand;
69 const ChecksFilter &filter;
70
71 public:
WalkAST(BugReporter & br,AnalysisDeclContext * ac,const ChecksFilter & f)72 WalkAST(BugReporter &br, AnalysisDeclContext* ac,
73 const ChecksFilter &f)
74 : BR(br), AC(ac), II_setid(),
75 CheckRand(isArc4RandomAvailable(BR.getContext())),
76 filter(f) {}
77
78 // Statement visitor methods.
79 void VisitCallExpr(CallExpr *CE);
80 void VisitForStmt(ForStmt *S);
81 void VisitCompoundStmt (CompoundStmt *S);
VisitStmt(Stmt * S)82 void VisitStmt(Stmt *S) { VisitChildren(S); }
83
84 void VisitChildren(Stmt *S);
85
86 // Helpers.
87 bool checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD);
88
89 typedef void (WalkAST::*FnCheck)(const CallExpr *, const FunctionDecl *);
90
91 // Checker-specific methods.
92 void checkLoopConditionForFloat(const ForStmt *FS);
93 void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
94 void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
95 void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
96 void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
97 void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
98 void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
99 void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
100 void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
101 void checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD);
102 void checkUncheckedReturnValue(CallExpr *CE);
103 };
104 } // end anonymous namespace
105
106 //===----------------------------------------------------------------------===//
107 // AST walking.
108 //===----------------------------------------------------------------------===//
109
VisitChildren(Stmt * S)110 void WalkAST::VisitChildren(Stmt *S) {
111 for (Stmt *Child : S->children())
112 if (Child)
113 Visit(Child);
114 }
115
VisitCallExpr(CallExpr * CE)116 void WalkAST::VisitCallExpr(CallExpr *CE) {
117 // Get the callee.
118 const FunctionDecl *FD = CE->getDirectCallee();
119
120 if (!FD)
121 return;
122
123 // Get the name of the callee. If it's a builtin, strip off the prefix.
124 IdentifierInfo *II = FD->getIdentifier();
125 if (!II) // if no identifier, not a simple C function
126 return;
127 StringRef Name = II->getName();
128 if (Name.startswith("__builtin_"))
129 Name = Name.substr(10);
130
131 // Set the evaluation function by switching on the callee name.
132 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
133 .Case("gets", &WalkAST::checkCall_gets)
134 .Case("getpw", &WalkAST::checkCall_getpw)
135 .Case("mktemp", &WalkAST::checkCall_mktemp)
136 .Case("mkstemp", &WalkAST::checkCall_mkstemp)
137 .Case("mkdtemp", &WalkAST::checkCall_mkstemp)
138 .Case("mkstemps", &WalkAST::checkCall_mkstemp)
139 .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
140 .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
141 .Case("drand48", &WalkAST::checkCall_rand)
142 .Case("erand48", &WalkAST::checkCall_rand)
143 .Case("jrand48", &WalkAST::checkCall_rand)
144 .Case("lrand48", &WalkAST::checkCall_rand)
145 .Case("mrand48", &WalkAST::checkCall_rand)
146 .Case("nrand48", &WalkAST::checkCall_rand)
147 .Case("lcong48", &WalkAST::checkCall_rand)
148 .Case("rand", &WalkAST::checkCall_rand)
149 .Case("rand_r", &WalkAST::checkCall_rand)
150 .Case("random", &WalkAST::checkCall_random)
151 .Case("vfork", &WalkAST::checkCall_vfork)
152 .Default(nullptr);
153
154 // If the callee isn't defined, it is not of security concern.
155 // Check and evaluate the call.
156 if (evalFunction)
157 (this->*evalFunction)(CE, FD);
158
159 // Recurse and check children.
160 VisitChildren(CE);
161 }
162
VisitCompoundStmt(CompoundStmt * S)163 void WalkAST::VisitCompoundStmt(CompoundStmt *S) {
164 for (Stmt *Child : S->children())
165 if (Child) {
166 if (CallExpr *CE = dyn_cast<CallExpr>(Child))
167 checkUncheckedReturnValue(CE);
168 Visit(Child);
169 }
170 }
171
VisitForStmt(ForStmt * FS)172 void WalkAST::VisitForStmt(ForStmt *FS) {
173 checkLoopConditionForFloat(FS);
174
175 // Recurse and check children.
176 VisitChildren(FS);
177 }
178
179 //===----------------------------------------------------------------------===//
180 // Check: floating poing variable used as loop counter.
181 // Originally: <rdar://problem/6336718>
182 // Implements: CERT security coding advisory FLP-30.
183 //===----------------------------------------------------------------------===//
184
185 static const DeclRefExpr*
getIncrementedVar(const Expr * expr,const VarDecl * x,const VarDecl * y)186 getIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {
187 expr = expr->IgnoreParenCasts();
188
189 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {
190 if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||
191 B->getOpcode() == BO_Comma))
192 return nullptr;
193
194 if (const DeclRefExpr *lhs = getIncrementedVar(B->getLHS(), x, y))
195 return lhs;
196
197 if (const DeclRefExpr *rhs = getIncrementedVar(B->getRHS(), x, y))
198 return rhs;
199
200 return nullptr;
201 }
202
203 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {
204 const NamedDecl *ND = DR->getDecl();
205 return ND == x || ND == y ? DR : nullptr;
206 }
207
208 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))
209 return U->isIncrementDecrementOp()
210 ? getIncrementedVar(U->getSubExpr(), x, y) : nullptr;
211
212 return nullptr;
213 }
214
215 /// CheckLoopConditionForFloat - This check looks for 'for' statements that
216 /// use a floating point variable as a loop counter.
217 /// CERT: FLP30-C, FLP30-CPP.
218 ///
checkLoopConditionForFloat(const ForStmt * FS)219 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
220 if (!filter.check_FloatLoopCounter)
221 return;
222
223 // Does the loop have a condition?
224 const Expr *condition = FS->getCond();
225
226 if (!condition)
227 return;
228
229 // Does the loop have an increment?
230 const Expr *increment = FS->getInc();
231
232 if (!increment)
233 return;
234
235 // Strip away '()' and casts.
236 condition = condition->IgnoreParenCasts();
237 increment = increment->IgnoreParenCasts();
238
239 // Is the loop condition a comparison?
240 const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);
241
242 if (!B)
243 return;
244
245 // Is this a comparison?
246 if (!(B->isRelationalOp() || B->isEqualityOp()))
247 return;
248
249 // Are we comparing variables?
250 const DeclRefExpr *drLHS =
251 dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenLValueCasts());
252 const DeclRefExpr *drRHS =
253 dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParenLValueCasts());
254
255 // Does at least one of the variables have a floating point type?
256 drLHS = drLHS && drLHS->getType()->isRealFloatingType() ? drLHS : nullptr;
257 drRHS = drRHS && drRHS->getType()->isRealFloatingType() ? drRHS : nullptr;
258
259 if (!drLHS && !drRHS)
260 return;
261
262 const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : nullptr;
263 const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : nullptr;
264
265 if (!vdLHS && !vdRHS)
266 return;
267
268 // Does either variable appear in increment?
269 const DeclRefExpr *drInc = getIncrementedVar(increment, vdLHS, vdRHS);
270
271 if (!drInc)
272 return;
273
274 // Emit the error. First figure out which DeclRefExpr in the condition
275 // referenced the compared variable.
276 assert(drInc->getDecl());
277 const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;
278
279 SmallVector<SourceRange, 2> ranges;
280 SmallString<256> sbuf;
281 llvm::raw_svector_ostream os(sbuf);
282
283 os << "Variable '" << drCond->getDecl()->getName()
284 << "' with floating point type '" << drCond->getType().getAsString()
285 << "' should not be used as a loop counter";
286
287 ranges.push_back(drCond->getSourceRange());
288 ranges.push_back(drInc->getSourceRange());
289
290 const char *bugType = "Floating point variable used as loop counter";
291
292 PathDiagnosticLocation FSLoc =
293 PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
294 BR.EmitBasicReport(AC->getDecl(), filter.checkName_FloatLoopCounter,
295 bugType, "Security", os.str(),
296 FSLoc, ranges);
297 }
298
299 //===----------------------------------------------------------------------===//
300 // Check: Any use of 'gets' is insecure.
301 // Originally: <rdar://problem/6335715>
302 // Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)
303 // CWE-242: Use of Inherently Dangerous Function
304 //===----------------------------------------------------------------------===//
305
checkCall_gets(const CallExpr * CE,const FunctionDecl * FD)306 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
307 if (!filter.check_gets)
308 return;
309
310 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
311 if (!FPT)
312 return;
313
314 // Verify that the function takes a single argument.
315 if (FPT->getNumParams() != 1)
316 return;
317
318 // Is the argument a 'char*'?
319 const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
320 if (!PT)
321 return;
322
323 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
324 return;
325
326 // Issue a warning.
327 PathDiagnosticLocation CELoc =
328 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
329 BR.EmitBasicReport(AC->getDecl(), filter.checkName_gets,
330 "Potential buffer overflow in call to 'gets'",
331 "Security",
332 "Call to function 'gets' is extremely insecure as it can "
333 "always result in a buffer overflow",
334 CELoc, CE->getCallee()->getSourceRange());
335 }
336
337 //===----------------------------------------------------------------------===//
338 // Check: Any use of 'getpwd' is insecure.
339 // CWE-477: Use of Obsolete Functions
340 //===----------------------------------------------------------------------===//
341
checkCall_getpw(const CallExpr * CE,const FunctionDecl * FD)342 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
343 if (!filter.check_getpw)
344 return;
345
346 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
347 if (!FPT)
348 return;
349
350 // Verify that the function takes two arguments.
351 if (FPT->getNumParams() != 2)
352 return;
353
354 // Verify the first argument type is integer.
355 if (!FPT->getParamType(0)->isIntegralOrUnscopedEnumerationType())
356 return;
357
358 // Verify the second argument type is char*.
359 const PointerType *PT = FPT->getParamType(1)->getAs<PointerType>();
360 if (!PT)
361 return;
362
363 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
364 return;
365
366 // Issue a warning.
367 PathDiagnosticLocation CELoc =
368 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
369 BR.EmitBasicReport(AC->getDecl(), filter.checkName_getpw,
370 "Potential buffer overflow in call to 'getpw'",
371 "Security",
372 "The getpw() function is dangerous as it may overflow the "
373 "provided buffer. It is obsoleted by getpwuid().",
374 CELoc, CE->getCallee()->getSourceRange());
375 }
376
377 //===----------------------------------------------------------------------===//
378 // Check: Any use of 'mktemp' is insecure. It is obsoleted by mkstemp().
379 // CWE-377: Insecure Temporary File
380 //===----------------------------------------------------------------------===//
381
checkCall_mktemp(const CallExpr * CE,const FunctionDecl * FD)382 void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD) {
383 if (!filter.check_mktemp) {
384 // Fall back to the security check of looking for enough 'X's in the
385 // format string, since that is a less severe warning.
386 checkCall_mkstemp(CE, FD);
387 return;
388 }
389
390 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
391 if(!FPT)
392 return;
393
394 // Verify that the function takes a single argument.
395 if (FPT->getNumParams() != 1)
396 return;
397
398 // Verify that the argument is Pointer Type.
399 const PointerType *PT = FPT->getParamType(0)->getAs<PointerType>();
400 if (!PT)
401 return;
402
403 // Verify that the argument is a 'char*'.
404 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
405 return;
406
407 // Issue a warning.
408 PathDiagnosticLocation CELoc =
409 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
410 BR.EmitBasicReport(AC->getDecl(), filter.checkName_mktemp,
411 "Potential insecure temporary file in call 'mktemp'",
412 "Security",
413 "Call to function 'mktemp' is insecure as it always "
414 "creates or uses insecure temporary file. Use 'mkstemp' "
415 "instead",
416 CELoc, CE->getCallee()->getSourceRange());
417 }
418
419
420 //===----------------------------------------------------------------------===//
421 // Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 X's.
422 //===----------------------------------------------------------------------===//
423
checkCall_mkstemp(const CallExpr * CE,const FunctionDecl * FD)424 void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD) {
425 if (!filter.check_mkstemp)
426 return;
427
428 StringRef Name = FD->getIdentifier()->getName();
429 std::pair<signed, signed> ArgSuffix =
430 llvm::StringSwitch<std::pair<signed, signed> >(Name)
431 .Case("mktemp", std::make_pair(0,-1))
432 .Case("mkstemp", std::make_pair(0,-1))
433 .Case("mkdtemp", std::make_pair(0,-1))
434 .Case("mkstemps", std::make_pair(0,1))
435 .Default(std::make_pair(-1, -1));
436
437 assert(ArgSuffix.first >= 0 && "Unsupported function");
438
439 // Check if the number of arguments is consistent with out expectations.
440 unsigned numArgs = CE->getNumArgs();
441 if ((signed) numArgs <= ArgSuffix.first)
442 return;
443
444 const StringLiteral *strArg =
445 dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first)
446 ->IgnoreParenImpCasts());
447
448 // Currently we only handle string literals. It is possible to do better,
449 // either by looking at references to const variables, or by doing real
450 // flow analysis.
451 if (!strArg || strArg->getCharByteWidth() != 1)
452 return;
453
454 // Count the number of X's, taking into account a possible cutoff suffix.
455 StringRef str = strArg->getString();
456 unsigned numX = 0;
457 unsigned n = str.size();
458
459 // Take into account the suffix.
460 unsigned suffix = 0;
461 if (ArgSuffix.second >= 0) {
462 const Expr *suffixEx = CE->getArg((unsigned)ArgSuffix.second);
463 llvm::APSInt Result;
464 if (!suffixEx->EvaluateAsInt(Result, BR.getContext()))
465 return;
466 // FIXME: Issue a warning.
467 if (Result.isNegative())
468 return;
469 suffix = (unsigned) Result.getZExtValue();
470 n = (n > suffix) ? n - suffix : 0;
471 }
472
473 for (unsigned i = 0; i < n; ++i)
474 if (str[i] == 'X') ++numX;
475
476 if (numX >= 6)
477 return;
478
479 // Issue a warning.
480 PathDiagnosticLocation CELoc =
481 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
482 SmallString<512> buf;
483 llvm::raw_svector_ostream out(buf);
484 out << "Call to '" << Name << "' should have at least 6 'X's in the"
485 " format string to be secure (" << numX << " 'X'";
486 if (numX != 1)
487 out << 's';
488 out << " seen";
489 if (suffix) {
490 out << ", " << suffix << " character";
491 if (suffix > 1)
492 out << 's';
493 out << " used as a suffix";
494 }
495 out << ')';
496 BR.EmitBasicReport(AC->getDecl(), filter.checkName_mkstemp,
497 "Insecure temporary file creation", "Security",
498 out.str(), CELoc, strArg->getSourceRange());
499 }
500
501 //===----------------------------------------------------------------------===//
502 // Check: Any use of 'strcpy' is insecure.
503 //
504 // CWE-119: Improper Restriction of Operations within
505 // the Bounds of a Memory Buffer
506 //===----------------------------------------------------------------------===//
checkCall_strcpy(const CallExpr * CE,const FunctionDecl * FD)507 void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) {
508 if (!filter.check_strcpy)
509 return;
510
511 if (!checkCall_strCommon(CE, FD))
512 return;
513
514 // Issue a warning.
515 PathDiagnosticLocation CELoc =
516 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
517 BR.EmitBasicReport(AC->getDecl(), filter.checkName_strcpy,
518 "Potential insecure memory buffer bounds restriction in "
519 "call 'strcpy'",
520 "Security",
521 "Call to function 'strcpy' is insecure as it does not "
522 "provide bounding of the memory buffer. Replace "
523 "unbounded copy functions with analogous functions that "
524 "support length arguments such as 'strlcpy'. CWE-119.",
525 CELoc, CE->getCallee()->getSourceRange());
526 }
527
528 //===----------------------------------------------------------------------===//
529 // Check: Any use of 'strcat' is insecure.
530 //
531 // CWE-119: Improper Restriction of Operations within
532 // the Bounds of a Memory Buffer
533 //===----------------------------------------------------------------------===//
checkCall_strcat(const CallExpr * CE,const FunctionDecl * FD)534 void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD) {
535 if (!filter.check_strcpy)
536 return;
537
538 if (!checkCall_strCommon(CE, FD))
539 return;
540
541 // Issue a warning.
542 PathDiagnosticLocation CELoc =
543 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
544 BR.EmitBasicReport(AC->getDecl(), filter.checkName_strcpy,
545 "Potential insecure memory buffer bounds restriction in "
546 "call 'strcat'",
547 "Security",
548 "Call to function 'strcat' is insecure as it does not "
549 "provide bounding of the memory buffer. Replace "
550 "unbounded copy functions with analogous functions that "
551 "support length arguments such as 'strlcat'. CWE-119.",
552 CELoc, CE->getCallee()->getSourceRange());
553 }
554
555 //===----------------------------------------------------------------------===//
556 // Common check for str* functions with no bounds parameters.
557 //===----------------------------------------------------------------------===//
checkCall_strCommon(const CallExpr * CE,const FunctionDecl * FD)558 bool WalkAST::checkCall_strCommon(const CallExpr *CE, const FunctionDecl *FD) {
559 const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>();
560 if (!FPT)
561 return false;
562
563 // Verify the function takes two arguments, three in the _chk version.
564 int numArgs = FPT->getNumParams();
565 if (numArgs != 2 && numArgs != 3)
566 return false;
567
568 // Verify the type for both arguments.
569 for (int i = 0; i < 2; i++) {
570 // Verify that the arguments are pointers.
571 const PointerType *PT = FPT->getParamType(i)->getAs<PointerType>();
572 if (!PT)
573 return false;
574
575 // Verify that the argument is a 'char*'.
576 if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)
577 return false;
578 }
579
580 return true;
581 }
582
583 //===----------------------------------------------------------------------===//
584 // Check: Linear congruent random number generators should not be used
585 // Originally: <rdar://problem/63371000>
586 // CWE-338: Use of cryptographically weak prng
587 //===----------------------------------------------------------------------===//
588
checkCall_rand(const CallExpr * CE,const FunctionDecl * FD)589 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
590 if (!filter.check_rand || !CheckRand)
591 return;
592
593 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
594 if (!FTP)
595 return;
596
597 if (FTP->getNumParams() == 1) {
598 // Is the argument an 'unsigned short *'?
599 // (Actually any integer type is allowed.)
600 const PointerType *PT = FTP->getParamType(0)->getAs<PointerType>();
601 if (!PT)
602 return;
603
604 if (! PT->getPointeeType()->isIntegralOrUnscopedEnumerationType())
605 return;
606 } else if (FTP->getNumParams() != 0)
607 return;
608
609 // Issue a warning.
610 SmallString<256> buf1;
611 llvm::raw_svector_ostream os1(buf1);
612 os1 << '\'' << *FD << "' is a poor random number generator";
613
614 SmallString<256> buf2;
615 llvm::raw_svector_ostream os2(buf2);
616 os2 << "Function '" << *FD
617 << "' is obsolete because it implements a poor random number generator."
618 << " Use 'arc4random' instead";
619
620 PathDiagnosticLocation CELoc =
621 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
622 BR.EmitBasicReport(AC->getDecl(), filter.checkName_rand, os1.str(),
623 "Security", os2.str(), CELoc,
624 CE->getCallee()->getSourceRange());
625 }
626
627 //===----------------------------------------------------------------------===//
628 // Check: 'random' should not be used
629 // Originally: <rdar://problem/63371000>
630 //===----------------------------------------------------------------------===//
631
checkCall_random(const CallExpr * CE,const FunctionDecl * FD)632 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD) {
633 if (!CheckRand || !filter.check_rand)
634 return;
635
636 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
637 if (!FTP)
638 return;
639
640 // Verify that the function takes no argument.
641 if (FTP->getNumParams() != 0)
642 return;
643
644 // Issue a warning.
645 PathDiagnosticLocation CELoc =
646 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
647 BR.EmitBasicReport(AC->getDecl(), filter.checkName_rand,
648 "'random' is not a secure random number generator",
649 "Security",
650 "The 'random' function produces a sequence of values that "
651 "an adversary may be able to predict. Use 'arc4random' "
652 "instead", CELoc, CE->getCallee()->getSourceRange());
653 }
654
655 //===----------------------------------------------------------------------===//
656 // Check: 'vfork' should not be used.
657 // POS33-C: Do not use vfork().
658 //===----------------------------------------------------------------------===//
659
checkCall_vfork(const CallExpr * CE,const FunctionDecl * FD)660 void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) {
661 if (!filter.check_vfork)
662 return;
663
664 // All calls to vfork() are insecure, issue a warning.
665 PathDiagnosticLocation CELoc =
666 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
667 BR.EmitBasicReport(AC->getDecl(), filter.checkName_vfork,
668 "Potential insecure implementation-specific behavior in "
669 "call 'vfork'",
670 "Security",
671 "Call to function 'vfork' is insecure as it can lead to "
672 "denial of service situations in the parent process. "
673 "Replace calls to vfork with calls to the safer "
674 "'posix_spawn' function",
675 CELoc, CE->getCallee()->getSourceRange());
676 }
677
678 //===----------------------------------------------------------------------===//
679 // Check: Should check whether privileges are dropped successfully.
680 // Originally: <rdar://problem/6337132>
681 //===----------------------------------------------------------------------===//
682
checkUncheckedReturnValue(CallExpr * CE)683 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
684 if (!filter.check_UncheckedReturn)
685 return;
686
687 const FunctionDecl *FD = CE->getDirectCallee();
688 if (!FD)
689 return;
690
691 if (II_setid[0] == nullptr) {
692 static const char * const identifiers[num_setids] = {
693 "setuid", "setgid", "seteuid", "setegid",
694 "setreuid", "setregid"
695 };
696
697 for (size_t i = 0; i < num_setids; i++)
698 II_setid[i] = &BR.getContext().Idents.get(identifiers[i]);
699 }
700
701 const IdentifierInfo *id = FD->getIdentifier();
702 size_t identifierid;
703
704 for (identifierid = 0; identifierid < num_setids; identifierid++)
705 if (id == II_setid[identifierid])
706 break;
707
708 if (identifierid >= num_setids)
709 return;
710
711 const FunctionProtoType *FTP = FD->getType()->getAs<FunctionProtoType>();
712 if (!FTP)
713 return;
714
715 // Verify that the function takes one or two arguments (depending on
716 // the function).
717 if (FTP->getNumParams() != (identifierid < 4 ? 1 : 2))
718 return;
719
720 // The arguments must be integers.
721 for (unsigned i = 0; i < FTP->getNumParams(); i++)
722 if (!FTP->getParamType(i)->isIntegralOrUnscopedEnumerationType())
723 return;
724
725 // Issue a warning.
726 SmallString<256> buf1;
727 llvm::raw_svector_ostream os1(buf1);
728 os1 << "Return value is not checked in call to '" << *FD << '\'';
729
730 SmallString<256> buf2;
731 llvm::raw_svector_ostream os2(buf2);
732 os2 << "The return value from the call to '" << *FD
733 << "' is not checked. If an error occurs in '" << *FD
734 << "', the following code may execute with unexpected privileges";
735
736 PathDiagnosticLocation CELoc =
737 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
738 BR.EmitBasicReport(AC->getDecl(), filter.checkName_UncheckedReturn, os1.str(),
739 "Security", os2.str(), CELoc,
740 CE->getCallee()->getSourceRange());
741 }
742
743 //===----------------------------------------------------------------------===//
744 // SecuritySyntaxChecker
745 //===----------------------------------------------------------------------===//
746
747 namespace {
748 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
749 public:
750 ChecksFilter filter;
751
checkASTCodeBody(const Decl * D,AnalysisManager & mgr,BugReporter & BR) const752 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
753 BugReporter &BR) const {
754 WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter);
755 walker.Visit(D->getBody());
756 }
757 };
758 }
759
760 #define REGISTER_CHECKER(name) \
761 void ento::register##name(CheckerManager &mgr) { \
762 SecuritySyntaxChecker *checker = \
763 mgr.registerChecker<SecuritySyntaxChecker>(); \
764 checker->filter.check_##name = true; \
765 checker->filter.checkName_##name = mgr.getCurrentCheckName(); \
766 }
767
768 REGISTER_CHECKER(gets)
769 REGISTER_CHECKER(getpw)
770 REGISTER_CHECKER(mkstemp)
771 REGISTER_CHECKER(mktemp)
772 REGISTER_CHECKER(strcpy)
773 REGISTER_CHECKER(rand)
774 REGISTER_CHECKER(vfork)
775 REGISTER_CHECKER(FloatLoopCounter)
776 REGISTER_CHECKER(UncheckedReturn)
777
778
779