On Windows user-state debugging mechanism

Source: Internet
Author: User

We sigh onlydbg powerful and convenient at the same time, whether to consider the principle of its implementation?

As a technician know it is necessary to know why, this is our pursuit of the heart.

Recently in learning Zhang Banque Teacher's "software debugging", benefited a lot. Familiarity with the Windows debugging mechanism is a great benefit to our deep understanding of the operating system and the principles of game protection.

0x01

Preliminary discussion on debugging principle

The implementation of the debugging system ideas:

The debugger is connected to the debugged program, and the program sends debugging information like a debugger, and the debugger pauses the program to run after the debugging information, so the cycle is resumed.

Let's look at how to implement a simple debugger using the API provided by the operating system.

// start the process to be debugged or hook the debugger to a running process  = True;dword dwcontinuestatus;  while (bcontinue) {  = waitfordebugevent (&de, INFINITE);   Switch (De.dwdebugeventcode)  {  ...   default :    {      = dbg_continue;        Break ;    }  }  Continuedebugevent (De.dwprocessid, De.dwthreadid, dwcontinuestatus);}

When the debugger starts debugging, a new process or hook (attach) of the debugger is initiated to a running process, at which point the WIN32 system starts the server side of the debug interface, and the debugger calls the Waitfordebugevent function to wait for the debug server-side debug event to be raised The debugger handles the appropriate processing according to the debug event, and finally calls the Continuedebugevent function to request the debug server to continue executing the debugged process to wait for and process the next debug event.

0X02

The debugging mechanism of extracting cocoon and stripping silk

An in-depth analysis of three functions is essential to understand the Windows debugging mechanism in depth.

1.DebugActiveProcess

BOOL WINAPI debugactiveprocessself (_in_ DWORD dwprocessid) {NTSTATUS status;    HANDLE Targprocesshandle; Status= dbguiconnecttodbg ();//Debugobject    if(!nt_success (status))        {Basesetlastnterror (status); return false; } targprocesshandle=Gettargprocesshandle (DWPROCESSID); if(Targprocesshandle = =0)    {        return false; }    //Debugging a target processStatus =dbguidebugactiveprocess (Targprocesshandle); //close the target process handle regardless of whether the debug was successful or notZwclose (Targprocesshandle); if(!nt_success (status))        {Basesetlastnterror (status); return false; }    return true;}

The dbguiconnecttodbg function internally calls Zwcreatedebugobject to create a debug object and save the Debug object handle in the debugger The TEB structure of the current thread in dbgssreserved[1].

Where TEB can be obtained through fs:[0x18], dbgssreserved fields are not the same in different operating system versions, TEB in 0XF20 structure in the Win732 bit. Then we can get dbgssreserved through the assembly.

    __asm{        push    eax        mov        eax,fs:[0x18]        Lea        Eax,[eax+ 0xf20 ]        mov        dbgssreserved,eax        pop        eax    }

So what exactly is a debug object?

The debugging task goes smoothly in the event that the debugger interacts with the debugger, which is already well represented in the first diagram. Since it is a two-process interaction, it must involve inter-process communication, which I have summed up in the Windows process communication, which relies on all processes sharing kernel objects in high 2G kernel space.

such as event objects, pipe objects, and so on. Thus, it can be inferred that the debug object is a bridge between the debugger and the debugged program! the Debug object is saved in the debugger TEB thread environment variable block dbgssreserved[1] and is saved in the DebugPort field of the debugged process . (This is a detailed analysis) so it is possible to determine whether a process is being debugged

To see the DebugPort field of this process. One of the protection means of game protection is by constantly erasing debugport, so as to achieve the purpose of anti-debugging, so we found that with OD cannot attach the game, of course, we can pass the port to bypass this method of protection, this is not discussed here.

Gettargprocesshandle function is mainly to use the Zwopenprocess function to obtain the next process handle, here do not analyze, we mainly look at the last of this dbguidebugactiveprocess function.

 ntstatus dbguidebugactiveprocess (HANDLE htargprocess) {NTSTATUS status;    HANDLE Hdebugobject; Hdebugobject  = (getthreaddbgssreserved ()) [1      = zwdebugactiveprocess (htargprocess,hdebugobject);  if  (! return   status;  } Status  = Dbguiissueremotebreakin (htargprocess); //     if  (!    nt_success (status))    {dbguistopdebugging (htargprocess);  return   status;}  

Let's take a look at the Dbguiissueremotebreakin function.

This function is relatively simple main role is to create a remote thread under the remote breakpoint, if there is no breakpoint to intercept, then how to Debug.

To this debugactiveprocess function in the Ring3 under the analysis of the almost, left we can see the debugger and debug objects as parameters to call the system function zwdebugactiveprocess

Is it clear what I'm trying to say about this system call doing something in the kernel? Obviously the kernel puts the debug object in the DebugPort field of the debugging process!

But what zwdebugactiveprocess does in the kernel is more than that. Oh, this function mainly does three things:

(1) Get pointers to the debug process eprocess and Debug objects.

(2) Send a fabricated debug event to the Debug object. (When the debugger attaches to a process that is already running, in order to report debug events that have occurred previously but still make sense to the debugger, the debug subsystem "fabricates" some debug events to simulate past debug events, such as debug messages that are called fabricated debug messages).

(3) Call Dbgsetprocessdebugobject to set the Debug object to the Debug field of the debugged process, and call Dbgkpmarkprocesspeb to set the Beingdebugged field in PEB.

I think that learning new knowledge should be from the general beginning, must not be too key to the details, in a clear framework after the gradual understanding of the implementation of the problem. See here there must be a lot of questions, such as debug event structure is what, it is how to get, and how to pass through the debugging object? Let's find out what's going on here.

To take a debug event

First of all, we should understand what counts as debug events: A process was created by the debug process, a thread was created, a module was loaded ... These are debug events, so how does the debugger know?

In the operating system, there is a set of functions that begin with DBGK, which are collection routines. To create a thread, for example, let's take a look at debugging the message passing process.

When we call the CreateThread function, the function establishes the thread's necessary kernel objects and data structures, makes the necessary registrations, and eventually calls the Pspuserthreadstartup function, ready to start the thread. To support debugging, the Pspuserthreadstartup function always calls Dbgkcreatethread to collect debug events. The Dbgkcreatethread function checks to see if its DebugPort field is empty to determine if it is being debugged, and if it is debugged, the Dbgkpsendapimessage function is called to send a message to DebugPort. Similarly, LoadLibrary calls the system function ntmapviewofsection and then calls the acquisition function Dbgkmapviewofmapsection, Finally determine whether you are being debugged to decide whether to collect debug events to invoke Dbgkpsendapimessage.

We see the final call to Dbgkpsendapimessage in the Acquisition debug event, so what exactly does this function do?

Let's take a look at the definition of this function.




On Windows user-state debugging mechanism

Related Article

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.