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