-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp-scanner.js
More file actions
260 lines (221 loc) · 9.38 KB
/
Copy pathphp-scanner.js
File metadata and controls
260 lines (221 loc) · 9.38 KB
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
#!/usr/bin/env node
// PHP Malware & Obfuscation Scanner - Vanilla Node.js
// Compatible with Windows 10 / Linux / macOS
const fs = require('fs').promises;
const path = require('path');
const os = require('os');
const fsSync = require('fs');
// ================= CONFIGURATION =================
const CONFIG = {
maxFileSizeMB: 5, // Skip files > 5MB to avoid memory issues
phpExtensions: ['.php', '.phtml', '.php3', '.php4', '.php5', '.inc'],
entropyThreshold: 4.5, // Shannon entropy threshold for obfuscation
minEncodedStringLen: 150, // Minimum length of suspicious encoded strings
reportFormat: process.argv[3] || 'console' // 'console' or 'json'
};
// Malware signatures (function calls, patterns, techniques)
const SIGNATURES = [
{ name: 'eval() execution', pattern: /\beval\s*\(/i, severity: 'high', falsePositiveRisk: 'medium' },
{ name: 'assert() abuse', pattern: /\bassert\s*\(/i, severity: 'high', falsePositiveRisk: 'low' },
{ name: 'preg_replace /e modifier', pattern: /\bpreg_replace\s*\(\s*["'][^"']*\/e/i, severity: 'critical', falsePositiveRisk: 'low' },
{ name: 'base64_decode()', pattern: /\bbase64_decode\s*\(/i, severity: 'medium', falsePositiveRisk: 'high' },
{ name: 'gzinflate() + base64', pattern: /\bgzinflate\s*\(\s*base64_decode\s*\(/i, severity: 'critical', falsePositiveRisk: 'very-low' },
{ name: 'str_rot13() + eval', pattern: /\bstr_rot13\s*\(/i, severity: 'medium', falsePositiveRisk: 'medium' },
{ name: 'backtick execution', pattern: /`[^`]{5,}`/, severity: 'high', falsePositiveRisk: 'medium' },
{ name: 'php://input wrapper', pattern: /\bphp:\/\/input/i, severity: 'high', falsePositiveRisk: 'low' },
{ name: 'http/https include', pattern: /\b(include|require)(_once)?\s*\(\s*["'](https?:\/\/|ftp:\/)/i, severity: 'high', falsePositiveRisk: 'low' },
{ name: 'obfuscated variable names', pattern: /\$\b[_a-zA-Z0-9]{10,}\b(?!\s*=)/, severity: 'low', falsePositiveRisk: 'high' },
{ name: 'shell execution', pattern: /\b(shell_exec|system|passthru|exec|popen|proc_open)\s*\(/i, severity: 'critical', falsePositiveRisk: 'low' }
];
// ================= UTILITY FUNCTIONS =================
function calculateEntropy(str) {
if (!str || str.length === 0) return 0;
const freq = {};
for (const char of str) freq[char] = (freq[char] || 0) + 1;
let entropy = 0;
const len = str.length;
for (const count of Object.values(freq)) {
const p = count / len;
entropy -= p * Math.log2(p);
}
return entropy;
}
function isObfuscated(code) {
const issues = [];
// Check for long base64/hex strings
const base64Pattern = /[A-Za-z0-9+/]{100,}={0,2}/g;
const hexPattern = /(?:0x[0-9A-Fa-f]{2}){50,}/g;
const matches = [...code.matchAll(base64Pattern), ...code.matchAll(hexPattern)];
if (matches.length > 0) {
const longest = matches.reduce((a, b) => a[0].length > b[0].length ? a : b)[0];
if (longest.length >= CONFIG.minEncodedStringLen) {
issues.push(`Long encoded string found (${longest.length} chars)`);
}
}
// High entropy check on non-comment lines
const lines = code.split(/\r?\n/).filter(l => !l.trim().startsWith('//') && !l.trim().startsWith('/*') && !l.trim().startsWith('*'));
const suspiciousLines = lines.filter(l => {
const trimmed = l.replace(/\s+/g, '').trim();
if (trimmed.length < 50) return false;
return calculateEntropy(trimmed) > CONFIG.entropyThreshold;
});
if (suspiciousLines.length > 0) {
issues.push(`${suspiciousLines.length} line(s) with high entropy (> ${CONFIG.entropyThreshold})`);
}
// Chained decoding functions
if (/(base64_decode|gzinflate|gzuncompress|str_rot13|urldecode)\s*\(\s*(base64_decode|gzinflate|gzuncompress|str_rot13|urldecode)/i.test(code)) {
issues.push('Chained decoding/obfuscation functions detected');
}
return issues;
}
function analyzeFile(filePath, content) {
const findings = {
path: filePath,
signatures: [],
obfuscation: [],
riskScore: 0,
falsePositiveRisk: 'none'
};
// Signature detection
for (const sig of SIGNATURES) {
if (sig.pattern.test(content)) {
findings.signatures.push(sig.name);
findings.riskScore += sig.severity === 'critical' ? 3 : sig.severity === 'high' ? 2 : 1;
if (sig.falsePositiveRisk === 'very-low') findings.falsePositiveRisk = 'very-low';
else if (sig.falsePositiveRisk === 'low' && findings.falsePositiveRisk !== 'very-low') findings.falsePositiveRisk = 'low';
else if (sig.falsePositiveRisk === 'medium' && findings.falsePositiveRisk === 'none') findings.falsePositiveRisk = 'medium';
}
}
// Obfuscation detection
findings.obfuscation = isObfuscated(content);
if (findings.obfuscation.length > 0) findings.riskScore += 2;
return findings;
}
async function readSafe(filePath) {
try {
const stat = await fs.stat(filePath);
if (stat.size > CONFIG.maxFileSizeMB * 1024 * 1024) return null;
// Try UTF-8 first, fallback to latin1 to avoid binary crash
return await fs.readFile(filePath, 'utf8').catch(() => fs.readFile(filePath, 'latin1'));
} catch (e) {
return null;
}
}
// ================= SCANNER ENGINE =================
async function scanDirectory(dir, results = []) {
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch (e) {
console.error(`⚠️ Access denied or invalid directory: ${dir}`);
return results;
}
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
await scanDirectory(fullPath, results);
// Bisa switch filter extensi di sini
// } else if (CONFIG.phpExtensions.includes(path.extname(entry.name).toLowerCase())) {
} else if ( true ) {
const content = await readSafe(fullPath);
if (content) {
const findings = analyzeFile(fullPath, content);
// if (findings.riskScore > 0 || findings.obfuscation.length > 0) {
if (findings.riskScore > 1 || findings.obfuscation.length > 0) {
results.push(findings);
}
}
}
}
return results;
}
// ================= REPORTER =================
function formatConsoleReport(results, targetDir) {
console.log(`\n🔍 PHP Malware & Obfuscation Scanner`);
console.log(`📁 Target: ${targetDir}`);
console.log(`📊 Files scanned: ${results.length} suspicious out of scanned total\n`);
if (results.length === 0) {
console.log('✅ No suspicious patterns or obfuscation detected.');
return;
}
results.sort((a, b) => b.riskScore - a.riskScore);
for (const res of results) {
console.log(`📄 ${res.path}`);
console.log(` ⚠️ Risk Score: ${res.riskScore} | False Positive Risk: ${res.falsePositiveRisk.toUpperCase()}`);
if (res.signatures.length) console.log(` 🦠 Signatures: ${res.signatures.join(', ')}`);
if (res.obfuscation.length) console.log(` 🔒 Obfuscation: ${res.obfuscation.join('; ')}`);
console.log('');
}
// Save results as JSON into folder "hasil_php_scanner"
try {
const outDir = path.join(process.cwd(), 'hasil_php_scanner');
fsSync.mkdirSync(outDir, { recursive: true });
const safeTarget = (targetDir || 'scan').replace(/[<>:"\/\\|?*\s]+/g, '_').replace(/^_+|_+$/g, '');
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const outFile = path.join(outDir, `${safeTarget}_${timestamp}.json`);
const payload = {
scanDate: new Date().toISOString(),
target: targetDir,
totalSuspicious: results.length,
results: results
};
fsSync.writeFileSync(outFile, JSON.stringify(payload, null, 2), 'utf8');
console.log(`💾 Results saved to ${outFile}`);
} catch (e) {
console.error('❌ Failed to save results:', e.message);
}
console.log('💡 Tip: Always verify manually. High entropy/base64 is common in licensed themes/plugins.');
}
function formatJsonReport(results, targetDir) {
const output = {
scanDate: new Date().toISOString(),
target: targetDir,
totalSuspicious: results.length,
results: results
};
process.stdout.write(JSON.stringify(output, null, 2));
}
// ================= CLI ENTRY =================
async function main() {
const target = process.argv[2];
if (!target || !['-h', '--help'].includes(target)) {
const resolved = path.resolve(target);
try {
await fs.access(resolved);
} catch {
console.error('❌ Directory not found or inaccessible.');
console.log('Usage: node php-scanner.js <directory> [console|json]');
process.exit(1);
}
} else {
console.log(`
🔍 PHP Malware & Obfuscation Scanner
Usage: node php-scanner.js <target_directory> [console|json]
Examples:
node php-scanner.js C:\\xampp\\htdocs\\myproject
node php-scanner.js /var/www/html json
Features:
- Recursive .php file scanning
- Known malware signature detection
- Entropy & obfuscation heuristic analysis
- False-positive risk estimation
- Works offline, zero dependencies
`);
process.exit(0);
}
const targetDir = path.resolve(process.argv[2]);
console.log(`⏳ Scanning ${targetDir} ...`);
const startTime = Date.now();
const results = await scanDirectory(targetDir);
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
if (CONFIG.reportFormat === 'json') {
formatJsonReport(results, targetDir);
} else {
formatConsoleReport(results, targetDir);
}
console.log(`✅ Scan completed in ${duration}s`);
}
main().catch(err => {
console.error('❌ Unexpected error:', err.message);
process.exit(1);
});