Passed
Push — master ( fdf07c...5b75cb )
by Michael
13:50 queued 04:10
created

Protector::get_group1_ips()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 15
nc 18
nop 1
dl 0
loc 30
rs 8.4444
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * Class Protector
5
 */
6
class Protector
7
{
8
    public $mydirname;
9
10
    public $_conn;
11
    public $_conf            = array();
12
    public $_conf_serialized = '';
13
14
    public $_bad_globals = array();
15
16
    public $message                = '';
17
    public $warning                = false;
18
    public $error                  = false;
19
    public $_doubtful_requests     = array();
20
    public $_bigumbrella_doubtfuls = array();
21
22
    public $_dblayertrap_doubtfuls        = array();
23
    public $_dblayertrap_doubtful_needles = array(
24
        'information_schema',
25
        'select',
26
        "'",
27
        '"');
28
29
    public $_logged = false;
30
31
    public $_done_badext   = false;
32
    public $_done_intval   = false;
33
    public $_done_dotdot   = false;
34
    public $_done_nullbyte = false;
35
    public $_done_contami  = false;
36
    public $_done_isocom   = false;
37
    public $_done_union    = false;
38
    public $_done_dos      = false;
39
40
    public $_safe_badext  = true;
41
    public $_safe_contami = true;
42
    public $_safe_isocom  = true;
43
    public $_safe_union   = true;
44
45
    public $_spamcount_uri = 0;
46
47
    public $_should_be_banned_time0 = false;
48
    public $_should_be_banned       = false;
49
50
    public $_dos_stage;
51
52
    public $ip_matched_info;
53
54
    public $last_error_type = 'UNKNOWN';
55
56
    /**
57
     * Constructor
58
     */
59
    protected function __construct()
60
    {
61
        $this->mydirname = 'protector';
62
63
        // Preferences from configs/cache
64
        $this->_conf_serialized = @file_get_contents($this->get_filepath4confighcache());
65
        $this->_conf            = @unserialize($this->_conf_serialized, array('allowed_classes' => false));
0 ignored issues
show
Bug introduced by
It seems like $this->_conf_serialized can also be of type false; however, parameter $data of unserialize() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

65
        $this->_conf            = @unserialize(/** @scrutinizer ignore-type */ $this->_conf_serialized, array('allowed_classes' => false));
Loading history...
66
        if (empty($this->_conf)) {
67
            $this->_conf = array();
68
        }
69
70
        if (!empty($this->_conf['global_disabled'])) {
71
            return;
72
        }
73
74
        // die if PHP_SELF XSS found (disabled in 2.53)
75
        //    if ( preg_match( '/[<>\'";\n ]/' , @$_SERVER['PHP_SELF'] ) ) {
76
        //        $this->message .= "Invalid PHP_SELF '{$_SERVER['PHP_SELF']}' found.\n" ;
77
        //        $this->output_log( 'PHP_SELF XSS' ) ;
78
        //        die( 'invalid PHP_SELF' ) ;
79
        //    }
80
81
        // sanitize against PHP_SELF/PATH_INFO XSS (disabled in 3.33)
82
        //    $_SERVER['PHP_SELF'] = strtr( @$_SERVER['PHP_SELF'] , array( '<' => '%3C' , '>' => '%3E' , "'" => '%27' , '"' => '%22' ) ) ;
83
        //    if( ! empty( $_SERVER['PATH_INFO'] ) ) $_SERVER['PATH_INFO'] = strtr( @$_SERVER['PATH_INFO'] , array( '<' => '%3C' , '>' => '%3E' , "'" => '%27' , '"' => '%22' ) ) ;
84
85
        $this->_bad_globals = array(
86
            'GLOBALS',
87
            '_SESSION',
88
            'HTTP_SESSION_VARS',
89
            '_GET',
90
            'HTTP_GET_VARS',
91
            '_POST',
92
            'HTTP_POST_VARS',
93
            '_COOKIE',
94
            'HTTP_COOKIE_VARS',
95
            '_SERVER',
96
            'HTTP_SERVER_VARS',
97
            '_REQUEST',
98
            '_ENV',
99
            '_FILES',
100
            'xoopsDB',
101
            'xoopsUser',
102
            'xoopsUserId',
103
            'xoopsUserGroups',
104
            'xoopsUserIsAdmin',
105
            'xoopsConfig',
106
            'xoopsOption',
107
            'xoopsModule',
108
            'xoopsModuleConfig');
109
110
        $this->_initial_recursive($_GET, 'G');
111
        $this->_initial_recursive($_POST, 'P');
112
        $this->_initial_recursive($_COOKIE, 'C');
113
    }
114
115
    /**
116
     * @param $val
117
     * @param $key
118
     */
119
    protected function _initial_recursive($val, $key)
120
    {
121
        if (is_array($val)) {
122
            foreach ($val as $subkey => $subval) {
123
                // check bad globals
124
                if (in_array($subkey, $this->_bad_globals, true)) {
125
                    $this->message .= "Attempt to inject '$subkey' was found.\n";
126
                    $this->_safe_contami   = false;
127
                    $this->last_error_type = 'CONTAMI';
128
                }
129
                $this->_initial_recursive($subval, $key . '_' . base64_encode($subkey));
130
            }
131
        } else {
132
            // check nullbyte attack
133
            if (@$this->_conf['san_nullbyte'] && false !== strpos($val, chr(0))) {
134
                $val = str_replace(chr(0), ' ', $val);
135
                $this->replace_doubtful($key, $val);
136
                $this->message .= "Injecting Null-byte '$val' found.\n";
137
                $this->output_log('NullByte', 0, false, 32);
138
                // $this->purge() ;
139
            }
140
141
            // register as doubtful requests against SQL Injections
142
            if (preg_match('?[\s\'"`/]?', $val)) {
143
                $this->_doubtful_requests["$key"] = $val;
144
            }
145
        }
146
    }
147
148
    /**
149
     * @return Protector
150
     */
151
    public static function getInstance()
152
    {
153
        static $instance;
154
        if (!isset($instance)) {
155
            $instance = new Protector();
156
        }
157
158
        return $instance;
159
    }
160
161
    /**
162
     * @return bool
163
     */
164
    public function updateConfFromDb()
165
    {
166
        $constpref = '_MI_' . strtoupper($this->mydirname);
167
168
        if (empty($this->_conn)) {
169
            return false;
170
        }
171
172
        $result = @mysqli_query($this->_conn, 'SELECT conf_name,conf_value FROM ' . XOOPS_DB_PREFIX . "_config WHERE conf_title like '" . $constpref . "%'");
173
        if (!$result || mysqli_num_rows($result) < 5) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $result of mysqli_num_rows() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

173
        if (!$result || mysqli_num_rows(/** @scrutinizer ignore-type */ $result) < 5) {
Loading history...
174
            return false;
175
        }
176
        $db_conf = array();
177
        while (list($key, $val) = mysqli_fetch_row($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $result of mysqli_fetch_row() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

177
        while (list($key, $val) = mysqli_fetch_row(/** @scrutinizer ignore-type */ $result)) {
Loading history...
178
            $db_conf[$key] = $val;
179
        }
180
        $db_conf_serialized = serialize($db_conf);
181
182
        // update config cache
183
        if ($db_conf_serialized != $this->_conf_serialized) {
184
            $fp = fopen($this->get_filepath4confighcache(), 'w');
185
            fwrite($fp, $db_conf_serialized);
186
            fclose($fp);
187
            $this->_conf = $db_conf;
188
        }
189
190
        return true;
191
    }
192
193
    /**
194
     * @param $conn
195
     */
196
    public function setConn($conn)
197
    {
198
        $this->_conn = $conn;
199
    }
200
201
    /**
202
     * @return array
203
     */
204
    public function getConf()
205
    {
206
        return $this->_conf;
207
    }
208
209
    /**
210
     * @param bool $redirect_to_top
211
     */
212
    public function purge($redirect_to_top = false)
213
    {
214
        $this->purgeNoExit();
215
216
        if ($redirect_to_top) {
217
            header('Location: ' . XOOPS_URL . '/');
218
            exit;
219
        } else {
220
            $ret = $this->call_filter('prepurge_exit');
221
            if ($ret == false) {
222
                die('Protector detects attacking actions');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
223
            }
224
        }
225
    }
226
227
    public function purgeSession()
228
    {
229
        // clear all session values
230
        if (isset($_SESSION)) {
231
            foreach ($_SESSION as $key => $val) {
232
                $_SESSION[$key] = '';
233
                if (isset($GLOBALS[$key])) {
234
                    $GLOBALS[$key] = '';
235
                }
236
            }
237
        }
238
    }
239
240
    public function purgeCookies()
241
    {
242
        if (!headers_sent()) {
243
            $domain =  defined(XOOPS_COOKIE_DOMAIN) ? XOOPS_COOKIE_DOMAIN : '';
244
            $past = time() - 3600;
245
            foreach ($_COOKIE as $key => $value) {
246
                setcookie($key, '', $past, '', $domain);
247
                setcookie($key, '', $past, '/', $domain);
248
            }
249
        }
250
    }
251
252
    public function purgeNoExit()
253
    {
254
        $this->purgeSession();
255
        $this->purgeCookies();
256
    }
257
258
    public function deactivateCurrentUser()
259
    {
260
        /* @var XoopsUser $xoopsUser */
261
        global $xoopsUser;
262
263
        if (is_object($xoopsUser)) {
264
            /** @var XoopsMemberHandler */
265
            $userHandler = xoops_getHandler('user');
266
            $xoopsUser->setVar('level', 0);
267
            $actkey = substr(md5(uniqid(mt_rand(), 1)), 0, 8);
268
            $xoopsUser->setVar('actkey', $actkey);
269
            $userHandler->insert($xoopsUser);
270
        }
271
        $this->purgeNoExit();
272
    }
273
274
    /**
275
     * @param string $type
276
     * @param int    $uid
277
     * @param bool   $unique_check
278
     * @param int    $level
279
     *
280
     * @return bool
281
     */
282
    public function output_log($type = 'UNKNOWN', $uid = 0, $unique_check = false, $level = 1)
283
    {
284
        if ($this->_logged) {
285
            return true;
286
        }
287
288
        if (!($this->_conf['log_level'] & $level)) {
289
            return true;
290
        }
291
292
        if (empty($this->_conn)) {
293
            mysqli_report(MYSQLI_REPORT_OFF);
294
            $this->_conn = new mysqli(XOOPS_DB_HOST, XOOPS_DB_USER, XOOPS_DB_PASS);
295
            if (0 !== $this->_conn->connect_errno) {
296
                die('db connection failed.');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
297
            }
298
            if (!mysqli_select_db($this->_conn, XOOPS_DB_NAME)) {
299
                die('db selection failed.');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
300
            }
301
        }
302
303
        $ip    = \Xmf\IPAddress::fromRequest()->asReadable();
304
        $agent = @$_SERVER['HTTP_USER_AGENT'];
305
306
        if ($unique_check) {
307
            $result = mysqli_query($this->_conn, 'SELECT ip,type FROM ' . XOOPS_DB_PREFIX . '_' . $this->mydirname . '_log ORDER BY timestamp DESC LIMIT 1');
308
            list($last_ip, $last_type) = mysqli_fetch_row($result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $result of mysqli_fetch_row() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

308
            list($last_ip, $last_type) = mysqli_fetch_row(/** @scrutinizer ignore-type */ $result);
Loading history...
309
            if ($last_ip == $ip && $last_type == $type) {
310
                $this->_logged = true;
311
312
                return true;
313
            }
314
        }
315
316
        mysqli_query(
317
            $this->_conn,
318
            'INSERT INTO ' . XOOPS_DB_PREFIX . '_' . $this->mydirname . "_log SET ip='"
319
            . mysqli_real_escape_string($this->_conn, $ip) . "',agent='"
320
            . mysqli_real_escape_string($this->_conn, $agent) . "',type='"
321
            . mysqli_real_escape_string($this->_conn, $type) . "',description='"
322
            . mysqli_real_escape_string($this->_conn, $this->message) . "',uid='"
323
            . (int)$uid . "',timestamp=NOW()"
324
        );
325
        $this->_logged = true;
326
327
        return true;
328
    }
329
330
    /**
331
     * @param $expire
332
     *
333
     * @return bool
334
     */
335
    public function write_file_bwlimit($expire)
336
    {
337
        $expire = min((int)$expire, time() + 300);
338
339
        $fp = @fopen($this->get_filepath4bwlimit(), 'w');
340
        if ($fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
341
            @flock($fp, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for flock(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

341
            /** @scrutinizer ignore-unhandled */ @flock($fp, LOCK_EX);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
342
            fwrite($fp, $expire . "\n");
343
            @flock($fp, LOCK_UN);
344
            fclose($fp);
345
346
            return true;
347
        } else {
348
            return false;
349
        }
350
    }
351
352
    /**
353
     * @return mixed
354
     */
355
    public function get_bwlimit()
356
    {
357
        list($expire) = @file(Protector::get_filepath4bwlimit());
358
        $expire = min((int)$expire, time() + 300);
359
360
        return $expire;
361
    }
362
363
    /**
364
     * @return string
365
     */
366
    public static function get_filepath4bwlimit()
367
    {
368
        return XOOPS_VAR_PATH . '/protector/bwlimit' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
369
    }
370
371
    /**
372
     * @param $bad_ips
373
     *
374
     * @return bool
375
     */
376
    public function write_file_badips($bad_ips)
377
    {
378
        asort($bad_ips);
379
380
        $fp = @fopen($this->get_filepath4badips(), 'w');
381
        if ($fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
382
            @flock($fp, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for flock(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

382
            /** @scrutinizer ignore-unhandled */ @flock($fp, LOCK_EX);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
383
            fwrite($fp, serialize($bad_ips) . "\n");
384
            @flock($fp, LOCK_UN);
385
            fclose($fp);
386
387
            return true;
388
        } else {
389
            return false;
390
        }
391
    }
392
393
    /**
394
     * @param int  $jailed_time
395
     * @param null|string|false $ip
396
     *
397
     * @return bool
398
     */
399
    public function register_bad_ips($jailed_time = 0, $ip = null)
400
    {
401
        if (empty($ip)) {
402
            $ip = \Xmf\IPAddress::fromRequest()->asReadable();
403
        }
404
        if (empty($ip)) {
405
            return false;
406
        }
407
408
        $bad_ips      = $this->get_bad_ips(true);
409
        $bad_ips[$ip] = $jailed_time ?: 0x7fffffff;
410
411
        return $this->write_file_badips($bad_ips);
412
    }
413
414
    /**
415
     * @param bool $with_jailed_time
416
     *
417
     * @return array|mixed
418
     */
419
    public function get_bad_ips($with_jailed_time = false)
420
    {
421
        //        list($bad_ips_serialized) = @file(Protector::get_filepath4badips());
422
        $filepath4badips = @file(Protector::get_filepath4badips());
423
424
        if (is_array($filepath4badips) && isset($filepath4badips[0])) {
425
            list($bad_ips_serialized) = $filepath4badips;
426
        }
427
        $bad_ips = empty($bad_ips_serialized) ? array() : @unserialize($bad_ips_serialized, array('allowed_classes' => false));
428
        if (!is_array($bad_ips) || isset($bad_ips[0])) {
429
            $bad_ips = array();
430
        }
431
432
        // expire jailed_time
433
        $pos = 0;
434
        foreach ($bad_ips as $bad_ip => $jailed_time) {
435
            if ($jailed_time >= time()) {
436
                break;
437
            }
438
            ++$pos;
439
        }
440
        $bad_ips = array_slice($bad_ips, $pos);
441
442
        if ($with_jailed_time) {
443
            return $bad_ips;
444
        } else {
445
            return array_keys($bad_ips);
446
        }
447
    }
448
449
    /**
450
     * @return string
451
     */
452
    public static function get_filepath4badips()
453
    {
454
        return XOOPS_VAR_PATH . '/protector/badips' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
455
    }
456
457
    /**
458
     * @param bool $with_info
459
     *
460
     * @return array|mixed
461
     */
462
    public function get_group1_ips($with_info = false)
463
    {
464
        //        list($group1_ips_serialized) = @file(Protector::get_filepath4group1ips());
465
        $group1_ips = [];
466
        // Check if the file exists before attempting to read it
467
        $filepath = Protector::get_filepath4group1ips();
468
        if (file_exists($filepath)) {
469
            $filepath4group1ips = file($filepath);
470
            if ($filepath4group1ips === false) {
471
                // Handle the error condition when file reading fails
472
            } else {
473
                // Proceed with your logic here
474
                if (is_array($filepath4group1ips) && isset($filepath4group1ips[0])) {
475
                    list($group1_ips_serialized) = $filepath4group1ips;
476
                }
477
478
                $group1_ips = empty($group1_ips_serialized) ? array() : @unserialize($group1_ips_serialized, array('allowed_classes' => false));
479
                if (!is_array($group1_ips)) {
480
                    $group1_ips = array();
481
                }
482
483
                if ($with_info) {
484
                    $group1_ips = array_flip($group1_ips);
485
                }
486
            }
487
        } else {
488
            // File does not exist; handle this condition
489
        }
490
491
        return $group1_ips;
492
    }
493
494
    /**
495
     * @return string
496
     */
497
    public static function get_filepath4group1ips()
498
    {
499
        return XOOPS_VAR_PATH . '/protector/group1ips' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
500
    }
501
502
    /**
503
     * @return string
504
     */
505
    public function get_filepath4confighcache()
506
    {
507
        return XOOPS_VAR_PATH . '/protector/configcache' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
508
    }
509
510
    /**
511
     * @param $ips
512
     *
513
     * @return bool
514
     */
515
    public function ip_match($ips)
516
    {
517
        $requestIp = \Xmf\IPAddress::fromRequest()->asReadable();
518
        if (false === $requestIp) { // nothing to match
0 ignored issues
show
introduced by
The condition false === $requestIp is always false.
Loading history...
519
            $this->ip_matched_info = null;
520
            return false;
521
        }
522
        foreach ($ips as $ip => $info) {
523
            if ($ip) {
524
                switch (strtolower(substr($ip, -1))) {
525
                    case '.' :
526
                    case ':' :
527
                        // foward match
528
                        if (substr($requestIp, 0, strlen($ip)) == $ip) {
529
                            $this->ip_matched_info = $info;
530
                            return true;
531
                        }
532
                        break;
533
                    case '0' :
534
                    case '1' :
535
                    case '2' :
536
                    case '3' :
537
                    case '4' :
538
                    case '5' :
539
                    case '6' :
540
                    case '7' :
541
                    case '8' :
542
                    case '9' :
543
                    case 'a' :
544
                    case 'b' :
545
                    case 'c' :
546
                    case 'd' :
547
                    case 'e' :
548
                    case 'f' :
549
                        // full match
550
                        if ($requestIp == $ip) {
551
                            $this->ip_matched_info = $info;
552
                            return true;
553
                        }
554
                        break;
555
                    default :
556
                        // perl regex
557
                        if (@preg_match($ip, $requestIp)) {
558
                            $this->ip_matched_info = $info;
559
                            return true;
560
                        }
561
                        break;
562
                }
563
            }
564
        }
565
        $this->ip_matched_info = null;
566
        return false;
567
    }
568
569
    /**
570
     * @param null|string|false $ip
571
     *
572
     * @return bool
573
     */
574
    public function deny_by_htaccess($ip = null)
575
    {
576
        if (empty($ip)) {
577
            $ip = \Xmf\IPAddress::fromRequest()->asReadable();
578
        }
579
        if (empty($ip)) {
580
            return false;
581
        }
582
        if (!function_exists('file_get_contents')) {
583
            return false;
584
        }
585
586
        $target_htaccess = XOOPS_ROOT_PATH . '/.htaccess';
587
        $backup_htaccess = XOOPS_ROOT_PATH . '/uploads/.htaccess.bak';
588
589
        $ht_body = file_get_contents($target_htaccess);
590
591
        // make backup as uploads/.htaccess.bak automatically
592
        if ($ht_body && !file_exists($backup_htaccess)) {
593
            $fw = fopen($backup_htaccess, 'w');
594
            fwrite($fw, $ht_body);
595
            fclose($fw);
596
        }
597
598
        // if .htaccess is broken, restore from backup
599
        if (!$ht_body && file_exists($backup_htaccess)) {
600
            $ht_body = file_get_contents($backup_htaccess);
601
        }
602
603
        // new .htaccess
604
        if ($ht_body === false) {
605
            $ht_body = '';
606
        }
607
608
        if (preg_match("/^(.*)#PROTECTOR#\s+(DENY FROM .*)\n#PROTECTOR#\n(.*)$/si", $ht_body, $regs)) {
609
            if (substr($regs[2], -strlen($ip)) == $ip) {
610
                return true;
611
            }
612
            $new_ht_body = $regs[1] . "#PROTECTOR#\n" . $regs[2] . " $ip\n#PROTECTOR#\n" . $regs[3];
613
        } else {
614
            $new_ht_body = "#PROTECTOR#\nDENY FROM $ip\n#PROTECTOR#\n" . $ht_body;
615
        }
616
617
        // error_log( "$new_ht_body\n" , 3 , "/tmp/error_log" ) ;
618
619
        $fw = fopen($target_htaccess, 'w');
620
        @flock($fw, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for flock(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

620
        /** @scrutinizer ignore-unhandled */ @flock($fw, LOCK_EX);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
621
        fwrite($fw, $new_ht_body);
622
        @flock($fw, LOCK_UN);
623
        fclose($fw);
624
625
        return true;
626
    }
627
628
    /**
629
     * @return array
630
     */
631
    public function getDblayertrapDoubtfuls()
632
    {
633
        return $this->_dblayertrap_doubtfuls;
634
    }
635
636
    /**
637
     * @param $val
638
     * @return null
639
     */
640
    protected function _dblayertrap_check_recursive($val)
641
    {
642
        if (is_array($val)) {
643
            foreach ($val as $subval) {
644
                $this->_dblayertrap_check_recursive($subval);
645
            }
646
        } else {
647
            if (strlen($val) < 6) {
648
                return null;
649
            }
650
            $val = @get_magic_quotes_gpc() ? stripslashes($val) : $val;
651
            foreach ($this->_dblayertrap_doubtful_needles as $needle) {
652
                if (false !== stripos($val, $needle)) {
653
                    $this->_dblayertrap_doubtfuls[] = $val;
654
                }
655
            }
656
        }
657
    }
658
659
    /**
660
     * @param  bool $force_override
661
     * @return null
662
     */
663
    public function dblayertrap_init($force_override = false)
664
    {
665
        if (!empty($GLOBALS['xoopsOption']['nocommon']) || defined('_LEGACY_PREVENT_EXEC_COMMON_') || defined('_LEGACY_PREVENT_LOAD_CORE_')) {
666
            return null;
667
        } // skip
668
669
        $this->_dblayertrap_doubtfuls = array();
670
        $this->_dblayertrap_check_recursive($_GET);
671
        $this->_dblayertrap_check_recursive($_POST);
672
        $this->_dblayertrap_check_recursive($_COOKIE);
673
        if (empty($this->_conf['dblayertrap_wo_server'])) {
674
            $this->_dblayertrap_check_recursive($_SERVER);
675
        }
676
677
        if (!empty($this->_dblayertrap_doubtfuls) || $force_override) {
678
            @define('XOOPS_DB_ALTERNATIVE', 'ProtectorMysqlDatabase');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for define(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

678
            /** @scrutinizer ignore-unhandled */ @define('XOOPS_DB_ALTERNATIVE', 'ProtectorMysqlDatabase');

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
679
            require_once dirname(__DIR__) . '/class/ProtectorMysqlDatabase.class.php';
680
        }
681
    }
682
683
    /**
684
     * @param $val
685
     */
686
    protected function _bigumbrella_check_recursive($val)
687
    {
688
        if (is_array($val)) {
689
            foreach ($val as $subval) {
690
                $this->_bigumbrella_check_recursive($subval);
691
            }
692
        } else {
693
            if (preg_match('/[<\'"].{15}/s', $val, $regs)) {
694
                $this->_bigumbrella_doubtfuls[] = $regs[0];
695
            }
696
        }
697
    }
698
699
    public function bigumbrella_init()
700
    {
701
        $this->_bigumbrella_doubtfuls = array();
702
        $this->_bigumbrella_check_recursive($_GET);
703
        $this->_bigumbrella_check_recursive(@$_SERVER['PHP_SELF']);
704
705
        if (!empty($this->_bigumbrella_doubtfuls)) {
706
            ob_start(array($this, 'bigumbrella_outputcheck'));
707
        }
708
    }
709
710
    /**
711
     * @param $s
712
     *
713
     * @return string
714
     */
715
    public function bigumbrella_outputcheck($s)
716
    {
717
        if (defined('BIGUMBRELLA_DISABLED')) {
718
            return $s;
719
        }
720
721
        if (function_exists('headers_list')) {
722
            foreach (headers_list() as $header) {
723
                if (false !== stripos($header, 'Content-Type:') && false === stripos($header, 'text/html')) {
724
                    return $s;
725
                }
726
            }
727
        }
728
729
        if (!is_array($this->_bigumbrella_doubtfuls)) {
0 ignored issues
show
introduced by
The condition is_array($this->_bigumbrella_doubtfuls) is always true.
Loading history...
730
            return 'bigumbrella injection found.';
731
        }
732
733
        foreach ($this->_bigumbrella_doubtfuls as $doubtful) {
734
            if (false !== strpos($s, $doubtful)) {
735
                return 'XSS found by Protector.';
736
            }
737
        }
738
739
        return $s;
740
    }
741
742
    /**
743
     * @return bool
744
     */
745
    public function intval_allrequestsendid()
746
    {
747
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
748
749
        if ($this->_done_intval) {
750
            return true;
751
        } else {
752
            $this->_done_intval = true;
753
        }
754
755
        foreach ($_GET as $key => $val) {
756
            if (substr($key, -2) === 'id' && !is_array($_GET[$key])) {
757
                $newval     = preg_replace('/[^0-9a-zA-Z_-]/', '', $val);
758
                $_GET[$key] = $HTTP_GET_VARS[$key] = $newval;
759
                if ($_REQUEST[$key] == $_GET[$key]) {
760
                    $_REQUEST[$key] = $newval;
761
                }
762
            }
763
        }
764
        foreach ($_POST as $key => $val) {
765
            if (substr($key, -2) === 'id' && !is_array($_POST[$key])) {
766
                $newval      = preg_replace('/[^0-9a-zA-Z_-]/', '', $val);
767
                $_POST[$key] = $HTTP_POST_VARS[$key] = $newval;
768
                if ($_REQUEST[$key] == $_POST[$key]) {
769
                    $_REQUEST[$key] = $newval;
770
                }
771
            }
772
        }
773
        foreach ($_COOKIE as $key => $val) {
774
            if (substr($key, -2) === 'id' && !is_array($_COOKIE[$key])) {
775
                $newval        = preg_replace('/[^0-9a-zA-Z_-]/', '', $val);
776
                $_COOKIE[$key] = $HTTP_COOKIE_VARS[$key] = $newval;
777
                if ($_REQUEST[$key] == $_COOKIE[$key]) {
778
                    $_REQUEST[$key] = $newval;
779
                }
780
            }
781
        }
782
783
        return true;
784
    }
785
786
    /**
787
     * @return bool
788
     */
789
    public function eliminate_dotdot()
790
    {
791
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
792
793
        if ($this->_done_dotdot) {
794
            return true;
795
        } else {
796
            $this->_done_dotdot = true;
797
        }
798
799
        foreach ($_GET as $key => $val) {
800
            if (is_array($_GET[$key])) {
801
                continue;
802
            }
803
            if (substr(trim($val), 0, 3) === '../' || false !== strpos($val, '/../')) {
804
                $this->last_error_type = 'DirTraversal';
805
                $this->message .= "Directory Traversal '$val' found.\n";
806
                $this->output_log($this->last_error_type, 0, false, 64);
807
                $sanitized_val = str_replace(chr(0), '', $val);
808
                if (substr($sanitized_val, -2) !== ' .') {
809
                    $sanitized_val .= ' .';
810
                }
811
                $_GET[$key] = $HTTP_GET_VARS[$key] = $sanitized_val;
812
                if ($_REQUEST[$key] == $_GET[$key]) {
813
                    $_REQUEST[$key] = $sanitized_val;
814
                }
815
            }
816
        }
817
818
        /*    foreach ($_POST as $key => $val) {
819
                if( is_array( $_POST[ $key ] ) ) continue ;
820
                if ( substr( trim( $val ) , 0 , 3 ) == '../' || false !== strpos( $val , '../../' ) ) {
821
                    $this->last_error_type = 'ParentDir' ;
822
                    $this->message .= "Doubtful file specification '$val' found.\n" ;
823
                    $this->output_log( $this->last_error_type , 0 , false , 128 ) ;
824
                    $sanitized_val = str_replace( chr(0) , '' , $val ) ;
825
                    if( substr( $sanitized_val , -2 ) != ' .' ) $sanitized_val .= ' .' ;
826
                    $_POST[ $key ] = $HTTP_POST_VARS[ $key ] = $sanitized_val ;
827
                    if ($_REQUEST[ $key ] == $_POST[ $key ]) {
828
                        $_REQUEST[ $key ] = $sanitized_val ;
829
                    }
830
                }
831
            }
832
            foreach ($_COOKIE as $key => $val) {
833
                if( is_array( $_COOKIE[ $key ] ) ) continue ;
834
                if ( substr( trim( $val ) , 0 , 3 ) == '../' || false !== strpos( $val , '../../' ) ) {
835
                    $this->last_error_type = 'ParentDir' ;
836
                    $this->message .= "Doubtful file specification '$val' found.\n" ;
837
                    $this->output_log( $this->last_error_type , 0 , false , 128 ) ;
838
                    $sanitized_val = str_replace( chr(0) , '' , $val ) ;
839
                    if( substr( $sanitized_val , -2 ) != ' .' ) $sanitized_val .= ' .' ;
840
                    $_COOKIE[ $key ] = $HTTP_COOKIE_VARS[ $key ] = $sanitized_val ;
841
                    if ($_REQUEST[ $key ] == $_COOKIE[ $key ]) {
842
                        $_REQUEST[ $key ] = $sanitized_val ;
843
                    }
844
                }
845
            }*/
846
847
        return true;
848
    }
849
850
    /**
851
     * @param $current
852
     * @param $indexes
853
     *
854
     * @return bool
855
     */
856
    public function &get_ref_from_base64index(&$current, $indexes)
857
    {
858
        foreach ($indexes as $index) {
859
            $index = base64_decode($index);
860
            if (!is_array($current)) {
861
                return false;
862
            }
863
            $current =& $current[$index];
864
        }
865
866
        return $current;
867
    }
868
869
    /**
870
     * @param $key
871
     * @param $val
872
     */
873
    public function replace_doubtful($key, $val)
874
    {
875
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
876
877
        $index_expression = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $index_expression is dead and can be removed.
Loading history...
878
        $indexes          = explode('_', $key);
879
        $base_array       = array_shift($indexes);
880
881
        switch ($base_array) {
882
            case 'G' :
883
                $main_ref   =& $this->get_ref_from_base64index($_GET, $indexes);
884
                $legacy_ref =& $this->get_ref_from_base64index($HTTP_GET_VARS, $indexes);
885
                break;
886
            case 'P' :
887
                $main_ref   =& $this->get_ref_from_base64index($_POST, $indexes);
888
                $legacy_ref =& $this->get_ref_from_base64index($HTTP_POST_VARS, $indexes);
889
                break;
890
            case 'C' :
891
                $main_ref   =& $this->get_ref_from_base64index($_COOKIE, $indexes);
892
                $legacy_ref =& $this->get_ref_from_base64index($HTTP_COOKIE_VARS, $indexes);
893
                break;
894
            default :
895
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
896
        }
897
        if (!isset($main_ref)) {
898
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
899
        }
900
        $request_ref =& $this->get_ref_from_base64index($_REQUEST, $indexes);
901
        if ($request_ref !== false && $main_ref == $request_ref) {
902
            $request_ref = $val;
903
        }
904
        $main_ref   = $val;
905
        $legacy_ref = $val;
906
    }
907
908
    /**
909
     * @return bool
910
     */
911
    public function check_uploaded_files()
912
    {
913
        if ($this->_done_badext) {
914
            return $this->_safe_badext;
915
        } else {
916
            $this->_done_badext = true;
917
        }
918
919
        // extensions never uploaded
920
        $bad_extensions = array('php', 'phtml', 'phtm', 'php3', 'php4', 'cgi', 'pl', 'asp');
921
        // extensions needed image check (anti-IE Content-Type XSS)
922
        $image_extensions = array(
923
            1  => 'gif',
924
            2  => 'jpg',
925
            3  => 'png',
926
            4  => 'swf',
927
            5  => 'psd',
928
            6  => 'bmp',
929
            7  => 'tif',
930
            8  => 'tif',
931
            9  => 'jpc',
932
            10 => 'jp2',
933
            11 => 'jpx',
934
            12 => 'jb2',
935
            13 => 'swc',
936
            14 => 'iff',
937
            15 => 'wbmp',
938
            16 => 'xbm');
939
940
        foreach ($_FILES as $_file) {
941
            if (!empty($_file['error'])) {
942
                continue;
943
            }
944
            if (!empty($_file['name']) && is_string($_file['name'])) {
945
                $ext = strtolower(substr(strrchr($_file['name'], '.'), 1));
946
                if ($ext === 'jpeg') {
947
                    $ext = 'jpg';
948
                } elseif ($ext === 'tiff') {
949
                    $ext = 'tif';
950
                }
951
952
                // anti multiple dot file (Apache mod_mime.c)
953
                if (count(explode('.', str_replace('.tar.gz', '.tgz', $_file['name']))) > 2) {
954
                    $this->message .= "Attempt to multiple dot file {$_file['name']}.\n";
955
                    $this->_safe_badext    = false;
956
                    $this->last_error_type = 'UPLOAD';
957
                }
958
959
                // anti dangerous extensions
960
                if (in_array($ext, $bad_extensions)) {
961
                    $this->message .= "Attempt to upload {$_file['name']}.\n";
962
                    $this->_safe_badext    = false;
963
                    $this->last_error_type = 'UPLOAD';
964
                }
965
966
                // anti camouflaged image file
967
                if (in_array($ext, $image_extensions)) {
968
                    $image_attributes = @getimagesize($_file['tmp_name']);
969
                    if ($image_attributes === false && is_uploaded_file($_file['tmp_name'])) {
970
                        // open_basedir restriction
971
                        $temp_file = XOOPS_ROOT_PATH . '/uploads/protector_upload_temporary' . md5(time());
972
                        move_uploaded_file($_file['tmp_name'], $temp_file);
973
                        $image_attributes = @getimagesize($temp_file);
974
                        @unlink($temp_file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

974
                        /** @scrutinizer ignore-unhandled */ @unlink($temp_file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
975
                    }
976
977
                    if ($image_attributes === false || $image_extensions[(int)$image_attributes[2]] != $ext) {
978
                        $this->message .= "Attempt to upload camouflaged image file {$_file['name']}.\n";
979
                        $this->_safe_badext    = false;
980
                        $this->last_error_type = 'UPLOAD';
981
                    }
982
                }
983
            }
984
        }
985
986
        return $this->_safe_badext;
987
    }
988
989
    /**
990
     * @return bool
991
     */
992
    public function check_contami_systemglobals()
993
    {
994
        /*    if( $this->_done_contami ) return $this->_safe_contami ;
995
    else $this->_done_contami = true ; */
996
997
        /*    foreach ($this->_bad_globals as $bad_global) {
998
                if ( isset( $_REQUEST[ $bad_global ] ) ) {
999
                    $this->message .= "Attempt to inject '$bad_global' was found.\n" ;
1000
                    $this->_safe_contami = false ;
1001
                    $this->last_error_type = 'CONTAMI' ;
1002
                }
1003
            }*/
1004
1005
        return $this->_safe_contami;
1006
    }
1007
1008
    /**
1009
     * @param bool $sanitize
1010
     *
1011
     * @return bool
1012
     */
1013
    public function check_sql_isolatedcommentin($sanitize = true)
1014
    {
1015
        if ($this->_done_isocom) {
1016
            return $this->_safe_isocom;
1017
        } else {
1018
            $this->_done_isocom = true;
1019
        }
1020
1021
        foreach ($this->_doubtful_requests as $key => $val) {
1022
            $str = $val;
1023
            while ($str = strstr($str, '/*')) { /* */
1024
                $str = strstr(substr($str, 2), '*/');
1025
                if ($str === false) {
1026
                    $this->message .= "Isolated comment-in found. ($val)\n";
1027
                    if ($sanitize) {
1028
                        $this->replace_doubtful($key, $val . '*/');
1029
                    }
1030
                    $this->_safe_isocom    = false;
1031
                    $this->last_error_type = 'ISOCOM';
1032
                }
1033
            }
1034
        }
1035
1036
        return $this->_safe_isocom;
1037
    }
1038
1039
    /**
1040
     * @param bool $sanitize
1041
     *
1042
     * @return bool
1043
     */
1044
    public function check_sql_union($sanitize = true)
1045
    {
1046
        if ($this->_done_union) {
1047
            return $this->_safe_union;
1048
        } else {
1049
            $this->_done_union = true;
1050
        }
1051
1052
        foreach ($this->_doubtful_requests as $key => $val) {
1053
            $str = str_replace(array('/*', '*/'), '', preg_replace('?/\*.+\*/?sU', '', $val));
1054
            if (preg_match('/\sUNION\s+(ALL|SELECT)/i', $str)) {
1055
                $this->message .= "Pattern like SQL injection found. ($val)\n";
1056
                if ($sanitize) {
1057
                    //                    $this->replace_doubtful($key, preg_replace('/union/i', 'uni-on', $val));
1058
                    $this->replace_doubtful($key, str_ireplace('union', 'uni-on', $val));
1059
                }
1060
                $this->_safe_union     = false;
1061
                $this->last_error_type = 'UNION';
1062
            }
1063
        }
1064
1065
        return $this->_safe_union;
1066
    }
1067
1068
    /**
1069
     * @param $uid
1070
     *
1071
     * @return bool
1072
     */
1073
    public function stopforumspam($uid)
1074
    {
1075
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
1076
            return false;
1077
        }
1078
1079
        $result = $this->stopForumSpamLookup(
1080
            isset($_POST['email']) ? $_POST['email'] : null,
1081
            $_SERVER['REMOTE_ADDR'],
1082
            isset($_POST['uname']) ? $_POST['uname'] : null
1083
        );
1084
1085
        if (false === $result || isset($result['http_code'])) {
1086
            return false;
1087
        }
1088
1089
        $spammer = false;
1090
        if (isset($result['email']) && isset($result['email']['lastseen'])) {
1091
            $spammer = true;
1092
        }
1093
1094
        if (isset($result['ip']) && isset($result['ip']['lastseen'])) {
1095
            $last        = strtotime($result['ip']['lastseen']);
1096
            $oneMonth    = 60 * 60 * 24 * 31;
1097
            $oneMonthAgo = time() - $oneMonth;
1098
            if ($last > $oneMonthAgo) {
1099
                $spammer = true;
1100
            }
1101
        }
1102
1103
        if (!$spammer) {
1104
            return false;
1105
        }
1106
1107
        $this->last_error_type = 'SPAMMER POST';
1108
1109
        switch ($this->_conf['stopforumspam_action']) {
1110
            default :
1111
            case 'log' :
1112
                break;
1113
            case 'san' :
1114
                $_POST = array();
1115
                $this->message .= 'POST deleted for IP:' . $_SERVER['REMOTE_ADDR'];
1116
                break;
1117
            case 'biptime0' :
1118
                $_POST = array();
1119
                $this->message .= 'BAN and POST deleted for IP:' . $_SERVER['REMOTE_ADDR'];
1120
                $this->_should_be_banned_time0 = true;
1121
                break;
1122
            case 'bip' :
1123
                $_POST = array();
1124
                $this->message .= 'Ban and POST deleted for IP:' . $_SERVER['REMOTE_ADDR'];
1125
                $this->_should_be_banned = true;
1126
                break;
1127
        }
1128
1129
        $this->output_log($this->last_error_type, $uid, false, 16);
1130
1131
        return true;
1132
    }
1133
1134
    public function stopForumSpamLookup($email, $ip, $username)
1135
    {
1136
        if (!function_exists('curl_init')) {
1137
            return false;
1138
        }
1139
1140
        $query = '';
1141
        $query .= (empty($ip)) ? '' : '&ip=' . $ip;
1142
        $query .= (empty($email)) ? '' : '&email=' . $email;
1143
        $query .= (empty($username)) ? '' : '&username=' . $username;
1144
1145
        if (empty($query)) {
1146
            return false;
1147
        }
1148
1149
        $url = 'http://www.stopforumspam.com/api?f=json' . $query;
1150
        $ch  = curl_init();
1151
        curl_setopt($ch, CURLOPT_URL, $url);
1152
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1153
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
1154
        $result = curl_exec($ch);
1155
        if (false === $result) {
1156
            $result = curl_getinfo($ch);
1157
        } else {
1158
            $result = json_decode(curl_exec($ch), true);
0 ignored issues
show
Bug introduced by
It seems like curl_exec($ch) can also be of type true; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1158
            $result = json_decode(/** @scrutinizer ignore-type */ curl_exec($ch), true);
Loading history...
1159
        }
1160
        curl_close($ch);
1161
1162
        return $result;
1163
    }
1164
1165
    /**
1166
     * @param int  $uid
1167
     * @param bool $can_ban
1168
     *
1169
     * @return bool
1170
     */
1171
    public function check_dos_attack($uid = 0, $can_ban = false)
1172
    {
1173
        global $xoopsDB;
1174
1175
        if ($this->_done_dos) {
1176
            return true;
1177
        }
1178
1179
        $ip      = \Xmf\IPAddress::fromRequest();
1180
        if (false === $ip->asReadable()) {
0 ignored issues
show
introduced by
The condition false === $ip->asReadable() is always false.
Loading history...
1181
            return true;
1182
        }
1183
        $uri     = @$_SERVER['REQUEST_URI'];
1184
1185
        $ip4sql  = $xoopsDB->quote($ip->asReadable());
1186
        $uri4sql = $xoopsDB->quote($uri);
1187
1188
        // gargage collection
1189
        $result = $xoopsDB->queryF(
1190
            'DELETE FROM ' . $xoopsDB->prefix($this->mydirname . '_access')
1191
            . ' WHERE expire < UNIX_TIMESTAMP()'
1192
        );
1193
1194
        // for older versions before updating this module
1195
        if ($result === false) {
1196
            $this->_done_dos = true;
1197
1198
            return true;
1199
        }
1200
1201
        // sql for recording access log (INSERT should be placed after SELECT)
1202
        $sql4insertlog = 'INSERT INTO ' . $xoopsDB->prefix($this->mydirname . '_access')
1203
                         . " SET ip={$ip4sql}, request_uri={$uri4sql},"
1204
                         . " expire=UNIX_TIMESTAMP()+'" . (int)$this->_conf['dos_expire'] . "'";
1205
1206
        // bandwidth limitation
1207
        if (@$this->_conf['bwlimit_count'] >= 10) {
1208
            $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access');
1209
            $result = $xoopsDB->query($sql);
1210
            if ($xoopsDB->isResultSet($result)) {
1211
                list($bw_count) = $xoopsDB->fetchRow($result);
1212
                if ($bw_count > $this->_conf['bwlimit_count']) {
1213
                    $this->write_file_bwlimit(time() + $this->_conf['dos_expire']);
1214
                }
1215
            }
1216
        }
1217
1218
        // F5 attack check (High load & same URI)
1219
1220
        $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . " WHERE ip={$ip4sql} AND request_uri={$uri4sql}";
1221
        $result = $xoopsDB->query($sql);
1222
        if (!$xoopsDB->isResultSet($result)) {
1223
            throw new \RuntimeException(
1224
                \sprintf(_DB_QUERY_ERROR, $sql) . $xoopsDB->error(), E_USER_ERROR
1225
            );
1226
        }
1227
        list($f5_count) = $xoopsDB->fetchRow($result);
1228
        if ($f5_count > $this->_conf['dos_f5count']) {
1229
1230
            // delayed insert
1231
            $xoopsDB->queryF($sql4insertlog);
1232
1233
            // extends the expires of the IP with 5 minutes at least (pending)
1234
            // $result = $xoopsDB->queryF( "UPDATE ".$xoopsDB->prefix($this->mydirname.'_access')." SET expire=UNIX_TIMESTAMP()+300 WHERE ip='$ip4sql' AND expire<UNIX_TIMESTAMP()+300" ) ;
1235
1236
            // call the filter first
1237
            $ret = $this->call_filter('f5attack_overrun');
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
1238
1239
            // actions for F5 Attack
1240
            $this->_done_dos       = true;
1241
            $this->last_error_type = 'DoS';
1242
            switch ($this->_conf['dos_f5action']) {
1243
                default :
1244
                case 'exit' :
1245
                    $this->output_log($this->last_error_type, $uid, true, 16);
1246
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1247
                case 'none' :
1248
                    $this->output_log($this->last_error_type, $uid, true, 16);
1249
1250
                    return true;
1251
                case 'biptime0' :
1252
                    if ($can_ban) {
1253
                        $this->register_bad_ips(time() + $this->_conf['banip_time0']);
1254
                    }
1255
                    break;
1256
                case 'bip' :
1257
                    if ($can_ban) {
1258
                        $this->register_bad_ips();
1259
                    }
1260
                    break;
1261
                case 'hta' :
1262
                    if ($can_ban) {
1263
                        $this->deny_by_htaccess();
1264
                    }
1265
                    break;
1266
                case 'sleep' :
1267
                    sleep(5);
1268
                    break;
1269
            }
1270
1271
            return false;
1272
        }
1273
1274
        // Check its Agent
1275
        if (trim($this->_conf['dos_crsafe']) != '' && preg_match($this->_conf['dos_crsafe'], @$_SERVER['HTTP_USER_AGENT'])) {
1276
            // welcomed crawler
1277
            $this->_done_dos = true;
1278
1279
            return true;
1280
        }
1281
1282
        // Crawler check (High load & different URI)
1283
        $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . " WHERE ip={$ip4sql}";
1284
        $result = $xoopsDB->query($sql);
1285
        if (!$xoopsDB->isResultSet($result)) {
1286
            return false;
1287
        }
1288
        list($crawler_count) = $xoopsDB->fetchRow($result);
1289
1290
        // delayed insert
1291
        $xoopsDB->queryF($sql4insertlog);
1292
1293
        if ($crawler_count > $this->_conf['dos_crcount']) {
1294
1295
            // call the filter first
1296
            $ret = $this->call_filter('crawler_overrun');
1297
1298
            // actions for bad Crawler
1299
            $this->_done_dos       = true;
1300
            $this->last_error_type = 'CRAWLER';
1301
            switch ($this->_conf['dos_craction']) {
1302
                default :
1303
                case 'exit' :
1304
                    $this->output_log($this->last_error_type, $uid, true, 16);
1305
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1306
                case 'none' :
1307
                    $this->output_log($this->last_error_type, $uid, true, 16);
1308
1309
                    return true;
1310
                case 'biptime0' :
1311
                    if ($can_ban) {
1312
                        $this->register_bad_ips(time() + $this->_conf['banip_time0']);
1313
                    }
1314
                    break;
1315
                case 'bip' :
1316
                    if ($can_ban) {
1317
                        $this->register_bad_ips();
1318
                    }
1319
                    break;
1320
                case 'hta' :
1321
                    if ($can_ban) {
1322
                        $this->deny_by_htaccess();
1323
                    }
1324
                    break;
1325
                case 'sleep' :
1326
                    sleep(5);
1327
                    break;
1328
            }
1329
1330
            return false;
1331
        }
1332
1333
        return true;
1334
    }
1335
1336
    //
1337
    /**
1338
     * @return bool|null
1339
     */
1340
    public function check_brute_force()
1341
    {
1342
        global $xoopsDB;
1343
1344
        $ip      = \Xmf\IPAddress::fromRequest();
1345
        if (false === $ip->asReadable()) {
0 ignored issues
show
introduced by
The condition false === $ip->asReadable() is always false.
Loading history...
1346
            return true;
1347
        }
1348
        $uri     = @$_SERVER['REQUEST_URI'];
1349
        $ip4sql  = $xoopsDB->quote($ip->asReadable());
1350
        $uri4sql = $xoopsDB->quote($uri);
1351
1352
        $victim_uname = empty($_COOKIE['autologin_uname']) ? $_POST['uname'] : $_COOKIE['autologin_uname'];
1353
        // some UA send 'deleted' as a value of the deleted cookie.
1354
        if ($victim_uname === 'deleted') {
1355
            return null;
1356
        }
1357
        $mal4sql = $xoopsDB->quote("BRUTE FORCE: $victim_uname");
1358
1359
        // gargage collection
1360
        $result = $xoopsDB->queryF(
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1361
            'DELETE FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . ' WHERE expire < UNIX_TIMESTAMP()'
1362
        );
1363
1364
        // sql for recording access log (INSERT should be placed after SELECT)
1365
        $sql4insertlog = 'INSERT INTO ' . $xoopsDB->prefix($this->mydirname . '_access')
1366
                         . " SET ip={$ip4sql}, request_uri={$uri4sql}, malicious_actions={$mal4sql}, expire=UNIX_TIMESTAMP()+600";
1367
1368
        // count check
1369
        $bf_count = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $bf_count is dead and can be removed.
Loading history...
1370
        $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . " WHERE ip={$ip4sql} AND malicious_actions like 'BRUTE FORCE:%'";
1371
        $result = $xoopsDB->query($sql);
1372
        if ($xoopsDB->isResultSet($result)) {
1373
            list($bf_count) = $xoopsDB->fetchRow($result);
1374
        } else {
1375
            throw new \RuntimeException(
1376
                \sprintf(_DB_QUERY_ERROR, $sql) . $xoopsDB->error(), E_USER_ERROR
1377
            );
1378
        }
1379
        if ($bf_count > $this->_conf['bf_count']) {
1380
            $this->register_bad_ips(time() + $this->_conf['banip_time0']);
1381
            $this->last_error_type = 'BruteForce';
1382
            $this->message .= "Trying to login as '" . addslashes($victim_uname) . "' found.\n";
1383
            $this->output_log('BRUTE FORCE', 0, true, 1);
1384
            $ret = $this->call_filter('bruteforce_overrun');
1385
            if ($ret == false) {
1386
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1387
            }
1388
        }
1389
        // delayed insert
1390
        $xoopsDB->queryF($sql4insertlog);
1391
        return null;
1392
    }
1393
1394
    /**
1395
     * @param $val
1396
     */
1397
    protected function _spam_check_point_recursive($val)
1398
    {
1399
        if (is_array($val)) {
1400
            foreach ($val as $subval) {
1401
                $this->_spam_check_point_recursive($subval);
1402
            }
1403
        } else {
1404
            // http_host
1405
            $path_array = parse_url(XOOPS_URL);
1406
            $http_host  = empty($path_array['host']) ? 'www.xoops.org' : $path_array['host'];
1407
1408
            // count URI up
1409
            $count = -1;
1410
            foreach (preg_split('#https?\:\/\/#i', $val) as $fragment) {
1411
                if (strncmp($fragment, $http_host, strlen($http_host)) !== 0) {
1412
                    ++$count;
1413
                }
1414
            }
1415
            if ($count > 0) {
1416
                $this->_spamcount_uri += $count;
1417
            }
1418
1419
            // count BBCode likd [url=www....] up (without [url=http://...])
1420
            $this->_spamcount_uri += count(preg_split('/\[url=(?!http|\\"http|\\\'http|' . $http_host . ')/i', $val)) - 1;
1421
        }
1422
    }
1423
1424
    /**
1425
     * @param $points4deny
1426
     * @param $uid
1427
     */
1428
    public function spam_check($points4deny, $uid)
1429
    {
1430
        $this->_spamcount_uri = 0;
1431
        $this->_spam_check_point_recursive($_POST);
1432
1433
        if ($this->_spamcount_uri >= $points4deny) {
1434
            $this->message .= @$_SERVER['REQUEST_URI'] . " SPAM POINT: $this->_spamcount_uri\n";
1435
            $this->output_log('URI SPAM', $uid, false, 128);
1436
            $ret = $this->call_filter('spamcheck_overrun');
1437
            if ($ret == false) {
1438
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1439
            }
1440
        }
1441
    }
1442
1443
    public function disable_features()
1444
    {
1445
        global $HTTP_POST_VARS, $HTTP_GET_VARS, $HTTP_COOKIE_VARS;
1446
1447
        // disable "Notice: Undefined index: ..."
1448
        $error_reporting_level = error_reporting(0);
1449
1450
        //
1451
        // bit 1 : disable XMLRPC , criteria bug
1452
        //
1453
        if ($this->_conf['disable_features'] & 1) {
1454
1455
            // zx 2005/1/5 disable xmlrpc.php in root
1456
            if (/* ! stristr( $_SERVER['SCRIPT_NAME'] , 'modules' ) && */
1457
                substr(@$_SERVER['SCRIPT_NAME'], -10) === 'xmlrpc.php'
1458
            ) {
1459
                $this->output_log('xmlrpc', 0, true, 1);
1460
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1461
            }
1462
1463
            // security bug of class/criteria.php 2005/6/27
1464
            if ((isset($_POST['uname']) && $_POST['uname'] === '0') || (isset($_COOKIE['autologin_pass']) && $_COOKIE['autologin_pass'] === '0')) {
1465
                $this->output_log('CRITERIA');
1466
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1467
            }
1468
        }
1469
1470
        //
1471
        // bit 11 : XSS+CSRFs in XOOPS < 2.0.10
1472
        //
1473
        if ($this->_conf['disable_features'] & 1024) {
1474
1475
            // root controllers
1476
            if (false === stripos(@$_SERVER['SCRIPT_NAME'], 'modules')) {
1477
                // zx 2004/12/13 misc.php debug (file check)
1478
                if (substr(@$_SERVER['SCRIPT_NAME'], -8) === 'misc.php' && ($_GET['type'] === 'debug' || $_POST['type'] === 'debug') && !preg_match('/^dummy_\d+\.html$/', $_GET['file'])) {
1479
                    $this->output_log('misc debug');
1480
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1481
                }
1482
1483
                // zx 2004/12/13 misc.php smilies
1484
                if (substr(@$_SERVER['SCRIPT_NAME'], -8) === 'misc.php' && ($_GET['type'] === 'smilies' || $_POST['type'] === 'smilies') && !preg_match('/^[0-9a-z_]*$/i', $_GET['target'])) {
1485
                    $this->output_log('misc smilies');
1486
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1487
                }
1488
1489
                // zx 2005/1/5 edituser.php avatarchoose
1490
                if (substr(@$_SERVER['SCRIPT_NAME'], -12) === 'edituser.php' && $_POST['op'] === 'avatarchoose' && false !== strpos($_POST['user_avatar'], '..')) {
1491
                    $this->output_log('edituser avatarchoose');
1492
                    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1493
                }
1494
            }
1495
1496
            // zx 2005/1/4 findusers
1497
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'findusers' || $_POST['fct'] === 'findusers')) {
1498
                foreach ($_POST as $key => $val) {
1499
                    if (false !== strpos($key, "'") || false !== strpos($val, "'")) {
1500
                        $this->output_log('findusers');
1501
                        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1502
                    }
1503
                }
1504
            }
1505
1506
            // preview CSRF zx 2004/12/14
1507
            // news submit.php
1508
            if (substr(@$_SERVER['SCRIPT_NAME'], -23) === 'modules/news/submit.php' && isset($_POST['preview']) && strpos(@$_SERVER['HTTP_REFERER'], XOOPS_URL . '/modules/news/submit.php') !== 0) {
1509
                $HTTP_POST_VARS['nohtml'] = $_POST['nohtml'] = 1;
1510
            }
1511
            // news admin/index.php
1512
            if (substr(@$_SERVER['SCRIPT_NAME'], -28) === 'modules/news/admin/index.php' && ($_POST['op'] === 'preview' || $_GET['op'] === 'preview') && strpos(@$_SERVER['HTTP_REFERER'], XOOPS_URL . '/modules/news/admin/index.php') !== 0) {
1513
                $HTTP_POST_VARS['nohtml'] = $_POST['nohtml'] = 1;
1514
            }
1515
            // comment comment_post.php
1516
            if (isset($_POST['com_dopreview']) && false === strpos(substr(@$_SERVER['HTTP_REFERER'], -16), 'comment_post.php')) {
1517
                $HTTP_POST_VARS['dohtml'] = $_POST['dohtml'] = 0;
1518
            }
1519
            // disable preview of system's blocksadmin
1520
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'blocksadmin' || $_POST['fct'] === 'blocksadmin') && isset($_POST['previewblock']) /* && strpos( $_SERVER['HTTP_REFERER'] , XOOPS_URL.'/modules/system/admin.php' ) !== 0 */) {
1521
                die("Danger! don't use this preview. Use 'altsys module' instead.(by Protector)");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1522
            }
1523
            // tpl preview
1524
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'tplsets' || $_POST['fct'] === 'tplsets')) {
1525
                if ($_POST['op'] === 'previewpopup' || $_GET['op'] === 'previewpopup' || isset($_POST['previewtpl'])) {
1526
                    die("Danger! don't use this preview.(by Protector)");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1527
                }
1528
            }
1529
        }
1530
1531
        // restore reporting level
1532
        error_reporting($error_reporting_level);
1533
    }
1534
1535
    /**
1536
     * @param        $type
1537
     * @param string $dying_message
1538
     *
1539
     * @return int|mixed
1540
     */
1541
    public function call_filter($type, $dying_message = '')
1542
    {
1543
        require_once __DIR__ . '/ProtectorFilter.php';
1544
        $filter_handler = ProtectorFilterHandler::getInstance();
1545
        $ret            = $filter_handler->execute($type);
1546
        if ($ret == false && $dying_message) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $ret of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
1547
            die($dying_message);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1548
        }
1549
1550
        return $ret;
1551
    }
1552
}
1553