I read some code about debugger, and I'm confused about the variable the code use to define memory address. Sometimes it use DWORD, and sometimes it use LPVOID, can anyone tell me that why windows use LPVOID to define address?
LPVOID in so-called "hungarian" notation means "long pointer to void", that is void far *. The latter originates in 16-bit code and nowadays has no meaning. So, LPVOID now is just the same as void *, but the name is still maintained for the compatibility.
My guess would be that there is no guarantee that a pointer value will fit into a DWORD (eg. on a 64-bit OS)
In windows, a DWORD is explicitly a 32 bit int. A LPVOID value is explicitly pointer-size.
Related
I'm trying to invoke ZwCreateThread(). But since it is a undocumented function I don't know how to do it. The 3rd, 5th, 6th and 7th argument of the function?
How to initialize those structures to use them in ZwCreateThread()?
The question is a loaded one
I don't fully agree with the assessment by Basile in the comments that - if something is undocumented - it should not be used. But it requires extra caution for sure.
There is also a relevant bit of information missing from your question: kernel or user mode?!
Resources
I cannot answer regarding fasm, but if you know how to read C function prototypes and make those work for you, you can use one of the following resources to find the prototypes:
undocumented.ntinternals.net
the phnt offspring of the Process Hacker (mind the license!)
ReactOS tries to be a fairly faithful functional clone of Windows (the target version has been adjusted over the years)
The desired information is part of the NDK inside psfuncs.h
The Windows Research Kernel and its documentation have leaked and were available in several shapes and forms all over the web (IIRC this was based on Windows 2003 Server)
Microsoft documents some functions and structs as part of their Windows Driver Kits (WDKs, formerly Device Driver Kits [DDKs])
winternl.h is one of the headers
"Windows NT/2000 Native API Reference" by Gary Nebbett
"Undocumented Windows 2000 Secrets" by Sven B. Schreiber; IIRC the author made this available on his website as several PDFs some years ago
"Undocumented Windows NT" by Prasad Dabak, Sandeep Phadke, and Milind Borate
The syscall tables (j00ru/windows-syscalls) as a reference of sorts for availability of functions from user mode
For structs as found from the PDBs (debugging symbols) made available by Microsoft: Vergilius Project
Yet again for structs, but more useful for user mode: Terminus Project by ReWolf
Windows NT, Secret APIs and the Consequences by Bruce Ediger
To a lesser extent the "Windows Internals" books from Microsoft Press
A code search or GitHub/GitLab/etc search for some of your desired function names or related functions
E.g. in the source code to several debuggers or other very low-level tools, to binary instrumentation frameworks etc ...
Books and resources for related topics such as sandboxes, rootkits, bootkits, malware ...
Useful knowledge
ZwCreateThread and NtCreateThread are identical in user mode (you can even verify this by using dumpbin on ntdll.dll and checking the RVA of the two exports. This is true for most (if not all) Zw* and Nt* functions
This means their prototype is identical!
In kernel mode they differ, one of them does more checking and is supposed to receive calls via the SSDT from user mode, the other is supposed to be called from kernel mode.
The identical prototype notion also holds true here
... let's try to answer it
Up front: if what you are trying to achieve is to create a user mode thread, in all likelihood RtlCreateUserThread() is more likely what you are looking for (for reference phnt)!
The prototype for ZwCreateThread is as follows:
// source: ntzwapi.h from https://github.com/processhacker/phnt
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateThread(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ProcessHandle,
_Out_ PCLIENT_ID ClientId,
_In_ PCONTEXT ThreadContext,
_In_ PINITIAL_TEB InitialTeb,
_In_ BOOLEAN CreateSuspended
);
// for reference, Nebbett gives the prototype as:
NTSYSAPI
NTSTATUS
NTAPI
ZwCreateThread(
OUT PHANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN HANDLE ProcessHandle,
OUT PCLIENT_ID ClientId,
IN PCONTEXT ThreadContext,
IN PUSER_STACK UserStack,
IN BOOLEAN CreateSuspended
);
You probably noticed the difference in the parameter 7 (starting at 1) immediately: PUSER_STACK vs. PINITIAL_TEB. TEB stands for Thread Environment Block and is the extension of the TIB (IIRC: Thread Information Block). Compare Nebbett's take on the USER_STACK struct:
typedef struct _USER_STACK {
PVOID FixedStackBase;
PVOID FixedStackLimit;
PVOID ExpandableStackBase;
PVOID ExpandableStackLimit;
PVOID ExpandableStackBottom;
} USER_STACK, *PUSER_STACK;
... with the INITIAL_TEB from undocumented.ntinternals.net you will notice they're the same (also for reference phnt). Nebbett took a guess at the name at the time of his writing. But this right there is the reason why Basile cautions not to use undocumented functions. You have to put in your own research and can't blindly rely on others' research. Also you should apply a very defensive coding style when using those functions.
Either way, Nebbett lists CreateThread() and CreateRemoteThread() as related Windows APIs. The latter is obviously a superset of the former and ZwCreateThread() uses ProcessHandle for the target process. It's always worthwhile looking for and looking at related Windows APIs.
3rd parameter: _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
The _In_opt (see SAL) tells you, that you may pass a NULL pointer here. But if you insist on passing the object attributes and know what to put in them: InitializeObjectAttributes() - a macro - is there to help.
5th parameter: _Out_ PCLIENT_ID ClientId
The _Out_ tells you that you supply the space for this info to be filled. The CLIENT_ID combines process and thread ID into a struct. The struct can be found in the headers of the WDKs/DDKs (e.g. wdm.h or ntddk.h) and looks like this in C:
typedef struct _CLIENT_ID {
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID;
6th parameter: _In_ PCONTEXT ThreadContext
The CONTEXT is indeed a documented struct and used in official APIs such as SetThreadContext(). Its definition depends on the target architecture, but can be found in official MS headers.
This struct also plays a big role in exception handling, e.g. when resuming execution after an exception.
For ZwCreateThread() this defines the initial state of the thread, especially the initial address of the instruction pointer and the initial CPU register states (which explains why it depends on the target architecture).
7th parameter: _In_ PINITIAL_TEB InitialTeb
By now you should have an idea that you need to supply the space and initial values for this struct as well.
Conclusion
And this complicated "having to know and fill in all details" explains why in all likelihood you want to use:
typedef NTSTATUS (NTAPI *PUSER_THREAD_START_ROUTINE)(
_In_ PVOID ThreadParameter
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateUserThread(
_In_ HANDLE Process,
_In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
_In_ BOOLEAN CreateSuspended,
_In_opt_ ULONG ZeroBits,
_In_opt_ SIZE_T MaximumStackSize,
_In_opt_ SIZE_T CommittedStackSize,
_In_ PUSER_THREAD_START_ROUTINE StartAddress,
_In_opt_ PVOID Parameter,
_Out_opt_ PHANDLE Thread,
_Out_opt_ PCLIENT_ID ClientId
);
// again taken from phnt
This is much closer to CreateRemoteThreadEx and similar APIs. You don't have to care about the initial CONTEXT and don't have to deal with OBJECT_ATTRIBUTES or INITIAL_TEB.
I am using the masm assembler, and I am using the kernel32.lib to create heap memory, however on the windows API page for the HeapCreate procedure it does not tell me where it's return value is stored. (i.e. the handle to the heap)
I would assume that it is stored in EAX? since most procedures place their return value in EAX. After I call HeapCreate, I call HealAlloc to allocate some memory in my heap:
INCLUDE \masm32\include\kernel32.inc
INCLUDELIB \masm32\lib\kernel32.lib
.CODE
PUSH DWORD PTR 00h ;max size
PUSH DWORD PTR 00h ;initial size
PUSH DWORD PTR 04h ;flOption
CALL HeapCreate
PUSH DWORD PTR 04h ;dwBytes (the size in bytes)
PUSH DWORD PTR 04h ;dwFlag
PUSH EAX ;I am not sure if the heap handle is stored in EAX or not?
CALL HeapAlloc
END
Essentially, I do not know where the return value to HeapCreate is stored. If anyone could clarify where, I would appreciate it.
Thanks
The MSDN page for HeapCreate gives the following prototype for the function:
HANDLE WINAPI HeapCreate(
_In_ DWORD flOptions,
_In_ SIZE_T dwInitialSize,
_In_ SIZE_T dwMaximumSize
);
All x86 calling conventions leave the return value in R/EAX, so the resulting HANDLE will be found in either EAX (in 32-bit builds) or RAX (in 64-bit builds).
It depends on whether you are compiling for 32-bit or 64-bit.
The declaration of HeapCreate() is as follows:
HANDLE WINAPI HeapCreate(
_In_ DWORD flOptions,
_In_ SIZE_T dwInitialSize,
_In_ SIZE_T dwMaximumSize
);
WINAPI is a preprocessor macro that resolves to the __stdcall calling convention, which is meaningful only in 32-bit and is ignored in 64-bit.
In 32-bit, __stdcall stores return values up to 32 bits in EAX, and larger return values in EAX:EDX.
In 64-bit, the x64 calling convention stores return values in RAX (the first 32 bits of which are EAX).
HANDLE is a pointer type, so it is 32 bits in size on a 32-bit compilation, and 64 bits in size on a 64-bit compilation. However, MSDN states:
64-bit versions of Windows use 32-bit handles for interoperability. When sharing a handle between 32-bit and 64-bit applications, only the lower 32 bits are significant, so it is safe to truncate the handle (when passing it from 64-bit to 32-bit) or sign-extend the handle (when passing it from 32-bit to 64-bit). Handles that can be shared include handles to user objects such as windows (HWND), handles to GDI objects such as pens and brushes (HBRUSH and HPEN), and handles to named objects such as mutexes, semaphores, and file handles.
Because of this, using EAX alone may be valid for HANDLE values returned by HeapCreate() in both 32-bit and 64-bit compilations. However, the HANDLE returned by HeapCreate() is not generally shared across process boundaries, so it may take up more than 32 bits.
Best not to take chances one way or the other. Use EAX in 32-bit, and RAX in 64-bit, since that is what the respective calling conventions dictate.
My question is related to the WIN32 API for a keyboard event.
VOID WINAPI keybd_event(
_In_ BYTE bVk,
_In_ BYTE bScan,
_In_ DWORD dwFlags,
_In_ ULONG_PTR dwExtraInfo
);
this method accepts a BYTE for a Key value. As long as its a char things go fine but for a wchar_t its not working, obviously because of the data type difference. Is there any method exposed for a wchar_t datatypes or any other conversion I can do to send this word on to the screen?
Thanks
You don't send this function char per se, you send it a set of Virtual Key Codes, and these are limited in their range. So trying to send it a wchar_t type doesn't really make any sense.
Also you'll see this note in MSDN documentation for this function:
Note This function has been superseded. Use SendInput instead.
I should think you'd be better off using SendInput instead.
Is there a simple way to hook registry access of a process that my code executes? I know about SetWindowsHookEx and friends, but its just too complex... I still have hopes that there is a way as simple as LD_PRELOAD on Unix...
Read up on the theory of DLL Injection here: http://en.wikipedia.org/wiki/DLL_injection
However, I will supply you with a DLL Injection snippet here: http://www.dreamincode.net/code/snippet407.htm
It's pretty easy to do these types of things once you're in the memory of an external application, upon injection, you might as well be a part of the process.
There's something called detouring, which I believe is what you're looking for, it simply hooks a function, and when that process calls it, it executes your own function instead. (To ensure that it doesn't crash, call the function at the end of your function)
So if you were wanting to write your own function over CreateRegKeyEx
(http://msdn.microsoft.com/en-us/library/ms724844%28v=vs.85%29.aspx)
It might look something like this:
LONG WINAPI myRegCreateKeyEx(HKEY hKey, LPCTSTR lpSubKey, DWORD Reserved, LPTSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition)
{
//check for suspicious keys being made via the parameters
RegCreateKeyEx(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition);
}
You can get a very well written detour library called DetourXS here: http://www.gamedeception.net/threads/10649-DetourXS
Here is his example code of how to establish a detour using it:
#include <detourxs.h>
typedef DWORD (WINAPI* tGetTickCount)(void);
tGetTickCount oGetTickCount;
DWORD WINAPI hGetTickCount(void)
{
printf("GetTickCount hooked!");
return oGetTickCount();
}
// To create the detour
oGetTickCount = (tGetTickCount) DetourCreate("kernel32.dll", "GetTickCount", hGetTickCount, DETOUR_TYPE_JMP);
// ...Or an address
oGetTickCount = (tGetTickCount) DetourCreate(0x00000000, hGetTickCount, DETOUR_TYPE_JMP);
// ...You can also specify the detour len
oGetTickCount = (tGetTickCount) DetourCreate(0x00000000, hGetTickCount, DETOUR_TYPE_JMP, 5);
// To remove the detour
DetourRemove(oGetTickCount);
And if you can't tell, that snippet is hooking GetTickCount() and whenever the function is called, he writes "GetTickCount hooked!" -- then he executes the function GetTickCount is it was intended.
Sorry for being so scattered with info, but I hope this helps. :)
-- I realize this is an old question. --
Most winapi calls generate symbol table entries for inter modular calls, this makes it pretty simple to hook them, all you need to do is overwrite the IAT addresses. Using something such as MSDetours, it can be done safely in a few lines of code. MSDetours also provides the tools to inject a custom dll into the target process so you can do the hooking
SetWindowsHookEx won't help at all - it provides different functionality.
Check if https://web.archive.org/web/20080212040635/http://www.codeproject.com/KB/system/RegMon.aspx helps. SysInternals' RegMon uses a kernel-mode driver which is very complicated way.
Update: Our company offers CallbackRegistry product, that lets you track registry operations without hassle. And BTW we offer free non-commercial licenses upon request (subject to approval on case by case basis).
Specifically, I want to use Point-to-point Message Queue but because I am still using legacy codes in eVC++ 4 and it only support until PocketPC 2003SE SDK, I cannot find CreateMsgQueue and friends in the headers (the port to newer VisualStudio is still in progess)
I am using the Message Queue to do IPC with apps developed with WM-6.5-DTK (VS2005).
Update:
I am using the following code (taken from msgqueue.h) to store function pointers and load CoreDLL.dll using GetProcAddress() and LoadLibrary() respectively.
HANDLE /*WINAPI*/ (*CreateMsgQueue)(LPCWSTR lpName, LPMSGQUEUEOPTIONS lpOptions);
HANDLE /*WINAPI*/ (*OpenMsgQueue)(HANDLE hSrcProc, HANDLE hMsgQ
, LPMSGQUEUEOPTIONS lpOptions);
BOOL /*WINAPI*/ (*ReadMsgQueue)(HANDLE hMsgQ,
/*__out_bcount(cbBufferSize)*/ LPVOID lpBuffer, DWORD cbBufferSize,
LPDWORD lpNumberOfBytesRead, DWORD dwTimeout, DWORD *pdwFlags);
BOOL /*WINAPI*/ (*WriteMsgQueue)(HANDLE hMsgQ, LPVOID lpBuffer, DWORD cbDataSize,
DWORD dwTimeout, DWORD dwFlags);
BOOL /*WINAPI*/ (*GetMsgQueueInfo)(HANDLE hMsgQ, LPMSGQUEUEINFO lpInfo);
BOOL /*WINAPI*/ (*CloseMsgQueue)(HANDLE hMsgQ);
Is the above code alright since I need to comment out WINAPI and __out_bcount(cbBufferSize) in order for them to compile.
As pointed out by ctacke, it is actually available on PPC2003 SDK. The Requirement in the MSDN is wrong.
Btw, the above approach seems to work fine even after commenting out WINAPI and __out_bcount(cbBufferSize)