-
Notifications
You must be signed in to change notification settings - Fork 1
/
Module.php
390 lines (328 loc) · 12.6 KB
/
Module.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
namespace wdmg\guard;
/**
* Yii2 Guard
*
* @category Module
* @version 1.3.0
* @author Alexsander Vyshnyvetskyy <[email protected]>
* @link https://github.com/wdmg/yii2-guard
* @copyright Copyright (c) 2019 - 2023 W.D.M.Group, Ukraine
* @license https://opensource.org/licenses/MIT Massachusetts Institute of Technology (MIT) License
*
*/
use Yii;
use wdmg\base\BaseModule;
use wdmg\guard\filters\RateLimit;
use wdmg\guard\behaviors\RequestBehavior;
use wdmg\guard\models\Security;
use wdmg\guard\models\Scanning;
use wdmg\helpers\ArrayHelper;
/**
* Guard module definition class
*/
class Module extends BaseModule
{
/**
* {@inheritdoc}
*/
public $controllerNamespace = 'wdmg\guard\controllers';
/**
* {@inheritdoc}
*/
public $defaultRoute = "security/index";
/**
* @var string, the name of module
*/
public $name = "Guard";
/**
* @var string, the description of module
*/
public $description = "Security System";
/**
* @var string the module version
*/
private $version = "1.3.0";
/**
* @var integer, priority of initialization
*/
private $priority = 1;
/**
* @var bool, check password recency
*/
public $passwordRecency = true;
/**
* @var bool, flag for use filters
*/
public $useFilters = true;
/**
* @var array, flag for use request filters
*/
public $filters = [
'xss' => false, // flag for scan for XSS attack`s
'lfi' => true, // flag for scan for LFI/RFI/RCE attack`s
'php' => true, // flag for scan for PHP-injection attack`s
'sql' => true // flag for scan for SQL-injection attack`s
];
/**
* @var array, security filters (regexp patterns)
*/
public $patterns = [
'xss' => '/(<.*?(script|body|object|iframe|applet|meta|style|form|frameset|frame|svg).*?>)|(base64|data\\:|fromCharCode|expression|onmouse|onload|alert|getcookie|document\\.)/uim',
'lfi' => '/((\\.|%2e){2,}(\\/|%5c|\\\\)|php:\\/\\/|file:\\/\\/|expect:\\/\\/|zip:\\/\\/|yii\\.php|init\\.php|web\\.php|params\\.php|db\\.php|console\\.php|test\\.php|test_db\\.php|phpinfo|passwd|htaccess)/uism',
'php' => '/(php:\\/\\/|(eval|preg_replace|require|include|call_user|create_func|array_filter|array_reduce|array_walk|array_map|reflection)\\()/uism',
'sql' => '/(UNION|SELECT|OUTFILE|ALTER|INSERT|DROP|TRUNCATE|({%tables}))\\s/uism'
];
/**
* @var bool, flag for use requests limitation
*/
public $useRateLimit = true;
/**
* @var integer, request limit`s per minute
*/
public $rateLimit = 60;
/**
* @var array, ignoring by IP
*/
public $rateLimitIgnoringIP = [
'::1',
'127.0.0.1',
];
/**
* @var array, ignoring by request route
*/
public $rateLimitIgnoringRoutes = [
'/admin'
];
/**
* @var array, exception from ignoring by request route
*/
public $rateLimitExceptionRoutes = [
'/admin/login',
'/admin/restore',
];
/**
* @var array, ignoring by request type
*/
public $rateLimitIgnoringRequests = [
'post' => false,
'get' => false,
'ajax' => true
];
/**
* @var string, request limit error message
*/
public $rateLimitErrorMessage = 'Your request limit has been exceeded! Try later.';
/**
* @var bool, flag for use overdrive limitation
*/
public $useOverdriveLimit = true;
/**
* @var bool, limit for $_POST and $_GET data overdrive
*/
public $overdriveLimit = [
'post' => 200,
'get' => 100
];
/**
* @var int, maximum number of attack attempts before blocking
*/
public $maxAttempts = 5;
/**
* @var int, time in seconds of storage the history of attempted attacks in the cache
*/
public $attemptsDuration = 3600;
/**
* @var int, time in seconds of removal restrictions (time of blocking)
*/
public $releaseTime = 3600;
/**
* @var bool, use blocking also by a range of network IP addresses
*/
public $useIpRange = true;
/**
* @var null|string, use forbidden error layout for frontend
*/
public $forbiddenLayout = "@wdmg/guard/views/layouts/default";
/**
* @var bool, use a filesystem scan for modification
*/
public $useFileSystemScan = true;
/**
* @var array, file system scan options
*/
public $fileSystemScan = [
'scanInterval' => null, // integer seconds, null|false - for disable auto scan
'autoClear' => true, // deletes reports oldest a week
'onlyTypes' => [
"*.php",
"*.js"
],
'exceptTypes' => [],
'excludesPath' => [
"@runtime",
"@tests",
"@runtime/cache",
"@webroot/assets",
"@webroot/uploads",
"/node_modules",
"/.git"
]
];
/**
* @var array, options for sending scan notifications by email
*/
public $scanReport = [
'emailViewPath' => [
'html' => "@wdmg/guard/mail/report-html",
'text' => "@wdmg/guard/mail/report-text"
],
'reportEmail' => "[email protected]"
];
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
// Set version of current module
$this->setVersion($this->version);
// Set priority of current module
$this->setPriority($this->priority);
// Configure module from app params
if (isset(Yii::$app->params['guard.passwordRecency']))
$this->passwordRecency = Yii::$app->params['guard.passwordRecency'];
if (isset(Yii::$app->params['guard.useFilters']))
$this->useFilters = Yii::$app->params['guard.useFilters'];
if (isset(Yii::$app->params['guard.filters']))
$this->filters = Yii::$app->params['guard.filters'];
if (isset(Yii::$app->params['guard.patterns']))
$this->patterns = Yii::$app->params['guard.patterns'];
if (isset(Yii::$app->params['guard.useRateLimit']))
$this->useRateLimit = Yii::$app->params['guard.useRateLimit'];
if (isset(Yii::$app->params['guard.rateLimit']))
$this->rateLimit = Yii::$app->params['guard.rateLimit'];
if (isset(Yii::$app->params['guard.rateLimitIgnoringIP']))
$this->rateLimitIgnoringIP = Yii::$app->params['guard.rateLimitIgnoringIP'];
if (isset(Yii::$app->params['guard.rateLimitIgnoringRoutes']))
$this->rateLimitIgnoringRoutes = Yii::$app->params['guard.rateLimitIgnoringRoutes'];
if (isset(Yii::$app->params['guard.rateLimitExceptionRoutes']))
$this->rateLimitExceptionRoutes = Yii::$app->params['guard.rateLimitExceptionRoutes'];
if (isset(Yii::$app->params['guard.rateLimitIgnoringRequests']))
$this->rateLimitIgnoringRequests = Yii::$app->params['guard.rateLimitIgnoringRequests'];
if (isset(Yii::$app->params['guard.rateLimitErrorMessage']))
$this->rateLimitErrorMessage = Yii::$app->params['guard.rateLimitErrorMessage'];
if (isset(Yii::$app->params['guard.useOverdriveLimit']))
$this->useOverdriveLimit = Yii::$app->params['guard.useOverdriveLimit'];
if (isset(Yii::$app->params['guard.overdriveLimit']))
$this->overdriveLimit = Yii::$app->params['guard.overdriveLimit'];
if (isset(Yii::$app->params['guard.useFileSystemScan']))
$this->useFileSystemScan = Yii::$app->params['guard.useFileSystemScan'];
if (isset(Yii::$app->params['guard.fileSystemScan']))
$this->fileSystemScan = Yii::$app->params['guard.fileSystemScan'];
}
/**
* {@inheritdoc}
*/
public function dashboardNavItems($options = null)
{
$items = [
'label' => $this->name,
'url' => [$this->routePrefix . '/'. $this->id],
'icon' => 'fa fa-fw fa-shield-alt',
'active' => in_array(\Yii::$app->controller->module->id, [$this->id]),
'items' => [
[
'label' => Yii::t('app/modules/guard', 'Banned List'),
'url' => [$this->routePrefix . '/guard/banned/'],
'icon' => 'fa fa-fw fa-traffic-light',
'active' => (in_array(\Yii::$app->controller->module->id, ['guard']) && Yii::$app->controller->id == 'banned'),
], [
'label' => Yii::t('app/modules/guard', 'Scan Reports'),
'url' => [$this->routePrefix . '/guard/scan/'],
'icon' => 'fa fa-fw fa-history',
'active' => (in_array(\Yii::$app->controller->module->id, ['guard']) && Yii::$app->controller->id == 'scan'),
]
]
];
if (!is_null($options)) {
if (isset($options['count'])) {
$items['label'] .= '<span class="badge badge-default float-right">' . $options['count'] . '</span>';
unset($options['count']);
}
if (is_array($options))
$items = ArrayHelper::merge($items, $options);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function bootstrap($app)
{
parent::bootstrap($app);
// Add guard behaviors for web app
if (!($app instanceof \yii\console\Application) && $this->module) {
// Prepare SQL-filter and add DB tables
if (isset($this->filters['sql']) && ($connection = Yii::$app->getDb())) {
if (preg_match('{%tables}', $this->filters['sql'])) {
$tables = $connection->getSchema()->getTableNames();
$no_prefix_tables = str_replace($connection->tablePrefix, '', $tables);
$tables = ArrayHelper::merge($tables, $no_prefix_tables);
$this->filters['sql'] = str_replace('{%tables}', join('|', $tables), $this->filters['sql']);
}
}
// Attach request query behavior
$app->attachBehavior('requestBehavior', [
'class' => RequestBehavior::class,
'security' => new Security(),
'module' => $this
]);
// Attach rate-limit behavior
if ($this->useRateLimit && intval($this->rateLimit) > 0) {
$app->attachBehavior('rateLimit', [
'class' => RateLimit::class,
'rateLimit' => intval($this->rateLimit),
'security' => new Security(),
'module' => $this
]);
}
// Check admin, manager or editor users password relevance at last 14 days
if (!(Yii::$app->user->isGuest) && ($this->isBackend() && $this->passwordRecency)) {
\yii\base\Event::on(\yii\base\Controller::class, \yii\base\Controller::EVENT_BEFORE_ACTION, function ($event) {
if ($auth = Yii::$app->authManager) {
$user = Yii::$app->user->identity;
if ($roles = $auth->getRolesByUser($user->getId())) {
if (!empty(array_intersect(['admin', 'manager', 'editor'], array_keys($roles)))) {
if (strtotime($user->updated_at) <= strtotime("- 14 day")) {
Yii::$app->getSession()->setFlash(
'danger',
Yii::t(
'app/modules/guard',
'It seems that you have not changed your access password for a long time. We recommend that you, periodically, change the password for access to the administrative interface of the site.'
)
);
}
}
}
}
});
}
// Filesystem scan of modifications
if ($this->useFileSystemScan) {
\yii\base\Event::on(\yii\base\Controller::class, \yii\base\Controller::EVENT_AFTER_ACTION, function ($event) {
if ($this->fileSystemScan['scanInterval']) {
$scanner = new Scanning();
if ($lastscan = $scanner::find()->orderBy(['id' => SORT_DESC])->one()) {
if (strtotime($lastscan->updated_at) <= strtotime("- " . intval($this->fileSystemScan['scanInterval']) . ' seconds')) {
$scanner->scan();
}
} else {
$scanner->scan();
}
}
});
}
}
}
}