Learn about Windows Kernel API

Source: Internet
Author: User

The Windows kernel API is the ntoskrnl.exe exported function . We can call the kernel API just like the API that invokes 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. Export is not documented, then we will declare. What is documented and not documented? Let's look at a function:

UCHAR *psgetprocessimagefilename(in peprocess Process);

Documentation: It is assumed that the function is exported and can be searched on MSDN. is to document that the function that we call the document is called directly.

Not documented: The assumption that the function has been exported, but not found on MSDN, is the non-documented function we want to invoke it, we have to manually declare.

Kernel programming is the same as the application layer, are API calls, are hooks, are anti- hook, the same programming thinking. Their essential difference is only in a sequence, such as looking at the picture - What is the difference between the essence : order out

The order in which functions are called from ring3 to SSDT layer bodies:

openprocesss-->ntdll! zwopenprocess-->ntos! zwopenprocess-->ntos! Ntopenprocess--> back. If you understand the kernel layer and application point of view, then that is openprocess has been called to ntopenprocess and back.

Example code:

Kernelapicode.c

#include <ntifs.h> #include <ntimage.h>//call function number # 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; The name of the process kpriority basepriority;                   ULONG ProcessId; Process of Pidulong Inheritedfromprocessid; ULONG Handlecount; ULONG reserved2[2]; Vm_counters vmcounters;io_counters iocounters;}  _system_processes, *psystem_processes;//system module information Structural Body node typedef struct _SYSTEM_MODULE_INFORMATION {ULONG reserved[2];            ULONG Base;            Base address of the module ulong Size;        The size of the module ULONG Flags;       USHORT Index;     USHORT Unknown;   USHORT Loadcount; USHORT Modulenameoffset;  CHAR imagename[256]; Module name} system_module_information, *psystem_module_information;//module chain structure typedef struct _TAGSYSMODULELIST{ULONG Ulcount; System_module_information smi[1];}MODULES, the *pmodules;//zwquerysysteminformation function was exported, but not documented, so to manually declare ntstatus __stdcall zwquerysysteminformation ( ULONG_PTR Systeminformationclass,//Call function number pvoid SystemInformation,//Information structure ULONG systeminformationlength,//Letter Pulong returnlength//return actual length)//In the drive layer traversal process void enumprocesslist () {//Declare variable ntstatus status; ULONG Neededsize,i; PVOID pbuffer = NULL; Used to point to buffer psystem_processes pInfo = NULL; Pointer to system_processes __try{//gets the actual byte length of the process and thread information that holds the system status = Zwquerysysteminformation ( Systemprocessesandthreadsinformation,null,0,&neededsize); if (status! = Status_info_length_mismatch) {//length mismatch Dbgprint ("! = Status_info_length_mismatch"); return;} Based on the obtained neededsize request nonpaged Memory pbuffer = ExAllocatePool (NonPagedPool, Neededsize), if (pbuffer! = NULL) {dbgprint ("neededsize :%d\r\n ", neededsize);//Use the 5th function to get information about the process and thread of the system status = Zwquerysysteminformation ( Systemprocessesandthreadsinformation,//systemprocessesandthreadsinformation = 5 pbuffer,neededsize, NULL);// If the call succeeds if (Nt_success (statUS) {Dbgprint ("zwquerysysteminformation () success\r\n");//pointer type conversion pinfo = (psystem_processes) pbuffer;while (TRUE) {// Pid=0, System if (Pinfo->processid = = 0) {dbgprint ("PID%5d system Idle process\r\n", Pinfo->processid);} else{//the PID of the print process and the name of the process dbgprint ("pid%5d%ws\r\n", Pinfo->processid, Pinfo->processname.buffer);//This is unicode}/ /If there is no next End if (Pinfo->nextentrydelta = = 0) {break;} Traverse the next pInfo = (psystem_processes) (((Puchar) pInfo) + Pinfo->nextentrydelta);}}} Exception handling __except (Exception_execute_handler) {//Output exception information Codedbgprint ("%08x\r\n", GetExceptionCode ());} Frees the requested Nonpaged memory resource if (pbuffer! = null) {Exfreepool (pbuffer);p buffer = null;}} Drive layer Traversal system module void Getkernelmoduleinfo () {//variable declaration ntstatus status; ULONG Neededsize, I; PVOID pbuffer = NULL; Used to point to buffer pmodules pmodulelist = NULL; Point to modules pointer __try{//Gets the size of the buffer that holds the information structure of the system module status = Zwquerysysteminformation (Systemmoduleinformation, null,0,& Neededsize); if (status! = Status_info_length_mismatch) {dbgprint ("! = Status_info_length_mismatch"); return;} //depending on the size of the neededsize, request the size of the nonpaged memory pbuffer = ExAllocatePool (NonPagedPool, neededsize); if (pbuffer) {// Call the function number 11来 get the system's module information status=zwquerysysteminformation (systemmoduleinformation,//systemmoduleinformation = 11pBuffer, Neededsize,null); if (nt_success (status)) {//pointer type conversion pmodulelist = (pmodules) pbuffer;//The information for the module that traverses the system for (i = 0; i< pmodulelist->ulcount; i++) {//print the base address of the system module, the size of the module, the name of the module dbgprint ("0x%08x:%d:%s\r\n", Pmodulelist->smi[i]. Base, Pmodulelist->smi[i]. Size, Pmodulelist->smi[i]. ImageName);}}} __except (Exception_execute_handler) {//Print exception code dbgprint ("%08x\r\n", GetExceptionCode ());} Frees the requested Nonpaged memory resource if (pbuffer) {exfreepool (pbuffer);p buffer = NULL;}} /** Create the registry *safekey the path to the registry *reg_type the key value type of the registry *valuename the name of the key value of the registry *value the value of the key value of the registry in */boolean Safe_createvaluekey (Pwchar SafeKey, Ulong_ptr Reg_type, Pwchar ValueName, Pwchar Value) {//DECLARE variable object_attributes objectattributes; Unicode_string regunicodestring, Unicode_valuename; NTSTATUS NTSTATUS; HANDLE Hregister; ULONG_PTR Ulvalue_dword; Ulong_ptr Ulresult = 0; BOOLEAN BREtok = False;//wchar string to unicode_string string rtlinitunicodestring (&unicode_valuename, ValueName); The name of the key value rtlinitunicodestring (&regunicodestring, SafeKey); Registry path//initialization objectattributesinitializeobjectattributes (&objectattributes,&regunicodestring,// Registry path obj_case_insensitive,//Case sensitive NULL, NULL);//Open Registry Ntstatus = Zwcreatekey (&hregister,//return registry handle KEY_ALL_ACC ESS,//registry permissions &objectattributes,0,null,reg_option_non_volatile,&ulresult); if (Nt_success (NtStatus)) { Bretok = true;//implements various functions according to the incoming parameter Reg_type//calls the Zwsetvaluekey function to set the registry switch (Reg_type) {case Reg_sz:{zwsetvaluekey ( Hregister,&unicode_valuename,//Key value name 0,reg_type,//Key value of type value,//Key value Wcslen (value) * *);D bgprint ("R eg_sz--Registry creation succeeded!\n ");              Case Reg_expand_sz:{zwsetvaluekey (Hregister,&unicode_valuename,//Name of the key value 0,reg_type,//Key value of type value, The value of the key value Wcslen (value) * *);D bgprint ("reg_expand_sz--Registry creation succeeded!\n"); 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)//value of key value);D b Gprint ("reg_dword--Registry creation succeeded!\n"); break;}} Close handle Zwclose (Hregister);} return Bretok;} //************************************************************************************************************* Drive unload routine function void Driverunload (in Pdriver_object driverobject) {dbgprint ("Unload Complete!\n");} Driver entry function Driverentryntstatus driverentry (pdriver_object driverobject, punicode_string registrypath) {// Set the driver's unload routine function driverobject->driverunload = driverunload;//traverse the system's process enumprocesslist ();// Traverse the system's Drive module Getkernelmoduleinfo ();//Create Registry Safe_createvaluekey (L "\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\ Services\\ ", REG_DWORD, L" Start ", (Pwchar) 0x3); Safe_createvaluekey (L "\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services\\", REG_SZ, L "start_string", L "hi~ I am AGP "); return status_success;}


Makefile File:

# # does not EDIT the 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#, which is a 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 + + preprocessorc_defines=$ (C_ Defines) sources=kernelapicode.c        drvversion.rc

Resources:

AGP Lecture materials Collation and learning



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learn about Windows Kernel API

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.