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