Passed
Pull Request — master (#1301)
by Michael
05:46
created

Protector::check_dos_attack()   F

Complexity

Conditions 31
Paths 187

Size

Total Lines 162
Code Lines 97

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 31
eloc 97
c 1
b 0
f 0
nc 187
nop 2
dl 0
loc 162
rs 3.4416

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        $filepath4group1ips = @file(Protector::get_filepath4group1ips());
466
467
        if (is_array($filepath4group1ips) && isset($filepath4group1ips[0])) {
468
            list($group1_ips_serialized) = $filepath4group1ips;
469
        }
470
471
        $group1_ips = empty($group1_ips_serialized) ? array() : @unserialize($group1_ips_serialized, array('allowed_classes' => false));
472
        if (!is_array($group1_ips)) {
473
            $group1_ips = array();
474
        }
475
476
        if ($with_info) {
477
            $group1_ips = array_flip($group1_ips);
478
        }
479
480
        return $group1_ips;
481
    }
482
483
    /**
484
     * @return string
485
     */
486
    public static function get_filepath4group1ips()
487
    {
488
        return XOOPS_VAR_PATH . '/protector/group1ips' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
489
    }
490
491
    /**
492
     * @return string
493
     */
494
    public function get_filepath4confighcache()
495
    {
496
        return XOOPS_VAR_PATH . '/protector/configcache' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
497
    }
498
499
    /**
500
     * @param $ips
501
     *
502
     * @return bool
503
     */
504
    public function ip_match($ips)
505
    {
506
        $requestIp = \Xmf\IPAddress::fromRequest()->asReadable();
507
        if (false === $requestIp) { // nothing to match
0 ignored issues
show
introduced by
The condition false === $requestIp is always false.
Loading history...
508
            $this->ip_matched_info = null;
509
            return false;
510
        }
511
        foreach ($ips as $ip => $info) {
512
            if ($ip) {
513
                switch (strtolower(substr($ip, -1))) {
514
                    case '.' :
515
                    case ':' :
516
                        // foward match
517
                        if (substr($requestIp, 0, strlen($ip)) == $ip) {
518
                            $this->ip_matched_info = $info;
519
                            return true;
520
                        }
521
                        break;
522
                    case '0' :
523
                    case '1' :
524
                    case '2' :
525
                    case '3' :
526
                    case '4' :
527
                    case '5' :
528
                    case '6' :
529
                    case '7' :
530
                    case '8' :
531
                    case '9' :
532
                    case 'a' :
533
                    case 'b' :
534
                    case 'c' :
535
                    case 'd' :
536
                    case 'e' :
537
                    case 'f' :
538
                        // full match
539
                        if ($requestIp == $ip) {
540
                            $this->ip_matched_info = $info;
541
                            return true;
542
                        }
543
                        break;
544
                    default :
545
                        // perl regex
546
                        if (@preg_match($ip, $requestIp)) {
547
                            $this->ip_matched_info = $info;
548
                            return true;
549
                        }
550
                        break;
551
                }
552
            }
553
        }
554
        $this->ip_matched_info = null;
555
        return false;
556
    }
557
558
    /**
559
     * @param null|string|false $ip
560
     *
561
     * @return bool
562
     */
563
    public function deny_by_htaccess($ip = null)
564
    {
565
        if (empty($ip)) {
566
            $ip = \Xmf\IPAddress::fromRequest()->asReadable();
567
        }
568
        if (empty($ip)) {
569
            return false;
570
        }
571
        if (!function_exists('file_get_contents')) {
572
            return false;
573
        }
574
575
        $target_htaccess = XOOPS_ROOT_PATH . '/.htaccess';
576
        $backup_htaccess = XOOPS_ROOT_PATH . '/uploads/.htaccess.bak';
577
578
        $ht_body = file_get_contents($target_htaccess);
579
580
        // make backup as uploads/.htaccess.bak automatically
581
        if ($ht_body && !file_exists($backup_htaccess)) {
582
            $fw = fopen($backup_htaccess, 'w');
583
            fwrite($fw, $ht_body);
584
            fclose($fw);
585
        }
586
587
        // if .htaccess is broken, restore from backup
588
        if (!$ht_body && file_exists($backup_htaccess)) {
589
            $ht_body = file_get_contents($backup_htaccess);
590
        }
591
592
        // new .htaccess
593
        if ($ht_body === false) {
594
            $ht_body = '';
595
        }
596
597
        if (preg_match("/^(.*)#PROTECTOR#\s+(DENY FROM .*)\n#PROTECTOR#\n(.*)$/si", $ht_body, $regs)) {
598
            if (substr($regs[2], -strlen($ip)) == $ip) {
599
                return true;
600
            }
601
            $new_ht_body = $regs[1] . "#PROTECTOR#\n" . $regs[2] . " $ip\n#PROTECTOR#\n" . $regs[3];
602
        } else {
603
            $new_ht_body = "#PROTECTOR#\nDENY FROM $ip\n#PROTECTOR#\n" . $ht_body;
604
        }
605
606
        // error_log( "$new_ht_body\n" , 3 , "/tmp/error_log" ) ;
607
608
        $fw = fopen($target_htaccess, 'w');
609
        @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

609
        /** @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...
610
        fwrite($fw, $new_ht_body);
611
        @flock($fw, LOCK_UN);
612
        fclose($fw);
613
614
        return true;
615
    }
616
617
    /**
618
     * @return array
619
     */
620
    public function getDblayertrapDoubtfuls()
621
    {
622
        return $this->_dblayertrap_doubtfuls;
623
    }
624
625
    /**
626
     * @param $val
627
     * @return null
628
     */
629
    protected function _dblayertrap_check_recursive($val)
630
    {
631
        if (is_array($val)) {
632
            foreach ($val as $subval) {
633
                $this->_dblayertrap_check_recursive($subval);
634
            }
635
        } else {
636
            if (strlen($val) < 6) {
637
                return null;
638
            }
639
            $val = @get_magic_quotes_gpc() ? stripslashes($val) : $val;
640
            foreach ($this->_dblayertrap_doubtful_needles as $needle) {
641
                if (false !== stripos($val, $needle)) {
642
                    $this->_dblayertrap_doubtfuls[] = $val;
643
                }
644
            }
645
        }
646
    }
647
648
    /**
649
     * @param  bool $force_override
650
     * @return null
651
     */
652
    public function dblayertrap_init($force_override = false)
653
    {
654
        if (!empty($GLOBALS['xoopsOption']['nocommon']) || defined('_LEGACY_PREVENT_EXEC_COMMON_') || defined('_LEGACY_PREVENT_LOAD_CORE_')) {
655
            return null;
656
        } // skip
657
658
        $this->_dblayertrap_doubtfuls = array();
659
        $this->_dblayertrap_check_recursive($_GET);
660
        $this->_dblayertrap_check_recursive($_POST);
661
        $this->_dblayertrap_check_recursive($_COOKIE);
662
        if (empty($this->_conf['dblayertrap_wo_server'])) {
663
            $this->_dblayertrap_check_recursive($_SERVER);
664
        }
665
666
        if (!empty($this->_dblayertrap_doubtfuls) || $force_override) {
667
            @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

667
            /** @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...
668
            require_once dirname(__DIR__) . '/class/ProtectorMysqlDatabase.class.php';
669
        }
670
    }
671
672
    /**
673
     * @param $val
674
     */
675
    protected function _bigumbrella_check_recursive($val)
676
    {
677
        if (is_array($val)) {
678
            foreach ($val as $subval) {
679
                $this->_bigumbrella_check_recursive($subval);
680
            }
681
        } else {
682
            if (preg_match('/[<\'"].{15}/s', $val, $regs)) {
683
                $this->_bigumbrella_doubtfuls[] = $regs[0];
684
            }
685
        }
686
    }
687
688
    public function bigumbrella_init()
689
    {
690
        $this->_bigumbrella_doubtfuls = array();
691
        $this->_bigumbrella_check_recursive($_GET);
692
        $this->_bigumbrella_check_recursive(@$_SERVER['PHP_SELF']);
693
694
        if (!empty($this->_bigumbrella_doubtfuls)) {
695
            ob_start(array($this, 'bigumbrella_outputcheck'));
696
        }
697
    }
698
699
    /**
700
     * @param $s
701
     *
702
     * @return string
703
     */
704
    public function bigumbrella_outputcheck($s)
705
    {
706
        if (defined('BIGUMBRELLA_DISABLED')) {
707
            return $s;
708
        }
709
710
        if (function_exists('headers_list')) {
711
            foreach (headers_list() as $header) {
712
                if (false !== stripos($header, 'Content-Type:') && false === stripos($header, 'text/html')) {
713
                    return $s;
714
                }
715
            }
716
        }
717
718
        if (!is_array($this->_bigumbrella_doubtfuls)) {
0 ignored issues
show
introduced by
The condition is_array($this->_bigumbrella_doubtfuls) is always true.
Loading history...
719
            return 'bigumbrella injection found.';
720
        }
721
722
        foreach ($this->_bigumbrella_doubtfuls as $doubtful) {
723
            if (false !== strpos($s, $doubtful)) {
724
                return 'XSS found by Protector.';
725
            }
726
        }
727
728
        return $s;
729
    }
730
731
    /**
732
     * @return bool
733
     */
734
    public function intval_allrequestsendid()
735
    {
736
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
737
738
        if ($this->_done_intval) {
739
            return true;
740
        } else {
741
            $this->_done_intval = true;
742
        }
743
744
        foreach ($_GET as $key => $val) {
745
            if (substr($key, -2) === 'id' && !is_array($_GET[$key])) {
746
                $newval     = preg_replace('/[^0-9a-zA-Z_-]/', '', $val);
747
                $_GET[$key] = $HTTP_GET_VARS[$key] = $newval;
748
                if ($_REQUEST[$key] == $_GET[$key]) {
749
                    $_REQUEST[$key] = $newval;
750
                }
751
            }
752
        }
753
        foreach ($_POST as $key => $val) {
754
            if (substr($key, -2) === 'id' && !is_array($_POST[$key])) {
755
                $newval      = preg_replace('/[^0-9a-zA-Z_-]/', '', $val);
756
                $_POST[$key] = $HTTP_POST_VARS[$key] = $newval;
757
                if ($_REQUEST[$key] == $_POST[$key]) {
758
                    $_REQUEST[$key] = $newval;
759
                }
760
            }
761
        }
762
        foreach ($_COOKIE as $key => $val) {
763
            if (substr($key, -2) === 'id' && !is_array($_COOKIE[$key])) {
764
                $newval        = preg_replace('/[^0-9a-zA-Z_-]/', '', $val);
765
                $_COOKIE[$key] = $HTTP_COOKIE_VARS[$key] = $newval;
766
                if ($_REQUEST[$key] == $_COOKIE[$key]) {
767
                    $_REQUEST[$key] = $newval;
768
                }
769
            }
770
        }
771
772
        return true;
773
    }
774
775
    /**
776
     * @return bool
777
     */
778
    public function eliminate_dotdot()
779
    {
780
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
781
782
        if ($this->_done_dotdot) {
783
            return true;
784
        } else {
785
            $this->_done_dotdot = true;
786
        }
787
788
        foreach ($_GET as $key => $val) {
789
            if (is_array($_GET[$key])) {
790
                continue;
791
            }
792
            if (substr(trim($val), 0, 3) === '../' || false !== strpos($val, '/../')) {
793
                $this->last_error_type = 'DirTraversal';
794
                $this->message .= "Directory Traversal '$val' found.\n";
795
                $this->output_log($this->last_error_type, 0, false, 64);
796
                $sanitized_val = str_replace(chr(0), '', $val);
797
                if (substr($sanitized_val, -2) !== ' .') {
798
                    $sanitized_val .= ' .';
799
                }
800
                $_GET[$key] = $HTTP_GET_VARS[$key] = $sanitized_val;
801
                if ($_REQUEST[$key] == $_GET[$key]) {
802
                    $_REQUEST[$key] = $sanitized_val;
803
                }
804
            }
805
        }
806
807
        /*    foreach ($_POST as $key => $val) {
808
                if( is_array( $_POST[ $key ] ) ) continue ;
809
                if ( substr( trim( $val ) , 0 , 3 ) == '../' || false !== strpos( $val , '../../' ) ) {
810
                    $this->last_error_type = 'ParentDir' ;
811
                    $this->message .= "Doubtful file specification '$val' found.\n" ;
812
                    $this->output_log( $this->last_error_type , 0 , false , 128 ) ;
813
                    $sanitized_val = str_replace( chr(0) , '' , $val ) ;
814
                    if( substr( $sanitized_val , -2 ) != ' .' ) $sanitized_val .= ' .' ;
815
                    $_POST[ $key ] = $HTTP_POST_VARS[ $key ] = $sanitized_val ;
816
                    if ($_REQUEST[ $key ] == $_POST[ $key ]) {
817
                        $_REQUEST[ $key ] = $sanitized_val ;
818
                    }
819
                }
820
            }
821
            foreach ($_COOKIE as $key => $val) {
822
                if( is_array( $_COOKIE[ $key ] ) ) continue ;
823
                if ( substr( trim( $val ) , 0 , 3 ) == '../' || false !== strpos( $val , '../../' ) ) {
824
                    $this->last_error_type = 'ParentDir' ;
825
                    $this->message .= "Doubtful file specification '$val' found.\n" ;
826
                    $this->output_log( $this->last_error_type , 0 , false , 128 ) ;
827
                    $sanitized_val = str_replace( chr(0) , '' , $val ) ;
828
                    if( substr( $sanitized_val , -2 ) != ' .' ) $sanitized_val .= ' .' ;
829
                    $_COOKIE[ $key ] = $HTTP_COOKIE_VARS[ $key ] = $sanitized_val ;
830
                    if ($_REQUEST[ $key ] == $_COOKIE[ $key ]) {
831
                        $_REQUEST[ $key ] = $sanitized_val ;
832
                    }
833
                }
834
            }*/
835
836
        return true;
837
    }
838
839
    /**
840
     * @param $current
841
     * @param $indexes
842
     *
843
     * @return bool
844
     */
845
    public function &get_ref_from_base64index(&$current, $indexes)
846
    {
847
        foreach ($indexes as $index) {
848
            $index = base64_decode($index);
849
            if (!is_array($current)) {
850
                return false;
851
            }
852
            $current =& $current[$index];
853
        }
854
855
        return $current;
856
    }
857
858
    /**
859
     * @param $key
860
     * @param $val
861
     */
862
    public function replace_doubtful($key, $val)
863
    {
864
        global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS;
865
866
        $index_expression = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $index_expression is dead and can be removed.
Loading history...
867
        $indexes          = explode('_', $key);
868
        $base_array       = array_shift($indexes);
869
870
        switch ($base_array) {
871
            case 'G' :
872
                $main_ref   =& $this->get_ref_from_base64index($_GET, $indexes);
873
                $legacy_ref =& $this->get_ref_from_base64index($HTTP_GET_VARS, $indexes);
874
                break;
875
            case 'P' :
876
                $main_ref   =& $this->get_ref_from_base64index($_POST, $indexes);
877
                $legacy_ref =& $this->get_ref_from_base64index($HTTP_POST_VARS, $indexes);
878
                break;
879
            case 'C' :
880
                $main_ref   =& $this->get_ref_from_base64index($_COOKIE, $indexes);
881
                $legacy_ref =& $this->get_ref_from_base64index($HTTP_COOKIE_VARS, $indexes);
882
                break;
883
            default :
884
                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...
885
        }
886
        if (!isset($main_ref)) {
887
            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...
888
        }
889
        $request_ref =& $this->get_ref_from_base64index($_REQUEST, $indexes);
890
        if ($request_ref !== false && $main_ref == $request_ref) {
891
            $request_ref = $val;
892
        }
893
        $main_ref   = $val;
894
        $legacy_ref = $val;
895
    }
896
897
    /**
898
     * @return bool
899
     */
900
    public function check_uploaded_files()
901
    {
902
        if ($this->_done_badext) {
903
            return $this->_safe_badext;
904
        } else {
905
            $this->_done_badext = true;
906
        }
907
908
        // extensions never uploaded
909
        $bad_extensions = array('php', 'phtml', 'phtm', 'php3', 'php4', 'cgi', 'pl', 'asp');
910
        // extensions needed image check (anti-IE Content-Type XSS)
911
        $image_extensions = array(
912
            1  => 'gif',
913
            2  => 'jpg',
914
            3  => 'png',
915
            4  => 'swf',
916
            5  => 'psd',
917
            6  => 'bmp',
918
            7  => 'tif',
919
            8  => 'tif',
920
            9  => 'jpc',
921
            10 => 'jp2',
922
            11 => 'jpx',
923
            12 => 'jb2',
924
            13 => 'swc',
925
            14 => 'iff',
926
            15 => 'wbmp',
927
            16 => 'xbm');
928
929
        foreach ($_FILES as $_file) {
930
            if (!empty($_file['error'])) {
931
                continue;
932
            }
933
            if (!empty($_file['name']) && is_string($_file['name'])) {
934
                $ext = strtolower(substr(strrchr($_file['name'], '.'), 1));
935
                if ($ext === 'jpeg') {
936
                    $ext = 'jpg';
937
                } elseif ($ext === 'tiff') {
938
                    $ext = 'tif';
939
                }
940
941
                // anti multiple dot file (Apache mod_mime.c)
942
                if (count(explode('.', str_replace('.tar.gz', '.tgz', $_file['name']))) > 2) {
943
                    $this->message .= "Attempt to multiple dot file {$_file['name']}.\n";
944
                    $this->_safe_badext    = false;
945
                    $this->last_error_type = 'UPLOAD';
946
                }
947
948
                // anti dangerous extensions
949
                if (in_array($ext, $bad_extensions)) {
950
                    $this->message .= "Attempt to upload {$_file['name']}.\n";
951
                    $this->_safe_badext    = false;
952
                    $this->last_error_type = 'UPLOAD';
953
                }
954
955
                // anti camouflaged image file
956
                if (in_array($ext, $image_extensions)) {
957
                    $image_attributes = @getimagesize($_file['tmp_name']);
958
                    if ($image_attributes === false && is_uploaded_file($_file['tmp_name'])) {
959
                        // open_basedir restriction
960
                        $temp_file = XOOPS_ROOT_PATH . '/uploads/protector_upload_temporary' . md5(time());
961
                        move_uploaded_file($_file['tmp_name'], $temp_file);
962
                        $image_attributes = @getimagesize($temp_file);
963
                        @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

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

1147
            $result = json_decode(/** @scrutinizer ignore-type */ curl_exec($ch), true);
Loading history...
1148
        }
1149
        curl_close($ch);
1150
1151
        return $result;
1152
    }
1153
1154
    /**
1155
     * @param int  $uid
1156
     * @param bool $can_ban
1157
     *
1158
     * @return bool
1159
     */
1160
    public function check_dos_attack($uid = 0, $can_ban = false)
1161
    {
1162
        global $xoopsDB;
1163
1164
        if ($this->_done_dos) {
1165
            return true;
1166
        }
1167
1168
        $ip      = \Xmf\IPAddress::fromRequest();
1169
        if (false === $ip->asReadable()) {
0 ignored issues
show
introduced by
The condition false === $ip->asReadable() is always false.
Loading history...
1170
            return true;
1171
        }
1172
        $uri     = @$_SERVER['REQUEST_URI'];
1173
1174
        $ip4sql  = $xoopsDB->quote($ip->asReadable());
1175
        $uri4sql = $xoopsDB->quote($uri);
1176
1177
        // gargage collection
1178
        $result = $xoopsDB->queryF(
1179
            'DELETE FROM ' . $xoopsDB->prefix($this->mydirname . '_access')
1180
            . ' WHERE expire < UNIX_TIMESTAMP()'
1181
        );
1182
1183
        // for older versions before updating this module
1184
        if ($result === false) {
1185
            $this->_done_dos = true;
1186
1187
            return true;
1188
        }
1189
1190
        // sql for recording access log (INSERT should be placed after SELECT)
1191
        $sql4insertlog = 'INSERT INTO ' . $xoopsDB->prefix($this->mydirname . '_access')
1192
                         . " SET ip={$ip4sql}, request_uri={$uri4sql},"
1193
                         . " expire=UNIX_TIMESTAMP()+'" . (int)$this->_conf['dos_expire'] . "'";
1194
1195
        // bandwidth limitation
1196
        if (@$this->_conf['bwlimit_count'] >= 10) {
1197
            $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access');
1198
            $result = $xoopsDB->query($sql);
1199
            if ($xoopsDB->isResultSet($result)) {
1200
            list($bw_count) = $xoopsDB->fetchRow($result);
1201
            if ($bw_count > $this->_conf['bwlimit_count']) {
1202
                $this->write_file_bwlimit(time() + $this->_conf['dos_expire']);
1203
            }
1204
        }
1205
        }
1206
1207
        // F5 attack check (High load & same URI)
1208
1209
        $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . " WHERE ip={$ip4sql} AND request_uri={$uri4sql}";
1210
        $result = $xoopsDB->query($sql);
1211
        if (!$xoopsDB->isResultSet($result)) {
1212
            \trigger_error("Query Failed! SQL: $sql- Error: " . $xoopsDB->error(), E_USER_ERROR);
1213
        }
1214
        list($f5_count) = $xoopsDB->fetchRow($result);
1215
        if ($f5_count > $this->_conf['dos_f5count']) {
1216
1217
            // delayed insert
1218
            $xoopsDB->queryF($sql4insertlog);
1219
1220
            // extends the expires of the IP with 5 minutes at least (pending)
1221
            // $result = $xoopsDB->queryF( "UPDATE ".$xoopsDB->prefix($this->mydirname.'_access')." SET expire=UNIX_TIMESTAMP()+300 WHERE ip='$ip4sql' AND expire<UNIX_TIMESTAMP()+300" ) ;
1222
1223
            // call the filter first
1224
            $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...
1225
1226
            // actions for F5 Attack
1227
            $this->_done_dos       = true;
1228
            $this->last_error_type = 'DoS';
1229
            switch ($this->_conf['dos_f5action']) {
1230
                default :
1231
                case 'exit' :
1232
                    $this->output_log($this->last_error_type, $uid, true, 16);
1233
                    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...
1234
                case 'none' :
1235
                    $this->output_log($this->last_error_type, $uid, true, 16);
1236
1237
                    return true;
1238
                case 'biptime0' :
1239
                    if ($can_ban) {
1240
                        $this->register_bad_ips(time() + $this->_conf['banip_time0']);
1241
                    }
1242
                    break;
1243
                case 'bip' :
1244
                    if ($can_ban) {
1245
                        $this->register_bad_ips();
1246
                    }
1247
                    break;
1248
                case 'hta' :
1249
                    if ($can_ban) {
1250
                        $this->deny_by_htaccess();
1251
                    }
1252
                    break;
1253
                case 'sleep' :
1254
                    sleep(5);
1255
                    break;
1256
            }
1257
1258
            return false;
1259
        }
1260
1261
        // Check its Agent
1262
        if (trim($this->_conf['dos_crsafe']) != '' && preg_match($this->_conf['dos_crsafe'], @$_SERVER['HTTP_USER_AGENT'])) {
1263
            // welcomed crawler
1264
            $this->_done_dos = true;
1265
1266
            return true;
1267
        }
1268
1269
        // Crawler check (High load & different URI)
1270
        $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . " WHERE ip={$ip4sql}";
1271
        $result = $xoopsDB->query($sql);
1272
        if (!$xoopsDB->isResultSet($result)) {
1273
//            \trigger_error("Query Failed! SQL: $sql- Error: " . $xoopsDB->error(), E_USER_ERROR);
1274
            return false;
1275
        }
1276
        list($crawler_count) = $xoopsDB->fetchRow($result);
1277
1278
        // delayed insert
1279
        $xoopsDB->queryF($sql4insertlog);
1280
1281
        if ($crawler_count > $this->_conf['dos_crcount']) {
1282
1283
            // call the filter first
1284
            $ret = $this->call_filter('crawler_overrun');
1285
1286
            // actions for bad Crawler
1287
            $this->_done_dos       = true;
1288
            $this->last_error_type = 'CRAWLER';
1289
            switch ($this->_conf['dos_craction']) {
1290
                default :
1291
                case 'exit' :
1292
                    $this->output_log($this->last_error_type, $uid, true, 16);
1293
                    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...
1294
                case 'none' :
1295
                    $this->output_log($this->last_error_type, $uid, true, 16);
1296
1297
                    return true;
1298
                case 'biptime0' :
1299
                    if ($can_ban) {
1300
                        $this->register_bad_ips(time() + $this->_conf['banip_time0']);
1301
                    }
1302
                    break;
1303
                case 'bip' :
1304
                    if ($can_ban) {
1305
                        $this->register_bad_ips();
1306
                    }
1307
                    break;
1308
                case 'hta' :
1309
                    if ($can_ban) {
1310
                        $this->deny_by_htaccess();
1311
                    }
1312
                    break;
1313
                case 'sleep' :
1314
                    sleep(5);
1315
                    break;
1316
            }
1317
1318
            return false;
1319
        }
1320
1321
        return true;
1322
    }
1323
1324
    //
1325
    /**
1326
     * @return bool|null
1327
     */
1328
    public function check_brute_force()
1329
    {
1330
        global $xoopsDB;
1331
1332
        $ip      = \Xmf\IPAddress::fromRequest();
1333
        if (false === $ip->asReadable()) {
0 ignored issues
show
introduced by
The condition false === $ip->asReadable() is always false.
Loading history...
1334
            return true;
1335
        }
1336
        $uri     = @$_SERVER['REQUEST_URI'];
1337
        $ip4sql  = $xoopsDB->quote($ip->asReadable());
1338
        $uri4sql = $xoopsDB->quote($uri);
1339
1340
        $victim_uname = empty($_COOKIE['autologin_uname']) ? $_POST['uname'] : $_COOKIE['autologin_uname'];
1341
        // some UA send 'deleted' as a value of the deleted cookie.
1342
        if ($victim_uname === 'deleted') {
1343
            return null;
1344
        }
1345
        $mal4sql = $xoopsDB->quote("BRUTE FORCE: $victim_uname");
1346
1347
        // gargage collection
1348
        $result = $xoopsDB->queryF(
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
1349
            'DELETE FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . ' WHERE expire < UNIX_TIMESTAMP()'
1350
        );
1351
1352
        // sql for recording access log (INSERT should be placed after SELECT)
1353
        $sql4insertlog = 'INSERT INTO ' . $xoopsDB->prefix($this->mydirname . '_access')
1354
                         . " SET ip={$ip4sql}, request_uri={$uri4sql}, malicious_actions={$mal4sql}, expire=UNIX_TIMESTAMP()+600";
1355
1356
        // count check
1357
        $bf_count = 0;
1358
        $sql = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix($this->mydirname . '_access') . " WHERE ip={$ip4sql} AND malicious_actions like 'BRUTE FORCE:%'";
1359
        $result = $xoopsDB->query($sql);
1360
        if ($xoopsDB->isResultSet($result)) {
1361
            list($bf_count) = $xoopsDB->fetchRow($result);}
1362
        else{
1363
            \trigger_error("Query Failed! SQL: $sql- Error: " . $xoopsDB->error(), E_USER_ERROR);
1364
        }
1365
        if ($bf_count > $this->_conf['bf_count']) {
1366
            $this->register_bad_ips(time() + $this->_conf['banip_time0']);
1367
            $this->last_error_type = 'BruteForce';
1368
            $this->message .= "Trying to login as '" . addslashes($victim_uname) . "' found.\n";
1369
            $this->output_log('BRUTE FORCE', 0, true, 1);
1370
            $ret = $this->call_filter('bruteforce_overrun');
1371
            if ($ret == false) {
1372
                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...
1373
            }
1374
        }
1375
        // delayed insert
1376
        $xoopsDB->queryF($sql4insertlog);
1377
        return null;
1378
    }
1379
1380
    /**
1381
     * @param $val
1382
     */
1383
    protected function _spam_check_point_recursive($val)
1384
    {
1385
        if (is_array($val)) {
1386
            foreach ($val as $subval) {
1387
                $this->_spam_check_point_recursive($subval);
1388
            }
1389
        } else {
1390
            // http_host
1391
            $path_array = parse_url(XOOPS_URL);
1392
            $http_host  = empty($path_array['host']) ? 'www.xoops.org' : $path_array['host'];
1393
1394
            // count URI up
1395
            $count = -1;
1396
            foreach (preg_split('#https?\:\/\/#i', $val) as $fragment) {
1397
                if (strncmp($fragment, $http_host, strlen($http_host)) !== 0) {
1398
                    ++$count;
1399
                }
1400
            }
1401
            if ($count > 0) {
1402
                $this->_spamcount_uri += $count;
1403
            }
1404
1405
            // count BBCode likd [url=www....] up (without [url=http://...])
1406
            $this->_spamcount_uri += count(preg_split('/\[url=(?!http|\\"http|\\\'http|' . $http_host . ')/i', $val)) - 1;
1407
        }
1408
    }
1409
1410
    /**
1411
     * @param $points4deny
1412
     * @param $uid
1413
     */
1414
    public function spam_check($points4deny, $uid)
1415
    {
1416
        $this->_spamcount_uri = 0;
1417
        $this->_spam_check_point_recursive($_POST);
1418
1419
        if ($this->_spamcount_uri >= $points4deny) {
1420
            $this->message .= @$_SERVER['REQUEST_URI'] . " SPAM POINT: $this->_spamcount_uri\n";
1421
            $this->output_log('URI SPAM', $uid, false, 128);
1422
            $ret = $this->call_filter('spamcheck_overrun');
1423
            if ($ret == false) {
1424
                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...
1425
            }
1426
        }
1427
    }
1428
1429
    public function disable_features()
1430
    {
1431
        global $HTTP_POST_VARS, $HTTP_GET_VARS, $HTTP_COOKIE_VARS;
1432
1433
        // disable "Notice: Undefined index: ..."
1434
        $error_reporting_level = error_reporting(0);
1435
1436
        //
1437
        // bit 1 : disable XMLRPC , criteria bug
1438
        //
1439
        if ($this->_conf['disable_features'] & 1) {
1440
1441
            // zx 2005/1/5 disable xmlrpc.php in root
1442
            if (/* ! stristr( $_SERVER['SCRIPT_NAME'] , 'modules' ) && */
1443
                substr(@$_SERVER['SCRIPT_NAME'], -10) === 'xmlrpc.php'
1444
            ) {
1445
                $this->output_log('xmlrpc', 0, true, 1);
1446
                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...
1447
            }
1448
1449
            // security bug of class/criteria.php 2005/6/27
1450
            if ((isset($_POST['uname']) && $_POST['uname'] === '0') || (isset($_COOKIE['autologin_pass']) && $_COOKIE['autologin_pass'] === '0')) {
1451
                $this->output_log('CRITERIA');
1452
                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...
1453
            }
1454
        }
1455
1456
        //
1457
        // bit 11 : XSS+CSRFs in XOOPS < 2.0.10
1458
        //
1459
        if ($this->_conf['disable_features'] & 1024) {
1460
1461
            // root controllers
1462
            if (false === stripos(@$_SERVER['SCRIPT_NAME'], 'modules')) {
1463
                // zx 2004/12/13 misc.php debug (file check)
1464
                if (substr(@$_SERVER['SCRIPT_NAME'], -8) === 'misc.php' && ($_GET['type'] === 'debug' || $_POST['type'] === 'debug') && !preg_match('/^dummy_\d+\.html$/', $_GET['file'])) {
1465
                    $this->output_log('misc debug');
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
                // zx 2004/12/13 misc.php smilies
1470
                if (substr(@$_SERVER['SCRIPT_NAME'], -8) === 'misc.php' && ($_GET['type'] === 'smilies' || $_POST['type'] === 'smilies') && !preg_match('/^[0-9a-z_]*$/i', $_GET['target'])) {
1471
                    $this->output_log('misc smilies');
1472
                    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...
1473
                }
1474
1475
                // zx 2005/1/5 edituser.php avatarchoose
1476
                if (substr(@$_SERVER['SCRIPT_NAME'], -12) === 'edituser.php' && $_POST['op'] === 'avatarchoose' && false !== strpos($_POST['user_avatar'], '..')) {
1477
                    $this->output_log('edituser avatarchoose');
1478
                    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...
1479
                }
1480
            }
1481
1482
            // zx 2005/1/4 findusers
1483
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'findusers' || $_POST['fct'] === 'findusers')) {
1484
                foreach ($_POST as $key => $val) {
1485
                    if (false !== strpos($key, "'") || false !== strpos($val, "'")) {
1486
                        $this->output_log('findusers');
1487
                        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...
1488
                    }
1489
                }
1490
            }
1491
1492
            // preview CSRF zx 2004/12/14
1493
            // news submit.php
1494
            if (substr(@$_SERVER['SCRIPT_NAME'], -23) === 'modules/news/submit.php' && isset($_POST['preview']) && strpos(@$_SERVER['HTTP_REFERER'], XOOPS_URL . '/modules/news/submit.php') !== 0) {
1495
                $HTTP_POST_VARS['nohtml'] = $_POST['nohtml'] = 1;
1496
            }
1497
            // news admin/index.php
1498
            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) {
1499
                $HTTP_POST_VARS['nohtml'] = $_POST['nohtml'] = 1;
1500
            }
1501
            // comment comment_post.php
1502
            if (isset($_POST['com_dopreview']) && false === strpos(substr(@$_SERVER['HTTP_REFERER'], -16), 'comment_post.php')) {
1503
                $HTTP_POST_VARS['dohtml'] = $_POST['dohtml'] = 0;
1504
            }
1505
            // disable preview of system's blocksadmin
1506
            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 */) {
1507
                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...
1508
            }
1509
            // tpl preview
1510
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'tplsets' || $_POST['fct'] === 'tplsets')) {
1511
                if ($_POST['op'] === 'previewpopup' || $_GET['op'] === 'previewpopup' || isset($_POST['previewtpl'])) {
1512
                    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...
1513
                }
1514
            }
1515
        }
1516
1517
        // restore reporting level
1518
        error_reporting($error_reporting_level);
1519
    }
1520
1521
    /**
1522
     * @param        $type
1523
     * @param string $dying_message
1524
     *
1525
     * @return int|mixed
1526
     */
1527
    public function call_filter($type, $dying_message = '')
1528
    {
1529
        require_once __DIR__ . '/ProtectorFilter.php';
1530
        $filter_handler = ProtectorFilterHandler::getInstance();
1531
        $ret            = $filter_handler->execute($type);
1532
        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...
1533
            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...
1534
        }
1535
1536
        return $ret;
1537
    }
1538
}
1539