Skip to content

Commit

Permalink
Version 2 update
Browse files Browse the repository at this point in the history
  • Loading branch information
Vicshann committed Apr 22, 2020
1 parent 124de69 commit 80c6649
Show file tree
Hide file tree
Showing 12 changed files with 603 additions and 279 deletions.
314 changes: 195 additions & 119 deletions InjectLib/InjectDll.cpp

Large diffs are not rendered by default.

25 changes: 20 additions & 5 deletions InjectLib/InjectDll.h
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@

#pragma once

/*
Copyright (c) 2020 Victor Sheinmann, Vicshann@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <intrin.h>
#include <Windows.h>
//#include <Windows.h>
#include "Utils.h"
#include "UniHook.hpp"
#include "json.h"
#include "FormatPE.h"
#include "NtDllEx.hpp"
#include "CompileTime.hpp"
#include "InjDllLdr.hpp"
#include "GhostDbg.hpp"
#include "..\..\GlobalInjector\GInjer\LoaderCode.h"

//====================================================================================
#define CFGFILE ".InjLib.jsn"
Expand All @@ -20,15 +34,16 @@ void _stdcall LoadConfiguration(void);
void _stdcall SaveConfiguration(int BinFmt=-1);
void _stdcall UnInitApplication(void);
bool _stdcall InitApplication(void);
int _stdcall DbgUsrReqCallback(ShMem::CMessageIPC::SMsgHdr* Req, PVOID ArgA, UINT ArgB);
int _fastcall DbgUsrReqCallback(ShMem::CMessageIPC::SMsgHdr* Req, PVOID ArgA, UINT ArgB);
//------------------------------------------------------------------------------------
bool _cdecl ProcExpDispBefore(volatile PVOID ArgA, volatile PVOID ArgB, volatile PVOID ArgC, volatile PVOID ArgD, volatile PVOID RetVal);
bool _cdecl ProcExpDispAfter(volatile PVOID ArgA, volatile PVOID ArgB, volatile PVOID ArgC, volatile PVOID ArgD, volatile PVOID RetVal);
//__declspec(noreturn) VOID NTAPI ProcRtlRestoreContext(PCONTEXT ContextRecord, PEXCEPTION_RECORD ExceptionRecord);
//__declspec(noreturn) void _fastcall ProcKiUserExceptionDispatcher(void);
//__declspec(noreturn) void NTAPI ProcLdrInitializeThunk(PVOID ArgA, PVOID ArgB, PVOID ArgC, PVOID ArgD);
void _stdcall ProcLdrpInitialize(volatile PCONTEXT Ctx, volatile PVOID NtDllBase);
NTSTATUS NTAPI ProcNtContinue(PCONTEXT ContextRecord, BOOLEAN TestAlert);
//NTSTATUS NTAPI ProcNtTerminateProcess(HANDLE ProcessHandle, NTSTATUS ExitStatus);
NTSTATUS NTAPI ProcNtTerminateProcess(HANDLE ProcessHandle, NTSTATUS ExitStatus);
NTSTATUS NTAPI ProcNtTerminateThread(HANDLE ThreadHandle, NTSTATUS ExitStatus);
NTSTATUS NTAPI ProcNtGetContextThread(HANDLE ThreadHandle, PCONTEXT Context);
NTSTATUS NTAPI ProcNtSetContextThread(HANDLE ThreadHandle, PCONTEXT Context);
Expand Down
53 changes: 29 additions & 24 deletions InjectLib/InjectDll.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -112,30 +112,31 @@
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<Optimization>Full</Optimization>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>$(SolutionDir)COMMON\;$(SolutionDir)COMMON\ThirdParty\;$(SolutionDir)COMMON\ModuleTools\;$(SolutionDir)COMMON\ThirdParty\ntdll\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_NODESTR;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<StructMemberAlignment>Default</StructMemberAlignment>
<BufferSecurityCheck>false</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SuppressStartupBanner>false</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
<CallingConvention>FastCall</CallingConvention>
<ShowIncludes>false</ShowIncludes>
<StringPooling>true</StringPooling>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FunctionLevelLinking>true</FunctionLevelLinking>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<LanguageStandard>stdcpplatest</LanguageStandard>
<AdditionalOptions>/Gs100000000 %(AdditionalOptions)</AdditionalOptions>
<ControlFlowGuard>false</ControlFlowGuard>
</ClCompile>
<Link>
<ShowProgress>LinkVerboseLib</ShowProgress>
Expand Down Expand Up @@ -172,31 +173,32 @@
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<Optimization>Full</Optimization>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>$(SolutionDir)COMMON\;$(SolutionDir)COMMON\ThirdParty\;$(SolutionDir)COMMON\ModuleTools\;$(SolutionDir)COMMON\ThirdParty\ntdll\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_NODESTR;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<StructMemberAlignment>Default</StructMemberAlignment>
<BufferSecurityCheck>false</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SuppressStartupBanner>false</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
<CallingConvention>FastCall</CallingConvention>
<ShowIncludes>false</ShowIncludes>
<StringPooling>true</StringPooling>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FunctionLevelLinking>true</FunctionLevelLinking>
<OmitFramePointers>false</OmitFramePointers>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<LanguageStandard>stdcpplatest</LanguageStandard>
<AdditionalOptions>/Gs100000000 %(AdditionalOptions)</AdditionalOptions>
<ControlFlowGuard>false</ControlFlowGuard>
</ClCompile>
<Link>
<ShowProgress>LinkVerboseLib</ShowProgress>
Expand Down Expand Up @@ -235,24 +237,25 @@
<OmitFramePointers>true</OmitFramePointers>
<WholeProgramOptimization>false</WholeProgramOptimization>
<AdditionalIncludeDirectories>$(SolutionDir)COMMON\;$(SolutionDir)COMMON\ThirdParty\;$(SolutionDir)COMMON\ModuleTools\;$(SolutionDir)COMMON\ThirdParty\ntdll\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_NODESTR;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<StructMemberAlignment>Default</StructMemberAlignment>
<BufferSecurityCheck>false</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SuppressStartupBanner>false</SuppressStartupBanner>
<DebugInformationFormat>
</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
<CompileAs>CompileAsCpp</CompileAs>
<CallingConvention>FastCall</CallingConvention>
<CompileAs>Default</CompileAs>
<FunctionLevelLinking>true</FunctionLevelLinking>
<LanguageStandard>stdcpplatest</LanguageStandard>
<AdditionalOptions>/Gs100000000 %(AdditionalOptions)</AdditionalOptions>
<ControlFlowGuard>false</ControlFlowGuard>
</ClCompile>
<Link>
<ShowProgress>LinkVerboseLib</ShowProgress>
Expand Down Expand Up @@ -297,24 +300,25 @@ copy /Y "$(OutDir)$(TargetName)$(TargetExt)" "$(SolutionDir)BUILD\RELEASE\$(Solu
<OmitFramePointers>true</OmitFramePointers>
<WholeProgramOptimization>false</WholeProgramOptimization>
<AdditionalIncludeDirectories>$(SolutionDir)COMMON\;$(SolutionDir)COMMON\ThirdParty\;$(SolutionDir)COMMON\ModuleTools\;$(SolutionDir)COMMON\ThirdParty\ntdll\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_NODESTR;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<StructMemberAlignment>
</StructMemberAlignment>
<StructMemberAlignment>Default</StructMemberAlignment>
<BufferSecurityCheck>false</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SuppressStartupBanner>false</SuppressStartupBanner>
<DebugInformationFormat>
</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
<CompileAs>CompileAsCpp</CompileAs>
<CallingConvention>FastCall</CallingConvention>
<CompileAs>Default</CompileAs>
<FunctionLevelLinking>true</FunctionLevelLinking>
<LanguageStandard>stdcpplatest</LanguageStandard>
<AdditionalOptions>/Gs100000000 %(AdditionalOptions)</AdditionalOptions>
<ControlFlowGuard>false</ControlFlowGuard>
</ClCompile>
<Link>
<ShowProgress>LinkVerboseLib</ShowProgress>
Expand Down Expand Up @@ -362,6 +366,7 @@ copy /Y "$(OutDir)$(TargetName)$(TargetExt)" "$(SolutionDir)BUILD\RELEASE\$(Solu
<ClInclude Include="..\COMMON\InjDllLdr.hpp" />
<ClInclude Include="..\COMMON\json.h" />
<ClInclude Include="..\COMMON\MiniString.h" />
<ClInclude Include="..\COMMON\NtDllEx.hpp" />
<ClInclude Include="..\COMMON\ShMemIPC.hpp" />
<ClInclude Include="..\COMMON\ThirdParty\ntdll\ntdll.h" />
<ClInclude Include="..\COMMON\UniHook.hpp" />
Expand Down
3 changes: 3 additions & 0 deletions InjectLib/InjectDll.vcxproj.filters
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,8 @@
<ClInclude Include="..\COMMON\UniHook.hpp">
<Filter>Common</Filter>
</ClInclude>
<ClInclude Include="..\COMMON\NtDllEx.hpp">
<Filter>Common</Filter>
</ClInclude>
</ItemGroup>
</Project>
88 changes: 81 additions & 7 deletions NOTES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,98 @@
ETHREAD -> StartAddress ?

https://www.codeproject.com/Articles/543542/Windows-x-system-service-hooks-and-advanced-debu
https://www.codeproject.com/Articles/543542/Windows-x64-system-service-hooks-and-advanced-debu


TODO:
Unload inject DLL if it was loaded by a debugger and it is going to detach
Unload inject DLL if it was loaded by a debugger and it is going to detach?
Intercept Any exception (Optional)
Start target as Explorer.exe
Start a target as Explorer.exe
Hardware BP only for an active thread (Last for GetThreadContext?)
Inject into child processes
Block constant Thread Suspend/Resume calls except for BP setting
Kernel exception dispatcer hook(No hook of KiUserExceptionDispatcher and NtContinue)
Use unly a low level WinAPI in GhostDbg.hpp
Block constant Thread Suspend/Resume calls by x64Dbg if it is already in DbgEvent handler?
Kernel exception dispatcher hook(No hook of KiUserExceptionDispatcher and NtContinue) (GhostDrv)
Make DebugBreak less intrusive (No CreateThread?) (APC?)
Alternate software BP support?
Single IPC buffer for all GhostDbg clients (Required for GhostDrv)
IPC SRW locks
Enable Config files
IDA compatibility
Fix NativeCreateThread on latest Windows 10
Fix extreme slowness on Windows XP (Sync problem? Fix for GhostDrv) // https://communities.vmware.com/thread/466749
GInjer compatibility (Especially WOW64 debugging)

ISSUES:
Software breakpoints is very dangerous to set
Software breakpoints is very dangerous to set if not all threads are suspended on a Debug Event
Because of SEH recursion a DBG context protection is not used(Find a way to mark a thread with RefCtr)

//-----------------------------------------------------------------------------------------------------------------
MSVC compiler will always generate ExceptionDirectory for x64 builds. Need to use CLANG to make InjLib smaller: '/clang:-fno-unwind-tables'
//---------------------------

BOOL IsWow64Process2(HANDLE hProcess, USHORT *pProcessMachine, USHORT *pNativeMachine) --> NTSTATUS RtlWow64GetProcessMachines(HANDLE hProcess, USHORT *pProcessMachine, USHORT *pNativeMachine);

//-----------------------------------------------------------------------------------------------------------------
How DebugActiveProcess works:
1) Suspends all process` threads
2) Creates a remote thread at ntdll.dll:DbgUiRemoteBreakin
3) Suspends all other process` threads again (Including at DbgUiRemoteBreakin) // Suspend count 1,2,2,2,...
3) Suspends all other process` threads again (Including at DbgUiRemoteBreakin) // Suspend count is 1,2,2,2,...


------------------------------------------
https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread

Note that while reporting debug events, all threads within the reporting process are frozen.
Debuggers are expected to use the SuspendThread and ResumeThread functions to limit the set of threads that can execute within a process.
By suspending all threads in a process except for the one reporting a debug event, it is possible to "single step" a single thread.
The other threads are not released by a continue operation if they are suspended.

-----------------------------------------------------------------------
_chkstk Routine is a helper routine for the C compiler. For x86 compilers, _chkstk Routine is called when the local variables exceed 4K bytes; for x64 compilers it is 8K.

-------------------------------------
RtlDispatchException hooking:
1) Find a call to RtlDispatchException in KiUserExceptionDispatcher
2) Put a jump to a stub at beginning of RtlDispatchException (Save original instructions)

----------------------------------------------------------------------
__int64 __fastcall Wow64NtCreateThread(_QWORD *a1, unsigned int a2, __int64 a3, __int64 aProcessHandle, __int64 a5, CONTEXT *a6, __int64 a7, char aSuspended)
{
void *vProcessHandle; // rbp
struct _OBJECT_ATTRIBUTES *v9; // r15
unsigned int v10; // er14
void **v11; // rbx
__int64 result; // rax
NTSTATUS vStatus; // edi
__int16 vMachine; // [rsp+40h] [rbp-538h]
CONTEXT Dst; // [rsp+50h] [rbp-528h]

vProcessHandle = (void *)aProcessHandle;
v9 = (struct _OBJECT_ATTRIBUTES *)a3;
v10 = a2;
v11 = (void **)a1;
if ( !a1 || !a7 || !a6 )return 0xC000000Di64;
result = RtlWow64GetProcessMachines(aProcessHandle, &vMachine, 0i64);
if ( (int)result < 0 )return result;
if ( vMachine )return 0xC0000022i64; // ??????????????????????????????? // Not IMAGE_FILE_MACHINE_UNKNOWN // IsWow64Process is TRUE
memset_0(&Dst, 0, 1232u);
Dst.Rip = LODWORD(a6->R8);
Dst.Rcx = LODWORD(a6->Rdi);
Dst.Rdx = HIDWORD(a6->Rbp);
Dst.R8 = HIDWORD(a6->R9);
Dst.ContextFlags = 0x100003;
vStatus = NtCreateThread(v11, v10, v9, vProcessHandle, (PCLIENT_ID)a5, &Dst, (PINITIAL_TEB)a7, 1u);
if ( vStatus < 0 )return (unsigned int)vStatus;
if ( vMachine == 0x14C && (unsigned __int16)RtlWow64GetCurrentMachine() == 0x14C )Wow64pCpuInitializeStartupContext((__int64)vProcessHandle, (__int64)*v11, (__int64)a6);
if ( !aSuspended )
{
vStatus = NtResumeThread(*v11, 0i64);
if ( vStatus < 0 )
{
NtTerminateThread(*v11, 0);
return (unsigned int)vStatus;
}
}
return 0i64;
}
----------------------------------------------------------------------
Binary file added XDbgPlugin/LogoIcon.ico
Binary file not shown.
12 changes: 6 additions & 6 deletions XDbgPlugin/Resources.rc
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ LANGUAGE LANG_ENGLISH, SUBLANG_DEFAULT
#pragma code_page(1251)
#endif //_WIN32


5 ICON "LogoIcon.ico"
MAINICON RCDATA "MainIcon.png" // ICON
InjLib RCDATA INJLIBPATH

Expand All @@ -16,8 +16,8 @@ InjLib RCDATA INJLIBPATH
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,1,0,0
PRODUCTVERSION 1,1,0,0
FILEVERSION 2,1,0,0
PRODUCTVERSION 2,1,0,0
FILEFLAGSMASK 0x17L
#ifdef _DEBUG
FILEFLAGS 0x1L
Expand All @@ -35,12 +35,12 @@ BEGIN
VALUE "Comments", "https://github.com/Vicshann" // Github page
VALUE "CompanyName", "Vicshann"
VALUE "FileDescription", "x64Dbg plugin"
VALUE "FileVersion", "0, 8, 0, 0"
VALUE "FileVersion", "2, 0, 0, 0"
VALUE "InternalName", "GhostDbg"
VALUE "LegalCopyright", "Copyright (c) 2018 Vicshann"
VALUE "LegalCopyright", "Copyright (c) 2020 Vicshann"
VALUE "OriginalFilename", "GhostDbg.dll"
VALUE "ProductName", "GhostDbg"
VALUE "ProductVersion", "0, 8, 0, 0"
VALUE "ProductVersion", "2, 0, 0, 0"
END
END
BLOCK "VarFileInfo"
Expand Down
Loading

0 comments on commit 80c6649

Please sign in to comment.