├── .gitattributes ├── .gitignore ├── README.md ├── RansomFS.sln ├── RansomFS ├── RansomFS.vcxproj ├── RansomFS.vcxproj.filters ├── common.h └── main.cpp └── babyk.png /.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 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Detecting Ransomware using the Projected File System 2 | 3 | This repository is an example of using canary files and directories, chained with different threshold engines to map a PID to its malicious behaviour and trigger a response when this threshold is breached. 4 | 5 | ```cpp 6 | DetectionEngine engine(/*threshold=*/5, /*ttlSec=*/300); 7 | engine.addDetector(std::make_unique(3)); 8 | engine.addDetector(std::make_unique(1.5)); 9 | engine.addDetector(std::make_unique()); 10 | 11 | engine.addResponse(logSuspicious); 12 | engine.addResponse(terminateProcess); 13 | 14 | InMemoryProvider provider(std::move(fs), engine); 15 | ``` 16 | 17 | While FindFirstFile does not guarantee to return files in alphabetical order, this is almost always due to NTFS returning files in directory entry table order. 18 | 19 | Almost all ransomware uses this API to perform a depth first search of the drive, we can hijack this enumerate by creating directories in common locations such as `C:\` or in the users home dir to detect ransomware operations. 20 | 21 | Requirements: 22 | 23 | - `Enable-WindowsOptionalFeature -Online -FeatureName Client-ProjFS -NoRestart` 24 | - Virtualization root cannot have any pre-existing files 25 | 26 | ![Detecting Babyk](./babyk.png) 27 | 28 | ## References 29 | 30 | [Windows Projected File System (ProjFS)](https://learn.microsoft.com/en-us/windows/win32/projfs/projected-file-system) 31 | 32 | [Elastic Security Ransomware Protection Artifact Code](https://github.com/elastic/protections-artifacts/tree/main/ransomware) 33 | -------------------------------------------------------------------------------- /RansomFS.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.12.35707.178 d17.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RansomFS", "RansomFS\RansomFS.vcxproj", "{C7E82450-1EAE-4DF7-AB3B-270D42C4800E}" 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 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Debug|x64.ActiveCfg = Debug|x64 17 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Debug|x64.Build.0 = Debug|x64 18 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Debug|x86.ActiveCfg = Debug|Win32 19 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Debug|x86.Build.0 = Debug|Win32 20 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Release|x64.ActiveCfg = Release|x64 21 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Release|x64.Build.0 = Release|x64 22 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Release|x86.ActiveCfg = Release|Win32 23 | {C7E82450-1EAE-4DF7-AB3B-270D42C4800E}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /RansomFS/RansomFS.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 | 17.0 23 | Win32Proj 24 | {c7e82450-1eae-4df7-ab3b-270d42c4800e} 25 | RansomFS 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 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 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | 80 | 81 | Console 82 | true 83 | 84 | 85 | 86 | 87 | Level3 88 | true 89 | true 90 | true 91 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 92 | true 93 | 94 | 95 | Console 96 | true 97 | true 98 | true 99 | 100 | 101 | 102 | 103 | Level3 104 | true 105 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | stdcpp20 108 | 109 | 110 | Console 111 | true 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | true 119 | true 120 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 121 | true 122 | stdcpp20 123 | 124 | 125 | Console 126 | true 127 | true 128 | true 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /RansomFS/RansomFS.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 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /RansomFS/common.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace std { 4 | template<> 5 | struct hash { 6 | size_t operator()(const GUID& guid) const noexcept { 7 | const uint64_t* p = reinterpret_cast(&guid); 8 | std::hash hasher; 9 | return hasher(p[0]) ^ hasher(p[1]); 10 | } 11 | }; 12 | 13 | template 14 | basic_ostream& operator<<(basic_ostream& os, const GUID& guid) { 15 | ios_base::fmtflags f(os.flags()); 16 | 17 | os << '{' 18 | << hex << uppercase << setfill(CharT('0')) 19 | << setw(8) << guid.Data1 << '-' 20 | << setw(4) << guid.Data2 << '-' 21 | << setw(4) << guid.Data3 << '-' 22 | << setw(2) << static_cast(guid.Data4[0]) 23 | << setw(2) << static_cast(guid.Data4[1]) << '-' 24 | << setw(2) << static_cast(guid.Data4[2]) 25 | << setw(2) << static_cast(guid.Data4[3]) 26 | << setw(2) << static_cast(guid.Data4[4]) 27 | << setw(2) << static_cast(guid.Data4[5]) 28 | << setw(2) << static_cast(guid.Data4[6]) 29 | << setw(2) << static_cast(guid.Data4[7]) 30 | << '}'; 31 | 32 | os.flags(f); // Restore original stream flags 33 | return os; 34 | } 35 | } -------------------------------------------------------------------------------- /RansomFS/main.cpp: -------------------------------------------------------------------------------- 1 | #define WIN32_LEAN_AND_MEAN 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #pragma comment(lib, "psapi.lib") 26 | #pragma comment(lib, "ProjectedFSLib.lib") 27 | 28 | namespace std 29 | { 30 | template <> 31 | struct hash { 32 | size_t operator()(const GUID& g) const noexcept { 33 | const uint64_t* p = reinterpret_cast(&g); 34 | std::hash h; 35 | return h(p[0]) ^ h(p[1]); 36 | } 37 | }; 38 | } 39 | 40 | static std::string toNarrow(const std::wstring& ws) 41 | { 42 | if (ws.empty()) return {}; 43 | int needed = ::WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), -1, nullptr, 0, nullptr, nullptr); 44 | if (needed <= 0) return {}; 45 | std::string out(needed - 1, '\0'); 46 | ::WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), -1, out.data(), needed, nullptr, nullptr); 47 | return out; 48 | } 49 | 50 | static std::string notificationName(PRJ_NOTIFICATION n) 51 | { 52 | switch (n) { 53 | case PRJ_NOTIFICATION_FILE_OPENED: return "FILE_OPENED"; 54 | case PRJ_NOTIFICATION_NEW_FILE_CREATED: return "NEW_FILE_CREATED"; 55 | case PRJ_NOTIFICATION_FILE_OVERWRITTEN: return "FILE_OVERWRITTEN"; 56 | case PRJ_NOTIFICATION_PRE_DELETE: return "PRE_DELETE"; 57 | case PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_DELETED: return "HANDLE_CLOSED_FILE_DELETED"; 58 | case PRJ_NOTIFICATION_PRE_RENAME: return "PRE_RENAME"; 59 | case PRJ_NOTIFICATION_FILE_RENAMED: return "FILE_RENAMED"; 60 | case PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_MODIFIED: return "FILE_HANDLE_CLOSED_FILE_MODIFIED"; 61 | default: return "OTHER"; 62 | } 63 | } 64 | 65 | static uint64_t nowMillis() 66 | { 67 | using namespace std::chrono; 68 | return (uint64_t)duration_cast( 69 | steady_clock::now().time_since_epoch()).count(); 70 | } 71 | 72 | static std::wstring unifyPath(const std::wstring& root, const std::wstring& rel) 73 | { 74 | if (root.empty()) return rel; 75 | if (rel.empty()) return root; 76 | if (root.back() == L'\\') return root + rel; 77 | return root + L'\\' + rel; 78 | } 79 | 80 | namespace regfs { 81 | 82 | enum OptionalMethods { 83 | None = 0, 84 | Notify = 0x1, 85 | QueryFileName = 0x2, 86 | CancelCommand = 0x4 87 | }; 88 | DEFINE_ENUM_FLAG_OPERATORS(OptionalMethods); 89 | 90 | class NotImplemented : public std::logic_error { 91 | public: 92 | NotImplemented() : std::logic_error("Function not implemented") {} 93 | }; 94 | 95 | class VirtualizationInstance { 96 | public: 97 | HRESULT Start(LPCWSTR rootPath, PRJ_STARTVIRTUALIZING_OPTIONS* opts = nullptr); 98 | void Stop(); 99 | 100 | HRESULT WritePlaceholderInfo(LPCWSTR relativePath, 101 | PRJ_PLACEHOLDER_INFO* placeholderInfo, 102 | DWORD length); 103 | HRESULT WriteFileData(LPCGUID streamId, 104 | PVOID buffer, 105 | ULONGLONG byteOffset, 106 | DWORD length); 107 | 108 | protected: 109 | // Required ProjFS callbacks 110 | virtual HRESULT StartDirEnum(const PRJ_CALLBACK_DATA* data, const GUID* eId) = 0; 111 | virtual HRESULT EndDirEnum(const PRJ_CALLBACK_DATA* data, const GUID* eId) = 0; 112 | virtual HRESULT GetDirEnum(const PRJ_CALLBACK_DATA* data, const GUID* eId, 113 | PCWSTR expr, 114 | PRJ_DIR_ENTRY_BUFFER_HANDLE h) = 0; 115 | virtual HRESULT GetPlaceholderInfo(const PRJ_CALLBACK_DATA* data) = 0; 116 | virtual HRESULT GetFileData(const PRJ_CALLBACK_DATA* data, 117 | UINT64 off, 118 | UINT32 length) = 0; 119 | 120 | // optional 121 | virtual HRESULT Notify(const PRJ_CALLBACK_DATA* data, 122 | BOOLEAN isDirectory, 123 | PRJ_NOTIFICATION notification, 124 | PCWSTR destinationFileName, 125 | PRJ_NOTIFICATION_PARAMETERS* parameters) 126 | { 127 | throw NotImplemented(); 128 | } 129 | virtual HRESULT QueryFileName(const PRJ_CALLBACK_DATA* data) 130 | { 131 | throw NotImplemented(); 132 | } 133 | virtual void CancelCommand(const PRJ_CALLBACK_DATA* data) 134 | { 135 | throw NotImplemented(); 136 | } 137 | 138 | void SetOptionalMethods(OptionalMethods m) { _opt |= m; } 139 | OptionalMethods GetOptionalMethods() const { return _opt; } 140 | 141 | std::wstring _rootPath; 142 | PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT _instanceHandle = nullptr; 143 | 144 | private: 145 | OptionalMethods _opt = OptionalMethods::None; 146 | PRJ_STARTVIRTUALIZING_OPTIONS _options = {}; 147 | PRJ_CALLBACKS _callbacks = {}; 148 | 149 | HRESULT ensureRoot(); 150 | 151 | // Thunks with correct function_class_ annotation 152 | _Function_class_(PRJ_START_DIRECTORY_ENUMERATION_CB) 153 | static HRESULT STDMETHODCALLTYPE StartDirEnum_C( 154 | const PRJ_CALLBACK_DATA* data, 155 | const GUID* enumerationId); 156 | 157 | _Function_class_(PRJ_END_DIRECTORY_ENUMERATION_CB) 158 | static HRESULT STDMETHODCALLTYPE EndDirEnum_C( 159 | const PRJ_CALLBACK_DATA* data, 160 | const GUID* enumerationId); 161 | 162 | _Function_class_(PRJ_GET_DIRECTORY_ENUMERATION_CB) 163 | static HRESULT STDMETHODCALLTYPE GetDirEnum_C( 164 | const PRJ_CALLBACK_DATA* data, 165 | const GUID* enumerationId, 166 | PCWSTR expr, 167 | PRJ_DIR_ENTRY_BUFFER_HANDLE h); 168 | 169 | _Function_class_(PRJ_GET_PLACEHOLDER_INFO_CB) 170 | static HRESULT STDMETHODCALLTYPE GetPlaceholderInfo_C( 171 | const PRJ_CALLBACK_DATA* data); 172 | 173 | _Function_class_(PRJ_GET_FILE_DATA_CB) 174 | static HRESULT STDMETHODCALLTYPE GetFileData_C( 175 | const PRJ_CALLBACK_DATA* data, 176 | UINT64 off, 177 | UINT32 len); 178 | 179 | _Function_class_(PRJ_NOTIFICATION_CB) 180 | static HRESULT STDMETHODCALLTYPE Notification_C( 181 | const PRJ_CALLBACK_DATA* data, 182 | BOOLEAN isDir, 183 | PRJ_NOTIFICATION note, 184 | PCWSTR destName, 185 | PRJ_NOTIFICATION_PARAMETERS* p); 186 | 187 | _Function_class_(PRJ_QUERY_FILE_NAME_CB) 188 | static HRESULT STDMETHODCALLTYPE QueryFileName_C( 189 | const PRJ_CALLBACK_DATA* data); 190 | 191 | _Function_class_(PRJ_CANCEL_COMMAND_CB) 192 | static void STDMETHODCALLTYPE CancelCommand_C( 193 | const PRJ_CALLBACK_DATA* data); 194 | }; 195 | 196 | // Implementation 197 | HRESULT VirtualizationInstance::Start(LPCWSTR rootPath, PRJ_STARTVIRTUALIZING_OPTIONS* opts) 198 | { 199 | _rootPath = rootPath; 200 | if (opts) _options = *opts; 201 | 202 | HRESULT hr = ensureRoot(); 203 | if (FAILED(hr)) return hr; 204 | 205 | // required 206 | _callbacks.StartDirectoryEnumerationCallback = &StartDirEnum_C; 207 | _callbacks.EndDirectoryEnumerationCallback = &EndDirEnum_C; 208 | _callbacks.GetDirectoryEnumerationCallback = &GetDirEnum_C; 209 | _callbacks.GetPlaceholderInfoCallback = &GetPlaceholderInfo_C; 210 | _callbacks.GetFileDataCallback = &GetFileData_C; 211 | 212 | // optional 213 | if (((GetOptionalMethods() & OptionalMethods::Notify) != 0) && 214 | (_options.NotificationMappingsCount > 0)) 215 | { 216 | _callbacks.NotificationCallback = &Notification_C; 217 | } 218 | if ((GetOptionalMethods() & OptionalMethods::QueryFileName) != 0) { 219 | _callbacks.QueryFileNameCallback = &QueryFileName_C; 220 | } 221 | if ((GetOptionalMethods() & OptionalMethods::CancelCommand) != 0) { 222 | _callbacks.CancelCommandCallback = &CancelCommand_C; 223 | } 224 | 225 | hr = ::PrjStartVirtualizing(_rootPath.c_str(), 226 | &_callbacks, 227 | this, 228 | &_options, 229 | &_instanceHandle); 230 | return hr; 231 | } 232 | 233 | void VirtualizationInstance::Stop() 234 | { 235 | if (_instanceHandle) { 236 | ::PrjStopVirtualizing(_instanceHandle); 237 | _instanceHandle = nullptr; 238 | } 239 | } 240 | 241 | HRESULT VirtualizationInstance::WritePlaceholderInfo(LPCWSTR rel, 242 | PRJ_PLACEHOLDER_INFO* ph, 243 | DWORD len) 244 | { 245 | if (!_instanceHandle) return E_FAIL; 246 | return ::PrjWritePlaceholderInfo(_instanceHandle, rel, ph, len); 247 | } 248 | 249 | HRESULT VirtualizationInstance::WriteFileData(LPCGUID sid, 250 | PVOID buf, 251 | ULONGLONG off, 252 | DWORD len) 253 | { 254 | if (!_instanceHandle) return E_FAIL; 255 | return ::PrjWriteFileData(_instanceHandle, sid, buf, off, len); 256 | } 257 | 258 | HRESULT VirtualizationInstance::ensureRoot() 259 | { 260 | std::error_code ec; 261 | std::filesystem::create_directories(_rootPath, ec); 262 | 263 | GUID dummy{}; 264 | HRESULT hr = ::PrjMarkDirectoryAsPlaceholder(_rootPath.c_str(), nullptr, nullptr, &dummy); 265 | if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)) hr = S_OK; 266 | return hr; 267 | } 268 | 269 | // Thunks 270 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::StartDirEnum_C( 271 | const PRJ_CALLBACK_DATA* data, 272 | const GUID* enumerationId) 273 | { 274 | auto self = reinterpret_cast(data->InstanceContext); 275 | return self->StartDirEnum(data, enumerationId); 276 | } 277 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::EndDirEnum_C( 278 | const PRJ_CALLBACK_DATA* data, 279 | const GUID* enumerationId) 280 | { 281 | auto self = reinterpret_cast(data->InstanceContext); 282 | return self->EndDirEnum(data, enumerationId); 283 | } 284 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::GetDirEnum_C( 285 | const PRJ_CALLBACK_DATA* data, 286 | const GUID* enumerationId, 287 | PCWSTR expr, 288 | PRJ_DIR_ENTRY_BUFFER_HANDLE h) 289 | { 290 | auto self = reinterpret_cast(data->InstanceContext); 291 | return self->GetDirEnum(data, enumerationId, expr, h); 292 | } 293 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::GetPlaceholderInfo_C( 294 | const PRJ_CALLBACK_DATA* data) 295 | { 296 | auto self = reinterpret_cast(data->InstanceContext); 297 | return self->GetPlaceholderInfo(data); 298 | } 299 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::GetFileData_C( 300 | const PRJ_CALLBACK_DATA* data, 301 | UINT64 off, 302 | UINT32 len) 303 | { 304 | auto self = reinterpret_cast(data->InstanceContext); 305 | return self->GetFileData(data, off, len); 306 | } 307 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::Notification_C( 308 | const PRJ_CALLBACK_DATA* data, 309 | BOOLEAN isDir, 310 | PRJ_NOTIFICATION note, 311 | PCWSTR dstName, 312 | PRJ_NOTIFICATION_PARAMETERS* p) 313 | { 314 | auto self = reinterpret_cast(data->InstanceContext); 315 | return self->Notify(data, isDir, note, dstName, p); 316 | } 317 | HRESULT STDMETHODCALLTYPE VirtualizationInstance::QueryFileName_C( 318 | const PRJ_CALLBACK_DATA* data) 319 | { 320 | auto self = reinterpret_cast(data->InstanceContext); 321 | return self->QueryFileName(data); 322 | } 323 | void STDMETHODCALLTYPE VirtualizationInstance::CancelCommand_C( 324 | const PRJ_CALLBACK_DATA* data) 325 | { 326 | auto self = reinterpret_cast(data->InstanceContext); 327 | self->CancelCommand(data); 328 | } 329 | 330 | } // namespace regfs 331 | 332 | 333 | class IContentGenerator { 334 | public: 335 | virtual ~IContentGenerator() {} 336 | virtual std::string name() const = 0; 337 | virtual std::vector magicHeader() const = 0; 338 | virtual std::vector generateFile() const = 0; 339 | }; 340 | 341 | static size_t randomSize1to10KB() 342 | { 343 | static thread_local std::mt19937_64 rng(std::random_device{}()); 344 | std::uniform_int_distribution dist(1024, 10 * 1024); 345 | return dist(rng); 346 | } 347 | class TxtGenerator : public IContentGenerator { 348 | public: 349 | std::string name() const override { return "txt"; } 350 | std::vector magicHeader() const override { 351 | return { 'T','X','T','_' }; 352 | } 353 | std::vector generateFile() const override { 354 | size_t sz = randomSize1to10KB(); 355 | std::vector data(sz, 0); 356 | 357 | auto mh = magicHeader(); 358 | size_t offset = 0; 359 | for (auto c : mh) { 360 | if (offset < sz) data[offset++] = c; 361 | } 362 | // random letters 363 | static const char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "; 364 | std::mt19937_64 rng(std::random_device{}()); 365 | std::uniform_int_distribution dist(0, sizeof(alpha) - 2); 366 | while (offset < sz) { 367 | data[offset++] = alpha[dist(rng)]; 368 | } 369 | return data; 370 | } 371 | }; 372 | class PdfGenerator : public IContentGenerator { 373 | public: 374 | std::string name() const override { return "pdf"; } 375 | std::vector magicHeader() const override { 376 | return { '%','P','D','F','-' }; 377 | } 378 | std::vector generateFile() const override { 379 | size_t sz = randomSize1to10KB(); 380 | std::vector data(sz, 0); 381 | auto mh = magicHeader(); 382 | size_t offset = 0; 383 | for (auto c : mh) { 384 | if (offset < sz) data[offset++] = c; 385 | } 386 | std::mt19937_64 rng(std::random_device{}()); 387 | std::uniform_int_distribution dist(0, 255); 388 | while (offset < sz) { 389 | data[offset++] = (char)dist(rng); 390 | } 391 | return data; 392 | } 393 | }; 394 | class DocxGenerator : public IContentGenerator { 395 | public: 396 | std::string name() const override { return "docx"; } 397 | std::vector magicHeader() const override { 398 | return { 'P','K',0x03,0x04 }; 399 | } 400 | std::vector generateFile() const override { 401 | size_t sz = randomSize1to10KB(); 402 | std::vector data(sz, 0); 403 | auto mh = magicHeader(); 404 | size_t offset = 0; 405 | for (auto c : mh) { 406 | if (offset < sz) data[offset++] = c; 407 | } 408 | std::mt19937_64 rng(std::random_device{}()); 409 | std::uniform_int_distribution dist(0, 255); 410 | while (offset < sz) { 411 | data[offset++] = (char)dist(rng); 412 | } 413 | return data; 414 | } 415 | }; 416 | class XlsxGenerator : public IContentGenerator { 417 | public: 418 | std::string name() const override { return "xlsx"; } 419 | std::vector magicHeader() const override { 420 | return { 'P','K',0x03,0x04 }; 421 | } 422 | std::vector generateFile() const override { 423 | size_t sz = randomSize1to10KB(); 424 | std::vector data(sz, 0); 425 | auto mh = magicHeader(); 426 | size_t offset = 0; 427 | for (auto c : mh) { 428 | if (offset < sz) data[offset++] = c; 429 | } 430 | std::mt19937_64 rng(std::random_device{}()); 431 | std::uniform_int_distribution dist(0, 255); 432 | while (offset < sz) { 433 | data[offset++] = (char)dist(rng); 434 | } 435 | return data; 436 | } 437 | }; 438 | class ContentRegistry { 439 | public: 440 | static ContentRegistry& instance() 441 | { 442 | static ContentRegistry s_inst; 443 | return s_inst; 444 | } 445 | void registerGen(std::unique_ptr gen) 446 | { 447 | m_map[gen->name()] = std::move(gen); 448 | } 449 | const IContentGenerator* get(const std::string& nm) const 450 | { 451 | auto it = m_map.find(nm); 452 | if (it != m_map.end()) return it->second.get(); 453 | return nullptr; 454 | } 455 | // detect by magic 456 | std::string detectTypeByMagic(const std::vector& data) const 457 | { 458 | if (data.empty()) return {}; 459 | std::vector hits; 460 | for (auto& kv : m_map) { 461 | auto& gen = kv.second; 462 | const auto& mh = gen->magicHeader(); 463 | if (data.size() >= mh.size()) { 464 | bool same = true; 465 | for (size_t i = 0;i < mh.size();i++) { 466 | if (data[i] != mh[i]) { same = false; break; } 467 | } 468 | if (same) hits.push_back(gen->name()); 469 | } 470 | } 471 | if (hits.size() == 1) return hits[0]; 472 | return {}; 473 | } 474 | 475 | private: 476 | std::unordered_map> m_map; 477 | }; 478 | static void registerDefaultTypes() 479 | { 480 | auto& reg = ContentRegistry::instance(); 481 | reg.registerGen(std::make_unique()); 482 | reg.registerGen(std::make_unique()); 483 | reg.registerGen(std::make_unique()); 484 | reg.registerGen(std::make_unique()); 485 | } 486 | 487 | 488 | static double computeEntropy(const std::vector& data) { 489 | std::vector freq(256, 0); 490 | 491 | for (unsigned char c : data) { 492 | freq[c]++; 493 | } 494 | 495 | double total = static_cast(data.size()); 496 | if (total == 0) return 0.0; 497 | 498 | double H = 0.0; 499 | for (size_t f : freq) { 500 | if (f > 0) { 501 | double p = f / total; 502 | H -= p * std::log2(p); 503 | } 504 | } 505 | 506 | return H; // bits of entropy per byte 507 | } 508 | 509 | class FsNode 510 | { 511 | public: 512 | enum class Type { Directory, File }; 513 | FsNode(std::wstring name, Type t) 514 | : m_name(std::move(name)), m_type(t) 515 | { 516 | ZeroMemory(&m_creationTime, sizeof(m_creationTime)); 517 | ZeroMemory(&m_lastWriteTime, sizeof(m_lastWriteTime)); 518 | m_size.QuadPart = 0; 519 | } 520 | const std::wstring& name() const { return m_name; } 521 | bool isDirectory() const { return (m_type == Type::Directory); } 522 | 523 | LARGE_INTEGER size() const { return m_size; } 524 | FILETIME creationTime() const { return m_creationTime; } 525 | FILETIME lastWriteTime() const { return m_lastWriteTime; } 526 | 527 | double originalEntropy() const { return m_entropy; } 528 | const std::vector& content() const { return m_content; } 529 | 530 | void setContent(const std::vector& c) 531 | { 532 | m_content = c; 533 | m_size.QuadPart = (LONGLONG)c.size(); 534 | m_entropy = computeEntropy(c); 535 | updateLastWrite(); 536 | } 537 | 538 | // Directory children 539 | std::map, std::less<>> children; 540 | void addChild(std::unique_ptr c) 541 | { 542 | std::wstring key = c->m_name; 543 | std::transform(key.begin(), key.end(), key.begin(), ::towlower); 544 | children[key] = std::move(c); 545 | } 546 | FsNode* getChild(const std::wstring& nm) 547 | { 548 | std::wstring k = nm; 549 | std::transform(k.begin(), k.end(), k.begin(), ::towlower); 550 | auto it = children.find(k); 551 | if (it != children.end()) return it->second.get(); 552 | return nullptr; 553 | } 554 | void setName(const std::wstring& newN) 555 | { 556 | m_name = newN; 557 | updateLastWrite(); 558 | } 559 | void setRandomTimes() 560 | { 561 | m_creationTime = randomFileTime(); 562 | m_lastWriteTime = randomFileTime(); 563 | } 564 | 565 | private: 566 | std::wstring m_name; 567 | Type m_type; 568 | LARGE_INTEGER m_size{}; 569 | FILETIME m_creationTime{}, m_lastWriteTime{}; 570 | std::vector m_content; 571 | double m_entropy = 0.0; 572 | 573 | static FILETIME randomFileTime() 574 | { 575 | SYSTEMTIME now; 576 | ::GetSystemTime(&now); 577 | FILETIME ft; 578 | ::SystemTimeToFileTime(&now, &ft); 579 | 580 | ULARGE_INTEGER uli; 581 | uli.LowPart = ft.dwLowDateTime; 582 | uli.HighPart = ft.dwHighDateTime; 583 | 584 | static thread_local std::mt19937_64 rng(std::random_device{}()); 585 | std::uniform_int_distribution dist(0ULL, 864000000000ULL); 586 | 587 | ULONGLONG delta = dist(rng); 588 | if (uli.QuadPart > delta) uli.QuadPart -= delta; 589 | 590 | FILETIME ret; 591 | ret.dwLowDateTime = uli.LowPart; 592 | ret.dwHighDateTime = uli.HighPart; 593 | return ret; 594 | } 595 | void updateLastWrite() 596 | { 597 | SYSTEMTIME st; 598 | ::GetSystemTime(&st); 599 | ::SystemTimeToFileTime(&st, &m_lastWriteTime); 600 | } 601 | }; 602 | 603 | class InMemoryFS 604 | { 605 | public: 606 | InMemoryFS(std::wstring rootName) 607 | { 608 | m_root = std::make_unique(std::move(rootName), FsNode::Type::Directory); 609 | m_root->setRandomTimes(); 610 | } 611 | FsNode* root() const { return m_root.get(); } 612 | 613 | FsNode* findNode(const std::wstring& path) 614 | { 615 | std::lock_guard lk(m_mutex); 616 | return findNodeUnlocked(path); 617 | } 618 | bool overwriteFile(const std::wstring& path, const std::vector& data) 619 | { 620 | std::lock_guard lk(m_mutex); 621 | FsNode* node = findNodeUnlocked(path); 622 | if (!node || node->isDirectory()) return false; 623 | node->setContent(data); 624 | return true; 625 | } 626 | bool renamePath(const std::wstring& oldP, const std::wstring& newP) 627 | { 628 | std::lock_guard lk(m_mutex); 629 | auto [odir, oleaf] = splitPop(oldP); 630 | auto [ndir, nleaf] = splitPop(newP); 631 | 632 | FsNode* od = findNodeUnlocked(odir); 633 | FsNode* nd = findNodeUnlocked(ndir); 634 | if (!od || !nd) return false; 635 | 636 | auto c = detach(od, oleaf); 637 | if (!c) return false; 638 | c->setName(nleaf); 639 | nd->addChild(std::move(c)); 640 | return true; 641 | } 642 | bool removePath(const std::wstring& path) 643 | { 644 | std::lock_guard lk(m_mutex); 645 | auto [dir, leaf] = splitPop(path); 646 | FsNode* dnode = findNodeUnlocked(dir); 647 | if (!dnode || !dnode->isDirectory()) return false; 648 | auto c = detach(dnode, leaf); 649 | return (c != nullptr); 650 | } 651 | 652 | private: 653 | std::unique_ptr m_root; 654 | mutable std::mutex m_mutex; 655 | 656 | FsNode* findNodeUnlocked(const std::wstring& p) 657 | { 658 | if (p.empty()) return m_root.get(); 659 | auto segs = split(p); 660 | FsNode* cur = m_root.get(); 661 | for (auto& s : segs) { 662 | if (!cur->isDirectory()) return nullptr; 663 | cur = cur->getChild(s); 664 | if (!cur) return nullptr; 665 | } 666 | return cur; 667 | } 668 | static std::unique_ptr detach(FsNode* parent, const std::wstring& leaf) 669 | { 670 | if (!parent->isDirectory()) return nullptr; 671 | std::wstring key = leaf; 672 | std::transform(key.begin(), key.end(), key.begin(), ::towlower); 673 | auto it = parent->children.find(key); 674 | if (it == parent->children.end()) return nullptr; 675 | auto ptr = std::move(it->second); 676 | parent->children.erase(it); 677 | return ptr; 678 | } 679 | static std::vector split(const std::wstring& p) 680 | { 681 | std::vector segs; 682 | size_t start = 0; 683 | while (true) { 684 | auto pos = p.find(L'\\', start); 685 | if (pos == std::wstring::npos) { 686 | segs.push_back(p.substr(start)); 687 | break; 688 | } 689 | segs.push_back(p.substr(start, pos - start)); 690 | start = pos + 1; 691 | } 692 | segs.erase(std::remove_if(segs.begin(), segs.end(), 693 | [](auto& s) {return s.empty();}), 694 | segs.end()); 695 | return segs; 696 | } 697 | static std::pair splitPop(const std::wstring& p) 698 | { 699 | auto pos = p.rfind(L'\\'); 700 | if (pos == std::wstring::npos) { 701 | return { L"",p }; 702 | } 703 | return { p.substr(0,pos), p.substr(pos + 1) }; 704 | } 705 | }; 706 | 707 | struct DetectionEvent { 708 | DWORD pid = 0; 709 | PRJ_NOTIFICATION note = (PRJ_NOTIFICATION)0; 710 | FsNode* oldNode = nullptr; // old in-memory node 711 | std::vector oldData; 712 | std::vector newData; 713 | std::wstring oldPath, newPath; 714 | }; 715 | struct DetectionResult { 716 | int score = 0; 717 | std::string reason; 718 | }; 719 | class IDetector { 720 | public: 721 | virtual ~IDetector() {} 722 | virtual DetectionResult onEvent(const DetectionEvent& e) = 0; 723 | }; 724 | // rename threshold 725 | class RenameThresholdDetector : public IDetector { 726 | public: 727 | explicit RenameThresholdDetector(int threshold) 728 | : m_threshold(threshold) 729 | { 730 | } 731 | DetectionResult onEvent(const DetectionEvent& e) override 732 | { 733 | DetectionResult r{}; 734 | // use bitwise check 735 | if (((e.note & PRJ_NOTIFICATION_FILE_RENAMED) != 0) || 736 | ((e.note & PRJ_NOTIFICATION_PRE_RENAME) != 0)) 737 | { 738 | std::lock_guard lock(m_mtx); 739 | int& count = m_map[e.pid]; 740 | count++; 741 | if (count >= m_threshold) { 742 | r.score = 2; 743 | r.reason = "Excessive rename count"; 744 | } 745 | } 746 | return r; 747 | } 748 | private: 749 | int m_threshold = 3; 750 | std::mutex m_mtx; 751 | std::unordered_map m_map; 752 | }; 753 | 754 | class EntropyDetector : public IDetector { 755 | public: 756 | explicit EntropyDetector(double delta = 1.5) 757 | : m_delta(delta) 758 | { 759 | } 760 | 761 | DetectionResult onEvent(const DetectionEvent& e) override 762 | { 763 | DetectionResult r{}; 764 | // Only consider overwrites or "file handle closed after modification" 765 | if (((e.note & PRJ_NOTIFICATION_FILE_OVERWRITTEN) != 0) || 766 | ((e.note & PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_MODIFIED) != 0)) 767 | { 768 | // Compare actual oldData vs. newData 769 | if (!e.oldData.empty() && !e.newData.empty()) 770 | { 771 | double oldEnt = computeEntropy(e.oldData); 772 | double newEnt = computeEntropy(e.newData); 773 | if ((newEnt - oldEnt) >= m_delta) 774 | { 775 | r.score = 2; 776 | char buf[128]; 777 | sprintf_s(buf, "Entropy rose from %.2f to %.2f", oldEnt, newEnt); 778 | r.reason = buf; 779 | } 780 | } 781 | } 782 | return r; 783 | } 784 | private: 785 | double m_delta = 1.5; 786 | }; 787 | 788 | class MagicHeaderDetector : public IDetector { 789 | public: 790 | DetectionResult onEvent(const DetectionEvent& e) override 791 | { 792 | DetectionResult r{}; 793 | if (((e.note & PRJ_NOTIFICATION_FILE_OVERWRITTEN) != 0) || 794 | ((e.note & PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_MODIFIED) != 0)) 795 | { 796 | if (!e.oldData.empty() && !e.newData.empty()) { 797 | auto oldType = ContentRegistry::instance().detectTypeByMagic(e.oldData); 798 | auto newType = ContentRegistry::instance().detectTypeByMagic(e.newData); 799 | if (!oldType.empty() && oldType != newType) { 800 | std::printf("Magic header changed from %s to %s\n", oldType.c_str(), newType.empty() ? "UNKNOWN" : newType.c_str()); 801 | r.score = 2; 802 | if (newType.empty()) { 803 | r.reason = "Magic header changed from " + oldType + " to UNKNOWN"; 804 | } 805 | else { 806 | r.reason = "Magic header changed from " + oldType + " to " + newType; 807 | } 808 | } 809 | } 810 | } 811 | return r; 812 | } 813 | }; 814 | 815 | // aggregator 816 | struct PIDInfo { 817 | int score = 0; 818 | uint64_t lastUpdate = 0ULL; 819 | }; 820 | 821 | class DetectionEngine 822 | { 823 | public: 824 | DetectionEngine(int threshold, int ttlSec = 300) 825 | : m_threshold(threshold) 826 | , m_ttlMs((uint64_t)ttlSec * 1000ULL) 827 | , m_stop(false) 828 | { 829 | m_pruneThread = std::thread([this]() { this->pruneLoop(); }); 830 | } 831 | ~DetectionEngine() 832 | { 833 | m_stop = true; 834 | if (m_pruneThread.joinable()) m_pruneThread.join(); 835 | } 836 | 837 | void addDetector(std::unique_ptr d) 838 | { 839 | std::lock_guard lk(m_detectorsMtx); 840 | m_detectors.push_back(std::move(d)); 841 | } 842 | 843 | void addResponse(std::function r) 844 | { 845 | std::lock_guard lk(m_respMtx); 846 | m_responses.push_back(std::move(r)); 847 | } 848 | 849 | // We'll store log events here 850 | struct LoggedEvent { 851 | uint64_t timestamp = 0ULL; 852 | DWORD pid = 0; 853 | std::string operation; 854 | std::string oldPath; 855 | std::string newPath; 856 | int finalScore = 0; 857 | }; 858 | void printLog() const 859 | { 860 | std::lock_guard lk(m_logMtx); 861 | for (auto& e : m_eventLog) { 862 | std::printf("[%llu ms] PID=%u, op=%s, old=%s, new=%s, finalScore=%d\n", 863 | (unsigned long long)e.timestamp, 864 | (unsigned)e.pid, 865 | e.operation.c_str(), 866 | e.oldPath.c_str(), 867 | e.newPath.c_str(), 868 | e.finalScore); 869 | } 870 | } 871 | 872 | // main entry 873 | void handleEvent(const DetectionEvent& e) 874 | { 875 | // 1) run detectors outside aggregator lock 876 | int sumScore = 0; 877 | std::string reasons; 878 | { 879 | std::lock_guard lkd(m_detectorsMtx); 880 | for (auto& det : m_detectors) { 881 | auto dr = det->onEvent(e); 882 | sumScore += dr.score; 883 | if (!dr.reason.empty()) { 884 | reasons += dr.reason + "; "; 885 | } 886 | } 887 | } 888 | 889 | // 2) create a LoggedEvent 890 | LoggedEvent le; 891 | le.timestamp = nowMillis(); 892 | le.pid = e.pid; 893 | le.operation = notificationName(e.note); 894 | le.oldPath = toNarrow(e.oldPath); 895 | le.newPath = toNarrow(e.newPath); 896 | // finalScore is assigned later if we update aggregator 897 | 898 | // 3) aggregator logic 899 | int finalScore = 0; 900 | bool newlySus = false; 901 | { 902 | std::lock_guard lk(m_storeMtx); 903 | 904 | if (sumScore > 0) { 905 | auto& st = m_pidMap[e.pid]; 906 | st.score += sumScore; 907 | st.lastUpdate = le.timestamp; 908 | 909 | finalScore = st.score; 910 | if (finalScore >= m_threshold && 911 | (m_flagged.find(e.pid) == m_flagged.end())) 912 | { 913 | m_flagged.insert(e.pid); 914 | newlySus = true; 915 | } 916 | } 917 | 918 | le.finalScore = finalScore; 919 | 920 | // insert into log 921 | { 922 | std::lock_guard loglk(m_logMtx); 923 | m_eventLog.push_back(le); 924 | } 925 | } // aggregator lock ends 926 | 927 | // 4) If newly suspicious => call responses 928 | if (newlySus) { 929 | std::lock_guard lkr(m_respMtx); 930 | for (auto& fn : m_responses) { 931 | fn(e.pid, finalScore, reasons); 932 | } 933 | } 934 | } 935 | 936 | private: 937 | // detectors 938 | std::vector> m_detectors; 939 | mutable std::mutex m_detectorsMtx; 940 | // aggregator store 941 | std::unordered_map m_pidMap; 942 | std::unordered_set m_flagged; 943 | mutable std::mutex m_storeMtx; 944 | 945 | // event log 946 | std::vector m_eventLog; 947 | mutable std::mutex m_logMtx; 948 | 949 | // responses 950 | std::vector> m_responses; 951 | mutable std::mutex m_respMtx; 952 | 953 | int m_threshold = 5; 954 | uint64_t m_ttlMs = 300000ULL; 955 | 956 | std::atomic m_stop; 957 | std::thread m_pruneThread; 958 | 959 | void pruneLoop() 960 | { 961 | while (!m_stop) { 962 | std::this_thread::sleep_for(std::chrono::seconds(30)); 963 | pruneExpired(); 964 | } 965 | } 966 | void pruneExpired() 967 | { 968 | uint64_t now = nowMillis(); 969 | std::lock_guard lk(m_storeMtx); 970 | for (auto it = m_pidMap.begin(); it != m_pidMap.end(); ) 971 | { 972 | auto& st = it->second; 973 | if ((now - st.lastUpdate) >= m_ttlMs) { 974 | it = m_pidMap.erase(it); 975 | } 976 | else { 977 | ++it; 978 | } 979 | } 980 | } 981 | }; 982 | 983 | 984 | void logSuspicious(DWORD pid, int score, const std::string& reasons) 985 | { 986 | std::printf("[ALERT] PID=%u => suspicious (score=%d). reasons=%s\n", 987 | (unsigned)pid, score, reasons.c_str()); 988 | } 989 | void terminateProcess(DWORD pid, int score, const std::string& reasons) 990 | { 991 | HANDLE hProc = ::OpenProcess(PROCESS_TERMINATE, FALSE, pid); 992 | if (!hProc) { 993 | std::printf("[ALERT] Could not open PID=%u to terminate\n", (unsigned)pid); 994 | return; 995 | } 996 | if (!::TerminateProcess(hProc, 0)) { 997 | std::printf("[ALERT] TerminateProcess on PID=%u => GLE=0x%x\n", (unsigned)pid, ::GetLastError()); 998 | } 999 | else { 1000 | std::printf("[ALERT] Terminated PID=%u.\n", (unsigned)pid); 1001 | } 1002 | ::CloseHandle(hProc); 1003 | } 1004 | 1005 | static bool readAllFile(const std::wstring& path, std::vector& out) 1006 | { 1007 | HANDLE h = ::CreateFileW(path.c_str(), 1008 | GENERIC_READ, 1009 | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 1010 | nullptr, 1011 | OPEN_EXISTING, 1012 | FILE_ATTRIBUTE_NORMAL, 1013 | nullptr); 1014 | if (h == INVALID_HANDLE_VALUE) return false; 1015 | LARGE_INTEGER sz; 1016 | if (!::GetFileSizeEx(h, &sz) || sz.QuadPart <= 0) { 1017 | ::CloseHandle(h); 1018 | return false; 1019 | } 1020 | out.resize((size_t)sz.QuadPart); 1021 | DWORD got = 0; 1022 | BOOL ok = ::ReadFile(h, out.data(), (DWORD)sz.QuadPart, &got, nullptr); 1023 | ::CloseHandle(h); 1024 | if (!ok || got < (DWORD)sz.QuadPart) { 1025 | out.clear(); 1026 | return false; 1027 | } 1028 | return true; 1029 | } 1030 | 1031 | class InMemoryProvider : public regfs::VirtualizationInstance 1032 | { 1033 | public: 1034 | InMemoryProvider(std::unique_ptr fs, 1035 | DetectionEngine& engine) 1036 | : m_fs(std::move(fs)) 1037 | , m_engine(engine) 1038 | { 1039 | SetOptionalMethods(regfs::OptionalMethods::Notify); 1040 | } 1041 | 1042 | // required 1043 | HRESULT StartDirEnum(const PRJ_CALLBACK_DATA* d, const GUID* eId) override 1044 | { 1045 | std::lock_guard lk(m_enumLock); 1046 | m_enums[*eId].index = 0; 1047 | return S_OK; 1048 | } 1049 | HRESULT EndDirEnum(const PRJ_CALLBACK_DATA* d, const GUID* eId) override 1050 | { 1051 | std::lock_guard lk(m_enumLock); 1052 | m_enums.erase(*eId); 1053 | return S_OK; 1054 | } 1055 | HRESULT GetDirEnum(const PRJ_CALLBACK_DATA* d, 1056 | const GUID* eId, 1057 | PCWSTR expr, 1058 | PRJ_DIR_ENTRY_BUFFER_HANDLE h) override 1059 | { 1060 | if (!expr || !*expr) expr = L"*"; 1061 | std::lock_guard lk(m_enumLock); 1062 | auto it = m_enums.find(*eId); 1063 | if (it == m_enums.end()) return E_INVALIDARG; 1064 | auto& st = it->second; 1065 | 1066 | if ((d->Flags & PRJ_CB_DATA_FLAG_ENUM_RESTART_SCAN) != 0) { 1067 | st.index = 0; 1068 | st.entries.clear(); 1069 | } 1070 | if (st.entries.empty()) { 1071 | auto wpath = removeLeadingSlash(d->FilePathName); 1072 | FsNode* node = m_fs->findNode(wpath); 1073 | if (!node || !node->isDirectory()) { 1074 | return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); 1075 | } 1076 | for (auto& kv : node->children) { 1077 | const FsNode* c = kv.second.get(); 1078 | if (::PrjFileNameMatch(c->name().c_str(), expr)) { 1079 | st.entries.push_back(c); 1080 | } 1081 | } 1082 | } 1083 | while (st.index < st.entries.size()) { 1084 | const FsNode* c = st.entries[st.index]; 1085 | PRJ_FILE_BASIC_INFO info{}; 1086 | info.IsDirectory = c->isDirectory(); 1087 | info.FileSize = c->isDirectory() ? 0 : c->size().QuadPart; 1088 | 1089 | LARGE_INTEGER ct, wt; 1090 | ct.LowPart = c->creationTime().dwLowDateTime; 1091 | ct.HighPart = c->creationTime().dwHighDateTime; 1092 | wt.LowPart = c->lastWriteTime().dwLowDateTime; 1093 | wt.HighPart = c->lastWriteTime().dwHighDateTime; 1094 | 1095 | info.CreationTime = ct; 1096 | info.LastWriteTime = wt; 1097 | info.ChangeTime = wt; 1098 | info.LastAccessTime = wt; 1099 | info.FileAttributes = c->isDirectory() ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; 1100 | 1101 | HRESULT hr = ::PrjFillDirEntryBuffer(c->name().c_str(), &info, h); 1102 | if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) { 1103 | return hr; 1104 | } 1105 | if (FAILED(hr)) return hr; 1106 | st.index++; 1107 | } 1108 | return S_OK; 1109 | } 1110 | 1111 | HRESULT GetPlaceholderInfo(const PRJ_CALLBACK_DATA* d) override 1112 | { 1113 | auto wpath = removeLeadingSlash(d->FilePathName); 1114 | FsNode* node = m_fs->findNode(wpath); 1115 | if (!node) { 1116 | return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); 1117 | } 1118 | PRJ_PLACEHOLDER_INFO ph{}; 1119 | ph.FileBasicInfo.IsDirectory = node->isDirectory(); 1120 | ph.FileBasicInfo.FileSize = node->isDirectory() ? 0 : node->size().QuadPart; 1121 | 1122 | LARGE_INTEGER ct, wt; 1123 | ct.LowPart = node->creationTime().dwLowDateTime; 1124 | ct.HighPart = node->creationTime().dwHighDateTime; 1125 | wt.LowPart = node->lastWriteTime().dwLowDateTime; 1126 | wt.HighPart = node->lastWriteTime().dwHighDateTime; 1127 | 1128 | ph.FileBasicInfo.CreationTime = ct; 1129 | ph.FileBasicInfo.LastWriteTime = wt; 1130 | ph.FileBasicInfo.ChangeTime = wt; 1131 | ph.FileBasicInfo.LastAccessTime = wt; 1132 | ph.FileBasicInfo.FileAttributes = node->isDirectory() ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; 1133 | 1134 | return WritePlaceholderInfo(d->FilePathName, &ph, sizeof(ph)); 1135 | } 1136 | HRESULT GetFileData(const PRJ_CALLBACK_DATA* d, 1137 | UINT64 off, 1138 | UINT32 len) override 1139 | { 1140 | auto wpath = removeLeadingSlash(d->FilePathName); 1141 | FsNode* node = m_fs->findNode(wpath); 1142 | if (!node || node->isDirectory()) { 1143 | return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); 1144 | } 1145 | const auto& buf = node->content(); 1146 | if (off >= buf.size()) return S_OK; 1147 | UINT64 remain = buf.size() - off; 1148 | UINT32 toRead = (remain < len) ? (UINT32)remain : len; 1149 | 1150 | void* block = ::PrjAllocateAlignedBuffer(_instanceHandle, toRead); 1151 | if (!block) return E_OUTOFMEMORY; 1152 | memcpy(block, &buf[(size_t)off], toRead); 1153 | 1154 | HRESULT hr = WriteFileData(&d->DataStreamId, block, off, toRead); 1155 | ::PrjFreeAlignedBuffer(block); 1156 | return hr; 1157 | } 1158 | 1159 | // main detection logic 1160 | HRESULT Notify(const PRJ_CALLBACK_DATA* d, 1161 | BOOLEAN isDirectory, 1162 | PRJ_NOTIFICATION nt, 1163 | PCWSTR dstName, 1164 | PRJ_NOTIFICATION_PARAMETERS* params) override 1165 | { 1166 | DWORD pid = d->TriggeringProcessId; 1167 | auto oldPath = removeLeadingSlash(d->FilePathName); 1168 | std::wstring newPath; 1169 | if (dstName && *dstName) { 1170 | newPath = removeLeadingSlash(dstName); 1171 | } 1172 | std::printf("[Notify] PID=%u, %s, old=%ls, new=%ls\n", 1173 | (unsigned)pid, 1174 | notificationName(nt).c_str(), 1175 | oldPath.c_str(), 1176 | newPath.c_str()); 1177 | 1178 | // 1) copy old data 1179 | FsNode* oldNode = m_fs->findNode(oldPath); 1180 | std::vector oldData; 1181 | if (oldNode && !oldNode->isDirectory()) { 1182 | oldData = oldNode->content(); // copy 1183 | } 1184 | 1185 | // 2) do delete, rename 1186 | if ((nt & PRJ_NOTIFICATION_PRE_DELETE) != 0) { 1187 | m_fs->removePath(oldPath); 1188 | } 1189 | if ((nt & PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_DELETED) != 0) { 1190 | m_fs->removePath(oldPath); 1191 | } 1192 | if ((nt & PRJ_NOTIFICATION_PRE_RENAME) != 0) { 1193 | if (!newPath.empty()) { 1194 | m_fs->renamePath(oldPath, newPath); 1195 | } 1196 | } 1197 | 1198 | // 3) overwritten => read new data 1199 | std::vector newData; 1200 | if (((nt & PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_MODIFIED) != 0) || 1201 | ((nt & PRJ_NOTIFICATION_FILE_OVERWRITTEN) != 0)) 1202 | { 1203 | if (!isDirectory) { 1204 | auto diskPath = unifyPath(_rootPath, d->FilePathName); 1205 | if (readAllFile(diskPath, newData)) { 1206 | m_fs->overwriteFile(oldPath, newData); 1207 | } 1208 | } 1209 | } 1210 | 1211 | // 4) build detection event 1212 | DetectionEvent ev{}; 1213 | ev.pid = pid; 1214 | ev.note = nt; 1215 | ev.oldNode = oldNode; 1216 | ev.oldData = std::move(oldData); 1217 | ev.newData = std::move(newData); 1218 | ev.oldPath = oldPath; 1219 | ev.newPath = newPath; 1220 | 1221 | // 5) pass to aggregator 1222 | m_engine.handleEvent(ev); 1223 | 1224 | return S_OK; 1225 | } 1226 | 1227 | private: 1228 | struct EnumState { 1229 | size_t index = 0; 1230 | std::vector entries; 1231 | }; 1232 | std::mutex m_enumLock; 1233 | std::unordered_map m_enums; 1234 | 1235 | std::unique_ptr m_fs; 1236 | DetectionEngine& m_engine; 1237 | 1238 | static std::wstring removeLeadingSlash(const std::wstring& s) 1239 | { 1240 | if (!s.empty() && s[0] == L'\\') return s.substr(1); 1241 | return s; 1242 | } 1243 | }; 1244 | 1245 | 1246 | static bool IsRunningAsAdmin() 1247 | { 1248 | BOOL isAdmin = FALSE; 1249 | SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; 1250 | PSID adminGroup = nullptr; 1251 | if (::AllocateAndInitializeSid(&NtAuthority, 2, 1252 | SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 1253 | 0, 0, 0, 0, 0, 0, &adminGroup)) 1254 | { 1255 | ::CheckTokenMembership(nullptr, adminGroup, &isAdmin); 1256 | ::FreeSid(adminGroup); 1257 | } 1258 | return (isAdmin == TRUE); 1259 | } 1260 | 1261 | static void createSampleFiles(FsNode* parent) 1262 | { 1263 | if (!parent || !parent->isDirectory()) return; 1264 | static const std::string types[] = { "docx","xlsx","pdf","txt" }; 1265 | for (int i = 0;i < 4;i++) { 1266 | auto gen = ContentRegistry::instance().get(types[i]); 1267 | if (!gen) continue; 1268 | 1269 | auto node = std::make_unique( 1270 | std::wstring(L"Random_") + std::to_wstring(i) + L"." + std::wstring(types[i].begin(), types[i].end()), 1271 | FsNode::Type::File); 1272 | node->setRandomTimes(); 1273 | auto data = gen->generateFile(); 1274 | node->setContent(data); 1275 | parent->addChild(std::move(node)); 1276 | } 1277 | } 1278 | 1279 | int wmain() 1280 | { 1281 | if (!IsRunningAsAdmin()) { 1282 | std::printf("Must run as Administrator.\n"); 1283 | return 1; 1284 | } 1285 | // register content generators 1286 | registerDefaultTypes(); 1287 | 1288 | // build FS 1289 | auto fs = std::make_unique(L"Root"); 1290 | { 1291 | auto sub = std::make_unique(L"FolderA", FsNode::Type::Directory); 1292 | sub->setRandomTimes(); 1293 | createSampleFiles(sub.get()); 1294 | fs->root()->addChild(std::move(sub)); 1295 | } 1296 | { 1297 | auto sub = std::make_unique(L"FolderB", FsNode::Type::Directory); 1298 | sub->setRandomTimes(); 1299 | createSampleFiles(sub.get()); 1300 | fs->root()->addChild(std::move(sub)); 1301 | } 1302 | 1303 | DetectionEngine engine(/*threshold=*/5, /*ttlSec=*/300); 1304 | engine.addDetector(std::make_unique(3)); 1305 | engine.addDetector(std::make_unique(1.5)); 1306 | engine.addDetector(std::make_unique()); 1307 | 1308 | engine.addResponse(logSuspicious); 1309 | engine.addResponse(terminateProcess); 1310 | 1311 | InMemoryProvider provider(std::move(fs), engine); 1312 | 1313 | PRJ_NOTIFICATION_MAPPING nm[1]; 1314 | nm[0].NotificationRoot = L""; 1315 | nm[0].NotificationBitMask = (PRJ_NOTIFY_TYPES)( 1316 | PRJ_NOTIFICATION_FILE_OPENED 1317 | | PRJ_NOTIFICATION_FILE_RENAMED 1318 | | PRJ_NOTIFICATION_PRE_RENAME 1319 | | PRJ_NOTIFICATION_FILE_OVERWRITTEN 1320 | | PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_MODIFIED 1321 | | PRJ_NOTIFICATION_PRE_DELETE 1322 | | PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_DELETED 1323 | ); 1324 | PRJ_STARTVIRTUALIZING_OPTIONS opts{}; 1325 | opts.NotificationMappings = nm; 1326 | opts.NotificationMappingsCount = 1; 1327 | opts.PoolThreadCount = 4; 1328 | opts.ConcurrentThreadCount = 4; 1329 | 1330 | HRESULT hr = provider.Start(LR"(C:\$Honeypot)", &opts); 1331 | if (FAILED(hr)) { 1332 | std::printf("Failed to start ProjFS, hr=0x%08X\n", (unsigned)hr); 1333 | return 2; 1334 | } 1335 | std::printf("ProjFS running on C:\\$Honeypot. Press ENTER to stop...\n"); 1336 | std::wstring dummy; 1337 | std::getline(std::wcin, dummy); 1338 | 1339 | provider.Stop(); 1340 | std::printf("Stopped.\n"); 1341 | 1342 | // optional: final log 1343 | std::printf("\n---- Final Chronological Event Log ----\n"); 1344 | engine.printLog(); 1345 | 1346 | return 0; 1347 | } 1348 | -------------------------------------------------------------------------------- /babyk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rad9800/RansomFS/b24fdbd4fac18c83536d3fe39d4c1e626ede68df/babyk.png --------------------------------------------------------------------------------