]> git.mxchange.org Git - ctracker.git/blob - libs/lib_detector.php
Updated to allow database-less operation
[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 blok
44         $GLOBALS['ctracker_wormprotector'] = array(
45                 'chr(', 'chr=', 'chr%20', '%20chr', 'wget%20', '%20wget', 'wget(',
46                 'cmd=', '%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','/etc/passwd','/etc/shadow', '/etc/groups', '/etc/gshadow',
57                 'HTTP_USER_AGENT', 'HTTP_HOST', 'wget%20', 'uname\x20-a', 'bin/id', '/bin/', '/chgrp',
58                 '/chown', '/usr/bin', 'g\+\+', 'bin/python', 'bin/tclsh', 'bin/nasm', 'perl%20', 'traceroute%20',
59                 'ping%20', '.pl', 'bin/xterm', 'lsof%20', '.conf', 'motd%20', 'HTTP/1.', '.inc.php', '.lib.php',
60                 'config.php', 'file\://', 'window.open', '<SCRIPT>', '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=', 'action=http',
68                 'page=http', 'module=http', 'op=http', 'id=http', 'id%3Dhttp', 'action%3Dhttp', 'page%3Dhttp',
69                 'module%3Dhttp', 'op%3Dhttp', 'starhack', '../../', 'directory=http', 'dir=http', 'busca', 'uol.com',
70                 '=http://', '=https://','=ftp://','_SESSION'
71         );
72
73         // Block these words found in POST requests
74         $GLOBALS['ctracker_post_blacklist'] = array(
75                 // These two lines are for detecting hidden link spam in wikis, forums, guestbooks, etc.
76                 'div style=', 'overflow:auto', 'height:1px', 'width:1px', 'display:hidden',
77                 'overflow: auto', 'height: 1px', 'display: hidden',
78                 // "Common" login name from VHCS exploiters ;-)
79                 'starhack', 'DeLiMehmet', 'hisset', 'Hisset', 'delimert', 'MecTruy',
80                 'busca'
81         );
82
83         // Load email header
84         $GLOBALS['ctracker_header'] = crackerTrackerLoadEmailTemplate('header');
85 }
86
87 // Checks for worms
88 function isCrackerTrackerWormDetected () {
89         // Check against the whole list
90         $GLOBALS['ctracker_checkworm'] = str_replace($GLOBALS['ctracker_wormprotector'], '*', crackerTrackerQueryString());
91
92         // If it differs to original and the *whole* request string is not in whitelist
93         // then blog the attempt
94         return ($GLOBALS['ctracker_checkworm'] != crackerTrackerQueryString() && (!in_array(crackerTrackerQueryString(), $GLOBALS['ctracker_whitelist'])));
95 }
96
97 // Checks POST data
98 function isCrackerTrackerPostAttackDetected () {
99         // Implode recursive the whole $_POST array
100         $GLOBALS['ctracker_post_track'] = implode_r('', $_POST);
101
102         // Check for suspicious POST data
103         $GLOBALS['ctracker_check_post'] = str_replace($GLOBALS['ctracker_post_blacklist'], '*', $GLOBALS['ctracker_post_track']);
104
105         // Is it detected?
106         return ((isCrackerTrackerWormDetected()) || ($GLOBALS['ctracker_check_post'] != $GLOBALS['ctracker_post_track']));
107 }
108
109 // Prepares a mail and send it out
110 function sendCrackerTrackerMail () {
111         // Mail content
112         $mail = "Attack detected:
113 -----------------------------------------------------
114 Remote-IP       : ".determineCrackerTrackerRealRemoteAddress()."
115 User-Agent      : ".crackerTrackerUserAgent()."
116 Request-string  : ".crackerTrackerQueryString()."
117 Filtered string : ".$GLOBALS['ctracker_checkworm']."
118 Server          : ".crackerTrackerServerName()."
119 Script          : ".crackerTrackerScriptName()."
120 Referrer        : ".crackerTrackerReferer()."
121 -----------------------------------------------------
122 ";
123
124         // Log the attack
125         crackerTrackerLogAttack();
126
127         // Send it out
128         crackerTrackerSendMail($mail);
129
130         // And die here
131         crackerTrackerDie();
132 }
133
134 // Sends the ticket emails out
135 function sendCrackerTrackerTicketMails () {
136         // Load user template
137         $mail = crackerTrackerLoadEmailTemplate('user_add_ticket', $GLOBALS['ctracker_last_ticket']);
138
139         // Send email to the user
140         crackerTrackerSendMail($mail, $GLOBALS['ctracker_last_ticket']['ctracker_ticket_email'], getCrackerTrackerLocalized('user_add_ticket_subject'));
141
142         // Load webmaster template
143         $mail = crackerTrackerLoadEmailTemplate('webmaster_add_ticket', $GLOBALS['ctracker_last_ticket'], getCrackerTrackerConfig('ctracker_language'));
144
145         // Send email to the user
146         crackerTrackerSendMail($mail, null, getCrackerTrackerLocalized('webmaster_add_ticket_subject'));
147 }
148
149 // Sends a mail out
150 function crackerTrackerSendMail ($mail, $recipient = null, $subject = null) {
151         // Construct dummy array
152         $rowData = array(
153                 'remote_addr' => determineCrackerTrackerRealRemoteAddress(),
154                 'check_worm'  => $GLOBALS['ctracker_checkworm'],
155                 'server_name' => crackerTrackerServerName()
156         );
157
158         // Only send email if not yet found
159         if (!isCrackerTrackerEntryFound($rowData)) {
160                 // Send the email out only in non-debug mode
161                 if (isCrackerTrackerDebug()) {
162                         // Output message
163                         print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
164
165                         // All fine
166                         return true;
167                 } elseif (!is_null($recipient)) {
168                         // Recipient specified
169                         return mail($recipient, $subject, $mail, $GLOBALS['ctracker_header']);
170                 } elseif (isset($GLOBALS['ctracker_email'])) {
171                         // Send it
172                         return mail($GLOBALS['ctracker_email'], 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
173                 } else {
174                         // Send it the deprecated way with constant
175                         return mail(constant('__CTRACKER_EMAIL'), 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
176                 }
177         } elseif (isCrackerTrackerDebug()) {
178                 // Output message
179                 print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
180
181                 // All fine
182                 return true;
183         }
184 }
185
186 // Sends a detected POST attack mail
187 function sendCrackerTrackerPostMail () {
188         // Mail text
189         $mail = "POST-Attack detected:
190 -----------------------------------------------------
191 Remote-IP            : ".determineCrackerTrackerRealRemoteAddress()."
192 User-Agent           : ".crackerTrackerUserAgent()."
193 Request-string       : ".crackerTrackerQueryString()."
194 Filtered string      : ".$GLOBALS['ctracker_checkworm']."
195 Server               : ".crackerTrackerServerName()."
196 Script               : ".crackerTrackerScriptName()."
197 Referrer             : ".crackerTrackerReferer()."
198 -----------------------------------------------------
199 POST string          : ".$GLOBALS['ctracker_post_track']."
200 Filtered POST string : ".$GLOBALS['ctracker_check_post']."
201 -----------------------------------------------------
202 ";
203
204         // Log the attack
205         crackerTrackerLogAttack();
206
207         // Send it out
208         crackerTrackerSendMail($mail);
209
210         // And die here
211         crackerTrackerDie();
212 }
213
214 // Sleeps for a random time and aborts the script
215 function crackerTrackerDie () {
216         // Close database link
217         crackerTrackerCloseDatabaseLink();
218
219         // Sleep a little to waste the attacker's time
220         if (!isCrackerTrackerDebug()) sleep(mt_rand(10,30));
221
222         // Bye, bye...
223         if (isCrackerTrackerDebug()) {
224                 // With debug backtrace
225                 print '<pre>';
226                 debug_print_backtrace();
227                 die('</pre>');
228         } else {
229                 // Simple die()
230                 die();
231         }
232 }
233
234 // Logs the attack attempt
235 function crackerTrackerLogAttack () {
236         // Aquire database link
237         aquireCrackerTrackerDatabaseLink();
238
239         // By default no proxy is used
240         $proxyUsed = 'N';
241
242         // Did the attacker use a proxy?
243         if (isCrackerTrackerProxyUsed()) {
244                 // Set it
245                 $proxyUsed = 'Y';
246         } // END - if
247
248         // Prepare array for database insert
249         $rowData = array(
250                 'remote_addr'   => determineCrackerTrackerRealRemoteAddress(),
251                 'user_agent'    => crackerTrackerUserAgent(),
252                 'get_data'      => crackerTrackerQueryString(),
253                 'post_data'     => $GLOBALS['ctracker_post_track'],
254                 'check_worm'    => $GLOBALS['ctracker_checkworm'],
255                 'check_post'    => $GLOBALS['ctracker_check_post'],
256                 'server_name'   => crackerTrackerServerName(),
257                 'script_name'   => crackerTrackerScriptName(),
258                 'referer'       => crackerTrackerReferer(),
259                 'proxy_used'    => $proxyUsed,
260                 'first_attempt' => 'NOW()'
261         );
262
263         // Insert the array in database
264         crackerTrackerInsertArray('ctracker_data', $rowData);
265 }
266
267 // Alerts the current user about malicious/suspicious traffic
268 function crackerTrackerAlertCurrentUser () {
269         // Is there some data?
270         if (isset($GLOBALS['ctracker_last_suspicious_entry'])) {
271                 // Does the user have a ticket?
272                 if (ifCrackerTrackerIpHasTicket()) {
273                         // Should we continue?
274                         if (isset($_POST['ctracker_continue'])) {
275                                 // Set cookie
276                                 sendCrackerTrackerCookie();
277
278                                 // And redirect to same URL
279                                 crackerTrackerRedirectSameUrl();
280                         } elseif (ifCrackerTrackerCookieIsSet()) {
281                                 // Return here to normal program
282                                 return;
283                         } else {
284                                 // Load "Thank you" template
285                                 crackerTrackerLoadTemplate('add_ticket_thanks');
286                         }
287                 } elseif ((isset($_POST['ctracker_add_ticket'])) && (!empty($_POST['name'])) && (!empty($_POST['email']))) {
288                         // Add the ticket
289                         addCrackerTrackerTicket($_POST);
290
291                         // Send the email out
292                         sendCrackerTrackerTicketMails();
293                 } else {
294                         // Display the form for new ticket
295                         crackerTrackerLoadTemplate('add_ticket');
296                 }
297         } // END - if
298
299         // And stop here
300         die();
301 }
302
303 // [EOF]
304 ?>