]> git.mxchange.org Git - ctracker.git/blob - libs/lib_detector.php
1a932ba40a253422b1f4722204704cff098c57cd
[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                 // Annoying script name
158                 'vuln.php',
159
160                 // @TODO Misc/unsorted
161                 'cgi-', '.eml', '$_request', '$_get', '$request', '$get', '.system',
162                 '&aim', 'new_password', '&icq', '.conf', 'motd ', 'HTTP/1.',
163                 'window.open', 'img src', 'img src', '.jsp', 'servlet', 'org.apache',
164                 'wwwacl', '/servlet/con', 'http_', 'secure_site, ok', 'chunked',
165                 '<script', 'mod_gzip_status', '.system', 'uol.com', ',0x', '(0x',
166                 'INSERT_RANDOM_NUMBER_HERE',
167         ];
168
169         // BLock these words found in User-Agent
170         $GLOBALS['ctracker_ua_blacklist'] = [
171                 // Compiler/interpreter
172                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
173                 'bin/tclsh', 'bin/nasm', '/perl', 'wget ', 'system(', 'curl ',
174
175                 // Windows-related
176                 'cmd.exe', 'nc.exe', 'ftp.exe', 'powershell', 'system.net.webclient',
177
178                 // php.ini settings
179                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
180
181                 // PHP commands/scripts
182                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
183                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
184
185                 // Typical PHP script remote-inclusions and typical include file names
186                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
187                 'php_', 'class_', '_class.php', 'db_mysql.inc',
188
189                 // PHP arrays
190                 '_phplib', '__callbackparam',
191
192                 // Request header being inserted
193                 'content-type',
194
195                 // /proc/ and other forbidden paths
196                 'proc/self/environ',
197         ];
198
199         // BLock these words found in User-Agent
200         $GLOBALS['ctracker_ua_blacklist'] = array(
201                 // Compiler/interpreter
202                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
203                 'bin/tclsh', 'bin/nasm', '/perl', 'cmd.exe',
204                 'nc.exe', 'ftp.exe', 'wget ', 'system(', 'curl ',
205
206                 // php.ini settings
207                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
208
209                 // PHP commands/scripts
210                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
211                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
212
213                 // Server configuration (e.g. Apache)
214                 'application/x-httpd-php',
215
216                 // Typical PHP script remote-inclusions and typical include file names
217                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
218                 'php_', 'class_', '_class.php', 'db_mysql.inc',
219
220                 // PHP arrays
221                 '_phplib', '__callbackparam',
222
223                 // Request header being inserted
224                 'content-type',
225
226                 // /proc/ and other forbidden paths
227                 'proc/self/environ',
228         );
229
230         // Block these words found in POST requests
231         $GLOBALS['ctracker_post_blacklist'] = [
232                 // This line is for detecting hidden link spam in wikis, forums, guestbooks, etc.
233                 ' style=', 'overflow:auto', 'height:1px', 'width:1px', 'display:hidden', 'style.display',
234
235                 // Windows-related
236                 'cmd.exe', 'nc.exe', 'ftp.exe', 'powershell', 'system.net.webclient',
237
238                 // Server configuration (e.g. Apache)
239                 'application/x-httpd-php',
240
241                 // Annoying script name
242                 'vuln.php',
243
244                 // "Common" login names from VHCS exploiters
245                 'starhack', 'DeLiMehmet', 'hisset', 'Hisset', 'delimert', 'MecTruy'
246         ];
247
248         // Also block these requests (mostly you don't want CONNECT to some SMTP sites)
249         $GLOBALS['ctracker_blocked_methods'] = [
250                 'CONNECT' => TRUE,
251         ];
252
253         // Init more elements
254         $GLOBALS['ctracker_post_track']   = '';
255         $GLOBALS['ctracker_checked_get']  = '';
256         $GLOBALS['ctracker_checked_post'] = '';
257         $GLOBALS['ctracker_checked_ua']   = '';
258 }
259
260 // Checks for worms
261 function isCrackerTrackerWormDetected () {
262         // Check against the whole list
263         $GLOBALS['ctracker_checked_get'] = urldecode(str_ireplace($GLOBALS['ctracker_get_blacklist'], '*', crackerTrackerQueryString(TRUE)));
264         $GLOBALS['ctracker_checked_ua']  = urldecode(str_ireplace($GLOBALS['ctracker_ua_blacklist'], '*', crackerTrackerUserAgent(TRUE)));
265
266         /*
267          * If it differs to original and the *whole* request string is not in
268          * whitelist then blog the attempt.
269          */
270         $isWorm = (
271                 (
272                         $GLOBALS['ctracker_checked_get'] != crackerTrackerQueryString(TRUE) && (!in_array(crackerTrackerQueryString(TRUE), $GLOBALS['ctracker_whitelist']))
273                 ) || (
274                         $GLOBALS['ctracker_checked_ua'] != crackerTrackerUserAgent(TRUE)
275                 ) || (
276                         isset($GLOBALS['ctracker_blocked_methods'][crackerTrackerRequestMethod()])
277                 )
278         );
279         //* 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);
280
281         // Return it
282         return $isWorm;
283 }
284
285 // Checks POST data
286 function isCrackerTrackerPostAttackDetected () {
287         // Implode recursive the whole $_POST array
288         $GLOBALS['ctracker_post_track'] = urldecode(implode_r('&', $_POST));
289
290         // Check for suspicious POST data
291         $GLOBALS['ctracker_checked_post'] = urldecode(str_ireplace($GLOBALS['ctracker_post_blacklist'], '*', crackerTrackerSanitize($GLOBALS['ctracker_post_track'])));
292
293         // Is it detected?
294         return ((isCrackerTrackerWormDetected()) || ($GLOBALS['ctracker_checked_post'] != crackerTrackerSanitize($GLOBALS['ctracker_post_track'])));
295 }
296
297 // Prepares a mail and send it out
298 function sendCrackerTrackerMail () {
299         // Log the attack
300         crackerTrackerLogAttack();
301
302         // Mail content
303         $mail = 'Attack detected:
304 -----------------------------------------------------
305 Remote-IP       : ' . determineCrackerTrackerRealRemoteAddress() . '
306 User-Agent      : ' . crackerTrackerUserAgent() . '
307 Request-string  : ' . crackerTrackerQueryString() . '
308 Filtered string : ' . $GLOBALS['ctracker_checked_get'] . '
309 Server          : ' . crackerTrackerServerName() . '
310 Script          : ' . crackerTrackerScriptName() . '
311 Method          : ' . crackerTrackerRequestMethod() . '
312 Referrer        : ' . crackerTrackerReferer() . '
313 -----------------------------------------------------
314 ';
315
316         // Send it out
317         crackerTrackerSendMail($mail);
318
319         // And die here
320         crackerTrackerDie();
321 }
322
323 // Sends the ticket emails out
324 function sendCrackerTrackerTicketMails () {
325         // Load user template
326         $mail = crackerTrackerLoadEmailTemplate('user_add_ticket', $GLOBALS['ctracker_last_ticket']);
327
328         // Send email to the user
329         crackerTrackerSendMail($mail, $GLOBALS['ctracker_last_ticket']['ctracker_ticket_email'], getCrackerTrackerLocalized('user_add_ticket_subject'));
330
331         // Load webmaster template
332         $mail = crackerTrackerLoadEmailTemplate('webmaster_add_ticket', $GLOBALS['ctracker_last_ticket'], getCrackerTrackerConfig('ctracker_language'));
333
334         // Send email to the user
335         crackerTrackerSendMail($mail, NULL, getCrackerTrackerLocalized('webmaster_add_ticket_subject'));
336 }
337
338 // Sends a mail out
339 function crackerTrackerSendMail ($mail, $recipient = NULL, $subject = NULL) {
340         // Construct dummy array
341         $rowData = [
342                 'remote_addr'    => determineCrackerTrackerRealRemoteAddress(),
343                 'proxy_addr'     => getenv('REMOTE_ADDR'),
344                 'check_get'      => $GLOBALS['ctracker_checked_get'],
345                 'server_name'    => crackerTrackerServerName(),
346                 'request_method' => crackerTrackerRequestMethod(),
347         ];
348
349         // Only send email if not yet found
350         if (!isCrackerTrackerEntryFound($rowData)) {
351                 // Send the email out only in non-debug mode
352                 if (isCrackerTrackerDebug()) {
353                         // Output message
354                         print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
355
356                         // All fine
357                         return TRUE;
358                 } elseif (!is_null($recipient)) {
359                         // Recipient specified
360                         return mail($recipient, $subject, $mail, $GLOBALS['ctracker_header']);
361                 } elseif (isset($GLOBALS['ctracker_email'])) {
362                         // Send it
363                         return mail($GLOBALS['ctracker_email'], 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
364                 } else {
365                         // Send it the deprecated way with constant
366                         return mail(constant('__CTRACKER_EMAIL'), 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
367                 }
368         } elseif (isCrackerTrackerDebug()) {
369                 // Output message
370                 print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
371
372                 // All fine
373                 return TRUE;
374         }
375 }
376
377 // Sends a detected POST attack mail
378 function sendCrackerTrackerPostMail () {
379         // Log the attack
380         crackerTrackerLogAttack();
381
382         // Mail text
383         $mail = 'POST-Attack detected:
384 -----------------------------------------------------
385 Remote-IP            : ' . determineCrackerTrackerRealRemoteAddress() . '
386 User-Agent           : ' . crackerTrackerUserAgent() . '
387 Request-string       : ' . crackerTrackerQueryString() . '
388 Filtered string      : ' . $GLOBALS['ctracker_checked_get'] . '
389 Server               : ' . crackerTrackerServerName() . '
390 Script               : ' . crackerTrackerScriptName() . '
391 Method               : ' . crackerTrackerRequestMethod() . '
392 Referrer             : ' . crackerTrackerReferer() . '
393 -----------------------------------------------------
394 POST string          : ' . $GLOBALS['ctracker_post_track'] . '
395 Filtered POST string : ' . $GLOBALS['ctracker_checked_post'] . '
396 -----------------------------------------------------
397 ';
398
399         // Send it out
400         crackerTrackerSendMail($mail);
401
402         // And die here
403         crackerTrackerDie();
404 }
405
406 // Sleeps for a random time and aborts the script
407 function crackerTrackerDie () {
408         // Close database link
409         crackerTrackerCloseDatabaseLink();
410
411         // Do only sleep if debug/developer mode is not enabled
412         if (!isCrackerTrackerDebug()) {
413                 // Sleep a little to waste the attacker's time
414                 sleep(mt_rand(10,30));
415         } // END - if
416
417         // Bye, bye...
418         if (isCrackerTrackerDebug()) {
419                 // With debug backtrace in debug/developer mode
420                 print '<pre>';
421                 debug_print_backtrace();
422                 die('</pre>');
423         } else {
424                 // Simple die() call
425                 die();
426         }
427 }
428
429 // Logs the attack attempt
430 function crackerTrackerLogAttack () {
431         // Aquire database link
432         aquireCrackerTrackerDatabaseLink();
433
434         // By default no proxy is used
435         $proxyUsed = 'N';
436
437         // Did the attacker use a proxy?
438         if (isCrackerTrackerProxyUsed()) {
439                 // Set it
440                 $proxyUsed = 'Y';
441         } // END - if
442
443         // Prepare array for database insert
444         $rowData = [
445                 'remote_addr'    => determineCrackerTrackerRealRemoteAddress(),
446                 'proxy_addr'     => getenv('REMOTE_ADDR'),
447                 'user_agent'     => crackerTrackerUserAgent(),
448                 'get_data'       => crackerTrackerQueryString(),
449                 'post_data'      => $GLOBALS['ctracker_post_track'],
450                 'check_ua'       => $GLOBALS['ctracker_checked_ua'],
451                 'check_get'      => $GLOBALS['ctracker_checked_get'],
452                 'check_post'     => $GLOBALS['ctracker_checked_post'],
453                 'server_name'    => crackerTrackerServerName(),
454                 'script_name'    => crackerTrackerScriptName(),
455                 'referer'        => crackerTrackerReferer(),
456                 'request_method' => crackerTrackerRequestMethod(),
457                 'proxy_used'     => $proxyUsed,
458                 'first_attempt'  => 'NOW()'
459         ];
460
461         // Insert the array in database
462         crackerTrackerInsertArray('ctracker_data', $rowData);
463 }
464
465 // Alerts the current user about malicious/suspicious traffic
466 function crackerTrackerAlertCurrentUser () {
467         // Is there some data?
468         if (isset($GLOBALS['ctracker_last_suspicious_entry'])) {
469                 // Does the user have a ticket?
470                 if (ifCrackerTrackerIpHasTicket()) {
471                         // Load "Thank you" template
472                         crackerTrackerLoadTemplate('add_ticket_thanks');
473                 } elseif ((isset($_POST['ctracker_add_ticket'])) && (!empty($_POST['name'])) && (!empty($_POST['email']))) {
474                         // Add the ticket
475                         addCrackerTrackerTicket($_POST);
476
477                         // Send the email out
478                         sendCrackerTrackerTicketMails();
479                 } else {
480                         // Display the form for new ticket
481                         crackerTrackerLoadTemplate('add_ticket');
482                 }
483         } // END - if
484
485         // And stop here
486         die();
487 }