Which module is called my exported DLL function?

Background

I am developing a Windows C ++ DLL module that exports a single function

__declspec(dllexport) void Run() 

Motivation

I would like to implement some access rights to my function. I want unauthorized modules to activate my DLL process.

I don't need a reliable / bulletproof mechanism. I like to β€œprotect” this process from other modules working under my own application.

An approach

Get the name of the calling module and decide based on the name if access is granted.

Question

  • Would such an approach suffice?
  • if so, how do I get the name of the calling module?
+5
source share
1 answer

if so, how do I get the name of the calling module?

so the code could be like that

 HMODULE hmod; if (RtlPcToFileHeader(_ReturnAddress(), (void**)&hmod)) { WCHAR sz[MAX_PATH]; if (GetModuleFileName(hmod, sz, MAX_PATH)) { DbgPrint("%p %S\n", hmod, sz); } } 

about - is this work in XP? yes, but with one note. _ReturnAddress CL intrinsic - therefore it does not depend on the version of os (for example, gcc exists __builtin_return_address (0)) GetModuleFileName is also a very old api function and exists in win2000, xp, everywhere. o RtlPcToFileHeader - it is exported (and implemented) to ntdll.dll in all versions of Windows from xp to the latest. also start with win2003, it is also exported from kernel32.dll, but implemented here - just go to ntdll.RtlPcToFileHeader - so if you want to use this on xp as well - link with ntdll.lib and put it before kernel32.lib in libs order or you can get it this runtime GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader");

or even if someone is afraid that RtlPcToFileHeader will be removed from ntdll (it certainly is not), you can use this GetProcAddress(GetModuleHandle(g_xp ? L"ntdll" : L"kernel32"), "RtlPcToFileHeader");

+5
source

Source: https://habr.com/ru/post/1266220/


All Articles