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