├── .gitattributes ├── LICENSE ├── README.md ├── .clang-format ├── CODE_OF_CONDUCT.md └── winapi_import.hpp /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 SaulBerrenson 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WinApi Call (import) Obfuscator 2 | Header-only c++17 library for obfuscation import winapi functions. 3 | This based on https://github.com/XShar/Win_API_Obfuscation and https://xakep.ru/2018/12/06/hidden-winapi/ 4 | 5 | It's hide your table of import functions. 6 | 7 | 8 | ### How it work? 9 | 10 | Importing win api functions calling by hash-value function 11 | 12 | 13 | ### How to using? 14 | ```c++ 15 | #include 16 | 17 | #include "winapi_import.hpp" 18 | 19 | int main() 20 | { 21 | // Define function types we want to import 22 | using MessageBoxType = int(WINAPI)(HWND, LPCSTR, LPCSTR, UINT); 23 | using GetSystemMetricsType = int(WINAPI)(int); 24 | 25 | auto msgBox = win_api::get("MessageBoxA", "user32.dll"); 26 | auto msgBox2 = win_api::get("MessageBoxA2", "user32.dll"); 27 | 28 | auto GetSystemMetrics = win_api::get("GetSystemMetrics", "user32.dll"); 29 | 30 | // Use the imported functions 31 | if (msgBox) { 32 | msgBox(nullptr, "Hello from dynamic import!", "Dynamic Import", MB_OK); 33 | } 34 | 35 | if (GetSystemMetrics) { 36 | int screenWidth = GetSystemMetrics(SM_CXSCREEN); 37 | int screenHeight = GetSystemMetrics(SM_CYSCREEN); 38 | std::cout << "Screen resolution: " << screenWidth << "x" << screenHeight << std::endl; 39 | } 40 | 41 | if (!msgBox2) { 42 | std::cout << "invalid link" << '\n'; 43 | } 44 | 45 | std::cout << "Hello World!\n"; 46 | } 47 | ``` 48 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | # This is the clang-format configuration style to be used by Qt, 2 | # based on the rules from https://wiki.qt.io/Qt_Coding_Style and 3 | # https://wiki.qt.io/Coding_Conventions 4 | 5 | --- 6 | # Webkit style was loosely based on the Qt style 7 | BasedOnStyle: WebKit 8 | 9 | Standard: Cpp11 10 | Cpp11BracedListStyle: true 11 | 12 | # Leave the line breaks up to the user. 13 | # Note that this may be changed at some point in the future. 14 | ColumnLimit: 128 15 | # How much weight do extra characters after the line length limit have. 16 | # PenaltyExcessCharacter: 4 17 | 18 | # Disable reflow of qdoc comments: indentation rules are different. 19 | # Translation comments are also excluded. 20 | CommentPragmas: "^!|^:" 21 | 22 | # We want a space between the type and the star for pointer types. 23 | PointerBindsToType: false 24 | 25 | # We use template< without space. 26 | SpaceAfterTemplateKeyword: false 27 | 28 | SpaceBeforeCpp11BracedList: false 29 | SpaceInEmptyBlock: false 30 | 31 | # We want to break before the operators, but not before a '='. 32 | BreakBeforeBinaryOperators: NonAssignment 33 | 34 | 35 | # Braces are usually attached, but not after functions or class declarations. 36 | BreakBeforeBraces: Custom 37 | BraceWrapping: 38 | AfterClass: false 39 | AfterControlStatement: false 40 | AfterEnum: false 41 | AfterFunction: true 42 | AfterNamespace: false 43 | AfterObjCDeclaration: false 44 | AfterStruct: false 45 | AfterUnion: false 46 | BeforeCatch: false 47 | BeforeElse: true 48 | IndentBraces: false 49 | 50 | # When constructor initializers do not fit on one line, put them each on a new line. 51 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 52 | # Indent initializers by 4 spaces 53 | ConstructorInitializerIndentWidth: 4 54 | 55 | # Indent width for line continuations. 56 | ContinuationIndentWidth: 8 57 | 58 | # No indentation for namespaces. 59 | NamespaceIndentation: None 60 | 61 | # Horizontally align arguments after an open bracket. 62 | # The coding style does not specify the following, but this is what gives 63 | # results closest to the existing code. 64 | AlignAfterOpenBracket: true 65 | AlwaysBreakTemplateDeclarations: true 66 | 67 | # Ideally we should also allow less short function in a single line, but 68 | # clang-format does not handle that. 69 | AllowShortFunctionsOnASingleLine: All 70 | 71 | # The coding style specifies some include order categories, but also tells to 72 | # separate categories with an empty line. It does not specify the order within 73 | # the categories. Since the SortInclude feature of clang-format does not 74 | # re-order includes separated by empty lines, the feature is not used. 75 | SortIncludes: false 76 | 77 | # macros for which the opening brace stays attached. 78 | ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH, forever, Q_FOREVER, QBENCHMARK, QBENCHMARK_ONCE ] 79 | 80 | 81 | #AllowShortIfStatementsOnASingleLine: true 82 | FixNamespaceComments: true 83 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /winapi_import.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | /** 6 | * @namespace win_api 7 | * @brief Namespace containing Windows API import functionality 8 | */ 9 | namespace win_api { 10 | 11 | /// @brief Type alias for LoadLibrary function pointer 12 | using t_load_library = HMODULE(WINAPI *)(__in LPCSTR file_name); 13 | 14 | /** 15 | * @struct unicode_string 16 | * @brief Structure representing a Unicode string in Windows 17 | */ 18 | struct unicode_string { 19 | USHORT length; ///< Length of the string 20 | USHORT maximum_length; ///< Maximum length of the buffer 21 | PWSTR buffer; ///< Pointer to the string buffer 22 | }; 23 | 24 | /** 25 | * @struct ldr_module 26 | * @brief Structure representing a loaded module in Windows 27 | */ 28 | struct ldr_module { 29 | LIST_ENTRY e[3]; ///< Module links 30 | HMODULE base; ///< Base address of the module 31 | void* entry; ///< Entry point 32 | UINT size; ///< Size of the module 33 | unicode_string dll_path; ///< Full path to the DLL 34 | unicode_string dll_name; ///< Name of the DLL 35 | }; 36 | 37 | /** 38 | * @brief Macro for MurmurHash2A mixing function 39 | * @param h Hash accumulator 40 | * @param k Current value to mix 41 | */ 42 | #define mmix(h, k) \ 43 | { \ 44 | k *= m; \ 45 | k ^= k >> r; \ 46 | k *= m; \ 47 | h *= m; \ 48 | h ^= k; \ 49 | } 50 | 51 | /** 52 | * @namespace detail 53 | * @brief Implementation details namespace 54 | */ 55 | namespace detail { 56 | 57 | /** 58 | * @brief Implements MurmurHash2A algorithm 59 | */ 60 | [[nodiscard]] unsigned int murmur_hash2_a(const void* key, int len, unsigned int seed) 61 | { 62 | constexpr unsigned int m = 0x5bd1e995; 63 | constexpr auto r = 24; 64 | auto current_data = static_cast(key); 65 | auto h = seed; 66 | auto remaining_len = len; 67 | 68 | while (remaining_len >= 4) { 69 | auto k = *reinterpret_cast(current_data); 70 | k *= m; 71 | k ^= k >> r; 72 | k *= m; 73 | h *= m; 74 | h ^= k; 75 | current_data += 4; 76 | remaining_len -= 4; 77 | } 78 | 79 | unsigned int t = 0; 80 | switch (remaining_len) { 81 | case 3: 82 | t ^= static_cast(current_data[2]) << 16; 83 | case 2: 84 | t ^= static_cast(current_data[1]) << 8; 85 | case 1: 86 | t ^= static_cast(current_data[0]); 87 | } 88 | 89 | auto result = h; 90 | result *= m; 91 | result ^= t; 92 | result *= m; 93 | result ^= static_cast(len); 94 | result ^= result >> 13; 95 | result *= m; 96 | result ^= result >> 15; 97 | 98 | return result; 99 | } 100 | 101 | /** 102 | * @brief Parses the export table of a module to find a function 103 | */ 104 | [[nodiscard]] LPVOID parse_export_table(HMODULE module, DWORD api_hash, int len, unsigned seed) 105 | { 106 | if (!module) 107 | return nullptr; 108 | 109 | const auto img_dos_header = reinterpret_cast(module); 110 | const auto img_nt_header = 111 | reinterpret_cast(reinterpret_cast(img_dos_header) + img_dos_header->e_lfanew); 112 | const auto in_export = reinterpret_cast( 113 | reinterpret_cast(img_dos_header) 114 | + img_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); 115 | 116 | const auto rva_name = reinterpret_cast(reinterpret_cast(img_dos_header) + in_export->AddressOfNames); 117 | const auto rva_ordinal = 118 | reinterpret_cast(reinterpret_cast(img_dos_header) + in_export->AddressOfNameOrdinals); 119 | 120 | for (UINT i = 0; i < in_export->NumberOfNames - 1; ++i) { 121 | const auto api_name = reinterpret_cast(reinterpret_cast(img_dos_header) + rva_name[i]); 122 | 123 | if (api_hash == murmur_hash2_a(api_name, len, seed)) { 124 | const auto func_addr = 125 | reinterpret_cast(reinterpret_cast(img_dos_header) + in_export->AddressOfFunctions); 126 | const auto ord = static_cast(rva_ordinal[i]); 127 | 128 | if (ord > reinterpret_cast(func_addr)) 129 | return nullptr; 130 | 131 | return reinterpret_cast(reinterpret_cast(img_dos_header) + func_addr[ord]); 132 | } 133 | } 134 | return nullptr; 135 | } 136 | } // namespace detail 137 | 138 | /** 139 | * @class win_api_import 140 | * @brief Class for importing Windows API functions dynamically 141 | */ 142 | template 143 | class win_api_import { 144 | public: 145 | /** 146 | * @class function_holder 147 | * @brief RAII wrapper for imported function and its module 148 | */ 149 | struct function_holder final { 150 | HMODULE dll_handle; ///< Handle to the loaded DLL 151 | T* func_ptr; ///< Pointer to the imported function 152 | 153 | function_holder() 154 | : dll_handle(nullptr) 155 | , func_ptr(nullptr) {} 156 | 157 | function_holder(HMODULE dll, T* func) 158 | : dll_handle(dll) 159 | , func_ptr(func) {} 160 | 161 | function_holder(function_holder&& other) noexcept 162 | : dll_handle(other.dll_handle) 163 | , func_ptr(other.func_ptr) 164 | { 165 | other.dll_handle = nullptr; 166 | other.func_ptr = nullptr; 167 | } 168 | 169 | function_holder& operator=(function_holder&& other) noexcept 170 | { 171 | if (this != &other) { 172 | cleanup(); 173 | dll_handle = other.dll_handle; 174 | func_ptr = other.func_ptr; 175 | other.dll_handle = nullptr; 176 | other.func_ptr = nullptr; 177 | } 178 | return *this; 179 | } 180 | 181 | ~function_holder() { cleanup(); } 182 | 183 | template 184 | auto operator()(Args&&... args) const 185 | { 186 | return func_ptr(std::forward(args)...); 187 | } 188 | 189 | explicit operator bool() const { return func_ptr != nullptr; } 190 | 191 | private: 192 | void cleanup() 193 | { 194 | if (dll_handle) { 195 | FreeLibrary(dll_handle); 196 | dll_handle = nullptr; 197 | func_ptr = nullptr; 198 | } 199 | } 200 | 201 | function_holder(const function_holder&) = delete; 202 | function_holder& operator=(const function_holder&) = delete; 203 | }; 204 | 205 | win_api_import(std::string_view func_name, std::string_view module_name, unsigned seed = 0) 206 | : m_func_name(func_name) 207 | , m_module_name(module_name) 208 | , m_len(static_cast(func_name.length())) 209 | , m_seed(seed == 0 ? m_len : seed) {} 210 | 211 | [[nodiscard]] function_holder get_function() 212 | { 213 | try { 214 | const auto [krnl32, hdll] = get_modules(); 215 | const auto api_hash = detail::murmur_hash2_a(m_func_name.data(), m_len, m_seed); 216 | auto api_func = detail::parse_export_table(hdll, api_hash, m_len, m_seed); 217 | return function_holder(hdll, reinterpret_cast(api_func)); 218 | } catch (...) { 219 | return function_holder(); 220 | } 221 | } 222 | 223 | private: 224 | const std::string_view m_func_name; ///< Name of the function to import 225 | const std::string_view m_module_name; ///< Name of the module 226 | const int m_len; ///< Length of the function name 227 | const unsigned m_seed; ///< Seed for hash function 228 | 229 | struct module_pair { 230 | HMODULE kernel32; ///< Handle to kernel32.dll 231 | HMODULE dll; ///< Handle to target module 232 | }; 233 | 234 | [[nodiscard]] module_pair get_modules() const 235 | { 236 | #ifdef _WIN64 237 | constexpr auto module_list = 0x18; 238 | constexpr auto module_list_flink = 0x18; 239 | constexpr auto kernel_base_addr = 0x10; 240 | const auto peb = __readgsqword(0x60); 241 | #else 242 | constexpr auto module_list = 0x0C; 243 | constexpr auto module_list_flink = 0x10; 244 | constexpr auto kernel_base_addr = 0x10; 245 | const auto peb = __readfsdword(0x30); 246 | #endif 247 | const auto mdllist = *reinterpret_cast(peb + module_list); 248 | const auto mlink = *reinterpret_cast(mdllist + module_list_flink); 249 | auto mdl = reinterpret_cast(mlink); 250 | HMODULE krnl32 = nullptr; 251 | 252 | do { 253 | mdl = reinterpret_cast(mdl->e[0].Flink); 254 | if (mdl->base && !lstrcmpiW(mdl->dll_name.buffer, L"kernel32.dll")) { 255 | krnl32 = mdl->base; 256 | break; 257 | } 258 | } while (mlink != reinterpret_cast(mdl)); 259 | 260 | const auto api_hash_load_library = detail::murmur_hash2_a("LoadLibraryA", 12, 10); 261 | auto temp_load_library = static_cast(detail::parse_export_table(krnl32, api_hash_load_library, 12, 10)); 262 | auto hdll = temp_load_library(m_module_name.data()); 263 | 264 | return {krnl32, hdll}; 265 | } 266 | }; 267 | 268 | /** 269 | * @brief Helper function to import an API function 270 | */ 271 | template 272 | [[nodiscard]] typename win_api_import::function_holder get(std::string_view func_name, std::string_view module_name, 273 | unsigned seed = 0) 274 | { 275 | win_api_import importer(func_name, module_name, seed); 276 | return importer.get_function(); 277 | } 278 | 279 | } // namespace win_api --------------------------------------------------------------------------------