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