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