├── readme.md ├── sleep_duck ├── tools.h ├── head.h ├── stack_tracker.h ├── sleep_duck.vcxproj.filters ├── tools.cpp ├── sleep_duck.vcxproj ├── sleep_duck.cpp └── stack_tracker.cpp ├── sleep_duck.sln ├── .gitattributes └── .gitignore /readme.md: -------------------------------------------------------------------------------- 1 | 检测sleepmask就如同喝水一样 2 | 详细介绍: 3 | https://key08.com/index.php/2025/07/13/2716.html 4 | -------------------------------------------------------------------------------- /sleep_duck/tools.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "head.h" 3 | namespace Tools { 4 | auto EnableDebugPrivilege(bool bEnable) -> bool; 5 | auto Is64BitPorcess(HANDLE hProcess) -> bool; 6 | auto FindPatternInMemory(uint64_t StartAddress, size_t MemorySize, 7 | std::string pattern) -> uint64_t; 8 | }; // namespace Tools 9 | -------------------------------------------------------------------------------- /sleep_duck/head.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #pragma comment(lib, "dbghelp.lib") 15 | #include "tlhelp32.h" 16 | 17 | #include "include/capstone/capstone.h" 18 | #include "include/capstone/x86.h" 19 | #include 20 | 21 | #pragma comment(lib, "capstone64.lib") 22 | 23 | #include "tools.h" 24 | #include "stack_tracker.h" 25 | -------------------------------------------------------------------------------- /sleep_duck/stack_tracker.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "head.h" 3 | enum class _features { kNone, kNonCallOnly, kCallRip, kCallReg, kSyscall }; 4 | class StackTracker { 5 | private: 6 | bool readSuccess; 7 | bool isWow64; 8 | HANDLE targetProcess; 9 | std::vector> insList; 10 | csh capstoneHandle; 11 | uint64_t ins_ip, ins_ip_address, baseAddr, trackSize; 12 | auto getNextIns() -> std::shared_ptr; 13 | auto LookslikeValidEntry(cs_insn* insn, size_t count) -> bool; 14 | inline auto is_call(cs_insn* ins) -> bool; 15 | 16 | template 17 | auto matchCode(T match_fn, B process_fn, 18 | std::optional num_operands, 19 | std::vector> operand_types) 20 | -> bool; 21 | auto rpm(uintptr_t address, size_t readSize) -> std::vector; 22 | 23 | public: 24 | cs_insn* insn = nullptr; 25 | size_t disasmCount = 0; 26 | std::vector SuccessReadedBuffer; 27 | _features feature; 28 | StackTracker(HANDLE hProcess, uint64_t StartAddress, size_t trackSize, 29 | bool isX32); 30 | ~StackTracker(); 31 | auto PrintAsm() -> void; 32 | auto CalcNextJmpAddress() -> std::pair; 33 | auto TryFindValidDisasm(uint64_t baseAddr, size_t maxOffset) -> bool; 34 | }; 35 | -------------------------------------------------------------------------------- /sleep_duck.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.35731.53 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sleep_duck", "sleep_duck\sleep_duck.vcxproj", "{8A01CC2B-278C-411F-BEB7-286DC920E493}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Debug|x64.ActiveCfg = Debug|x64 17 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Debug|x64.Build.0 = Debug|x64 18 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Debug|x86.ActiveCfg = Debug|Win32 19 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Debug|x86.Build.0 = Debug|Win32 20 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Release|x64.ActiveCfg = Release|x64 21 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Release|x64.Build.0 = Release|x64 22 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Release|x86.ActiveCfg = Release|Win32 23 | {8A01CC2B-278C-411F-BEB7-286DC920E493}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {52DFFDE6-0BC8-468E-8698-A824D5F47E90} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /sleep_duck/sleep_duck.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | 源文件 20 | 21 | 22 | 源文件 23 | 24 | 25 | 源文件 26 | 27 | 28 | 29 | 30 | 头文件 31 | 32 | 33 | 头文件 34 | 35 | 36 | 头文件 37 | 38 | 39 | -------------------------------------------------------------------------------- /sleep_duck/tools.cpp: -------------------------------------------------------------------------------- 1 | #include "tools.h" 2 | // 71 A3 52 10 47 AE A0 3 | #define INRANGE(x, a, b) (x >= a && x <= b) 4 | #define getBits(x) \ 5 | (INRANGE((x & (~0x20)), 'A', 'F') ? ((x & (~0x20)) - 'A' + 0xa) \ 6 | : (INRANGE(x, '0', '9') ? x - '0' : 0)) 7 | #define getByte(x) (getBits(x[0]) << 4 | getBits(x[1])) 8 | namespace Tools { 9 | auto FindPatternInMemory(uint64_t StartAddress, size_t MemorySize, 10 | std::string pattern) -> uint64_t { 11 | const char* pat = pattern.c_str(); 12 | uint64_t firstMatch = 0; 13 | uint64_t rangeStart = StartAddress; 14 | uint64_t rangeEnd = rangeStart + MemorySize; 15 | for (uint64_t pCur = rangeStart; pCur < rangeEnd; pCur++) { 16 | if (!*pat) return firstMatch; 17 | 18 | if (*(PBYTE)pat == '\?' || *(BYTE*)pCur == getByte(pat)) { 19 | if (!firstMatch) firstMatch = pCur; 20 | 21 | if (!pat[2]) return firstMatch; 22 | 23 | if (*(PWORD)pat == '\?\?' || *(PBYTE)pat != '\?') 24 | pat += 3; 25 | 26 | else 27 | pat += 2; // one ? 28 | } else { 29 | pat = pattern.c_str(); 30 | firstMatch = 0; 31 | } 32 | } 33 | return 0; 34 | } 35 | auto Is64BitPorcess(HANDLE hProcess) -> bool { 36 | BOOL bIsWow64 = false; 37 | IsWow64Process(hProcess, &bIsWow64); 38 | return bIsWow64 == false; 39 | } 40 | auto EnableDebugPrivilege(bool bEnable) -> bool { 41 | bool fOK = FALSE; // Assume function fails 42 | HANDLE hToken; 43 | if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, 44 | &hToken)) { 45 | TOKEN_PRIVILEGES tp; 46 | tp.PrivilegeCount = 1; 47 | LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[0].Luid); 48 | tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0; 49 | AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL); 50 | fOK = (GetLastError() == ERROR_SUCCESS); 51 | CloseHandle(hToken); 52 | } 53 | return fOK; 54 | } 55 | }; // namespace Tools 56 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /sleep_duck/sleep_duck.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {8a01cc2b-278c-411f-beb7-286dc920e493} 25 | sleepduck 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v142 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v142 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v142 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v142 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | true 75 | 76 | 77 | false 78 | 79 | 80 | true 81 | F:\project\white_patch_detect\white_patch_detect\libs;$(LibraryPath) 82 | F:\project\white_patch_detect\white_patch_detect\capstone-master;$(IncludePath) 83 | 84 | 85 | false 86 | F:\project\white_patch_detect\white_patch_detect\capstone-master;$(IncludePath) 87 | F:\project\white_patch_detect\white_patch_detect\libs;$(LibraryPath) 88 | 89 | 90 | 91 | Level3 92 | true 93 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 94 | true 95 | 96 | 97 | Console 98 | true 99 | 100 | 101 | 102 | 103 | Level3 104 | true 105 | true 106 | true 107 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 108 | true 109 | 110 | 111 | Console 112 | true 113 | true 114 | true 115 | 116 | 117 | 118 | 119 | Level3 120 | true 121 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 122 | true 123 | stdcpplatest 124 | 125 | 126 | Console 127 | true 128 | 129 | 130 | 131 | 132 | Level3 133 | true 134 | true 135 | true 136 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 137 | true 138 | stdcpplatest 139 | MultiThreaded 140 | 141 | 142 | Console 143 | true 144 | true 145 | true 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /sleep_duck/sleep_duck.cpp: -------------------------------------------------------------------------------- 1 | #include "head.h" 2 | 3 | auto PrintProcessInfoFromHandle(HANDLE hProcess) -> void { 4 | DWORD pid = GetProcessId(hProcess); 5 | DWORD bufferSize = MAX_PATH; 6 | std::vector pathBuffer(bufferSize); 7 | if (!QueryFullProcessImageNameW(hProcess, 0, pathBuffer.data(), 8 | &bufferSize)) { 9 | if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { 10 | pathBuffer.resize(bufferSize); 11 | if (!QueryFullProcessImageNameW(hProcess, 0, pathBuffer.data(), 12 | &bufferSize)) { 13 | throw std::runtime_error( 14 | "Failed to query process image name on second attempt. " 15 | "Error code: " + 16 | std::to_string(GetLastError())); 17 | } 18 | } else { 19 | throw std::runtime_error( 20 | "Failed to query process image name. Error code: " + 21 | std::to_string(GetLastError())); 22 | } 23 | } 24 | std::wstring processPath(pathBuffer.data(), bufferSize); 25 | printf("target process %d -> %ws \n", pid, pathBuffer.data()); 26 | } 27 | 28 | auto SimpleCheckIn2020(HANDLE hProcess, uint64_t Address) -> bool { 29 | MEMORY_BASIC_INFORMATION mbi = {0}; 30 | SIZE_T ReadNum = 0; 31 | bool detect = false; 32 | do { 33 | if (VirtualQueryEx(hProcess, (PVOID)Address, &mbi, sizeof(mbi)) == 34 | false) { 35 | break; 36 | } 37 | if (mbi.Type == MEM_IMAGE) { 38 | break; 39 | } 40 | bool CheckExcuteFlag = mbi.AllocationProtect & PAGE_EXECUTE || 41 | mbi.AllocationProtect & PAGE_EXECUTE_READ || 42 | mbi.AllocationProtect & PAGE_EXECUTE_READWRITE || 43 | mbi.AllocationProtect & PAGE_EXECUTE_WRITECOPY; 44 | if (CheckExcuteFlag) { 45 | printf("rwx memory detect-> \n\t"); 46 | PrintProcessInfoFromHandle(hProcess); 47 | detect = true; 48 | char PEStack[0x2]; 49 | if (ReadProcessMemory(hProcess, mbi.BaseAddress, PEStack, 50 | sizeof(PEStack), &ReadNum)) { 51 | if (PEStack[0] == 'M' && PEStack[1] == 'Z') { 52 | printf("rwx memory has pe module-> \n\t"); 53 | PrintProcessInfoFromHandle(hProcess); 54 | } 55 | } 56 | } else if (mbi.AllocationProtect & PAGE_READONLY || 57 | mbi.AllocationProtect & PAGE_READWRITE || 58 | mbi.AllocationProtect & PAGE_NOACCESS) { 59 | printf("no-excute-page detect at %p \n\t", Address); 60 | PrintProcessInfoFromHandle(hProcess); 61 | detect = true; 62 | } 63 | } while (false); 64 | return detect; 65 | } 66 | auto DoCFTrackX64(HANDLE hProcess, 67 | std::vector>& stackArrays) 68 | -> void { 69 | for (size_t i = stackArrays.size() - 1; i > 0; i--) { 70 | auto ripAddr = stackArrays[i].first; 71 | auto retAddr = stackArrays[i].second; 72 | 73 | if (retAddr == 0) { 74 | continue; 75 | } 76 | auto rawAddress = ripAddr - 0x20; 77 | StackTracker stackTrack(hProcess, rawAddress, 0x28, false); 78 | if (stackTrack.TryFindValidDisasm(rawAddress, 0x28) == false) { 79 | printf("\nSleepMask Encryption Memory Detected: %p\n\t", 80 | rawAddress); 81 | PrintProcessInfoFromHandle(hProcess); 82 | stackTrack.PrintAsm(); 83 | continue; 84 | } 85 | auto [successTrack, nextJmpAddress] = stackTrack.CalcNextJmpAddress(); 86 | 87 | if (successTrack == false) { 88 | // very perfer lazy method 89 | static const std::string WaitonAddressGate = "52 10 47 AE"; 90 | if (Tools::FindPatternInMemory( 91 | (uint64_t)stackTrack.SuccessReadedBuffer.data(), 92 | stackTrack.SuccessReadedBuffer.size(), 93 | WaitonAddressGate) != 0) { 94 | printf("skip waitonaddress, golang detect\n"); 95 | continue; 96 | } 97 | if (stackTrack.feature != _features::kCallRip && 98 | stackTrack.feature != _features::kCallReg && 99 | stackTrack.feature != _features::kSyscall) { 100 | printf("\nNon-integrity Stack Detect: %p ripAddr: %p \n\t", 101 | rawAddress, ripAddr); 102 | PrintProcessInfoFromHandle(hProcess); 103 | stackTrack.PrintAsm(); 104 | } 105 | 106 | break; 107 | } 108 | } 109 | return; 110 | } 111 | auto DoX64StackDetect(HANDLE hProcess, HANDLE hThread) -> void { 112 | STACKFRAME64 StackFarmeEx = {}; 113 | CONTEXT context = {0}; 114 | context.ContextFlags = CONTEXT_ALL; 115 | std::vector> stackArrays; 116 | SymInitialize(hProcess, nullptr, TRUE); 117 | printf("scan tid: %d \n", GetThreadId(hThread)); 118 | do { 119 | if (GetThreadContext(hThread, &context) == false) { 120 | break; 121 | } 122 | 123 | StackFarmeEx.AddrPC.Offset = context.Rip; 124 | StackFarmeEx.AddrPC.Mode = AddrModeFlat; 125 | StackFarmeEx.AddrStack.Offset = context.Rsp; 126 | StackFarmeEx.AddrStack.Mode = AddrModeFlat; 127 | StackFarmeEx.AddrFrame.Offset = context.Rsp; 128 | StackFarmeEx.AddrFrame.Mode = AddrModeFlat; 129 | bool detect = false; 130 | while (true) { 131 | if (StackWalk64(IMAGE_FILE_MACHINE_AMD64, hProcess, hThread, 132 | &StackFarmeEx, &context, NULL, 133 | SymFunctionTableAccess, SymGetModuleBase, 134 | NULL) == false) { 135 | break; 136 | } 137 | if (StackFarmeEx.AddrFrame.Offset == 0) { 138 | break; 139 | } 140 | if (SimpleCheckIn2020(hProcess, StackFarmeEx.AddrPC.Offset)) { 141 | detect = true; 142 | // break; 143 | } 144 | 145 | stackArrays.push_back( 146 | {StackFarmeEx.AddrPC.Offset, StackFarmeEx.AddrReturn.Offset}); 147 | } 148 | // if (detect) { 149 | // break; 150 | // } 151 | DoCFTrackX64(hProcess, stackArrays); 152 | } while (false); 153 | SymCleanup(hProcess); 154 | } 155 | 156 | // 主扫描函数 157 | auto DoLittleHackerMemeDetect(DWORD pidFilter = 0, bool scanAll = false) 158 | -> void { 159 | HANDLE hThreadSnap = 160 | CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); // 所有线程 161 | THREADENTRY32 te32 = {}; 162 | te32.dwSize = sizeof(THREADENTRY32); 163 | 164 | if (hThreadSnap == INVALID_HANDLE_VALUE || 165 | !Thread32First(hThreadSnap, &te32)) 166 | return; 167 | 168 | do { 169 | // 跳过当前线程 170 | if (te32.th32OwnerProcessID == GetCurrentProcessId() && 171 | te32.th32ThreadID == GetCurrentThreadId()) 172 | continue; 173 | 174 | // 判断是否过滤进程 175 | if (!scanAll && pidFilter != 0 && te32.th32OwnerProcessID != pidFilter) 176 | continue; 177 | 178 | if (!scanAll && pidFilter == 0 && 179 | te32.th32OwnerProcessID != GetCurrentProcessId()) 180 | continue; 181 | 182 | auto handleDeleter = [](HANDLE h) { 183 | if (h && h != INVALID_HANDLE_VALUE) CloseHandle(h); 184 | }; 185 | 186 | std::unique_ptr hThread( 187 | OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID), 188 | handleDeleter); 189 | std::unique_ptr hProcess( 190 | OpenProcess(PROCESS_ALL_ACCESS, FALSE, te32.th32OwnerProcessID), 191 | handleDeleter); 192 | 193 | if (!hProcess || hProcess.get() == INVALID_HANDLE_VALUE || !hThread || 194 | hThread.get() == INVALID_HANDLE_VALUE) 195 | continue; 196 | 197 | if (!Tools::Is64BitPorcess(hProcess.get())) continue; 198 | DoX64StackDetect(hProcess.get(), hThread.get()); 199 | 200 | } while (Thread32Next(hThreadSnap, &te32)); 201 | 202 | CloseHandle(hThreadSnap); 203 | } 204 | 205 | int main(int argc, char* argv[]) { 206 | bool scanAll = true; 207 | DWORD targetPid = 0; 208 | 209 | for (int i = 1; i < argc; ++i) { 210 | std::string arg = argv[i]; 211 | 212 | if (arg == "-all") { 213 | scanAll = true; 214 | } else if (arg == "-pid" && i + 1 < argc) { 215 | scanAll = false; 216 | targetPid = static_cast(std::stoul(argv[++i])); 217 | } else { 218 | std::cerr << "[!] Unknown argument ,go scan all: " << arg << "\n"; 219 | scanAll = true; 220 | } 221 | } 222 | 223 | DoLittleHackerMemeDetect(targetPid, scanAll); 224 | return 0; 225 | } 226 | -------------------------------------------------------------------------------- /sleep_duck/stack_tracker.cpp: -------------------------------------------------------------------------------- 1 | #include "stack_tracker.h" 2 | 3 | auto StackTracker::rpm(uintptr_t address, size_t readSize) 4 | -> std::vector { 5 | size_t NumOfRead = 0; 6 | std::vector buffer(readSize); 7 | 8 | if (ReadProcessMemory(this->targetProcess, (LPCVOID)address, buffer.data(), 9 | readSize, &NumOfRead) == false || 10 | NumOfRead != readSize) { 11 | return {}; 12 | } 13 | return buffer; 14 | } 15 | auto StackTracker::LookslikeValidEntry(cs_insn* insn, size_t count) -> bool { 16 | if (insn == nullptr || count == 0) return false; 17 | 18 | int threshold_score = 2; 19 | int score = 0; 20 | 21 | // 限制最多检查前几条指令 22 | size_t check_limit = min(count, static_cast(8)); 23 | 24 | for (size_t i = 0; i < check_limit; ++i) { 25 | const cs_insn& inst = insn[i]; 26 | 27 | switch (inst.id) { 28 | case X86_INS_PUSH: 29 | if (strcmp(inst.mnemonic, "push") == 0) score++; 30 | break; 31 | case X86_INS_MOV: 32 | if (strstr(inst.op_str, "rbp") != nullptr || 33 | strstr(inst.op_str, "rsp") != nullptr) 34 | score++; 35 | break; 36 | case X86_INS_SUB: 37 | case X86_INS_ADD: 38 | if (strstr(inst.op_str, "rsp") != nullptr) score++; 39 | break; 40 | case X86_INS_CALL: 41 | score += 1; 42 | break; 43 | case X86_INS_LEA: 44 | if (strstr(inst.op_str, "rip") != nullptr) score++; 45 | break; 46 | case X86_INS_TEST: 47 | case X86_INS_CMP: 48 | case X86_INS_JE: 49 | case X86_INS_JNE: 50 | case X86_INS_JMP: 51 | score++; 52 | break; 53 | case X86_INS_NOP: 54 | break; // 忽略 55 | default: 56 | if (score == 0) score -= 1; // 杂指令降低一点分数 57 | break; 58 | } 59 | 60 | if (score >= threshold_score) { 61 | return true; 62 | } 63 | } 64 | return score >= threshold_score; 65 | } 66 | auto StackTracker::TryFindValidDisasm(uint64_t baseAddr, size_t maxOffset) 67 | -> bool { 68 | for (size_t i = 0; i < maxOffset; ++i) { 69 | auto buf = this->rpm(baseAddr + i, this->trackSize); 70 | if (buf.size() != this->trackSize) continue; 71 | cs_insn* testInsn = nullptr; 72 | this->disasmCount = cs_disasm(this->capstoneHandle, 73 | reinterpret_cast(buf.data()), 74 | this->trackSize, baseAddr + i, 0, &testInsn); 75 | // this->PrintAsm(testInsn); 76 | if (this->disasmCount > 0) { 77 | this->insn = testInsn; 78 | } 79 | if (this->disasmCount > 0 && LookslikeValidEntry(testInsn, this->disasmCount)) { 80 | this->baseAddr += i; 81 | if (this->insn != nullptr) { 82 | cs_free(this->insn, this->disasmCount); 83 | } 84 | for (size_t j = 0; j < this->disasmCount; ++j) { 85 | // this->PrintAsm(&this->insn[j]); 86 | 87 | this->insList.push_back( 88 | std::make_shared(this->insn[j])); 89 | } 90 | this->SuccessReadedBuffer = buf; 91 | this->readSuccess = true; 92 | return true; 93 | } 94 | } 95 | return false; 96 | } 97 | StackTracker::StackTracker(HANDLE hProcess, uint64_t StartAddress, 98 | size_t trackSize, bool isX32) { 99 | this->isWow64 = isX32; 100 | this->targetProcess = hProcess; 101 | this->baseAddr = StartAddress; 102 | this->trackSize = trackSize; 103 | if (cs_open(CS_ARCH_X86, this->isWow64 ? CS_MODE_32 : CS_MODE_64, 104 | &capstoneHandle) != CS_ERR_OK) { 105 | __debugbreak(); 106 | } 107 | cs_option(capstoneHandle, CS_OPT_DETAIL, CS_OPT_ON); 108 | cs_option(capstoneHandle, CS_OPT_SKIPDATA, CS_OPT_ON); 109 | /* 110 | do { 111 | // 1.读取 112 | auto bufferArrays = this->rpm(StartAddress, trackSize); 113 | if (bufferArrays.size() != trackSize) { 114 | break; 115 | } 116 | // 2. 反过来 117 | std::reverse(bufferArrays.begin(), bufferArrays.end()); 118 | // 3. 这里就是向上的了.指令是对的上的 119 | disasmCount = 120 | cs_disasm(capstoneHandle, 121 | reinterpret_cast(bufferArrays.data()), 122 | trackSize, StartAddress, 0, &insn); 123 | if (disasmCount == 0) { 124 | break; 125 | } 126 | // 4. 再反过来 127 | for (size_t index = disasmCount; index > 0; index--) { 128 | const auto code = insn[index]; 129 | this->PrintAsm(&code); 130 | this->insList.push_back(std::make_shared(code)); 131 | } 132 | this->readSuccess = true; 133 | } while (false); 134 | */ 135 | } 136 | 137 | auto StackTracker::getNextIns() -> std::shared_ptr { 138 | if (this->ins_ip >= this->insList.size()) { 139 | return nullptr; 140 | } 141 | const auto result = this->insList[this->ins_ip]; 142 | this->ins_ip++; 143 | this->ins_ip_address = result->address; 144 | return result; 145 | } 146 | StackTracker::~StackTracker() { 147 | if (insn) { 148 | //cs_free(insn, disasmCount); 149 | cs_close(&capstoneHandle); 150 | } 151 | } 152 | template 153 | auto StackTracker::matchCode( 154 | T match_fn, B process_fn, std::optional num_operands, 155 | std::vector> operand_types) -> bool { 156 | while (auto instruction = getNextIns()) { 157 | if (&process_fn != nullptr) { 158 | process_fn(instruction.get()); 159 | } 160 | if (num_operands) { 161 | if (instruction->detail->x86.op_count != *num_operands) continue; 162 | bool operand_type_mismatch = false; 163 | for (uint32_t i = 0; i < *num_operands; i++) { 164 | auto& target_type = operand_types[i]; 165 | if (target_type && 166 | target_type != instruction->detail->x86.operands[i].type) { 167 | operand_type_mismatch = true; 168 | break; 169 | } 170 | } 171 | if (operand_type_mismatch) continue; 172 | } 173 | if (match_fn(instruction.get())) return true; 174 | } 175 | return false; 176 | } 177 | 178 | inline auto StackTracker::is_call(cs_insn* ins) -> bool { 179 | return ins->id == X86_INS_CALL; 180 | } 181 | auto StackTracker::PrintAsm() -> void { 182 | for (size_t j = 0; j < this->disasmCount; ++j) { 183 | for (int x = 0; x < this->insn[j].size; x++) { 184 | printf("%02X ", this->insn[j].bytes[x]); 185 | } 186 | printf("0x%llx :\t\t%s\t%s\t\n", this->insn[j].address, 187 | this->insn[j].mnemonic, this->insn[j].op_str); 188 | 189 | } 190 | 191 | } 192 | auto StackTracker::CalcNextJmpAddress() -> std::pair { 193 | if (this->readSuccess == false) { 194 | return {false, 0}; 195 | } 196 | this->feature = _features::kNonCallOnly; 197 | 198 | uint64_t callAddress = 0; 199 | auto isMatchCall = matchCode( 200 | [&](cs_insn* instruction) { 201 | if (instruction->id != X86_INS_CALL) { 202 | if (instruction->id == X86_INS_SYSCALL) { 203 | this->feature = _features::kSyscall; 204 | } 205 | return false; 206 | } 207 | if (instruction->detail->x86.op_count != 1) { 208 | return false; 209 | } 210 | const cs_x86_op& operand = instruction->detail->x86.operands[0]; 211 | if (operand.type == X86_OP_IMM) { 212 | callAddress = 213 | instruction->address + instruction->size + operand.imm; 214 | return true; 215 | } else if (operand.type == X86_OP_MEM) { 216 | const x86_op_mem& mem = operand.mem; 217 | // 我们只处理可以静态计算的 RIP 相对寻址 218 | if (mem.base == X86_REG_RIP) { 219 | uint64_t pointerAddress = 220 | instruction->address + instruction->size + mem.disp; 221 | size_t pointerSize = this->isWow64 ? 4 : 8; 222 | std::vector pointerBuffer = 223 | this->rpm(pointerAddress, pointerSize); 224 | if (pointerBuffer.empty()) { 225 | std::cerr << "Failed to read pointer at 0x" << std::hex 226 | << pointerAddress << std::endl; 227 | return false; 228 | } 229 | if (pointerSize == 8) { 230 | callAddress = 231 | *reinterpret_cast(pointerBuffer.data()); 232 | } else { // 32位 233 | callAddress = 234 | *reinterpret_cast(pointerBuffer.data()); 235 | } 236 | 237 | // std::cout << "Found RIP-relative call at 0x" << std::hex 238 | // << instruction->address 239 | // << ". Pointer at 0x" << pointerAddress 240 | // << ". Final Target: 0x" << callAddress << std::endl; 241 | return true; 242 | } 243 | // std::cout << "Skipping non-RIP-relative memory call at 0x" << 244 | // std::hex << instruction->address << std::endl; 245 | this->feature = _features::kCallRip; 246 | return false; 247 | } else if (operand.type == X86_OP_REG) { 248 | this->feature = _features::kCallReg; 249 | return false; 250 | } 251 | return false; 252 | }, 253 | [&](cs_insn* instruction) {}, {}, {}); 254 | return {isMatchCall, callAddress}; 255 | } 256 | --------------------------------------------------------------------------------