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