Passed
Pull Request — master (#1270)
by Michael
05:10
created

Protector::purgeNoExit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1467
                }
1468
            }
1469
1470
            // zx 2005/1/4 findusers
1471
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'findusers' || $_POST['fct'] === 'findusers')) {
1472
                foreach ($_POST as $key => $val) {
1473
                    if (false !== strpos($key, "'") || false !== strpos($val, "'")) {
1474
                        $this->output_log('findusers');
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
            }
1479
1480
            // preview CSRF zx 2004/12/14
1481
            // news submit.php
1482
            if (substr(@$_SERVER['SCRIPT_NAME'], -23) === 'modules/news/submit.php' && isset($_POST['preview']) && strpos(@$_SERVER['HTTP_REFERER'], XOOPS_URL . '/modules/news/submit.php') !== 0) {
1483
                $HTTP_POST_VARS['nohtml'] = $_POST['nohtml'] = 1;
1484
            }
1485
            // news admin/index.php
1486
            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) {
1487
                $HTTP_POST_VARS['nohtml'] = $_POST['nohtml'] = 1;
1488
            }
1489
            // comment comment_post.php
1490
            if (isset($_POST['com_dopreview']) && false === strpos(substr(@$_SERVER['HTTP_REFERER'], -16), 'comment_post.php')) {
1491
                $HTTP_POST_VARS['dohtml'] = $_POST['dohtml'] = 0;
1492
            }
1493
            // disable preview of system's blocksadmin
1494
            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 */) {
1495
                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...
1496
            }
1497
            // tpl preview
1498
            if (substr(@$_SERVER['SCRIPT_NAME'], -24) === 'modules/system/admin.php' && ($_GET['fct'] === 'tplsets' || $_POST['fct'] === 'tplsets')) {
1499
                if ($_POST['op'] === 'previewpopup' || $_GET['op'] === 'previewpopup' || isset($_POST['previewtpl'])) {
1500
                    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...
1501
                }
1502
            }
1503
        }
1504
1505
        // restore reporting level
1506
        error_reporting($error_reporting_level);
1507
    }
1508
1509
    /**
1510
     * @param        $type
1511
     * @param string $dying_message
1512
     *
1513
     * @return int|mixed
1514
     */
1515
    public function call_filter($type, $dying_message = '')
1516
    {
1517
        require_once __DIR__ . '/ProtectorFilter.php';
1518
        $filter_handler = ProtectorFilterHandler::getInstance();
1519
        $ret            = $filter_handler->execute($type);
1520
        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...
1521
            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...
1522
        }
1523
1524
        return $ret;
1525
    }
1526
}
1527