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