GithubHelp home page GithubHelp logo

nektra / deviare-inproc Goto Github PK

View Code? Open in Web Editor NEW
325.0 325.0 87.0 839 KB

Deviare In Process Instrumentation Engine

Home Page: http://nektra.com/products/deviare-api-hook-windows/deviare-in-process/

License: Other

C++ 41.71% C 37.09% C# 2.64% Assembly 8.86% Batchfile 0.06% Objective-C 0.52% Makefile 0.45% Shell 0.47% M4 1.31% Python 6.10% CSS 0.15% XSLT 0.20% VBScript 0.44%

deviare-inproc's People

Contributors

adamjames avatar helios-vmg avatar mxmauro avatar scnale avatar srw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

deviare-inproc's Issues

Is there anyway to createprocess from a dotnet exe and suspend it at its main method?

Suppose the target exe looks like this:

namespace Target {
   class Target {
      static void Main(string[] args) {
            while (true) {
               Console.WriteLine("NOT HOOKED");
               Thread.Sleep(1000);
            }
      }
   }
}

What I want to do is to hook the Console.WriteLine method right before the target has any chance to run "Main" method, so I tried to open process with HookLib.ProcessCreationFlags.CREATE_SUSPENDED flag:

HookLib.ProcessInfo pi = cHook.CreateProcess(targetPath, "", null, null, false, HookLib.ProcessCreationFlags.CREATE_SUSPENDED, null, null, si);

Then I injected my C++ DLL which would load my C# DLL:

cHook.InjectDll(pi.procId, injecteePath, "ImplantDotNetAssembly", 0);
HRESULT __stdcall ImplantDotNetAssembly() {
   //...
   CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&metaHost));
   metaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&runtimeInfo));
   runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&runtimeHost));
   runtimeHost->Start();
   runtimeHost->ExecuteInDefaultAppDomain(
      L"Managed DLL.dll", // my C# DLL
      L"MyCode.Program",
      L"AddHandler",
      L"No need",
      &returnValue);
}

In my C# DLL, the code looks like this:

namespace MyCode {
   public class Program {
      public static int AddHandler(string arg) {
         HookLib cHook;
         cHook = new HookLib();
         Console.WriteLine("Hook WriteLine");
         var o = cHook.Hook(typeof(Console), "WriteLine", new Type[] { typeof(string) }, typeof(Handler), "Hooked_WriteLine", new Type[] { typeof(string) });
         return 1;
      }
      public static void Hooked_WriteLine(string value) {
         Console.WriteLine("HOOKED!");
      }
   }
}

But everytime I run it, when I resume the target process, it just crashes with an error: "CLR error: 80004005. The program will now terminate."

So is there a way to suspend it at its Main method?

Problem injecting a DLL into a C# app

Hi! I'm having problems injecting a 32bit dll into a 32bit C# app.

Symptoms are as follows:

  • CreateProcessWithDllW returns success.
  • My dll fprintfs stuff out to confim it has been injected - this is not triggered.
  • Other pure C++ apps work fine - only seems to affect dotnet.
  • Using vanilla CreateProcess and then using InjectDllByHandle works, but then I have other issues (not relevant to this problem).

It looks like it's fairly easy to repro - I just did a test by creating an empty C# console app which sleeps for a few seconds, and my simple test dll fails to start.

Let me know if I'm doing anything stupid, or if you need more information.

Thanks!

Simon

x64 unhooking problem in MT application

Hello guys,

I encountered a problem with unhooking in the next scenario.
There is a simple native x64 application:

#include <iostream>
#include <Windows.h>
#include <process.h>
#include "NktHookLib.h"

typedef int (*TheFunctionFunc)(void*);

CNktHookLib::HOOK_INFO g_hook;

int TheFunctionHook(void* p1) {
    std::cout << "Hook" << std::endl;

    if (g_hook.lpCallOriginal) {
        return ((TheFunctionFunc)(g_hook.lpCallOriginal))(p1);
    }

    return 0;
}

TheFunctionFunc TheFunction;

void init() {
    HMODULE hModule = LoadLibrary(L"module.dll");

    if (!hModule)
        return;

    TheFunction = (TheFunctionFunc)GetProcAddress(hModule, "TheFunction");
}

CNktHookLib g_lib;

void install_hooks() {
    g_lib.SetEnableDebugOutput(TRUE);
    g_hook.lpProcToHook = TheFunction;
    g_hook.lpNewProcAddr = TheFunctionHook;
    g_lib.Hook(&g_hook, 1);
}

void uninstall_hooks() {
    g_lib.Unhook(&g_hook, 1);
}

unsigned __stdcall run(void*) {
    while (true) {
        TheFunction(nullptr);
    }

    return 0;
}

int main() {
    init();
    TheFunction(nullptr);
    HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 2048, run, nullptr, 0, 0);

    while (true) {
        install_hooks();
        //WaitForSingleObject(hThread, 61000);
        uninstall_hooks();
        //WaitForSingleObject(hThread, 1000);
    }

    CloseHandle(hThread);
}

This code lead to crash of the application during uninstallation of the hook in the _beginthreadex thread.
Analyzing disassembly code and NktHookLib.cpp revealed next.

            *p++ = 0x48;  *p++ = 0xF7;  *p++ = 0x02;                             //test  QWORD PTR [rdx], 00000101h
            *((ULONG NKT_UNALIGNED*)p) = 0x00000101;
            p += sizeof(ULONG);
            //----
            *p++ = 0x75;                                                         //jne   CALL_ORIGINAL
            *p++ = ((lpHookEntry->dwFlags & NKTHOOKLIB_DisallowReentrancy) != 0) ? 0x7A : 0x06;
            //check for reentranct

Which as I understood lead to this code:

000007FEBA6A0022 75 06                jne         000007FEBA6A002A  
000007FEBA6A0024 5A                   pop         rdx  
000007FEBA6A0025 FF 25 00 00 00 00    jmp         qword ptr [7FEBA6A002Bh]  
000007FEBA6A002B 4B 10 FC             adc         r12b,dil  
000007FEBA6A002E ??                   db          3fh  
000007FEBA6A002F 01 00                add         dword ptr [rax],eax  
000007FEBA6A0031 00 00                add         byte ptr [rax],al  
000007FEBA6A0033 5A                   pop         rdx  
000007FEBA6A0034 4C 89 4C 24 20       mov         qword ptr [rsp+20h],r9  
000007FEBA6A0039 FF 25 00 00 00 00    jmp         qword ptr [7FEBA6A003Fh]  

but jump 000007FEBA6A002A is not correct in case of unloading. The correct address I suppose is 000007FEBA6A0033 thus offset 0x06 should be replaced with 0x0F. Doing this fixed the problem on my side.
So, if you have a chance to review this place that would be great.

Thanks,
Mikalaj

[Suggestion] CreateProcessWithBuffer

Another nice feature would be to be able to Create a new Process with an injected DLL which is already read from the disk or downloaded from the internet.

So, eg. If I downloaded a DLL from XY website, but I don't want to write it to disk before Injecting, then I could just call this API and inject it from buffer.

I'm not sure how your Dll injection works (could you explain quickly? LoadLibrary, LdrLoadDll, Manual mapping, etc), but I'm sure it would require some kind of Manual mapping method. It would be great to see such a feature :)

(I'm not yet familiar with GitHub, so I'm not sure if I'm writing to to wrong place, actually I couldn't find any better place. Did I miss anything?)

STATUS_STACK_BUFFER_OVERRUN was raised

I inject the process using NKTHOOKLIB_DisallowReentrancy

hook function
NtClose
NtOpenFile
NtCreateSection
NtQueryAttributesFile

STATUS_STACK_BUFFER_OVERRUN was raised
But without using NKTHOOKLIB_DisallowReentrancy everything works fine
Below is the dmp file

Test platform windows 11 x64 22h2
computer Alienware x17 R2

CrashDump_2a50_2022-10-07_21-48-57-595_3248.zip

The problem might be
http://forum.madshi.net/viewtopic.php?f=7&t=28896

madCodeHook 4.2.1 comes with the following changes (compared to 4.1.3):
· rewrite of many assembler stubs to make Intel CET happy

After testing Visual Studio (2019-2022) open /CETCOMPAT the problem will reproduce,
the hardware must support CET

How to hook .NET methods in remote process?

Hi, I would like to hook certain methods in a .NET executable while it is running. I found this sample code:

object o = cHook.Hook(typeof(SampleClass), "Call", new Type[] { typeof(string), typeof(string) }, typeof(MySampleClass), "Call", new Type[] { typeof(string), typeof(string) });

But this of course only works inside the current executable, is it possible to achieve the same thing in a remote process using Deviare In-Proc? I know it can also inject DLL's, but as far as I can see, that will only work with a native DLL, and I'd first just like to know if I can do this with C# instead.

Unsafe hooks, lpOriginal is not set right after resuming threads

Here's the problem, when we call Hook(), the function calls RemoteHook() which then build the trampoline, suspend the threads and do the actual hooking. Once hooked, all the threads is resumed and one of the threads which calls the hooked functions will crash if the detoured function try to call lpOriginal function too, before the Hook() actually return and give proper lpOriginal address.

Let me illustrate a bit:

Thread 1 -------------------------- Thread 2
Hook(&lpOriginal) -----------------
RemoteHook() ----------------------
SuspendThreads() ------------------ Suspended
ActualHooking ---------------------
ResumeThreads() ------------------- Running
----------------------------------- Call hooked function
----------------------------------- Call original function (lpOriginal)
----------------------------------- crash due to lpOriginal not set yet
RemoteHook() return ---------------
Hook() return with lpOriginal set -

how hook DateTime.Now

it will return local time
I had hook kernel32.dll getlocaltime , but it no effect
when i step into the method 'Now' source , I found it invoke DateTime.GetSystemTimeAsFileTime() so I hook DateTime.GetSystemTimeAsFileTime() and get the right result。

it is not a stylish method, how can I hook it directly?
Abstract point: how hook a c# Struct ' prop

Missing files

Hi all,

I just downloaded the ZIP, unpacked it into an empty dir, loaded Src\Vs2012\NktHookLib.sln into the IDE, and started compilation. The file amalgamation.c contains the following includes, which all are not included in the ZIP (neither in the given pathes, nor anywhere else):

include "source\libudis86\decode.h"

include "source\libudis86\extern.h"

include "source\libudis86\syn.h"

include "source\libudis86\types.h"

include "source\libudis86\udint.h"

I also tried the build.bat in the src directory, which gave the same result:

d:\Programme\ExtC\DeviareInProc\Src>build /MSVCVERSION 2012

Microsoft (R) Microsoft Visual Studio 2012 Version 11.0.60610.1.
Copyright (C) Microsoft Corp. All rights reserved.
1>------ Rebuild All started: Project: NktHookLib, Configuration: Debug Win32 ------
1> Compiling assembler code...
1> Assembling: d:\Programme\ExtC\DeviareInProc\Src\Lib\Asm\Helpers_x86.asm
1> Compiling assembler code...
1> Assembling: d:\Programme\ExtC\DeviareInProc\Src\Lib\Asm\RelocatableCode_x86.asm
1> Done!
1> WaitableObjects.cpp
1> ThreadSuspend.cpp
1> ProcessInjection.cpp
1> ProcessEntry.cpp
1> NtSysCallGen.cpp
1> NktHookLibHelpers.cpp
1> NktHookLib.cpp
1> HookEntry.cpp
1> DynamicNtApi.cpp
1> DynamicApiFinder.cpp
1> Generating Code...
1> amalgamation.c
1>d:\programme\extc\deviareinproc\src\lib\libudis86\tables\decode.h(1): fatal error C1083: Cannot open include file: '../source/libudis86/decode.h': No such file or directory
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
Errors detected while compiling project

Looks like I'm missing something, but I have no idea what to do about these missing files. Any help is highly appreciated.

BuildNtSysCalls fail

BuildNtSysCalls function not works on windows 10(14393) HRESULT_FROM_WIN32(NktHookLibHelpers::BuildNtSysCalls(...) return with "31 -
HRESULT_FROM_WIN32(ERROR_GEN_FAILURE) : A device attached to the system is not functioning"

a question

sorry for my english i can not clear understand what difference between
Deviare2 and Deviare-InProc?
i am a c# develper and want to hook managed and unmanaged dll , which one I should Use? just they both can do it

TEST instruction using RIP is not updated in trampoline

I'm getting a crash while hooking the nvapi function. It looks to me like In-Proc is not updating the relative addressing for the 'test' opcode using RIP register.

I'm using the latest version of the In-Proc code, cloned and built successfully.


Here is the original nvapi_QueryInterface function from nvapi64.dll.

00007FFD6C855E00  sub         rsp,28h  
00007FFD6C855E04  test        byte ptr [7FFD6CC52488h],4  
00007FFD6C855E0B  mov         r9d,ecx  
00007FFD6C855E0E  jne         00007FFD6C855E20  
00007FFD6C855E10  cmp         ecx,33C7358Ch  
...

After hooking, we get the debug output from In-Proc:

NktHookLib: Disassembly 0x7FFD6C855E00 -> sub rsp, 0x28
NktHookLib: Disassembly 0x7FFD6C855E04 -> test byte [rip+0x3fc67d], 0x4
NktHookLib: Hook installed. Proc @ 0x7FFD6C855E00 -> 0x7FFD53D19C50 (Stub @ 0x7FFD2C850000) 

The test byte ptr [7FFD6CC52488h],4 is using relative addressing off the RIP register. This is shown in In-Proc disassembly, although the syntax is slightly different in the VS dissassembly.

The function address then looks like (disassembly slightly off after jmp):

00007FFD6C855E00  jmp         00007FFD2C850000  
00007FFD6C855E05  add         eax,3FC67Dh  
00007FFD6C855E0A  add         al,44h  
00007FFD6C855E0C  mov         ecx,ecx  
00007FFD6C855E0E  jne         00007FFD6C855E20  
00007FFD6C855E10  cmp         ecx,33C7358Ch  
00007FFD6C855E16  je          00007FFD6C855E7E  

The trampoline function:

00007FFD2C850000  nop  
00007FFD2C850001  nop  
00007FFD2C850002  nop  
00007FFD2C850003  nop  
00007FFD2C850004  nop  
00007FFD2C850005  nop  
00007FFD2C850006  nop  
00007FFD2C850007  nop  
00007FFD2C850008  push        rdx  
00007FFD2C850009  mov         rdx,7FFD2C860000h  
00007FFD2C850013  test        qword ptr [rdx],101h  
00007FFD2C85001A  jne         00007FFD2C85002B  
00007FFD2C85001C  pop         rdx  
00007FFD2C85001D  jmp         qword ptr [7FFD2C850023h]  
00007FFD2C850023  push        rax  
00007FFD2C850024  pushfq  
00007FFD2C850025  rcl         dword ptr [rbx-3],1  
00007FFD2C850028  jg          00007FFD2C85002A  
00007FFD2C85002A  add         byte ptr [rax],al  
00007FFD2C85002C  sub         rsp,28h           <---- original function start
00007FFD2C850030  test        byte ptr [7FFD2CC4C6B4h],4    <----- Bad instruction ** crash
00007FFD2C850037  jmp         qword ptr [7FFD2C85003Dh]  
00007FFD2C85003D  or          ebx,dword ptr [rsi-7Bh]  
00007FFD2C850040  ins         byte ptr [rdi],dx  00007FFD2C850041  std  
00007FFD2C850042  jg          00007FFD2C850044  
00007FFD2C850044  add         byte ptr [rax],al  
00007FFD2C850046  add         byte ptr [rax],al  

The newly hooked destination function:

void* __cdecl Hooked_nvapi_QueryInterface(
	UINT32 offset)
{
00007FFD48E59BB0  mov         dword ptr [rsp+8],ecx  
00007FFD48E59BB4  push        rdi  
00007FFD48E59BB5  sub         rsp,30h  
00007FFD48E59BB9  mov         rdi,rsp  
00007FFD48E59BBC  mov         ecx,0Ch  
00007FFD48E59BC1  mov         eax,0CCCCCCCCh  
00007FFD48E59BC6  rep stos    dword ptr [rdi]  
00007FFD48E59BC8  mov         ecx,dword ptr [offset]  
00007FFD48E59BCC  lea         rcx,[__40B02ED0_inproc_dx11@cpp (07FFD48EA8071h)]  
00007FFD48E59BD3  call        __CheckForDebuggerJustMyCode (07FFD48E6C9C0h)  
	void* ptr = pOrignvapi_QueryInterface(offset);
00007FFD48E59BD8  mov         ecx,dword ptr [offset]  
00007FFD48E59BDC  call        qword ptr [pOrignvapi_QueryInterface (07FFD48E9E000h)]  
00007FFD48E59BE2  mov         qword ptr [ptr],rax  

	return ptr;
00007FFD48E59BE7  mov         rax,qword ptr [ptr]  
}
00007FFD48E59BEC  add         rsp,30h  
00007FFD48E59BF0  pop         rdi  
00007FFD48E59BF1  ret  

Minimized Cpp code implementing hook:

void* (__cdecl *pOrignvapi_QueryInterface)(
	UINT32 offset
	) = nullptr;

void* __cdecl Hooked_nvapi_QueryInterface(
	UINT32 offset)
{
	void* ptr = pOrignvapi_QueryInterface(offset);

	return ptr;
}

void HookNvapiQueryInterface()
{
	HMODULE hNvapi = LoadLibrary(L"nvapi64.dll");
	FARPROC pQueryInterface = GetProcAddress(hNvapi, "nvapi_QueryInterface");

	nktInProc.SetEnableDebugOutput(TRUE);

	SIZE_T hook_id;
	DWORD dwOsErr = nktInProc.Hook(&hook_id, (void**)&pOrignvapi_QueryInterface,
		pQueryInterface, Hooked_nvapi_QueryInterface, 0);
}

Unable to generate lib file

I am trying to download and compile the source code of WinDbg. Ntkhooklib is required, but the Lib file cannot be generated normally after I compile deviare InProc. The error code is as follows:
Custom build of "..\Lib\Asm\Helpers ×64.asm;.\Lib\Asm\RelocatableCode ×64.asm..\Lib\Asm\RelocatableCodex86.asm" exited with code 1.

The generation error code of WinDbg is as follows:
LNK1181 Unable to open input file:D:\下载\浏览器下载\WingDbg-master\Deviare-InProc\Libs\2015\NktHookLib64_Debug.lib” WingDbg D:\下载\浏览器下载\WingDbg-master\WingDbg\LINK 1

My develop environment is visual studio 2019, with Windows SDK Version10.0

Thank you for your reply.

Doesn't build?

If I do a git clone of the repository, the project structure does not seem to match the code.

Looking just at NktHookLib to be built, I get:

1>..\Lib\libudis86\amalgamation.c(33): fatal error C1083: Cannot open include file: 'source\libudis86\decode.h': No such file or directory

amalgamation.c has includes of:

#include "stdint.h"
#include "source\libudis86\decode.h"
#include "source\libudis86\extern.h"

And the path source\libudis86\ does not exist.

Here is how the hierarchy looks:

image

Decode.h is under tables not source and in any case is under ``libudis86` not above it.

image

Visual Studio 2013.

I'm sure I can get it building, I just figured you might want to know.

Question about Deviare-InProc

Hello Mauro,

Do you know of any Deviare-InProc example code that also writes the "NktProcessMemory" parameters?

I am trying to intercept process calls and then redirect file and registry requests to another drive location (on a network).

Is this possible to do with Deviare-InProc?

hook .NET methods Property error

Hi, While i doing any test with .NET got a "Error type: System.ArgumentNullException"

The test case is the follow:

public class TestClass
{
public String Name;

public Object Value
{
get
{
return "the value";
}
set
{
Name=value;
}
}
}

ClassDetours
{
public String Name_detour;

    public Object Value_detour
    {
        get
        {
            return "answer_detour";
        }

        set
        {
          Name_detour=value;
        }
    }

}
}

o = cHook.Hook(typeof(TestClass), "Value", new Type[] {} ,
typeof(ClassDetours), "Value_detour",new Type[] {});

Regards.

_CrtIsValidHeapPointer(block)

Hi, i have compiled the last code source from Git.

I have tested the new updates for injection. I use visual studio 2015.

In release mode work fine. This error is for NktHookLibHelpers::CreateProcessWithDllW API.

I have compiled the sample code in debug mode for x32. When try do injection got the follow error:


Microsoft Visual C++ Runtime Library

Debug Assertion Failed!

Program: C:\InjectDll.exe
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 888

Expression: _CrtIsValidHeapPointer(block)

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

Regards.

Possible bug in CNktHookLib::EnableHook?

Hi folks,

After trying deviare-inproc, I find it does not work when I use LPHOOK_INFO aHookInfo[] instead of HOOK_INFO aHookInfo[].

And I guess the issue is because of the following line, in CNktHookLib::EnableHook, we should call EnableHookCommon with INTERNALFLAG_HookInfoArrayIsPtr instead of INTERNALFLAG_CallToOriginalIsPtr2Ptr

DWORD CNktHookLib::EnableHook(__in LPHOOK_INFO aHookInfo[], __in SIZE_T nCount, __in BOOL bEnable)
{
return EnableHookCommon(aHookInfo, nCount, bEnable, INTERNALFLAG_CallToOriginalIsPtr2Ptr);
}

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.