├── .clang-format ├── .editorconfig ├── .gitattributes ├── .github ├── Invoke-VisualStudio.ps1 └── workflows │ └── build.yml ├── .gitignore ├── CMakeLists.txt ├── Common ├── CMakeLists.txt ├── Log.cpp ├── Log.hpp ├── Utils.cpp └── Utils.hpp ├── DeviceDriver ├── CMakeLists.txt ├── DeviceDriver.cpp └── DeviceDriver.hpp ├── LICENSE ├── MiniFilter ├── CMakeLists.txt ├── MinifilterDriver.cpp ├── MinifilterDriver.hpp ├── MinifilterDriver.inf └── MinifilterDriver.rc ├── README.md ├── Scripts └── SignDriver.ps1 └── cmake └── FindWdk.cmake /.clang-format: -------------------------------------------------------------------------------- 1 | # Format Style Options - Created with Clang Power Tools 2 | --- 3 | AccessModifierOffset: -4 4 | AlignAfterOpenBracket: AlwaysBreak 5 | AlignConsecutiveAssignments: true 6 | AlignConsecutiveBitFields: true 7 | AlignConsecutiveMacros: false 8 | AlignEscapedNewlines: Right 9 | AlignOperands: true 10 | AlignTrailingComments: true 11 | AllowAllArgumentsOnNextLine: false 12 | AllowAllConstructorInitializersOnNextLine: false 13 | AllowAllParametersOfDeclarationOnNextLine: false 14 | AllowShortBlocksOnASingleLine: false 15 | AllowShortCaseLabelsOnASingleLine: false 16 | AllowShortLambdasOnASingleLine: Empty 17 | AllowShortEnumsOnASingleLine: false 18 | AllowShortFunctionsOnASingleLine: None 19 | AllowShortIfStatementsOnASingleLine: Never 20 | AllowShortLoopsOnASingleLine: false 21 | AlwaysBreakAfterReturnType: All 22 | AlwaysBreakBeforeMultilineStrings: true 23 | AlwaysBreakTemplateDeclarations: Yes 24 | BasedOnStyle: Google 25 | BinPackArguments: false 26 | BinPackParameters: false 27 | BitFieldColonSpacing: Both 28 | BraceWrapping: 29 | AfterCaseLabel: true 30 | AfterClass: true 31 | AfterControlStatement: true 32 | AfterEnum: true 33 | AfterFunction: true 34 | AfterNamespace: true 35 | AfterObjCDeclaration: true 36 | AfterStruct: true 37 | AfterUnion: true 38 | AfterExternBlock: true 39 | BeforeCatch: true 40 | BeforeElse: true 41 | IndentBraces: true 42 | SplitEmptyFunction: true 43 | SplitEmptyRecord: true 44 | SplitEmptyNamespace: true 45 | BeforeLambdaBody: false 46 | BeforeWhile: false 47 | BreakBeforeBinaryOperators: None 48 | BreakBeforeBraces: Allman 49 | BreakInheritanceList: AfterColon 50 | BreakBeforeTernaryOperators: false 51 | BreakConstructorInitializers: AfterColon 52 | ColumnLimit: 120 53 | CommentPragmas: '^ IWYU pragma:' 54 | CompactNamespaces: false 55 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 56 | ConstructorInitializerIndentWidth : 4 57 | ContinuationIndentWidth: 4 58 | Cpp11BracedListStyle: true 59 | DerivePointerAlignment: false 60 | ExperimentalAutoDetectBinPacking: false 61 | FixNamespaceComments: true 62 | ForEachMacros: 63 | [foreach, Q_FOREACH, BOOST_FOREACH] 64 | IndentCaseBlocks: false 65 | IndentCaseLabels: false 66 | IndentExternBlock: NoIndent 67 | IndentGotoLabels: false 68 | IndentPPDirectives: None 69 | IndentWidth: 4 70 | IndentWrappedFunctionNames: false 71 | KeepEmptyLinesAtTheStartOfBlocks: true 72 | Language: Cpp 73 | MaxEmptyLinesToKeep: 2 74 | NamespaceIndentation: None 75 | PenaltyBreakBeforeFirstCallParameter: 1 76 | PenaltyBreakComment: 300 77 | PenaltyBreakFirstLessLess: 120 78 | PenaltyBreakString: 1000 79 | PenaltyExcessCharacter: 1000000 80 | PenaltyReturnTypeOnItsOwnLine: 200 81 | PointerAlignment: Left 82 | ReflowComments: true 83 | SortUsingDeclarations: true 84 | SpaceAfterCStyleCast: false 85 | SpaceAfterLogicalNot: false 86 | SpaceAfterTemplateKeyword: false 87 | SpaceAroundPointerQualifiers: Before 88 | SpaceBeforeAssignmentOperators: true 89 | SpaceBeforeCpp11BracedList: true 90 | SpaceBeforeParens: ControlStatements 91 | SpaceBeforeRangeBasedForLoopColon: true 92 | SpaceBeforeSquareBrackets: false 93 | SpaceInEmptyBlock: false 94 | SpaceInEmptyParentheses: false 95 | SpacesBeforeTrailingComments: 1 96 | SpacesInAngles: false 97 | SpacesInContainerLiterals: false 98 | SpacesInCStyleCastParentheses: false 99 | SpacesInConditionalStatement: true 100 | SpacesInParentheses: false 101 | SpacesInSquareBrackets: false 102 | Standard: Auto 103 | StatementMacros: 104 | ['EXTERN_C', 'PAGED', 'PAGEDX', 'NONPAGED', 'PNPCODE', 'INITCODE', '_At_', '_When_', '_Success_', '_Check_return_', '_Must_inspect_result_', '_IRQL_requires_', '_IRQL_requires_max_', '_IRQL_requires_min_', '_IRQL_saves_', '_IRQL_restores_', '_IRQL_saves_global_', '_IRQL_restores_global_', '_IRQL_raises_', '_IRQL_lowers_', '_Acquires_lock_', '_Releases_lock_', '_Acquires_exclusive_lock_', '_Releases_exclusive_lock_', '_Acquires_shared_lock_', '_Releases_shared_lock_', '_Requires_lock_held_', '_Use_decl_annotations_', '_Guarded_by_', '__drv_preferredFunction', '__drv_allocatesMem', '__drv_freesMem'] 105 | TabWidth: 4 106 | UseCRLF: true 107 | UseTab: Never 108 | ... 109 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties 2 | 3 | root = true 4 | 5 | [*] 6 | end_of_line = lf 7 | insert_final_newline = true 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.{cpp,cc,h,hpp}] 13 | indent_style = space 14 | indent_size = 4 15 | 16 | 17 | [CMakeLists.txt] 18 | indent_style = space 19 | indent_size = 4 20 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.github/Invoke-VisualStudio.ps1: -------------------------------------------------------------------------------- 1 | Function Invoke-CmdScript { 2 | param( 3 | [String] $scriptName 4 | ) 5 | $cmdLine = """$scriptName"" $args & set" 6 | & $env:SystemRoot\system32\cmd.exe /c $cmdLine | 7 | Select-String '^([^=]*)=(.*)$' | ForEach-Object { 8 | $varName = $_.Matches[0].Groups[1].Value 9 | $varValue = $_.Matches[0].Groups[2].Value 10 | Set-Item Env:$varName $varValue 11 | } 12 | } 13 | 14 | Function Invoke-VisualStudio2019win32 { 15 | Invoke-CmdScript "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars32.bat" 16 | } 17 | 18 | Function Invoke-VisualStudio2019x64 { 19 | Invoke-CmdScript "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars64.bat" 20 | } 21 | 22 | Function Invoke-VisualStudio2019arm64 { 23 | Invoke-CmdScript "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvarsamd64_arm64.bat" 24 | } 25 | 26 | Function Invoke-VisualStudio2022win32 { 27 | Invoke-CmdScript "C:/Program Files/Microsoft Visual Studio/2022/Enterprise/VC/Auxiliary/Build/vcvars32.bat" 28 | } 29 | 30 | Function Invoke-VisualStudio2022x64 { 31 | Invoke-CmdScript "C:/Program Files/Microsoft Visual Studio/2022/Enterprise/VC/Auxiliary/Build/vcvars64.bat" 32 | } 33 | 34 | Function Invoke-VisualStudio2022arm64 { 35 | Invoke-CmdScript "C:/Program Files/Microsoft Visual Studio/2022/Enterprise/VC/Auxiliary/Build/vcvarsamd64_arm64.bat" 36 | } 37 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: "Build Driver" 2 | 3 | env: 4 | PROJECT: changeme 5 | AUTHOR: hugsy 6 | 7 | on: 8 | workflow_dispatch: 9 | pull_request: 10 | branches: 11 | - main 12 | push: 13 | branches: 14 | - main 15 | 16 | jobs: 17 | build: 18 | env: 19 | VERBOSE: 1 20 | NB_CPU: 1 21 | CMAKE_FLAGS: 22 | 23 | name: "win${{ matrix.windows_version }}/${{ matrix.platform }}/${{ matrix.configuration }}" 24 | 25 | strategy: 26 | fail-fast: false 27 | matrix: 28 | windows_version: ['2022', '2019'] 29 | platform: ['x64', 'win32', 'arm64'] 30 | configuration: ['RelWithDebInfo', 'Debug'] 31 | 32 | runs-on: windows-${{ matrix.windows_version }} 33 | permissions: 34 | actions: read 35 | contents: read 36 | 37 | steps: 38 | - uses: actions/checkout@v4 39 | with: 40 | submodules: true 41 | 42 | - name: Sets Environment Variables 43 | shell: powershell 44 | run: | 45 | echo "NB_CPU=$env:NUMBER_OF_PROCESSORS" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append 46 | 47 | - name: Prepare Windows environment 48 | shell: pwsh 49 | run: | 50 | Import-Module .\.github\Invoke-VisualStudio.ps1 51 | Invoke-VisualStudio${{ matrix.windows_version }}${{ matrix.platform }} 52 | 53 | - name: Build source 54 | run: | 55 | cmake -S . -B build -A ${{ matrix.platform }} ${{ env.CMAKE_FLAGS }} 56 | cmake --build ./build --verbose --parallel ${{ env.NB_CPU }} --config ${{ matrix.configuration }} 57 | 58 | - name: Prepare artifact 59 | run: | 60 | mkdir artifact 61 | cmake --install ./build --config ${{ matrix.configuration }} --prefix ./artifact --verbose 62 | 63 | - name: Publish artifact 64 | uses: actions/upload-artifact@v4 65 | with: 66 | name: ${{ env.PROJECT }}_${{ github.ref_name }}_win${{ matrix.windows_version }}_${{ matrix.platform }}_${{ matrix.configuration }}_${{ github.sha }} 67 | path: artifact/ 68 | -------------------------------------------------------------------------------- /.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 364 | 365 | build 366 | .vscode 367 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.16) 2 | set(CMAKE_CXX_STANDARD 20) 3 | set(CMAKE_CXX_STANDARD_REQUIRED True) 4 | set(CMAKE_CXX_EXTENSIONS OFF) 5 | set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) 6 | 7 | project( 8 | changeme 9 | LANGUAGES CXX 10 | VERSION 0.1.0 11 | DESCRIPTION "changeme" 12 | HOMEPAGE_URL https://github.com/hugsy/changeme 13 | ) 14 | 15 | set(PROJECT_AUTHOR hugsy) 16 | set(PROJECT_LICENSE MIT) 17 | 18 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") 19 | 20 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 21 | 22 | option(DEBUG "Enable Debug" ON) 23 | option(BUILD_DEVICEDRIVER "Compile the device driver" ON) 24 | option(BUILD_MINIFILTER "Compile the minifilter driver" ON) 25 | 26 | message(STATUS "Locating Windows Driver Kit") 27 | find_package(WDK REQUIRED) 28 | 29 | 30 | # 31 | # Build DriverLib 32 | # 33 | add_subdirectory(Common) 34 | 35 | 36 | # 37 | # Build Driver 38 | # 39 | if(BUILD_DEVICEDRIVER) 40 | add_subdirectory(DeviceDriver) 41 | endif() 42 | 43 | 44 | # 45 | # Build Minifilter 46 | # 47 | if(BUILD_MINIFILTER) 48 | add_subdirectory(MiniFilter) 49 | endif() 50 | -------------------------------------------------------------------------------- /Common/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | message(STATUS "Configuring DriverLib") 2 | 3 | wdk_add_library(DriverLib 4 | STATIC 5 | KMDF 6 | 1.15 7 | 8 | ../Common/Log.cpp 9 | ../Common/Log.hpp 10 | ../Common/Utils.cpp 11 | ../Common/Utils.hpp 12 | ) 13 | 14 | target_include_directories(DriverLib INTERFACE ../Common) 15 | 16 | -------------------------------------------------------------------------------- /Common/Log.cpp: -------------------------------------------------------------------------------- 1 | #include "Log.hpp" 2 | 3 | 4 | namespace Log 5 | { 6 | 7 | void 8 | Log(_In_ const wchar_t* FormatString, ...) 9 | { 10 | va_list args; 11 | wchar_t buffer[1024] {}; 12 | va_start(args, FormatString); 13 | ::vswprintf_s(buffer, sizeof(buffer) / sizeof(wchar_t), FormatString, args); 14 | va_end(args); 15 | Log("%S", buffer); 16 | } 17 | 18 | void 19 | Log(_In_ const char* FormatString, ...) 20 | { 21 | va_list args; 22 | va_start(args, FormatString); 23 | char buffer[1024] {}; 24 | ::vDbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, FormatString, args); 25 | va_end(args); 26 | } 27 | 28 | } // namespace Log 29 | -------------------------------------------------------------------------------- /Common/Log.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #define _NO_CRT_STDIO_INLINE 1 6 | #include 7 | #include 8 | 9 | #define WIDEN2(x) L##x 10 | #define WIDEN(x) WIDEN2(x) 11 | #define __WFILE__ WIDEN(__FILE__) 12 | #define __WFUNCTION__ WIDEN(__FUNCTION__) 13 | 14 | 15 | namespace Log 16 | { 17 | void 18 | Log(_In_ const wchar_t* FormatString, ...); 19 | 20 | void 21 | Log(_In_ const char* FormatString, ...); 22 | 23 | void 24 | ntperror(_In_ const wchar_t* prefix, _In_ NTSTATUS Status); 25 | }; // namespace Log 26 | 27 | 28 | #ifdef _DEBUG 29 | #define dbg(fmt, ...) Log::Log(L"[=] " fmt L"\n", __VA_ARGS__) 30 | #else 31 | #define dbg(fmt, ...) 32 | #endif // _DEBUG 33 | 34 | #define ok(fmt, ...) Log::Log(L"[+] " fmt L"\n", __VA_ARGS__) 35 | #define info(fmt, ...) Log::Log(L"[*] " fmt L"\n", __VA_ARGS__) 36 | #define warn(fmt, ...) Log::Log(L"[!] " fmt L"\n", __VA_ARGS__) 37 | #define err(fmt, ...) Log::Log(L"[-] " fmt L"\n", __VA_ARGS__) 38 | 39 | -------------------------------------------------------------------------------- /Common/Utils.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Utils.hpp" 4 | 5 | 6 | Utils::KMutex::KMutex() 7 | { 8 | ::KeInitializeMutex(&_mutex, 0); 9 | } 10 | 11 | void Utils::KMutex::Lock() 12 | { 13 | ::KeWaitForSingleObject(&_mutex, Executive, KernelMode, false, nullptr); 14 | } 15 | 16 | void Utils::KMutex::Unlock() 17 | { 18 | if (!::KeReleaseMutex(&_mutex, true)) 19 | { 20 | ::KeWaitForSingleObject(&_mutex, Executive, KernelMode, false, nullptr); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Common/Utils.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "../Common/Log.hpp" 6 | 7 | // 8 | // Types 9 | // 10 | 11 | /// 12 | /// Static types 13 | /// 14 | using u8 = UINT8; 15 | using u16 = UINT16; 16 | using u32 = UINT32; 17 | using u64 = UINT64; 18 | 19 | using i8 = INT8; 20 | using i16 = INT16; 21 | using i32 = INT32; 22 | using i64 = INT64; 23 | 24 | using usize = SIZE_T; 25 | 26 | #ifndef countof 27 | #define countof(arr) ((sizeof(arr)) / (sizeof(arr[0]))) 28 | #endif 29 | 30 | 31 | /// 32 | /// Compile-time types 33 | /// 34 | 35 | 36 | template 37 | class GenericBuffer 38 | { 39 | public: 40 | constexpr GenericBuffer(const C* str) noexcept 41 | { 42 | auto i = 0; 43 | const C* ptr = str; 44 | for ( ptr = str, i = 0; i < S + 1; i++ ) 45 | { 46 | m_buffer[i] = ptr[i]; 47 | } 48 | } 49 | 50 | constexpr usize 51 | size() const noexcept 52 | { 53 | return m_size; 54 | } 55 | 56 | constexpr 57 | operator C*() noexcept 58 | { 59 | return m_buffer; 60 | } 61 | 62 | constexpr operator const C*() const noexcept 63 | { 64 | return m_buffer; 65 | } 66 | 67 | const C* 68 | get() const noexcept 69 | { 70 | return m_buffer; 71 | } 72 | 73 | 74 | private: 75 | C m_buffer[S + 1] = {0}; 76 | usize m_size = S; 77 | }; 78 | 79 | using basic_string = GenericBuffer; 80 | using basic_wstring = GenericBuffer; 81 | 82 | 83 | namespace Utils 84 | { 85 | 86 | 87 | template 88 | class KLock 89 | { 90 | KLock(T& lock) : _lock(lock) 91 | { 92 | _lock.Lock(); 93 | } 94 | ~KLock() 95 | { 96 | _lock.Unlock(); 97 | } 98 | 99 | private: 100 | T& _lock; 101 | }; 102 | 103 | 104 | class KMutex 105 | { 106 | public: 107 | KMutex(); 108 | void 109 | Lock(); 110 | void 111 | Unlock(); 112 | 113 | private: 114 | KMUTEX _mutex; 115 | }; 116 | 117 | 118 | template 119 | class ScopedWrapper 120 | { 121 | public: 122 | ScopedWrapper(T& f, DTOR_FUNC d) : _f(f), _d(d) 123 | { 124 | } 125 | 126 | ~ScopedWrapper() 127 | { 128 | _d(); 129 | } 130 | 131 | T 132 | get() const 133 | { 134 | return _f; 135 | } 136 | 137 | private: 138 | T _f; 139 | DTOR_FUNC _d; 140 | }; 141 | 142 | 143 | template 144 | class KAlloc 145 | { 146 | public: 147 | KAlloc(const usize sz = 0, const u32 tag = 0) : _tag(tag), _sz(sz), _mem(nullptr) 148 | { 149 | if ( !sz || sz >= MAXUSHORT ) 150 | return; 151 | 152 | auto p = ::ExAllocatePoolWithTag(PagedPool, _sz, _tag); 153 | if ( p ) 154 | { 155 | _mem = reinterpret_cast(p); 156 | ::RtlSecureZeroMemory((PUCHAR)_mem, _sz); 157 | } 158 | } 159 | 160 | ~KAlloc() 161 | { 162 | __free(); 163 | } 164 | 165 | virtual void 166 | __free() 167 | { 168 | if ( _mem != nullptr ) 169 | { 170 | ::RtlSecureZeroMemory((PUCHAR)_mem, _sz); 171 | ::ExFreePoolWithTag(_mem, _tag); 172 | _mem = nullptr; 173 | _tag = 0; 174 | _sz = 0; 175 | } 176 | } 177 | 178 | KAlloc(const KAlloc&) = delete; 179 | 180 | KAlloc& 181 | operator=(const KAlloc&) = delete; 182 | 183 | KAlloc& 184 | operator=(KAlloc&& other) noexcept 185 | { 186 | if ( this != &other ) 187 | { 188 | _mem = other._mem; 189 | _tag = other._tag; 190 | _sz = other._sz; 191 | other._mem = nullptr; 192 | other._tag = 0; 193 | other._sz = 0; 194 | } 195 | return *this; 196 | } 197 | 198 | const T 199 | get() const 200 | { 201 | return _mem; 202 | } 203 | 204 | const size_t 205 | size() const 206 | { 207 | return _sz; 208 | } 209 | 210 | operator bool() const 211 | { 212 | return _mem != nullptr && _sz > 0; 213 | } 214 | 215 | friend bool 216 | operator==(KAlloc const& lhs, KAlloc const& rhs) 217 | { 218 | return lhs._mem == rhs._mem && lhs._tag == rhs._tag; 219 | } 220 | 221 | protected: 222 | T _mem; 223 | size_t _sz; 224 | u32 _tag; 225 | }; 226 | 227 | 228 | class KUnicodeString : public Utils::KAlloc 229 | { 230 | public: 231 | KUnicodeString(size_t sz = 0, const wchar_t* content = nullptr, u32 tag = 0) : 232 | KAlloc(sizeof(UNICODE_STRING) + sz + sizeof(WCHAR), tag) 233 | { 234 | _mem->Length = (u16)_sz; 235 | _mem->MaximumLength = (u16)sz + 1; 236 | _mem->Buffer = (PWCH)((ULONG_PTR)(_mem) + sizeof(UNICODE_STRING)); 237 | if ( content && _sz ) 238 | { 239 | ::RtlCopyMemory(_mem->Buffer, content, _sz); 240 | } 241 | } 242 | 243 | const PUNICODE_STRING 244 | get() const 245 | { 246 | return _mem; 247 | } 248 | 249 | const PWCH 250 | c_str() const 251 | { 252 | return _mem->Buffer; 253 | } 254 | }; 255 | } // namespace Utils 256 | -------------------------------------------------------------------------------- /DeviceDriver/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | message(STATUS "Configuring DeviceDriver") 2 | 3 | wdk_add_driver( 4 | DeviceDriver 5 | KMDF 6 | 1.15 7 | 8 | DeviceDriver.cpp 9 | ) 10 | 11 | target_compile_definitions(DeviceDriver PRIVATE DEBUG=1) 12 | target_link_options(DeviceDriver PUBLIC /integritycheck) 13 | target_link_libraries(DeviceDriver DriverLib) 14 | 15 | set(CERT_CN "BlahCat Corp") 16 | set(CERT_STORE "PrivateCertStore") 17 | set(CERT_FILE "$/BlahCatTest.cer") 18 | 19 | add_custom_command( 20 | TARGET DeviceDriver POST_BUILD 21 | COMMAND 22 | powershell.exe -ExecutionPolicy Bypass -File ${CMAKE_SOURCE_DIR}/Scripts/SignDriver.ps1 23 | ARGS "$" "${CERT_STORE}" "${CERT_CN}" 24 | COMMENT 25 | "Signing driver with self-signed certificate" 26 | ) 27 | 28 | install(TARGETS DeviceDriver DESTINATION Drivers) 29 | install(FILES $ DESTINATION Drivers/Debug) 30 | -------------------------------------------------------------------------------- /DeviceDriver/DeviceDriver.cpp: -------------------------------------------------------------------------------- 1 | #include "DeviceDriver.hpp" 2 | 3 | #include "../Common/Log.hpp" 4 | 5 | static PDEVICE_OBJECT g_pDeviceObject; 6 | 7 | 8 | /// 9 | /// @brief Generic IRP completion function 10 | /// 11 | /// @param [inout] Irp 12 | /// @param [inout] Status 13 | /// @param [inout] Information 14 | /// @return NTSTATUS 15 | /// 16 | EXTERN_C 17 | NTSTATUS 18 | CompleteRequest(_In_ PIRP Irp, _In_ NTSTATUS Status, _In_ ULONG_PTR Information) 19 | { 20 | Irp->IoStatus.Status = Status; 21 | Irp->IoStatus.Information = Information; 22 | IoCompleteRequest(Irp, IO_NO_INCREMENT); 23 | return Status; 24 | } 25 | 26 | 27 | /// 28 | /// @brief Generic routine for unsupported major types. 29 | /// 30 | /// @param [inout] DeviceObject 31 | /// @param [inout] Irp 32 | /// @return NTSTATUS 33 | /// 34 | EXTERN_C 35 | NTSTATUS 36 | IrpNotImplementedHandler(_In_ PDEVICE_OBJECT DeviceObject, _In_ PIRP Irp) 37 | { 38 | UNREFERENCED_PARAMETER(DeviceObject); 39 | PAGED_CODE(); 40 | CompleteRequest(Irp, STATUS_NOT_IMPLEMENTED, 0); 41 | return STATUS_NOT_IMPLEMENTED; 42 | } 43 | 44 | 45 | /// 46 | /// @brief Unload routine 47 | /// 48 | /// @param [inout] DriverObject 49 | /// 50 | EXTERN_C 51 | void 52 | DriverUnloadRoutine(_In_ PDRIVER_OBJECT DriverObject) 53 | { 54 | UNICODE_STRING symLink = RTL_CONSTANT_STRING(DOS_DEVICE_PATH); 55 | ::IoDeleteSymbolicLink(&symLink); 56 | ::IoDeleteDevice(DriverObject->DeviceObject); 57 | 58 | ok(L"Device '%s' unloaded\n", DEVICE_NAME); 59 | return; 60 | } 61 | 62 | 63 | /// 64 | /// @brief 65 | /// 66 | /// @param [inout] DriverObject 67 | /// @param [inout] RegistryPath 68 | /// @return NTSTATUS 69 | /// 70 | EXTERN_C 71 | NTSTATUS 72 | DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) 73 | { 74 | UNREFERENCED_PARAMETER(RegistryPath); 75 | 76 | NTSTATUS Status = STATUS_UNSUCCESSFUL; 77 | g_pDeviceObject = nullptr; 78 | 79 | info(L"Loading '%s'\n", DEVICE_NAME); 80 | do 81 | { 82 | UNICODE_STRING name = RTL_CONSTANT_STRING(DEVICE_PATH); 83 | UNICODE_STRING symLink = RTL_CONSTANT_STRING(DOS_DEVICE_PATH); 84 | 85 | for ( auto i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++ ) 86 | { 87 | DriverObject->MajorFunction[i] = IrpNotImplementedHandler; 88 | } 89 | 90 | DriverObject->DriverUnload = DriverUnloadRoutine; 91 | 92 | Status = ::IoCreateDevice( 93 | DriverObject, 94 | 0, 95 | &name, 96 | FILE_DEVICE_UNKNOWN, 97 | FILE_DEVICE_SECURE_OPEN, 98 | true, 99 | &g_pDeviceObject); 100 | if ( !NT_SUCCESS(Status) ) 101 | { 102 | err(L"Error creating device object (0x%08X)\n", Status); 103 | break; 104 | } 105 | 106 | ok(L"device '%s' successfully created\n", DEVICE_NAME); 107 | 108 | Status = ::IoCreateSymbolicLink(&symLink, &name); 109 | if ( !NT_SUCCESS(Status) ) 110 | { 111 | err(L"IoCreateSymbolicLink() failed: 0x%08X\n", Status); 112 | break; 113 | } 114 | 115 | ok(L"Symlink for '%s' created\n", DEVICE_NAME); 116 | 117 | g_pDeviceObject->Flags |= DO_DIRECT_IO; 118 | g_pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING); 119 | 120 | ok(L"Device initialization for '%s' done\n", DEVICE_NAME); 121 | 122 | } while ( false ); 123 | 124 | return Status; 125 | } 126 | -------------------------------------------------------------------------------- /DeviceDriver/DeviceDriver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "../Common/Utils.hpp" 6 | 7 | #define _NO_CRT_STDIO_INLINE 1 8 | #include 9 | #include 10 | 11 | 12 | #define DEVICE_NAME L"CHANGEME" 13 | #define DEVICE_PATH L"\\Device\\" DEVICE_NAME 14 | #define DOS_DEVICE_PATH L"\\??\\" DEVICE_NAME 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 hugsy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MiniFilter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | message(STATUS "Configuring MinifilterDriver") 2 | 3 | wdk_add_driver(MinifilterDriver 4 | KMDF 5 | 1.15 6 | 7 | MinifilterDriver.cpp 8 | ) 9 | 10 | target_compile_definitions(MinifilterDriver PRIVATE DEBUG=1) 11 | target_link_options(MinifilterDriver PUBLIC /integritycheck) 12 | target_link_libraries(MinifilterDriver DriverLib WDK::FLTMGR WDK::KSECDD) 13 | 14 | set(RC_FILE ${CMAKE_CURRENT_SOURCE_DIR}/MinifilterDriver.rc) 15 | set(INF_FILE ${CMAKE_CURRENT_SOURCE_DIR}/MinifilterDriver.inf) 16 | set(CERT_CN "BlahCat Corp") 17 | set(CERT_STORE "PrivateCertStore") 18 | set(CERT_FILE "$/BlahCatTest.cer") 19 | 20 | add_custom_command( 21 | TARGET MinifilterDriver POST_BUILD 22 | COMMAND 23 | powershell.exe -ExecutionPolicy Bypass -File ${CMAKE_SOURCE_DIR}/Scripts/SignDriver.ps1 24 | ARGS "$" "${CERT_STORE}" "${CERT_CN}" 25 | COMMAND 26 | ${CMAKE_COMMAND} -E copy 27 | ${CMAKE_CURRENT_SOURCE_DIR}/MinifilterDriver.inf 28 | "$/MinifilterDriver.inf" 29 | COMMENT 30 | "Signing driver with self-signed certificate" 31 | ) 32 | 33 | install(TARGETS MinifilterDriver DESTINATION Drivers) 34 | install(FILES $ ${RC_FILE} ${INF_FILE} DESTINATION Drivers/Debug) 35 | -------------------------------------------------------------------------------- /MiniFilter/MinifilterDriver.cpp: -------------------------------------------------------------------------------- 1 | #include "MinifilterDriver.hpp" 2 | 3 | #include "../Common/Log.hpp" 4 | #include "../Common/Utils.hpp" 5 | 6 | #pragma prefast(disable : __WARNING_ENCODE_MEMBER_FUNCTION_POINTER, "Not valid for kernel mode drivers") 7 | 8 | 9 | EXTERN_C_START 10 | 11 | DRIVER_INITIALIZE DriverEntry; 12 | NTSTATUS 13 | DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath); 14 | 15 | 16 | NTSTATUS 17 | MinifilterDriverUnload(_In_ FLT_FILTER_UNLOAD_FLAGS Flags); 18 | 19 | NTSTATUS 20 | MinifilterDriverInstanceSetup( 21 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 22 | _In_ FLT_INSTANCE_SETUP_FLAGS Flags, 23 | _In_ DEVICE_TYPE VolumeDeviceType, 24 | _In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType); 25 | 26 | FLT_PREOP_CALLBACK_STATUS 27 | MinifilterDriverPreCreateOperation( 28 | _Inout_ PFLT_CALLBACK_DATA Data, 29 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 30 | _Flt_CompletionContext_Outptr_ PVOID* CompletionContext); 31 | 32 | FLT_POSTOP_CALLBACK_STATUS 33 | MinifilterDriverPostCreateOperation( 34 | _Inout_ PFLT_CALLBACK_DATA Data, 35 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 36 | _In_opt_ PVOID CompletionContext, 37 | _In_ FLT_POST_OPERATION_FLAGS Flags); 38 | 39 | FLT_PREOP_CALLBACK_STATUS 40 | MinifilterDriverPreWriteOperation( 41 | _Inout_ PFLT_CALLBACK_DATA Data, 42 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 43 | _Flt_CompletionContext_Outptr_ PVOID* CompletionContext); 44 | 45 | EXTERN_C_END 46 | 47 | 48 | const FLT_OPERATION_REGISTRATION Callbacks[] = { 49 | {IRP_MJ_CREATE, 0, MinifilterDriverPreCreateOperation, MinifilterDriverPostCreateOperation}, 50 | {IRP_MJ_WRITE, FLTFL_OPERATION_REGISTRATION_SKIP_PAGING_IO, MinifilterDriverPreWriteOperation}, 51 | {IRP_MJ_OPERATION_END}}; 52 | 53 | 54 | const FLT_REGISTRATION g_FilterRegistration = { 55 | sizeof(FLT_REGISTRATION), // Size 56 | FLT_REGISTRATION_VERSION, // Version 57 | 0, // Flags 58 | nullptr, // Context 59 | Callbacks, // Operation callbacks 60 | MinifilterDriverUnload, // MiniFilterUnload 61 | MinifilterDriverInstanceSetup, // InstanceSetup 62 | nullptr, // InstanceQueryTeardown 63 | nullptr, // InstanceTeardownStart 64 | nullptr, // InstanceTeardownComplete 65 | nullptr, // GenerateFileName 66 | nullptr, // GenerateDestinationFileName 67 | nullptr // NormalizeNameComponent 68 | }; 69 | 70 | 71 | #ifdef ALLOC_PRAGMA 72 | #pragma alloc_text(INIT, DriverEntry) 73 | #pragma alloc_text(PAGE, MinifilterDriverUnload) 74 | #pragma alloc_text(PAGE, MinifilterDriverInstanceSetup) 75 | #endif 76 | 77 | PFLT_FILTER g_FilterHandle; 78 | 79 | 80 | NTSTATUS 81 | DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) 82 | { 83 | UNREFERENCED_PARAMETER(RegistryPath); 84 | PAGED_CODE(); 85 | 86 | info(L"Loading %s\n", DEVICE_NAME); 87 | 88 | auto Status = ::FltRegisterFilter(DriverObject, &g_FilterRegistration, &g_FilterHandle); 89 | if ( !NT_SUCCESS(Status) ) 90 | { 91 | return Status; 92 | } 93 | 94 | Status = ::FltStartFiltering(g_FilterHandle); 95 | if ( !NT_SUCCESS(Status) ) 96 | { 97 | ::FltUnregisterFilter(g_FilterHandle); 98 | } 99 | 100 | ok(L"Loaded fs filter %s\n", DEVICE_NAME); 101 | 102 | return Status; 103 | } 104 | 105 | 106 | NTSTATUS 107 | MinifilterDriverUnload(_In_ FLT_FILTER_UNLOAD_FLAGS Flags) 108 | { 109 | UNREFERENCED_PARAMETER(Flags); 110 | PAGED_CODE(); 111 | ::FltUnregisterFilter(g_FilterHandle); 112 | ok(L"Unloaded fs filter %s\n", DEVICE_NAME); 113 | return STATUS_SUCCESS; 114 | } 115 | 116 | 117 | NTSTATUS 118 | MinifilterDriverInstanceSetup( 119 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 120 | _In_ FLT_INSTANCE_SETUP_FLAGS Flags, 121 | _In_ DEVICE_TYPE VolumeDeviceType, 122 | _In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType) 123 | { 124 | UNREFERENCED_PARAMETER(FltObjects); 125 | UNREFERENCED_PARAMETER(Flags); 126 | UNREFERENCED_PARAMETER(VolumeDeviceType); 127 | UNREFERENCED_PARAMETER(VolumeFilesystemType); 128 | 129 | PAGED_CODE(); 130 | 131 | return STATUS_SUCCESS; 132 | } 133 | 134 | 135 | FLT_PREOP_CALLBACK_STATUS 136 | MinifilterDriverPreCreateOperation( 137 | _Inout_ PFLT_CALLBACK_DATA Data, 138 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 139 | _Flt_CompletionContext_Outptr_ PVOID* CompletionContext) 140 | { 141 | UNREFERENCED_PARAMETER(FltObjects); 142 | UNREFERENCED_PARAMETER(CompletionContext); 143 | 144 | return FLT_PREOP_SUCCESS_NO_CALLBACK; 145 | } 146 | 147 | 148 | FLT_POSTOP_CALLBACK_STATUS 149 | MinifilterDriverPostCreateOperation( 150 | _Inout_ PFLT_CALLBACK_DATA Data, 151 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 152 | _In_opt_ PVOID CompletionContext, 153 | _In_ FLT_POST_OPERATION_FLAGS Flags) 154 | { 155 | UNREFERENCED_PARAMETER(Data); 156 | UNREFERENCED_PARAMETER(FltObjects); 157 | UNREFERENCED_PARAMETER(CompletionContext); 158 | UNREFERENCED_PARAMETER(Flags); 159 | 160 | return FLT_POSTOP_FINISHED_PROCESSING; 161 | } 162 | 163 | 164 | FLT_PREOP_CALLBACK_STATUS 165 | MinifilterDriverPreWriteOperation( 166 | _Inout_ PFLT_CALLBACK_DATA Data, 167 | _In_ PCFLT_RELATED_OBJECTS FltObjects, 168 | _Flt_CompletionContext_Outptr_ PVOID* CompletionContext) 169 | { 170 | auto Status = FLT_PREOP_SUCCESS_NO_CALLBACK; 171 | 172 | UNREFERENCED_PARAMETER(FltObjects); 173 | UNREFERENCED_PARAMETER(CompletionContext); 174 | 175 | if ( Data->RequestorMode == KernelMode ) 176 | return FLT_PREOP_SUCCESS_NO_CALLBACK; 177 | 178 | return Status; 179 | } 180 | -------------------------------------------------------------------------------- /MiniFilter/MinifilterDriver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | 7 | #define DEVICE_NAME "CHANGEME" 8 | #define DRIVER_CONTEXT_TAG 'CHGM' 9 | #define DRIVER_TAG DRIVER_CONTEXT_TAG 10 | 11 | 12 | EXTERN_C_START 13 | 14 | NTKERNELAPI 15 | NTSTATUS 16 | ZwQueryInformationProcess( 17 | _In_ HANDLE ProcessHandle, 18 | _In_ PROCESSINFOCLASS ProcessInformationClass, 19 | _Out_ PVOID ProcessInformation, 20 | _In_ ULONG ProcessInformationLength, 21 | _Out_opt_ PULONG ReturnLength); 22 | 23 | 24 | NTKERNELAPI 25 | NTSTATUS 26 | NTAPI 27 | MmCopyVirtualMemory( 28 | PEPROCESS SourceProcess, 29 | PVOID SourceAddress, 30 | PEPROCESS TargetProcess, 31 | PVOID TargetAddress, 32 | SIZE_T BufferSize, 33 | KPROCESSOR_MODE PreviousMode, 34 | PSIZE_T ReturnSize); 35 | 36 | 37 | NTKERNELAPI 38 | NTSTATUS 39 | PsLookupProcessByProcessId(_In_ HANDLE ProcessId, _Outptr_ PEPROCESS* Process); 40 | 41 | 42 | EXTERN_C_END 43 | -------------------------------------------------------------------------------- /MiniFilter/MinifilterDriver.inf: -------------------------------------------------------------------------------- 1 | ;;; 2 | ;;; MinifilterDriver 3 | ;;; 4 | 5 | [Version] 6 | Signature = "$Windows NT$" 7 | Class = "ActivityMonitor" 8 | ClassGuid = {b86dff51-a31e-4bac-b3cf-e8cfe75c9fc2} 9 | Provider = %ManufacturerName% 10 | DriverVer = 11 | CatalogFile = MinifilterDriver.cat 12 | 13 | [DestinationDirs] 14 | DefaultDestDir = 12 15 | MiniFilter.DriverFiles = 12 ;%windir%\system32\drivers 16 | 17 | ;; 18 | ;; Default install sections 19 | ;; 20 | 21 | [DefaultInstall] 22 | OptionDesc = %ServiceDescription% 23 | CopyFiles = MiniFilter.DriverFiles 24 | 25 | [DefaultInstall.Services] 26 | AddService = %ServiceName%,,MiniFilter.Service 27 | 28 | ;; 29 | ;; Default uninstall sections 30 | ;; 31 | 32 | [DefaultUninstall] 33 | DelFiles = MiniFilter.DriverFiles 34 | 35 | [DefaultUninstall.Services] 36 | DelService = %ServiceName%,0x200 ;Ensure service is stopped before deleting 37 | 38 | ; 39 | ; Services Section 40 | ; 41 | 42 | [MiniFilter.Service] 43 | DisplayName = %ServiceName% 44 | Description = %ServiceDescription% 45 | ServiceBinary = %12%\%DriverName%.sys ;%windir%\system32\drivers\ 46 | Dependencies = "FltMgr" 47 | ServiceType = 2 ;SERVICE_FILE_SYSTEM_DRIVER 48 | StartType = 3 ;SERVICE_DEMAND_START 49 | ErrorControl = 1 ;SERVICE_ERROR_NORMAL 50 | ; TODO - Change the Load Order Group value 51 | ; LoadOrderGroup = "FSFilter Activity Monitor" 52 | LoadOrderGroup = "FSFilter Activity Monitor" 53 | AddReg = MiniFilter.AddRegistry 54 | 55 | ; 56 | ; Registry Modifications 57 | ; 58 | 59 | [MiniFilter.AddRegistry] 60 | HKR,,"DebugFlags",0x00010001 ,0x0 61 | HKR,,"SupportedFeatures",0x00010001,0x3 62 | HKR,"Instances","DefaultInstance",0x00000000,%DefaultInstance% 63 | HKR,"Instances\"%Instance1.Name%,"Altitude",0x00000000,%Instance1.Altitude% 64 | HKR,"Instances\"%Instance1.Name%,"Flags",0x00010001,%Instance1.Flags% 65 | 66 | ; 67 | ; Copy Files 68 | ; 69 | 70 | [MiniFilter.DriverFiles] 71 | %DriverName%.sys 72 | 73 | [SourceDisksFiles] 74 | MinifilterDriver.sys = 1,, 75 | 76 | [SourceDisksNames] 77 | 1 = %DiskId1%,,, 78 | 79 | ;; 80 | ;; String Section 81 | ;; 82 | 83 | [Strings] 84 | ManufacturerName = "BlahCat Corp." 85 | ServiceDescription = "MinifilterDriver Mini-Filter Driver" 86 | ServiceName = "MinifilterDriver" 87 | DriverName = "MinifilterDriver" 88 | DiskId1 = "MinifilterDriver Device Installation Disk" 89 | 90 | ;Instances specific information. 91 | DefaultInstance = "MinifilterDriver Instance" 92 | Instance1.Name = "MinifilterDriver Instance" 93 | Instance1.Altitude = "360010" 94 | Instance1.Flags = 0x0 ; Allow all attachments 95 | -------------------------------------------------------------------------------- /MiniFilter/MinifilterDriver.rc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #define VER_FILETYPE VFT_DRV 6 | #define VER_FILESUBTYPE VFT2_DRV_SYSTEM 7 | #define VER_FILEDESCRIPTION_STR "MinifilterDriver Filter Driver" 8 | #define VER_INTERNALNAME_STR "MinifilterDriver.sys" 9 | 10 | #include "common.ver" 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Start with 3 | 4 | ```bash 5 | gh repo create MyDriver --template hugsy/modern-cpp-windows-driver-template # --private 6 | ``` 7 | 8 | Then, grep & change the pattern `CHANGEME` with your project name. 9 | -------------------------------------------------------------------------------- /Scripts/SignDriver.ps1: -------------------------------------------------------------------------------- 1 | param ( 2 | [string]$DriverPath, 3 | [string]$CertificateStore, 4 | [string]$CertCommonName 5 | ) 6 | 7 | $cert = New-SelfSignedCertificate -Type CodeSigningCert -KeyUsage DigitalSignature -HashAlgorithm SHA256 -Subject "$CertCommonName" -CertStoreLocation "cert:\CurrentUser\My" 8 | Set-AuthenticodeSignature -FilePath $DriverPath $cert 9 | 10 | $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", "CurrentUser") 11 | $store.Open("ReadWrite") 12 | $certs = $store.Certificates | Where-Object { $_.Subject -like "*CN=${CertCommonName}*" } 13 | foreach ($cert in $certs) { 14 | $store.Remove($cert); 15 | } 16 | $store.Close() 17 | -------------------------------------------------------------------------------- /cmake/FindWdk.cmake: -------------------------------------------------------------------------------- 1 | # Redistribution and use is allowed under the OSI-approved 3-clause BSD license. 2 | # Copyright (c) 2018 Sergey Podobry (sergey.podobry at gmail.com). All rights reserved. 3 | 4 | # .rst: 5 | # FindWDK 6 | # ---------- 7 | # 8 | # This module searches for the installed Windows Development Kit (WDK) and 9 | # exposes commands for creating kernel drivers and kernel libraries. 10 | # 11 | # Output variables: 12 | # - `WDK_FOUND` -- if false, do not try to use WDK 13 | # - `WDK_ROOT` -- where WDK is installed 14 | # - `WDK_VERSION` -- the version of the selected WDK 15 | # - `WDK_WINVER` -- the WINVER used for kernel drivers and libraries 16 | # (default value is `0x0601` and can be changed per target or globally) 17 | # 18 | # Example usage: 19 | # ``` 20 | # find_package(WDK REQUIRED) 21 | # 22 | # wdk_add_library(KmdfCppLib STATIC KMDF 1.15 23 | # KmdfCppLib.h 24 | # KmdfCppLib.cpp 25 | # ) 26 | # target_include_directories(KmdfCppLib INTERFACE .) 27 | # 28 | # wdk_add_driver(KmdfCppDriver KMDF 1.15 29 | # Main.cpp 30 | # ) 31 | # target_link_libraries(KmdfCppDriver KmdfCppLib) 32 | # ``` 33 | cmake_minimum_required(VERSION 3.20) 34 | 35 | if(DEFINED ENV{WDKContentRoot}) 36 | file(GLOB WDK_NTDDK_FILES 37 | "$ENV{WDKContentRoot}/Include/*/km/ntddk.h" 38 | ) 39 | else() 40 | file(GLOB WDK_NTDDK_FILES 41 | "C:/Program Files*/Windows Kits/10/Include/*/km/ntddk.h" 42 | ) 43 | endif() 44 | 45 | if(WDK_NTDDK_FILES) 46 | list(GET WDK_NTDDK_FILES -1 WDK_LATEST_NTDDK_FILE) 47 | endif() 48 | 49 | include(FindPackageHandleStandardArgs) 50 | find_package_handle_standard_args(WDK REQUIRED_VARS WDK_LATEST_NTDDK_FILE) 51 | 52 | if(NOT WDK_LATEST_NTDDK_FILE) 53 | return() 54 | endif() 55 | 56 | get_filename_component(WDK_ROOT ${WDK_LATEST_NTDDK_FILE} DIRECTORY) 57 | get_filename_component(WDK_ROOT ${WDK_ROOT} DIRECTORY) 58 | get_filename_component(WDK_VERSION ${WDK_ROOT} NAME) 59 | get_filename_component(WDK_ROOT ${WDK_ROOT} DIRECTORY) 60 | get_filename_component(WDK_ROOT ${WDK_ROOT} DIRECTORY) 61 | 62 | message(STATUS "WDK_ROOT: " ${WDK_ROOT}) 63 | message(STATUS "WDK_VERSION: " ${WDK_VERSION}) 64 | 65 | set(WDK_WINVER "0x0A00" CACHE STRING "Default WINVER for WDK targets") 66 | 67 | set(WDK_ADDITIONAL_FLAGS_FILE "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/wdkflags.h") 68 | file(WRITE ${WDK_ADDITIONAL_FLAGS_FILE} "#pragma runtime_checks(\"suc\", off)") 69 | 70 | set(WDK_COMPILE_FLAGS 71 | "/Zp8" # set struct alignment 72 | "/GF" # enable string pooling 73 | "/GR-" # disable RTTI 74 | "/Gz" # __stdcall by default 75 | "/kernel" # create kernel mode binary 76 | "/FIwarning.h" # disable warnings in WDK headers 77 | "/FI${WDK_ADDITIONAL_FLAGS_FILE}" # include file to disable RTC 78 | ) 79 | 80 | set(WDK_COMPILE_DEFINITIONS "WINNT=1") 81 | set(WDK_COMPILE_DEFINITIONS_DEBUG "MSC_NOOPT;DEPRECATE_DDK_FUNCTIONS=1;DBG=1") 82 | 83 | if(CMAKE_GENERATOR_PLATFORM STREQUAL "win32") 84 | list(APPEND WDK_COMPILE_DEFINITIONS "_X86_=1;i386=1;STD_CALL") 85 | set(WDK_PLATFORM "x86") 86 | elseif(CMAKE_GENERATOR_PLATFORM STREQUAL "x64") 87 | list(APPEND WDK_COMPILE_DEFINITIONS "_WIN64;_AMD64_;AMD64") 88 | set(WDK_PLATFORM "x64") 89 | elseif(CMAKE_GENERATOR_PLATFORM STREQUAL "arm64") 90 | list(APPEND WDK_COMPILE_DEFINITIONS "_WIN64;_ARM64_;ARM64") 91 | set(WDK_COMPILE_FLAGS ${WDK_COMPILE_FLAGS} /GS-) # TODO: fixes missing symbol __security_pop_cookie, fix 92 | set(WDK_PLATFORM "arm64") 93 | else() 94 | message(FATAL_ERROR "Unsupported architecture") 95 | endif() 96 | 97 | string(CONCAT WDK_LINK_FLAGS 98 | "/MANIFEST:NO " # 99 | "/DRIVER " # 100 | "/OPT:REF " # 101 | "/INCREMENTAL:NO " # 102 | "/OPT:ICF " # 103 | "/SUBSYSTEM:NATIVE " # 104 | "/MERGE:_TEXT=.text;_PAGE=PAGE " # 105 | "/NODEFAULTLIB " # do not link default CRT 106 | "/SECTION:INIT,d " # 107 | "/VERSION:10.0 " # 108 | ) 109 | 110 | # Generate imported targets for WDK lib files 111 | file(GLOB WDK_LIBRARIES "${WDK_ROOT}/Lib/${WDK_VERSION}/km/${WDK_PLATFORM}/*.lib") 112 | 113 | foreach(LIBRARY IN LISTS WDK_LIBRARIES) 114 | get_filename_component(LIBRARY_NAME ${LIBRARY} NAME_WE) 115 | string(TOUPPER ${LIBRARY_NAME} LIBRARY_NAME) 116 | add_library(WDK::${LIBRARY_NAME} INTERFACE IMPORTED) 117 | set_property(TARGET WDK::${LIBRARY_NAME} PROPERTY INTERFACE_LINK_LIBRARIES ${LIBRARY}) 118 | endforeach(LIBRARY) 119 | 120 | unset(WDK_LIBRARIES) 121 | 122 | function(wdk_add_driver _target) 123 | cmake_parse_arguments(WDK "" "KMDF;WINVER" "" ${ARGN}) 124 | 125 | add_executable(${_target} ${WDK_UNPARSED_ARGUMENTS}) 126 | 127 | set_target_properties(${_target} PROPERTIES SUFFIX ".sys") 128 | set_target_properties(${_target} PROPERTIES COMPILE_OPTIONS "${WDK_COMPILE_FLAGS}") 129 | set_target_properties(${_target} PROPERTIES COMPILE_DEFINITIONS 130 | "${WDK_COMPILE_DEFINITIONS};$<$:${WDK_COMPILE_DEFINITIONS_DEBUG}>;_WIN32_WINNT=${WDK_WINVER}" 131 | ) 132 | set_target_properties(${_target} PROPERTIES LINK_FLAGS "${WDK_LINK_FLAGS}") 133 | 134 | target_include_directories(${_target} SYSTEM PRIVATE 135 | "${WDK_ROOT}/Include/${WDK_VERSION}/shared" 136 | "${WDK_ROOT}/Include/${WDK_VERSION}/km" 137 | "${WDK_ROOT}/Include/${WDK_VERSION}/km/crt" 138 | ) 139 | 140 | target_link_libraries(${_target} 141 | WDK::NTOSKRNL 142 | WDK::HAL 143 | WDK::WMILIB 144 | 145 | $<$:WDK::BUFFEROVERFLOWFASTFAILK> 146 | $<$:WDK::BUFFEROVERFLOWK> 147 | $<$:WDK::BUFFEROVERFLOWK WDK::MEMCMP> 148 | ) 149 | 150 | if(DEFINED WDK_KMDF) 151 | target_include_directories(${_target} SYSTEM PRIVATE "${WDK_ROOT}/Include/wdf/kmdf/${WDK_KMDF}") 152 | target_link_libraries(${_target} 153 | "${WDK_ROOT}/Lib/wdf/kmdf/${WDK_PLATFORM}/${WDK_KMDF}/WdfDriverEntry.lib" 154 | "${WDK_ROOT}/Lib/wdf/kmdf/${WDK_PLATFORM}/${WDK_KMDF}/WdfLdr.lib" 155 | ) 156 | 157 | if(CMAKE_SIZEOF_VOID_P EQUAL 4) 158 | set_property(TARGET ${_target} APPEND_STRING PROPERTY LINK_FLAGS "/ENTRY:FxDriverEntry@8") 159 | elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) 160 | set_property(TARGET ${_target} APPEND_STRING PROPERTY LINK_FLAGS "/ENTRY:FxDriverEntry") 161 | endif() 162 | else() 163 | if(CMAKE_SIZEOF_VOID_P EQUAL 4) 164 | set_property(TARGET ${_target} APPEND_STRING PROPERTY LINK_FLAGS "/ENTRY:GsDriverEntry@8") 165 | elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) 166 | set_property(TARGET ${_target} APPEND_STRING PROPERTY LINK_FLAGS "/ENTRY:GsDriverEntry") 167 | endif() 168 | endif() 169 | endfunction() 170 | 171 | function(wdk_add_library _target) 172 | cmake_parse_arguments(WDK "" "KMDF;WINVER" "" ${ARGN}) 173 | 174 | add_library(${_target} ${WDK_UNPARSED_ARGUMENTS}) 175 | 176 | set_target_properties(${_target} PROPERTIES COMPILE_OPTIONS "${WDK_COMPILE_FLAGS}") 177 | set_target_properties(${_target} PROPERTIES COMPILE_DEFINITIONS 178 | "${WDK_COMPILE_DEFINITIONS};$<$:${WDK_COMPILE_DEFINITIONS_DEBUG};>_WIN32_WINNT=${WDK_WINVER}" 179 | ) 180 | 181 | target_include_directories(${_target} SYSTEM PRIVATE 182 | "${WDK_ROOT}/Include/${WDK_VERSION}/shared" 183 | "${WDK_ROOT}/Include/${WDK_VERSION}/km" 184 | "${WDK_ROOT}/Include/${WDK_VERSION}/km/crt" 185 | ) 186 | 187 | if(DEFINED WDK_KMDF) 188 | target_include_directories(${_target} SYSTEM PRIVATE "${WDK_ROOT}/Include/wdf/kmdf/${WDK_KMDF}") 189 | endif() 190 | endfunction() 191 | --------------------------------------------------------------------------------