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
  • 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
  • Bug: Error process of GetQueuedCompletionStatus in syelogd.cpp.

    Bug: Error process of GetQueuedCompletionStatus in syelogd.cpp.

    Describe the bug When I use syslog to test my project, I found there is a bug in error process of GetQueuedCompletionStatus in syslogd.cpp (line 334). The else branch will never be triggered. And in this logic if client closed a piep, a work thread will exit.

           if (!b || lpo == NULL) {
                fKeepLooping = FALSE;
                MyErrExit("GetQueuedCompletionState");
                break;
            }
            else if (!b) {
                if (pClient) {
                    if (GetLastError() == ERROR_BROKEN_PIPE) {
                        LogMessageV(SYELOG_SEVERITY_INFORMATION, "Client closed pipe.");
                    }
                    else {
                        LogMessageV(SYELOG_SEVERITY_ERROR,
                                    "GetQueuedCompletionStatus failed %d [%p]",
                                    GetLastError(), pClient);
                    }
                    CloseConnection(pClient);
                }
                continue;
            }
    

    Expected behavior I thought thread will exit only when both return value is false and lpo is NULL, as description in doc of GetQueuedCompletionStatus:

    If a call to GetQueuedCompletionStatus fails because the completion port handle associated with it is closed while the call is outstanding, the function returns FALSE, *lpOverlapped will be NULL, and GetLastError will return ERROR_ABANDONED_WAIT_0.

    I will create a PR for it.

    Detours version

    current master

    bug 
    opened by qieziting 0
  • DetourAttach ERROR

    DetourAttach ERROR

    1667642974117

    Describe the bug A clear and concise description of what the bug is. Please check that you've read the guidelines for submitting a bug report in the Bug Reports section of the FAQ.

    Command-line test case

    C:\Temp>type repro.cpp
    #include <iostream>
    #include <windows.h>
    #include <detours.h>
    
    void main() {
        // Replace this program with one demonstrating your actual bug report,
        // along with the following compilation command. Please leave compiler
        // version banners in the output (don't use /nologo), and include output
        // of your test program, if any.
        std::cout << "Test Case Result: ";
        if (DetourIsHelperProcess()) {
            std::cout << "Fail\n";
        } else {
            std::cout << "Pass\n";
        }
    }
    
    C:\Temp>cl.exe /EHsc /W4 /WX .\repro.cpp -I. ..\lib.X64\detours.lib
    Microsoft (R) C/C++ Optimizing Compiler Version 19.27.29111 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    repro.cpp
    Microsoft (R) Incremental Linker Version 14.27.29111.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:repro.exe
    repro.obj
    ..\lib.X64\detours.lib
    
    C:\Temp>.\repro.exe
    Test Case Result: Pass
    

    Expected behavior A clear and concise description of what you expected to happen. Alternatively, include static_assert or assert lines in your test case above whose failure clearly indicates the problem.

    Detours version

    • Option 1: Release version

      • Displayed on the releases page: https://github.com/microsoft/Detours/releases/
      • Example:
        Version 4.0.1 of Detours
        
    • Option 2: git commit hash

      • Example:
        https://github.com/microsoft/Detours/commit/2195148
        

    Additional context Add any other context about the problem here.

    bug 
    opened by kouzhudong 0
  • Enable Detours to be used without allocating or freeing memory while threads are suspended.

    Enable Detours to be used without allocating or freeing memory while threads are suspended.

    Detours uses new and delete while threads are suspended. This can cause deadlocks if the suspended thread has locked a mutex in the heap. (See issue #70.) Additionally, when AppVerifier is enabled, VirtualFree and VirtualAlloc can be hooked by AppVerifier. These hooks do memory operations on the heap internally. The deadlocks are easier to hit when AppVerifier is enabled.

    Back in 2014, I worked with https://github.com/KnicKnic on a fix for this. We also consulted with https://github.com/galenh on the API design changes. I checked in the fix to a copy of Detours in the Windows repository within Microsoft, but this wasn't propagated back to the Detours master sources. I'm now bringing a cleaned-up version of the fix through GitHub so my code in the Windows repo can switch to the open-source version of Detours.

    The fix makes it so all calls to free and VirtualFree are done after all calls to ResumeThread in DetourTransactionAbort and DetourTransactionCommit. However, to fully avoid deadlocks, the user needs to also do the following:

    • Switch from DetourUpdateThread to the new DetourUpdateThreadPreallocated API.
    • Make all calls to DetourAttach, DetourAttachEx, and DetourDetach before calling DetourUpdateThreadPreallocated in a given transaction.
    • Avoid allocating or freeing any memory in user code between the first call to DetourUpdateThreadPreallocated and the call to DetourTransactionAbort or DetourTransactionCommit.

    If you follow those rules, you will avoid memory allocations while threads are suspended in the process.

    The DetourUpdateThreadPreallocated API is like DetourUpdateThread except the user passes in a DETOUR_THREAD_DATA struct that they allocated themselves ahead of time. The user is responsible for freeing the memory after aborting or committing the transaction. In my code, I store the DETOUR_THREAD_DATA instances in a std::vector that I resize ahead of time in order to front-load the allocation before starting the detour transaction.

    Microsoft Reviewers: Open in CodeFlow
    opened by PDeets 3
  • DetourEnumerateImports() needs a thunk for pfImportFile

    DetourEnumerateImports() needs a thunk for pfImportFile

    Description

    DetourEnumerateImports() internally invokes DetourEnumerateImportsEx() and uses an intermediate thunk callback to wrap pfImportFunc. Unfortunately it does not also do the same for pfImportFile, so the client callback ends up getting a pointer to &context instead of the client-supplied pContext. It's easy enough to fix by adding a similar intermediate thunk callback to wrap pfImportFile.

    https://github.com/microsoft/Detours/blob/734ac64899c44933151c1335f6ef54a590219221/src/modules.cpp#L667

    Version https://github.com/microsoft/Detours/commit/734ac64899c44933151c1335f6ef54a590219221

    bug 
    opened by luke727 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
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 Oct 24, 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 40 Oct 12, 2022
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
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
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.5k Nov 21, 2022
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.1k Nov 19, 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 221 Nov 26, 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 25 Oct 3, 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 52 Nov 11, 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 179 Nov 26, 2022
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
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 320 Nov 25, 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 4 Jun 1, 2022
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