Passed
Pull Request — master (#1323)
by Michael
05:22
created

Protector::spam_check()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 5
nop 2
dl 0
loc 11
rs 10
c 0
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 (isset($this->_conf['san_nullbyte']) && $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 = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
305
306
307
        if ($unique_check) {
308
            $result = mysqli_query($this->_conn, 'SELECT ip,type FROM ' . XOOPS_DB_PREFIX . '_' . $this->mydirname . '_log ORDER BY timestamp DESC LIMIT 1');
309
            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

309
            list($last_ip, $last_type) = mysqli_fetch_row(/** @scrutinizer ignore-type */ $result);
Loading history...
310
            if ($last_ip == $ip && $last_type == $type) {
311
                $this->_logged = true;
312
313
                return true;
314
            }
315
        }
316
317
        mysqli_query(
318
            $this->_conn,
319
            'INSERT INTO ' . XOOPS_DB_PREFIX . '_' . $this->mydirname . "_log SET ip='"
320
            . mysqli_real_escape_string($this->_conn, $ip) . "',agent='"
321
            . mysqli_real_escape_string($this->_conn, $agent) . "',type='"
322
            . mysqli_real_escape_string($this->_conn, $type) . "',description='"
323
            . mysqli_real_escape_string($this->_conn, $this->message) . "',uid='"
324
            . (int)$uid . "',timestamp=NOW()"
325
        );
326
        $this->_logged = true;
327
328
        return true;
329
    }
330
331
    /**
332
     * @param $expire
333
     *
334
     * @return bool
335
     */
336
    public function write_file_bwlimit($expire)
337
    {
338
        $expire = min((int)$expire, time() + 300);
339
340
        $fp = @fopen($this->get_filepath4bwlimit(), 'w');
341
        if ($fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
342
            @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

342
            /** @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...
343
            fwrite($fp, $expire . "\n");
344
            @flock($fp, LOCK_UN);
345
            fclose($fp);
346
347
            return true;
348
        } else {
349
            return false;
350
        }
351
    }
352
353
    /**
354
     * @return mixed
355
     */
356
    public function get_bwlimit()
357
    {
358
        list($expire) = @file(Protector::get_filepath4bwlimit());
359
        $expire = min((int)$expire, time() + 300);
360
361
        return $expire;
362
    }
363
364
    /**
365
     * @return string
366
     */
367
    public static function get_filepath4bwlimit()
368
    {
369
        return XOOPS_VAR_PATH . '/protector/bwlimit' . substr(md5(XOOPS_ROOT_PATH . XOOPS_DB_USER . XOOPS_DB_PREFIX), 0, 6);
370
    }
371
372
    /**
373
     * @param $bad_ips
374
     *
375
     * @return bool
376
     */
377
    public function write_file_badips($bad_ips)
378
    {
379
        asort($bad_ips);
380
381
        $fp = @fopen($this->get_filepath4badips(), 'w');
382
        if ($fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
383
            @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

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

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

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

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

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