-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsDefenderScanner.php
More file actions
227 lines (191 loc) · 7.05 KB
/
WindowsDefenderScanner.php
File metadata and controls
227 lines (191 loc) · 7.05 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
<?php
class WindowsDefenderScanner
{
public function healthCheck(): array
{
if (!$this->isWindows()) {
return [
'status' => 'unsupported',
'message' => 'Windows Defender sample only works on Windows.',
'details' => [],
];
}
$statusJson = $this->runPowerShell(
'Get-MpComputerStatus | Select-Object AMServiceEnabled, AntispywareEnabled, AntivirusEnabled, RealTimeProtectionEnabled, ' .
'AntivirusSignatureVersion, AMProductVersion, AMRunningMode, QuickScanAge, FullScanAge | ConvertTo-Json -Compress'
);
if (!$statusJson['success']) {
return [
'status' => 'unhealthy',
'message' => 'Unable to read Microsoft Defender status.',
'details' => $statusJson,
];
}
$decoded = json_decode($statusJson['stdout'], true);
if (!is_array($decoded)) {
return [
'status' => 'unhealthy',
'message' => 'Failed to parse Microsoft Defender status output.',
'details' => $statusJson,
];
}
$healthy =
!empty($decoded['AMServiceEnabled']) &&
!empty($decoded['AntivirusEnabled']) &&
!empty($decoded['RealTimeProtectionEnabled']);
return [
'status' => $healthy ? 'healthy' : 'unhealthy',
'message' => $healthy
? 'Microsoft Defender appears ready for scanning.'
: 'Microsoft Defender is not fully active. Check service state, running mode, and protection settings.',
'details' => $decoded,
'raw' => $statusJson,
];
}
public function updateSignatures(): array
{
return $this->runPowerShell('Update-MpSignature');
}
public function scan(string $filePath): array
{
if (!$this->isWindows()) {
return [
'status' => 'error',
'message' => 'This scanner only works on Windows.',
'virus' => null,
'output' => [],
];
}
if (!file_exists($filePath)) {
return [
'status' => 'error',
'message' => 'File does not exist.',
'virus' => null,
'output' => [],
];
}
$realPath = realpath($filePath);
if ($realPath === false) {
return [
'status' => 'error',
'message' => 'Unable to resolve file path.',
'virus' => null,
'output' => [],
];
}
// Clear old data reference point (best effort; history can still contain older items)
$before = $this->getThreatDetections();
$scan = $this->runPowerShell(
"Start-MpScan -ScanType CustomScan -ScanPath '" . $this->escapePowerShellString($realPath) . "'"
);
$after = $this->getThreatDetections();
if (!$scan['success']) {
return [
'status' => 'error',
'message' => 'Defender scan command failed.',
'virus' => null,
'output' => [$scan['stderr'] ?: $scan['stdout']],
'scan_command' => 'Start-MpScan -ScanType CustomScan -ScanPath <file>',
];
}
$detection = $this->findDetectionForPath($realPath, $before['items'] ?? [], $after['items'] ?? []);
if ($detection !== null) {
return [
'status' => 'infected',
'message' => 'Threat detected by Microsoft Defender.',
'virus' => $detection['ThreatName'] ?? 'Unknown threat',
'output' => [$after['stdout'] ?? ''],
'detection' => $detection,
'scan_command' => 'Start-MpScan -ScanType CustomScan -ScanPath <file>',
];
}
return [
'status' => 'clean',
'message' => 'No threat detection found for the uploaded file.',
'virus' => null,
'output' => [$scan['stdout']],
'scan_command' => 'Start-MpScan -ScanType CustomScan -ScanPath <file>',
];
}
protected function getThreatDetections(): array
{
$result = $this->runPowerShell(
'Get-MpThreatDetection | Select-Object ThreatName, Resources, InitialDetectionTime, ActionSuccess, CurrentAction, DomainUser | ConvertTo-Json -Compress'
);
if (!$result['success']) {
return [
'items' => [],
'stdout' => $result['stdout'] ?? '',
'stderr' => $result['stderr'] ?? '',
];
}
$decoded = json_decode($result['stdout'], true);
if ($decoded === null || $decoded === '') {
return [
'items' => [],
'stdout' => $result['stdout'] ?? '',
'stderr' => $result['stderr'] ?? '',
];
}
if (isset($decoded['ThreatName']) || isset($decoded['Resources'])) {
$decoded = [$decoded];
}
return [
'items' => is_array($decoded) ? $decoded : [],
'stdout' => $result['stdout'] ?? '',
'stderr' => $result['stderr'] ?? '',
];
}
protected function findDetectionForPath(string $filePath, array $before, array $after): ?array
{
$beforeHashes = [];
foreach ($before as $item) {
$beforeHashes[] = md5(json_encode($item));
}
foreach ($after as $item) {
$hash = md5(json_encode($item));
$resources = $item['Resources'] ?? [];
if (!is_array($resources)) {
$resources = [$resources];
}
foreach ($resources as $resource) {
if (is_string($resource) && stripos($resource, $filePath) !== false) {
return $item;
}
}
if (!in_array($hash, $beforeHashes, true)) {
foreach ($resources as $resource) {
if (is_string($resource) && stripos($resource, basename($filePath)) !== false) {
return $item;
}
}
}
}
return null;
}
protected function runPowerShell(string $script): array
{
$command = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ' . escapeshellarg($script);
$output = [];
$exitCode = null;
exec($command . ' 2>&1', $output, $exitCode);
$stdout = implode("\n", $output);
$success = ($exitCode === 0);
return [
'success' => $success,
'exit_code' => $exitCode,
'stdout' => $stdout,
'stderr' => $success ? '' : $stdout,
'command' => $command,
];
}
protected function escapePowerShellString(string $value): string
{
return str_replace("'", "''", $value);
}
protected function isWindows(): bool
{
return PHP_OS_FAMILY === 'Windows';
}
}
?>