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