-
Notifications
You must be signed in to change notification settings - Fork 15
/
scanner.php
538 lines (470 loc) · 18.4 KB
/
scanner.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<?php namespace Ollyxar\AntiMalware;
/**
* Warning!
* This file generated automatically with [single_file_generator.php]
*/
/**
* Class Console
* See nice article about bash colours: https://misc.flogisoft.com/bash/tip_colors_and_formatting
*
* @package Ollyxar\AntiMalware
*/
class Console
{
/**
* Window width
*
* @var int
*/
private static $width;
/**
* Available colours (256bit)
*
* @var array
*/
public static $colors = [
'back' => [
'blue' => "\e[48;5;4m",
'red' => "\e[48;5;124m",
'gray' => "\e[48;5;242m",
'yellow' => "\e[48;5;227m",
'orange' => "\e[48;5;166m"
],
'front' => [
'white' => "\e[38;5;231m",
'black' => "\e[38;5;232m",
'blue' => "\e[38;5;14m"
]
];
/**
* Drawing text in one line
*
* @param $text
* @return void
*/
public static function line($text = '')
{
if (!static::$width) {
static::$width = @exec('tput cols') or 80;
}
$offset = 0;
if (preg_match_all("/\e\[(\d|\;)+m/", $text, $matches)) {
foreach ($matches[0] as $match) {
$offset += strlen($match);
}
}
$length = static::$width + $offset;
print str_pad($text, $length) . "\e[0m\n";
}
}
/**
* Class Mode
* Possible script execution mode
*
* @package Ollyxar\AntiMalware
*/
class Mode
{
const CRON = 0;
const CONSOLE = 1;
const WEB = 2;
}
/**
* Class Patterns
* Common detection patterns
*
* @package Ollyxar\AntiMalware
*/
class Patterns
{
/**
* Ensure that file is PHP
*/
const isPHP = '/<\?(php)?[\n|\r|\s|{$|_|@|\[]/';
/**
* Detect dangerous functions or tricky approaches
*
* @var array
*/
public static $suspicious = [
'non-printable' => '/(function|return|base64_decode).{,256}[^\x09-\x0d\x20-\x7E]{3}/',
'evaluation' => '/\b(eval|create_function|system|assert|passthru|proc_open|(pcntl_|shell_)?exec|call_user_func(_array)?)\b\s*(\/\*(.*)\*\/)?\s*\(/',
'networking' => '/\b(fputs|file_get_contents|fsockopen|curl_exec|curl_multi_exec)\b\s*\(/',
'double-variable' => '/\${?\$[0-9a-zA-z]+/',
'var-as-function' => '/\$_(GET|POST|COOKIE|REQUEST|SERVER)\s*\[[^\]]+\]\s*\(/',
'callback' => '/\b(eval|assert|passthru|exec|include|system|pcntl_exec|shell_exec|base64_decode|`|array_map|ob_start|call_user_func(_array)?)\s*\(\s*(base64_decode|php:\/\/input|str_rot13|gz(inflate|uncompress)|getenv|pack|\\\\?\$_(GET|REQUEST|POST|COOKIE|SERVER))/',
'callback-2' => '/\b(array_(diff|intersect)_u(key|assoc)|array_(udiff|filter|reduce|walk(_recursive)?)|assert_options|uasort|uksort|usort|preg_replace_callback|iterator_apply)\s*\(\s*.*[,]+(base64_decode|php:\/\/input|str_rot13|gz(inflate|uncompress)|getenv|pack|\\\\?\$_(GET|REQUEST|POST|COOKIE|SERVER))/',
'preg_replace-e' => '/\b(preg_replace)\s*\(\s*((("|\').*(\/e)("|\'))|base64_decode|php:\/\/input|str_rot13|gz(inflate|uncompress)|getenv|pack|\\\\?\$_(GET|REQUEST|POST|COOKIE|SERVER))/',
'obfuscation' => '/((\\\\x[0-9a-zA-z]{2,3}){3})|((chr\([\d]+\)\s?\.\s?){5})|((\$|"|\')[0-9a-zA-z]+(\'|")?+\s?\.\s?){4}|(\bexplode\b\s*\(\s*\bchr\b\()/',
'php-params' => '/ini_(get|set|restore)\s*\(\s*[\'"](safe_mode|open_basedir|disable_(function|classe)s|safe_mode_exec_dir|safe_mode_include_dir|register_globals|allow_url_include)/',
'include-images' => '/include\s*(\(|"|\')\s*[^\.]+\.(png|jpg|gif|bmp|ico)/',
'register-function' => '/register_[a-z]+_function\s*\(\s*[\'"]\s*(eval|assert|passthru|exec|include|system|shell_exec|`)/',
'extraction' => '/\bextract\b\s*\(\s*\$_(GET|REQUEST|POST|COOKIE|SERVER|)/'
];
}
/**
* Class Report
*
* @package Ollyxar\AntiMalware
*/
class Report
{
/**
* Readable filesize
*
* @param string $file
* @return string
*/
protected static function getFileSize($file)
{
$size = filesize($file);
$mod = 1024;
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
return round($size, 2) . ' ' . $units[$i];
}
/**
* Print header
*
* @return void
*/
public static function header()
{
switch (Settings::$mode) {
case Mode::CONSOLE:
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white']);
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white'] . " " . Scanner::title);
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white']);
break;
case Mode::WEB:
$style = '<style type="text/css" media="all">@import url(https://fonts.googleapis.com/css?family=Titillium+Web);*{box-sizing:border-box}body{font-size:14px;color:#fff;font-family:"Titillium Web",sans-serif;background:#2f2b33}.in-progress{display:block}.complete{display:none}#content{max-width:1080px;margin:0 auto;}.s{padding:10px 0}.y{background:#fdf59a;color:#000;padding:5px 10px}.o{background: #d58512;padding:5px 10px}.r{background: #bd4a47;padding:5px 10px}.l{display:inline-block;width:150px}.ri{display:inline-block}.code{background:#464242;color:#fdfdfd;padding:5px 10px;font-size: 12px}.h-g{color:#5bf5a1;font-size:14px;margin-top:10px}span.r{padding:0 3px}</style>';
print '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1">' . $style . '</head><body><div id="content">';
print '<h1>' . Scanner::title . '</h1>';
print '<h2 class="in-progress">Scanning...</h2>';
print '<h2 class="complete">Scan complete.</h2>';
flush();
break;
default:
print "\n [ " . Scanner::title . " ] \n\n";
print date("Y-m-d H:i:s") . " - scan start.\n\n";
}
}
/**
* Print footer
*
* @param $scannedTotal
* @param $suspiciousTotal
* @return void
*/
public static function footer($scannedTotal, $suspiciousTotal)
{
switch (Settings::$mode) {
case Mode::CONSOLE:
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white']);
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white'] . " " . date("Y-m-d H:i:s") . " - scan end.");
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white'] . " Total PHP files scanned: {$scannedTotal}");
if ($suspiciousTotal) {
$suspiciousTotal = Console::$colors['back']['red'] . ' ' . $suspiciousTotal . ' ' . Console::$colors['back']['blue'];
} else {
$suspiciousTotal = " " . $suspiciousTotal . " ";
}
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white'] . " Total suspicious files:{$suspiciousTotal}");
Console::line(Console::$colors['back']['blue'] . Console::$colors['front']['white']);
break;
case Mode::WEB:
if ($suspiciousTotal) {
$suspiciousTotal = '<span class="r">' . $suspiciousTotal . '</span>';
}
print '<h2>' . date("Y-m-d H:i:s") . " - scan end. Total PHP files scanned: {$scannedTotal}. Total suspicious files: {$suspiciousTotal}</h2>";
print '<div class="s"></div>';
print '</div></body><style type="text/css" media="all">.in-progress{display:none}.complete{display:block}</style></html>';
break;
default:
print date("Y-m-d H:i:s") . " - scan end. Total PHP files scanned: {$scannedTotal}. Total suspicious files: {$suspiciousTotal}\n";
}
}
/**
* Report suspicious file
*
* @param $file
* @param $suspicion
*/
public static function suspect($file, $suspicion)
{
$fileSize = static::getFileSize($file);
$owner = fileowner($file);
$selfOwner = getmyuid();
$permissions = substr(sprintf('%o', fileperms($file)), -4);
$hazardLevel = count($suspicion);
if (function_exists('posix_getpwuid')) {
$owner = posix_getpwuid($owner);
$owner = $owner['name'];
$selfOwner = posix_getpwuid($selfOwner);
$selfOwner = $selfOwner['name'];
}
switch (Settings::$mode) {
case Mode::CONSOLE:
$background = Console::$colors['back']['yellow'];
$foreground = Console::$colors['front']['black'];
if ($hazardLevel > 4) {
$background = Console::$colors['back']['orange'];
$foreground = Console::$colors['front']['white'];
}
if ($hazardLevel > 9) {
$background = Console::$colors['back']['red'];
$foreground = Console::$colors['front']['white'];
}
Console::line();
Console::line($background . $foreground . " File: " . $file);
Console::line($background . $foreground . " Size: " . $fileSize);
if ($owner !== $selfOwner) {
$owner = "[Warning] " . $owner;
}
Console::line($background . $foreground . " Owner: " . $owner);
if ((int)$permissions == 777) {
$permissions = "[Warning] " . $permissions;
}
Console::line($background . $foreground . " Permissions: " . $permissions);
Console::line($background . $foreground . " Hazard level: " . $hazardLevel);
Console::line($background . $foreground . "");
foreach ($suspicion as $value) {
Console::line(Console::$colors['back']['gray'] . Console::$colors['front']['blue'] . ' [' . $value['group'] . '] at line ' . $value['line']);
$textLeft = substr($value['buffer'], 0, strpos($value['buffer'], $value['danger']));
$textRight = substr($value['buffer'], strpos($value['buffer'], $value['danger']) + strlen($value['danger']));
$textLeft = substr($textLeft, -10);
$textRight = substr($textRight, 0, 10);
$text = Console::$colors['back']['gray'] . Console::$colors['front']['white'] . " " . $textLeft . Console::$colors['back']['red'] . $value['danger'] . Console::$colors['back']['gray'] . $textRight;
$text = trim(str_replace(["\n", "\r", "\t"], "", $text));
Console::line($text);
Console::line(Console::$colors['back']['gray'] . Console::$colors['front']['white']);
}
Console::line();
break;
case Mode::WEB:
if ($hazardLevel > 9) {
print '<div class="r">';
} elseif ($hazardLevel > 4) {
print '<div class="o">';
} else {
print '<div class="y">';
}
print '<div class="l">File:</div><div class="ri">' . $file . '</div><div></div>';
print '<div class="l">Size:</div><div class="ri">' . $fileSize . '</div><div></div>';
if ($owner !== $selfOwner) {
$owner = "[Warning] " . $owner;
}
print '<div class="l">Owner:</div><div class="ri">' . $owner . '</div><div></div>';
if ((int)$permissions == 777) {
$permissions = "[Warning] " . $permissions;
}
print '<div class="l">Permissions:</div><div class="ri">' . $permissions . '</div><div></div>';
print '<div class="l">Hazard level:</div><div class="ri">' . $hazardLevel . '</div><div></div>';
print '<div class="code">';
foreach ($suspicion as $value) {
print '<div class="h-g">' . ' [' . $value['group'] . '] at line ' . $value['line'] . '</div>';
$textLeft = substr($value['buffer'], 0, strpos($value['buffer'], $value['danger']));
$textRight = substr($value['buffer'], strpos($value['buffer'], $value['danger']) + strlen($value['danger']));
$textLeft = substr($textLeft, -10);
$textRight = substr($textRight, 0, 10);
$text = htmlspecialchars($textLeft) . '<span class="r">' . htmlspecialchars($value['danger']) . '</span>' . htmlspecialchars($textRight);
$text = trim(str_replace(["\n", "\r", "\t"], "", $text));
print $text;
}
print '</div></div><div class="s"></div>';
flush();
break;
default:
print str_pad("", Settings::$width, "=") . "\n";
print "File: " . $file . "\n";
print "Size: " . $fileSize . "\n";
print "Owner: ";
if ($owner !== $selfOwner) {
print "[Warning] ";
}
print $owner . "\n";
print "Permissions: ";
if ((int)$permissions == 777) {
print "[Warning] ";
}
print $permissions . "\n";
print "Hazard level: " . $hazardLevel . "\n";
foreach ($suspicion as $value) {
print str_pad("", Settings::$width, "-") . "\n";
print '[' . $value['group'] . '] at line ' . $value['line'] . "\n";
print 'danger: ' . $value['danger'] . "\n";
}
print str_pad("", Settings::$width, "=") . "\n";
}
}
}
/**
* Class Scanner
*
* @package Ollyxar\AntiMalware
*/
class Scanner
{
/**
* Self title
*/
const title = 'PHP malware scanner';
/**
* Total files scanned
*
* @var int
*/
private $scannedTotal = 0;
/**
* Total suspicions
*
* @var int
*/
private $suspiciousTotal = 0;
/**
* Recursive directory scan
*
* @param string $dir
* @param callable $callback
* @return void
*/
protected function getFiles($dir, $callback)
{
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
if (is_dir($dir . "/" . $file)) {
$this->getFiles($dir . "/" . $file, $callback);
} else {
$callback($dir . "/" . $file);
}
}
}
}
}
/**
* Scan certain file for vulnerabilities
*
* @param $file
* @param bool $report
* @return array
*/
protected function scanFile($file, $report = true)
{
$handle = fopen($file, "r");
$isPHP = false;
$line = 0;
$detected = false;
$suspicion = [];
if ($handle) {
while (!feof($handle)) {
$line++;
$buffer = fgets($handle, 4096);
if (!$isPHP && preg_match(Patterns::isPHP, $buffer)) {
$isPHP = true;
$this->scannedTotal++;
}
if ($isPHP) {
foreach (Patterns::$suspicious as $group => $suspect) {
if ($isPHP && preg_match_all($suspect, $buffer, $matches)) {
if (!$detected) {
$this->suspiciousTotal++;
$detected = true;
}
$suspicion[] = [
'group' => $group,
'line' => $line,
'buffer' => $buffer,
'danger' => $matches[0][0]
];
}
}
}
}
fclose($handle);
if ($report && !empty($suspicion)) {
Report::suspect($file, $suspicion);
}
}
return $suspicion;
}
/**
* Scanner constructor.
*
* @param string $dir
* @param array $extensions
*/
public function __construct($dir = __DIR__, $extensions = [])
{
Settings::$dir = $dir;
if (!empty($extensions)) {
Settings::$extensions = $extensions;
}
if (php_sapi_name() !== 'cli') {
Settings::$mode = Mode::WEB;
} elseif (function_exists('posix_isatty') && @posix_isatty(STDOUT)) {
Settings::$mode = Mode::CONSOLE;
} else {
Settings::$mode = Mode::CRON;
}
}
/**
* Application start
*
* @return void
*/
public function run()
{
error_reporting(E_ALL);
set_time_limit(0);
Report::header();
$this->getFiles(Settings::$dir, function ($file) {
if (is_file($file) && filesize($file) <= Settings::$fileSizeMax && in_array(pathinfo($file, PATHINFO_EXTENSION), Settings::$extensions)) {
$this->scanFile($file);
}
});
Report::footer($this->scannedTotal, $this->suspiciousTotal);
}
}
/**
* Class Settings
* Setting will be filled automatically on start
*
* @package Ollyxar\AntiMalware
*/
class Settings
{
/**
* Maximum filesize to be scanned (2Mb in bytes)
*
* @var int
*/
public static $fileSizeMax = 2097152;
/**
* Directory to scan
*
* @var string
*/
public static $dir = __DIR__;
/**
* File types to scan
*
* @var array
*/
public static $extensions = ['php', 'txt'];
/**
* Current mode
*
* @var Mode
*/
public static $mode;
/**
* Current window width. Can be applied only for File output
*
* @var int
*/
public static $width = 80;
}
(new Scanner())->run();