commit de531703ab53b43d8e7166b72ab2c628fd12ca2b Author: nganhkhoa Date: Tue Feb 18 02:25:14 2020 +0700 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..089a506 --- /dev/null +++ b/.gitignore @@ -0,0 +1,485 @@ + +# Created by https://www.gitignore.io/api/c,vim,c++,windows,visualstudio,visualstudiocode +# Edit at https://www.gitignore.io/?templates=c,vim,c++,windows,visualstudio,visualstudiocode + +### C ### +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +### C++ ### +# Prerequisites + +# Compiled Object files +*.slo + +# Precompiled Headers + +# Compiled Dynamic libraries + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai + +# Executables + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ + +# Auto-generated tag files +tags + +# Persistent undo +[._]*.un~ + +# Coc configuration directory +.vim + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.iobj +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# End of https://www.gitignore.io/api/c,vim,c++,windows,visualstudio,visualstudiocode diff --git a/KMDF Driver2.sln b/KMDF Driver2.sln new file mode 100644 index 0000000..29e418c --- /dev/null +++ b/KMDF Driver2.sln @@ -0,0 +1,51 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29409.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "KMDF Driver2", "KMDF Driver2\KMDF Driver2.vcxproj", "{905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|ARM.ActiveCfg = Debug|ARM + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|ARM.Build.0 = Debug|ARM + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|ARM.Deploy.0 = Debug|ARM + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|ARM64.Build.0 = Debug|ARM64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|x64.ActiveCfg = Debug|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|x64.Build.0 = Debug|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|x64.Deploy.0 = Debug|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|x86.ActiveCfg = Debug|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|x86.Build.0 = Debug|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Debug|x86.Deploy.0 = Debug|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|ARM.ActiveCfg = Release|ARM + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|ARM.Build.0 = Release|ARM + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|ARM.Deploy.0 = Release|ARM + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|ARM64.ActiveCfg = Release|ARM64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|ARM64.Build.0 = Release|ARM64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|ARM64.Deploy.0 = Release|ARM64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|x64.ActiveCfg = Release|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|x64.Build.0 = Release|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|x64.Deploy.0 = Release|x64 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|x86.ActiveCfg = Release|Win32 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|x86.Build.0 = Release|Win32 + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4}.Release|x86.Deploy.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BEF2B030-38D0-445E-8EE8-6A31B825389D} + EndGlobalSection +EndGlobal diff --git a/KMDF Driver2/Driver.cpp b/KMDF Driver2/Driver.cpp new file mode 100644 index 0000000..4c0f504 --- /dev/null +++ b/KMDF Driver2/Driver.cpp @@ -0,0 +1,307 @@ +#include +#include +#include + +#include "sioctl.h" +#include "Driver.h" +// #include "peformat.h" + +extern "C" DRIVER_INITIALIZE DriverEntry; +extern "C" DRIVER_UNLOAD UnloadRoutine; +extern "C" PDBGKD_GET_VERSION64 FindKdVersionBlock(void); + +#define NT_DEVICE_NAME L"\\Device\\poolscanner" +#define DOS_DEVICE_NAME L"\\DosDevices\\poolscanner" + +#define F_DbgPrint(...) \ + DbgPrint("[NAK] :: ");\ + DbgPrint(__VA_ARGS__); + +#define POOL_HEADER_SIZE 0x10 // windows 10 +#define CHUNK_SIZE 16 // 64 bit +// #define PAGE_SIZE 4096 // 4KB + +PVOID SelfAllocKernelBuffer = nullptr; +PVOID ChunkAddr = nullptr; +constexpr ULONG POOL_TAG = 'NakD'; + +NTSTATUS +DriverEntry( + _In_ PDRIVER_OBJECT DriverObject, + _In_ PUNICODE_STRING /* RegistryPath */ +) { + DbgPrint("[NAK] :: [+] Hello from Kernel\n"); + NTSTATUS returnStatus = STATUS_SUCCESS; + UNICODE_STRING ntUnicodeString; + UNICODE_STRING ntWin32NameString; + PDEVICE_OBJECT deviceObject = nullptr; + constexpr SIZE_T POOL_BUFFER_SIZE = 0x100; // a small chunk + + // PVOID kernelBuffer = nullptr; + + DriverObject->DriverUnload = UnloadRoutine; + + RtlInitUnicodeString(&ntUnicodeString, NT_DEVICE_NAME); + returnStatus = IoCreateDevice( + DriverObject, // Our Driver Object + 0, // We don't use a device extension + &ntUnicodeString, // Device name "\Device\poolscanner" + FILE_DEVICE_UNKNOWN, // Device type + FILE_DEVICE_SECURE_OPEN, // Device characteristics + FALSE, // Not an exclusive device + &deviceObject); // Returned ptr to Device Object + if (!NT_SUCCESS(returnStatus)) { + DbgPrint(("[NAK] :: [-] Couldn't create the device object\n")); + return returnStatus; + } + + RtlInitUnicodeString(&ntWin32NameString, DOS_DEVICE_NAME); + returnStatus = IoCreateSymbolicLink(&ntWin32NameString, &ntUnicodeString); + if (!NT_SUCCESS(returnStatus)) { + DbgPrint("[NAK] :: [-] Couldn't create symbolic link for driver\n"); + IoDeleteDevice(deviceObject); + } + + DbgPrint("[NAK] :: [+] GO GO GO !"); + + // DbgPrint("[NAK] :: [+] Allocating a chunk in NonPagedPool...\n"); + SelfAllocKernelBuffer = ExAllocatePoolWithTag(NonPagedPool, POOL_BUFFER_SIZE, POOL_TAG); + PVOID kernelBuffer = SelfAllocKernelBuffer; + + // if (!kernelBuffer) { + // DbgPrint("[NAK] :: [-] Unable to allocate Pool chunk\n"); + // returnStatus = STATUS_NO_MEMORY; + // return returnStatus; + // } + + // DbgPrint("[NAK] :: [+] Successfully allocated a chunk in NonPagedPool"); + ChunkAddr = (PVOID)((long long int)kernelBuffer - POOL_HEADER_SIZE); + POOL_HEADER p; // use one POOL_HEADER to index + toPoolHeader(&p, ChunkAddr); + printChunkInfo(&p); + + // if (p.tag == 'NakD') { + // DbgPrint("[NAK] :: [+] tag == 'NakD'"); + // } + // else if (p.tag == 'DkaN') { + // DbgPrint("[NAK] :: [+] tag == 'DkaN'"); + // } + // else { + // DbgPrint("[NAK] :: [-] tag equals something else"); + // } + + // Try to find `MmNonPagedPoolStart` and `MmNonPagedPoolEnd` + // https://web.archive.org/web/20061110120809/http://www.rootkit.com/newsread.php?newsid=153 + // KPCR->Version Data->Debugger Data List Entry->Flink + ULONG64 nonPagedPoolStart = 0; + ULONG64 nonPagedPoolEnd = 0; + + PDBGKD_GET_VERSION64 kdVersionBlock = nullptr; + // PKDDEBUGGER_DATA64 dbgBlock = nullptr; + + kdVersionBlock = (PDBGKD_GET_VERSION64) FindKdVersionBlock(); + DbgPrint("[NAK] :: [ ] KdVersionBlock : 0x%p\n", kdVersionBlock); + + if (kdVersionBlock == nullptr) { + // The below can be summarized in these few lines of this README + // https://github.com/nganhkhoa/pdb_for_nonpagedpool + DbgPrint("[NAK] :: [ ] Cannot get KdVersionBlock try ntoskrnl+pdb\n"); + + // https://www.unknowncheats.me/forum/general-programming-and-reversing/259921-finding-kernel-function-address-user-mode.html + + // seems like this shellcode is wrong for Windows insider Feb 2020 upgrade + // shellcode: https://gist.github.com/Barakat/34e9924217ed81fd78c9c92d746ec9c6 + static const UCHAR shellcode[] = { + 0x65, 0x48, 0x8B, 0x04, 0x25, 0x38, 0x00, 0x00, 0x00, 0xB9, 0x4D, 0x5A, 0x00, 0x00, 0x48, 0x8B, + 0x40, 0x04, 0x48, 0x25, 0x00, 0xF0, 0xFF, 0xFF, 0xEB, 0x06, 0x48, 0x2D, 0x00, 0x10, 0x00, 0x00, + 0x66, 0x39, 0x08, 0x75, 0xF5, 0xC3 + }; + const auto shellPool = ExAllocatePoolWithTag(NonPagedPoolExecute, sizeof(getNtoskrnlBaseShellcode), 'NakD'); + RtlCopyMemory(shellPool, getNtoskrnlBaseShellcode, sizeof(getNtoskrnlBaseShellcode)); + const auto get_ntoskrnl_base_address = reinterpret_cast(shellPool); + PVOID ntosbase = get_ntoskrnl_base_address(); + DbgPrint("[NAK] :: [ ] ntoskrnl.exe : 0x%p\n", ntosbase); + ExFreePoolWithTag(shellPool, 'NakD'); + + // parsing PE file + // https://stackoverflow.com/a/4316804 + // https://stackoverflow.com/a/47898643 + // https://github.com/Reetus/RazorRE/blob/42f441093bd85443b39fcff5d2a02069b524b114/Crypt/Misc.cpp#L63 + // if (ntosbase->e_magic == IMAGE_DOS_SIGNATURE) { + // DbgPrint("[NAK] :: [ ] DOS Signature (MZ) Matched \n"); + // const PIMAGE_NT_HEADERS32 peHeader = (PIMAGE_NT_HEADERS32) ((unsigned char*)ntosbase+ntosbase->e_lfanew); + // if(peHeader->Signature == IMAGE_NT_SIGNATURE) { + // DbgPrint("[NAK] :: [ ] PE Signature (PE) Matched \n"); + // // yeah we really got ntoskrnl.exe base + // } + // } + + // In Windows 10, the global debug is MiState + // dt (_MI_SYSTEM_NODE_NONPAGED_POOL*) ( + + ) + // Sample output + + // +0x000 DynamicBitMapNonPagedPool : _MI_DYNAMIC_BITMAP + // +0x048 CachedNonPagedPoolCount : 0 + // +0x050 NonPagedPoolSpinLock : 0 + // +0x058 CachedNonPagedPool : (null) + // +0x060 NonPagedPoolFirstVa : 0xffffe580`00000000 Void + // +0x068 NonPagedPoolLastVa : 0xfffff580`00000000 Void + // +0x070 SystemNodeInformation : 0xffffe58f`9283b050 _MI_SYSTEM_NODE_INFORMATION + + PVOID miState = (PVOID)((ULONG64)ntosbase + 0xc4f200); + _MI_SYSTEM_NODE_NONPAGED_POOL* systemNonPageInfo = + (_MI_SYSTEM_NODE_NONPAGED_POOL*)((ULONG64)miState + 0x1580 + 0x20); + DbgPrint("[NAK] :: [ ] MiState : 0x%p\n", miState); + DbgPrint("[NAK] :: [ ] systemNonPageInfo : 0x%p\n", systemNonPageInfo); + DbgPrint("[NAK] :: [ ] NonPagedPoolFirstVa : 0x%p\n", systemNonPageInfo->NonPagedPoolFirstVa); + DbgPrint("[NAK] :: [ ] NonPagedPoolLastVa : 0x%p\n", systemNonPageInfo->NonPagedPoolLastVa); + // nonPagedPoolStart = *(ULONG64*)(systemNonPageInfo->NonPagedPoolFirstVa); + // nonPagedPoolEnd = *(ULONG64*)(systemNonPageInfo->NonPagedPoolLastVa); + } else { + // x32 windows, KdVersionBlock get is usable + DbgPrint("[NAK] :: [ ] Successfully get KdVersionBlock, not sure whether this works\n"); + // dbgBlock = (PKDDEBUGGER_DATA64) ((PLIST_ENTRY)kdVersionBlock->DebuggerDataList)->Flink; + } + + DbgPrint("[NAK] :: [ ] MmNonPagedPoolStart : 0x%llx\n", nonPagedPoolStart); + DbgPrint("[NAK] :: [ ] MmNonPagedPoolEnd : 0x%llx\n", nonPagedPoolEnd); + + // now wait for user call to scan + // current debug mode, scan now + // scan(&p, nonPagedPoolStart, nonPagedPoolEnd); + + return returnStatus; +} + +VOID +UnloadRoutine(_In_ PDRIVER_OBJECT DriverObject) { + PDEVICE_OBJECT deviceObject = DriverObject->DeviceObject; + UNICODE_STRING uniWin32NameString; + + if (SelfAllocKernelBuffer != nullptr) { + ExFreePoolWithTag(SelfAllocKernelBuffer, POOL_TAG); + } + + RtlInitUnicodeString(&uniWin32NameString, DOS_DEVICE_NAME); + IoDeleteSymbolicLink(&uniWin32NameString); + + if (deviceObject != nullptr) { + IoDeleteDevice(deviceObject); + } + + DbgPrint("[NAK] :: [+] Goodbye from Kernel\n"); +} + +PPOOL_HEADER +toPoolHeader(PPOOL_HEADER p, PVOID chunkAddr) { + p->addr = chunkAddr; + __try { + p->prevBlockSize = *(USHORT*)((long long int) chunkAddr + 0x0) & 0xff; + p->poolIndex = *(USHORT*)((long long int) chunkAddr + 0x0) >> 8; + p->blockSize = *(USHORT*)((long long int) chunkAddr + 0x2) & 0xff; + p->poolType = *(USHORT*)((long long int) chunkAddr + 0x2) >> 8; + p->tag = *(ULONG*)((long long int) chunkAddr + 0x4); + } + __except(EXCEPTION_EXECUTE_HANDLER) { + p->prevBlockSize = 0; + p->poolIndex = 0; + p->poolType = 0; + p->tag = 0; + } + return p; +} + +PPOOL_HEADER +tryNextChunk(PPOOL_HEADER p) { + return toPoolHeader(p, (PVOID)((long long int)p->addr + CHUNK_SIZE)); +} + +bool +validTag(PPOOL_HEADER p) { + // I know the compiler will optimize for me, so meeh :) + __try { + const char a = (char)(p->tag & 0xff); + const char b = (char)((p->tag & 0xff00) >> 8); + const char c = (char)((p->tag & 0xff0000) >> 16); + const char d = (char)(p->tag >> 24); + + // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-exallocatepoolwithtag + // > Each ASCII character in the tag must be a value in the range 0x20 (space) to 0x7E (tilde) + if (!(a >= 0x20 && a <= 0x7e) || + !(b >= 0x20 && b <= 0x7e) || + !(c >= 0x20 && c <= 0x7e) || + !(d >= 0x20 && d <= 0x7e)) + return false; + } + __except(EXCEPTION_EXECUTE_HANDLER) { + return false; + } + return true; +} + +bool +checkValidPool(PPOOL_HEADER /* p */) { + // https://subs.emis.de/LNI/Proceedings/Proceedings97/GI-Proceedings-97-9.pdf + // long long int offsetInPage = (long long int)p->addr % PAGE_SIZE; // OffsetInPage = addr % pagesize + // (offsetInPage % CHUNK_SIZE == 0) && // rule 1 + // (p->blockSize > 0) && // rule 2 + // (p->blockSize * CHUNK_SIZE + offsetInPage == PAGE_SIZE) && // rule 3 + // (p->prevBlockSize * CHUNK_SIZE <= offsetInPage) // rule 5 + return true; +} + +VOID +printChunkInfo(PPOOL_HEADER p) { + DbgPrint("[NAK] :: [+] ==== PoolStart 0x%p ====\n", p->addr); + DbgPrint("[NAK] :: [|] \tPreviousSize : 0x%x\n", p->prevBlockSize); + DbgPrint("[NAK] :: [|] \tPoolIndex : 0x%x\n", p->poolIndex); + DbgPrint("[NAK] :: [|] \tBlockSize : 0x%x\n", p->blockSize * CHUNK_SIZE); + DbgPrint("[NAK] :: [|] \tPoolType : 0x%x\n", p->poolType); + DbgPrint("[NAK] :: [|] \tPoolTag : 0x%lx [%c%c%c%c]\n", p->tag, p->tag, p->tag >> 8, p->tag >> 16, p->tag >> 24); + DbgPrint("[NAK] :: [+] ==== PoolEnd 0x%p ====\n", p->addr); +} + +VOID +scan(PPOOL_HEADER p, ULONG64 /* nonPagedPoolStart */, ULONG64 /* nonPagedPoolEnd */) { + DbgPrint("[NAK] :: [+] Scanning\n"); + + // scan by moving up and down 16 bytes? + // Or by moving by BlockSize and PreviousBlockSize? + + // Also, when to stop? + + // int i = 0; + for (p = tryNextChunk(p); + (long long int)p->addr < 0xFFFFFFFFFFFFFFFF; + p = tryNextChunk(p)) + { + // if (i++ >= 100000) break; + if (p->tag == 0) continue; + if (!validTag(p)) continue; + + printChunkInfo(p); + + // if (p->poolIndex == 0) { + // DbgPrint("[NAK] :: [+] Seems like we hit the first pool chunk"); + // break; + // } + if (p->tag != 'Proc' && p->tag != 'corP') + continue; + DbgPrint("[NAK] :: [+] HEY EPROCESS POOL CHUNK"); + break; + } + + DbgPrint("[NAK] :: [+] Finish scanning"); + + // go up + // for (; + // KernelBuffer = (PVOID)((long long int)chunk_addr + blockSize); + // ) { + // } + + // go down + // for (; + // KernelBuffer = (PVOID)((long long int)chunk_addr - prevBlockSize); + // ) { + // } +} diff --git a/KMDF Driver2/Driver.h b/KMDF Driver2/Driver.h new file mode 100644 index 0000000..b134cad --- /dev/null +++ b/KMDF Driver2/Driver.h @@ -0,0 +1,241 @@ +#ifndef _DRIVER_H +#define _DRIVER_H + +typedef struct _POOL_HEADER { + PVOID addr; + USHORT prevBlockSize; + USHORT poolIndex; + USHORT blockSize; + USHORT poolType; + ULONG tag; +} POOL_HEADER, *PPOOL_HEADER; + +struct _MI_SYSTEM_NODE_NONPAGED_POOL { + char reserved[0x60]; + PVOID NonPagedPoolFirstVa; + PVOID NonPagedPoolLastVa; +}; + +typedef struct _DBGKD_GET_VERSION64 { + USHORT MajorVersion; + USHORT MinorVersion; + UCHAR ProtocolVersion; + UCHAR KdSecondaryVersion; + USHORT Flags; + USHORT MachineType; + UCHAR MaxPacketType; + UCHAR MaxStateChange; + UCHAR MaxManipulate; + UCHAR Simulation; + USHORT Unused[1]; + ULONG64 KernBase; + ULONG64 PsLoadedModuleList; + ULONG64 DebuggerDataList; +} DBGKD_GET_VERSION64, *PDBGKD_GET_VERSION64; + +typedef struct _DBGKD_DEBUG_DATA_HEADER64 { + LIST_ENTRY64 List; + ULONG OwnerTag; + ULONG Size; +} DBGKD_DEBUG_DATA_HEADER64, *PDBGKD_DEBUG_DATA_HEADER64; + +typedef struct _KDDEBUGGER_DATA64 { + DBGKD_DEBUG_DATA_HEADER64 Header; + ULONG64 KernBase; + ULONG64 BreakpointWithStatus; + ULONG64 SavedContext; + USHORT ThCallbackStack; + USHORT NextCallback; + USHORT FramePointer; + USHORT PaeEnabled:1; + + // https://web.archive.org/web/20061110120809/http://www.rootkit.com/newsread.php?newsid=153 + ULONG64 KiCallUserMode; + ULONG64 KeUserCallbackDispatcher; + ULONG64 PsLoadedModuleList; + ULONG64 PsActiveProcessHead; + ULONG64 PspCidTable; + + ULONG64 ExpSystemResourcesList; + ULONG64 ExpPagedPoolDescriptor; + ULONG64 ExpNumberOfPagedPools; + + ULONG64 KeTimeIncrement; + ULONG64 KeBugCheckCallbackListHead; + ULONG64 KiBugcheckData; + + ULONG64 IopErrorLogListHead; + + ULONG64 ObpRootDirectoryObject; + ULONG64 ObpTypeObjectType; + + ULONG64 MmSystemCacheStart; + ULONG64 MmSystemCacheEnd; + ULONG64 MmSystemCacheWs; + + ULONG64 MmPfnDatabase; + ULONG64 MmSystemPtesStart; + ULONG64 MmSystemPtesEnd; + ULONG64 MmSubsectionBase; + ULONG64 MmNumberOfPagingFiles; + + ULONG64 MmLowestPhysicalPage; + ULONG64 MmHighestPhysicalPage; + ULONG64 MmNumberOfPhysicalPages; + + ULONG64 MmMaximumNonPagedPoolInBytes; + ULONG64 MmNonPagedSystemStart; + ULONG64 MmNonPagedPoolStart; + ULONG64 MmNonPagedPoolEnd; + + ULONG64 MmPagedPoolStart; + ULONG64 MmPagedPoolEnd; + ULONG64 MmPagedPoolInformation; + ULONG64 MmPageSize; + + ULONG64 MmSizeOfPagedPoolInBytes; + + ULONG64 MmTotalCommitLimit; + ULONG64 MmTotalCommittedPages; + ULONG64 MmSharedCommit; + ULONG64 MmDriverCommit; + ULONG64 MmProcessCommit; + ULONG64 MmPagedPoolCommit; + ULONG64 MmExtendedCommit; + + ULONG64 MmZeroedPageListHead; + ULONG64 MmFreePageListHead; + ULONG64 MmStandbyPageListHead; + ULONG64 MmModifiedPageListHead; + ULONG64 MmModifiedNoWritePageListHead; + ULONG64 MmAvailablePages; + ULONG64 MmResidentAvailablePages; + + ULONG64 PoolTrackTable; + ULONG64 NonPagedPoolDescriptor; + + ULONG64 MmHighestUserAddress; + ULONG64 MmSystemRangeStart; + ULONG64 MmUserProbeAddress; + + ULONG64 KdPrintCircularBuffer; + ULONG64 KdPrintCircularBufferEnd; + ULONG64 KdPrintWritePointer; + ULONG64 KdPrintRolloverCount; + + ULONG64 MmLoadedUserImageList; + + // NT 5.1 Addition + + ULONG64 NtBuildLab; + ULONG64 KiNormalSystemCall; + + // NT 5.0 QFE addition + + ULONG64 KiProcessorBlock; + ULONG64 MmUnloadedDrivers; + ULONG64 MmLastUnloadedDriver; + ULONG64 MmTriageActionTaken; + ULONG64 MmSpecialPoolTag; + ULONG64 KernelVerifier; + ULONG64 MmVerifierData; + ULONG64 MmAllocatedNonPagedPool; + ULONG64 MmPeakCommitment; + ULONG64 MmTotalCommitLimitMaximum; + ULONG64 CmNtCSDVersion; + + // NT 5.1 Addition + + ULONG64 MmPhysicalMemoryBlock; + ULONG64 MmSessionBase; + ULONG64 MmSessionSize; + ULONG64 MmSystemParentTablePage; + + // Server 2003 addition + + ULONG64 MmVirtualTranslationBase; + + USHORT OffsetKThreadNextProcessor; + USHORT OffsetKThreadTeb; + USHORT OffsetKThreadKernelStack; + USHORT OffsetKThreadInitialStack; + + USHORT OffsetKThreadApcProcess; + USHORT OffsetKThreadState; + USHORT OffsetKThreadBStore; + USHORT OffsetKThreadBStoreLimit; + + USHORT SizeEProcess; + USHORT OffsetEprocessPeb; + USHORT OffsetEprocessParentCID; + USHORT OffsetEprocessDirectoryTableBase; + + USHORT SizePrcb; + USHORT OffsetPrcbDpcRoutine; + USHORT OffsetPrcbCurrentThread; + USHORT OffsetPrcbMhz; + + USHORT OffsetPrcbCpuType; + USHORT OffsetPrcbVendorString; + USHORT OffsetPrcbProcStateContext; + USHORT OffsetPrcbNumber; + + USHORT SizeEThread; + + ULONG64 KdPrintCircularBufferPtr; + ULONG64 KdPrintBufferSize; + + ULONG64 KeLoaderBlock; + + USHORT SizePcr; + USHORT OffsetPcrSelfPcr; + USHORT OffsetPcrCurrentPrcb; + USHORT OffsetPcrContainedPrcb; + + USHORT OffsetPcrInitialBStore; + USHORT OffsetPcrBStoreLimit; + USHORT OffsetPcrInitialStack; + USHORT OffsetPcrStackLimit; + + USHORT OffsetPrcbPcrPage; + USHORT OffsetPrcbProcStateSpecialReg; + USHORT GdtR0Code; + USHORT GdtR0Data; + + USHORT GdtR0Pcr; + USHORT GdtR3Code; + USHORT GdtR3Data; + USHORT GdtR3Teb; + + USHORT GdtLdt; + USHORT GdtTss; + USHORT Gdt64R3CmCode; + USHORT Gdt64R3CmTeb; + + ULONG64 IopNumTriageDumpDataBlocks; + ULONG64 IopTriageDumpDataBlocks; + + // Longhorn addition + + ULONG64 VfCrashDataBlock; +} KDDEBUGGER_DATA64, *PKDDEBUGGER_DATA64; + +PPOOL_HEADER +toPoolHeader(PPOOL_HEADER p, PVOID chunkAddr); + +PPOOL_HEADER +tryNextChunk(PPOOL_HEADER p); + +bool +validTag(PPOOL_HEADER p); + +bool +checkValidPool(PPOOL_HEADER p); + +VOID +printChunkInfo(PPOOL_HEADER p); + +VOID +scan(PPOOL_HEADER p, ULONG64 nonPagedPoolStart, ULONG64 nonPagedPoolEnd); + +#endif diff --git a/KMDF Driver2/KMDF Driver2.vcxproj b/KMDF Driver2/KMDF Driver2.vcxproj new file mode 100644 index 0000000..e6b5fd7 --- /dev/null +++ b/KMDF Driver2/KMDF Driver2.vcxproj @@ -0,0 +1,163 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + Debug + ARM + + + Release + ARM + + + Debug + ARM64 + + + Release + ARM64 + + + + {905D3C7D-3EAD-4977-975E-B1FFD3E6FBE4} + {1bc93793-694f-48fe-9372-81e2b05556fd} + v4.5 + 12.0 + Debug + Win32 + KMDF_Driver2 + + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + true + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + Windows10 + false + WindowsKernelModeDriver10.0 + Driver + KMDF + Universal + + + + + + + + + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + DbgengKernelDebugger + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/KMDF Driver2/KMDF Driver2.vcxproj.filters b/KMDF Driver2/KMDF Driver2.vcxproj.filters new file mode 100644 index 0000000..a484801 --- /dev/null +++ b/KMDF Driver2/KMDF Driver2.vcxproj.filters @@ -0,0 +1,47 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {8E41214B-6785-4CFE-B992-037D68949A14} + inf;inv;inx;mof;mc; + + + + + Driver Files + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + \ No newline at end of file diff --git a/KMDF Driver2/KMDFDriver2.inf b/KMDF Driver2/KMDFDriver2.inf new file mode 100644 index 0000000..4c142fd --- /dev/null +++ b/KMDF Driver2/KMDFDriver2.inf @@ -0,0 +1,86 @@ +; +; KMDFDriver2.inf +; + +[Version] +Signature="$WINDOWS NT$" +Class=Sample ; TODO: edit Class +ClassGuid={78A1C341-4539-11d3-B88D-00C04FAD5171} ; TODO: edit ClassGuid +Provider=%ManufacturerName% +CatalogFile=KMDFDriver2.cat +DriverVer= ; TODO: set DriverVer in stampinf property pages + +[DestinationDirs] +DefaultDestDir = 12 +KMDFDriver2_Device_CoInstaller_CopyFiles = 11 + +; ================= Class section ===================== + +[ClassInstall32] +Addreg=SampleClassReg + +[SampleClassReg] +HKR,,,0,%ClassName% +HKR,,Icon,,-5 + +[SourceDisksNames] +1 = %DiskName%,,,"" + +[SourceDisksFiles] +KMDFDriver2.sys = 1,, +WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll=1 ; make sure the number matches with SourceDisksNames + +;***************************************** +; Install Section +;***************************************** + +[Manufacturer] +%ManufacturerName%=Standard,NT$ARCH$ + +[Standard.NT$ARCH$] +%KMDFDriver2.DeviceDesc%=KMDFDriver2_Device, Root\KMDFDriver2 ; TODO: edit hw-id + +[KMDFDriver2_Device.NT] +CopyFiles=Drivers_Dir + +[Drivers_Dir] +KMDFDriver2.sys + +;-------------- Service installation +[KMDFDriver2_Device.NT.Services] +AddService = KMDFDriver2,%SPSVCINST_ASSOCSERVICE%, KMDFDriver2_Service_Inst + +; -------------- KMDFDriver2 driver install sections +[KMDFDriver2_Service_Inst] +DisplayName = %KMDFDriver2.SVCDESC% +ServiceType = 1 ; SERVICE_KERNEL_DRIVER +StartType = 3 ; SERVICE_DEMAND_START +ErrorControl = 1 ; SERVICE_ERROR_NORMAL +ServiceBinary = %12%\KMDFDriver2.sys + +; +;--- KMDFDriver2_Device Coinstaller installation ------ +; + +[KMDFDriver2_Device.NT.CoInstallers] +AddReg=KMDFDriver2_Device_CoInstaller_AddReg +CopyFiles=KMDFDriver2_Device_CoInstaller_CopyFiles + +[KMDFDriver2_Device_CoInstaller_AddReg] +HKR,,CoInstallers32,0x00010000, "WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll,WdfCoInstaller" + +[KMDFDriver2_Device_CoInstaller_CopyFiles] +WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll + +[KMDFDriver2_Device.NT.Wdf] +KmdfService = KMDFDriver2, KMDFDriver2_wdfsect +[KMDFDriver2_wdfsect] +KmdfLibraryVersion = $KMDFVERSION$ + +[Strings] +SPSVCINST_ASSOCSERVICE= 0x00000002 +ManufacturerName="" ;TODO: Replace with your manufacturer name +ClassName="Samples" ; TODO: edit ClassName +DiskName = "KMDFDriver2 Installation Disk" +KMDFDriver2.DeviceDesc = "KMDFDriver2 Device" +KMDFDriver2.SVCDESC = "KMDFDriver2 Service" diff --git a/KMDF Driver2/findglobalkernelvars.png b/KMDF Driver2/findglobalkernelvars.png new file mode 100644 index 0000000..95a3e5e Binary files /dev/null and b/KMDF Driver2/findglobalkernelvars.png differ diff --git a/KMDF Driver2/kpcr.asm b/KMDF Driver2/kpcr.asm new file mode 100644 index 0000000..2c5190f --- /dev/null +++ b/KMDF Driver2/kpcr.asm @@ -0,0 +1,11 @@ +PUBLIC FindKdVersionBlock +.code _text + + +FindKdVersionBlock PROC PUBLIC +mov rax, gs:[108h] +ret +FindKdVersionBlock ENDP + + +END diff --git a/KMDF Driver2/note.md b/KMDF Driver2/note.md new file mode 100644 index 0000000..7eaaddf --- /dev/null +++ b/KMDF Driver2/note.md @@ -0,0 +1,53 @@ +Scanning the memory is not working well, we go with Pool tag quick scanning + +[address in kernel space](https://www.codemachine.com/article_x64kvas.html) + +find `MmNonPagedPoolStart` and `MmNonPagedPoolEnd` values in kernel variable. + +These two variables located inside `KdDebuggerDataBlock` of type `_KDDEBUGGER_DATA64`. `KdDebuggerDataBlock` can be found somewhere in `KdVersionBlock`. `KdVersionBlock` is a member of `KPCR`. `KPCR` pointer can be get through `gs:[0x0]` + +> Unfortunately this method stopped working in recent versions of Windows. Recently the KdVersionBlock member is always 0 and does not link to the kernel debugger block. + +[kdbg.c](https://raw.githubusercontent.com/libvmi/libvmi/master/libvmi/os/windows/kdbg.c) + +[KPCR at gs:[0x0]](https://sizzop.github.io/2016/07/07/kernel-hacking-with-hevd-part-3.html) + +[finding kdbg](http://scudette.blogspot.com/2012/11/finding-kernel-debugger-block.html) + +[finding kernel variables](http://moyix.blogspot.com/2008/04/finding-kernel-global-variables-in.html) + +[get kernel shellcode](https://github.com/FuzzySecurity/PSKernel-Primitives/blob/master/Get-KernelShellCode.ps1) + +[www.rootkit.com artifacts](https://github.com/fdiskyou/www.rootkit.com) + - GetVarXP.pdf + +[ghidra on fs/gs and kdbg](https://github.com/NationalSecurityAgency/ghidra/issues/1339) + +[big ram kdbg](https://laserkittens.com/big-ram-kernel-debugger-data-block/) + +[](blackstormsecurity.com/docs/NO_HAT_2019.pdf) + +> KPCR -> KdVersionBlock -> `_DBGKD_GET_VERSION64` -> `LIST_ENTRY _KDDEBUGGER_DATA64` (`GetDebuggerData()`) -> `_KDDEBUGGER_DATA64 KdDebuggerDataBlock` -> kernel variables + + + +> `_KPCR gs:[0]` -> `_DBGKD_GET_VERSION64 KdVersionBlock` -> `PLIST_ENTRY DebuggerDataList` -> `PLIST_ENTRY Flink` -> `Debugger block` + +This only works with windows x86, x64 Windows KdVersionBlock is always null. + +[KdVersionBlock](https://web.archive.org/web/20061110120809/http://www.rootkit.com/newsread.php?newsid=153) + +``` +_DBGKD_GET_VERSION64* KdVersionBlock; +__asm { + mov eax, gs:[0x108] + mov KdVersionBlock, eax +} +PLIST_ENTRY dbglist = KdVersionBlock->DebuggerDataList; +DebuggerBlock dbgBlock = (DebuggerBlock)*(dbglist->Flink); +``` + + + +`AuxKlibQueryModuleInformation` to get all `PsActiveProcessModules` +[Sample](https://correy.webs.com/articles/computer/c/AuxKlibQueryModuleInformation.C.txt) diff --git a/KMDF Driver2/peformat.h b/KMDF Driver2/peformat.h new file mode 100644 index 0000000..2d063a2 --- /dev/null +++ b/KMDF Driver2/peformat.h @@ -0,0 +1,209 @@ +// Copyright Ric Vieler, 2006 +// Support header for hookManager.c +// Contains required PE file format data structures used by GetFunctionAddress() + +#ifndef _PE_FORMAT_HEADER_ +#define _PE_FORMAT_HEADER_ + + +typedef unsigned short WORD; +typedef unsigned long DWORD; +typedef long LONG; +typedef unsigned char BYTE; +typedef unsigned long ULONG; +typedef unsigned short USHORT; +typedef unsigned char UCHAR; + typedef unsigned __int64 ULONGLONG; + + +// +// Image Format +// + +#define IMAGE_DOS_SIGNATURE 0x5A4D // MZ +#define IMAGE_NT_SIGNATURE 0x00004550 // PE00 + +typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header + WORD e_magic; // Magic number + WORD e_cblp; // Bytes on last page of file + WORD e_cp; // Pages in file + WORD e_crlc; // Relocations + WORD e_cparhdr; // Size of header in paragraphs + WORD e_minalloc; // Minimum extra paragraphs needed + WORD e_maxalloc; // Maximum extra paragraphs needed + WORD e_ss; // Initial (relative) SS value + WORD e_sp; // Initial SP value + WORD e_csum; // Checksum + WORD e_ip; // Initial IP value + WORD e_cs; // Initial (relative) CS value + WORD e_lfarlc; // File address of relocation table + WORD e_ovno; // Overlay number + WORD e_res[4]; // Reserved words + WORD e_oemid; // OEM identifier (for e_oeminfo) + WORD e_oeminfo; // OEM information; e_oemid specific + WORD e_res2[10]; // Reserved words + LONG e_lfanew; // File address of new exe header + } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; + + +// +// File header format. +// + +typedef struct _IMAGE_FILE_HEADER { + WORD Machine; + WORD NumberOfSections; + DWORD TimeDateStamp; + DWORD PointerToSymbolTable; + DWORD NumberOfSymbols; + WORD SizeOfOptionalHeader; + WORD Characteristics; +} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; + + +// +// Directory format. +// + +typedef struct _IMAGE_DATA_DIRECTORY { + DWORD VirtualAddress; + DWORD Size; +} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; + +#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 + +// +// Optional header format. +// + +typedef struct _IMAGE_OPTIONAL_HEADER { + // + // Standard fields. + // + + WORD Magic; + BYTE MajorLinkerVersion; + BYTE MinorLinkerVersion; + DWORD SizeOfCode; + DWORD SizeOfInitializedData; + DWORD SizeOfUninitializedData; + DWORD AddressOfEntryPoint; + DWORD BaseOfCode; + DWORD BaseOfData; + + // + // NT additional fields. + // + + DWORD ImageBase; + DWORD SectionAlignment; + DWORD FileAlignment; + WORD MajorOperatingSystemVersion; + WORD MinorOperatingSystemVersion; + WORD MajorImageVersion; + WORD MinorImageVersion; + WORD MajorSubsystemVersion; + WORD MinorSubsystemVersion; + DWORD Win32VersionValue; + DWORD SizeOfImage; + DWORD SizeOfHeaders; + DWORD CheckSum; + WORD Subsystem; + WORD DllCharacteristics; + DWORD SizeOfStackReserve; + DWORD SizeOfStackCommit; + DWORD SizeOfHeapReserve; + DWORD SizeOfHeapCommit; + DWORD LoaderFlags; + DWORD NumberOfRvaAndSizes; + IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; +} IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER; + +typedef struct _IMAGE_OPTIONAL_HEADER64 { + WORD Magic; + BYTE MajorLinkerVersion; + BYTE MinorLinkerVersion; + DWORD SizeOfCode; + DWORD SizeOfInitializedData; + DWORD SizeOfUninitializedData; + DWORD AddressOfEntryPoint; + DWORD BaseOfCode; + ULONGLONG ImageBase; + DWORD SectionAlignment; + DWORD FileAlignment; + WORD MajorOperatingSystemVersion; + WORD MinorOperatingSystemVersion; + WORD MajorImageVersion; + WORD MinorImageVersion; + WORD MajorSubsystemVersion; + WORD MinorSubsystemVersion; + DWORD Win32VersionValue; + DWORD SizeOfImage; + DWORD SizeOfHeaders; + DWORD CheckSum; + WORD Subsystem; + WORD DllCharacteristics; + ULONGLONG SizeOfStackReserve; + ULONGLONG SizeOfStackCommit; + ULONGLONG SizeOfHeapReserve; + ULONGLONG SizeOfHeapCommit; + DWORD LoaderFlags; + DWORD NumberOfRvaAndSizes; + IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; +} IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64; + +typedef struct _IMAGE_NT_HEADERS { + ULONG Signature; + IMAGE_FILE_HEADER FileHeader; + IMAGE_OPTIONAL_HEADER OptionalHeader; +} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32; + +typedef struct _IMAGE_NT_HEADER64 { + DWORD Signature; + IMAGE_FILE_HEADER FileHeader; + IMAGE_OPTIONAL_HEADER64 OptionalHeader; +} IMAGE_NT_HEADER64, *PIMAGE_NT_HEADER64; + +#define IMAGE_SIZEOF_SHORT_NAME 8 + +typedef struct _IMAGE_SECTION_HEADER { + UCHAR Name[IMAGE_SIZEOF_SHORT_NAME]; + union { + ULONG PhysicalAddress; + ULONG VirtualSize; + } Misc; + ULONG VirtualAddress; + ULONG SizeOfRawData; + ULONG PointerToRawData; + ULONG PointerToRelocations; + ULONG PointerToLinenumbers; + USHORT NumberOfRelocations; + USHORT NumberOfLinenumbers; + ULONG Characteristics; +} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; + +// +// Export Format +// + +typedef struct _IMAGE_EXPORT_DIRECTORY { + DWORD Characteristics; + DWORD TimeDateStamp; + WORD MajorVersion; + WORD MinorVersion; + DWORD Name; + DWORD Base; + DWORD NumberOfFunctions; + DWORD NumberOfNames; + DWORD AddressOfFunctions; // RVA from base of image + DWORD AddressOfNames; // RVA from base of image + DWORD AddressOfNameOrdinals; // RVA from base of image +} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; + +// Directory Entries + +#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory + +#endif + + diff --git a/KMDF Driver2/sioctl.h b/KMDF Driver2/sioctl.h new file mode 100644 index 0000000..627ad22 --- /dev/null +++ b/KMDF Driver2/sioctl.h @@ -0,0 +1,47 @@ +/*++ + +Copyright (c) 1997 Microsoft Corporation + +Module Name: + + SIOCTL.H + +Abstract: + + + Defines the IOCTL codes that will be used by this driver. The IOCTL code + contains a command identifier, plus other information about the device, + the type of access with which the file must have been opened, + and the type of buffering. + +Environment: + + Kernel mode only. + +--*/ + +// +// Device type -- in the "User Defined" range." +// +#define SIOCTL_TYPE 40000 +// +// The IOCTL function codes from 0x800 to 0xFFF are for customer use. +// +#define IOCTL_SIOCTL_METHOD_IN_DIRECT \ + CTL_CODE( SIOCTL_TYPE, 0x900, METHOD_IN_DIRECT, FILE_ANY_ACCESS ) + +#define IOCTL_SIOCTL_METHOD_OUT_DIRECT \ + CTL_CODE( SIOCTL_TYPE, 0x901, METHOD_OUT_DIRECT , FILE_ANY_ACCESS ) + +#define IOCTL_SIOCTL_METHOD_BUFFERED \ + CTL_CODE( SIOCTL_TYPE, 0x902, METHOD_BUFFERED, FILE_ANY_ACCESS ) + +#define IOCTL_SIOCTL_METHOD_NEITHER \ + CTL_CODE( SIOCTL_TYPE, 0x903, METHOD_NEITHER , FILE_ANY_ACCESS ) + + +#define DRIVER_FUNC_INSTALL 0x01 +#define DRIVER_FUNC_REMOVE 0x02 + +#define DRIVER_NAME "poolscanner" +