-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathIncludeFileSniff.php
103 lines (98 loc) · 3.27 KB
/
IncludeFileSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Sniffs\Security;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
/**
* Detects possible improper usage of include functions.
*/
class IncludeFileSniff implements Sniff
{
/**
* Warning violation code.
*
* @var string
*/
protected $warningCode = 'FoundIncludeFile';
/**
* Pattern to match urls.
*
* @var string
*/
protected $urlPattern = '#(https?|ftp)://.*#i';
/**
* @inheritdoc
*/
public function register()
{
return Tokens::$includeTokens;
}
/**
* @inheritdoc
* phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
*/
public function process(File $phpcsFile, $stackPtr)
{
// phpcs:enable
$tokens = $phpcsFile->getTokens();
$firstToken = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true);
$message = '"%s" statement detected. File manipulations are discouraged.';
if ($tokens[$firstToken]['code'] === T_OPEN_PARENTHESIS) {
$message .= ' Statement is not a function, no parentheses are required.';
$firstToken = $phpcsFile->findNext(Tokens::$emptyTokens, $firstToken + 1, null, true);
}
$nextToken = $firstToken;
$ignoredTokens = array_merge(Tokens::$emptyTokens, [T_CLOSE_PARENTHESIS]);
$isConcatenated = false;
$isUrl = false;
$hasVariable = false;
$includePath = '';
while ($tokens[$nextToken]['code'] !== T_SEMICOLON &&
$tokens[$nextToken]['code'] !== T_CLOSE_TAG) {
switch ($tokens[$nextToken]['code']) {
case T_CONSTANT_ENCAPSED_STRING:
$includePath = trim($tokens[$nextToken]['content'], '"\'');
if (preg_match($this->urlPattern, $includePath)) {
$isUrl = true;
}
break;
case T_STRING_CONCAT:
$isConcatenated = true;
break;
case T_VARIABLE:
$hasVariable = true;
break;
}
$nextToken = $phpcsFile->findNext($ignoredTokens, $nextToken + 1, null, true);
}
if ($tokens[$stackPtr]['level'] === 0 && stripos($includePath, 'controller') !== false) {
$nextToken = $phpcsFile->findNext(T_CLASS, $nextToken + 1);
if ($nextToken) {
$nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, $nextToken + 1, null, true);
$className = $tokens[$nextToken]['content'];
if (strripos($className, 'controller') !== false) {
return;
}
}
}
if ($isUrl) {
$message .= ' Passing urls is forbidden.';
}
if ($isConcatenated) {
$message .= ' Concatenating is forbidden.';
}
if ($hasVariable) {
$message .= ' Variables inside are insecure.';
}
$phpcsFile->addError(
$message,
$stackPtr,
$this->warningCode,
[$tokens[$stackPtr]['content']]
);
}
}