Example of the basic framework for driving communication

Source: Internet
Author: User

Example of the basic framework for driving communication

1. Write the Ring0 driver layer code:

 

// Codemsg. h Communication Control Code definition # ifndef _ DEFINE_H _ # define _ DEFINE_H _ // _ number: 0-> 2047: reserved for Microsoft reserved // 2047-> 4095: reserved for OEMs User-Defined # define CODEMSG (_ number) CTL_CODE (FILE_DEVICE_UNKNOWN, _ number, METHOD_BUFFERED, \ FILE_READ_DATA | FILE_WRITE_DATA) // define the control code # define INIT_FILE_NAME 2047 # endif // ++ ++ ++

// Ring0.h # ifndef _ KERNEL_MODULE_H _ # define _ KERNEL_MODULE_H _ # include
 
  
# Include "codemsg. h "// DEVICE object name # define Device L" \ DEVICE \ www.AntiGameProtect.com "// name of The Link symbol # define dosdevice l" \ DosDevices \ www.AntiGameProtect.com "PDEVICE_OBJECT DriverDeviceObject; # endif // ++ ++ ++
 

 

 

// Ring0.c # include "Ring0.h" // The driver uninstalls the routine function and releases some resources here. VOID DriverUnload (PDRIVER_OBJECT DriverObject) {UNICODE_STRING DeviceName; UNICODE_STRING DosDeviceName; // Delete the symbolic link RtlInitUnicodeString (& DosDeviceName, DOSDEVICE); disconnect (& DosDeviceName ); // Delete the driver object if (DriverDeviceObject! = NULL) IoDeleteDevice (DriverDeviceObject); dbuplint ("the driver has been uninstalled successfully! \ R \ n ");} // The default routine processing function NTSTATUS IODispatch (PDEVICE_OBJECT DeviceObject, pirirp) {Irp-> IoStatus. status = STATUS_SUCCESS; IoCompleteRequest (Irp, callback); return STATUS_SUCCESS;} // verify whether a pointer to a WCHAR content can access BOOLEAN ValidateWCHARString (WCHAR * pwzStr, ULONG_PTR Length) {ULONG I; __try {// check whether the pointer and size are NULL in the first step. if yes, it is unnecessary to verify if (* pwzStr = NULL | Length = 0) {return FALSE;} // cyclically checks the value in the pointer pwzStr for (I = 0; I <Le Ngth; I ++) {// check whether the memory is accessible. If (! MmIsAddressValid (PUCHAR) pwzStr + I) {// if one byte is unreadable, return FALSE; }}__ failed T (EXCEPTION_EXECUTE_HANDLER) {// return FALSE;} return TRUE;} // The processing function of the IRP communication routine NTSTATUS IOManager (PDEVICE_OBJECT DeviceObject, piririrp) {// obtain the current IrpStack, read the structure members and obtain the required control code IRPcodePIO_STACK_LOCATION StackLocation = IoGetCurrentIrpStackLocation (Irp); // obtain the control code IRPcodeULONG IRPcode = StackLocation-> Parameters. deviceIoControl. ioCo NtrolCode; WCHAR * buf; SIZE_T size; WCHAR * pwzCopyBuf = NULL; // obtain the memory buffer buf passed in at the application layer = (WCHAR *) Irp-> AssociatedIrp. systemBuffer; // size of the bytes in the memory buffer = (SIZE_T) Irp-> Size; // set the Irp status Irp-> IoStatus. status = STATUS_SUCCESS; switch (IRPcode) {case CODEMSG (INIT_FILE_NAME): // The buf passed in from the application layer. You cannot predict whether the value can be accessed. Therefore, here we need to verify the validity of the buf we passed in to access the buf // on the driver layer, here I wrote a ValidateWCHARString to verify this variable _ try {// determine the validity of the Buffer if (ValidateWCHARString (bu F, size) {// prompt-the application layer data is transferred to the driver layer dbuplint ("Buf ==> % ws: % d \ r \ n", buf, size ); // apply for memory, similar to new at the application layer, and give the identifier 'fp' pwzCopyBuf = (WCHAR *) ExAllocatePoolWithTag (NonPagedPool, size, 'fp '); // if the memory application is successful if (pwzCopyBuf) {// memory initialization memset (pwzCopyBuf, 0, size); // copy to the memory memcpy (pwzCopyBuf, buf, size); // display the string information obtained from the application layer dbuplint ("CopyBuf ==>% ws \ r \ n", pwzCopyBuf ); // use the C language below the driver to follow the windows rules. The Applied memory must be released. // Remember to release the memory ExFreePool (pwzCopyBuf); }}__ failed T (EXCEPTION_EXECUTE_HANDLER) {// get the abnormal status code Irp-> IoStatus. status = GetExceptionCode ();} break; default: Irp-> IoStatus. status = STATUS_INVALID_DEVICE_REQUEST;} // sets the return code IoCompleteRequest (Irp, IO_NO_INCREMENT) for the Irp; return Irp-> IoStatus. status;} // The driver's entry function DriverEntryNTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING theRegistryPath) {UNICODE_STRING DeviceName; UNICODE_STRING DosDeviceName; NTSTATUS status; // initialize the driver symbol name // UNICODE_STRING is a struct, similar to the struct in win32, such as SYSTEMTIME // In Win system, the kernel struct can be obtained through windbg or wrk/* lkd> dt_unicode_stringnt! _ UNICODE_STRING + 0x000 Length: Uint2B // text Length + 0x002 MaximumLength: Uint2B // maximum Length + 0x004 Buffer: Ptr32 Uint2B // text content, is of the unicode type, that is, WCHAR * // DEVICE name string RtlInitUnicodeString (& DeviceName, DEVICE); // The Symbolic Link string RtlInitUnicodeString (& DosDeviceName, DOSDEVICE ); // create the device object status = IoCreateDevice (DriverObject, // ptr to caller object0, // extension device allocated byte number & DeviceName, // device name FILE_DEVICE_UNKNO WN, 0, // no special caracteristicsFALSE, // we can open your handles in same time & DeviceObject); // [OUT] ptr to the created objectif (! NT_SUCCESS (status) {return STATUS_NO_SUCH_DEVICE;} // a symbolic link is also required. Otherwise, the communication status between the driver and the application layer is changed to IoCreateSymbolicLink (& DosDeviceName, & DeviceName ); if (! NT_SUCCESS (status) {IoDeleteDevice (DriverDeviceObject); return success;} // sets the driver to unload the routine function DriverObject-> DriverUnload = DriverUnload; // IRP_MJ_CREATE, which responds to the application layer function CreateFile, when the application layer calls this function, it will enter this routine DriverObject-> MajorFunction [IRP_MJ_CREATE] = IODispatch; // The following functions correspond to the application layer CloseHandle, ReadFile, and WriteFile functions DriverObject-> MajorFunction [IRP_MJ_CLOSE] = IODispatch; DriverObject-> MajorFunction [IRP_MJ_READ] = IODispatch; DriverObject-> MajorFunction [IRP_MJ_WRITE] = IODispatch; // generally, we communicate with the application layer through the IRP_MJ_DEVICE_CONTROL routine, this routine corresponds to the DeviceIoControlDriverObject at the application layer-> MajorFunction [IRP_MJ_DEVICE_CONTROL] = IOManager; // DeviceIoControl () // set the communication mode-direct I/O DeviceObject-> Flags | = DO_DIRECT_IO; // set the file to align with DeviceObject-> AlignmentRequirement = FILE_WORD_ALIGNMENT; // After device Initialization is complete, you can work with DeviceObject-> Flags & = ~ DO_DEVICE_INITIALIZING; // a message is displayed, indicating that the Driver has been loaded successfully! \ R \ n "); return STATUS_SUCCESS ;} // ++ ++ +

 

2. Write the Ring3 Application Layer Code:

 

// Ring3.cpp # include
 
  
# Include
  
   
// Header file containing control code # include ".. \ Ring0 \ codemsg. h "// send the request BOOL CallDriver (char * ID, char * lpBuffer) {HANDLE service = 0; HANDLE device = 0; char ret [1024] to the driver; WCHAR ToSend [512]; DWORD code =-1; DWORD bytes; // open the device object device = CreateFile ("\\\\. \ www.AntiGameProtect.com ", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (! Device | device = INVALID_HANDLE_VALUE) {printf ("failed to open the driver, failed to load the driver. % d \ r \ n ", GetLastError (); return FALSE;} // determines whether the input command is"-file "if (! Strcmp (ID, "-file") {// corresponds to the control code below our driver. Code = INIT_FILE_NAME;} // determine whether the driver's control code is valid if (code =-1) {printf ("invalid ID \ r \ n"); return FALSE ;} // convert the ascii code lpBuffer string to the unicode code string ToSendMultiByteToWideChar (CP_ACP, 0, lpBuffer,-1, ToSend, sizeof (ToSend); DeviceIoControl (device, CODEMSG (code ), // The driver's control code ToSend, // input buffer (wcslen (ToSend) + 1) * 2, // input buffer size & ret, // output buffer sizeof (ret), // output buffer size & bytes, // The number of returned bytes is NULL); // disable the driver file CloseHandle (device ); printf ("finished! \ R \ n "); return TRUE;} // main function void main (int argc, char * argv []) {// determine the legality of user input if (argc! = 3) {printf ("Example: % s ID CommandLine \ r \ n", argv [0]); return ;} // call the driver code CallDriver (argv [1], argv [2]); return ;}
  
 



 

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.