Windows Kernel Api learning, windows Kernel api

Source: Internet
Author: User

Windows Kernel Api learning, windows Kernel api

Function exported by apipolicntoskrnl.exe in windows. We can call the kernel api just like the api at the application layer. However, the kernel api should note that if the function is exported and the function is documented (that is, it can be searched directly on msdn ). The ExFreePool function is exported and documented, so we can call it directly. If the exported file is not documented, We need to declare it. What is docalization and non-docalization? Let's look at a function:

UCHAR * PsGetProcessImageFileName (in peprocess Process );

 

Documented: assume that the function is exported and can be searched on msdn. That is, docized functions are called directly.

Undocumented: assume that the function has been exported, but it is not found on msdn. If the function is not documented, We must manually declare it if we want to call it.

 

Kernel programming, like the application layer, is api calling, Hook, anti-Hook, and the same programming thinking. The essential difference lies in a sequential order, for example, looking at the figure-what is the essential difference: Order loss

The sequence in which functions are called from ring3 to the ssdt layer:

OpenProcesss --> ntdll! ZwOpenProcess --> ntos! ZwOpenProcess --> ntos! NtOpenProcess -->. If you understand it from the perspective of the kernel layer and application, openprocess is always called until NtOpenProcess has a back end.

 

Sample Code:

KernelApiCode. c

# Include <ntifs. h> # include <ntimage. h> // call function # define SystemModuleInformation 11 # define SystemProcessesAndThreadsInformation 5 // system process information structure typedef struct _ SYSTEM_PROCESSES {ULONG NextEntryDelta; ULONG ThreadCount; ULONG Reserved [6]; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ProcessName; // process name KPRIORITY BasePriority; ULONG ProcessId; // process PIDULONG InheritedFr OmProcessId; ULONG HandleCount; ULONG Reserved2 [2]; VM_COUNTERS VmCounters; IO_COUNTERS IoCounters;} _ SYSTEM_PROCESSES, * PSYSTEM_PROCESSES; // system module information struct node typedef struct _ SYSTEM_MODULE_INFORMATION {ULONG Reserved [2]; ULONG Base; // Module Base Address ULONG Size; // module Size ULONG Flags; USHORT Index; USHORT Unknown; USHORT LoadCount; USHORT ModuleNameOffset; CHAR ImageName [256]; // Module name} SYSTEM_MODULE_INFORMATION, * PSYSTEM _ MODULE_INFORMATION; // The typedef struct _ tagSysModuleList {ULONG ulCount; SYSTEM_MODULE_INFORMATION smi [1];} MODULES, * PMODULES; // The ZwQuerySystemInformation function is exported, but not documented, therefore, you must manually declare NTSTATUS _ stdcall ZwQuerySystemInformation (ULONG_PTR SystemInformationClass, // call function no. PVOID SystemInformation, // information structure ULONG SystemInformationLength, // The Byte Length of the Information struct PULONG ReturnLength // the actual length returned); // traverses the process VOID EnumProcessList (){// Declare the variable NTSTATUS status; ULONG NeededSize, I; PVOID pBuffer = NULL; // point to the buffer zone PSYSTEM_PROCESSES pInfo = NULL; // pointer to SYSTEM_PROCESSES _ try {// obtain the actual byte length of the process and thread information that stores the system. status = ZwQuerySystemInformation (SystemProcessesAndThreadsInformation, NULL, 0, & NeededSize ); if (status! = STATUS_INFO_LENGTH_MISMATCH) {// The length does not match dbuplint ("! = STATUS_INFO_LENGTH_MISMATCH "); return;} // apply for non-Paging memory pBuffer = ExAllocatePool (NonPagedPool, NeededSize) based on the obtained NeededSize; if (pBuffer! = NULL) {dbuplint ("NeededSize: % d \ r \ n", NeededSize ); // use the 5th function to obtain information about system processes and threads. status = ZwQuerySystemInformation (SystemProcessesAndThreadsInformation, // SystemProcessesAndThreadsInformation = 5 pBuffer, NeededSize, NULL ); // if the call is successful if (NT_SUCCESS (status) {dbuplint ("ZwQuerySystemInformation () success \ r \ n"); // pointer type conversion pInfo = (PSYSTEM_PROCESSES) pBuffer; while (TRUE) {// PID = 0, if (pInfo-> ProcessId = 0) {dbuplint (" PID % 5d System Idle Process \ r \ n ", pInfo-> ProcessId );} else {// print the PID of the process and the name of the Process dbuplint ("PID % 5d % ws \ r \ n", pInfo-> ProcessId, pInfo-> ProcessName. buffer); // here is unicode} // end if (pInfo-> NextEntryDelta = 0) {break;} // traverse the next pInfo = (PSYSTEM_PROCESSES) (PUCHAR) pInfo) + pInfo-> NextEntryDelta) ;}}}// Exception Handling _ handle t (EXCEPTION_EXECUTE_HANDLER) {// output the exception information codedbuplint ("% 08x \ r \ n", GetExceptionCode ();} // release the requested non-Paging Save resource if (pBuffer! = NULL) {ExFreePool (pBuffer); pBuffer = NULL ;}// the driver layer traverses the system module VOID GetKernelModuleInfo () {// The declared NTSTATUS status of the variable; ULONG NeededSize, I; PVOID pBuffer = NULL; // point to buffer PMODULES pModuleList = NULL; // point to MODULES pointer _ try {// obtain the buffer size of the system module information structure. status = ZwQuerySystemInformation (SystemModuleInformation, NULL, 0, & NeededSize); if (status! = STATUS_INFO_LENGTH_MISMATCH) {dbuplint ("! = STATUS_INFO_LENGTH_MISMATCH "); return;} // Based on the NeededSize, apply for the non-Paging memory size pBuffer = ExAllocatePool (NonPagedPool, NeededSize); if (pBuffer) {// call function 11 to obtain information about the system module. status = ZwQuerySystemInformation (SystemModuleInformation, // SystemModuleInformation = 11 pBuffer, NeededSize, NULL); if (NT_SUCCESS (status )) {// pointer type conversion pModuleList = (PMODULES) pBuffer; // traverses the information of the system module for (I = 0; I <pModuleList-> ulCount; I ++) {// print the base address, module size, and module of the system module The block name dbuplint ("0x % 08X: % d: % s \ r \ n", pModuleList-> smi [I]. base, pModuleList-> smi [I]. size, pModuleList-> smi [I]. imageName) ;}}__ T (EXCEPTION_EXECUTE_HANDLER) {// print the abnormal code dbuplint ("% 08x \ r \ n", GetExceptionCode ());} // release the requested non-Paging memory resource if (pBuffer) {ExFreePool (pBuffer); pBuffer = NULL ;}} /** create registry * SafeKey registry path * Reg_Type registry key Value type * ValueName registry key Value name * Value registry key Value */BOOLEAN Safe_CreateValueKey (PWCHAR SafeKey, ULONG_PTR R Eg_Type, PWCHAR ValueName, PWCHAR Value) {// declare the variable incluobjectattributes; UNICODE_STRING RegUnicodeString, identifier; NTSTATUS ntStatus; HANDLE hRegister; ULONG_PTR identifier; ULONG_PTR ulResult = 0; BOOLEAN bRetOK = FALSE; // convert WCHAR string to UNICODE_STRING RtlInitUnicodeString (& Unicode_ValueName, ValueName); // key value name RtlInitUnicodeString (& RegUnicodeString, SafeKey); // registry path // initialize objectAttri ButesInitializeObjectAttributes (& objectAttributes, & RegUnicodeString, // registry path OBJ_CASE_INSENSITIVE, // case sensitive NULL, NULL); // open the Registry ntStatus = ZwCreateKey (& hRegister, // return the Registry handle KEY_ALL_ACCESS, // registry permission & objectAttributes, 0, NULL, REG_OPTION_NON_VOLATILE, & ulResult); if (NT_SUCCESS (ntStatus) {bRetOK = TRUE; // implement various functions based on the input parameter Reg_Type // call the ZwSetValueKey function to set the switch (Reg_Type) of the Registry {case REG_SZ: {ZwSetValueKey (hRegister, & Unicode_ValueName, // key Value name 0, Reg_Type, // key Value type Value, // key Value wcslen (Value) * 2 ); dbuplint ("REG_SZ -- registry created successfully! \ N "); break;} case REG_EXPAND_SZ: {ZwSetValueKey (hRegister, & Unicode_ValueName, // key Value type Value, // key Value wcslen (Value) * 2); dbuplint ("REG_EXPAND_SZ -- registry created successfully! \ N "); break;} case REG_DWORD: {ulValue_DWORD = sizeof (REG_DWORD); ZwSetValueKey (hRegister, & Unicode_ValueName, // key value name 0, Reg_Type, // key Value type & Value, sizeof (ulValue_DWORD) // key Value); dbuplint ("REG_DWORD -- registry created successfully! \ N "); break ;}/// close handle ZwClose (hRegister);} return bRetOK ;} //************************************** **************************************** **************************************** * ******* // The VOID DriverUnload (IN PDRIVER_OBJECT DriverObject) function of the driver uninstall routine) {dbuplint ("Uninstall completed! \ N ");} // driver entry function DriverEntryNTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) {// set the driver's uninstall routine function DriverObject-> DriverUnload = DriverUnload; // traverse the system process EnumProcessList (); // traverse the system's driver module GetKernelModuleInfo (); // create the Registry Safe_CreateValueKey (L "\ Registry \ Machine \ SYSTEM \ CurrentControlSet \ Services \", REG_DWORD, L "Start", (PWCHAR) 0x3); Safe_CreateValueKey (L "\ Registry \ Machine \ SYSTEM \ Curren TControlSet \ Services \ ", REG_SZ, L" Start_String ", L" Hi ~ I am agp "); return STATUS_SUCCESS ;}


Makefile file:

## DO NOT EDIT THIS FILE!!!  Edit .\sources. if you want to add a new source# file to this component.  This file merely indirects to the real make file# that is shared by all the driver components of the Windows NT DDK#!INCLUDE $(NTMAKEENV)\makefile.def

Sources File

TARGETNAME=KernelApiCodeTARGETPATH=objTARGETTYPE=DRIVER# Additional defines for the C/C++ preprocessorC_DEFINES=$(C_DEFINES)SOURCES=KernelApiCode.c\        drvversion.rc


Organized code and documentation: http://download.csdn.net/detail/qq1084283172/8862791


References:

Organize and learn the teaching materials of AGP



Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.