Tuesday, June 24, 2014

ShareCount As Anti-Debugging Trick

In this post i will share with you an Anti-Debugging trick that is very similar to the "PAGE_EXECUTE_WRITECOPY" trick mentioned here, where we had to flag code section as writeable such that any memory write to its page(s) would force OS to change the page protection from PAGE_EXECUTE_WRITECOPY to PAGE_EXECUTE_READWRITE. But in this case we don't have to make any modifications to the code section's page protection. We will just query the process for its current working set info. Among the stuff we receive querying the working set of a process are two fields, "Shared" and "ShareCount".

By default the OS assumes the memory pages of code section (Non-writable sections) should share physical memory across all process instances. This is true till one process instance commits a memory-write to the shared page. At this point the page becomes no longer shared. Thus, querying the working set of the process and inspecting the "Shared" and/or "ShareCount" fields for our Code section pages would reveal the presence  of  debugger, only if the debugger uses INT3 for breakpoints.


To implement the trick, all you have to do is call the "QueryWorkingSet" or "QueryWorkingSetEx" functions.

N.B. You can also use the "ZwQueryVirtualMemory" function with the "MemoryInformationClass" parameter set to MemoryWorkingSetList for more portable code.

Code from here and demo from here. Tested on Windows 7.

For any suggestions, leave me a comment or drop me a mail waliedassar@gmail.com.

You can also follow me on Twitter @waleedassar