Thursday, April 2, 2009

FltLockUserBuffer locks the buffer in CORRECT process context- HOW?

The WDK documentation says "The caller can be running in any process context. FltLockUserBuffer automatically locks the buffer in the correct process context." Remember that in our legacy filters we used to call MmProbeAndLockPages in the correct process context to lock the pages? Well, the fact is that we can do the same thing that FltLockUserBuffer does, to lock the pages properly, no matter in which process context we are.

Anyways, let's see how FltLockUserBuffer locks the buffer of a process properly even if it is called from a different process context.

Let's see a portion of the disassembly for FltLockUserBuffer and it becomes obvious as to how it is able to lock the pages in correct process context.


 

f84cc355 ff15b4df4cf8    call dword ptr [fltMgr!_imp__IoThreadToProcess (f84cdfb4)]

f84cc35b 50        push eax

f84cc35c ff36        push dword ptr [esi]

f84cc35e ff1568df4cf8    call dword ptr [fltMgr!_imp__MmProbeAndLockProcessPages (f84cdf68)]

f84cc364 834dfcff    or dword ptr [ebp-4],0FFFFFFFFh

f84cc368 807de700    cmp byte ptr [ebp-19h],0


 

In the disassembly, you can see 2 functions that make things obvious: IoThreadToProcess and MmProbeAndLockProcessPages.

So, what does each function do? Well, IoThreadToProcess returns a PEPROCESS given a PETHREAD. And if you remember, FLT_CALLBACK_DATA structure already has a parameter 'Thread' which identifies the thread that initiated the I/O. So, from this thread, the target process is found using the IoThreadToProcess function. The next function is MmProbeAndLockProcessPages. As the name suggests, it locks the pages of a particular process.

Let's see a portion of the disassembly of MmProbeAndLockProcessPages.

8059c5d8 e85bb0f5ff        call nt!KeStackAttachProcess (804f7638)

8059c5dd c745e401000000    mov dword ptr [ebp-1Ch],1

8059c5e4 8975fc        mov dword ptr [ebp-4],esi

8059c5e7 ff7514            push dword ptr [ebp+14h]

8059c5ea ff7510            push dword ptr [ebp+10h]

8059c5ed ff7508            push dword ptr [ebp+8]

8059c5f0 e8c19bf6ff        call nt!MmProbeAndLockPages (805061b6)


 

As you can see, MmProbeAndLockProcessPages internally calls KeStackAttachProcess to attach to the target process for which the pages have to be locked. Once it gets attached, it then calls MmProbeAndLockPages to lock the pages!


 

Simple and sweet! J

No comments:

Post a Comment