Passed
Push — 2.x ( 10f0b2...b3dee1 )
by Terry
02:37
created

Kernel::enablePerformanceReport()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
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;
24
25
use Psr\Http\Message\ResponseInterface;
26
use Psr\Http\Message\ServerRequestInterface;
27
use Shieldon\Firewall\Captcha\Foundation;
28
use Shieldon\Firewall\Helpers;
29
use Shieldon\Firewall\HttpFactory;
30
use Shieldon\Firewall\IpTrait;
31
use Shieldon\Firewall\Kernel\CaptchaTrait;
32
use Shieldon\Firewall\Kernel\ComponentTrait;
33
use Shieldon\Firewall\Kernel\DriverTrait;
34
use Shieldon\Firewall\Kernel\FilterTrait;
35
use Shieldon\Firewall\Kernel\MessengerTrait;
36
use Shieldon\Firewall\Kernel\RuleTrait;
37
use Shieldon\Firewall\Kernel\SessionTrait;
38
use Shieldon\Firewall\Kernel\TemplateTrait;
39
use Shieldon\Firewall\Log\ActionLogger;
40
use Shieldon\Firewall\Container;
41
use Shieldon\Event\Event;
42
use Closure;
43
use function Shieldon\Firewall\get_default_properties;
44
use function Shieldon\Firewall\get_request;
45
use function Shieldon\Firewall\get_session_instance;
46
use function array_push;
47
use function get_class;
48
use function gethostbyaddr;
49
use function ltrim;
50
use function strpos;
51
use function strrpos;
52
use function substr;
53
use function time;
54
55
/**
56
 * The primary Shiendon class.
57
 */
58
class Kernel
59
{
60
    /**
61
     *   Public methods       | Desctiotion
62
     *  ----------------------|---------------------------------------------
63
     *   ban                  | Ban an IP.
64
     *   getCurrentUrl        | Get current user's browsing path.
65
     *   managedBy            | Used on testing purpose.
66
     *   run                  | Run the checking process.
67
     *   setClosure           | Set a closure function.
68
     *   exclude              | Set a URL you want them excluded them from protection.
69
     *   setExcludedList      | Set the URLs you want them excluded them from protection.
70
     *   setLogger            | Set the action log logger.
71
     *   setProperties        | Set the property settings.
72
     *   setProperty          | Set a property setting.
73
     *   setStrict            | Strict mode apply to all components.
74
     *   unban                | Unban an IP.
75
     *  ----------------------|---------------------------------------------
76
     */
77
78
    /**
79
     *   Public methods       | Desctiotion
80
     *  ----------------------|---------------------------------------------
81
     *   setIp                | Ban an IP.
82
     *   getIp                | Get current user's browsing path.
83
     *   setRdns              | Print a JavaScript snippet in the pages.
84
     *   getRdns              | Used on testing purpose.
85
     *  ----------------------|---------------------------------------------
86
     */
87
    use CaptchaTrait;
88
89
    /**
90
     *   Public methods       | Desctiotion
91
     *  ----------------------|---------------------------------------------
92
     *   setComponent         | Set a commponent.
93
     *   getComponent         | Get a component instance from component's container.
94
     *   disableComponents    | Disable all components.
95
     *  ----------------------|---------------------------------------------
96
     */
97
    use ComponentTrait;
98
99
    /**
100
     *   Public methods       | Desctiotion
101
     *  ----------------------|---------------------------------------------
102
     *   setDriver            | Set a data driver.
103
     *   setChannel           | Set a data channel.
104
     *   disableDbBuilder     | disable creating data tables.
105
     *  ----------------------|---------------------------------------------
106
     */
107
    use DriverTrait;
108
109
    /**
110
     *   Public methods       | Desctiotion
111
     *  ----------------------|---------------------------------------------
112
     *   setFilters           | Set the filters.
113
     *   setFilter            | Set a filter.
114
     *   disableFilters       | Disable all filters.
115
     *  ----------------------|---------------------------------------------
116
     */
117
    use FilterTrait;
118
119
    /**
120
     *   Public methods       | Desctiotion
121
     *  ----------------------|---------------------------------------------
122
     *   setIp                | Set an IP address.
123
     *   getIp                | Get current set IP.
124
     *   setRdns              | Set a RDNS record for the check.
125
     *   getRdns              | Get IP resolved hostname.
126
     *  ----------------------|---------------------------------------------
127
     */
128
    use IpTrait;
129
130
    /**
131
     *   Public methods       | Desctiotion
132
     *  ----------------------|---------------------------------------------
133
     *   setMessenger         | Set a messenger
134
     *  ----------------------|---------------------------------------------
135
     */
136
    use MessengerTrait;
137
138
    /**
139
     *   Public methods       | Desctiotion
140
     *  ----------------------|---------------------------------------------
141
     *                        | No public methods.
142
     *  ----------------------|---------------------------------------------
143
     */
144
    use RuleTrait;
145
146
    /**
147
     *   Public methods       | Desctiotion
148
     *  ----------------------|---------------------------------------------
149
     *   limitSession         | Limit the amount of the online users.
150
     *   getSessionCount      | Get the amount of the sessions.
151
     *   removeSessionsByIp   | Remove sessions using the same IP address.
152
     *  ----------------------|---------------------------------------------
153
     */
154
    use SessionTrait;
155
156
    /**
157
     *   Public methods       | Desctiotion
158
     *  ----------------------|---------------------------------------------
159
     *   respond              | Respond the result.
160
     *   setTemplateDirectory | Set the frontend template directory.
161
     *   getJavascript        | Print a JavaScript snippet in the pages.
162
     *  ----------------------|---------------------------------------------
163
     */
164
    use TemplateTrait;
165
166
    /**
167
     * HTTP Status Codes
168
     */
169
    const HTTP_STATUS_OK                 = 200;
170
    const HTTP_STATUS_SEE_OTHER          = 303;
171
    const HTTP_STATUS_BAD_REQUEST        = 400;
172
    const HTTP_STATUS_FORBIDDEN          = 403;
173
    const HTTP_STATUS_TOO_MANY_REQUESTS  = 429;
174
175
    /**
176
     * Reason Codes (ALLOW)
177
     */
178
    const REASON_IS_SEARCH_ENGINE        = 100;
179
    const REASON_IS_GOOGLE               = 101;
180
    const REASON_IS_BING                 = 102;
181
    const REASON_IS_YAHOO                = 103;
182
    const REASON_IS_SOCIAL_NETWORK       = 110;
183
    const REASON_IS_FACEBOOK             = 111;
184
    const REASON_IS_TWITTER              = 112;
185
186
    /**
187
     * Reason Codes (DENY)
188
     */
189
    const REASON_TOO_MANY_SESSIONS       = 1;
190
    const REASON_TOO_MANY_ACCESSES       = 2; // (not used)
191
    const REASON_EMPTY_JS_COOKIE         = 3;
192
    const REASON_EMPTY_REFERER           = 4;
193
    const REASON_REACHED_LIMIT_DAY       = 11;
194
    const REASON_REACHED_LIMIT_HOUR      = 12;
195
    const REASON_REACHED_LIMIT_MINUTE    = 13;
196
    const REASON_REACHED_LIMIT_SECOND    = 14;
197
    const REASON_INVALID_IP              = 40;
198
    const REASON_DENY_IP                 = 41;
199
    const REASON_ALLOW_IP                = 42;
200
    const REASON_COMPONENT_IP            = 81;
201
    const REASON_COMPONENT_RDNS          = 82;
202
    const REASON_COMPONENT_HEADER        = 83;
203
    const REASON_COMPONENT_USERAGENT     = 84;
204
    const REASON_COMPONENT_TRUSTED_ROBOT = 85;
205
    const REASON_MANUAL_BAN              = 99;
206
207
    /**
208
     * Action Codes
209
     */
210
    const ACTION_DENY                    = 0;
211
    const ACTION_ALLOW                   = 1;
212
    const ACTION_TEMPORARILY_DENY        = 2;
213
    const ACTION_UNBAN                   = 9;
214
215
    /**
216
     * Result Codes
217
     */
218
    const RESPONSE_DENY                  = 0;
219
    const RESPONSE_ALLOW                 = 1;
220
    const RESPONSE_TEMPORARILY_DENY      = 2;
221
    const RESPONSE_LIMIT_SESSION         = 3;
222
223
    /**
224
     * Logger Codes
225
     */
226
    const LOG_LIMIT                      = 3;
227
    const LOG_PAGEVIEW                   = 11;
228
    const LOG_BLACKLIST                  = 98;
229
    const LOG_CAPTCHA                    = 99;
230
231
    const KERNEL_DIR = __DIR__;
232
233
    /**
234
     * The result passed from filters, compoents, etc.
235
     * 
236
     * DENY    : 0
237
     * ALLOW   : 1
238
     * CAPTCHA : 2
239
     *
240
     * @var int
241
     */
242
    protected $result = 1;
243
244
    /**
245
     * Default settings
246
     *
247
     * @var array
248
     */
249
    protected $properties = [];
250
251
    /**
252
     * Logger instance.
253
     *
254
     * @var ActionLogger
255
     */
256
    public $logger;
257
258
    /**
259
     * The closure functions that will be executed in this->run()
260
     *
261
     * @var array
262
     */
263
    protected $closures = [];
264
265
    /**
266
     * URLs that are excluded from Shieldon's protection.
267
     *
268
     * @var array
269
     */
270
    protected $excludedUrls = [];
271
272
    /**
273
     * Strict mode.
274
     * 
275
     * Set by `strictMode()` only. The default value of this propertry is undefined.
276
     *
277
     * @var bool|null
278
     */
279
    protected $strictMode;
280
281
    /**
282
     * Which type of configuration source that Shieldon firewall managed?
283
     * value: managed | config | self | demo
284
     *
285
     * @var string
286
     */
287
    protected $firewallType = 'self'; 
288
289
    /**
290
     * The session cookie will be created by the PSR-7 HTTP resolver.
291
     * If this option is false, created by PHP native function `setcookie`.
292
     *
293
     * @var bool
294
     */
295
    public $psr7 = true;
296
297
    /**
298
     * Shieldon constructor.
299
     *
300
     * @param ServerRequestInterface|null $request  A PSR-7 server request.
301
     * @param ResponseInterface|null      $response A PSR-7 server response.
302
     *
303
     * @return void
304
     */
305
    public function __construct(?ServerRequestInterface $request = null, ?ResponseInterface $response = null)
306
    {
307
        // Load helper functions. This is the must and first.
308
        new Helpers();
309
310
        if (is_null($request)) {
311
            $request = HttpFactory::createRequest();
312
            $this->psr7 = false;
313
        }
314
315
        if (is_null($response)) {
316
            $response = HttpFactory::createResponse();
317
        }
318
319
        // Load default settings.
320
        $this->properties = get_default_properties();
321
322
        // Basic form for Captcha.
323
        $this->setCaptcha(new Foundation());
324
325
        Container::set('request', $request);
326
        Container::set('response', $response);
327
        Container::set('shieldon', $this);
328
329
        Event::AddListener('set_session_driver', function($args) {
330
            $session = get_session_instance();
331
332
            $session->init(
333
                $args['driver'],
334
                $args['gc_expires'],
335
                $args['gc_probability'],
336
                $args['gc_divisor'],
337
                $args['psr7']
338
            );
339
340
            /**
341
             * Hook - session_init
342
             */
343
            Event::doDispatch('session_init');
344
345
            set_session_instance($session);
346
        });
347
    }
348
349
    /**
350
     * Run, run, run!
351
     *
352
     * Check the rule tables first, if an IP address has been listed.
353
     * Call function filter() if an IP address is not listed in rule tables.
354
     *
355
     * @return int
356
     */
357
    public function run(): int
358
    {
359
        $this->assertDriver();
360
361
        // Ignore the excluded urls.
362
        foreach ($this->excludedUrls as $url) {
363
            if (strpos($this->getCurrentUrl(), $url) === 0) {
364
                return $this->result = self::RESPONSE_ALLOW;
365
            }
366
        }
367
368
        // Execute closure functions.
369
        foreach ($this->closures as $closure) {
370
            $closure();
371
        }
372
373
        $result = $this->process();
374
375
        if ($result !== self::RESPONSE_ALLOW) {
376
377
            // Current session did not pass the CAPTCHA, it is still stuck in 
378
            // CAPTCHA page.
379
            $actionCode = self::LOG_CAPTCHA;
380
381
            // If current session's respone code is RESPONSE_DENY, record it as 
382
            // `blacklist_count` in our logs.
383
            // It is stuck in warning page, not CAPTCHA.
384
            if ($result === self::RESPONSE_DENY) {
385
                $actionCode = self::LOG_BLACKLIST;
386
            }
387
388
            if ($result === self::RESPONSE_LIMIT_SESSION) {
389
                $actionCode = self::LOG_LIMIT;
390
            }
391
392
            $this->log($actionCode);
393
394
        } else {
395
396
            $this->log(self::LOG_PAGEVIEW);
397
        }
398
399
        // @ MessengerTrait
400
        $this->triggerMessengers();
401
402
        /**
403
         * Hook - kernel_end
404
         */
405
        Event::doDispatch('kernel_end');
406
407
        return $result;
408
    }
409
410
    /**
411
     * Ban an IP.
412
     *
413
     * @param string $ip A valid IP address.
414
     *
415
     * @return void
416
     */
417
    public function ban(string $ip = ''): void
418
    {
419
        if ('' === $ip) {
420
            $ip = $this->ip;
421
        }
422
 
423
        $this->action(
424
            self::ACTION_DENY,
425
            self::REASON_MANUAL_BAN,
426
            $ip
427
        );
428
    }
429
430
    /**
431
     * Unban an IP.
432
     *
433
     * @param string $ip A valid IP address.
434
     *
435
     * @return void
436
     */
437
    public function unban(string $ip = ''): void
438
    {
439
        if ($ip === '') {
440
            $ip = $this->ip;
441
        }
442
443
        $this->action(
444
            self::ACTION_UNBAN,
445
            self::REASON_MANUAL_BAN,
446
            $ip
447
        );
448
        $this->log(self::ACTION_UNBAN);
449
450
        $this->result = self::RESPONSE_ALLOW;
451
    }
452
453
    /**
454
     * Set a property setting.
455
     *
456
     * @param string $key   The key of a property setting.
457
     * @param mixed  $value The value of a property setting.
458
     *
459
     * @return void
460
     */
461
    public function setProperty(string $key = '', $value = '')
462
    {
463
        if (isset($this->properties[$key])) {
464
            $this->properties[$key] = $value;
465
        }
466
    }
467
468
    /**
469
     * Set the property settings.
470
     * 
471
     * @param array $settings The settings.
472
     *
473
     * @return void
474
     */
475
    public function setProperties(array $settings): void
476
    {
477
        foreach (array_keys($this->properties) as $k) {
478
            if (isset($settings[$k])) {
479
                $this->properties[$k] = $settings[$k];
480
            }
481
        }
482
    }
483
484
    /**
485
     * Strict mode.
486
     * This option will take effects to all components.
487
     * 
488
     * @param bool $bool Set true to enble strict mode, false to disable it overwise.
489
     *
490
     * @return void
491
     */
492
    public function setStrict(bool $bool)
493
    {
494
        $this->strictMode = $bool;
495
    }
496
497
    /**
498
     * Set an action log logger.
499
     *
500
     * @param ActionLogger $logger Record action logs for users.
501
     *
502
     * @return void
503
     */
504
    public function setLogger(ActionLogger $logger): void
505
    {
506
        $this->logger = $logger;
507
    }
508
509
    /**
510
     * Add a path into the excluded list.
511
     *
512
     * @param string $uriPath The path component of a URI.
513
     * 
514
     * @return void
515
     */
516
    public function exclude(string $uriPath): void
517
    {
518
        $uriPath = '/' . ltrim($uriPath, '/');
519
520
        array_push($this->excludedUrls, $uriPath);
521
    }
522
523
    /**
524
     * Set the URLs you want them excluded them from protection.
525
     *
526
     * @param array $urls The list of URL want to be excluded.
527
     *
528
     * @return void
529
     */
530
    public function setExcludedList(array $urls = []): void
531
    {
532
        $this->excludedUrls = $urls;
533
    }
534
535
    /**
536
     * Set a closure function.
537
     *
538
     * @param string  $key     The name for the closure class.
539
     * @param Closure $closure An instance will be later called.
540
     *
541
     * @return void
542
     */
543
    public function setClosure(string $key, Closure $closure): void
544
    {
545
        $this->closures[$key] = $closure;
546
    }
547
548
    /**
549
     * Get current visior's path.
550
     *
551
     * @return string
552
     */
553
    public function getCurrentUrl(): string
554
    {
555
        return get_request()->getUri()->getPath();
556
    }
557
558
    /**
559
     * Displayed on Firewall Panel, telling you current what type of 
560
     * configuration is used.
561
     * 
562
     * @param string $type The type of configuration.
563
     *                     accepted value: demo | managed | config
564
     *
565
     * @return void
566
     */
567
    public function managedBy(string $type = ''): void
568
    {
569
        if (in_array($type, ['managed', 'config', 'demo'])) {
570
            $this->firewallType = $type;
571
        }
572
    }
573
574
    /*
575
    |-------------------------------------------------------------------
576
    | Non-public methods.
577
    |-------------------------------------------------------------------
578
    */
579
580
    /**
581
     * Run, run, run!
582
     *
583
     * Check the rule tables first, if an IP address has been listed.
584
     * Call function filter() if an IP address is not listed in rule tables.
585
     *
586
     * @return int The response code.
587
     */
588
    protected function process(): int
589
    {
590
        $this->initComponents();
591
592
        $processMethods = [
593
            'isRuleExist',   // Stage 1 - Looking for rule table.
594
            'isTrustedBot',  // Stage 2 - Detect popular search engine.
595
            'isFakeRobot',   // Stage 3 - Reject fake search engine crawlers.
596
            'isIpComponent', // Stage 4 - IP manager.
597
            'isComponents'   // Stage 5 - Check other components.
598
        ];
599
600
        foreach ($processMethods as $method) {
601
            if ($this->{$method}()) {
602
                return $this->result;
603
            }
604
        }
605
606
        // Stage 6 - Check filters if set.
607
        if (array_search(true, $this->filterStatus)) {
608
            return $this->result = $this->sessionHandler($this->filter());
609
        }
610
611
        // Stage 7 - Go into session limit check.
612
        return $this->result = $this->sessionHandler(self::RESPONSE_ALLOW);
613
    }
614
615
    /**
616
     * Start an action for this IP address, allow or deny, and give a reason for it.
617
     *
618
     * @param int    $actionCode The action code. - 0: deny, 1: allow, 9: unban.
619
     * @param string $reasonCode The response code.
620
     * @param string $assignIp   The IP address.
621
     * 
622
     * @return void
623
     */
624
    protected function action(int $actionCode, int $reasonCode, string $assignIp = ''): void
625
    {
626
        $ip = $this->ip;
627
        $rdns = $this->rdns;
628
        $now = time();
629
        $logData = [];
630
    
631
        if ('' !== $assignIp) {
632
            $ip = $assignIp;
633
            $rdns = gethostbyaddr($ip);
634
        }
635
636
        if ($actionCode === self::ACTION_UNBAN) {
637
            $this->driver->delete($ip, 'rule');
638
        } else {
639
            $logData['log_ip']     = $ip;
640
            $logData['ip_resolve'] = $rdns;
641
            $logData['time']       = $now;
642
            $logData['type']       = $actionCode;
643
            $logData['reason']     = $reasonCode;
644
            $logData['attempts']   = 0;
645
646
            $this->driver->save($ip, $logData, 'rule');
647
        }
648
649
        // Remove logs for this IP address because It already has it's own rule on system.
650
        // No need to count for it anymore.
651
        $this->driver->delete($ip, 'filter');
652
653
        $this->removeSessionsByIp($ip);
654
655
        // Log this action.
656
        $this->log($actionCode, $ip);
657
658
        $this->reason = $reasonCode;
659
    }
660
661
    /**
662
     * Log actions.
663
     *
664
     * @param int    $actionCode The code number of the action.
665
     * @param string $ip         The IP address.
666
     *
667
     * @return void
668
     */
669
    protected function log(int $actionCode, $ip = ''): void
670
    {
671
        if (!$this->logger) {
672
            return;
673
        }
674
675
        $logData = [];
676
 
677
        $logData['ip'] = $ip ?: $this->getIp();
678
        $logData['session_id'] = get_session_instance()->getId();
679
        $logData['action_code'] = $actionCode;
680
        $logData['timesamp'] = time();
681
682
        $this->logger->add($logData);
683
    }
684
685
    /**
686
     * Get a class name without namespace string.
687
     *
688
     * @param object $instance Class
689
     * 
690
     * @return string
691
     */
692
    protected function getClassName($instance): string
693
    {
694
        $class = get_class($instance);
695
        return substr($class, strrpos($class, '\\') + 1); 
696
    }
697
698
    /**
699
     * Save and return the result identifier.
700
     * This method is for passing value from traits.
701
     *
702
     * @param int $resultCode The result identifier.
703
     *
704
     * @return int
705
     */
706
    protected function setResultCode(int $resultCode): int
707
    {
708
        return $this->result = $resultCode;
709
    }
710
}
711