idanshmu
idanshmu

Reputation: 5251

Which module called my DLL exported function?

Background

I'm developing a C++ windows DLL module that exports a single function

__declspec(dllexport) void Run()

Motivation

I would like to implement some sort of accessing rights to my function. I wish to prevent unauthorized modules from activating my DLL proc.

I don't need a robust/bullet proof mechanism. I only like to "defend" this proc from other modules running under my own app.

Approach

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

Question

  1. Would this approach suffice?
  2. if so, how do I get the name of the calling module?

Upvotes: 4

Views: 680

Answers (1)

RbMm
RbMm

Reputation: 33706

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

  1. get return address by call _ReturnAddress
  2. get base address of the image that contains this return address - RtlPcToFileHeader
  3. finally call GetModuleFileName function

so code can be like this

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

about - are this work in XP ? yes, but with one note. _ReturnAddress is CL intrinsic - so not depended from os version (for say gcc exist __builtin_return_address (0) ) GetModuleFileName also very old api function and exist in win2000, xp, everywhere. about RtlPcToFileHeader - it exported (and implemented) in ntdll.dll in all windows versions from xp to latest. also begin from win2003 it also exported from kernel32.dll but implementation here - simply jump to ntdll.RtlPcToFileHeader - so if want use this on xp also - link with ntdll.lib and place it before kernel32.lib in libs order or can get it it runtime by GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader");

or even if somebody afraid that RtlPcToFileHeader will be removed from ntdll (this is of course no) can use this GetProcAddress(GetModuleHandle(g_xp ? L"ntdll" : L"kernel32"), "RtlPcToFileHeader");

Upvotes: 4

Related Questions