From 2f7960dd039d9362b8ee516b93a0bfbe7ba36228 Mon Sep 17 00:00:00 2001 From: Violet Hansen Date: Wed, 16 Oct 2024 19:35:07 +0300 Subject: [PATCH 1/2] Applied many best practices in the code Applied many best practices in the code --- Harden-Windows-Security Module/.editorconfig | 9 +- README.md | 2 +- WDACConfig/.editorconfig | 68 +++++++- WDACConfig/Utilities/Hashes.csv | 1 - .../ArgumentCompleterAttribute.cs | 86 ++------- .../C#/ArgumentCompleters/BasePolicyNamez.cs | 7 +- .../C#/ArgumentCompleters/RuleOptionsx.cs | 81 --------- .../Shared Logics/AllCertificatesGrabber.cs | 4 +- .../C#/Shared Logics/CertCNz.cs | 5 +- .../C#/Shared Logics/CertificateHelper.cs | 4 +- .../CheckPolicyDeploymentStatus.cs | 4 +- .../C#/Shared Logics/CiToolHelper.cs | 10 +- .../C#/Shared Logics/ConfigureISGServices.cs | 25 +++ .../C#/Shared Logics/Crypt32CertCN.cs | 2 +- .../C#/Shared Logics/DeviceGuardInfo.cs | 4 +- .../C#/Shared Logics/DirectorySelector.cs | 5 +- .../C#/Shared Logics/DriveLetterMapper.cs | 2 +- .../C#/Shared Logics/EventLogUtility.cs | 8 +- .../FileDirectoryPathComparer.cs | 2 +- .../C#/Shared Logics/FileSystemPicker.cs | 3 +- .../C#/Shared Logics/GetExtendedFileAttrib.cs | 2 +- .../C#/Shared Logics/GetFilesFast.cs | 2 +- .../C#/Shared Logics/Initializer.cs | 7 +- .../Logging/LoggerInitializer.cs | 2 +- .../Main Cmdlets/AssertWDACConfigIntegrity.cs | 35 ++-- .../Main Cmdlets/BasePolicyCreator.cs | 55 +++--- .../Main Cmdlets/GetCIPolicySetting.cs | 4 +- .../Main Cmdlets/SetCiRuleOptions.cs | 40 ++++- .../Main Cmdlets/TestCiPolicy.cs | 2 +- .../Main Cmdlets/UserConfiguration.cs | 20 +-- .../C#/Shared Logics/MeowOpener.cs | 30 +++- .../Shared Logics/MoveUserModeToKernelMode.cs | 8 +- .../PolicyFileSigningStatusDetection.cs | 2 +- .../C#/Shared Logics/PolicyMerger.cs | 2 +- .../C#/Shared Logics/PolicyToCIPConverter.cs | 2 +- .../C#/Shared Logics/PowerShellExecutor.cs | 10 +- .../RemoveSupplementalSigners.cs | 2 +- .../C#/Shared Logics/ScanLevelz.cs | 2 +- .../C#/Shared Logics/SnapBackGuarantee.cs | 2 +- .../C#/Shared Logics/SupplementalForSelf.cs | 2 +- .../AuthenticodePageHashes.cs | 2 +- .../CertificateDetailsCreator.cs | 2 +- .../CertificateSignerCreator.cs | 2 +- .../Types And Definitions/ChainElement.cs | 2 +- .../Types And Definitions/ChainPackage.cs | 2 +- .../FileBasedInfoPackage.cs | 2 +- .../FilePublisherSignerCreator.cs | 2 +- .../Types And Definitions/HashCreator.cs | 2 +- .../Types And Definitions/OpusSigner.cs | 2 +- .../Types And Definitions/PolicyHashObj.cs | 2 +- .../PublisherSignerCreator.cs | 2 +- .../Types And Definitions/Signer.cs | 2 +- .../Types And Definitions/SimulationInput.cs | 2 +- .../Types And Definitions/SimulationOutput.cs | 2 +- .../Types And Definitions/WinTrust.cs | 4 +- .../C#/Shared Logics/Variables/CILogIntel.cs | 6 +- .../C#/Shared Logics/Variables/GlobalVars.cs | 2 +- .../C#/Shared Logics/VersionIncrementer.cs | 2 +- .../WDAC Simulation/GetCertificateDetails.cs | 4 +- .../WDAC Simulation/GetFileRuleOutput.cs | 18 +- .../WDAC Simulation/GetSignerInfo.cs | 6 +- .../Shared Logics/WldpQuerySecurityPolicy.cs | 2 +- .../XMLOps/CloseEmptyXmlNodesSemantic.cs | 6 +- .../Shared Logics/XMLOps/SetCiPolicyInfo.cs | 2 +- .../XMLOps/SignerAndHashBuilder.cs | 163 +++++++++--------- .../Shared Logics/XMLOps/UpdateHvciOptions.cs | 2 +- .../C#/Shared Logics/XmlFilePathExtractor.cs | 2 +- .../Core/Build-WDACCertificate.psm1 | 10 +- .../Core/Edit-SignedWDACConfig.psm1 | 5 +- .../Core/Edit-WDACConfig.psm1 | 4 +- .../Core/New-WDACConfig.psm1 | 4 +- .../WDACConfig Module Files/WDACConfig.psd1 | 2 +- .../Compare-SignerAndCertificate.psm1 | 3 + WDACConfig/WinUI3/.editorconfig | 68 +++++++- WDACConfig/WinUI3/App.xaml.cs | 2 + WDACConfig/WinUI3/AppControl Manager.csproj | 11 +- .../WinUI3/AppControl Manager.csproj.user | 3 +- WDACConfig/WinUI3/Package.appxmanifest | 2 +- .../Pages/ConfigurePolicyRuleOptions.xaml.cs | 5 +- WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs | 4 +- .../Shared Logics/AllCertificatesGrabber.cs | 4 +- WDACConfig/WinUI3/Shared Logics/CertCNz.cs | 5 +- .../WinUI3/Shared Logics/CertificateHelper.cs | 4 +- .../CheckPolicyDeploymentStatus.cs | 4 +- .../WinUI3/Shared Logics/CiToolHelper.cs | 10 +- .../Shared Logics/ConfigureISGServices.cs | 25 +++ .../WinUI3/Shared Logics/Crypt32CertCN.cs | 2 +- .../WinUI3/Shared Logics/DeviceGuardInfo.cs | 4 +- .../WinUI3/Shared Logics/DirectorySelector.cs | 5 +- .../WinUI3/Shared Logics/DriveLetterMapper.cs | 2 +- .../WinUI3/Shared Logics/EventLogUtility.cs | 8 +- .../FileDirectoryPathComparer.cs | 2 +- .../WinUI3/Shared Logics/FileSystemPicker.cs | 3 +- .../Shared Logics/GetExtendedFileAttrib.cs | 2 +- .../WinUI3/Shared Logics/GetFilesFast.cs | 2 +- .../WinUI3/Shared Logics/Initializer.cs | 7 +- .../Logging/LoggerInitializer.cs | 2 +- .../Main Cmdlets/AssertWDACConfigIntegrity.cs | 35 ++-- .../Main Cmdlets/BasePolicyCreator.cs | 55 +++--- .../Main Cmdlets/GetCIPolicySetting.cs | 4 +- .../Main Cmdlets/SetCiRuleOptions.cs | 40 ++++- .../Main Cmdlets/TestCiPolicy.cs | 2 +- .../Main Cmdlets/UserConfiguration.cs | 20 +-- WDACConfig/WinUI3/Shared Logics/MeowOpener.cs | 30 +++- .../Shared Logics/MoveUserModeToKernelMode.cs | 8 +- .../PolicyFileSigningStatusDetection.cs | 2 +- .../WinUI3/Shared Logics/PolicyMerger.cs | 2 +- .../Shared Logics/PolicyToCIPConverter.cs | 2 +- .../Shared Logics/PowerShellExecutor.cs | 10 +- .../RemoveSupplementalSigners.cs | 2 +- WDACConfig/WinUI3/Shared Logics/ScanLevelz.cs | 2 +- .../WinUI3/Shared Logics/SnapBackGuarantee.cs | 2 +- .../Shared Logics/SupplementalForSelf.cs | 2 +- .../AuthenticodePageHashes.cs | 2 +- .../CertificateDetailsCreator.cs | 2 +- .../CertificateSignerCreator.cs | 2 +- .../Types And Definitions/ChainElement.cs | 2 +- .../Types And Definitions/ChainPackage.cs | 2 +- .../FileBasedInfoPackage.cs | 2 +- .../FilePublisherSignerCreator.cs | 2 +- .../Types And Definitions/HashCreator.cs | 2 +- .../Types And Definitions/OpusSigner.cs | 2 +- .../Types And Definitions/PolicyHashObj.cs | 2 +- .../PublisherSignerCreator.cs | 2 +- .../Types And Definitions/Signer.cs | 2 +- .../Types And Definitions/SimulationInput.cs | 2 +- .../Types And Definitions/SimulationOutput.cs | 2 +- .../Types And Definitions/WinTrust.cs | 4 +- .../Shared Logics/Variables/CILogIntel.cs | 6 +- .../Shared Logics/Variables/GlobalVars.cs | 2 +- .../Shared Logics/VersionIncrementer.cs | 2 +- .../WDAC Simulation/GetCertificateDetails.cs | 4 +- .../WDAC Simulation/GetFileRuleOutput.cs | 18 +- .../WDAC Simulation/GetSignerInfo.cs | 6 +- .../Shared Logics/WldpQuerySecurityPolicy.cs | 2 +- .../XMLOps/CloseEmptyXmlNodesSemantic.cs | 6 +- .../Shared Logics/XMLOps/SetCiPolicyInfo.cs | 2 +- .../XMLOps/SignerAndHashBuilder.cs | 163 +++++++++--------- .../Shared Logics/XMLOps/UpdateHvciOptions.cs | 2 +- .../Shared Logics/XmlFilePathExtractor.cs | 2 +- WDACConfig/version.txt | 2 +- 141 files changed, 800 insertions(+), 691 deletions(-) delete mode 100644 WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/RuleOptionsx.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/ConfigureISGServices.cs create mode 100644 WDACConfig/WinUI3/Shared Logics/ConfigureISGServices.cs diff --git a/Harden-Windows-Security Module/.editorconfig b/Harden-Windows-Security Module/.editorconfig index 782504b03..487a9de7e 100644 --- a/Harden-Windows-Security Module/.editorconfig +++ b/Harden-Windows-Security Module/.editorconfig @@ -285,12 +285,6 @@ dotnet_diagnostic.IDE0004.severity = error # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error -# IDE0060: Remove unused parameter -dotnet_diagnostic.IDE0060.severity = error - -# IDE0044: Add readonly modifier -dotnet_diagnostic.IDE0044.severity = error - # IDE0063: Use simple 'using' statement dotnet_diagnostic.IDE0063.severity = error @@ -344,3 +338,6 @@ dotnet_diagnostic.CA1839.severity = error # CA2265: Do not compare Span to 'null' or 'default' dotnet_diagnostic.CA2265.severity = error + +# CA1507: Use nameof to express symbol names +dotnet_diagnostic.CA1507.severity = error diff --git a/README.md b/README.md index 107bb9a88..0c0a05e10 100644 --- a/README.md +++ b/README.md @@ -1547,7 +1547,7 @@ This repository uses the simplest possible, yet effective, methods that make it > [!TIP]\ > All files in this repository, including packages like MSIX files attached to releases, are zipped and automatically submitted to VirusTotal for scanning through a [GitHub Action](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/VirusTotal.yml). Find the history of the uploaded files in [my Virus Total profile](https://www.virustotal.com/gui/user/SpyNetGirl). -[![PSScriptAnalyzer](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/powershell.yml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/powershell.yml) [![Repository And Package Scan on Virus Total](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/VirusTotal.yml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/VirusTotal.yml) [![CodeQL Advanced](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/codeql.yml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/codeql.yml) [![Sync to Azure DevOps](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/Sync%20to%20Azure%20DevOps.yaml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/Sync%20to%20Azure%20DevOps.yaml) +[![PSScriptAnalyzer](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/powershell.yml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/powershell.yml) [![Repository And Package Scan on Virus Total](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/VirusTotal.yml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/VirusTotal.yml) [![CodeQL Advanced](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/codeql.yml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/codeql.yml) [![Sync to Azure DevOps](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/Sync%20to%20Azure%20DevOps.yaml/badge.svg)](https://github.com/HotCakeX/Harden-Windows-Security/actions/workflows/Sync%20to%20Azure%20DevOps.yaml)

💡 (back to top)

diff --git a/WDACConfig/.editorconfig b/WDACConfig/.editorconfig index 3ab9b4c35..487a9de7e 100644 --- a/WDACConfig/.editorconfig +++ b/WDACConfig/.editorconfig @@ -31,7 +31,7 @@ dotnet_diagnostic.CA1309.severity = error dotnet_diagnostic.CA1311.severity = error # CA1416: Validate platform compatibility -dotnet_diagnostic.CA1416.severity = error +dotnet_diagnostic.CA1416.severity = silent # CA5384: Do Not Use Digital Signature Algorithm (DSA) dotnet_diagnostic.CA5384.severity = error @@ -275,3 +275,69 @@ dotnet_diagnostic.CA2101.severity = error # IL2026: Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code dotnet_diagnostic.IL2026.severity = error + +# IDE0305: Simplify collection initialization +dotnet_diagnostic.IDE0305.severity = error + +# IDE0004: Remove Unnecessary Cast +dotnet_diagnostic.IDE0004.severity = error + +# IDE0017: Simplify object initialization +dotnet_diagnostic.IDE0017.severity = error + +# IDE0063: Use simple 'using' statement +dotnet_diagnostic.IDE0063.severity = error + +# CA1001: Types that own disposable fields should be disposable +dotnet_diagnostic.CA1001.severity = error + +# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +dotnet_diagnostic.CA1831.severity = error + +# CA5382: Use Secure Cookies In ASP.NET Core +dotnet_diagnostic.CA5382.severity = error + +# CA1063: Implement IDisposable Correctly +dotnet_diagnostic.CA1063.severity = error + +# CA1852: Seal internal types +dotnet_diagnostic.CA1852.severity = error + +# CA2011: Avoid infinite recursion +dotnet_diagnostic.CA2011.severity = error + +# CA2015: Do not define finalizers for types derived from MemoryManager +dotnet_diagnostic.CA2015.severity = error + +# CA2017: Parameter count mismatch +dotnet_diagnostic.CA2017.severity = error + +# CA5397: Do not use deprecated SslProtocols values +dotnet_diagnostic.CA5397.severity = error + +# CA5394: Do not use insecure randomness +dotnet_diagnostic.CA5394.severity = error + +# CA2207: Initialize value type static fields inline +dotnet_diagnostic.CA2207.severity = error + +# CA2219: Do not raise exceptions in finally clauses +dotnet_diagnostic.CA2219.severity = error + +# CA2259: 'ThreadStatic' only affects static fields +dotnet_diagnostic.CA2259.severity = error + +# CA5371: Use XmlReader for 'XmlSchema.Read()' +dotnet_diagnostic.CA5371.severity = error + +# CA5364: Do Not Use Deprecated Security Protocols +dotnet_diagnostic.CA5364.severity = error + +# CA1839: Use 'Environment.ProcessPath' +dotnet_diagnostic.CA1839.severity = error + +# CA2265: Do not compare Span to 'null' or 'default' +dotnet_diagnostic.CA2265.severity = error + +# CA1507: Use nameof to express symbol names +dotnet_diagnostic.CA1507.severity = error diff --git a/WDACConfig/Utilities/Hashes.csv b/WDACConfig/Utilities/Hashes.csv index f66e2efeb..05d78e30a 100644 --- a/WDACConfig/Utilities/Hashes.csv +++ b/WDACConfig/Utilities/Hashes.csv @@ -53,7 +53,6 @@ "XMLOps\Remove-UnreferencedFileRuleRefs.psm1","Remove-UnreferencedFileRuleRefs.psm1","796FBE2B74EE4BDF8C9C7B3960DE85D67D1C5D407739EC8FC604A697C96938B1CC3B66010262FE5B48B2B0648CA52D7FD8A5E21166EF41B01A8D1963A03F0162", "C#\ArgumentCompleters\ArgumentCompleterAttribute.cs","ArgumentCompleterAttribute.cs","B88EC477DC0EA32D701F86E6C1F0A11236F8D644133E969653C8E1A1A0E6BBEF88EAD2E35AE455FABB74203A2C27EFAAEB614F24D2119FA9BC1045EC6A79CC9E", "C#\ArgumentCompleters\BasePolicyNamez.cs","BasePolicyNamez.cs","732044E59CA6287F9F3B3CBF4278C71E1BE4EA910116C18C09419507682A9BD3F42AB388E22B6428FECA3CB4F247826EE9802DBDEADA510349B4896DAD103DC8", -"C#\ArgumentCompleters\RuleOptionsx.cs","RuleOptionsx.cs","E2C200DC83FB7791ADD97848FC792FBC45E369B3AC54D8DACD63386A57F9D7050482E7FD7BA4F00C35B9ED9B44A12E8CA8E3B56183A11B0009029AE09D2E0E6C", "C#\Shared Logics\AllCertificatesGrabber.cs","AllCertificatesGrabber.cs","F55C696401877DBF35F0753C31BB47937CC174945D25FC1A91C617C3CA9317C57110EE8BB8E7C4F0F9B76A27F50F0235D7B0E5715912648AB9EF8AED24B71237", "C#\Shared Logics\CertCNz.cs","CertCNz.cs","8769157D63762A0AED599C09F78AEB3D25AFC382259809A060A3AD174EDACF7FAF93A2F0CB2D88DF2FC7ADEEBEB93556E78406BCB0424B895CF227A90D89CF53", "C#\Shared Logics\CertificateHelper.cs","CertificateHelper.cs","3FD96DC69FFFD1CDF5961F62F486E9120853E3160B3680F8FAC683A0DD1634A96FD9A20EBBEC4323406CD755D5470A5C66E350D6066F40BCC23B0EC41C92F48E", diff --git a/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/ArgumentCompleterAttribute.cs b/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/ArgumentCompleterAttribute.cs index 812c0ddf6..e5cf116c1 100644 --- a/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/ArgumentCompleterAttribute.cs +++ b/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/ArgumentCompleterAttribute.cs @@ -17,7 +17,7 @@ namespace WDACConfig.ArgCompleter /// /// Opens File picker GUI so that user can select any files /// - public class AnyFilePathsPicker : IArgumentCompleter + public sealed class AnyFilePathsPicker : IArgumentCompleter { // Method to complete the argument with file path selection public IEnumerable CompleteArgument( @@ -53,7 +53,7 @@ public IEnumerable CompleteArgument( // Attribute to use AnyFilePathsPicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class AnyFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class AnyFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with AnyFilePathsPicker public AnyFilePathsPickerAttribute() : base(typeof(AnyFilePathsPicker)) { } @@ -68,7 +68,7 @@ public IArgumentCompleter Create() /// /// Opens File picker GUI so that user can select a .xml file /// - public class XmlFilePathsPicker : IArgumentCompleter + public sealed class XmlFilePathsPicker : IArgumentCompleter { // Directory to initialize the file dialog private readonly string initialDirectory = WDACConfig.GlobalVars.UserConfigDir; @@ -114,7 +114,7 @@ public IEnumerable CompleteArgument( // Attribute to use XmlFilePathsPicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class XmlFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class XmlFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with XmlFilePathsPicker public XmlFilePathsPickerAttribute() : base(typeof(XmlFilePathsPicker)) { } @@ -129,7 +129,7 @@ public IArgumentCompleter Create() /// /// Opens Folder picker GUI so that user can select folders to be processed /// - public class FolderPicker : IArgumentCompleter + public sealed class FolderPicker : IArgumentCompleter { // Method to complete the argument with folder path selection public IEnumerable CompleteArgument( @@ -165,7 +165,7 @@ public IEnumerable CompleteArgument( // Attribute to use FolderPicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class FolderPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class FolderPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with FolderPicker public FolderPickerAttribute() : base(typeof(FolderPicker)) { } @@ -180,7 +180,7 @@ public IArgumentCompleter Create() /// /// Opens File picker GUI so that user can select multiple .xml files /// - public class XmlFileMultiSelectPicker : IArgumentCompleter + public sealed class XmlFileMultiSelectPicker : IArgumentCompleter { // Directory to initialize the file dialog private readonly string initialDirectory = WDACConfig.GlobalVars.UserConfigDir; @@ -228,7 +228,7 @@ public IEnumerable CompleteArgument( // Attribute to use XmlFileMultiSelectPicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class XmlFileMultiSelectPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class XmlFileMultiSelectPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with XmlFileMultiSelectPicker public XmlFileMultiSelectPickerAttribute() : base(typeof(XmlFileMultiSelectPicker)) { } @@ -243,7 +243,7 @@ public IArgumentCompleter Create() /// /// Opens File picker GUI so that user can select multiple files /// - public class MultipleAnyFilePathsPicker : IArgumentCompleter + public sealed class MultipleAnyFilePathsPicker : IArgumentCompleter { // Method to complete the argument with multiple file path selection public IEnumerable CompleteArgument( @@ -284,7 +284,7 @@ public IEnumerable CompleteArgument( // Attribute to use MultipleAnyFilePathsPicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class MultipleAnyFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class MultipleAnyFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with MultipleAnyFilePathsPicker public MultipleAnyFilePathsPickerAttribute() : base(typeof(MultipleAnyFilePathsPicker)) { } @@ -299,7 +299,7 @@ public IArgumentCompleter Create() /// /// Opens File picker GUI so that user can select an .exe file /// - public class ExeFilePathsPicker : IArgumentCompleter + public sealed class ExeFilePathsPicker : IArgumentCompleter { // Directory to initialize the file dialog private readonly string initialDirectory = WDACConfig.GlobalVars.UserConfigDir; @@ -345,7 +345,7 @@ public IEnumerable CompleteArgument( // Attribute to use ExeFilePathsPicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class ExeFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class ExeFilePathsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with ExeFilePathsPicker public ExeFilePathsPickerAttribute() : base(typeof(ExeFilePathsPicker)) { } @@ -360,7 +360,7 @@ public IArgumentCompleter Create() /// /// Opens File picker GUI so that user can select a single .cer file /// - public class SingleCerFilePicker : IArgumentCompleter + public sealed class SingleCerFilePicker : IArgumentCompleter { // Directory to initialize the file dialog private readonly string initialDirectory = WDACConfig.GlobalVars.UserConfigDir; @@ -408,7 +408,7 @@ public IEnumerable CompleteArgument( // Attribute to use SingleCerFilePicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class SingleCerFilePickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class SingleCerFilePickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with SingleCerFilePicker public SingleCerFilePickerAttribute() : base(typeof(SingleCerFilePicker)) { } @@ -423,7 +423,7 @@ public IArgumentCompleter Create() /// /// Opens File picker GUI so that user can select multiple .cer files /// - public class MultipleCerFilePicker : IArgumentCompleter + public sealed class MultipleCerFilePicker : IArgumentCompleter { // Directory to initialize the file dialog private readonly string initialDirectory = WDACConfig.GlobalVars.UserConfigDir; @@ -471,7 +471,7 @@ public IEnumerable CompleteArgument( // Attribute to use MultipleCerFilePicker as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class MultipleCerFilePickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class MultipleCerFilePickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with MultipleCerFilePicker public MultipleCerFilePickerAttribute() : base(typeof(MultipleCerFilePicker)) { } @@ -486,7 +486,7 @@ public IArgumentCompleter Create() /// /// Opens Folder picker GUI so that user can select a folder, and returns the selected path with quotes and a wildcard character at the end /// - public class FolderPickerWithWildcard : IArgumentCompleter + public sealed class FolderPickerWithWildcard : IArgumentCompleter { // Method to complete the argument with folder path selection, adding a wildcard character public IEnumerable CompleteArgument( @@ -522,7 +522,7 @@ public IEnumerable CompleteArgument( // Attribute to use FolderPickerWithWildcard as an argument completer [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class FolderPickerWithWildcardAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + public sealed class FolderPickerWithWildcardAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { // Constructor initializing the base class with FolderPickerWithWildcard public FolderPickerWithWildcardAttribute() : base(typeof(FolderPickerWithWildcard)) { } @@ -533,53 +533,5 @@ public IArgumentCompleter Create() return new FolderPickerWithWildcard(); } } - - /// - /// This argument completer suggests rule options that are not already selected on the command line by *any* other parameter - /// It currently doesn't make a distinction between the RulesToAdd/RulesToRemove parameters and other parameters. - /// - public class RuleOptionsPicker : IArgumentCompleter - { - // Method to complete the argument with rule options that are not already selected - public IEnumerable CompleteArgument( - string commandName, - string parameterName, - string wordToComplete, - CommandAst commandAst, - IDictionary fakeBoundParameters) - { - // Find all string constants in the AST - var existingValues = commandAst.FindAll( - ast => ast is StringConstantExpressionAst, - false - ).OfType() - .Select(ast => ast.Value) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - // Get all valid rule options - var validOptions = new WDACConfig.RuleOptionsx().GetValidValues(); - - // Filter out the options that are already selected - var suggestions = validOptions - .Where(option => !existingValues.Contains(option, StringComparer.OrdinalIgnoreCase)) - .Select(option => new CompletionResult($"'{option}'")); - - return suggestions; - } - } - - // Attribute to use RuleOptionsPicker as an argument completer - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] - public class RuleOptionsPickerAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory - { - // Constructor initializing the base class with RuleOptionsPicker - public RuleOptionsPickerAttribute() : base(typeof(RuleOptionsPicker)) { } - - // Create method to return an instance of RuleOptionsPicker - public IArgumentCompleter Create() - { - return new RuleOptionsPicker(); - } - } - + } diff --git a/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/BasePolicyNamez.cs b/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/BasePolicyNamez.cs index 02ea277aa..d8ce7cbab 100644 --- a/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/BasePolicyNamez.cs +++ b/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/BasePolicyNamez.cs @@ -1,11 +1,12 @@ using System; using System.Collections.Generic; +using System.Management.Automation; #nullable enable namespace WDACConfig { - public class BasePolicyNamez : IValidateSetValuesGenerator + public sealed class BasePolicyNamez : IValidateSetValuesGenerator { // Argument tab auto-completion and ValidateSet for Non-System Policy names public string[] GetValidValues() @@ -22,11 +23,11 @@ public string[] GetValidValues() BasePolicyNames.Add(policy.FriendlyName); } } - return BasePolicyNames.ToArray(); + return [.. BasePolicyNames]; } else { - return Array.Empty(); + return []; } } } diff --git a/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/RuleOptionsx.cs b/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/RuleOptionsx.cs deleted file mode 100644 index 82ef4db92..000000000 --- a/WDACConfig/WDACConfig Module Files/C#/ArgumentCompleters/RuleOptionsx.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml; - -#nullable enable - -namespace WDACConfig -{ - public interface IValidateSetValuesGenerator - { - string[] GetValidValues(); - } - - public class RuleOptionsx : IValidateSetValuesGenerator - { - - public string[] GetValidValues() - { - // Load the CI Schema content - XmlDocument schemaData = new(); - schemaData.Load(Path.Combine(WDACConfig.GlobalVars.CISchemaPath)); - - // Create a namespace manager to handle namespaces - XmlNamespaceManager nsManager = new(schemaData.NameTable); - nsManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); - - // Define the XPath query to fetch enumeration values - string xpathQuery = "//xs:simpleType[@name='OptionType']/xs:restriction/xs:enumeration/@value"; - - // Create a new HashSet to store the valid policy rule options - HashSet validOptions = new(StringComparer.OrdinalIgnoreCase); - - // Fetch enumeration values from the schema - XmlNodeList? optionNodes = schemaData.SelectNodes(xpathQuery, nsManager) ?? throw new InvalidOperationException("No valid options found in the Code Integrity Schema."); - - foreach (XmlNode node in optionNodes) - { - if (node.Value != null) - { - _ = validOptions.Add(node.Value); - } - } - - if (WDACConfig.GlobalVars.ModuleRootPath == null) - { - throw new InvalidOperationException("ModuleRootPath is null!"); - } - - // Construct the full path to PolicyRuleOptions.Json - string jsonFilePath = Path.Combine(WDACConfig.GlobalVars.ModuleRootPath, "Resources", "PolicyRuleOptions.Json"); - - // Read PolicyRuleOptions.Json - string jsonContent = File.ReadAllText(jsonFilePath); - - // Deserialize the JSON content - Dictionary? intel = System.Text.Json.JsonSerializer.Deserialize>(jsonContent) ?? throw new InvalidOperationException("The PolicyRuleOptions.Json file did not have valid JSON content to be deserialized."); - - // Perform validation - foreach (string key in intel.Values) - { - if (!validOptions.Contains(key)) - { - throw new InvalidOperationException($"Invalid Policy Rule Option detected that is not part of the Code Integrity Schema: {key}"); - } - } - - foreach (string option in validOptions) - { - if (!intel.Values.Contains(option, StringComparer.OrdinalIgnoreCase)) - { - // this should be a verbose or warning message - // throw new Exception($"Rule option '{option}' exists in the Code Integrity Schema but not being used by the module."); - } - } - - return intel.Values.ToArray(); - } - } -} diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/AllCertificatesGrabber.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/AllCertificatesGrabber.cs index cfead2ddf..50c2ccc58 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/AllCertificatesGrabber.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/AllCertificatesGrabber.cs @@ -14,12 +14,12 @@ namespace WDACConfig { // a class to throw a custom exception when the certificate has HashMismatch - public class ExceptionHashMismatchInCertificate(string message, string functionName) : Exception($"{functionName}: {message}") + public sealed class ExceptionHashMismatchInCertificate(string message, string functionName) : Exception($"{functionName}: {message}") { } // Represents a signed CMS and its certificate chain - public class AllFileSigners(SignedCms signerCertificate, X509Chain certificateChain) + public sealed class AllFileSigners(SignedCms signerCertificate, X509Chain certificateChain) { public SignedCms Signer { get; } = signerCertificate; public X509Chain Chain { get; } = certificateChain; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertCNz.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertCNz.cs index c2c11ec25..87b880e48 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertCNz.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertCNz.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; @@ -9,7 +8,7 @@ namespace WDACConfig { // Argument completer and ValidateSet for CertCNs - public class CertCNz : IValidateSetValuesGenerator + public sealed class CertCNz : IValidateSetValuesGenerator { public string[] GetValidValues() { @@ -41,7 +40,7 @@ public string[] GetValidValues() } // Explicitly call ToArray() from Enumerable - return output.ToArray(); + return [.. output]; } } } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertificateHelper.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertificateHelper.cs index e9ed356d1..0ed73727e 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertificateHelper.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CertificateHelper.cs @@ -8,11 +8,11 @@ namespace WDACConfig { // A class to throw a custom exception when the certificate collection cannot be obtained during WDAC Simulation - public class ExceptionFailedToGetCertificateCollection(string message, string functionName) : Exception($"{functionName}: {message}") + public sealed class ExceptionFailedToGetCertificateCollection(string message, string functionName) : Exception($"{functionName}: {message}") { } - public class CertificateHelper + public static class CertificateHelper { public static string GetTBSCertificate(X509Certificate2 cert) // Calculates the TBS value of a certificate diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CheckPolicyDeploymentStatus.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CheckPolicyDeploymentStatus.cs index 86ec34eb0..dee045d52 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CheckPolicyDeploymentStatus.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CheckPolicyDeploymentStatus.cs @@ -7,7 +7,7 @@ namespace WDACConfig { - public class CheckPolicyDeploymentStatus + public static class CheckPolicyDeploymentStatus { /// @@ -25,7 +25,7 @@ public static bool IsDeployed(string policyXMLFile) var policies = CiToolHelper.GetPolicies(false, true, true); // Loop through each policy and add its ID to the HashSet - foreach (WDACConfig.CiPolicyInfo item in policies) + foreach (CiPolicyInfo item in policies) { _ = currentPolicyIDs.Add(item.PolicyID!); } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CiToolHelper.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CiToolHelper.cs index 747ca721e..58db82ec5 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CiToolHelper.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/CiToolHelper.cs @@ -11,7 +11,7 @@ namespace WDACConfig { // Class to represent a policy with various attributes - public class CiPolicyInfo + public sealed class CiPolicyInfo { public string? PolicyID { get; set; } // Unique identifier for the policy public string? BasePolicyID { get; set; } // Identifier for the base policy @@ -71,7 +71,7 @@ public static Version Measure(string number) catch (Exception ex) { // Handle errors by printing an error message and returning a default version of 0.0.0.0 - WDACConfig.Logger.Write($"Error converting number to version: {ex.Message}"); + Logger.Write($"Error converting number to version: {ex.Message}"); return new Version(0, 0, 0, 0); } } @@ -205,7 +205,7 @@ public static void RemovePolicy(string policyId) if (process.ExitCode != 0) { - throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}"); + throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}. Output: {jsonOutput}"); } } @@ -256,7 +256,7 @@ public static void UpdatePolicy(string CipPath) if (process.ExitCode != 0) { - throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}"); + throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}. Output: {jsonOutput}"); } } @@ -291,7 +291,7 @@ public static void RefreshPolicy() if (process.ExitCode != 0) { - throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}"); + throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}. Output: {jsonOutput}"); } } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ConfigureISGServices.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ConfigureISGServices.cs new file mode 100644 index 000000000..03832fba4 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ConfigureISGServices.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WDACConfig +{ + internal static class ConfigureISGServices + { + /// + /// Starts the AppIdTel and sets the appidsvc service to auto start + /// + public static void Configure() + { + Logger.Write("Configuring and starting the required ISG related services"); + + _ = PowerShellExecutor.ExecuteScript(""" +appidtel.exe start +sc.exe config appidsvc start=auto +"""); + + } + } +} diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Crypt32CertCN.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Crypt32CertCN.cs index e90fb77ef..e006329cc 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Crypt32CertCN.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Crypt32CertCN.cs @@ -8,7 +8,7 @@ namespace WDACConfig { - public class CryptoAPI + public static class CryptoAPI { // Importing function from crypt32.dll to access certificate information // https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certgetnamestringa diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DeviceGuardInfo.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DeviceGuardInfo.cs index 2a7fadb5e..d27a7a085 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DeviceGuardInfo.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DeviceGuardInfo.cs @@ -6,13 +6,13 @@ namespace WDACConfig { - public class DeviceGuardStatus + public sealed class DeviceGuardStatus { public uint? UsermodeCodeIntegrityPolicyEnforcementStatus { get; set; } public uint? CodeIntegrityPolicyEnforcementStatus { get; set; } } - public class DeviceGuardInfo + public static class DeviceGuardInfo { /// /// Get the Device Guard status information from the Win32_DeviceGuard WMI class diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DirectorySelector.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DirectorySelector.cs index 53bf65821..ef3c11556 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DirectorySelector.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DirectorySelector.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; #nullable enable @@ -35,11 +34,11 @@ public static class DirectorySelector } while (true); // return null if no directories were selected or the array of selected directories if there are any - return programsPaths.Count > 0 ? programsPaths.ToArray() : null; + return programsPaths.Count > 0 ? [.. programsPaths] : null; } // Comparer for DirectoryInfo to ensure uniqueness and do it in a case-insensitive way - private class DirectoryInfoComparer : IEqualityComparer + private sealed class DirectoryInfoComparer : IEqualityComparer { public bool Equals(DirectoryInfo? x, DirectoryInfo? y) { diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DriveLetterMapper.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DriveLetterMapper.cs index 8a8349140..9e87aa026 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DriveLetterMapper.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/DriveLetterMapper.cs @@ -89,7 +89,7 @@ public static List GetGlobalRootDrives() // Get the mount point for the volume _ = GetVolumePathNamesForVolumeNameW(volume, sbMountPoint, max, ref lpcchReturnLength); // Get the device path for the volume - uint returnLength = QueryDosDevice(volume.Substring(4, volume.Length - 5), sbPathName, (int)max); + uint returnLength = QueryDosDevice(volume[4..^1], sbPathName, (int)max); // Check if the device path is found if (returnLength > 0) diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/EventLogUtility.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/EventLogUtility.cs index ea9d82081..8bbbcf794 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/EventLogUtility.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/EventLogUtility.cs @@ -16,7 +16,7 @@ public static class EventLogUtility /// Size of the Code Integrity Operational Event Log public static void SetLogSize(ulong logSize = 0) { - WDACConfig.Logger.Write("Set-SetLogSize method started..."); + Logger.Write("Set-SetLogSize method started..."); string logName = "Microsoft-Windows-CodeIntegrity/Operational"; @@ -32,7 +32,7 @@ public static void SetLogSize(ulong logSize = 0) { if (currentLogMaxSize <= 10 * 1024 * 1024) { - WDACConfig.Logger.Write("Increasing the Code Integrity log size by 1MB because its current free space is less than 1MB."); + Logger.Write("Increasing the Code Integrity log size by 1MB because its current free space is less than 1MB."); logConfig.MaximumSizeInBytes = currentLogMaxSize + 1 * 1024 * 1024; logConfig.IsEnabled = true; logConfig.SaveChanges(); @@ -45,14 +45,14 @@ public static void SetLogSize(ulong logSize = 0) // To prevent from disabling the log or setting it to a very small size that is lower than its default size if (logSize > 1100 * 1024) { - WDACConfig.Logger.Write($"Setting Code Integrity log size to {logSize}."); + Logger.Write($"Setting Code Integrity log size to {logSize}."); logConfig.MaximumSizeInBytes = (long)logSize; logConfig.IsEnabled = true; logConfig.SaveChanges(); } else { - WDACConfig.Logger.Write("Provided log size is less than or equal to 1100 KB. No changes made."); + Logger.Write("Provided log size is less than or equal to 1100 KB. No changes made."); } } } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileDirectoryPathComparer.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileDirectoryPathComparer.cs index a3db9579d..f26324358 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileDirectoryPathComparer.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileDirectoryPathComparer.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class FileDirectoryPathComparer + public static class FileDirectoryPathComparer { /// /// Method that takes 2 arrays, one containing file paths and the other containing folder paths. diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileSystemPicker.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileSystemPicker.cs index 6c0992509..c85555627 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileSystemPicker.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/FileSystemPicker.cs @@ -5,10 +5,9 @@ namespace WDACConfig { - public class FileSystemPicker + public static class FileSystemPicker { - /// /// Usage example /// All params are optional diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetExtendedFileAttrib.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetExtendedFileAttrib.cs index 17979b426..6f8c7bb56 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetExtendedFileAttrib.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetExtendedFileAttrib.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class ExFileInfo + public sealed class ExFileInfo { // Constants used for encoding fallback and error handling private const string UnicodeFallbackCode = "04B0"; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetFilesFast.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetFilesFast.cs index 1fb43c0bb..89cf38804 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetFilesFast.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/GetFilesFast.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class FileUtility + public static class FileUtility { /// /// A flexible and fast method that can accept directory paths and file paths as input and return a list of FileInfo objects that are compliant with the WDAC policy. diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Initializer.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Initializer.cs index 6671759fb..5c9a6f1d5 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Initializer.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Initializer.cs @@ -7,9 +7,14 @@ namespace WDACConfig { // Prepares the environment. It also runs commands that would otherwise run in the default constructor for the GlobalVars Class - public class Initializer + public static class Initializer { + /// /// These are the codes that were present in the GlobalVar class's default constructor but defining them as a separate method allows any errors thrown in them to be properly displayed in PowerShell instead of showing an error occurred in the default constructor of a class + /// + /// + /// + /// public static void Initialize() { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion") ?? throw new InvalidOperationException("Could not get the current Windows version from the registry")) diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Logging/LoggerInitializer.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Logging/LoggerInitializer.cs index d40f28a62..c7b8c378c 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Logging/LoggerInitializer.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Logging/LoggerInitializer.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class LoggerInitializer + public static class LoggerInitializer { /// /// Gets the VerbosePreference, DebugPreference, and Host from the PowerShell session, each main cmdlet of the WDACConfig module diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs index 5e55aaa11..110097f57 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs @@ -11,7 +11,7 @@ namespace WDACConfig { // This class defines Hash entries for each file in the WDACConfig PowerShell module based on the cloud CSV - public class WDACConfigHashEntry(string? relativePath, string? fileName, string? fileHash, string? fileHashSHA3_512) + public sealed class WDACConfigHashEntry(string? relativePath, string? fileName, string? fileHash, string? fileHashSHA3_512) { public string? RelativePath { get; set; } = relativePath; public string? FileName { get; set; } = fileName; @@ -20,7 +20,7 @@ public class WDACConfigHashEntry(string? relativePath, string? fileName, string? } - public class AssertWDACConfigIntegrity + public static class AssertWDACConfigIntegrity { /// /// Hashes all of the files in the WDACConfig, download the cloud hashes, compares them with each other and report back hash mismatches @@ -34,9 +34,6 @@ public class AssertWDACConfigIntegrity string OutputFileName = "Hashes.csv"; string url = "https://raw.githubusercontent.com/HotCakeX/Harden-Windows-Security/main/WDACConfig/Utilities/Hashes.csv"; - // Parse the CSV content - List ParsedCSVList = []; - // Hash details of the current PowerShell files List CurrentFileHashes = []; @@ -46,7 +43,7 @@ public class AssertWDACConfigIntegrity string csvData = client.GetStringAsync(url).Result; // Parse the CSV content - ParsedCSVList = ParseCSV(csvData); + List ParsedCSVList = ParseCSV(csvData); // Get all of the files in the PowerShell module directory List files = WDACConfig.FileUtility.GetFilesFast([new DirectoryInfo(WDACConfig.GlobalVars.ModuleRootPath!)], null, ["*"]); @@ -171,24 +168,22 @@ private static List ParseCSV(string csvData) private static void ExportToCsv(string outputPath, List entries) { // Ensure we create a new file or overwrite an existing one - using (StreamWriter writer = new(outputPath, false, Encoding.UTF8)) - { - // Write the CSV header - writer.WriteLine(""" + using StreamWriter writer = new(outputPath, false, Encoding.UTF8); + // Write the CSV header + writer.WriteLine(""" "RelativePath","FileName","FileHash","FileHashSHA3_512" """); - // Write each entry in the list - foreach (var entry in entries) - { - string relativePath = EscapeCsv(entry.RelativePath); - string fileName = EscapeCsv(entry.FileName); - string fileHash = EscapeCsv(entry.FileHash); - string fileHashSHA3_512 = EscapeCsv(entry.FileHashSHA3_512); + // Write each entry in the list + foreach (var entry in entries) + { + string relativePath = EscapeCsv(entry.RelativePath); + string fileName = EscapeCsv(entry.FileName); + string fileHash = EscapeCsv(entry.FileHash); + string fileHashSHA3_512 = EscapeCsv(entry.FileHashSHA3_512); - // Write the CSV row - writer.WriteLine($"{relativePath},{fileName},{fileHash},{fileHashSHA3_512}"); - } + // Write the CSV row + writer.WriteLine($"{relativePath},{fileName},{fileHash},{fileHashSHA3_512}"); } } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/BasePolicyCreator.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/BasePolicyCreator.cs index ad1f66650..d5d074bf5 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/BasePolicyCreator.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/BasePolicyCreator.cs @@ -13,7 +13,7 @@ namespace WDACConfig { - public class BasePolicyCreator + public static class BasePolicyCreator { /// /// Creates scheduled task that keeps the Microsoft recommended driver block rules up to date on the system @@ -168,7 +168,7 @@ public static void SetAutoUpdateDriverBlockRules() } - public class DriverBlockListInfo + public sealed class DriverBlockListInfo { public string? Version { get; set; } public DateTime LastUpdated { get; set; } @@ -272,7 +272,7 @@ public static void DeployDriversBlockRules(string StagingArea) // Initialize the final destination of the SiPolicy file string SiPolicyFinalDestination; - if (systemDrive != null) + if (systemDrive is not null) { // Construct the final destination of the SiPolicy file SiPolicyFinalDestination = System.IO.Path.Combine(systemDrive, "Windows", "System32", "CodeIntegrity", "SiPolicy.p7b"); @@ -296,7 +296,7 @@ public static void DeployDriversBlockRules(string StagingArea) // Get the path of the SiPolicy file string[] SiPolicyPaths = System.IO.Directory.GetFiles(ZipExtractionDir, "SiPolicy_Enforced.p7b", System.IO.SearchOption.AllDirectories); - // Make sure to get only one file is there is more than one (which is unexpected) + // Make sure to get only one file if there is more than one (which is unexpected) string SiPolicyPath = SiPolicyPaths[0]; // If the SiPolicy file already exists, delete it @@ -308,13 +308,11 @@ public static void DeployDriversBlockRules(string StagingArea) // Move the SiPolicy file to the final destination, renaming it in the process File.Move(SiPolicyPath, SiPolicyFinalDestination); - Logger.Write("Refreshing the system WDAC policies"); CiToolHelper.RefreshPolicy(); Logger.Write("SiPolicy.p7b has been deployed and policies refreshed."); - Logger.Write("Displaying extra info about the Microsoft recommended Drivers block list"); _ = DriversBlockListInfoGathering(); } @@ -410,22 +408,20 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi policyName = "AllowMicrosoft"; } - // Path only used during staging area processing + // Paths only used during staging area processing string tempPolicyPath = Path.Combine(StagingArea, $"{policyName}.xml"); - string tempPolicyCIPPath = Path.Combine(StagingArea, $"{policyName}.cip"); + // Final Policy Path string finalPolicyPath = Path.Combine(GlobalVars.UserConfigDir, $"{policyName}.xml"); - GetBlockRules(StagingArea, deploy, false); - + // Get/Deploy the block rules + GetBlockRules(StagingArea, deploy); Logger.Write("Copying the AllowMicrosoft.xml from Windows directory to the Staging Area"); File.Copy(@"C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml", tempPolicyPath, true); - - Logger.Write("Resetting the policy ID and assigning policy name"); // Get the policy ID of the policy being created @@ -450,7 +446,6 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi if (deploy) { - Logger.Write("Converting the policy file to .CIP binary"); PolicyToCIPConverter.Convert(tempPolicyPath, tempPolicyCIPPath); @@ -460,7 +455,6 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi File.Copy(tempPolicyPath, finalPolicyPath, true); - } @@ -470,7 +464,7 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi /// It generates a XML file compliant with CI Policies Schema. /// /// - public static void GetBlockRules(string StagingArea, bool deploy, bool? deployAppControlSupplementalPolicy) + public static void GetBlockRules(string StagingArea, bool deploy) { string policyName = "Microsoft Windows Recommended User Mode BlockList"; @@ -510,23 +504,19 @@ public static void GetBlockRules(string StagingArea, bool deploy, bool? deployAp // Fix the elements userModeBlockRulesXML = FixMissingElements(userModeBlockRulesXML); - // Path only used during staging area processing + // Paths only used during staging area processing string tempPolicyPath = Path.Combine(StagingArea, $"{policyName}.xml"); - string tempPolicyCIPPath = Path.Combine(StagingArea, $"{policyName}.cip"); - // Save the XML content to a file userModeBlockRulesXML.Save(tempPolicyPath); - CiRuleOptions.Set(filePath: tempPolicyPath, rulesToAdd: [CiRuleOptions.PolicyRuleOptions.EnabledUpdatePolicyNoReboot, CiRuleOptions.PolicyRuleOptions.DisabledScriptEnforcement], rulesToRemove: [CiRuleOptions.PolicyRuleOptions.EnabledAuditMode, CiRuleOptions.PolicyRuleOptions.EnabledAdvancedBootOptionsMenu]); Logger.Write("Assigning policy name and resetting policy ID"); // Get the policyID of the policy being created - string policyID = SetCiPolicyInfo.Set(tempPolicyPath, true, policyName, null, null); - + _ = SetCiPolicyInfo.Set(tempPolicyPath, true, policyName, null, null); string finalPolicyPath = Path.Combine(GlobalVars.UserConfigDir, $"{policyName}.xml"); @@ -535,37 +525,41 @@ public static void GetBlockRules(string StagingArea, bool deploy, bool? deployAp Logger.Write($"Checking if the {policyName} policy is already deployed"); - + // Getting the list of the deployed base policies whose names match the policyName List CurrentlyDeployedBlockRules = CiToolHelper.GetPolicies(false, true, false).Where(policy => string.Equals(policy.FriendlyName, policyName, StringComparison.OrdinalIgnoreCase)).ToList(); + // If any policy was found if (CurrentlyDeployedBlockRules.Count > 0) { + // Get the ID of the policy string CurrentlyDeployedBlockRulesGUID = CurrentlyDeployedBlockRules.First().PolicyID!; Logger.Write($"{policyName} policy is already deployed, updating it using the same GUID which is {CurrentlyDeployedBlockRulesGUID}."); - PolicyEditor.EditGuids(CurrentlyDeployedBlockRulesGUID, new FileInfo(tempPolicyPath)); + // Swap the policyID in the current policy XML file with the one from the deployed policy + PolicyEditor.EditGuids(CurrentlyDeployedBlockRulesGUID, new FileInfo(tempPolicyPath)); } else { Logger.Write($"{policyName} policy is not deployed, deploying it now."); } + // Convert it to CIP PolicyToCIPConverter.Convert(tempPolicyPath, tempPolicyCIPPath); + // Deploy the CIP file CiToolHelper.UpdatePolicy(tempPolicyCIPPath); } File.Copy(tempPolicyPath, finalPolicyPath, true); - } /// - /// Creates SignedAndReputable WDAC policy which is based on AllowMicrosoft template policy. + /// Creates SignedAndReputable App Control policy which is based on AllowMicrosoft template policy. /// It uses ISG to authorize files with good reputation. /// /// @@ -591,15 +585,15 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo policyName = "SignedAndReputable"; } - // Path only used during staging area processing + // Paths only used during staging area processing string tempPolicyPath = Path.Combine(StagingArea, $"{policyName}.xml"); - string tempPolicyCIPPath = Path.Combine(StagingArea, $"{policyName}.cip"); + // Final policy XML path string finalPolicyPath = Path.Combine(GlobalVars.UserConfigDir, $"{policyName}.xml"); - GetBlockRules(StagingArea, deploy, false); - + // Get/Deploy the block rules + GetBlockRules(StagingArea, deploy); Logger.Write("Copying the AllowMicrosoft.xml from Windows directory to the Staging Area"); @@ -615,7 +609,6 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo TestMode: TestMode); - Logger.Write("Resetting the policy ID and assigning policy name"); // Get the policyID of the policy being created @@ -631,6 +624,7 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo if (deploy) { + ConfigureISGServices.Configure(); Logger.Write("Converting the policy file to .CIP binary"); @@ -641,7 +635,6 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo File.Copy(tempPolicyPath, finalPolicyPath, true); - } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs index 0ec5372f4..01210bd07 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class SecurePolicySetting(object? Value, WDACConfig.WLDP_SECURE_SETTING_VALUE_TYPE ValueType, uint ValueSize, bool Status, int StatusCode) + public sealed class SecurePolicySetting(object? Value, WDACConfig.WLDP_SECURE_SETTING_VALUE_TYPE ValueType, uint ValueSize, bool Status, int StatusCode) { public object? Value { get; set; } = Value; public WDACConfig.WLDP_SECURE_SETTING_VALUE_TYPE ValueType { get; set; } = ValueType; @@ -14,7 +14,7 @@ public class SecurePolicySetting(object? Value, WDACConfig.WLDP_SECURE_SETTING_V public int StatusCode { get; set; } = StatusCode; } - public class GetCIPolicySetting + public static class GetCIPolicySetting { public static SecurePolicySetting Invoke(string provider, string key, string valueName) diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs index 1cad61749..45304fb89 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs @@ -7,7 +7,7 @@ namespace WDACConfig { - public class CiRuleOptions + public static class CiRuleOptions { public enum PolicyTemplate @@ -158,6 +158,39 @@ public enum PolicyRuleOptions #endregion + + /* + #region Policy Rule Options + // Fetches the latest policy rule options from the Schema file that exists on the system + + // Load the CI Schema content + XmlDocument schemaData = new(); + schemaData.Load(Path.Combine(WDACConfig.GlobalVars.CISchemaPath)); + + // Create a namespace manager to handle namespaces + XmlNamespaceManager nsManager = new(schemaData.NameTable); + nsManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); + + // Define the XPath query to fetch enumeration values + string xpathQuery = "//xs:simpleType[@name='OptionType']/xs:restriction/xs:enumeration/@value"; + + // Create a new HashSet to store the valid policy rule options + HashSet validOptions = new(StringComparer.OrdinalIgnoreCase); + + // Fetch enumeration values from the schema + XmlNodeList? optionNodes = schemaData.SelectNodes(xpathQuery, nsManager) ?? throw new InvalidOperationException("No valid options found in the Code Integrity Schema."); + + foreach (XmlNode node in optionNodes) + { + if (node.Value != null) + { + _ = validOptions.Add(node.Value); + } + } + #endregion + */ + + /// /// Configures the Policy rule options in a given XML file and sets the HVCI to Strict in the output XML file. /// It offers many ways to configure the policy rule options in a given XML file. @@ -410,10 +443,7 @@ public static void Set( // Always remove any existing rule options initially. The calculations determining which // Rules must be included in the policy are all made in this method. - if (RulesNode is not null) - { - RulesNode.RemoveAll(); - } + RulesNode?.RemoveAll(); // Convert the HashSet to a List and sort it diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/TestCiPolicy.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/TestCiPolicy.cs index 89b4d5a4a..922137d03 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/TestCiPolicy.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/TestCiPolicy.cs @@ -24,7 +24,7 @@ public static class CiPolicyTest if (!string.IsNullOrEmpty(xmlFilePath)) { // Get the Code Integrity Schema file path - string schemaPath = WDACConfig.GlobalVars.CISchemaPath; + string schemaPath = GlobalVars.CISchemaPath; // Make sure the schema file exists if (!File.Exists(schemaPath)) diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/UserConfiguration.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/UserConfiguration.cs index 675944c26..fc9e8b05c 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/UserConfiguration.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/UserConfiguration.cs @@ -22,7 +22,7 @@ public partial class UserConfigurationContext : JsonSerializerContext // Represents an instance of the User configurations JSON settings file // Maintains the order of the properties when writing to the JSON file // Includes the methods for interacting with user configurations JSON file - public partial class UserConfiguration( + public sealed partial class UserConfiguration( string? signedPolicyPath, string? unsignedPolicyPath, string? signToolCustomPath, @@ -237,17 +237,17 @@ private static UserConfiguration ParseJson(string json) var root = doc.RootElement; return new UserConfiguration( - TryGetStringProperty(root, "SignedPolicyPath"), - TryGetStringProperty(root, "UnsignedPolicyPath"), - TryGetStringProperty(root, "SignToolCustomPath"), - TryGetStringProperty(root, "CertificateCommonName"), - TryGetStringProperty(root, "CertificatePath"), + TryGetStringProperty(root, nameof(SignedPolicyPath)), + TryGetStringProperty(root, nameof(UnsignedPolicyPath)), + TryGetStringProperty(root, nameof(SignToolCustomPath)), + TryGetStringProperty(root, nameof(CertificateCommonName)), + TryGetStringProperty(root, nameof(CertificatePath)), - TryGetGuidProperty(root, "StrictKernelPolicyGUID"), - TryGetGuidProperty(root, "StrictKernelNoFlightRootsPolicyGUID"), + TryGetGuidProperty(root, nameof(StrictKernelPolicyGUID)), + TryGetGuidProperty(root, nameof(StrictKernelNoFlightRootsPolicyGUID)), - TryGetDateTimeProperty(root, "LastUpdateCheck"), - TryGetDateTimeProperty(root, "StrictKernelModePolicyTimeOfDeployment") + TryGetDateTimeProperty(root, nameof(LastUpdateCheck)), + TryGetDateTimeProperty(root, nameof(StrictKernelModePolicyTimeOfDeployment)) ); static string? TryGetStringProperty(JsonElement root, string propertyName) diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MeowOpener.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MeowOpener.cs index 3eb4052e5..31b02fcb8 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MeowOpener.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MeowOpener.cs @@ -46,12 +46,14 @@ internal struct MeowMemberCrypt // A public static method that returns a HashSet of strings. public static HashSet GetHashes(string SecurityCatalogFilePath) { - HashSet OutputHashSet = []; // Initializes a new HashSet to store the hashes. + // Initializes a new HashSet to store the hashes. + HashSet OutputHashSet = []; // Creates a new XmlDocument instance. XmlDocument PurrfectCatalogXMLDoc = new() { - XmlResolver = null // Disables the XML resolver for security reasons. + // Disables the XML resolver for security reasons. + XmlResolver = null }; IntPtr MainCryptProviderHandle = IntPtr.Zero; // Initializes the handle to zero. @@ -63,28 +65,36 @@ public static HashSet GetHashes(string SecurityCatalogFilePath) // Attempts to acquire a cryptographic context. if (!CryptAcquireContext(out MainCryptProviderHandle, string.Empty, string.Empty, 1, 4026531840)) { - // If the context is not acquired, the error can be captured (commented out). - // int lastWin32Error = Marshal.GetLastWin32Error(); + // If the context is not acquired, capture the error code. + int lastWin32Error = Marshal.GetLastWin32Error(); + Logger.Write($"CryptAcquireContext failed with error code: {lastWin32Error}"); } // Opens the catalog file and gets a handle to the catalog context. MeowLogHandle = WinTrust.CryptCATOpen(SecurityCatalogFilePath, 0, MainCryptProviderHandle, 0, 0); + if (MeowLogHandle == IntPtr.Zero) { - // If the handle is not obtained, the error can be captured (commented out). - // int lastWin32Error = Marshal.GetLastWin32Error(); + // If the handle is not obtained, capture the error code. + int lastWin32Error = Marshal.GetLastWin32Error(); + Logger.Write($"CryptCATOpen failed with error code: {lastWin32Error}"); } + // Creates an XML element to represent the catalog file. XmlElement catalogElement = PurrfectCatalogXMLDoc.CreateElement("MeowFile"); - _ = PurrfectCatalogXMLDoc.AppendChild(catalogElement); // Appends the element to the XML document. + + // Appends the element to the XML document. + _ = PurrfectCatalogXMLDoc.AppendChild(catalogElement); // Iterates through the catalog members. while ((KittyPointer = WinTrust.CryptCATEnumerateMember(MeowLogHandle, KittyPointer)) != IntPtr.Zero) { // Converts the pointer to a structure. MeowMemberCrypt member = Marshal.PtrToStructure(KittyPointer); - _ = OutputHashSet.Add(member.Hashes); // Adds the hashes to the HashSet. + + // Adds the hashes to the HashSet. + _ = OutputHashSet.Add(member.Hashes); } } finally @@ -96,7 +106,9 @@ public static HashSet GetHashes(string SecurityCatalogFilePath) if (MeowLogHandle != IntPtr.Zero) _ = WinTrust.CryptCATClose(MeowLogHandle); } - return OutputHashSet; // Returns the HashSet containing the hashes. + + // Returns the HashSet containing the hashes. + return OutputHashSet; } } } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MoveUserModeToKernelMode.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MoveUserModeToKernelMode.cs index 141a53ea9..82d265397 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MoveUserModeToKernelMode.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/MoveUserModeToKernelMode.cs @@ -38,7 +38,7 @@ public static void Move(string filePath) XmlNode? signingScenario131 = null; // If there is no SigningScenarios block in the XML then exit the method - if (signingScenarios == null) + if (signingScenarios is null) { return; } @@ -59,13 +59,13 @@ public static void Move(string filePath) } // If both SigningScenario nodes were found - if (signingScenario12 != null && signingScenario131 != null) + if (signingScenario12 is not null && signingScenario131 is not null) { // Get AllowedSigners from SigningScenario with Value 12 XmlNode? allowedSigners12 = signingScenario12.SelectSingleNode("./sip:ProductSigners/sip:AllowedSigners", nsManager); // If AllowedSigners node exists in SigningScenario 12 and has child nodes - if (allowedSigners12 != null && allowedSigners12.HasChildNodes) + if (allowedSigners12 is not null && allowedSigners12.HasChildNodes) { // Loop through each child node of AllowedSigners in SigningScenario 12 foreach (XmlNode allowedSignerNode in allowedSigners12.ChildNodes) @@ -96,7 +96,7 @@ public static void Move(string filePath) XmlNode? allowedSigners131 = signingScenario131.SelectSingleNode("./sip:ProductSigners/sip:AllowedSigners", nsManager); // If the AllowedSigners node exists in SigningScenario 131 - if (allowedSigners131 != null) + if (allowedSigners131 is not null) { // Append the new AllowedSigner node to the AllowedSigners node in SigningScenario 131 _ = allowedSigners131.AppendChild(newAllowedSigner); diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyFileSigningStatusDetection.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyFileSigningStatusDetection.cs index 05508d620..18f874b7b 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyFileSigningStatusDetection.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyFileSigningStatusDetection.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class PolicyFileSigningStatusDetection + public static class PolicyFileSigningStatusDetection { public enum SigningStatus diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyMerger.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyMerger.cs index df4f1bb9a..8d09eff3d 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyMerger.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyMerger.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class PolicyMerger + public static class PolicyMerger { /// /// Merges multiple policies into a single policy using the PowerShell cmdlet of the ConfigCI module diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyToCIPConverter.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyToCIPConverter.cs index 4dd40d512..71efee3ab 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyToCIPConverter.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PolicyToCIPConverter.cs @@ -1,6 +1,6 @@ namespace WDACConfig { - public class PolicyToCIPConverter + public static class PolicyToCIPConverter { /// /// Converts a XML policy file to CIP binary file using the ConvertFrom-CIPolicy PowerShell cmdlet of the ConfigCI module diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PowerShellExecutor.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PowerShellExecutor.cs index 213851642..a24449a2f 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PowerShellExecutor.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/PowerShellExecutor.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class PowerShellExecutor + public static class PowerShellExecutor { /// /// Runs a PowerShell script and displays verbose and normal output in real-time. @@ -37,7 +37,7 @@ public class PowerShellExecutor outputCollection = []; outputCollection.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { var outputStream = (PSDataCollection)sender; var output = outputStream[args.Index]?.ToString(); @@ -49,7 +49,7 @@ public class PowerShellExecutor // Handle verbose output psInstance.Streams.Verbose.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { var verboseStream = (PSDataCollection)sender; Logger.Write($"Verbose: {verboseStream[args.Index].Message}"); @@ -59,7 +59,7 @@ public class PowerShellExecutor // Handle warning output psInstance.Streams.Warning.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { var warningStream = (PSDataCollection)sender; Logger.Write($"Warning: {warningStream[args.Index].Message}"); @@ -69,7 +69,7 @@ public class PowerShellExecutor // Handle error output and throw exception psInstance.Streams.Error.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { // Get the error details var errorStream = (PSDataCollection)sender; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/RemoveSupplementalSigners.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/RemoveSupplementalSigners.cs index 046e0514f..75d0eba94 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/RemoveSupplementalSigners.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/RemoveSupplementalSigners.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class CiPolicyHandler + public static class CiPolicyHandler { /// /// Removes the entire SupplementalPolicySigners block diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ScanLevelz.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ScanLevelz.cs index 02862a5fd..69b0ddc41 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ScanLevelz.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/ScanLevelz.cs @@ -5,7 +5,7 @@ namespace WDACConfig { // Argument tab auto-completion and ValidateSet for Levels and Fallbacks parameters in the entire module - public class ScanLevelz : IValidateSetValuesGenerator + public sealed class ScanLevelz : IValidateSetValuesGenerator { public string[] GetValidValues() { diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SnapBackGuarantee.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SnapBackGuarantee.cs index e13942e96..327d43648 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SnapBackGuarantee.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SnapBackGuarantee.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class SnapBackGuarantee + public static class SnapBackGuarantee { /// diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SupplementalForSelf.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SupplementalForSelf.cs index 33f0a391a..f64fbaaab 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SupplementalForSelf.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/SupplementalForSelf.cs @@ -9,7 +9,7 @@ namespace WDACConfig { - internal class SupplementalForSelf + internal static class SupplementalForSelf { /// /// Deploys the Supplemental Policy that allows the Application to be allowed to run after deployment diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs index 7edf4b4a3..2823bd1f7 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs @@ -2,7 +2,7 @@ namespace WDACConfig { - public class CodeIntegrityHashes(string? sha1Page, string? sha256Page, string? sha1Authenticode, string? sha256Authenticode) + public sealed class CodeIntegrityHashes(string? sha1Page, string? sha256Page, string? sha1Authenticode, string? sha256Authenticode) { public string? SHA1Page { get; set; } = sha1Page; public string? SHA256Page { get; set; } = sha256Page; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs index e0777e36b..24ecf67ca 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs @@ -3,7 +3,7 @@ namespace WDACConfig { - public class CertificateDetailsCreator(string intermediateCertTBS, string intermediateCertName, string leafCertTBS, string leafCertName) + public sealed class CertificateDetailsCreator(string intermediateCertTBS, string intermediateCertName, string leafCertTBS, string leafCertName) { public string IntermediateCertTBS { get; set; } = intermediateCertTBS; public string IntermediateCertName { get; set; } = intermediateCertName; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateSignerCreator.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateSignerCreator.cs index 625c2615a..aba209704 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateSignerCreator.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CertificateSignerCreator.cs @@ -2,7 +2,7 @@ namespace WDACConfig { - public class CertificateSignerCreator(string tbs, string signerName, int siSigningScenario) + public sealed class CertificateSignerCreator(string tbs, string signerName, int siSigningScenario) { public string TBS { get; set; } = tbs; public string SignerName { get; set; } = signerName; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainElement.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainElement.cs index 228ae3140..e7ac1844b 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainElement.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainElement.cs @@ -13,7 +13,7 @@ public enum CertificateType Leaf = 2 } - public class ChainElement(string subjectcn, string issuercn, DateTime notafter, string tbsvalue, X509Certificate2 certificate, CertificateType type) + public sealed class ChainElement(string subjectcn, string issuercn, DateTime notafter, string tbsvalue, X509Certificate2 certificate, CertificateType type) { public string SubjectCN { get; set; } = subjectcn; public string IssuerCN { get; set; } = issuercn; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainPackage.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainPackage.cs index 623ff6673..0854ee427 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainPackage.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/ChainPackage.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class ChainPackage(X509Chain certificatechain, SignedCms signedcms, ChainElement rootcertificate, + public sealed class ChainPackage(X509Chain certificatechain, SignedCms signedcms, ChainElement rootcertificate, ChainElement[]? intermediatecertificates, ChainElement? leafcertificate) { diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs index ce8c2c7e9..53505b2ad 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs @@ -5,7 +5,7 @@ namespace WDACConfig { // Used by the BuildSignerAndHashObjects method to store and return the output - public class FileBasedInfoPackage(List filepublishersigners, List publishersigners, List completehashes) + public sealed class FileBasedInfoPackage(List filepublishersigners, List publishersigners, List completehashes) { public List FilePublisherSigners { get; set; } = filepublishersigners; public List PublisherSigners { get; set; } = publishersigners; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs index 668fce85d..06527565c 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class FilePublisherSignerCreator + public sealed class FilePublisherSignerCreator { public List CertificateDetails { get; set; } public Version? FileVersion { get; set; } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/HashCreator.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/HashCreator.cs index 3eb1de338..5461bb5ba 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/HashCreator.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/HashCreator.cs @@ -3,7 +3,7 @@ namespace WDACConfig { - public class HashCreator(string authenticodeSHA256, string authenticodeSHA1, string fileName, int siSigningScenario) + public sealed class HashCreator(string authenticodeSHA256, string authenticodeSHA1, string fileName, int siSigningScenario) { public string AuthenticodeSHA256 { get; set; } = authenticodeSHA256; public string AuthenticodeSHA1 { get; set; } = authenticodeSHA1; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/OpusSigner.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/OpusSigner.cs index 778756cac..4356d2d8e 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/OpusSigner.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/OpusSigner.cs @@ -3,7 +3,7 @@ namespace WDACConfig { - public class OpusSigner(string tbsHash, string subjectCN) + public sealed class OpusSigner(string tbsHash, string subjectCN) { public string TBSHash { get; set; } = tbsHash; public string SubjectCN { get; set; } = subjectCN; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PolicyHashObj.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PolicyHashObj.cs index 04633850b..87de7475c 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PolicyHashObj.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PolicyHashObj.cs @@ -5,7 +5,7 @@ // Used by WDAC Simulations namespace WDACConfig { - public class PolicyHashObj(string hashvalue, string hashtype, string filepathforhash) + public sealed class PolicyHashObj(string hashvalue, string hashtype, string filepathforhash) { // Adding public getters and setters for the properties public string HashValue { get; set; } = hashvalue; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PublisherSignerCreator.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PublisherSignerCreator.cs index 7728a55d3..b168ef4d2 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PublisherSignerCreator.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/PublisherSignerCreator.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class PublisherSignerCreator + public sealed class PublisherSignerCreator { public List CertificateDetails { get; set; } public string? FileName { get; set; } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/Signer.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/Signer.cs index 7e60b8333..3bd370a56 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/Signer.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/Signer.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class Signer(string id, string name, string certRoot, string? certPublisher, string? certIssuer, + public sealed class Signer(string id, string name, string certRoot, string? certPublisher, string? certIssuer, string[]? certEKU, string? certOemID, string[]? fileAttribRef, Dictionary>? fileAttrib, string signerScope, bool isWHQL, bool isAllowed, bool hasEKU) diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationInput.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationInput.cs index 7996b7b96..9e1efc703 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationInput.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationInput.cs @@ -4,7 +4,7 @@ // Used by WDAC Simulations namespace WDACConfig { - public class SimulationInput(System.IO.FileInfo filepath, ChainPackage[] allfilesigners, Signer[] signerinfo, string[] ekuoids) + public sealed class SimulationInput(System.IO.FileInfo filepath, ChainPackage[] allfilesigners, Signer[] signerinfo, string[] ekuoids) { // Adding public getters and setters for the properties public System.IO.FileInfo FilePath { get; set; } = filepath; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationOutput.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationOutput.cs index c374d79c8..3fa858cdd 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationOutput.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/SimulationOutput.cs @@ -4,7 +4,7 @@ namespace WDACConfig { // This class holds the details of the current file in the WDAC Simulation comparer - public class SimulationOutput( + public sealed class SimulationOutput( string path, string source, bool isAuthorized, diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/WinTrust.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/WinTrust.cs index 10b966f35..d8a829e85 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/WinTrust.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/WinTrust.cs @@ -1,10 +1,12 @@ using System; using System.Runtime.InteropServices; +#nullable enable + namespace WDACConfig { // This class contains all of the WinTrust related functions and codes - internal partial class WinTrust + internal static partial class WinTrust { #region necessary logics for Authenticode and First Page hash calculation diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/CILogIntel.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/CILogIntel.cs index 0c3621e22..e8d6eb702 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/CILogIntel.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/CILogIntel.cs @@ -5,14 +5,14 @@ namespace WDACConfig { // Application Control event tags intelligence - public class CILogIntel + public static class CILogIntel { // Requested and Validated Signing Level Mappings: https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-tag-explanations#requested-and-validated-signing-level public static readonly Dictionary ReqValSigningLevels = new() { { 0 , "Signing level hasn't yet been checked"}, { 1 , "File is unsigned or has no signature that passes the active policies"}, - { 2 , "Trusted by Windows Defender Application Control policy"}, + { 2 , "Trusted by App Control for Business policy"}, { 3 , "Developer signed code"}, { 4 , "Authenticode signed"}, { 5 , "Microsoft Store signed app PPL (Protected Process Light)"}, @@ -61,7 +61,7 @@ public class CILogIntel { 18 , "Custom signing level not met; returned if signature fails to match CISigners in UMCI."}, { 19 , "Binary is revoked based on its file hash."}, { 20 , "SHA1 cert hash's timestamp is missing or after valid cutoff as defined by Weak Crypto Policy."}, - { 21 , "Failed to pass Windows Defender Application Control policy."}, + { 21 , "Failed to pass App Control for Business policy."}, { 22 , "Not Isolated User Mode (IUM) signed; indicates an attempt to load a standard Windows binary into a virtualization-based security (VBS) trustlet."}, { 23 , "Invalid image hash. This error can indicate file corruption or a problem with the file's signature. Signatures using elliptic curve cryptography (ECC), such as ECDSA, return this VerificationError."}, { 24 , "Flight root not allowed; indicates trying to run flight-signed code on production OS."}, diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/GlobalVars.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/GlobalVars.cs index f71196699..c3acd8863 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/GlobalVars.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/Variables/GlobalVars.cs @@ -19,7 +19,7 @@ public static class GlobalVars public const string MSFTRecommendedDriverBlockRulesURL = "https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/refs/heads/public/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules.md"; // Minimum required OS build number - public const decimal Requiredbuild = 22631.4169M; + public const decimal Requiredbuild = 26100.2033M; // Current OS build version public static decimal OSBuildNumber = Environment.OSVersion.Version.Build; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/VersionIncrementer.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/VersionIncrementer.cs index b4357e705..77efbf14c 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/VersionIncrementer.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/VersionIncrementer.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class VersionIncrementer + public static class VersionIncrementer { public static Version AddVersion(Version version) // This can recursively increment an input version by one, and is aware of the max limit diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetCertificateDetails.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetCertificateDetails.cs index ca2450bc8..f76c6590b 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetCertificateDetails.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetCertificateDetails.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class GetCertificateDetails + public static class GetCertificateDetails { /// /// A method to detect Root, Intermediate and Leaf certificates @@ -84,7 +84,7 @@ public static List Get(AllFileSigners[] completeSignatureResult) currentChain, // The entire current chain of the certificate currentSignedCms, // The entire current SignedCms object rootCertificate, - intermediateCertificates.ToArray(), + [.. intermediateCertificates], leafCertificate )); diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs index bdc5a89cc..25e2b5444 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs @@ -16,10 +16,10 @@ public static class GetFileRuleOutput /// /// /// - public static HashSet Get(XmlDocument xml) + public static HashSet Get(XmlDocument xml) { // Create an empty HashSet to store the output - var outputHashInfoProcessing = new HashSet(); + var outputHashInfoProcessing = new HashSet(); // Get the namespace manager var nsmgr = new XmlNamespaceManager(xml.NameTable); @@ -27,11 +27,11 @@ public static class GetFileRuleOutput // Loop through each file rule in the XML file var fileRules = xml.SelectNodes("//si:FileRules/si:Allow", nsmgr); - if (fileRules != null) + if (fileRules is not null) { foreach (XmlNode fileRule in fileRules) { - if (fileRule.Attributes != null) + if (fileRule.Attributes is not null) { // Extract the hash value from the Hash attribute var hashValue = fileRule.Attributes["Hash"]?.InnerText; @@ -41,16 +41,16 @@ public static class GetFileRuleOutput if (!string.IsNullOrEmpty(friendlyName)) { // Extract the hash type from the FriendlyName attribute using regex - var hashTypeMatch = System.Text.RegularExpressions.Regex.Match(friendlyName, @".* (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", RegexOptions.IgnoreCase); + var hashTypeMatch = Regex.Match(friendlyName, @".* (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", RegexOptions.IgnoreCase); var hashType = hashTypeMatch.Success ? hashTypeMatch.Groups[1].Value : string.Empty; // Extract the file path from the FriendlyName attribute using regex - var filePathForHash = System.Text.RegularExpressions.Regex.Replace(friendlyName, @" (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", string.Empty, RegexOptions.IgnoreCase); + var filePathForHash = Regex.Replace(friendlyName, @" (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", string.Empty, RegexOptions.IgnoreCase); // Add the extracted values of the current Hash rule to the output HashSet if (!string.IsNullOrEmpty(hashValue) && !string.IsNullOrEmpty(hashType) && !string.IsNullOrEmpty(filePathForHash)) { - _ = outputHashInfoProcessing.Add(new WDACConfig.PolicyHashObj(hashValue, hashType, filePathForHash)); + _ = outputHashInfoProcessing.Add(new PolicyHashObj(hashValue, hashType, filePathForHash)); } } } @@ -58,9 +58,9 @@ public static class GetFileRuleOutput } // Only keep the Authenticode Hash SHA256 - outputHashInfoProcessing = new HashSet(outputHashInfoProcessing.Where(obj => string.Equals(obj.HashType, "Hash Sha256", StringComparison.OrdinalIgnoreCase))); + outputHashInfoProcessing = new HashSet(outputHashInfoProcessing.Where(obj => string.Equals(obj.HashType, "Hash Sha256", StringComparison.OrdinalIgnoreCase))); - WDACConfig.Logger.Write($"Returning {outputHashInfoProcessing.Count} file rules that are based on file hashes"); + Logger.Write($"Returning {outputHashInfoProcessing.Count} file rules that are based on file hashes"); // Return the output HashSet return outputHashInfoProcessing; diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetSignerInfo.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetSignerInfo.cs index af0407f04..2e83926c0 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetSignerInfo.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/GetSignerInfo.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class GetSignerInfo + public static class GetSignerInfo { /// /// Takes an XML policy content as input and returns an array of Signer objects @@ -385,9 +385,9 @@ public static List Get(XmlDocument xmlContent) certRoot: certRootValue!, certPublisher: certPublisher, certIssuer: certIssuer, - certEKU: CertEKUs.ToArray(), + certEKU: [.. CertEKUs], certOemID: CertOemID, - fileAttribRef: ruleIds.ToArray(), + fileAttribRef: [.. ruleIds], fileAttrib: SignerFileAttributesProperty, signerScope: signerScope, isWHQL: IsWHQL, diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WldpQuerySecurityPolicy.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WldpQuerySecurityPolicy.cs index bcb917e4b..094c4a9e7 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WldpQuerySecurityPolicy.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/WldpQuerySecurityPolicy.cs @@ -22,7 +22,7 @@ public struct UNICODE_STRING public IntPtr Buffer; } - public class WldpQuerySecurityPolicyWrapper + public static class WldpQuerySecurityPolicyWrapper { [DllImport("Wldp.dll", CharSet = CharSet.Unicode)] internal static extern int WldpQuerySecurityPolicy( diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs index 46a9bac3b..28e03b22c 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class CloseEmptyXmlNodesSemantic + public static class CloseEmptyXmlNodesSemantic { /// @@ -44,8 +44,8 @@ to this public static void Close(string xmlFilePath) { // Define the base node names that should not be removed even if empty - string[] baseNodeNames = { "SiPolicy", "Rules", "EKUs", "FileRules", "Signers", "SigningScenarios", - "UpdatePolicySigners", "CiSigners", "HvciOptions", "BasePolicyID", "PolicyID" }; + string[] baseNodeNames = [ "SiPolicy", "Rules", "EKUs", "FileRules", "Signers", "SigningScenarios", + "UpdatePolicySigners", "CiSigners", "HvciOptions", "BasePolicyID", "PolicyID" ]; // Load the XML file XmlDocument xmlDoc = new(); diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SetCiPolicyInfo.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SetCiPolicyInfo.cs index 8a2fc17d8..06cf4a34f 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SetCiPolicyInfo.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SetCiPolicyInfo.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class SetCiPolicyInfo + public static class SetCiPolicyInfo { /// /// Configures a XML Code Integrity policy by modifying its details. diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SignerAndHashBuilder.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SignerAndHashBuilder.cs index 6058fcfe6..d2ff2f498 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SignerAndHashBuilder.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/SignerAndHashBuilder.cs @@ -49,20 +49,20 @@ public static class SignerAndHashBuilder public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, string incomingDataType = "MDEAH", string level = "Auto", bool publisherToHash = false) { // An array to store the Signers created with FilePublisher Level - List filePublisherSigners = []; + List filePublisherSigners = []; // An array to store the Signers created with Publisher Level - List publisherSigners = []; + List publisherSigners = []; // An array to store the FileAttributes created using Hash Level - List completeHashes = []; + List completeHashes = []; // Lists to separate data List signedFilePublisherData = []; List signedPublisherData = []; List unsignedData = []; - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Starting the data separation process."); + Logger.Write("BuildSignerAndHashObjects: Starting the data separation process."); // Data separation based on the level switch (level.ToLowerInvariant()) @@ -70,13 +70,13 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // If Hash level is used then add everything to the Unsigned data so Hash rules will be created for them case "hash": - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Using only Hash level."); + Logger.Write("BuildSignerAndHashObjects: Using only Hash level."); - foreach (var item in data) + foreach (Hashtable item in data) { - if (item == null) + if (item is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); + Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); } else { @@ -88,19 +88,15 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // If Publisher level is used then add all Signed data to the SignedPublisherData list and Unsigned data to the Hash list case "publisher": - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Using Publisher -> Hash levels."); + Logger.Write("BuildSignerAndHashObjects: Using Publisher -> Hash levels."); - foreach (var item in data) + foreach (Hashtable item in data) { - if (item == null) + if (item is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); + Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); } - else if ( - item.ContainsKey("SignatureStatus") && - item["SignatureStatus"] != null && - string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase) && - !publisherToHash) + else if (string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase) && !publisherToHash) { signedPublisherData.Add(item); } @@ -114,29 +110,26 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // Detect and separate FilePublisher, Publisher and Hash (Unsigned) data if the level is Auto or FilePublisher default: - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Using FilePublisher -> Publisher -> Hash levels."); + Logger.Write("BuildSignerAndHashObjects: Using FilePublisher -> Publisher -> Hash levels."); // Loop over each data - foreach (var item in data) + foreach (Hashtable item in data) { - if (item == null) + if (item is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); + Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); } // If the file's version is empty or it has no file attribute, then add it to the Publishers array // because FilePublisher rule cannot be created for it - else if ( - item.ContainsKey("SignatureStatus") && - item["SignatureStatus"] != null && - string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase)) { // Safely get values from the item and check for null or whitespace - bool hasNoFileAttributes = string.IsNullOrWhiteSpace(item.ContainsKey("OriginalFileName") ? item["OriginalFileName"]?.ToString() : null) && - string.IsNullOrWhiteSpace(item.ContainsKey("InternalName") ? item["InternalName"]?.ToString() : null) && - string.IsNullOrWhiteSpace(item.ContainsKey("FileDescription") ? item["FileDescription"]?.ToString() : null) && - string.IsNullOrWhiteSpace(item.ContainsKey("ProductName") ? item["ProductName"]?.ToString() : null); + bool hasNoFileAttributes = string.IsNullOrWhiteSpace(item["OriginalFileName"]?.ToString()) && + string.IsNullOrWhiteSpace(item["InternalName"]?.ToString()) && + string.IsNullOrWhiteSpace(item["FileDescription"]?.ToString()) && + string.IsNullOrWhiteSpace(item["ProductName"]?.ToString()); - bool hasNoFileVersion = string.IsNullOrWhiteSpace(item.ContainsKey("FileVersion") ? item["FileVersion"]?.ToString() : null); + bool hasNoFileVersion = string.IsNullOrWhiteSpace(item["FileVersion"]?.ToString()); if (hasNoFileAttributes || hasNoFileVersion) { @@ -147,7 +140,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s } else { - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: Passing Publisher rule to the hash array for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? item["FileName"] : item["File Name"])}"); + Logger.Write($"BuildSignerAndHashObjects: Passing Publisher rule to the hash array for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? item["FileName"] : item["File Name"])}"); // Add the current signed data to Unsigned data array so that Hash rules will be created for it instead unsignedData.Add(item); } @@ -165,16 +158,16 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s break; } - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: {signedFilePublisherData.Count} FilePublisher Rules."); - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: {signedPublisherData.Count} Publisher Rules."); - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: {unsignedData.Count} Hash Rules."); + Logger.Write($"BuildSignerAndHashObjects: {signedFilePublisherData.Count} FilePublisher Rules."); + Logger.Write($"BuildSignerAndHashObjects: {signedPublisherData.Count} Publisher Rules."); + Logger.Write($"BuildSignerAndHashObjects: {unsignedData.Count} Hash Rules."); - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Processing FilePublisher data."); + Logger.Write("BuildSignerAndHashObjects: Processing FilePublisher data."); - foreach (var signedData in signedFilePublisherData) + foreach (Hashtable signedData in signedFilePublisherData) { // Create a new FilePublisherSignerCreator object - WDACConfig.FilePublisherSignerCreator currentFilePublisherSigner = new(); + FilePublisherSignerCreator currentFilePublisherSigner = new(); // Get the certificate details of the current event data based on the incoming type, they can be stored under different names. // Safely casting the objects to a HashTable, returning null if the cast fails instead of throwing an exception. @@ -182,9 +175,9 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s ? (signedData["CorrelatedEventsData"] as Hashtable)?.Values : (signedData["SignerInfo"] as Hashtable)?.Values; - if (correlatedEventsDataValues == null) + if (correlatedEventsDataValues is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); + Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); } else { @@ -198,17 +191,17 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // For those files, the FilePublisher rule will be created with the file's leaf Certificate details only (Publisher certificate) // Safely access dictionary values and handle nulls - string? issuerTBSHash = corDataValue.ContainsKey("IssuerTBSHash") ? corDataValue["IssuerTBSHash"]?.ToString() : null; - string? publisherTBSHash = corDataValue.ContainsKey("PublisherTBSHash") ? corDataValue["PublisherTBSHash"]?.ToString() : null; + string? issuerTBSHash = corDataValue["IssuerTBSHash"]?.ToString(); + string? publisherTBSHash = corDataValue["PublisherTBSHash"]?.ToString(); // currentCorData to store the current SignerInfo/Correlated CertificateDetailsCreator? currentCorData; // Perform the check with null-safe values if (string.IsNullOrWhiteSpace(issuerTBSHash) && !string.IsNullOrWhiteSpace(publisherTBSHash)) { - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}, using the leaf certificate TBS hash instead"); + Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}, using the leaf certificate TBS hash instead"); - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( corDataValue["PublisherTBSHash"]!.ToString()!, corDataValue["PublisherName"]!.ToString()!, corDataValue["PublisherTBSHash"]!.ToString()!, @@ -218,7 +211,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s } else { - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( corDataValue["IssuerTBSHash"]!.ToString()!, corDataValue["IssuerName"]!.ToString()!, corDataValue["PublisherTBSHash"]!.ToString()!, @@ -232,26 +225,26 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s } } - #region Initialize properties with null-safe checks - string? fileVersionString = signedData.ContainsKey("FileVersion") ? signedData["FileVersion"]?.ToString() : null; - string? fileDescription = signedData.ContainsKey("FileDescription") ? signedData["FileDescription"]?.ToString() : null; - string? internalName = signedData.ContainsKey("InternalName") ? signedData["InternalName"]?.ToString() : null; - string? originalFileName = signedData.ContainsKey("OriginalFileName") ? signedData["OriginalFileName"]?.ToString() : null; - string? productName = signedData.ContainsKey("ProductName") ? signedData["ProductName"]?.ToString() : null; + #region Initialize properties + string? fileVersionString = signedData["FileVersion"]?.ToString(); + string? fileDescription = signedData["FileDescription"]?.ToString(); + string? internalName = signedData["InternalName"]?.ToString(); + string? originalFileName = signedData["OriginalFileName"]?.ToString(); + string? productName = signedData["ProductName"]?.ToString(); string? fileName = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("FileName") ? signedData["FileName"]?.ToString() : null) - : (signedData.ContainsKey("File Name") ? signedData["File Name"]?.ToString() : null); + ? (signedData["FileName"]?.ToString()) + : (signedData["File Name"]?.ToString()); string? sha256 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("SHA256") ? signedData["SHA256"]?.ToString() : null) - : (signedData.ContainsKey("SHA256 Hash") ? signedData["SHA256 Hash"]?.ToString() : null); + ? (signedData["SHA256"]?.ToString()) + : (signedData["SHA256 Hash"]?.ToString()); string? sha1 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("SHA1") ? signedData["SHA1"]?.ToString() : null) - : (signedData.ContainsKey("SHA1 Hash") ? signedData["SHA1 Hash"]?.ToString() : null); + ? (signedData["SHA1"]?.ToString()) + : (signedData["SHA1 Hash"]?.ToString()); _ = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("SiSigningScenario") ? signedData["SiSigningScenario"]?.ToString() : null) - : (signedData.ContainsKey("SI Signing Scenario") ? signedData["SI Signing Scenario"]?.ToString() : null); + ? (signedData["SiSigningScenario"]?.ToString()) + : (signedData["SI Signing Scenario"]?.ToString()); // Assign properties, handle null or missing values currentFilePublisherSigner.FileVersion = !string.IsNullOrWhiteSpace(fileVersionString) @@ -272,33 +265,33 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // Check if necessary details are not empty if (string.IsNullOrWhiteSpace(currentFilePublisherSigner.AuthenticodeSHA256)) { - WDACConfig.Logger.Write($"SHA256 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); + Logger.Write($"SHA256 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); } if (string.IsNullOrWhiteSpace(currentFilePublisherSigner.AuthenticodeSHA1)) { - WDACConfig.Logger.Write($"SHA1 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); + Logger.Write($"SHA1 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); } // Add the completed FilePublisherSigner to the list filePublisherSigners.Add(currentFilePublisherSigner); } - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Processing Publisher data."); + Logger.Write("BuildSignerAndHashObjects: Processing Publisher data."); - foreach (var signedData in signedPublisherData) + foreach (Hashtable signedData in signedPublisherData) { // Create a new PublisherSignerCreator object - WDACConfig.PublisherSignerCreator currentPublisherSigner = new(); + PublisherSignerCreator currentPublisherSigner = new(); // Get the certificate details of the current event data based on the incoming type, they can be stored under different names ICollection? correlatedEventsDataValues = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? (signedData?["CorrelatedEventsData"] as Hashtable)?.Values : (signedData?["SignerInfo"] as Hashtable)?.Values; - if (correlatedEventsDataValues == null) + if (correlatedEventsDataValues is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); + Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); } else { @@ -307,19 +300,19 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s { // Safely access dictionary values and handle nulls - string? issuerTBSHash = corDataValue.ContainsKey("IssuerTBSHash") ? corDataValue["IssuerTBSHash"]?.ToString() : null; - string? issuerName = corDataValue.ContainsKey("IssuerName") ? corDataValue["IssuerName"]?.ToString() : null; - string? publisherTBSHash = corDataValue.ContainsKey("PublisherTBSHash") ? corDataValue["PublisherTBSHash"]?.ToString() : null; - string? publisherName = corDataValue.ContainsKey("PublisherName") ? corDataValue["PublisherName"]?.ToString() : null; + string? issuerTBSHash = corDataValue["IssuerTBSHash"]?.ToString(); + string? issuerName = corDataValue["IssuerName"]?.ToString(); + string? publisherTBSHash = corDataValue["PublisherTBSHash"]?.ToString(); + string? publisherName = corDataValue["PublisherName"]?.ToString(); CertificateDetailsCreator? currentCorData; // Perform the check with null-safe values if (string.IsNullOrWhiteSpace(issuerTBSHash) && !string.IsNullOrWhiteSpace(publisherTBSHash)) { - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData!["FileName"] : signedData!["File Name"])}, using the leaf certificate TBS hash instead"); + Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData!["FileName"] : signedData!["File Name"])}, using the leaf certificate TBS hash instead"); // Create a new CertificateDetailsCreator object with the safely retrieved and used values - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( publisherTBSHash, publisherName!, publisherTBSHash, @@ -329,7 +322,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s else { // Create a new CertificateDetailsCreator object with the safely retrieved and used values - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( issuerTBSHash!, issuerName!, publisherTBSHash!, @@ -354,27 +347,27 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s publisherSigners.Add(currentPublisherSigner); } - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Processing Unsigned Hash data."); + Logger.Write("BuildSignerAndHashObjects: Processing Unsigned Hash data."); - foreach (var hashData in unsignedData) + foreach (Hashtable hashData in unsignedData) { - if (hashData == null) + if (hashData is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null hashData item."); + Logger.Write("BuildSignerAndHashObjects: Found a null hashData item."); continue; } string? sha256 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (hashData.ContainsKey("SHA256") ? hashData["SHA256"]?.ToString() : null) - : (hashData.ContainsKey("SHA256 Hash") ? hashData["SHA256 Hash"]?.ToString() : null); + ? (hashData["SHA256"]?.ToString()) + : (hashData["SHA256 Hash"]?.ToString()); string? sha1 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (hashData.ContainsKey("SHA1") ? hashData["SHA1"]?.ToString() : null) - : (hashData.ContainsKey("SHA1 Hash") ? hashData["SHA1 Hash"]?.ToString() : null); + ? (hashData["SHA1"]?.ToString()) + : (hashData["SHA1 Hash"]?.ToString()); string? fileName = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (hashData.ContainsKey("FileName") ? hashData["FileName"]?.ToString() : null) - : (hashData.ContainsKey("File Name") ? hashData["File Name"]?.ToString() : null); + ? (hashData["FileName"]?.ToString()) + : (hashData["File Name"]?.ToString()); int siSigningScenario = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? (hashData.ContainsKey("SiSigningScenario") ? int.Parse(hashData["SiSigningScenario"]?.ToString()!, CultureInfo.InvariantCulture) : 1) @@ -382,11 +375,11 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s if (string.IsNullOrWhiteSpace(sha256) || string.IsNullOrWhiteSpace(sha1) || string.IsNullOrWhiteSpace(fileName)) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: One or more necessary properties are null or empty in hashData."); + Logger.Write("BuildSignerAndHashObjects: One or more necessary properties are null or empty in hashData."); continue; } - completeHashes.Add(new WDACConfig.HashCreator( + completeHashes.Add(new HashCreator( sha256, sha1, fileName, @@ -394,7 +387,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s )); } - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Completed the process."); + Logger.Write("BuildSignerAndHashObjects: Completed the process."); return new FileBasedInfoPackage(filePublisherSigners, publisherSigners, completeHashes); } diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/UpdateHvciOptions.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/UpdateHvciOptions.cs index 045ab46db..7c258b822 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/UpdateHvciOptions.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/UpdateHvciOptions.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class UpdateHvciOptions + public static class UpdateHvciOptions { /// /// Sets the HVCI option to Strict or (2) in a policy XML file diff --git a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XmlFilePathExtractor.cs b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XmlFilePathExtractor.cs index 4ec8bb807..6da4fd13b 100644 --- a/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XmlFilePathExtractor.cs +++ b/WDACConfig/WDACConfig Module Files/C#/Shared Logics/XmlFilePathExtractor.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class XmlFilePathExtractor + public static class XmlFilePathExtractor { public static HashSet GetFilePaths(string xmlFilePath) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Build-WDACCertificate.psm1 b/WDACConfig/WDACConfig Module Files/Core/Build-WDACCertificate.psm1 index 254b61baa..fed429745 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Build-WDACCertificate.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Build-WDACCertificate.psm1 @@ -220,8 +220,14 @@ ValidityPeriod = Years [WDACConfig.Logger]::Write('Removing the certificate from the certificate store') $TheCert | Remove-Item -Force - [WDACConfig.Logger]::Write('Importing the certificate to the certificate store again, this time with the private key protected by VSM (Virtual Secure Mode - Virtualization Based Security)') - $null = Import-PfxCertificate -ProtectPrivateKey 'VSM' -FilePath (Join-Path -Path ([WDACConfig.GlobalVars]::UserConfigDir) -ChildPath "$FileName.pfx") -CertStoreLocation 'Cert:\CurrentUser\My' -Password $Password + try { + [WDACConfig.Logger]::Write('Importing the certificate to the certificate store again, this time with the private key protected by VSM (Virtual Secure Mode - Virtualization Based Security)') + $null = Import-PfxCertificate -ProtectPrivateKey 'VSM' -FilePath (Join-Path -Path ([WDACConfig.GlobalVars]::UserConfigDir) -ChildPath "$FileName.pfx") -CertStoreLocation 'Cert:\CurrentUser\My' -Password $Password + } + catch { + [WDACConfig.Logger]::Write('Importing the certificate to the certificate store again (VSM could not be be used due to lack of hardware virtualization support)') + $null = Import-PfxCertificate -FilePath (Join-Path -Path ([WDACConfig.GlobalVars]::UserConfigDir) -ChildPath "$FileName.pfx") -CertStoreLocation 'Cert:\CurrentUser\My' -Password $Password + } [WDACConfig.Logger]::Write('Saving the common name of the certificate to the User configurations') $null = [WDACConfig.UserConfiguration]::Set($null, $null, $null, $CommonName, $null, $null, $null, $null , $null) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index e44414535..4c4b66ec3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -767,10 +767,7 @@ Function Edit-SignedWDACConfig { [WDACConfig.CiRuleOptions]::Set($BasePolicyPath, [WDACConfig.CiRuleOptions+PolicyTemplate]::BaseISG, $null, $null, $null, $null, $null, $RequireEVSigners, $null, $null, $null) - # Configure required services for ISG authorization - [WDACConfig.Logger]::Write('Configuring required services for ISG authorization') - Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -NoNewWindow - Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -NoNewWindow + [WDACConfig.ConfigureISGServices]::Configure() } 'DefaultWindows' { $Name = 'DefaultWindows' diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index ab4a4dba3..23e63c84e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -683,9 +683,7 @@ Function Edit-WDACConfig { [WDACConfig.CiRuleOptions]::Set($BasePolicyPath, [WDACConfig.CiRuleOptions+PolicyTemplate]::BaseISG, $null, $null, $null, $null, $null, $RequireEVSigners, $null, $null, $null) - [WDACConfig.Logger]::Write('Configuring required services for ISG authorization') - Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -NoNewWindow - Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -NoNewWindow + [WDACConfig.ConfigureISGServices]::Configure() } 'DefaultWindows' { $Name = 'DefaultWindows' diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 78f7fcece..f185d2a74 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -90,7 +90,7 @@ Function New-WDACConfig { $CurrentStep++ Write-Progress -Id 7 -Activity 'Getting the recommended block rules' -Status "Step $CurrentStep/$TotalSteps" -PercentComplete ($CurrentStep / $TotalSteps * 100) - [WDACConfig.BasePolicyCreator]::GetBlockRules($StagingArea, $Deploy, $false) + [WDACConfig.BasePolicyCreator]::GetBlockRules($StagingArea, $Deploy) [System.IO.FileInfo]$FinalPolicyPath = Join-Path -Path $StagingArea -ChildPath "$Name.xml" @@ -149,7 +149,7 @@ Function New-WDACConfig { 'SignedAndReputable' { [WDACConfig.BasePolicyCreator]::BuildSignedAndReputable($StagingArea, $Audit, $LogSize, $Deploy, $RequireEVSigners, $EnableScriptEnforcement, $TestMode, $false) ; break } } } - 'GetUserModeBlockRules' { [WDACConfig.BasePolicyCreator]::GetBlockRules($StagingArea, $Deploy, $false) ; break } + 'GetUserModeBlockRules' { [WDACConfig.BasePolicyCreator]::GetBlockRules($StagingArea, $Deploy) ; break } 'GetDriverBlockRules' { if ($AutoUpdate) { [WDACConfig.BasePolicyCreator]::SetAutoUpdateDriverBlockRules(); break diff --git a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 index 1ba182165..62fc3bf7b 100644 --- a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 @@ -2,7 +2,7 @@ # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_module_manifests RootModule = 'WDACConfig.psm1' - ModuleVersion = '0.4.6' + ModuleVersion = '0.4.7' CompatiblePSEditions = @('Core') GUID = '79920947-efb5-48c1-a567-5b02ebe74793' Author = 'HotCakeX' diff --git a/WDACConfig/WDACConfig Module Files/WDACSimulation/Compare-SignerAndCertificate.psm1 b/WDACConfig/WDACConfig Module Files/WDACSimulation/Compare-SignerAndCertificate.psm1 index 40096571a..fb045e998 100644 --- a/WDACConfig/WDACConfig Module Files/WDACSimulation/Compare-SignerAndCertificate.psm1 +++ b/WDACConfig/WDACConfig Module Files/WDACSimulation/Compare-SignerAndCertificate.psm1 @@ -278,6 +278,9 @@ Function Compare-SignerAndCertificate { # Check if the matched signer has FileAttrib indicating that it was generated either with FilePublisher or SignedVersion level if ($Signer.FileAttrib) { + # Loop over each in the nodes, only those that belong to the Signer + # Which we retrieved based on the elements under the Signer + # And only keep those where the current file being examined has an equal or higher version than the version in those elements [System.Collections.Hashtable[]]$CandidateFileAttrib = foreach ($Attrib in $signer.FileAttrib.GetEnumerator()) { if ($ExtendedFileInfo.Version -ge [System.Version]::New($Attrib.Value.MinimumFileVersion)) { diff --git a/WDACConfig/WinUI3/.editorconfig b/WDACConfig/WinUI3/.editorconfig index 3ab9b4c35..487a9de7e 100644 --- a/WDACConfig/WinUI3/.editorconfig +++ b/WDACConfig/WinUI3/.editorconfig @@ -31,7 +31,7 @@ dotnet_diagnostic.CA1309.severity = error dotnet_diagnostic.CA1311.severity = error # CA1416: Validate platform compatibility -dotnet_diagnostic.CA1416.severity = error +dotnet_diagnostic.CA1416.severity = silent # CA5384: Do Not Use Digital Signature Algorithm (DSA) dotnet_diagnostic.CA5384.severity = error @@ -275,3 +275,69 @@ dotnet_diagnostic.CA2101.severity = error # IL2026: Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code dotnet_diagnostic.IL2026.severity = error + +# IDE0305: Simplify collection initialization +dotnet_diagnostic.IDE0305.severity = error + +# IDE0004: Remove Unnecessary Cast +dotnet_diagnostic.IDE0004.severity = error + +# IDE0017: Simplify object initialization +dotnet_diagnostic.IDE0017.severity = error + +# IDE0063: Use simple 'using' statement +dotnet_diagnostic.IDE0063.severity = error + +# CA1001: Types that own disposable fields should be disposable +dotnet_diagnostic.CA1001.severity = error + +# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +dotnet_diagnostic.CA1831.severity = error + +# CA5382: Use Secure Cookies In ASP.NET Core +dotnet_diagnostic.CA5382.severity = error + +# CA1063: Implement IDisposable Correctly +dotnet_diagnostic.CA1063.severity = error + +# CA1852: Seal internal types +dotnet_diagnostic.CA1852.severity = error + +# CA2011: Avoid infinite recursion +dotnet_diagnostic.CA2011.severity = error + +# CA2015: Do not define finalizers for types derived from MemoryManager +dotnet_diagnostic.CA2015.severity = error + +# CA2017: Parameter count mismatch +dotnet_diagnostic.CA2017.severity = error + +# CA5397: Do not use deprecated SslProtocols values +dotnet_diagnostic.CA5397.severity = error + +# CA5394: Do not use insecure randomness +dotnet_diagnostic.CA5394.severity = error + +# CA2207: Initialize value type static fields inline +dotnet_diagnostic.CA2207.severity = error + +# CA2219: Do not raise exceptions in finally clauses +dotnet_diagnostic.CA2219.severity = error + +# CA2259: 'ThreadStatic' only affects static fields +dotnet_diagnostic.CA2259.severity = error + +# CA5371: Use XmlReader for 'XmlSchema.Read()' +dotnet_diagnostic.CA5371.severity = error + +# CA5364: Do Not Use Deprecated Security Protocols +dotnet_diagnostic.CA5364.severity = error + +# CA1839: Use 'Environment.ProcessPath' +dotnet_diagnostic.CA1839.severity = error + +# CA2265: Do not compare Span to 'null' or 'default' +dotnet_diagnostic.CA2265.severity = error + +# CA1507: Use nameof to express symbol names +dotnet_diagnostic.CA1507.severity = error diff --git a/WDACConfig/WinUI3/App.xaml.cs b/WDACConfig/WinUI3/App.xaml.cs index 078f6e26a..0e341a642 100644 --- a/WDACConfig/WinUI3/App.xaml.cs +++ b/WDACConfig/WinUI3/App.xaml.cs @@ -2,9 +2,11 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; +using System.Xml; // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info. diff --git a/WDACConfig/WinUI3/AppControl Manager.csproj b/WDACConfig/WinUI3/AppControl Manager.csproj index a503ad4b2..cd4cd79e4 100644 --- a/WDACConfig/WinUI3/AppControl Manager.csproj +++ b/WDACConfig/WinUI3/AppControl Manager.csproj @@ -7,8 +7,7 @@ WDACConfig app.manifest x64;ARM64 - win-x64;win-arm64 - win10-x64;win10-arm64 + win-x64;win-arm64 win-$(Platform).pubxml true true @@ -65,7 +64,7 @@ - + @@ -119,20 +118,20 @@ An application that simplifies management of Application Control in Windows. https://github.com/HotCakeX/Harden-Windows-Security https://github.com/HotCakeX/Harden-Windows-Security - App Control,WDAC,WDACConfig + App Control,WDAC,WDACConfig,AppControl For Business, AppControl Manager https://github.com/HotCakeX/Harden-Windows-Security/releases False False SHA512 - True + False MSIXOutput\ True True Auto - x64 + x64|arm64 0 True AppControlManager diff --git a/WDACConfig/WinUI3/AppControl Manager.csproj.user b/WDACConfig/WinUI3/AppControl Manager.csproj.user index fe78e5290..dfe31853d 100644 --- a/WDACConfig/WinUI3/AppControl Manager.csproj.user +++ b/WDACConfig/WinUI3/AppControl Manager.csproj.user @@ -12,8 +12,9 @@ J:\Cloned Repositories\Harden-Windows-Security\WDACConfig\IconFullSize.png SideloadOnly False - x64 + x64|arm64 False + <_LastSelectedProfileId>J:\Cloned Repositories\Harden-Windows-Security\WDACConfig\WinUI3\Properties\PublishProfiles\win-x64.pubxml diff --git a/WDACConfig/WinUI3/Package.appxmanifest b/WDACConfig/WinUI3/Package.appxmanifest index 418265778..8c08cd62d 100644 --- a/WDACConfig/WinUI3/Package.appxmanifest +++ b/WDACConfig/WinUI3/Package.appxmanifest @@ -10,7 +10,7 @@ + Version="1.1.0.0" /> diff --git a/WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml.cs b/WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml.cs index 001a5b1ec..3d1339c10 100644 --- a/WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml.cs +++ b/WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml.cs @@ -3,7 +3,6 @@ using Microsoft.UI.Xaml.Controls; using System; using System.Collections.Generic; -using System.Linq; using static WDACConfig.CiRuleOptions; namespace WDACConfig.Pages @@ -20,7 +19,7 @@ public ConfigurePolicyRuleOptions() this.NavigationCacheMode = Microsoft.UI.Xaml.Navigation.NavigationCacheMode.Enabled; // Initialize the keys property with dictionary keys - PolicyRuleOptionsKeys = WDACConfig.CiRuleOptions.PolicyRuleOptionsActual.Keys.ToList(); + PolicyRuleOptionsKeys = [.. WDACConfig.CiRuleOptions.PolicyRuleOptionsActual.Keys]; // Call the method to generate SettingsCards dynamically GenerateSettingsCards(); @@ -187,7 +186,7 @@ private PolicyRuleOptions[] GetSelectedPolicyRuleOptions() } } - return selectedRules.ToArray(); + return [.. selectedRules]; } diff --git a/WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs b/WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs index 58eb11a0d..f5c4007a9 100644 --- a/WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs +++ b/WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs @@ -473,7 +473,7 @@ private async void RecommendedUserModeBlockRulesCreate_Click(object sender, Micr // Run the background operation using captured values await Task.Run(() => { - BasePolicyCreator.GetBlockRules(stagingArea, false, false); + BasePolicyCreator.GetBlockRules(stagingArea, false); }); } @@ -503,7 +503,7 @@ private async void RecommendedUserModeBlockRulesCreateAndDeploy_Click(object sen // Run the background operation using captured values await Task.Run(() => { - BasePolicyCreator.GetBlockRules(stagingArea, true, true); + BasePolicyCreator.GetBlockRules(stagingArea, true); }); diff --git a/WDACConfig/WinUI3/Shared Logics/AllCertificatesGrabber.cs b/WDACConfig/WinUI3/Shared Logics/AllCertificatesGrabber.cs index cfead2ddf..50c2ccc58 100644 --- a/WDACConfig/WinUI3/Shared Logics/AllCertificatesGrabber.cs +++ b/WDACConfig/WinUI3/Shared Logics/AllCertificatesGrabber.cs @@ -14,12 +14,12 @@ namespace WDACConfig { // a class to throw a custom exception when the certificate has HashMismatch - public class ExceptionHashMismatchInCertificate(string message, string functionName) : Exception($"{functionName}: {message}") + public sealed class ExceptionHashMismatchInCertificate(string message, string functionName) : Exception($"{functionName}: {message}") { } // Represents a signed CMS and its certificate chain - public class AllFileSigners(SignedCms signerCertificate, X509Chain certificateChain) + public sealed class AllFileSigners(SignedCms signerCertificate, X509Chain certificateChain) { public SignedCms Signer { get; } = signerCertificate; public X509Chain Chain { get; } = certificateChain; diff --git a/WDACConfig/WinUI3/Shared Logics/CertCNz.cs b/WDACConfig/WinUI3/Shared Logics/CertCNz.cs index c2c11ec25..87b880e48 100644 --- a/WDACConfig/WinUI3/Shared Logics/CertCNz.cs +++ b/WDACConfig/WinUI3/Shared Logics/CertCNz.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; @@ -9,7 +8,7 @@ namespace WDACConfig { // Argument completer and ValidateSet for CertCNs - public class CertCNz : IValidateSetValuesGenerator + public sealed class CertCNz : IValidateSetValuesGenerator { public string[] GetValidValues() { @@ -41,7 +40,7 @@ public string[] GetValidValues() } // Explicitly call ToArray() from Enumerable - return output.ToArray(); + return [.. output]; } } } diff --git a/WDACConfig/WinUI3/Shared Logics/CertificateHelper.cs b/WDACConfig/WinUI3/Shared Logics/CertificateHelper.cs index e9ed356d1..0ed73727e 100644 --- a/WDACConfig/WinUI3/Shared Logics/CertificateHelper.cs +++ b/WDACConfig/WinUI3/Shared Logics/CertificateHelper.cs @@ -8,11 +8,11 @@ namespace WDACConfig { // A class to throw a custom exception when the certificate collection cannot be obtained during WDAC Simulation - public class ExceptionFailedToGetCertificateCollection(string message, string functionName) : Exception($"{functionName}: {message}") + public sealed class ExceptionFailedToGetCertificateCollection(string message, string functionName) : Exception($"{functionName}: {message}") { } - public class CertificateHelper + public static class CertificateHelper { public static string GetTBSCertificate(X509Certificate2 cert) // Calculates the TBS value of a certificate diff --git a/WDACConfig/WinUI3/Shared Logics/CheckPolicyDeploymentStatus.cs b/WDACConfig/WinUI3/Shared Logics/CheckPolicyDeploymentStatus.cs index 86ec34eb0..dee045d52 100644 --- a/WDACConfig/WinUI3/Shared Logics/CheckPolicyDeploymentStatus.cs +++ b/WDACConfig/WinUI3/Shared Logics/CheckPolicyDeploymentStatus.cs @@ -7,7 +7,7 @@ namespace WDACConfig { - public class CheckPolicyDeploymentStatus + public static class CheckPolicyDeploymentStatus { /// @@ -25,7 +25,7 @@ public static bool IsDeployed(string policyXMLFile) var policies = CiToolHelper.GetPolicies(false, true, true); // Loop through each policy and add its ID to the HashSet - foreach (WDACConfig.CiPolicyInfo item in policies) + foreach (CiPolicyInfo item in policies) { _ = currentPolicyIDs.Add(item.PolicyID!); } diff --git a/WDACConfig/WinUI3/Shared Logics/CiToolHelper.cs b/WDACConfig/WinUI3/Shared Logics/CiToolHelper.cs index 747ca721e..58db82ec5 100644 --- a/WDACConfig/WinUI3/Shared Logics/CiToolHelper.cs +++ b/WDACConfig/WinUI3/Shared Logics/CiToolHelper.cs @@ -11,7 +11,7 @@ namespace WDACConfig { // Class to represent a policy with various attributes - public class CiPolicyInfo + public sealed class CiPolicyInfo { public string? PolicyID { get; set; } // Unique identifier for the policy public string? BasePolicyID { get; set; } // Identifier for the base policy @@ -71,7 +71,7 @@ public static Version Measure(string number) catch (Exception ex) { // Handle errors by printing an error message and returning a default version of 0.0.0.0 - WDACConfig.Logger.Write($"Error converting number to version: {ex.Message}"); + Logger.Write($"Error converting number to version: {ex.Message}"); return new Version(0, 0, 0, 0); } } @@ -205,7 +205,7 @@ public static void RemovePolicy(string policyId) if (process.ExitCode != 0) { - throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}"); + throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}. Output: {jsonOutput}"); } } @@ -256,7 +256,7 @@ public static void UpdatePolicy(string CipPath) if (process.ExitCode != 0) { - throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}"); + throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}. Output: {jsonOutput}"); } } @@ -291,7 +291,7 @@ public static void RefreshPolicy() if (process.ExitCode != 0) { - throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}"); + throw new InvalidOperationException($"Command execution failed with error code {process.ExitCode}. Output: {jsonOutput}"); } } diff --git a/WDACConfig/WinUI3/Shared Logics/ConfigureISGServices.cs b/WDACConfig/WinUI3/Shared Logics/ConfigureISGServices.cs new file mode 100644 index 000000000..03832fba4 --- /dev/null +++ b/WDACConfig/WinUI3/Shared Logics/ConfigureISGServices.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WDACConfig +{ + internal static class ConfigureISGServices + { + /// + /// Starts the AppIdTel and sets the appidsvc service to auto start + /// + public static void Configure() + { + Logger.Write("Configuring and starting the required ISG related services"); + + _ = PowerShellExecutor.ExecuteScript(""" +appidtel.exe start +sc.exe config appidsvc start=auto +"""); + + } + } +} diff --git a/WDACConfig/WinUI3/Shared Logics/Crypt32CertCN.cs b/WDACConfig/WinUI3/Shared Logics/Crypt32CertCN.cs index e90fb77ef..e006329cc 100644 --- a/WDACConfig/WinUI3/Shared Logics/Crypt32CertCN.cs +++ b/WDACConfig/WinUI3/Shared Logics/Crypt32CertCN.cs @@ -8,7 +8,7 @@ namespace WDACConfig { - public class CryptoAPI + public static class CryptoAPI { // Importing function from crypt32.dll to access certificate information // https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certgetnamestringa diff --git a/WDACConfig/WinUI3/Shared Logics/DeviceGuardInfo.cs b/WDACConfig/WinUI3/Shared Logics/DeviceGuardInfo.cs index 2a7fadb5e..d27a7a085 100644 --- a/WDACConfig/WinUI3/Shared Logics/DeviceGuardInfo.cs +++ b/WDACConfig/WinUI3/Shared Logics/DeviceGuardInfo.cs @@ -6,13 +6,13 @@ namespace WDACConfig { - public class DeviceGuardStatus + public sealed class DeviceGuardStatus { public uint? UsermodeCodeIntegrityPolicyEnforcementStatus { get; set; } public uint? CodeIntegrityPolicyEnforcementStatus { get; set; } } - public class DeviceGuardInfo + public static class DeviceGuardInfo { /// /// Get the Device Guard status information from the Win32_DeviceGuard WMI class diff --git a/WDACConfig/WinUI3/Shared Logics/DirectorySelector.cs b/WDACConfig/WinUI3/Shared Logics/DirectorySelector.cs index 53bf65821..ef3c11556 100644 --- a/WDACConfig/WinUI3/Shared Logics/DirectorySelector.cs +++ b/WDACConfig/WinUI3/Shared Logics/DirectorySelector.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; #nullable enable @@ -35,11 +34,11 @@ public static class DirectorySelector } while (true); // return null if no directories were selected or the array of selected directories if there are any - return programsPaths.Count > 0 ? programsPaths.ToArray() : null; + return programsPaths.Count > 0 ? [.. programsPaths] : null; } // Comparer for DirectoryInfo to ensure uniqueness and do it in a case-insensitive way - private class DirectoryInfoComparer : IEqualityComparer + private sealed class DirectoryInfoComparer : IEqualityComparer { public bool Equals(DirectoryInfo? x, DirectoryInfo? y) { diff --git a/WDACConfig/WinUI3/Shared Logics/DriveLetterMapper.cs b/WDACConfig/WinUI3/Shared Logics/DriveLetterMapper.cs index 8a8349140..9e87aa026 100644 --- a/WDACConfig/WinUI3/Shared Logics/DriveLetterMapper.cs +++ b/WDACConfig/WinUI3/Shared Logics/DriveLetterMapper.cs @@ -89,7 +89,7 @@ public static List GetGlobalRootDrives() // Get the mount point for the volume _ = GetVolumePathNamesForVolumeNameW(volume, sbMountPoint, max, ref lpcchReturnLength); // Get the device path for the volume - uint returnLength = QueryDosDevice(volume.Substring(4, volume.Length - 5), sbPathName, (int)max); + uint returnLength = QueryDosDevice(volume[4..^1], sbPathName, (int)max); // Check if the device path is found if (returnLength > 0) diff --git a/WDACConfig/WinUI3/Shared Logics/EventLogUtility.cs b/WDACConfig/WinUI3/Shared Logics/EventLogUtility.cs index ea9d82081..8bbbcf794 100644 --- a/WDACConfig/WinUI3/Shared Logics/EventLogUtility.cs +++ b/WDACConfig/WinUI3/Shared Logics/EventLogUtility.cs @@ -16,7 +16,7 @@ public static class EventLogUtility /// Size of the Code Integrity Operational Event Log public static void SetLogSize(ulong logSize = 0) { - WDACConfig.Logger.Write("Set-SetLogSize method started..."); + Logger.Write("Set-SetLogSize method started..."); string logName = "Microsoft-Windows-CodeIntegrity/Operational"; @@ -32,7 +32,7 @@ public static void SetLogSize(ulong logSize = 0) { if (currentLogMaxSize <= 10 * 1024 * 1024) { - WDACConfig.Logger.Write("Increasing the Code Integrity log size by 1MB because its current free space is less than 1MB."); + Logger.Write("Increasing the Code Integrity log size by 1MB because its current free space is less than 1MB."); logConfig.MaximumSizeInBytes = currentLogMaxSize + 1 * 1024 * 1024; logConfig.IsEnabled = true; logConfig.SaveChanges(); @@ -45,14 +45,14 @@ public static void SetLogSize(ulong logSize = 0) // To prevent from disabling the log or setting it to a very small size that is lower than its default size if (logSize > 1100 * 1024) { - WDACConfig.Logger.Write($"Setting Code Integrity log size to {logSize}."); + Logger.Write($"Setting Code Integrity log size to {logSize}."); logConfig.MaximumSizeInBytes = (long)logSize; logConfig.IsEnabled = true; logConfig.SaveChanges(); } else { - WDACConfig.Logger.Write("Provided log size is less than or equal to 1100 KB. No changes made."); + Logger.Write("Provided log size is less than or equal to 1100 KB. No changes made."); } } } diff --git a/WDACConfig/WinUI3/Shared Logics/FileDirectoryPathComparer.cs b/WDACConfig/WinUI3/Shared Logics/FileDirectoryPathComparer.cs index a3db9579d..f26324358 100644 --- a/WDACConfig/WinUI3/Shared Logics/FileDirectoryPathComparer.cs +++ b/WDACConfig/WinUI3/Shared Logics/FileDirectoryPathComparer.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class FileDirectoryPathComparer + public static class FileDirectoryPathComparer { /// /// Method that takes 2 arrays, one containing file paths and the other containing folder paths. diff --git a/WDACConfig/WinUI3/Shared Logics/FileSystemPicker.cs b/WDACConfig/WinUI3/Shared Logics/FileSystemPicker.cs index 6c0992509..c85555627 100644 --- a/WDACConfig/WinUI3/Shared Logics/FileSystemPicker.cs +++ b/WDACConfig/WinUI3/Shared Logics/FileSystemPicker.cs @@ -5,10 +5,9 @@ namespace WDACConfig { - public class FileSystemPicker + public static class FileSystemPicker { - /// /// Usage example /// All params are optional diff --git a/WDACConfig/WinUI3/Shared Logics/GetExtendedFileAttrib.cs b/WDACConfig/WinUI3/Shared Logics/GetExtendedFileAttrib.cs index 17979b426..6f8c7bb56 100644 --- a/WDACConfig/WinUI3/Shared Logics/GetExtendedFileAttrib.cs +++ b/WDACConfig/WinUI3/Shared Logics/GetExtendedFileAttrib.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class ExFileInfo + public sealed class ExFileInfo { // Constants used for encoding fallback and error handling private const string UnicodeFallbackCode = "04B0"; diff --git a/WDACConfig/WinUI3/Shared Logics/GetFilesFast.cs b/WDACConfig/WinUI3/Shared Logics/GetFilesFast.cs index 1fb43c0bb..89cf38804 100644 --- a/WDACConfig/WinUI3/Shared Logics/GetFilesFast.cs +++ b/WDACConfig/WinUI3/Shared Logics/GetFilesFast.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class FileUtility + public static class FileUtility { /// /// A flexible and fast method that can accept directory paths and file paths as input and return a list of FileInfo objects that are compliant with the WDAC policy. diff --git a/WDACConfig/WinUI3/Shared Logics/Initializer.cs b/WDACConfig/WinUI3/Shared Logics/Initializer.cs index 6671759fb..5c9a6f1d5 100644 --- a/WDACConfig/WinUI3/Shared Logics/Initializer.cs +++ b/WDACConfig/WinUI3/Shared Logics/Initializer.cs @@ -7,9 +7,14 @@ namespace WDACConfig { // Prepares the environment. It also runs commands that would otherwise run in the default constructor for the GlobalVars Class - public class Initializer + public static class Initializer { + /// /// These are the codes that were present in the GlobalVar class's default constructor but defining them as a separate method allows any errors thrown in them to be properly displayed in PowerShell instead of showing an error occurred in the default constructor of a class + /// + /// + /// + /// public static void Initialize() { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion") ?? throw new InvalidOperationException("Could not get the current Windows version from the registry")) diff --git a/WDACConfig/WinUI3/Shared Logics/Logging/LoggerInitializer.cs b/WDACConfig/WinUI3/Shared Logics/Logging/LoggerInitializer.cs index d40f28a62..c7b8c378c 100644 --- a/WDACConfig/WinUI3/Shared Logics/Logging/LoggerInitializer.cs +++ b/WDACConfig/WinUI3/Shared Logics/Logging/LoggerInitializer.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class LoggerInitializer + public static class LoggerInitializer { /// /// Gets the VerbosePreference, DebugPreference, and Host from the PowerShell session, each main cmdlet of the WDACConfig module diff --git a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs index 5e55aaa11..110097f57 100644 --- a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs +++ b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs @@ -11,7 +11,7 @@ namespace WDACConfig { // This class defines Hash entries for each file in the WDACConfig PowerShell module based on the cloud CSV - public class WDACConfigHashEntry(string? relativePath, string? fileName, string? fileHash, string? fileHashSHA3_512) + public sealed class WDACConfigHashEntry(string? relativePath, string? fileName, string? fileHash, string? fileHashSHA3_512) { public string? RelativePath { get; set; } = relativePath; public string? FileName { get; set; } = fileName; @@ -20,7 +20,7 @@ public class WDACConfigHashEntry(string? relativePath, string? fileName, string? } - public class AssertWDACConfigIntegrity + public static class AssertWDACConfigIntegrity { /// /// Hashes all of the files in the WDACConfig, download the cloud hashes, compares them with each other and report back hash mismatches @@ -34,9 +34,6 @@ public class AssertWDACConfigIntegrity string OutputFileName = "Hashes.csv"; string url = "https://raw.githubusercontent.com/HotCakeX/Harden-Windows-Security/main/WDACConfig/Utilities/Hashes.csv"; - // Parse the CSV content - List ParsedCSVList = []; - // Hash details of the current PowerShell files List CurrentFileHashes = []; @@ -46,7 +43,7 @@ public class AssertWDACConfigIntegrity string csvData = client.GetStringAsync(url).Result; // Parse the CSV content - ParsedCSVList = ParseCSV(csvData); + List ParsedCSVList = ParseCSV(csvData); // Get all of the files in the PowerShell module directory List files = WDACConfig.FileUtility.GetFilesFast([new DirectoryInfo(WDACConfig.GlobalVars.ModuleRootPath!)], null, ["*"]); @@ -171,24 +168,22 @@ private static List ParseCSV(string csvData) private static void ExportToCsv(string outputPath, List entries) { // Ensure we create a new file or overwrite an existing one - using (StreamWriter writer = new(outputPath, false, Encoding.UTF8)) - { - // Write the CSV header - writer.WriteLine(""" + using StreamWriter writer = new(outputPath, false, Encoding.UTF8); + // Write the CSV header + writer.WriteLine(""" "RelativePath","FileName","FileHash","FileHashSHA3_512" """); - // Write each entry in the list - foreach (var entry in entries) - { - string relativePath = EscapeCsv(entry.RelativePath); - string fileName = EscapeCsv(entry.FileName); - string fileHash = EscapeCsv(entry.FileHash); - string fileHashSHA3_512 = EscapeCsv(entry.FileHashSHA3_512); + // Write each entry in the list + foreach (var entry in entries) + { + string relativePath = EscapeCsv(entry.RelativePath); + string fileName = EscapeCsv(entry.FileName); + string fileHash = EscapeCsv(entry.FileHash); + string fileHashSHA3_512 = EscapeCsv(entry.FileHashSHA3_512); - // Write the CSV row - writer.WriteLine($"{relativePath},{fileName},{fileHash},{fileHashSHA3_512}"); - } + // Write the CSV row + writer.WriteLine($"{relativePath},{fileName},{fileHash},{fileHashSHA3_512}"); } } diff --git a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/BasePolicyCreator.cs b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/BasePolicyCreator.cs index ad1f66650..d5d074bf5 100644 --- a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/BasePolicyCreator.cs +++ b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/BasePolicyCreator.cs @@ -13,7 +13,7 @@ namespace WDACConfig { - public class BasePolicyCreator + public static class BasePolicyCreator { /// /// Creates scheduled task that keeps the Microsoft recommended driver block rules up to date on the system @@ -168,7 +168,7 @@ public static void SetAutoUpdateDriverBlockRules() } - public class DriverBlockListInfo + public sealed class DriverBlockListInfo { public string? Version { get; set; } public DateTime LastUpdated { get; set; } @@ -272,7 +272,7 @@ public static void DeployDriversBlockRules(string StagingArea) // Initialize the final destination of the SiPolicy file string SiPolicyFinalDestination; - if (systemDrive != null) + if (systemDrive is not null) { // Construct the final destination of the SiPolicy file SiPolicyFinalDestination = System.IO.Path.Combine(systemDrive, "Windows", "System32", "CodeIntegrity", "SiPolicy.p7b"); @@ -296,7 +296,7 @@ public static void DeployDriversBlockRules(string StagingArea) // Get the path of the SiPolicy file string[] SiPolicyPaths = System.IO.Directory.GetFiles(ZipExtractionDir, "SiPolicy_Enforced.p7b", System.IO.SearchOption.AllDirectories); - // Make sure to get only one file is there is more than one (which is unexpected) + // Make sure to get only one file if there is more than one (which is unexpected) string SiPolicyPath = SiPolicyPaths[0]; // If the SiPolicy file already exists, delete it @@ -308,13 +308,11 @@ public static void DeployDriversBlockRules(string StagingArea) // Move the SiPolicy file to the final destination, renaming it in the process File.Move(SiPolicyPath, SiPolicyFinalDestination); - Logger.Write("Refreshing the system WDAC policies"); CiToolHelper.RefreshPolicy(); Logger.Write("SiPolicy.p7b has been deployed and policies refreshed."); - Logger.Write("Displaying extra info about the Microsoft recommended Drivers block list"); _ = DriversBlockListInfoGathering(); } @@ -410,22 +408,20 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi policyName = "AllowMicrosoft"; } - // Path only used during staging area processing + // Paths only used during staging area processing string tempPolicyPath = Path.Combine(StagingArea, $"{policyName}.xml"); - string tempPolicyCIPPath = Path.Combine(StagingArea, $"{policyName}.cip"); + // Final Policy Path string finalPolicyPath = Path.Combine(GlobalVars.UserConfigDir, $"{policyName}.xml"); - GetBlockRules(StagingArea, deploy, false); - + // Get/Deploy the block rules + GetBlockRules(StagingArea, deploy); Logger.Write("Copying the AllowMicrosoft.xml from Windows directory to the Staging Area"); File.Copy(@"C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml", tempPolicyPath, true); - - Logger.Write("Resetting the policy ID and assigning policy name"); // Get the policy ID of the policy being created @@ -450,7 +446,6 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi if (deploy) { - Logger.Write("Converting the policy file to .CIP binary"); PolicyToCIPConverter.Convert(tempPolicyPath, tempPolicyCIPPath); @@ -460,7 +455,6 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi File.Copy(tempPolicyPath, finalPolicyPath, true); - } @@ -470,7 +464,7 @@ public static void BuildAllowMSFT(string StagingArea, bool IsAudit, ulong? LogSi /// It generates a XML file compliant with CI Policies Schema. /// /// - public static void GetBlockRules(string StagingArea, bool deploy, bool? deployAppControlSupplementalPolicy) + public static void GetBlockRules(string StagingArea, bool deploy) { string policyName = "Microsoft Windows Recommended User Mode BlockList"; @@ -510,23 +504,19 @@ public static void GetBlockRules(string StagingArea, bool deploy, bool? deployAp // Fix the elements userModeBlockRulesXML = FixMissingElements(userModeBlockRulesXML); - // Path only used during staging area processing + // Paths only used during staging area processing string tempPolicyPath = Path.Combine(StagingArea, $"{policyName}.xml"); - string tempPolicyCIPPath = Path.Combine(StagingArea, $"{policyName}.cip"); - // Save the XML content to a file userModeBlockRulesXML.Save(tempPolicyPath); - CiRuleOptions.Set(filePath: tempPolicyPath, rulesToAdd: [CiRuleOptions.PolicyRuleOptions.EnabledUpdatePolicyNoReboot, CiRuleOptions.PolicyRuleOptions.DisabledScriptEnforcement], rulesToRemove: [CiRuleOptions.PolicyRuleOptions.EnabledAuditMode, CiRuleOptions.PolicyRuleOptions.EnabledAdvancedBootOptionsMenu]); Logger.Write("Assigning policy name and resetting policy ID"); // Get the policyID of the policy being created - string policyID = SetCiPolicyInfo.Set(tempPolicyPath, true, policyName, null, null); - + _ = SetCiPolicyInfo.Set(tempPolicyPath, true, policyName, null, null); string finalPolicyPath = Path.Combine(GlobalVars.UserConfigDir, $"{policyName}.xml"); @@ -535,37 +525,41 @@ public static void GetBlockRules(string StagingArea, bool deploy, bool? deployAp Logger.Write($"Checking if the {policyName} policy is already deployed"); - + // Getting the list of the deployed base policies whose names match the policyName List CurrentlyDeployedBlockRules = CiToolHelper.GetPolicies(false, true, false).Where(policy => string.Equals(policy.FriendlyName, policyName, StringComparison.OrdinalIgnoreCase)).ToList(); + // If any policy was found if (CurrentlyDeployedBlockRules.Count > 0) { + // Get the ID of the policy string CurrentlyDeployedBlockRulesGUID = CurrentlyDeployedBlockRules.First().PolicyID!; Logger.Write($"{policyName} policy is already deployed, updating it using the same GUID which is {CurrentlyDeployedBlockRulesGUID}."); - PolicyEditor.EditGuids(CurrentlyDeployedBlockRulesGUID, new FileInfo(tempPolicyPath)); + // Swap the policyID in the current policy XML file with the one from the deployed policy + PolicyEditor.EditGuids(CurrentlyDeployedBlockRulesGUID, new FileInfo(tempPolicyPath)); } else { Logger.Write($"{policyName} policy is not deployed, deploying it now."); } + // Convert it to CIP PolicyToCIPConverter.Convert(tempPolicyPath, tempPolicyCIPPath); + // Deploy the CIP file CiToolHelper.UpdatePolicy(tempPolicyCIPPath); } File.Copy(tempPolicyPath, finalPolicyPath, true); - } /// - /// Creates SignedAndReputable WDAC policy which is based on AllowMicrosoft template policy. + /// Creates SignedAndReputable App Control policy which is based on AllowMicrosoft template policy. /// It uses ISG to authorize files with good reputation. /// /// @@ -591,15 +585,15 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo policyName = "SignedAndReputable"; } - // Path only used during staging area processing + // Paths only used during staging area processing string tempPolicyPath = Path.Combine(StagingArea, $"{policyName}.xml"); - string tempPolicyCIPPath = Path.Combine(StagingArea, $"{policyName}.cip"); + // Final policy XML path string finalPolicyPath = Path.Combine(GlobalVars.UserConfigDir, $"{policyName}.xml"); - GetBlockRules(StagingArea, deploy, false); - + // Get/Deploy the block rules + GetBlockRules(StagingArea, deploy); Logger.Write("Copying the AllowMicrosoft.xml from Windows directory to the Staging Area"); @@ -615,7 +609,6 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo TestMode: TestMode); - Logger.Write("Resetting the policy ID and assigning policy name"); // Get the policyID of the policy being created @@ -631,6 +624,7 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo if (deploy) { + ConfigureISGServices.Configure(); Logger.Write("Converting the policy file to .CIP binary"); @@ -641,7 +635,6 @@ public static void BuildSignedAndReputable(string StagingArea, bool IsAudit, ulo File.Copy(tempPolicyPath, finalPolicyPath, true); - } diff --git a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs index 0ec5372f4..01210bd07 100644 --- a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs +++ b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class SecurePolicySetting(object? Value, WDACConfig.WLDP_SECURE_SETTING_VALUE_TYPE ValueType, uint ValueSize, bool Status, int StatusCode) + public sealed class SecurePolicySetting(object? Value, WDACConfig.WLDP_SECURE_SETTING_VALUE_TYPE ValueType, uint ValueSize, bool Status, int StatusCode) { public object? Value { get; set; } = Value; public WDACConfig.WLDP_SECURE_SETTING_VALUE_TYPE ValueType { get; set; } = ValueType; @@ -14,7 +14,7 @@ public class SecurePolicySetting(object? Value, WDACConfig.WLDP_SECURE_SETTING_V public int StatusCode { get; set; } = StatusCode; } - public class GetCIPolicySetting + public static class GetCIPolicySetting { public static SecurePolicySetting Invoke(string provider, string key, string valueName) diff --git a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs index 1cad61749..45304fb89 100644 --- a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs +++ b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs @@ -7,7 +7,7 @@ namespace WDACConfig { - public class CiRuleOptions + public static class CiRuleOptions { public enum PolicyTemplate @@ -158,6 +158,39 @@ public enum PolicyRuleOptions #endregion + + /* + #region Policy Rule Options + // Fetches the latest policy rule options from the Schema file that exists on the system + + // Load the CI Schema content + XmlDocument schemaData = new(); + schemaData.Load(Path.Combine(WDACConfig.GlobalVars.CISchemaPath)); + + // Create a namespace manager to handle namespaces + XmlNamespaceManager nsManager = new(schemaData.NameTable); + nsManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); + + // Define the XPath query to fetch enumeration values + string xpathQuery = "//xs:simpleType[@name='OptionType']/xs:restriction/xs:enumeration/@value"; + + // Create a new HashSet to store the valid policy rule options + HashSet validOptions = new(StringComparer.OrdinalIgnoreCase); + + // Fetch enumeration values from the schema + XmlNodeList? optionNodes = schemaData.SelectNodes(xpathQuery, nsManager) ?? throw new InvalidOperationException("No valid options found in the Code Integrity Schema."); + + foreach (XmlNode node in optionNodes) + { + if (node.Value != null) + { + _ = validOptions.Add(node.Value); + } + } + #endregion + */ + + /// /// Configures the Policy rule options in a given XML file and sets the HVCI to Strict in the output XML file. /// It offers many ways to configure the policy rule options in a given XML file. @@ -410,10 +443,7 @@ public static void Set( // Always remove any existing rule options initially. The calculations determining which // Rules must be included in the policy are all made in this method. - if (RulesNode is not null) - { - RulesNode.RemoveAll(); - } + RulesNode?.RemoveAll(); // Convert the HashSet to a List and sort it diff --git a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/TestCiPolicy.cs b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/TestCiPolicy.cs index 89b4d5a4a..922137d03 100644 --- a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/TestCiPolicy.cs +++ b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/TestCiPolicy.cs @@ -24,7 +24,7 @@ public static class CiPolicyTest if (!string.IsNullOrEmpty(xmlFilePath)) { // Get the Code Integrity Schema file path - string schemaPath = WDACConfig.GlobalVars.CISchemaPath; + string schemaPath = GlobalVars.CISchemaPath; // Make sure the schema file exists if (!File.Exists(schemaPath)) diff --git a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/UserConfiguration.cs b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/UserConfiguration.cs index 675944c26..fc9e8b05c 100644 --- a/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/UserConfiguration.cs +++ b/WDACConfig/WinUI3/Shared Logics/Main Cmdlets/UserConfiguration.cs @@ -22,7 +22,7 @@ public partial class UserConfigurationContext : JsonSerializerContext // Represents an instance of the User configurations JSON settings file // Maintains the order of the properties when writing to the JSON file // Includes the methods for interacting with user configurations JSON file - public partial class UserConfiguration( + public sealed partial class UserConfiguration( string? signedPolicyPath, string? unsignedPolicyPath, string? signToolCustomPath, @@ -237,17 +237,17 @@ private static UserConfiguration ParseJson(string json) var root = doc.RootElement; return new UserConfiguration( - TryGetStringProperty(root, "SignedPolicyPath"), - TryGetStringProperty(root, "UnsignedPolicyPath"), - TryGetStringProperty(root, "SignToolCustomPath"), - TryGetStringProperty(root, "CertificateCommonName"), - TryGetStringProperty(root, "CertificatePath"), + TryGetStringProperty(root, nameof(SignedPolicyPath)), + TryGetStringProperty(root, nameof(UnsignedPolicyPath)), + TryGetStringProperty(root, nameof(SignToolCustomPath)), + TryGetStringProperty(root, nameof(CertificateCommonName)), + TryGetStringProperty(root, nameof(CertificatePath)), - TryGetGuidProperty(root, "StrictKernelPolicyGUID"), - TryGetGuidProperty(root, "StrictKernelNoFlightRootsPolicyGUID"), + TryGetGuidProperty(root, nameof(StrictKernelPolicyGUID)), + TryGetGuidProperty(root, nameof(StrictKernelNoFlightRootsPolicyGUID)), - TryGetDateTimeProperty(root, "LastUpdateCheck"), - TryGetDateTimeProperty(root, "StrictKernelModePolicyTimeOfDeployment") + TryGetDateTimeProperty(root, nameof(LastUpdateCheck)), + TryGetDateTimeProperty(root, nameof(StrictKernelModePolicyTimeOfDeployment)) ); static string? TryGetStringProperty(JsonElement root, string propertyName) diff --git a/WDACConfig/WinUI3/Shared Logics/MeowOpener.cs b/WDACConfig/WinUI3/Shared Logics/MeowOpener.cs index 3eb4052e5..31b02fcb8 100644 --- a/WDACConfig/WinUI3/Shared Logics/MeowOpener.cs +++ b/WDACConfig/WinUI3/Shared Logics/MeowOpener.cs @@ -46,12 +46,14 @@ internal struct MeowMemberCrypt // A public static method that returns a HashSet of strings. public static HashSet GetHashes(string SecurityCatalogFilePath) { - HashSet OutputHashSet = []; // Initializes a new HashSet to store the hashes. + // Initializes a new HashSet to store the hashes. + HashSet OutputHashSet = []; // Creates a new XmlDocument instance. XmlDocument PurrfectCatalogXMLDoc = new() { - XmlResolver = null // Disables the XML resolver for security reasons. + // Disables the XML resolver for security reasons. + XmlResolver = null }; IntPtr MainCryptProviderHandle = IntPtr.Zero; // Initializes the handle to zero. @@ -63,28 +65,36 @@ public static HashSet GetHashes(string SecurityCatalogFilePath) // Attempts to acquire a cryptographic context. if (!CryptAcquireContext(out MainCryptProviderHandle, string.Empty, string.Empty, 1, 4026531840)) { - // If the context is not acquired, the error can be captured (commented out). - // int lastWin32Error = Marshal.GetLastWin32Error(); + // If the context is not acquired, capture the error code. + int lastWin32Error = Marshal.GetLastWin32Error(); + Logger.Write($"CryptAcquireContext failed with error code: {lastWin32Error}"); } // Opens the catalog file and gets a handle to the catalog context. MeowLogHandle = WinTrust.CryptCATOpen(SecurityCatalogFilePath, 0, MainCryptProviderHandle, 0, 0); + if (MeowLogHandle == IntPtr.Zero) { - // If the handle is not obtained, the error can be captured (commented out). - // int lastWin32Error = Marshal.GetLastWin32Error(); + // If the handle is not obtained, capture the error code. + int lastWin32Error = Marshal.GetLastWin32Error(); + Logger.Write($"CryptCATOpen failed with error code: {lastWin32Error}"); } + // Creates an XML element to represent the catalog file. XmlElement catalogElement = PurrfectCatalogXMLDoc.CreateElement("MeowFile"); - _ = PurrfectCatalogXMLDoc.AppendChild(catalogElement); // Appends the element to the XML document. + + // Appends the element to the XML document. + _ = PurrfectCatalogXMLDoc.AppendChild(catalogElement); // Iterates through the catalog members. while ((KittyPointer = WinTrust.CryptCATEnumerateMember(MeowLogHandle, KittyPointer)) != IntPtr.Zero) { // Converts the pointer to a structure. MeowMemberCrypt member = Marshal.PtrToStructure(KittyPointer); - _ = OutputHashSet.Add(member.Hashes); // Adds the hashes to the HashSet. + + // Adds the hashes to the HashSet. + _ = OutputHashSet.Add(member.Hashes); } } finally @@ -96,7 +106,9 @@ public static HashSet GetHashes(string SecurityCatalogFilePath) if (MeowLogHandle != IntPtr.Zero) _ = WinTrust.CryptCATClose(MeowLogHandle); } - return OutputHashSet; // Returns the HashSet containing the hashes. + + // Returns the HashSet containing the hashes. + return OutputHashSet; } } } diff --git a/WDACConfig/WinUI3/Shared Logics/MoveUserModeToKernelMode.cs b/WDACConfig/WinUI3/Shared Logics/MoveUserModeToKernelMode.cs index 141a53ea9..82d265397 100644 --- a/WDACConfig/WinUI3/Shared Logics/MoveUserModeToKernelMode.cs +++ b/WDACConfig/WinUI3/Shared Logics/MoveUserModeToKernelMode.cs @@ -38,7 +38,7 @@ public static void Move(string filePath) XmlNode? signingScenario131 = null; // If there is no SigningScenarios block in the XML then exit the method - if (signingScenarios == null) + if (signingScenarios is null) { return; } @@ -59,13 +59,13 @@ public static void Move(string filePath) } // If both SigningScenario nodes were found - if (signingScenario12 != null && signingScenario131 != null) + if (signingScenario12 is not null && signingScenario131 is not null) { // Get AllowedSigners from SigningScenario with Value 12 XmlNode? allowedSigners12 = signingScenario12.SelectSingleNode("./sip:ProductSigners/sip:AllowedSigners", nsManager); // If AllowedSigners node exists in SigningScenario 12 and has child nodes - if (allowedSigners12 != null && allowedSigners12.HasChildNodes) + if (allowedSigners12 is not null && allowedSigners12.HasChildNodes) { // Loop through each child node of AllowedSigners in SigningScenario 12 foreach (XmlNode allowedSignerNode in allowedSigners12.ChildNodes) @@ -96,7 +96,7 @@ public static void Move(string filePath) XmlNode? allowedSigners131 = signingScenario131.SelectSingleNode("./sip:ProductSigners/sip:AllowedSigners", nsManager); // If the AllowedSigners node exists in SigningScenario 131 - if (allowedSigners131 != null) + if (allowedSigners131 is not null) { // Append the new AllowedSigner node to the AllowedSigners node in SigningScenario 131 _ = allowedSigners131.AppendChild(newAllowedSigner); diff --git a/WDACConfig/WinUI3/Shared Logics/PolicyFileSigningStatusDetection.cs b/WDACConfig/WinUI3/Shared Logics/PolicyFileSigningStatusDetection.cs index 05508d620..18f874b7b 100644 --- a/WDACConfig/WinUI3/Shared Logics/PolicyFileSigningStatusDetection.cs +++ b/WDACConfig/WinUI3/Shared Logics/PolicyFileSigningStatusDetection.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class PolicyFileSigningStatusDetection + public static class PolicyFileSigningStatusDetection { public enum SigningStatus diff --git a/WDACConfig/WinUI3/Shared Logics/PolicyMerger.cs b/WDACConfig/WinUI3/Shared Logics/PolicyMerger.cs index df4f1bb9a..8d09eff3d 100644 --- a/WDACConfig/WinUI3/Shared Logics/PolicyMerger.cs +++ b/WDACConfig/WinUI3/Shared Logics/PolicyMerger.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class PolicyMerger + public static class PolicyMerger { /// /// Merges multiple policies into a single policy using the PowerShell cmdlet of the ConfigCI module diff --git a/WDACConfig/WinUI3/Shared Logics/PolicyToCIPConverter.cs b/WDACConfig/WinUI3/Shared Logics/PolicyToCIPConverter.cs index 4dd40d512..71efee3ab 100644 --- a/WDACConfig/WinUI3/Shared Logics/PolicyToCIPConverter.cs +++ b/WDACConfig/WinUI3/Shared Logics/PolicyToCIPConverter.cs @@ -1,6 +1,6 @@ namespace WDACConfig { - public class PolicyToCIPConverter + public static class PolicyToCIPConverter { /// /// Converts a XML policy file to CIP binary file using the ConvertFrom-CIPolicy PowerShell cmdlet of the ConfigCI module diff --git a/WDACConfig/WinUI3/Shared Logics/PowerShellExecutor.cs b/WDACConfig/WinUI3/Shared Logics/PowerShellExecutor.cs index 213851642..a24449a2f 100644 --- a/WDACConfig/WinUI3/Shared Logics/PowerShellExecutor.cs +++ b/WDACConfig/WinUI3/Shared Logics/PowerShellExecutor.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class PowerShellExecutor + public static class PowerShellExecutor { /// /// Runs a PowerShell script and displays verbose and normal output in real-time. @@ -37,7 +37,7 @@ public class PowerShellExecutor outputCollection = []; outputCollection.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { var outputStream = (PSDataCollection)sender; var output = outputStream[args.Index]?.ToString(); @@ -49,7 +49,7 @@ public class PowerShellExecutor // Handle verbose output psInstance.Streams.Verbose.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { var verboseStream = (PSDataCollection)sender; Logger.Write($"Verbose: {verboseStream[args.Index].Message}"); @@ -59,7 +59,7 @@ public class PowerShellExecutor // Handle warning output psInstance.Streams.Warning.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { var warningStream = (PSDataCollection)sender; Logger.Write($"Warning: {warningStream[args.Index].Message}"); @@ -69,7 +69,7 @@ public class PowerShellExecutor // Handle error output and throw exception psInstance.Streams.Error.DataAdded += (sender, args) => { - if (sender != null) + if (sender is not null) { // Get the error details var errorStream = (PSDataCollection)sender; diff --git a/WDACConfig/WinUI3/Shared Logics/RemoveSupplementalSigners.cs b/WDACConfig/WinUI3/Shared Logics/RemoveSupplementalSigners.cs index 046e0514f..75d0eba94 100644 --- a/WDACConfig/WinUI3/Shared Logics/RemoveSupplementalSigners.cs +++ b/WDACConfig/WinUI3/Shared Logics/RemoveSupplementalSigners.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class CiPolicyHandler + public static class CiPolicyHandler { /// /// Removes the entire SupplementalPolicySigners block diff --git a/WDACConfig/WinUI3/Shared Logics/ScanLevelz.cs b/WDACConfig/WinUI3/Shared Logics/ScanLevelz.cs index 02862a5fd..69b0ddc41 100644 --- a/WDACConfig/WinUI3/Shared Logics/ScanLevelz.cs +++ b/WDACConfig/WinUI3/Shared Logics/ScanLevelz.cs @@ -5,7 +5,7 @@ namespace WDACConfig { // Argument tab auto-completion and ValidateSet for Levels and Fallbacks parameters in the entire module - public class ScanLevelz : IValidateSetValuesGenerator + public sealed class ScanLevelz : IValidateSetValuesGenerator { public string[] GetValidValues() { diff --git a/WDACConfig/WinUI3/Shared Logics/SnapBackGuarantee.cs b/WDACConfig/WinUI3/Shared Logics/SnapBackGuarantee.cs index e13942e96..327d43648 100644 --- a/WDACConfig/WinUI3/Shared Logics/SnapBackGuarantee.cs +++ b/WDACConfig/WinUI3/Shared Logics/SnapBackGuarantee.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class SnapBackGuarantee + public static class SnapBackGuarantee { /// diff --git a/WDACConfig/WinUI3/Shared Logics/SupplementalForSelf.cs b/WDACConfig/WinUI3/Shared Logics/SupplementalForSelf.cs index 33f0a391a..f64fbaaab 100644 --- a/WDACConfig/WinUI3/Shared Logics/SupplementalForSelf.cs +++ b/WDACConfig/WinUI3/Shared Logics/SupplementalForSelf.cs @@ -9,7 +9,7 @@ namespace WDACConfig { - internal class SupplementalForSelf + internal static class SupplementalForSelf { /// /// Deploys the Supplemental Policy that allows the Application to be allowed to run after deployment diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs index 7edf4b4a3..2823bd1f7 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs @@ -2,7 +2,7 @@ namespace WDACConfig { - public class CodeIntegrityHashes(string? sha1Page, string? sha256Page, string? sha1Authenticode, string? sha256Authenticode) + public sealed class CodeIntegrityHashes(string? sha1Page, string? sha256Page, string? sha1Authenticode, string? sha256Authenticode) { public string? SHA1Page { get; set; } = sha1Page; public string? SHA256Page { get; set; } = sha256Page; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs index e0777e36b..24ecf67ca 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs @@ -3,7 +3,7 @@ namespace WDACConfig { - public class CertificateDetailsCreator(string intermediateCertTBS, string intermediateCertName, string leafCertTBS, string leafCertName) + public sealed class CertificateDetailsCreator(string intermediateCertTBS, string intermediateCertName, string leafCertTBS, string leafCertName) { public string IntermediateCertTBS { get; set; } = intermediateCertTBS; public string IntermediateCertName { get; set; } = intermediateCertName; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateSignerCreator.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateSignerCreator.cs index 625c2615a..aba209704 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateSignerCreator.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/CertificateSignerCreator.cs @@ -2,7 +2,7 @@ namespace WDACConfig { - public class CertificateSignerCreator(string tbs, string signerName, int siSigningScenario) + public sealed class CertificateSignerCreator(string tbs, string signerName, int siSigningScenario) { public string TBS { get; set; } = tbs; public string SignerName { get; set; } = signerName; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainElement.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainElement.cs index 228ae3140..e7ac1844b 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainElement.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainElement.cs @@ -13,7 +13,7 @@ public enum CertificateType Leaf = 2 } - public class ChainElement(string subjectcn, string issuercn, DateTime notafter, string tbsvalue, X509Certificate2 certificate, CertificateType type) + public sealed class ChainElement(string subjectcn, string issuercn, DateTime notafter, string tbsvalue, X509Certificate2 certificate, CertificateType type) { public string SubjectCN { get; set; } = subjectcn; public string IssuerCN { get; set; } = issuercn; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainPackage.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainPackage.cs index 623ff6673..0854ee427 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainPackage.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/ChainPackage.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class ChainPackage(X509Chain certificatechain, SignedCms signedcms, ChainElement rootcertificate, + public sealed class ChainPackage(X509Chain certificatechain, SignedCms signedcms, ChainElement rootcertificate, ChainElement[]? intermediatecertificates, ChainElement? leafcertificate) { diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs index ce8c2c7e9..53505b2ad 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs @@ -5,7 +5,7 @@ namespace WDACConfig { // Used by the BuildSignerAndHashObjects method to store and return the output - public class FileBasedInfoPackage(List filepublishersigners, List publishersigners, List completehashes) + public sealed class FileBasedInfoPackage(List filepublishersigners, List publishersigners, List completehashes) { public List FilePublisherSigners { get; set; } = filepublishersigners; public List PublisherSigners { get; set; } = publishersigners; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs index 668fce85d..06527565c 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class FilePublisherSignerCreator + public sealed class FilePublisherSignerCreator { public List CertificateDetails { get; set; } public Version? FileVersion { get; set; } diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/HashCreator.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/HashCreator.cs index 3eb1de338..5461bb5ba 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/HashCreator.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/HashCreator.cs @@ -3,7 +3,7 @@ namespace WDACConfig { - public class HashCreator(string authenticodeSHA256, string authenticodeSHA1, string fileName, int siSigningScenario) + public sealed class HashCreator(string authenticodeSHA256, string authenticodeSHA1, string fileName, int siSigningScenario) { public string AuthenticodeSHA256 { get; set; } = authenticodeSHA256; public string AuthenticodeSHA1 { get; set; } = authenticodeSHA1; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/OpusSigner.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/OpusSigner.cs index 778756cac..4356d2d8e 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/OpusSigner.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/OpusSigner.cs @@ -3,7 +3,7 @@ namespace WDACConfig { - public class OpusSigner(string tbsHash, string subjectCN) + public sealed class OpusSigner(string tbsHash, string subjectCN) { public string TBSHash { get; set; } = tbsHash; public string SubjectCN { get; set; } = subjectCN; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PolicyHashObj.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PolicyHashObj.cs index 04633850b..87de7475c 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PolicyHashObj.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PolicyHashObj.cs @@ -5,7 +5,7 @@ // Used by WDAC Simulations namespace WDACConfig { - public class PolicyHashObj(string hashvalue, string hashtype, string filepathforhash) + public sealed class PolicyHashObj(string hashvalue, string hashtype, string filepathforhash) { // Adding public getters and setters for the properties public string HashValue { get; set; } = hashvalue; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PublisherSignerCreator.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PublisherSignerCreator.cs index 7728a55d3..b168ef4d2 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PublisherSignerCreator.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/PublisherSignerCreator.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class PublisherSignerCreator + public sealed class PublisherSignerCreator { public List CertificateDetails { get; set; } public string? FileName { get; set; } diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/Signer.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/Signer.cs index 7e60b8333..3bd370a56 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/Signer.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/Signer.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class Signer(string id, string name, string certRoot, string? certPublisher, string? certIssuer, + public sealed class Signer(string id, string name, string certRoot, string? certPublisher, string? certIssuer, string[]? certEKU, string? certOemID, string[]? fileAttribRef, Dictionary>? fileAttrib, string signerScope, bool isWHQL, bool isAllowed, bool hasEKU) diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationInput.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationInput.cs index 7996b7b96..9e1efc703 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationInput.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationInput.cs @@ -4,7 +4,7 @@ // Used by WDAC Simulations namespace WDACConfig { - public class SimulationInput(System.IO.FileInfo filepath, ChainPackage[] allfilesigners, Signer[] signerinfo, string[] ekuoids) + public sealed class SimulationInput(System.IO.FileInfo filepath, ChainPackage[] allfilesigners, Signer[] signerinfo, string[] ekuoids) { // Adding public getters and setters for the properties public System.IO.FileInfo FilePath { get; set; } = filepath; diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationOutput.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationOutput.cs index c374d79c8..3fa858cdd 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationOutput.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/SimulationOutput.cs @@ -4,7 +4,7 @@ namespace WDACConfig { // This class holds the details of the current file in the WDAC Simulation comparer - public class SimulationOutput( + public sealed class SimulationOutput( string path, string source, bool isAuthorized, diff --git a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/WinTrust.cs b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/WinTrust.cs index 10b966f35..d8a829e85 100644 --- a/WDACConfig/WinUI3/Shared Logics/Types And Definitions/WinTrust.cs +++ b/WDACConfig/WinUI3/Shared Logics/Types And Definitions/WinTrust.cs @@ -1,10 +1,12 @@ using System; using System.Runtime.InteropServices; +#nullable enable + namespace WDACConfig { // This class contains all of the WinTrust related functions and codes - internal partial class WinTrust + internal static partial class WinTrust { #region necessary logics for Authenticode and First Page hash calculation diff --git a/WDACConfig/WinUI3/Shared Logics/Variables/CILogIntel.cs b/WDACConfig/WinUI3/Shared Logics/Variables/CILogIntel.cs index 0c3621e22..e8d6eb702 100644 --- a/WDACConfig/WinUI3/Shared Logics/Variables/CILogIntel.cs +++ b/WDACConfig/WinUI3/Shared Logics/Variables/CILogIntel.cs @@ -5,14 +5,14 @@ namespace WDACConfig { // Application Control event tags intelligence - public class CILogIntel + public static class CILogIntel { // Requested and Validated Signing Level Mappings: https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-tag-explanations#requested-and-validated-signing-level public static readonly Dictionary ReqValSigningLevels = new() { { 0 , "Signing level hasn't yet been checked"}, { 1 , "File is unsigned or has no signature that passes the active policies"}, - { 2 , "Trusted by Windows Defender Application Control policy"}, + { 2 , "Trusted by App Control for Business policy"}, { 3 , "Developer signed code"}, { 4 , "Authenticode signed"}, { 5 , "Microsoft Store signed app PPL (Protected Process Light)"}, @@ -61,7 +61,7 @@ public class CILogIntel { 18 , "Custom signing level not met; returned if signature fails to match CISigners in UMCI."}, { 19 , "Binary is revoked based on its file hash."}, { 20 , "SHA1 cert hash's timestamp is missing or after valid cutoff as defined by Weak Crypto Policy."}, - { 21 , "Failed to pass Windows Defender Application Control policy."}, + { 21 , "Failed to pass App Control for Business policy."}, { 22 , "Not Isolated User Mode (IUM) signed; indicates an attempt to load a standard Windows binary into a virtualization-based security (VBS) trustlet."}, { 23 , "Invalid image hash. This error can indicate file corruption or a problem with the file's signature. Signatures using elliptic curve cryptography (ECC), such as ECDSA, return this VerificationError."}, { 24 , "Flight root not allowed; indicates trying to run flight-signed code on production OS."}, diff --git a/WDACConfig/WinUI3/Shared Logics/Variables/GlobalVars.cs b/WDACConfig/WinUI3/Shared Logics/Variables/GlobalVars.cs index f71196699..c3acd8863 100644 --- a/WDACConfig/WinUI3/Shared Logics/Variables/GlobalVars.cs +++ b/WDACConfig/WinUI3/Shared Logics/Variables/GlobalVars.cs @@ -19,7 +19,7 @@ public static class GlobalVars public const string MSFTRecommendedDriverBlockRulesURL = "https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/refs/heads/public/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules.md"; // Minimum required OS build number - public const decimal Requiredbuild = 22631.4169M; + public const decimal Requiredbuild = 26100.2033M; // Current OS build version public static decimal OSBuildNumber = Environment.OSVersion.Version.Build; diff --git a/WDACConfig/WinUI3/Shared Logics/VersionIncrementer.cs b/WDACConfig/WinUI3/Shared Logics/VersionIncrementer.cs index b4357e705..77efbf14c 100644 --- a/WDACConfig/WinUI3/Shared Logics/VersionIncrementer.cs +++ b/WDACConfig/WinUI3/Shared Logics/VersionIncrementer.cs @@ -4,7 +4,7 @@ namespace WDACConfig { - public class VersionIncrementer + public static class VersionIncrementer { public static Version AddVersion(Version version) // This can recursively increment an input version by one, and is aware of the max limit diff --git a/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetCertificateDetails.cs b/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetCertificateDetails.cs index ca2450bc8..f76c6590b 100644 --- a/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetCertificateDetails.cs +++ b/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetCertificateDetails.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class GetCertificateDetails + public static class GetCertificateDetails { /// /// A method to detect Root, Intermediate and Leaf certificates @@ -84,7 +84,7 @@ public static List Get(AllFileSigners[] completeSignatureResult) currentChain, // The entire current chain of the certificate currentSignedCms, // The entire current SignedCms object rootCertificate, - intermediateCertificates.ToArray(), + [.. intermediateCertificates], leafCertificate )); diff --git a/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs b/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs index bdc5a89cc..25e2b5444 100644 --- a/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs +++ b/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs @@ -16,10 +16,10 @@ public static class GetFileRuleOutput /// /// /// - public static HashSet Get(XmlDocument xml) + public static HashSet Get(XmlDocument xml) { // Create an empty HashSet to store the output - var outputHashInfoProcessing = new HashSet(); + var outputHashInfoProcessing = new HashSet(); // Get the namespace manager var nsmgr = new XmlNamespaceManager(xml.NameTable); @@ -27,11 +27,11 @@ public static class GetFileRuleOutput // Loop through each file rule in the XML file var fileRules = xml.SelectNodes("//si:FileRules/si:Allow", nsmgr); - if (fileRules != null) + if (fileRules is not null) { foreach (XmlNode fileRule in fileRules) { - if (fileRule.Attributes != null) + if (fileRule.Attributes is not null) { // Extract the hash value from the Hash attribute var hashValue = fileRule.Attributes["Hash"]?.InnerText; @@ -41,16 +41,16 @@ public static class GetFileRuleOutput if (!string.IsNullOrEmpty(friendlyName)) { // Extract the hash type from the FriendlyName attribute using regex - var hashTypeMatch = System.Text.RegularExpressions.Regex.Match(friendlyName, @".* (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", RegexOptions.IgnoreCase); + var hashTypeMatch = Regex.Match(friendlyName, @".* (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", RegexOptions.IgnoreCase); var hashType = hashTypeMatch.Success ? hashTypeMatch.Groups[1].Value : string.Empty; // Extract the file path from the FriendlyName attribute using regex - var filePathForHash = System.Text.RegularExpressions.Regex.Replace(friendlyName, @" (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", string.Empty, RegexOptions.IgnoreCase); + var filePathForHash = Regex.Replace(friendlyName, @" (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$", string.Empty, RegexOptions.IgnoreCase); // Add the extracted values of the current Hash rule to the output HashSet if (!string.IsNullOrEmpty(hashValue) && !string.IsNullOrEmpty(hashType) && !string.IsNullOrEmpty(filePathForHash)) { - _ = outputHashInfoProcessing.Add(new WDACConfig.PolicyHashObj(hashValue, hashType, filePathForHash)); + _ = outputHashInfoProcessing.Add(new PolicyHashObj(hashValue, hashType, filePathForHash)); } } } @@ -58,9 +58,9 @@ public static class GetFileRuleOutput } // Only keep the Authenticode Hash SHA256 - outputHashInfoProcessing = new HashSet(outputHashInfoProcessing.Where(obj => string.Equals(obj.HashType, "Hash Sha256", StringComparison.OrdinalIgnoreCase))); + outputHashInfoProcessing = new HashSet(outputHashInfoProcessing.Where(obj => string.Equals(obj.HashType, "Hash Sha256", StringComparison.OrdinalIgnoreCase))); - WDACConfig.Logger.Write($"Returning {outputHashInfoProcessing.Count} file rules that are based on file hashes"); + Logger.Write($"Returning {outputHashInfoProcessing.Count} file rules that are based on file hashes"); // Return the output HashSet return outputHashInfoProcessing; diff --git a/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetSignerInfo.cs b/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetSignerInfo.cs index af0407f04..2e83926c0 100644 --- a/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetSignerInfo.cs +++ b/WDACConfig/WinUI3/Shared Logics/WDAC Simulation/GetSignerInfo.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class GetSignerInfo + public static class GetSignerInfo { /// /// Takes an XML policy content as input and returns an array of Signer objects @@ -385,9 +385,9 @@ public static List Get(XmlDocument xmlContent) certRoot: certRootValue!, certPublisher: certPublisher, certIssuer: certIssuer, - certEKU: CertEKUs.ToArray(), + certEKU: [.. CertEKUs], certOemID: CertOemID, - fileAttribRef: ruleIds.ToArray(), + fileAttribRef: [.. ruleIds], fileAttrib: SignerFileAttributesProperty, signerScope: signerScope, isWHQL: IsWHQL, diff --git a/WDACConfig/WinUI3/Shared Logics/WldpQuerySecurityPolicy.cs b/WDACConfig/WinUI3/Shared Logics/WldpQuerySecurityPolicy.cs index bcb917e4b..094c4a9e7 100644 --- a/WDACConfig/WinUI3/Shared Logics/WldpQuerySecurityPolicy.cs +++ b/WDACConfig/WinUI3/Shared Logics/WldpQuerySecurityPolicy.cs @@ -22,7 +22,7 @@ public struct UNICODE_STRING public IntPtr Buffer; } - public class WldpQuerySecurityPolicyWrapper + public static class WldpQuerySecurityPolicyWrapper { [DllImport("Wldp.dll", CharSet = CharSet.Unicode)] internal static extern int WldpQuerySecurityPolicy( diff --git a/WDACConfig/WinUI3/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs b/WDACConfig/WinUI3/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs index 46a9bac3b..28e03b22c 100644 --- a/WDACConfig/WinUI3/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs +++ b/WDACConfig/WinUI3/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class CloseEmptyXmlNodesSemantic + public static class CloseEmptyXmlNodesSemantic { /// @@ -44,8 +44,8 @@ to this public static void Close(string xmlFilePath) { // Define the base node names that should not be removed even if empty - string[] baseNodeNames = { "SiPolicy", "Rules", "EKUs", "FileRules", "Signers", "SigningScenarios", - "UpdatePolicySigners", "CiSigners", "HvciOptions", "BasePolicyID", "PolicyID" }; + string[] baseNodeNames = [ "SiPolicy", "Rules", "EKUs", "FileRules", "Signers", "SigningScenarios", + "UpdatePolicySigners", "CiSigners", "HvciOptions", "BasePolicyID", "PolicyID" ]; // Load the XML file XmlDocument xmlDoc = new(); diff --git a/WDACConfig/WinUI3/Shared Logics/XMLOps/SetCiPolicyInfo.cs b/WDACConfig/WinUI3/Shared Logics/XMLOps/SetCiPolicyInfo.cs index 8a2fc17d8..06cf4a34f 100644 --- a/WDACConfig/WinUI3/Shared Logics/XMLOps/SetCiPolicyInfo.cs +++ b/WDACConfig/WinUI3/Shared Logics/XMLOps/SetCiPolicyInfo.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class SetCiPolicyInfo + public static class SetCiPolicyInfo { /// /// Configures a XML Code Integrity policy by modifying its details. diff --git a/WDACConfig/WinUI3/Shared Logics/XMLOps/SignerAndHashBuilder.cs b/WDACConfig/WinUI3/Shared Logics/XMLOps/SignerAndHashBuilder.cs index 6058fcfe6..d2ff2f498 100644 --- a/WDACConfig/WinUI3/Shared Logics/XMLOps/SignerAndHashBuilder.cs +++ b/WDACConfig/WinUI3/Shared Logics/XMLOps/SignerAndHashBuilder.cs @@ -49,20 +49,20 @@ public static class SignerAndHashBuilder public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, string incomingDataType = "MDEAH", string level = "Auto", bool publisherToHash = false) { // An array to store the Signers created with FilePublisher Level - List filePublisherSigners = []; + List filePublisherSigners = []; // An array to store the Signers created with Publisher Level - List publisherSigners = []; + List publisherSigners = []; // An array to store the FileAttributes created using Hash Level - List completeHashes = []; + List completeHashes = []; // Lists to separate data List signedFilePublisherData = []; List signedPublisherData = []; List unsignedData = []; - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Starting the data separation process."); + Logger.Write("BuildSignerAndHashObjects: Starting the data separation process."); // Data separation based on the level switch (level.ToLowerInvariant()) @@ -70,13 +70,13 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // If Hash level is used then add everything to the Unsigned data so Hash rules will be created for them case "hash": - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Using only Hash level."); + Logger.Write("BuildSignerAndHashObjects: Using only Hash level."); - foreach (var item in data) + foreach (Hashtable item in data) { - if (item == null) + if (item is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); + Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); } else { @@ -88,19 +88,15 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // If Publisher level is used then add all Signed data to the SignedPublisherData list and Unsigned data to the Hash list case "publisher": - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Using Publisher -> Hash levels."); + Logger.Write("BuildSignerAndHashObjects: Using Publisher -> Hash levels."); - foreach (var item in data) + foreach (Hashtable item in data) { - if (item == null) + if (item is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); + Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); } - else if ( - item.ContainsKey("SignatureStatus") && - item["SignatureStatus"] != null && - string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase) && - !publisherToHash) + else if (string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase) && !publisherToHash) { signedPublisherData.Add(item); } @@ -114,29 +110,26 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // Detect and separate FilePublisher, Publisher and Hash (Unsigned) data if the level is Auto or FilePublisher default: - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Using FilePublisher -> Publisher -> Hash levels."); + Logger.Write("BuildSignerAndHashObjects: Using FilePublisher -> Publisher -> Hash levels."); // Loop over each data - foreach (var item in data) + foreach (Hashtable item in data) { - if (item == null) + if (item is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); + Logger.Write("BuildSignerAndHashObjects: Found a null item in data."); } // If the file's version is empty or it has no file attribute, then add it to the Publishers array // because FilePublisher rule cannot be created for it - else if ( - item.ContainsKey("SignatureStatus") && - item["SignatureStatus"] != null && - string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(item["SignatureStatus"]?.ToString(), "Signed", StringComparison.OrdinalIgnoreCase)) { // Safely get values from the item and check for null or whitespace - bool hasNoFileAttributes = string.IsNullOrWhiteSpace(item.ContainsKey("OriginalFileName") ? item["OriginalFileName"]?.ToString() : null) && - string.IsNullOrWhiteSpace(item.ContainsKey("InternalName") ? item["InternalName"]?.ToString() : null) && - string.IsNullOrWhiteSpace(item.ContainsKey("FileDescription") ? item["FileDescription"]?.ToString() : null) && - string.IsNullOrWhiteSpace(item.ContainsKey("ProductName") ? item["ProductName"]?.ToString() : null); + bool hasNoFileAttributes = string.IsNullOrWhiteSpace(item["OriginalFileName"]?.ToString()) && + string.IsNullOrWhiteSpace(item["InternalName"]?.ToString()) && + string.IsNullOrWhiteSpace(item["FileDescription"]?.ToString()) && + string.IsNullOrWhiteSpace(item["ProductName"]?.ToString()); - bool hasNoFileVersion = string.IsNullOrWhiteSpace(item.ContainsKey("FileVersion") ? item["FileVersion"]?.ToString() : null); + bool hasNoFileVersion = string.IsNullOrWhiteSpace(item["FileVersion"]?.ToString()); if (hasNoFileAttributes || hasNoFileVersion) { @@ -147,7 +140,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s } else { - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: Passing Publisher rule to the hash array for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? item["FileName"] : item["File Name"])}"); + Logger.Write($"BuildSignerAndHashObjects: Passing Publisher rule to the hash array for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? item["FileName"] : item["File Name"])}"); // Add the current signed data to Unsigned data array so that Hash rules will be created for it instead unsignedData.Add(item); } @@ -165,16 +158,16 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s break; } - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: {signedFilePublisherData.Count} FilePublisher Rules."); - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: {signedPublisherData.Count} Publisher Rules."); - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: {unsignedData.Count} Hash Rules."); + Logger.Write($"BuildSignerAndHashObjects: {signedFilePublisherData.Count} FilePublisher Rules."); + Logger.Write($"BuildSignerAndHashObjects: {signedPublisherData.Count} Publisher Rules."); + Logger.Write($"BuildSignerAndHashObjects: {unsignedData.Count} Hash Rules."); - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Processing FilePublisher data."); + Logger.Write("BuildSignerAndHashObjects: Processing FilePublisher data."); - foreach (var signedData in signedFilePublisherData) + foreach (Hashtable signedData in signedFilePublisherData) { // Create a new FilePublisherSignerCreator object - WDACConfig.FilePublisherSignerCreator currentFilePublisherSigner = new(); + FilePublisherSignerCreator currentFilePublisherSigner = new(); // Get the certificate details of the current event data based on the incoming type, they can be stored under different names. // Safely casting the objects to a HashTable, returning null if the cast fails instead of throwing an exception. @@ -182,9 +175,9 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s ? (signedData["CorrelatedEventsData"] as Hashtable)?.Values : (signedData["SignerInfo"] as Hashtable)?.Values; - if (correlatedEventsDataValues == null) + if (correlatedEventsDataValues is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); + Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); } else { @@ -198,17 +191,17 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // For those files, the FilePublisher rule will be created with the file's leaf Certificate details only (Publisher certificate) // Safely access dictionary values and handle nulls - string? issuerTBSHash = corDataValue.ContainsKey("IssuerTBSHash") ? corDataValue["IssuerTBSHash"]?.ToString() : null; - string? publisherTBSHash = corDataValue.ContainsKey("PublisherTBSHash") ? corDataValue["PublisherTBSHash"]?.ToString() : null; + string? issuerTBSHash = corDataValue["IssuerTBSHash"]?.ToString(); + string? publisherTBSHash = corDataValue["PublisherTBSHash"]?.ToString(); // currentCorData to store the current SignerInfo/Correlated CertificateDetailsCreator? currentCorData; // Perform the check with null-safe values if (string.IsNullOrWhiteSpace(issuerTBSHash) && !string.IsNullOrWhiteSpace(publisherTBSHash)) { - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}, using the leaf certificate TBS hash instead"); + Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}, using the leaf certificate TBS hash instead"); - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( corDataValue["PublisherTBSHash"]!.ToString()!, corDataValue["PublisherName"]!.ToString()!, corDataValue["PublisherTBSHash"]!.ToString()!, @@ -218,7 +211,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s } else { - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( corDataValue["IssuerTBSHash"]!.ToString()!, corDataValue["IssuerName"]!.ToString()!, corDataValue["PublisherTBSHash"]!.ToString()!, @@ -232,26 +225,26 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s } } - #region Initialize properties with null-safe checks - string? fileVersionString = signedData.ContainsKey("FileVersion") ? signedData["FileVersion"]?.ToString() : null; - string? fileDescription = signedData.ContainsKey("FileDescription") ? signedData["FileDescription"]?.ToString() : null; - string? internalName = signedData.ContainsKey("InternalName") ? signedData["InternalName"]?.ToString() : null; - string? originalFileName = signedData.ContainsKey("OriginalFileName") ? signedData["OriginalFileName"]?.ToString() : null; - string? productName = signedData.ContainsKey("ProductName") ? signedData["ProductName"]?.ToString() : null; + #region Initialize properties + string? fileVersionString = signedData["FileVersion"]?.ToString(); + string? fileDescription = signedData["FileDescription"]?.ToString(); + string? internalName = signedData["InternalName"]?.ToString(); + string? originalFileName = signedData["OriginalFileName"]?.ToString(); + string? productName = signedData["ProductName"]?.ToString(); string? fileName = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("FileName") ? signedData["FileName"]?.ToString() : null) - : (signedData.ContainsKey("File Name") ? signedData["File Name"]?.ToString() : null); + ? (signedData["FileName"]?.ToString()) + : (signedData["File Name"]?.ToString()); string? sha256 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("SHA256") ? signedData["SHA256"]?.ToString() : null) - : (signedData.ContainsKey("SHA256 Hash") ? signedData["SHA256 Hash"]?.ToString() : null); + ? (signedData["SHA256"]?.ToString()) + : (signedData["SHA256 Hash"]?.ToString()); string? sha1 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("SHA1") ? signedData["SHA1"]?.ToString() : null) - : (signedData.ContainsKey("SHA1 Hash") ? signedData["SHA1 Hash"]?.ToString() : null); + ? (signedData["SHA1"]?.ToString()) + : (signedData["SHA1 Hash"]?.ToString()); _ = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (signedData.ContainsKey("SiSigningScenario") ? signedData["SiSigningScenario"]?.ToString() : null) - : (signedData.ContainsKey("SI Signing Scenario") ? signedData["SI Signing Scenario"]?.ToString() : null); + ? (signedData["SiSigningScenario"]?.ToString()) + : (signedData["SI Signing Scenario"]?.ToString()); // Assign properties, handle null or missing values currentFilePublisherSigner.FileVersion = !string.IsNullOrWhiteSpace(fileVersionString) @@ -272,33 +265,33 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s // Check if necessary details are not empty if (string.IsNullOrWhiteSpace(currentFilePublisherSigner.AuthenticodeSHA256)) { - WDACConfig.Logger.Write($"SHA256 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); + Logger.Write($"SHA256 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); } if (string.IsNullOrWhiteSpace(currentFilePublisherSigner.AuthenticodeSHA1)) { - WDACConfig.Logger.Write($"SHA1 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); + Logger.Write($"SHA1 is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData["FileName"] : signedData["File Name"])}"); } // Add the completed FilePublisherSigner to the list filePublisherSigners.Add(currentFilePublisherSigner); } - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Processing Publisher data."); + Logger.Write("BuildSignerAndHashObjects: Processing Publisher data."); - foreach (var signedData in signedPublisherData) + foreach (Hashtable signedData in signedPublisherData) { // Create a new PublisherSignerCreator object - WDACConfig.PublisherSignerCreator currentPublisherSigner = new(); + PublisherSignerCreator currentPublisherSigner = new(); // Get the certificate details of the current event data based on the incoming type, they can be stored under different names ICollection? correlatedEventsDataValues = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? (signedData?["CorrelatedEventsData"] as Hashtable)?.Values : (signedData?["SignerInfo"] as Hashtable)?.Values; - if (correlatedEventsDataValues == null) + if (correlatedEventsDataValues is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); + Logger.Write("BuildSignerAndHashObjects: correlatedEventsDataValues is null."); } else { @@ -307,19 +300,19 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s { // Safely access dictionary values and handle nulls - string? issuerTBSHash = corDataValue.ContainsKey("IssuerTBSHash") ? corDataValue["IssuerTBSHash"]?.ToString() : null; - string? issuerName = corDataValue.ContainsKey("IssuerName") ? corDataValue["IssuerName"]?.ToString() : null; - string? publisherTBSHash = corDataValue.ContainsKey("PublisherTBSHash") ? corDataValue["PublisherTBSHash"]?.ToString() : null; - string? publisherName = corDataValue.ContainsKey("PublisherName") ? corDataValue["PublisherName"]?.ToString() : null; + string? issuerTBSHash = corDataValue["IssuerTBSHash"]?.ToString(); + string? issuerName = corDataValue["IssuerName"]?.ToString(); + string? publisherTBSHash = corDataValue["PublisherTBSHash"]?.ToString(); + string? publisherName = corDataValue["PublisherName"]?.ToString(); CertificateDetailsCreator? currentCorData; // Perform the check with null-safe values if (string.IsNullOrWhiteSpace(issuerTBSHash) && !string.IsNullOrWhiteSpace(publisherTBSHash)) { - WDACConfig.Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData!["FileName"] : signedData!["File Name"])}, using the leaf certificate TBS hash instead"); + Logger.Write($"BuildSignerAndHashObjects: Intermediate Certificate TBS hash is empty for the file: {(string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? signedData!["FileName"] : signedData!["File Name"])}, using the leaf certificate TBS hash instead"); // Create a new CertificateDetailsCreator object with the safely retrieved and used values - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( publisherTBSHash, publisherName!, publisherTBSHash, @@ -329,7 +322,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s else { // Create a new CertificateDetailsCreator object with the safely retrieved and used values - currentCorData = new WDACConfig.CertificateDetailsCreator( + currentCorData = new CertificateDetailsCreator( issuerTBSHash!, issuerName!, publisherTBSHash!, @@ -354,27 +347,27 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s publisherSigners.Add(currentPublisherSigner); } - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Processing Unsigned Hash data."); + Logger.Write("BuildSignerAndHashObjects: Processing Unsigned Hash data."); - foreach (var hashData in unsignedData) + foreach (Hashtable hashData in unsignedData) { - if (hashData == null) + if (hashData is null) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Found a null hashData item."); + Logger.Write("BuildSignerAndHashObjects: Found a null hashData item."); continue; } string? sha256 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (hashData.ContainsKey("SHA256") ? hashData["SHA256"]?.ToString() : null) - : (hashData.ContainsKey("SHA256 Hash") ? hashData["SHA256 Hash"]?.ToString() : null); + ? (hashData["SHA256"]?.ToString()) + : (hashData["SHA256 Hash"]?.ToString()); string? sha1 = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (hashData.ContainsKey("SHA1") ? hashData["SHA1"]?.ToString() : null) - : (hashData.ContainsKey("SHA1 Hash") ? hashData["SHA1 Hash"]?.ToString() : null); + ? (hashData["SHA1"]?.ToString()) + : (hashData["SHA1 Hash"]?.ToString()); string? fileName = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) - ? (hashData.ContainsKey("FileName") ? hashData["FileName"]?.ToString() : null) - : (hashData.ContainsKey("File Name") ? hashData["File Name"]?.ToString() : null); + ? (hashData["FileName"]?.ToString()) + : (hashData["File Name"]?.ToString()); int siSigningScenario = string.Equals(incomingDataType, "MDEAH", StringComparison.OrdinalIgnoreCase) ? (hashData.ContainsKey("SiSigningScenario") ? int.Parse(hashData["SiSigningScenario"]?.ToString()!, CultureInfo.InvariantCulture) : 1) @@ -382,11 +375,11 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s if (string.IsNullOrWhiteSpace(sha256) || string.IsNullOrWhiteSpace(sha1) || string.IsNullOrWhiteSpace(fileName)) { - WDACConfig.Logger.Write("BuildSignerAndHashObjects: One or more necessary properties are null or empty in hashData."); + Logger.Write("BuildSignerAndHashObjects: One or more necessary properties are null or empty in hashData."); continue; } - completeHashes.Add(new WDACConfig.HashCreator( + completeHashes.Add(new HashCreator( sha256, sha1, fileName, @@ -394,7 +387,7 @@ public static FileBasedInfoPackage BuildSignerAndHashObjects(Hashtable[] data, s )); } - WDACConfig.Logger.Write("BuildSignerAndHashObjects: Completed the process."); + Logger.Write("BuildSignerAndHashObjects: Completed the process."); return new FileBasedInfoPackage(filePublisherSigners, publisherSigners, completeHashes); } diff --git a/WDACConfig/WinUI3/Shared Logics/XMLOps/UpdateHvciOptions.cs b/WDACConfig/WinUI3/Shared Logics/XMLOps/UpdateHvciOptions.cs index 045ab46db..7c258b822 100644 --- a/WDACConfig/WinUI3/Shared Logics/XMLOps/UpdateHvciOptions.cs +++ b/WDACConfig/WinUI3/Shared Logics/XMLOps/UpdateHvciOptions.cs @@ -5,7 +5,7 @@ namespace WDACConfig { - public class UpdateHvciOptions + public static class UpdateHvciOptions { /// /// Sets the HVCI option to Strict or (2) in a policy XML file diff --git a/WDACConfig/WinUI3/Shared Logics/XmlFilePathExtractor.cs b/WDACConfig/WinUI3/Shared Logics/XmlFilePathExtractor.cs index 4ec8bb807..6da4fd13b 100644 --- a/WDACConfig/WinUI3/Shared Logics/XmlFilePathExtractor.cs +++ b/WDACConfig/WinUI3/Shared Logics/XmlFilePathExtractor.cs @@ -6,7 +6,7 @@ namespace WDACConfig { - public class XmlFilePathExtractor + public static class XmlFilePathExtractor { public static HashSet GetFilePaths(string xmlFilePath) { diff --git a/WDACConfig/version.txt b/WDACConfig/version.txt index c0a1ac199..5546bd2c5 100644 --- a/WDACConfig/version.txt +++ b/WDACConfig/version.txt @@ -1 +1 @@ -0.4.6 \ No newline at end of file +0.4.7 \ No newline at end of file From 9fb938f03cb179af25fb00ce8a00190d6a4e5dc5 Mon Sep 17 00:00:00 2001 From: Violet Hansen Date: Thu, 17 Oct 2024 19:35:51 +0300 Subject: [PATCH 2/2] App Control Manager v.1.1.0.0 major features * The AppControl Simulation feature has been fully integrated into the AppControl Manager GUI, with rewritten components and improved arbitration logic. * A new Advanced Code Integrity section has been introduced in the AppControl Manager app, offering detailed insights into system integrity. * The SHA3-512 hashing algorithm is now used for hashing files in the WDACConfig module, enhancing security standards. * The repository's Extras folder has been removed; its PowerShell scripts are now embedded within corresponding Wiki articles, and all C# code previously in that directory has been integrated into the AppControl Manager app. * A new GitHub workflow has been added for enhanced security and transparency, allowing the AppControl Manager to be built directly from the source code and generate verified artifacts publicly on GitHub. This workflow uses cryptographic signatures to ensure that the AppControl Manager MSIX package in the release section is verifiably built from the repository's source code and that workflow will upload the package with verification details to the release. [Find more about the process in here](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations/using-artifact-attestations-to-establish-provenance-for-builds). * Keyboard navigation in the AppControl Manager app has been improved, enhancing the selection experience for UI elements. * The color pickers on the Logs page have been refined, with clearer distinctions between selected colors and their labels. * The main navigation in the AppControl Manager app now dynamically adapts to window width, automatically switching modes for optimal responsiveness. * Windows 11 version 24H2 introduces several new features, including support for the SHA-3 hashing algorithm, enhancements to CiTool.exe that display which policies are signed and which are not, and the ability to remove App Control policies without requiring a reboot. Due to these advancements, both the WDACConfig module and the AppControl Manager app will require Windows 11 24H2 or later. * Updated some internal [log names](https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-tag-explanations#requested-and-validated-signing-level) that were referring to "Windows Defender Application Control" to "App Control for Business" to match the new naming convention. * Improved code optimizations and applied best practices through the GitHub's CodeQL scans and detections. --- .../Build AppControl Manager MSIX Package.yml | 74 ++ .github/workflows/codeql.yml | 2 +- .gitignore | 10 +- .../.editorconfig | 0 .../WinUI3 => AppControl Manager}/App.xaml | 0 .../WinUI3 => AppControl Manager}/App.xaml.cs | 6 +- .../AppControl Manager.csproj | 37 +- .../AppControl Manager.sln | 8 - .../Assets/BadgeLogo.scale-100.png | Bin .../Assets/BadgeLogo.scale-125.png | Bin .../Assets/BadgeLogo.scale-150.png | Bin .../Assets/BadgeLogo.scale-200.png | Bin .../Assets/BadgeLogo.scale-400.png | Bin .../Assets/LargeTile.scale-100.png | Bin .../Assets/LargeTile.scale-125.png | Bin .../Assets/LargeTile.scale-150.png | Bin .../Assets/LargeTile.scale-200.png | Bin .../Assets/LargeTile.scale-400.png | Bin .../Assets/LockScreenLogo.scale-200.png | Bin .../Assets/SmallTile.scale-100.png | Bin .../Assets/SmallTile.scale-125.png | Bin .../Assets/SmallTile.scale-150.png | Bin .../Assets/SmallTile.scale-200.png | Bin .../Assets/SmallTile.scale-400.png | Bin .../Assets/SplashScreen.scale-100.png | Bin .../Assets/SplashScreen.scale-125.png | Bin .../Assets/SplashScreen.scale-150.png | Bin .../Assets/SplashScreen.scale-200.png | Bin .../Assets/SplashScreen.scale-400.png | Bin .../Assets/Square150x150Logo.scale-100.png | Bin .../Assets/Square150x150Logo.scale-125.png | Bin .../Assets/Square150x150Logo.scale-150.png | Bin .../Assets/Square150x150Logo.scale-200.png | Bin .../Assets/Square150x150Logo.scale-400.png | Bin ...go.altform-lightunplated_targetsize-16.png | Bin ...go.altform-lightunplated_targetsize-24.png | Bin ...o.altform-lightunplated_targetsize-256.png | Bin ...go.altform-lightunplated_targetsize-32.png | Bin ...go.altform-lightunplated_targetsize-48.png | Bin ...x44Logo.altform-unplated_targetsize-16.png | Bin ...44Logo.altform-unplated_targetsize-256.png | Bin ...x44Logo.altform-unplated_targetsize-32.png | Bin ...x44Logo.altform-unplated_targetsize-48.png | Bin .../Assets/Square44x44Logo.scale-100.png | Bin .../Assets/Square44x44Logo.scale-125.png | Bin .../Assets/Square44x44Logo.scale-150.png | Bin .../Assets/Square44x44Logo.scale-200.png | Bin .../Assets/Square44x44Logo.scale-400.png | Bin .../Assets/Square44x44Logo.targetsize-16.png | Bin .../Assets/Square44x44Logo.targetsize-24.png | Bin ...x44Logo.targetsize-24_altform-unplated.png | Bin .../Assets/Square44x44Logo.targetsize-256.png | Bin .../Assets/Square44x44Logo.targetsize-32.png | Bin .../Assets/Square44x44Logo.targetsize-48.png | Bin .../Assets/StoreLogo.backup.png | Bin .../Assets/StoreLogo.scale-100.png | Bin .../Assets/StoreLogo.scale-125.png | Bin .../Assets/StoreLogo.scale-150.png | Bin .../Assets/StoreLogo.scale-200.png | Bin .../Assets/StoreLogo.scale-400.png | Bin .../Assets/Wide310x150Logo.scale-100.png | Bin .../Assets/Wide310x150Logo.scale-125.png | Bin .../Assets/Wide310x150Logo.scale-150.png | Bin .../Assets/Wide310x150Logo.scale-200.png | Bin .../Assets/Wide310x150Logo.scale-400.png | Bin AppControl Manager/MainWindow.xaml | 117 +++ .../MainWindow.xaml.cs | 18 +- .../Package.appxmanifest | 7 +- .../Pages/ConfigurePolicyRuleOptions.xaml | 36 +- .../Pages/ConfigurePolicyRuleOptions.xaml.cs | 0 .../Pages/CreatePolicy.xaml | 10 +- .../Pages/CreatePolicy.xaml.cs | 0 .../Pages/GetCIHashes.xaml | 11 +- .../Pages/GetCIHashes.xaml.cs | 0 .../Pages/GetSecurePolicySettings.xaml | 15 +- .../Pages/GetSecurePolicySettings.xaml.cs | 0 .../Pages/GitHubDocumentation.xaml | 0 .../Pages/GitHubDocumentation.xaml.cs | 0 .../Pages/Logs.xaml | 23 +- .../Pages/Logs.xaml.cs | 0 .../Pages/MicrosoftDocumentation.xaml | 0 .../Pages/MicrosoftDocumentation.xaml.cs | 0 .../Pages/Settings.xaml | 67 +- .../Pages/Settings.xaml.cs | 0 AppControl Manager/Pages/Simulation.xaml | 185 +++++ AppControl Manager/Pages/Simulation.xaml.cs | 244 ++++++ .../SystemInformation/CodeIntegrityInfo.xaml | 65 ++ .../CodeIntegrityInfo.xaml.cs | 24 + .../SystemInformation/SystemInformation.xaml | 38 + .../SystemInformation.xaml.cs | 55 ++ .../ViewCurrentPolicies.xaml | 21 +- .../ViewCurrentPolicies.xaml.cs | 0 .../Properties/PublishProfiles/win-x64.pubxml | 1 + .../Properties/launchSettings.json | 0 .../AppControlManagerSupplementalPolicy.xml | 0 .../Shared Logics/AllCertificatesGrabber.cs | 0 .../Shared Logics/CertCNz.cs | 0 .../Shared Logics/CertificateHelper.cs | 0 .../CheckPolicyDeploymentStatus.cs | 49 ++ .../Shared Logics/CiPolicyUtility.cs | 0 .../Shared Logics/CiToolHelper.cs | 4 +- .../Shared Logics/CodeIntegrityInfo.cs | 118 +++ .../Shared Logics/ConfigureISGServices.cs | 8 +- .../Shared Logics/Crypt32CertCN.cs | 0 .../Shared Logics/DeviceGuardInfo.cs | 0 .../Shared Logics/DirectorySelector.cs | 0 .../Shared Logics/DriveLetterMapper.cs | 2 +- AppControl Manager/Shared Logics/EditGUIDs.cs | 29 + .../Shared Logics/EventLogUtility.cs | 0 .../FileDirectoryPathComparer.cs | 0 .../Shared Logics/FileSystemPicker.cs | 7 +- .../Shared Logics/GetExtendedFileAttrib.cs | 0 .../Shared Logics/GetFilesFast.cs | 12 +- .../Shared Logics/GetOpusData.cs | 0 .../Shared Logics/Initializer.cs | 0 .../Shared Logics/Logging/Logger.cs | 0 .../Logging/LoggerInitializer.cs | 0 .../Main Cmdlets/AssertWDACConfigIntegrity.cs | 27 +- .../Main Cmdlets/BasePolicyCreator.cs | 90 +- .../Main Cmdlets/GetCIPolicySetting.cs | 0 .../Main Cmdlets/GetCiFileHashes.cs | 0 .../Main Cmdlets/InvokeWDACSimulation.cs | 620 ++++++++++++++ .../Main Cmdlets/SetCiRuleOptions.cs | 28 +- .../Main Cmdlets/TestCiPolicy.cs | 0 .../Main Cmdlets/UserConfiguration.cs | 2 +- .../Shared Logics/MeowOpener.cs | 0 .../Shared Logics/MoveUserModeToKernelMode.cs | 80 ++ .../Shared Logics/PageHashCalc.cs | 0 .../PolicyFileSigningStatusDetection.cs | 20 +- .../Shared Logics/PolicyMerger.cs | 0 .../Shared Logics/PolicyToCIPConverter.cs | 0 .../Shared Logics/PowerShellExecutor.cs | 0 .../RemoveSupplementalSigners.cs | 32 +- .../Shared Logics/ScanLevelz.cs | 0 .../Shared Logics/SecureStringComparer.cs | 0 .../Shared Logics/SignToolHelper.cs | 0 .../Shared Logics/SnapBackGuarantee.cs | 0 .../Shared Logics/StagingArea.cs | 0 .../Shared Logics/SupplementalForSelf.cs | 32 +- .../AuthenticodePageHashes.cs | 0 .../CertificateDetailsCreator.cs | 0 .../CertificateSignerCreator.cs | 0 .../Types And Definitions/ChainElement.cs | 0 .../Types And Definitions/ChainPackage.cs | 0 .../CodeIntegrityPolicy.cs | 232 ++++++ .../FileBasedInfoPackage.cs | 0 .../FilePublisherSignerCreator.cs | 0 .../Types And Definitions/HashCreator.cs | 0 .../Types And Definitions/OpusSigner.cs | 0 .../Types And Definitions/PolicyHashObj.cs | 0 .../PublisherSignerCreator.cs | 0 .../Types And Definitions/Signer.cs | 8 +- .../Types And Definitions/SimulationInput.cs | 0 .../Types And Definitions/SimulationOutput.cs | 52 +- .../Types And Definitions/WinTrust.cs | 0 .../Shared Logics/Variables/CILogIntel.cs | 0 .../Shared Logics/Variables/GlobalVars.cs | 0 .../Shared Logics/VersionIncrementer.cs | 0 .../WDAC Simulation/Arbitrator.cs | 785 ++++++++++++++++++ .../WDAC Simulation/GetCertificateDetails.cs | 2 +- .../WDAC Simulation/GetFileRuleOutput.cs | 6 +- .../WDAC Simulation/GetSignerInfo.cs | 39 +- .../Shared Logics/WldpQuerySecurityPolicy.cs | 0 .../XMLOps/ClearCiPolicySemantic.cs | 77 ++ .../XMLOps/CloseEmptyXmlNodesSemantic.cs | 0 .../Shared Logics/XMLOps/Macros.cs | 166 ++++ .../XMLOps/NewCertificateSignerRules.cs | 111 +++ .../XMLOps/NewFilePublisherLevelRules.cs | 191 +++++ .../Shared Logics/XMLOps/NewHashLevelRules.cs | 136 +++ .../Shared Logics/XMLOps/NewPFNLevelRules.cs | 66 ++ .../XMLOps/NewPublisherLevelRules.cs | 138 +++ .../XMLOps/RemoveAllowElementsSemantic.cs | 107 +++ .../XMLOps/RemoveUnreferencedFileRuleRefs.cs | 53 ++ .../Shared Logics/XMLOps/SetCiPolicyInfo.cs | 107 +-- .../XMLOps/SignerAndHashBuilder.cs | 2 +- .../Shared Logics/XMLOps/UpdateHvciOptions.cs | 57 ++ .../Shared Logics/XmlFilePathExtractor.cs | 10 +- .../app.manifest | 0 .../exclusion.dic | 0 Extras/CodeIntegrity.cs | 80 -- Extras/Get-BlockedPackets.ps1 | 186 ----- Extras/Get-EventData.ps1 | 94 --- ...r Methods and Properties in PowerShell.ps1 | 102 --- Extras/OSVERSIONINFOEX.cs | 116 --- WDACConfig/Program.cs | 4 +- WDACConfig/Utilities/Hashes.csv | 130 +-- WDACConfig/Utilities/Invoke-WDACConfig.ps1 | 1 + .../.NETAssembliesToLoad.txt | 1 + .../ArgumentCompleterAttribute.cs | 3 +- .../C#/ArgumentCompleters/BasePolicyNamez.cs | 1 - .../CheckPolicyDeploymentStatus.cs | 40 +- .../C#/Shared Logics/CiToolHelper.cs | 4 +- .../C#/Shared Logics/CodeIntegrityInfo.cs | 118 +++ .../C#/Shared Logics/ConfigureISGServices.cs | 8 +- .../C#/Shared Logics/DriveLetterMapper.cs | 2 +- .../C#/Shared Logics/EditGUIDs.cs | 40 +- .../C#/Shared Logics/FileSystemPicker.cs | 7 +- .../C#/Shared Logics/GetFilesFast.cs | 12 +- .../Main Cmdlets/AssertWDACConfigIntegrity.cs | 27 +- .../Main Cmdlets/BasePolicyCreator.cs | 90 +- .../Main Cmdlets/InvokeWDACSimulation.cs | 597 +++++++++++++ .../Main Cmdlets/SetCiRuleOptions.cs | 28 +- .../Main Cmdlets/UserConfiguration.cs | 2 +- .../Shared Logics/MoveUserModeToKernelMode.cs | 123 +-- .../PolicyFileSigningStatusDetection.cs | 20 +- .../RemoveSupplementalSigners.cs | 32 +- .../C#/Shared Logics/SupplementalForSelf.cs | 32 +- .../CodeIntegrityPolicy.cs | 232 ++++++ .../Types And Definitions/Signer.cs | 8 +- .../Types And Definitions/SimulationOutput.cs | 52 +- .../WDAC Simulation/Arbitrator.cs | 785 ++++++++++++++++++ .../WDAC Simulation/GetCertificateDetails.cs | 2 +- .../WDAC Simulation/GetFileRuleOutput.cs | 6 +- .../WDAC Simulation/GetSignerInfo.cs | 39 +- .../XMLOps/ClearCiPolicySemantic.cs | 77 ++ .../C#/Shared Logics/XMLOps/Macros.cs | 166 ++++ .../XMLOps/NewCertificateSignerRules.cs | 111 +++ .../XMLOps/NewFilePublisherLevelRules.cs | 191 +++++ .../Shared Logics/XMLOps/NewHashLevelRules.cs | 136 +++ .../Shared Logics/XMLOps/NewPFNLevelRules.cs | 66 ++ .../XMLOps/NewPublisherLevelRules.cs | 138 +++ .../XMLOps/RemoveAllowElementsSemantic.cs | 107 +++ .../XMLOps/RemoveUnreferencedFileRuleRefs.cs | 53 ++ .../Shared Logics/XMLOps/SetCiPolicyInfo.cs | 107 +-- .../XMLOps/SignerAndHashBuilder.cs | 2 +- .../Shared Logics/XMLOps/UpdateHvciOptions.cs | 39 +- .../C#/Shared Logics/XmlFilePathExtractor.cs | 10 +- .../Core/Assert-WDACConfigIntegrity.psm1 | 25 +- .../Core/Build-WDACCertificate.psm1 | 7 +- .../Core/Confirm-WDACConfig.psm1 | 28 +- .../Core/ConvertTo-WDACPolicy.psm1 | 117 +-- .../Core/Deploy-SignedWDACConfig.psm1 | 18 +- .../Core/Edit-SignedWDACConfig.psm1 | 54 +- .../Core/Edit-WDACConfig.psm1 | 54 +- .../Core/Get-CIPolicySetting.psm1 | 3 +- .../Core/Get-CiFileHashes.psm1 | 7 +- .../Core/Invoke-WDACSimulation.psm1 | 661 ++------------- .../Core/New-DenyWDACConfig.psm1 | 33 +- .../Core/New-KernelModeWDACConfig.psm1 | 26 +- .../Core/New-SupplementalWDACConfig.psm1 | 44 +- .../Core/New-WDACConfig.psm1 | 32 +- .../Core/Remove-CommonWDACConfig.psm1 | 19 +- .../Core/Remove-WDACConfig.psm1 | 15 +- .../Core/Set-CommonWDACConfig.psm1 | 1 - .../Core/Test-CiPolicy.psm1 | 1 - .../Help/ConvertTo-WDACPolicy.md | 2 +- .../Help/ConvertTo-WDACPolicy.xml | 8 +- .../Public/Write-ColorfulText.psm1 | 14 +- .../Shared/Get-KernelModeDrivers.psm1 | 2 - .../Shared/Get-KernelModeDriversAudit.psm1 | 1 - .../Shared/Get-SignTool.psm1 | 1 - .../Shared/Receive-CodeIntegrityLogs.psm1 | 1 - .../Shared/Set-LogPropertiesVisibility.psm1 | 1 - .../Shared/Test-ECCSignedFiles.psm1 | 16 +- .../Shared/Test-KernelProtectedFiles.psm1 | 1 - .../WDACConfig Module Files/WDACConfig.psm1 | 13 - .../Compare-SignerAndCertificate.psm1 | 613 -------------- .../XMLOps/Checkpoint-Macros.psm1 | 105 --- .../XMLOps/Clear-CiPolicy_Semantic.psm1 | 64 -- .../XMLOps/Compare-CorrelatedData.psm1 | 1 - .../XMLOps/New-CertificateSignerRules.psm1 | 117 --- .../XMLOps/New-FilePublisherLevelRules.psm1 | 178 ---- .../XMLOps/New-HashLevelRules.psm1 | 129 --- .../XMLOps/New-Macros.psm1 | 1 - .../XMLOps/New-PFNLevelRules.psm1 | 64 -- .../XMLOps/New-PublisherLevelRules.psm1 | 135 --- .../XMLOps/Optimize-MDECSVData.psm1 | 1 - .../XMLOps/Remove-AllowElements_Semantic.psm1 | 152 ---- .../Remove-UnreferencedFileRuleRefs.psm1 | 46 - WDACConfig/WDACConfig.code-workspace | 1 - WDACConfig/WDACConfig.csproj | 6 +- .../WinUI3/AppControl Manager.csproj.user | 54 -- WDACConfig/WinUI3/MainWindow.xaml | 75 -- WDACConfig/WinUI3/Pages/Home.xaml | 14 - WDACConfig/WinUI3/Pages/Home.xaml.cs | 18 - .../PublishProfiles/win-arm64.pubxml | 13 - .../CheckPolicyDeploymentStatus.cs | 67 -- WDACConfig/WinUI3/Shared Logics/EditGUIDs.cs | 43 - .../Shared Logics/MoveUserModeToKernelMode.cs | 121 --- .../Shared Logics/XMLOps/UpdateHvciOptions.cs | 76 -- WDACConfig/version.txt | 2 +- Wiki posts/Miscellaneous/Event Viewer.md | 106 ++- Wiki posts/Miscellaneous/Group Policy.md | 120 ++- ...DAC, App Control for Business, Policies.md | 1 + 284 files changed, 7543 insertions(+), 4791 deletions(-) create mode 100644 .github/workflows/Build AppControl Manager MSIX Package.yml rename {WDACConfig/WinUI3 => AppControl Manager}/.editorconfig (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/App.xaml (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/App.xaml.cs (94%) rename {WDACConfig/WinUI3 => AppControl Manager}/AppControl Manager.csproj (88%) rename {WDACConfig/WinUI3 => AppControl Manager}/AppControl Manager.sln (69%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/BadgeLogo.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/BadgeLogo.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/BadgeLogo.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/BadgeLogo.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/BadgeLogo.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/LargeTile.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/LargeTile.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/LargeTile.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/LargeTile.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/LargeTile.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/LockScreenLogo.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SmallTile.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SmallTile.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SmallTile.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SmallTile.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SmallTile.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SplashScreen.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SplashScreen.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SplashScreen.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SplashScreen.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/SplashScreen.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square150x150Logo.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square150x150Logo.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square150x150Logo.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square150x150Logo.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square150x150Logo.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-lightunplated_targetsize-16.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-lightunplated_targetsize-24.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-lightunplated_targetsize-256.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-lightunplated_targetsize-32.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-lightunplated_targetsize-48.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-unplated_targetsize-16.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-unplated_targetsize-256.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-unplated_targetsize-32.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.altform-unplated_targetsize-48.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.targetsize-16.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.targetsize-24.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.targetsize-24_altform-unplated.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.targetsize-256.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.targetsize-32.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Square44x44Logo.targetsize-48.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/StoreLogo.backup.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/StoreLogo.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/StoreLogo.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/StoreLogo.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/StoreLogo.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/StoreLogo.scale-400.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Wide310x150Logo.scale-100.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Wide310x150Logo.scale-125.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Wide310x150Logo.scale-150.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Wide310x150Logo.scale-200.png (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Assets/Wide310x150Logo.scale-400.png (100%) create mode 100644 AppControl Manager/MainWindow.xaml rename {WDACConfig/WinUI3 => AppControl Manager}/MainWindow.xaml.cs (79%) rename {WDACConfig/WinUI3 => AppControl Manager}/Package.appxmanifest (81%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/ConfigurePolicyRuleOptions.xaml (94%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/ConfigurePolicyRuleOptions.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/CreatePolicy.xaml (97%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/CreatePolicy.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/GetCIHashes.xaml (79%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/GetCIHashes.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/GetSecurePolicySettings.xaml (79%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/GetSecurePolicySettings.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/GitHubDocumentation.xaml (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/GitHubDocumentation.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/Logs.xaml (83%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/Logs.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/MicrosoftDocumentation.xaml (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/MicrosoftDocumentation.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/Settings.xaml (92%) rename {WDACConfig/WinUI3 => AppControl Manager}/Pages/Settings.xaml.cs (100%) create mode 100644 AppControl Manager/Pages/Simulation.xaml create mode 100644 AppControl Manager/Pages/Simulation.xaml.cs create mode 100644 AppControl Manager/Pages/SystemInformation/CodeIntegrityInfo.xaml create mode 100644 AppControl Manager/Pages/SystemInformation/CodeIntegrityInfo.xaml.cs create mode 100644 AppControl Manager/Pages/SystemInformation/SystemInformation.xaml create mode 100644 AppControl Manager/Pages/SystemInformation/SystemInformation.xaml.cs rename {WDACConfig/WinUI3/Pages => AppControl Manager/Pages/SystemInformation}/ViewCurrentPolicies.xaml (89%) rename {WDACConfig/WinUI3/Pages => AppControl Manager/Pages/SystemInformation}/ViewCurrentPolicies.xaml.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Properties/PublishProfiles/win-x64.pubxml (92%) rename {WDACConfig/WinUI3 => AppControl Manager}/Properties/launchSettings.json (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Resources/AppControlManagerSupplementalPolicy.xml (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/AllCertificatesGrabber.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/CertCNz.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/CertificateHelper.cs (100%) create mode 100644 AppControl Manager/Shared Logics/CheckPolicyDeploymentStatus.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/CiPolicyUtility.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/CiToolHelper.cs (99%) create mode 100644 AppControl Manager/Shared Logics/CodeIntegrityInfo.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/ConfigureISGServices.cs (75%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Crypt32CertCN.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/DeviceGuardInfo.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/DirectorySelector.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/DriveLetterMapper.cs (98%) create mode 100644 AppControl Manager/Shared Logics/EditGUIDs.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/EventLogUtility.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/FileDirectoryPathComparer.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/FileSystemPicker.cs (97%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/GetExtendedFileAttrib.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/GetFilesFast.cs (88%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/GetOpusData.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Initializer.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Logging/Logger.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Logging/LoggerInitializer.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/AssertWDACConfigIntegrity.cs (92%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/BasePolicyCreator.cs (89%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/GetCIPolicySetting.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/GetCiFileHashes.cs (100%) create mode 100644 AppControl Manager/Shared Logics/Main Cmdlets/InvokeWDACSimulation.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/SetCiRuleOptions.cs (95%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/TestCiPolicy.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Main Cmdlets/UserConfiguration.cs (99%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/MeowOpener.cs (100%) create mode 100644 AppControl Manager/Shared Logics/MoveUserModeToKernelMode.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/PageHashCalc.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/PolicyFileSigningStatusDetection.cs (64%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/PolicyMerger.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/PolicyToCIPConverter.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/PowerShellExecutor.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/RemoveSupplementalSigners.cs (69%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/ScanLevelz.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/SecureStringComparer.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/SignToolHelper.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/SnapBackGuarantee.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/StagingArea.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/SupplementalForSelf.cs (72%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/AuthenticodePageHashes.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/CertificateDetailsCreator.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/CertificateSignerCreator.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/ChainElement.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/ChainPackage.cs (100%) create mode 100644 AppControl Manager/Shared Logics/Types And Definitions/CodeIntegrityPolicy.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/FileBasedInfoPackage.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/FilePublisherSignerCreator.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/HashCreator.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/OpusSigner.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/PolicyHashObj.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/PublisherSignerCreator.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/Signer.cs (83%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/SimulationInput.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/SimulationOutput.cs (55%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Types And Definitions/WinTrust.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Variables/CILogIntel.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/Variables/GlobalVars.cs (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/VersionIncrementer.cs (100%) create mode 100644 AppControl Manager/Shared Logics/WDAC Simulation/Arbitrator.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/WDAC Simulation/GetCertificateDetails.cs (99%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/WDAC Simulation/GetFileRuleOutput.cs (91%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/WDAC Simulation/GetSignerInfo.cs (91%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/WldpQuerySecurityPolicy.cs (100%) create mode 100644 AppControl Manager/Shared Logics/XMLOps/ClearCiPolicySemantic.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/XMLOps/CloseEmptyXmlNodesSemantic.cs (100%) create mode 100644 AppControl Manager/Shared Logics/XMLOps/Macros.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/NewCertificateSignerRules.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/NewFilePublisherLevelRules.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/NewHashLevelRules.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/NewPFNLevelRules.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/NewPublisherLevelRules.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/RemoveAllowElementsSemantic.cs create mode 100644 AppControl Manager/Shared Logics/XMLOps/RemoveUnreferencedFileRuleRefs.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/XMLOps/SetCiPolicyInfo.cs (67%) rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/XMLOps/SignerAndHashBuilder.cs (99%) create mode 100644 AppControl Manager/Shared Logics/XMLOps/UpdateHvciOptions.cs rename {WDACConfig/WinUI3 => AppControl Manager}/Shared Logics/XmlFilePathExtractor.cs (75%) rename {WDACConfig/WinUI3 => AppControl Manager}/app.manifest (100%) rename {WDACConfig/WinUI3 => AppControl Manager}/exclusion.dic (100%) delete mode 100644 Extras/CodeIntegrity.cs delete mode 100644 Extras/Get-BlockedPackets.ps1 delete mode 100644 Extras/Get-EventData.ps1 delete mode 100644 Extras/How to Get All CIM Namespaces, Their Methods and Properties in PowerShell.ps1 delete mode 100644 Extras/OSVERSIONINFOEX.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/CodeIntegrityInfo.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/Main Cmdlets/InvokeWDACSimulation.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/Types And Definitions/CodeIntegrityPolicy.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/WDAC Simulation/Arbitrator.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/ClearCiPolicySemantic.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/Macros.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/NewCertificateSignerRules.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/NewFilePublisherLevelRules.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/NewHashLevelRules.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/NewPFNLevelRules.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/NewPublisherLevelRules.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/RemoveAllowElementsSemantic.cs create mode 100644 WDACConfig/WDACConfig Module Files/C#/Shared Logics/XMLOps/RemoveUnreferencedFileRuleRefs.cs delete mode 100644 WDACConfig/WDACConfig Module Files/WDACSimulation/Compare-SignerAndCertificate.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/Checkpoint-Macros.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/Clear-CiPolicy_Semantic.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/New-CertificateSignerRules.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/New-FilePublisherLevelRules.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/New-HashLevelRules.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/New-PFNLevelRules.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/New-PublisherLevelRules.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/Remove-AllowElements_Semantic.psm1 delete mode 100644 WDACConfig/WDACConfig Module Files/XMLOps/Remove-UnreferencedFileRuleRefs.psm1 delete mode 100644 WDACConfig/WinUI3/AppControl Manager.csproj.user delete mode 100644 WDACConfig/WinUI3/MainWindow.xaml delete mode 100644 WDACConfig/WinUI3/Pages/Home.xaml delete mode 100644 WDACConfig/WinUI3/Pages/Home.xaml.cs delete mode 100644 WDACConfig/WinUI3/Properties/PublishProfiles/win-arm64.pubxml delete mode 100644 WDACConfig/WinUI3/Shared Logics/CheckPolicyDeploymentStatus.cs delete mode 100644 WDACConfig/WinUI3/Shared Logics/EditGUIDs.cs delete mode 100644 WDACConfig/WinUI3/Shared Logics/MoveUserModeToKernelMode.cs delete mode 100644 WDACConfig/WinUI3/Shared Logics/XMLOps/UpdateHvciOptions.cs diff --git a/.github/workflows/Build AppControl Manager MSIX Package.yml b/.github/workflows/Build AppControl Manager MSIX Package.yml new file mode 100644 index 000000000..50d5221e9 --- /dev/null +++ b/.github/workflows/Build AppControl Manager MSIX Package.yml @@ -0,0 +1,74 @@ +name: Build AppControl Manager MSIX Package + +permissions: + id-token: write + contents: read + attestations: write + +on: + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + steps: + + - name: Check out the repository code + uses: actions/checkout@v4 + + - name: Setting up and downloading Winget + shell: pwsh + run: | + # Set up URLs and retrieve Winget latest release information + [string]$WingetRepoURL = 'https://api.github.com/repos/microsoft/winget-cli/releases' + $WingetReleases = Invoke-RestMethod -Uri $WingetRepoURL + $LatestRelease = $WingetReleases | Select-Object -First 1 + [string]$WingetURL2 = $LatestRelease.assets.browser_download_url | Where-Object { $_.EndsWith('.msixbundle') } | Select-Object -First 1 + [string]$WingetLicense = $LatestRelease.assets.browser_download_url | Where-Object { $_.EndsWith('License1.xml') } | Select-Object -First 1 + [hashtable]$Downloads = @{ + 'VCLibs.appx' = 'https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx' + 'Microsoft.UI.Xaml.appx' = 'https://github.com/microsoft/microsoft-ui-xaml/releases/download/v2.8.6/Microsoft.UI.Xaml.2.8.x64.appx' + 'Winget.msixbundle' = 'https://aka.ms/getwinget' + 'License1.xml' = $WingetLicense + } + $Downloads.GetEnumerator() | ForEach-Object -Parallel { + $FileName = $_.Key + $URL = $_.Value + Invoke-RestMethod -Uri $URL -OutFile $FileName + } + Add-AppxProvisionedPackage -Online -PackagePath 'Winget.msixbundle' -DependencyPackagePath 'Microsoft.UI.Xaml.appx', 'VCLibs.appx' -LicensePath 'License1.xml' + + - name: Finishing setting up Winget + shell: powershell + run: | + Add-AppPackage -Path 'Winget.msixbundle' -DependencyPath 'Microsoft.UI.Xaml.appx', 'VCLibs.appx' -ForceTargetApplicationShutdown -ForceUpdateFromAnyVersion + # Add-AppPackage on Windows Server throws error so we use Windows PowerShell for this section. + + - name: Installing the necessary programs + run: | + winget install --id Microsoft.DotNet.SDK.Preview --exact --accept-package-agreements --accept-source-agreements --uninstall-previous --force + winget install --id Microsoft.VisualStudio.2022.BuildTools --exact --accept-package-agreements --accept-source-agreements --uninstall-previous --force + winget install --id Microsoft.WindowsSDK.10.0.26100 --exact --accept-package-agreements --accept-source-agreements --uninstall-previous --force + winget install --id Microsoft.AppInstaller --exact --accept-package-agreements --accept-source-agreements --uninstall-previous --force + winget install --id Microsoft.VCRedist.2015+.x64 --exact --accept-package-agreements --accept-source-agreements --uninstall-previous --force + + - name: Building the AppControl Manager + run: dotnet build "AppControl Manager/AppControl Manager.sln" --configuration Release --verbosity minimal + + - name: Generating the MSIX Package + run: dotnet msbuild "AppControl Manager/AppControl Manager.sln" /p:Configuration=Release /p:AppxPackageDir="MSIXOutput\" /p:GenerateAppxPackageOnBuild=true + + - name: Capturing the Generated MSIX file Path + shell: pwsh + run: | + [string]$MSIXPath = (Get-ChildItem -Path '.\AppControl Manager\MSIXOutput\AppControl Manage*\AppControl Manager*.msix').FullName + + if ([string]::IsNullOrWhiteSpace($MSIXPath)) { throw "Couldn't find the generated MSIX package" } + + # Write the MSIXPath to GITHUB_ENV to set it as an environment variable for the entire workflow + Add-Content -Path $env:GITHUB_ENV -Value "MSIX_PATH=$MSIXPath" + + - name: Generate Artifact Attestation + uses: actions/attest-build-provenance@v1 + with: + subject-path: ${{ env.MSIX_PATH }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index a54e6fa66..10e3d84e2 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -43,7 +43,7 @@ jobs: - language: csharp build-mode: none # CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' - # Use `c-cpp` to analyze code written in C, C++ or both + # Use `c-cpp` to analyze code written in C, C++ or both # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how diff --git a/.gitignore b/.gitignore index c5972cb28..de7e35997 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,8 @@ Harden-Windows-Security Module/bin/ WDACConfig/obj/ WDACConfig/.vs/ WDACConfig/bin/ -WDACConfig/WinUI3/.vs/ -WDACConfig/WinUI3/bin/ -WDACConfig/WinUI3/obj/ -WDACConfig/WinUI3/Generated Files/ -WDACConfig/WinUI3/signtool.exe +AppControl Manager/.vs/ +AppControl Manager/bin/ +AppControl Manager/obj/ +AppControl Manager/Generated Files/ +AppControl Manager/signtool.exe diff --git a/WDACConfig/WinUI3/.editorconfig b/AppControl Manager/.editorconfig similarity index 100% rename from WDACConfig/WinUI3/.editorconfig rename to AppControl Manager/.editorconfig diff --git a/WDACConfig/WinUI3/App.xaml b/AppControl Manager/App.xaml similarity index 100% rename from WDACConfig/WinUI3/App.xaml rename to AppControl Manager/App.xaml diff --git a/WDACConfig/WinUI3/App.xaml.cs b/AppControl Manager/App.xaml.cs similarity index 94% rename from WDACConfig/WinUI3/App.xaml.cs rename to AppControl Manager/App.xaml.cs index 0e341a642..e31dcceee 100644 --- a/WDACConfig/WinUI3/App.xaml.cs +++ b/AppControl Manager/App.xaml.cs @@ -2,11 +2,9 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using System; -using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; -using System.Xml; // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info. @@ -32,6 +30,10 @@ public App() { this.InitializeComponent(); + // Give beautiful outline to the UI elements when using the tab key and keyboard for navigation + // https://learn.microsoft.com/en-us/windows/apps/design/style/reveal-focus + this.FocusVisualKind = FocusVisualKind.Reveal; + // to handle unhandled exceptions this.UnhandledException += App_UnhandledException; } diff --git a/WDACConfig/WinUI3/AppControl Manager.csproj b/AppControl Manager/AppControl Manager.csproj similarity index 88% rename from WDACConfig/WinUI3/AppControl Manager.csproj rename to AppControl Manager/AppControl Manager.csproj index cd4cd79e4..20ad26299 100644 --- a/WDACConfig/WinUI3/AppControl Manager.csproj +++ b/AppControl Manager/AppControl Manager.csproj @@ -6,8 +6,8 @@ 10.0.26100.0 WDACConfig app.manifest - x64;ARM64 - win-x64;win-arm64 + x64 + win-x64 win-$(Platform).pubxml true true @@ -33,6 +33,9 @@ + + + @@ -59,8 +62,11 @@ + + + @@ -131,7 +137,7 @@ True True Auto - x64|arm64 + x64 0 True AppControlManager @@ -141,15 +147,9 @@ True - - True - True - - True - @@ -157,14 +157,25 @@ - - - - + + + MSBuild:Compile + + + + + MSBuild:Compile + + + + + MSBuild:Compile + + MSBuild:Compile diff --git a/WDACConfig/WinUI3/AppControl Manager.sln b/AppControl Manager/AppControl Manager.sln similarity index 69% rename from WDACConfig/WinUI3/AppControl Manager.sln rename to AppControl Manager/AppControl Manager.sln index 2135f6743..14247f804 100644 --- a/WDACConfig/WinUI3/AppControl Manager.sln +++ b/AppControl Manager/AppControl Manager.sln @@ -6,21 +6,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppControl Manager", "AppCo EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|ARM64 = Debug|ARM64 Debug|x64 = Debug|x64 - Release|ARM64 = Release|ARM64 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Debug|ARM64.ActiveCfg = Debug|ARM64 - {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Debug|ARM64.Build.0 = Debug|ARM64 - {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Debug|ARM64.Deploy.0 = Debug|ARM64 {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Debug|x64.ActiveCfg = Debug|x64 {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Debug|x64.Build.0 = Debug|x64 {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Debug|x64.Deploy.0 = Debug|x64 - {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Release|ARM64.ActiveCfg = Release|ARM64 - {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Release|ARM64.Build.0 = Release|ARM64 - {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Release|ARM64.Deploy.0 = Release|ARM64 {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Release|x64.ActiveCfg = Release|x64 {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Release|x64.Build.0 = Release|x64 {8467BDD7-CAF9-478A-B74C-894D30C73E3A}.Release|x64.Deploy.0 = Release|x64 diff --git a/WDACConfig/WinUI3/Assets/BadgeLogo.scale-100.png b/AppControl Manager/Assets/BadgeLogo.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/BadgeLogo.scale-100.png rename to AppControl Manager/Assets/BadgeLogo.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/BadgeLogo.scale-125.png b/AppControl Manager/Assets/BadgeLogo.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/BadgeLogo.scale-125.png rename to AppControl Manager/Assets/BadgeLogo.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/BadgeLogo.scale-150.png b/AppControl Manager/Assets/BadgeLogo.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/BadgeLogo.scale-150.png rename to AppControl Manager/Assets/BadgeLogo.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/BadgeLogo.scale-200.png b/AppControl Manager/Assets/BadgeLogo.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/BadgeLogo.scale-200.png rename to AppControl Manager/Assets/BadgeLogo.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/BadgeLogo.scale-400.png b/AppControl Manager/Assets/BadgeLogo.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/BadgeLogo.scale-400.png rename to AppControl Manager/Assets/BadgeLogo.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/LargeTile.scale-100.png b/AppControl Manager/Assets/LargeTile.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/LargeTile.scale-100.png rename to AppControl Manager/Assets/LargeTile.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/LargeTile.scale-125.png b/AppControl Manager/Assets/LargeTile.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/LargeTile.scale-125.png rename to AppControl Manager/Assets/LargeTile.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/LargeTile.scale-150.png b/AppControl Manager/Assets/LargeTile.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/LargeTile.scale-150.png rename to AppControl Manager/Assets/LargeTile.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/LargeTile.scale-200.png b/AppControl Manager/Assets/LargeTile.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/LargeTile.scale-200.png rename to AppControl Manager/Assets/LargeTile.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/LargeTile.scale-400.png b/AppControl Manager/Assets/LargeTile.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/LargeTile.scale-400.png rename to AppControl Manager/Assets/LargeTile.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/LockScreenLogo.scale-200.png b/AppControl Manager/Assets/LockScreenLogo.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/LockScreenLogo.scale-200.png rename to AppControl Manager/Assets/LockScreenLogo.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/SmallTile.scale-100.png b/AppControl Manager/Assets/SmallTile.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SmallTile.scale-100.png rename to AppControl Manager/Assets/SmallTile.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/SmallTile.scale-125.png b/AppControl Manager/Assets/SmallTile.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SmallTile.scale-125.png rename to AppControl Manager/Assets/SmallTile.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/SmallTile.scale-150.png b/AppControl Manager/Assets/SmallTile.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SmallTile.scale-150.png rename to AppControl Manager/Assets/SmallTile.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/SmallTile.scale-200.png b/AppControl Manager/Assets/SmallTile.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SmallTile.scale-200.png rename to AppControl Manager/Assets/SmallTile.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/SmallTile.scale-400.png b/AppControl Manager/Assets/SmallTile.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SmallTile.scale-400.png rename to AppControl Manager/Assets/SmallTile.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/SplashScreen.scale-100.png b/AppControl Manager/Assets/SplashScreen.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SplashScreen.scale-100.png rename to AppControl Manager/Assets/SplashScreen.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/SplashScreen.scale-125.png b/AppControl Manager/Assets/SplashScreen.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SplashScreen.scale-125.png rename to AppControl Manager/Assets/SplashScreen.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/SplashScreen.scale-150.png b/AppControl Manager/Assets/SplashScreen.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SplashScreen.scale-150.png rename to AppControl Manager/Assets/SplashScreen.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/SplashScreen.scale-200.png b/AppControl Manager/Assets/SplashScreen.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SplashScreen.scale-200.png rename to AppControl Manager/Assets/SplashScreen.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/SplashScreen.scale-400.png b/AppControl Manager/Assets/SplashScreen.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/SplashScreen.scale-400.png rename to AppControl Manager/Assets/SplashScreen.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/Square150x150Logo.scale-100.png b/AppControl Manager/Assets/Square150x150Logo.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square150x150Logo.scale-100.png rename to AppControl Manager/Assets/Square150x150Logo.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/Square150x150Logo.scale-125.png b/AppControl Manager/Assets/Square150x150Logo.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square150x150Logo.scale-125.png rename to AppControl Manager/Assets/Square150x150Logo.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/Square150x150Logo.scale-150.png b/AppControl Manager/Assets/Square150x150Logo.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square150x150Logo.scale-150.png rename to AppControl Manager/Assets/Square150x150Logo.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/Square150x150Logo.scale-200.png b/AppControl Manager/Assets/Square150x150Logo.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square150x150Logo.scale-200.png rename to AppControl Manager/Assets/Square150x150Logo.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/Square150x150Logo.scale-400.png b/AppControl Manager/Assets/Square150x150Logo.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square150x150Logo.scale-400.png rename to AppControl Manager/Assets/Square150x150Logo.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-16.png b/AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-16.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-16.png rename to AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-16.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-24.png b/AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-24.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-24.png rename to AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-24.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-256.png b/AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-256.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-256.png rename to AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-256.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-32.png b/AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-32.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-32.png rename to AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-32.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-48.png b/AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-48.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-lightunplated_targetsize-48.png rename to AppControl Manager/Assets/Square44x44Logo.altform-lightunplated_targetsize-48.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-16.png b/AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-16.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-16.png rename to AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-16.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-256.png b/AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-256.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-256.png rename to AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-256.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-32.png b/AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-32.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-32.png rename to AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-32.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-48.png b/AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-48.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.altform-unplated_targetsize-48.png rename to AppControl Manager/Assets/Square44x44Logo.altform-unplated_targetsize-48.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.scale-100.png b/AppControl Manager/Assets/Square44x44Logo.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.scale-100.png rename to AppControl Manager/Assets/Square44x44Logo.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.scale-125.png b/AppControl Manager/Assets/Square44x44Logo.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.scale-125.png rename to AppControl Manager/Assets/Square44x44Logo.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.scale-150.png b/AppControl Manager/Assets/Square44x44Logo.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.scale-150.png rename to AppControl Manager/Assets/Square44x44Logo.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.scale-200.png b/AppControl Manager/Assets/Square44x44Logo.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.scale-200.png rename to AppControl Manager/Assets/Square44x44Logo.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.scale-400.png b/AppControl Manager/Assets/Square44x44Logo.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.scale-400.png rename to AppControl Manager/Assets/Square44x44Logo.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-16.png b/AppControl Manager/Assets/Square44x44Logo.targetsize-16.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-16.png rename to AppControl Manager/Assets/Square44x44Logo.targetsize-16.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-24.png b/AppControl Manager/Assets/Square44x44Logo.targetsize-24.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-24.png rename to AppControl Manager/Assets/Square44x44Logo.targetsize-24.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/AppControl Manager/Assets/Square44x44Logo.targetsize-24_altform-unplated.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-24_altform-unplated.png rename to AppControl Manager/Assets/Square44x44Logo.targetsize-24_altform-unplated.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-256.png b/AppControl Manager/Assets/Square44x44Logo.targetsize-256.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-256.png rename to AppControl Manager/Assets/Square44x44Logo.targetsize-256.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-32.png b/AppControl Manager/Assets/Square44x44Logo.targetsize-32.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-32.png rename to AppControl Manager/Assets/Square44x44Logo.targetsize-32.png diff --git a/WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-48.png b/AppControl Manager/Assets/Square44x44Logo.targetsize-48.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Square44x44Logo.targetsize-48.png rename to AppControl Manager/Assets/Square44x44Logo.targetsize-48.png diff --git a/WDACConfig/WinUI3/Assets/StoreLogo.backup.png b/AppControl Manager/Assets/StoreLogo.backup.png similarity index 100% rename from WDACConfig/WinUI3/Assets/StoreLogo.backup.png rename to AppControl Manager/Assets/StoreLogo.backup.png diff --git a/WDACConfig/WinUI3/Assets/StoreLogo.scale-100.png b/AppControl Manager/Assets/StoreLogo.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/StoreLogo.scale-100.png rename to AppControl Manager/Assets/StoreLogo.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/StoreLogo.scale-125.png b/AppControl Manager/Assets/StoreLogo.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/StoreLogo.scale-125.png rename to AppControl Manager/Assets/StoreLogo.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/StoreLogo.scale-150.png b/AppControl Manager/Assets/StoreLogo.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/StoreLogo.scale-150.png rename to AppControl Manager/Assets/StoreLogo.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/StoreLogo.scale-200.png b/AppControl Manager/Assets/StoreLogo.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/StoreLogo.scale-200.png rename to AppControl Manager/Assets/StoreLogo.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/StoreLogo.scale-400.png b/AppControl Manager/Assets/StoreLogo.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/StoreLogo.scale-400.png rename to AppControl Manager/Assets/StoreLogo.scale-400.png diff --git a/WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-100.png b/AppControl Manager/Assets/Wide310x150Logo.scale-100.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-100.png rename to AppControl Manager/Assets/Wide310x150Logo.scale-100.png diff --git a/WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-125.png b/AppControl Manager/Assets/Wide310x150Logo.scale-125.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-125.png rename to AppControl Manager/Assets/Wide310x150Logo.scale-125.png diff --git a/WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-150.png b/AppControl Manager/Assets/Wide310x150Logo.scale-150.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-150.png rename to AppControl Manager/Assets/Wide310x150Logo.scale-150.png diff --git a/WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-200.png b/AppControl Manager/Assets/Wide310x150Logo.scale-200.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-200.png rename to AppControl Manager/Assets/Wide310x150Logo.scale-200.png diff --git a/WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-400.png b/AppControl Manager/Assets/Wide310x150Logo.scale-400.png similarity index 100% rename from WDACConfig/WinUI3/Assets/Wide310x150Logo.scale-400.png rename to AppControl Manager/Assets/Wide310x150Logo.scale-400.png diff --git a/AppControl Manager/MainWindow.xaml b/AppControl Manager/MainWindow.xaml new file mode 100644 index 000000000..466eb986f --- /dev/null +++ b/AppControl Manager/MainWindow.xaml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WDACConfig/WinUI3/MainWindow.xaml.cs b/AppControl Manager/MainWindow.xaml.cs similarity index 79% rename from WDACConfig/WinUI3/MainWindow.xaml.cs rename to AppControl Manager/MainWindow.xaml.cs index e435c8a50..6cbc1b0a0 100644 --- a/WDACConfig/WinUI3/MainWindow.xaml.cs +++ b/AppControl Manager/MainWindow.xaml.cs @@ -1,5 +1,6 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; +using System.Linq; namespace WDACConfig { @@ -12,6 +13,13 @@ public MainWindow() // https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.window.extendscontentintotitlebar // Make title bar Mica ExtendsContentIntoTitleBar = true; + + // Navigate to the CreatePolicy page when the window is loaded + _ = ContentFrame.Navigate(typeof(Pages.CreatePolicy)); + + // Set the "CreatePolicy" item as selected in the NavigationView + MainNavigation.SelectedItem = MainNavigation.MenuItems.OfType() + .First(item => item.Tag.ToString() == "CreatePolicy"); } // Event handler for the main navigation menu @@ -25,9 +33,6 @@ private void NavigationView_SelectionChanged(NavigationView sender, NavigationVi // Navigate to the page based on the Tag switch (selectedTag) { - case "Home": - _ = ContentFrame.Navigate(typeof(Pages.Home)); - break; case "CreatePolicy": _ = ContentFrame.Navigate(typeof(Pages.CreatePolicy)); break; @@ -47,8 +52,8 @@ private void NavigationView_SelectionChanged(NavigationView sender, NavigationVi case "GetSecurePolicySettings": _ = ContentFrame.Navigate(typeof(Pages.GetSecurePolicySettings)); break; - case "ViewCurrentPolicies": - _ = ContentFrame.Navigate(typeof(Pages.ViewCurrentPolicies)); + case "SystemInformation": + _ = ContentFrame.Navigate(typeof(Pages.SystemInformation)); break; case "ConfigurePolicyRuleOptions": _ = ContentFrame.Navigate(typeof(Pages.ConfigurePolicyRuleOptions)); @@ -56,6 +61,9 @@ private void NavigationView_SelectionChanged(NavigationView sender, NavigationVi case "Logs": _ = ContentFrame.Navigate(typeof(Pages.Logs)); break; + case "Simulation": + _ = ContentFrame.Navigate(typeof(Pages.Simulation)); + break; default: break; } diff --git a/WDACConfig/WinUI3/Package.appxmanifest b/AppControl Manager/Package.appxmanifest similarity index 81% rename from WDACConfig/WinUI3/Package.appxmanifest rename to AppControl Manager/Package.appxmanifest index 8c08cd62d..7e6c96153 100644 --- a/WDACConfig/WinUI3/Package.appxmanifest +++ b/AppControl Manager/Package.appxmanifest @@ -5,7 +5,8 @@ xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="uap rescap"> + xmlns:uap18="http://schemas.microsoft.com/appx/manifest/uap/windows10/18" + IgnorableNamespaces="uap rescap uap18"> + EntryPoint="$targetentrypoint$" uap18:TrustLevel="mediumIL" uap18:RuntimeBehavior="windowsApp"> diff --git a/WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml b/AppControl Manager/Pages/ConfigurePolicyRuleOptions.xaml similarity index 94% rename from WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml rename to AppControl Manager/Pages/ConfigurePolicyRuleOptions.xaml index 46843a1c2..33dab6645 100644 --- a/WDACConfig/WinUI3/Pages/ConfigurePolicyRuleOptions.xaml +++ b/AppControl Manager/Pages/ConfigurePolicyRuleOptions.xaml @@ -12,10 +12,8 @@ - 4 - - + + + + + Spacing="{StaticResource SettingsCardSpacing}" Grid.Row="1" Margin="0,40,0,0"> - diff --git a/WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs b/AppControl Manager/Pages/CreatePolicy.xaml.cs similarity index 100% rename from WDACConfig/WinUI3/Pages/CreatePolicy.xaml.cs rename to AppControl Manager/Pages/CreatePolicy.xaml.cs diff --git a/WDACConfig/WinUI3/Pages/GetCIHashes.xaml b/AppControl Manager/Pages/GetCIHashes.xaml similarity index 79% rename from WDACConfig/WinUI3/Pages/GetCIHashes.xaml rename to AppControl Manager/Pages/GetCIHashes.xaml index 8e2adb665..b9328f271 100644 --- a/WDACConfig/WinUI3/Pages/GetCIHashes.xaml +++ b/AppControl Manager/Pages/GetCIHashes.xaml @@ -8,8 +8,15 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AppControl Manager/Pages/Simulation.xaml.cs b/AppControl Manager/Pages/Simulation.xaml.cs new file mode 100644 index 000000000..39819acb4 --- /dev/null +++ b/AppControl Manager/Pages/Simulation.xaml.cs @@ -0,0 +1,244 @@ +using CommunityToolkit.WinUI.Controls; +using CommunityToolkit.WinUI.UI.Controls; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; + +namespace WDACConfig.Pages +{ + public sealed partial class Simulation : Page + { + public ObservableCollection SimulationOutputs { get; set; } + private List AllSimulationOutputs; // Store all outputs for searching + private List filePaths; // For selected file paths + private List folderPaths; // For selected folder paths + private string? xmlFilePath; // For selected XML file path + private List catRootPaths; // For selected Cat Root paths + + public Simulation() + { + this.InitializeComponent(); + this.NavigationCacheMode = Microsoft.UI.Xaml.Navigation.NavigationCacheMode.Enabled; + + SimulationOutputs = []; + AllSimulationOutputs = []; + filePaths = []; + folderPaths = []; + catRootPaths = []; + } + + // Event handler for the Begin Simulation button + private async void BeginSimulationButton_Click(object sender, RoutedEventArgs e) + { + try + { + // Collect values from UI elements + bool noCatRootScanning = (NoCatRootScanningToggle.IsChecked == true); + double radialGaugeValue = ScalabilityRadialGauge.Value; // Value from radial gauge + bool CSVOutput = (CSVOutputToggle.IsChecked == true); + + BeginSimulationButton.IsEnabled = false; + ScalabilityRadialGauge.IsEnabled = false; + + // Run the simulation + var result = await Task.Run(() => + { + return InvokeWDACSimulation.Invoke( + filePaths, + folderPaths, + xmlFilePath, + noCatRootScanning, + CSVOutput, + catRootPaths, + (ushort)radialGaugeValue, + SimulationProgressBar + ); + }); + + // Clear the current ObservableCollection and backup the full data set + SimulationOutputs.Clear(); + AllSimulationOutputs.Clear(); + + // Update the TextBox with the total count of files + TotalCountOfTheFilesTextBox.Text = result.Count.ToString(CultureInfo.InvariantCulture); + + // Update the ObservableCollection on the UI thread + foreach (var entry in result) + { + var simOutput = entry.Value; + + var simulationOutput = new SimulationOutput( + simOutput.Path, + simOutput.Source, + simOutput.IsAuthorized, + simOutput.SignerID, + simOutput.SignerName, + simOutput.SignerCertRoot, + simOutput.SignerCertPublisher, + simOutput.SignerScope, + simOutput.SignerFileAttributeIDs, + simOutput.MatchCriteria, + simOutput.SpecificFileNameLevelMatchCriteria, + simOutput.CertSubjectCN, + simOutput.CertIssuerCN, + simOutput.CertNotAfter, + simOutput.CertTBSValue, + simOutput.FilePath + ); + + // Add to the full list and observable collection + AllSimulationOutputs.Add(simulationOutput); + + // Add to the ObservableCollection bound to the UI + _ = DispatcherQueue.TryEnqueue(() => + { + SimulationOutputs.Add(simulationOutput); + }); + } + } + finally + { + BeginSimulationButton.IsEnabled = true; + ScalabilityRadialGauge.IsEnabled = true; + } + } + + // Event handler for the Select XML File button + private void SelectXmlFileButton_Click(object sender, RoutedEventArgs e) + { + string? selectedFile = FileSystemPicker.ShowFilePicker(); + if (!string.IsNullOrEmpty(selectedFile)) + { + // Store the selected XML file path + xmlFilePath = selectedFile; + + // Update the TextBox with the selected XML file path + XmlFilePathTextBox.Text = selectedFile; + } + } + + // Event handler for the Select Files button + private void SelectFilesButton_Click(object sender, RoutedEventArgs e) + { + List? selectedFiles = FileSystemPicker.ShowMultiFilePicker(); + if (selectedFiles != null && selectedFiles.Count != 0) + { + filePaths = [.. selectedFiles]; + } + } + + // Event handler for the Select Folders button + private void SelectFoldersButton_Click(object sender, RoutedEventArgs e) + { + string? selectedFolder = FileSystemPicker.ShowDirectoryPicker(); + if (!string.IsNullOrEmpty(selectedFolder)) + { + folderPaths.Add(selectedFolder); + } + } + + // Event handler for the Cat Root Paths button + private void CatRootPathsButton_Click(object sender, RoutedEventArgs e) + { + List? selectedCatRoots = FileSystemPicker.ShowMultiFilePicker(); + if (selectedCatRoots != null && selectedCatRoots.Count != 0) + { + catRootPaths = [.. selectedCatRoots]; + } + } + + // Event handler for RadialGauge ValueChanged + private void ScalabilityRadialGauge_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) + { + if (sender is RadialGauge gauge) + { + // Update the button content with the current value of the gauge + ScalabilityButton.Content = $"Scalability: {gauge.Value:N0}"; + } + } + + // Event handler for the Clear Data button + private void ClearDataButton_Click(object sender, RoutedEventArgs e) + { + // Clear the ObservableCollection + SimulationOutputs.Clear(); + // Clear the full data + AllSimulationOutputs.Clear(); + } + + // Event handler for the SearchBox text change + private void SearchBox_TextChanged(object sender, TextChangedEventArgs e) + { + string searchTerm = SearchBox.Text.Trim().ToLowerInvariant(); + + // Perform a case-insensitive search in all relevant fields + List filteredResults = AllSimulationOutputs.Where(output => + (output.Path != null && output.Path.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) || + (output.Source != null && output.Source.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) || + (output.MatchCriteria != null && output.MatchCriteria.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) || + (output.SpecificFileNameLevelMatchCriteria != null && output.SpecificFileNameLevelMatchCriteria.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) || + (output.CertSubjectCN != null && output.CertSubjectCN.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) || + (output.SignerName != null && output.SignerName.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) || + (output.FilePath != null && output.FilePath.Contains(searchTerm, System.StringComparison.InvariantCultureIgnoreCase)) + ).ToList(); + + + // Update the ObservableCollection on the UI thread with the filtered results + SimulationOutputs.Clear(); + foreach (var result in filteredResults) + { + SimulationOutputs.Add(result); + } + } + + + // https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/group_sort_filter + + // Column sorting logic for the entire DataGrid + private void SimulationDataGrid_Sorting(object sender, DataGridColumnEventArgs e) + { + // Check if the column being sorted is the "IsAuthorized" column + if (string.Equals(e.Column.Tag?.ToString(), "IsAuthorized", System.StringComparison.OrdinalIgnoreCase)) + { + // Perform the sorting based on the current SortDirection (ascending or descending) + // At first it is null since no direction has been chosen for the column + if (e.Column.SortDirection is null || e.Column.SortDirection is DataGridSortDirection.Ascending) + { + // Descending: First True, then False + SimulationOutputs = new ObservableCollection( + AllSimulationOutputs.OrderBy(output => !output.IsAuthorized) + ); + + // Set the column direction to Descending + e.Column.SortDirection = DataGridSortDirection.Descending; + } + else + { + // Ascending: First False, then True + SimulationOutputs = new ObservableCollection( + AllSimulationOutputs.OrderBy(output => output.IsAuthorized) + ); + e.Column.SortDirection = DataGridSortDirection.Ascending; + } + + // Update the ItemsSource of the DataGrid + SimulationDataGrid.ItemsSource = SimulationOutputs; + + // Clear SortDirection for other columns + foreach (var column in SimulationDataGrid.Columns) + { + if (column != e.Column) + { + column.SortDirection = null; + } + } + } + } + + } +} diff --git a/AppControl Manager/Pages/SystemInformation/CodeIntegrityInfo.xaml b/AppControl Manager/Pages/SystemInformation/CodeIntegrityInfo.xaml new file mode 100644 index 000000000..d895f5a21 --- /dev/null +++ b/AppControl Manager/Pages/SystemInformation/CodeIntegrityInfo.xaml @@ -0,0 +1,65 @@ + + + + + + + + + + + + +