├── .gitattributes ├── tests ├── dllmain_msg_x86.zip └── Windows 7 Calculator.zip ├── src ├── injector.ixx ├── injector_interface.ixx ├── utility │ ├── windows_error.ixx │ └── injection.ixx ├── running_injector.ixx ├── main.cpp └── startup_injector.ixx ├── CITATION.cff ├── docs └── badges │ ├── C++.svg │ ├── License-MIT.svg │ └── Microsoft-Windows.svg ├── LICENSE ├── README-CN.md ├── .clang-format ├── README.md └── .gitignore /.gitattributes: -------------------------------------------------------------------------------- 1 | *.ixx linguist-language=C++ 2 | -------------------------------------------------------------------------------- /tests/dllmain_msg_x86.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhuagenborn/Windows-DLL-Injector/HEAD/tests/dllmain_msg_x86.zip -------------------------------------------------------------------------------- /tests/Windows 7 Calculator.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhuagenborn/Windows-DLL-Injector/HEAD/tests/Windows 7 Calculator.zip -------------------------------------------------------------------------------- /src/injector.ixx: -------------------------------------------------------------------------------- 1 | export module injector; 2 | 3 | export import injector_interface; 4 | export import running_injector; 5 | export import startup_injector; -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | authors: 3 | - family-names: Chen 4 | given-names: Zhenshuo 5 | orcid: https://orcid.org/0000-0003-2091-4160 6 | - family-names: Liu 7 | given-names: Guowen 8 | orcid: https://orcid.org/0000-0002-8375-5729 9 | title: Windows Dynamic-Link Library Injector 10 | date-released: 2022-05-21 11 | url: https://github.com/Zhuagenborn/Windows-DLL-Injector -------------------------------------------------------------------------------- /src/injector_interface.ixx: -------------------------------------------------------------------------------- 1 | /** 2 | * @file injector_interface.ixx 3 | * @brief The interface of a dynamic-link library injector. 4 | * 5 | * @author Chen Zhenshuo (chenzs108@outlook.com) 6 | * @author Liu Guowen (liu.guowen@outlook.com) 7 | * @version 1.0 8 | * @date 2020-10-09 9 | * @par GitHub 10 | * https://github.com/Zhuagenborn 11 | */ 12 | 13 | export module injector_interface; 14 | 15 | //! The interface of a dynamic-link library injector. 16 | export class Injector { 17 | public: 18 | virtual ~Injector() = default; 19 | 20 | //! Injection. 21 | virtual void Inject() = 0; 22 | }; -------------------------------------------------------------------------------- /src/utility/windows_error.ixx: -------------------------------------------------------------------------------- 1 | /** 2 | * @file windows_error.ixx 3 | * @brief Windows error handling. 4 | * 5 | * @author Chen Zhenshuo (chenzs108@outlook.com) 6 | * @author Liu Guowen (liu.guowen@outlook.com) 7 | * @version 1.0 8 | * @date 2020-10-09 9 | * @par GitHub 10 | * https://github.com/Zhuagenborn 11 | * 12 | * @see https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes 13 | */ 14 | 15 | module; 16 | #include 17 | 18 | #include 19 | export module utility.windows_error; 20 | 21 | //! Throw a @p std::system_error exception containing the last-error. 22 | export [[noreturn]] void ThrowLastError(); 23 | 24 | module : private; 25 | 26 | [[noreturn]] void ThrowLastError() { 27 | throw std::system_error{ static_cast(GetLastError()), std::system_category() }; 28 | } -------------------------------------------------------------------------------- /docs/badges/C++.svg: -------------------------------------------------------------------------------- 1 | C++C++ -------------------------------------------------------------------------------- /docs/badges/License-MIT.svg: -------------------------------------------------------------------------------- 1 | License: MITLicenseMIT -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Zhuagenborn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /docs/badges/Microsoft-Windows.svg: -------------------------------------------------------------------------------- 1 | Microsoft: WindowsMicrosoftWindows -------------------------------------------------------------------------------- /README-CN.md: -------------------------------------------------------------------------------- 1 | # *Windows* Dynamic-Link Library Injector 2 | 3 | ![C++](docs/badges/C++.svg) 4 | [![Windows](docs/badges/Microsoft-Windows.svg)](https://www.microsoft.com/en-ie/windows) 5 | ![License](docs/badges/License-MIT.svg) 6 | 7 | ## 翻译 8 | 9 | - [English](https://github.com/Zhuagenborn/Windows-DLL-Injector/blob/main/README.md) 10 | - [简体中文](https://github.com/Zhuagenborn/Windows-DLL-Injector/blob/main/README-CN.md) 11 | 12 | ## 简介 13 | 14 | ***Dll-Injector***是一款使用*C++20*编写的***Windows*动态链接库**注入工具。它可以通过搜索窗口标题将`.dll`文件注入至运行中的进程,或在创建新进程时进行注入。 15 | 16 | ## 开始 17 | 18 | **警告** 19 | 20 | > 项目不包含工程配置文件,源代码可以使用*Visual Studio 2022*手动构建。 21 | 22 | ### 前置条件 23 | 24 | 该项目需要编译为***Windows* 32位**版本。 25 | 26 | ## 使用 27 | 28 | ```console 29 | Dll-Injector [-f | ] 30 | ``` 31 | 32 | **将动态链接库注入至运行中的进程** 33 | 34 | 对运行中的进程进行注入时,需要指定目标进程的*窗口标题*和`.dll`文件的*路径*。如果`dll-path`参数是一个相对路径,则其必须相对于`Dll-Injector.exe`文件。 35 | 36 | ```console 37 | Dll-Injector 38 | ``` 39 | 40 | 例如,将`dllmain_msg.dll`(假定其位于*Dll-Injector*目录)注入*Windows Calculator*进程: 41 | 42 | ```console 43 | Dll-Injector Calculator dllmain_msg.dll 44 | ``` 45 | 46 | **创建新进程时进行注入** 47 | 48 | 若需要在创建新进程时进行注入,必须先设置`-f`选项,然后再指定目标进程和`.dll`文件的*路径*。如果`dll-path`参数是一个相对路径,则其必须相对于进程文件。 49 | 50 | ```console 51 | Dll-Injector -f 52 | ``` 53 | 54 | ## 文档 55 | 56 | 代码注释采用[*Doxygen*](https://www.doxygen.nl)规范。 57 | 58 | ### 类图 59 | 60 | ```mermaid 61 | classDiagram 62 | 63 | class Injector { 64 | <> 65 | +Inject() 66 | } 67 | 68 | class RunningInjector { 69 | -string win_title 70 | -string dll_path 71 | } 72 | 73 | Injector <|.. RunningInjector 74 | 75 | class StartupInjector { 76 | -string proc_path 77 | -string dll_path 78 | 79 | +Running() bool 80 | +Terminate() 81 | } 82 | 83 | Injector <|.. StartupInjector 84 | ``` 85 | 86 | ## 许可证 87 | 88 | 使用*MIT*协议,请参考`LICENSE`文件。 -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | 3 | Standard: Latest 4 | 5 | ColumnLimit: 80 6 | 7 | DeriveLineEnding: false 8 | UseCRLF: false 9 | 10 | AlignAfterOpenBracket: Align 11 | AlignConsecutiveAssignments: false 12 | AlignConsecutiveDeclarations: false 13 | AlignConsecutiveMacros: false 14 | AlignEscapedNewlines: Left 15 | AlignTrailingComments: true 16 | AlignOperands: true 17 | 18 | AllowAllArgumentsOnNextLine: true 19 | AllowAllConstructorInitializersOnNextLine: true 20 | AllowAllParametersOfDeclarationOnNextLine: true 21 | AllowShortBlocksOnASingleLine: Never 22 | AllowShortCaseLabelsOnASingleLine: false 23 | AllowShortFunctionsOnASingleLine: Empty 24 | AllowShortIfStatementsOnASingleLine: Never 25 | AllowShortLambdasOnASingleLine: Inline 26 | AllowShortLoopsOnASingleLine: false 27 | 28 | AlwaysBreakAfterReturnType: None 29 | AlwaysBreakBeforeMultilineStrings: false 30 | AlwaysBreakTemplateDeclarations: Yes 31 | BinPackArguments: true 32 | BinPackParameters: true 33 | BreakBeforeBinaryOperators: NonAssignment 34 | BreakBeforeBraces: Attach 35 | BreakBeforeTernaryOperators: true 36 | BreakConstructorInitializers: AfterColon 37 | BreakInheritanceList: AfterColon 38 | BreakStringLiterals: true 39 | CompactNamespaces: false 40 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 41 | DerivePointerAlignment: false 42 | PointerAlignment: Left 43 | 44 | IncludeBlocks: Preserve 45 | IndentCaseLabels: true 46 | IndentGotoLabels: true 47 | IndentPPDirectives: BeforeHash 48 | IndentWrappedFunctionNames: false 49 | NamespaceIndentation: None 50 | AccessModifierOffset: -4 51 | IndentWidth: 4 52 | ContinuationIndentWidth: 4 53 | ConstructorInitializerIndentWidth: 4 54 | TabWidth: 4 55 | UseTab: Never 56 | 57 | KeepEmptyLinesAtTheStartOfBlocks: false 58 | MaxEmptyLinesToKeep: 2 59 | ReflowComments: false 60 | FixNamespaceComments: true 61 | SortIncludes: true 62 | SortUsingDeclarations: true 63 | 64 | SpaceAfterCStyleCast: false 65 | Cpp11BracedListStyle: false 66 | SpaceAfterLogicalNot: false 67 | SpaceAfterTemplateKeyword: true 68 | SpaceBeforeAssignmentOperators: true 69 | SpaceBeforeCpp11BracedList: false 70 | SpaceBeforeCtorInitializerColon: true 71 | SpaceBeforeInheritanceColon: true 72 | SpaceBeforeParens: ControlStatements 73 | SpaceBeforeRangeBasedForLoopColon: true 74 | SpaceInEmptyBlock: false 75 | SpaceInEmptyParentheses: false 76 | SpacesBeforeTrailingComments: 2 77 | SpacesInAngles: false 78 | SpacesInCStyleCastParentheses: false 79 | SpacesInConditionalStatement: false 80 | SpacesInContainerLiterals: false 81 | SpacesInParentheses: false 82 | SpacesInSquareBrackets: false -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # *Windows* Dynamic-Link Library Injector 2 | 3 | ![C++](docs/badges/C++.svg) 4 | [![Windows](docs/badges/Microsoft-Windows.svg)](https://www.microsoft.com/en-ie/windows) 5 | ![License](docs/badges/License-MIT.svg) 6 | 7 | ## Languages 8 | 9 | - [English](https://github.com/Zhuagenborn/Windows-DLL-Injector/blob/main/README.md) 10 | - [简体中文](https://github.com/Zhuagenborn/Windows-DLL-Injector/blob/main/README-CN.md) 11 | 12 | ## Introduction 13 | 14 | ***Dll-Injector*** is a ***Windows* dynamic-link library** injection tool written in *C++20*. It can inject a `.dll` file into a running process by searching its window title or create a new process with an injection. 15 | 16 | ## Getting Started 17 | 18 | **Warning** 19 | 20 | > The project does not contain building configuration files, the source code can be built manually with *Visual Studio 2022*. 21 | 22 | ### Prerequisites 23 | 24 | The project need to configure on/for ***Windows* 32-bit**. 25 | 26 | ## Usage 27 | 28 | ```console 29 | Dll-Injector [-f | ] 30 | ``` 31 | 32 | **Inject a Dynamic-Link Library Into a Running Process** 33 | 34 | To inject a `.dll` file into a running process, you need to specify the *window title* of the target process and the *path* of the `.dll` file. If `dll-path` is a relative path, it must be relative to the `Dll-Injector.exe`. 35 | 36 | ```console 37 | Dll-Injector 38 | ``` 39 | 40 | For example, inject the `dllmain_msg.dll` (assume it is in the same directory as *Dll-Injector*) into *Windows Calculator*: 41 | 42 | ```console 43 | Dll-Injector Calculator dllmain_msg.dll 44 | ``` 45 | 46 | **Create a New Process With an Injection** 47 | 48 | To create a new process with an injection, you must enable the `-f` option firstly and then specify the *paths* of the target process and the `.dll` file. If `dll-path` is a relative path, it must be relative to the process file. 49 | 50 | ```console 51 | Dll-Injector -f 52 | ``` 53 | 54 | ## Documents 55 | 56 | Code comments follow [*Doxygen*](https://www.doxygen.nl) specification. 57 | 58 | ### Class Diagram 59 | 60 | ```mermaid 61 | classDiagram 62 | 63 | class Injector { 64 | <> 65 | +Inject() 66 | } 67 | 68 | class RunningInjector { 69 | -string win_title 70 | -string dll_path 71 | } 72 | 73 | Injector <|.. RunningInjector 74 | 75 | class StartupInjector { 76 | -string proc_path 77 | -string dll_path 78 | 79 | +Running() bool 80 | +Terminate() 81 | } 82 | 83 | Injector <|.. StartupInjector 84 | ``` 85 | 86 | ## License 87 | 88 | Distributed under the *MIT License*. See `LICENSE` for more information. -------------------------------------------------------------------------------- /src/utility/injection.ixx: -------------------------------------------------------------------------------- 1 | /** 2 | * @file injection.ixx 3 | * @brief Some injection tools. 4 | * 5 | * @author Chen Zhenshuo (chenzs108@outlook.com) 6 | * @author Liu Guowen (liu.guowen@outlook.com) 7 | * @version 1.0 8 | * @date 2020-10-09 9 | * @par GitHub 10 | * https://github.com/Zhuagenborn 11 | */ 12 | 13 | module; 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | #include 21 | #include 22 | export module utility.injection; 23 | 24 | import utility.windows_error; 25 | 26 | //! The function type for closing a handle. 27 | export using HandleCloser = std::function; 28 | 29 | //! A default function for closing a handle. 30 | export HandleCloser default_handle_closer{ [](HANDLE* const handle) noexcept { 31 | assert(handle != nullptr); 32 | 33 | if (*handle != nullptr) { 34 | CloseHandle(*handle); 35 | } 36 | } }; 37 | 38 | //! A default function for closing a handle and deleting its memory. 39 | export HandleCloser default_handle_deleter{ [](HANDLE* const handle) noexcept { 40 | assert(handle != nullptr); 41 | 42 | default_handle_closer(handle); 43 | delete handle; 44 | } }; 45 | 46 | /** 47 | * @brief Allocate memory within a process. 48 | * 49 | * @param proc The handle of a process. 50 | * @param size The required size. 51 | * @return The base address of the memory. 52 | */ 53 | export void* AllocRemoteMemory(HANDLE proc, std::size_t size); 54 | 55 | /** 56 | * @brief Create a dynamic-link library injection thread within a process. 57 | * 58 | * @param proc The handle of a process. 59 | * @param size The path of a dynamic-link library. 60 | * @param wait Whether to wait for the thread to end. 61 | */ 62 | export void CreateRemoteInjectThread(HANDLE proc, 63 | std::string_view dll_path, 64 | bool wait); 65 | 66 | 67 | module : private; 68 | 69 | void* AllocRemoteMemory(const HANDLE proc, const std::size_t size) { 70 | assert(proc != nullptr); 71 | assert(size != 0); 72 | 73 | // The memory cannot be deleted. Otherwise, the target process might crash. 74 | if (const auto buffer{ VirtualAllocEx( 75 | proc, nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; 76 | buffer == nullptr) { 77 | ThrowLastError(); 78 | } else { 79 | return buffer; 80 | } 81 | } 82 | 83 | 84 | void CreateRemoteInjectThread(const HANDLE proc, 85 | const std::string_view dll_path, 86 | const bool wait) { 87 | assert(proc != nullptr); 88 | assert(!dll_path.empty()); 89 | 90 | const auto dll_path_size{ dll_path.length() + 1 }; 91 | const auto buffer{ AllocRemoteMemory(proc, dll_path_size) }; 92 | if (!WriteProcessMemory(proc, buffer, dll_path.data(), dll_path_size, 93 | nullptr)) { 94 | ThrowLastError(); 95 | } 96 | 97 | const auto kernel32{ GetModuleHandleA("kernel32.dll") }; 98 | if (kernel32 == nullptr) { 99 | ThrowLastError(); 100 | } 101 | 102 | const auto load_library{ GetProcAddress(kernel32, "LoadLibraryA") }; 103 | if (load_library == nullptr) { 104 | ThrowLastError(); 105 | } 106 | 107 | HANDLE thread{ nullptr }; 108 | std::unique_ptr thread_raii{ &thread, 109 | default_handle_closer }; 110 | if (thread = CreateRemoteThread( 111 | proc, nullptr, 0, 112 | reinterpret_cast(load_library), buffer, 0, 113 | nullptr); 114 | thread == nullptr) { 115 | ThrowLastError(); 116 | } 117 | 118 | if (wait) { 119 | if (WaitForSingleObject(thread, INFINITE) == WAIT_FAILED) { 120 | ThrowLastError(); 121 | } 122 | } 123 | } -------------------------------------------------------------------------------- /src/running_injector.ixx: -------------------------------------------------------------------------------- 1 | /** 2 | * @file running_injector.ixx 3 | * @brief The injector for running processes. 4 | * 5 | * @author Chen Zhenshuo (chenzs108@outlook.com) 6 | * @author Liu Guowen (liu.guowen@outlook.com) 7 | * @version 1.0 8 | * @date 2020-10-09 9 | * @par GitHub 10 | * https://github.com/Zhuagenborn 11 | */ 12 | 13 | module; 14 | #include 15 | #include 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | export module running_injector; 25 | 26 | import injector_interface; 27 | 28 | import utility.injection; 29 | import utility.windows_error; 30 | 31 | #pragma comment(lib, "shlwapi.lib") 32 | 33 | /** 34 | * @brief 35 | * The injector for running processes. 36 | * It can inject a dynamic-link library into a running process by searching its window title. 37 | */ 38 | export class RunningInjector final : public Injector { 39 | public: 40 | /** 41 | * @brief A constructor. 42 | * 43 | * @param win_title The window title of a process. 44 | * @param dll_path The path of a dynamic-link library. 45 | */ 46 | RunningInjector(std::string_view win_title, std::string_view dll_path); 47 | 48 | void Inject() override; 49 | 50 | private: 51 | //! The window title of the process. 52 | std::string win_title_; 53 | 54 | //! The path of the dynamic-link library. 55 | std::string dll_path_; 56 | }; 57 | 58 | 59 | module : private; 60 | 61 | /** 62 | * @brief Get the full path of a file. 63 | * 64 | * @param path The relative path of a file. 65 | */ 66 | std::string GetFullFilePath(std::string_view path); 67 | 68 | /** 69 | * @brief Get the handle of a process by its window title. 70 | * 71 | * @param win_title The window title of a process. 72 | * 73 | * @warning 74 | * If the function cannot find the target window, 75 | * it will throw a @p std::system_error exception containing an @p ERROR_SUCCESS code. 76 | */ 77 | std::unique_ptr GetProcessHandle( 78 | std::string_view win_title); 79 | 80 | 81 | RunningInjector::RunningInjector(const std::string_view win_title, 82 | const std::string_view dll_path) : 83 | win_title_{ win_title }, dll_path_{ dll_path } { 84 | if (win_title_.empty() || dll_path_.empty()) { 85 | throw std::invalid_argument{ 86 | "The target windows title or dynamic-link library path is null.\n" 87 | }; 88 | } 89 | 90 | if (PathIsRelativeA(dll_path_.data())) { 91 | dll_path_ = GetFullFilePath(dll_path_); 92 | } 93 | } 94 | 95 | 96 | void RunningInjector::Inject() { 97 | assert(!win_title_.empty() && !dll_path_.empty()); 98 | 99 | const auto proc{ GetProcessHandle(win_title_) }; 100 | if (proc == nullptr) { 101 | ThrowLastError(); 102 | } 103 | 104 | CreateRemoteInjectThread(*proc, dll_path_, false); 105 | } 106 | 107 | 108 | std::string GetFullFilePath(const std::string_view path) { 109 | assert(!path.empty()); 110 | 111 | char full_path[MAX_PATH]{}; 112 | if (const auto length{ 113 | GetFullPathNameA(path.data(), MAX_PATH, full_path, nullptr) }; 114 | length == 0) { 115 | ThrowLastError(); 116 | } 117 | 118 | return full_path; 119 | } 120 | 121 | 122 | std::unique_ptr GetProcessHandle( 123 | const std::string_view win_title) { 124 | assert(!win_title.empty()); 125 | 126 | const auto win{ FindWindowA(nullptr, win_title.data()) }; 127 | if (win == nullptr) { 128 | ThrowLastError(); 129 | } 130 | 131 | DWORD pid{ 0 }; 132 | GetWindowThreadProcessId(win, &pid); 133 | 134 | std::unique_ptr proc{ new HANDLE{ nullptr }, 135 | default_handle_deleter }; 136 | if (*proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); *proc == nullptr) { 137 | ThrowLastError(); 138 | } 139 | 140 | return proc; 141 | } -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.cpp 3 | * @brief The main program. 4 | * 5 | * @author Chen Zhenshuo (chenzs108@outlook.com) 6 | * @author Liu Guowen (liu.guowen@outlook.com) 7 | * @version 1.0 8 | * @date 2020-10-09 9 | * @par GitHub 10 | * https://github.com/Zhuagenborn 11 | */ 12 | 13 | import injector; 14 | 15 | import utility.windows_error; 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #include 28 | 29 | namespace { 30 | 31 | /** 32 | * Get command line arguments. 33 | */ 34 | std::vector GetCmdLineArguments(std::size_t argc, 35 | const char* argv[]) noexcept; 36 | 37 | /** 38 | * Print the help information. 39 | */ 40 | void PrintHelp() noexcept; 41 | 42 | } // namespace 43 | 44 | 45 | int main(int argc, char* argv[]) { 46 | assert(argc >= 0); 47 | 48 | const auto args{ GetCmdLineArguments(static_cast(argc), argv) }; 49 | 50 | if (args.size() != 3 && args.size() != 4) { 51 | PrintHelp(); 52 | return EXIT_SUCCESS; 53 | } 54 | 55 | try { 56 | std::unique_ptr injector{}; 57 | if (args.size() == 3) { 58 | injector = std::make_unique(args[1], args[2]); 59 | 60 | } else if (args.size() == 4) { 61 | if (args[1] != "-f") { 62 | throw std::invalid_argument{ 63 | "The format of the command arguments is invalid.\n" 64 | }; 65 | } 66 | 67 | injector = std::make_unique(args[2], args[3]); 68 | 69 | } else { 70 | assert(false); 71 | } 72 | 73 | assert(injector != nullptr); 74 | 75 | injector->Inject(); 76 | 77 | std::cout << "[*] The injection has finished." << std::endl; 78 | return EXIT_SUCCESS; 79 | 80 | } catch (const std::system_error& exp) { 81 | if (exp.code().value() == ERROR_SUCCESS) { 82 | std::cerr << "[!] Error: Maybe Dll-Injector cannot find the " 83 | "target window." 84 | << std::endl; 85 | 86 | } else { 87 | std::cerr << "[!] Error: " << exp.what() << std::endl; 88 | } 89 | 90 | } catch (const std::exception& exp) { 91 | std::cerr << "[!] Error: " << exp.what() << std::endl; 92 | } 93 | 94 | return EXIT_FAILURE; 95 | } 96 | 97 | 98 | namespace { 99 | 100 | std::vector GetCmdLineArguments( 101 | const std::size_t argc, const char* const argv[]) noexcept { 102 | std::vector args{}; 103 | std::ranges::copy_n(argv, argc, std::back_inserter(args)); 104 | return args; 105 | } 106 | 107 | 108 | void PrintHelp() noexcept { 109 | std::cout << "[!] Usage: Dll-Injector [-f | ] " 110 | "" 111 | << std::endl 112 | << std::endl; 113 | 114 | std::cout << "[!] Example (1): Create a new process with a dynamic-link library injected." 115 | << std::endl; 116 | std::cout << "\t```" << std::endl; 117 | std::cout << "\tDll-Injector -f " << std::endl; 118 | std::cout << "\t```" << std::endl; 119 | std::cout << "\tIf is a relative path, it must be relative " 120 | "to the process." 121 | << std::endl 122 | << std::endl; 123 | 124 | std::cout << "[!] Example (2): Inject a dynamic-link library into a running process by " 125 | "its window title." 126 | << std::endl; 127 | std::cout << "\t```" << std::endl; 128 | std::cout << "\tDll-Injector " << std::endl; 129 | std::cout << "\t```" << std::endl; 130 | std::cout << "\tIf is a relative path, it must be " 131 | "relative to the Dll-Injector." 132 | << std::endl 133 | << std::endl; 134 | } 135 | 136 | } // namespace -------------------------------------------------------------------------------- /src/startup_injector.ixx: -------------------------------------------------------------------------------- 1 | /** 2 | * @file startup_injector.ixx 3 | * @brief The injector for new starting processes. 4 | * 5 | * @author Chen Zhenshuo (chenzs108@outlook.com) 6 | * @author Liu Guowen (liu.guowen@outlook.com) 7 | * @version 1.0 8 | * @date 2020-10-09 9 | * @par GitHub 10 | * https://github.com/Zhuagenborn 11 | */ 12 | 13 | module; 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | export module startup_injector; 25 | 26 | import injector_interface; 27 | 28 | import utility.injection; 29 | import utility.windows_error; 30 | 31 | /** 32 | * @brief 33 | * The injector for new starting processes. 34 | * It can create a new process with a dynamic-link library injected. 35 | */ 36 | export class StartupInjector final : public Injector { 37 | public: 38 | /** 39 | * @brief A constructor. 40 | * 41 | * @param proc_path The path of a process. 42 | * @param dll_path The path of a dynamic-link library. 43 | */ 44 | StartupInjector(std::string_view proc_path, std::string_view dll_path); 45 | 46 | void Inject() override; 47 | 48 | /** 49 | * @brief Get the information of the process. 50 | * 51 | * @return If the process failed to create, the return value is empty. 52 | */ 53 | std::optional GetHandle() const noexcept; 54 | 55 | /** 56 | * @brief Check whether the process is running. 57 | * 58 | * @return @p true if the process is running, otherwise @p false. 59 | */ 60 | bool Running() const noexcept; 61 | 62 | //! Terminate the process. 63 | void Terminate() noexcept; 64 | 65 | private: 66 | //! The function type for closing all handles of a process. 67 | using HandleCloser = std::function; 68 | 69 | //! The path of the process. 70 | std::string proc_path_; 71 | 72 | //! The path of the dynamic-link library. 73 | std::string dll_path_; 74 | 75 | //! The process information. 76 | std::unique_ptr proc_{}; 77 | }; 78 | 79 | 80 | module : private; 81 | 82 | /** 83 | * @brief Close all handles of a process. 84 | * 85 | * @param proc The @p PROCESS_INFORMATION structure of a process. 86 | */ 87 | void CloseHandles(PROCESS_INFORMATION* proc) noexcept; 88 | 89 | /** 90 | * @brief Terminate a process. 91 | * 92 | * @param proc The @p PROCESS_INFORMATION structure of a process. 93 | */ 94 | void Terminate(PROCESS_INFORMATION* proc) noexcept; 95 | 96 | 97 | StartupInjector::StartupInjector(const std::string_view proc_path, 98 | const std::string_view dll_path) : 99 | proc_path_{ proc_path }, dll_path_{ dll_path } { 100 | if (proc_path_.empty() || dll_path_.empty()) { 101 | throw std::invalid_argument{ 102 | "The path of the process or dynamic-link library is null.\n" 103 | }; 104 | } 105 | } 106 | 107 | 108 | void StartupInjector::Inject() { 109 | assert(!proc_path_.empty() && !dll_path_.empty()); 110 | 111 | auto proc_terminator{ [](PROCESS_INFORMATION* const proc) noexcept { 112 | assert(proc != nullptr); 113 | 114 | ::Terminate(proc); 115 | CloseHandles(proc); 116 | delete proc; 117 | } }; 118 | 119 | std::unique_ptr proc{ 120 | new PROCESS_INFORMATION{}, proc_terminator 121 | }; 122 | 123 | STARTUPINFOA startup{ .cb = sizeof(startup) }; 124 | if (CreateProcessA(proc_path_.data(), nullptr, nullptr, nullptr, FALSE, 125 | CREATE_SUSPENDED | NORMAL_PRIORITY_CLASS, nullptr, 126 | nullptr, &startup, proc.get()) 127 | == FALSE) { 128 | ThrowLastError(); 129 | } 130 | 131 | CreateRemoteInjectThread(proc->hProcess, dll_path_, true); 132 | 133 | if (ResumeThread(proc->hThread) == static_cast(-1)) { 134 | ThrowLastError(); 135 | } 136 | 137 | auto proc_closer{ [](PROCESS_INFORMATION* const proc) noexcept { 138 | assert(proc != nullptr); 139 | 140 | CloseHandles(proc); 141 | delete proc; 142 | } }; 143 | 144 | proc_ = { proc.release(), proc_closer }; 145 | } 146 | 147 | 148 | std::optional StartupInjector::GetHandle() const noexcept { 149 | return Running() ? std::make_optional(*proc_) : std::nullopt; 150 | } 151 | 152 | 153 | bool StartupInjector::Running() const noexcept { 154 | return proc_ != nullptr; 155 | } 156 | 157 | 158 | void StartupInjector::Terminate() noexcept { 159 | if (Running()) { 160 | ::Terminate(proc_.get()); 161 | proc_.reset(); 162 | } 163 | } 164 | 165 | 166 | void CloseHandles(PROCESS_INFORMATION* const proc) noexcept { 167 | assert(proc != nullptr); 168 | 169 | if (proc->hThread != nullptr) { 170 | CloseHandle(proc->hThread); 171 | } 172 | 173 | if (proc->hProcess != nullptr) { 174 | CloseHandle(proc->hProcess); 175 | } 176 | } 177 | 178 | 179 | void Terminate(PROCESS_INFORMATION* const proc) noexcept { 180 | assert(proc != nullptr); 181 | 182 | if (proc->hProcess != nullptr) { 183 | TerminateProcess(proc->hProcess, EXIT_SUCCESS); 184 | } 185 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # #################################################################### 2 | # For C 3 | # #################################################################### 4 | # Prerequisites 5 | *.d 6 | 7 | # Object files 8 | *.o 9 | *.ko 10 | *.obj 11 | *.elf 12 | 13 | # Linker output 14 | *.ilk 15 | *.map 16 | *.exp 17 | 18 | # Precompiled Headers 19 | *.gch 20 | *.pch 21 | 22 | # Libraries 23 | *.lib 24 | *.a 25 | *.la 26 | *.lo 27 | 28 | # Shared objects (inc. Windows DLLs) 29 | *.dll 30 | *.so 31 | *.so.* 32 | *.dylib 33 | 34 | # Executables 35 | *.exe 36 | *.out 37 | *.app 38 | *.i*86 39 | *.x86_64 40 | *.hex 41 | 42 | # Debug files 43 | *.dSYM/ 44 | *.su 45 | *.idb 46 | *.pdb 47 | 48 | # Kernel Module Compile Results 49 | # *.mod* 50 | *.cmd 51 | .tmp_versions/ 52 | modules.order 53 | Module.symvers 54 | Mkfile.old 55 | dkms.conf 56 | 57 | 58 | # #################################################################### 59 | # For CMake 60 | # #################################################################### 61 | CMakeLists.txt.user 62 | CMakeCache.txt 63 | CMakeFiles 64 | CMakeScripts 65 | Testing 66 | Makefile 67 | cmake_install.cmake 68 | install_manifest.txt 69 | compile_commands.json 70 | CTestTestfile.cmake 71 | _deps 72 | 73 | 74 | # #################################################################### 75 | # For Visual Studio Code 76 | # #################################################################### 77 | .vscode 78 | *.code-workspace 79 | 80 | 81 | # #################################################################### 82 | # For Visual Studio 83 | # Ignore temporary files, build results, and 84 | # files generated by popular Visual Studio add-ons. 85 | # #################################################################### 86 | # User-specific files 87 | *.rsuser 88 | *.suo 89 | *.user 90 | *.userosscache 91 | *.sln.docstates 92 | 93 | # User-specific files (MonoDevelop/Xamarin Studio) 94 | *.userprefs 95 | 96 | # Mono auto generated files 97 | mono_crash.* 98 | 99 | # Build results 100 | [Dd]ebug/ 101 | [Dd]ebugPublic/ 102 | [Rr]elease/ 103 | [Rr]eleases/ 104 | x64/ 105 | x86/ 106 | [Aa][Rr][Mm]/ 107 | [Aa][Rr][Mm]64/ 108 | bld/ 109 | [Bb]in/ 110 | [Oo]bj/ 111 | [Ll]og/ 112 | [Ll]ogs/ 113 | 114 | # Visual Studio 2015/2017 cache/options directory 115 | .vs/ 116 | # Uncomment if you have tasks that create the project's static files in wwwroot 117 | #wwwroot/ 118 | 119 | # Visual Studio 2017 auto generated files 120 | Generated\ Files/ 121 | 122 | # MSTest test Results 123 | [Tt]est[Rr]esult*/ 124 | [Bb]uild[Ll]og.* 125 | 126 | # NUnit 127 | *.VisualState.xml 128 | TestResult.xml 129 | nunit-*.xml 130 | 131 | # Build Results of an ATL Project 132 | [Dd]ebugPS/ 133 | [Rr]eleasePS/ 134 | dlldata.c 135 | 136 | # Benchmark Results 137 | BenchmarkDotNet.Artifacts/ 138 | 139 | # .NET Core 140 | project.lock.json 141 | project.fragment.lock.json 142 | artifacts/ 143 | 144 | # StyleCop 145 | StyleCopReport.xml 146 | 147 | # Files built by Visual Studio 148 | *_i.c 149 | *_p.c 150 | *_h.h 151 | *.ilk 152 | *.meta 153 | *.obj 154 | *.iobj 155 | *.pch 156 | *.pdb 157 | *.ipdb 158 | *.pgc 159 | *.pgd 160 | *.rsp 161 | *.sbr 162 | *.tlb 163 | *.tli 164 | *.tlh 165 | *.tmp 166 | *.tmp_proj 167 | *_wpftmp.csproj 168 | *.log 169 | *.vspscc 170 | *.vssscc 171 | .builds 172 | *.pidb 173 | *.svclog 174 | *.scc 175 | 176 | # Chutzpah Test files 177 | _Chutzpah* 178 | 179 | # Visual C++ cache files 180 | ipch/ 181 | *.aps 182 | *.ncb 183 | *.opendb 184 | *.opensdf 185 | *.sdf 186 | *.cachefile 187 | *.VC.db 188 | *.VC.VC.opendb 189 | 190 | # Visual Studio profiler 191 | *.psess 192 | *.vsp 193 | *.vspx 194 | *.sap 195 | 196 | # Visual Studio Trace Files 197 | *.e2e 198 | 199 | # TFS 2012 Local Workspace 200 | $tf/ 201 | 202 | # Guidance Automation Toolkit 203 | *.gpState 204 | 205 | # ReSharper is a .NET coding add-in 206 | _ReSharper*/ 207 | *.[Rr]e[Ss]harper 208 | *.DotSettings.user 209 | 210 | # TeamCity is a build add-in 211 | _TeamCity* 212 | 213 | # DotCover is a Code Coverage Tool 214 | *.dotCover 215 | 216 | # AxoCover is a Code Coverage Tool 217 | .axoCover/* 218 | !.axoCover/settings.json 219 | 220 | # Coverlet is a free, cross platform Code Coverage Tool 221 | coverage*[.json, .xml, .info] 222 | 223 | # Visual Studio code coverage results 224 | *.coverage 225 | *.coveragexml 226 | 227 | # NCrunch 228 | _NCrunch_* 229 | .*crunch*.local.xml 230 | nCrunchTemp_* 231 | 232 | # MightyMoose 233 | *.mm.* 234 | AutoTest.Net/ 235 | 236 | # Web workbench (sass) 237 | .sass-cache/ 238 | 239 | # Installshield output folder 240 | [Ee]xpress/ 241 | 242 | # DocProject is a documentation generator add-in 243 | DocProject/buildhelp/ 244 | DocProject/Help/*.HxT 245 | DocProject/Help/*.HxC 246 | DocProject/Help/*.hhc 247 | DocProject/Help/*.hhk 248 | DocProject/Help/*.hhp 249 | DocProject/Help/Html2 250 | DocProject/Help/html 251 | 252 | # Click-Once directory 253 | publish/ 254 | 255 | # Publish Web Output 256 | *.[Pp]ublish.xml 257 | *.azurePubxml 258 | # Note: Comment the next line if you want to checkin your web deploy settings, 259 | # but database connection strings (with potential passwords) will be unencrypted 260 | *.pubxml 261 | *.publishproj 262 | 263 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 264 | # checkin your Azure Web App publish settings, but sensitive information contained 265 | # in these scripts will be unencrypted 266 | PublishScripts/ 267 | 268 | # NuGet Packages 269 | *.nupkg 270 | # NuGet Symbol Packages 271 | *.snupkg 272 | # The packages folder can be ignored because of Package Restore 273 | **/[Pp]ackages/* 274 | # except build/, which is used as an MSBuild target. 275 | !**/[Pp]ackages/build/ 276 | # Uncomment if necessary however generally it will be regenerated when needed 277 | #!**/[Pp]ackages/repositories.config 278 | # NuGet v3's project.json files produces more ignorable files 279 | *.nuget.props 280 | *.nuget.targets 281 | 282 | # Microsoft Azure Build Output 283 | csx/ 284 | *.build.csdef 285 | 286 | # Microsoft Azure Emulator 287 | ecf/ 288 | rcf/ 289 | 290 | # Windows Store app package directories and files 291 | AppPackages/ 292 | BundleArtifacts/ 293 | Package.StoreAssociation.xml 294 | _pkginfo.txt 295 | *.appx 296 | *.appxbundle 297 | *.appxupload 298 | 299 | # Visual Studio cache files 300 | # files ending in .cache can be ignored 301 | *.[Cc]ache 302 | # but keep track of directories ending in .cache 303 | !?*.[Cc]ache/ 304 | 305 | # Others 306 | ClientBin/ 307 | ~$* 308 | *~ 309 | *.dbmdl 310 | *.dbproj.schemaview 311 | *.jfm 312 | *.pfx 313 | *.publishsettings 314 | orleans.codegen.cs 315 | 316 | # Including strong name files can present a security risk 317 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 318 | #*.snk 319 | 320 | # Since there are multiple workflows, uncomment next line to ignore bower_components 321 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 322 | #bower_components/ 323 | 324 | # RIA/Silverlight projects 325 | Generated_Code/ 326 | 327 | # Backup & report files from converting an old project file 328 | # to a newer Visual Studio version. Backup files are not needed, 329 | # because we have git ;-) 330 | _UpgradeReport_Files/ 331 | Backup*/ 332 | UpgradeLog*.XML 333 | UpgradeLog*.htm 334 | ServiceFabricBackup/ 335 | *.rptproj.bak 336 | 337 | # SQL Server files 338 | *.mdf 339 | *.ldf 340 | *.ndf 341 | 342 | # Business Intelligence projects 343 | *.rdl.data 344 | *.bim.layout 345 | *.bim_*.settings 346 | *.rptproj.rsuser 347 | *- [Bb]ackup.rdl 348 | *- [Bb]ackup ([0-9]).rdl 349 | *- [Bb]ackup ([0-9][0-9]).rdl 350 | 351 | # Microsoft Fakes 352 | FakesAssemblies/ 353 | 354 | # GhostDoc plugin setting file 355 | *.GhostDoc.xml 356 | 357 | # Node.js Tools for Visual Studio 358 | .ntvs_analysis.dat 359 | node_modules/ 360 | 361 | # Visual Studio 6 build log 362 | *.plg 363 | 364 | # Visual Studio 6 workspace options file 365 | *.opt 366 | 367 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 368 | *.vbw 369 | 370 | # Visual Studio LightSwitch build output 371 | **/*.HTMLClient/GeneratedArtifacts 372 | **/*.DesktopClient/GeneratedArtifacts 373 | **/*.DesktopClient/ModelManifest.xml 374 | **/*.Server/GeneratedArtifacts 375 | **/*.Server/ModelManifest.xml 376 | _Pvt_Extensions 377 | 378 | # Paket dependency manager 379 | .paket/paket.exe 380 | paket-files/ 381 | 382 | # FAKE - F# Make 383 | .fake/ 384 | 385 | # CodeRush personal settings 386 | .cr/personal 387 | 388 | # Python Tools for Visual Studio (PTVS) 389 | __pycache__/ 390 | *.pyc 391 | 392 | # Cake - Uncomment if you are using it 393 | # tools/** 394 | # !tools/packages.config 395 | 396 | # Tabs Studio 397 | *.tss 398 | 399 | # Telerik's JustMock configuration file 400 | *.jmconfig 401 | 402 | # BizTalk build output 403 | *.btp.cs 404 | *.btm.cs 405 | *.odx.cs 406 | *.xsd.cs 407 | 408 | # OpenCover UI analysis results 409 | OpenCover/ 410 | 411 | # Azure Stream Analytics local run output 412 | ASALocalRun/ 413 | 414 | # MSBuild Binary and Structured Log 415 | *.binlog 416 | 417 | # NVidia Nsight GPU debugger configuration file 418 | *.nvuser 419 | 420 | # MFractors (Xamarin productivity tool) working folder 421 | .mfractor/ 422 | 423 | # Local History for Visual Studio 424 | .localhistory/ 425 | 426 | # BeatPulse healthcheck temp database 427 | healthchecksdb 428 | 429 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 430 | MigrationBackup/ 431 | 432 | # Ionide (cross platform F# VS Code tools) working folder 433 | .ionide/ --------------------------------------------------------------------------------