Detours is a software package for monitoring and instrumenting API calls on Windows.

Overview

Microsoft Research Detours Package

Detours is a software package for monitoring and instrumenting API calls on Windows. Detours has been used by many ISVs and is also used by product teams at Microsoft. Detours is now available under a standard open source license (MIT). This simplifies licensing for programmers using Detours and allows the community to support Detours using open source tools and processes.

Detours is compatible with the Windows NT family of operating systems: Windows NT, Windows XP, Windows Server 2003, Windows 7, Windows 8, and Windows 10. It cannot be used by Windows Store apps because Detours requires APIs not available to those applications. This repo contains the source code for version 4.0.1 of Detours.

For technical documentation on Detours, see the Detours Wiki. For directions on how to build and run samples, see the samples README.txt file.

Contributing

The Detours repository is where development is done. Here are some ways you can participate in the project:

Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Issues, questions, and feedback

Mailing list for announcements

The detours-announce mailing list is a low-traffic email list for important announcements about the project, such as the availability of new versions of Detours. To join it, send an email to [email protected] with a message body containing only the text SUBSCRIBE DETOURS-ANNOUNCE. To leave it, send an email to [email protected] with a message body containing only the text UNSUBSCRIBE DETOURS-ANNOUNCE.

License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

Comments
  • Feature: Add DetourFindRemotePayload and improve other payload-related methods

    Feature: Add DetourFindRemotePayload and improve other payload-related methods

    Other improvements are:

    • Makes the pcbData parameter in DetourFindPayload and DetourFindPayloadEx optional, so that if an application only needs to search for the presence of a payload, they can ignore the size by passing nullptr.
    • Makes the pvData parameter in DetourCopyPayloadToProcess const, so that a pointer to a const C++ object can be passed instead of the object needing to be const_casted or being non-const.
    • Adds DetourCopyPayloadToProcessEx, which has the same interface than DetourCopyPayloadToProcess, but it returns the address of the payload in the remote module, if the program later wants to write to it.

    Fixes #79

    From basic testing, it seems to work for me. I can apply corrections and add a sample if required (although finding a trivial use case for those APIs would be required)

    enhancement 
    opened by sylveon 20
  • Improved 32bit detection

    Improved 32bit detection

    I noticed that Detours failed to inject a DLL into an IL-only .NET application. I'm pretty sure this worked in the past (right now, this is only triggered on Windows 10 machines but not on Windows 7).

    These two commits resolve the issue. Instead of sticking with the approach of enumerating the modules, I went for a simpler mechanism for detecting if the running process is 32bit or 64bit. This seems to work well. See the commit logs for all the gory details.

    Any feedback would be much appreciated!

    enhancement 
    opened by frerich 15
  • Add IsWow64ProcessHelper function

    Add IsWow64ProcessHelper function

    I needed to compile Detours with VS 2005, which doesn't include IsWow64Process in its Windows SDK, so added a small wrapper function around it using GetModuleHandleW and GetProcAddress.

    Used the example on MSDN as a reference.

    enhancement 
    opened by zeffy 13
  • Can't Seem To Make x64?

    Can't Seem To Make x64?

    Hey Peeps,

    I have VS2017 installed latest updates with the C++ tools installed. I might be missing dependencies however when I open up the Developer Command Prompt and make the project it compiles fine for x86. I did try make all and it certainly tries but when it gets to x64 it seems to error out on: iping_d.obj : error LNK2001: unresolved external symbol _iping_ProxyFileInfo Would I be able to get any advice on this why it pops up when making for x64 and not x86 or am I being so stupid I'm not seeing what is wrong.

    opened by Arefu 11
  • Detouring LoadLibrary at process creation

    Detouring LoadLibrary at process creation

    I'm trying to detour LoadLibrary at process creation: imagine running an exe that references some DLL that isn't in the search path. I need to be able to detour LoadLibrary in that process, early enough that my detour ends up providing the right path to load the missing DLL from.

    I've read the doc for DetourCreateProcessWithDllEx, specifically this paragraph:

    Execution in the process is then resumed. When execution resumes, the Windows process loader will first load the target DLL and then any other DLLs in the application's import table, before calling the application entry point.

    What I can't figure out is how to ensure that my detour DLL not only gets loaded first, but also has its DllMain run before the nt loader tries to resolve the rest of the DLL dependencies.

    Is this possible? Any tips on how to achieve this?

    I also noticed there is a requirement of having an ordinal @1 which I do, but I couldn't find mention of any requirements on the signature of this export, if there are any, and whether this export is supposed to be called? (it doesn't seem like it is called, at least not before all the dependencies are resolved).

    opened by asklar 8
  • Can Detours hook functions defined by myself???

    Can Detours hook functions defined by myself???

    Hi: I've been learning to use Detours recently, but I have a question: Can Detours hook functions defined by myself? For example, there is a function in the header file written by myself: void runcmd(const char *) If I get this header file, is it possible for me to hook this function using Detours? Thank U!

    question needs-author-feedback 
    opened by hiber987 7
  • Allow compilation with MinGW to succeed

    Allow compilation with MinGW to succeed

    What the title says. MinGW doesn't support __try and __except, so it's just defined out here as it doesn't seem there's a better way to handle it.

    Note: Includes #107

    enhancement 
    opened by virtuald 7
  • sn.exe not found

    sn.exe not found

    Window 10 VS2017 15.8.9 SDK 10.0.17763.0 VC++ 15.8 v14.15

    git clone https://github.com/Microsoft/Detours.git
    cd Detours
    nmake
    

    Got an error:

    if not exist ..\..\bin.X64\key.snk sn -k ..\..\bin.X64\key.snk
    'sn' is not recognized as an internal or external command,
    operable program or batch file.
    NMAKE : fatal error U1077: 'if' : return code '0x1'
    Stop.
    NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX64\x64\nmake.exe"' : return code '0x2'
    Stop.
    NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX64\x64\nmake.exe"' : return code '0x2'
    Stop.
    
    opened by TrueBers 7
  • Exception upon hooking the API GetKeyboardState

    Exception upon hooking the API GetKeyboardState

    I'm trying to hook the WINAPI GetKeyboardState but the process throws an exception as soon I type something:

    detours

    Commenting on these lines I still get an exception:

    //lpKeyState[VK_CONTROL] = 0;
    //lpKeyState[VK_LCONTROL] = 0;
    

    I have tested hooking other APIs and they did work 'correctly'. I'm doing something wrong?

        #include "pch.h"
        #include "detours.h"
        #include "dllmain.h"
        
        
        BOOL(WINAPI* GetKeyboardState_Hook)(PBYTE) = GetKeyboardState;
        
        BOOL WINAPI HookedGetKeyboardState(PBYTE& lpKeyState) {
        
        	if (lpKeyState == NULL)
        		return 1;
        
        	//lpKeyState[VK_CONTROL] = 0;
        	//lpKeyState[VK_LCONTROL] = 0;
        
        	return GetKeyboardState(lpKeyState);
        }
        
        
        
        BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
        {
            switch (ul_reason_for_call)
            {
            case DLL_PROCESS_ATTACH:
            {
                Sleep(1000);
                DetourTransactionBegin();
                DetourUpdateThread(GetCurrentThread());
                DetourAttach(&(PVOID&)GetKeyboardState_Hook, HookedGetKeyboardState);
        
                LONG lError = DetourTransactionCommit();
                if (lError != NO_ERROR) {
                    MessageBox(HWND_DESKTOP, L"Failed to detour", L"", MB_OK);
                    return FALSE;
                }
            }
            break;
        
            case DLL_PROCESS_DETACH:
            {
                DetourTransactionBegin();
                DetourUpdateThread(GetCurrentThread());
                DetourDetach(&(PVOID&)GetKeyboardState_Hook, HookedGetKeyboardState);
        
                LONG lError = DetourTransactionCommit();
                if (lError != NO_ERROR) {
                    MessageBox(HWND_DESKTOP, L"DLL_PROCESS_DETACH", L"", MB_OK);
                    return FALSE;
                }
            }
            break;
            }
        
            return TRUE;
        }
    
    
    question 
    opened by derricck 6
  • Fix: Eliminate possible deadlock related to memory allocation on global heap

    Fix: Eliminate possible deadlock related to memory allocation on global heap

    Addresses https://github.com/microsoft/Detours/issues/70 by utilizing the HeapLock/HeapUnlock APIs as discussed in the issue.

    Microsoft Reviewers: Open in CodeFlow
    opened by adams85 6
  • Enable compilation time configuration of maximum section count and expose DetourIsFunctionImported

    Enable compilation time configuration of maximum section count and expose DetourIsFunctionImported

    A few minor changes:

    1. Expose detour_is_imported via a new public function DetourIsFunctionImported
    2. Make certain runtime checks happy by masking pbTarget before casting to smaller type
    3. Enable user to compile with a different number of supported section headers (leaves default at 32)
    Microsoft Reviewers: Open in CodeFlow
    opened by JohnMcPMS 6
  • API Refernce on Home Page of Wiki doesn't redirect properly

    API Refernce on Home Page of Wiki doesn't redirect properly

    Describe the bug When I click on Wiki then API Reference I expect to see it, but I get a the awesome "Not Found" page.

    It takes me here: https://github.com/microsoft/Detours/Reference Not here: https://github.com/microsoft/Detours/wiki/Reference

    bug 
    opened by Arefu 0
  • update m_SectionHeaders to use configurable limit from !225

    update m_SectionHeaders to use configurable limit from !225

    brings CImage in line with DETOUR_EXE_RESTORE and better aligns Microsoft documentation describing limit of 96 sections

    Addresses https://github.com/microsoft/Detours/issues/268

    Microsoft Reviewers: Open in CodeFlow
    opened by mikewintersjr 0
  • Bug: DetourOpenBinary doesn't accept valid PEs because of incorrect limit on sections

    Bug: DetourOpenBinary doesn't accept valid PEs because of incorrect limit on sections

    Bug Description: Detours allocates IMAGE_NUMBEROF_DIRECTORY_ENTRIES (i.e., 16) entries in the m_SectionHeaders array (https://github.com/microsoft/Detours/blob/master/src/image.cpp#L260). 16 is the correct limit for the DataDirectory[] member of the IMAGE_OPTIONAL_HEADERs. However, Microsoft documentation specifies that the Windows loader can accept up to 96 sections (https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#coff-file-header-object-and-image). I believe this discrepancy is a bug, and it is causing some real world issues with DetourOpenBinary.

    PEs compiled with mingw will contain DWARF sections unless the user strips the binary. In practice, there appear to be 8 DWARF sections included by mingw. For x64 binaries, there are also the .pdata and .xdata sections for exception information. On x64 PE binaries compiled with mingw gcc 7.3, there are 17 sections by default. As a result, when DetourOpenBinary is called, it fails in CImage::Read (https://github.com/microsoft/Detours/blob/master/src/image.cpp#L1088).

    While stripping the DWARF sections from the binary is a workaround, I believe the appropriate solution is to bring the Detours sections limit in line with published Microsoft documentation and allow up to 96 sections. Looking through winnt.h there doesn't appear to be a good macro for this. Is anyone aware of an existing variable/macro that could be used for this instead of a magic number?

    Command-line test case

    C:\> x86_64-w64-mingw-gcc helloworld.c -o helloworld.exe
    C:\> x86_64-w64-mingw-gcc -shared library.c -o library.dll
    C:\> setdll64.exe /d:library.dll helloworld.exe
    Adding library.dll to binary files.
      helloworld.exe:
    DetourBinaryOpen failed: 192
    
    C:\> x86_64-w64-mingw-strip helloworld.exe
    C:\> setdll64.exe /d:library.dll helloworld.exe
    Adding library.dll to binary files.
      helloworld.exe:
        library.dll
        KERNEL32.dll -> KERNEL32.dll
    

    Detours version Version 4.0.1 of Detours (https://github.com/microsoft/Detours/commit/734ac64)

    bug 
    opened by mikewintersjr 0
  • Divide by zero in 'cping.cpp'

    Divide by zero in 'cping.cpp'

    Building and running the sample client bin.X64\cping.exe /i /l localhost, I got a divide by zero exception at this line:

    s_rllCycles[E_DCOM] /= s_rllCounts[E_DCOM];
    

    Not sure why. Some issue with incorrect CPU-speed calculation? But I patched it like this:

    --- a/samples/cping/cping.cpp 2022-12-24 09:26:38
    +++ b/samples/cping/cping.cpp 2022-12-24 12:55:27
    @@ -384,14 +384,19 @@
         DumpCycles(E_NET);
     #endif
    
    -    s_rllCycles[E_DCOM] /= s_rllCounts[E_DCOM];
    -    s_rllCycles[E_RPC] /= s_rllCounts[E_DCOM];
    -    s_rllCycles[E_UDP] /= s_rllCounts[E_DCOM];
    -    s_rllCycles[E_NET] /= s_rllCounts[E_DCOM];
    -    s_rllTotals[E_DCOM] /= s_rllCounts[E_DCOM];
    -    s_rllTotals[E_RPC] /= s_rllCounts[E_DCOM];
    -    s_rllTotals[E_UDP] /= s_rllCounts[E_DCOM];
    -    s_rllTotals[E_NET] /= s_rllCounts[E_DCOM];
    +#define SAFE_DIV(res, div) do {             \
    +                             if (div)       \
    +                                res /= div; \
    +                           } while (0)
    +
    +    SAFE_DIV (s_rllCycles[E_DCOM], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllCycles[E_RPC], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllCycles[E_UDP], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllCycles[E_NET], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllTotals[E_DCOM], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllTotals[E_RPC], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllTotals[E_UDP], s_rllCounts[E_DCOM]);
    +    SAFE_DIV (s_rllTotals[E_NET], s_rllCounts[E_DCOM]);
    
    
    bug 
    opened by gvanem 0
  • Fix error process of GetQueuedCompletionStatus

    Fix error process of GetQueuedCompletionStatus

    PR for Bug: Error process of GetQueuedCompletionStatus in syelogd.cpp. https://github.com/microsoft/Detours/issues/264

    Microsoft Reviewers: Open in CodeFlow
    opened by qieziting 0
Releases(v4.0.1)
  • v4.0.1(Apr 16, 2018)

    Detours 4.0.1 supports x86, x64 and other Windows-compatible processors (IA64 and ARM). It includes support for either 32-bit or 64-bit processes.

    The source code is identical to Build 343 of Detours 3.0. Detours Build 338 and later fix a security vulnerability that has been identified in releases of Detours before 3.0 Build 334.

    Source code(tar.gz)
    Source code(zip)
Owner
Microsoft
Open source projects and samples from Microsoft
Microsoft
An R package for monitoring the trend of daily COVID-19 positive cases in Tokyo

R Package TokyoCovidMonitor A simple RStan-based package for monitoring daily COVID-19 positive cases in Tokyo Overview This package offers a simple m

Takashi J. OZAKI 14 Mar 15, 2022
Add virtual monitors to your windows 10 device! Works with Oculus software, obs, and any desktop sharing software

License MIT and CC0 or Public Domain, whichever is least restrictive -- Use it AS IS - NO IMPLICIT OR EXPLICIT warranty This may break your computer,

Rashi Abramson 230 Jan 6, 2023
Operating system project - implementing scheduling algorithms and some system calls for XV6 OS

About XV6 xv6 is a modern reimplementation of Sixth Edition Unix in ANSI C for multiprocessor x86 and RISC-V systems.

Amirhossein Rajabpour 22 Dec 22, 2022
A refactored Proof-of-concept originally developed in 2017 to print all function calls with their arguments data types and values using Ptrace during program execution.

print-function-args-debugger A refactored Proof-of-concept originally developed in 2017 to print all function calls with their arguments data types an

*finixbit 15 Jun 17, 2022
Obfuscate calls to imports by patching in stubs. ICO works on both X86 and X64 binaries.

ICO adds a new section into the image, then begins building stubs for each import that uses a extremely basic routine to decrypt an RVA and places them into the section.

null 43 Dec 15, 2022
Shell program written in C to implement various system calls, with support of executing commands, output redirection and signals.

Use ./shell command to start the shell. $<space>path/executable to run the executable(please specify the path without beginning it with "/"). Eg. type

Ayuj Panchal 1 Nov 15, 2021
Automatic plant growing and monitoring system using Arduino

Plant Automatic Growing and Monitoring System Roadmap Read sensors Ambient Temperature Ambient Moisture Ambient Light Soil Moisture LCD with custom ch

Diego Santos Seabra 1 Oct 7, 2021
SQL powered operating system instrumentation, monitoring, and analytics.

osquery osquery is a SQL powered operating system instrumentation, monitoring, and analytics framework. Available for Linux, macOS, Windows, and FreeB

osquery 19.8k Jan 3, 2023
Linux System Optimizer and Monitoring - https://oguzhaninan.github.io/Stacer-Web

Linux System Optimizer and Monitoring Reviews Required Packages curl, systemd PPA Repository (for ubuntu) sudo add-apt-repository ppa:oguzhaninan/stac

Oguzhan Inan 8.2k Dec 31, 2022
Malloc geiger is a hook for malloc that plays geiger counter blips in proportion to the amount of calls to malloc as a way of knowing what an application does

Malloc Geiger Malloc geiger is a hook for malloc that plays geiger counter blips in proportion to the amount of calls to malloc as a way of knowing wh

David Larsson 321 Dec 19, 2022
Turn your ESP32 into a easy to use micro web-server allowing to interact with any GPIO by simple http(s) calls.

WebhooksTriggeredESP32WiFi Turn your ESP32 into an easy to use and manage wireless micro web-server allowing it to process reliably and asynchronouly

JayDeLux 3 Nov 24, 2022
Single-Cell Li-Ion Battery Charger with Monitoring

TinyCharger - Single Cell Li-Ion Battery Charger with Monitoring TinyCharger is an ATtiny25/45/85-based, single-cell Li-ion battery charger with selec

Stefan Wagner 26 Dec 30, 2022
multispectral monitoring of a sourdough starter; esp32 eink module, scd30 co2 sensor, vl6180 distance sensor

EINK STARTER MONITOR See full blogpost here Tracks height of starter with a VL6180 i2c distance sensor, and CO2/temperature/humidity with an SCD30. A

AKA 15 Feb 16, 2022
Phantom Attack: Evading System Call Monitoring

Phantom attack is a collection of attacks that evade Linux system call monitoring. A user mode program does not need any special privileges or capabilities to reliably evade system call monitoring using Phantom attack by exploiting insecure tracing implementations.

Rex Guo 62 Dec 7, 2022
Monitoring Radeon GPU temperature on macOS

RadeonSensor - Kext and Gadget to show Radeon GPU temperature on macOS The kext is based on FakeSMCs RadeonMonitor to provide GPU temperature to a ded

Aluveitie 192 Jan 5, 2023
jvm-monitor is a lightweight monitoring tool that logs all the local variables whenever exceptions occur.

jvm-monitor jvm-monitor is a Java agent attached to a Java VM (virtual machine), which logs all the local variables when exceptions occur. Rationales

Barosl Lee 13 Nov 21, 2021
A software serial driver package by using the hardware timer capture / comparison functionality.

Soft serial 1.简介 Soft serial 是利用硬件定时器捕获/比较功能实现软件模拟串口的软件包。 1.1目录结构 Soft serial 软件包目录结构如下所示: soft_serial ├───inc // 头文件目录 │

齐永忠 2 Jul 14, 2022
OpenFOAM is a free, open source computational fluid dynamics (CFD) software package

acousticStreamingFoam About OpenFOAM OpenFOAM is a free, open source computational fluid dynamics (CFD) software package released by the OpenFOAM Foun

Bruno 3 Oct 28, 2022
Simple Software Application Package Installer for CachyOS which helps setting up & installing applications

cachyos-packageinstaller Simple Software Application Package Installer. Requirements C++20 feature required (tested with GCC 11.1.0 and Clang 13(clang

CachyOS 3 Jul 1, 2022