-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDefenderCheck.dpr
More file actions
618 lines (535 loc) · 19.3 KB
/
DefenderCheck.dpr
File metadata and controls
618 lines (535 loc) · 19.3 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
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
program DefenderCheck;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
System.IOUtils,
System.JSON,
System.Generics.Collections;
// ---------------------------------------------------------
// SECTION 1: TYPE DEFINITIONS
// ---------------------------------------------------------
// Enumerates the possible results of a single scan operation.
// Used to return status codes from the Scan function.
type
TScanResult = (
NoThreatFound, // The file segment was clean.
ThreatFound, // The file segment contained a known bad signature.
FileNotFound, // The file path provided was invalid.
Timeout, // The scan command took too long to execute.
ScanError // An unexpected error occurred during the scan.
);
// Record structure to store the result of finding a bad byte.
// Used to aggregate findings for the JSON output at the end.
TDetectionRecord = record
AbsoluteOffset: Integer; // The byte index where the threat was found.
Signature: string; // The name of the signature detected (e.g., "Backdoor:...").
HexDump: string; // The 256-byte hex dump of the offending segment.
end;
// ---------------------------------------------------------
// SECTION 2: CORE HELPERS
// ---------------------------------------------------------
// ------------------------------------------------------------------
// FUNCTION: RunProcessCapture
// PURPOSE: Spawns a child process (external tool) and captures its
// stdout output to a string.
// HOW: Uses CreateProcess with STARTF_USESTDHANDLES to redirect
// stdout to a pipe, then reads the pipe until the process ends.
// WHY: We cannot query Windows Defender's scanner directly; we must
// execute the command-line tool and read its text output.
// ------------------------------------------------------------------
function RunProcessCapture(const CommandLine: string;
TimeoutMS: Cardinal;
out ExitCode: Cardinal;
out Output: string): Boolean;
var
SA: TSecurityAttributes;
StdOutRead, StdOutWrite: THandle;
SI: TStartupInfoW;
PI: TProcessInformation;
Buffer: array[0..4095] of Byte;
BytesRead: DWORD;
WaitRes: DWORD;
sBuf: string;
begin
Result := False;
Output := '';
ExitCode := 0;
// Setup pipe attributes to allow child process to inherit handles
ZeroMemory(@SA, SizeOf(SA));
SA.nLength := SizeOf(SA);
SA.bInheritHandle := True;
// Create a pipe for communication. StdOutRead is for reading, StdOutWrite is for writing.
if not CreatePipe(StdOutRead, StdOutWrite, @SA, 0) then
Exit;
try
// Configure StartupInfo to capture output from the new process
ZeroMemory(@SI, SizeOf(SI));
SI.cb := SizeOf(SI);
SI.dwFlags := STARTF_USESTDHANDLES;
SI.hStdOutput := StdOutWrite;
SI.hStdError := StdOutWrite;
ZeroMemory(@PI, SizeOf(PI));
// Execute the command line. CREATE_NO_WINDOW prevents a console window from popping up.
if not CreateProcessW(
nil,
PWideChar(CommandLine),
nil,
nil,
True,
CREATE_NO_WINDOW,
nil,
nil,
SI,
PI) then
Exit;
// Close the write handle as the child process is the only one writing to it.
CloseHandle(StdOutWrite);
try
// Wait for the process to finish, but with a timeout.
WaitRes := WaitForSingleObject(PI.hProcess, TimeoutMS);
// Handle timeout: Terminate the process and report failure.
if WaitRes = WAIT_TIMEOUT then
begin
TerminateProcess(PI.hProcess, 1);
ExitCode := Cardinal(-1);
Exit;
end;
// Retrieve the process exit code.
GetExitCodeProcess(PI.hProcess, ExitCode);
// Read all output from the pipe until it is empty.
Output := '';
while ReadFile(StdOutRead, Buffer, SizeOf(Buffer), BytesRead, nil) and (BytesRead > 0) do
begin
SetString(sBuf, PAnsiChar(@Buffer[0]), BytesRead);
Output := Output + sBuf;
end;
Result := True;
finally
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
end;
finally
CloseHandle(StdOutRead);
end;
end;
// ------------------------------------------------------------------
// FUNCTION: Scan
// PURPOSE: Executes the Windows Defender command-line tool on a file.
// HOW: Constructs a specific command string and calls RunProcessCapture.
// WHY: We rely on Windows Defender's database to validate if a byte
// segment is malicious. We use ScanType 3 (Quick Scan) for speed.
// ------------------------------------------------------------------
function Scan(const FileName: string; GetSig: Boolean; out OutSig: string): TScanResult;
var
Cmd: string;
ExitCode: Cardinal;
Output: string;
Lines: TStringList;
I: Integer;
Parts: TArray<string>;
begin
OutSig := '';
if not TFile.Exists(FileName) then
Exit(FileNotFound);
// Construct the MpCmdRun.exe command.
// -Scan -ScanType 3: Quick Scan.
// -File "%s": Target file.
// -DisableRemediation: Do not delete the file (crucial for our analysis).
// -Trace -Level 0x10: Enable verbose logging.
Cmd := Format(
'"C:\Program Files\Windows Defender\MpCmdRun.exe" -Scan -ScanType 3 -File "%s" -DisableRemediation -Trace -Level 0x10',
[FileName]);
if not RunProcessCapture(Cmd, 60000, ExitCode, Output) then
Exit(ScanError);
if ExitCode = Cardinal(-1) then
Exit(Timeout);
Lines := TStringList.Create;
try
Lines.Text := Output;
for I := 0 to Lines.Count - 1 do
begin
// Defender outputs a line like: "Threat 0x00000000 ... [Signature]"
if Lines[I].Contains('Threat ') then
begin
Parts := Lines[I].Split([' ']);
// Extract the signature name from the end of the line.
if Length(Parts) > 19 then
begin
OutSig := Parts[19];
if GetSig then
Writeln('File matched signature: "', OutSig, '"');
end;
Break;
end;
end;
finally
Lines.Free;
end;
// Return result based on exit code.
// Exit code 0 = Clean, Exit code 2 = Threat Found.
case ExitCode of
0: Result := NoThreatFound;
2: Result := ThreatFound;
else
Result := ScanError;
end;
end;
// ------------------------------------------------------------------
// FUNCTION: GetHexDumpString
// PURPOSE: Converts a raw byte array into a formatted hex string.
// HOW: Iterates through bytes, converting each to two hex digits and
// appending the corresponding ASCII character (or dot if non-printable).
// WHY: To visualize the raw memory content for the user.
// ------------------------------------------------------------------
function GetHexDumpString(const Bytes: TBytes; BytesPerLine: Integer = 16): string;
var
I, J: Integer;
B: Byte;
HexPart, CharPart: string;
sb: TStringBuilder;
begin
sb := TStringBuilder.Create;
try
// Loop for each line of the dump (e.g., every 16 bytes)
for I := 0 to (Length(Bytes) - 1) div BytesPerLine do
begin
HexPart := '';
CharPart := '';
// Loop for each byte on the line
for J := 0 to BytesPerLine - 1 do
begin
if (I * BytesPerLine + J) < Length(Bytes) then
begin
B := Bytes[I * BytesPerLine + J];
// Format byte as hex (e.g., 0x2B -> "2B")
HexPart := HexPart + Format('%.2X ', [B]);
// Format ASCII character
if B < 32 then
CharPart := CharPart + '.' // Non-printable chars are dots
else
CharPart := CharPart + Char(B);
end
else
begin
// Padding for the end of the file
HexPart := HexPart + ' ';
end;
end;
// Append formatted line: Offset | Hex | ASCII
sb.AppendLine(Format('%.8x %s %s', [I * BytesPerLine, HexPart, CharPart]));
end;
Result := sb.ToString;
finally
sb.Free;
end;
end;
// ------------------------------------------------------------------
// PROCEDURE: HexDump
// PURPOSE: Wrapper for GetHexDumpString to output directly to stdout.
// ------------------------------------------------------------------
procedure HexDump(const Bytes: TBytes; BytesPerLine: Integer = 16);
begin
Write(GetHexDumpString(Bytes, BytesPerLine));
end;
// ------------------------------------------------------------------
// PROCEDURE: NeutralizeByte
// PURPOSE: Modifies a specific byte in a TBytes array to break the signature.
// HOW: Sets the byte at Index to 0 (or 255 if already 0).
// WHY: This is the "zeroing" step. By setting a byte to 0, we alter
// the signature so Defender won't match it anymore.
// ------------------------------------------------------------------
procedure NeutralizeByte(var Data: TBytes; Index: Integer);
begin
if (Index < 0) or (Index >= Length(Data)) then Exit;
if Data[Index] = 0 then
Data[Index] := $FF // If already 0, set to 255 to avoid no-change
else
Data[Index] := 0; // Set to 0 to corrupt signature
end;
// ------------------------------------------------------------------
// FUNCTION: SafeWriteBytes
// PURPOSE: Writes a byte array to a temporary file on disk.
// HOW: Creates a unique filename in C:\Temp and uses TFile.WriteAllBytes.
// WHY: Defender requires a file path to scan; it cannot scan raw memory.
// ------------------------------------------------------------------
function SafeWriteBytes(const Data: TBytes): string;
var
TempFile: string;
RetryCount: Integer;
begin
Result := '';
RetryCount := 0;
// Retry loop to handle potential file locking or permission issues
while RetryCount < 5 do
begin
try
TempFile := TPath.Combine('C:\Temp', TPath.GetRandomFileName + '.exe');
TFile.WriteAllBytes(TempFile, Data);
Result := TempFile;
Exit;
except
on E: Exception do
begin
Inc(RetryCount);
Sleep(200); // Wait briefly before retrying
end;
end;
end;
end;
// ---------------------------------------------------------
// SECTION 3: CORE ALGORITHM (BINARY SEARCH)
// ---------------------------------------------------------
// ------------------------------------------------------------------
// FUNCTION: FindBadBytes
// PURPOSE: Uses a Binary Search algorithm to isolate the first byte
// causing a detection in the file.
// HOW: 1. Divides the file length in half repeatedly.
// 2. Writes a temporary file representing the file[0..Mid].
// 3. Scans it with Defender.
// 4. Adjusts search bounds based on result (Clean vs Dirty).
// 5. Once found, zeroes the 256-byte segment and updates bounds.
// WHY: Binary search is O(log N), which is much faster than checking
// every byte sequentially, allowing for large files.
// The 256-byte zeroing ensures we don't find the same byte twice.
// ------------------------------------------------------------------
function FindBadBytes(var FileBytes: TBytes; IsDebug, FindAllMode: Boolean;
var DetectionResults: TList<TDetectionRecord>): Boolean;
var
Low, High, Mid: Integer;
Detection: TScanResult;
Offending: TBytes;
FoundOffset: Integer;
SigName: string;
Rec: TDetectionRecord;
TempFile: string;
TestBytes: TBytes;
i, ZeroStart, ZeroEnd: Integer;
begin
Result := False;
// Initialize bounds for binary search
Low := 0;
High := Length(FileBytes);
// Binary Search Loop
// We are looking for the first index 'Low' where File[0..Low] is Dirty.
// Initially, Low=0 (empty prefix), which is trivially clean.
while Low < High do
begin
Mid := Low + (High - Low) div 2;
// Create a byte array representing the first 'Mid' bytes of the file
SetLength(TestBytes, Mid + 1);
Move(FileBytes[0], TestBytes[0], Mid + 1);
if IsDebug then
Writeln('Testing range [0..', Mid, ']')
else
Write('.'); // Progress indicator
// Write the test bytes to a temp file
TempFile := SafeWriteBytes(TestBytes);
if TempFile = '' then
begin
Writeln('[-] Failed to write temp file.');
Exit;
end;
try
// Scan the temporary file
Detection := Scan(TempFile, False, SigName);
finally
// Cleanup temp file immediately after scanning
try
if TFile.Exists(TempFile) then TFile.Delete(TempFile);
except end;
end;
if Detection = ThreatFound then
begin
// If the prefix is dirty, the bad byte is at 'Mid' or earlier.
// We need to search the left half.
High := Mid;
end
else if Detection = NoThreatFound then
begin
// If the prefix is clean, the bad byte is after 'Mid'.
// We need to search the right half.
Low := Mid + 1;
end
else
begin
Writeln('[-] Scan error/timeout. Retrying...');
Sleep(1000);
// Do not change bounds, just retry current Mid
end;
end;
// Loop finished. Low == High. This is the exact offset of the bad byte.
FoundOffset := Low;
// Sanity check: verify this specific byte is indeed the trigger
// (It should be, because Low-1 was clean and Low is dirty)
if FoundOffset < Length(FileBytes) then
begin
if not IsDebug then Writeln;
Writeln(Format('[!] Identified bad byte at offset 0x%x', [FoundOffset]));
// Prepare the specific offending chunk for display and signature
SetLength(TestBytes, FoundOffset + 1);
Move(FileBytes[0], TestBytes[0], FoundOffset + 1);
TempFile := SafeWriteBytes(TestBytes);
try
Scan(TempFile, True, SigName);
finally
try
if TFile.Exists(TempFile) then TFile.Delete(TempFile);
except end;
end;
// Prepare the 256-byte hex dump for output
if Length(TestBytes) < 256 then
Offending := Copy(TestBytes, 0, Length(TestBytes))
else
Offending := Copy(TestBytes, FoundOffset - 255, 256); // Show 256 bytes leading up to offset
HexDump(Offending);
Rec.AbsoluteOffset := FoundOffset;
Rec.Signature := SigName;
Rec.HexDump := GetHexDumpString(Offending);
DetectionResults.Add(Rec);
Result := True;
if FindAllMode then
begin
Writeln('[*] Neutralizing 256-byte segment and rescanning...');
Writeln;
// Calculate the 256-byte segment to zero (context before the bad byte)
ZeroStart := FoundOffset - 255;
if ZeroStart < 0 then ZeroStart := 0;
ZeroEnd := FoundOffset;
// Zero out the entire 256-byte segment in memory
for i := ZeroStart to ZeroEnd do
NeutralizeByte(FileBytes, i);
// Update binary search bounds to skip the neutralized area
// The file is now clean from 0 to ZeroEnd, so the next bad byte is at ZeroEnd + 1
Low := ZeroEnd + 1;
Sleep(750);
end
else
begin
Halt(0); // Exit if only finding the first byte
end;
end;
end;
// ---------------------------------------------------------
// SECTION 4: MAIN EXECUTION
// ---------------------------------------------------------
var
TargetFile: string;
OriginalBytes, CurrentBytes: TBytes;
Detection: TScanResult;
Debug, FindAllMode: Boolean;
DetectionResults: TList<TDetectionRecord>;
I: Integer;
JsonArray: TJSONArray;
JsonObj, RootObj: TJSONObject;
OutputPath, DummySig: string;
ScanTemp: string;
begin
try
// Usage instructions
if ParamCount < 1 then
begin
Writeln('Usage: DefenderCheck.exe [path/to/file] [-all] [debug]');
Exit;
end;
TargetFile := ParamStr(1);
Debug := False;
FindAllMode := False;
// Parse command line arguments
if ParamCount >= 2 then
begin
if FindCmdLineSwitch('all') then
FindAllMode := True;
if (ParamCount >= 2) and (ParamStr(2).Contains('debug')) then
Debug := True
else if (ParamCount >= 3) and (ParamStr(3).Contains('debug')) then
Debug := True;
end;
if not TFile.Exists(TargetFile) then
begin
Writeln('[-] Can''t access the target file');
Exit;
end;
// Initial scan of the whole file to confirm it's dirty
ScanTemp := SafeWriteBytes(TFile.ReadAllBytes(TargetFile));
try
Detection := Scan(ScanTemp, False, DummySig);
finally
try
if TFile.Exists(ScanTemp) then TFile.Delete(ScanTemp);
except end;
end;
if Detection = NoThreatFound then
begin
Writeln('[+] No threat found in submitted file!');
Exit;
end;
// Ensure temp directory exists
if not TDirectory.Exists('C:\Temp') then
TDirectory.CreateDirectory('C:\Temp');
// Load original bytes into memory for manipulation
OriginalBytes := TFile.ReadAllBytes(TargetFile);
DetectionResults := TList<TDetectionRecord>.Create;
try
// Create a copy of the byte array to manipulate
CurrentBytes := Copy(OriginalBytes, 0, Length(OriginalBytes));
Writeln('Target file size: ', Length(OriginalBytes), ' bytes');
Writeln('Analyzing...');
Writeln;
// Main Loop: Repeatedly find bad bytes until scan is clean or max attempts
repeat
if not FindBadBytes(CurrentBytes, Debug, FindAllMode, DetectionResults) then
Break;
if FindAllMode then
begin
Writeln('[*] Verifying remaining file...');
Sleep(750);
ScanTemp := SafeWriteBytes(CurrentBytes);
try
Detection := Scan(ScanTemp, False, DummySig);
finally
try
if TFile.Exists(ScanTemp) then TFile.Delete(ScanTemp);
except end;
end;
if Detection <> ThreatFound then
begin
Writeln('[+] No further threats found in the remaining file.');
Break;
end;
Writeln('[*] Threat still detected. Continuing analysis...');
Writeln;
end;
until not FindAllMode;
// Output JSON results if detections were found
if DetectionResults.Count > 0 then
begin
OutputPath := TPath.Combine(ExtractFilePath(ParamStr(0)), 'results.json');
RootObj := TJSONObject.Create;
JsonArray := TJSONArray.Create;
try
RootObj.AddPair('file', TJSONString.Create(TargetFile));
RootObj.AddPair('detections', JsonArray);
for I := 0 to DetectionResults.Count - 1 do
begin
JsonObj := TJSONObject.Create;
JsonObj.AddPair('offset', TJSONNumber.Create(DetectionResults[I].AbsoluteOffset));
JsonObj.AddPair('signature', TJSONString.Create(DetectionResults[I].Signature));
JsonObj.AddPair('hex_dump', TJSONString.Create(DetectionResults[I].HexDump));
JsonArray.AddElement(JsonObj);
end;
TFile.WriteAllText(OutputPath, RootObj.Format(2));
Writeln(#13#10 + Format('[*] Results written to %s', [OutputPath]));
finally
RootObj.Free;
end;
end;
finally
DetectionResults.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.