Catching Image Unload

Hi,
I was wondering, using PsSetLoadImageNotifyRoutine I can get a callback each time an image LOADS (or mapped) to the memory. Is there an opposite callback?
What if I want to also get information each time an image UNLOADS (or unmapped)?

Thank you.

I don’t believe there is a kernel-mode callback which can provide this functionality. Since I’ve read your previous posts and I am aware that you’re intercepting process execution and patching the starting up program for monitoring, you can use this as leverage to control execution flow to NtUnmapViewOfSection, and alike. These routines are exported by NTDLL which will perform the system-call transition.

Good idea? Probably not. However, user-mode hooking is not as much of a concern compared to patching of the Windows Kernel. Microsoft do offer their own library for user-mode hooking, and it’s called Microsoft Detours. There’s an Express version which is free for 32-bit software and has some commercial usage restrictions, and then there’s a paid version which you can only purchase after speaking to Microsoft. Writing your own user-mode API hooking library isn’t a big deal anyway.

You’ll at least be able to process checks before allowing/denying the operation, or log the data for future reference. Bear in mind that direct system calls will bypass this technique by default so you’ll need to do a lot of extensive things to work-around this downside, which can cause more harm than good, and I’ve mentioned this because you previously noted being involved in analysis of malicious software, so it would be non-decent of me not to make sure you’re aware of this.

Keep looking for options before jumping into the API hooking bandwagon because a documented and stable approach will always be best over less-documented and less-stable approaches, like API hooking.