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