Checking against GET parameters is for the user-agent string not possible as
[ctracker.git] / libs / lib_detector.php
1 <?php
2 /**
3  * Detector library
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             3.0.0
7  * @copyright   Copyright (c) 2009 - 2017 Cracker Tracker Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.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         // Base path
37         $GLOBALS['ctracker_base_path'] = dirname(dirname(__FILE__));
38
39         // Whitelist some absolute query strings (see below)
40         $GLOBALS['ctracker_whitelist'] = [
41                 'cmd=new',    // LinPHA
42                 'cmd=edit',   // LinPHA
43                 'cmd=lostpw', // LinPHA
44                 '/css/status_config.php', // MantisBT
45                 '/css/common_config.php', // MantisBT
46                 '/javascript_config.php', // MantisBT
47         ];
48
49         // Attacks we should detect and block
50         $GLOBALS['ctracker_get_blacklist'] = [
51                 // SQL injections
52                 'union ', ' union', 'insert ',
53                 'select ', ' like', 'like ', 'drop ', 'update ',
54                 'union(', 'union=',
55
56                 // $GLOBAL/$_SERVER array elements
57                 'HTTP_USER_AGENT', 'HTTP_HOST', 'HTTP_PHP', '_SESSION', 'CFG_ROOT',
58                 'DOCUMENT_ROOT', '_SERVER',
59
60                 // Sensitive files
61                 '/environ', 'etc/shadow', 'etc/gshadow', 'etc/passwd', 'etc/group',
62                 'etc/./shadow', 'etc/./gshadow', 'etc/./passwd', 'etc/./group',
63                 '.htaccess', '.htpasswd', '.htgroup', '.history', 'bash_history',
64                 'bashrc',
65
66                 // Other Linux/FreeBSD/??? programs (sometimes with space)
67                 'traceroute ', 'ping ', 'bin/xterm', 'bin/./xterm', 'lsof ',
68                 'telnet ', 'wget ', 'bin/perl', 'bin/id', 'uname\x20', 'uname ',
69                 'killall', 'diff ', 'kill ', 'locate ', 'grep ', 'vi ', 'mv ',
70                 'rmdir ', 'mcd ', 'mrd ', 'rm ', ' mcd', ' mrd', ' rm',
71                 'passwd ', ' passwd', 'mdir ', ' mdir', 'cp ', ' cp',
72                 'esystem ', 'chr ', ' chr', 'wget ', ' wget', ' cmd',
73                 'cmd ', ' rush', 'rush ', ' echr', 'echr ', ' getenv',
74                 'getenv', 'reboot ', 'halt ', 'powerdown ',
75
76                 // Other Linux programs (+ brace)
77                 'locate(', 'grep(', 'kill(', 'mcd(', 'mrd(', 'rm(', 'mv(', 'rmdir(',
78                 'chmod(', 'chmod(', 'chown(', 'chgrp(', 'passwd(', 'vi(', 'cp(',
79                 'mdir(', 'system(', 'chr(', 'wget(', 'rush(', 'echr(',
80
81                 // Other Linux programs (+ equal)
82                 'mcd=', 'mrd=', 'chmod=', 'chr=', 'rush=', 'echr=',
83
84                 // Paths
85                 '/etc/', '/bin/', '/sbin/', '/self/', '/proc/', '../../','..//', '././',
86                 '/home/ftp', '/home/./ftp', '/home/./www', '/home/www', '/www/virtual/',
87                 '/www/./virtual/',
88
89                 // Uni* commands:
90                 '/chgrp', '/chown', '/chmod', 'chown ', 'chmod ', 'chgrp ',
91
92                 // Compiler/interpreter
93                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
94                 'bin/tclsh', 'bin/nasm', '/perl', 'cmd.exe',
95                 'nc.exe', 'ftp.exe',
96
97                 // php.ini settings
98                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
99                 'open_basedir', 'suhosin', 'cgi.force_redirect', 'cgi.redirect_status_env',
100
101                 // PHP commands/scripts
102                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
103                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
104
105                 // Typical PHP script remote-inclusions and typical include file names
106                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
107                 'php_', 'class_', '_class.php', 'db_mysql.inc',
108
109                 // PHP arrays
110                 '_phplib', '__callbackparam',
111
112                 // Generic remote inclusion
113                 '=http://', '=https://', '=php://',
114                 'path=', 'sql=',
115                 '=%7BQUOT%7D', '=%5C', '=%22http','=%22ftp','=%22file','=%27http','=%27ftp',
116                 '=%27file',
117
118                 // Wrappers
119                 'data://', 'tcp://', 'udp://', 'raw://', 'javascript://', 'file://', 'ftp://',
120
121                 // Blocked "users"
122                 'nigga(', ' nigga', 'nigga ', 'starhack', 'busca',
123
124                 // Hidden HTML stuff
125                 ' style=', 'style =',
126                 'overflow:auto', 'overflow: auto',
127                 'overflow :auto', 'overflow : auto',
128                 'display:hidden', 'display: hidden',
129                 'display :hidden', 'display : hidden',
130                 'height:0px', 'height: 0px','height:1px', 'height: 1px',
131                 'width:0px', 'width: 0px','width:1px', 'width: 1px',
132
133                 // Uncommon user websites
134                 '~root', '~ftp', '~nobody',
135
136                 // Windows XP (?) hacks
137                 'xp_enumdsn', 'xp_availablemedia', 'xp_filelist', 'xp_cmdshell',
138
139                 // Attempts to insert links into a badly secured URL
140                 '%3E%3C',
141
142                 // Request header being inserted
143                 'content-type',
144
145                 // /proc/ and other forbidden paths
146                 'proc/self/environ',
147
148                 // MySQL internal functions
149                 'name_const',
150
151                 // @TODO Misc/unsorted
152                 'cgi-', '.eml', '$_request', '$_get', '$request', '$get', '.system',
153                 '&aim', 'new_password', '&icq', '.conf', 'motd ', 'HTTP/1.',
154                 'window.open', 'img src', 'img src', '.jsp', 'servlet', 'org.apache',
155                 'wwwacl', 'server-info', 'server-status', '/servlet/con', 'http_',
156                 'secure_site, ok', 'chunked', '<script', 'mod_gzip_status', '.system',
157                 'uol.com', ',0x', '(0x', 'INSERT_RANDOM_NUMBER_HERE',
158         ];
159
160         // BLock these words found in User-Agent
161         $GLOBALS['ctracker_ua_blacklist'] = [
162                 // Compiler/interpreter
163                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
164                 'bin/tclsh', 'bin/nasm', '/perl', 'cmd.exe',
165                 'nc.exe', 'ftp.exe', 'wget ', 'system(', 'curl ',
166
167                 // php.ini settings
168                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
169
170                 // PHP commands/scripts
171                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
172                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
173
174                 // Typical PHP script remote-inclusions and typical include file names
175                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
176                 'php_', 'class_', '_class.php', 'db_mysql.inc',
177
178                 // PHP arrays
179                 '_phplib', '__callbackparam',
180
181                 // Request header being inserted
182                 'content-type',
183
184                 // /proc/ and other forbidden paths
185                 'proc/self/environ',
186         ];
187
188         // BLock these words found in User-Agent
189         $GLOBALS['ctracker_ua_blacklist'] = array(
190                 // Compiler/interpreter
191                 'bin/g++ ', 'bin/c++ ', 'cc ', 'bin/python', 'bin/python', 'bin/tclsh',
192                 'bin/tclsh', 'bin/nasm', '/perl', 'cmd.exe',
193                 'nc.exe', 'ftp.exe', 'wget ', 'system(', 'curl ',
194
195                 // php.ini settings
196                 'allow_url_fopen', 'allow_url_include', 'auto_prepend_file', 'disable_functions', 'safe_mode',
197
198                 // PHP commands/scripts
199                 'fopen', 'fwrite', 'phpinfo()', '\<?', '?\>', 'base64_decode', 'file_put_contents',
200                 'set_magic_quotes_runtime', 'set_magic_quotes_runtime', 'display_errors', 'passthru',
201
202                 // Typical PHP script remote-inclusions and typical include file names
203                 '.inc.php', '.lib.php', '.class.php', 'config.php', '.inc', '_php',
204                 'php_', 'class_', '_class.php', 'db_mysql.inc',
205
206                 // PHP arrays
207                 '_PHPLIB',
208
209                 // Request header being inserted
210                 'content-type',
211
212                 // /proc/ and other forbidden paths
213                 'proc/self/environ',
214         );
215
216         // Block these words found in POST requests
217         $GLOBALS['ctracker_post_blacklist'] = [
218                 // This line is for detecting hidden link spam in wikis, forums, guestbooks, etc.
219                 ' style=', 'overflow:auto', 'height:1px', 'width:1px', 'display:hidden', 'style.display',
220
221                 // "Common" login names from VHCS exploiters ;-)
222                 'starhack', 'DeLiMehmet', 'hisset', 'Hisset', 'delimert', 'MecTruy'
223         ];
224
225         // Also block these requests (mostly you don't want CONNECT to some SMTP sites)
226         $GLOBALS['ctracker_blocked_methods'] = [
227                 'CONNECT' => TRUE,
228         ];
229
230         // Init more elements
231         $GLOBALS['ctracker_post_track']   = '';
232         $GLOBALS['ctracker_checked_get']  = '';
233         $GLOBALS['ctracker_checked_post'] = '';
234         $GLOBALS['ctracker_checked_ua']   = '';
235 }
236
237 // Checks for worms
238 function isCrackerTrackerWormDetected () {
239         // Check against the whole list
240         $GLOBALS['ctracker_checked_get'] = urldecode(str_ireplace($GLOBALS['ctracker_get_blacklist'], '*', crackerTrackerQueryString(TRUE)));
241         $GLOBALS['ctracker_checked_ua']  = urldecode(str_ireplace($GLOBALS['ctracker_ua_blacklist'], '*', crackerTrackerUserAgent(TRUE)));
242
243         /*
244          * If it differs to original and the *whole* request string is not in
245          * whitelist then blog the attempt.
246          */
247         $isWorm = (
248                 (
249                         $GLOBALS['ctracker_checked_get'] != crackerTrackerQueryString(TRUE) && (!in_array(crackerTrackerQueryString(TRUE), $GLOBALS['ctracker_whitelist']))
250                 ) || (
251                         $GLOBALS['ctracker_checked_ua'] != crackerTrackerUserAgent(TRUE)
252                 ) || (
253                         isset($GLOBALS['ctracker_blocked_methods'][crackerTrackerRequestMethod()])
254                 )
255         );
256         //* DEBUG-DIE: */ die('isWorm='.intval($isWorm).PHP_EOL.'get='.PHP_EOL.'"'.$GLOBALS['ctracker_checked_get'].'"'.PHP_EOL.'"'.crackerTrackerQueryString().'"'.PHP_EOL.'ua='.PHP_EOL.'"'.$GLOBALS['ctracker_checked_ua'].'"'.PHP_EOL.'"'.crackerTrackerUserAgent().'"'.PHP_EOL);
257
258         // Return it
259         return $isWorm;
260 }
261
262 // Checks POST data
263 function isCrackerTrackerPostAttackDetected () {
264         // Implode recursive the whole $_POST array
265         $GLOBALS['ctracker_post_track'] = urldecode(implode_r('&', $_POST));
266
267         // Check for suspicious POST data
268         $GLOBALS['ctracker_checked_post'] = urldecode(str_ireplace($GLOBALS['ctracker_post_blacklist'], '*', crackerTrackerSanitize($GLOBALS['ctracker_post_track'])));
269
270         // Is it detected?
271         return ((isCrackerTrackerWormDetected()) || ($GLOBALS['ctracker_checked_post'] != crackerTrackerSanitize($GLOBALS['ctracker_post_track'])));
272 }
273
274 // Prepares a mail and send it out
275 function sendCrackerTrackerMail () {
276         // Log the attack
277         crackerTrackerLogAttack();
278
279         // Mail content
280         $mail = 'Attack detected:
281 -----------------------------------------------------
282 Remote-IP       : ' . determineCrackerTrackerRealRemoteAddress() . '
283 User-Agent      : ' . crackerTrackerUserAgent() . '
284 Request-string  : ' . crackerTrackerQueryString() . '
285 Filtered string : ' . $GLOBALS['ctracker_checked_get'] . '
286 Server          : ' . crackerTrackerServerName() . '
287 Script          : ' . crackerTrackerScriptName() . '
288 Method          : ' . crackerTrackerRequestMethod() . '
289 Referrer        : ' . crackerTrackerReferer() . '
290 -----------------------------------------------------
291 ';
292
293         // Send it out
294         crackerTrackerSendMail($mail);
295
296         // And die here
297         crackerTrackerDie();
298 }
299
300 // Sends the ticket emails out
301 function sendCrackerTrackerTicketMails () {
302         // Load user template
303         $mail = crackerTrackerLoadEmailTemplate('user_add_ticket', $GLOBALS['ctracker_last_ticket']);
304
305         // Send email to the user
306         crackerTrackerSendMail($mail, $GLOBALS['ctracker_last_ticket']['ctracker_ticket_email'], getCrackerTrackerLocalized('user_add_ticket_subject'));
307
308         // Load webmaster template
309         $mail = crackerTrackerLoadEmailTemplate('webmaster_add_ticket', $GLOBALS['ctracker_last_ticket'], getCrackerTrackerConfig('ctracker_language'));
310
311         // Send email to the user
312         crackerTrackerSendMail($mail, NULL, getCrackerTrackerLocalized('webmaster_add_ticket_subject'));
313 }
314
315 // Sends a mail out
316 function crackerTrackerSendMail ($mail, $recipient = NULL, $subject = NULL) {
317         // Construct dummy array
318         $rowData = [
319                 'remote_addr'    => determineCrackerTrackerRealRemoteAddress(),
320                 'proxy_addr'     => getenv('REMOTE_ADDR'),
321                 'check_get'      => $GLOBALS['ctracker_checked_get'],
322                 'server_name'    => crackerTrackerServerName(),
323                 'request_method' => crackerTrackerRequestMethod(),
324         ];
325
326         // Only send email if not yet found
327         if (!isCrackerTrackerEntryFound($rowData)) {
328                 // Send the email out only in non-debug mode
329                 if (isCrackerTrackerDebug()) {
330                         // Output message
331                         print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
332
333                         // All fine
334                         return TRUE;
335                 } elseif (!is_null($recipient)) {
336                         // Recipient specified
337                         return mail($recipient, $subject, $mail, $GLOBALS['ctracker_header']);
338                 } elseif (isset($GLOBALS['ctracker_email'])) {
339                         // Send it
340                         return mail($GLOBALS['ctracker_email'], 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
341                 } else {
342                         // Send it the deprecated way with constant
343                         return mail(constant('__CTRACKER_EMAIL'), 'CTracker: Attack detected!', $mail, $GLOBALS['ctracker_header']);
344                 }
345         } elseif (isCrackerTrackerDebug()) {
346                 // Output message
347                 print 'Recipient=' . $recipient . '<br />Subject=' . $subject . '<br />Text=<pre>' . $mail . '</pre>';
348
349                 // All fine
350                 return TRUE;
351         }
352 }
353
354 // Sends a detected POST attack mail
355 function sendCrackerTrackerPostMail () {
356         // Log the attack
357         crackerTrackerLogAttack();
358
359         // Mail text
360         $mail = 'POST-Attack detected:
361 -----------------------------------------------------
362 Remote-IP            : ' . determineCrackerTrackerRealRemoteAddress() . '
363 User-Agent           : ' . crackerTrackerUserAgent() . '
364 Request-string       : ' . crackerTrackerQueryString() . '
365 Filtered string      : ' . $GLOBALS['ctracker_checked_get'] . '
366 Server               : ' . crackerTrackerServerName() . '
367 Script               : ' . crackerTrackerScriptName() . '
368 Method               : ' . crackerTrackerRequestMethod() . '
369 Referrer             : ' . crackerTrackerReferer() . '
370 -----------------------------------------------------
371 POST string          : ' . $GLOBALS['ctracker_post_track'] . '
372 Filtered POST string : ' . $GLOBALS['ctracker_checked_post'] . '
373 -----------------------------------------------------
374 ';
375
376         // Send it out
377         crackerTrackerSendMail($mail);
378
379         // And die here
380         crackerTrackerDie();
381 }
382
383 // Sleeps for a random time and aborts the script
384 function crackerTrackerDie () {
385         // Close database link
386         crackerTrackerCloseDatabaseLink();
387
388         // Do only sleep if debug/developer mode is not enabled
389         if (!isCrackerTrackerDebug()) {
390                 // Sleep a little to waste the attacker's time
391                 sleep(mt_rand(10,30));
392         } // END - if
393
394         // Bye, bye...
395         if (isCrackerTrackerDebug()) {
396                 // With debug backtrace in debug/developer mode
397                 print '<pre>';
398                 debug_print_backtrace();
399                 die('</pre>');
400         } else {
401                 // Simple die() call
402                 die();
403         }
404 }
405
406 // Logs the attack attempt
407 function crackerTrackerLogAttack () {
408         // Aquire database link
409         aquireCrackerTrackerDatabaseLink();
410
411         // By default no proxy is used
412         $proxyUsed = 'N';
413
414         // Did the attacker use a proxy?
415         if (isCrackerTrackerProxyUsed()) {
416                 // Set it
417                 $proxyUsed = 'Y';
418         } // END - if
419
420         // Prepare array for database insert
421         $rowData = [
422                 'remote_addr'    => determineCrackerTrackerRealRemoteAddress(),
423                 'proxy_addr'     => getenv('REMOTE_ADDR'),
424                 'user_agent'     => crackerTrackerUserAgent(),
425                 'get_data'       => crackerTrackerQueryString(),
426                 'post_data'      => $GLOBALS['ctracker_post_track'],
427                 'check_ua'       => $GLOBALS['ctracker_checked_ua'],
428                 'check_get'      => $GLOBALS['ctracker_checked_get'],
429                 'check_post'     => $GLOBALS['ctracker_checked_post'],
430                 'server_name'    => crackerTrackerServerName(),
431                 'script_name'    => crackerTrackerScriptName(),
432                 'referer'        => crackerTrackerReferer(),
433                 'request_method' => crackerTrackerRequestMethod(),
434                 'proxy_used'     => $proxyUsed,
435                 'first_attempt'  => 'NOW()'
436         ];
437
438         // Insert the array in database
439         crackerTrackerInsertArray('ctracker_data', $rowData);
440 }
441
442 // Alerts the current user about malicious/suspicious traffic
443 function crackerTrackerAlertCurrentUser () {
444         // Is there some data?
445         if (isset($GLOBALS['ctracker_last_suspicious_entry'])) {
446                 // Does the user have a ticket?
447                 if (ifCrackerTrackerIpHasTicket()) {
448                         // Load "Thank you" template
449                         crackerTrackerLoadTemplate('add_ticket_thanks');
450                 } elseif ((isset($_POST['ctracker_add_ticket'])) && (!empty($_POST['name'])) && (!empty($_POST['email']))) {
451                         // Add the ticket
452                         addCrackerTrackerTicket($_POST);
453
454                         // Send the email out
455                         sendCrackerTrackerTicketMails();
456                 } else {
457                         // Display the form for new ticket
458                         crackerTrackerLoadTemplate('add_ticket');
459                 }
460         } // END - if
461
462         // And stop here
463         die();
464 }