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