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