Check if winapi function is available - c++

Is is possible in c++ to check if a function is available? For example SetThreadPriority. If it is available, I want to call it, if not I want to simply ignore it, as it is not critical for my application.

You can use the GetProcAddress function. The example in the link does exactly this kind of thing: it checks if the GetNativeSystemInfo is available and calls it if yes, otherwise it calls the GetSystemInfo function.

May be you are looking for Dynamic Linking Function. If so, then use LoadLibraryEx then GetProcAddress
This will allow you skip the DLL load if it is not available

Related

Using a windows kernal function via GetModuleHandle

I would like to use FsRtlIsDbcsInExpression (https://msdn.microsoft.com/en-us/library/windows/hardware/ff546803(v=vs.85).aspx) to do wild card checking exactly the same as Windows does it natively without have to re-implement it in my program. When I use:
auto module = GetModuleHandle(TEXT("NtosKrnl.exe"));
module turns up null. From what I can find on the internet, since this is a kernel mode function, KernelGetModuleBase is required. However, this function doesn't seem to resolve automatically and there are no msdn docs on it, so I am doubtful that is the solution. Does anyone have pointers for how to use function?
GetModuleHandle for ntoskrnl is going to fail because it's not loaded into your memory space. You can only call such functions from kernel.
You might want to try for the function PathMatch spec (https://msdn.microsoft.com/en-us/library/windows/desktop/bb773727%28v=vs.85%29.aspx). It appears to do the same job.

Can I access Windows Kernel system calls directly?

I have been doing research into Windows internals, and have just recently learned about system calls and I am wondering if it is possible to use these system calls like functions? I understand they aren't really meant to be accessed externally.
For instance: NtUserEmptyClipboard is a system call in Win32k.sys, and it's address is 0x117f
If I wanted to use this call like a function, how could I do so?
What you want to do depends heavily on the architecture you're interested, but the thing to know is, that ntdll.dll is the user-mode trampoline for every syscall - i.e. the only one who actually makes syscalls at the end of the day is ntdll.
So, let's disassemble one of these methods in WinDbg, by opening up any old exe (I picked notepad). First, use x ntdll!* to find the symbols exported by ntdll:
0:000> x ntdll!*
00007ff9`ed1aec20 ntdll!RtlpMuiRegCreateLanguageList (void)
00007ff9`ed1cf194 ntdll!EtwDeliverDataBlock (void)
00007ff9`ed20fed0 ntdll!shortsort_s (void)
00007ff9`ed22abbf ntdll!RtlUnicodeStringToOemString$fin$0 (void)
00007ff9`ed1e9af0 ntdll!LdrpAllocateDataTableEntry (void)
...
So, let's pick one at random, NtReadFile looks neato. Let's disassemble it:
0:000> uf ntdll!NtReadFile
ntdll!NtReadFile:
00007ff9`ed21abe0 4c8bd1 mov r10,rcx
00007ff9`ed21abe3 b805000000 mov eax,5
00007ff9`ed21abe8 0f05 syscall
00007ff9`ed21abea c3 ret
Here, we see that we stuff away rcx, put the syscall number into eax, then call the syscall instruction. Every syscall has a number that is assigned arbitrarily by Windows (i.e. this number is a secret handshake between ntdll and the kernel, and changes whenever Microsoft wants)
None of these instructions are "magic", you could execute them in your app directly too (but there's no practical reason to do so, of course - just for funsies)
EmptyClipboard is one of so-called "Win32 API" and NtUserEmptyClipboard is a corresponding "native API".
http://en.wikipedia.org/wiki/Native_API
Unlike Linux syscall(2), we are rarely supposed to directly call "native API". I heard they are in ntdll.dll rather than win32k.sys. But we should be able to invoke them just like normal functions defined in a normal DLL.
Is there any way to call the Windows Native API functions from the user mode?
I strongly doubt that 0x117f is the address you're looking for. I suspect it might be the value which you need to pass to GetProcAddress. But I don't know for sure, since those things vary across Windows versions (that's why ordinary people use documented functions instead)
The main part of the native API is exported via normal functions from ntdll.dll. You can load this dll into your process and call these functions just like any other API functions. As long as you have the right function prototypes and parameters, the calls will work just fine. What they do internally is transition from usermode to kernelmode and then they use an offset into the system service descriptor table (SSDT) to find the address of the function in kernel mode memory, and then the function is called. There is an open source project http://nativetest.codeplex.com/ that makes calls to the native api that you might refer to.
The functions in win32k.sys are not exposed in ntdll.dll. As far as I can tell they are not exposed anywhere. The address you have listed - I believe - is actually an offset into the SSDT. If you really needed to call this function, you would have to make the transition from usermode to kernelmode yourself, putting all the parameters for the function and the SSDT offset into the right places.
As others have recommended, I would suggest to find the usermode API to help accomplish what you want to do. FWIW, in user32.dll the function EmptyClipboard appears to forward directly to NtUserEmptyClipboard, according to the link /dump output.
1731 DF 0002018A EmptyClipboard = _NtUserEmptyClipboard#0

Extracting from a Dll in c++

I have a DLL given named Lib.ddl. In the dll i have a function named add that takes an integer as a parameter.
Using the windows API and by using the following class.
class WindoswAPI
{
public:
WindowsAPI();//constructor
//helper functions
~WindowsAPI();
private:
}
How do I load this library in the constructor of the class. Extract the function via helper functions, and unload the function in the destructor?
I have looked on the internet for solutions and help but i cant find any.
You should first look at LoadLibraryEx() in order to load the dll in your process, then you can use GetProcAddress() to obtain a pointer to a function by name. Note the HMODULE parameter requested from the second function is returned by the first. You have to carefully know the function signature to invoke it without causing GPFs, so don't be surprised if you have to do some debug before having it working.
First easy thing to check anyway are the return values of both functions: the first one should return something different from zero ( it actually returns the virtual address where the dll is loaded ), if it returns NULL, use GetLastError to have some hints.
The same for GetProcAddress, if it return zero something didn't work, and usually is the incorrect spelling of the function name. As I said before having back an address from GetProcAddress does not guarantee you have finished: you must know perfectly how to call the function. If you need help in discovering which name are exposed from the dll, you will find useful DUMPBIN.EXE, you should have it already available from the Visual Studio Tools command prompt.
When your code finish with the dll, you can try to unload it by using FreeLibrary().
Look at POCO C++ Libraries, it contains very nice crossplatfrom DLL-Loader to avoid hand-written workarounds and boilerplate.

calling kernel32.dll function without including windows.h

if kernel32.dll is guaranteed to loaded into a process virtual memory,why couldn't i call function such as Sleep without including windows.h?
the below is an excerpt quoting from vividmachine.com
5. So, what about windows? How do I find the addresses of my needed DLL functions? Don't these addresses change with every service pack upgrade?
There are multitudes of ways to find the addresses of the functions that you need to use in your shellcode. There are two methods for addressing functions; you can find the desired function at runtime or use hard coded addresses. This tutorial will mostly discuss the hard coded method. The only DLL that is guaranteed to be mapped into the shellcode's address space is kernel32.dll. This DLL will hold LoadLibrary and GetProcAddress, the two functions needed to obtain any functions address that can be mapped into the exploits process space. There is a problem with this method though, the address offsets will change with every new release of Windows (service packs, patches etc.). So, if you use this method your shellcode will ONLY work for a specific version of Windows. Further dynamic addressing will be referenced at the end of the paper in the Further Reading section.
The article you quoted focuses on getting the address of the function. You still need the function prototype of the function (which doesn't change across versions), in order to generate the code for calling the function - with appropriate handling of input and output arguments, register values, and stack.
The windows.h header provides the function prototype that you wish to call to the C/C++ compiler, so that the code for calling the function (the passing of arguments via register or stack, and getting the function's return value) can be generated.
After knowing the function prototype by reading windows.h, a skillful assembly programmer may also be able to write the assembly code to call the Sleep function. Together with the function's address, these are all you need to make the function call.
With some black magic you can ;). there have been many custom implementations of GetProcAddress, which would allow you to get away with not needing windows.h, this however isn't be all and end all and could probably end up with problems due to internal windows changes. Another method is using toolhlp to enumerate the modules in the process to get kernel.dll's base, then spelunks its PE for the EAT and grab the address of GetProcAddress. from there you just need function pointer prototypes to call the addresses correctly(and any structure defs needed), which isn't too hard meerly labour intensive(if you have many functions), infact under windows xp this is required to disable DEP due to service pack differencing, ofc you need windows.h as a reference to get this, you just don't need to include it.
You'd still need to declare the function in order to call it, and you'd need to link with kernel32.lib. The header file isn't anything magic, it's basically just a lot of function declarations.
I can do it with 1 line of assembly and then some helper functions to walk the PEB
file by hard coding the correct offsets to different members.
You'll have to start here:
static void*
JMIM_ASM_GetBaseAddr_PEB_x64()
{
void* base_address = 0;
unsigned long long var_out = 0;
__asm__(
" movq %%gs:0x60, %[sym_out] ; \n\t"
:[sym_out] "=r" (var_out) //:OUTPUTS
);
//: printf("[var_out]:%d\n", (int)var_out);
base_address=(void*)var_out;
return( base_address );
}
Then use windbg on an executable file to inspect the data structures on your machine.
A lot of the values you'll be needing are hard to find and only really documented by random hackers. You'll find yourself on a lot of malware writing sites digging for answers.
dt nt!_PEB -r #$peb
Was pretty useful in windbg to get information on the PEB file.
There is a full working implementation of this in my game engine.
Just look in: /DEP/PEB2020 for the code.
https://github.com/KanjiCoder/AAC2020
I don't include <windows.h> in my game engine. Yet I use "GetProcAddress"
and "LoadLibraryA". Might be in-advisable to do this. But my thought was the more
moving parts, the more that can go wrong. So figured I'd take the "#define WIN32_LEAN_AND_MEAN" to it's absurd conclusion and not include <windows.h> at all.

Call function in c++ dll without header

I would like to call a method from an dll, but i don't have the source neither the header file. I tried to use the dumpbin /exports to see the name of the method, but i can found the methods signature?
Is there any way to call this method?
Thanks,
If the function is a C++ one, you may be able to derive the function signature from the mangled name. Dependency Walker is one tool that will do this for you. However, if the DLL was created with C linkage (Dependency Walker will tell you this), then you are out of luck.
The C++ language does not know anything about dlls.
Is this on Windows? One way would be to:
open the dll up in depends.exe shipped with (Visual Studio)
verify the signature of the function you want to call
use LoadLibrary() to get load this dll (be careful about the path)
use GetProcAddress() to get a pointer to the function you want to call
use this pointer-to-function to make a call with valid arguments
use FreeLibrary() to release the handle
BTW: This method is also commonly referred to as runtime dynamic linking as opposed to compile-time dynamic linking where you compile your sources with the associated lib file.
There exists some similar mechanism for *nixes with dlopen, but my memory starts to fail after that. Something called objdump or nm should get you started with inspecting the function(s).
As you have found, the exports list in a DLL only stores names, not signatures. If your DLL exports C functions, you will probably have to disassemble and reverse engineer the functions to determine method signatures. However, C++ encodes the method signature in the export name. This process of combining the method name and signature is called "name mangling". This Stackoverflow question has a reference for determining the method signature from the mangled export name.
Try the free "Dependency Walker" (a.k.a. "depends") utility. The "Undecorate C++ Functions" option should determine the signature of a C++ method.
It is possible to figure out a C function signature by analysing beginnig of its disassembly. The function arguments will be on the stack and the function will do some "pops" to read them in reverse order. You will not find the argument names, but you should be able to find out their number and the types. Things may get more difficult with return value - it may be via 'eax' register or via a special pointer passed to the function as the last pseudo-argument (on the top of the stack).
If you indeed know or strongly suspect the function is there, you can dynamically load the DLL with loadLibrary and get a pointer to the function with getProcAddress. See MSDN
Note that this is a manual, dynamic way to load the library; you'll still have to know the correct function signature to map to the function pointer in order to use it. AFAIK there is no way to use the dll in a load-time capability and use the functions without a header file.
Calling non-external functions is a great way to have your program break whenever the 3rd party DLL is updated.
That said, the undname utility may also be helpful.