GetLastError
GetLastError() in the Win32 API retrieves the error code for the last operation, aiding in diagnosing and handling errors in Windows programming.
Sometimes when we are calling Win32 APIs from shellcode we need to understand why the function has not carried out the tasks we expected. The Win32 APIs have a really useful function called GetLastError
. We can make this one of the first functions we resolve and use it later in subsequent assembly code.
Resolving the function is the same as any other:
Now, if we are not seeing the results we expect from Win32 APIs, we can call GetLastError
and the error code will be in rax
after the call:
Once your shellcode is working as intended you can remove the GetLastError
code.
Example
The following example uses a the WinHttp
APIs to download some malicious shellcode, with the intention of injectiing it in to memory (this could be a basic stager):
The flow on the left shows the order in which the calls should be made. The flow on the right shows what happens if we forget to call WinHttpReceiveResponse
.
WinHttpQueryDataAvailable
will return 0
instead of the number of bytes in the shellcode. This is because it has failed. If we find this during debugging our mistake might not be that obvious.
During the different calls the HINTERNET
handle is used to track the request. If we use the GetLastError
call imediately after our mistake we can get an insight in to why it failed.
The 12019
error is the ERROR_INTERNET_INCORRECT_HANDLE_STATE
, which should help us diagnose the problem.
Last updated