]> git.mxchange.org Git - ctracker.git/blob - libs/lib_detector.php
3b6dd587b197392da0cc19c144c38a94f1d67408
[ctracker.git] / libs / lib_detector.php
1 <?php
2 /**
3  * Detector library
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             3.0.0
7  * @copyright   Copyright (c) 2009 - 2017 Cracker Tracker Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 // Initializes all detector arrays
26 function initCrackerTrackerArrays () {
27         // Set error_reporting
28         if (isCrackerTrackerDebug()) {
29                 // For debugging purposes, this is fine
30                 @error_reporting(E_ALL | E_STRICT);
31         } else {
32                 // No output
33                 @error_reporting(0);
34         }
35
36         // Base path
37         $GLOBALS['ctracker_base_path'] = dirname(dirname(__FILE__));
38
39         // Whitelist some absolute query strings (see below)
40         $GLOBALS['ctracker_whitelist'] = [
41                 'cmd=new',    // LinPHA
42                 'cmd=edit',   // LinPHA
43                 'cmd=lostpw', // LinPHA
44                 '/css/status_config.php', // MantisBT
45                 '/css/common_config.php', // MantisBT
46                 '/javascript_config.php', // MantisBT
47         ];
48
49         // Attacks we should detect and block
50         $GLOBALS['ctracker_get_blacklist'] = [
51                 // SQL injections
52                 'union ', ' union', 'insert ',
53                 'select ', ' like', 'like ', 'drop ', 'update ',
54                 'union(', 'union=',
55
56                 // $GLOBAL/$_SERVER array elements
57                 'HTTP_USER_AGENT', 'HTTP_HOST', 'HTTP_PHP', '_SESSION', 'CFG_ROOT',
58                 'DOCUMENT_ROOT', '_SERVER',
59
60                 // Sensitive files
61                 '/environ', 'etc/shadow', 'etc/gshadow', 'etc/passwd', 'etc/group',
62                 'etc/./shadow', 'etc/./gshadow', 'etc/./passwd', 'etc/./group',
63                 '.htaccess', '.htpasswd', '.htgroup', '.history', 'bash_history',
64                 'bashrc',
65
66                 // Other Linux/FreeBSD/??? programs (sometimes with space)
67                 'traceroute ', 'ping ', 'bin/xterm', 'bin/./xterm', 'lsof ',
68                 'telnet ', 'wget ', 'bin/perl', 'bin/id', 'uname\x20', 'uname ',
69                 'killall', 'diff ', 'kill ', 'locate ', 'grep ', 'vi ', 'mv ',
70                 'rmdir ', 'mcd ', 'mrd ', 'rm ', ' mcd', ' mrd', ' rm',
71                 'passwd ', ' passwd', 'mdir ', ' mdir', 'cp ', ' cp',
72                 'esystem ', 'chr ', ' chr', 'wget ', ' wget', ' cmd',
73                 'cmd ', ' rush', 'rush ', ' echr', 'echr ', ' getenv',
74                 'getenv', 'reboot ', 'halt ', 'powerdown ',
75
76                 // Other Linux programs (+ brace)
77                 'locate(', 'grep(', 'kill(', 'mcd(', 'mrd(', 'rm(', 'mv(', 'rmdir(',
78                 'chmod(', 'chmod(', 'chown(', 'chgrp(', 'passwd(', 'vi(', 'cp(',
79                 'mdir(', 'system(', 'chr(', 'wget(', 'rush(', 'echr(',
80
81                 // Other Linux programs (+ equal)
82                 'mcd=', 'mrd=', 'chmod=', 'chr=', 'rush=', 'echr=',
83
84                 // Paths
85                 '/etc/', '/bin/', '/sbin/', '/self/', '/proc/', '../../','..//', '././',
86                 '/home/ftp', '/home/./ftp', '/home/./www', '/home/www', '/www/virtual/',
87                 '/www/./virtual/',
88
89                 // Uni* commands:
90                 '/chgrp', '/chown', '/chmod', 'chown ', 'chmod ', 'chgrp ',
91
92                 // Compiler/interpreter
93                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
94                 'bin/tclsh', 'bin/nasm', '/perl',
95
96                 // Windows-related
97                 'cmd.exe', 'nc.exe', 'ftp.exe', 'powershell', 'system.net.webclient',
98
99                 // php.ini settings
100                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
101                 'open_basedir', 'suhosin', 'cgi.force_redirect', 'cgi.redirect_status_env',
102
103                 // PHP commands/scripts
104                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
105                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
106                 'call_user_func',
107
108                 // Typical PHP script remote-inclusions and typical include file names
109                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
110                 'php_', 'class_', '_class.php', 'db_mysql.inc',
111
112                 // PHP arrays
113                 '_phplib', '__callbackparam',
114
115                 // Generic remote inclusion
116                 '=http://', '=https://', '=php://',
117                 'path=', 'sql=',
118                 '=%7BQUOT%7D', '=%5C', '=%22http','=%22ftp','=%22file','=%27http','=%27ftp',
119                 '=%27file',
120
121                 // Wrappers
122                 'data://', 'tcp://', 'udp://', 'raw://', 'javascript://', 'file://', 'ftp://',
123
124                 // Blocked "users"
125                 'nigga(', ' nigga', 'nigga ', 'starhack', 'busca',
126
127                 // Hidden HTML stuff
128                 ' style=', 'style =',
129                 'overflow:auto', 'overflow: auto',
130                 'overflow :auto', 'overflow : auto',
131                 'display:hidden', 'display: hidden',
132                 'display :hidden', 'display : hidden',
133                 'height:0px', 'height: 0px','height:1px', 'height: 1px',
134                 'width:0px', 'width: 0px','width:1px', 'width: 1px',
135
136                 // Uncommon user websites
137                 '~root', '~ftp', '~nobody',
138
139                 // Windows XP (?) hacks
140                 'xp_enumdsn', 'xp_availablemedia', 'xp_filelist', 'xp_cmdshell',
141
142                 // Attempts to insert links into a badly secured URL
143                 '%3E%3C',
144
145                 // Request header being inserted
146                 'content-type',
147
148                 // /proc/ and other forbidden paths
149                 'proc/self/environ',
150
151                 // MySQL internal functions
152                 'name_const',
153
154                 // Server configuration (e.g. Apache)
155                 'application/x-httpd-php', 'addtype', 'server-info', 'server-status',
156
157                 // @TODO Misc/unsorted
158                 'cgi-', '.eml', '$_request', '$_get', '$request', '$get', '.system',
159                 '&aim', 'new_password', '&icq', '.conf', 'motd ', 'HTTP/1.',
160                 'window.open', 'img src', 'img src', '.jsp', 'servlet', 'org.apache',
161                 'wwwacl', '/servlet/con', 'http_', 'secure_site, ok', 'chunked',
162                 '<script', 'mod_gzip_status', '.system', 'uol.com', ',0x', '(0x',
163                 'INSERT_RANDOM_NUMBER_HERE',
164         ];
165
166         // BLock these words found in User-Agent
167         $GLOBALS['ctracker_ua_blacklist'] = [
168                 // Compiler/interpreter
169                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
170                 'bin/tclsh', 'bin/nasm', '/perl', 'wget ', 'system(', 'curl ',
171
172                 // Windows-related
173                 'cmd.exe', 'nc.exe', 'ftp.exe', 'powershell', 'system.net.webclient',
174
175                 // php.ini settings
176                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
177
178                 // PHP commands/scripts
179                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
180                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
181
182                 // Typical PHP script remote-inclusions and typical include file names
183                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
184                 'php_', 'class_', '_class.php', 'db_mysql.inc',
185
186                 // PHP arrays
187                 '_phplib', '__callbackparam',
188
189                 // Request header being inserted
190                 'content-type',
191
192                 // /proc/ and other forbidden paths
193                 'proc/self/environ',
194         ];
195
196         // BLock these words found in User-Agent
197         $GLOBALS['ctracker_ua_blacklist'] = array(
198                 // Compiler/interpreter
199                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
200                 'bin/tclsh', 'bin/nasm', '/perl', 'cmd.exe',
201                 'nc.exe', 'ftp.exe', 'wget ', 'system(', 'curl ',
202
203                 // php.ini settings
204                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
205
206                 // PHP commands/scripts
207                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
208                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
209
210                 // Server configuration (e.g. Apache)
211                 'application/x-httpd-php',
212
213                 // Typical PHP script remote-inclusions and typical include file names
214                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
215                 'php_', 'class_', '_class.php', 'db_mysql.inc',
216
217                 // PHP arrays
218                 '_phplib', '__callbackparam',
219
220                 // Request header being inserted
221                 'content-type',
222
223                 // /proc/ and other forbidden paths
224                 'proc/self/environ',
225         );
226
227         // Block these words found in POST requests
228         $GLOBALS['ctracker_post_blacklist'] = [
229                 // This line is for detecting hidden link spam in wikis, forums, guestbooks, etc.
230                 ' style=', 'overflow:auto', 'height:1px', 'width:1px', 'display:hidden', 'style.display',
231
232                 // Windows-related
233                 'cmd.exe', 'nc.exe', 'ftp.exe', 'powershell', 'system.net.webclient',
234
235                 // Server configuration (e.g. Apache)
236                 'application/x-httpd-php',
237
238                 // "Common" login names from VHCS exploiters
239                 'starhack', 'DeLiMehmet', 'hisset', 'Hisset', 'delimert', 'MecTruy'
240         ];
241
242         // Also block these requests (mostly you don't want CONNECT to some SMTP sites)
243         $GLOBALS['ctracker_blocked_methods'] = [
244                 'CONNECT' => TRUE,
245         ];
246
247         // Init more elements
248         $GLOBALS['ctracker_post_track']   = '';
249         $GLOBALS['ctracker_checked_get']  = '';
250         $GLOBALS['ctracker_checked_post'] = '';
251         $GLOBALS['ctracker_checked_ua']   = '';
252 }
253
254 // Checks for worms
255 function isCrackerTrackerWormDetected () {
256         // Check against the whole list
257         $GLOBALS['ctracker_checked_get'] = urldecode(str_ireplace($GLOBALS['ctracker_get_blacklist'], '*', crackerTrackerQueryString(TRUE)));
258         $GLOBALS['ctracker_checked_ua']  = urldecode(str_ireplace($GLOBALS['ctracker_ua_blacklist'], '*', crackerTrackerUserAgent(TRUE)));
259
260         /*
261          * If it differs to original and the *whole* request string is not in
262          * whitelist then blog the attempt.
263          */
264         $isWorm = (
265                 (
266                         $GLOBALS['ctracker_checked_get'] != crackerTrackerQueryString(TRUE) && (!in_array(crackerTrackerQueryString(TRUE), $GLOBALS['ctracker_whitelist']))
267                 ) || (
268                         $GLOBALS['ctracker_checked_ua'] != crackerTrackerUserAgent(TRUE)
269                 ) || (
270                         isset($GLOBALS['ctracker_blocked_methods'][crackerTrackerRequestMethod()])
271                 )
272         );
273         //* DEBUG-DIE: */ die('isWorm='.intval($isWorm).PHP_EOL.'get='.PHP_EOL.'"'.$GLOBALS['ctracker_checked_get'].'"'.PHP_EOL.'"'.crackerTrackerQueryString().'"'.PHP_EOL.'ua='.PHP_EOL.'"'.$GLOBALS['ctracker_checked_ua'].'"'.PHP_EOL.'"'.crackerTrackerUserAgent().'"'.PHP_EOL);
274
275         // Return it
276         return $isWorm;
277 }
278
279 // Checks POST data
280 function isCrackerTrackerPostAttackDetected () {
281         // Implode recursive the whole $_POST array
282         $GLOBALS['ctracker_post_track'] = urldecode(implode_r('&', $_POST));
283
284         // Check for suspicious POST data
285         $GLOBALS['ctracker_checked_post'] = urldecode(str_ireplace($GLOBALS['ctracker_post_blacklist'], '*', crackerTrackerSanitize($GLOBALS['ctracker_post_track'])));
286
287         // Is it detected?
288         return ((isCrackerTrackerWormDetected()) || ($GLOBALS['ctracker_checked_post'] != crackerTrackerSanitize($GLOBALS['ctracker_post_track'])));
289 }
290
291 // Prepares a mail and send it out
292 function sendCrackerTrackerMail () {
293         // Log the attack
294         crackerTrackerLogAttack();
295
296         // Mail content
297         $mail = 'Attack detected:
298 -----------------------------------------------------
299 Remote-IP       : ' . determineCrackerTrackerRealRemoteAddress() . '
300 User-Agent      : ' . crackerTrackerUserAgent() . '
301 Request-string  : ' . crackerTrackerQueryString() . '
302 Filtered string : ' . $GLOBALS['ctracker_checked_get'] . '
303 Server          : ' . crackerTrackerServerName() . '
304 Script          : ' . crackerTrackerScriptName() . '
305 Method          : ' . crackerTrackerRequestMethod() . '
306 Referrer        : ' . crackerTrackerReferer() . '
307 -----------------------------------------------------
308 ';
309
310         // Send it out
311         crackerTrackerSendMail($mail);
312
313         // And die here
314         crackerTrackerDie();
315 }
316
317 // Sends the ticket emails out
318 function sendCrackerTrackerTicketMails () {
319         // Load user template
320         $mail = crackerTrackerLoadEmailTemplate('user_add_ticket', $GLOBALS['ctracker_last_ticket']);
321
322         // Send email to the user
323         crackerTrackerSendMail($mail, $GLOBALS['ctracker_last_ticket']['ctracker_ticket_email'], getCrackerTrackerLocalized('user_add_ticket_subject'));
324
325         // Load webmaster template
326         $mail = crackerTrackerLoadEmailTemplate('webmaster_add_ticket', $GLOBALS['ctracker_last_ticket'], getCrackerTrackerConfig('ctracker_language'));
327
328         // Send email to the user
329         crackerTrackerSendMail($mail, NULL, getCrackerTrackerLocalized('webmaster_add_ticket_subject'));
330 }
331
332 // Sends a mail out
333 function crackerTrackerSendMail ($mail, $recipient = NULL, $subject = NULL) {
334         // Construct dummy array
335         $rowData = [
336                 'remote_addr'    => determineCrackerTrackerRealRemoteAddress(),
337                 'proxy_addr'     => getenv('REMOTE_ADDR'),
338                 'check_get'      => $GLOBALS['ctracker_checked_get'],
339                 'server_name'    => crackerTrackerServerName(),
340                 'request_method' => crackerTrackerRequestMethod(),
341         ];
342
343         // Only send email if not yet found
344         if (!isCrackerTrackerEntryFound($rowData)) {
345                 // Send the email out only in non-debug mode
346                 if (isCrackerTrackerDebug()) {
347                         // Output message
348                         print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
349
350                         // All fine
351                         return TRUE;
352                 } elseif (!is_null($recipient)) {
353                         // Recipient specified
354                         return mail($recipient, $subject, $mail, $GLOBALS['ctracker_header']);
355                 } elseif (isset($GLOBALS['ctracker_email'])) {
356                         // Send it
357                         return mail($GLOBALS['ctracker_email'], 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
358                 } else {
359                         // Send it the deprecated way with constant
360                         return mail(constant('__CTRACKER_EMAIL'), 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
361                 }
362         } elseif (isCrackerTrackerDebug()) {
363                 // Output message
364                 print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
365
366                 // All fine
367                 return TRUE;
368         }
369 }
370
371 // Sends a detected POST attack mail
372 function sendCrackerTrackerPostMail () {
373         // Log the attack
374         crackerTrackerLogAttack();
375
376         // Mail text
377         $mail = 'POST-Attack detected:
378 -----------------------------------------------------
379 Remote-IP            : ' . determineCrackerTrackerRealRemoteAddress() . '
380 User-Agent           : ' . crackerTrackerUserAgent() . '
381 Request-string       : ' . crackerTrackerQueryString() . '
382 Filtered string      : ' . $GLOBALS['ctracker_checked_get'] . '
383 Server               : ' . crackerTrackerServerName() . '
384 Script               : ' . crackerTrackerScriptName() . '
385 Method               : ' . crackerTrackerRequestMethod() . '
386 Referrer             : ' . crackerTrackerReferer() . '
387 -----------------------------------------------------
388 POST string          : ' . $GLOBALS['ctracker_post_track'] . '
389 Filtered POST string : ' . $GLOBALS['ctracker_checked_post'] . '
390 -----------------------------------------------------
391 ';
392
393         // Send it out
394         crackerTrackerSendMail($mail);
395
396         // And die here
397         crackerTrackerDie();
398 }
399
400 // Sleeps for a random time and aborts the script
401 function crackerTrackerDie () {
402         // Close database link
403         crackerTrackerCloseDatabaseLink();
404
405         // Do only sleep if debug/developer mode is not enabled
406         if (!isCrackerTrackerDebug()) {
407                 // Sleep a little to waste the attacker's time
408                 sleep(mt_rand(10,30));
409         } // END - if
410
411         // Bye, bye...
412         if (isCrackerTrackerDebug()) {
413                 // With debug backtrace in debug/developer mode
414                 print '<pre>';
415                 debug_print_backtrace();
416                 die('</pre>');
417         } else {
418                 // Simple die() call
419                 die();
420         }
421 }
422
423 // Logs the attack attempt
424 function crackerTrackerLogAttack () {
425         // Aquire database link
426         aquireCrackerTrackerDatabaseLink();
427
428         // By default no proxy is used
429         $proxyUsed = 'N';
430
431         // Did the attacker use a proxy?
432         if (isCrackerTrackerProxyUsed()) {
433                 // Set it
434                 $proxyUsed = 'Y';
435         } // END - if
436
437         // Prepare array for database insert
438         $rowData = [
439                 'remote_addr'    => determineCrackerTrackerRealRemoteAddress(),
440                 'proxy_addr'     => getenv('REMOTE_ADDR'),
441                 'user_agent'     => crackerTrackerUserAgent(),
442                 'get_data'       => crackerTrackerQueryString(),
443                 'post_data'      => $GLOBALS['ctracker_post_track'],
444                 'check_ua'       => $GLOBALS['ctracker_checked_ua'],
445                 'check_get'      => $GLOBALS['ctracker_checked_get'],
446                 'check_post'     => $GLOBALS['ctracker_checked_post'],
447                 'server_name'    => crackerTrackerServerName(),
448                 'script_name'    => crackerTrackerScriptName(),
449                 'referer'        => crackerTrackerReferer(),
450                 'request_method' => crackerTrackerRequestMethod(),
451                 'proxy_used'     => $proxyUsed,
452                 'first_attempt'  => 'NOW()'
453         ];
454
455         // Insert the array in database
456         crackerTrackerInsertArray('ctracker_data', $rowData);
457 }
458
459 // Alerts the current user about malicious/suspicious traffic
460 function crackerTrackerAlertCurrentUser () {
461         // Is there some data?
462         if (isset($GLOBALS['ctracker_last_suspicious_entry'])) {
463                 // Does the user have a ticket?
464                 if (ifCrackerTrackerIpHasTicket()) {
465                         // Load "Thank you" template
466                         crackerTrackerLoadTemplate('add_ticket_thanks');
467                 } elseif ((isset($_POST['ctracker_add_ticket'])) && (!empty($_POST['name'])) && (!empty($_POST['email']))) {
468                         // Add the ticket
469                         addCrackerTrackerTicket($_POST);
470
471                         // Send the email out
472                         sendCrackerTrackerTicketMails();
473                 } else {
474                         // Display the form for new ticket
475                         crackerTrackerLoadTemplate('add_ticket');
476                 }
477         } // END - if
478
479         // And stop here
480         die();
481 }