Passed
Push — 2.x ( d24405...546b7d )
by Terry
05:52 queued 11s
created

SetupTrait::setupAndApplyComponentIpManager()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 28
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.0178

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 28
ccs 13
cts 14
cp 0.9286
rs 8.8333
cc 7
nc 7
nop 0
crap 7.0178
1
<?php
2
/**
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 * 
10
 * php version 7.1.0
11
 * 
12
 * @category  Web-security
13
 * @package   Shieldon
14
 * @author    Terry Lin <[email protected]>
15
 * @copyright 2019 terrylinooo
16
 * @license   https://github.com/terrylinooo/shieldon/blob/2.x/LICENSE MIT
17
 * @link      https://github.com/terrylinooo/shieldon
18
 * @see       https://shieldon.io
19
 */
20
21
declare(strict_types=1);
22
23
namespace Shieldon\Firewall\Firewall;
24
25
use Psr\Http\Server\MiddlewareInterface;
26
use Shieldon\Firewall\Firewall\Captcha\CaptchaFactory;
27
use Shieldon\Firewall\Firewall\Driver\DriverFactory;
28
use Shieldon\Firewall\Log\ActionLogger;
29
use Shieldon\Firewall\Middleware\HttpAuthentication;
30
use Shieldon\Event\Event;
31
use RuntimeException;
32
use function Shieldon\Firewall\get_request;
33
use function Shieldon\Firewall\get_session_instance;
34
use function strpos;
35
use function time;
36
37
/*
38
 * Main Trait for Firwall class.
39
 */
40
trait SetupTrait
41
{
42
    /**
43
     * If status is false and then Sheldon will stop working.
44
     *
45
     * @var bool
46
     */
47
    protected $status = true;
48
49
    /**
50
     * Get options from the configuration file.
51
     * This method is same as `$this->getConfig()` but returning value from array directly.
52
     *
53
     * @param string $option  The option of the section in the the configuration.
54
     * @param string $section The section in the configuration.
55
     *
56
     * @return mixed
57
     */
58
    abstract protected function getOption(string $option, string $section = '');
59
60
    /**
61
     * Update configuration file.
62
     *
63
     * @return void
64
     */
65
    abstract protected function updateConfig(): void;
66
67
    /**
68
     * Set a variable to the configuration.
69
     *
70
     * @param string $field The field of the configuration.
71
     * @param mixed  $value The vale of a field in the configuration.
72
     *
73
     * @return void
74
     */
75
    abstract public function setConfig(string $field, $value): void;
76
77
    /**
78
     * Add middlewares and use them before going into Shieldon kernal.
79
     *
80
     * @param MiddlewareInterface $middleware A PSR-15 middlewares.
81
     *
82
     * @return void
83
     */
84
    abstract public function add(MiddlewareInterface $middleware): void;
85
86
    /**
87
     * Are database tables created? 
88
     *
89
     * @return bool
90
     */
91
    abstract protected function hasCheckpoint(): bool;
92
93
    /**
94
     * Are database tables created?
95
     * 
96
     * @param bool $create Is create the checkpoint file, or not.
97
     *
98
     * @return void
99
     */
100
    abstract protected function setCheckpoint(bool $create = true): void;
101
102
    /**
103
     * Set a data driver for the use of Shiedon Firewall.
104
     * Currently supports File, Redis, MySQL and SQLite.
105
     *
106
     * @return void
107
     */
108 83
    public function setupDriver(): void
109
    {
110 83
        $driverType = $this->getOption('driver_type');
111 83
        $driverSetting = $this->getOption($driverType, 'drivers');
112
113 83
        if (isset($driverSetting['directory_path'])) {
114 83
            $driverSetting['directory_path'] = $driverSetting['directory_path'] ?: $this->directory . '/data_driver_' . $driverType;
115
        }
116
117 83
        $driverInstance = DriverFactory::getInstance($driverType, $driverSetting);
118
119 83
        if ($this->hasCheckpoint()) {
120 81
            $this->kernel->disableDbBuilder();
121
        } else {
122 5
            $this->setCheckpoint();
123
        }
124
125 83
        $this->status = false;
126
127 83
        if ($driverInstance !== null) {
128 83
            $this->kernel->setDriver($driverInstance);
129 83
            $this->status = true;
130
        }
131 83
    }
132
133
    /**
134
     * Filters
135
     *
136
     * (1) Session.
137
     * (2) Cookie generated by JavaScript code.
138
     * (3) HTTP referrer information.
139
     * (4) Pageview frequency.
140
     *
141
     * @return void
142
     */
143 83
    protected function setupFilters(): void
144
    {
145
        $filters = [
146 83
            'session',
147
            'cookie',
148
            'referer',
149
        ];
150
151 83
        $settings = [];
152 83
        $filterConfig = [];
153 83
        $filterLimit = [];
154
155 83
        foreach ($filters as $filter) {
156 83
            $setting = $this->getOption($filter, 'filters');
157
158 83
            $settings[$filter] = $setting;
159 83
            $filterConfig[$filter] = $setting['enable'];
160 83
            $filterLimit[$filter] = $setting['config']['quota']; // default: 5
161
162 83
            unset($setting);
163
        }
164
165 83
        $settings['frequency'] = $this->getOption('frequency', 'filters');
166 83
        $filterConfig['frequency'] = $settings['frequency']['enable'];
167
168 83
        $this->kernel->setFilters($filterConfig);
169
170 83
        $this->kernel->setProperty(
171 83
            'limit_unusual_behavior',
172
            $filterLimit
173
        );
174
175
        $frequencyQuota = [
176 83
            's' => $settings['frequency']['config']['quota_s'],
177 83
            'm' => $settings['frequency']['config']['quota_m'],
178 83
            'h' => $settings['frequency']['config']['quota_h'],
179 83
            'd' => $settings['frequency']['config']['quota_d'],
180
        ];
181
182 83
        $this->kernel->setProperty('time_unit_quota', $frequencyQuota);
183
184 83
        $this->kernel->setProperty(
185 83
            'cookie_name',
186 83
            $settings['cookie']['config']['cookie_name'] // default: ssjd
187
        );
188
189 83
        $this->kernel->setProperty(
190 83
            'cookie_domain',
191 83
            $settings['cookie']['config']['cookie_domain'] // default: ''
192
        );
193
194 83
        $this->kernel->setProperty(
195 83
            'cookie_value',
196 83
            $settings['cookie']['config']['cookie_value'] // default: 1
197
        );
198
199 83
        $this->kernel->setProperty(
200 83
            'interval_check_referer',
201 83
            $settings['referer']['config']['time_buffer']
202
        );
203
204 83
        $this->kernel->setProperty(
205 83
            'interval_check_session',
206 83
            $settings['session']['config']['time_buffer']
207
        );
208 83
    }
209
210
    /**
211
     * Components
212
     * 
213
     * (1) Ip
214
     * (2) Rdns
215
     * (3) Header
216
     * (4) User-agent
217
     * (5) Trusted bot
218
     *
219
     * @return void
220
     */
221 83
    protected function setupComponents(): void
222
    {
223
        $componentConfig = [
224 83
            'Ip'         => $this->getOption('ip', 'components'),
225 83
            'Rdns'       => $this->getOption('rdns', 'components'),
226 83
            'Header'     => $this->getOption('header', 'components'),
227 83
            'UserAgent'  => $this->getOption('user_agent', 'components'),
228 83
            'TrustedBot' => $this->getOption('trusted_bot', 'components'),
229
        ];
230
231 83
        foreach ($componentConfig as $className => $config) {
232 83
            $class = 'Shieldon\Firewall\Component\\' . $className;
233
234 83
            if ($config['enable']) {
235 83
                $componentInstance = new $class();
236
237 83
                if ($className === 'Ip') {
238 83
                    $this->kernel->setComponent($componentInstance);
239
240
                    // Need Ip component to be loaded before calling this method.
241 83
                    $this->setupAndApplyComponentIpManager();
242
                } else {
243 83
                    $componentInstance->setStrict($config['strict_mode']);
244 83
                    $this->kernel->setComponent($componentInstance);
245
                }
246
            }
247
        }
248 83
    }
249
250
    /**
251
     * Captcha modules.
252
     * 
253
     * (1) Google ReCaptcha
254
     * (2) Simple image captcha.
255
     *
256
     * @return void
257
     */
258 83
    protected function setupCaptchas(): void
259
    {
260
        $captchaList = [
261 83
            'recaptcha',
262
            'image',
263
        ];
264
265 83
        foreach ($captchaList as $captcha) {
266 83
            $setting = (array) $this->getOption($captcha, 'captcha_modules');
267
268
            // Initialize messenger instances from the factory/
269 83
            if (CaptchaFactory::check($setting)) {
270
271 19
                $this->kernel->setCaptcha(
272 19
                    CaptchaFactory::getInstance(
273
                        // The ID of the captcha module in the configuration.
274 19
                        $captcha, 
275
                        // The settings of the captcha module in the configuration.
276
                        $setting    
277
                    )
278
                );
279
            }
280
281 83
            unset($setting);
282
        }
283 83
    }
284
285
    /**
286
     * Set up the action logger.
287
     *
288
     * @return void
289
     */
290 83
    protected function setupLogger(): void
291
    {
292 83
        $loggerSetting = $this->getOption('action', 'loggers');
293
294 83
        if ($loggerSetting['enable']) {
295 82
            if (!empty($loggerSetting['config']['directory_path'])) {
296 76
                $this->kernel->setLogger(
297 76
                    new ActionLogger($loggerSetting['config']['directory_path'])
298
                );
299
            }
300
        }
301 83
    }
302
303
    /**
304
     * Apply the denied list and the allowed list to Ip Component.
305
     * 
306
     * @return void
307
     */
308 83
    protected function setupAndApplyComponentIpManager(): void
309
    {
310 83
        $ipList = (array) $this->getOption('ip_manager');
311
312 83
        $allowedList = [];
313 83
        $deniedList = [];
314
315 83
        foreach ($ipList as $ip) {
316 83
            if (empty($ip))
317
                continue;
318
319 83
            if (0 === strpos($this->kernel->getCurrentUrl(), empty($ip['url']) ? '/' : $ip['url']) ) {
320
321 82
                if ('allow' === $ip['rule']) {
322 82
                    $allowedList[] = $ip['ip'];
323
                }
324
325 82
                if ('deny' === $ip['rule']) {
326 83
                    $deniedList[] = $ip['ip'];
327
                }
328
            }
329
        }
330
331
        /** @scrutinizer ignore-call */ 
332 83
        $this->kernel->component['Ip']->setAllowedItems($allowedList);
333
334
        /** @scrutinizer ignore-call */ 
335 83
        $this->kernel->component['Ip']->setDeniedItems($deniedList);
336 83
    }
337
338
    /**
339
     * If you use CDN, please choose the real IP source.
340
     *
341
     * @return void
342
     */
343 83
    protected function setupIpSource(): void
344
    {
345 83
        $ipSourceType = $this->getOption('ip_variable_source');
346 83
        $serverParams = get_request()->getServerParams();
347
348
        /**
349
         * REMOTE_ADDR: general
350
         * HTTP_CF_CONNECTING_IP: Cloudflare
351
         * HTTP_X_FORWARDED_FOR: Google Cloud CDN, Google Load-balancer, AWS.
352
         * HTTP_X_FORWARDED_HOST: KeyCDN, or other CDN providers not listed here.
353
         */
354 83
        $key = array_search(true, $ipSourceType);
355 83
        $ip = $serverParams[$key];
356
357 83
        if (empty($ip)) {
358
359
            // @codeCoverageIgnoreStart
360
            throw new RuntimeException(
361
                'IP source is not set correctly.'
362
            );
363
            // @codeCoverageIgnoreEnd
364
        }
365
366 83
        $this->kernel->setIp($ip, true);
367 83
    }
368
369
    /**
370
     * Set deny attempts.
371
     *
372
     * @return void
373
     */
374 83
    protected function setupDenyTooManyAttempts(): void
375
    {
376 83
        $setting = $this->getOption('failed_attempts_in_a_row', 'events');
377
378 83
        $this->kernel->setProperty(
379 83
            'deny_attempt_enable',
380
            [
381 83
                'data_circle'     => $setting['data_circle']['enable'],     // false   
382 83
                'system_firewall' => $setting['system_firewall']['enable'], // false   
383
            ]
384
        );
385
386 83
        $this->kernel->setProperty(
387 83
            'deny_attempt_buffer',
388
            [
389 83
                'data_circle'     => $setting['data_circle']['buffer'],     // 10
390 83
                'system_firewall' => $setting['system_firewall']['buffer'], // 10
391
            ]
392
        );
393
394
        // Check the time of the last failed attempt.
395 83
        $recordAttempt = $this->getOption('record_attempt');
396
397 83
        $this->kernel->setProperty(
398 83
            'record_attempt_detection_period',
399 83
            $recordAttempt['detection_period'] // 5
400
        ); 
401
402 83
        $this->kernel->setProperty(
403 83
            'reset_attempt_counter',
404 83
            $recordAttempt['time_to_reset'] // 1800
405
        );  
406 83
    }
407
408
    /**
409
     * Set iptables working folder.
410
     *
411
     * @return void
412
     */
413 83
    protected function setupiptablesBridgeDirectory(): void
414
    {
415 83
        $iptablesSetting = $this->getOption('config', 'iptables');
416
417 83
        $this->kernel->setProperty(
418 83
            'iptables_watching_folder',
419 83
            $iptablesSetting['watching_folder']
420
        );
421 83
    }
422
423
    /**
424
     * Set the online session limit.
425
     *
426
     * @return void
427
     */
428 83
    protected function setupLimitSession(): void
429
    {
430 83
        $sessionLimitSetting = $this->getOption('online_session_limit');
431
432 83
        if ($sessionLimitSetting['enable']) {
433
434 82
            $onlineUsers = $sessionLimitSetting['config']['count'];       // default: 100
435 82
            $alivePeriod = $sessionLimitSetting['config']['period'];      // default: 300
436 82
            $isUniqueIp  = $sessionLimitSetting['config']['unique_only']; // false
437
438 82
            $this->kernel->limitSession($onlineUsers, $alivePeriod, $isUniqueIp);
439
        }
440 83
    }
441
442
    /**
443
     * Set the cron job.
444
     * This is triggered by the pageviews, not system cron job.
445
     *
446
     * @return void
447
     */
448 83
    protected function setupCronJob(): void 
449
    {
450 83
        $cronjobSetting = $this->getOption('reset_circle', 'cronjob');
451
452 83
        if ($cronjobSetting['enable']) {
453
454 59
            $nowTime = time();
455
456 59
            $lastResetTime = $cronjobSetting['config']['last_update'];
457
458 59
            if (!empty($lastResetTime) ) {
459 59
                $lastResetTime = strtotime($lastResetTime);
460
            } else {
461
                // @codeCoverageIgnoreStart
462
463
                $lastResetTime = strtotime(date('Y-m-d 00:00:00'));
464
465
                // @codeCoverageIgnoreEnd
466
            }
467
468 59
            if (($nowTime - $lastResetTime) > $cronjobSetting['config']['period']) {
469
470 12
                $updateResetTime = date('Y-m-d 00:00:00');
471
472
                // Update new reset time.
473 12
                $this->setConfig(
474 12
                    'cronjob.reset_circle.config.last_update',
475
                    $updateResetTime
476
                );
477
478 12
                $this->updateConfig();
479
480
                // Remove all logs.
481
                /** @scrutinizer ignore-call */ 
482 12
                $this->kernel->driver->rebuild();
483
            }
484
        }
485 83
    }
486
487
    /**
488
     * Set the URLs that want to be excluded from Shieldon protection.
489
     *
490
     * @return void
491
     */
492 83
    protected function setupExcludedUrls(): void
493
    {
494 83
        $excludedUrls = $this->getOption('excluded_urls');
495
496 83
        if (!empty($excludedUrls)) {
497 83
            $list = array_column($excludedUrls, 'url');
498
499 83
            $this->kernel->setExcludedList($list);
500
        }
501 83
    }
502
503
    /**
504
     * WWW-Athentication.
505
     *
506
     * @return void
507
     */
508 83
    protected function setupPageAuthentication(): void
509
    {
510 83
        $authenticateList = $this->getOption('www_authenticate');
511
512 83
        if (is_array($authenticateList)) {
513 83
            $this->add(
514 83
                new HttpAuthentication($authenticateList)
515
            );
516
        }
517 83
    }
518
519
    /**
520
     * Set dialog UI.
521
     *
522
     * @return void
523
     */
524 83
    protected function setupDialogUserInterface()
525
    {
526
        Event::AddListener('session_init', function() {
527 72
            $ui = $this->getOption('dialog_ui');
528
529 72
            if (!empty($ui)) {
530 72
                get_session_instance()->set('shieldon_ui_lang', $ui['lang']);
531 72
                $this->kernel->setDialog($this->getOption('dialog_ui'));
532
            }
533 83
        });
534
535 83
        $dialogInfo = $this->getOption('dialog_info_disclosure');
536
537 83
        $this->kernel->setProperty('display_online_info', $dialogInfo['online_user_amount']);
538 83
        $this->kernel->setProperty('display_user_info',   $dialogInfo['user_inforamtion']);
539 83
        $this->kernel->setProperty('display_http_code',   $dialogInfo['http_status_code']);
540 83
        $this->kernel->setProperty('display_reason_code', $dialogInfo['reason_code']);
541 83
        $this->kernel->setProperty('display_reason_text', $dialogInfo['reason_text']);
542 83
    }
543
}
544