Added some php.ini settings to block
[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                 // Attempts to insert links into a badly secured URL
127                 '%3E%3C',
128
129                 // php.ini settings
130                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions',
131
132                 // @TODO Misc/unsorted
133                 'cgi-', '.eml', '$_request', '$_get', '$request', '$get', '.system',
134                 '&aim', 'new_password', '&icq', '.conf', 'motd ', 'HTTP/1.',
135                 'window.open', 'img src', 'img src', '.jsp', 'servlet',
136                 'wwwacl', '.js', '.jsp', 'server-info', 'server-status',
137                 'secure_site, ok', 'chunked', 'org.apache', '/servlet/con',
138                 '<script', 'mod_gzip_status', '.system', 'http_',
139                 'uol.com', ',0x', '(0x',
140         );
141
142         // Block these words found in POST requests
143         $GLOBALS['ctracker_post_blacklist'] = array(
144                 // This line is for detecting hidden link spam in wikis, forums, guestbooks, etc.
145                 ' style=', 'overflow:auto', 'height:1px', 'width:1px', 'display:hidden', 'style.display',
146
147                 // "Common" login names from VHCS exploiters ;-)
148                 'starhack', 'DeLiMehmet', 'hisset', 'Hisset', 'delimert', 'MecTruy'
149         );
150
151         // Load email header
152         $GLOBALS['ctracker_header'] = crackerTrackerLoadEmailTemplate('header');
153
154         // Init more elements
155         $GLOBALS['ctracker_post_track'] = '';
156         $GLOBALS['ctracker_checkworm']  = '';
157         $GLOBALS['ctracker_check_post'] = '';
158 }
159
160 // Checks for worms
161 function isCrackerTrackerWormDetected () {
162         // Check against the whole list
163         $GLOBALS['ctracker_checkworm'] = urldecode(str_ireplace($GLOBALS['ctracker_get_blacklist'], '*', crackerTrackerQueryString()));
164
165         // If it differs to original and the *whole* request string is not in whitelist
166         // then blog the attempt
167         return ($GLOBALS['ctracker_checkworm'] != crackerTrackerQueryString() && (!in_array(crackerTrackerQueryString(), $GLOBALS['ctracker_whitelist'])));
168 }
169
170 // Checks POST data
171 function isCrackerTrackerPostAttackDetected () {
172         // Implode recursive the whole $_POST array
173         $GLOBALS['ctracker_post_track'] = urldecode(implode_r('', $_POST));
174
175         // Check for suspicious POST data
176         $GLOBALS['ctracker_check_post'] = str_ireplace($GLOBALS['ctracker_post_blacklist'], '*', $GLOBALS['ctracker_post_track']);
177
178         // Is it detected?
179         return ((isCrackerTrackerWormDetected()) || ($GLOBALS['ctracker_check_post'] != $GLOBALS['ctracker_post_track']));
180 }
181
182 // Prepares a mail and send it out
183 function sendCrackerTrackerMail () {
184         // Log the attack
185         crackerTrackerLogAttack();
186
187         // Mail content
188         $mail = 'Attack detected:
189 -----------------------------------------------------
190 Remote-IP       : ' . determineCrackerTrackerRealRemoteAddress() . '
191 User-Agent      : ' . crackerTrackerUserAgent() . '
192 Request-string  : ' . crackerTrackerQueryString() . '
193 Filtered string : ' . $GLOBALS['ctracker_checkworm'] . '
194 Server          : ' . crackerTrackerServerName() . '
195 Script          : ' . crackerTrackerScriptName() . '
196 Referrer        : ' . crackerTrackerReferer() . '
197 -----------------------------------------------------
198 ';
199
200         // Send it out
201         crackerTrackerSendMail($mail);
202
203         // And die here
204         crackerTrackerDie();
205 }
206
207 // Sends the ticket emails out
208 function sendCrackerTrackerTicketMails () {
209         // Load user template
210         $mail = crackerTrackerLoadEmailTemplate('user_add_ticket', $GLOBALS['ctracker_last_ticket']);
211
212         // Send email to the user
213         crackerTrackerSendMail($mail, $GLOBALS['ctracker_last_ticket']['ctracker_ticket_email'], getCrackerTrackerLocalized('user_add_ticket_subject'));
214
215         // Load webmaster template
216         $mail = crackerTrackerLoadEmailTemplate('webmaster_add_ticket', $GLOBALS['ctracker_last_ticket'], getCrackerTrackerConfig('ctracker_language'));
217
218         // Send email to the user
219         crackerTrackerSendMail($mail, NULL, getCrackerTrackerLocalized('webmaster_add_ticket_subject'));
220 }
221
222 // Sends a mail out
223 function crackerTrackerSendMail ($mail, $recipient = NULL, $subject = NULL) {
224         // Construct dummy array
225         $rowData = array(
226                 'remote_addr' => determineCrackerTrackerRealRemoteAddress(),
227                 'proxy_addr'  => getenv('REMOTE_ADDR'),
228                 'check_worm'  => $GLOBALS['ctracker_checkworm'],
229                 'server_name' => crackerTrackerServerName()
230         );
231
232         // Only send email if not yet found
233         if (!isCrackerTrackerEntryFound($rowData)) {
234                 // Send the email out only in non-debug mode
235                 if (isCrackerTrackerDebug()) {
236                         // Output message
237                         print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
238
239                         // All fine
240                         return TRUE;
241                 } elseif (!is_null($recipient)) {
242                         // Recipient specified
243                         return mail($recipient, $subject, $mail, $GLOBALS['ctracker_header']);
244                 } elseif (isset($GLOBALS['ctracker_email'])) {
245                         // Send it
246                         return mail($GLOBALS['ctracker_email'], 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
247                 } else {
248                         // Send it the deprecated way with constant
249                         return mail(constant('__CTRACKER_EMAIL'), 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
250                 }
251         } elseif (isCrackerTrackerDebug()) {
252                 // Output message
253                 print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
254
255                 // All fine
256                 return TRUE;
257         }
258 }
259
260 // Sends a detected POST attack mail
261 function sendCrackerTrackerPostMail () {
262         // Log the attack
263         crackerTrackerLogAttack();
264
265         // Mail text
266         $mail = 'POST-Attack detected:
267 -----------------------------------------------------
268 Remote-IP            : '.determineCrackerTrackerRealRemoteAddress().'
269 User-Agent           : '.crackerTrackerUserAgent().'
270 Request-string       : '.crackerTrackerQueryString().'
271 Filtered string      : '.$GLOBALS['ctracker_checkworm'].'
272 Server               : '.crackerTrackerServerName().'
273 Script               : '.crackerTrackerScriptName().'
274 Referrer             : '.crackerTrackerReferer().'
275 -----------------------------------------------------
276 POST string          : '.$GLOBALS['ctracker_post_track'].'
277 Filtered POST string : '.$GLOBALS['ctracker_check_post'].'
278 -----------------------------------------------------
279 ';
280
281         // Send it out
282         crackerTrackerSendMail($mail);
283
284         // And die here
285         crackerTrackerDie();
286 }
287
288 // Sleeps for a random time and aborts the script
289 function crackerTrackerDie () {
290         // Close database link
291         crackerTrackerCloseDatabaseLink();
292
293         // Do only sleep if debug/developer mode is not enabled
294         if (!isCrackerTrackerDebug()) {
295                 // Sleep a little to waste the attacker's time
296                 sleep(mt_rand(10,30));
297         } // END - if
298
299         // Bye, bye...
300         if (isCrackerTrackerDebug()) {
301                 // With debug backtrace in debug/developer mode
302                 print '<pre>';
303                 debug_print_backtrace();
304                 die('</pre>');
305         } else {
306                 // Simple die() call
307                 die();
308         }
309 }
310
311 // Logs the attack attempt
312 function crackerTrackerLogAttack () {
313         // Aquire database link
314         aquireCrackerTrackerDatabaseLink();
315
316         // By default no proxy is used
317         $proxyUsed = 'N';
318
319         // Did the attacker use a proxy?
320         if (isCrackerTrackerProxyUsed()) {
321                 // Set it
322                 $proxyUsed = 'Y';
323         } // END - if
324
325         // Prepare array for database insert
326         $rowData = array(
327                 'remote_addr'   => determineCrackerTrackerRealRemoteAddress(),
328                 'proxy_addr'    => getenv('REMOTE_ADDR'),
329                 'user_agent'    => crackerTrackerUserAgent(),
330                 'get_data'      => crackerTrackerQueryString(),
331                 'post_data'     => $GLOBALS['ctracker_post_track'],
332                 'check_worm'    => $GLOBALS['ctracker_checkworm'],
333                 'check_post'    => $GLOBALS['ctracker_check_post'],
334                 'server_name'   => crackerTrackerServerName(),
335                 'script_name'   => crackerTrackerScriptName(),
336                 'referer'       => crackerTrackerReferer(),
337                 'proxy_used'    => $proxyUsed,
338                 'first_attempt' => 'NOW()'
339         );
340
341         // Insert the array in database
342         crackerTrackerInsertArray('ctracker_data', $rowData);
343 }
344
345 // Alerts the current user about malicious/suspicious traffic
346 function crackerTrackerAlertCurrentUser () {
347         // Is there some data?
348         if (isset($GLOBALS['ctracker_last_suspicious_entry'])) {
349                 // Does the user have a ticket?
350                 if (ifCrackerTrackerIpHasTicket()) {
351                         // Should we continue?
352                         if (isset($_POST['ctracker_continue'])) {
353                                 // Set cookie
354                                 sendCrackerTrackerCookie();
355
356                                 // And redirect to same URL
357                                 crackerTrackerRedirectSameUrl();
358                         } elseif (ifCrackerTrackerCookieIsSet()) {
359                                 // Return here to normal program
360                                 return;
361                         } else {
362                                 // Load "Thank you" template
363                                 crackerTrackerLoadTemplate('add_ticket_thanks');
364                         }
365                 } elseif ((isset($_POST['ctracker_add_ticket'])) && (!empty($_POST['name'])) && (!empty($_POST['email']))) {
366                         // Add the ticket
367                         addCrackerTrackerTicket($_POST);
368
369                         // Send the email out
370                         sendCrackerTrackerTicketMails();
371                 } else {
372                         // Display the form for new ticket
373                         crackerTrackerLoadTemplate('add_ticket');
374                 }
375         } // END - if
376
377         // And stop here
378         die();
379 }
380
381 // [EOF]
382 ?>