]> git.mxchange.org Git - ctracker.git/blob - libs/lib_detector.php
:( Not good enough
[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 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(', ' nigga', 'nigga ', 'starhack', 'busca',
110
111                 // Hidden HTML stuff
112                 ' style=', 'style =',
113                 'overflow:auto', 'overflow: auto',
114                 'overflow :auto', 'overflow : auto',
115                 'display:hidden', 'display: hidden',
116                 'display :hidden', 'display : hidden',
117                 'height:0px', 'height: 0px','height:1px', 'height: 1px',
118                 'width:0px', 'width: 0px','width:1px', 'width: 1px',
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 ', 'HTTP/1.',
129                 'window.open', 'img src', 'img src', '.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                 ' style=', '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                 'proxy_addr'  => getenv('REMOTE_ADDR'),
222                 'check_worm'  => $GLOBALS['ctracker_checkworm'],
223                 'server_name' => crackerTrackerServerName()
224         );
225
226         // Only send email if not yet found
227         if (!isCrackerTrackerEntryFound($rowData)) {
228                 // Send the email out only in non-debug mode
229                 if (isCrackerTrackerDebug()) {
230                         // Output message
231                         print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
232
233                         // All fine
234                         return TRUE;
235                 } elseif (!is_null($recipient)) {
236                         // Recipient specified
237                         return mail($recipient, $subject, $mail, $GLOBALS['ctracker_header']);
238                 } elseif (isset($GLOBALS['ctracker_email'])) {
239                         // Send it
240                         return mail($GLOBALS['ctracker_email'], 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
241                 } else {
242                         // Send it the deprecated way with constant
243                         return mail(constant('__CTRACKER_EMAIL'), 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
244                 }
245         } elseif (isCrackerTrackerDebug()) {
246                 // Output message
247                 print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
248
249                 // All fine
250                 return TRUE;
251         }
252 }
253
254 // Sends a detected POST attack mail
255 function sendCrackerTrackerPostMail () {
256         // Log the attack
257         crackerTrackerLogAttack();
258
259         // Mail text
260         $mail = 'POST-Attack detected:
261 -----------------------------------------------------
262 Remote-IP            : '.determineCrackerTrackerRealRemoteAddress().'
263 User-Agent           : '.crackerTrackerUserAgent().'
264 Request-string       : '.crackerTrackerQueryString().'
265 Filtered string      : '.$GLOBALS['ctracker_checkworm'].'
266 Server               : '.crackerTrackerServerName().'
267 Script               : '.crackerTrackerScriptName().'
268 Referrer             : '.crackerTrackerReferer().'
269 -----------------------------------------------------
270 POST string          : '.$GLOBALS['ctracker_post_track'].'
271 Filtered POST string : '.$GLOBALS['ctracker_check_post'].'
272 -----------------------------------------------------
273 ';
274
275         // Send it out
276         crackerTrackerSendMail($mail);
277
278         // And die here
279         crackerTrackerDie();
280 }
281
282 // Sleeps for a random time and aborts the script
283 function crackerTrackerDie () {
284         // Close database link
285         crackerTrackerCloseDatabaseLink();
286
287         // Do only sleep if debug/developer mode is not enabled
288         if (!isCrackerTrackerDebug()) {
289                 // Sleep a little to waste the attacker's time
290                 sleep(mt_rand(10,30));
291         } // END - if
292
293         // Bye, bye...
294         if (isCrackerTrackerDebug()) {
295                 // With debug backtrace in debug/developer mode
296                 print '<pre>';
297                 debug_print_backtrace();
298                 die('</pre>');
299         } else {
300                 // Simple die() call
301                 die();
302         }
303 }
304
305 // Logs the attack attempt
306 function crackerTrackerLogAttack () {
307         // Aquire database link
308         aquireCrackerTrackerDatabaseLink();
309
310         // By default no proxy is used
311         $proxyUsed = 'N';
312
313         // Did the attacker use a proxy?
314         if (isCrackerTrackerProxyUsed()) {
315                 // Set it
316                 $proxyUsed = 'Y';
317         } // END - if
318
319         // Prepare array for database insert
320         $rowData = array(
321                 'remote_addr'   => determineCrackerTrackerRealRemoteAddress(),
322                 'proxy_addr'    => getenv('REMOTE_ADDR'),
323                 'user_agent'    => crackerTrackerUserAgent(),
324                 'get_data'      => crackerTrackerQueryString(),
325                 'post_data'     => $GLOBALS['ctracker_post_track'],
326                 'check_worm'    => $GLOBALS['ctracker_checkworm'],
327                 'check_post'    => $GLOBALS['ctracker_check_post'],
328                 'server_name'   => crackerTrackerServerName(),
329                 'script_name'   => crackerTrackerScriptName(),
330                 'referer'       => crackerTrackerReferer(),
331                 'proxy_used'    => $proxyUsed,
332                 'first_attempt' => 'NOW()'
333         );
334
335         // Insert the array in database
336         crackerTrackerInsertArray('ctracker_data', $rowData);
337 }
338
339 // Alerts the current user about malicious/suspicious traffic
340 function crackerTrackerAlertCurrentUser () {
341         // Is there some data?
342         if (isset($GLOBALS['ctracker_last_suspicious_entry'])) {
343                 // Does the user have a ticket?
344                 if (ifCrackerTrackerIpHasTicket()) {
345                         // Should we continue?
346                         if (isset($_POST['ctracker_continue'])) {
347                                 // Set cookie
348                                 sendCrackerTrackerCookie();
349
350                                 // And redirect to same URL
351                                 crackerTrackerRedirectSameUrl();
352                         } elseif (ifCrackerTrackerCookieIsSet()) {
353                                 // Return here to normal program
354                                 return;
355                         } else {
356                                 // Load "Thank you" template
357                                 crackerTrackerLoadTemplate('add_ticket_thanks');
358                         }
359                 } elseif ((isset($_POST['ctracker_add_ticket'])) && (!empty($_POST['name'])) && (!empty($_POST['email']))) {
360                         // Add the ticket
361                         addCrackerTrackerTicket($_POST);
362
363                         // Send the email out
364                         sendCrackerTrackerTicketMails();
365                 } else {
366                         // Display the form for new ticket
367                         crackerTrackerLoadTemplate('add_ticket');
368                 }
369         } // END - if
370
371         // And stop here
372         die();
373 }
374
375 // [EOF]
376 ?>