Passed
Push — 2.x ( 3181da...fa7f46 )
by Terry
01:56
created

SetupTrait::setupCronJob()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 35
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 15
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 35
rs 9.7666
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 function Shieldon\Firewall\get_request;
31
use function Shieldon\Firewall\get_session;
32
33
use RuntimeException;
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
    protected function setupDriver(): void
109
    {
110
        $driverType = $this->getOption('driver_type');
111
        $driverSetting = $this->getOption($driverType, 'drivers');
112
113
        if ($this->hasCheckpoint()) {
114
            $this->kernel->disableDbBuilder();
115
        } else {
116
            $this->setCheckpoint();
117
        }
118
119
        if (isset($driverSetting['directory_path'])) {
120
            $driverSetting['directory_path'] = $driverSetting['directory_path'] ?: $this->directory;
121
        }
122
123
        $driverInstance = DriverFactory::getInstance($driverType, $driverSetting);
124
125
        $this->status = false;
126
        if ($driverInstance !== null) {
127
            $this->kernel->setDriver($driverInstance);
128
            $this->status = true;
129
        }
130
    }
131
132
    /**
133
     * Filters
134
     *
135
     * (1) Session.
136
     * (2) Cookie generated by JavaScript code.
137
     * (3) HTTP referrer information.
138
     * (4) Pageview frequency.
139
     *
140
     * @return void
141
     */
142
    protected function setupFilters(): void
143
    {
144
        $filters = [
145
            'session',
146
            'cookie',
147
            'referer',
148
        ];
149
150
        $settings = [];
151
        $filterConfig = [];
152
        $filterLimit = [];
153
154
        foreach ($filters as $filter) {
155
            $setting = $this->getOption($filter, 'filters');
156
157
            $settings[$filter] = $setting;
158
            $filterConfig[$filter] = $setting['enable'];
159
            $filterLimit[$filter] = $setting['config']['quota']; // default: 5
160
161
            unset($setting);
162
        }
163
164
        $settings['frequency'] = $this->getOption('frequency', 'filters');
165
        $filterConfig['frequency'] = $settings['frequency']['enable'];
166
167
        $this->kernel->setFilters($filterConfig);
168
169
        $this->kernel->setProperty(
170
            'limit_unusual_behavior',
171
            $filterLimit
172
        );
173
174
        $frequencyQuota = [
175
            's' => $settings['frequency']['config']['quota_s'],
176
            'm' => $settings['frequency']['config']['quota_m'],
177
            'h' => $settings['frequency']['config']['quota_h'],
178
            'd' => $settings['frequency']['config']['quota_d'],
179
        ];
180
181
        $this->kernel->setProperty('time_unit_quota', $frequencyQuota);
182
183
        $this->kernel->setProperty(
184
            'cookie_name',
185
            $settings['cookie']['config']['cookie_name'] // default: ssjd
186
        );
187
188
        $this->kernel->setProperty(
189
            'cookie_domain',
190
            $settings['cookie']['config']['cookie_domain'] // default: ''
191
        );
192
193
        $this->kernel->setProperty(
194
            'cookie_value',
195
            $settings['cookie']['config']['cookie_value'] // default: 1
196
        );
197
198
        $this->kernel->setProperty(
199
            'interval_check_referer',
200
            $settings['referer']['config']['time_buffer']
201
        );
202
203
        $this->kernel->setProperty(
204
            'interval_check_session',
205
            $settings['referer']['config']['time_buffer']
206
        );
207
    }
208
209
    /**
210
     * Components
211
     * 
212
     * (1) Ip
213
     * (2) Rdns
214
     * (3) Header
215
     * (4) User-agent
216
     * (5) Trusted bot
217
     *
218
     * @return void
219
     */
220
    protected function setupComponents(): void
221
    {
222
        $componentConfig = [
223
            'Ip'         => $this->getOption('ip', 'components'),
224
            'Rdns'       => $this->getOption('rdns', 'components'),
225
            'Header'     => $this->getOption('header', 'components'),
226
            'UserAgent'  => $this->getOption('user_agent', 'components'),
227
            'TrustedBot' => $this->getOption('trusted_bot', 'components'),
228
        ];
229
230
        foreach ($componentConfig as $className => $config) {
231
            $class = 'Shieldon\Firewall\Component\\' . $className;
232
233
            if ($config['enable']) {
234
                $componentInstance = new $class();
235
236
                if ($className === 'Ip') {
237
                    $this->kernel->setComponent($componentInstance);
238
239
                    // Need Ip component to be loaded before calling this method.
240
                    $this->setupAndApplyComponentIpManager();
241
                } else {
242
                    $componentInstance->setStrict($config['strict_mode']);
243
                    $this->kernel->setComponent($componentInstance);
244
                }
245
            }
246
        }
247
    }
248
249
    /**
250
     * Captcha modules.
251
     * 
252
     * (1) Google ReCaptcha
253
     * (2) Simple image captcha.
254
     *
255
     * @return void
256
     */
257
    protected function setupCaptchas(): void
258
    {
259
        $captchaList = [
260
            'recaptcha',
261
            'image',
262
        ];
263
264
        foreach ($captchaList as $captcha) {
265
            $setting = (array) $this->getOption($captcha, 'captcha_modules');
266
267
            // Initialize messenger instances from the factory/
268
            if (CaptchaFactory::check($setting)) {
269
270
                $this->kernel->setCaptcha(
271
                    CaptchaFactory::getInstance(
272
                        // The ID of the captcha module in the configuration.
273
                        $captcha, 
274
                        // The settings of the captcha module in the configuration.
275
                        $setting    
276
                    )
277
                );
278
            }
279
280
            unset($setting);
281
        }
282
    }
283
284
    /**
285
     * Set up the action logger.
286
     *
287
     * @return void
288
     */
289
    protected function setupLogger(): void
290
    {
291
        $loggerSetting = $this->getOption('action', 'loggers');
292
293
        if ($loggerSetting['enable']) {
294
            if (!empty($loggerSetting['config']['directory_path'])) {
295
                $this->kernel->setLogger(
296
                    new ActionLogger($loggerSetting['config']['directory_path'])
297
                );
298
            }
299
        }
300
    }
301
302
    /**
303
     * Apply the denied list and the allowed list to Ip Component.
304
     * 
305
     * @return void
306
     */
307
    protected function setupAndApplyComponentIpManager(): void
308
    {
309
        $ipList = (array) $this->getOption('ip_manager');
310
311
        $allowedList = [];
312
        $deniedList = [];
313
314
        foreach ($ipList as $ip) {
315
316
            if (0 === strpos($this->kernel->getCurrentUrl(), $ip['url']) ) {
317
318
                if ('allow' === $ip['rule']) {
319
                    $allowedList[] = $ip['ip'];
320
                }
321
322
                if ('deny' === $ip['rule']) {
323
                    $deniedList[] = $ip['ip'];
324
                }
325
            }
326
        }
327
328
        /** @scrutinizer ignore-call */ 
329
        $this->kernel->component['Ip']->setAllowedItems($allowedList);
330
331
        /** @scrutinizer ignore-call */ 
332
        $this->kernel->component['Ip']->setDeniedItems($deniedList);
333
    }
334
335
    /**
336
     * If you use CDN, please choose the real IP source.
337
     *
338
     * @return void
339
     */
340
    protected function setupIpSource(): void
341
    {
342
        $ipSourceType = $this->getOption('ip_variable_source');
343
        $serverParams = get_request()->getServerParams();
344
345
        /**
346
         * REMOTE_ADDR: general
347
         * HTTP_CF_CONNECTING_IP: Cloudflare
348
         * HTTP_X_FORWARDED_FOR: Google Cloud CDN, Google Load-balancer, AWS.
349
         * HTTP_X_FORWARDED_HOST: KeyCDN, or other CDN providers not listed here.
350
         */
351
        $key = array_search(true, $ipSourceType);
352
        $ip = $serverParams[$key];
353
354
        if (empty($ip)) {
355
356
            // @codeCoverageIgnoreStart
357
            throw new RuntimeException(
358
                'IP source is not set correctly.'
359
            );
360
            // @codeCoverageIgnoreEnd
361
        }
362
363
        $this->kernel->setIp($ip);
364
    }
365
366
    /**
367
     * Set deny attempts.
368
     *
369
     * @return void
370
     */
371
    protected function setupDenyTooManyAttempts(): void
372
    {
373
        $setting = $this->getOption('failed_attempts_in_a_row', 'events');
374
375
        $this->kernel->setProperty(
376
            'deny_attempt_enable',
377
            [
378
                'data_circle'     => $setting['data_circle']['enable'],     // false   
379
                'system_firewall' => $setting['system_firewall']['enable'], // false   
380
            ]
381
        );
382
383
        $this->kernel->setProperty(
384
            'deny_attempt_buffer',
385
            [
386
                'data_circle'     => $setting['data_circle']['buffer'],     // 10
387
                'system_firewall' => $setting['system_firewall']['buffer'], // 10
388
            ]
389
        );
390
391
        // Check the time of the last failed attempt.
392
        $recordAttempt = $this->getOption('record_attempt');
393
394
        $this->kernel->setProperty(
395
            'record_attempt_detection_period',
396
            $recordAttempt['detection_period'] // 5
397
        ); 
398
399
        $this->kernel->setProperty(
400
            'reset_attempt_counter',
401
            $recordAttempt['time_to_reset'] // 1800
402
        );  
403
    }
404
405
    /**
406
     * Set iptables working folder.
407
     *
408
     * @return void
409
     */
410
    protected function setupIptablesBridgeDirectory(): void
411
    {
412
        $iptablesSetting = $this->getOption('config', 'iptables');
413
414
        $this->kernel->setProperty(
415
            'iptables_watching_folder',
416
            $iptablesSetting['watching_folder']
417
        );
418
    }
419
420
    /**
421
     * Set the online session limit.
422
     *
423
     * @return void
424
     */
425
    protected function setupLimitSession(): void
426
    {
427
        $sessionLimitSetting = $this->getOption('online_session_limit');
428
429
        if ($sessionLimitSetting['enable']) {
430
431
            $onlineUsers = $sessionLimitSetting['config']['count']; // default: 100
432
            $alivePeriod = $sessionLimitSetting['config']['period']; // default: 300
433
434
            $this->kernel->limitSession($onlineUsers, $alivePeriod);
435
        }
436
    }
437
438
    /**
439
     * Set the cron job.
440
     * This is triggered by the pageviews, not system cron job.
441
     *
442
     * @return void
443
     */
444
    protected function setupCronJob(): void 
445
    {
446
        $cronjobSetting = $this->getOption('reset_circle', 'cronjob');
447
448
        if ($cronjobSetting['enable']) {
449
450
            $nowTime = time();
451
452
            $lastResetTime = $cronjobSetting['config']['last_update'];
453
454
            if (!empty($lastResetTime) ) {
455
                $lastResetTime = strtotime($lastResetTime);
456
            } else {
457
                // @codeCoverageIgnoreStart
458
459
                $lastResetTime = strtotime(date('Y-m-d 00:00:00'));
460
461
                // @codeCoverageIgnoreEnd
462
            }
463
464
            if (($nowTime - $lastResetTime) > $cronjobSetting['config']['period']) {
465
466
                $updateResetTime = date('Y-m-d 00:00:00');
467
468
                // Update new reset time.
469
                $this->setConfig(
470
                    'cronjob.reset_circle.config.last_update',
471
                    $updateResetTime
472
                );
473
474
                $this->updateConfig();
475
476
                // Remove all logs.
477
                /** @scrutinizer ignore-call */ 
478
                $this->kernel->driver->rebuild();
479
            }
480
        }
481
    }
482
483
    /**
484
     * Set the URLs that want to be excluded from Shieldon protection.
485
     *
486
     * @return void
487
     */
488
    protected function setupExcludedUrls(): void
489
    {
490
        $excludedUrls = $this->getOption('excluded_urls');
491
492
        if (!empty($excludedUrls)) {
493
            $list = array_column($excludedUrls, 'url');
494
495
            $this->kernel->setExcludedList($list);
496
        }
497
    }
498
499
    /**
500
     * WWW-Athentication.
501
     *
502
     * @return void
503
     */
504
    protected function setupPageAuthentication(): void
505
    {
506
        $authenticateList = $this->getOption('www_authenticate');
507
508
        if (is_array($authenticateList)) {
509
            $this->add(
510
                new HttpAuthentication($authenticateList)
511
            );
512
        }
513
    }
514
515
    /**
516
     * Set dialog UI.
517
     *
518
     * @return void
519
     */
520
    protected function setupDialogUserInterface()
521
    {
522
        $ui = $this->getOption('dialog_ui');
523
524
        if (!empty($ui)) {
525
            get_session()->set('shieldon_ui_lang', $ui['lang']);
526
            $this->kernel->setDialog($this->getOption('dialog_ui'));
527
        }
528
    }
529
}
530