How does one read a localized name from the registry? - c++

Consider the following registry export:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WinSock2\Parameters\Protocol_Catalog9\Catalog_Entries\000000000001]
;...
"ProtocolName"="#%SystemRoot%\\System32\\wshtcpip.dll,-60100"
The intention here appears to be for someone to load the DLL in question, and use some form of API retrieve the actual name. But I don't know what that API is :/
I'd like to avoid loading the DLL into my address space (and thus call DLL_PROCESS_ATTACH) if at all possible; can't really trust third party DLLs to be trustworthy.

RegLoadMUIString will do the necessary for you. Note however, that it was introduced in Vista so won't help if you need to support XP.
If you want to avoid code in the DLL running whilst you extract resources, use LoadLibraryEx passing LOAD_LIBRARY_AS_IMAGE_RESOURCE | LOAD_LIBRARY_AS_DATAFILE, or possibly LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE. Once you have done that, you can call LoadString to extract the MUI value.

This is going to help:
HMODULE hModule = LoadLibrary(_T("wshtcpip.dll")); // LoadLibraryEx is even better
TCHAR pszValue[1024] = { 0 };
INT nResult = LoadString(hModule, 60100, pszValue, _countof(pszValue));
LoadString will take care of downloading resource from MUI, if needed. LoadString uses thread locale, which you might want to override prior to the call.
Also: Loading Language Resources on MSDN.

Related

Hook APIs that imported to program by LoadLibrary/GetProcAddress

I know how I can hook functions from the IAT table, but I have a problem with APIs which were imported by calling LoadLibrary/GetProcAddress functions. I want to know exactly how someone could hook those functions. I realize that I should hook the GetProcAddress function but how can I check the parameters that were passsed to that function?
For example, consider a program which is going to include MessageBoxW via LoadLibrary/GetProcAddress, how can I hook that MessageBoxW and then check the parameters that have been passed to it?
I have searched a lot in StackOverflow and Google, but I couldn't find a step-by-step tutorial about this. So, if you have such a tutorial or article, I would be really grateful to read them.
In order to hook APIs that they are loaded into a binary dynamically with help of LoadLibrary/GetProcAddress, you should intercept return address of the GetProcAddress and name of the functions that passed to it (for example, consider a program try to load MessageBoxA in this way).
In the second step, you should save that original address of MessageBoxA API in a variable like OriginalMessageBoxA.
In the third and final step, you should return address of your modified API (HookedMessageBoxA) to the callee of the GetProcAddress so when the program try to call that address, program redirected to your function. Something like the following one:
VOID* HookedGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
if (std::string(lpProcName).compare("MessageBoxA") == 0)
{
OMessageBoxA = (PMessageBoxA)GetProcAddress(hModule, lpProcName);
return HookedMessageBoxA;
}
else
{
return OGetProcAddress(hModule, lpProcName);
}
}
In that moment, caller will go through your HookedMessageBoxA and you can check parameters that passed to MessageBoxA. As folks said, it is kinda same like normal IAT hook with a minor changes and tricks.

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
Would this approach suffice?
if so, how do I get the name of the calling module?
if so, how do I get the name of the calling module?
get return address by call _ReturnAddress
get base address of the image that contains this return address -
RtlPcToFileHeader
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");

Using GetProcAddress and EasyHook to hook class methods and constructors

I've had plenty of success using EasyHook to hook system API routines (in C++) out of libraries. These libraries have always been flat and basically filled with globally callable routines. Here is a small sample using MessageBeep() out of the User32.dll library (minus setup code):
HMODULE hUser32 = GetModuleHandle ( L"User32" );
FARPROC TrampolineMethod; // This would have been set to my new replacement trampoline method.
TRACED_HOOK_HANDLE hHook = new HOOK_TRACE_INFO();
NTSTATUS status;
status = LhInstallHook(
GetProcAddress(hUser32, "MessageBeep"),
TrampolineMethod,
(PVOID)0x12345678,
hHook);
This is all works great. The problem is, I now have a need to hook methods out of a class, not just a global function. I don't really care about the object itself, I'm really more interested in examining the parameters of the method and that's it. I don't know how to syntactically identify the routine in the function name parameter for GetProcAddress(), and I'm not even sure if GetProcAddress() supports it. For example, I'd like to hook the Pen::SetColor() method out of the gdiplus.dll library:
HMODULE hGDIPlus = GetModuleHandle ( L"Gdiplus" );
FARPROC TrampolineMethod; // This would have been set to my new replacement trampoline method.
TRACED_HOOK_HANDLE hHook = new HOOK_TRACE_INFO();
NTSTATUS status;
status = LhInstallHook(
GetProcAddress(hGDIPlus, "Pen.SetColor"), // this is probably wrong or not possible here
TrampolineMethod,
(PVOID)0x12345678,
hHook);
This doesn't work of course and I don't think the GetProcAddress(hGDIPlus, "Pen.SetColor") is correct. How do I specify a member function of a class to GetProcAddress()? Is this even possible? Also, how would this look if I wanted to hook a constructor such as Pen::Pen()?
The Portable Executable (PE) format that Windows uses doesn't really supports exporting or importing objects or their methods, so that's not what GdiPlus (or any other DLL) uses internally. The object notation is probably an abstraction implemented in the import library for the DLL.
If you take a look at GdiPlus's export table with the Dependency Walker tool (Windows SDK), or similar, you will see
GdipGetPenColor
GdipSetPenColor
etc.
So it is basically no different than the legacy exports, like MessageBeep.

C++ How do we make our application start on computer startup (and of course, after a user signed in)?

How do we make our application start on computer startup (and of course, after the user had signed in)?
And no, I am not making a virus.
Does registry editing sound like a good idea?
My OS is Windows 8.
However, I will try to make my application available for all possible Window OS.
The correct way to do this is simply to add a shortcut to your application's executable to the user's Startup folder. You do not need to (and should not) modify the registry.
Advanced users know how to do this manually already, but it may also be an option you want to provide as part of your installer and/or a configuration dialog in your application.
To do this from C++ code, you will need to do two things:
Retrieve the location of the current user's Startup folder.
This is accomplished by calling the SHGetKnownFolderPath function and specifying the KNOWNFOLDERID of the folder you're interested in. In this case, that would be FOLDERID_Startup.
Sample code:
std::wstring GetStartupFolderPath()
{
PWSTR pszPath;
HRESULT hr = SHGetKnownFolderPath(&FOLDERID_Startup,
0, // no special options required
NULL, // no access token required
&pszPath);
if (SUCCEEDED(hr))
{
// The function succeeded, so copy the returned path to a
// C++ string, free the memory allocated by the function,
// and return the path string.
std::wstring path(pszPath);
CoTaskMemFree(static_cast<LPVOID>(pszPath));
return path;
}
else
{
// The function failed, so handle the error.
// ...
// You might want to throw an exception, or just return an
// empty string here.
throw std::runtime_error("The SHGetKnownFolderPath function failed");
}
}
Note, however, that while SHGetKnownFolderPath is the recommended function to use, it is supported only by Windows Vista and later. If you need to support older versions of the operating system, you'll need to call it dynamically on newer versions where it is available, and otherwise fall back to calling the SHGetFolderPath function. This one takes a different type of identifier, a CSIDL value. The one you want is CSIDL_STARTUP.
Create a shortcut to your application's executable.
This is accomplished using a different set of Shell API functions. I won't bother writing up sample code here because it's all quite well explained on MSDN already: Shell Links
Now you just connect the dots: when you create the shortcut to your application's executable, specify the user's Startup folder as its destination path.
The only other thing to be aware of is that there are actually multiple Startup folders. Each user has one, which is the one we retrieved above using FOLDERID_Startup. About 99% of the time, that's the one you want. Putting a shortcut to your app there will cause it to be launched automatically when that user logs on.
However, there is also a global Startup folder that is shared by all users. This one is identified by FOLDERID_CommonStartup (or CSIDL_COMMON_STARTUP) and requires administrative privileges to add items to. That makes sense, of course, because whatever you put in there is going to launch automatically when any user logs on to the computer. Only administrators can affect global behavior like this. And chances are, your app doesn't need this anyway.
Start menu
Simplest solution is to place .lnk of .bat file into the Start Menu\On startup folder. This is easiest and not too sneaky against the user.
Registry:
Another solution is creating the key in the registry keys:
[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run] //All users
[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce] //All users once
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run] //Currend user
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce] //Current user once
This is not that transparent - so a bit more agressive against the user.
On windows you can put a shortcut to your application in the Startup folder, or you can implement it as a service.
And that "I am not making a virus" does make you sound guilty... Maybe it is a keylogger? ;)
There are a lot of ways, but they all depend on your OS. For windows take a look at the "Task Schedualer" under "Administrative tools" in the control panel.
Maybe something like this? Note, this code snippet is not written by me.
#include <windows.h>
void Reg() {
::HKEY Handle_Key = 0;
::DWORD Dispoition = 0;
::RegOpenKeyEx( HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
0,
KEY_ALL_ACCESS,
&Handle_Key );
const unsigned char Path[ MAX_PATH ] = "C:\\Windows\\YourProgramName.exe";
::RegSetValueEx( Handle_Key, "My Directory", 0, 1, Path, sizeof( unsigned char ) );
};
What do you guys think?

How to replace WinAPI functions calls in the MS VC++ project with my own implementation (name and parameters set are the same)?

I need to replace all WinAPI calls of the
CreateFile,
ReadFile,
SetFilePointer,
CloseHandle
with my own implementation (which use low-level file reading via Bluetooth).
The code, where functions will be replaced, is Video File Player and it already works with the regular hdd files.
It is also needed, that Video Player still can play files from HDD, if the file in the VideoPlayer input is a regular hdd file.
What is the best practice for such task?
I suggest that you follow these steps:
Write a set of wrapper functions, e.g MyCreateFile, MyReadFile, etc, that initially just call the corresponding API and pass the same arguments along, unmodified.
Use your text editor to search for all calls to the original APIs, and replace these with calls to your new wrapper functions.
Test that the application still functions correctly.
Modify the wrapper functions to suit your own purposes.
Note that CreateFile is a macro which expands to either CreateFileW or CreateFileA, depending on whether UNICODE is defined. Consider using LPCTSTR and the TCHAR functions so that your application can be built as either ANSI or Unicode.
Please don't use #define, as suggested in other responses here, as this will just lead to maintenance problems, and as Maximilian correctly points out, it's not a best-practice.
You could just write your new functions in a custom namespace. e.g.
namespace Bluetooth
{
void CreateFile(/*params*/);
void etc...
}
Then in your code, the only thing you would have to change is:
if (::CreateFile(...))
{
}
to
if (Bluetooth::CreateFile(...))
{
}
Easy! :)
If you're trying to intercept calls to these APIs from another application, consider Detours.
If you can edit the code, you should just re-write it to use a custom API that does what you want. Failing that, use Maximilian's technique, but be warned that it is a maintenance horror.
If you cannot edit the code, you can patch the import tables to redirect calls to your own code. A description of this technique can be found in this article - search for the section titled "Spying by altering of the Import Address Table".
This is dangerous, but if you're careful you can make it work. Also check out Microsoft Detours, which does the same sort of thing but doesn't require you to mess around with the actual patching.
If you really want to hijack the API, look at syringe.dll (L-GPL).
I don't think this is best practice but it should work if you put it in an include file that's included everywhere the function you want to change is called:
#define CreateFile MyCreateFile
HRESULT MyCreateFile(whatever the params are);
Implementation of MyCreateFile looks something like this:
#undef CreateFile
HRESULT MyCreateFile(NobodyCanRememberParamListsLikeThat params)
{
if (InputIsNormalFile())
CreateFile(params);
else
// do your thing
}
You basically make every CreateFile call a MyCreateFile call where you can decide if you want need to use your own implementation or the orginal one.
Disclaimer: I think doing this is ugly and I wouldn't do it. I'd rather search and replace all occurences or something.