From 81530914214257a957ac496736c25cbd4b7c9332 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 10 Nov 2023 08:51:52 +0000 Subject: [PATCH 001/178] Quality of Life improvements Improved Windows build number detection Improved variable types Improved error messages Increased required PowerShell version for the module --- WDACConfig/Resources.ps1 | 72 ++++++++++++++++++++++---------------- WDACConfig/WDACConfig.psd1 | 4 +-- WDACConfig/version.txt | 2 +- 3 files changed, 45 insertions(+), 33 deletions(-) diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index e7445e8a5..bdf7a0167 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -1,6 +1,18 @@ # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise $ErrorActionPreference = 'Stop' -if (-NOT ([System.Environment]::OSVersion.Version -ge '10.0.22621')) { Write-Error -Message "You're not using Windows 11 22H2, exiting..." } + +# Minimum required OS build number +[decimal]$Requiredbuild = '22622.2428' +# Get OS build version +[decimal]$OSBuild = [System.Environment]::OSVersion.Version.Build +# Get Update Build Revision (UBR) number +[decimal]$UBR = Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'UBR' +# Create full OS build number as seen in Windows Settings +[decimal]$FullOSBuild = "$OSBuild.$UBR" +# Make sure the current OS build is equal or greater than the required build number +if (-NOT ($FullOSBuild -ge $Requiredbuild)) { + Throw [System.PlatformNotSupportedException] "You are not using the latest build of the Windows OS. A minimum build of $Requiredbuild is required but your OS build is $FullOSBuild`nPlease go to Windows Update to install the updates and then try again." +} # Get the path to SignTool function Get-SignTool { @@ -14,15 +26,15 @@ function Get-SignTool { $SignToolExePath = 'C:\Program Files (x86)\Windows Kits\*\bin\*\x64\signtool.exe' } else { - Write-Error -Message "signtool.exe couldn't be found" + Throw [System.IO.FileNotFoundException] 'signtool.exe could not be found' } } elseif ($Env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { if (Test-Path -Path 'C:\Program Files (x86)\Windows Kits\*\bin\*\arm64\signtool.exe') { $SignToolExePath = 'C:\Program Files (x86)\Windows Kits\*\bin\*\arm64\signtool.exe' - } + } else { - Write-Error -Message "signtool.exe couldn't be found" + Throw [System.IO.FileNotFoundException] 'signtool.exe could not be found' } } } @@ -36,11 +48,11 @@ function Get-SignTool { [System.Boolean]$GreenFlag5 = ((Get-AuthenticodeSignature -FilePath $SignToolExePath).StatusMessage -eq 'Signature verified.') } catch { - Write-Error "SignTool executable couldn't be verified." + Throw [System.Security.VerificationException] 'SignTool executable could not be verified.' } # If any of the 5 checks above fails, the operation stops if (!$GreenFlag1 -or !$GreenFlag2 -or !$GreenFlag3 -or !$GreenFlag4 -or !$GreenFlag5) { - Write-Error -Message "The SignTool executable was found but couldn't be verified. Please download the latest Windows SDK to get the newest SignTool executable. Official download link: http://aka.ms/WinSDK" + Throw [System.Security.VerificationException] 'The SignTool executable was found but could not be verified. Please download the latest Windows SDK to get the newest SignTool executable. Official download link: http://aka.ms/WinSDK' } else { return $SignToolExePath @@ -82,8 +94,8 @@ function Update-self { # If GitHub source is unavailable, use the Azure DevOps source $LatestVersion = Invoke-RestMethod -Uri 'https://dev.azure.com/SpyNetGirl/011c178a-7b92-462b-bd23-2c014528a67e/_apis/git/repositories/5304fef0-07c0-4821-a613-79c01fb75657/items?path=/WDACConfig/version.txt' } - catch { - Write-Error -Message "Couldn't verify if the latest version of the module is installed, please check your Internet connection. You can optionally bypass the online check by using -SkipVersionCheck parameter." + catch { + Throw [System.Security.VerificationException] 'Could not verify if the latest version of the module is installed, please check your Internet connection. You can optionally bypass the online check by using -SkipVersionCheck parameter.' } } if ($CurrentVersion -lt $LatestVersion) { @@ -116,11 +128,11 @@ function Update-self { function Set-LogSize { [CmdletBinding()] param ([System.Int64]$LogSize) - $logName = 'Microsoft-Windows-CodeIntegrity/Operational' - $log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName - $log.MaximumSizeInBytes = $LogSize - $log.IsEnabled = $true - $log.SaveChanges() + [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' + $Log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $LogName + $Log.MaximumSizeInBytes = $LogSize + $Log.IsEnabled = $true + $Log.SaveChanges() } @@ -142,7 +154,7 @@ function Test-FilePath { $FileFullPath = Resolve-Path $file # Initialize a variable to store the result - $Result = $false + [bool]$Result = $false # Loop through each directory path foreach ($directory in $DirectoryPath) { @@ -240,8 +252,8 @@ Function Get-AuditEventLogsProcessing { # Event Viewer Code Integrity logs scan foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { - $xml = [xml]$event.toxml() - $xml.event.eventdata.data | + $Xml = [xml]$event.toxml() + $Xml.event.eventdata.data | ForEach-Object { $hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | ForEach-Object { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { @@ -270,7 +282,7 @@ function New-EmptyPolicy { $RulesContent, $RuleRefsContent ) - $EmptyPolicy = @" + [System.String]$EmptyPolicy = @" 10.0.0.0 @@ -337,7 +349,7 @@ $RuleRefsContent # Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json -function Confirm-CertCN ([string]$CN) { +function Confirm-CertCN ([System.String]$CN) { $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } @@ -384,13 +396,13 @@ Function Remove-ZerosFromIDs { param( [Parameter(Mandatory = $true)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] - [string]$FilePath + [System.String]$FilePath ) # Load the xml file - [xml]$xml = Get-Content -Path $FilePath + [xml]$Xml = Get-Content -Path $FilePath # Get all the elements with ID attribute - $Elements = $xml.SelectNodes('//*[@ID]') + $Elements = $Xml.SelectNodes('//*[@ID]') # Loop through the elements and replace _0 with empty string in the ID value and SignerId value foreach ($Element in $Elements) { @@ -407,7 +419,7 @@ Function Remove-ZerosFromIDs { } # Get the CiSigners element by name - $CiSigners = $xml.SiPolicy.CiSigners + $CiSigners = $Xml.SiPolicy.CiSigners # Check if the CiSigners element has child elements with SignerId attribute if ($CiSigners.HasChildNodes) { @@ -420,7 +432,7 @@ Function Remove-ZerosFromIDs { } # Save the modified xml file - $xml.Save($FilePath) + $Xml.Save($FilePath) } @@ -430,14 +442,14 @@ Function Move-UserModeToKernelMode { param( [Parameter(Mandatory = $true)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] - [string]$FilePath + [System.String]$FilePath ) # Load the XML file as an XmlDocument object - $xml = [xml](Get-Content -Path $FilePath) + $Xml = [xml](Get-Content -Path $FilePath) # Get the SigningScenario nodes as an array - $signingScenarios = $xml.SiPolicy.SigningScenarios.SigningScenario + $signingScenarios = $Xml.SiPolicy.SigningScenarios.SigningScenario # Find the SigningScenario node with Value 131 and store it in a variable $signingScenario131 = $signingScenarios | Where-Object { $_.Value -eq '131' } @@ -454,7 +466,7 @@ Function Move-UserModeToKernelMode { foreach ($AllowedSigner in $AllowedSigners12.AllowedSigner) { # Create a new AllowedSigner node and copy the SignerId attribute from the original node # Use the namespace of the parent element when creating the new element - $NewAllowedSigner = $xml.CreateElement('AllowedSigner', $signingScenario131.NamespaceURI) + $NewAllowedSigner = $Xml.CreateElement('AllowedSigner', $signingScenario131.NamespaceURI) $NewAllowedSigner.SetAttribute('SignerId', $AllowedSigner.SignerId) # Append the new AllowedSigner node to the AllowedSigners node of the SigningScenario node with Value 131 @@ -464,15 +476,15 @@ Function Move-UserModeToKernelMode { # Remove the SigningScenario node with Value 12 from the XML document # out-null to prevent console display - $xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) | Out-Null + $Xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) | Out-Null } # Remove Signing Scenario 12 block only if it exists and has no allowed signers (i.e. is empty) if ($signingScenario12 -and $AllowedSigners12.count -eq 0) { # Remove the SigningScenario node with Value 12 from the XML document - $xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) + $Xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) } # Save the modified XML document to a new file - $xml.Save($FilePath) + $Xml.Save($FilePath) } diff --git a/WDACConfig/WDACConfig.psd1 b/WDACConfig/WDACConfig.psd1 index 77365bf97..a3330545a 100644 --- a/WDACConfig/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig.psd1 @@ -8,7 +8,7 @@ # RootModule = "" # Version number of this module. - ModuleVersion = '0.2.6' + ModuleVersion = '0.2.7' # Supported PSEditions CompatiblePSEditions = @('Core') @@ -80,7 +80,7 @@ To get help and syntax on PowerShell console, type: '@ # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '7.3.6' + PowerShellVersion = '7.3.9' # Name of the PowerShell host required by this module # PowerShellHostName = '' diff --git a/WDACConfig/version.txt b/WDACConfig/version.txt index a53741c09..967b33ffb 100644 --- a/WDACConfig/version.txt +++ b/WDACConfig/version.txt @@ -1 +1 @@ -0.2.6 \ No newline at end of file +0.2.7 \ No newline at end of file From 9b4f940e00855ab7c6c012daf2cbfb38439a52d3 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 10 Nov 2023 09:01:46 +0000 Subject: [PATCH 002/178] Updated the task scheduling creation This update uses SYSTEM account's well known SID to create the scheduled task that keeps the Microsoft recommended driver block rules updated quickly --- WDACConfig/New-WDACConfig.psm1 | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 9950213c5..7ed3ea57f 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -293,18 +293,21 @@ function New-WDACConfig { [scriptblock]$SetAutoUpdateDriverBlockRulesSCRIPTBLOCK = { # create a scheduled task that runs every 7 days - if (-NOT (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -ErrorAction SilentlyContinue)) { - $action = New-ScheduledTaskAction -Execute 'Powershell.exe' ` - -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' - $TaskPrincipal = New-ScheduledTaskPrincipal -LogonType S4U -UserId $env:USERNAME -RunLevel Highest + if (-NOT (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath '\MSFT Driver Block list update\' -ErrorAction SilentlyContinue)) { + # Get the SID of the SYSTEM account. It is a well-known SID, but still querying it, going to use it to create the scheduled task + $SYSTEMSID = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null) + # create a scheduled task that runs every 7 days + $Action = New-ScheduledTaskAction -Execute 'Powershell.exe' ` + -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' + $TaskPrincipal = New-ScheduledTaskPrincipal -LogonType S4U -UserId $($SYSTEMSID.Value) -RunLevel Highest # trigger $Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) # register the task - Register-ScheduledTask -Action $action -Trigger $Time -Principal $TaskPrincipal -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Description 'Microsoft Recommended Driver Block List update' + Register-ScheduledTask -Action $Action -Trigger $Time -Principal $TaskPrincipal -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Description 'Microsoft Recommended Driver Block List update' # define advanced settings for the task $TaskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Compatibility Win8 -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 3) # add advanced settings we defined to the task - Set-ScheduledTask -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Settings $TaskSettings + Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings } Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } From 02f1ddbcf8ad4877db94c8900e8a38ec4c9064df Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 10 Nov 2023 09:04:15 +0000 Subject: [PATCH 003/178] Fixed the OS build version --- WDACConfig/Resources.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index bdf7a0167..c66b0f448 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -2,7 +2,7 @@ $ErrorActionPreference = 'Stop' # Minimum required OS build number -[decimal]$Requiredbuild = '22622.2428' +[decimal]$Requiredbuild = '22621.2428' # Get OS build version [decimal]$OSBuild = [System.Environment]::OSVersion.Version.Build # Get Update Build Revision (UBR) number From 0bd3bfa6c982490379ab9d6441b4e7aa36ab5387 Mon Sep 17 00:00:00 2001 From: Violet Date: Wed, 29 Nov 2023 10:45:07 -0930 Subject: [PATCH 004/178] Variable type definitions and comments Strictly defined a lot of variable types. Added some comments, Increased module required version. --- WDACConfig/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-WDACConfig.psm1 | 2 +- WDACConfig/New-WDACConfig.psm1 | 12 +-- WDACConfig/Resources.ps1 | 102 +++++++++++++++----------- WDACConfig/Set-CommonWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig.psd1 | 2 +- 6 files changed, 70 insertions(+), 52 deletions(-) diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index f922fce72..33d6356c9 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -261,7 +261,7 @@ function Edit-SignedWDACConfig { Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue # Get the current date so that instead of the entire event viewer logs, only audit logs created after running this module will be captured # The notice about variable being assigned and never used should be ignored - it's being dot-sourced from Resources file - [datetime]$Date = Get-Date + [System.DateTime]$Date = Get-Date # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index bcd1740ef..1e137d281 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -398,7 +398,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue # Get the current date so that instead of the entire event viewer logs, only audit logs created after running this module will be captured # The notice about variable being assigned and never used should be ignored - it's being dot-sourced from Resources file - [datetime]$Date = Get-Date + [System.DateTime]$Date = Get-Date # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 7ed3ea57f..90f24bc19 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -139,7 +139,7 @@ function New-WDACConfig { } [scriptblock]$GetDriverBlockRulesSCRIPTBLOCK = { - [System.String]$DriverRules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md').Content -replace "(?s).*``````xml(.*)``````.*", '$1' + [System.String]$DriverRules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty $DriverRules = $DriverRules -replace '', '' $DriverRules = $DriverRules -replace '', '' @@ -265,7 +265,7 @@ function New-WDACConfig { } [scriptblock]$DeployLatestDriverBlockRulesSCRIPTBLOCK = { - Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip + Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip -ProgressAction SilentlyContinue Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' @@ -276,7 +276,7 @@ function New-WDACConfig { } [scriptblock]$DeployLatestBlockRulesSCRIPTBLOCK = { - (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md').Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File '.\Microsoft recommended block rules TEMP.xml' + (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File '.\Microsoft recommended block rules TEMP.xml' # Remove empty lines from the policy file Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete @@ -541,11 +541,11 @@ function New-WDACConfig { [System.String]$path = 'windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' [System.String]$ApiUrl = "https://api.github.com/repos/$owner/$repo/commits?path=$path" - [System.Object[]]$Response = Invoke-RestMethod $ApiUrl - [datetime]$Date = $Response[0].commit.author.date + [System.Object[]]$Response = Invoke-RestMethod -Uri $ApiUrl -ProgressAction SilentlyContinue + [System.DateTime]$Date = $Response[0].commit.author.date &$WriteLavender "The document containing the drivers block list on GitHub was last updated on $Date" - [System.String]$MicrosoftRecommendeDriverBlockRules = (Invoke-WebRequest 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md').Content + [System.String]$MicrosoftRecommendeDriverBlockRules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -ProgressAction SilentlyContinue).Content $MicrosoftRecommendeDriverBlockRules -match '(.*)' | Out-Null &$WritePink "The current version of Microsoft recommended drivers block list is $($Matches[1])" } diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index c66b0f448..85923604b 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -2,13 +2,13 @@ $ErrorActionPreference = 'Stop' # Minimum required OS build number -[decimal]$Requiredbuild = '22621.2428' +[System.Decimal]$Requiredbuild = '22621.2428' # Get OS build version -[decimal]$OSBuild = [System.Environment]::OSVersion.Version.Build +[System.Decimal]$OSBuild = [System.Environment]::OSVersion.Version.Build # Get Update Build Revision (UBR) number -[decimal]$UBR = Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'UBR' +[System.Decimal]$UBR = Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'UBR' # Create full OS build number as seen in Windows Settings -[decimal]$FullOSBuild = "$OSBuild.$UBR" +[System.Decimal]$FullOSBuild = "$OSBuild.$UBR" # Make sure the current OS build is equal or greater than the required build number if (-NOT ($FullOSBuild -ge $Requiredbuild)) { Throw [System.PlatformNotSupportedException] "You are not using the latest build of the Windows OS. A minimum build of $Requiredbuild is required but your OS build is $FullOSBuild`nPlease go to Windows Update to install the updates and then try again." @@ -65,34 +65,34 @@ function Update-self { try { # Get the last update check time - [Datetime]$UserConfigDate = Get-CommonWDACConfig -LastUpdateCheck + [System.DateTime]$UserConfigDate = Get-CommonWDACConfig -LastUpdateCheck } catch { # If the User Config file doesn't exist then set this flag to perform online update check - [bool]$PerformOnlineUpdateCheck = $true + [System.Boolean]$PerformOnlineUpdateCheck = $true } # Ensure these are run only if the User Config file exists and contains a date for last update check if (!$PerformOnlineUpdateCheck) { # Get the current time - [Datetime]$CurrentDateTime = Get-Date + [System.DateTime]$CurrentDateTime = Get-Date # Calculate the minutes elapsed since the last online update check - [int]$TimeDiff = ($CurrentDateTime - $UserConfigDate).TotalMinutes + [System.Int64]$TimeDiff = ($CurrentDateTime - $UserConfigDate).TotalMinutes } # Only check for updates if the last attempt occured more than 10 minutes ago or the User Config file for last update check doesn't exist # This prevents the module from constantly doing an update check by fetching the version file from GitHub if (($TimeDiff -gt 10) -or $PerformOnlineUpdateCheck) { - $CurrentVersion = (Test-ModuleManifest "$psscriptroot\WDACConfig.psd1").Version.ToString() + [System.Version]$CurrentVersion = (Test-ModuleManifest "$psscriptroot\WDACConfig.psd1").Version.ToString() try { # First try the GitHub source - $LatestVersion = Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/HotCakeX/Harden-Windows-Security/main/WDACConfig/version.txt' + [System.Version]$LatestVersion = Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/HotCakeX/Harden-Windows-Security/main/WDACConfig/version.txt' -ProgressAction SilentlyContinue } catch { try { # If GitHub source is unavailable, use the Azure DevOps source - $LatestVersion = Invoke-RestMethod -Uri 'https://dev.azure.com/SpyNetGirl/011c178a-7b92-462b-bd23-2c014528a67e/_apis/git/repositories/5304fef0-07c0-4821-a613-79c01fb75657/items?path=/WDACConfig/version.txt' + [System.Version]$LatestVersion = Invoke-RestMethod -Uri 'https://dev.azure.com/SpyNetGirl/011c178a-7b92-462b-bd23-2c014528a67e/_apis/git/repositories/5304fef0-07c0-4821-a613-79c01fb75657/items?path=/WDACConfig/version.txt' -ProgressAction SilentlyContinue } catch { Throw [System.Security.VerificationException] 'Could not verify if the latest version of the module is installed, please check your Internet connection. You can optionally bypass the online check by using -SkipVersionCheck parameter.' @@ -129,7 +129,7 @@ function Set-LogSize { [CmdletBinding()] param ([System.Int64]$LogSize) [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' - $Log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $LogName + [System.Diagnostics.Eventing.Reader.EventLogConfiguration]$Log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $LogName $Log.MaximumSizeInBytes = $LogSize $Log.IsEnabled = $true $Log.SaveChanges() @@ -149,19 +149,19 @@ function Test-FilePath { # Loop through each file path foreach ($file in $FilePath) { # Check if the file path is valid - if (Test-Path $file -PathType 'Leaf') { + if (Test-Path -Path $file -PathType 'Leaf') { # Get the full path of the file - $FileFullPath = Resolve-Path $file + $FileFullPath = Resolve-Path -Path $file # Initialize a variable to store the result - [bool]$Result = $false + [System.Boolean]$Result = $false # Loop through each directory path - foreach ($directory in $DirectoryPath) { + foreach ($Directory in $DirectoryPath) { # Check if the directory path is valid - if (Test-Path $directory -PathType 'Container') { + if (Test-Path -Path $Directory -PathType 'Container') { # Get the full path of the directory - $DirectoryFullPath = Resolve-Path $directory + $DirectoryFullPath = Resolve-Path -Path $Directory # Check if the file path starts with the directory path if ($FileFullPath -like "$DirectoryFullPath\*") { @@ -172,7 +172,7 @@ function Test-FilePath { } else { # The directory path is not valid - Write-Warning "The directory path '$directory' is not valid." + Write-Warning "The directory path '$Directory' is not valid." } } @@ -191,8 +191,11 @@ function Test-FilePath { # Script block that lists every \Device\Harddiskvolume - https://superuser.com/questions/1058217/list-every-device-harddiskvolume # These are DriveLetter mappings +# Define a script block that fixes the drive letters in the global root namespace [scriptblock]$DriveLettersGlobalRootFixScriptBlock = { - $signature = @' + + # Import the kernel32.dll functions using P/Invoke + [System.String]$Signature = @' [DllImport("kernel32.dll", SetLastError=true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetVolumePathNamesForVolumeNameW([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, @@ -210,36 +213,51 @@ public static extern bool FindNextVolume(IntPtr hFindVolume, [Out] StringBuilder public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax); '@ - Add-Type -ErrorAction SilentlyContinue -MemberDefinition $signature -Name Win32Utils -Namespace PInvoke -Using PInvoke, System.Text - - [UInt32] $lpcchReturnLength = 0 - [UInt32] $Max = 65535 - $sbVolumeName = New-Object System.Text.StringBuilder($Max, $Max) - $sbPathName = New-Object System.Text.StringBuilder($Max, $Max) - $sbMountPoint = New-Object System.Text.StringBuilder($Max, $Max) - [IntPtr] $volumeHandle = [PInvoke.Win32Utils]::FindFirstVolume($sbVolumeName, $Max) + # Add the signature to the current session as a new type + Add-Type -ErrorAction SilentlyContinue -MemberDefinition $Signature -Name 'Win32Utils' -Namespace 'PInvoke' -Using PInvoke, System.Text + + # Initialize some variables for storing the volume names, paths, and mount points + [System.UInt32]$lpcchReturnLength = 0 + [System.UInt32]$Max = 65535 + [System.Text.StringBuilder]$SbVolumeName = New-Object -TypeName System.Text.StringBuilder($Max, $Max) + [System.Text.StringBuilder]$SbPathName = New-Object -TypeName System.Text.StringBuilder($Max, $Max) + [System.Text.StringBuilder]$SbMountPoint = New-Object -TypeName System.Text.StringBuilder($Max, $Max) + + # Find the first volume in the system and get a handle to it + [System.IntPtr]$VolumeHandle = [PInvoke.Win32Utils]::FindFirstVolume($SbVolumeName, $Max) + + # Loop through all the volumes in the system do { - $volume = $sbVolumeName.toString() - $unused = [PInvoke.Win32Utils]::GetVolumePathNamesForVolumeNameW($volume, $sbMountPoint, $Max, [Ref] $lpcchReturnLength) - $ReturnLength = [PInvoke.Win32Utils]::QueryDosDevice($volume.Substring(4, $volume.Length - 1 - 4), $sbPathName, [UInt32] $Max) + # Get the volume name as a string + [System.String]$Volume = $SbVolumeName.toString() + # Get the mount point for the volume, if any + [System.Boolean]$unused = [PInvoke.Win32Utils]::GetVolumePathNamesForVolumeNameW($Volume, $SbMountPoint, $Max, [System.Management.Automation.PSReference]$lpcchReturnLength) + # Get the device path for the volume, if any + [System.UInt32]$ReturnLength = [PInvoke.Win32Utils]::QueryDosDevice($Volume.Substring(4, $Volume.Length - 1 - 4), $SbPathName, [System.UInt32]$Max) + + # If the device path is found, create a custom object with the drive mapping information if ($ReturnLength) { - $DriveMapping = @{ - DriveLetter = $sbMountPoint.toString() - VolumeName = $volume - DevicePath = $sbPathName.ToString() + [System.Collections.Hashtable]$DriveMapping = @{ + DriveLetter = $SbMountPoint.toString() + VolumeName = $Volume + DevicePath = $SbPathName.ToString() } - Write-Output (New-Object PSObject -Property $DriveMapping) + # Write the custom object to the output stream + Write-Output (New-Object -TypeName PSObject -Property $DriveMapping) } else { - Write-Output 'No mountpoint found for: ' + $volume + # If no device path is found, write a message to the output stream + Write-Output 'No mountpoint found for: ' + $Volume } - } while ([PInvoke.Win32Utils]::FindNextVolume([IntPtr] $volumeHandle, $sbVolumeName, $Max)) + # Find the next volume in the system and repeat the loop + } while ([PInvoke.Win32Utils]::FindNextVolume([System.IntPtr]$VolumeHandle, $SbVolumeName, $Max)) + } ### Function to separately capture FileHashes of deleted files and FilePaths of available files from Event Viewer Audit Logs #### Function Get-AuditEventLogsProcessing { - param ($Date) + param ([System.DateTime]$Date) $DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock @@ -263,10 +281,10 @@ Function Get-AuditEventLogsProcessing { $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk - if (Test-Path $_.'File Name') { + if (Test-Path -Path $_.'File Name') { $AuditEventLogsProcessingResults.AvailableFilesPaths += $_.'File Name' } # If file is not currently on the disk, extract its hashes from event log - elseif (-NOT (Test-Path $_.'File Name')) { + elseif (-NOT (Test-Path -Path $_.'File Name')) { $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } } @@ -335,7 +353,7 @@ $RuleRefsContent # Gets the latest Microsoft Recommended block rules, removes its allow all rules and sets HVCI to strict [scriptblock]$GetBlockRulesSCRIPTBLOCK = { - $Rules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md').Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' + $Rules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File '.\Microsoft recommended block rules TEMP.xml' # Removing empty lines from policy file Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index 3df33a3b8..6aad9531a 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -50,7 +50,7 @@ function Set-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.Guid]$StrictKernelNoFlightRootsPolicyGUID, - [parameter(Mandatory = $false, DontShow = $true)][datetime]$LastUpdateCheck + [parameter(Mandatory = $false, DontShow = $true)][System.DateTime]$LastUpdateCheck ) begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable diff --git a/WDACConfig/WDACConfig.psd1 b/WDACConfig/WDACConfig.psd1 index a3330545a..1b355ffbd 100644 --- a/WDACConfig/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig.psd1 @@ -80,7 +80,7 @@ To get help and syntax on PowerShell console, type: '@ # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '7.3.9' + PowerShellVersion = '7.4.0' # Name of the PowerShell host required by this module # PowerShellHostName = '' From dbfd9d09ed0b755cb800cce97e49fe5ac2fa46b5 Mon Sep 17 00:00:00 2001 From: Violet Date: Wed, 29 Nov 2023 12:57:25 -0930 Subject: [PATCH 005/178] More improvements to the variable types Strictly defined more variable types and improved functions in the resources file for better readability Added more comments to the code --- WDACConfig/ArgumentCompleters.ps1 | 4 +- WDACConfig/Deploy-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 16 ++-- WDACConfig/Edit-WDACConfig.psm1 | 16 ++-- WDACConfig/New-KernelModeWDACConfig.psm1 | 2 +- WDACConfig/New-SupplementalWDACConfig.psm1 | 2 +- WDACConfig/New-WDACConfig.psm1 | 8 +- WDACConfig/Remove-WDACConfig.psm1 | 4 +- WDACConfig/Resources.ps1 | 86 ++++++++++++++-------- WDACConfig/Resources2.ps1 | 4 +- WDACConfig/Set-CommonWDACConfig.psm1 | 4 +- 11 files changed, 88 insertions(+), 60 deletions(-) diff --git a/WDACConfig/ArgumentCompleters.ps1 b/WDACConfig/ArgumentCompleters.ps1 index 8706200c2..019d475af 100644 --- a/WDACConfig/ArgumentCompleters.ps1 +++ b/WDACConfig/ArgumentCompleters.ps1 @@ -69,7 +69,7 @@ # Get the xml files in the current directory Get-ChildItem | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { - $xmlitem = [xml](Get-Content $_) + $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType if ($PolicyType -eq 'Base Policy') { @@ -99,7 +99,7 @@ # Get the xml files in the current directory Get-ChildItem | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { - $xmlitem = [xml](Get-Content $_) + $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType if ($PolicyType -eq 'Supplemental Policy') { diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index f5432ee3a..343f50856 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -108,7 +108,7 @@ function Deploy-SignedWDACConfig { foreach ($PolicyPath in $PolicyPaths) { # Gather policy details - $xml = [xml](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyType = $xml.SiPolicy.PolicyType [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 33d6356c9..94328dac6 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -48,7 +48,7 @@ function Edit-SignedWDACConfig { # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit an Unsigned policy using Edit-SignedWDACConfig cmdlet which is only made for Signed policies $_ | ForEach-Object { - $xmlTest = [xml](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID @@ -275,7 +275,7 @@ function Edit-SignedWDACConfig { $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [xml](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -505,9 +505,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item [scriptblock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { - $xml = [xml]$event.toxml() + $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | - ForEach-Object { $hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | + ForEach-Object { $Hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | ForEach-Object { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] @@ -640,7 +640,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [xml](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -836,7 +836,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [xml](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object { return "{$_}" } @@ -853,7 +853,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [xml](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID Citool --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them @@ -948,7 +948,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $CurrentID = "{$CurrentID}" Remove-Item ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue - [xml]$xml = Get-Content '.\BasePolicy.xml' + [System.Xml.XmlDocument]$xml = Get-Content '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 1e137d281..96eb46410 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -27,7 +27,7 @@ function Edit-WDACConfig { # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit a Signed policy using Edit-WDACConfig cmdlet which is only made for Unsigned policies $_ | ForEach-Object { - $xmlTest = [xml](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID @@ -208,7 +208,7 @@ function Edit-WDACConfig { $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [xml](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -412,7 +412,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [xml](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -620,9 +620,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item [scriptblock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { - $xml = [xml]$event.toxml() + $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | - ForEach-Object { $hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | + ForEach-Object { $Hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | ForEach-Object { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] @@ -725,7 +725,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [xml](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object { return "{$_}" } @@ -742,7 +742,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [xml](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID Citool --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them @@ -811,7 +811,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Write-Debug -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" - [xml]$xml = Get-Content '.\BasePolicy.xml' + [System.Xml.XmlDocument]$xml = Get-Content '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') diff --git a/WDACConfig/New-KernelModeWDACConfig.psm1 b/WDACConfig/New-KernelModeWDACConfig.psm1 index ac1e1ab13..d8c1620d8 100644 --- a/WDACConfig/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/New-KernelModeWDACConfig.psm1 @@ -56,7 +56,7 @@ function New-KernelModeWDACConfig { [System.String]$PolicyID = "{$PolicyIDInput}" # Read the xml file as an xml object - [xml]$xml = Get-Content -Path $PolicyFilePathInput + [System.Xml.XmlDocument]$xml = Get-Content -Path $PolicyFilePathInput # Define the new values for PolicyID and BasePolicyID [System.String]$newPolicyID = $PolicyID diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index ed68c3681..dbb5ab1ba 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -119,7 +119,7 @@ function New-SupplementalWDACConfig { # Ensure when user selects the -Deploy parameter, the base policy is not signed if ($Deploy) { - $xmlTest = [xml](Get-Content $PolicyPath) + $xmlTest = [System.Xml.XmlDocument](Get-Content $PolicyPath) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 90f24bc19..7ee6d85db 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -375,14 +375,14 @@ function New-WDACConfig { switch ($BasePolicyType) { 'Allow Microsoft Base' { Invoke-Command -ScriptBlock $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK | Out-Null - $xml = [xml](Get-Content .\AllowMicrosoftPlusBlockRules.xml) + $xml = [System.Xml.XmlDocument](Get-Content .\AllowMicrosoftPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' } 'Default Windows Base' { Invoke-Command -ScriptBlock $MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK | Out-Null - $xml = [xml](Get-Content .\DefaultWindowsPlusBlockRules.xml) + $xml = [System.Xml.XmlDocument](Get-Content .\DefaultWindowsPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy $BasePolicy = 'DefaultWindowsPlusBlockRules.xml' @@ -426,9 +426,9 @@ function New-WDACConfig { # Get Event viewer logs for code integrity - check the file path of all of the files in the log, resolve them using the command above - show files that are no longer available on the disk [scriptblock]$AuditEventLogsDeletedFilesScriptBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 }) { - $xml = [xml]$event.toxml() + $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | - ForEach-Object { $hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | + ForEach-Object { $Hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | ForEach-Object { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index 75393573d..fe5cf5cab 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -16,7 +16,7 @@ function Remove-WDACConfig { [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to remove an Unsigned policy $_ | ForEach-Object { - $xmlTest = [xml](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { return $True } @@ -239,7 +239,7 @@ function Remove-WDACConfig { if ($SignedBase) { foreach ($PolicyPath in $PolicyPaths) { - $xml = [xml](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object { "{$_}" } diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index 85923604b..505d581cc 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -257,40 +257,68 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa ### Function to separately capture FileHashes of deleted files and FilePaths of available files from Event Viewer Audit Logs #### Function Get-AuditEventLogsProcessing { - param ([System.DateTime]$Date) + param ( + [System.DateTime]$Date + ) - $DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock + begin { + # Get the results of the local disks from the script block + [System.Object[]]$DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock - # Defining a custom object to store and finally return it as results - $AuditEventLogsProcessingResults = [PSCustomObject]@{ - # Defining object properties as arrays - AvailableFilesPaths = @() - DeletedFileHashes = @() + # Defining a custom object to store the results and return it at the end + $AuditEventLogsProcessingResults = [PSCustomObject]@{ + # Defining object properties as arrays that store file paths + AvailableFilesPaths = [System.IO.FileInfo[]]@() + DeletedFileHashes = [System.IO.FileInfo[]]@() + } } + + process { - # Event Viewer Code Integrity logs scan - foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { - $Xml = [xml]$event.toxml() - $Xml.event.eventdata.data | - ForEach-Object { $hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | - ForEach-Object { - if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { - $hardDiskVolumeNumber = $Matches[1] - $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } - $usablePath = "$($getletter.DriveLetter)$remainingPath" - $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath - } # Check if file is currently on the disk - if (Test-Path -Path $_.'File Name') { - $AuditEventLogsProcessingResults.AvailableFilesPaths += $_.'File Name' - } # If file is not currently on the disk, extract its hashes from event log - elseif (-NOT (Test-Path -Path $_.'File Name')) { - $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + # Event Viewer Code Integrity logs scan + foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { + + $Xml = [System.Xml.XmlDocument]$event.toxml() + + $Xml.event.eventdata.data | ForEach-Object { + # Begin + $Hash = @{} + } { + # Process + $Hash[$_.name] = $_.'#text' + } { + # End + [pscustomobject]$Hash + } | ForEach-Object { + + # Define the regex pattern + [System.String]$Pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$' + + if ($_.'File Name' -match $Pattern) { + [System.Int64]$HardDiskVolumeNumber = $Matches[1] + [System.String]$RemainingPath = $Matches[2] + [PSCustomObject]$GetLetter = $DriveLettersGlobalRootFix | Where-Object { $_.devicepath -eq "\Device\HarddiskVolume$HardDiskVolumeNumber" } + [System.IO.FileInfo]$UsablePath = "$($GetLetter.DriveLetter)$RemainingPath" + $_.'File Name' = $_.'File Name' -replace $Pattern, $UsablePath + } + + # Check if the file is currently on the disk + if (Test-Path -Path $_.'File Name') { + $AuditEventLogsProcessingResults.AvailableFilesPaths += $_.'File Name' + } + + # If the file is not currently on the disk, extract its hashes from event log + else { + $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + } } } } - # return the results as an object - return $AuditEventLogsProcessingResults + + end { + # return the results as an object + return $AuditEventLogsProcessingResults + } } @@ -417,7 +445,7 @@ Function Remove-ZerosFromIDs { [System.String]$FilePath ) # Load the xml file - [xml]$Xml = Get-Content -Path $FilePath + [System.Xml.XmlDocument]$Xml = Get-Content -Path $FilePath # Get all the elements with ID attribute $Elements = $Xml.SelectNodes('//*[@ID]') @@ -464,7 +492,7 @@ Function Move-UserModeToKernelMode { ) # Load the XML file as an XmlDocument object - $Xml = [xml](Get-Content -Path $FilePath) + $Xml = [System.Xml.XmlDocument](Get-Content -Path $FilePath) # Get the SigningScenario nodes as an array $signingScenarios = $Xml.SiPolicy.SigningScenarios.SigningScenario diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 081338b8b..76e3a41b9 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -19,7 +19,7 @@ function Get-SignerInfo { ) # Load the XML file and select the Signer nodes - $xml = [xml](Get-Content $XmlFilePath) + $xml = [System.Xml.XmlDocument](Get-Content $XmlFilePath) $Signers = $xml.SiPolicy.Signers.Signer # Create an empty array to store the output @@ -705,7 +705,7 @@ function Compare-SignerAndCertificate { function Get-FileRuleOutput ($xmlPath) { # Load the xml file into a variable - $xml = [xml](Get-Content -Path $xmlPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $xmlPath) # Create an empty array to store the output [System.Object[]]$OutPutHashInfoProcessing = @() diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index 6aad9531a..3d3d10f66 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -21,7 +21,7 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ $_ | ForEach-Object { - $xmlTest = [xml](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if (!$RedFlag1 -and !$RedFlag2) { @@ -35,7 +35,7 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ $_ | ForEach-Object { - $xmlTest = [xml](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { From 2af515e568a74037ce2d9a764ec2bbc0d2be1d83 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 08:14:45 -0930 Subject: [PATCH 006/178] improvements to the code style --- WDACConfig/ArgumentCompleters.ps1 | 30 ++--- WDACConfig/Confirm-WDACConfig.psm1 | 4 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-WDACConfig.psm1 | 2 +- WDACConfig/New-WDACConfig.psm1 | 24 ++-- WDACConfig/Resources.ps1 | 99 ++++++++-------- WDACConfig/Resources2.ps1 | 162 +++++++++++++------------- 7 files changed, 160 insertions(+), 163 deletions(-) diff --git a/WDACConfig/ArgumentCompleters.ps1 b/WDACConfig/ArgumentCompleters.ps1 index 019d475af..82cf88800 100644 --- a/WDACConfig/ArgumentCompleters.ps1 +++ b/WDACConfig/ArgumentCompleters.ps1 @@ -1,6 +1,6 @@ <# # argument tab auto-completion for CertPath param to show only .cer files in current directory and 2 sub-directories recursively -[scriptblock]$ArgumentCompleterCertPath = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterCertPath = { # Note the use of -Depth 1 # Enclosing the $results = ... assignment in (...) also passes the value through. ($results = Get-ChildItem -Depth 2 -Filter *.cer | ForEach-Object { "`"$_`"" }) @@ -13,7 +13,7 @@ # argument tab auto-completion for Policy Paths to show only .xml files and only suggest files that haven't been already selected by user # https://stackoverflow.com/questions/76141864/how-to-make-a-powershell-argument-completer-that-only-suggests-files-not-already/76142865 -[scriptblock]$ArgumentCompleterPolicyPaths = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterPolicyPaths = { # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) @@ -26,7 +26,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem -Filter *.xml | ForEach-Object { + Get-ChildItem -File -Filter *.xml | ForEach-Object { # Check if the file is already selected if ($_.FullName -notin $existing) { # Return the file name with quotes @@ -36,15 +36,15 @@ } # argument tab auto-completion for Certificate common name -[scriptblock]$ArgumentCompleterCertificateCN = { - $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterCertificateCN = { + $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } $certs | ForEach-Object { return "`"$_`"" } } # Argument tab auto-completion for installed Appx package names -[scriptblock]$ArgumentCompleterAppxPackageNames = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterAppxPackageNames = { # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Get the app package names that match the word to complete @@ -54,7 +54,7 @@ } # argument tab auto-completion for Base Policy Paths to show only .xml files and only suggest files that haven't been already selected by user -[scriptblock]$ArgumentCompleterPolicyPathsBasePoliciesOnly = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterPolicyPathsBasePoliciesOnly = { # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) @@ -67,7 +67,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { + Get-ChildItem -File | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType @@ -84,7 +84,7 @@ } # argument tab auto-completion for Supplemental Policy Paths to show only .xml files and only suggest files that haven't been already selected by user -[scriptblock]$ArgumentCompleterPolicyPathsSupplementalPoliciesOnly = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterPolicyPathsSupplementalPoliciesOnly = { # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) @@ -97,7 +97,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { + Get-ChildItem -File | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType @@ -114,7 +114,7 @@ } # Opens Folder picker GUI so that user can select folders to be processed -[scriptblock]$ArgumentCompleterFolderPathsPicker = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterFolderPathsPicker = { # Load the System.Windows.Forms assembly Add-Type -AssemblyName System.Windows.Forms # non-top-most, works better with window focus @@ -125,7 +125,7 @@ } # Opens File picker GUI so that user can select an .exe file - for SignTool.exe -[scriptblock]$ArgumentCompleterExeFilePathsPicker = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterExeFilePathsPicker = { # Load the System.Windows.Forms assembly Add-Type -AssemblyName System.Windows.Forms # Create a new OpenFileDialog object @@ -141,7 +141,7 @@ } # Opens File picker GUI so that user can select a .cer file -[scriptblock]$ArgumentCompleterCerFilePathsPicker = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterCerFilePathsPicker = { # Load the System.Windows.Forms assembly Add-Type -AssemblyName System.Windows.Forms # Create a new OpenFileDialog object @@ -157,7 +157,7 @@ } # Opens File picker GUI so that user can select a .xml file -[scriptblock]$ArgumentCompleterXmlFilePathsPicker = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterXmlFilePathsPicker = { # Load the System.Windows.Forms assembly Add-Type -AssemblyName System.Windows.Forms # Create a new OpenFileDialog object @@ -174,7 +174,7 @@ # Opens Folder picker GUI so that user can select folders to be processed # WildCard file paths -[scriptblock]$ArgumentCompleterFolderPathsPickerWildCards = { +[System.Management.Automation.ScriptBlock]$ArgumentCompleterFolderPathsPickerWildCards = { # Load the System.Windows.Forms assembly Add-Type -AssemblyName System.Windows.Forms # non-top-most, works better with window focus diff --git a/WDACConfig/Confirm-WDACConfig.psm1 b/WDACConfig/Confirm-WDACConfig.psm1 index 640ea06a2..4b27d1b74 100644 --- a/WDACConfig/Confirm-WDACConfig.psm1 +++ b/WDACConfig/Confirm-WDACConfig.psm1 @@ -82,13 +82,13 @@ function Confirm-WDACConfig { if (-NOT $SkipVersionCheck) { . Update-self } # Script block to show only non-system Base policies - [scriptblock]$OnlyBasePoliciesBLOCK = { + [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { $BasePolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.PolicyID -eq $_.BasePolicyID } &$WriteLavender "`nThere are currently $(($BasePolicies.count)) Non-system Base policies deployed" $BasePolicies } # Script block to show only non-system Supplemental policies - [scriptblock]$OnlySupplementalPoliciesBLOCK = { + [System.Management.Automation.ScriptBlock]$OnlySupplementalPoliciesBLOCK = { $SupplementalPolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.PolicyID -ne $_.BasePolicyID } &$WriteLavender "`nThere are currently $(($SupplementalPolicies.count)) Non-system Supplemental policies deployed`n" $SupplementalPolicies diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 94328dac6..2d9b24533 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -503,7 +503,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" if ($Debug) { $ExesWithNoHash | ForEach-Object { Write-Debug -Message "$_" } } - [scriptblock]$KernelProtectedHashesBlock = { + [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 96eb46410..fd86e971d 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -618,7 +618,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" if ($Debug) { $ExesWithNoHash | ForEach-Object { Write-Debug -Message "$_" } } - [scriptblock]$KernelProtectedHashesBlock = { + [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 7ee6d85db..7d0e95f56 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -138,7 +138,7 @@ function New-WDACConfig { } } - [scriptblock]$GetDriverBlockRulesSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$GetDriverBlockRulesSCRIPTBLOCK = { [System.String]$DriverRules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty $DriverRules = $DriverRules -replace '', '' @@ -158,7 +158,7 @@ function New-WDACConfig { } } - [scriptblock]$MakeAllowMSFTWithBlockRulesSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$MakeAllowMSFTWithBlockRulesSCRIPTBLOCK = { param([System.Boolean]$NoCIP) # Get the latest Microsoft recommended block rules @@ -193,7 +193,7 @@ function New-WDACConfig { { Remove-Item -Path "$PolicyID.cip" -Force } } - [scriptblock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { param([System.Boolean]$NoCIP) Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' @@ -264,7 +264,7 @@ function New-WDACConfig { if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } } - [scriptblock]$DeployLatestDriverBlockRulesSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$DeployLatestDriverBlockRulesSCRIPTBLOCK = { Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip -ProgressAction SilentlyContinue Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force @@ -275,7 +275,7 @@ function New-WDACConfig { Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } - [scriptblock]$DeployLatestBlockRulesSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File '.\Microsoft recommended block rules TEMP.xml' # Remove empty lines from the policy file Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' @@ -291,7 +291,7 @@ function New-WDACConfig { Remove-Item "$PolicyID.cip" -Force } - [scriptblock]$SetAutoUpdateDriverBlockRulesSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$SetAutoUpdateDriverBlockRulesSCRIPTBLOCK = { # create a scheduled task that runs every 7 days if (-NOT (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath '\MSFT Driver Block list update\' -ErrorAction SilentlyContinue)) { # Get the SID of the SYSTEM account. It is a well-known SID, but still querying it, going to use it to create the scheduled task @@ -312,7 +312,7 @@ function New-WDACConfig { Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } - [scriptblock]$PrepMSFTOnlyAuditSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$PrepMSFTOnlyAuditSCRIPTBLOCK = { if ($PrepMSFTOnlyAudit -and $LogSize) { Set-LogSize -LogSize $LogSize } Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml -Destination .\AllowMicrosoft.xml Set-RuleOption -FilePath .\AllowMicrosoft.xml -Option 3 @@ -330,7 +330,7 @@ function New-WDACConfig { } } - [scriptblock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { if ($PrepDefaultWindowsAudit -and $LogSize) { Set-LogSize -LogSize $LogSize } Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml -Destination .\DefaultWindows_Audit.xml -Force @@ -362,7 +362,7 @@ function New-WDACConfig { } } - [scriptblock]$MakePolicyFromAuditLogsSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$MakePolicyFromAuditLogsSCRIPTBLOCK = { if ($MakePolicyFromAuditLogs -and $LogSize) { Set-LogSize -LogSize $LogSize } # Make sure there is no leftover files from previous operations of this same command Remove-Item -Path "$home\WDAC\*" -Recurse -Force -ErrorAction SilentlyContinue @@ -424,7 +424,7 @@ function New-WDACConfig { if (!$NoDeletedFiles) { # Get Event viewer logs for code integrity - check the file path of all of the files in the log, resolve them using the command above - show files that are no longer available on the disk - [scriptblock]$AuditEventLogsDeletedFilesScriptBlock = { + [System.Management.Automation.ScriptBlock]$AuditEventLogsDeletedFilesScriptBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 }) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | @@ -505,7 +505,7 @@ function New-WDACConfig { } } - [scriptblock]$MakeLightPolicySCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$MakeLightPolicySCRIPTBLOCK = { # Delete the any policy with the same name in the current working directory Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue Invoke-Command $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK -ArgumentList $true | Out-Null @@ -535,7 +535,7 @@ function New-WDACConfig { } # Script block that is used to supply extra information regarding Microsoft recommended driver block rules in commands that use them - [scriptblock]$DriversBlockListInfoGatheringSCRIPTBLOCK = { + [System.Management.Automation.ScriptBlock]$DriversBlockListInfoGatheringSCRIPTBLOCK = { [System.String]$owner = 'MicrosoftDocs' [System.String]$repo = 'windows-itpro-docs' [System.String]$path = 'windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index 505d581cc..a99702714 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -16,14 +16,14 @@ if (-NOT ($FullOSBuild -ge $Requiredbuild)) { # Get the path to SignTool function Get-SignTool { - param( + param( [parameter(Mandatory = $false)][System.String]$SignToolExePath - ) + ) # If Sign tool path wasn't provided by parameter, try to detect it automatically, if fails, stop the operation if (!$SignToolExePath) { if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64') { if ( Test-Path -Path 'C:\Program Files (x86)\Windows Kits\*\bin\*\x64\signtool.exe') { - $SignToolExePath = 'C:\Program Files (x86)\Windows Kits\*\bin\*\x64\signtool.exe' + $SignToolExePath = 'C:\Program Files (x86)\Windows Kits\*\bin\*\x64\signtool.exe' } else { Throw [System.IO.FileNotFoundException] 'signtool.exe could not be found' @@ -39,7 +39,7 @@ function Get-SignTool { } } try { - # Validate the SignTool executable + # Validate the SignTool executable [System.Version]$WindowsSdkVersion = '10.0.22621.755' # Setting the minimum version of SignTool that is allowed to be executed [System.Boolean]$GreenFlag1 = (((Get-Item -Path $SignToolExePath).VersionInfo).ProductVersionRaw -ge $WindowsSdkVersion) [System.Boolean]$GreenFlag2 = (((Get-Item -Path $SignToolExePath).VersionInfo).FileVersionRaw -ge $WindowsSdkVersion) @@ -52,11 +52,11 @@ function Get-SignTool { } # If any of the 5 checks above fails, the operation stops if (!$GreenFlag1 -or !$GreenFlag2 -or !$GreenFlag3 -or !$GreenFlag4 -or !$GreenFlag5) { - Throw [System.Security.VerificationException] 'The SignTool executable was found but could not be verified. Please download the latest Windows SDK to get the newest SignTool executable. Official download link: http://aka.ms/WinSDK' + Throw [System.Security.VerificationException] 'The SignTool executable was found but could not be verified. Please download the latest Windows SDK to get the newest SignTool executable. Official download link: http://aka.ms/WinSDK' } else { return $SignToolExePath - } + } } @@ -69,7 +69,7 @@ function Update-self { } catch { # If the User Config file doesn't exist then set this flag to perform online update check - [System.Boolean]$PerformOnlineUpdateCheck = $true + [System.Boolean]$PerformOnlineUpdateCheck = $true } # Ensure these are run only if the User Config file exists and contains a date for last update check @@ -83,7 +83,7 @@ function Update-self { # Only check for updates if the last attempt occured more than 10 minutes ago or the User Config file for last update check doesn't exist # This prevents the module from constantly doing an update check by fetching the version file from GitHub if (($TimeDiff -gt 10) -or $PerformOnlineUpdateCheck) { - + [System.Version]$CurrentVersion = (Test-ModuleManifest "$psscriptroot\WDACConfig.psd1").Version.ToString() try { # First try the GitHub source @@ -92,7 +92,7 @@ function Update-self { catch { try { # If GitHub source is unavailable, use the Azure DevOps source - [System.Version]$LatestVersion = Invoke-RestMethod -Uri 'https://dev.azure.com/SpyNetGirl/011c178a-7b92-462b-bd23-2c014528a67e/_apis/git/repositories/5304fef0-07c0-4821-a613-79c01fb75657/items?path=/WDACConfig/version.txt' -ProgressAction SilentlyContinue + [System.Version]$LatestVersion = Invoke-RestMethod -Uri 'https://dev.azure.com/SpyNetGirl/011c178a-7b92-462b-bd23-2c014528a67e/_apis/git/repositories/5304fef0-07c0-4821-a613-79c01fb75657/items?path=/WDACConfig/version.txt' -ProgressAction SilentlyContinue } catch { Throw [System.Security.VerificationException] 'Could not verify if the latest version of the module is installed, please check your Internet connection. You can optionally bypass the online check by using -SkipVersionCheck parameter.' @@ -104,30 +104,30 @@ function Update-self { # Do this if the module was installed properly using Install-module cmdlet try { Uninstall-Module -Name 'WDACConfig' -AllVersions -Force -ErrorAction Stop - Install-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force + Install-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force Import-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force -Global } # Do this if module files/folder was just copied to Documents folder and not properly installed - Should rarely happen catch { Install-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force Import-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force -Global - } + } # Make sure the old version isn't run after update - Write-Output "$($PSStyle.Foreground.FromRGB(152,255,152))Update successful, please run the cmdlet again.$($PSStyle.Reset)" + Write-Output "$($PSStyle.Foreground.FromRGB(152,255,152))Update successful, please run the cmdlet again.$($PSStyle.Reset)" break return } # Reset the last update timer to the current time Set-CommonWDACConfig -LastUpdateCheck $(Get-Date ) | Out-Null - } + } } # Increase Code Integrity Operational Event Logs size from the default 1MB to user defined size function Set-LogSize { [CmdletBinding()] - param ([System.Int64]$LogSize) + param ([System.Int64]$LogSize) [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' [System.Diagnostics.Eventing.Reader.EventLogConfiguration]$Log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $LogName $Log.MaximumSizeInBytes = $LogSize @@ -192,14 +192,14 @@ function Test-FilePath { # Script block that lists every \Device\Harddiskvolume - https://superuser.com/questions/1058217/list-every-device-harddiskvolume # These are DriveLetter mappings # Define a script block that fixes the drive letters in the global root namespace -[scriptblock]$DriveLettersGlobalRootFixScriptBlock = { +[System.Management.Automation.ScriptBlock]$DriveLettersGlobalRootFixScriptBlock = { # Import the kernel32.dll functions using P/Invoke [System.String]$Signature = @' [DllImport("kernel32.dll", SetLastError=true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetVolumePathNamesForVolumeNameW([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, -[MarshalAs(UnmanagedType.LPWStr)] [Out] StringBuilder lpszVolumeNamePaths, uint cchBuferLength, +[MarshalAs(UnmanagedType.LPWStr)] [Out] StringBuilder lpszVolumeNamePaths, uint cchBuferLength, ref UInt32 lpcchReturnLength); [DllImport("kernel32.dll", SetLastError = true)] @@ -222,10 +222,10 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa [System.Text.StringBuilder]$SbVolumeName = New-Object -TypeName System.Text.StringBuilder($Max, $Max) [System.Text.StringBuilder]$SbPathName = New-Object -TypeName System.Text.StringBuilder($Max, $Max) [System.Text.StringBuilder]$SbMountPoint = New-Object -TypeName System.Text.StringBuilder($Max, $Max) - + # Find the first volume in the system and get a handle to it [System.IntPtr]$VolumeHandle = [PInvoke.Win32Utils]::FindFirstVolume($SbVolumeName, $Max) - + # Loop through all the volumes in the system do { # Get the volume name as a string @@ -234,7 +234,7 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa [System.Boolean]$unused = [PInvoke.Win32Utils]::GetVolumePathNamesForVolumeNameW($Volume, $SbMountPoint, $Max, [System.Management.Automation.PSReference]$lpcchReturnLength) # Get the device path for the volume, if any [System.UInt32]$ReturnLength = [PInvoke.Win32Utils]::QueryDosDevice($Volume.Substring(4, $Volume.Length - 1 - 4), $SbPathName, [System.UInt32]$Max) - + # If the device path is found, create a custom object with the drive mapping information if ($ReturnLength) { [System.Collections.Hashtable]$DriveMapping = @{ @@ -248,7 +248,7 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa else { # If no device path is found, write a message to the output stream Write-Output 'No mountpoint found for: ' + $Volume - } + } # Find the next volume in the system and repeat the loop } while ([PInvoke.Win32Utils]::FindNextVolume([System.IntPtr]$VolumeHandle, $SbVolumeName, $Max)) @@ -274,39 +274,36 @@ Function Get-AuditEventLogsProcessing { } process { - + # Event Viewer Code Integrity logs scan - foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { - + foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { + $Xml = [System.Xml.XmlDocument]$event.toxml() - - $Xml.event.eventdata.data | ForEach-Object { - # Begin - $Hash = @{} - } { - # Process + + $Xml.event.eventdata.data | ForEach-Object -Begin { + $Hash = @{} + } -Process { $Hash[$_.name] = $_.'#text' - } { - # End + } -End { [pscustomobject]$Hash } | ForEach-Object { # Define the regex pattern [System.String]$Pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$' - + if ($_.'File Name' -match $Pattern) { [System.Int64]$HardDiskVolumeNumber = $Matches[1] [System.String]$RemainingPath = $Matches[2] - [PSCustomObject]$GetLetter = $DriveLettersGlobalRootFix | Where-Object { $_.devicepath -eq "\Device\HarddiskVolume$HardDiskVolumeNumber" } + [PSCustomObject]$GetLetter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$HardDiskVolumeNumber" } [System.IO.FileInfo]$UsablePath = "$($GetLetter.DriveLetter)$RemainingPath" $_.'File Name' = $_.'File Name' -replace $Pattern, $UsablePath } # Check if the file is currently on the disk if (Test-Path -Path $_.'File Name') { - $AuditEventLogsProcessingResults.AvailableFilesPaths += $_.'File Name' + $AuditEventLogsProcessingResults.AvailableFilesPaths += $_.'File Name' } - + # If the file is not currently on the disk, extract its hashes from event log else { $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' @@ -327,7 +324,7 @@ function New-EmptyPolicy { param ( $RulesContent, $RuleRefsContent - ) + ) [System.String]$EmptyPolicy = @" @@ -380,12 +377,12 @@ $RuleRefsContent # Gets the latest Microsoft Recommended block rules, removes its allow all rules and sets HVCI to strict -[scriptblock]$GetBlockRulesSCRIPTBLOCK = { - $Rules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' +[System.Management.Automation.ScriptBlock]$GetBlockRulesSCRIPTBLOCK = { + [System.String]$Rules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File '.\Microsoft recommended block rules TEMP.xml' # Removing empty lines from policy file - Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' - Remove-Item '.\Microsoft recommended block rules TEMP.xml' -Force + Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath '.\Microsoft recommended block rules.xml' + Remove-Item -Path '.\Microsoft recommended block rules TEMP.xml' -Force Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' [PSCustomObject]@{ @@ -398,20 +395,20 @@ $RuleRefsContent function Confirm-CertCN ([System.String]$CN) { $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } + } $certs -contains $CN ? $true : $false } # script blocks for custom color writing -[scriptblock]$WriteHotPink = { Write-Output "$($PSStyle.Foreground.FromRGB(255,105,180))$($args[0])$($PSStyle.Reset)" } -[scriptblock]$WritePink = { Write-Output "$($PSStyle.Foreground.FromRGB(255,0,230))$($args[0])$($PSStyle.Reset)" } -[scriptblock]$WriteLavender = { Write-Output "$($PSStyle.Foreground.FromRgb(255,179,255))$($args[0])$($PSStyle.Reset)" } -[scriptblock]$WriteTeaGreen = { Write-Output "$($PSStyle.Foreground.FromRgb(133, 222, 119))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WriteHotPink = { Write-Output "$($PSStyle.Foreground.FromRGB(255,105,180))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WritePink = { Write-Output "$($PSStyle.Foreground.FromRGB(255,0,230))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WriteLavender = { Write-Output "$($PSStyle.Foreground.FromRgb(255,179,255))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WriteTeaGreen = { Write-Output "$($PSStyle.Foreground.FromRgb(133, 222, 119))$($args[0])$($PSStyle.Reset)" } # Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable function Get-FileRules { - param ($HashesArray) + param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $Rules += Write-Output "`n" $Rules += Write-Output "`n" @@ -425,7 +422,7 @@ function Get-FileRules { # Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable function Get-RuleRefs { - param ($HashesArray) + param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $RulesRefs += Write-Output "`n" $RulesRefs += Write-Output "`n" @@ -443,7 +440,7 @@ Function Remove-ZerosFromIDs { [Parameter(Mandatory = $true)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [System.String]$FilePath - ) + ) # Load the xml file [System.Xml.XmlDocument]$Xml = Get-Content -Path $FilePath @@ -489,7 +486,7 @@ Function Move-UserModeToKernelMode { [Parameter(Mandatory = $true)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [System.String]$FilePath - ) + ) # Load the XML file as an XmlDocument object $Xml = [System.Xml.XmlDocument](Get-Content -Path $FilePath) @@ -498,10 +495,10 @@ Function Move-UserModeToKernelMode { $signingScenarios = $Xml.SiPolicy.SigningScenarios.SigningScenario # Find the SigningScenario node with Value 131 and store it in a variable - $signingScenario131 = $signingScenarios | Where-Object { $_.Value -eq '131' } + $signingScenario131 = $signingScenarios | Where-Object -FilterScript { $_.Value -eq '131' } # Find the SigningScenario node with Value 12 and store it in a variable - $signingScenario12 = $signingScenarios | Where-Object { $_.Value -eq '12' } + $signingScenario12 = $signingScenarios | Where-Object -FilterScript { $_.Value -eq '12' } # Get the AllowedSigners node from the SigningScenario node with Value 12 $AllowedSigners12 = $signingScenario12.ProductSigners.AllowedSigners diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 76e3a41b9..145211d73 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -11,20 +11,20 @@ class Signer { [string]$CertRoot [string]$CertPublisher } - + # Function that takes an XML file path as input and returns an array of Signer objects function Get-SignerInfo { param( [Parameter(Mandatory = $true)][string]$XmlFilePath ) - + # Load the XML file and select the Signer nodes $xml = [System.Xml.XmlDocument](Get-Content $XmlFilePath) $Signers = $xml.SiPolicy.Signers.Signer - + # Create an empty array to store the output [System.Object[]]$output = @() - + # Loop through each Signer node and extract the information foreach ($signer in $signers) { # Create a new Signer object and assign the properties @@ -33,11 +33,11 @@ function Get-SignerInfo { $SignerObj.Name = $signer.Name $SignerObj.CertRoot = $signer.CertRoot.Value $SignerObj.CertPublisher = $signer.CertPublisher.Value - + # Add the Signer object to the output array $output += $SignerObj } - + # Return the output array return $output } @@ -45,25 +45,25 @@ function Get-SignerInfo { # Function to calculate the TBS of a certificate function Get-TBSCertificate { param ($Cert) - + # Get the raw data of the certificate $RawData = $Cert.RawData - + # Create an ASN.1 reader to parse the certificate $AsnReader = New-Object System.Formats.Asn1.AsnReader -ArgumentList $RawData, ([System.Formats.Asn1.AsnEncodingRules]::DER) - + # Read the certificate sequence $Certificate = $AsnReader.ReadSequence() - + # Read the TBS (To be signed) value of the certificate $TbsCertificate = $Certificate.ReadEncodedValue() - + # Read the signature algorithm sequence $SignatureAlgorithm = $Certificate.ReadSequence() - + # Read the algorithm OID of the signature $AlgorithmOid = $SignatureAlgorithm.ReadObjectIdentifier() - + # Define a hash function based on the algorithm OID switch ($AlgorithmOid) { '1.2.840.113549.1.1.4' { $HashFunction = [System.Security.Cryptography.MD5]::Create() } @@ -77,14 +77,14 @@ function Get-TBSCertificate { '1.2.840.10045.4.3.4' { $HashFunction = [System.Security.Cryptography.SHA512]::Create() } '1.2.840.113549.1.1.5' { $HashFunction = [System.Security.Cryptography.SHA1]::Create() } '1.2.840.113549.1.1.11' { $HashFunction = [System.Security.Cryptography.SHA256]::Create() } - '1.2.840.113549.1.1.12' { $HashFunction = [System.Security.Cryptography.SHA384]::Create() } + '1.2.840.113549.1.1.12' { $HashFunction = [System.Security.Cryptography.SHA384]::Create() } '1.2.840.113549.1.1.13' { $HashFunction = [System.Security.Cryptography.SHA512]::Create() } default { throw "No handler for algorithm $AlgorithmOid" } } - + # Compute the hash of the TBS value using the hash function - $Hash = $HashFunction.ComputeHash($TbsCertificate.ToArray()) - + $Hash = $HashFunction.ComputeHash($TbsCertificate.ToArray()) + # Convert the hash to a hex string and return it return [System.BitConverter]::ToString($hash) -replace '-', '' } @@ -142,11 +142,11 @@ function Get-AuthenticodeSignatureEx { $CERT_QUERY_OBJECT_FILE = 0x1 $CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 0x400 $CERT_QUERY_FORMAT_FLAG_BINARY = 0x2 - + # Define a helper function to get the timestamps of the countersigners function getTimeStamps($SignerInfo) { [System.Object[]]$retValue = @() - foreach ($CounterSignerInfos in $Infos.CounterSignerInfos) { + foreach ($CounterSignerInfos in $Infos.CounterSignerInfos) { # Get the signing time attribute from the countersigner info object $sTime = ($CounterSignerInfos.SignedAttributes | Where-Object { $_.Oid.Value -eq '1.2.840.113549.1.9.5' }).Values | ` Where-Object { $null -ne $_.SigningTime } @@ -205,7 +205,7 @@ function Get-AuthenticodeSignatureEx { $Output | Add-Member -MemberType NoteProperty -Name TimeStamps -Value $null $Output | Add-Member -MemberType NoteProperty -Name DigestAlgorithm -Value $Infos.DigestAlgorithm.FriendlyName # Call the helper function to get the timestamps of the countersigners and assign it to the TimeStamps property - $Output.TimeStamps = getTimeStamps $Infos + $Output.TimeStamps = getTimeStamps $Infos # Check if there is a nested signature attribute in the signer info object by looking for the OID 1.3.6.1.4.1.311.2.4.1 $second = $Infos.UnsignedAttributes | Where-Object { $_.Oid.Value -eq '1.3.6.1.4.1.311.2.4.1' } if ($second) { @@ -214,7 +214,7 @@ function Get-AuthenticodeSignatureEx { $value = $second.Values | Where-Object { $_.Oid.Value -eq '1.3.6.1.4.1.311.2.4.1' } $SignedCms2 = New-Object Security.Cryptography.Pkcs.SignedCms # Create another SignedCms object to decode the nested signature data $SignedCms2.Decode($value.RawData) # Decode the nested signature data and populate the SignedCms object properties - $Output | Add-Member -MemberType NoteProperty -Name NestedSignature -Value $null + $Output | Add-Member -MemberType NoteProperty -Name NestedSignature -Value $null $Infos = $SignedCms2.SignerInfos[0] # Get the first signer info object from the nested signature SignedCms object # Create a custom object with some properties of the nested signature, such as signer certificate, digest algorithm and timestamps $nested = New-Object psobject -Property @{ @@ -249,7 +249,7 @@ function Get-SignedFileCertificates { # Define two sets of parameters, one for the FilePath and one for the CertObject [Parameter()] [string]$FilePath, - [Parameter(ValueFromPipeline = $true)] + [Parameter(ValueFromPipeline = $true)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$X509Certificate2 ) @@ -278,11 +278,11 @@ function Get-CertificateDetails { [System.String]$FilePath, [Parameter(ParameterSetName = 'Based on Certificate', Mandatory = $true)] - $X509Certificate2, + $X509Certificate2, + + [Parameter(ParameterSetName = 'Based on Certificate')] + [System.String]$LeafCNOfTheNestedCertificate, # This is used only for when -X509Certificate2 parameter is used, so that we can filter out the Leaf certificate and only get the Intermediate certificates at the end of this function - [Parameter(ParameterSetName = 'Based on Certificate')] - [System.String]$LeafCNOfTheNestedCertificate, # This is used only for when -X509Certificate2 parameter is used, so that we can filter out the Leaf certificate and only get the Intermediate certificates at the end of this function - [Parameter(ParameterSetName = 'Based on File Path')] [Parameter(ParameterSetName = 'Based on Certificate')] [switch]$IntermediateOnly, @@ -306,7 +306,7 @@ function Get-CertificateDetails { # Loop through each certificate in the collection and call this function recursively with the certificate object as an input foreach ($Cert in $CertCollection) { - + # Build the certificate chain $Chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain @@ -315,8 +315,8 @@ function Get-CertificateDetails { $chain.ChainPolicy.RevocationFlag = 'EndCertificateOnly' $chain.ChainPolicy.VerificationFlags = 'NoFlag' - [void]$Chain.Build($Cert) - + [void]$Chain.Build($Cert) + # If AllCertificates is present, loop through all chain elements and display all certificates foreach ($Element in $Chain.ChainElements) { # Create a custom object with the certificate properties @@ -327,10 +327,10 @@ function Get-CertificateDetails { $Element.Certificate.Subject -match 'CN=(?.*?),.*' | Out-Null $SubjectCN = $matches['InitialRegexTest2'] -like '*"*' ? ($Element.Certificate.Subject -split 'CN="(.+?)"')[1] : $matches['InitialRegexTest2'] - + $Element.Certificate.Issuer -match 'CN=(?.*?),.*' | Out-Null $IssuerCN = $matches['InitialRegexTest3'] -like '*"*' ? ($Element.Certificate.Issuer -split 'CN="(.+?)"')[1] : $matches['InitialRegexTest3'] - + # Get the TBS value of the certificate using the Get-TBSCertificate function $TbsValue = Get-TBSCertificate -cert $Element.Certificate # Create a custom object with the extracted properties and the TBS value @@ -338,9 +338,9 @@ function Get-CertificateDetails { SubjectCN = $SubjectCN IssuerCN = $IssuerCN NotAfter = $element.Certificate.NotAfter - TBSValue = $TbsValue - } - } + TBSValue = $TbsValue + } + } } if ($FilePath) { @@ -351,13 +351,13 @@ function Get-CertificateDetails { $CertificateUsingAlternativeMethod = [System.Security.Cryptography.X509Certificates.X509Certificate]::CreateFromSignedFile($FilePath) $CertificateUsingAlternativeMethod.Subject -match 'CN=(?.*?),.*' | Out-Null - + [string]$TestAgainst = $matches['InitialRegexTest4'] -like '*"*' ? ((Get-AuthenticodeSignature -FilePath $FilePath).SignerCertificate.Subject -split 'CN="(.+?)"')[1] : $matches['InitialRegexTest4'] - + if ($IntermediateOnly) { - $FinalObj = $Obj | + $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -ne $TestAgainst } | # To omit the Leaf certificate Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property @@ -366,8 +366,8 @@ function Get-CertificateDetails { } elseif ($LeafCertificate) { - - $FinalObj = $Obj | + + $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -eq $TestAgainst } | # To get the Leaf certificate Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property @@ -375,30 +375,30 @@ function Get-CertificateDetails { return $FinalObj } - } + } # If nested certificate is being processed and X509Certificate2 object is passed elseif ($X509Certificate2) { - + if ($IntermediateOnly) { - $FinalObj = $Obj | - Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result + $FinalObj = $Obj | + Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -ne $LeafCNOfTheNestedCertificate } | # To omit the Leaf certificate Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj - } + } elseif ($LeafCertificate) { - $FinalObj = $Obj | + $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -eq $LeafCNOfTheNestedCertificate } | # To get the Leaf certificate Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj - } + } } } @@ -414,7 +414,7 @@ function Get-CertificateDetails { [Parameter()] [ValidateScript({ Test-Path $_ -PathType Leaf })] [string]$FilePath, - $X509Certificate2, + $X509Certificate2, [switch]$IntermediateOnly, [switch]$AllCertificates, [switch]$LeafCertificate @@ -428,7 +428,7 @@ function Get-CertificateDetails { elseif ($X509Certificate2) { $Cert = $X509Certificate2 } - + # Build the certificate chain $Chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain @@ -438,7 +438,7 @@ function Get-CertificateDetails { $chain.ChainPolicy.VerificationFlags = 'NoFlag' [void]$Chain.Build($Cert) - + # Check the value of the switch parameters if ($IntermediateOnly) { # If IntermediateOnly is present, loop through the chain elements and display only the intermediate certificates @@ -497,7 +497,7 @@ function Get-CertificateDetails { } # Display the object Write-Output 'Leaf Certificate:' - Write-Output $obj + Write-Output $obj } else { # If none of the switch parameters are present, display a message to inform the user of their options @@ -513,11 +513,11 @@ function Compare-SignerAndCertificate { param( [Parameter(Mandatory = $true)][string]$XmlFilePath, [Parameter(Mandatory = $true)] [string]$SignedFilePath - ) + ) # Get the signer information from the XML file path using the Get-SignerInfo function - $SignerInfo = Get-SignerInfo -XmlFilePath $XmlFilePath - + $SignerInfo = Get-SignerInfo -XmlFilePath $XmlFilePath + # An array to store the details of the main certificate of the signed file [System.Object[]]$CertificateDetails = @() @@ -529,21 +529,21 @@ function Compare-SignerAndCertificate { # Get the certificate details from the signed file path using the Get-CertificateDetails function with the -IntermediateOnly parameter $CertificateDetails = Get-CertificateDetails -IntermediateOnly -FilePath $SignedFilePath - + # Get the Nested certificate of the signed file, if any $ExtraCertificateDetails = Get-AuthenticodeSignatureEx -FilePath $SignedFilePath # Extract it from the nested property $NestedCertificate = ($ExtraCertificateDetails).NestedSignature.SignerCertificate - + if ($null -ne $NestedCertificate) { - # First get the CN of the leaf certificate of the nested Certificate + # First get the CN of the leaf certificate of the nested Certificate $NestedCertificate.Subject -match 'CN=(?.*?),.*' | Out-Null $LeafCNOfTheNestedCertificate = $matches['InitialRegexTest1'] -like '*"*' ? ($NestedCertificate.Subject -split 'CN="(.+?)"')[1] : $matches['InitialRegexTest1'] - + # Send the nested certificate along with its Leaf certificate's CN to the Get-CertificateDetails function with -IntermediateOnly parameter in order to only get the intermediate certificates of the Nested certificate - $NestedCertificateDetails = Get-CertificateDetails -IntermediateOnly -X509Certificate2 $NestedCertificate -LeafCNOfTheNestedCertificate $LeafCNOfTheNestedCertificate + $NestedCertificateDetails = Get-CertificateDetails -IntermediateOnly -X509Certificate2 $NestedCertificate -LeafCNOfTheNestedCertificate $LeafCNOfTheNestedCertificate } @@ -552,7 +552,7 @@ function Compare-SignerAndCertificate { # Declare $NestedLeafCertificateDetails as an array [System.Object[]]$NestedLeafCertificateDetails = @() - + # Get the leaf certificate details of the Main Certificate from the signed file path $LeafCertificateDetails = Get-CertificateDetails -LeafCertificate -FilePath $SignedFilePath @@ -562,7 +562,7 @@ function Compare-SignerAndCertificate { $NestedLeafCertificateDetails = Get-CertificateDetails -LeafCertificate -X509Certificate2 $NestedCertificate -LeafCNOfTheNestedCertificate $LeafCNOfTheNestedCertificate } - + # Loop through each signer in the signer information array foreach ($Signer in $SignerInfo) { # Create a custom object to store the comparison result for this signer @@ -580,7 +580,7 @@ function Compare-SignerAndCertificate { CertPublisherMatch = $false FilePath = $SignedFilePath # Add the file path to the object } - + # Loop through each certificate in the certificate details array of the Main Cert foreach ($Certificate in $CertificateDetails) { @@ -604,7 +604,7 @@ function Compare-SignerAndCertificate { } # Check if the signer's name (Referring to the one in the XML file) matches the Intermediate certificate's SubjectCN - if ($Signer.Name -eq $Certificate.SubjectCN) { + if ($Signer.Name -eq $Certificate.SubjectCN) { # Set the CertNameMatch to true $ComparisonResult.CertNameMatch = $true # this should naturally be always true like the CertRootMatch because this is the CN of the same cert that has its TBS value in the xml file in signers } @@ -615,13 +615,13 @@ function Compare-SignerAndCertificate { # if the signed file has nested certificate, only set a flag instead of setting the entire CertPublisherMatch property to true if ($null -ne $NestedCertificate) { - $CertPublisherMatchPart1 = $true + $CertPublisherMatchPart1 = $true } - else { - $ComparisonResult.CertPublisherMatch = $true + else { + $ComparisonResult.CertPublisherMatch = $true } } - + # Break out of the inner loop whether we found a match for this signer or not break } @@ -642,9 +642,9 @@ function Compare-SignerAndCertificate { $ComparisonResult.CertSubjectCN = $Certificate.SubjectCN $ComparisonResult.CertIssuerCN = $Certificate.IssuerCN $ComparisonResult.CertNotAfter = $Certificate.NotAfter - $ComparisonResult.CertTBSValue = $Certificate.TBSValue + $ComparisonResult.CertTBSValue = $Certificate.TBSValue - # When file has nested signature, only set a flag instead of setting the entire property to true + # When file has nested signature, only set a flag instead of setting the entire property to true $CertRootMatchPart2 = $true # Check if the signer's Name matches the Intermediate certificate's SubjectCN @@ -656,10 +656,10 @@ function Compare-SignerAndCertificate { # Check if the signer's CertPublisher (aka Leaf Certificate's CN used in the xml policy) matches the leaf certificate's SubjectCN (of the file) if ($Signer.CertPublisher -eq $LeafCNOfTheNestedCertificate) { - # If yes, set the CertPublisherMatch to true for this comparison result object - $CertPublisherMatchPart2 = $true + # If yes, set the CertPublisherMatch to true for this comparison result object + $CertPublisherMatchPart2 = $true } - + # Break out of the inner loop whether we found a match for this signer or not break } @@ -675,28 +675,28 @@ function Compare-SignerAndCertificate { $ComparisonResult.CertRootMatch = $true # meaning all of the TBS values of the double signed file's intermediate certificates exists in the xml file's signers' TBS values } else { - $ComparisonResult.CertRootMatch = $false + $ComparisonResult.CertRootMatch = $false } - + # check if Lean certificate CN of both of the file's certificates (Nested and Main) are available in the Signers in xml policy if (($CertPublisherMatchPart1 -eq $true) -and ($CertPublisherMatchPart2 -eq $true)) { - $ComparisonResult.CertPublisherMatch = $true + $ComparisonResult.CertPublisherMatch = $true } else { - $ComparisonResult.CertPublisherMatch = $false + $ComparisonResult.CertPublisherMatch = $false } } - + # Add the comparison result object to the comparison results array $ComparisonResults += $ComparisonResult - + } - + # Return the comparison results array - return $ComparisonResults -} + return $ComparisonResults +} @@ -721,7 +721,7 @@ function Get-FileRuleOutput ($xmlPath) { # Extract the file path from the FriendlyName attribute using regex $FilePathForHash = $filerule.FriendlyName -replace ' (Hash (Sha1|Sha256|Page Sha1|Page Sha256|Authenticode SIP Sha256))$', '' - + # Create a custom object with the three properties $object = [PSCustomObject]@{ HashValue = $hashvalue From 846553ab6a601ab5ad8063dea906a0b542e32f14 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 08:30:25 -0930 Subject: [PATCH 007/178] improved parameters with best practices --- WDACConfig/ArgumentCompleters.ps1 | 8 ++-- WDACConfig/Edit-SignedWDACConfig.psm1 | 48 +++++++++++----------- WDACConfig/Edit-WDACConfig.psm1 | 44 ++++++++++---------- WDACConfig/Invoke-WDACSimulation.psm1 | 2 +- WDACConfig/New-DenyWDACConfig.psm1 | 12 +++--- WDACConfig/New-KernelModeWDACConfig.psm1 | 12 +++--- WDACConfig/New-SupplementalWDACConfig.psm1 | 6 +-- WDACConfig/New-WDACConfig.psm1 | 26 ++++++------ WDACConfig/Remove-WDACConfig.psm1 | 10 ++--- WDACConfig/Resources.ps1 | 8 +--- WDACConfig/Resources2.ps1 | 10 ++--- WDACConfig/Set-CommonWDACConfig.psm1 | 4 +- 12 files changed, 92 insertions(+), 98 deletions(-) diff --git a/WDACConfig/ArgumentCompleters.ps1 b/WDACConfig/ArgumentCompleters.ps1 index 82cf88800..6e2323d89 100644 --- a/WDACConfig/ArgumentCompleters.ps1 +++ b/WDACConfig/ArgumentCompleters.ps1 @@ -26,7 +26,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem -File -Filter *.xml | ForEach-Object { + Get-ChildItem -File -Filter *.xml | ForEach-Object -Process { # Check if the file is already selected if ($_.FullName -notin $existing) { # Return the file name with quotes @@ -40,7 +40,7 @@ $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } - $certs | ForEach-Object { return "`"$_`"" } + $certs | ForEach-Object -Process { return "`"$_`"" } } # Argument tab auto-completion for installed Appx package names @@ -48,7 +48,7 @@ # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Get the app package names that match the word to complete - Get-AppxPackage -Name *$wordToComplete* | ForEach-Object { + Get-AppxPackage -Name *$wordToComplete* | ForEach-Object -Process { "`"$($_.Name)`"" } } @@ -97,7 +97,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem -File | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { + Get-ChildItem -File | Where-Object { $_.extension -like '*.xml' } | ForEach-Object -Process { $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 2d9b24533..3d258cf3a 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -47,12 +47,12 @@ function Edit-SignedWDACConfig { [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit an Unsigned policy using Edit-SignedWDACConfig cmdlet which is only made for Signed policies - $_ | ForEach-Object { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object { "{$_}" } + $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if ($RedFlag1 -or $RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { @@ -293,7 +293,7 @@ function Edit-SignedWDACConfig { ConvertFrom-CIPolicy $PolicyPath '.\EnforcedModeTemp.cip' | Out-Null # Sign both CIPs - '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object { + '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', "`"$_`"" @@ -366,7 +366,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host 'Here are the paths you selected:' -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object { $_ } + $ProgramsPaths | ForEach-Object -Process { $_ } ################################### EventCapturing ################################ @@ -391,7 +391,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-Item -Path "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" - $TestFilePathResults | ForEach-Object { + $TestFilePathResults | ForEach-Object -Process { Write-Debug -Message "$_" Copy-Item -Path $_ -Destination "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue } @@ -428,7 +428,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { Write-Debug -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" - $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object { + $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { Write-Debug -Message "$($_.'File Name')" } @@ -483,7 +483,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $AnyAvailableExes = (Get-ChildItem -Recurse -Path $ProgramsPath -Filter '*.exe').FullName # if any .exe was found then continue testing them if ($AnyAvailableExes) { - $AnyAvailableExes | ForEach-Object { + $AnyAvailableExes | ForEach-Object -Process { $CurrentExeWithNoHash = $_ try { # Testing each executable to find the protected ones @@ -501,14 +501,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($ExesWithNoHash) { Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" - if ($Debug) { $ExesWithNoHash | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | - ForEach-Object { $Hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | - ForEach-Object { + ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | + ForEach-Object -Process { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] @@ -542,13 +542,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } else { Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on.`n" - $ExesWithNoHash | ForEach-Object { Write-Warning -Message "$_" } + $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -592,7 +592,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' @@ -658,7 +658,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item ConvertFrom-CIPolicy $PolicyPath '.\EnforcedModeTemp.cip' | Out-Null # Sign both CIPs - '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object { + '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', "`"$_`"" @@ -754,7 +754,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host "`nHere are the paths you selected:" -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object { $_ } + $ProgramsPaths | ForEach-Object -Process { $_ } #Process Program Folders From User input @@ -787,7 +787,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -802,7 +802,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' @@ -839,7 +839,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object { return "{$_}" } + $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies if ($SupplementalPolicyType -ne 'Supplemental Policy') { Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." @@ -896,15 +896,15 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" - @(0, 2, 5, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(0, 2, 5, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } # Configure required services for ISG authorization Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow @@ -930,8 +930,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } } diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index fd86e971d..3facd4dd9 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -26,12 +26,12 @@ function Edit-WDACConfig { [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit a Signed policy using Edit-WDACConfig cmdlet which is only made for Unsigned policies - $_ | ForEach-Object { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object { "{$_}" } + $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if (!$RedFlag1 -and !$RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { @@ -328,7 +328,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host "`nHere are the paths you selected:" -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object { $_ } + $ProgramsPaths | ForEach-Object -Process { $_ } #Process Program Folders From User input @@ -361,7 +361,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -375,7 +375,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $SuppPolicyID = $SuppPolicyID.Substring(11) # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' @@ -481,7 +481,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host 'Here are the paths you selected:' -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object { $_ } + $ProgramsPaths | ForEach-Object -Process { $_ } ################################### EventCapturing ################################ @@ -506,7 +506,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-Item -Path "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" - $TestFilePathResults | ForEach-Object { + $TestFilePathResults | ForEach-Object -Process { Write-Debug -Message "$_" Copy-Item -Path $_ -Destination "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue } @@ -543,7 +543,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { Write-Debug -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" - $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object { + $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { Write-Debug -Message "$($_.'File Name')" } @@ -598,7 +598,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $AnyAvailableExes = (Get-ChildItem -Recurse -Path $ProgramsPath -Filter '*.exe').FullName # if any .exe was found then continue testing them if ($AnyAvailableExes) { - $AnyAvailableExes | ForEach-Object { + $AnyAvailableExes | ForEach-Object -Process { $CurrentExeWithNoHash = $_ try { # Testing each executable to find the protected ones @@ -616,14 +616,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($ExesWithNoHash) { Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" - if ($Debug) { $ExesWithNoHash | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | - ForEach-Object { $Hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | - ForEach-Object { + ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | + ForEach-Object -Process { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] @@ -657,13 +657,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } else { Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on.`n" - $ExesWithNoHash | ForEach-Object { Write-Warning -Message "$_" } + $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -706,7 +706,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $SuppPolicyID = $SuppPolicyID.Substring(11) # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' @@ -728,7 +728,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object { return "{$_}" } + $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies if ($SupplementalPolicyType -ne 'Supplemental Policy') { Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." @@ -768,15 +768,15 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" - @(0, 2, 5, 6, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(0, 2, 5, 6, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } # Configure required services for ISG authorization Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow @@ -793,8 +793,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } } diff --git a/WDACConfig/Invoke-WDACSimulation.psm1 b/WDACConfig/Invoke-WDACSimulation.psm1 index 5be864ef3..db8ebb4de 100644 --- a/WDACConfig/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/Invoke-WDACSimulation.psm1 @@ -59,7 +59,7 @@ function Invoke-WDACSimulation { [System.Object[]]$CollectedFiles = (Get-ChildItem -Recurse -Path $FolderPath -File -Include '*.sys', '*.exe', '*.com', '*.dll', '*.ocx', '*.msp', '*.mst', '*.msi', '*.js', '*.vbs', '*.ps1', '*.appx').FullName # Loop through each file - $CollectedFiles | ForEach-Object { + $CollectedFiles | ForEach-Object -Process { $CurrentFilePath = $_ diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index 4b09a996c..63b0e76d4 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -134,10 +134,10 @@ function New-DenyWDACConfig { [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' - @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" @@ -193,10 +193,10 @@ function New-DenyWDACConfig { [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' - @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" @@ -248,10 +248,10 @@ function New-DenyWDACConfig { [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Version '1.0.0.0' - @(0, 2, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { + @(0, 2, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Option $_ } - @(3, 4, 8, 9, 10, 13, 14, 15, 18) | ForEach-Object { + @(3, 4, 8, 9, 10, 13, 14, 15, 18) | ForEach-Object -Process { Set-RuleOption -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" diff --git a/WDACConfig/New-KernelModeWDACConfig.psm1 b/WDACConfig/New-KernelModeWDACConfig.psm1 index d8c1620d8..2ed3037d7 100644 --- a/WDACConfig/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/New-KernelModeWDACConfig.psm1 @@ -117,8 +117,8 @@ function New-KernelModeWDACConfig { $Global:PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath "$PolicyFileName" -Version '1.0.0.0' # Setting policy rule options for the audit mode policy - @(2, 3, 6, 16, 17, 20) | ForEach-Object { Set-RuleOption -FilePath "$PolicyFileName" -Option $_ } - @(0, 4, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object { Set-RuleOption -FilePath "$PolicyFileName" -Option $_ -Delete } + @(2, 3, 6, 16, 17, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "$PolicyFileName" -Option $_ } + @(0, 4, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object -Process { Set-RuleOption -FilePath "$PolicyFileName" -Option $_ -Delete } # If user chooses to add EVSigners, add it to the policy if ($EVSigners) { Set-RuleOption -FilePath "$PolicyFileName" -Option 8 } # If user chooses to go with no flight root certs then block flight/insider builds in policy rule options @@ -206,8 +206,8 @@ function New-KernelModeWDACConfig { Set-CIPolicyVersion -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Version '1.0.0.0' # Setting policy rule options for the final Enforced mode policy - @(2, 6, 16, 17, 20) | ForEach-Object { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ } - @(0, 3, 4, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ -Delete } + @(2, 6, 16, 17, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ } + @(0, 3, 4, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ -Delete } if ($EVSigners) { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option 8 } @@ -304,8 +304,8 @@ function New-KernelModeWDACConfig { Set-CIPolicyVersion -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Version '1.0.0.0' # Setting policy rule options for the final Enforced mode policy - @(2, 4, 6, 16, 17, 20) | ForEach-Object { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ } - @(0, 3, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ -Delete } + @(2, 4, 6, 16, 17, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ } + @(0, 3, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ -Delete } if ($EVSigners) { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option 8 } diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index dbb5ab1ba..709c90cf5 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -157,7 +157,7 @@ function New-SupplementalWDACConfig { [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { + @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy "SupplementalPolicy $SuppPolicyName.xml" "$policyID.cip" | Out-Null @@ -187,7 +187,7 @@ function New-SupplementalWDACConfig { Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { + @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } # Adding policy rule option 18 Disabled:Runtime FilePath Rule Protection @@ -246,7 +246,7 @@ function New-SupplementalWDACConfig { Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20) | ForEach-Object { + @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 7d0e95f56..e6a1d2448 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -168,10 +168,10 @@ function New-WDACConfig { [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoftPlusBlockRules.xml -PolicyName "Allow Microsoft Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath .\AllowMicrosoftPlusBlockRules.xml -Version '1.0.0.0' - @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ -Delete } + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ -Delete } if ($TestMode -and $MakeAllowMSFTWithBlockRules) { - 9..10 | ForEach-Object { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } + 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } } if ($RequireEVSigners -and $MakeAllowMSFTWithBlockRules) { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option 8 @@ -236,10 +236,10 @@ function New-WDACConfig { [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindowsPlusBlockRules.xml -PolicyName "Default Windows Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath .\DefaultWindowsPlusBlockRules.xml -Version '1.0.0.0' - @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ -Delete } + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ -Delete } if ($TestMode -and $MakeDefaultWindowsWithBlockRules) { - 9..10 | ForEach-Object { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } + 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } } if ($RequireEVSigners -and $MakeDefaultWindowsWithBlockRules) { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option 8 @@ -280,7 +280,7 @@ function New-WDACConfig { # Remove empty lines from the policy file Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete - @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } + @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' Remove-Item -Path '.\Microsoft recommended block rules TEMP.xml' -Force [System.String]$PolicyID = (Set-CIPolicyIdInfo -FilePath '.\Microsoft recommended block rules.xml' -ResetPolicyID).Substring(11) @@ -389,7 +389,7 @@ function New-WDACConfig { } } if ($TestMode -and $MakePolicyFromAuditLogs) { - 9..10 | ForEach-Object { Set-RuleOption -FilePath $BasePolicy -Option $_ } + 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath $BasePolicy -Option $_ } } if ($RequireEVSigners -and $MakePolicyFromAuditLogs) { Set-RuleOption -FilePath $BasePolicy -Option 8 @@ -428,8 +428,8 @@ function New-WDACConfig { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 }) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | - ForEach-Object { $Hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } | - ForEach-Object { + ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | + ForEach-Object -Process { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] @@ -467,7 +467,7 @@ function New-WDACConfig { [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath 'SupplementalPolicy.xml' -PolicyName "Supplemental Policy made from Audit Event Logs on $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $BasePolicy [System.String]$PolicyID = $PolicyID.Substring(11) # Make sure policy rule options that don't belong to a Supplemental policy don't exit - @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object { Set-RuleOption -FilePath 'SupplementalPolicy.xml' -Option $_ -Delete } + @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath 'SupplementalPolicy.xml' -Option $_ -Delete } # Set the hypervisor Code Integrity option for Supplemental policy to Strict Set-HVCIOptions -Strict -FilePath 'SupplementalPolicy.xml' @@ -510,9 +510,9 @@ function New-WDACConfig { Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue Invoke-Command $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK -ArgumentList $true | Out-Null Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force - @(14, 15) | ForEach-Object { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } + @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } if ($TestMode -and $MakeLightPolicy) { - 9..10 | ForEach-Object { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } + 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } } if ($RequireEVSigners -and $MakeLightPolicy) { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option 8 diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index fe5cf5cab..929387125 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -15,7 +15,7 @@ function Remove-WDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to remove an Unsigned policy - $_ | ForEach-Object { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId @@ -242,7 +242,7 @@ function Remove-WDACConfig { $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object { "{$_}" } + $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } Write-Debug -Message "The policy ID of the currently processing xml file is $PolicyID" if ($CurrentPolicyIDs -notcontains $PolicyID) { Write-Error -Message "The selected policy file isn't deployed on the system." -ErrorAction Stop @@ -253,7 +253,7 @@ function Remove-WDACConfig { $PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string if ($SuppSingerIDs) { Write-Debug -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." - $SuppSingerIDs | ForEach-Object { + $SuppSingerIDs | ForEach-Object -Process { $PolContent = Get-Content -Raw -Path $PolicyPath $PolContent -match "" | Out-Null $PolContent = $PolContent -replace $Matches[0], '' @@ -311,9 +311,9 @@ function Remove-WDACConfig { } Write-Debug -Message 'The Following policy IDs have been gathered from the supplied policy names and are going to be removed from the system' - if ($Debug) { $NameID | Select-Object -Unique | ForEach-Object { Write-Debug -Message "$_" } } + if ($Debug) { $NameID | Select-Object -Unique | ForEach-Object -Process { Write-Debug -Message "$_" } } - $NameID | Select-Object -Unique | ForEach-Object { + $NameID | Select-Object -Unique | ForEach-Object -Process { citool --remove-policy "{$_}" -json | Out-Null Write-Host "Policy with the ID $_ has been successfully removed." -ForegroundColor Green } diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index a99702714..c38c138ee 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -280,13 +280,7 @@ Function Get-AuditEventLogsProcessing { $Xml = [System.Xml.XmlDocument]$event.toxml() - $Xml.event.eventdata.data | ForEach-Object -Begin { - $Hash = @{} - } -Process { - $Hash[$_.name] = $_.'#text' - } -End { - [pscustomobject]$Hash - } | ForEach-Object { + $Xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $Hash[$_.name] = $_.'#text' } -End { [pscustomobject]$Hash } | ForEach-Object -Process { # Define the regex pattern [System.String]$Pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$' diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 145211d73..7362af7dc 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -165,7 +165,7 @@ function Get-AuthenticodeSignatureEx { } process { # For each file path, get the authenticode signature using the built-in cmdlet - Get-AuthenticodeSignature $FilePath | ForEach-Object { + Get-AuthenticodeSignature $FilePath | ForEach-Object -Process { $Output = $_ # Store the output object in a variable if ($null -ne $Output.SignerCertificate) { # If the output object has a signer certificate property @@ -360,7 +360,7 @@ function Get-CertificateDetails { $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -ne $TestAgainst } | # To omit the Leaf certificate - Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property + Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj @@ -370,7 +370,7 @@ function Get-CertificateDetails { $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -eq $TestAgainst } | # To get the Leaf certificate - Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property + Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj } @@ -384,7 +384,7 @@ function Get-CertificateDetails { $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -ne $LeafCNOfTheNestedCertificate } | # To omit the Leaf certificate - Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property + Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj @@ -394,7 +394,7 @@ function Get-CertificateDetails { $FinalObj = $Obj | Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result Where-Object { $_.SubjectCN -eq $LeafCNOfTheNestedCertificate } | # To get the Leaf certificate - Group-Object -Property TBSValue | ForEach-Object { $_.Group[0] } # To make sure the output values are unique based on TBSValue property + Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index 3d3d10f66..d592f0b4d 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -20,7 +20,7 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ - $_ | ForEach-Object { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId @@ -34,7 +34,7 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ - $_ | ForEach-Object { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId From 0cb3fabf23c97ab1f02e10fe266f1ea67c5bba7a Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 08:35:28 -0930 Subject: [PATCH 008/178] parameter improvements --- WDACConfig/ArgumentCompleters.ps1 | 4 +-- WDACConfig/Confirm-WDACConfig.psm1 | 4 +-- WDACConfig/Deploy-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 18 ++++++------- WDACConfig/Edit-WDACConfig.psm1 | 18 ++++++------- WDACConfig/Invoke-WDACSimulation.psm1 | 8 +++--- WDACConfig/New-DenyWDACConfig.psm1 | 2 +- WDACConfig/New-KernelModeWDACConfig.psm1 | 4 +-- WDACConfig/New-WDACConfig.psm1 | 10 ++++---- WDACConfig/Remove-WDACConfig.psm1 | 28 ++++++++++----------- WDACConfig/Resources2.ps1 | 32 ++++++++++++------------ 11 files changed, 65 insertions(+), 65 deletions(-) diff --git a/WDACConfig/ArgumentCompleters.ps1 b/WDACConfig/ArgumentCompleters.ps1 index 6e2323d89..9670d829d 100644 --- a/WDACConfig/ArgumentCompleters.ps1 +++ b/WDACConfig/ArgumentCompleters.ps1 @@ -67,7 +67,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem -File | Where-Object { $_.extension -like '*.xml' } | ForEach-Object { + Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object { $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType @@ -97,7 +97,7 @@ ).Value # Get the xml files in the current directory - Get-ChildItem -File | Where-Object { $_.extension -like '*.xml' } | ForEach-Object -Process { + Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { $xmlitem = [System.Xml.XmlDocument](Get-Content $_) $PolicyType = $xmlitem.SiPolicy.PolicyType diff --git a/WDACConfig/Confirm-WDACConfig.psm1 b/WDACConfig/Confirm-WDACConfig.psm1 index 4b27d1b74..930d17b76 100644 --- a/WDACConfig/Confirm-WDACConfig.psm1 +++ b/WDACConfig/Confirm-WDACConfig.psm1 @@ -83,13 +83,13 @@ function Confirm-WDACConfig { # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { - $BasePolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.PolicyID -eq $_.BasePolicyID } + $BasePolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID } &$WriteLavender "`nThere are currently $(($BasePolicies.count)) Non-system Base policies deployed" $BasePolicies } # Script block to show only non-system Supplemental policies [System.Management.Automation.ScriptBlock]$OnlySupplementalPoliciesBLOCK = { - $SupplementalPolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.PolicyID -ne $_.BasePolicyID } + $SupplementalPolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -ne $_.BasePolicyID } &$WriteLavender "`nThere are currently $(($SupplementalPolicies.count)) Non-system Supplemental policies deployed`n" $SupplementalPolicies } diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index 343f50856..a00b747b2 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -111,7 +111,7 @@ function Deploy-SignedWDACConfig { $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyType = $xml.SiPolicy.PolicyType [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string [System.String[]]$PolicyRuleOptions = $xml.SiPolicy.Rules.Rule.Option # Remove the .CIP file of the same policy being signed and deployed if any in the current working directory diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 3d258cf3a..c4749f84c 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -52,7 +52,7 @@ function Edit-SignedWDACConfig { $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } + $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if ($RedFlag1 -or $RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { @@ -216,7 +216,7 @@ function Edit-SignedWDACConfig { # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname + $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname return [System.String[]]$BasePolicyNamez } } @@ -277,7 +277,7 @@ function Edit-SignedWDACConfig { # Defining Base policy $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue @@ -465,7 +465,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -504,7 +504,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { - foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { + foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | @@ -512,7 +512,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk @@ -642,7 +642,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Defining Base policy $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue @@ -781,7 +781,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -944,7 +944,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Get the policy ID of the currently deployed base policy based on the policy name that user selected - $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID + $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Remove-Item ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 3facd4dd9..05e833c8d 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -31,7 +31,7 @@ function Edit-WDACConfig { $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } + $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if (!$RedFlag1 -and !$RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { @@ -153,7 +153,7 @@ function Edit-WDACConfig { # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname + $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname return [System.String[]]$BasePolicyNamez } @@ -210,7 +210,7 @@ function Edit-WDACConfig { # Defining Base policy $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue @@ -355,7 +355,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -414,7 +414,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Defining Base policy $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue @@ -580,7 +580,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -619,7 +619,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { - foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object { $_.TimeCreated -ge $Date } ) { + foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() $xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | @@ -627,7 +627,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk @@ -808,7 +808,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item '.\Microsoft recommended block rules.xml' -Force # Get the policy ID of the currently deployed base policy based on the policy name that user selected - $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID + $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Write-Debug -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" [System.Xml.XmlDocument]$xml = Get-Content '.\BasePolicy.xml' diff --git a/WDACConfig/Invoke-WDACSimulation.psm1 b/WDACConfig/Invoke-WDACSimulation.psm1 index db8ebb4de..649a67a84 100644 --- a/WDACConfig/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/Invoke-WDACSimulation.psm1 @@ -73,7 +73,7 @@ function Invoke-WDACSimulation { $CurrentHashOutput = New-CIPolicyRule -Level hash -Fallback none -AllowFileNameFallbacks -UserWriteablePaths -DriverFilePath $CurrentFilePath - $CurrentFilePathHash = ($CurrentHashOutput | Where-Object { $_.name -like '*Hash Sha256*' }).attributes.hash + $CurrentFilePathHash = ($CurrentHashOutput | Where-Object -FilterScript { $_.name -like '*Hash Sha256*' }).attributes.hash } # if the file's hash exists in the XML file @@ -90,7 +90,7 @@ function Invoke-WDACSimulation { Write-Host "Currently processing signed file: `n$CurrentFilePath" -ForegroundColor Yellow } # Use the function in Resources2.ps1 file to process it - $SignedResult += Compare-SignerAndCertificate -XmlFilePath $XmlFilePath -SignedFilePath $CurrentFilePath | Where-Object { ($_.CertRootMatch -eq $true) -and ($_.CertNameMatch -eq $true) -and ($_.CertPublisherMatch -eq $true) } + $SignedResult += Compare-SignerAndCertificate -XmlFilePath $XmlFilePath -SignedFilePath $CurrentFilePath | Where-Object -FilterScript { ($_.CertRootMatch -eq $true) -and ($_.CertNameMatch -eq $true) -and ($_.CertPublisherMatch -eq $true) } break } 'HashMismatch' { @@ -166,7 +166,7 @@ function Invoke-WDACSimulation { } # Unique number of files allowed by hash - used for counting only - $UniqueFilesAllowedByHash = $MegaOutputObject | Select-Object -Property FilePath, source, Permission -Unique | Where-Object { $_.source -eq 'hash' } + $UniqueFilesAllowedByHash = $MegaOutputObject | Select-Object -Property FilePath, source, Permission -Unique | Where-Object -FilterScript { $_.source -eq 'hash' } # To detect files that are not allowed @@ -174,7 +174,7 @@ function Invoke-WDACSimulation { if ($($MegaOutputObject.Filepath) -and $CollectedFiles) { # Compare the paths of all the supported files that were found in user provided directory with the array of files that were allowed by Signer or hash in the policy # Then save the output to a different array - [System.Object[]]$FinalComparisonForFilesNotAllowed = Compare-Object -ReferenceObject $($MegaOutputObject.Filepath) -DifferenceObject $CollectedFiles -PassThru | Where-Object { $_.SideIndicator -eq '=>' } + [System.Object[]]$FinalComparisonForFilesNotAllowed = Compare-Object -ReferenceObject $($MegaOutputObject.Filepath) -DifferenceObject $CollectedFiles -PassThru | Where-Object -FilterScript { $_.SideIndicator -eq '=>' } } # If there is any files in the user selected directory that is not allowed by the policy diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index 63b0e76d4..dccd695db 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -119,7 +119,7 @@ function New-DenyWDACConfig { if ($Debug) { $UserInputProgramFoldersPolicyMakerHashTable } # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName diff --git a/WDACConfig/New-KernelModeWDACConfig.psm1 b/WDACConfig/New-KernelModeWDACConfig.psm1 index 2ed3037d7..9734a6613 100644 --- a/WDACConfig/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/New-KernelModeWDACConfig.psm1 @@ -90,7 +90,7 @@ function New-KernelModeWDACConfig { If ($CurrentStrictKernelPolicyGUID) { # Check if the pending Audit mode Kernel mode WDAC policy is deployed on the system - [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.PolicyID -eq $CurrentStrictKernelPolicyGUID }).policyID + [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelPolicyGUID }).policyID } } @@ -104,7 +104,7 @@ function New-KernelModeWDACConfig { If ($CurrentStrictKernelNoFlightRootsPolicyGUID) { # Check if the pending Audit mode Kernel mode WDAC No Flight Roots policy is deployed on the system - [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.PolicyID -eq $CurrentStrictKernelNoFlightRootsPolicyGUID }).policyID + [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelNoFlightRootsPolicyGUID }).policyID } } diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index e6a1d2448..9cf41e997 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -146,7 +146,7 @@ function New-WDACConfig { $DriverRules = $DriverRules -replace '', '' $DriverRules | Out-File 'Microsoft recommended driver block rules TEMP.xml' # Remove empty lines from the policy file - Get-Content 'Microsoft recommended driver block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File 'Microsoft recommended driver block rules.xml' + Get-Content 'Microsoft recommended driver block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File 'Microsoft recommended driver block rules.xml' Remove-Item 'Microsoft recommended driver block rules TEMP.xml' -Force Set-RuleOption -FilePath 'Microsoft recommended driver block rules.xml' -Option 3 -Delete Set-HVCIOptions -Strict -FilePath 'Microsoft recommended driver block rules.xml' @@ -278,7 +278,7 @@ function New-WDACConfig { [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File '.\Microsoft recommended block rules TEMP.xml' # Remove empty lines from the policy file - Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' + Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' @@ -433,7 +433,7 @@ function New-WDACConfig { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } @@ -494,10 +494,10 @@ function New-WDACConfig { # Get the correct Prep mode Audit policy ID to remove from the system switch ($BasePolicyType) { 'Allow Microsoft Base' { - $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.FriendlyName -eq 'PrepMSFTOnlyAudit' }).PolicyID + $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepMSFTOnlyAudit' }).PolicyID } 'Default Windows Base' { - $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.FriendlyName -eq 'PrepDefaultWindows' }).PolicyID + $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepDefaultWindows' }).PolicyID } } CiTool --remove-policy "{$IDToRemove}" -json | Out-Null diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index 929387125..8c4b18aa2 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -41,8 +41,8 @@ function Remove-WDACConfig { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Get a list of policies using the CiTool, excluding system policies and policies that aren't on disk. - # by adding "| Where-Object { $_.FriendlyName }" we make sure the auto completion works when at least one of the policies doesn't have a friendly name - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.IsSystemPolicy -ne 'True' } | Where-Object { $_.FriendlyName } + # by adding "| Where-Object -FilterScript { $_.FriendlyName }" we make sure the auto completion works when at least one of the policies doesn't have a friendly name + $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.FriendlyName } # Create a hashtable mapping policy names to policy IDs. This will be used later to check if a policy ID already exists. $NameIDMap = @{} @@ -61,12 +61,12 @@ function Remove-WDACConfig { # Filter out the policy names that are already being used or whose corresponding policy IDs are already being used. # The resulting list of policy names is what will be shown as autocomplete suggestions. - $candidates = $policies.Friendlyname | Where-Object { $_ -notin $existing -and $NameIDMap[$_] -notin $existingIDs } + $candidates = $policies.Friendlyname | Where-Object -FilterScript { $_ -notin $existing -and $NameIDMap[$_] -notin $existingIDs } # Additionally, if the policy name contains spaces, it's enclosed in single quotes to ensure it's treated as a single argument. # This is achieved using the Compare-Object cmdlet to compare the existing and candidate values, and outputting the resulting matches. # For each resulting match, it checks if the match contains a space, if so, it's enclosed in single quotes, if not, it's returned as is. - (Compare-Object -PassThru $candidates $existing | Where-Object SideIndicator -EQ '<='). + (Compare-Object -PassThru $candidates $existing | Where-Object -FilterScript { SideIndicator -EQ '<=' }). ForEach({ if ($_ -match ' ') { "'{0}'" -f $_ } else { $_ } }) })] [ValidateScript({ @@ -82,7 +82,7 @@ function Remove-WDACConfig { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Get a list of policies using the CiTool, excluding system policies and policies that aren't on disk. - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.IsSystemPolicy -ne 'True' } + $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } # Create a hashtable mapping policy IDs to policy names. This will be used later to check if a policy name already exists. $IDNameMap = @{} foreach ($policy in $policies) { @@ -97,7 +97,7 @@ function Remove-WDACConfig { }, $false).Value # Filter out the policy IDs that are already being used or whose corresponding policy names are already being used. # The resulting list of policy IDs is what will be shown as autocomplete suggestions. - $candidates = $policies.policyID | Where-Object { $_ -notin $existing -and $IDNameMap[$_] -notin $existingNames } + $candidates = $policies.policyID | Where-Object -FilterScript { $_ -notin $existing -and $IDNameMap[$_] -notin $existingNames } # Return the candidates. return $candidates })] @@ -174,7 +174,7 @@ function Remove-WDACConfig { # ValidateSet for Policy names Class PolicyNamezx : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $PolicyNamezx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.IsSystemPolicy -ne 'True' }).Friendlyname | Select-Object -Unique + $PolicyNamezx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).Friendlyname | Select-Object -Unique return [System.String[]]$PolicyNamezx } } @@ -182,7 +182,7 @@ function Remove-WDACConfig { # ValidateSet for Policy IDs Class PolicyIDzx : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $PolicyIDzx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID + $PolicyIDzx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID return [System.String[]]$PolicyIDzx } @@ -197,7 +197,7 @@ function Remove-WDACConfig { # Defines a method to get valid policy names from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.IsSystemPolicy -ne 'True' } + $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$IDNameMap = @{} foreach ($policy in $policies) { self::$IDNameMap[$policy.policyID] = $policy.Friendlyname @@ -219,7 +219,7 @@ function Remove-WDACConfig { # Defines a method to get valid policy IDs from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.IsSystemPolicy -ne 'True' } + $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$NameIDMap = @{} foreach ($policy in $policies) { self::$NameIDMap[$policy.Friendlyname] = $policy.policyID @@ -242,7 +242,7 @@ function Remove-WDACConfig { $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } + $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } Write-Debug -Message "The policy ID of the currently processing xml file is $PolicyID" if ($CurrentPolicyIDs -notcontains $PolicyID) { Write-Error -Message "The selected policy file isn't deployed on the system." -ErrorAction Stop @@ -250,7 +250,7 @@ function Remove-WDACConfig { ######################## Sanitize the policy file by removing SupplementalPolicySigners ######################## $SuppSingerIDs = $xml.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + $PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string if ($SuppSingerIDs) { Write-Debug -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." $SuppSingerIDs | ForEach-Object -Process { @@ -264,7 +264,7 @@ function Remove-WDACConfig { Set-Content -Value $PolContent -Path $PolicyPath # remove empty lines from the entire policy file - (Get-Content -Path $PolicyPath) | Where-Object { $_.trim() -ne '' } | Set-Content -Path $PolicyPath -Force + (Get-Content -Path $PolicyPath) | Where-Object -FilterScript { $_.trim() -ne '' } | Set-Content -Path $PolicyPath -Force Write-Debug -Message 'Policy successfully sanitized and all SupplementalPolicySigners have been removed.' } else { @@ -307,7 +307,7 @@ function Remove-WDACConfig { # Empty array to store Policy IDs based on the input name, this will take care of the situations where multiple policies with the same name are deployed [System.Object[]]$NameID = @() foreach ($PolicyName in $PolicyNames) { - $NameID += ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object { $_.IsOnDisk -eq 'True' } | Where-Object { $_.FriendlyName -eq $PolicyName }).PolicyID + $NameID += ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.FriendlyName -eq $PolicyName }).PolicyID } Write-Debug -Message 'The Following policy IDs have been gathered from the supplied policy names and are going to be removed from the system' diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 7362af7dc..670468ff3 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -148,8 +148,8 @@ function Get-AuthenticodeSignatureEx { [System.Object[]]$retValue = @() foreach ($CounterSignerInfos in $Infos.CounterSignerInfos) { # Get the signing time attribute from the countersigner info object - $sTime = ($CounterSignerInfos.SignedAttributes | Where-Object { $_.Oid.Value -eq '1.2.840.113549.1.9.5' }).Values | ` - Where-Object { $null -ne $_.SigningTime } + $sTime = ($CounterSignerInfos.SignedAttributes | Where-Object -FilterScript { $_.Oid.Value -eq '1.2.840.113549.1.9.5' }).Values | ` + Where-Object -FilterScript { $null -ne $_.SigningTime } # Create a custom object with the countersigner certificate and signing time properties $tsObject = New-Object psobject -Property @{ Certificate = $CounterSignerInfos.Certificate @@ -207,11 +207,11 @@ function Get-AuthenticodeSignatureEx { # Call the helper function to get the timestamps of the countersigners and assign it to the TimeStamps property $Output.TimeStamps = getTimeStamps $Infos # Check if there is a nested signature attribute in the signer info object by looking for the OID 1.3.6.1.4.1.311.2.4.1 - $second = $Infos.UnsignedAttributes | Where-Object { $_.Oid.Value -eq '1.3.6.1.4.1.311.2.4.1' } + $second = $Infos.UnsignedAttributes | Where-Object -FilterScript { $_.Oid.Value -eq '1.3.6.1.4.1.311.2.4.1' } if ($second) { # If there is a nested signature attribute # Get the value of the nested signature attribute as a raw data byte array - $value = $second.Values | Where-Object { $_.Oid.Value -eq '1.3.6.1.4.1.311.2.4.1' } + $value = $second.Values | Where-Object -FilterScript { $_.Oid.Value -eq '1.3.6.1.4.1.311.2.4.1' } $SignedCms2 = New-Object Security.Cryptography.Pkcs.SignedCms # Create another SignedCms object to decode the nested signature data $SignedCms2.Decode($value.RawData) # Decode the nested signature data and populate the SignedCms object properties $Output | Add-Member -MemberType NoteProperty -Name NestedSignature -Value $null @@ -297,11 +297,11 @@ function Get-CertificateDetails { if ($FilePath) { # Get all the certificates from the file path using the Get-SignedFileCertificates function - $CertCollection = Get-SignedFileCertificates -FilePath $FilePath | Where-Object { $_.EnhancedKeyUsageList.FriendlyName -ne 'Time Stamping' } + $CertCollection = Get-SignedFileCertificates -FilePath $FilePath | Where-Object -FilterScript { $_.EnhancedKeyUsageList.FriendlyName -ne 'Time Stamping' } } else { - # The "| Where-Object {$_ -ne 0}" part is used to filter the output coming from Get-AuthenticodeSignatureEx function that gets nested certificate - $CertCollection = Get-SignedFileCertificates -X509Certificate2 $X509Certificate2 | Where-Object { $_.EnhancedKeyUsageList.FriendlyName -ne 'Time Stamping' } | Where-Object { $_ -ne 0 } + # The "| Where-Object -FilterScript {$_ -ne 0}" part is used to filter the output coming from Get-AuthenticodeSignatureEx function that gets nested certificate + $CertCollection = Get-SignedFileCertificates -X509Certificate2 $X509Certificate2 | Where-Object -FilterScript { $_.EnhancedKeyUsageList.FriendlyName -ne 'Time Stamping' } | Where-Object -FilterScript { $_ -ne 0 } } # Loop through each certificate in the collection and call this function recursively with the certificate object as an input @@ -358,8 +358,8 @@ function Get-CertificateDetails { if ($IntermediateOnly) { $FinalObj = $Obj | - Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result - Where-Object { $_.SubjectCN -ne $TestAgainst } | # To omit the Leaf certificate + Where-Object -FilterScript { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result + Where-Object -FilterScript { $_.SubjectCN -ne $TestAgainst } | # To omit the Leaf certificate Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj @@ -368,8 +368,8 @@ function Get-CertificateDetails { elseif ($LeafCertificate) { $FinalObj = $Obj | - Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result - Where-Object { $_.SubjectCN -eq $TestAgainst } | # To get the Leaf certificate + Where-Object -FilterScript { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result + Where-Object -FilterScript { $_.SubjectCN -eq $TestAgainst } | # To get the Leaf certificate Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj @@ -382,8 +382,8 @@ function Get-CertificateDetails { if ($IntermediateOnly) { $FinalObj = $Obj | - Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result - Where-Object { $_.SubjectCN -ne $LeafCNOfTheNestedCertificate } | # To omit the Leaf certificate + Where-Object -FilterScript { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result + Where-Object -FilterScript { $_.SubjectCN -ne $LeafCNOfTheNestedCertificate } | # To omit the Leaf certificate Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj @@ -392,8 +392,8 @@ function Get-CertificateDetails { elseif ($LeafCertificate) { $FinalObj = $Obj | - Where-Object { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result - Where-Object { $_.SubjectCN -eq $LeafCNOfTheNestedCertificate } | # To get the Leaf certificate + Where-Object -FilterScript { $_.SubjectCN -ne $_.IssuerCN } | # To omit Root certificate from the result + Where-Object -FilterScript { $_.SubjectCN -eq $LeafCNOfTheNestedCertificate } | # To get the Leaf certificate Group-Object -Property TBSValue | ForEach-Object -Process { $_.Group[0] } # To make sure the output values are unique based on TBSValue property return $FinalObj @@ -736,7 +736,7 @@ function Get-FileRuleOutput ($xmlPath) { } # Only show the Authenticode Hash SHA256 - $OutPutHashInfoProcessing = $OutPutHashInfoProcessing | Where-Object { $_.hashtype -eq 'Hash Sha256' } + $OutPutHashInfoProcessing = $OutPutHashInfoProcessing | Where-Object -FilterScript { $_.hashtype -eq 'Hash Sha256' } # Return the output array return $OutPutHashInfoProcessing From 90b0846c11c48e0797d456d0a717fbb4e0290385 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 08:40:32 -0930 Subject: [PATCH 009/178] param improvements to the GCI --- WDACConfig/Deploy-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 6 +++--- WDACConfig/Edit-WDACConfig.psm1 | 4 ++-- WDACConfig/New-DenyWDACConfig.psm1 | 2 +- WDACConfig/Remove-WDACConfig.psm1 | 2 +- WDACConfig/Resources.ps1 | 2 +- WDACConfig/Set-CommonWDACConfig.psm1 | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index a00b747b2..4074eb4ba 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -17,7 +17,7 @@ function Deploy-SignedWDACConfig { [parameter(Mandatory = $false)][System.String]$CertPath, [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { + $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } $certs -contains $_ diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index c4749f84c..28a19eab3 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -71,7 +71,7 @@ function Edit-SignedWDACConfig { [System.String[]]$PolicyPaths, [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { + $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } $certs -contains $_ @@ -465,7 +465,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -781,7 +781,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 05e833c8d..6dd30f3ea 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -355,7 +355,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -580,7 +580,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index dccd695db..f0cb4081e 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -119,7 +119,7 @@ function New-DenyWDACConfig { if ($Debug) { $UserInputProgramFoldersPolicyMakerHashTable } # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index 8c4b18aa2..1c6e3c5c9 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -26,7 +26,7 @@ function Remove-WDACConfig { [System.String[]]$PolicyPaths, [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { + $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } $certs -contains $_ diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index c38c138ee..7954771e5 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -387,7 +387,7 @@ $RuleRefsContent # Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json function Confirm-CertCN ([System.String]$CN) { - $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { + $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } $certs -contains $CN ? $true : $false diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index d592f0b4d..b42be02f0 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -3,7 +3,7 @@ function Set-CommonWDACConfig { [CmdletBinding()] Param( [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem 'Cert:\CurrentUser\my')) { + $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } $certs -contains $_ From 0ea3746e113408a6f46323adcbf162227ed1fdcc Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 08:51:32 -0930 Subject: [PATCH 010/178] param improvements --- WDACConfig/Deploy-SignedWDACConfig.psm1 | 10 +++--- WDACConfig/Edit-SignedWDACConfig.psm1 | 36 ++++++++++---------- WDACConfig/Edit-WDACConfig.psm1 | 38 +++++++++++----------- WDACConfig/Get-CommonWDACConfig.psm1 | 16 ++++----- WDACConfig/New-DenyWDACConfig.psm1 | 6 ++-- WDACConfig/New-KernelModeWDACConfig.psm1 | 8 ++--- WDACConfig/New-SupplementalWDACConfig.psm1 | 6 ++-- WDACConfig/New-WDACConfig.psm1 | 14 ++++---- WDACConfig/Remove-WDACConfig.psm1 | 6 ++-- WDACConfig/Resources.ps1 | 32 +++++++++--------- WDACConfig/Resources2.ps1 | 10 +++--- 11 files changed, 91 insertions(+), 91 deletions(-) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index 4074eb4ba..d62f8e571 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -138,7 +138,7 @@ function Deploy-SignedWDACConfig { } Set-HVCIOptions -Strict -FilePath $PolicyPath Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete - ConvertFrom-CIPolicy $PolicyPath "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath "$PolicyID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ @@ -160,8 +160,8 @@ function Deploy-SignedWDACConfig { CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID`n" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID`n" Remove-Item -Path ".\$PolicyID.cip" -Force #region Detecting Strict Kernel mode policy and removing it from User Configs @@ -211,8 +211,8 @@ function Deploy-SignedWDACConfig { else { Write-Host "`npolicy with the following details has been Signed and is ready for deployment:" -ForegroundColor Green - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID`n" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID`n" } } } diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 28a19eab3..3cc4c7d81 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -242,8 +242,8 @@ function Edit-SignedWDACConfig { # Deploy Enforced mode CIP CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:" - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item ".\$PolicyID.cip" -Force } @@ -285,12 +285,12 @@ function Edit-SignedWDACConfig { # Create CIP for Audit Mode Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\AuditModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\EnforcedModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null # Sign both CIPs '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { @@ -327,8 +327,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time @@ -597,7 +597,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy $SuppPolicyPath "$SuppPolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ @@ -615,8 +615,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" - Write-Output "SupplementalPolicyName = $SuppPolicyName" - Write-Output "SupplementalPolicyGUID = $SuppPolicyID" + Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" + Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } @@ -650,12 +650,12 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Create CIP for Audit Mode Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\AuditModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\EnforcedModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null # Sign both CIPs '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { @@ -692,8 +692,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time @@ -807,7 +807,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy $SuppPolicyPath "$SuppPolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ @@ -825,8 +825,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" - Write-Output "SupplementalPolicyName = $SuppPolicyName" - Write-Output "SupplementalPolicyGUID = $SuppPolicyID" + Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" + Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } @@ -865,7 +865,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Add-SignerRule -FilePath "$SuppPolicyName.xml" -CertificatePath $CertPath -Update -User -Kernel Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" Set-RuleOption -FilePath "$SuppPolicyName.xml" -Option 6 -Delete - ConvertFrom-CIPolicy "$SuppPolicyName.xml" "$SuppPolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ @@ -958,7 +958,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-CIPolicyVersion -FilePath .\BasePolicy.xml -Version '1.0.0.1' Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml - ConvertFrom-CIPolicy '.\BasePolicy.xml' "$CurrentID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 6dd30f3ea..40d06a4f0 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -180,8 +180,8 @@ function Edit-WDACConfig { # Deploy Enforced mode CIP CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item ".\$PolicyID.cip" -Force } @@ -217,11 +217,11 @@ function Edit-WDACConfig { # Create CIP for Audit Mode Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\AuditMode.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\EnforcedMode.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' @@ -259,8 +259,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time @@ -380,12 +380,12 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy $SuppPolicyPath "$SuppPolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" - Write-Output "SupplementalPolicyName = $SuppPolicyName" - Write-Output "SupplementalPolicyGUID = $SuppPolicyID" - Remove-Item ".\$SuppPolicyID.cip" -Force + Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" + Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } } @@ -421,11 +421,11 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Create CIP for Audit Mode Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\AuditMode.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy $PolicyPath '.\EnforcedMode.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' @@ -442,8 +442,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time @@ -711,11 +711,11 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy $SuppPolicyPath "$SuppPolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" - Write-Output "SupplementalPolicyName = $SuppPolicyName" - Write-Output "SupplementalPolicyGUID = $SuppPolicyID" + Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" + Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } @@ -752,7 +752,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" - ConvertFrom-CIPolicy "$SuppPolicyName.xml" "$SuppPolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force @@ -815,7 +815,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') - ConvertFrom-CIPolicy '.\BasePolicy.xml' "$CurrentID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null # Deploy the new base policy with the same GUID on the system CiTool --update-policy "$CurrentID.cip" -json | Out-Null # Remove the policy binary after it's been deployed diff --git a/WDACConfig/Get-CommonWDACConfig.psm1 b/WDACConfig/Get-CommonWDACConfig.psm1 index 7946ac589..f8d0dee35 100644 --- a/WDACConfig/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/Get-CommonWDACConfig.psm1 @@ -69,14 +69,14 @@ function Get-CommonWDACConfig { end { # Use a switch statement to check which parameter is present and output the corresponding value from the json file switch ($true) { - $SignedPolicyPath.IsPresent { Write-Output $CurrentUserConfigurations.SignedPolicyPath } - $UnsignedPolicyPath.IsPresent { Write-Output $CurrentUserConfigurations.UnsignedPolicyPath } - $SignToolPath.IsPresent { Write-Output $CurrentUserConfigurations.SignToolCustomPath } - $CertCN.IsPresent { Write-Output $CurrentUserConfigurations.CertificateCommonName } - $StrictKernelPolicyGUID.IsPresent { Write-Output $CurrentUserConfigurations.StrictKernelPolicyGUID } - $StrictKernelNoFlightRootsPolicyGUID.IsPresent { Write-Output $CurrentUserConfigurations.StrictKernelNoFlightRootsPolicyGUID } - $CertPath.IsPresent { Write-Output $CurrentUserConfigurations.CertificatePath } - $LastUpdateCheck.IsPresent { Write-Output $CurrentUserConfigurations.LastUpdateCheck } + $SignedPolicyPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.SignedPolicyPath } + $UnsignedPolicyPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.UnsignedPolicyPath } + $SignToolPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.SignToolCustomPath } + $CertCN.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.CertificateCommonName } + $StrictKernelPolicyGUID.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.StrictKernelPolicyGUID } + $StrictKernelNoFlightRootsPolicyGUID.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.StrictKernelNoFlightRootsPolicyGUID } + $CertPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.CertificatePath } + $LastUpdateCheck.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.LastUpdateCheck } } } } diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index f0cb4081e..6d271c1eb 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -141,7 +141,7 @@ function New-DenyWDACConfig { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" - ConvertFrom-CIPolicy "DenyPolicy $PolicyName.xml" "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ DenyPolicyFile = "DenyPolicy $PolicyName.xml" DenyPolicyGUID = $PolicyID @@ -200,7 +200,7 @@ function New-DenyWDACConfig { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" - ConvertFrom-CIPolicy "DenyPolicy $PolicyName.xml" "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ DenyPolicyFile = "DenyPolicy $PolicyName.xml" @@ -255,7 +255,7 @@ function New-DenyWDACConfig { Set-RuleOption -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" - ConvertFrom-CIPolicy ".\AppxDenyPolicy $PolicyName.xml" "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath ".\AppxDenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ DenyPolicyFile = ".\AppxDenyPolicy $PolicyName.xml" diff --git a/WDACConfig/New-KernelModeWDACConfig.psm1 b/WDACConfig/New-KernelModeWDACConfig.psm1 index 9734a6613..9b6eb57bf 100644 --- a/WDACConfig/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/New-KernelModeWDACConfig.psm1 @@ -143,7 +143,7 @@ function New-KernelModeWDACConfig { # Build the Audit mode policy Build-PrepModeStrictKernelPolicy -DefaultWindowsKernel # Convert the xml to CIP binary - ConvertFrom-CIPolicy .\DefaultWindows_Enforced_Kernel.xml "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Enforced_Kernel.xml -BinaryFilePath "$PolicyID.cip" | Out-Null # Deploy the policy if Deploy parameter is used and perform additional tasks on the system if ($Deploy) { @@ -215,7 +215,7 @@ function New-KernelModeWDACConfig { # Deploy the policy if Deploy parameter is used if ($Deploy) { - ConvertFrom-CIPolicy '.\Final_DefaultWindows_Enforced_Kernel.xml' "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null &$WritePink 'Strict Kernel mode policy has been deployed in Enforced mode, no restart required.' @@ -242,7 +242,7 @@ function New-KernelModeWDACConfig { # Creating the audit mode policy Build-PrepModeStrictKernelPolicy -DefaultWindowsKernelNoFlights # Convert the xml to CIP binary - ConvertFrom-CIPolicy .\DefaultWindows_Enforced_Kernel_NoFlights.xml "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Enforced_Kernel_NoFlights.xml -BinaryFilePath "$PolicyID.cip" | Out-Null # Deploy the policy if Deploy parameter is used and perform additional tasks on the system if ($Deploy) { @@ -313,7 +313,7 @@ function New-KernelModeWDACConfig { # Deploy the policy if Deploy parameter is used if ($Deploy) { - ConvertFrom-CIPolicy '.\Final_DefaultWindows_Enforced_Kernel.xml' "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null &$WritePink 'Strict Kernel mode policy with no flighting root certs has been deployed in Enforced mode, no restart required.' diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index 709c90cf5..c88364b14 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -160,7 +160,7 @@ function New-SupplementalWDACConfig { @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" - ConvertFrom-CIPolicy "SupplementalPolicy $SuppPolicyName.xml" "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ SupplementalPolicyFile = "SupplementalPolicy $SuppPolicyName.xml" SupplementalPolicyGUID = $PolicyID @@ -194,7 +194,7 @@ function New-SupplementalWDACConfig { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option 18 Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" - ConvertFrom-CIPolicy ".\SupplementalPolicy $SuppPolicyName.xml" "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ SupplementalPolicyFile = ".\SupplementalPolicy $SuppPolicyName.xml" SupplementalPolicyGUID = $PolicyID @@ -250,7 +250,7 @@ function New-SupplementalWDACConfig { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" - ConvertFrom-CIPolicy ".\SupplementalPolicy $SuppPolicyName.xml" "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ SupplementalPolicyFile = ".\SupplementalPolicy $SuppPolicyName.xml" SupplementalPolicyGUID = $PolicyID diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 9cf41e997..9e0ff9e10 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -177,7 +177,7 @@ function New-WDACConfig { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option 8 } Set-HVCIOptions -Strict -FilePath .\AllowMicrosoftPlusBlockRules.xml - ConvertFrom-CIPolicy .\AllowMicrosoftPlusBlockRules.xml "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules. -BinaryFilePath "$PolicyID.cip" | Out-Null # Remove the extra files that were created during module operation and are no longer needed Remove-Item '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force [PSCustomObject]@{ @@ -245,7 +245,7 @@ function New-WDACConfig { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option 8 } Set-HVCIOptions -Strict -FilePath .\DefaultWindowsPlusBlockRules.xml - ConvertFrom-CIPolicy .\DefaultWindowsPlusBlockRules.xml "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindowsPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null Remove-Item .\AllowPowerShell.xml -Force -ErrorAction SilentlyContinue Remove-Item '.\DefaultWindows_Enforced.xml', 'Microsoft recommended block rules.xml' -Force @@ -285,7 +285,7 @@ function New-WDACConfig { Remove-Item -Path '.\Microsoft recommended block rules TEMP.xml' -Force [System.String]$PolicyID = (Set-CIPolicyIdInfo -FilePath '.\Microsoft recommended block rules.xml' -ResetPolicyID).Substring(11) Set-CIPolicyIdInfo -PolicyName "Microsoft Windows User Mode Policy - Enforced - $(Get-Date -Format 'MM-dd-yyyy')" -FilePath '.\Microsoft recommended block rules.xml' - ConvertFrom-CIPolicy '.\Microsoft recommended block rules.xml' "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath '.\Microsoft recommended block rules.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null CiTool --update-policy "$PolicyID.cip" -json | Out-Null &$WriteLavender 'The Microsoft recommended block rules policy has been deployed in enforced mode.' Remove-Item "$PolicyID.cip" -Force @@ -319,7 +319,7 @@ function New-WDACConfig { [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoft.xml -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyIdInfo -PolicyName 'PrepMSFTOnlyAudit' -FilePath .\AllowMicrosoft.xml - ConvertFrom-CIPolicy .\AllowMicrosoft.xml "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoft.xml -BinaryFilePath "$PolicyID.cip" | Out-Null if ($Deploy) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null &$WriteHotPink 'The default AllowMicrosoft policy has been deployed in Audit mode. No reboot required.' @@ -351,7 +351,7 @@ function New-WDACConfig { [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindows_Audit.xml -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyIdInfo -PolicyName 'PrepDefaultWindows' -FilePath .\DefaultWindows_Audit.xml - ConvertFrom-CIPolicy .\DefaultWindows_Audit.xml "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Audit.xml -BinaryFilePath "$PolicyID.cip" | Out-Null if ($Deploy) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null &$WriteLavender 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' @@ -472,7 +472,7 @@ function New-WDACConfig { # Set the hypervisor Code Integrity option for Supplemental policy to Strict Set-HVCIOptions -Strict -FilePath 'SupplementalPolicy.xml' # convert the Supplemental Policy file to .cip binary file - ConvertFrom-CIPolicy 'SupplementalPolicy.xml' "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ BasePolicyFile = $BasePolicy @@ -521,7 +521,7 @@ function New-WDACConfig { $BasePolicyID = $BasePolicyID.Substring(11) Set-CIPolicyVersion -FilePath .\SignedAndReputable.xml -Version '1.0.0.0' Set-HVCIOptions -Strict -FilePath .\SignedAndReputable.xml - ConvertFrom-CIPolicy .\SignedAndReputable.xml "$BasePolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\SignedAndReputable.xml -BinaryFilePath "$BasePolicyID.cip" | Out-Null # Configure required services for ISG authorization Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index 1c6e3c5c9..0d5d9578f 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -272,7 +272,7 @@ function Remove-WDACConfig { } Set-RuleOption -FilePath $PolicyPath -Option 6 - ConvertFrom-CIPolicy $PolicyPath "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath "$PolicyID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ @@ -290,8 +290,8 @@ function Remove-WDACConfig { Rename-Item "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green - Write-Output "PolicyName = $PolicyName" - Write-Output "PolicyGUID = $PolicyID`n" + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID`n" } } diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/Resources.ps1 index 7954771e5..ac2c83c03 100644 --- a/WDACConfig/Resources.ps1 +++ b/WDACConfig/Resources.ps1 @@ -113,7 +113,7 @@ function Update-self { Import-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force -Global } # Make sure the old version isn't run after update - Write-Output "$($PSStyle.Foreground.FromRGB(152,255,152))Update successful, please run the cmdlet again.$($PSStyle.Reset)" + Write-Output -InputObject "$($PSStyle.Foreground.FromRGB(152,255,152))Update successful, please run the cmdlet again.$($PSStyle.Reset)" break return } @@ -178,7 +178,7 @@ function Test-FilePath { # Output the file path if it is not inside any of the directory paths if (-not $Result) { - Write-Output $FileFullPath + Write-Output -InputObject $FileFullPath } } else { @@ -243,11 +243,11 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa DevicePath = $SbPathName.ToString() } # Write the custom object to the output stream - Write-Output (New-Object -TypeName PSObject -Property $DriveMapping) + Write-Output -InputObject (New-Object -TypeName PSObject -Property $DriveMapping) } else { # If no device path is found, write a message to the output stream - Write-Output 'No mountpoint found for: ' + $Volume + Write-Output -InputObject 'No mountpoint found for: ' + $Volume } # Find the next volume in the system and repeat the loop } while ([PInvoke.Win32Utils]::FindNextVolume([System.IntPtr]$VolumeHandle, $SbVolumeName, $Max)) @@ -395,19 +395,19 @@ function Confirm-CertCN ([System.String]$CN) { # script blocks for custom color writing -[System.Management.Automation.ScriptBlock]$WriteHotPink = { Write-Output "$($PSStyle.Foreground.FromRGB(255,105,180))$($args[0])$($PSStyle.Reset)" } -[System.Management.Automation.ScriptBlock]$WritePink = { Write-Output "$($PSStyle.Foreground.FromRGB(255,0,230))$($args[0])$($PSStyle.Reset)" } -[System.Management.Automation.ScriptBlock]$WriteLavender = { Write-Output "$($PSStyle.Foreground.FromRgb(255,179,255))$($args[0])$($PSStyle.Reset)" } -[System.Management.Automation.ScriptBlock]$WriteTeaGreen = { Write-Output "$($PSStyle.Foreground.FromRgb(133, 222, 119))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WriteHotPink = { Write-Output -InputObject "$($PSStyle.Foreground.FromRGB(255,105,180))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WritePink = { Write-Output -InputObject "$($PSStyle.Foreground.FromRGB(255,0,230))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WriteLavender = { Write-Output -InputObject "$($PSStyle.Foreground.FromRgb(255,179,255))$($args[0])$($PSStyle.Reset)" } +[System.Management.Automation.ScriptBlock]$WriteTeaGreen = { Write-Output -InputObject "$($PSStyle.Foreground.FromRgb(133, 222, 119))$($args[0])$($PSStyle.Reset)" } # Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable function Get-FileRules { param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { - $Rules += Write-Output "`n" - $Rules += Write-Output "`n" - $Rules += Write-Output "`n" - $Rules += Write-Output "`n" + $Rules += Write-Output -InputObject "`n" + $Rules += Write-Output -InputObject "`n" + $Rules += Write-Output -InputObject "`n" + $Rules += Write-Output -InputObject "`n" $i++ } return ($Rules.Trim()) @@ -418,10 +418,10 @@ function Get-FileRules { function Get-RuleRefs { param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { - $RulesRefs += Write-Output "`n" - $RulesRefs += Write-Output "`n" - $RulesRefs += Write-Output "`n" - $RulesRefs += Write-Output "`n" + $RulesRefs += Write-Output -InputObject "`n" + $RulesRefs += Write-Output -InputObject "`n" + $RulesRefs += Write-Output -InputObject "`n" + $RulesRefs += Write-Output -InputObject "`n" $i++ } return ($RulesRefs.Trim()) diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 670468ff3..096f7366c 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -458,7 +458,7 @@ function Get-CertificateDetails { TBSValue = $TbsValue } # Display the object - Write-Output $Obj + Write-Output -InputObject $Obj } } elseif ($AllCertificates) { @@ -478,7 +478,7 @@ function Get-CertificateDetails { TBSValue = $TbsValue } # Display the object - Write-Output $obj + Write-Output -InputObject $obj } } elseif ($LeafCertificate) { @@ -496,12 +496,12 @@ function Get-CertificateDetails { TBSValue = $TbsValue } # Display the object - Write-Output 'Leaf Certificate:' - Write-Output $obj + Write-Output -InputObject 'Leaf Certificate:' + Write-Output -InputObject $obj } else { # If none of the switch parameters are present, display a message to inform the user of their options - Write-Output 'Please specify one of the following switch parameters to get certificate details: -IntermediateOnly, -AllCertificates, or -LeafCertificate.' + Write-Output -InputObject 'Please specify one of the following switch parameters to get certificate details: -IntermediateOnly, -AllCertificates, or -LeafCertificate.' } } From 5f88fe67b89d585bada5f61aa895330ec12b31a1 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:02:17 -0930 Subject: [PATCH 011/178] improved params according to best practices --- WDACConfig/Deploy-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 40 ++++++++++++------------- WDACConfig/Edit-WDACConfig.psm1 | 20 ++++++------- WDACConfig/New-WDACConfig.psm1 | 28 ++++++++--------- WDACConfig/Remove-WDACConfig.psm1 | 2 +- 5 files changed, 46 insertions(+), 46 deletions(-) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index d62f8e571..7312822aa 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -153,7 +153,7 @@ function Deploy-SignedWDACConfig { # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force Rename-Item "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force if ($Deploy) { diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 3cc4c7d81..750ed7f5c 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -245,7 +245,7 @@ function Edit-SignedWDACConfig { Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force } $DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock } @@ -330,9 +330,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { @@ -611,13 +611,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item ".\$SuppPolicyID.cip" -Force - Rename-Item "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + Remove-Item -Path ".\$SuppPolicyID.cip" -Force + Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" - Remove-Item ".\$SuppPolicyID.cip" -Force + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } } @@ -695,9 +695,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { @@ -821,13 +821,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item ".\$SuppPolicyID.cip" -Force - Rename-Item "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + Remove-Item -Path ".\$SuppPolicyID.cip" -Force + Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" - Remove-Item ".\$SuppPolicyID.cip" -Force + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } } @@ -879,8 +879,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item ".\$SuppPolicyID.cip" -Force - Rename-Item "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + Remove-Item -Path ".\$SuppPolicyID.cip" -Force + Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force @@ -939,14 +939,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Remove the extra files create during module operation that are no longer necessary if (!$Debug) { - Remove-Item '.\AllowPowerShell.xml', '.\SignTool.xml', '.\AllowMicrosoft.xml', '.\DefaultWindows_Enforced.xml' -Force -ErrorAction SilentlyContinue - Remove-Item '.\Microsoft recommended block rules.xml' -Force + Remove-Item -Path '.\AllowPowerShell.xml', '.\SignTool.xml', '.\AllowMicrosoft.xml', '.\DefaultWindows_Enforced.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force } # Get the policy ID of the currently deployed base policy based on the policy name that user selected $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" - Remove-Item ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue + Remove-Item -Path ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue [System.Xml.XmlDocument]$xml = Get-Content '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID @@ -972,8 +972,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item ".\$CurrentID.cip" -Force - Rename-Item "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force + Remove-Item -Path ".\$CurrentID.cip" -Force + Rename-Item -Path "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force # Deploy the new base policy with the same GUID on the system CiTool --update-policy "$CurrentID.cip" -json | Out-Null # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later @@ -982,8 +982,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Lightly_Managed_system_Policy' = 'SignedAndReputable.xml' 'DefaultWindows_WithBlockRules' = 'DefaultWindowsPlusBlockRules.xml' } - Remove-Item ".\$CurrentID.cip" -Force - Remove-Item $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue + Remove-Item -Path ".\$CurrentID.cip" -Force + Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] &$WritePink "Base Policy has been successfully updated to $NewBasePolicyType" &$WriteLavender 'Keep in mind that your previous policy path saved in User Configurations is no longer valid as you just changed your Base policy.' diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 40d06a4f0..9be8b9dac 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -183,7 +183,7 @@ function Edit-WDACConfig { Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force } $DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock @@ -262,9 +262,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { @@ -445,9 +445,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { @@ -716,7 +716,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item &$WriteTeaGreen "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" - Remove-Item ".\$SuppPolicyID.cip" -Force + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } } @@ -804,8 +804,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml # Remove the extra files create during module operation that are no longer necessary - Remove-Item '.\AllowPowerShell.xml', '.\DefaultWindows_Enforced.xml', '.\AllowMicrosoft.xml' -Force -ErrorAction SilentlyContinue - Remove-Item '.\Microsoft recommended block rules.xml' -Force + Remove-Item -Path '.\AllowPowerShell.xml', '.\DefaultWindows_Enforced.xml', '.\AllowMicrosoft.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force # Get the policy ID of the currently deployed base policy based on the policy name that user selected $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID @@ -819,7 +819,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy the new base policy with the same GUID on the system CiTool --update-policy "$CurrentID.cip" -json | Out-Null # Remove the policy binary after it's been deployed - Remove-Item "$CurrentID.cip" -Force + Remove-Item -Path "$CurrentID.cip" -Force # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later $PolicyFiles = @{ @@ -827,7 +827,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Lightly_Managed_system_Policy' = 'SignedAndReputable.xml' 'DefaultWindows_WithBlockRules' = 'DefaultWindowsPlusBlockRules.xml' } - Remove-Item $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue + Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force &$WritePink "Base Policy has been successfully updated to $NewBasePolicyType" &$WriteLavender 'Keep in mind that your previous policy path saved in User Configurations is no longer valid as you just changed your Base policy.' diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 9e0ff9e10..1ec31c00b 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -146,8 +146,8 @@ function New-WDACConfig { $DriverRules = $DriverRules -replace '', '' $DriverRules | Out-File 'Microsoft recommended driver block rules TEMP.xml' # Remove empty lines from the policy file - Get-Content 'Microsoft recommended driver block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File 'Microsoft recommended driver block rules.xml' - Remove-Item 'Microsoft recommended driver block rules TEMP.xml' -Force + Get-Content -Path 'Microsoft recommended driver block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File 'Microsoft recommended driver block rules.xml' + Remove-Item -Path 'Microsoft recommended driver block rules TEMP.xml' -Force Set-RuleOption -FilePath 'Microsoft recommended driver block rules.xml' -Option 3 -Delete Set-HVCIOptions -Strict -FilePath 'Microsoft recommended driver block rules.xml' # Display extra info about the Microsoft Drivers block list @@ -179,7 +179,7 @@ function New-WDACConfig { Set-HVCIOptions -Strict -FilePath .\AllowMicrosoftPlusBlockRules.xml ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules. -BinaryFilePath "$PolicyID.cip" | Out-Null # Remove the extra files that were created during module operation and are no longer needed - Remove-Item '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force + Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force [PSCustomObject]@{ PolicyFile = 'AllowMicrosoftPlusBlockRules.xml' BinaryFile = "$PolicyID.cip" @@ -247,8 +247,8 @@ function New-WDACConfig { Set-HVCIOptions -Strict -FilePath .\DefaultWindowsPlusBlockRules.xml ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindowsPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - Remove-Item .\AllowPowerShell.xml -Force -ErrorAction SilentlyContinue - Remove-Item '.\DefaultWindows_Enforced.xml', 'Microsoft recommended block rules.xml' -Force + Remove-Item -Path .\AllowPowerShell.xml -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\DefaultWindows_Enforced.xml', 'Microsoft recommended block rules.xml' -Force if ($global:MergeSignToolPolicy -and !$Debug) { Remove-Item -Path .\SignTool.xml -Force } [PSCustomObject]@{ @@ -266,12 +266,12 @@ function New-WDACConfig { [System.Management.Automation.ScriptBlock]$DeployLatestDriverBlockRulesSCRIPTBLOCK = { Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip -ProgressAction SilentlyContinue - Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force - Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force - Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' + Expand-Archive -Path .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force + Rename-Item -Path .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force + Copy-Item -Path .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' citool --refresh -json | Out-Null &$WritePink 'SiPolicy.p7b has been deployed and policies refreshed.' - Remove-Item .\VulnerableDriverBlockList* -Recurse -Force + Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } @@ -288,7 +288,7 @@ function New-WDACConfig { ConvertFrom-CIPolicy -XmlFilePath '.\Microsoft recommended block rules.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null CiTool --update-policy "$PolicyID.cip" -json | Out-Null &$WriteLavender 'The Microsoft recommended block rules policy has been deployed in enforced mode.' - Remove-Item "$PolicyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } [System.Management.Automation.ScriptBlock]$SetAutoUpdateDriverBlockRulesSCRIPTBLOCK = { @@ -323,7 +323,7 @@ function New-WDACConfig { if ($Deploy) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null &$WriteHotPink 'The default AllowMicrosoft policy has been deployed in Audit mode. No reboot required.' - Remove-Item 'AllowMicrosoft.xml', "$PolicyID.cip" -Force + Remove-Item -Path 'AllowMicrosoft.xml', "$PolicyID.cip" -Force } else { &$WriteHotPink 'The default AllowMicrosoft policy has been created in Audit mode and is ready for deployment.' @@ -342,9 +342,9 @@ function New-WDACConfig { New-CIPolicy -ScanPath "$psscriptroot" -Level hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\WDACConfigModule.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Audit.xml, .\AllowPowerShell.xml, .\WDACConfigModule.xml -OutputFilePath .\DefaultWindows_Audit_temp.xml | Out-Null - Remove-Item DefaultWindows_Audit.xml -Force + Remove-Item -Path DefaultWindows_Audit.xml -Force Rename-Item -Path .\DefaultWindows_Audit_temp.xml -NewName 'DefaultWindows_Audit.xml' -Force - Remove-Item 'WDACConfigModule.xml', 'AllowPowerShell.xml' -Force + Remove-Item -Path 'WDACConfigModule.xml', 'AllowPowerShell.xml' -Force } Set-RuleOption -FilePath .\DefaultWindows_Audit.xml -Option 3 @@ -355,7 +355,7 @@ function New-WDACConfig { if ($Deploy) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null &$WriteLavender 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' - Remove-Item 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force + Remove-Item -Path 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force } else { &$WriteLavender 'The defaultWindows policy has been created in Audit mode and is ready for deployment.' diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index 0d5d9578f..a2715f461 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -286,7 +286,7 @@ function Remove-WDACConfig { # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force Rename-Item "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green From 4e8ace410b98bf833ab08a42ebdbafcf201c4c67 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:05:07 -0930 Subject: [PATCH 012/178] Improved params best practices --- WDACConfig/ArgumentCompleters.ps1 | 8 ++++---- WDACConfig/Deploy-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 12 ++++++------ WDACConfig/Edit-WDACConfig.psm1 | 12 ++++++------ WDACConfig/New-SupplementalWDACConfig.psm1 | 2 +- WDACConfig/New-WDACConfig.psm1 | 6 +++--- WDACConfig/Remove-WDACConfig.psm1 | 6 +++--- WDACConfig/Resources2.ps1 | 2 +- WDACConfig/Set-CommonWDACConfig.psm1 | 4 ++-- 9 files changed, 27 insertions(+), 27 deletions(-) diff --git a/WDACConfig/ArgumentCompleters.ps1 b/WDACConfig/ArgumentCompleters.ps1 index 9670d829d..784c1970e 100644 --- a/WDACConfig/ArgumentCompleters.ps1 +++ b/WDACConfig/ArgumentCompleters.ps1 @@ -3,7 +3,7 @@ [System.Management.Automation.ScriptBlock]$ArgumentCompleterCertPath = { # Note the use of -Depth 1 # Enclosing the $results = ... assignment in (...) also passes the value through. - ($results = Get-ChildItem -Depth 2 -Filter *.cer | ForEach-Object { "`"$_`"" }) + ($results = Get-ChildItem -Depth 2 -Filter *.cer | ForEach-Object -Process { "`"$_`"" }) if (-not $results) { # No results? $null # Dummy response that prevents fallback to the default file-name completion. @@ -67,9 +67,9 @@ ).Value # Get the xml files in the current directory - Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object { + Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { - $xmlitem = [System.Xml.XmlDocument](Get-Content $_) + $xmlitem = [System.Xml.XmlDocument](Get-Content -Path $_) $PolicyType = $xmlitem.SiPolicy.PolicyType if ($PolicyType -eq 'Base Policy') { @@ -99,7 +99,7 @@ # Get the xml files in the current directory Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { - $xmlitem = [System.Xml.XmlDocument](Get-Content $_) + $xmlitem = [System.Xml.XmlDocument](Get-Content -Path $_) $PolicyType = $xmlitem.SiPolicy.PolicyType if ($PolicyType -eq 'Supplemental Policy') { diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index 7312822aa..4a1c1c972 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -108,7 +108,7 @@ function Deploy-SignedWDACConfig { foreach ($PolicyPath in $PolicyPaths) { # Gather policy details - $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyType = $xml.SiPolicy.PolicyType [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 750ed7f5c..9a7ca4336 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -48,7 +48,7 @@ function Edit-SignedWDACConfig { # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit an Unsigned policy using Edit-SignedWDACConfig cmdlet which is only made for Signed policies $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID @@ -275,7 +275,7 @@ function Edit-SignedWDACConfig { $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -640,7 +640,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -836,7 +836,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } @@ -853,7 +853,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID Citool --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them @@ -948,7 +948,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $CurrentID = "{$CurrentID}" Remove-Item -Path ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue - [System.Xml.XmlDocument]$xml = Get-Content '.\BasePolicy.xml' + [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 9be8b9dac..7853de1dc 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -27,7 +27,7 @@ function Edit-WDACConfig { # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit a Signed policy using Edit-WDACConfig cmdlet which is only made for Unsigned policies $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID @@ -208,7 +208,7 @@ function Edit-WDACConfig { $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -412,7 +412,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string @@ -725,7 +725,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } @@ -742,7 +742,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them foreach ($SuppPolicyPath in $SuppPolicyPaths) { - $Supplementalxml = [System.Xml.XmlDocument](Get-Content $SuppPolicyPath) + $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID Citool --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them @@ -811,7 +811,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Write-Debug -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" - [System.Xml.XmlDocument]$xml = Get-Content '.\BasePolicy.xml' + [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index c88364b14..b3a7c95b6 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -119,7 +119,7 @@ function New-SupplementalWDACConfig { # Ensure when user selects the -Deploy parameter, the base policy is not signed if ($Deploy) { - $xmlTest = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 1ec31c00b..f98e52f96 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -278,7 +278,7 @@ function New-WDACConfig { [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File '.\Microsoft recommended block rules TEMP.xml' # Remove empty lines from the policy file - Get-Content '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' + Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' @@ -375,14 +375,14 @@ function New-WDACConfig { switch ($BasePolicyType) { 'Allow Microsoft Base' { Invoke-Command -ScriptBlock $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK | Out-Null - $xml = [System.Xml.XmlDocument](Get-Content .\AllowMicrosoftPlusBlockRules.xml) + $xml = [System.Xml.XmlDocument](Get-Content -Path .\AllowMicrosoftPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' } 'Default Windows Base' { Invoke-Command -ScriptBlock $MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK | Out-Null - $xml = [System.Xml.XmlDocument](Get-Content .\DefaultWindowsPlusBlockRules.xml) + $xml = [System.Xml.XmlDocument](Get-Content -Path .\DefaultWindowsPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy $BasePolicy = 'DefaultWindowsPlusBlockRules.xml' diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index a2715f461..ba0bff331 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -16,7 +16,7 @@ function Remove-WDACConfig { [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to remove an Unsigned policy $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { return $True } @@ -239,7 +239,7 @@ function Remove-WDACConfig { if ($SignedBase) { foreach ($PolicyPath in $PolicyPaths) { - $xml = [System.Xml.XmlDocument](Get-Content $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } @@ -254,7 +254,7 @@ function Remove-WDACConfig { if ($SuppSingerIDs) { Write-Debug -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." $SuppSingerIDs | ForEach-Object -Process { - $PolContent = Get-Content -Raw -Path $PolicyPath + $PolContent = Get-Content -Path -Raw -Path $PolicyPath $PolContent -match "" | Out-Null $PolContent = $PolContent -replace $Matches[0], '' Set-Content -Value $PolContent -Path $PolicyPath diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 096f7366c..87786665e 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -19,7 +19,7 @@ function Get-SignerInfo { ) # Load the XML file and select the Signer nodes - $xml = [System.Xml.XmlDocument](Get-Content $XmlFilePath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $XmlFilePath) $Signers = $xml.SiPolicy.Signers.Signer # Create an empty array to store the output diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index b42be02f0..35db7ac1e 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -21,7 +21,7 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if (!$RedFlag1 -and !$RedFlag2) { @@ -35,7 +35,7 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content $_) + $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { From abe73e5e3b6205fe0d2bd8a8e7c58c59f2e99e81 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:07:02 -0930 Subject: [PATCH 013/178] Improved params of Rename-Item --- WDACConfig/Deploy-SignedWDACConfig.psm1 | 2 +- WDACConfig/Edit-SignedWDACConfig.psm1 | 12 ++++++------ WDACConfig/Edit-WDACConfig.psm1 | 4 ++-- WDACConfig/New-WDACConfig.psm1 | 2 +- WDACConfig/Remove-WDACConfig.psm1 | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index 4a1c1c972..d92aa6f3e 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -154,7 +154,7 @@ function Deploy-SignedWDACConfig { Start-Process @ProcessParams Remove-Item -Path ".\$PolicyID.cip" -Force - Rename-Item "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force + Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force if ($Deploy) { diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 9a7ca4336..a598a59d8 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -309,8 +309,8 @@ function Edit-SignedWDACConfig { # After creating signed .p7 files for each CIP, remove the old Unsigned ones Remove-Item -Path $_ -Force } - Rename-Item '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force - Rename-Item '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force + Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force + Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' @@ -324,7 +324,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' - Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" @@ -674,8 +674,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # After creating signed .p7 files for each CIP, remove the old Unsigned ones Remove-Item -Path $_ -Force } - Rename-Item '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force - Rename-Item '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force + Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force + Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' @@ -689,7 +689,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' - Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 7853de1dc..2edcebf70 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -256,7 +256,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' - Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" @@ -439,7 +439,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' - Rename-Item '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force + Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index f98e52f96..a35aa85e0 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -460,7 +460,7 @@ function New-WDACConfig { } # do this only if there are no event logs detected with files no longer on the disk, so we use the policy file created earlier using Audit even logs else { - Rename-Item 'AuditLogsPolicy_NoDeletedFiles.xml' -NewName 'SupplementalPolicy.xml' -Force + Rename-Item -Path 'AuditLogsPolicy_NoDeletedFiles.xml' -NewName 'SupplementalPolicy.xml' -Force } # Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy Set-CIPolicyVersion -FilePath 'SupplementalPolicy.xml' -Version '1.0.0.0' diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index ba0bff331..12c1e14be 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -287,7 +287,7 @@ function Remove-WDACConfig { Start-Process @ProcessParams Remove-Item -Path ".\$PolicyID.cip" -Force - Rename-Item "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force + Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" From f5ac75d5275a50e03fdeae51741cf39ea764186e Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:11:56 -0930 Subject: [PATCH 014/178] Improved Write-Host params --- WDACConfig/Deploy-SignedWDACConfig.psm1 | 6 +++--- WDACConfig/Edit-SignedWDACConfig.psm1 | 14 +++++++------- WDACConfig/Edit-WDACConfig.psm1 | 16 ++++++++-------- WDACConfig/Invoke-WDACSimulation.psm1 | 4 ++-- WDACConfig/New-DenyWDACConfig.psm1 | 12 ++++++------ WDACConfig/New-SupplementalWDACConfig.psm1 | 2 +- WDACConfig/New-WDACConfig.psm1 | 6 +++--- WDACConfig/Remove-WDACConfig.psm1 | 6 +++--- 8 files changed, 33 insertions(+), 33 deletions(-) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index d92aa6f3e..a49e53765 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -159,7 +159,7 @@ function Deploy-SignedWDACConfig { if ($Deploy) { CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-Host "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green + Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" Remove-Item -Path ".\$PolicyID.cip" -Force @@ -194,7 +194,7 @@ function Deploy-SignedWDACConfig { # Ask user question about whether or not to add the Signed policy xml file to the User Config Json for easier usage later $userInput = '' while ($userInput -notin 1, 2) { - $userInput = $(Write-Host 'Add the Signed policy xml file path just created to the User Configurations? Please enter 1 to Confirm or 2 to Skip.' -ForegroundColor Cyan ; Read-Host) + $userInput = $(Write-Host -Object 'Add the Signed policy xml file path just created to the User Configurations? Please enter 1 to Confirm or 2 to Skip.' -ForegroundColor Cyan ; Read-Host) if ($userInput -eq 1) { Set-CommonWDACConfig -SignedPolicyPath $PolicyPath &$WriteHotPink "Added $PolicyPath to the User Configuration file." @@ -210,7 +210,7 @@ function Deploy-SignedWDACConfig { } else { - Write-Host "`npolicy with the following details has been Signed and is ready for deployment:" -ForegroundColor Green + Write-Host -Object "`npolicy with the following details has been Signed and is ready for deployment:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" } diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index a598a59d8..50e227494 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -343,7 +343,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() - Write-Host "`nSelect program directories to scan" -ForegroundColor Cyan + Write-Host -Object "`nSelect program directories to scan" -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -360,17 +360,17 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } - Write-Host 'Here are the paths you selected:' -ForegroundColor Yellow + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } ################################### EventCapturing ################################ - Write-Host 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan + Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date @@ -708,7 +708,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() - Write-Host "`nSelect program directories to scan`n" -ForegroundColor Cyan + Write-Host -Object "`nSelect program directories to scan`n" -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -725,7 +725,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } @@ -753,7 +753,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - Write-Host "`nHere are the paths you selected:" -ForegroundColor Yellow + Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } #Process Program Folders From User input diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index 2edcebf70..ae1a068a9 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -275,7 +275,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() - Write-Host "`nSelect program directories to scan" -ForegroundColor Cyan + Write-Host -Object "`nSelect program directories to scan" -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -292,7 +292,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } @@ -327,7 +327,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Remove-Item -Path 'c:\EnforcedModeSnapBack.cmd' -Force } - Write-Host "`nHere are the paths you selected:" -ForegroundColor Yellow + Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } #Process Program Folders From User input @@ -458,7 +458,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() - Write-Host "`nSelect program directories to scan`n" -ForegroundColor Cyan + Write-Host -Object "`nSelect program directories to scan`n" -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -475,17 +475,17 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } - Write-Host 'Here are the paths you selected:' -ForegroundColor Yellow + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } ################################### EventCapturing ################################ - Write-Host 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan + Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date @@ -785,7 +785,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed if (Test-Path 'C:\Program Files\PowerShell') { - Write-Host 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue + Write-Host -Object 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } diff --git a/WDACConfig/Invoke-WDACSimulation.psm1 b/WDACConfig/Invoke-WDACSimulation.psm1 index 649a67a84..fc348cb16 100644 --- a/WDACConfig/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/Invoke-WDACSimulation.psm1 @@ -87,7 +87,7 @@ function Invoke-WDACSimulation { 'valid' { # If debug is used show extra info on the console if ($Debug) { - Write-Host "Currently processing signed file: `n$CurrentFilePath" -ForegroundColor Yellow + Write-Host -Object "Currently processing signed file: `n$CurrentFilePath" -ForegroundColor Yellow } # Use the function in Resources2.ps1 file to process it $SignedResult += Compare-SignerAndCertificate -XmlFilePath $XmlFilePath -SignedFilePath $CurrentFilePath | Where-Object -FilterScript { ($_.CertRootMatch -eq $true) -and ($_.CertNameMatch -eq $true) -and ($_.CertPublisherMatch -eq $true) } @@ -220,7 +220,7 @@ function Invoke-WDACSimulation { $MegaOutputObject | Select-Object -Property FilePath, source, Permission -Unique | Sort-Object -Property Permission | Export-Csv -Path .\WDACSimulationOutput.csv -Force if ($Debug) { - Write-Host 'Files that were UNSIGNED' -ForegroundColor Blue + Write-Host -Object 'Files that were UNSIGNED' -ForegroundColor Blue $AllowedUnsignedFilePaths } diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index 6d271c1eb..ff88a16a4 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -153,9 +153,9 @@ function New-DenyWDACConfig { if ($Deploy) { CiTool --update-policy "$policyID.cip" -json | Out-Null - Write-Host -NoNewline "`n$policyID.cip for " -ForegroundColor Green - Write-Host -NoNewline "$PolicyName" -ForegroundColor Magenta - Write-Host ' has been deployed.' -ForegroundColor Green + Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green + Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta + Write-Host -Object ' has been deployed.' -ForegroundColor Green Remove-Item -Path "$policyID.cip" -Force } } @@ -208,9 +208,9 @@ function New-DenyWDACConfig { } if ($Deploy) { CiTool --update-policy "$policyID.cip" -json | Out-Null - Write-Host -NoNewline "`n$policyID.cip for " -ForegroundColor Green - Write-Host -NoNewline "$PolicyName" -ForegroundColor Magenta - Write-Host ' has been deployed.' -ForegroundColor Green + Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green + Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta + Write-Host -Object ' has been deployed.' -ForegroundColor Green Remove-Item -Path "$policyID.cip" -Force } } diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index b3a7c95b6..988d13cc7 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -149,7 +149,7 @@ function New-SupplementalWDACConfig { &$WriteHotPink "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable - Write-Host "`n" + Write-Host -Object "`n" # Create the supplemental policy via parameter splatting New-CIPolicy @PolicyMakerHashTable diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index a35aa85e0..db5289412 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -186,7 +186,7 @@ function New-WDACConfig { } if ($Deploy -and $MakeAllowMSFTWithBlockRules) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null - Write-Host "`n" + Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } if ($NoCIP) @@ -258,7 +258,7 @@ function New-WDACConfig { if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null - Write-Host "`n" + Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } @@ -418,7 +418,7 @@ function New-WDACConfig { &$WriteHotPink "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable - Write-Host "`n" + Write-Host -Object "`n" # Create the supplemental policy via parameter splatting for files in event viewer that are currently on the disk New-CIPolicy @PolicyMakerHashTable diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index 12c1e14be..cc65b34c6 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -289,7 +289,7 @@ function Remove-WDACConfig { Remove-Item -Path ".\$PolicyID.cip" -Force Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-Host "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green + Write-Host -Object "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" } @@ -300,7 +300,7 @@ function Remove-WDACConfig { # If IDs were supplied by user foreach ($ID in $PolicyIDs ) { citool --remove-policy "{$ID}" -json | Out-Null - Write-Host "Policy with the ID $ID has been successfully removed." -ForegroundColor Green + Write-Host -Object "Policy with the ID $ID has been successfully removed." -ForegroundColor Green } # If names were supplied by user @@ -315,7 +315,7 @@ function Remove-WDACConfig { $NameID | Select-Object -Unique | ForEach-Object -Process { citool --remove-policy "{$_}" -json | Out-Null - Write-Host "Policy with the ID $_ has been successfully removed." -ForegroundColor Green + Write-Host -Object "Policy with the ID $_ has been successfully removed." -ForegroundColor Green } } } From c90262c7170434b1ae4e8c48366b48a28acf0675 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:14:31 -0930 Subject: [PATCH 015/178] Improved params of Test-Path --- WDACConfig/Deploy-SignedWDACConfig.psm1 | 6 +++--- WDACConfig/Edit-SignedWDACConfig.psm1 | 12 ++++++------ WDACConfig/Edit-WDACConfig.psm1 | 8 ++++---- WDACConfig/Invoke-WDACSimulation.psm1 | 4 ++-- WDACConfig/New-DenyWDACConfig.psm1 | 2 +- WDACConfig/New-SupplementalWDACConfig.psm1 | 6 +++--- WDACConfig/New-WDACConfig.psm1 | 6 +++--- WDACConfig/Resources2.ps1 | 2 +- WDACConfig/Set-CommonWDACConfig.psm1 | 4 ++-- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index a49e53765..6b18b0e58 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -7,13 +7,13 @@ function Deploy-SignedWDACConfig { )] Param( [ValidatePattern('\.xml$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $true)][System.String[]]$PolicyPaths, [Parameter(Mandatory = $false)][Switch]$Deploy, [ValidatePattern('\.cer$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $false)][System.String]$CertPath, [ValidateScript({ @@ -72,7 +72,7 @@ function Deploy-SignedWDACConfig { if (!$CertPath) { if ($UserConfig.CertificatePath) { # validate user config values for Certificate Path - if (Test-Path $($UserConfig.CertificatePath)) { + if (Test-Path -Path $($UserConfig.CertificatePath)) { # If the user config values are correct then use them $CertPath = $UserConfig.CertificatePath } diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 50e227494..69088f98f 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -23,7 +23,7 @@ function Edit-SignedWDACConfig { [System.String]$SuppPolicyName, [ValidatePattern('\.xml$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [Parameter(Mandatory = $true, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] [System.String[]]$SuppPolicyPaths, @@ -39,7 +39,7 @@ function Edit-SignedWDACConfig { [System.String]$NewBasePolicyType, [ValidatePattern('\.cer$')] # Used by the entire Cmdlet - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [System.String]$CertPath, @@ -160,7 +160,7 @@ function Edit-SignedWDACConfig { if (!$CertPath) { if ($UserConfig.CertificatePath) { # validate user config values for Certificate Path - if (Test-Path $($UserConfig.CertificatePath)) { + if (Test-Path -Path $($UserConfig.CertificatePath)) { # If the user config values are correct then use them $CertPath = $UserConfig.CertificatePath } @@ -196,7 +196,7 @@ function Edit-SignedWDACConfig { if ($PSCmdlet.ParameterSetName -in 'Allow New Apps Audit Events', 'Allow New Apps', 'Merge Supplemental Policies') { if ($UserConfig.SignedPolicyPath) { # validate each policyPath read from user config file - if (Test-Path $($UserConfig.SignedPolicyPath)) { + if (Test-Path -Path $($UserConfig.SignedPolicyPath)) { $PolicyPaths = $UserConfig.SignedPolicyPath } else { @@ -516,7 +516,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk - if (Test-Path $_.'File Name') { + if (Test-Path -Path $_.'File Name') { # Check if the file exits in the $ExesWithNoHash array if ($ExesWithNoHash -contains $_.'File Name') { $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' @@ -921,7 +921,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$Debug) { Remove-Item -Recurse -Path "$global:UserTempDirectoryPath\TemporarySignToolFile" -Force } # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed - if (Test-Path 'C:\Program Files\PowerShell') { + if (Test-Path -Path 'C:\Program Files\PowerShell') { &$WriteHotPink "`nCreating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it." New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index ae1a068a9..c5547aecb 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -50,7 +50,7 @@ function Edit-WDACConfig { [System.String[]]$PolicyPaths, [ValidatePattern('\.xml$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [Parameter(Mandatory = $true, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] [System.String[]]$SuppPolicyPaths, @@ -136,7 +136,7 @@ function Edit-WDACConfig { if (!$PolicyPaths) { if ($UserConfig.UnsignedPolicyPath) { # validate each policyPath read from user config file - if (Test-Path $($UserConfig.UnsignedPolicyPath)) { + if (Test-Path -Path $($UserConfig.UnsignedPolicyPath)) { $PolicyPaths = $UserConfig.UnsignedPolicyPath } else { @@ -631,7 +631,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk - if (Test-Path $_.'File Name') { + if (Test-Path -Path $_.'File Name') { # Check if the file exits in the $ExesWithNoHash array if ($ExesWithNoHash -contains $_.'File Name') { $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' @@ -784,7 +784,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'DefaultWindows_WithBlockRules' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed - if (Test-Path 'C:\Program Files\PowerShell') { + if (Test-Path -Path 'C:\Program Files\PowerShell') { Write-Host -Object 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null diff --git a/WDACConfig/Invoke-WDACSimulation.psm1 b/WDACConfig/Invoke-WDACSimulation.psm1 index fc348cb16..e2bcf08a7 100644 --- a/WDACConfig/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/Invoke-WDACSimulation.psm1 @@ -5,10 +5,10 @@ function Invoke-WDACSimulation { SupportsShouldProcess = $true )] Param( - [ValidateScript({ Test-Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] [Parameter(Mandatory = $true)][System.String]$FolderPath, - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [Parameter(Mandatory = $true)][System.String]$XmlFilePath, [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck # Used by the entire Cmdlet diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index ff88a16a4..7e352ce64 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -22,7 +22,7 @@ function New-DenyWDACConfig { [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet [System.String]$PolicyName, - [ValidateScript({ Test-Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] [Parameter(Mandatory = $false, ParameterSetName = 'Drivers')] [System.String[]]$ScanLocations, diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index 988d13cc7..ac2c17105 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -18,7 +18,7 @@ function New-SupplementalWDACConfig { [parameter(Mandatory = $true, ParameterSetName = 'Installed AppXPackages', ValueFromPipelineByPropertyName = $true)] [System.String]$PackageName, - [ValidateScript({ Test-Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] [parameter(Mandatory = $true, ParameterSetName = 'Normal', ValueFromPipelineByPropertyName = $true)] [System.String]$ScanLocation, @@ -31,7 +31,7 @@ function New-SupplementalWDACConfig { [System.String]$SuppPolicyName, [ValidatePattern('\.xml$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet [System.String]$PolicyPath, @@ -104,7 +104,7 @@ function New-SupplementalWDACConfig { if (!$PolicyPath) { if ($UserConfig.UnsignedPolicyPath) { # validate each policyPath read from user config file - if (Test-Path $($UserConfig.UnsignedPolicyPath)) { + if (Test-Path -Path $($UserConfig.UnsignedPolicyPath)) { $PolicyPath = $UserConfig.UnsignedPolicyPath } else { diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index db5289412..06e3a358a 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -213,7 +213,7 @@ function New-WDACConfig { } # Scan PowerShell core directory and allow its files in the Default Windows base policy so that module can still be used once it's been deployed - if (Test-Path 'C:\Program Files\PowerShell') { + if (Test-Path -Path 'C:\Program Files\PowerShell') { &$WriteLavender 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml @@ -337,7 +337,7 @@ function New-WDACConfig { # Making Sure neither PowerShell core nor WDACConfig module files are added to the Supplemental policy created by -MakePolicyFromAuditLogs parameter # by adding them first to the deployed Default Windows policy in Audit mode. Because WDACConfig module files don't need to be allowed to run since they are *.ps1 and .*psm1 files # And PowerShell core files will be added to the DefaultWindows Base policy anyway - if (Test-Path 'C:\Program Files\PowerShell') { + if (Test-Path -Path 'C:\Program Files\PowerShell') { New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml New-CIPolicy -ScanPath "$psscriptroot" -Level hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\WDACConfigModule.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Audit.xml, .\AllowPowerShell.xml, .\WDACConfigModule.xml -OutputFilePath .\DefaultWindows_Audit_temp.xml | Out-Null @@ -437,7 +437,7 @@ function New-WDACConfig { $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } - if (-NOT (Test-Path $_.'File Name')) { + if (-NOT (Test-Path -Path $_.'File Name')) { $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } } diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index 87786665e..a07912dcf 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -412,7 +412,7 @@ function Get-CertificateDetails { param ( # Make the FilePath parameter mandatory and validate that it is a valid file path [Parameter()] - [ValidateScript({ Test-Path $_ -PathType Leaf })] + [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [string]$FilePath, $X509Certificate2, [switch]$IntermediateOnly, diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index 35db7ac1e..b1cb5748e 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -11,11 +11,11 @@ function Set-CommonWDACConfig { [parameter(Mandatory = $false)][System.String]$CertCN, [ValidatePattern('\.cer$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $false)][System.String]$CertPath, [ValidatePattern('\.exe$')] - [ValidateScript({ Test-Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $false)][System.String]$SignToolPath, [ValidatePattern('\.xml$')] From 63f76a73961e080f1733614e2c49aeb8ad8ecef4 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:15:52 -0930 Subject: [PATCH 016/178] Update New-WDACConfig.psm1 --- WDACConfig/New-WDACConfig.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 06e3a358a..79e7085a6 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -508,7 +508,7 @@ function New-WDACConfig { [System.Management.Automation.ScriptBlock]$MakeLightPolicySCRIPTBLOCK = { # Delete the any policy with the same name in the current working directory Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue - Invoke-Command $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK -ArgumentList $true | Out-Null + Invoke-Command -ScriptBlock $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK -ArgumentList $true | Out-Null Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } if ($TestMode -and $MakeLightPolicy) { From 4d3a7cd997d513dd5c86b22eb5ef4e0be6f26061 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 1 Dec 2023 09:23:44 -0930 Subject: [PATCH 017/178] Improved all cmdlet param types --- WDACConfig/Confirm-WDACConfig.psm1 | 14 ++++---- WDACConfig/Deploy-SignedWDACConfig.psm1 | 6 ++-- WDACConfig/Edit-SignedWDACConfig.psm1 | 24 +++++++------- WDACConfig/Edit-WDACConfig.psm1 | 24 +++++++------- WDACConfig/Get-CommonWDACConfig.psm1 | 20 ++++++------ WDACConfig/Invoke-WDACSimulation.psm1 | 2 +- WDACConfig/New-DenyWDACConfig.psm1 | 14 ++++---- WDACConfig/New-KernelModeWDACConfig.psm1 | 18 +++++----- WDACConfig/New-SupplementalWDACConfig.psm1 | 16 ++++----- WDACConfig/New-WDACConfig.psm1 | 38 +++++++++++----------- WDACConfig/Remove-CommonWDACConfig.psm1 | 18 +++++----- WDACConfig/Remove-WDACConfig.psm1 | 12 +++---- WDACConfig/Resources2.ps1 | 32 +++++++++--------- WDACConfig/Set-CommonWDACConfig.psm1 | 2 +- 14 files changed, 120 insertions(+), 120 deletions(-) diff --git a/WDACConfig/Confirm-WDACConfig.psm1 b/WDACConfig/Confirm-WDACConfig.psm1 index 930d17b76..5ff84f1f3 100644 --- a/WDACConfig/Confirm-WDACConfig.psm1 +++ b/WDACConfig/Confirm-WDACConfig.psm1 @@ -3,13 +3,13 @@ function Confirm-WDACConfig { [CmdletBinding(DefaultParameterSetName = 'List Active Policies')] Param( [Alias('L')] - [Parameter(Mandatory = $false, ParameterSetName = 'List Active Policies')][Switch]$ListActivePolicies, + [Parameter(Mandatory = $false, ParameterSetName = 'List Active Policies')][System.Management.Automation.SwitchParameter]$ListActivePolicies, [Alias('V')] - [Parameter(Mandatory = $false, ParameterSetName = 'Verify WDAC Status')][Switch]$VerifyWDACStatus, + [Parameter(Mandatory = $false, ParameterSetName = 'Verify WDAC Status')][System.Management.Automation.SwitchParameter]$VerifyWDACStatus, [Alias('S')] - [Parameter(Mandatory = $false, ParameterSetName = 'Check SmartAppControl Status')][Switch]$CheckSmartAppControlStatus, + [Parameter(Mandatory = $false, ParameterSetName = 'Check SmartAppControl Status')][System.Management.Automation.SwitchParameter]$CheckSmartAppControlStatus, - [Parameter(Mandatory = $false, DontShow = $true)][Switch]$DummyParameter # To hide common parameters + [Parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$DummyParameter # To hide common parameters ) DynamicParam { @@ -28,7 +28,7 @@ function Confirm-WDACConfig { $ParamDictionary.Add('OnlyBasePolicies', [System.Management.Automation.RuntimeDefinedParameter]::new( 'OnlyBasePolicies', - [switch], + [System.Management.Automation.SwitchParameter], [System.Management.Automation.ParameterAttribute[]]@($OnlyBasePoliciesDynamicParameter) )) @@ -42,7 +42,7 @@ function Confirm-WDACConfig { $ParamDictionary.Add('OnlySupplementalPolicies', [System.Management.Automation.RuntimeDefinedParameter]::new( 'OnlySupplementalPolicies', - [switch], + [System.Management.Automation.SwitchParameter], [System.Management.Automation.ParameterAttribute[]]@($OnlySupplementalPoliciesDynamicParameter) )) } @@ -57,7 +57,7 @@ function Confirm-WDACConfig { $ParamDictionary.Add('SkipVersionCheck', [System.Management.Automation.RuntimeDefinedParameter]::new( 'SkipVersionCheck', - [switch], + [System.Management.Automation.SwitchParameter], [System.Management.Automation.ParameterAttribute[]]@($SkipVersionCheckDynamicParameter) )) diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/Deploy-SignedWDACConfig.psm1 index 6b18b0e58..23d669db7 100644 --- a/WDACConfig/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/Deploy-SignedWDACConfig.psm1 @@ -10,7 +10,7 @@ function Deploy-SignedWDACConfig { [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $true)][System.String[]]$PolicyPaths, - [Parameter(Mandatory = $false)][Switch]$Deploy, + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$Deploy, [ValidatePattern('\.cer$')] [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] @@ -27,7 +27,7 @@ function Deploy-SignedWDACConfig { [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [System.String]$SignToolPath, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -42,7 +42,7 @@ function Deploy-SignedWDACConfig { $Debug = $PSBoundParameters.Debug.IsPresent # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/Edit-SignedWDACConfig.psm1 index 69088f98f..1e6b79228 100644 --- a/WDACConfig/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/Edit-SignedWDACConfig.psm1 @@ -8,13 +8,13 @@ function Edit-SignedWDACConfig { )] Param( [Alias('E')] - [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][Switch]$AllowNewAppsAuditEvents, + [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][System.Management.Automation.SwitchParameter]$AllowNewAppsAuditEvents, [Alias('A')] - [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')][Switch]$AllowNewApps, + [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')][System.Management.Automation.SwitchParameter]$AllowNewApps, [Alias('M')] - [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')][Switch]$MergeSupplementalPolicies, + [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')][System.Management.Automation.SwitchParameter]$MergeSupplementalPolicies, [Alias('U')] - [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][Switch]$UpdateBasePolicy, + [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][System.Management.Automation.SwitchParameter]$UpdateBasePolicy, [ValidatePattern('^[a-zA-Z0-9 ]+$', ErrorMessage = 'The Supplemental Policy Name can only contain alphanumeric and space characters.')] [Parameter(Mandatory = $true, ParameterSetName = 'Allow New Apps Audit Events', ValueFromPipelineByPropertyName = $true)] @@ -28,7 +28,7 @@ function Edit-SignedWDACConfig { [System.String[]]$SuppPolicyPaths, [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')] - [switch]$KeepOldSupplementalPolicies, + [System.Management.Automation.SwitchParameter]$KeepOldSupplementalPolicies, [ValidateSet([BasePolicyNamez])] [Parameter(Mandatory = $true, ParameterSetName = 'Update Base Policy')] @@ -85,18 +85,18 @@ function Edit-SignedWDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] - [Switch]$NoScript, + [System.Management.Automation.SwitchParameter]$NoScript, [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] - [Switch]$NoUserPEs, + [System.Management.Automation.SwitchParameter]$NoUserPEs, [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] [System.String]$SpecificFileNameLevel, - [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][Switch]$IncludeDeletedFiles, + [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][System.Management.Automation.SwitchParameter]$IncludeDeletedFiles, [ValidateSet([Levelz])] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] @@ -112,10 +112,10 @@ function Edit-SignedWDACConfig { [System.String]$SignToolPath, [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')] - [Switch]$RequireEVSigners, + [System.Management.Automation.SwitchParameter]$RequireEVSigners, [Parameter(Mandatory = $false)] # Used by the entire Cmdlet - [Switch]$SkipVersionCheck + [System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -127,10 +127,10 @@ function Edit-SignedWDACConfig { if (-NOT $SkipVersionCheck) { . Update-self } # Fetching Temp Directory - [string]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() + [System.String]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/Edit-WDACConfig.psm1 index c5547aecb..9b5c43fa3 100644 --- a/WDACConfig/Edit-WDACConfig.psm1 +++ b/WDACConfig/Edit-WDACConfig.psm1 @@ -8,13 +8,13 @@ function Edit-WDACConfig { )] Param( [Alias('E')] - [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][Switch]$AllowNewAppsAuditEvents, + [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][System.Management.Automation.SwitchParameter]$AllowNewAppsAuditEvents, [Alias('A')] - [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')][Switch]$AllowNewApps, + [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')][System.Management.Automation.SwitchParameter]$AllowNewApps, [Alias('M')] - [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')][Switch]$MergeSupplementalPolicies, + [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')][System.Management.Automation.SwitchParameter]$MergeSupplementalPolicies, [Alias('U')] - [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][Switch]$UpdateBasePolicy, + [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][System.Management.Automation.SwitchParameter]$UpdateBasePolicy, [ValidatePattern('^[a-zA-Z0-9 ]+$', ErrorMessage = 'The Supplemental Policy Name can only contain alphanumeric and space characters.')] [Parameter(Mandatory = $true, ParameterSetName = 'Allow New Apps Audit Events', ValueFromPipelineByPropertyName = $true)] @@ -55,7 +55,7 @@ function Edit-WDACConfig { [System.String[]]$SuppPolicyPaths, [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')] - [switch]$KeepOldSupplementalPolicies, + [System.Management.Automation.SwitchParameter]$KeepOldSupplementalPolicies, [ValidateSet([Levelz])] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] @@ -69,11 +69,11 @@ function Edit-WDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] - [Switch]$NoScript, + [System.Management.Automation.SwitchParameter]$NoScript, [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] - [Switch]$NoUserPEs, + [System.Management.Automation.SwitchParameter]$NoUserPEs, [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] @@ -85,7 +85,7 @@ function Edit-WDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [System.Int64]$LogSize, - [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][Switch]$IncludeDeletedFiles, + [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')][System.Management.Automation.SwitchParameter]$IncludeDeletedFiles, [ValidateSet([BasePolicyNamez])] [Parameter(Mandatory = $true, ParameterSetName = 'Update Base Policy')][System.String[]]$CurrentBasePolicyName, @@ -93,9 +93,9 @@ function Edit-WDACConfig { [ValidateSet('AllowMicrosoft_Plus_Block_Rules', 'Lightly_Managed_system_Policy', 'DefaultWindows_WithBlockRules')] [Parameter(Mandatory = $true, ParameterSetName = 'Update Base Policy')][System.String]$NewBasePolicyType, - [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][Switch]$RequireEVSigners, + [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][System.Management.Automation.SwitchParameter]$RequireEVSigners, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -107,10 +107,10 @@ function Edit-WDACConfig { if (-NOT $SkipVersionCheck) { . Update-self } # Fetching Temp Directory - [string]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() + [System.String]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath # Detecting if Debug switch is used, will do debugging actions based on that $Debug = $PSBoundParameters.Debug.IsPresent diff --git a/WDACConfig/Get-CommonWDACConfig.psm1 b/WDACConfig/Get-CommonWDACConfig.psm1 index f8d0dee35..4d3927204 100644 --- a/WDACConfig/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/Get-CommonWDACConfig.psm1 @@ -2,15 +2,15 @@ function Get-CommonWDACConfig { [CmdletBinding()] Param( - [parameter(Mandatory = $false)][switch]$CertCN, - [parameter(Mandatory = $false)][switch]$CertPath, - [parameter(Mandatory = $false)][switch]$SignToolPath, - [parameter(Mandatory = $false)][switch]$SignedPolicyPath, - [parameter(Mandatory = $false)][switch]$UnsignedPolicyPath, - [parameter(Mandatory = $false, DontShow = $true)][switch]$StrictKernelPolicyGUID, # DontShow prevents common parameters from being displayed too - [parameter(Mandatory = $false, DontShow = $true)][switch]$StrictKernelNoFlightRootsPolicyGUID, - [parameter(Mandatory = $false)][switch]$Open, - [parameter(Mandatory = $false, DontShow = $true)][switch]$LastUpdateCheck + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignToolPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$UnsignedPolicyPath, + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, # DontShow prevents common parameters from being displayed too + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$Open, + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck ) begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable @@ -20,7 +20,7 @@ function Get-CommonWDACConfig { $ErrorActionPreference = 'Stop' # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\")) { diff --git a/WDACConfig/Invoke-WDACSimulation.psm1 b/WDACConfig/Invoke-WDACSimulation.psm1 index e2bcf08a7..b813c5bff 100644 --- a/WDACConfig/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/Invoke-WDACSimulation.psm1 @@ -11,7 +11,7 @@ function Invoke-WDACSimulation { [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [Parameter(Mandatory = $true)][System.String]$XmlFilePath, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck # Used by the entire Cmdlet + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck # Used by the entire Cmdlet ) begin { diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/New-DenyWDACConfig.psm1 index 7e352ce64..3749f74a1 100644 --- a/WDACConfig/New-DenyWDACConfig.psm1 +++ b/WDACConfig/New-DenyWDACConfig.psm1 @@ -9,11 +9,11 @@ function New-DenyWDACConfig { Param( # Main parameters for position 0 [Alias('N')] - [Parameter(Mandatory = $false, ParameterSetName = 'Normal')][Switch]$Normal, + [Parameter(Mandatory = $false, ParameterSetName = 'Normal')][System.Management.Automation.SwitchParameter]$Normal, [Alias('D')] - [Parameter(Mandatory = $false, ParameterSetName = 'Drivers')][Switch]$Drivers, + [Parameter(Mandatory = $false, ParameterSetName = 'Drivers')][System.Management.Automation.SwitchParameter]$Drivers, [Alias('P')] - [parameter(mandatory = $false, ParameterSetName = 'Installed AppXPackages')][switch]$InstalledAppXPackages, + [parameter(mandatory = $false, ParameterSetName = 'Installed AppXPackages')][System.Management.Automation.SwitchParameter]$InstalledAppXPackages, [parameter(Mandatory = $true, ParameterSetName = 'Installed AppXPackages', ValueFromPipelineByPropertyName = $true)] [System.String]$PackageName, @@ -42,15 +42,15 @@ function New-DenyWDACConfig { [System.String]$SpecificFileNameLevel, [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] - [Switch]$NoUserPEs, + [System.Management.Automation.SwitchParameter]$NoUserPEs, [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] - [Switch]$NoScript, + [System.Management.Automation.SwitchParameter]$NoScript, [Parameter(Mandatory = $false)] # Used by the entire Cmdlet - [Switch]$Deploy, + [System.Management.Automation.SwitchParameter]$Deploy, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck # Used by the entire Cmdlet + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck # Used by the entire Cmdlet ) begin { diff --git a/WDACConfig/New-KernelModeWDACConfig.psm1 b/WDACConfig/New-KernelModeWDACConfig.psm1 index 9b6eb57bf..d612ccca5 100644 --- a/WDACConfig/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/New-KernelModeWDACConfig.psm1 @@ -6,26 +6,26 @@ function New-KernelModeWDACConfig { ConfirmImpact = 'High' )] Param( - [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')][switch]$Default, - [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')][switch]$NoFlightRoots, + [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')][System.Management.Automation.SwitchParameter]$Default, + [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')][System.Management.Automation.SwitchParameter]$NoFlightRoots, [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')] [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')] - [switch]$PrepMode, + [System.Management.Automation.SwitchParameter]$PrepMode, [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')] [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')] - [switch]$AuditAndEnforce, + [System.Management.Automation.SwitchParameter]$AuditAndEnforce, [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')] [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')] - [Switch]$Deploy, + [System.Management.Automation.SwitchParameter]$Deploy, [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')] [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')] - [switch]$EVSigners, + [System.Management.Automation.SwitchParameter]$EVSigners, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -74,8 +74,8 @@ function New-KernelModeWDACConfig { function Build-PrepModeStrictKernelPolicy { [CmdletBinding()] param ( - [Parameter(Mandatory = $false)][switch]$DefaultWindowsKernel, - [Parameter(Mandatory = $false)][switch]$DefaultWindowsKernelNoFlights + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$DefaultWindowsKernel, + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$DefaultWindowsKernelNoFlights ) begin { diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/New-SupplementalWDACConfig.psm1 index ac2c17105..d2360fd5a 100644 --- a/WDACConfig/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/New-SupplementalWDACConfig.psm1 @@ -9,11 +9,11 @@ function New-SupplementalWDACConfig { Param( # Main parameters for position 0 [Alias('N')] - [Parameter(Mandatory = $false, ParameterSetName = 'Normal')][Switch]$Normal, + [Parameter(Mandatory = $false, ParameterSetName = 'Normal')][System.Management.Automation.SwitchParameter]$Normal, [Alias('W')] - [Parameter(Mandatory = $false, ParameterSetName = 'Folder Path With WildCards')][Switch]$PathWildCards, + [Parameter(Mandatory = $false, ParameterSetName = 'Folder Path With WildCards')][System.Management.Automation.SwitchParameter]$PathWildCards, [Alias('P')] - [parameter(mandatory = $false, ParameterSetName = 'Installed AppXPackages')][switch]$InstalledAppXPackages, + [parameter(mandatory = $false, ParameterSetName = 'Installed AppXPackages')][System.Management.Automation.SwitchParameter]$InstalledAppXPackages, [parameter(Mandatory = $true, ParameterSetName = 'Installed AppXPackages', ValueFromPipelineByPropertyName = $true)] [System.String]$PackageName, @@ -36,17 +36,17 @@ function New-SupplementalWDACConfig { [System.String]$PolicyPath, [parameter(Mandatory = $false)] # Used by the entire Cmdlet - [Switch]$Deploy, + [System.Management.Automation.SwitchParameter]$Deploy, [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] [System.String]$SpecificFileNameLevel, [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] - [Switch]$NoUserPEs, + [System.Management.Automation.SwitchParameter]$NoUserPEs, [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] - [Switch]$NoScript, + [System.Management.Automation.SwitchParameter]$NoScript, [ValidateSet([Levelz])] [parameter(Mandatory = $false, ParameterSetName = 'Normal')] @@ -56,7 +56,7 @@ function New-SupplementalWDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Normal')] [System.String[]]$Fallbacks = 'Hash', # Setting the default value for the Fallbacks parameter - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -83,7 +83,7 @@ function New-SupplementalWDACConfig { if (-NOT $SkipVersionCheck) { . Update-self } # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/New-WDACConfig.psm1 index 79e7085a6..02e4f2da0 100644 --- a/WDACConfig/New-WDACConfig.psm1 +++ b/WDACConfig/New-WDACConfig.psm1 @@ -8,15 +8,15 @@ function New-WDACConfig { )] Param( # 9 Main parameters - should be used for position 0 - [Parameter(Mandatory = $false, ParameterSetName = 'Get Block Rules')][Switch]$GetBlockRules, - [Parameter(Mandatory = $false, ParameterSetName = 'Get Driver Block Rules')][Switch]$GetDriverBlockRules, - [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')][Switch]$MakeAllowMSFTWithBlockRules, - [Parameter(Mandatory = $false, ParameterSetName = 'Set Auto Update Driver Block Rules')][Switch]$SetAutoUpdateDriverBlockRules, - [Parameter(Mandatory = $false, ParameterSetName = 'Prep MSFT Only Audit')][Switch]$PrepMSFTOnlyAudit, - [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')][Switch]$PrepDefaultWindowsAudit, - [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')][Switch]$MakePolicyFromAuditLogs, - [Parameter(Mandatory = $false, ParameterSetName = 'Make Light Policy')][Switch]$MakeLightPolicy, - [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')][Switch]$MakeDefaultWindowsWithBlockRules, + [Parameter(Mandatory = $false, ParameterSetName = 'Get Block Rules')][System.Management.Automation.SwitchParameter]$GetBlockRules, + [Parameter(Mandatory = $false, ParameterSetName = 'Get Driver Block Rules')][System.Management.Automation.SwitchParameter]$GetDriverBlockRules, + [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')][System.Management.Automation.SwitchParameter]$MakeAllowMSFTWithBlockRules, + [Parameter(Mandatory = $false, ParameterSetName = 'Set Auto Update Driver Block Rules')][System.Management.Automation.SwitchParameter]$SetAutoUpdateDriverBlockRules, + [Parameter(Mandatory = $false, ParameterSetName = 'Prep MSFT Only Audit')][System.Management.Automation.SwitchParameter]$PrepMSFTOnlyAudit, + [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')][System.Management.Automation.SwitchParameter]$PrepDefaultWindowsAudit, + [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')][System.Management.Automation.SwitchParameter]$MakePolicyFromAuditLogs, + [Parameter(Mandatory = $false, ParameterSetName = 'Make Light Policy')][System.Management.Automation.SwitchParameter]$MakeLightPolicy, + [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')][System.Management.Automation.SwitchParameter]$MakeDefaultWindowsWithBlockRules, [ValidateSet('Allow Microsoft Base', 'Default Windows Base')] [Parameter(Mandatory = $true, ParameterSetName = 'Make Policy From Audit Logs')] @@ -30,10 +30,10 @@ function New-WDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')] [Parameter(Mandatory = $false, ParameterSetName = 'Get Block Rules')] [Parameter(Mandatory = $false, ParameterSetName = 'Get Driver Block Rules')] - [Switch]$Deploy, + [System.Management.Automation.SwitchParameter]$Deploy, [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')] - [switch]$IncludeSignTool, + [System.Management.Automation.SwitchParameter]$IncludeSignTool, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Make DefaultWindows With Block Rules')] [System.String]$SignToolPath, @@ -42,26 +42,26 @@ function New-WDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')] [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')] - [Switch]$TestMode, + [System.Management.Automation.SwitchParameter]$TestMode, [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Light Policy')] [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')] - [Switch]$RequireEVSigners, + [System.Management.Automation.SwitchParameter]$RequireEVSigners, [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [System.String]$SpecificFileNameLevel, [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] - [Switch]$NoDeletedFiles, + [System.Management.Automation.SwitchParameter]$NoDeletedFiles, [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] - [Switch]$NoUserPEs, + [System.Management.Automation.SwitchParameter]$NoUserPEs, [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] - [Switch]$NoScript, + [System.Management.Automation.SwitchParameter]$NoScript, [ValidateSet([Levelz])] [parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] @@ -78,7 +78,7 @@ function New-WDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [System.Int64]$LogSize, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -89,10 +89,10 @@ function New-WDACConfig { $ErrorActionPreference = 'Stop' # Fetching Temp Directory - [string]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() + [System.String]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath #region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path diff --git a/WDACConfig/Remove-CommonWDACConfig.psm1 b/WDACConfig/Remove-CommonWDACConfig.psm1 index d3158b34e..cb7f0072a 100644 --- a/WDACConfig/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/Remove-CommonWDACConfig.psm1 @@ -2,14 +2,14 @@ function Remove-CommonWDACConfig { [CmdletBinding()] Param( - [parameter(Mandatory = $false)][switch]$CertCN, - [parameter(Mandatory = $false)][switch]$CertPath, - [parameter(Mandatory = $false)][switch]$SignToolPath, - [parameter(Mandatory = $false)][switch]$UnsignedPolicyPath, - [parameter(Mandatory = $false)][switch]$SignedPolicyPath, - [parameter(Mandatory = $false)][switch]$StrictKernelPolicyGUID, - [parameter(Mandatory = $false)][switch]$StrictKernelNoFlightRootsPolicyGUID, - [parameter(Mandatory = $false, DontShow = $true)][switch]$LastUpdateCheck # DontShow prevents common parameters from being displayed too + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignToolPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$UnsignedPolicyPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck # DontShow prevents common parameters from being displayed too ) begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable @@ -19,7 +19,7 @@ function Remove-CommonWDACConfig { $ErrorActionPreference = 'Stop' # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\")) { diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/Remove-WDACConfig.psm1 index cc65b34c6..0c7ecf625 100644 --- a/WDACConfig/Remove-WDACConfig.psm1 +++ b/WDACConfig/Remove-WDACConfig.psm1 @@ -8,9 +8,9 @@ function Remove-WDACConfig { )] Param( [Alias('S')] - [Parameter(Mandatory = $false, ParameterSetName = 'Signed Base')][Switch]$SignedBase, + [Parameter(Mandatory = $false, ParameterSetName = 'Signed Base')][System.Management.Automation.SwitchParameter]$SignedBase, [Alias('U')] - [Parameter(Mandatory = $false, ParameterSetName = 'Unsigned Or Supplemental')][Switch]$UnsignedOrSupplemental, + [Parameter(Mandatory = $false, ParameterSetName = 'Unsigned Or Supplemental')][System.Management.Automation.SwitchParameter]$UnsignedOrSupplemental, [ValidatePattern('\.xml$')] [ValidateScript({ @@ -111,7 +111,7 @@ function Remove-WDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Signed Base', ValueFromPipelineByPropertyName = $true)] [System.String]$SignToolPath, - [Parameter(Mandatory = $false)][Switch]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -125,7 +125,7 @@ function Remove-WDACConfig { $Debug = $PSBoundParameters.Debug.IsPresent # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath #region User-Configurations-Processing-Validation if ($PSCmdlet.ParameterSetName -eq 'Signed Base') { @@ -193,7 +193,7 @@ function Remove-WDACConfig { # Defines the PolicyNamez class that implements the IValidateSetValuesGenerator interface. This class is responsible for generating a list of valid values for the policy names. Class PolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { # Creates a static hashtable to store a mapping of policy IDs to their respective friendly names. - static [Hashtable] $IDNameMap = @{} + static [System.Collections.Hashtable] $IDNameMap = @{} # Defines a method to get valid policy names from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { @@ -215,7 +215,7 @@ function Remove-WDACConfig { # Defines the PolicyIDz class that also implements the IValidateSetValuesGenerator interface. This class is responsible for generating a list of valid values for the policy IDs. Class PolicyIDz : System.Management.Automation.IValidateSetValuesGenerator { # Creates a static hashtable to store a mapping of policy friendly names to their respective IDs. - static [Hashtable] $NameIDMap = @{} + static [System.Collections.Hashtable] $NameIDMap = @{} # Defines a method to get valid policy IDs from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/Resources2.ps1 index a07912dcf..c58573099 100644 --- a/WDACConfig/Resources2.ps1 +++ b/WDACConfig/Resources2.ps1 @@ -6,16 +6,16 @@ # Defining a custom object to store the signer information class Signer { - [string]$ID - [string]$Name - [string]$CertRoot - [string]$CertPublisher + [System.String]$ID + [System.String]$Name + [System.String]$CertRoot + [System.String]$CertPublisher } # Function that takes an XML file path as input and returns an array of Signer objects function Get-SignerInfo { param( - [Parameter(Mandatory = $true)][string]$XmlFilePath + [Parameter(Mandatory = $true)][System.String]$XmlFilePath ) # Load the XML file and select the Signer nodes @@ -96,7 +96,7 @@ function Get-AuthenticodeSignatureEx { [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] - [String[]]$FilePath # The path of the file(s) to get the signature of + [System.String[]]$FilePath # The path of the file(s) to get the signature of ) begin { # Define the signature of the Crypt32.dll library functions to use @@ -248,7 +248,7 @@ function Get-SignedFileCertificates { param ( # Define two sets of parameters, one for the FilePath and one for the CertObject [Parameter()] - [string]$FilePath, + [System.String]$FilePath, [Parameter(ValueFromPipeline = $true)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$X509Certificate2 ) @@ -285,11 +285,11 @@ function Get-CertificateDetails { [Parameter(ParameterSetName = 'Based on File Path')] [Parameter(ParameterSetName = 'Based on Certificate')] - [switch]$IntermediateOnly, + [System.Management.Automation.SwitchParameter]$IntermediateOnly, [Parameter(ParameterSetName = 'Based on File Path')] [Parameter(ParameterSetName = 'Based on Certificate')] - [switch]$LeafCertificate + [System.Management.Automation.SwitchParameter]$LeafCertificate ) # An array to hold objects @@ -352,7 +352,7 @@ function Get-CertificateDetails { $CertificateUsingAlternativeMethod.Subject -match 'CN=(?.*?),.*' | Out-Null - [string]$TestAgainst = $matches['InitialRegexTest4'] -like '*"*' ? ((Get-AuthenticodeSignature -FilePath $FilePath).SignerCertificate.Subject -split 'CN="(.+?)"')[1] : $matches['InitialRegexTest4'] + [System.String]$TestAgainst = $matches['InitialRegexTest4'] -like '*"*' ? ((Get-AuthenticodeSignature -FilePath $FilePath).SignerCertificate.Subject -split 'CN="(.+?)"')[1] : $matches['InitialRegexTest4'] if ($IntermediateOnly) { @@ -413,11 +413,11 @@ function Get-CertificateDetails { # Make the FilePath parameter mandatory and validate that it is a valid file path [Parameter()] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] - [string]$FilePath, + [System.String]$FilePath, $X509Certificate2, - [switch]$IntermediateOnly, - [switch]$AllCertificates, - [switch]$LeafCertificate + [System.Management.Automation.SwitchParameter]$IntermediateOnly, + [System.Management.Automation.SwitchParameter]$AllCertificates, + [System.Management.Automation.SwitchParameter]$LeafCertificate ) if ($FilePath) { @@ -511,8 +511,8 @@ function Get-CertificateDetails { # a function that takes WDAC XML policy file path and a Signed file path as inputs and compares the output of the Get-SignerInfo and Get-CertificateDetails functions function Compare-SignerAndCertificate { param( - [Parameter(Mandatory = $true)][string]$XmlFilePath, - [Parameter(Mandatory = $true)] [string]$SignedFilePath + [Parameter(Mandatory = $true)][System.String]$XmlFilePath, + [Parameter(Mandatory = $true)] [System.String]$SignedFilePath ) # Get the signer information from the XML file path using the Get-SignerInfo function diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/Set-CommonWDACConfig.psm1 index b1cb5748e..587685e1f 100644 --- a/WDACConfig/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/Set-CommonWDACConfig.psm1 @@ -60,7 +60,7 @@ function Set-CommonWDACConfig { $ErrorActionPreference = 'Stop' # Fetch User account directory path - [string]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath + [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\")) { From 4f3e5fdc98db4f0fe4989a0529cc89adb33b9451 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 2 Dec 2023 01:04:55 -0930 Subject: [PATCH 018/178] Added VS code workspace for easy debugging --- WDACConfig/Utilities/Invoke-WDACConfig.ps1 | 10 ++++++ .../ArgumentCompleters.ps1 | 0 .../Confirm-WDACConfig.psm1 | 0 .../Deploy-SignedWDACConfig.psm1 | 0 .../Edit-SignedWDACConfig.psm1 | 0 .../Edit-WDACConfig.psm1 | 0 .../Get-CommonWDACConfig.psm1 | 0 .../Invoke-WDACSimulation.psm1 | 0 .../New-DenyWDACConfig.psm1 | 0 .../New-KernelModeWDACConfig.psm1 | 0 .../New-SupplementalWDACConfig.psm1 | 0 .../New-WDACConfig.psm1 | 0 .../Remove-CommonWDACConfig.psm1 | 0 .../Remove-WDACConfig.psm1 | 0 .../Resources.ps1 | 0 .../Resources2.ps1 | 0 .../Set-CommonWDACConfig.psm1 | 0 .../DefaultWindows_Enforced_Kernel.xml | 0 ...faultWindows_Enforced_Kernel_NoFlights.xml | 0 .../WDACConfig.psd1 | 0 WDACConfig/WDACConfig.code-workspace | 31 +++++++++++++++++++ 21 files changed, 41 insertions(+) create mode 100644 WDACConfig/Utilities/Invoke-WDACConfig.ps1 rename WDACConfig/{ => WDACConfig Module Files}/ArgumentCompleters.ps1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Confirm-WDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Deploy-SignedWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Edit-SignedWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Edit-WDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Get-CommonWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Invoke-WDACSimulation.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/New-DenyWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/New-KernelModeWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/New-SupplementalWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/New-WDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Remove-CommonWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Remove-WDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Resources.ps1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Resources2.ps1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/Set-CommonWDACConfig.psm1 (100%) rename WDACConfig/{ => WDACConfig Module Files}/WDAC Policies/DefaultWindows_Enforced_Kernel.xml (100%) rename WDACConfig/{ => WDACConfig Module Files}/WDAC Policies/DefaultWindows_Enforced_Kernel_NoFlights.xml (100%) rename WDACConfig/{ => WDACConfig Module Files}/WDACConfig.psd1 (100%) create mode 100644 WDACConfig/WDACConfig.code-workspace diff --git a/WDACConfig/Utilities/Invoke-WDACConfig.ps1 b/WDACConfig/Utilities/Invoke-WDACConfig.ps1 new file mode 100644 index 000000000..dc752b9b0 --- /dev/null +++ b/WDACConfig/Utilities/Invoke-WDACConfig.ps1 @@ -0,0 +1,10 @@ +# This file is for launching WDACConfig module in VS Code so that it can attach its debugger to the process + +# Get the current folder of this script file +[System.String]$ScriptFilePath = ($MyInvocation.MyCommand.path | Split-Path -Parent) + +# Import the module into the current scope using the relative path of the module itself +Import-Module -FullyQualifiedName "$ScriptFilePath\..\WDACConfig Module Files\WDACConfig.psd1" + +# Uncomment and replace with any cmdlet of the WDACConfig module that is going to be debugged +# Confirm-WDACConfig diff --git a/WDACConfig/ArgumentCompleters.ps1 b/WDACConfig/WDACConfig Module Files/ArgumentCompleters.ps1 similarity index 100% rename from WDACConfig/ArgumentCompleters.ps1 rename to WDACConfig/WDACConfig Module Files/ArgumentCompleters.ps1 diff --git a/WDACConfig/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Confirm-WDACConfig.psm1 similarity index 100% rename from WDACConfig/Confirm-WDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Confirm-WDACConfig.psm1 diff --git a/WDACConfig/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 similarity index 100% rename from WDACConfig/Deploy-SignedWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 diff --git a/WDACConfig/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 similarity index 100% rename from WDACConfig/Edit-SignedWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 diff --git a/WDACConfig/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Edit-WDACConfig.psm1 similarity index 100% rename from WDACConfig/Edit-WDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Edit-WDACConfig.psm1 diff --git a/WDACConfig/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Get-CommonWDACConfig.psm1 similarity index 100% rename from WDACConfig/Get-CommonWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Get-CommonWDACConfig.psm1 diff --git a/WDACConfig/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Invoke-WDACSimulation.psm1 similarity index 100% rename from WDACConfig/Invoke-WDACSimulation.psm1 rename to WDACConfig/WDACConfig Module Files/Invoke-WDACSimulation.psm1 diff --git a/WDACConfig/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-DenyWDACConfig.psm1 similarity index 100% rename from WDACConfig/New-DenyWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/New-DenyWDACConfig.psm1 diff --git a/WDACConfig/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-KernelModeWDACConfig.psm1 similarity index 100% rename from WDACConfig/New-KernelModeWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/New-KernelModeWDACConfig.psm1 diff --git a/WDACConfig/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-SupplementalWDACConfig.psm1 similarity index 100% rename from WDACConfig/New-SupplementalWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/New-SupplementalWDACConfig.psm1 diff --git a/WDACConfig/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 similarity index 100% rename from WDACConfig/New-WDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 diff --git a/WDACConfig/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Remove-CommonWDACConfig.psm1 similarity index 100% rename from WDACConfig/Remove-CommonWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Remove-CommonWDACConfig.psm1 diff --git a/WDACConfig/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 similarity index 100% rename from WDACConfig/Remove-WDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 diff --git a/WDACConfig/Resources.ps1 b/WDACConfig/WDACConfig Module Files/Resources.ps1 similarity index 100% rename from WDACConfig/Resources.ps1 rename to WDACConfig/WDACConfig Module Files/Resources.ps1 diff --git a/WDACConfig/Resources2.ps1 b/WDACConfig/WDACConfig Module Files/Resources2.ps1 similarity index 100% rename from WDACConfig/Resources2.ps1 rename to WDACConfig/WDACConfig Module Files/Resources2.ps1 diff --git a/WDACConfig/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 similarity index 100% rename from WDACConfig/Set-CommonWDACConfig.psm1 rename to WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 diff --git a/WDACConfig/WDAC Policies/DefaultWindows_Enforced_Kernel.xml b/WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel.xml similarity index 100% rename from WDACConfig/WDAC Policies/DefaultWindows_Enforced_Kernel.xml rename to WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel.xml diff --git a/WDACConfig/WDAC Policies/DefaultWindows_Enforced_Kernel_NoFlights.xml b/WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel_NoFlights.xml similarity index 100% rename from WDACConfig/WDAC Policies/DefaultWindows_Enforced_Kernel_NoFlights.xml rename to WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel_NoFlights.xml diff --git a/WDACConfig/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 similarity index 100% rename from WDACConfig/WDACConfig.psd1 rename to WDACConfig/WDACConfig Module Files/WDACConfig.psd1 diff --git a/WDACConfig/WDACConfig.code-workspace b/WDACConfig/WDACConfig.code-workspace new file mode 100644 index 000000000..eb9780719 --- /dev/null +++ b/WDACConfig/WDACConfig.code-workspace @@ -0,0 +1,31 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": { + "powershell.codeFormatting.autoCorrectAliases": true, + "powershell.codeFormatting.avoidSemicolonsAsLineTerminators": true, + "powershell.codeFormatting.trimWhitespaceAroundPipe": true, + "powershell.codeFormatting.useConstantStrings": true, + "powershell.codeFormatting.useCorrectCasing": true, + "powershell.codeFormatting.whitespaceBetweenParameters": true + }, + "extensions": { + "recommendations": [ + "ms-vscode.powershell" + ] + }, + "launch": { + "version": "0.2.0", + "configurations": [ + { + "name": "Debug", + "request": "launch", + "type": "PowerShell", + "script": "${workspaceFolder}/Utilities/Invoke-WDACConfig.ps1" + } + ] + } +} \ No newline at end of file From 067c17cb41e4a095de0940b120f46870ab46f705 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 2 Dec 2023 22:52:14 -0930 Subject: [PATCH 019/178] best practice improvements to Confirm-WDACConfig --- .../Confirm-WDACConfig.psm1 | 55 +++++++++---------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Confirm-WDACConfig.psm1 index 5ff84f1f3..f7806a367 100644 --- a/WDACConfig/WDACConfig Module Files/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Confirm-WDACConfig.psm1 @@ -8,37 +8,36 @@ function Confirm-WDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Verify WDAC Status')][System.Management.Automation.SwitchParameter]$VerifyWDACStatus, [Alias('S')] [Parameter(Mandatory = $false, ParameterSetName = 'Check SmartAppControl Status')][System.Management.Automation.SwitchParameter]$CheckSmartAppControlStatus, - + [Parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$DummyParameter # To hide common parameters ) - + DynamicParam { # Add the dynamic parameters to the param dictionary $ParamDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new() if ($PSBoundParameters['ListActivePolicies']) { - + # Create a dynamic parameter for -OnlyBasePolicies $OnlyBasePoliciesDynamicParameter = [System.Management.Automation.ParameterAttribute]@{ Mandatory = $false - ParameterSetName = 'List Active Policies' + ParameterSetName = 'List Active Policies' HelpMessage = 'Only List Base Policies' - } + } $ParamDictionary.Add('OnlyBasePolicies', [System.Management.Automation.RuntimeDefinedParameter]::new( 'OnlyBasePolicies', [System.Management.Automation.SwitchParameter], [System.Management.Automation.ParameterAttribute[]]@($OnlyBasePoliciesDynamicParameter) - )) - + )) # Create a dynamic parameter for -OnlySupplementalPolicies $OnlySupplementalPoliciesDynamicParameter = [System.Management.Automation.ParameterAttribute]@{ Mandatory = $false ParameterSetName = 'List Active Policies' HelpMessage = 'Only List Supplemental Policies' - } + } $ParamDictionary.Add('OnlySupplementalPolicies', [System.Management.Automation.RuntimeDefinedParameter]::new( 'OnlySupplementalPolicies', @@ -51,16 +50,16 @@ function Confirm-WDACConfig { $SkipVersionCheckDynamicParameter = [System.Management.Automation.ParameterAttribute]@{ Mandatory = $false # To make this parameter available for all parameter sets - ParameterSetName = '__AllParameterSets' + ParameterSetName = '__AllParameterSets' HelpMessage = 'Skip Version Check' - } - + } + $ParamDictionary.Add('SkipVersionCheck', [System.Management.Automation.RuntimeDefinedParameter]::new( 'SkipVersionCheck', [System.Management.Automation.SwitchParameter], [System.Management.Automation.ParameterAttribute[]]@($SkipVersionCheckDynamicParameter) - )) - + )) + return $ParamDictionary } @@ -68,32 +67,30 @@ function Confirm-WDACConfig { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources.ps1" - # Regular parameters are automatically bound to variables in the function scope - # Dynamic parameters however, are only available in the parameter dictionary, which is why we have to access them using $PSBoundParameters + # Dynamic parameters however, are only available in the parameter dictionary, which is why we have to access them using $PSBoundParameters # or assign them manually to another variable in the function's scope - $OnlyBasePolicies = $($PSBoundParameters['OnlyBasePolicies']) - $OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) - $SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) - + [System.Management.Automation.SwitchParameter]$OnlyBasePolicies = $($PSBoundParameters['OnlyBasePolicies']) + [System.Management.Automation.SwitchParameter]$OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) + [System.Management.Automation.SwitchParameter]$SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise - $ErrorActionPreference = 'Stop' + $ErrorActionPreference = 'Stop' if (-NOT $SkipVersionCheck) { . Update-self } # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { - $BasePolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID } + [System.Object[]]$BasePolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID } &$WriteLavender "`nThere are currently $(($BasePolicies.count)) Non-system Base policies deployed" $BasePolicies } # Script block to show only non-system Supplemental policies [System.Management.Automation.ScriptBlock]$OnlySupplementalPoliciesBLOCK = { - $SupplementalPolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -ne $_.BasePolicyID } + [System.Object[]]$SupplementalPolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -ne $_.BasePolicyID } &$WriteLavender "`nThere are currently $(($SupplementalPolicies.count)) Non-system Supplemental policies deployed`n" $SupplementalPolicies - } - + } + # If no main parameter was passed, run all of them if (!$ListActivePolicies -and !$VerifyWDACStatus -and !$CheckSmartAppControlStatus) { $ListActivePolicies = $true @@ -105,10 +102,10 @@ function Confirm-WDACConfig { process { if ($ListActivePolicies) { if ($OnlyBasePolicies) { &$OnlyBasePoliciesBLOCK } - if ($OnlySupplementalPolicies) { &$OnlySupplementalPoliciesBLOCK } + if ($OnlySupplementalPolicies) { &$OnlySupplementalPoliciesBLOCK } if (!$OnlyBasePolicies -and !$OnlySupplementalPolicies) { &$OnlyBasePoliciesBLOCK; &$OnlySupplementalPoliciesBLOCK } } - + if ($VerifyWDACStatus) { Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard | Select-Object -Property *codeintegrity* | Format-List &$WriteLavender "2 -> Enforced`n1 -> Audit mode`n0 -> Disabled/Not running`n" @@ -125,9 +122,9 @@ function Confirm-WDACConfig { elseif ((Get-MpComputerStatus).SmartAppControlState -eq 'Off') { &$WritePink "`nSmart App Control is turned off." } - } + } } - + <# .SYNOPSIS Show the status of WDAC on the system and lists the current deployed policies and shows details about each of them @@ -165,7 +162,7 @@ Confirm-WDACConfig -ListActivePolicies -OnlySupplementalPolicies .EXAMPLE Confirm-WDACConfig -ListActivePolicies -#> +#> } # Set PSReadline tab completion to complete menu for easier access to available parameters - Only for the current session From f0050efb522763400c19b2e31000252b299d69c5 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 2 Dec 2023 23:14:14 -0930 Subject: [PATCH 020/178] Improved best practices for Argument completers --- .../ArgumentCompleters.ps1 | 120 +++++++++--------- 1 file changed, 60 insertions(+), 60 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/ArgumentCompleters.ps1 b/WDACConfig/WDACConfig Module Files/ArgumentCompleters.ps1 index 784c1970e..6eac2c1ff 100644 --- a/WDACConfig/WDACConfig Module Files/ArgumentCompleters.ps1 +++ b/WDACConfig/WDACConfig Module Files/ArgumentCompleters.ps1 @@ -2,33 +2,33 @@ # argument tab auto-completion for CertPath param to show only .cer files in current directory and 2 sub-directories recursively [System.Management.Automation.ScriptBlock]$ArgumentCompleterCertPath = { # Note the use of -Depth 1 - # Enclosing the $results = ... assignment in (...) also passes the value through. - ($results = Get-ChildItem -Depth 2 -Filter *.cer | ForEach-Object -Process { "`"$_`"" }) - if (-not $results) { + # Enclosing the $Results = ... assignment in (...) also passes the value through. + ($Results = Get-ChildItem -Depth 2 -Filter *.cer | ForEach-Object -Process { "`"$_`"" }) + if (-not $Results) { # No results? $null # Dummy response that prevents fallback to the default file-name completion. - } + } } #> -# argument tab auto-completion for Policy Paths to show only .xml files and only suggest files that haven't been already selected by user +# argument tab auto-completion for Policy Paths to show only .xml files and only suggest files that haven't been already selected by user # https://stackoverflow.com/questions/76141864/how-to-make-a-powershell-argument-completer-that-only-suggests-files-not-already/76142865 [System.Management.Automation.ScriptBlock]$ArgumentCompleterPolicyPaths = { # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Find all string constants in the AST that end in ".xml" - $existing = $commandAst.FindAll({ - $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and - $args[0].Value -like '*.xml' - }, + $Existing = $commandAst.FindAll({ + $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and + $args[0].Value -like '*.xml' + }, $false - ).Value + ).Value # Get the xml files in the current directory Get-ChildItem -File -Filter *.xml | ForEach-Object -Process { # Check if the file is already selected - if ($_.FullName -notin $existing) { + if ($_.FullName -notin $Existing) { # Return the file name with quotes "`"$_`"" } @@ -36,11 +36,11 @@ } # argument tab auto-completion for Certificate common name -[System.Management.Automation.ScriptBlock]$ArgumentCompleterCertificateCN = { - $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { - (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } - $certs | ForEach-Object -Process { return "`"$_`"" } +[System.Management.Automation.ScriptBlock]$ArgumentCompleterCertificateCN = { + [System.String[]]$Certificates = foreach ($Cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { + (($Cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() + } + $Certificates | ForEach-Object -Process { return "`"$_`"" } } # Argument tab auto-completion for installed Appx package names @@ -53,29 +53,29 @@ } } -# argument tab auto-completion for Base Policy Paths to show only .xml files and only suggest files that haven't been already selected by user +# argument tab auto-completion for Base Policy Paths to show only .xml files and only suggest files that haven't been already selected by user [System.Management.Automation.ScriptBlock]$ArgumentCompleterPolicyPathsBasePoliciesOnly = { # Get the current command and the already bound parameters param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Find all string constants in the AST that end in ".xml" - $existing = $commandAst.FindAll({ - $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and - $args[0].Value -like '*.xml' - }, + $Existing = $commandAst.FindAll({ + $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and + $args[0].Value -like '*.xml' + }, $false - ).Value + ).Value # Get the xml files in the current directory Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { - $xmlitem = [System.Xml.XmlDocument](Get-Content -Path $_) - $PolicyType = $xmlitem.SiPolicy.PolicyType + $XMLItem = [System.Xml.XmlDocument](Get-Content -Path $_) + $PolicyType = $XMLItem.SiPolicy.PolicyType if ($PolicyType -eq 'Base Policy') { # Check if the file is already selected - if ($_.FullName -notin $existing) { + if ($_.FullName -notin $Existing) { # Return the file name with quotes "`"$_`"" } @@ -89,23 +89,23 @@ param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Find all string constants in the AST that end in ".xml" - $existing = $commandAst.FindAll({ - $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and - $args[0].Value -like '*.xml' - }, + $Existing = $commandAst.FindAll({ + $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and + $args[0].Value -like '*.xml' + }, $false - ).Value + ).Value # Get the xml files in the current directory Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { - $xmlitem = [System.Xml.XmlDocument](Get-Content -Path $_) - $PolicyType = $xmlitem.SiPolicy.PolicyType + $XMLItem = [System.Xml.XmlDocument](Get-Content -Path $_) + $PolicyType = $XMLItem.SiPolicy.PolicyType if ($PolicyType -eq 'Supplemental Policy') { # Check if the file is already selected - if ($_.FullName -notin $existing) { + if ($_.FullName -notin $Existing) { # Return the file name with quotes "`"$_`"" } @@ -116,59 +116,59 @@ # Opens Folder picker GUI so that user can select folders to be processed [System.Management.Automation.ScriptBlock]$ArgumentCompleterFolderPathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName System.Windows.Forms + Add-Type -AssemblyName 'System.Windows.Forms' # non-top-most, works better with window focus - $browser = New-Object System.Windows.Forms.FolderBrowserDialog - $null = $browser.ShowDialog() + [System.Windows.Forms.FolderBrowserDialog]$Browser = New-Object -TypeName 'System.Windows.Forms.FolderBrowserDialog' + $null = $Browser.ShowDialog() # Add quotes around the selected path - return "`"$($browser.SelectedPath)`"" + return "`"$($Browser.SelectedPath)`"" } # Opens File picker GUI so that user can select an .exe file - for SignTool.exe [System.Management.Automation.ScriptBlock]$ArgumentCompleterExeFilePathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName System.Windows.Forms + Add-Type -AssemblyName 'System.Windows.Forms' # Create a new OpenFileDialog object - $dialog = New-Object System.Windows.Forms.OpenFileDialog + [System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog' # Set the filter to show only executable files - $dialog.Filter = 'Executable files (*.exe)|*.exe' + $Dialog.Filter = 'Executable files (*.exe)|*.exe' # Show the dialog and get the result - $result = $dialog.ShowDialog() + [System.String]$Result = $Dialog.ShowDialog() # If the user clicked OK, return the selected file path - if ($result -eq 'OK') { - return "`"$($dialog.FileName)`"" + if ($Result -eq 'OK') { + return "`"$($Dialog.FileName)`"" } } # Opens File picker GUI so that user can select a .cer file [System.Management.Automation.ScriptBlock]$ArgumentCompleterCerFilePathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName System.Windows.Forms + Add-Type -AssemblyName 'System.Windows.Forms' # Create a new OpenFileDialog object - $dialog = New-Object System.Windows.Forms.OpenFileDialog + [System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog' # Set the filter to show only certificate files - $dialog.Filter = 'Certificate files (*.cer)|*.cer' + $Dialog.Filter = 'Certificate files (*.cer)|*.cer' # Show the dialog and get the result - $result = $dialog.ShowDialog() + [System.String]$Result = $Dialog.ShowDialog() # If the user clicked OK, return the selected file path - if ($result -eq 'OK') { - return "`"$($dialog.FileName)`"" + if ($Result -eq 'OK') { + return "`"$($Dialog.FileName)`"" } } # Opens File picker GUI so that user can select a .xml file [System.Management.Automation.ScriptBlock]$ArgumentCompleterXmlFilePathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName System.Windows.Forms + Add-Type -AssemblyName 'System.Windows.Forms' # Create a new OpenFileDialog object - $dialog = New-Object System.Windows.Forms.OpenFileDialog + [System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog' # Set the filter to show only XML files - $dialog.Filter = 'XML files (*.xml)|*.xml' + $Dialog.Filter = 'XML files (*.xml)|*.xml' # Show the dialog and get the result - $result = $dialog.ShowDialog() + [System.String]$Result = $Dialog.ShowDialog() # If the user clicked OK, return the selected file path - if ($result -eq 'OK') { - return "`"$($dialog.FileName)`"" + if ($Result -eq 'OK') { + return "`"$($Dialog.FileName)`"" } } @@ -176,10 +176,10 @@ # WildCard file paths [System.Management.Automation.ScriptBlock]$ArgumentCompleterFolderPathsPickerWildCards = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName System.Windows.Forms + Add-Type -AssemblyName 'System.Windows.Forms' # non-top-most, works better with window focus - $browser = New-Object System.Windows.Forms.FolderBrowserDialog - $null = $browser.ShowDialog() - # Add quotes around the selected path - return "`"$($browser.SelectedPath)\*`"" + [System.Windows.Forms.FolderBrowserDialog]$Browser = New-Object -TypeName 'System.Windows.Forms.FolderBrowserDialog' + $null = $Browser.ShowDialog() + # Add quotes around the selected path and a wildcard character at the end + return "`"$($Browser.SelectedPath)\*`"" } \ No newline at end of file From adf4628474d6342b5c9efd96915e62dcd03555c3 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 3 Dec 2023 00:45:30 -0930 Subject: [PATCH 021/178] Improved the variable types and functions --- .../Deploy-SignedWDACConfig.psm1 | 84 +++++++++---------- .../Edit-SignedWDACConfig.psm1 | 6 +- .../New-WDACConfig.psm1 | 2 +- .../Remove-WDACConfig.psm1 | 10 +-- .../WDACConfig Module Files/Resources.ps1 | 18 +++- .../Set-CommonWDACConfig.psm1 | 4 +- 6 files changed, 67 insertions(+), 57 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 index 23d669db7..886f1a70d 100644 --- a/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 @@ -11,31 +11,31 @@ function Deploy-SignedWDACConfig { [parameter(Mandatory = $true)][System.String[]]$PolicyPaths, [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$Deploy, - + [ValidatePattern('\.cer$')] [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [parameter(Mandatory = $false)][System.String]$CertPath, [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { - (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() + [System.String[]]$Certificates = foreach ($Cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { + (($Cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } - $certs -contains $_ + $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)][System.String]$CertCN, [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [System.String]$SignToolPath, - + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources.ps1" - + # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise - $ErrorActionPreference = 'Stop' + $ErrorActionPreference = 'Stop' if (-NOT $SkipVersionCheck) { . Update-self } # Detecting if Debug switch is used, will do debugging actions based on that @@ -48,15 +48,15 @@ function Deploy-SignedWDACConfig { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertPath -or !$CertCN) { # Read User configuration file if it exists - $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue + $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue if ($UserConfig) { # Validate the Json file and read its content to make sure it's not corrupted try { $UserConfig = $UserConfig | ConvertFrom-Json } - catch { + catch { Write-Error 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig - } + Set-CommonWDACConfig -DeleteUserConfig + } } } @@ -66,16 +66,16 @@ function Deploy-SignedWDACConfig { } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) - } - + } + # If CertPath parameter wasn't provided by user if (!$CertPath) { if ($UserConfig.CertificatePath) { - # validate user config values for Certificate Path + # validate user config values for Certificate Path if (Test-Path -Path $($UserConfig.CertificatePath)) { # If the user config values are correct then use them $CertPath = $UserConfig.CertificatePath - } + } else { throw 'The currently saved value for CertPath in user configurations is invalid.' } @@ -84,12 +84,12 @@ function Deploy-SignedWDACConfig { throw "CertPath parameter can't be empty and no valid configuration was found for it." } } - + # If CertCN was not provided by user if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN $($UserConfig.CertificateCommonName)) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } @@ -101,12 +101,12 @@ function Deploy-SignedWDACConfig { throw "CertCN parameter can't be empty and no valid configuration was found for it." } } - #endregion User-Configurations-Processing-Validation + #endregion User-Configurations-Processing-Validation } - process { - foreach ($PolicyPath in $PolicyPaths) { - + process { + foreach ($PolicyPath in $PolicyPaths) { + # Gather policy details $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyType = $xml.SiPolicy.PolicyType @@ -116,11 +116,11 @@ function Deploy-SignedWDACConfig { # Remove the .CIP file of the same policy being signed and deployed if any in the current working directory Remove-Item -Path ".\$PolicyID.cip" -ErrorAction SilentlyContinue - + # Ensure -Supplemental is not used when the policy type is supplemental if ($PolicyType -eq 'Supplemental Policy') { # Make sure -User is not added if the UMCI policy rule option doesn't exist in the policy, typically for Strict kernel mode policies - if ('Enabled:UMCI' -in $PolicyRuleOptions) { + if ('Enabled:UMCI' -in $PolicyRuleOptions) { Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -User -Kernel } else { @@ -129,7 +129,7 @@ function Deploy-SignedWDACConfig { } else { # Make sure -User is not added if the UMCI policy rule option doesn't exist in the policy, typically for Strict kernel mode policies - if ('Enabled:UMCI' -in $PolicyRuleOptions) { + if ('Enabled:UMCI' -in $PolicyRuleOptions) { Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -User -Kernel -Supplemental } else { @@ -138,28 +138,28 @@ function Deploy-SignedWDACConfig { } Set-HVCIOptions -Strict -FilePath $PolicyPath Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath "$PolicyID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$PolicyID.cip" - 'FilePath' = $SignToolPathFinal + 'FilePath' = $SignToolPathFinal 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' } # Hide the SignTool.exe's normal output unless -Debug parameter was used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item -Path ".\$PolicyID.cip" -Force + Remove-Item -Path ".\$PolicyID.cip" -Force Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force if ($Deploy) { CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green + Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" Remove-Item -Path ".\$PolicyID.cip" -Force @@ -169,47 +169,47 @@ function Deploy-SignedWDACConfig { [System.String]$StrictKernelPolicyGUID = Get-CommonWDACConfig -StrictKernelPolicyGUID [System.String]$StrictKernelNoFlightRootsPolicyGUID = Get-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID - + if (($PolicyName -like '*Strict Kernel mode policy Enforced*')) { - if ($StrictKernelPolicyGUID) { + if ($StrictKernelPolicyGUID) { if ($($PolicyID.TrimStart('{').TrimEnd('}')) -eq $StrictKernelPolicyGUID) { Remove-CommonWDACConfig -StrictKernelPolicyGUID | Out-Null - } + } } } - + elseif (($PolicyName -like '*Strict Kernel No Flights mode policy Enforced*')) { - if ($StrictKernelNoFlightRootsPolicyGUID) { + if ($StrictKernelNoFlightRootsPolicyGUID) { if ($($PolicyID.TrimStart('{').TrimEnd('}')) -eq $StrictKernelNoFlightRootsPolicyGUID) { Remove-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID | Out-Null - } + } } } } #endregion Detecting Strict Kernel mode policy and removing it from User Configs - + # Show the question only for base policies. Don't show it for Strict kernel mode policies if (($PolicyType -ne 'Supplemental Policy') -and ($PolicyName -notlike '*Strict Kernel*')) { # Ask user question about whether or not to add the Signed policy xml file to the User Config Json for easier usage later $userInput = '' while ($userInput -notin 1, 2) { - $userInput = $(Write-Host -Object 'Add the Signed policy xml file path just created to the User Configurations? Please enter 1 to Confirm or 2 to Skip.' -ForegroundColor Cyan ; Read-Host) + $userInput = $(Write-Host -Object 'Add the Signed policy xml file path just created to the User Configurations? Please enter 1 to Confirm or 2 to Skip.' -ForegroundColor Cyan ; Read-Host) if ($userInput -eq 1) { Set-CommonWDACConfig -SignedPolicyPath $PolicyPath - &$WriteHotPink "Added $PolicyPath to the User Configuration file." + &$WriteHotPink "Added $PolicyPath to the User Configuration file." } - elseif ($userInput -eq 2) { - &$WritePink 'Skipping...' + elseif ($userInput -eq 2) { + &$WritePink 'Skipping...' } else { Write-Warning 'Invalid input. Please enter 1 or 2 only.' - } + } } } } - else { + else { Write-Host -Object "`npolicy with the following details has been Signed and is ready for deployment:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" diff --git a/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 index 1e6b79228..23ecae412 100644 --- a/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 @@ -71,10 +71,10 @@ function Edit-SignedWDACConfig { [System.String[]]$PolicyPaths, [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { + [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } - $certs -contains $_ + $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet [System.String]$CertCN, @@ -177,7 +177,7 @@ function Edit-SignedWDACConfig { if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN $($UserConfig.CertificateCommonName)) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } diff --git a/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 index 02e4f2da0..4721b8fd0 100644 --- a/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 @@ -177,7 +177,7 @@ function New-WDACConfig { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option 8 } Set-HVCIOptions -Strict -FilePath .\AllowMicrosoftPlusBlockRules.xml - ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules. -BinaryFilePath "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null # Remove the extra files that were created during module operation and are no longer needed Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force [PSCustomObject]@{ diff --git a/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 index 0c7ecf625..dcf7ac41c 100644 --- a/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 @@ -26,10 +26,10 @@ function Remove-WDACConfig { [System.String[]]$PolicyPaths, [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { - (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } - $certs -contains $_ + [System.String[]]$Certificates = foreach ($Cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { + (($Cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() + } + $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [parameter(Mandatory = $false, ParameterSetName = 'Signed Base', ValueFromPipelineByPropertyName = $true)] [System.String]$CertCN, @@ -156,7 +156,7 @@ function Remove-WDACConfig { if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN $($UserConfig.CertificateCommonName)) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } diff --git a/WDACConfig/WDACConfig Module Files/Resources.ps1 b/WDACConfig/WDACConfig Module Files/Resources.ps1 index ac2c83c03..31b27d464 100644 --- a/WDACConfig/WDACConfig Module Files/Resources.ps1 +++ b/WDACConfig/WDACConfig Module Files/Resources.ps1 @@ -385,12 +385,22 @@ $RuleRefsContent } -# Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json -function Confirm-CertCN ([System.String]$CN) { - $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { +function Confirm-CertCN { + <# + .SYNOPSIS + Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json + .INPUTS + System.String + .OUTPUTS + System.Boolean + #> + param ( + [System.String]$CN + ) + [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } - $certs -contains $CN ? $true : $false + return [System.Boolean]($Certificates -contains $CN ? $true : $false) } diff --git a/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 index 587685e1f..81ba317d1 100644 --- a/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 @@ -3,10 +3,10 @@ function Set-CommonWDACConfig { [CmdletBinding()] Param( [ValidateScript({ - $certs = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { + [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } - $certs -contains $_ + $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [parameter(Mandatory = $false)][System.String]$CertCN, From 2d60879e05024bedf4bc6cf897c48c4c3ac543c2 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 3 Dec 2023 00:51:18 -0930 Subject: [PATCH 022/178] Removed unnecessary trailing white space --- .../Deploy-SignedWDACConfig.psm1 | 2 +- .../Edit-SignedWDACConfig.psm1 | 390 +++++++++--------- .../Edit-WDACConfig.psm1 | 336 +++++++-------- .../Get-CommonWDACConfig.psm1 | 22 +- .../Invoke-WDACSimulation.psm1 | 82 ++-- .../New-DenyWDACConfig.psm1 | 120 +++--- .../New-KernelModeWDACConfig.psm1 | 114 ++--- .../New-SupplementalWDACConfig.psm1 | 118 +++--- .../New-WDACConfig.psm1 | 208 +++++----- .../Remove-CommonWDACConfig.psm1 | 24 +- .../Remove-WDACConfig.psm1 | 44 +- .../Set-CommonWDACConfig.psm1 | 42 +- .../DefaultWindows_Enforced_Kernel.xml | 6 +- ...faultWindows_Enforced_Kernel_NoFlights.xml | 6 +- .../WDACConfig Module Files/WDACConfig.psd1 | 2 +- 15 files changed, 758 insertions(+), 758 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 index 886f1a70d..2ade4d755 100644 --- a/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Deploy-SignedWDACConfig.psm1 @@ -19,7 +19,7 @@ function Deploy-SignedWDACConfig { [ValidateScript({ [System.String[]]$Certificates = foreach ($Cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($Cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } + } $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)][System.String]$CertCN, diff --git a/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 index 23ecae412..8fea11b78 100644 --- a/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Edit-SignedWDACConfig.psm1 @@ -12,14 +12,14 @@ function Edit-SignedWDACConfig { [Alias('A')] [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')][System.Management.Automation.SwitchParameter]$AllowNewApps, [Alias('M')] - [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')][System.Management.Automation.SwitchParameter]$MergeSupplementalPolicies, + [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies')][System.Management.Automation.SwitchParameter]$MergeSupplementalPolicies, [Alias('U')] [Parameter(Mandatory = $false, ParameterSetName = 'Update Base Policy')][System.Management.Automation.SwitchParameter]$UpdateBasePolicy, [ValidatePattern('^[a-zA-Z0-9 ]+$', ErrorMessage = 'The Supplemental Policy Name can only contain alphanumeric and space characters.')] [Parameter(Mandatory = $true, ParameterSetName = 'Allow New Apps Audit Events', ValueFromPipelineByPropertyName = $true)] [Parameter(Mandatory = $true, ParameterSetName = 'Allow New Apps', ValueFromPipelineByPropertyName = $true)] - [Parameter(Mandatory = $true, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] + [Parameter(Mandatory = $true, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] [System.String]$SuppPolicyName, [ValidatePattern('\.xml$')] @@ -40,14 +40,14 @@ function Edit-SignedWDACConfig { [ValidatePattern('\.cer$')] # Used by the entire Cmdlet [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] - [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] - [System.String]$CertPath, + [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] + [System.String]$CertPath, [ValidatePattern('\.xml$')] [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit an Unsigned policy using Edit-SignedWDACConfig cmdlet which is only made for Signed policies - $_ | ForEach-Object -Process { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId @@ -55,25 +55,25 @@ function Edit-SignedWDACConfig { $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if ($RedFlag1 -or $RedFlag2) { # Ensure the selected base policy xml file is deployed - if ($CurrentPolicyIDs -contains $RedFlag3) { + if ($CurrentPolicyIDs -contains $RedFlag3) { return $True } else { throw "The currently selected policy xml file isn't deployed." } } # This throw is shown only when User added a Signed policy xml file for Unsigned policy file path property in user configuration file # Without this, the error shown would be vague: The variable cannot be validated because the value System.String[] is not a valid value for the PolicyPaths variable. - else { throw 'The policy xml file in User Configurations for SignedPolicyPath is Unsigned policy.' } + else { throw 'The policy xml file in User Configurations for SignedPolicyPath is Unsigned policy.' } } }, ErrorMessage = 'The selected policy xml file is Unsigned. Please use Edit-WDACConfig cmdlet to edit Unsigned policies.')] [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events', ValueFromPipelineByPropertyName = $true)] [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps', ValueFromPipelineByPropertyName = $true)] - [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] + [Parameter(Mandatory = $false, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] [System.String[]]$PolicyPaths, [ValidateScript({ [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } + } $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet @@ -90,7 +90,7 @@ function Edit-SignedWDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] [System.Management.Automation.SwitchParameter]$NoUserPEs, - + [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] @@ -107,7 +107,7 @@ function Edit-SignedWDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] [System.String[]]$Fallbacks = 'Hash', # Setting the default value for the Fallbacks parameter - + [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet [System.String]$SignToolPath, @@ -123,8 +123,8 @@ function Edit-SignedWDACConfig { . "$psscriptroot\Resources.ps1" # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise - $ErrorActionPreference = 'Stop' - if (-NOT $SkipVersionCheck) { . Update-self } + $ErrorActionPreference = 'Stop' + if (-NOT $SkipVersionCheck) { . Update-self } # Fetching Temp Directory [System.String]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() @@ -136,34 +136,34 @@ function Edit-SignedWDACConfig { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPaths -or !$SignToolPath -or !$CertPath -or !$CertCN) { # Read User configuration file if it exists - $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue + $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue if ($UserConfig) { # Validate the Json file and read its content to make sure it's not corrupted try { $UserConfig = $UserConfig | ConvertFrom-Json } - catch { + catch { Write-Error 'User Configurations Json file is corrupted, deleting it...' -ErrorAction Continue # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig - } + Set-CommonWDACConfig -DeleteUserConfig + } } } - + # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) - } - + } + # If CertPath parameter wasn't provided by user if (!$CertPath) { if ($UserConfig.CertificatePath) { - # validate user config values for Certificate Path + # validate user config values for Certificate Path if (Test-Path -Path $($UserConfig.CertificatePath)) { # If the user config values are correct then use them $CertPath = $UserConfig.CertificatePath - } + } else { throw 'The currently saved value for CertPath in user configurations is invalid.' } @@ -172,7 +172,7 @@ function Edit-SignedWDACConfig { throw "CertPath parameter can't be empty and no valid configuration was found for it." } } - + # If CertCN was not provided by user if (!$CertCN) { if ($UserConfig.CertificateCommonName) { @@ -188,7 +188,7 @@ function Edit-SignedWDACConfig { else { throw "CertCN parameter can't be empty and no valid configuration was found for it." } - } + } # If PolicyPaths has no values if (!$PolicyPaths) { @@ -201,7 +201,7 @@ function Edit-SignedWDACConfig { } else { throw 'The currently saved value for SignedPolicyPath in user configurations is invalid.' - } + } } else { throw "PolicyPaths parameter can't be empty and no valid configuration was found for SignedPolicyPath." @@ -213,10 +213,10 @@ function Edit-SignedWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $Debug = $PSBoundParameters.Debug.IsPresent - # argument tab auto-completion and ValidateSet for Policy names + # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname + $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname return [System.String[]]$BasePolicyNamez } } @@ -224,7 +224,7 @@ function Edit-SignedWDACConfig { # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Fallbackz } } @@ -232,16 +232,16 @@ function Edit-SignedWDACConfig { # argument tab auto-completion and ValidateSet for level Class Levelz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Levelz } } - + #Re-Deploy Basepolicy in Enforced mode function Update-BasePolicyToEnforced { - # Deploy Enforced mode CIP - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:" + # Deploy Enforced mode CIP + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP @@ -251,9 +251,9 @@ function Edit-SignedWDACConfig { } process { - + if ($AllowNewAppsAuditEvents) { - + # Change Code Integrity event logs size if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize } # Make sure there is no leftover from previous runs @@ -270,15 +270,15 @@ function Edit-SignedWDACConfig { foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder - Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force + Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string - + # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue @@ -286,12 +286,12 @@ function Edit-SignedWDACConfig { Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null - + # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null - + # Sign both CIPs '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { # Configure the parameter splat @@ -302,31 +302,31 @@ function Edit-SignedWDACConfig { 'Wait' = $true 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams # After creating signed .p7 files for each CIP, remove the old Unsigned ones Remove-Item -Path $_ -Force - } + } Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' - + $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force "@ $command | Out-File 'C:\EnforcedModeSnapBack.ps1' New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - + # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP @@ -334,13 +334,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force - # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode - Try { + # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode + Try { ################################### User Interaction #################################### &$WritePink "`nAudit mode deployed, start installing your programs now" &$WriteHotPink "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" Pause - + # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() Write-Host -Object "`nSelect program directories to scan" -ForegroundColor Cyan @@ -356,46 +356,46 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Else { break } } while ($true) - + # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths - if ($ProgramsPaths.count -eq 0) { + if ($ProgramsPaths.count -eq 0) { Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } - + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } ################################### EventCapturing ################################ - Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan + Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date - + # Only create policy for files that are available on the disk based on Event viewer logs but weren't in user-selected program path(s), if there are any if ($AuditEventLogsProcessingResults.AvailableFilesPaths) { # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those # this prevents duplicate rule creation and double file copying $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique - + Write-Debug -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." # Another check to make sure there were indeed files found in Event viewer logs but weren't in any of the user-selected path(s) if ($TestFilePathResults) { # Create a folder in Temp directory to copy the files that are not included in user-selected program path(s) - # but detected in Event viewer audit logs, scan that folder, and in the end delete it + # but detected in Event viewer audit logs, scan that folder, and in the end delete it New-Item -Path "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null - - Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" + + Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" $TestFilePathResults | ForEach-Object -Process { - Write-Debug -Message "$_" + Write-Debug -Message "$_" Copy-Item -Path $_ -Destination "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue } - + # Create a policy XML file for available files on the disk # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -406,23 +406,23 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Fallback = $Fallbacks MultiplePolicyFormat = $true UserWriteablePaths = $true - AllowFileNameFallbacks = $true + AllowFileNameFallbacks = $true } - # Assess user input parameters and add the required parameters to the hash table + # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $AvailableFilesOnDiskPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } if ($NoScript) { $AvailableFilesOnDiskPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $AvailableFilesOnDiskPolicyMakerHashTable['UserPEs'] = $true } - + if (!$NoUserPEs) { $AvailableFilesOnDiskPolicyMakerHashTable['UserPEs'] = $true } + # Create the supplemental policy via parameter splatting New-CIPolicy @AvailableFilesOnDiskPolicyMakerHashTable - + # Add the policy XML file to the array that holds policy XML files $PolicyXMLFilesArray += '.\RulesForFilesNotInUserSelectedPaths.xml' # Delete the Temporary folder in the TEMP folder Remove-Item -Recurse -Path "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force } } - + # Only create policy for files that are on longer available on the disk if there are any and # if user chose to include deleted files in the final supplemental policy if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { @@ -432,16 +432,16 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Debug -Message "$($_.'File Name')" } - # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File FileRulesAndFileRefs.txt - # Put the Rules and RulesRefs in an empty policy file + # Put the Rules and RulesRefs in an empty policy file New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File .\DeletedFileHashesEventsPolicy.xml # adding the policy file that consists of rules from audit even logs, to the array $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } - + ######################## Process Program Folders From User input ##################### for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -455,22 +455,22 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item UserWriteablePaths = $true AllowFileNameFallbacks = $true } - # Assess user input parameters and add the required parameters to the hash table + # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } + if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable - } + } # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } - - #region Kernel-protected-files-automatic-detection-and-allow-rule-creation + + #region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them @@ -489,11 +489,11 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Testing each executable to find the protected ones Get-FileHash -Path $CurrentExeWithNoHash -ErrorAction Stop | Out-Null } - # Making sure only the right file is captured by narrowing down the error type. - # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException - catch [System.UnauthorizedAccessException] { + # Making sure only the right file is captured by narrowing down the error type. + # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException + catch [System.UnauthorizedAccessException] { $ExesWithNoHash += $CurrentExeWithNoHash - } + } } } } @@ -502,7 +502,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } - + [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() @@ -521,7 +521,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($ExesWithNoHash -contains $_.'File Name') { $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } - } + } } } } @@ -529,14 +529,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Only proceed further if any hashes belonging to the detected kernel protected files were found in Event viewer # If none is found then skip this part, because user didn't run those files/programs when audit mode was turned on in base policy, so no hash was found in audit logs - if ($KernelProtectedHashesBlockResults) { - - # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes + if ($KernelProtectedHashesBlockResults) { + + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File KernelProtectedFiles.txt - # Put the Rules and RulesRefs in an empty policy file + # Put the Rules and RulesRefs in an empty policy file New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File .\KernelProtectedFiles.xml - + # adding the policy file to the array of xml files $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' } @@ -544,7 +544,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on.`n" $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } - } + } #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' @@ -552,17 +552,17 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null - + # Delete these extra files unless user uses -Debug parameter if (-NOT $Debug) { - Remove-Item -Path '.\FileRulesAndFileRefs.txt', '.\DeletedFileHashesEventsPolicy.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\FileRulesAndFileRefs.txt', '.\DeletedFileHashesEventsPolicy.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\ProgramDir_ScanResults*.xml', '.\RulesForFilesNotInUserSelectedPaths.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\KernelProtectedFiles.txt', '.\KernelProtectedFiles.xml' -Force -ErrorAction SilentlyContinue } } # Unlike AllowNewApps parameter, AllowNewAppsAuditEvents parameter performs Event viewer scanning and kernel protected files detection # So the base policy enforced mode snap back can't happen any sooner than this point - catch { + catch { $_ $_.CategoryInfo $_.ErrorDetails @@ -574,31 +574,31 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $_.ScriptStackTrace $_.TargetObject } - finally { + finally { # Deploy Enforced mode CIP Write-Debug -Message 'Finally Block Running' Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - } + Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force + Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + } #################### Supplemental-policy-processing-and-deployment ############################ - - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath $SuppPolicyPath - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + + Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" @@ -607,43 +607,43 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Wait' = $true 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - - Remove-Item -Path ".\$SuppPolicyID.cip" -Force + + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item -Path ".\$SuppPolicyID.cip" -Force Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier - } + } } if ($AllowNewApps) { - + # remove any possible files from previous runs Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() - + #Initiate Live Audit Mode - - foreach ($PolicyPath in $PolicyPaths) { + + foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder - Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force + Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string - + # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue @@ -656,7 +656,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null - + # Sign both CIPs '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { # Configure the parameter splat @@ -667,31 +667,31 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Wait' = $true 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams # After creating signed .p7 files for each CIP, remove the old Unsigned ones Remove-Item -Path $_ -Force - } + } Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' - + $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force "@ $command | Out-File 'C:\EnforcedModeSnapBack.ps1' New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - + # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP @@ -699,13 +699,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force - # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode + # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - ################################### User Interaction #################################### + ################################### User Interaction #################################### &$WritePink "`nAudit mode deployed, start installing your programs now" &$WriteHotPink "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" Pause - + # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() Write-Host -Object "`nSelect program directories to scan`n" -ForegroundColor Cyan @@ -721,17 +721,17 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Else { break } } while ($true) - + # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths - if ($ProgramsPaths.count -eq 0) { + if ($ProgramsPaths.count -eq 0) { Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } } catch { - # Show any extra info about any possible error that might've occurred + # Show any extra info about any possible error that might've occurred $_ $_.CategoryInfo $_.ErrorDetails @@ -743,20 +743,20 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $_.ScriptStackTrace $_.TargetObject } - finally { + finally { # Deploy Enforced mode CIP Write-Debug -Message 'Finally Block Running' - Update-BasePolicyToEnforced + Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force + Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - + Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } - - #Process Program Folders From User input + + #Process Program Folders From User input # Scan each of the folder paths that user selected for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -773,42 +773,42 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } + if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable - } - + } + # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } - + # Merge all of the policy XML files in the array into the final Supplemental policy - Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null - + Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null + Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force #################### Supplemental-policy-processing-and-deployment ############################ - - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel - + # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath $SuppPolicyPath - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - - ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + + Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" @@ -817,29 +817,29 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Wait' = $true 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - - Remove-Item -Path ".\$SuppPolicyID.cip" -Force + + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" + &$WriteTeaGreen "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier - } + Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + } } - if ($MergeSupplementalPolicies) { + if ($MergeSupplementalPolicies) { foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ - foreach ($SuppPolicyPath in $SuppPolicyPaths) { + foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies if ($SupplementalPolicyType -ne 'Supplemental Policy') { Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." @@ -852,21 +852,21 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Perform the merge Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them - foreach ($SuppPolicyPath in $SuppPolicyPaths) { + foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) - $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID Citool --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them - if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } - } - # Prepare the final merged Supplemental policy for deployment + if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } + } + # Prepare the final merged Supplemental policy for deployment $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath - $SuppPolicyID = $SuppPolicyID.Substring(11) + $SuppPolicyID = $SuppPolicyID.Substring(11) Add-SignerRule -FilePath "$SuppPolicyName.xml" -CertificatePath $CertPath -Update -User -Kernel Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" Set-RuleOption -FilePath "$SuppPolicyName.xml" -Option 6 -Delete ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" @@ -875,43 +875,43 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Wait' = $true 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - - Remove-Item -Path ".\$SuppPolicyID.cip" -Force + + Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force - } + } } if ($UpdateBasePolicy) { # First get the Microsoft recommended driver block rules Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null - + switch ($NewBasePolicyType) { - 'AllowMicrosoft_Plus_Block_Rules' { + 'AllowMicrosoft_Plus_Block_Rules' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } - 'Lightly_Managed_system_Policy' { + 'Lightly_Managed_system_Policy' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } # Configure required services for ISG authorization Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow } - 'DefaultWindows_WithBlockRules' { + 'DefaultWindows_WithBlockRules' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' - + # Allowing SignTool to be able to run after Default Windows base policy is deployed &$WriteTeaGreen "`nCreating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy." New-Item -Path "$global:UserTempDirectoryPath\TemporarySignToolFile" -ItemType Directory -Force | Out-Null @@ -919,28 +919,28 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-CIPolicy -ScanPath "$global:UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml # Delete the Temporary folder in the TEMP folder if (!$Debug) { Remove-Item -Recurse -Path "$global:UserTempDirectoryPath\TemporarySignToolFile" -Force } - + # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed - if (Test-Path -Path 'C:\Program Files\PowerShell') { + if (Test-Path -Path 'C:\Program Files\PowerShell') { &$WriteHotPink "`nCreating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it." - New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml + New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } else { Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null - } + } Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } } - - if ($UpdateBasePolicy -and $RequireEVSigners) { Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 } - + + if ($UpdateBasePolicy -and $RequireEVSigners) { Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 } + # Remove the extra files create during module operation that are no longer necessary if (!$Debug) { Remove-Item -Path '.\AllowPowerShell.xml', '.\SignTool.xml', '.\AllowMicrosoft.xml', '.\DefaultWindows_Enforced.xml' -Force -ErrorAction SilentlyContinue - Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force + Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force } # Get the policy ID of the currently deployed base policy based on the policy name that user selected @@ -948,7 +948,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $CurrentID = "{$CurrentID}" Remove-Item -Path ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue - [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' + [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') @@ -958,7 +958,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-CIPolicyVersion -FilePath .\BasePolicy.xml -Version '1.0.0.1' Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml - ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null # Configure the parameter splat $ProcessParams = @{ @@ -968,12 +968,12 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'Wait' = $true 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - Remove-Item -Path ".\$CurrentID.cip" -Force - Rename-Item -Path "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force + Remove-Item -Path ".\$CurrentID.cip" -Force + Rename-Item -Path "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force # Deploy the new base policy with the same GUID on the system CiTool --update-policy "$CurrentID.cip" -json | Out-Null # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later @@ -988,7 +988,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item &$WritePink "Base Policy has been successfully updated to $NewBasePolicyType" &$WriteLavender 'Keep in mind that your previous policy path saved in User Configurations is no longer valid as you just changed your Base policy.' } - } + } <# .SYNOPSIS diff --git a/WDACConfig/WDACConfig Module Files/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Edit-WDACConfig.psm1 index 9b5c43fa3..dbd0de555 100644 --- a/WDACConfig/WDACConfig Module Files/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Edit-WDACConfig.psm1 @@ -21,12 +21,12 @@ function Edit-WDACConfig { [Parameter(Mandatory = $true, ParameterSetName = 'Allow New Apps', ValueFromPipelineByPropertyName = $true)] [Parameter(Mandatory = $true, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] [System.String]$SuppPolicyName, - + [ValidatePattern('\.xml$')] [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit a Signed policy using Edit-WDACConfig cmdlet which is only made for Unsigned policies - $_ | ForEach-Object -Process { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId @@ -35,13 +35,13 @@ function Edit-WDACConfig { if (!$RedFlag1 -and !$RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { - return $True + return $True } else { throw "The currently selected policy xml file isn't deployed." } } # This throw is shown only when User added a Signed policy xml file for Unsigned policy file path property in user configuration file # Without this, the error shown would be vague: The variable cannot be validated because the value System.String[] is not a valid value for the PolicyPaths variable. - else { throw 'The policy xml file in User Configurations for UnsignedPolicyPath is a Signed policy.' } + else { throw 'The policy xml file in User Configurations for UnsignedPolicyPath is a Signed policy.' } } }, ErrorMessage = 'The selected policy xml file is Signed. Please use Edit-SignedWDACConfig cmdlet to edit Signed policies.')] [Parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events', ValueFromPipelineByPropertyName = $true)] @@ -50,7 +50,7 @@ function Edit-WDACConfig { [System.String[]]$PolicyPaths, [ValidatePattern('\.xml$')] - [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] [Parameter(Mandatory = $true, ParameterSetName = 'Merge Supplemental Policies', ValueFromPipelineByPropertyName = $true)] [System.String[]]$SuppPolicyPaths, @@ -74,7 +74,7 @@ function Edit-WDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] [System.Management.Automation.SwitchParameter]$NoUserPEs, - + [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps Audit Events')] [parameter(Mandatory = $false, ParameterSetName = 'Allow New Apps')] @@ -103,8 +103,8 @@ function Edit-WDACConfig { . "$psscriptroot\Resources.ps1" # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise - $ErrorActionPreference = 'Stop' - if (-NOT $SkipVersionCheck) { . Update-self } + $ErrorActionPreference = 'Stop' + if (-NOT $SkipVersionCheck) { . Update-self } # Fetching Temp Directory [System.String]$global:UserTempDirectoryPath = [System.IO.Path]::GetTempPath() @@ -116,24 +116,24 @@ function Edit-WDACConfig { $Debug = $PSBoundParameters.Debug.IsPresent #region User-Configurations-Processing-Validation - # make sure the ParameterSet being used has PolicyPaths parameter - Then enforces "mandatory" attribute for the parameter + # make sure the ParameterSet being used has PolicyPaths parameter - Then enforces "mandatory" attribute for the parameter if ($PSCmdlet.ParameterSetName -in 'Allow New Apps Audit Events', 'Allow New Apps', 'Merge Supplemental Policies') { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPaths) { # Read User configuration file if it exists - $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue + $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue if ($UserConfig) { # Validate the Json file and read its content to make sure it's not corrupted try { $UserConfig = $UserConfig | ConvertFrom-Json } - catch { + catch { Write-Error 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig - } + Set-CommonWDACConfig -DeleteUserConfig + } } } # If PolicyPaths has no values - if (!$PolicyPaths) { + if (!$PolicyPaths) { if ($UserConfig.UnsignedPolicyPath) { # validate each policyPath read from user config file if (Test-Path -Path $($UserConfig.UnsignedPolicyPath)) { @@ -141,20 +141,20 @@ function Edit-WDACConfig { } else { throw 'The currently saved value for UnsignedPolicyPath in user configurations is invalid.' - } + } } else { throw "PolicyPaths parameter can't be empty and no valid configuration was found for UnsignedPolicyPath." } } - } + } #endregion User-Configurations-Processing-Validation - # argument tab auto-completion and ValidateSet for Policy names + # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname - + return [System.String[]]$BasePolicyNamez } } @@ -162,7 +162,7 @@ function Edit-WDACConfig { # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Fallbackz } } @@ -170,70 +170,70 @@ function Edit-WDACConfig { # argument tab auto-completion and ValidateSet for level Class Levelz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Levelz } } # Redeploy the base policy in Enforced mode function Update-BasePolicyToEnforced { - # Deploy Enforced mode CIP - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" + # Deploy Enforced mode CIP + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item -Path ".\$PolicyID.cip" -Force - } + } $DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock } - process { + process { if ($AllowNewApps) { # remove any possible files from previous runs Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue - Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue + Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() - + #Initiate Live Audit Mode - foreach ($PolicyPath in $PolicyPaths) { + foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder - Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force + Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string - + # Remove any cip file if there is any Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue # Create CIP for Audit Mode Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null - + # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' <# - # CMD and Scheduled Task Method + # CMD and Scheduled Task Method $taskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c c:\EnforcedModeSnapBack.cmd' $taskTrigger = New-ScheduledTaskTrigger -AtLogOn $principal = New-ScheduledTaskPrincipal -GroupId 'BUILTIN\Administrators' -RunLevel Highest $TaskSettings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8 -DontStopIfGoingOnBatteries -Priority 0 -AllowStartIfOnBatteries Register-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Action $taskAction -Trigger $taskTrigger -Principal $principal -Settings $TaskSettings -Force | Out-Null - + Set-Content -Force "c:\EnforcedModeSnapBack.cmd" -Value @" REM Deploying the Enforced Mode SnapBack CI Policy CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json @@ -243,32 +243,32 @@ REM Deleting the CI Policy file del /f /q "$((Get-Location).Path)\$PolicyID.cip" REM Deleting this CMD file itself del "%~f0" -"@ +"@ #> # PowerShell and RunOnce Method - + $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force "@ $command | Out-File 'C:\EnforcedModeSnapBack.ps1' New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - + # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item -Path ".\$PolicyID.cip" -Force # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force - - # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode + Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + + # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - ################################### User Interaction #################################### + ################################### User Interaction #################################### &$WritePink "`nAudit mode deployed, start installing your programs now" &$WriteHotPink "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" Pause @@ -291,14 +291,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths - if ($ProgramsPaths.count -eq 0) { + if ($ProgramsPaths.count -eq 0) { Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } } catch { - # Show any extra info about any possible error that might've occurred + # Show any extra info about any possible error that might've occurred $_ $_.CategoryInfo $_.ErrorDetails @@ -310,28 +310,28 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $_.ScriptStackTrace $_.TargetObject } - finally { + finally { # Deploy Enforced mode CIP Write-Debug -Message 'Finally Block Running' - Update-BasePolicyToEnforced - + Update-BasePolicyToEnforced + # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - + # For PowerShell Method - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force + Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - + # For CMD Method # Unregister-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Confirm:$false - # Remove-Item -Path 'c:\EnforcedModeSnapBack.cmd' -Force + # Remove-Item -Path 'c:\EnforcedModeSnapBack.cmd' -Force } - + Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } - - #Process Program Folders From User input - + + #Process Program Folders From User input + # Scan each of the folder paths that user selected for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -345,48 +345,48 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item UserWriteablePaths = $true AllowFileNameFallbacks = $true } - # Assess user input parameters and add the required parameters to the hash table + # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } + if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable - } - + } + # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } - + Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } - + # Merge all of the policy XML files in the array into the final Supplemental policy - Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null - + Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null + Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - + #################### Supplemental-policy-processing-and-deployment ############################ - - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath - $SuppPolicyID = $SuppPolicyID.Substring(11) - + $SuppPolicyID = $SuppPolicyID.Substring(11) + # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath $SuppPolicyPath - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } } @@ -403,33 +403,33 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item [System.Object[]]$PolicyXMLFilesArray = @() ################################### Initiate Live Audit Mode ################################### - - foreach ($PolicyPath in $PolicyPaths) { + + foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder - Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force + Remove-Item -Path "$global:UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Copy-Item -Path $PolicyPath -Destination $global:UserTempDirectoryPath -Force $PolicyPath = "$global:UserTempDirectoryPath\$PolicyFileName" - + # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any - Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue # Create CIP for Audit Mode Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null - + # Create CIP for Enforced Mode Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - + ################# Snap back guarantee ################# Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' - + $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force @@ -440,8 +440,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null - &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &$WriteTeaGreen "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP @@ -449,12 +449,12 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force - # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode + # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { ################################### User Interaction #################################### &$WritePink "`nAudit mode deployed, start installing your programs now" &$WriteHotPink "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" - Pause + Pause # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() @@ -471,21 +471,21 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Else { break } } while ($true) - + # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths - if ($ProgramsPaths.count -eq 0) { + if ($ProgramsPaths.count -eq 0) { Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } - + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } ################################### EventCapturing ################################ - Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan + Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date @@ -496,21 +496,21 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those # this prevents duplicate rule creation and double file copying $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique - + Write-Debug -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." # Another check to make sure there were indeed files found in Event viewer logs but weren't in any of the user-selected path(s) if ($TestFilePathResults) { # Create a folder in Temp directory to copy the files that are not included in user-selected program path(s) - # but detected in Event viewer audit logs, scan that folder, and in the end delete it + # but detected in Event viewer audit logs, scan that folder, and in the end delete it New-Item -Path "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null - - Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" + + Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" $TestFilePathResults | ForEach-Object -Process { - Write-Debug -Message "$_" + Write-Debug -Message "$_" Copy-Item -Path $_ -Destination "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue } - + # Create a policy XML file for available files on the disk # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -520,24 +520,24 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Level = $Level Fallback = $Fallbacks MultiplePolicyFormat = $true - UserWriteablePaths = $true - AllowFileNameFallbacks = $true + UserWriteablePaths = $true + AllowFileNameFallbacks = $true } - # Assess user input parameters and add the required parameters to the hash table + # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $AvailableFilesOnDiskPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } if ($NoScript) { $AvailableFilesOnDiskPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $AvailableFilesOnDiskPolicyMakerHashTable['UserPEs'] = $true } - + if (!$NoUserPEs) { $AvailableFilesOnDiskPolicyMakerHashTable['UserPEs'] = $true } + # Create the supplemental policy via parameter splatting New-CIPolicy @AvailableFilesOnDiskPolicyMakerHashTable - + # Add the policy XML file to the array that holds policy XML files $PolicyXMLFilesArray += '.\RulesForFilesNotInUserSelectedPaths.xml' # Delete the Temporary folder in the TEMP folder Remove-Item -Recurse -Path "$global:UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force } } - + # Only create policy for files that are on longer available on the disk if there are any and # if user chose to include deleted files in the final supplemental policy if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { @@ -546,17 +546,17 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { Write-Debug -Message "$($_.'File Name')" } - - # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes + + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes ((Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes)).Trim() | Out-File FileRulesAndFileRefs.txt - # Put the Rules and RulesRefs in an empty policy file + # Put the Rules and RulesRefs in an empty policy file New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File .\DeletedFileHashesEventsPolicy.xml - + # adding the policy file that consists of rules from audit even logs, to the array $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } - + ######################## Process Program Folders From User input ##################### for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -570,22 +570,22 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item UserWriteablePaths = $true AllowFileNameFallbacks = $true } - # Assess user input parameters and add the required parameters to the hash table + # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } + if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable - } + } # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } - - #region Kernel-protected-files-automatic-detection-and-allow-rule-creation + + #region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them @@ -604,11 +604,11 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Testing each executable to find the protected ones Get-FileHash -Path $CurrentExeWithNoHash -ErrorAction Stop | Out-Null } - # Making sure only the right file is captured by narrowing down the error type. - # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException - catch [System.UnauthorizedAccessException] { + # Making sure only the right file is captured by narrowing down the error type. + # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException + catch [System.UnauthorizedAccessException] { $ExesWithNoHash += $CurrentExeWithNoHash - } + } } } } @@ -617,7 +617,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } - + [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { $xml = [System.Xml.XmlDocument]$event.toxml() @@ -636,7 +636,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($ExesWithNoHash -contains $_.'File Name') { $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } - } + } } } } @@ -646,10 +646,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # If none is found then skip this part, because user didn't run those files/programs when audit mode was turned on in base policy, so no hash was found in audit logs if ($KernelProtectedHashesBlockResults) { - # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File KernelProtectedFiles.txt - # Put the Rules and RulesRefs in an empty policy file + # Put the Rules and RulesRefs in an empty policy file New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File .\KernelProtectedFiles.xml # adding the policy file to the array of xml files @@ -659,14 +659,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on.`n" $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } - } + } #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } # Merge all of the policy XML files in the array into the final Supplemental policy - Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null + Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null # Delete these extra files unless user uses -Debug parameter if (-NOT $Debug) { @@ -677,7 +677,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Unlike AllowNewApps parameter, AllowNewAppsAuditEvents parameter performs Event viewer scanning and kernel protected files detection # So the base policy enforced mode snap back can't happen any sooner than this point - catch { + catch { $_ $_.CategoryInfo $_.ErrorDetails @@ -689,46 +689,46 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $_.ScriptStackTrace $_.TargetObject } - finally { + finally { # Deploy Enforced mode CIP Write-Debug -Message 'Finally Block Running' - Update-BasePolicyToEnforced + Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force + Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } #################### Supplemental-policy-processing-and-deployment ############################ - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath $SuppPolicyPath - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier } } - if ($MergeSupplementalPolicies) { - foreach ($PolicyPath in $PolicyPaths) { + if ($MergeSupplementalPolicies) { + foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ - foreach ($SuppPolicyPath in $SuppPolicyPaths) { + foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies if ($SupplementalPolicyType -ne 'Supplemental Policy') { Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." @@ -741,68 +741,68 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Perform the merge Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them - foreach ($SuppPolicyPath in $SuppPolicyPaths) { + foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) - $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID Citool --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them - if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } + if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } } - # Prepare the final merged Supplemental policy for deployment + # Prepare the final merged Supplemental policy for deployment $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) - Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" + Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null + CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null &$WriteTeaGreen "`nThe Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force } } - if ($UpdateBasePolicy) { + if ($UpdateBasePolicy) { # First get the Microsoft recommended driver block rules - Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null - + Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null + switch ($NewBasePolicyType) { - 'AllowMicrosoft_Plus_Block_Rules' { + 'AllowMicrosoft_Plus_Block_Rules' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } - 'Lightly_Managed_system_Policy' { + 'Lightly_Managed_system_Policy' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 6, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } # Configure required services for ISG authorization Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow } - 'DefaultWindows_WithBlockRules' { + 'DefaultWindows_WithBlockRules' { Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { - Write-Host -Object 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue + Write-Host -Object 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } else { Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null - } + } Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } } - if ($UpdateBasePolicy -and $RequireEVSigners) { Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 } + if ($UpdateBasePolicy -and $RequireEVSigners) { Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 } Set-CIPolicyVersion -FilePath .\BasePolicy.xml -Version '1.0.0.1' Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml - + # Remove the extra files create during module operation that are no longer necessary Remove-Item -Path '.\AllowPowerShell.xml', '.\DefaultWindows_Enforced.xml', '.\AllowMicrosoft.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force @@ -811,7 +811,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Write-Debug -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" - [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' + [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID $xml.Save('.\BasePolicy.xml') @@ -820,8 +820,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item CiTool --update-policy "$CurrentID.cip" -json | Out-Null # Remove the policy binary after it's been deployed Remove-Item -Path "$CurrentID.cip" -Force - - # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later + + # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later $PolicyFiles = @{ 'AllowMicrosoft_Plus_Block_Rules' = 'AllowMicrosoftPlusBlockRules.xml' 'Lightly_Managed_system_Policy' = 'SignedAndReputable.xml' diff --git a/WDACConfig/WDACConfig Module Files/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Get-CommonWDACConfig.psm1 index 4d3927204..7f6c27285 100644 --- a/WDACConfig/WDACConfig Module Files/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Get-CommonWDACConfig.psm1 @@ -1,21 +1,21 @@ #Requires -RunAsAdministrator function Get-CommonWDACConfig { [CmdletBinding()] - Param( + Param( [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignToolPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$UnsignedPolicyPath, [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, # DontShow prevents common parameters from being displayed too - [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$Open, [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck ) begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources.ps1" - + # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise $ErrorActionPreference = 'Stop' @@ -27,17 +27,17 @@ function Get-CommonWDACConfig { New-Item -ItemType Directory -Path "$global:UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null Write-Debug -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." } - + # Create User configuration file if it doesn't already exist - if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { + if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$global:UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null Write-Debug -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." } - - if ($Open) { + + if ($Open) { . "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" break - } + } if ($PSBoundParameters.Count -eq 0) { # Display this message if User Configuration file is empty @@ -47,7 +47,7 @@ function Get-CommonWDACConfig { # Display this message if User Configuration file has content else { &$WritePink "`nThis is your current WDAC User Configurations: " - Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * + Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * } break } @@ -61,7 +61,7 @@ function Get-CommonWDACConfig { catch { Write-Warning 'The UserConfigurations.json was corrupted, clearing it.' Set-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -Value '' - } + } } process {} @@ -73,7 +73,7 @@ function Get-CommonWDACConfig { $UnsignedPolicyPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.UnsignedPolicyPath } $SignToolPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.SignToolCustomPath } $CertCN.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.CertificateCommonName } - $StrictKernelPolicyGUID.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.StrictKernelPolicyGUID } + $StrictKernelPolicyGUID.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.StrictKernelPolicyGUID } $StrictKernelNoFlightRootsPolicyGUID.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.StrictKernelNoFlightRootsPolicyGUID } $CertPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.CertificatePath } $LastUpdateCheck.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.LastUpdateCheck } diff --git a/WDACConfig/WDACConfig Module Files/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Invoke-WDACSimulation.psm1 index b813c5bff..6866f9661 100644 --- a/WDACConfig/WDACConfig Module Files/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Invoke-WDACSimulation.psm1 @@ -1,11 +1,11 @@ -#Requires -RunAsAdministrator +#Requires -RunAsAdministrator function Invoke-WDACSimulation { [CmdletBinding( PositionalBinding = $false, SupportsShouldProcess = $true )] Param( - [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] + [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] [Parameter(Mandatory = $true)][System.String]$FolderPath, [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] @@ -14,7 +14,7 @@ function Invoke-WDACSimulation { [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck # Used by the entire Cmdlet ) - begin { + begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources2.ps1" @@ -27,12 +27,12 @@ function Invoke-WDACSimulation { $ErrorActionPreference = 'Stop' if (-NOT $SkipVersionCheck) { . Update-self } } - + process { # For Testing purposes # $FolderPath = '' # $XmlFilePath = '' - + if ($FolderPath) { # Store the processed results of the valid Signed files [System.Object[]]$SignedResult = @() @@ -49,15 +49,15 @@ function Invoke-WDACSimulation { # File paths of the Signed files with HashMismatch Status [System.Object[]]$SignedHashMismatchFilePaths = @() - # File paths of the Signed files with a status that doesn't fall into any other category + # File paths of the Signed files with a status that doesn't fall into any other category [System.Object[]]$SignedButUnknownFilePaths = @() # Hash Sha256 values of all the file rules based on hash in the supplied xml policy file [System.Object[]]$SHA256HashesFromXML = (Get-FileRuleOutput -xmlPath $XmlFilePath).hashvalue - + # Get all of the files that WDAC supports from the user provided directory [System.Object[]]$CollectedFiles = (Get-ChildItem -Recurse -Path $FolderPath -File -Include '*.sys', '*.exe', '*.com', '*.dll', '*.ocx', '*.msp', '*.mst', '*.msi', '*.js', '*.vbs', '*.ps1', '*.appx').FullName - + # Loop through each file $CollectedFiles | ForEach-Object -Process { @@ -68,44 +68,44 @@ function Invoke-WDACSimulation { try { $CurrentFilePathHash = (Get-AppLockerFileInformation -Path $CurrentFilePath -ErrorAction Stop).hash -replace 'SHA256 0x', '' } - catch { - Write-Debug -Message "Get-AppLockerFileInformation failed for the file at $CurrentFilePath, using New-CIPolicyRule cmdlet..." - + catch { + Write-Debug -Message "Get-AppLockerFileInformation failed for the file at $CurrentFilePath, using New-CIPolicyRule cmdlet..." + $CurrentHashOutput = New-CIPolicyRule -Level hash -Fallback none -AllowFileNameFallbacks -UserWriteablePaths -DriverFilePath $CurrentFilePath - + $CurrentFilePathHash = ($CurrentHashOutput | Where-Object -FilterScript { $_.name -like '*Hash Sha256*' }).attributes.hash } - + # if the file's hash exists in the XML file if ($CurrentFilePathHash -in $SHA256HashesFromXML) { $AllowedUnsignedFilePaths += $CurrentFilePath } - else { - + else { + switch ((Get-AuthenticodeSignature -FilePath $CurrentFilePath).Status) { # If the file is signed and valid - 'valid' { + 'valid' { # If debug is used show extra info on the console - if ($Debug) { + if ($Debug) { Write-Host -Object "Currently processing signed file: `n$CurrentFilePath" -ForegroundColor Yellow } # Use the function in Resources2.ps1 file to process it $SignedResult += Compare-SignerAndCertificate -XmlFilePath $XmlFilePath -SignedFilePath $CurrentFilePath | Where-Object -FilterScript { ($_.CertRootMatch -eq $true) -and ($_.CertNameMatch -eq $true) -and ($_.CertPublisherMatch -eq $true) } break } - 'HashMismatch' { + 'HashMismatch' { $SignedHashMismatchFilePaths += $CurrentFilePath - break - } + break + } default { $SignedButUnknownFilePaths += $CurrentFilePath; break } - } - } + } + } } - + # File paths of the files allowed by Signer/certificate, Unique - [System.Object[]]$AllowedSignedFilePaths = $SignedResult.FilePath | Get-Unique + [System.Object[]]$AllowedSignedFilePaths = $SignedResult.FilePath | Get-Unique + - if ($AllowedUnsignedFilePaths) { # Loop through the first array and create output objects with the file path and source foreach ($Path in $AllowedUnsignedFilePaths) { @@ -117,8 +117,8 @@ function Invoke-WDACSimulation { } # Convert the hash table to a PSObject and add it to the output array $MegaOutputObject += New-Object -TypeName PSObject -Property $Object - } - } + } + } # For valid Signed files if ($AllowedSignedFilePaths) { @@ -132,7 +132,7 @@ function Invoke-WDACSimulation { } # Convert the hash table to a PSObject and add it to the output array $MegaOutputObject += New-Object -TypeName PSObject -Property $Object - } + } } # For Signed files with mismatch signature status @@ -147,7 +147,7 @@ function Invoke-WDACSimulation { } # Convert the hash table to a PSObject and add it to the output array $MegaOutputObject += New-Object -TypeName PSObject -Property $Object - } + } } # For Signed files with Unknown signature status @@ -162,7 +162,7 @@ function Invoke-WDACSimulation { } # Convert the hash table to a PSObject and add it to the output array $MegaOutputObject += New-Object -TypeName PSObject -Property $Object - } + } } # Unique number of files allowed by hash - used for counting only @@ -189,15 +189,15 @@ function Invoke-WDACSimulation { } # Convert the hash table to a PSObject and add it to the output array $MegaOutputObject += New-Object -TypeName PSObject -Property $Object - } + } } - + # Change the color of the Table header $PSStyle.Formatting.TableHeader = "$($PSStyle.Foreground.FromRGB(255,165,0))" - # Display the final main output array as a table - allowed files + # Display the final main output array as a table - allowed files $MegaOutputObject | Select-Object -Property FilePath, - + @{ Label = 'Source' Expression = @@ -209,24 +209,24 @@ function Invoke-WDACSimulation { "$color$($_.source)$($PSStyle.Reset)" # Use PSStyle to reset the color } }, Permission -Unique | Sort-Object -Property Permission | Format-Table -Property FilePath, Source, Permission - + # Showing Signature based allowed file details &$WriteLavender "`n$($AllowedSignedFilePaths.count) File(s) Inside the Selected Folder Are Allowed by Signatures by Your Policy." - + # Showing Hash based allowed file details &$WriteLavender "$($UniqueFilesAllowedByHash.count) File(s) Inside the Selected Folder Are Allowed by Hashes by Your Policy.`n" - + # Export the output as CSV $MegaOutputObject | Select-Object -Property FilePath, source, Permission -Unique | Sort-Object -Property Permission | Export-Csv -Path .\WDACSimulationOutput.csv -Force if ($Debug) { Write-Host -Object 'Files that were UNSIGNED' -ForegroundColor Blue $AllowedUnsignedFilePaths - } - - } + } + + } } - + <# .SYNOPSIS Simulates the deployment of the WDAC policy diff --git a/WDACConfig/WDACConfig Module Files/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-DenyWDACConfig.psm1 index 3749f74a1..e118cbb65 100644 --- a/WDACConfig/WDACConfig Module Files/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/New-DenyWDACConfig.psm1 @@ -1,6 +1,6 @@ -#Requires -RunAsAdministrator +#Requires -RunAsAdministrator function New-DenyWDACConfig { - [CmdletBinding( + [CmdletBinding( DefaultParameterSetName = 'Drivers', PositionalBinding = $false, SupportsShouldProcess = $true, @@ -19,10 +19,10 @@ function New-DenyWDACConfig { [System.String]$PackageName, [ValidatePattern('^[a-zA-Z0-9 ]+$', ErrorMessage = 'The Supplemental Policy Name can only contain alphanumeric characters and spaces.')] - [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet - [System.String]$PolicyName, - - [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] + [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet + [System.String]$PolicyName, + + [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] [Parameter(Mandatory = $false, ParameterSetName = 'Drivers')] [System.String[]]$ScanLocations, @@ -36,7 +36,7 @@ function New-DenyWDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] [Parameter(Mandatory = $false, ParameterSetName = 'Drivers')] [System.String[]]$Fallbacks = 'Hash', # Setting the default value for the Fallbacks parameter - + [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] [System.String]$SpecificFileNameLevel, @@ -49,11 +49,11 @@ function New-DenyWDACConfig { [Parameter(Mandatory = $false)] # Used by the entire Cmdlet [System.Management.Automation.SwitchParameter]$Deploy, - + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck # Used by the entire Cmdlet ) - begin { + begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources.ps1" @@ -65,25 +65,25 @@ function New-DenyWDACConfig { Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') - + return [System.String[]]$Fallbackz } } - + # argument tab auto-completion and ValidateSet for level Class Levelz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') - + return [System.String[]]$Levelz } } # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise $ErrorActionPreference = 'Stop' - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { . Update-self } } - + process { # Create deny supplemental policy for general files, apps etc. if ($Normal) { @@ -106,69 +106,69 @@ function New-DenyWDACConfig { Deny = $true AllowFileNameFallbacks = $true } - # Assess user input parameters and add the required parameters to the hash table + # Assess user input parameters and add the required parameters to the hash table if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } + if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable - } + } Write-Debug -Message 'The Deny policy with the following configuration is being created' if ($Debug) { $UserInputProgramFoldersPolicyMakerHashTable } - + # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName - + } # Adding the AllowAll default policy path to the array of policy paths $PolicyXMLFilesArray += 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowAll.xml' # creating the final Deny base policy from the xml files in the paths array Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\DenyPolicy $PolicyName.xml" | Out-Null - + [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' - + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ } - + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { - Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" + Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } + + Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ DenyPolicyFile = "DenyPolicy $PolicyName.xml" DenyPolicyGUID = $PolicyID } - + if (!$Debug) { Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force } - - if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + + if ($Deploy) { + CiTool --update-policy "$policyID.cip" -json | Out-Null Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta - Write-Host -Object ' has been deployed.' -ForegroundColor Green + Write-Host -Object ' has been deployed.' -ForegroundColor Green Remove-Item -Path "$policyID.cip" -Force } } # Create Deny base policy for Driver files - elseif ($Drivers) { + elseif ($Drivers) { powershell.exe { [System.Object[]]$DriverFilesObject = @() # loop through each user-selected folder paths foreach ($ScanLocation in $args[0]) { # DriverFile object holds the full details of all of the scanned drivers - This scan is greedy, meaning it stores as much information as it can find - # about each driver file, any available info about digital signature, hash, FileName, Internal Name etc. of each driver is saved and nothing is left out - $DriverFilesObject += Get-SystemDriver -ScanPath $ScanLocation -UserPEs + # about each driver file, any available info about digital signature, hash, FileName, Internal Name etc. of each driver is saved and nothing is left out + $DriverFilesObject += Get-SystemDriver -ScanPath $ScanLocation -UserPEs } [System.Collections.Hashtable]$PolicyMakerHashTable = @{ @@ -182,9 +182,9 @@ function New-DenyWDACConfig { } # Creating a base policy using the DriverFile object and specifying which detail about each driver should be used in the policy file New-CIPolicy @PolicyMakerHashTable - + } -args $ScanLocations, $Level, $Fallbacks - + # Merging AllowAll default policy with our Deny temp policy Merge-CIPolicy -PolicyPaths 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowAll.xml', '.\DenyPolicy Temp.xml' -OutputFilePath ".\DenyPolicy $PolicyName.xml" | Out-Null @@ -192,27 +192,27 @@ function New-DenyWDACConfig { [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' - + @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ } - + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" + + Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - + [PSCustomObject]@{ DenyPolicyFile = "DenyPolicy $PolicyName.xml" DenyPolicyGUID = $PolicyID - } - if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + } + if ($Deploy) { + CiTool --update-policy "$policyID.cip" -json | Out-Null Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta - Write-Host -Object ' has been deployed.' -ForegroundColor Green + Write-Host -Object ' has been deployed.' -ForegroundColor Green Remove-Item -Path "$policyID.cip" -Force - } + } } # Creating Deny rule for Appx Packages @@ -220,21 +220,21 @@ function New-DenyWDACConfig { do { Get-AppxPackage -Name $PackageName Write-Debug -Message "This is the Selected package name $PackageName" - $Question = Read-Host "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit`n" + $Question = Read-Host "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit`n" } until ( (($Question -eq 1) -or ($Question -eq 2)) ) if ($Question -eq 2) { break } - powershell.exe { + powershell.exe { # Get all the packages based on the supplied name - $Package = Get-AppxPackage -Name $args[0] + $Package = Get-AppxPackage -Name $args[0] # Create rules for each package foreach ($item in $Package) { $Rules += New-CIPolicyRule -Deny -Package $item } - + # Generate the supplemental policy xml file New-CIPolicy -MultiplePolicyFormat -FilePath '.\AppxDenyPolicyTemp.xml' -Rules $Rules } -args $PackageName @@ -247,29 +247,29 @@ function New-DenyWDACConfig { [System.String]$policyID = Set-CIPolicyIdInfo -FilePath ".\AppxDenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Version '1.0.0.0' - + @(0, 2, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Option $_ } - + @(3, 4, 8, 9, 10, 13, 14, 15, 18) | ForEach-Object -Process { Set-RuleOption -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Option $_ -Delete } - Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" + Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\AppxDenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - + [PSCustomObject]@{ DenyPolicyFile = ".\AppxDenyPolicy $PolicyName.xml" DenyPolicyGUID = $PolicyID } - - if ($Deploy) { + + if ($Deploy) { CiTool --update-policy "$policyID.cip" -json | Out-Null &$WritePink "A Deny Base policy with the name $PolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force - } + } } - } - + } + <# .SYNOPSIS Creates Deny base policies (Windows Defender Application Control) diff --git a/WDACConfig/WDACConfig Module Files/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-KernelModeWDACConfig.psm1 index d612ccca5..e1a59e04b 100644 --- a/WDACConfig/WDACConfig Module Files/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/New-KernelModeWDACConfig.psm1 @@ -5,7 +5,7 @@ function New-KernelModeWDACConfig { PositionalBinding = $false, ConfirmImpact = 'High' )] - Param( + Param( [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')][System.Management.Automation.SwitchParameter]$Default, [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')][System.Management.Automation.SwitchParameter]$NoFlightRoots, @@ -24,8 +24,8 @@ function New-KernelModeWDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Default Strict Kernel')] [Parameter(Mandatory = $false, ParameterSetName = 'No Flight Roots')] [System.Management.Automation.SwitchParameter]$EVSigners, - - [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck + + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -36,9 +36,9 @@ function New-KernelModeWDACConfig { $ErrorActionPreference = 'Stop' # Detecting if Debug switch is used, will do debugging actions based on that - $Debug = $PSBoundParameters.Debug.IsPresent + $Debug = $PSBoundParameters.Debug.IsPresent - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { . Update-self } # Check if the PrepMode and AuditAndEnforce parameters are used together and ensure one of them is used if (-not ($PSBoundParameters.ContainsKey('PrepMode') -xor $PSBoundParameters.ContainsKey('AuditAndEnforce'))) { @@ -52,7 +52,7 @@ function New-KernelModeWDACConfig { [System.String]$PolicyIDInput, [System.String]$PolicyFilePathInput ) - + [System.String]$PolicyID = "{$PolicyIDInput}" # Read the xml file as an xml object @@ -67,7 +67,7 @@ function New-KernelModeWDACConfig { $xml.SiPolicy.BasePolicyID = $newBasePolicyID # Save the modified xml file - $xml.Save($PolicyFilePathInput) + $xml.Save($PolicyFilePathInput) } # Function to build Audit mode policy only @@ -88,13 +88,13 @@ function New-KernelModeWDACConfig { # Check if there is a pending Audit mode Kernel mode WDAC policy already available in User Config file [System.String]$CurrentStrictKernelPolicyGUID = Get-CommonWDACConfig -StrictKernelPolicyGUID - If ($CurrentStrictKernelPolicyGUID) { + If ($CurrentStrictKernelPolicyGUID) { # Check if the pending Audit mode Kernel mode WDAC policy is deployed on the system [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelPolicyGUID }).policyID } } - if ($DefaultWindowsKernelNoFlights) { + if ($DefaultWindowsKernelNoFlights) { $PolicyPath = "$psscriptroot\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml" $PolicyFileName = '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' $PolicyName = 'Strict Kernel No Flights mode policy Audit' @@ -102,11 +102,11 @@ function New-KernelModeWDACConfig { # Check if there is a pending Audit mode Kernel mode WDAC No Flight Roots policy already available in User Config file [System.String]$CurrentStrictKernelNoFlightRootsPolicyGUID = Get-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID - If ($CurrentStrictKernelNoFlightRootsPolicyGUID) { + If ($CurrentStrictKernelNoFlightRootsPolicyGUID) { # Check if the pending Audit mode Kernel mode WDAC No Flight Roots policy is deployed on the system [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelNoFlightRootsPolicyGUID }).policyID } - } + } } @@ -123,14 +123,14 @@ function New-KernelModeWDACConfig { if ($EVSigners) { Set-RuleOption -FilePath "$PolicyFileName" -Option 8 } # If user chooses to go with no flight root certs then block flight/insider builds in policy rule options if ($DefaultWindowsKernelNoFlights) { Set-RuleOption -FilePath "$PolicyFileName" -Option 4 } - + # Set the already available and deployed GUID as the new PolicyID to prevent deploying duplicate Audit mode policies if ($CurrentStrictKernelPolicyGUIDConfirmation) { Edit-GUIDs -PolicyIDInput $CurrentStrictKernelPolicyGUIDConfirmation -PolicyFilePathInput "$PolicyFileName" $Global:PolicyID = $CurrentStrictKernelPolicyGUIDConfirmation - } - - Set-HVCIOptions -Strict -FilePath "$PolicyFileName" + } + + Set-HVCIOptions -Strict -FilePath "$PolicyFileName" } } } @@ -144,15 +144,15 @@ function New-KernelModeWDACConfig { Build-PrepModeStrictKernelPolicy -DefaultWindowsKernel # Convert the xml to CIP binary ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Enforced_Kernel.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - + # Deploy the policy if Deploy parameter is used and perform additional tasks on the system - if ($Deploy) { - + if ($Deploy) { + # Set the GUID of the Audit mode policy in the User Configuration file Set-CommonWDACConfig -StrictKernelPolicyGUID $PolicyID | Out-Null CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null &$WriteHotPink 'Strict Kernel mode policy has been deployed in Audit mode, please restart your system.' - + # Clear Code Integrity operational before system restart so that after boot it will only have the correct and new logs wevtutil cl 'Microsoft-Windows-CodeIntegrity/Operational' wevtutil cl 'Microsoft-Windows-AppLocker/MSI and Script' @@ -163,13 +163,13 @@ function New-KernelModeWDACConfig { } else { &$WriteHotPink 'Strict Kernel mode Audit policy has been created in the current working directory.' - } + } } if ($AuditAndEnforce) { # Get the Strict Kernel Audit mode policy's GUID to use for the Enforced mode policy - # This will eliminate the need for an extra reboot + # This will eliminate the need for an extra reboot [System.String]$PolicyID = Get-CommonWDACConfig -StrictKernelPolicyGUID # Verify the Policy ID in the User Config exists and is valid $ObjectGuid = [System.Guid]::Empty @@ -179,20 +179,20 @@ function New-KernelModeWDACConfig { else { Write-Error 'Invalid or nonexistent GUID in User Configs for Audit mode policy, Use the -PrepMode parameter first.' } - - powershell.exe { + + powershell.exe { # Scan Event viewer logs for drivers $DriverFilesObj = Get-SystemDriver -Audit # Create a policy xml file from the driver files - New-CIPolicy -MultiplePolicyFormat -Level FilePublisher -Fallback None -FilePath '.\DriverFilesScanPolicy.xml' -DriverFiles $DriverFilesObj - } - - # Build the same policy again after restart, do not trust the policy xml file made before restart + New-CIPolicy -MultiplePolicyFormat -Level FilePublisher -Fallback None -FilePath '.\DriverFilesScanPolicy.xml' -DriverFiles $DriverFilesObj + } + + # Build the same policy again after restart, do not trust the policy xml file made before restart Copy-Item -Path "$psscriptroot\WDAC Policies\DefaultWindows_Enforced_Kernel.xml" -Destination .\DefaultWindows_Enforced_Kernel.xml -Force - + # Merge the base policy with the policy made from driver files to deploy it as one Merge-CIPolicy -PolicyPaths '.\DefaultWindows_Enforced_Kernel.xml', '.\DriverFilesScanPolicy.xml' -OutputFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null - + # Remove the old policy again because we used it in merge and don't need it anymore Remove-Item -Path '.\DefaultWindows_Enforced_Kernel.xml' -Force @@ -210,11 +210,11 @@ function New-KernelModeWDACConfig { @(0, 3, 4, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ -Delete } if ($EVSigners) { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option 8 } - + Set-HVCIOptions -Strict -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' - + # Deploy the policy if Deploy parameter is used - if ($Deploy) { + if ($Deploy) { ConvertFrom-CIPolicy -XmlFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null &$WritePink 'Strict Kernel mode policy has been deployed in Enforced mode, no restart required.' @@ -231,10 +231,10 @@ function New-KernelModeWDACConfig { } if (!$Debug) { Remove-Item -Path ".\$PolicyID.cip", '.\DriverFilesScanPolicy.xml' -Force -ErrorAction SilentlyContinue - } + } } } - + # For Strict Kernel mode WDAC policy without allowing Flight root certs (i.e. not allowing insider builds) if ($PSCmdlet.ParameterSetName -eq 'No Flight Roots' -and $PSBoundParameters.ContainsKey('NoFlightRoots')) { @@ -245,29 +245,29 @@ function New-KernelModeWDACConfig { ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Enforced_Kernel_NoFlights.xml -BinaryFilePath "$PolicyID.cip" | Out-Null # Deploy the policy if Deploy parameter is used and perform additional tasks on the system - if ($Deploy) { + if ($Deploy) { # Set the GUID of the Audit mode policy in the User Configuration file Set-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID $PolicyID | Out-Null CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null &$WriteHotPink 'Strict Kernel mode policy with no flighting root certs has been deployed in Audit mode, please restart your system.' - + # Clear Code Integrity operational before system restart so that after boot it will only have the correct and new logs wevtutil cl 'Microsoft-Windows-CodeIntegrity/Operational' wevtutil cl 'Microsoft-Windows-AppLocker/MSI and Script' if (!$Debug) { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel_NoFlights.xml', ".\$PolicyID.cip" -Force -ErrorAction SilentlyContinue - } + } } else { &$WriteHotPink 'Strict Kernel mode Audit policy with no flighting root certs has been created in the current working directory.' - } + } } - if ($AuditAndEnforce) { - + if ($AuditAndEnforce) { + # Get the Strict Kernel Audit mode policy's GUID to use for the Enforced mode policy - # This will eliminate the need for an extra reboot + # This will eliminate the need for an extra reboot [System.String]$PolicyID = Get-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID # Verify the Policy ID in the User Config exists and is valid $ObjectGuid = [System.Guid]::Empty @@ -276,27 +276,27 @@ function New-KernelModeWDACConfig { } else { Write-Error 'Invalid or nonexistent GUID in User Configs for Audit mode policy, Use the -PrepMode parameter first.' - } + } powershell.exe { # Scan Event viewer logs for drivers $DriverFilesObj = Get-SystemDriver -Audit # Create a policy xml file from the driver files - New-CIPolicy -MultiplePolicyFormat -Level FilePublisher -Fallback None -FilePath '.\DriverFilesScanPolicy.xml' -DriverFiles $DriverFilesObj - } - - # Build the same policy again after restart, do not trust the policy xml file made before restart + New-CIPolicy -MultiplePolicyFormat -Level FilePublisher -Fallback None -FilePath '.\DriverFilesScanPolicy.xml' -DriverFiles $DriverFilesObj + } + + # Build the same policy again after restart, do not trust the policy xml file made before restart Copy-Item -Path "$psscriptroot\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml" -Destination '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' -Force - + # Merge the base policy with the policy made from driver files to deploy it as one Merge-CIPolicy -PolicyPaths '.\DefaultWindows_Enforced_Kernel_NoFlights.xml', '.\DriverFilesScanPolicy.xml' -OutputFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null - + # Remove the old policy again because we used it in merge and don't need it anymore Remove-Item -Path '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' -Force # Move all AllowedSigners from Usermode to Kernel mode signing scenario Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null - + # Set the GUIDs for the XML policy file Edit-GUIDs -PolicyIDInput $PolicyID -PolicyFilePathInput '.\Final_DefaultWindows_Enforced_Kernel.xml' @@ -308,15 +308,15 @@ function New-KernelModeWDACConfig { @(0, 3, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option $_ -Delete } if ($EVSigners) { Set-RuleOption -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Option 8 } - + Set-HVCIOptions -Strict -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' - + # Deploy the policy if Deploy parameter is used - if ($Deploy) { + if ($Deploy) { ConvertFrom-CIPolicy -XmlFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null &$WritePink 'Strict Kernel mode policy with no flighting root certs has been deployed in Enforced mode, no restart required.' - + # Delete its GUID from User Configurations Remove-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID | Out-Null } @@ -326,14 +326,14 @@ function New-KernelModeWDACConfig { # And instead wants to first Sign and then deploy it using the Deploy-SignedWDACConfig cmdlet CiTool.exe --remove-policy "{$PolicyID}" -json | Out-Null &$WritePink 'Strict Kernel mode Enforced policy with no flighting root certs has been created in the current working directory.' - } + } if (!$Debug) { Remove-Item -Path ".\$PolicyID.cip", '.\DriverFilesScanPolicy.xml' -Force -ErrorAction SilentlyContinue - } + } } } - } - + } + <# .SYNOPSIS Creates Kernel only mode WDAC policy capable of protecting against BYOVD attacks category diff --git a/WDACConfig/WDACConfig Module Files/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-SupplementalWDACConfig.psm1 index d2360fd5a..23f7aaeca 100644 --- a/WDACConfig/WDACConfig Module Files/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/New-SupplementalWDACConfig.psm1 @@ -14,12 +14,12 @@ function New-SupplementalWDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Folder Path With WildCards')][System.Management.Automation.SwitchParameter]$PathWildCards, [Alias('P')] [parameter(mandatory = $false, ParameterSetName = 'Installed AppXPackages')][System.Management.Automation.SwitchParameter]$InstalledAppXPackages, - + [parameter(Mandatory = $true, ParameterSetName = 'Installed AppXPackages', ValueFromPipelineByPropertyName = $true)] [System.String]$PackageName, - [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] - [parameter(Mandatory = $true, ParameterSetName = 'Normal', ValueFromPipelineByPropertyName = $true)] + [ValidateScript({ Test-Path -Path $_ -PathType 'Container' }, ErrorMessage = 'The path you selected is not a folder path.')] + [parameter(Mandatory = $true, ParameterSetName = 'Normal', ValueFromPipelineByPropertyName = $true)] [System.String]$ScanLocation, [ValidatePattern('\*', ErrorMessage = "You didn't supply a path that contains wildcard character '*' .")] @@ -29,15 +29,15 @@ function New-SupplementalWDACConfig { [ValidatePattern('^[a-zA-Z0-9 ]+$', ErrorMessage = 'The Supplemental Policy Name can only contain alphanumeric and space characters.')] [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet [System.String]$SuppPolicyName, - + [ValidatePattern('\.xml$')] [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' }, ErrorMessage = 'The path you selected is not a file path.')] - [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet + [parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] # Used by the entire Cmdlet [System.String]$PolicyPath, - [parameter(Mandatory = $false)] # Used by the entire Cmdlet + [parameter(Mandatory = $false)] # Used by the entire Cmdlet [System.Management.Automation.SwitchParameter]$Deploy, - + [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [Parameter(Mandatory = $false, ParameterSetName = 'Normal')] [System.String]$SpecificFileNameLevel, @@ -55,8 +55,8 @@ function New-SupplementalWDACConfig { [ValidateSet([Fallbackz])] [parameter(Mandatory = $false, ParameterSetName = 'Normal')] [System.String[]]$Fallbacks = 'Hash', # Setting the default value for the Fallbacks parameter - - [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck + + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -66,42 +66,42 @@ function New-SupplementalWDACConfig { # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Fallbackz } } # argument tab auto-completion and ValidateSet for level Class Levelz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Levelz } } - + # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise $ErrorActionPreference = 'Stop' if (-NOT $SkipVersionCheck) { . Update-self } # Fetch User account directory path [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath - + #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPath) { # Read User configuration file if it exists - $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue + $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue if ($UserConfig) { # Validate the Json file and read its content to make sure it's not corrupted try { $UserConfig = $UserConfig | ConvertFrom-Json } - catch { + catch { Write-Error 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig - } + Set-CommonWDACConfig -DeleteUserConfig + } } } # If PolicyPaths has no values - if (!$PolicyPath) { + if (!$PolicyPath) { if ($UserConfig.UnsignedPolicyPath) { # validate each policyPath read from user config file if (Test-Path -Path $($UserConfig.UnsignedPolicyPath)) { @@ -109,12 +109,12 @@ function New-SupplementalWDACConfig { } else { throw 'The currently saved value for UnsignedPolicyPath in user configurations is invalid.' - } + } } else { throw "PolicyPath parameter can't be empty and no valid configuration was found for UnsignedPolicyPath." } - } + } #endregion User-Configurations-Processing-Validation # Ensure when user selects the -Deploy parameter, the base policy is not signed @@ -122,16 +122,16 @@ function New-SupplementalWDACConfig { $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId - if ($RedFlag1 -or $RedFlag2) { + if ($RedFlag1 -or $RedFlag2) { Write-Error -Message 'You are using -Deploy parameter and the selected base policy is Signed. Please use Deploy-SignedWDACConfig to deploy it.' - } + } } } process { - + if ($Normal) { - + # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet [System.Collections.Hashtable]$PolicyMakerHashTable = @{ FilePath = "SupplementalPolicy $SuppPolicyName.xml" @@ -143,40 +143,40 @@ function New-SupplementalWDACConfig { AllowFileNameFallbacks = $true } # Assess user input parameters and add the required parameters to the hash table - if ($SpecificFileNameLevel) { $PolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $PolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $PolicyMakerHashTable['UserPEs'] = $true } + if ($SpecificFileNameLevel) { $PolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } + if ($NoScript) { $PolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $PolicyMakerHashTable['UserPEs'] = $true } &$WriteHotPink "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable Write-Host -Object "`n" # Create the supplemental policy via parameter splatting - New-CIPolicy @PolicyMakerHashTable - + New-CIPolicy @PolicyMakerHashTable + [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { - Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } - Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" + Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } + Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ SupplementalPolicyFile = "SupplementalPolicy $SuppPolicyName.xml" SupplementalPolicyGUID = $PolicyID - } - if ($Deploy) { + } + if ($Deploy) { CiTool --update-policy "$policyID.cip" -json | Out-Null &$WritePink "A Supplemental policy with the name $SuppPolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force } } - + if ($PathWildCards) { - + # Using Windows PowerShell to handle serialized data since PowerShell core throws an error # Creating the Supplemental policy file - powershell.exe { + powershell.exe { $RulesWildCards = New-CIPolicyRule -FilePathRule $args[0] New-CIPolicy -MultiplePolicyFormat -FilePath ".\SupplementalPolicy $($args[1]).xml" -Rules $RulesWildCards } -args $FolderPath, $SuppPolicyName @@ -185,25 +185,25 @@ function New-SupplementalWDACConfig { [System.String]$policyID = Set-CIPolicyIdInfo -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' - - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + + # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } - + # Adding policy rule option 18 Disabled:Runtime FilePath Rule Protection Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option 18 - - Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" + + Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ SupplementalPolicyFile = ".\SupplementalPolicy $SuppPolicyName.xml" SupplementalPolicyGUID = $PolicyID } - - if ($Deploy) { + + if ($Deploy) { CiTool --update-policy "$policyID.cip" -json | Out-Null &$WritePink "A Supplemental policy with the name $SuppPolicyName has been deployed." - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$policyID.cip" -Force } } @@ -211,13 +211,13 @@ function New-SupplementalWDACConfig { do { Get-AppxPackage -Name $PackageName Write-Debug -Message "This is the Selected package name $PackageName" - $Question = Read-Host "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit" + $Question = Read-Host "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit" } until ( (($Question -eq 1) -or ($Question -eq 2)) ) if ($Question -eq 2) { break } - powershell.exe { + powershell.exe { # Get all the packages based on the supplied name $Package = Get-AppxPackage -Name $args[0] # Get package dependencies if any @@ -227,14 +227,14 @@ function New-SupplementalWDACConfig { foreach ($item in $Package) { $Rules += New-CIPolicyRule -Package $item } - + # Create rules for each pacakge dependency, if any if ($PackageDependencies) { foreach ($item in $PackageDependencies) { $Rules += New-CIPolicyRule -Package $item } } - + # Generate the supplemental policy xml file New-CIPolicy -MultiplePolicyFormat -FilePath ".\SupplementalPolicy $($args[1]).xml" -Rules $Rules } -args $PackageName, $SuppPolicyName @@ -244,26 +244,26 @@ function New-SupplementalWDACConfig { [System.String]$policyID = Set-CIPolicyIdInfo -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' - - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + + # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20) | ForEach-Object -Process { - Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" + Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } + + Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ SupplementalPolicyFile = ".\SupplementalPolicy $SuppPolicyName.xml" SupplementalPolicyGUID = $PolicyID } - if ($Deploy) { + if ($Deploy) { CiTool --update-policy "$policyID.cip" -json | Out-Null &$WritePink "A Supplemental policy with the name $SuppPolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force } } - } - + } + <# .SYNOPSIS Automate a lot of tasks related to WDAC (Windows Defender Application Control) @@ -280,7 +280,7 @@ Windows Defender Application Control, ConfigCI PowerShell module .FUNCTIONALITY Automate various tasks related to Windows Defender Application Control (WDAC) -.PARAMETER Normal +.PARAMETER Normal Make a Supplemental policy by scanning a directory, you can optionally use other parameters too to fine tune the scan process .PARAMETER PathWildCards @@ -311,7 +311,7 @@ Indicates that the module will automatically deploy the Supplemental policy afte You can choose one of the following options: "OriginalFileName", "InternalName", "FileDescription", "ProductName", "PackageFamilyName", "FilePath" .PARAMETER NoUserPEs -By default the module includes user PEs in the scan, but when you use this switch parameter, they won't be included. +By default the module includes user PEs in the scan, but when you use this switch parameter, they won't be included. .PARAMETER NoScript https://learn.microsoft.com/en-us/powershell/module/configci/new-cipolicy#-noscript diff --git a/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 index 4721b8fd0..5a1d98ad0 100644 --- a/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/New-WDACConfig.psm1 @@ -13,11 +13,11 @@ function New-WDACConfig { [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')][System.Management.Automation.SwitchParameter]$MakeAllowMSFTWithBlockRules, [Parameter(Mandatory = $false, ParameterSetName = 'Set Auto Update Driver Block Rules')][System.Management.Automation.SwitchParameter]$SetAutoUpdateDriverBlockRules, [Parameter(Mandatory = $false, ParameterSetName = 'Prep MSFT Only Audit')][System.Management.Automation.SwitchParameter]$PrepMSFTOnlyAudit, - [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')][System.Management.Automation.SwitchParameter]$PrepDefaultWindowsAudit, - [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')][System.Management.Automation.SwitchParameter]$MakePolicyFromAuditLogs, + [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')][System.Management.Automation.SwitchParameter]$PrepDefaultWindowsAudit, + [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')][System.Management.Automation.SwitchParameter]$MakePolicyFromAuditLogs, [Parameter(Mandatory = $false, ParameterSetName = 'Make Light Policy')][System.Management.Automation.SwitchParameter]$MakeLightPolicy, [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')][System.Management.Automation.SwitchParameter]$MakeDefaultWindowsWithBlockRules, - + [ValidateSet('Allow Microsoft Base', 'Default Windows Base')] [Parameter(Mandatory = $true, ParameterSetName = 'Make Policy From Audit Logs')] [System.String]$BasePolicyType, @@ -37,19 +37,19 @@ function New-WDACConfig { [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Make DefaultWindows With Block Rules')] [System.String]$SignToolPath, - + [Parameter(Mandatory = $false, ParameterSetName = 'Make Light Policy')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')] [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')] [System.Management.Automation.SwitchParameter]$TestMode, - + [Parameter(Mandatory = $false, ParameterSetName = 'Make AllowMSFT With Block Rules')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Light Policy')] [Parameter(Mandatory = $false, ParameterSetName = 'Make DefaultWindows With Block Rules')] [System.Management.Automation.SwitchParameter]$RequireEVSigners, - + [ValidateSet('OriginalFileName', 'InternalName', 'FileDescription', 'ProductName', 'PackageFamilyName', 'FilePath')] [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [System.String]$SpecificFileNameLevel, @@ -75,10 +75,10 @@ function New-WDACConfig { [ValidateRange(1024KB, 18014398509481983KB)] [Parameter(Mandatory = $false, ParameterSetName = 'Prep MSFT Only Audit')] [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')] - [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] + [Parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] [System.Int64]$LogSize, - [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck + [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SkipVersionCheck ) begin { @@ -93,28 +93,28 @@ function New-WDACConfig { # Fetch User account directory path [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath - + #region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path if ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { # Read User configuration file if it exists - $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue + $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue if ($UserConfig) { # Validate the Json file and read its content to make sure it's not corrupted try { $UserConfig = $UserConfig | ConvertFrom-Json } - catch { + catch { Write-Error 'User Configurations Json file is corrupted, deleting it...' -ErrorAction Continue # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig - } - } - } - + Set-CommonWDACConfig -DeleteUserConfig + } + } + } + # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. - elseif ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { + elseif ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } #endregion User-Configurations-Processing-Validation @@ -125,7 +125,7 @@ function New-WDACConfig { # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Fallbackz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Fallbackz } } @@ -133,11 +133,11 @@ function New-WDACConfig { # argument tab auto-completion and ValidateSet for level Class Levelz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') + $Levelz = ('Hash', 'FileName', 'SignedVersion', 'Publisher', 'FilePublisher', 'LeafCertificate', 'PcaCertificate', 'RootCertificate', 'WHQL', 'WHQLPublisher', 'WHQLFilePublisher', 'PFN', 'FilePath', 'None') return [System.String[]]$Levelz } } - + [System.Management.Automation.ScriptBlock]$GetDriverBlockRulesSCRIPTBLOCK = { [System.String]$DriverRules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty @@ -155,36 +155,36 @@ function New-WDACConfig { # Display the result as object [PSCustomObject]@{ PolicyFile = 'Microsoft recommended driver block rules.xml' - } + } } [System.Management.Automation.ScriptBlock]$MakeAllowMSFTWithBlockRulesSCRIPTBLOCK = { param([System.Boolean]$NoCIP) # Get the latest Microsoft recommended block rules - Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null + Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' - Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\AllowMicrosoftPlusBlockRules.xml | Out-Null + Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\AllowMicrosoftPlusBlockRules.xml | Out-Null [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoftPlusBlockRules.xml -PolicyName "Allow Microsoft Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath .\AllowMicrosoftPlusBlockRules.xml -Version '1.0.0.0' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ -Delete } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ -Delete } if ($TestMode -and $MakeAllowMSFTWithBlockRules) { 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } } if ($RequireEVSigners -and $MakeAllowMSFTWithBlockRules) { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option 8 - } + } Set-HVCIOptions -Strict -FilePath .\AllowMicrosoftPlusBlockRules.xml - ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null # Remove the extra files that were created during module operation and are no longer needed Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force [PSCustomObject]@{ PolicyFile = 'AllowMicrosoftPlusBlockRules.xml' BinaryFile = "$PolicyID.cip" } - if ($Deploy -and $MakeAllowMSFTWithBlockRules) { + if ($Deploy -and $MakeAllowMSFTWithBlockRules) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force @@ -192,12 +192,12 @@ function New-WDACConfig { if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } } - + [System.Management.Automation.ScriptBlock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { param([System.Boolean]$NoCIP) - Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null + Invoke-Command -ScriptBlock $GetBlockRulesSCRIPTBLOCK | Out-Null Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' - + [System.Boolean]$global:MergeSignToolPolicy = $false if ($SignToolPathFinal) { @@ -207,45 +207,45 @@ function New-WDACConfig { Copy-Item -Path $SignToolPathFinal -Destination "$global:UserTempDirectoryPath\TemporarySignToolFile" -Force New-CIPolicy -ScanPath "$global:UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml # Delete the Temporary folder in the TEMP folder - if (!$Debug) { Remove-Item -Recurse -Path "$global:UserTempDirectoryPath\TemporarySignToolFile" -Force } + if (!$Debug) { Remove-Item -Recurse -Path "$global:UserTempDirectoryPath\TemporarySignToolFile" -Force } [System.Boolean]$global:MergeSignToolPolicy = $true - } - + } + # Scan PowerShell core directory and allow its files in the Default Windows base policy so that module can still be used once it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { - &$WriteLavender 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' + &$WriteLavender 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml - + if ($global:MergeSignToolPolicy) { Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, 'Microsoft recommended block rules.xml', .\SignTool.xml -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } - else { + else { Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null - } + } } else { if ($global:MergeSignToolPolicy) { Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, 'Microsoft recommended block rules.xml', .\SignTool.xml -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } else { - Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null - } - } - + Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null + } + } + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindowsPlusBlockRules.xml -PolicyName "Default Windows Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath .\DefaultWindowsPlusBlockRules.xml -Version '1.0.0.0' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } - @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ -Delete } + @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ -Delete } if ($TestMode -and $MakeDefaultWindowsWithBlockRules) { 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } } if ($RequireEVSigners -and $MakeDefaultWindowsWithBlockRules) { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option 8 - } + } Set-HVCIOptions -Strict -FilePath .\DefaultWindowsPlusBlockRules.xml - ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindowsPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindowsPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null Remove-Item -Path .\AllowPowerShell.xml -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\DefaultWindows_Enforced.xml', 'Microsoft recommended block rules.xml' -Force @@ -256,12 +256,12 @@ function New-WDACConfig { BinaryFile = "$PolicyID.cip" } - if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { + if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { CiTool --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } - if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } + if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } } [System.Management.Automation.ScriptBlock]$DeployLatestDriverBlockRulesSCRIPTBLOCK = { @@ -269,16 +269,16 @@ function New-WDACConfig { Expand-Archive -Path .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force Rename-Item -Path .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force Copy-Item -Path .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' - citool --refresh -json | Out-Null - &$WritePink 'SiPolicy.p7b has been deployed and policies refreshed.' - Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force + citool --refresh -json | Out-Null + &$WritePink 'SiPolicy.p7b has been deployed and policies refreshed.' + Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } - + [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File '.\Microsoft recommended block rules TEMP.xml' # Remove empty lines from the policy file - Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' + Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File '.\Microsoft recommended block rules.xml' Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' @@ -286,28 +286,28 @@ function New-WDACConfig { [System.String]$PolicyID = (Set-CIPolicyIdInfo -FilePath '.\Microsoft recommended block rules.xml' -ResetPolicyID).Substring(11) Set-CIPolicyIdInfo -PolicyName "Microsoft Windows User Mode Policy - Enforced - $(Get-Date -Format 'MM-dd-yyyy')" -FilePath '.\Microsoft recommended block rules.xml' ConvertFrom-CIPolicy -XmlFilePath '.\Microsoft recommended block rules.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null - CiTool --update-policy "$PolicyID.cip" -json | Out-Null - &$WriteLavender 'The Microsoft recommended block rules policy has been deployed in enforced mode.' + CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &$WriteLavender 'The Microsoft recommended block rules policy has been deployed in enforced mode.' Remove-Item -Path "$PolicyID.cip" -Force } [System.Management.Automation.ScriptBlock]$SetAutoUpdateDriverBlockRulesSCRIPTBLOCK = { # create a scheduled task that runs every 7 days - if (-NOT (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath '\MSFT Driver Block list update\' -ErrorAction SilentlyContinue)) { + if (-NOT (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath '\MSFT Driver Block list update\' -ErrorAction SilentlyContinue)) { # Get the SID of the SYSTEM account. It is a well-known SID, but still querying it, going to use it to create the scheduled task $SYSTEMSID = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null) - # create a scheduled task that runs every 7 days + # create a scheduled task that runs every 7 days $Action = New-ScheduledTaskAction -Execute 'Powershell.exe' ` - -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' + -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' $TaskPrincipal = New-ScheduledTaskPrincipal -LogonType S4U -UserId $($SYSTEMSID.Value) -RunLevel Highest # trigger - $Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) + $Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) # register the task Register-ScheduledTask -Action $Action -Trigger $Time -Principal $TaskPrincipal -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Description 'Microsoft Recommended Driver Block List update' # define advanced settings for the task $TaskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Compatibility Win8 -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 3) # add advanced settings we defined to the task - Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings + Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings } Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } @@ -321,45 +321,45 @@ function New-WDACConfig { Set-CIPolicyIdInfo -PolicyName 'PrepMSFTOnlyAudit' -FilePath .\AllowMicrosoft.xml ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoft.xml -BinaryFilePath "$PolicyID.cip" | Out-Null if ($Deploy) { - CiTool --update-policy "$PolicyID.cip" -json | Out-Null - &$WriteHotPink 'The default AllowMicrosoft policy has been deployed in Audit mode. No reboot required.' - Remove-Item -Path 'AllowMicrosoft.xml', "$PolicyID.cip" -Force + CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &$WriteHotPink 'The default AllowMicrosoft policy has been deployed in Audit mode. No reboot required.' + Remove-Item -Path 'AllowMicrosoft.xml', "$PolicyID.cip" -Force } else { &$WriteHotPink 'The default AllowMicrosoft policy has been created in Audit mode and is ready for deployment.' - } + } } [System.Management.Automation.ScriptBlock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { if ($PrepDefaultWindowsAudit -and $LogSize) { Set-LogSize -LogSize $LogSize } Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml -Destination .\DefaultWindows_Audit.xml -Force - + # Making Sure neither PowerShell core nor WDACConfig module files are added to the Supplemental policy created by -MakePolicyFromAuditLogs parameter # by adding them first to the deployed Default Windows policy in Audit mode. Because WDACConfig module files don't need to be allowed to run since they are *.ps1 and .*psm1 files # And PowerShell core files will be added to the DefaultWindows Base policy anyway - if (Test-Path -Path 'C:\Program Files\PowerShell') { + if (Test-Path -Path 'C:\Program Files\PowerShell') { New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml New-CIPolicy -ScanPath "$psscriptroot" -Level hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\WDACConfigModule.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Audit.xml, .\AllowPowerShell.xml, .\WDACConfigModule.xml -OutputFilePath .\DefaultWindows_Audit_temp.xml | Out-Null - - Remove-Item -Path DefaultWindows_Audit.xml -Force + + Remove-Item -Path DefaultWindows_Audit.xml -Force Rename-Item -Path .\DefaultWindows_Audit_temp.xml -NewName 'DefaultWindows_Audit.xml' -Force Remove-Item -Path 'WDACConfigModule.xml', 'AllowPowerShell.xml' -Force - } - + } + Set-RuleOption -FilePath .\DefaultWindows_Audit.xml -Option 3 [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindows_Audit.xml -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyIdInfo -PolicyName 'PrepDefaultWindows' -FilePath .\DefaultWindows_Audit.xml ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Audit.xml -BinaryFilePath "$PolicyID.cip" | Out-Null if ($Deploy) { - CiTool --update-policy "$PolicyID.cip" -json | Out-Null - &$WriteLavender 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' - Remove-Item -Path 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force + CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &$WriteLavender 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' + Remove-Item -Path 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force } else { - &$WriteLavender 'The defaultWindows policy has been created in Audit mode and is ready for deployment.' - } + &$WriteLavender 'The defaultWindows policy has been created in Audit mode and is ready for deployment.' + } } [System.Management.Automation.ScriptBlock]$MakePolicyFromAuditLogsSCRIPTBLOCK = { @@ -378,20 +378,20 @@ function New-WDACConfig { $xml = [System.Xml.XmlDocument](Get-Content -Path .\AllowMicrosoftPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy - $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' + $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' } 'Default Windows Base' { Invoke-Command -ScriptBlock $MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK | Out-Null $xml = [System.Xml.XmlDocument](Get-Content -Path .\DefaultWindowsPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy - $BasePolicy = 'DefaultWindowsPlusBlockRules.xml' + $BasePolicy = 'DefaultWindowsPlusBlockRules.xml' } } if ($TestMode -and $MakePolicyFromAuditLogs) { 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath $BasePolicy -Option $_ } } - if ($RequireEVSigners -and $MakePolicyFromAuditLogs) { + if ($RequireEVSigners -and $MakePolicyFromAuditLogs) { Set-RuleOption -FilePath $BasePolicy -Option 8 } @@ -412,9 +412,9 @@ function New-WDACConfig { AllowFileNameFallbacks = $true } # Assess user input parameters and add the required parameters to the hash table - if ($SpecificFileNameLevel) { $PolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $PolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $PolicyMakerHashTable['UserPEs'] = $true } + if ($SpecificFileNameLevel) { $PolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } + if ($NoScript) { $PolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $PolicyMakerHashTable['UserPEs'] = $true } &$WriteHotPink "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable @@ -447,12 +447,12 @@ function New-WDACConfig { $DeletedFileHashesArray = Invoke-Command -ScriptBlock $AuditEventLogsDeletedFilesScriptBlock } # run the following only if there are any event logs for files no longer on the disk and if -NoDeletedFiles switch parameter wasn't used - if ($DeletedFileHashesArray -and !$NoDeletedFiles) { + if ($DeletedFileHashesArray -and !$NoDeletedFiles) { - # Save the the File Rules and File Rule Refs to the Out-File FileRulesAndFileRefs.txt in the current working directory + # Save the the File Rules and File Rule Refs to the Out-File FileRulesAndFileRefs.txt in the current working directory (Get-FileRules -HashesArray $DeletedFileHashesArray) + (Get-RuleRefs -HashesArray $DeletedFileHashesArray) | Out-File FileRulesAndFileRefs.txt - # Put the Rules and RulesRefs in an empty policy file + # Put the Rules and RulesRefs in an empty policy file New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $DeletedFileHashesArray) -RuleRefsContent (Get-RuleRefs -HashesArray $DeletedFileHashesArray) | Out-File .\DeletedFilesHashes.xml # Merge the policy file we created at first using Event Viewer logs, with the policy file we created for Hash of the files no longer available on the disk @@ -461,36 +461,36 @@ function New-WDACConfig { # do this only if there are no event logs detected with files no longer on the disk, so we use the policy file created earlier using Audit even logs else { Rename-Item -Path 'AuditLogsPolicy_NoDeletedFiles.xml' -NewName 'SupplementalPolicy.xml' -Force - } + } # Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy Set-CIPolicyVersion -FilePath 'SupplementalPolicy.xml' -Version '1.0.0.0' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath 'SupplementalPolicy.xml' -PolicyName "Supplemental Policy made from Audit Event Logs on $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $BasePolicy - [System.String]$PolicyID = $PolicyID.Substring(11) + [System.String]$PolicyID = $PolicyID.Substring(11) # Make sure policy rule options that don't belong to a Supplemental policy don't exit @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath 'SupplementalPolicy.xml' -Option $_ -Delete } - # Set the hypervisor Code Integrity option for Supplemental policy to Strict + # Set the hypervisor Code Integrity option for Supplemental policy to Strict Set-HVCIOptions -Strict -FilePath 'SupplementalPolicy.xml' # convert the Supplemental Policy file to .cip binary file ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$policyID.cip" | Out-Null [PSCustomObject]@{ - BasePolicyFile = $BasePolicy + BasePolicyFile = $BasePolicy BasePolicyGUID = $BasePolicyID } [PSCustomObject]@{ SupplementalPolicyFile = 'SupplementalPolicy.xml' SupplementalPolicyGUID = $PolicyID - } + } if (-NOT $Debug) { Remove-Item -Path 'AuditLogsPolicy_NoDeletedFiles.xml', 'FileRulesAndFileRefs.txt', 'DeletedFilesHashes.xml' -Force -ErrorAction SilentlyContinue } - if ($Deploy -and $MakePolicyFromAuditLogs) { + if ($Deploy -and $MakePolicyFromAuditLogs) { CiTool --update-policy "$BasePolicyID.cip" -json | Out-Null - CiTool --update-policy "$policyID.cip" -json | Out-Null - &$WritePink "`nBase policy and Supplemental Policies deployed and activated.`n" + CiTool --update-policy "$policyID.cip" -json | Out-Null + &$WritePink "`nBase policy and Supplemental Policies deployed and activated.`n" # Get the correct Prep mode Audit policy ID to remove from the system switch ($BasePolicyType) { 'Allow Microsoft Base' { @@ -500,9 +500,9 @@ function New-WDACConfig { $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepDefaultWindows' }).PolicyID } } - CiTool --remove-policy "{$IDToRemove}" -json | Out-Null + CiTool --remove-policy "{$IDToRemove}" -json | Out-Null &$WriteLavender "`nSystem restart required to finish removing the Audit mode Prep policy" - } + } } [System.Management.Automation.ScriptBlock]$MakeLightPolicySCRIPTBLOCK = { @@ -514,22 +514,22 @@ function New-WDACConfig { if ($TestMode -and $MakeLightPolicy) { 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } } - if ($RequireEVSigners -and $MakeLightPolicy) { + if ($RequireEVSigners -and $MakeLightPolicy) { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option 8 } $BasePolicyID = Set-CIPolicyIdInfo -FilePath .\SignedAndReputable.xml -ResetPolicyID -PolicyName "Signed And Reputable policy - $(Get-Date -Format 'MM-dd-yyyy')" - $BasePolicyID = $BasePolicyID.Substring(11) + $BasePolicyID = $BasePolicyID.Substring(11) Set-CIPolicyVersion -FilePath .\SignedAndReputable.xml -Version '1.0.0.0' - Set-HVCIOptions -Strict -FilePath .\SignedAndReputable.xml + Set-HVCIOptions -Strict -FilePath .\SignedAndReputable.xml ConvertFrom-CIPolicy -XmlFilePath .\SignedAndReputable.xml -BinaryFilePath "$BasePolicyID.cip" | Out-Null # Configure required services for ISG authorization Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow if ($Deploy -and $MakeLightPolicy) { - CiTool --update-policy "$BasePolicyID.cip" -json | Out-Null - } + CiTool --update-policy "$BasePolicyID.cip" -json | Out-Null + } [PSCustomObject]@{ - BasePolicyFile = 'SignedAndReputable.xml' + BasePolicyFile = 'SignedAndReputable.xml' BasePolicyGUID = $BasePolicyID } } @@ -539,18 +539,18 @@ function New-WDACConfig { [System.String]$owner = 'MicrosoftDocs' [System.String]$repo = 'windows-itpro-docs' [System.String]$path = 'windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' - + [System.String]$ApiUrl = "https://api.github.com/repos/$owner/$repo/commits?path=$path" [System.Object[]]$Response = Invoke-RestMethod -Uri $ApiUrl -ProgressAction SilentlyContinue [System.DateTime]$Date = $Response[0].commit.author.date - + &$WriteLavender "The document containing the drivers block list on GitHub was last updated on $Date" [System.String]$MicrosoftRecommendeDriverBlockRules = (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -ProgressAction SilentlyContinue).Content $MicrosoftRecommendeDriverBlockRules -match '(.*)' | Out-Null &$WritePink "The current version of Microsoft recommended drivers block list is $($Matches[1])" } - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { . Update-self } $DriveLettersGlobalRootFix = Invoke-Command -ScriptBlock $DriveLettersGlobalRootFixScriptBlock } @@ -568,7 +568,7 @@ function New-WDACConfig { { $GetDriverBlockRules } { & $GetDriverBlockRulesSCRIPTBLOCK; break } $SetAutoUpdateDriverBlockRules { & $SetAutoUpdateDriverBlockRulesSCRIPTBLOCK; break } - $MakeAllowMSFTWithBlockRules { & $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK; break } + $MakeAllowMSFTWithBlockRules { & $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK; break } $MakePolicyFromAuditLogs { & $MakePolicyFromAuditLogsSCRIPTBLOCK; break } $PrepMSFTOnlyAudit { & $PrepMSFTOnlyAuditSCRIPTBLOCK; break } $MakeLightPolicy { & $MakeLightPolicySCRIPTBLOCK; break } @@ -576,8 +576,8 @@ function New-WDACConfig { $PrepDefaultWindowsAudit { & $PrepDefaultWindowsAuditSCRIPTBLOCK; break } default { Write-Warning 'None of the main parameters were selected.'; break } } - } - + } + <# .SYNOPSIS Automate a lot of tasks related to WDAC (Windows Defender Application Control) diff --git a/WDACConfig/WDACConfig Module Files/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Remove-CommonWDACConfig.psm1 index cb7f0072a..f9e279f8e 100644 --- a/WDACConfig/WDACConfig Module Files/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Remove-CommonWDACConfig.psm1 @@ -1,22 +1,22 @@ #Requires -RunAsAdministrator function Remove-CommonWDACConfig { [CmdletBinding()] - Param( - [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, - [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertPath, - [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignToolPath, + Param( + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignToolPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$UnsignedPolicyPath, - [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, - [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, + [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck # DontShow prevents common parameters from being displayed too ) begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources.ps1" - + # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise - $ErrorActionPreference = 'Stop' + $ErrorActionPreference = 'Stop' # Fetch User account directory path [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath @@ -28,11 +28,11 @@ function Remove-CommonWDACConfig { } # Create User configuration file if it doesn't already exist - if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { + if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$global:UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null Write-Debug -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." } - + # Delete the entire User Configs if a more specific parameter wasn't used if ($PSBoundParameters.Count -eq 0) { Remove-Item -Path "$global:UserAccountDirectoryPath\.WDACConfig\" -Recurse -Force @@ -93,7 +93,7 @@ function Remove-CommonWDACConfig { if ($CertCN) { $UserConfigurationsObject.CertificateCommonName = '' - } + } else { $UserConfigurationsObject.CertificateCommonName = $CurrentUserConfigurations.CertificateCommonName } @@ -121,7 +121,7 @@ function Remove-CommonWDACConfig { } end { # Update the User Configurations file - $UserConfigurationsObject | ConvertTo-Json | Set-Content "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + $UserConfigurationsObject | ConvertTo-Json | Set-Content "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" &$WritePink "`nThis is your new WDAC User Configurations: " Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * } diff --git a/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 index dcf7ac41c..e04b167dc 100644 --- a/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Remove-WDACConfig.psm1 @@ -28,7 +28,7 @@ function Remove-WDACConfig { [ValidateScript({ [System.String[]]$Certificates = foreach ($Cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($Cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } + } $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [parameter(Mandatory = $false, ParameterSetName = 'Signed Base', ValueFromPipelineByPropertyName = $true)] @@ -106,7 +106,7 @@ function Remove-WDACConfig { $true })] [Parameter(Mandatory = $false, ParameterSetName = 'Unsigned Or Supplemental')] - [System.String[]]$PolicyIDs, + [System.String[]]$PolicyIDs, [parameter(Mandatory = $false, ParameterSetName = 'Signed Base', ValueFromPipelineByPropertyName = $true)] [System.String]$SignToolPath, @@ -122,8 +122,8 @@ function Remove-WDACConfig { $ErrorActionPreference = 'Stop' if (-NOT $SkipVersionCheck) { . Update-self } # Detecting if Debug switch is used, will do debugging actions based on that - $Debug = $PSBoundParameters.Debug.IsPresent - + $Debug = $PSBoundParameters.Debug.IsPresent + # Fetch User account directory path [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath @@ -132,26 +132,26 @@ function Remove-WDACConfig { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertCN) { # Read User configuration file if it exists - $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue + $UserConfig = Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -ErrorAction SilentlyContinue if ($UserConfig) { # Validate the Json file and read its content to make sure it's not corrupted try { $UserConfig = $UserConfig | ConvertFrom-Json } - catch { + catch { Write-Error 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig - } + Set-CommonWDACConfig -DeleteUserConfig + } } } - + # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) - } - + } + # If CertCN was not provided by user if (!$CertCN) { if ($UserConfig.CertificateCommonName) { @@ -167,11 +167,11 @@ function Remove-WDACConfig { else { throw "CertCN parameter can't be empty and no valid configuration was found for it." } - } + } } #endregion User-Configurations-Processing-Validation - # ValidateSet for Policy names + # ValidateSet for Policy names Class PolicyNamezx : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { $PolicyNamezx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).Friendlyname | Select-Object -Unique @@ -179,14 +179,14 @@ function Remove-WDACConfig { } } - # ValidateSet for Policy IDs + # ValidateSet for Policy IDs Class PolicyIDzx : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { $PolicyIDzx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID - + return [System.String[]]$PolicyIDzx } - } + } # argument tab auto-completion and ValidateSet for Policy names @@ -282,13 +282,13 @@ function Remove-WDACConfig { 'Wait' = $true 'ErrorAction' = 'Stop' } - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams Remove-Item -Path ".\$PolicyID.cip" -Force Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host -Object "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" @@ -299,8 +299,8 @@ function Remove-WDACConfig { # If IDs were supplied by user foreach ($ID in $PolicyIDs ) { - citool --remove-policy "{$ID}" -json | Out-Null - Write-Host -Object "Policy with the ID $ID has been successfully removed." -ForegroundColor Green + citool --remove-policy "{$ID}" -json | Out-Null + Write-Host -Object "Policy with the ID $ID has been successfully removed." -ForegroundColor Green } # If names were supplied by user @@ -314,8 +314,8 @@ function Remove-WDACConfig { if ($Debug) { $NameID | Select-Object -Unique | ForEach-Object -Process { Write-Debug -Message "$_" } } $NameID | Select-Object -Unique | ForEach-Object -Process { - citool --remove-policy "{$_}" -json | Out-Null - Write-Host -Object "Policy with the ID $_ has been successfully removed." -ForegroundColor Green + citool --remove-policy "{$_}" -json | Out-Null + Write-Host -Object "Policy with the ID $_ has been successfully removed." -ForegroundColor Green } } } diff --git a/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 index 81ba317d1..766038dfc 100644 --- a/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Set-CommonWDACConfig.psm1 @@ -1,11 +1,11 @@ #Requires -RunAsAdministrator function Set-CommonWDACConfig { [CmdletBinding()] - Param( + Param( [ValidateScript({ [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } + } $Certificates -contains $_ }, ErrorMessage = "A certificate with the provided common name doesn't exist in the personal store of the user certificates." )] [parameter(Mandatory = $false)][System.String]$CertCN, @@ -20,28 +20,28 @@ function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ - $_ | ForEach-Object -Process { + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId - if (!$RedFlag1 -and !$RedFlag2) { + $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + if (!$RedFlag1 -and !$RedFlag2) { return $True - } - else { throw 'The selected policy xml file is Signed, Please select an Unsigned policy.' } + } + else { throw 'The selected policy xml file is Signed, Please select an Unsigned policy.' } } }, ErrorMessage = 'The selected policy xml file is Signed, Please select an Unsigned policy.')] [parameter(Mandatory = $false)][System.String]$UnsignedPolicyPath, [ValidatePattern('\.xml$')] - [ValidateScript({ - $_ | ForEach-Object -Process { + [ValidateScript({ + $_ | ForEach-Object -Process { $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId - if ($RedFlag1 -or $RedFlag2) { - return $True - } - else { throw 'The selected policy xml file is Unsigned, Please select a Signed policy.' } + $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + if ($RedFlag1 -or $RedFlag2) { + return $True + } + else { throw 'The selected policy xml file is Unsigned, Please select a Signed policy.' } } }, ErrorMessage = 'The selected policy xml file is Unsigned, Please select a Signed policy.')] [parameter(Mandatory = $false)][System.String]$SignedPolicyPath, @@ -55,9 +55,9 @@ function Set-CommonWDACConfig { begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$psscriptroot\Resources.ps1" - + # Stop operation as soon as there is an error anywhere, unless explicitly specified otherwise - $ErrorActionPreference = 'Stop' + $ErrorActionPreference = 'Stop' # Fetch User account directory path [System.String]$global:UserAccountDirectoryPath = (Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath @@ -69,11 +69,11 @@ function Set-CommonWDACConfig { } # Create User configuration file if it doesn't already exist - if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { + if (-NOT (Test-Path -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$global:UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null Write-Debug -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." - } - + } + if ($PSBoundParameters.Count -eq 0) { Write-Error 'No parameter was selected.' break @@ -133,7 +133,7 @@ function Set-CommonWDACConfig { if ($CertCN) { $UserConfigurationsObject.CertificateCommonName = $CertCN - } + } else { $UserConfigurationsObject.CertificateCommonName = $CurrentUserConfigurations.CertificateCommonName } @@ -161,7 +161,7 @@ function Set-CommonWDACConfig { } end { # Update the User Configurations file - $UserConfigurationsObject | ConvertTo-Json | Set-Content "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + $UserConfigurationsObject | ConvertTo-Json | Set-Content "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" &$WritePink "`nThis is your new WDAC User Configurations: " Get-Content -Path "$global:UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * } diff --git a/WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel.xml b/WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel.xml index b8838c2e3..757a47255 100644 --- a/WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel.xml +++ b/WDACConfig/WDACConfig Module Files/WDAC Policies/DefaultWindows_Enforced_Kernel.xml @@ -122,11 +122,11 @@ - - - - -$RulesContent - - - - - - - - - - - -$RuleRefsContent - - - - - - -0 -{B163125F-E30A-43FC-ABEC-E30B4EE88FA8} -{B163125F-E30A-43FC-ABEC-E30B4EE88FA8} - -"@ - return $EmptyPolicy -} - -Function Get-BlockRulesMeta { - <# - .SYNOPSIS - Gets the latest Microsoft Recommended block rules, removes its allow all rules and sets HVCI to strict - .INPUTS - System.Void - .OUTPUTS - PSCustomObject - #> - [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' - $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force - # Removing empty lines from policy file - Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath '.\Microsoft recommended block rules.xml' -Force - Remove-Item -Path '.\Microsoft recommended block rules TEMP.xml' -Force - Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete - Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' - return [PSCustomObject]@{ - PolicyFile = 'Microsoft recommended block rules.xml' - } -} - -function Confirm-CertCN { - <# - .SYNOPSIS - Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json - .INPUTS - System.String - .OUTPUTS - System.Boolean - #> - param ( - [System.String]$CN - ) - [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { - (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() - } - return [System.Boolean]($Certificates -contains $CN ? $true : $false) -} - -Function Write-ColorfulText { - <# - .SYNOPSIS - Function to write modern colorful text - .INPUTS - System.String - .OUTPUTS - System.String - #> - [CmdletBinding()] - [Alias('WCT')] - - param ( - [Parameter(Mandatory = $True)] - [Alias('C')] - [ValidateSet('Fuchsia', 'Orange', 'NeonGreen', 'MintGreen', 'PinkBoldBlink', 'PinkBold', 'Rainbow' , 'Gold', 'TeaGreen', 'Lavender', 'PinkNoNewLine', 'VioletNoNewLine', 'Violet', 'Pink', 'HotPink')] - [System.String]$Color, - - [parameter(Mandatory = $True)] - [Alias('I')] - [System.String]$InputText - ) - switch ($Color) { - 'Fuchsia' { Write-Host "$($PSStyle.Foreground.FromRGB(236,68,155))$InputText$($PSStyle.Reset)"; break } - 'Orange' { Write-Host "$($PSStyle.Foreground.FromRGB(255,165,0))$InputText$($PSStyle.Reset)"; break } - 'NeonGreen' { Write-Host "$($PSStyle.Foreground.FromRGB(153,244,67))$InputText$($PSStyle.Reset)"; break } - 'MintGreen' { Write-Host "$($PSStyle.Foreground.FromRGB(152,255,152))$InputText$($PSStyle.Reset)"; break } - 'PinkBoldBlink' { Write-Host "$($PSStyle.Foreground.FromRgb(255,192,203))$($PSStyle.Bold)$($PSStyle.Blink)$InputText$($PSStyle.Reset)"; break } - 'PinkBold' { Write-Host "$($PSStyle.Foreground.FromRgb(255,192,203))$($PSStyle.Bold)$($PSStyle.Reverse)$InputText$($PSStyle.Reset)"; break } - 'Gold' { Write-Host "$($PSStyle.Foreground.FromRgb(255,215,0))$InputText$($PSStyle.Reset)"; break } - 'VioletNoNewLine' { Write-Host "$($PSStyle.Foreground.FromRGB(153,0,255))$InputText$($PSStyle.Reset)" -NoNewline; break } - 'PinkNoNewLine' { Write-Host "$($PSStyle.Foreground.FromRGB(255,0,230))$InputText$($PSStyle.Reset)" -NoNewline; break } - 'Violet' { Write-Host "$($PSStyle.Foreground.FromRGB(153,0,255))$InputText$($PSStyle.Reset)"; break } - 'Pink' { Write-Host "$($PSStyle.Foreground.FromRGB(255,0,230))$InputText$($PSStyle.Reset)"; break } - 'Lavender' { Write-Host "$($PSStyle.Foreground.FromRgb(255,179,255))$InputText$($PSStyle.Reset)"; break } - 'TeaGreen' { Write-Host "$($PSStyle.Foreground.FromRgb(133, 222, 119))$InputText$($PSStyle.Reset)"; break } - 'HotPink' { Write-Host "$($PSStyle.Foreground.FromRGB(255,105,180))$InputText$($PSStyle.Reset)"; break } - 'Rainbow' { - [System.Object[]]$Colors = @( - [System.Drawing.Color]::Pink, - [System.Drawing.Color]::HotPink, - [System.Drawing.Color]::SkyBlue, - [System.Drawing.Color]::HotPink, - [System.Drawing.Color]::SkyBlue, - [System.Drawing.Color]::LightSkyBlue, - [System.Drawing.Color]::LightGreen, - [System.Drawing.Color]::Coral, - [System.Drawing.Color]::Plum, - [System.Drawing.Color]::Gold - ) - - [System.String]$Output = '' - for ($I = 0; $I -lt $InputText.Length; $I++) { - $Color = $Colors[$I % $Colors.Length] - $Output += "$($PSStyle.Foreground.FromRGB($Color.R, $Color.G, $Color.B))$($PSStyle.Blink)$($InputText[$I])$($PSStyle.BlinkOff)$($PSStyle.Reset)" - } - Write-Output $Output - break - } - - Default { Throw 'Unspecified Color' } - } -} - -function Get-FileRules { - <# - .SYNOPSIS - Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable - #> - param ($HashesArray) - $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { - $Rules += Write-Output -InputObject "`n" - $Rules += Write-Output -InputObject "`n" - $Rules += Write-Output -InputObject "`n" - $Rules += Write-Output -InputObject "`n" - $i++ - } - return ($Rules.Trim()) -} - -function Get-RuleRefs { - <# - .SYNOPSIS - Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable - #> - param ($HashesArray) - $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { - $RulesRefs += Write-Output -InputObject "`n" - $RulesRefs += Write-Output -InputObject "`n" - $RulesRefs += Write-Output -InputObject "`n" - $RulesRefs += Write-Output -InputObject "`n" - $i++ - } - return ($RulesRefs.Trim()) -} - -Function Remove-ZerosFromIDs { - <# - .SYNOPSIS - Can remove _0 from the ID and SignerId of all the elements in the policy xml file - #> - param( - [Parameter(Mandatory = $true)] - [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] - [System.String]$FilePath - ) - # Load the xml file - [System.Xml.XmlDocument]$Xml = Get-Content -Path $FilePath - - # Get all the elements with ID attribute - $Elements = $Xml.SelectNodes('//*[@ID]') - - # Loop through the elements and replace _0 with empty string in the ID value and SignerId value - foreach ($Element in $Elements) { - $Element.ID = $Element.ID -replace '_0', '' - # Check if the element has child elements with SignerId attribute - if ($Element.HasChildNodes) { - # Get the child elements with SignerId attribute - $childElements = $Element.SelectNodes('.//*[@SignerId]') - # Loop through the child elements and replace _0 with empty string in the SignerId value - foreach ($childElement in $childElements) { - $childElement.SignerId = $childElement.SignerId -replace '_0', '' - } - } - } - - # Get the CiSigners element by name - $CiSigners = $Xml.SiPolicy.CiSigners - - # Check if the CiSigners element has child elements with SignerId attribute - if ($CiSigners.HasChildNodes) { - # Get the child elements with SignerId attribute - $CiSignersChildren = $CiSigners.ChildNodes - # Loop through the child elements and replace _0 with empty string in the SignerId value - foreach ($CiSignerChild in $CiSignersChildren) { - $CiSignerChild.SignerId = $CiSignerChild.SignerId -replace '_0', '' - } - } - - # Save the modified xml file - $Xml.Save($FilePath) -} - -Function Move-UserModeToKernelMode { - <# - .SYNOPSIS - Moves all User mode AllowedSigners in the User mode signing scenario to the Kernel mode signing scenario and then - deletes the entire User mode signing scenario block - #> - param( - [Parameter(Mandatory = $true)] - [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] - [System.String]$FilePath - ) - - # Load the XML file as an XmlDocument object - $Xml = [System.Xml.XmlDocument](Get-Content -Path $FilePath) - - # Get the SigningScenario nodes as an array - $signingScenarios = $Xml.SiPolicy.SigningScenarios.SigningScenario - - # Find the SigningScenario node with Value 131 and store it in a variable - $signingScenario131 = $signingScenarios | Where-Object -FilterScript { $_.Value -eq '131' } - - # Find the SigningScenario node with Value 12 and store it in a variable - $signingScenario12 = $signingScenarios | Where-Object -FilterScript { $_.Value -eq '12' } - - # Get the AllowedSigners node from the SigningScenario node with Value 12 - $AllowedSigners12 = $signingScenario12.ProductSigners.AllowedSigners - - # Check if the AllowedSigners node has any child nodes - if ($AllowedSigners12.HasChildNodes) { - # Loop through each AllowedSigner node from the SigningScenario node with Value 12 - foreach ($AllowedSigner in $AllowedSigners12.AllowedSigner) { - # Create a new AllowedSigner node and copy the SignerId attribute from the original node - # Use the namespace of the parent element when creating the new element - $NewAllowedSigner = $Xml.CreateElement('AllowedSigner', $signingScenario131.NamespaceURI) - $NewAllowedSigner.SetAttribute('SignerId', $AllowedSigner.SignerId) - - # Append the new AllowedSigner node to the AllowedSigners node of the SigningScenario node with Value 131 - # out-null to prevent console display - $signingScenario131.ProductSigners.AllowedSigners.AppendChild($NewAllowedSigner) | Out-Null - } - - # Remove the SigningScenario node with Value 12 from the XML document - # out-null to prevent console display - $Xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) | Out-Null - } - - # Remove Signing Scenario 12 block only if it exists and has no allowed signers (i.e. is empty) - if ($signingScenario12 -and $AllowedSigners12.count -eq 0) { - # Remove the SigningScenario node with Value 12 from the XML document - $Xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) - } - - # Save the modified XML document to a new file - $Xml.Save($FilePath) -} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 new file mode 100644 index 000000000..4a51c9d5a --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 @@ -0,0 +1,17 @@ +Function Confirm-CertCN { + <# + .SYNOPSIS + Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json + .INPUTS + System.String + .OUTPUTS + System.Boolean + #> + param ( + [System.String]$CN + ) + [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { + (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() + } + return [System.Boolean]($Certificates -contains $CN ? $true : $false) +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 new file mode 100644 index 000000000..e13e5d886 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -0,0 +1,63 @@ +Function Get-AuditEventLogsProcessing { + <# + .SYNOPSIS + Function to separately capture FileHashes of deleted files and FilePaths of available files from Event Viewer Audit Logs + .INPUTS + System.DateTime + .OUTPUTS + PSCustomObject + #> + param ( + [System.DateTime]$Date + ) + + begin { + # Get the local disks mappings + [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives + + # Defining a custom object to store the results and return it at the end + $AuditEventLogsProcessingResults = [PSCustomObject]@{ + # Defining object properties as arrays that store file paths + AvailableFilesPaths = [System.IO.FileInfo[]]@() + DeletedFileHashes = [System.IO.FileInfo[]]@() + } + } + + process { + + # Event Viewer Code Integrity logs scan + foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { + + $Xml = [System.Xml.XmlDocument]$event.toxml() + + $Xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $Hash[$_.name] = $_.'#text' } -End { [pscustomobject]$Hash } | ForEach-Object -Process { + + # Define the regex pattern + [System.String]$Pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$' + + if ($_.'File Name' -match $Pattern) { + [System.Int64]$HardDiskVolumeNumber = $Matches[1] + [System.String]$RemainingPath = $Matches[2] + [PSCustomObject]$GetLetter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$HardDiskVolumeNumber" } + [System.IO.FileInfo]$UsablePath = "$($GetLetter.DriveLetter)$RemainingPath" + $_.'File Name' = $_.'File Name' -replace $Pattern, $UsablePath + } + + # Check if the file is currently on the disk + if (Test-Path -Path $_.'File Name') { + $AuditEventLogsProcessingResults.AvailableFilesPaths += $_.'File Name' + } + + # If the file is not currently on the disk, extract its hashes from event log + else { + $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + } + } + } + } + + end { + # return the results as an object + return $AuditEventLogsProcessingResults + } +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 new file mode 100644 index 000000000..1fb826f85 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -0,0 +1,20 @@ +Function Get-BlockRulesMeta { + <# + .SYNOPSIS + Gets the latest Microsoft Recommended block rules, removes its allow all rules and sets HVCI to strict + .INPUTS + System.Void + .OUTPUTS + PSCustomObject + #> + [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' + $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force + # Removing empty lines from policy file + Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath '.\Microsoft recommended block rules.xml' -Force + Remove-Item -Path '.\Microsoft recommended block rules TEMP.xml' -Force + Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete + Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' + return [PSCustomObject]@{ + PolicyFile = 'Microsoft recommended block rules.xml' + } +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 new file mode 100644 index 000000000..d97cb6444 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -0,0 +1,15 @@ +function Get-FileRules { + <# + .SYNOPSIS + Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable + #> + param ($HashesArray) + $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { + $Rules += Write-Output -InputObject "`n" + $Rules += Write-Output -InputObject "`n" + $Rules += Write-Output -InputObject "`n" + $Rules += Write-Output -InputObject "`n" + $i++ + } + return ($Rules.Trim()) +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 new file mode 100644 index 000000000..a30a3668d --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 @@ -0,0 +1,72 @@ +function Get-GlobalRootDrives { + <# + .SYNOPSIS + A function that gets the DriveLetter mappings in the global root namespace + And fixes these: \Device\Harddiskvolume + .LINK + https://superuser.com/questions/1058217/list-every-device-harddiskvolume + .INPUTS + System.Void + .OUTPUTS + System.Objects[] + #> + + # Import the kernel32.dll functions using P/Invoke + [System.String]$Signature = @' +[DllImport("kernel32.dll", SetLastError=true)] +[return: MarshalAs(UnmanagedType.Bool)] +public static extern bool GetVolumePathNamesForVolumeNameW([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, +[MarshalAs(UnmanagedType.LPWStr)] [Out] StringBuilder lpszVolumeNamePaths, uint cchBuferLength, +ref UInt32 lpcchReturnLength); + +[DllImport("kernel32.dll", SetLastError = true)] +public static extern IntPtr FindFirstVolume([Out] StringBuilder lpszVolumeName, +uint cchBufferLength); + +[DllImport("kernel32.dll", SetLastError = true)] +public static extern bool FindNextVolume(IntPtr hFindVolume, [Out] StringBuilder lpszVolumeName, uint cchBufferLength); + +[DllImport("kernel32.dll", SetLastError = true)] +public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax); + +'@ + # Add the signature to the current session as a new type + Add-Type -ErrorAction SilentlyContinue -MemberDefinition $Signature -Name 'Win32Utils' -Namespace 'PInvoke' -Using PInvoke, System.Text -Verbose:$false + + # Initialize some variables for storing the volume names, paths, and mount points + [System.UInt32]$lpcchReturnLength = 0 + [System.UInt32]$Max = 65535 + [System.Text.StringBuilder]$SbVolumeName = New-Object -TypeName System.Text.StringBuilder($Max, $Max) + [System.Text.StringBuilder]$SbPathName = New-Object -TypeName System.Text.StringBuilder($Max, $Max) + [System.Text.StringBuilder]$SbMountPoint = New-Object -TypeName System.Text.StringBuilder($Max, $Max) + + # Find the first volume in the system and get a handle to it + [System.IntPtr]$VolumeHandle = [PInvoke.Win32Utils]::FindFirstVolume($SbVolumeName, $Max) + + # Loop through all the volumes in the system + do { + # Get the volume name as a string + [System.String]$Volume = $SbVolumeName.toString() + # Get the mount point for the volume, if any + [System.Boolean]$unused = [PInvoke.Win32Utils]::GetVolumePathNamesForVolumeNameW($Volume, $SbMountPoint, $Max, [System.Management.Automation.PSReference]$lpcchReturnLength) + # Get the device path for the volume, if any + [System.UInt32]$ReturnLength = [PInvoke.Win32Utils]::QueryDosDevice($Volume.Substring(4, $Volume.Length - 1 - 4), $SbPathName, [System.UInt32]$Max) + + # If the device path is found, create a custom object with the drive mapping information + if ($ReturnLength) { + [System.Collections.Hashtable]$DriveMapping = @{ + DriveLetter = $SbMountPoint.toString() + VolumeName = $Volume + DevicePath = $SbPathName.ToString() + } + # Write the custom object to the output stream + Write-Output -InputObject (New-Object -TypeName PSObject -Property $DriveMapping) + } + else { + # If no device path is found, write a message to the output stream + Write-Output -InputObject 'No mountpoint found for: ' + $Volume + } + # Find the next volume in the system and repeat the loop + } while ([PInvoke.Win32Utils]::FindNextVolume([System.IntPtr]$VolumeHandle, $SbVolumeName, $Max)) + +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 new file mode 100644 index 000000000..bd95990fa --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -0,0 +1,15 @@ +function Get-RuleRefs { + <# + .SYNOPSIS + Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable + #> + param ($HashesArray) + $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { + $RulesRefs += Write-Output -InputObject "`n" + $RulesRefs += Write-Output -InputObject "`n" + $RulesRefs += Write-Output -InputObject "`n" + $RulesRefs += Write-Output -InputObject "`n" + $i++ + } + return ($RulesRefs.Trim()) +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 new file mode 100644 index 000000000..d1e36ce82 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -0,0 +1,53 @@ +function Get-SignTool { + <# + .SYNOPSIS + Gets the path to SignTool.exe and verifies it to make sure it's not tampered + .PARAMETER SignToolExePath + Path to the SignTool.exe + .INPUTS + System.String + .OUTPUTS + System.String + #> + param( + [parameter(Mandatory = $false)][System.String]$SignToolExePath + ) + # If Sign tool path wasn't provided by parameter, try to detect it automatically, if fails, stop the operation + if (!$SignToolExePath) { + if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64') { + if ( Test-Path -Path 'C:\Program Files (x86)\Windows Kits\*\bin\*\x64\signtool.exe') { + $SignToolExePath = 'C:\Program Files (x86)\Windows Kits\*\bin\*\x64\signtool.exe' + } + else { + Throw [System.IO.FileNotFoundException] 'signtool.exe could not be found' + } + } + elseif ($Env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { + if (Test-Path -Path 'C:\Program Files (x86)\Windows Kits\*\bin\*\arm64\signtool.exe') { + $SignToolExePath = 'C:\Program Files (x86)\Windows Kits\*\bin\*\arm64\signtool.exe' + } + else { + Throw [System.IO.FileNotFoundException] 'signtool.exe could not be found' + } + } + } + try { + # Validate the SignTool executable + [System.Version]$WindowsSdkVersion = '10.0.22621.755' # Setting the minimum version of SignTool that is allowed to be executed + [System.Boolean]$GreenFlag1 = (((Get-Item -Path $SignToolExePath).VersionInfo).ProductVersionRaw -ge $WindowsSdkVersion) + [System.Boolean]$GreenFlag2 = (((Get-Item -Path $SignToolExePath).VersionInfo).FileVersionRaw -ge $WindowsSdkVersion) + [System.Boolean]$GreenFlag3 = ((Get-Item -Path $SignToolExePath).VersionInfo).CompanyName -eq 'Microsoft Corporation' + [System.Boolean]$GreenFlag4 = ((Get-AuthenticodeSignature -FilePath $SignToolExePath).Status -eq 'Valid') + [System.Boolean]$GreenFlag5 = ((Get-AuthenticodeSignature -FilePath $SignToolExePath).StatusMessage -eq 'Signature verified.') + } + catch { + Throw [System.Security.VerificationException] 'SignTool executable could not be verified.' + } + # If any of the 5 checks above fails, the operation stops + if (!$GreenFlag1 -or !$GreenFlag2 -or !$GreenFlag3 -or !$GreenFlag4 -or !$GreenFlag5) { + Throw [System.Security.VerificationException] 'The SignTool executable was found but could not be verified. Please download the latest Windows SDK to get the newest SignTool executable. Official download link: http://aka.ms/WinSDK' + } + else { + return $SignToolExePath + } +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 new file mode 100644 index 000000000..4761ca7c3 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 @@ -0,0 +1,55 @@ +Function Move-UserModeToKernelMode { + <# + .SYNOPSIS + Moves all User mode AllowedSigners in the User mode signing scenario to the Kernel mode signing scenario and then + deletes the entire User mode signing scenario block + #> + param( + [Parameter(Mandatory = $true)] + [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] + [System.String]$FilePath + ) + + # Load the XML file as an XmlDocument object + $Xml = [System.Xml.XmlDocument](Get-Content -Path $FilePath) + + # Get the SigningScenario nodes as an array + $signingScenarios = $Xml.SiPolicy.SigningScenarios.SigningScenario + + # Find the SigningScenario node with Value 131 and store it in a variable + $signingScenario131 = $signingScenarios | Where-Object -FilterScript { $_.Value -eq '131' } + + # Find the SigningScenario node with Value 12 and store it in a variable + $signingScenario12 = $signingScenarios | Where-Object -FilterScript { $_.Value -eq '12' } + + # Get the AllowedSigners node from the SigningScenario node with Value 12 + $AllowedSigners12 = $signingScenario12.ProductSigners.AllowedSigners + + # Check if the AllowedSigners node has any child nodes + if ($AllowedSigners12.HasChildNodes) { + # Loop through each AllowedSigner node from the SigningScenario node with Value 12 + foreach ($AllowedSigner in $AllowedSigners12.AllowedSigner) { + # Create a new AllowedSigner node and copy the SignerId attribute from the original node + # Use the namespace of the parent element when creating the new element + $NewAllowedSigner = $Xml.CreateElement('AllowedSigner', $signingScenario131.NamespaceURI) + $NewAllowedSigner.SetAttribute('SignerId', $AllowedSigner.SignerId) + + # Append the new AllowedSigner node to the AllowedSigners node of the SigningScenario node with Value 131 + # out-null to prevent console display + $signingScenario131.ProductSigners.AllowedSigners.AppendChild($NewAllowedSigner) | Out-Null + } + + # Remove the SigningScenario node with Value 12 from the XML document + # out-null to prevent console display + $Xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) | Out-Null + } + + # Remove Signing Scenario 12 block only if it exists and has no allowed signers (i.e. is empty) + if ($signingScenario12 -and $AllowedSigners12.count -eq 0) { + # Remove the SigningScenario node with Value 12 from the XML document + $Xml.SiPolicy.SigningScenarios.RemoveChild($signingScenario12) + } + + # Save the modified XML document to a new file + $Xml.Save($FilePath) +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 new file mode 100644 index 000000000..bde41bbc0 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 @@ -0,0 +1,58 @@ +function New-EmptyPolicy { + <# + .SYNOPSIS + Creates a policy file and requires 2 parameters to supply the file rules and rule references + #> + param ( + $RulesContent, + $RuleRefsContent + ) + [System.String]$EmptyPolicy = @" + + +10.0.0.0 +{2E07F7E4-194C-4D20-B7C9-6F44A6C5A234} + + + + + + + + + + + + + + + + + + +$RulesContent + + + + + + + + + + + +$RuleRefsContent + + + + + + +0 +{B163125F-E30A-43FC-ABEC-E30B4EE88FA8} +{B163125F-E30A-43FC-ABEC-E30B4EE88FA8} + +"@ + return $EmptyPolicy +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 new file mode 100644 index 000000000..96d497ce8 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 @@ -0,0 +1,46 @@ +Function Remove-ZerosFromIDs { + <# + .SYNOPSIS + Can remove _0 from the ID and SignerId of all the elements in the policy xml file + #> + param( + [Parameter(Mandatory = $true)] + [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] + [System.String]$FilePath + ) + # Load the xml file + [System.Xml.XmlDocument]$Xml = Get-Content -Path $FilePath + + # Get all the elements with ID attribute + $Elements = $Xml.SelectNodes('//*[@ID]') + + # Loop through the elements and replace _0 with empty string in the ID value and SignerId value + foreach ($Element in $Elements) { + $Element.ID = $Element.ID -replace '_0', '' + # Check if the element has child elements with SignerId attribute + if ($Element.HasChildNodes) { + # Get the child elements with SignerId attribute + $childElements = $Element.SelectNodes('.//*[@SignerId]') + # Loop through the child elements and replace _0 with empty string in the SignerId value + foreach ($childElement in $childElements) { + $childElement.SignerId = $childElement.SignerId -replace '_0', '' + } + } + } + + # Get the CiSigners element by name + $CiSigners = $Xml.SiPolicy.CiSigners + + # Check if the CiSigners element has child elements with SignerId attribute + if ($CiSigners.HasChildNodes) { + # Get the child elements with SignerId attribute + $CiSignersChildren = $CiSigners.ChildNodes + # Loop through the child elements and replace _0 with empty string in the SignerId value + foreach ($CiSignerChild in $CiSignersChildren) { + $CiSignerChild.SignerId = $CiSignerChild.SignerId -replace '_0', '' + } + } + + # Save the modified xml file + $Xml.Save($FilePath) +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 new file mode 100644 index 000000000..9bfabd4e6 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 @@ -0,0 +1,21 @@ +function Set-LogSize { + <# + .SYNOPSIS + Increase Code Integrity Operational Event Logs size from the default 1MB to user defined size + .INPUTS + System.Int64 + .OUTPUTS + System.Void + .PARAMETER LogSize + Size of the Code Integrity Operational Event Log + #> + [CmdletBinding()] + param ( + [System.Int64]$LogSize + ) + [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' + [System.Diagnostics.Eventing.Reader.EventLogConfiguration]$Log = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogConfiguration -ArgumentList $LogName + $Log.MaximumSizeInBytes = $LogSize + $Log.IsEnabled = $true + $Log.SaveChanges() +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 new file mode 100644 index 000000000..4f18a434b --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 @@ -0,0 +1,55 @@ +Function Test-FilePath { + <# + .SYNOPSIS + function that takes 2 arrays, one contains file paths and the other contains folder paths. It checks them and shows file paths + that are not in any of the folder paths. Performs this check recursively too so works if the filepath is in a sub-directory of a folder path + + #> + param ( + [Parameter(Mandatory = $true)] + [System.String[]]$FilePath, + [Parameter(Mandatory = $true)] + [System.String[]]$DirectoryPath + ) + + # Loop through each file path + foreach ($file in $FilePath) { + # Check if the file path is valid + if (Test-Path -Path $file -PathType 'Leaf') { + # Get the full path of the file + $FileFullPath = Resolve-Path -Path $file + + # Initialize a variable to store the result + [System.Boolean]$Result = $false + + # Loop through each directory path + foreach ($Directory in $DirectoryPath) { + # Check if the directory path is valid + if (Test-Path -Path $Directory -PathType 'Container') { + # Get the full path of the directory + $DirectoryFullPath = Resolve-Path -Path $Directory + + # Check if the file path starts with the directory path + if ($FileFullPath -like "$DirectoryFullPath\*") { + # The file is inside the directory or its sub-directories + $Result = $true + break # Exit the inner loop + } + } + else { + # The directory path is not valid + Write-Warning "The directory path '$Directory' is not valid." + } + } + + # Output the file path if it is not inside any of the directory paths + if (-not $Result) { + Write-Output -InputObject $FileFullPath + } + } + else { + # The file path is not valid + Write-Warning "The file path '$file' is not valid." + } + } +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 new file mode 100644 index 000000000..e2d6ad544 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -0,0 +1,69 @@ +function Update-self { + <# + .SYNOPSIS + Make sure the latest version of the module is installed and if not, automatically update it, clean up any old versions + .INPUTS + System.Void + .OUTPUTS + System.Void + #> + + try { + # Get the last update check time + [System.DateTime]$UserConfigDate = Get-CommonWDACConfig -LastUpdateCheck + } + catch { + # If the User Config file doesn't exist then set this flag to perform online update check + [System.Boolean]$PerformOnlineUpdateCheck = $true + } + + # Ensure these are run only if the User Config file exists and contains a date for last update check + if (!$PerformOnlineUpdateCheck) { + # Get the current time + [System.DateTime]$CurrentDateTime = Get-Date + # Calculate the minutes elapsed since the last online update check + [System.Int64]$TimeDiff = ($CurrentDateTime - $UserConfigDate).TotalMinutes + } + + # Only check for updates if the last attempt occured more than 10 minutes ago or the User Config file for last update check doesn't exist + # This prevents the module from constantly doing an update check by fetching the version file from GitHub + if (($TimeDiff -gt 10) -or $PerformOnlineUpdateCheck) { + + [System.Version]$CurrentVersion = (Test-ModuleManifest -Path "$ModuleRootPath\WDACConfig.psd1").Version.ToString() + try { + # First try the GitHub source + [System.Version]$LatestVersion = Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/HotCakeX/Harden-Windows-Security/main/WDACConfig/version.txt' -ProgressAction SilentlyContinue + } + catch { + try { + # If GitHub source is unavailable, use the Azure DevOps source + [System.Version]$LatestVersion = Invoke-RestMethod -Uri 'https://dev.azure.com/SpyNetGirl/011c178a-7b92-462b-bd23-2c014528a67e/_apis/git/repositories/5304fef0-07c0-4821-a613-79c01fb75657/items?path=/WDACConfig/version.txt' -ProgressAction SilentlyContinue + } + catch { + Throw [System.Security.VerificationException] 'Could not verify if the latest version of the module is installed, please check your Internet connection. You can optionally bypass the online check by using -SkipVersionCheck parameter.' + } + } + if ($CurrentVersion -lt $LatestVersion) { + Write-ColorfulText -Color Pink -InputText "The currently installed module's version is $CurrentVersion while the latest version is $LatestVersion - Auto Updating the module... 💓" + Remove-Module -Name 'WDACConfig' -Force + # Do this if the module was installed properly using Install-module cmdlet + try { + Uninstall-Module -Name 'WDACConfig' -AllVersions -Force -ErrorAction Stop + Install-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force + Import-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force -Global + } + # Do this if module files/folder was just copied to Documents folder and not properly installed - Should rarely happen + catch { + Install-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force + Import-Module -Name 'WDACConfig' -RequiredVersion $LatestVersion -Force -Global + } + # Make sure the old version isn't run after update + Write-Output -InputObject "$($PSStyle.Foreground.FromRGB(152,255,152))Update successful, please run the cmdlet again.$($PSStyle.Reset)" + break + return + } + + # Reset the last update timer to the current time + Set-CommonWDACConfig -LastUpdateCheck $(Get-Date ) | Out-Null + } +} diff --git a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 new file mode 100644 index 000000000..8dcd8ffca --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 @@ -0,0 +1,63 @@ +Function Write-ColorfulText { + <# + .SYNOPSIS + Function to write modern colorful text + .INPUTS + System.String + .OUTPUTS + System.String + #> + [CmdletBinding()] + [Alias('WCT')] + + param ( + [Parameter(Mandatory = $True)] + [Alias('C')] + [ValidateSet('Fuchsia', 'Orange', 'NeonGreen', 'MintGreen', 'PinkBoldBlink', 'PinkBold', 'Rainbow' , 'Gold', 'TeaGreen', 'Lavender', 'PinkNoNewLine', 'VioletNoNewLine', 'Violet', 'Pink', 'HotPink')] + [System.String]$Color, + + [parameter(Mandatory = $True)] + [Alias('I')] + [System.String]$InputText + ) + switch ($Color) { + 'Fuchsia' { Write-Host "$($PSStyle.Foreground.FromRGB(236,68,155))$InputText$($PSStyle.Reset)"; break } + 'Orange' { Write-Host "$($PSStyle.Foreground.FromRGB(255,165,0))$InputText$($PSStyle.Reset)"; break } + 'NeonGreen' { Write-Host "$($PSStyle.Foreground.FromRGB(153,244,67))$InputText$($PSStyle.Reset)"; break } + 'MintGreen' { Write-Host "$($PSStyle.Foreground.FromRGB(152,255,152))$InputText$($PSStyle.Reset)"; break } + 'PinkBoldBlink' { Write-Host "$($PSStyle.Foreground.FromRgb(255,192,203))$($PSStyle.Bold)$($PSStyle.Blink)$InputText$($PSStyle.Reset)"; break } + 'PinkBold' { Write-Host "$($PSStyle.Foreground.FromRgb(255,192,203))$($PSStyle.Bold)$($PSStyle.Reverse)$InputText$($PSStyle.Reset)"; break } + 'Gold' { Write-Host "$($PSStyle.Foreground.FromRgb(255,215,0))$InputText$($PSStyle.Reset)"; break } + 'VioletNoNewLine' { Write-Host "$($PSStyle.Foreground.FromRGB(153,0,255))$InputText$($PSStyle.Reset)" -NoNewline; break } + 'PinkNoNewLine' { Write-Host "$($PSStyle.Foreground.FromRGB(255,0,230))$InputText$($PSStyle.Reset)" -NoNewline; break } + 'Violet' { Write-Host "$($PSStyle.Foreground.FromRGB(153,0,255))$InputText$($PSStyle.Reset)"; break } + 'Pink' { Write-Host "$($PSStyle.Foreground.FromRGB(255,0,230))$InputText$($PSStyle.Reset)"; break } + 'Lavender' { Write-Host "$($PSStyle.Foreground.FromRgb(255,179,255))$InputText$($PSStyle.Reset)"; break } + 'TeaGreen' { Write-Host "$($PSStyle.Foreground.FromRgb(133, 222, 119))$InputText$($PSStyle.Reset)"; break } + 'HotPink' { Write-Host "$($PSStyle.Foreground.FromRGB(255,105,180))$InputText$($PSStyle.Reset)"; break } + 'Rainbow' { + [System.Object[]]$Colors = @( + [System.Drawing.Color]::Pink, + [System.Drawing.Color]::HotPink, + [System.Drawing.Color]::SkyBlue, + [System.Drawing.Color]::HotPink, + [System.Drawing.Color]::SkyBlue, + [System.Drawing.Color]::LightSkyBlue, + [System.Drawing.Color]::LightGreen, + [System.Drawing.Color]::Coral, + [System.Drawing.Color]::Plum, + [System.Drawing.Color]::Gold + ) + + [System.String]$Output = '' + for ($I = 0; $I -lt $InputText.Length; $I++) { + $Color = $Colors[$I % $Colors.Length] + $Output += "$($PSStyle.Foreground.FromRGB($Color.R, $Color.G, $Color.B))$($PSStyle.Blink)$($InputText[$I])$($PSStyle.BlinkOff)$($PSStyle.Reset)" + } + Write-Output $Output + break + } + + Default { Throw 'Unspecified Color' } + } +} From 289185cad93dc80a3824458d282efa38ab2d64d1 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 10:01:25 -0930 Subject: [PATCH 059/178] Complete overhaul of the module phase 2 --- .../Shared/Confirm-CertCN.psm1 | 3 ++ .../Shared/Get-AuditEventLogsProcessing.psm1 | 3 ++ .../Shared/Get-BlockRulesMeta.psm1 | 3 ++ .../Shared/Get-FileRules.psm1 | 5 ++- .../Shared/Get-GlobalRootDrives.psm1 | 5 ++- .../Shared/Get-RuleRefs.psm1 | 5 ++- .../Shared/Get-SignTool.psm1 | 5 ++- .../Shared/Move-UserModeToKernelMode.psm1 | 3 ++ .../Shared/New-EmptyPolicy.psm1 | 5 ++- .../Shared/Remove-ZerosFromIDs.psm1 | 3 ++ .../Shared/Set-LogSize.psm1 | 5 ++- .../Shared/Test-FilePath.psm1 | 3 ++ .../Shared/Update-self.psm1 | 5 ++- .../Shared/Write-ColorfulText.psm1 | 3 ++ .../WDACConfig Module Files/WDACConfig.psd1 | 33 ++++++++++++++----- 15 files changed, 74 insertions(+), 15 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 index 4a51c9d5a..843ca12f7 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 @@ -15,3 +15,6 @@ Function Confirm-CertCN { } return [System.Boolean]($Certificates -contains $CN ? $true : $false) } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Confirm-CertCN' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 index e13e5d886..ba5a3a3a5 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -61,3 +61,6 @@ Function Get-AuditEventLogsProcessing { return $AuditEventLogsProcessingResults } } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Get-AuditEventLogsProcessing' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 1fb826f85..ad37b39e4 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -18,3 +18,6 @@ Function Get-BlockRulesMeta { PolicyFile = 'Microsoft recommended block rules.xml' } } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Get-BlockRulesMeta' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 index d97cb6444..9333019a4 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -1,4 +1,4 @@ -function Get-FileRules { +Function Get-FileRules { <# .SYNOPSIS Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable @@ -13,3 +13,6 @@ function Get-FileRules { } return ($Rules.Trim()) } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Get-FileRules' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 index a30a3668d..4357da216 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 @@ -1,4 +1,4 @@ -function Get-GlobalRootDrives { +Function Get-GlobalRootDrives { <# .SYNOPSIS A function that gets the DriveLetter mappings in the global root namespace @@ -70,3 +70,6 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa } while ([PInvoke.Win32Utils]::FindNextVolume([System.IntPtr]$VolumeHandle, $SbVolumeName, $Max)) } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Get-GlobalRootDrives' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 index bd95990fa..e615fc78d 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -1,4 +1,4 @@ -function Get-RuleRefs { +Function Get-RuleRefs { <# .SYNOPSIS Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable @@ -13,3 +13,6 @@ function Get-RuleRefs { } return ($RulesRefs.Trim()) } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Get-RuleRefs' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 index d1e36ce82..0fe5626c9 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -1,4 +1,4 @@ -function Get-SignTool { +Function Get-SignTool { <# .SYNOPSIS Gets the path to SignTool.exe and verifies it to make sure it's not tampered @@ -51,3 +51,6 @@ function Get-SignTool { return $SignToolExePath } } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Get-SignTool' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 index 4761ca7c3..633e188f0 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 @@ -53,3 +53,6 @@ Function Move-UserModeToKernelMode { # Save the modified XML document to a new file $Xml.Save($FilePath) } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Move-UserModeToKernelMode' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 index bde41bbc0..521634c53 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 @@ -1,4 +1,4 @@ -function New-EmptyPolicy { +Function New-EmptyPolicy { <# .SYNOPSIS Creates a policy file and requires 2 parameters to supply the file rules and rule references @@ -56,3 +56,6 @@ $RuleRefsContent "@ return $EmptyPolicy } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'New-EmptyPolicy' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 index 96d497ce8..b84bf2d0c 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 @@ -44,3 +44,6 @@ Function Remove-ZerosFromIDs { # Save the modified xml file $Xml.Save($FilePath) } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Remove-ZerosFromIDs' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 index 9bfabd4e6..47e658a1e 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 @@ -1,4 +1,4 @@ -function Set-LogSize { +Function Set-LogSize { <# .SYNOPSIS Increase Code Integrity Operational Event Logs size from the default 1MB to user defined size @@ -19,3 +19,6 @@ function Set-LogSize { $Log.IsEnabled = $true $Log.SaveChanges() } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Set-LogSize' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 index 4f18a434b..79051274b 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 @@ -53,3 +53,6 @@ Function Test-FilePath { } } } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Test-FilePath' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index e2d6ad544..51d60cb7c 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -1,4 +1,4 @@ -function Update-self { +Function Update-self { <# .SYNOPSIS Make sure the latest version of the module is installed and if not, automatically update it, clean up any old versions @@ -67,3 +67,6 @@ function Update-self { Set-CommonWDACConfig -LastUpdateCheck $(Get-Date ) | Out-Null } } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Update-self' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 index 8dcd8ffca..b814e97fd 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 @@ -61,3 +61,6 @@ Function Write-ColorfulText { Default { Throw 'Unspecified Color' } } } + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'Write-ColorfulText' -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 index 7c1d829f7..f4eaf06b1 100644 --- a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 @@ -166,25 +166,42 @@ To get help and syntax on PowerShell console, type: # ModuleList = @() # List of all files packaged with this module - FileList = @('WDACConfig.psd1', + FileList = @( + 'WDACConfig.psd1', + 'WDACConfig.psm1', + 'Preloader.ps1', 'Core\New-WDACConfig.psm1', 'Core\Deploy-SignedWDACConfig.psm1', 'Core\Remove-WDACConfig.psm1', 'Core\Confirm-WDACConfig.psm1', 'Core\Edit-WDACConfig.psm1', 'Core\Edit-SignedWDACConfig.psm1', - 'Core\New-SupplementalWDACConfig.psm1', - 'Resources\Resources.ps1', - 'Resources\ArgumentCompleters.ps1', + 'Core\New-SupplementalWDACConfig.psm1', 'Core\New-DenyWDACConfig.psm1', 'Core\Set-CommonWDACConfig.psm1', 'Core\New-KernelModeWDACConfig.psm1', - 'Resources\WDAC Policies\DefaultWindows_Enforced_Kernel.xml', - 'Resources\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml', 'Core\Invoke-WDACSimulation.psm1', - 'Resources\Resources2.ps1', 'Core\Get-CommonWDACConfig.psm1', - 'Core\Remove-CommonWDACConfig.psm1') + 'Core\Remove-CommonWDACConfig.psm1', + 'Resources\Resources2.ps1', + 'Resources\ArgumentCompleters.ps1' + 'Resources\WDAC Policies\DefaultWindows_Enforced_Kernel.xml', + 'Resources\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml', + 'Shared\Confirm-CertCN.psm1', + 'Shared\Get-AuditEventLogsProcessing.psm1', + 'Shared\Get-BlockRulesMeta.psm1', + 'Shared\Get-FileRules.psm1', + 'Shared\Get-GlobalRootDrives.psm1', + 'Shared\Get-RuleRefs.psm1', + 'Shared\Get-SignTool.psm1', + 'Shared\Move-UserModeToKernelMode.psm1', + 'Shared\New-EmptyPolicy.psm1', + 'Shared\Remove-ZerosFromIDs.psm1', + 'Shared\Set-LogSize.psm1', + 'Shared\Test-FilePath.psm1', + 'Shared\Update-self.psm1', + 'Shared\Write-ColorfulText.psm1' + ) # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ From 9504b1bc636a391d660508e29fbd4501477c9fd4 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:10:25 -0930 Subject: [PATCH 060/178] beginning to implement segmented function access --- .../Core/Confirm-WDACConfig.psm1 | 9 +++++---- .../Core/Get-CommonWDACConfig.psm1 | 8 ++++---- .../Core/Remove-CommonWDACConfig.psm1 | 11 ++++++----- .../Core/Set-CommonWDACConfig.psm1 | 10 +++++----- .../Shared/Get-AuditEventLogsProcessing.psm1 | 3 +++ .../WDACConfig Module Files/Shared/Update-self.psm1 | 3 +++ 6 files changed, 26 insertions(+), 18 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index b982bb17b..2d90dae7f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -63,9 +63,10 @@ function Confirm-WDACConfig { } begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Regular parameters are automatically bound to variables in the function scope # Dynamic parameters however, are only available in the parameter dictionary, which is why we have to access them using $PSBoundParameters # or assign them manually to another variable in the function's scope @@ -73,7 +74,7 @@ function Confirm-WDACConfig { [System.Management.Automation.SwitchParameter]$OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) [System.Management.Automation.SwitchParameter]$SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { Update-self } # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 3d1cd9a5d..8abff4440 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -12,9 +12,9 @@ function Get-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null @@ -40,7 +40,7 @@ function Get-CommonWDACConfig { # Display this message if User Configuration file has content else { Write-ColorfulText -Color Pink -InputText "`nThis is your current WDAC User Configurations: " - Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * + Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } break } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index db68ecd4a..f6078deb7 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -11,9 +11,9 @@ function Remove-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck # DontShow prevents common parameters from being displayed too ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null @@ -35,6 +35,7 @@ function Remove-CommonWDACConfig { # Read the current user configurations $CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + # If the file exists but is corrupted and has bad values, rewrite it try { $CurrentUserConfigurations = $CurrentUserConfigurations | ConvertFrom-Json @@ -114,9 +115,9 @@ function Remove-CommonWDACConfig { } end { # Update the User Configurations file - $UserConfigurationsObject | ConvertTo-Json | Set-Content "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " - Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * + Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } } <# diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index fe3fe371a..16e9e92df 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -52,9 +52,9 @@ function Set-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.DateTime]$LastUpdateCheck ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null @@ -154,9 +154,9 @@ function Set-CommonWDACConfig { } end { # Update the User Configurations file - $UserConfigurationsObject | ConvertTo-Json | Set-Content "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " - Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List * + Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } } <# diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 index ba5a3a3a5..9a22265ef 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -12,6 +12,9 @@ Function Get-AuditEventLogsProcessing { ) begin { + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false + # Get the local disks mappings [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index 51d60cb7c..496e4ad26 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -8,6 +8,9 @@ Function Update-self { System.Void #> + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + try { # Get the last update check time [System.DateTime]$UserConfigDate = Get-CommonWDACConfig -LastUpdateCheck From aca8010a4816802fb7d6d7227054dc251ca7dc43 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:23:27 -0930 Subject: [PATCH 061/178] Added selective sub-module import to Deploy-SignedWDACConfig --- .../Core/Deploy-SignedWDACConfig.psm1 | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 919cdc7ed..44285c1a9 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -30,10 +30,13 @@ function Deploy-SignedWDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - - if (-NOT $SkipVersionCheck) { . Update-self } + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + + if (-NOT $SkipVersionCheck) { Update-self } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null From 3d4cd8a0b77fd54450ff5c29215975884ef4d7e0 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:35:17 -0930 Subject: [PATCH 062/178] Added selective sub-module import to Edit-SignedWDACConfig --- .../Core/Edit-SignedWDACConfig.psm1 | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 794a0f18c..bc3e83680 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -117,10 +117,21 @@ function Edit-SignedWDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - - if (-NOT $SkipVersionCheck) { . Update-self } + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Test-FilePath.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-AuditEventLogsProcessing.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + + if (-NOT $SkipVersionCheck) { Update-self } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user From 82a477d79b22046f499530270eba16801696d9b0 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:47:54 -0930 Subject: [PATCH 063/178] Added selective sub-module import to Edit-WDACConfig --- .../Core/Edit-WDACConfig.psm1 | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index a4696f36d..fc6836b9a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -97,10 +97,19 @@ function Edit-WDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - - if (-NOT $SkipVersionCheck) { . Update-self } + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Test-FilePath.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-AuditEventLogsProcessing.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + + if (-NOT $SkipVersionCheck) { Update-self } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null From 6801bd9e17029db7d3b331e8c4b4ebb05b5abea8 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:48:08 -0930 Subject: [PATCH 064/178] Added selective sub-module import to Invoke-WDACSimulation --- .../Core/Invoke-WDACSimulation.psm1 | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index d321fe3ed..ecc72e9de 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -16,9 +16,12 @@ function Invoke-WDACSimulation { begin { # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$ModuleRootPath\Resources\Resources2.ps1" - . "$ModuleRootPath\Resources\Resources.ps1" - if (-NOT $SkipVersionCheck) { . Update-self } + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + + if (-NOT $SkipVersionCheck) { Update-self } # The total number of the main steps for the progress bar to render [System.Int16]$TotalSteps = 4 From 070195359148f2b798cf64d5f853d419bf3d95c5 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:48:22 -0930 Subject: [PATCH 065/178] Added selective sub-module import to New-DenyWDACConfig --- .../Core/New-DenyWDACConfig.psm1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index babc33a06..f4680aaa1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -53,10 +53,10 @@ function New-DenyWDACConfig { ) begin { - - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -78,7 +78,7 @@ function New-DenyWDACConfig { } } - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { Update-self } } process { From 3fcb9b9aba6f8cbfe55e8895506a923aea7d2046 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:48:35 -0930 Subject: [PATCH 066/178] Added selective sub-module import to New-KernelModeWDACConfig --- .../Core/New-KernelModeWDACConfig.psm1 | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index d6fc327a9..e68cb4b67 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -28,13 +28,15 @@ function New-KernelModeWDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Move-UserModeToKernelMode.psm1" -Force -Verbose:$false + # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { Update-self } # Check if the PrepMode and AuditAndEnforce parameters are used together and ensure one of them is used if (-not ($PSBoundParameters.ContainsKey('PrepMode') -xor $PSBoundParameters.ContainsKey('AuditAndEnforce'))) { From b3746cfa419a973e67e3201e9f8ffdbc1574fa8c Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:48:46 -0930 Subject: [PATCH 067/178] Added selective sub-module import to New-SupplementalWDACConfig --- .../Core/New-SupplementalWDACConfig.psm1 | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 5c7bc7cb7..8f53d9308 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -59,9 +59,10 @@ function New-SupplementalWDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { From c29b0fa0cd51e5c9f7f5a121468d1974c7a37020 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:48:55 -0930 Subject: [PATCH 068/178] Added selective sub-module import to Remove-WDACConfig --- .../Core/Remove-WDACConfig.psm1 | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 8160b8609..3f8a7cc2c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -114,10 +114,13 @@ function Remove-WDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - - if (-NOT $SkipVersionCheck) { . Update-self } + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + + if (-NOT $SkipVersionCheck) { Update-self } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null From 6d954b63e766c97466421e66b6de473023cfede7 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:49:10 -0930 Subject: [PATCH 069/178] Added selective sub-module import to New-WDACConfig --- .../Core/New-WDACConfig.psm1 | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index a1224226e..cef8b963a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -81,9 +81,17 @@ function New-WDACConfig { ) begin { - # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable - . "$ModuleRootPath\Resources\Resources.ps1" - + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + #region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path if ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { @@ -540,7 +548,7 @@ function New-WDACConfig { Write-ColorfulText -Color Pink -InputText "The current version of Microsoft recommended drivers block list is $($Matches[1])" } - if (-NOT $SkipVersionCheck) { . Update-self } + if (-NOT $SkipVersionCheck) { Update-self } [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives } From 442911d704ea7cd93b0b6064d87b7ade6a92ed3b Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:49:45 -0930 Subject: [PATCH 070/178] Removed unnecessary trailing whitespaces --- .../WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 | 2 +- .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 2 +- .../Core/New-KernelModeWDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 | 4 ++-- .../WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 | 2 +- .../Shared/Get-AuditEventLogsProcessing.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 | 2 +- .../WDACConfig Module Files/Shared/Write-ColorfulText.psm1 | 4 ++-- WDACConfig/WDACConfig Module Files/WDACConfig.psd1 | 2 +- 17 files changed, 19 insertions(+), 19 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 2d90dae7f..6890c4d85 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -66,7 +66,7 @@ function Confirm-WDACConfig { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + # Regular parameters are automatically bound to variables in the function scope # Dynamic parameters however, are only available in the parameter dictionary, which is why we have to access them using $PSBoundParameters # or assign them manually to another variable in the function's scope diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 44285c1a9..299b1d5ce 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -35,7 +35,7 @@ function Deploy-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + if (-NOT $SkipVersionCheck) { Update-self } # Detecting if Debug switch is used, will do debugging actions based on that diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index bc3e83680..cd77de518 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -130,7 +130,7 @@ function Edit-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - + if (-NOT $SkipVersionCheck) { Update-self } #region User-Configurations-Processing-Validation diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index fc6836b9a..c06cb24ac 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -108,7 +108,7 @@ function Edit-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - + if (-NOT $SkipVersionCheck) { Update-self } # Detecting if Debug switch is used, will do debugging actions based on that diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 8abff4440..4df6aa09c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -14,7 +14,7 @@ function Get-CommonWDACConfig { begin { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index ecc72e9de..d2a107b2f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -20,7 +20,7 @@ function Invoke-WDACSimulation { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + if (-NOT $SkipVersionCheck) { Update-self } # The total number of the main steps for the progress bar to render diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index f4680aaa1..241d22cdb 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -56,7 +56,7 @@ function New-DenyWDACConfig { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index e68cb4b67..a80a266e4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -32,7 +32,7 @@ function New-KernelModeWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Move-UserModeToKernelMode.psm1" -Force -Verbose:$false - + # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 8f53d9308..0232e9717 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -62,7 +62,7 @@ function New-SupplementalWDACConfig { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index cef8b963a..6e8e047af 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -91,7 +91,7 @@ function New-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - + #region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path if ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index f6078deb7..b00475810 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -13,7 +13,7 @@ function Remove-CommonWDACConfig { begin { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null @@ -35,7 +35,7 @@ function Remove-CommonWDACConfig { # Read the current user configurations $CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" - + # If the file exists but is corrupted and has bad values, rewrite it try { $CurrentUserConfigurations = $CurrentUserConfigurations | ConvertFrom-Json diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 3f8a7cc2c..24b59665e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -119,7 +119,7 @@ function Remove-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + if (-NOT $SkipVersionCheck) { Update-self } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 16e9e92df..732074e0c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -54,7 +54,7 @@ function Set-CommonWDACConfig { begin { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 index 9a22265ef..7c9b811ca 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -14,7 +14,7 @@ Function Get-AuditEventLogsProcessing { begin { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false - + # Get the local disks mappings [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index 496e4ad26..9a086b238 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -10,7 +10,7 @@ Function Update-self { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - + try { # Get the last update check time [System.DateTime]$UserConfigDate = Get-CommonWDACConfig -LastUpdateCheck diff --git a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 index b814e97fd..d1a845f5b 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 @@ -42,13 +42,13 @@ Function Write-ColorfulText { [System.Drawing.Color]::SkyBlue, [System.Drawing.Color]::HotPink, [System.Drawing.Color]::SkyBlue, - [System.Drawing.Color]::LightSkyBlue, + [System.Drawing.Color]::LightSkyBlue, [System.Drawing.Color]::LightGreen, [System.Drawing.Color]::Coral, [System.Drawing.Color]::Plum, [System.Drawing.Color]::Gold ) - + [System.String]$Output = '' for ($I = 0; $I -lt $InputText.Length; $I++) { $Color = $Colors[$I % $Colors.Length] diff --git a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 index f4eaf06b1..9a86f5b77 100644 --- a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 @@ -176,7 +176,7 @@ To get help and syntax on PowerShell console, type: 'Core\Confirm-WDACConfig.psm1', 'Core\Edit-WDACConfig.psm1', 'Core\Edit-SignedWDACConfig.psm1', - 'Core\New-SupplementalWDACConfig.psm1', + 'Core\New-SupplementalWDACConfig.psm1', 'Core\New-DenyWDACConfig.psm1', 'Core\Set-CommonWDACConfig.psm1', 'Core\New-KernelModeWDACConfig.psm1', From 2b000013037f227ab3c4d26ff448e60d06662638 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 11:53:56 -0930 Subject: [PATCH 071/178] Removed the unused Remove-ZerosFromIDs function --- .../Other functions.ps1} | 0 .../Functions no longer in use}/Remove-ZerosFromIDs.psm1 | 0 WDACConfig/WDACConfig Module Files/WDACConfig.psd1 | 1 - 3 files changed, 1 deletion(-) rename WDACConfig/Utilities/{Functions no longer in use.ps1 => Functions no longer in use/Other functions.ps1} (100%) rename WDACConfig/{WDACConfig Module Files/Shared => Utilities/Functions no longer in use}/Remove-ZerosFromIDs.psm1 (100%) diff --git a/WDACConfig/Utilities/Functions no longer in use.ps1 b/WDACConfig/Utilities/Functions no longer in use/Other functions.ps1 similarity index 100% rename from WDACConfig/Utilities/Functions no longer in use.ps1 rename to WDACConfig/Utilities/Functions no longer in use/Other functions.ps1 diff --git a/WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 b/WDACConfig/Utilities/Functions no longer in use/Remove-ZerosFromIDs.psm1 similarity index 100% rename from WDACConfig/WDACConfig Module Files/Shared/Remove-ZerosFromIDs.psm1 rename to WDACConfig/Utilities/Functions no longer in use/Remove-ZerosFromIDs.psm1 diff --git a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 index 9a86f5b77..b67d11a7e 100644 --- a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 @@ -196,7 +196,6 @@ To get help and syntax on PowerShell console, type: 'Shared\Get-SignTool.psm1', 'Shared\Move-UserModeToKernelMode.psm1', 'Shared\New-EmptyPolicy.psm1', - 'Shared\Remove-ZerosFromIDs.psm1', 'Shared\Set-LogSize.psm1', 'Shared\Test-FilePath.psm1', 'Shared\Update-self.psm1', From b2de7b990c797622129e8f036350e26bf537c1fb Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:00:31 -0930 Subject: [PATCH 072/178] Fixed WDAC Policies path --- .../Core/New-KernelModeWDACConfig.psm1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index a80a266e4..28194ded2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -79,7 +79,7 @@ function New-KernelModeWDACConfig { begin { if ($DefaultWindowsKernel) { - $PolicyPath = "$ModuleRootPath\WDAC Policies\DefaultWindows_Enforced_Kernel.xml" + $PolicyPath = "$ModuleRootPath\Resources\WDAC Policies\DefaultWindows_Enforced_Kernel.xml" $PolicyFileName = '.\DefaultWindows_Enforced_Kernel.xml' $PolicyName = 'Strict Kernel mode policy Audit' @@ -93,7 +93,7 @@ function New-KernelModeWDACConfig { } if ($DefaultWindowsKernelNoFlights) { - $PolicyPath = "$ModuleRootPath\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml" + $PolicyPath = "$ModuleRootPath\Resources\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml" $PolicyFileName = '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' $PolicyName = 'Strict Kernel No Flights mode policy Audit' @@ -186,7 +186,7 @@ function New-KernelModeWDACConfig { } # Build the same policy again after restart, do not trust the policy xml file made before restart - Copy-Item -Path "$ModuleRootPath\WDAC Policies\DefaultWindows_Enforced_Kernel.xml" -Destination .\DefaultWindows_Enforced_Kernel.xml -Force + Copy-Item -Path "$ModuleRootPath\Resources\WDAC Policies\DefaultWindows_Enforced_Kernel.xml" -Destination .\DefaultWindows_Enforced_Kernel.xml -Force # Merge the base policy with the policy made from driver files to deploy it as one Merge-CIPolicy -PolicyPaths '.\DefaultWindows_Enforced_Kernel.xml', '.\DriverFilesScanPolicy.xml' -OutputFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null @@ -284,7 +284,7 @@ function New-KernelModeWDACConfig { } # Build the same policy again after restart, do not trust the policy xml file made before restart - Copy-Item -Path "$ModuleRootPath\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml" -Destination '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' -Force + Copy-Item -Path "$ModuleRootPath\Resources\WDAC Policies\DefaultWindows_Enforced_Kernel_NoFlights.xml" -Destination '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' -Force # Merge the base policy with the policy made from driver files to deploy it as one Merge-CIPolicy -PolicyPaths '.\DefaultWindows_Enforced_Kernel_NoFlights.xml', '.\DriverFilesScanPolicy.xml' -OutputFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null From 41626d5550e88fe0d35f086241d89af4553dfa4b Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:07:01 -0930 Subject: [PATCH 073/178] Improved New-KernelModeWDACConfig cmdlet --- .../Core/New-KernelModeWDACConfig.psm1 | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 28194ded2..6c0fda47c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -44,8 +44,12 @@ function New-KernelModeWDACConfig { Write-Error -Message 'You must specify either -PrepMode or -AuditAndEnforce, but not both.' -Category InvalidArgument } - # Function to swap GUIDs in a WDAC policy XML file - function Edit-GUIDs { + # + Function Edit-GUIDs { + <# + .SYNOPSIS + Function to swap GUIDs in a WDAC policy XML file + #> param( [System.String]$PolicyIDInput, [System.String]$PolicyFilePathInput @@ -68,8 +72,11 @@ function New-KernelModeWDACConfig { $xml.Save($PolicyFilePathInput) } - # Function to build Audit mode policy only - function Build-PrepModeStrictKernelPolicy { + Function Build-PrepModeStrictKernelPolicy { + <# + .SYNOPSIS + Function to build Audit mode policy only + #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$DefaultWindowsKernel, @@ -152,8 +159,8 @@ function New-KernelModeWDACConfig { Write-ColorfulText -Color HotPink -InputText 'Strict Kernel mode policy has been deployed in Audit mode, please restart your system.' # Clear Code Integrity operational before system restart so that after boot it will only have the correct and new logs - wevtutil cl 'Microsoft-Windows-CodeIntegrity/Operational' - wevtutil cl 'Microsoft-Windows-AppLocker/MSI and Script' + &'C:\Windows\System32\wevtutil.exe' cl 'Microsoft-Windows-CodeIntegrity/Operational' + &'C:\Windows\System32\wevtutil.exe' cl 'Microsoft-Windows-AppLocker/MSI and Script' if (!$Debug) { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel.xml', ".\$PolicyID.cip" -Force -ErrorAction SilentlyContinue @@ -250,8 +257,8 @@ function New-KernelModeWDACConfig { Write-ColorfulText -Color HotPink -InputText 'Strict Kernel mode policy with no flighting root certs has been deployed in Audit mode, please restart your system.' # Clear Code Integrity operational before system restart so that after boot it will only have the correct and new logs - wevtutil cl 'Microsoft-Windows-CodeIntegrity/Operational' - wevtutil cl 'Microsoft-Windows-AppLocker/MSI and Script' + &'C:\Windows\System32\wevtutil.exe' cl 'Microsoft-Windows-CodeIntegrity/Operational' + &'C:\Windows\System32\wevtutil.exe' cl 'Microsoft-Windows-AppLocker/MSI and Script' if (!$Debug) { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel_NoFlights.xml', ".\$PolicyID.cip" -Force -ErrorAction SilentlyContinue From 38fdd5fce218c2f372d62d0e8aefa85b49593630 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:14:05 -0930 Subject: [PATCH 074/178] CiTool path explicit definition --- .../Core/Confirm-WDACConfig.psm1 | 4 ++-- .../Core/Deploy-SignedWDACConfig.psm1 | 2 +- .../Core/Edit-SignedWDACConfig.psm1 | 24 +++++++++---------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 6890c4d85..cae2f65c1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -78,13 +78,13 @@ function Confirm-WDACConfig { # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { - [System.Object[]]$BasePolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID } + [System.Object[]]$BasePolicies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID } Write-ColorfulText -Color Lavender -InputText "`nThere are currently $(($BasePolicies.count)) Non-system Base policies deployed" $BasePolicies } # Script block to show only non-system Supplemental policies [System.Management.Automation.ScriptBlock]$OnlySupplementalPoliciesBLOCK = { - [System.Object[]]$SupplementalPolicies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -ne $_.BasePolicyID } + [System.Object[]]$SupplementalPolicies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -ne $_.BasePolicyID } Write-ColorfulText -Color Lavender -InputText "`nThere are currently $(($SupplementalPolicies.count)) Non-system Supplemental policies deployed`n" $SupplementalPolicies } diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 299b1d5ce..9cad78abf 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -155,7 +155,7 @@ function Deploy-SignedWDACConfig { if ($Deploy) { - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index cd77de518..0f02c6a03 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -51,7 +51,7 @@ function Edit-SignedWDACConfig { $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } + $CurrentPolicyIDs = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if ($RedFlag1 -or $RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { @@ -217,7 +217,7 @@ function Edit-SignedWDACConfig { # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname + $BasePolicyNamez = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname return [System.String[]]$BasePolicyNamez } } @@ -241,7 +241,7 @@ function Edit-SignedWDACConfig { #Re-Deploy Basepolicy in Enforced mode function Update-BasePolicyToEnforced { # Deploy Enforced mode CIP - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -326,7 +326,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -614,7 +614,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" @@ -691,7 +691,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -824,7 +824,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" @@ -840,7 +840,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + $DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies if ($SupplementalPolicyType -ne 'Supplemental Policy') { Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." @@ -856,7 +856,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID - Citool --remove-policy $SupplementalPolicyID -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } } @@ -882,7 +882,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force } @@ -945,7 +945,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Get the policy ID of the currently deployed base policy based on the policy name that user selected - $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID + $CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Remove-Item -Path ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue @@ -976,7 +976,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$CurrentID.cip" -Force Rename-Item -Path "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force # Deploy the new base policy with the same GUID on the system - CiTool --update-policy "$CurrentID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later $PolicyFiles = @{ 'AllowMicrosoft_Plus_Block_Rules' = 'AllowMicrosoftPlusBlockRules.xml' From 9c0ed357360adfc041587fdf13c3681e4d38e028 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:16:44 -0930 Subject: [PATCH 075/178] CiTool Path explicit definition --- .../Core/Edit-WDACConfig.psm1 | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index c06cb24ac..67c43216c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -30,7 +30,7 @@ function Edit-WDACConfig { $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId $RedFlag3 = $xmlTest.SiPolicy.PolicyID - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } + $CurrentPolicyIDs = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if (!$RedFlag1 -and !$RedFlag2) { # Ensure the selected base policy xml file is deployed if ($CurrentPolicyIDs -contains $RedFlag3) { @@ -152,7 +152,7 @@ function Edit-WDACConfig { # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $BasePolicyNamez = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname + $BasePolicyNamez = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.PolicyID -eq $_.BasePolicyID }).Friendlyname return [System.String[]]$BasePolicyNamez } @@ -177,7 +177,7 @@ function Edit-WDACConfig { # Redeploy the base policy in Enforced mode function Update-BasePolicyToEnforced { # Deploy Enforced mode CIP - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -256,7 +256,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -380,7 +380,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" @@ -439,7 +439,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Audit mode CIP Write-Debug -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -711,7 +711,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - CiTool --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" @@ -727,7 +727,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (CiTool -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + $DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies if ($SupplementalPolicyType -ne 'Supplemental Policy') { Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." @@ -743,7 +743,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID - Citool --remove-policy $SupplementalPolicyID -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy $SupplementalPolicyID -json | Out-Null # remove the old policy files unless user chose to keep them if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } } @@ -752,7 +752,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $SuppPolicyID = $SuppPolicyID.Substring(11) Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - CiTool --update-policy "$SuppPolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force } @@ -807,7 +807,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force # Get the policy ID of the currently deployed base policy based on the policy name that user selected - $CurrentID = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID + $CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Write-Debug -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' @@ -816,7 +816,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $xml.Save('.\BasePolicy.xml') ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null # Deploy the new base policy with the same GUID on the system - CiTool --update-policy "$CurrentID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null # Remove the policy binary after it's been deployed Remove-Item -Path "$CurrentID.cip" -Force From 7305fa5d4d204dcbc02cde235772f1bfbca4b017 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:22:54 -0930 Subject: [PATCH 076/178] CiTool path explicit definition --- .../Core/New-DenyWDACConfig.psm1 | 6 ++--- .../Core/New-KernelModeWDACConfig.psm1 | 16 ++++++------- .../Core/New-SupplementalWDACConfig.psm1 | 6 ++--- .../Core/New-WDACConfig.psm1 | 24 +++++++++---------- .../Core/Remove-WDACConfig.psm1 | 22 ++++++++--------- 5 files changed, 37 insertions(+), 37 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 241d22cdb..0ec907684 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -149,7 +149,7 @@ function New-DenyWDACConfig { } if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta Write-Host -Object ' has been deployed.' -ForegroundColor Green @@ -204,7 +204,7 @@ function New-DenyWDACConfig { DenyPolicyGUID = $PolicyID } if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta Write-Host -Object ' has been deployed.' -ForegroundColor Green @@ -260,7 +260,7 @@ function New-DenyWDACConfig { } if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 6c0fda47c..d06b54594 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -95,7 +95,7 @@ function New-KernelModeWDACConfig { If ($CurrentStrictKernelPolicyGUID) { # Check if the pending Audit mode Kernel mode WDAC policy is deployed on the system - [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelPolicyGUID }).policyID + [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelPolicyGUID }).policyID } } @@ -109,7 +109,7 @@ function New-KernelModeWDACConfig { If ($CurrentStrictKernelNoFlightRootsPolicyGUID) { # Check if the pending Audit mode Kernel mode WDAC No Flight Roots policy is deployed on the system - [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelNoFlightRootsPolicyGUID }).policyID + [System.String]$CurrentStrictKernelPolicyGUIDConfirmation = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.PolicyID -eq $CurrentStrictKernelNoFlightRootsPolicyGUID }).policyID } } @@ -155,7 +155,7 @@ function New-KernelModeWDACConfig { # Set the GUID of the Audit mode policy in the User Configuration file Set-CommonWDACConfig -StrictKernelPolicyGUID $PolicyID | Out-Null - CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color HotPink -InputText 'Strict Kernel mode policy has been deployed in Audit mode, please restart your system.' # Clear Code Integrity operational before system restart so that after boot it will only have the correct and new logs @@ -221,7 +221,7 @@ function New-KernelModeWDACConfig { # Deploy the policy if Deploy parameter is used if ($Deploy) { ConvertFrom-CIPolicy -XmlFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null - CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText 'Strict Kernel mode policy has been deployed in Enforced mode, no restart required.' # Delete its GUID from User Configurations @@ -231,7 +231,7 @@ function New-KernelModeWDACConfig { # Remove the Audit mode policy from the system # This step is necessary if user didn't use the -Deploy parameter # And instead wants to first Sign and then deploy it using the Deploy-SignedWDACConfig cmdlet - CiTool.exe --remove-policy "{$PolicyID}" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy "{$PolicyID}" -json | Out-Null Write-ColorfulText -Color Pink -InputText 'Strict Kernel mode Enforced policy has been created in the current working directory.' } if (!$Debug) { @@ -253,7 +253,7 @@ function New-KernelModeWDACConfig { if ($Deploy) { # Set the GUID of the Audit mode policy in the User Configuration file Set-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID $PolicyID | Out-Null - CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color HotPink -InputText 'Strict Kernel mode policy with no flighting root certs has been deployed in Audit mode, please restart your system.' # Clear Code Integrity operational before system restart so that after boot it will only have the correct and new logs @@ -319,7 +319,7 @@ function New-KernelModeWDACConfig { # Deploy the policy if Deploy parameter is used if ($Deploy) { ConvertFrom-CIPolicy -XmlFilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null - CiTool.exe --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText 'Strict Kernel mode policy with no flighting root certs has been deployed in Enforced mode, no restart required.' # Delete its GUID from User Configurations @@ -329,7 +329,7 @@ function New-KernelModeWDACConfig { # Remove the Audit mode policy from the system # This step is necessary if user didn't use the -Deploy parameter # And instead wants to first Sign and then deploy it using the Deploy-SignedWDACConfig cmdlet - CiTool.exe --remove-policy "{$PolicyID}" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy "{$PolicyID}" -json | Out-Null Write-ColorfulText -Color Pink -InputText 'Strict Kernel mode Enforced policy with no flighting root certs has been created in the current working directory.' } if (!$Debug) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 0232e9717..c8afedf83 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -161,7 +161,7 @@ function New-SupplementalWDACConfig { SupplementalPolicyGUID = $PolicyID } if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force } @@ -196,7 +196,7 @@ function New-SupplementalWDACConfig { } if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force } @@ -252,7 +252,7 @@ function New-SupplementalWDACConfig { } if ($Deploy) { - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." Remove-Item -Path "$policyID.cip" -Force } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 6e8e047af..88feecd6b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -183,7 +183,7 @@ function New-WDACConfig { BinaryFile = "$PolicyID.cip" } if ($Deploy -and $MakeAllowMSFTWithBlockRules) { - CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } @@ -255,7 +255,7 @@ function New-WDACConfig { } if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { - CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } @@ -267,7 +267,7 @@ function New-WDACConfig { Expand-Archive -Path .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force Rename-Item -Path .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force Copy-Item -Path .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' - citool --refresh -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --refresh -json | Out-Null Write-ColorfulText -Color Pink -InputText 'SiPolicy.p7b has been deployed and policies refreshed.' Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK @@ -284,7 +284,7 @@ function New-WDACConfig { [System.String]$PolicyID = (Set-CIPolicyIdInfo -FilePath '.\Microsoft recommended block rules.xml' -ResetPolicyID).Substring(11) Set-CIPolicyIdInfo -PolicyName "Microsoft Windows User Mode Policy - Enforced - $(Get-Date -Format 'MM-dd-yyyy')" -FilePath '.\Microsoft recommended block rules.xml' ConvertFrom-CIPolicy -XmlFilePath '.\Microsoft recommended block rules.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null - CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Lavender -InputText 'The Microsoft recommended block rules policy has been deployed in enforced mode.' Remove-Item -Path "$PolicyID.cip" -Force } @@ -319,7 +319,7 @@ function New-WDACConfig { Set-CIPolicyIdInfo -PolicyName 'PrepMSFTOnlyAudit' -FilePath .\AllowMicrosoft.xml ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoft.xml -BinaryFilePath "$PolicyID.cip" | Out-Null if ($Deploy) { - CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color HotPink -InputText 'The default AllowMicrosoft policy has been deployed in Audit mode. No reboot required.' Remove-Item -Path 'AllowMicrosoft.xml', "$PolicyID.cip" -Force } @@ -351,7 +351,7 @@ function New-WDACConfig { Set-CIPolicyIdInfo -PolicyName 'PrepDefaultWindows' -FilePath .\DefaultWindows_Audit.xml ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Audit.xml -BinaryFilePath "$PolicyID.cip" | Out-Null if ($Deploy) { - CiTool --update-policy "$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Lavender -InputText 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' Remove-Item -Path 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force } @@ -486,19 +486,19 @@ function New-WDACConfig { } if ($Deploy -and $MakePolicyFromAuditLogs) { - CiTool --update-policy "$BasePolicyID.cip" -json | Out-Null - CiTool --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "`nBase policy and Supplemental Policies deployed and activated.`n" # Get the correct Prep mode Audit policy ID to remove from the system switch ($BasePolicyType) { 'Allow Microsoft Base' { - $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepMSFTOnlyAudit' }).PolicyID + $IDToRemove = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepMSFTOnlyAudit' }).PolicyID } 'Default Windows Base' { - $IDToRemove = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepDefaultWindows' }).PolicyID + $IDToRemove = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepDefaultWindows' }).PolicyID } } - CiTool --remove-policy "{$IDToRemove}" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy "{$IDToRemove}" -json | Out-Null Write-ColorfulText -Color Lavender -InputText "`nSystem restart required to finish removing the Audit mode Prep policy" } } @@ -524,7 +524,7 @@ function New-WDACConfig { Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow if ($Deploy -and $MakeLightPolicy) { - CiTool --update-policy "$BasePolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null } [PSCustomObject]@{ BasePolicyFile = 'SignedAndReputable.xml' diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 24b59665e..68b0c7255 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -41,7 +41,7 @@ function Remove-WDACConfig { # Get a list of policies using the CiTool, excluding system policies and policies that aren't on disk. # by adding "| Where-Object -FilterScript { $_.FriendlyName }" we make sure the auto completion works when at least one of the policies doesn't have a friendly name - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.FriendlyName } + $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.FriendlyName } # Create a hashtable mapping policy names to policy IDs. This will be used later to check if a policy ID already exists. $NameIDMap = @{} @@ -81,7 +81,7 @@ function Remove-WDACConfig { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Get a list of policies using the CiTool, excluding system policies and policies that aren't on disk. - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } + $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } # Create a hashtable mapping policy IDs to policy names. This will be used later to check if a policy name already exists. $IDNameMap = @{} foreach ($policy in $policies) { @@ -171,7 +171,7 @@ function Remove-WDACConfig { # ValidateSet for Policy names Class PolicyNamezx : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $PolicyNamezx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).Friendlyname | Select-Object -Unique + $PolicyNamezx = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).Friendlyname | Select-Object -Unique return [System.String[]]$PolicyNamezx } } @@ -179,7 +179,7 @@ function Remove-WDACConfig { # ValidateSet for Policy IDs Class PolicyIDzx : System.Management.Automation.IValidateSetValuesGenerator { [System.String[]] GetValidValues() { - $PolicyIDzx = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID + $PolicyIDzx = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID return [System.String[]]$PolicyIDzx } @@ -194,7 +194,7 @@ function Remove-WDACConfig { # Defines a method to get valid policy names from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } + $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$IDNameMap = @{} foreach ($policy in $policies) { self::$IDNameMap[$policy.policyID] = $policy.Friendlyname @@ -216,7 +216,7 @@ function Remove-WDACConfig { # Defines a method to get valid policy IDs from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { - $policies = (CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } + $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$NameIDMap = @{} foreach ($policy in $policies) { self::$NameIDMap[$policy.Friendlyname] = $policy.policyID @@ -239,7 +239,7 @@ function Remove-WDACConfig { $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system - $CurrentPolicyIDs = ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } + $CurrentPolicyIDs = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } Write-Debug -Message "The policy ID of the currently processing xml file is $PolicyID" if ($CurrentPolicyIDs -notcontains $PolicyID) { Write-Error -Message "The selected policy file isn't deployed on the system." -ErrorAction Stop @@ -285,7 +285,7 @@ function Remove-WDACConfig { Remove-Item -Path ".\$PolicyID.cip" -Force Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force - CiTool --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-Host -Object "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" @@ -296,7 +296,7 @@ function Remove-WDACConfig { # If IDs were supplied by user foreach ($ID in $PolicyIDs ) { - citool --remove-policy "{$ID}" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy "{$ID}" -json | Out-Null Write-Host -Object "Policy with the ID $ID has been successfully removed." -ForegroundColor Green } @@ -304,14 +304,14 @@ function Remove-WDACConfig { # Empty array to store Policy IDs based on the input name, this will take care of the situations where multiple policies with the same name are deployed [System.Object[]]$NameID = @() foreach ($PolicyName in $PolicyNames) { - $NameID += ((CiTool -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.FriendlyName -eq $PolicyName }).PolicyID + $NameID += ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.FriendlyName -eq $PolicyName }).PolicyID } Write-Debug -Message 'The Following policy IDs have been gathered from the supplied policy names and are going to be removed from the system' if ($Debug) { $NameID | Select-Object -Unique | ForEach-Object -Process { Write-Debug -Message "$_" } } $NameID | Select-Object -Unique | ForEach-Object -Process { - citool --remove-policy "{$_}" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --remove-policy "{$_}" -json | Out-Null Write-Host -Object "Policy with the ID $_ has been successfully removed." -ForegroundColor Green } } From 9f3bc8aac7291d9c824f5017e6c999f04de83894 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:23:58 -0930 Subject: [PATCH 077/178] Update New-KernelModeWDACConfig.psm1 --- .../WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index d06b54594..f3b3ac83f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -44,7 +44,7 @@ function New-KernelModeWDACConfig { Write-Error -Message 'You must specify either -PrepMode or -AuditAndEnforce, but not both.' -Category InvalidArgument } - # + # Function Edit-GUIDs { <# .SYNOPSIS From 3a44375a8c0db80b589d6a459080b2fc49f8801d Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:24:23 -0930 Subject: [PATCH 078/178] Update New-KernelModeWDACConfig.psm1 --- .../WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 | 1 - 1 file changed, 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index f3b3ac83f..adbcd083d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -44,7 +44,6 @@ function New-KernelModeWDACConfig { Write-Error -Message 'You must specify either -PrepMode or -AuditAndEnforce, but not both.' -Category InvalidArgument } - # Function Edit-GUIDs { <# .SYNOPSIS From a61959d584a44831d1398e59c7109ffbed1b1de7 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 12:36:25 -0930 Subject: [PATCH 079/178] Changed some debug messages to verbose --- .../Core/Edit-SignedWDACConfig.psm1 | 38 +++++++++--------- .../Core/Edit-WDACConfig.psm1 | 40 +++++++++---------- .../Core/New-KernelModeWDACConfig.psm1 | 4 +- 3 files changed, 41 insertions(+), 41 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 0f02c6a03..03785611e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -314,7 +314,7 @@ function Edit-SignedWDACConfig { Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# - Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' + Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" @@ -324,7 +324,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null # Deploy Audit mode CIP - Write-Debug -Message 'Deploying Audit mode CIP' + Write-Verbose -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" @@ -383,7 +383,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # this prevents duplicate rule creation and double file copying $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique - Write-Debug -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." + Write-Verbose -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." # Another check to make sure there were indeed files found in Event viewer logs but weren't in any of the user-selected path(s) if ($TestFilePathResults) { @@ -391,9 +391,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # but detected in Event viewer audit logs, scan that folder, and in the end delete it New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null - Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" + Write-Verbose -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" $TestFilePathResults | ForEach-Object -Process { - Write-Debug -Message "$_" + Write-Verbose -Message "$_" Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue } @@ -428,9 +428,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # if user chose to include deleted files in the final supplemental policy if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { - Write-Debug -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" + Write-Verbose -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { - Write-Debug -Message "$($_.'File Name')" + Write-Verbose -Message "$($_.'File Name')" } # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes @@ -501,8 +501,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { - Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" - if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message "The following Kernel protected files detected, creating allow rules for them:`n" + $ExesWithNoHash | ForEach-Object -Process { Write-Verbose -Message "$_" } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { @@ -548,8 +548,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation - Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' + $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -577,10 +577,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } finally { # Deploy Enforced mode CIP - Write-Debug -Message 'Finally Block Running' + Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced - Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' + Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } @@ -679,7 +679,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# - Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' + Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" @@ -689,7 +689,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null # Deploy Audit mode CIP - Write-Debug -Message 'Deploying Audit mode CIP' + Write-Verbose -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" @@ -746,10 +746,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } finally { # Deploy Enforced mode CIP - Write-Debug -Message 'Finally Block Running' + Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced - Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' + Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } @@ -787,8 +787,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyXMLFilesArray += $file.FullName } - Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' + $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 67c43216c..ab7502213 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -223,7 +223,7 @@ function Edit-WDACConfig { ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null ################# Snap back guarantee ################# - Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' + Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' <# # CMD and Scheduled Task Method @@ -254,7 +254,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null # Deploy Audit mode CIP - Write-Debug -Message 'Deploying Audit mode CIP' + Write-Verbose -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" @@ -311,11 +311,11 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } finally { # Deploy Enforced mode CIP - Write-Debug -Message 'Finally Block Running' + Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced - Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' + Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' # For PowerShell Method Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force @@ -359,8 +359,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyXMLFilesArray += $file.FullName } - Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' + $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -427,7 +427,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null ################# Snap back guarantee ################# - Write-Debug -Message 'Creating Enforced Mode SnapBack guarantee' + Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' $command = @" @@ -437,7 +437,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null # Deploy Audit mode CIP - Write-Debug -Message 'Deploying Audit mode CIP' + Write-Verbose -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" @@ -496,7 +496,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # this prevents duplicate rule creation and double file copying $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique - Write-Debug -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." + Write-Verbose -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." # Another check to make sure there were indeed files found in Event viewer logs but weren't in any of the user-selected path(s) if ($TestFilePathResults) { @@ -504,9 +504,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # but detected in Event viewer audit logs, scan that folder, and in the end delete it New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null - Write-Debug -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" + Write-Verbose -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" $TestFilePathResults | ForEach-Object -Process { - Write-Debug -Message "$_" + Write-Verbose -Message "$_" Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue } @@ -541,9 +541,9 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # if user chose to include deleted files in the final supplemental policy if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { - Write-Debug -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" + Write-Verbose -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { - Write-Debug -Message "$($_.'File Name')" + Write-Verbose -Message "$($_.'File Name')" } # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes @@ -614,8 +614,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { - Write-Debug -Message "The following Kernel protected files detected, creating allow rules for them:`n" - if ($Debug) { $ExesWithNoHash | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message "The following Kernel protected files detected, creating allow rules for them:`n" + $ExesWithNoHash | ForEach-Object -Process { Write-Verbose -Message "$_" } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { @@ -661,8 +661,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation - Write-Debug -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - if ($Debug) { $PolicyXMLFilesArray | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' + $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null @@ -690,10 +690,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } finally { # Deploy Enforced mode CIP - Write-Debug -Message 'Finally Block Running' + Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced # Enforced Mode Snapback removal after base policy has already been successfully re-enforced - Write-Debug -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' + Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } @@ -809,7 +809,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Get the policy ID of the currently deployed base policy based on the policy name that user selected $CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" - Write-Debug -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" + Write-Verbose -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' $xml.SiPolicy.PolicyID = $CurrentID $xml.SiPolicy.BasePolicyID = $CurrentID diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index adbcd083d..e3c7c3faa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -178,7 +178,7 @@ function New-KernelModeWDACConfig { # Verify the Policy ID in the User Config exists and is valid $ObjectGuid = [System.Guid]::Empty if ([System.Guid]::TryParse($PolicyID, [ref]$ObjectGuid)) { - Write-Debug -Message 'Valid GUID found in User Configs for Audit mode policy' + Write-Verbose -Message 'Valid GUID found in User Configs for Audit mode policy' } else { Write-Error -Message 'Invalid or nonexistent GUID in User Configs for Audit mode policy, Use the -PrepMode parameter first.' @@ -276,7 +276,7 @@ function New-KernelModeWDACConfig { # Verify the Policy ID in the User Config exists and is valid $ObjectGuid = [System.Guid]::Empty if ([System.Guid]::TryParse($PolicyID, [ref]$ObjectGuid)) { - Write-Debug -Message 'Valid GUID found in User Configs for Audit mode policy' + Write-Verbose -Message 'Valid GUID found in User Configs for Audit mode policy' } else { Write-Error -Message 'Invalid or nonexistent GUID in User Configs for Audit mode policy, Use the -PrepMode parameter first.' From f3a5d9bd4966f705511ea3ed2eac5fa2c0ed41f1 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 23:16:43 -0930 Subject: [PATCH 080/178] Improved verbose messages of Remove-WDACConfig --- .../Core/Remove-WDACConfig.psm1 | 64 ++++++++++++++----- 1 file changed, 49 insertions(+), 15 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 68b0c7255..3026cb0d0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -121,10 +121,14 @@ function Remove-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false if (-NOT $SkipVersionCheck) { Update-self } - # Detecting if Debug switch is used, will do debugging actions based on that - $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null + + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null #region User-Configurations-Processing-Validation + + Write-Verbose -Message 'Validating and processing user configurations' + if ($PSCmdlet.ParameterSetName -eq 'Signed Base') { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertCN) { @@ -162,7 +166,7 @@ function Remove-WDACConfig { } } else { - throw "CertCN parameter can't be empty and no valid configuration was found for it." + throw 'CertCN parameter cannot be empty and no valid configuration was found for it.' } } } @@ -233,42 +237,63 @@ function Remove-WDACConfig { } process { - + # If a signed policy is being removed if ($SignedBase) { + + Write-Verbose -Message 'Looping over each selected policy XML file' foreach ($PolicyPath in $PolicyPaths) { + + # Convert the XML file into an XML object + Write-Verbose -Message 'Converting the XML file to an XML object' $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyID = $xml.SiPolicy.PolicyID + + # Extract the Policy ID from the XML object + Write-Verbose -Message 'Extracting the Policy ID from the XML object' + [System.String]$PolicyID = $xml.SiPolicy.PolicyID + Write-Verbose -Message "The policy ID of the currently processing xml file is $PolicyID" + # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system + Write-Verbose -Message 'Making sure the selected XML policy is deployed on the system' $CurrentPolicyIDs = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } - Write-Debug -Message "The policy ID of the currently processing xml file is $PolicyID" if ($CurrentPolicyIDs -notcontains $PolicyID) { - Write-Error -Message "The selected policy file isn't deployed on the system." -ErrorAction Stop + Throw 'The selected policy file is not deployed on the system.' } - ######################## Sanitize the policy file by removing SupplementalPolicySigners ######################## + # Sanitize the policy file by removing SupplementalPolicySigners from it + Write-Verbose -Message 'Sanitizing the XML policy file by removing SupplementalPolicySigners from it' + + # Extracting the SupplementalPolicySigner ID from the selected XML policy file, if any $SuppSingerIDs = $xml.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + # Extracting the policy name from the selected XML policy file $PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + if ($SuppSingerIDs) { - Write-Debug -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." + Write-Verbose -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." + + # Looping over each SupplementalPolicySigner and removing it $SuppSingerIDs | ForEach-Object -Process { $PolContent = Get-Content -Path -Raw -Path $PolicyPath $PolContent -match "" | Out-Null $PolContent = $PolContent -replace $Matches[0], '' Set-Content -Value $PolContent -Path $PolicyPath } + + # Removing the Supplemental policy signers block from the XML file $PolContent -match '[\S\s]*' | Out-Null $PolContent = $PolContent -replace $Matches[0], '' Set-Content -Value $PolContent -Path $PolicyPath - # remove empty lines from the entire policy file + # Remove empty lines from the entire policy file (Get-Content -Path $PolicyPath) | Where-Object -FilterScript { $_.trim() -ne '' } | Set-Content -Path $PolicyPath -Force - Write-Debug -Message 'Policy successfully sanitized and all SupplementalPolicySigners have been removed.' + Write-Verbose -Message 'Policy successfully sanitized and all SupplementalPolicySigners have been removed.' } else { - Write-Debug -Message "`nNo sanitization required because no SupplementalPolicySigners have been found in $PolicyName policy." + Write-Verbose -Message "`nNo sanitization required because no SupplementalPolicySigners have been found in $PolicyName policy." } + # Adding policy rule option "Unsigned System Integrity Policy" to the selected XML policy file Set-RuleOption -FilePath $PolicyPath -Option 6 + # Converting the Policy XML file to CIP binary file ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath "$PolicyID.cip" | Out-Null # Configure the parameter splat @@ -279,19 +304,28 @@ function Remove-WDACConfig { 'Wait' = $true 'ErrorAction' = 'Stop' } - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Write-Verbose -Message 'Signing the new CIP binary' Start-Process @ProcessParams + # Removing the unsigned CIP file Remove-Item -Path ".\$PolicyID.cip" -Force + # Fixing the extension name of the newly signed CIP file Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force + + # Deploying the newly signed CIP file + Write-Verbose -Message 'Deploying the newly signed CIP file' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + Write-Host -Object "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" } } + # If an unsigned policy is being removed if ($UnsignedOrSupplemental) { # If IDs were supplied by user @@ -307,8 +341,8 @@ function Remove-WDACConfig { $NameID += ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.FriendlyName -eq $PolicyName }).PolicyID } - Write-Debug -Message 'The Following policy IDs have been gathered from the supplied policy names and are going to be removed from the system' - if ($Debug) { $NameID | Select-Object -Unique | ForEach-Object -Process { Write-Debug -Message "$_" } } + Write-Verbose -Message 'The Following policy IDs have been gathered from the supplied policy names and are going to be removed from the system' + $NameID | Select-Object -Unique | ForEach-Object -Process { Write-Verbose -Message "$_" } $NameID | Select-Object -Unique | ForEach-Object -Process { &'C:\Windows\System32\CiTool.exe' --remove-policy "{$_}" -json | Out-Null From 536660e8fab9051a53f20411ce2de791c0a3d85d Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 23:19:04 -0930 Subject: [PATCH 081/178] Added function help info --- .../WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 3026cb0d0..fbaead7e5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -376,6 +376,12 @@ function Remove-WDACConfig { .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases +.INPUTS + System.String + System.String[] + +.OUTPUTS + System.String #> } From 53bca33bc3c61bbc30a69f8bb7290357a50dbcd6 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 23:21:57 -0930 Subject: [PATCH 082/178] Added verbose messages to the entire module for module imports --- .../WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 | 1 + .../Core/Deploy-SignedWDACConfig.psm1 | 1 + .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 1 + WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 1 + .../WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 | 1 + .../WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 | 1 + .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 1 + .../Core/New-KernelModeWDACConfig.psm1 | 1 + .../Core/New-SupplementalWDACConfig.psm1 | 1 + WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 1 + .../WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 1 + .../WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 | 5 +++-- 12 files changed, 14 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index cae2f65c1..8681bfc58 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -64,6 +64,7 @@ function Confirm-WDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 9cad78abf..5b1ff093a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -31,6 +31,7 @@ function Deploy-SignedWDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 03785611e..433ecbfa8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -118,6 +118,7 @@ function Edit-SignedWDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index ab7502213..67fcc41c1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -98,6 +98,7 @@ function Edit-WDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 4df6aa09c..aab6b847c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -13,6 +13,7 @@ function Get-CommonWDACConfig { ) begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false # Create User configuration folder if it doesn't already exist diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index d2a107b2f..378c1fa48 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -18,6 +18,7 @@ function Invoke-WDACSimulation { . "$ModuleRootPath\Resources\Resources2.ps1" # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 0ec907684..b435a1995 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -54,6 +54,7 @@ function New-DenyWDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index e3c7c3faa..68c25a3f4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -29,6 +29,7 @@ function New-KernelModeWDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Move-UserModeToKernelMode.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index c8afedf83..b70a89e33 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -60,6 +60,7 @@ function New-SupplementalWDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 88feecd6b..325d304ce 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -82,6 +82,7 @@ function New-WDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index fbaead7e5..a6ba61d47 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -115,6 +115,7 @@ function Remove-WDACConfig { begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 732074e0c..3a7816ec8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -53,18 +53,19 @@ function Set-CommonWDACConfig { ) begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null - Write-Debug -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." + Write-Verbose -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." } # Create User configuration file if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null - Write-Debug -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." + Write-Verbose -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." } if ($PSBoundParameters.Count -eq 0) { From 7f0e384ac78084a5c5728758830ff46879f4d9df Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 23:38:29 -0930 Subject: [PATCH 083/178] Improved verbosity of Set-CommonWDACConfig --- .../Core/Set-CommonWDACConfig.psm1 | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 3a7816ec8..b9e5193ea 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -69,17 +69,19 @@ function Set-CommonWDACConfig { } if ($PSBoundParameters.Count -eq 0) { - Write-Error -Message 'No parameter was selected.' - break + Throw 'No parameter was selected.' } - # Read the current user configurations - $CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + # Trying to read the current user configurations + Write-Verbose -Message 'Trying to read the current user configurations' + [System.Object[]]$CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + # If the file exists but is corrupted and has bad values, rewrite it try { $CurrentUserConfigurations = $CurrentUserConfigurations | ConvertFrom-Json } catch { + Write-Verbose -Message 'The user configurations file exists but is corrupted and has bad values, rewriting it' Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -Value '' } @@ -97,66 +99,87 @@ function Set-CommonWDACConfig { } process { + Write-Verbose -Message 'Processing each user configuration property' + if ($SignedPolicyPath) { + Write-Verbose -Message 'Saving the supplied Signed Policy path in user configurations.' $UserConfigurationsObject.SignedPolicyPath = $SignedPolicyPath } else { + Write-Verbose -Message 'No changes to the Signed Policy path property was detected.' $UserConfigurationsObject.SignedPolicyPath = $CurrentUserConfigurations.SignedPolicyPath } if ($UnsignedPolicyPath) { + Write-Verbose -Message 'Saving the supplied Unsigned Policy path in user configurations.' $UserConfigurationsObject.UnsignedPolicyPath = $UnsignedPolicyPath } else { + Write-Verbose -Message 'No changes to the Unsigned Policy path property was detected.' $UserConfigurationsObject.UnsignedPolicyPath = $CurrentUserConfigurations.UnsignedPolicyPath } if ($SignToolPath) { + Write-Verbose -Message 'Saving the supplied SignTool path in user configurations.' $UserConfigurationsObject.SignToolCustomPath = $SignToolPath } else { + Write-Verbose -Message 'No changes to the Signtool path property was detected.' $UserConfigurationsObject.SignToolCustomPath = $CurrentUserConfigurations.SignToolCustomPath } if ($CertPath) { + Write-Verbose -Message 'Saving the supplied Certificate path in user configurations.' $UserConfigurationsObject.CertificatePath = $CertPath } else { + Write-Verbose -Message 'No changes to the Certificate path property was detected.' $UserConfigurationsObject.CertificatePath = $CurrentUserConfigurations.CertificatePath } if ($CertCN) { + Write-Verbose -Message 'Saving the supplied Certificate common name in user configurations.' $UserConfigurationsObject.CertificateCommonName = $CertCN } else { + Write-Verbose -Message 'No changes to the Certificate common name property was detected.' $UserConfigurationsObject.CertificateCommonName = $CurrentUserConfigurations.CertificateCommonName } if ($StrictKernelPolicyGUID) { + Write-Verbose -Message 'Saving the supplied Strict Kernel policy GUID in user configurations.' $UserConfigurationsObject.StrictKernelPolicyGUID = $StrictKernelPolicyGUID } else { + Write-Verbose -Message 'No changes to the Strict Kernel policy GUID property was detected.' $UserConfigurationsObject.StrictKernelPolicyGUID = $CurrentUserConfigurations.StrictKernelPolicyGUID } if ($StrictKernelNoFlightRootsPolicyGUID) { + Write-Verbose -Message 'Saving the supplied Strict Kernel NoFlightRoot policy GUID in user configurations.' $UserConfigurationsObject.StrictKernelNoFlightRootsPolicyGUID = $StrictKernelNoFlightRootsPolicyGUID } else { + Write-Verbose -Message 'No changes to the Strict Kernel NoFlightRoot policy GUID property was detected.' $UserConfigurationsObject.StrictKernelNoFlightRootsPolicyGUID = $CurrentUserConfigurations.StrictKernelNoFlightRootsPolicyGUID } if ($LastUpdateCheck) { + Write-Verbose -Message 'Saving the supplied Last Update Check in user configurations.' $UserConfigurationsObject.LastUpdateCheck = $LastUpdateCheck } else { + Write-Verbose -Message 'No changes to the Last Update Check property was detected.' $UserConfigurationsObject.LastUpdateCheck = $CurrentUserConfigurations.LastUpdateCheck } } end { # Update the User Configurations file + Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " + + Write-Verbose -Message 'Displaying the current user configurations' Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } } @@ -197,6 +220,13 @@ function Set-CommonWDACConfig { .PARAMETER StrictKernelNoFlightRootsPolicyGUID GUID of the Strict Kernel no Flights root mode policy +.INPUTS + System.DateTime + System.Guid + System.String + +.OUTPUTS + System.Object[] #> # Importing argument completer ScriptBlocks From 1056ffc481972cfb49ec1915ee34c20a4a690393 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 23:42:00 -0930 Subject: [PATCH 084/178] Using capital letter in Function --- WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 8681bfc58..5b242db83 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -1,4 +1,4 @@ -function Confirm-WDACConfig { +Function Confirm-WDACConfig { [CmdletBinding(DefaultParameterSetName = 'List Active Policies')] Param( [Alias('L')] diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 5b1ff093a..7dbb2361d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -1,4 +1,4 @@ -function Deploy-SignedWDACConfig { +Function Deploy-SignedWDACConfig { [CmdletBinding( SupportsShouldProcess = $true, PositionalBinding = $false, diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 433ecbfa8..4180f5849 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1,4 +1,4 @@ -function Edit-SignedWDACConfig { +Function Edit-SignedWDACConfig { [CmdletBinding( DefaultParameterSetName = 'Allow New Apps Audit Events', SupportsShouldProcess = $true, diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 67fcc41c1..da874685d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -1,4 +1,4 @@ -function Edit-WDACConfig { +Function Edit-WDACConfig { [CmdletBinding( DefaultParameterSetName = 'Allow New Apps Audit Events', SupportsShouldProcess = $true, diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index aab6b847c..a9d2f9f6f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -1,4 +1,4 @@ -function Get-CommonWDACConfig { +Function Get-CommonWDACConfig { [CmdletBinding()] Param( [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 378c1fa48..57f46e633 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -1,4 +1,4 @@ -function Invoke-WDACSimulation { +Function Invoke-WDACSimulation { [CmdletBinding( PositionalBinding = $false, SupportsShouldProcess = $true diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index b435a1995..f97d7c585 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -1,4 +1,4 @@ -function New-DenyWDACConfig { +Function New-DenyWDACConfig { [CmdletBinding( DefaultParameterSetName = 'Drivers', PositionalBinding = $false, diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 68c25a3f4..2f8dbed35 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -1,4 +1,4 @@ -function New-KernelModeWDACConfig { +Function New-KernelModeWDACConfig { [CmdletBinding( SupportsShouldProcess = $true, PositionalBinding = $false, diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index b70a89e33..00b5b1f40 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -1,4 +1,4 @@ -function New-SupplementalWDACConfig { +Function New-SupplementalWDACConfig { [CmdletBinding( DefaultParameterSetName = 'Normal', SupportsShouldProcess = $true, diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 325d304ce..3585d08df 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -1,4 +1,4 @@ -function New-WDACConfig { +Function New-WDACConfig { [CmdletBinding( DefaultParameterSetName = 'Get Block Rules', SupportsShouldProcess = $true, diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index b00475810..bbd3c5095 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -1,4 +1,4 @@ -function Remove-CommonWDACConfig { +Function Remove-CommonWDACConfig { [CmdletBinding()] Param( [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$CertCN, diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index a6ba61d47..1af03a222 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -1,4 +1,4 @@ -function Remove-WDACConfig { +Function Remove-WDACConfig { [CmdletBinding( DefaultParameterSetName = 'Signed Base', SupportsShouldProcess = $true, diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index b9e5193ea..1f002f57d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -1,4 +1,4 @@ -function Set-CommonWDACConfig { +Function Set-CommonWDACConfig { [CmdletBinding()] Param( [ValidateScript({ From 4ad0e7be82fc3c0b3b972f0856553bf7409a8d68 Mon Sep 17 00:00:00 2001 From: Violet Date: Thu, 7 Dec 2023 23:48:39 -0930 Subject: [PATCH 085/178] Improved Verbosity of Remove-CommonWDACConfig --- .../Core/Remove-CommonWDACConfig.psm1 | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index bbd3c5095..69495d78a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -12,18 +12,19 @@ Function Remove-CommonWDACConfig { ) begin { # Importing the required sub-modules + Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null - Write-Debug -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." + Write-Verbose -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." } # Create User configuration file if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null - Write-Debug -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." + Write-Verbose -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." } # Delete the entire User Configs if a more specific parameter wasn't used @@ -34,7 +35,7 @@ Function Remove-CommonWDACConfig { } # Read the current user configurations - $CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + [System.Object[]]$CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" # If the file exists but is corrupted and has bad values, rewrite it try { @@ -58,6 +59,7 @@ Function Remove-CommonWDACConfig { } process { if ($SignedPolicyPath) { + Write-Verbose -Message 'Removing the SignedPolicyPath' $UserConfigurationsObject.SignedPolicyPath = '' } else { @@ -65,6 +67,7 @@ Function Remove-CommonWDACConfig { } if ($UnsignedPolicyPath) { + Write-Verbose -Message 'Removing the UnsignedPolicyPath' $UserConfigurationsObject.UnsignedPolicyPath = '' } else { @@ -72,6 +75,7 @@ Function Remove-CommonWDACConfig { } if ($SignToolPath) { + Write-Verbose -Message 'Removing the SignToolPath' $UserConfigurationsObject.SignToolCustomPath = '' } else { @@ -79,6 +83,7 @@ Function Remove-CommonWDACConfig { } if ($CertPath) { + Write-Verbose -Message 'Removing the CertPath' $UserConfigurationsObject.CertificatePath = '' } else { @@ -86,6 +91,7 @@ Function Remove-CommonWDACConfig { } if ($CertCN) { + Write-Verbose -Message 'Removing the CertCN' $UserConfigurationsObject.CertificateCommonName = '' } else { @@ -93,6 +99,7 @@ Function Remove-CommonWDACConfig { } if ($StrictKernelPolicyGUID) { + Write-Verbose -Message 'Removing the StrictKernelPolicyGUID' $UserConfigurationsObject.StrictKernelPolicyGUID = '' } else { @@ -100,6 +107,7 @@ Function Remove-CommonWDACConfig { } if ($StrictKernelNoFlightRootsPolicyGUID) { + Write-Verbose -Message 'Removing the StrictKernelNoFlightRootsPolicyGUID' $UserConfigurationsObject.StrictKernelNoFlightRootsPolicyGUID = '' } else { @@ -107,6 +115,7 @@ Function Remove-CommonWDACConfig { } if ($LastUpdateCheck) { + Write-Verbose -Message 'Removing the LastUpdateCheck' $UserConfigurationsObject.LastUpdateCheck = '' } else { @@ -115,9 +124,8 @@ Function Remove-CommonWDACConfig { } end { # Update the User Configurations file + Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" - Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " - Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } } <# From 30fed47e8aa05514111f24d2edcb1582a81094e0 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 00:33:37 -0930 Subject: [PATCH 086/178] Added verbose messages and improved functions For New-WDACConfig cmdlet --- .../Core/New-WDACConfig.psm1 | 110 +++++++++++++----- 1 file changed, 78 insertions(+), 32 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 3585d08df..d2e90b71e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -136,24 +136,83 @@ Function New-WDACConfig { return [System.String[]]$Levelz } } + + Function Get-DriverBlockRules { + <# + .SYNOPSIS + Gets the latest Microsoft Recommended Driver Block rules and processes them + Can optionally deploy them + .INPUTS + System.Void + .OUTPUTS + PSCustomObject + .PARAMETER Deploy + Indicates that the function will deploy the latest Microsoft recommended drivers block list + #> + param ( + [System.Management.Automation.SwitchParameter]$Deploy + ) - [System.Management.Automation.ScriptBlock]$GetDriverBlockRulesSCRIPTBLOCK = { - [System.String]$DriverRules = (Invoke-WebRequest -Uri $MSFTRecommendeDriverBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' - # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty - $DriverRules = $DriverRules -replace '', '' - $DriverRules = $DriverRules -replace '', '' - $DriverRules = $DriverRules -replace '', '' - $DriverRules | Out-File -FilePath 'Microsoft recommended driver block rules TEMP.xml' -Force - # Remove empty lines from the policy file - Get-Content -Path 'Microsoft recommended driver block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath 'Microsoft recommended driver block rules.xml' -Force - Remove-Item -Path 'Microsoft recommended driver block rules TEMP.xml' -Force - Set-RuleOption -FilePath 'Microsoft recommended driver block rules.xml' -Option 3 -Delete - Set-HVCIOptions -Strict -FilePath 'Microsoft recommended driver block rules.xml' - # Display extra info about the Microsoft Drivers block list - Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK - # Display the result as object - [PSCustomObject]@{ - PolicyFile = 'Microsoft recommended driver block rules.xml' + if ($Deploy) { + Write-Verbose -Message 'Downloading the Microsoft Recommended Driver Block List archive' + Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip -ProgressAction SilentlyContinue + + Write-Verbose -Message 'Expanding the Block list archive' + Expand-Archive -Path .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force + + Write-Verbose -Message 'Renaming the block list file to SiPolicy.p7b' + Rename-Item -Path .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force + + Write-Verbose -Message 'Copying the new block list to the CodeIntegrity folder, replacing any old ones' + Copy-Item -Path .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' -Force + + Write-Verbose -Message 'Refreshing the system WDAC policies using CiTool.exe' + &'C:\Windows\System32\CiTool.exe' --refresh -json | Out-Null + + Write-ColorfulText -Color Pink -InputText 'SiPolicy.p7b has been deployed and policies refreshed.' + + Write-Verbose -Message 'Cleaning up' + Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force + + Write-Verbose -Message 'Displaying extra info about the Microsoft recommended Drivers block list' + Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK + } + else { + # Downloading the latest Microsoft Recommended Driver Block Rules from the official source + Write-Verbose -Message 'Downloading the latest Microsoft Recommended Driver Block Rules from the official source' + [System.String]$DriverRules = (Invoke-WebRequest -Uri $MSFTRecommendeDriverBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' + + # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty + Write-Verbose -Message 'Removing the allow all rules and rule refs from the policy' + $DriverRules = $DriverRules -replace '', '' + $DriverRules = $DriverRules -replace '', '' + $DriverRules = $DriverRules -replace '', '' + + # Output the XML content to a file + Write-Verbose -Message 'Creating XML policy file' + $DriverRules | Out-File -FilePath 'Microsoft recommended driver block rules TEMP.xml' -Force + + # Remove empty lines from the policy file + Write-Verbose -Message 'Removing the empty lines from the policy XML file' + Get-Content -Path 'Microsoft recommended driver block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath 'Microsoft recommended driver block rules.xml' -Force + + Write-Verbose -Message 'Removing the temp XML file' + Remove-Item -Path 'Microsoft recommended driver block rules TEMP.xml' -Force + + Write-Verbose -Message 'Removing the Audit mode policy rule option' + Set-RuleOption -FilePath 'Microsoft recommended driver block rules.xml' -Option 3 -Delete + + Write-Verbose -Message 'Setting the HVCI option to strict' + Set-HVCIOptions -Strict -FilePath 'Microsoft recommended driver block rules.xml' + + # Display extra info about the Microsoft recommended Drivers block list + Write-Verbose -Message 'Displaying extra info about the Microsoft recommended Drivers block list' + Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK + + # Display the result as object + [PSCustomObject]@{ + PolicyFile = 'Microsoft recommended driver block rules.xml' + } } } @@ -263,17 +322,6 @@ Function New-WDACConfig { if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } } - [System.Management.Automation.ScriptBlock]$DeployLatestDriverBlockRulesSCRIPTBLOCK = { - Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip -ProgressAction SilentlyContinue - Expand-Archive -Path .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force - Rename-Item -Path .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force - Copy-Item -Path .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' - &'C:\Windows\System32\CiTool.exe' --refresh -json | Out-Null - Write-ColorfulText -Color Pink -InputText 'SiPolicy.p7b has been deployed and policies refreshed.' - Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force - Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK - } - [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force # Remove empty lines from the policy file @@ -561,10 +609,8 @@ Function New-WDACConfig { { $GetBlockRules -and $Deploy } { & $DeployLatestBlockRulesSCRIPTBLOCK; break } # Get the latest block rules $GetBlockRules { Get-BlockRulesMeta ; break } - # Deploy the latest driver block rules - { $GetDriverBlockRules -and $Deploy } { & $DeployLatestDriverBlockRulesSCRIPTBLOCK; break } - # Get the latest driver block rules - { $GetDriverBlockRules } { & $GetDriverBlockRulesSCRIPTBLOCK; break } + # Get the latest driver block rules and Deploy them if New-WDACConfig -GetDriverBlockRules was called with -Deploy parameter + { $GetDriverBlockRules } { Get-DriverBlockRules -Deploy:$Deploy ; break } $SetAutoUpdateDriverBlockRules { & $SetAutoUpdateDriverBlockRulesSCRIPTBLOCK; break } $MakeAllowMSFTWithBlockRules { & $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK; break } From eca6518d40a940189d4aec2a9e9810f6ba71241d Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 00:55:15 -0930 Subject: [PATCH 087/178] Hide the automated update checker's normal output --- .../WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 | 3 ++- .../WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 | 3 ++- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 3 ++- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 3 ++- .../WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 | 3 ++- .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 3 ++- .../WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 | 3 ++- .../Core/New-SupplementalWDACConfig.psm1 | 3 ++- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 3 ++- WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 3 ++- 10 files changed, 20 insertions(+), 10 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 5b242db83..c15e4c653 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -75,7 +75,8 @@ Function Confirm-WDACConfig { [System.Management.Automation.SwitchParameter]$OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) [System.Management.Automation.SwitchParameter]$SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 7dbb2361d..9eadf7446 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -37,7 +37,8 @@ Function Deploy-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 4180f5849..002eda595 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -132,7 +132,8 @@ Function Edit-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index da874685d..e62fa3bd8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -110,7 +110,8 @@ Function Edit-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 57f46e633..e3b50fe8c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -22,7 +22,8 @@ Function Invoke-WDACSimulation { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } # The total number of the main steps for the progress bar to render [System.Int16]$TotalSteps = 4 diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index f97d7c585..d03a3bf17 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -79,7 +79,8 @@ Function New-DenyWDACConfig { } } - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } } process { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 2f8dbed35..12eeae9c9 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -37,7 +37,8 @@ Function New-KernelModeWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } # Check if the PrepMode and AuditAndEnforce parameters are used together and ensure one of them is used if (-not ($PSBoundParameters.ContainsKey('PrepMode') -xor $PSBoundParameters.ContainsKey('AuditAndEnforce'))) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 00b5b1f40..bb3b99696 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -79,7 +79,8 @@ Function New-SupplementalWDACConfig { } } - if (-NOT $SkipVersionCheck) { . Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index d2e90b71e..da4f91d6f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -597,7 +597,8 @@ Function New-WDACConfig { Write-ColorfulText -Color Pink -InputText "The current version of Microsoft recommended drivers block list is $($Matches[1])" } - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 1af03a222..42ea26bf5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -121,7 +121,8 @@ Function Remove-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - if (-NOT $SkipVersionCheck) { Update-self } + # if -SkipVersionCheck wasn't passed, run the updater and hide its output + if (-NOT $SkipVersionCheck) { Update-self *> $null } # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null From c1220a4550f194e9de0f30aed33ae4eca502386f Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 01:22:57 -0930 Subject: [PATCH 088/178] Added Cmdletbinding to all shared functions --- WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 | 1 + .../Shared/Get-AuditEventLogsProcessing.psm1 | 1 + .../WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 | 2 ++ .../WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 | 2 ++ .../Shared/Move-UserModeToKernelMode.psm1 | 1 + WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 | 1 + WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 | 1 + WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 | 2 ++ 11 files changed, 20 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 index 843ca12f7..9b1bd979d 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 @@ -7,6 +7,7 @@ Function Confirm-CertCN { .OUTPUTS System.Boolean #> + [CmdletBinding()] param ( [System.String]$CN ) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 index 7c9b811ca..657cd2744 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -7,6 +7,7 @@ Function Get-AuditEventLogsProcessing { .OUTPUTS PSCustomObject #> + [CmdletBinding()] param ( [System.DateTime]$Date ) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index ad37b39e4..81ea80301 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -7,6 +7,9 @@ Function Get-BlockRulesMeta { .OUTPUTS PSCustomObject #> + [CmdletBinding()] + param () + [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force # Removing empty lines from policy file diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 index 9333019a4..947710aaa 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -3,6 +3,8 @@ Function Get-FileRules { .SYNOPSIS Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable #> + [CmdletBinding()] + param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $Rules += Write-Output -InputObject "`n" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 index 4357da216..bf01f0762 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 @@ -11,6 +11,9 @@ Function Get-GlobalRootDrives { System.Objects[] #> + [CmdletBinding()] + param () + # Import the kernel32.dll functions using P/Invoke [System.String]$Signature = @' [DllImport("kernel32.dll", SetLastError=true)] diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 index e615fc78d..341a1f616 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -3,6 +3,9 @@ Function Get-RuleRefs { .SYNOPSIS Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable #> + + [CmdletBinding()] + param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $RulesRefs += Write-Output -InputObject "`n" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 index 0fe5626c9..2d8c4669d 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -9,6 +9,8 @@ Function Get-SignTool { .OUTPUTS System.String #> + [CmdletBinding()] + param( [parameter(Mandatory = $false)][System.String]$SignToolExePath ) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 index 633e188f0..185821052 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 @@ -4,6 +4,7 @@ Function Move-UserModeToKernelMode { Moves all User mode AllowedSigners in the User mode signing scenario to the Kernel mode signing scenario and then deletes the entire User mode signing scenario block #> + [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 index 521634c53..2b6951bdd 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 @@ -3,6 +3,7 @@ Function New-EmptyPolicy { .SYNOPSIS Creates a policy file and requires 2 parameters to supply the file rules and rule references #> + [CmdletBinding()] param ( $RulesContent, $RuleRefsContent diff --git a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 index 79051274b..046e31fc8 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 @@ -5,6 +5,7 @@ Function Test-FilePath { that are not in any of the folder paths. Performs this check recursively too so works if the filepath is in a sub-directory of a folder path #> + [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String[]]$FilePath, diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index 9a086b238..abae7ee28 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -7,6 +7,8 @@ Function Update-self { .OUTPUTS System.Void #> + [CmdletBinding()] + param() # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false From 7efabf969f826f3d39caf51d03a5c92af636ce84 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 01:38:06 -0930 Subject: [PATCH 089/178] Improved Update-Self's output and verbosity --- .../WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 | 6 ++++-- .../Core/Deploy-SignedWDACConfig.psm1 | 6 ++++-- .../Core/Edit-SignedWDACConfig.psm1 | 6 ++++-- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 6 ++++-- .../Core/Invoke-WDACSimulation.psm1 | 6 ++++-- .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 6 ++++-- .../Core/New-KernelModeWDACConfig.psm1 | 6 ++++-- .../Core/New-SupplementalWDACConfig.psm1 | 6 ++++-- .../WDACConfig Module Files/Core/New-WDACConfig.psm1 | 6 ++++-- .../WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 9 ++++----- .../WDACConfig Module Files/Shared/Update-self.psm1 | 1 + 11 files changed, 41 insertions(+), 23 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index c15e4c653..ab75da788 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -75,8 +75,10 @@ Function Confirm-WDACConfig { [System.Management.Automation.SwitchParameter]$OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) [System.Management.Automation.SwitchParameter]$SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 9eadf7446..6256d19dd 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -37,8 +37,10 @@ Function Deploy-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 002eda595..9b7688705 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -132,8 +132,10 @@ Function Edit-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index e62fa3bd8..d6533b0e2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -110,8 +110,10 @@ Function Edit-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index e3b50fe8c..132214954 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -22,8 +22,10 @@ Function Invoke-WDACSimulation { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } # The total number of the main steps for the progress bar to render [System.Int16]$TotalSteps = 4 diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index d03a3bf17..3a9d81959 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -79,8 +79,10 @@ Function New-DenyWDACConfig { } } - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } } process { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 12eeae9c9..9d3493711 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -37,8 +37,10 @@ Function New-KernelModeWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } # Check if the PrepMode and AuditAndEnforce parameters are used together and ensure one of them is used if (-not ($PSBoundParameters.ContainsKey('PrepMode') -xor $PSBoundParameters.ContainsKey('AuditAndEnforce'))) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index bb3b99696..8b1630153 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -79,8 +79,10 @@ Function New-SupplementalWDACConfig { } } - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index da4f91d6f..d83f5172e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -597,8 +597,10 @@ Function New-WDACConfig { Write-ColorfulText -Color Pink -InputText "The current version of Microsoft recommended drivers block list is $($Matches[1])" } - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 42ea26bf5..b932c4224 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -121,11 +121,10 @@ Function Remove-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - # if -SkipVersionCheck wasn't passed, run the updater and hide its output - if (-NOT $SkipVersionCheck) { Update-self *> $null } - - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater + # Redirecting the Update-Self function's information Stream to $null because Write-Host + # Used by Write-ColorfulText outputs to both information stream and host console + if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } #region User-Configurations-Processing-Validation diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index abae7ee28..4298dacce 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -15,6 +15,7 @@ Function Update-self { try { # Get the last update check time + Write-Verbose -Message 'Getting the last update check time' [System.DateTime]$UserConfigDate = Get-CommonWDACConfig -LastUpdateCheck } catch { From 0bd2279736578896810937247eedfe3b33c9fa17 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 01:43:40 -0930 Subject: [PATCH 090/178] Added logic for Verbose optional param detection --- .../WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 | 3 +++ .../WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 | 3 +++ .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 3 +++ .../WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 | 3 +++ .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 3 +++ .../WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 | 3 +++ .../Core/New-SupplementalWDACConfig.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 3 +++ 10 files changed, 30 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index ab75da788..b3bb043ea 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -75,6 +75,9 @@ Function Confirm-WDACConfig { [System.Management.Automation.SwitchParameter]$OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) [System.Management.Automation.SwitchParameter]$SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 6256d19dd..3012aae29 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -37,6 +37,9 @@ Function Deploy-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 9b7688705..941c85e9c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -132,6 +132,9 @@ Function Edit-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index d6533b0e2..23a83ad64 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -110,6 +110,9 @@ Function Edit-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 132214954..0de1befa2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -22,6 +22,9 @@ Function Invoke-WDACSimulation { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 3a9d81959..976346d7b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -79,6 +79,9 @@ Function New-DenyWDACConfig { } } + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 9d3493711..1b35e2b0b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -37,6 +37,9 @@ Function New-KernelModeWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 8b1630153..33225f957 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -79,6 +79,9 @@ Function New-SupplementalWDACConfig { } } + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index d83f5172e..80f539805 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -597,6 +597,9 @@ Function New-WDACConfig { Write-ColorfulText -Color Pink -InputText "The current version of Microsoft recommended drivers block list is $($Matches[1])" } + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index b932c4224..d448f0062 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -121,6 +121,9 @@ Function Remove-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console From 59b97a1dc5d84fa22b0807e71020b4ea3691d333 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 01:51:38 -0930 Subject: [PATCH 091/178] Added Verbose messages to the Update-Self function --- WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index 4298dacce..0b9c26ed6 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -20,6 +20,7 @@ Function Update-self { } catch { # If the User Config file doesn't exist then set this flag to perform online update check + Write-Verbose -Message 'No LastUpdateCheck was found in the user configurations, will perform online update check' [System.Boolean]$PerformOnlineUpdateCheck = $true } @@ -35,6 +36,8 @@ Function Update-self { # This prevents the module from constantly doing an update check by fetching the version file from GitHub if (($TimeDiff -gt 10) -or $PerformOnlineUpdateCheck) { + Write-Verbose -Message 'Performing online update check' + [System.Version]$CurrentVersion = (Test-ModuleManifest -Path "$ModuleRootPath\WDACConfig.psd1").Version.ToString() try { # First try the GitHub source @@ -70,7 +73,8 @@ Function Update-self { } # Reset the last update timer to the current time - Set-CommonWDACConfig -LastUpdateCheck $(Get-Date ) | Out-Null + Write-Verbose -Message 'Resetting the last update timer to the current time' + Set-CommonWDACConfig -LastUpdateCheck $(Get-Date) | Out-Null } } From f003bd20ccc74b4f0b1c2469a1dd716076f06fe5 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 01:53:23 -0930 Subject: [PATCH 092/178] Removed unnecessary spacing --- .../Core/New-WDACConfig.psm1 | 30 +++++++++---------- .../Core/Remove-WDACConfig.psm1 | 18 +++++------ .../Core/Set-CommonWDACConfig.psm1 | 4 +-- .../Shared/Get-BlockRulesMeta.psm1 | 2 +- .../Shared/Get-FileRules.psm1 | 1 - .../Shared/Get-GlobalRootDrives.psm1 | 1 - .../Shared/Get-RuleRefs.psm1 | 2 -- .../Shared/Get-SignTool.psm1 | 1 - 8 files changed, 27 insertions(+), 32 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 80f539805..ce3790b06 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -136,7 +136,7 @@ Function New-WDACConfig { return [System.String[]]$Levelz } } - + Function Get-DriverBlockRules { <# .SYNOPSIS @@ -156,21 +156,21 @@ Function New-WDACConfig { if ($Deploy) { Write-Verbose -Message 'Downloading the Microsoft Recommended Driver Block List archive' Invoke-WebRequest -Uri 'https://aka.ms/VulnerableDriverBlockList' -OutFile VulnerableDriverBlockList.zip -ProgressAction SilentlyContinue - + Write-Verbose -Message 'Expanding the Block list archive' Expand-Archive -Path .\VulnerableDriverBlockList.zip -DestinationPath 'VulnerableDriverBlockList' -Force - + Write-Verbose -Message 'Renaming the block list file to SiPolicy.p7b' Rename-Item -Path .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName 'SiPolicy.p7b' -Force - + Write-Verbose -Message 'Copying the new block list to the CodeIntegrity folder, replacing any old ones' Copy-Item -Path .\VulnerableDriverBlockList\SiPolicy.p7b -Destination 'C:\Windows\System32\CodeIntegrity' -Force - + Write-Verbose -Message 'Refreshing the system WDAC policies using CiTool.exe' &'C:\Windows\System32\CiTool.exe' --refresh -json | Out-Null - + Write-ColorfulText -Color Pink -InputText 'SiPolicy.p7b has been deployed and policies refreshed.' - + Write-Verbose -Message 'Cleaning up' Remove-Item -Path .\VulnerableDriverBlockList* -Recurse -Force @@ -181,34 +181,34 @@ Function New-WDACConfig { # Downloading the latest Microsoft Recommended Driver Block Rules from the official source Write-Verbose -Message 'Downloading the latest Microsoft Recommended Driver Block Rules from the official source' [System.String]$DriverRules = (Invoke-WebRequest -Uri $MSFTRecommendeDriverBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' - + # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty Write-Verbose -Message 'Removing the allow all rules and rule refs from the policy' $DriverRules = $DriverRules -replace '', '' $DriverRules = $DriverRules -replace '', '' $DriverRules = $DriverRules -replace '', '' - + # Output the XML content to a file Write-Verbose -Message 'Creating XML policy file' $DriverRules | Out-File -FilePath 'Microsoft recommended driver block rules TEMP.xml' -Force - + # Remove empty lines from the policy file Write-Verbose -Message 'Removing the empty lines from the policy XML file' Get-Content -Path 'Microsoft recommended driver block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath 'Microsoft recommended driver block rules.xml' -Force - + Write-Verbose -Message 'Removing the temp XML file' Remove-Item -Path 'Microsoft recommended driver block rules TEMP.xml' -Force - + Write-Verbose -Message 'Removing the Audit mode policy rule option' Set-RuleOption -FilePath 'Microsoft recommended driver block rules.xml' -Option 3 -Delete - + Write-Verbose -Message 'Setting the HVCI option to strict' Set-HVCIOptions -Strict -FilePath 'Microsoft recommended driver block rules.xml' - + # Display extra info about the Microsoft recommended Drivers block list Write-Verbose -Message 'Displaying extra info about the Microsoft recommended Drivers block list' Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK - + # Display the result as object [PSCustomObject]@{ PolicyFile = 'Microsoft recommended driver block rules.xml' diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index d448f0062..4b507af2b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -246,14 +246,14 @@ Function Remove-WDACConfig { Write-Verbose -Message 'Looping over each selected policy XML file' foreach ($PolicyPath in $PolicyPaths) { - + # Convert the XML file into an XML object Write-Verbose -Message 'Converting the XML file to an XML object' $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - + # Extract the Policy ID from the XML object Write-Verbose -Message 'Extracting the Policy ID from the XML object' - [System.String]$PolicyID = $xml.SiPolicy.PolicyID + [System.String]$PolicyID = $xml.SiPolicy.PolicyID Write-Verbose -Message "The policy ID of the currently processing xml file is $PolicyID" # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system @@ -265,15 +265,15 @@ Function Remove-WDACConfig { # Sanitize the policy file by removing SupplementalPolicySigners from it Write-Verbose -Message 'Sanitizing the XML policy file by removing SupplementalPolicySigners from it' - + # Extracting the SupplementalPolicySigner ID from the selected XML policy file, if any $SuppSingerIDs = $xml.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId # Extracting the policy name from the selected XML policy file $PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string - + if ($SuppSingerIDs) { Write-Verbose -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." - + # Looping over each SupplementalPolicySigner and removing it $SuppSingerIDs | ForEach-Object -Process { $PolContent = Get-Content -Path -Raw -Path $PolicyPath @@ -318,11 +318,11 @@ Function Remove-WDACConfig { Remove-Item -Path ".\$PolicyID.cip" -Force # Fixing the extension name of the newly signed CIP file Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force - + # Deploying the newly signed CIP file Write-Verbose -Message 'Deploying the newly signed CIP file' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - + Write-Host -Object "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" @@ -380,7 +380,7 @@ Function Remove-WDACConfig { .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases -.INPUTS +.INPUTS System.String System.String[] diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 1f002f57d..87c2a20d8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -75,7 +75,7 @@ Function Set-CommonWDACConfig { # Trying to read the current user configurations Write-Verbose -Message 'Trying to read the current user configurations' [System.Object[]]$CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" - + # If the file exists but is corrupted and has bad values, rewrite it try { $CurrentUserConfigurations = $CurrentUserConfigurations | ConvertFrom-Json @@ -178,7 +178,7 @@ Function Set-CommonWDACConfig { Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " - + Write-Verbose -Message 'Displaying the current user configurations' Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 81ea80301..5f85cee4a 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -9,7 +9,7 @@ Function Get-BlockRulesMeta { #> [CmdletBinding()] param () - + [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force # Removing empty lines from policy file diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 index 947710aaa..e29f233ad 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -4,7 +4,6 @@ Function Get-FileRules { Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable #> [CmdletBinding()] - param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $Rules += Write-Output -InputObject "`n" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 index bf01f0762..6c078e271 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 @@ -10,7 +10,6 @@ Function Get-GlobalRootDrives { .OUTPUTS System.Objects[] #> - [CmdletBinding()] param () diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 index 341a1f616..4f62787ac 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -3,9 +3,7 @@ Function Get-RuleRefs { .SYNOPSIS Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable #> - [CmdletBinding()] - param ($HashesArray) $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $RulesRefs += Write-Output -InputObject "`n" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 index 2d8c4669d..b0666861f 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -10,7 +10,6 @@ Function Get-SignTool { System.String #> [CmdletBinding()] - param( [parameter(Mandatory = $false)][System.String]$SignToolExePath ) From 67708371fbd9d2360b7b8ae9efbede66cb67af52 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 01:59:31 -0930 Subject: [PATCH 093/178] Updated Resources2 functions with Cmdletbinding --- .../Resources/Resources2.ps1 | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 b/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 index b5d8c7e19..c9c77f216 100644 --- a/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 +++ b/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 @@ -6,7 +6,7 @@ class Signer { [System.String]$CertPublisher } -function Get-SignerInfo { +Function Get-SignerInfo { <# .SYNOPSIS Function that takes an XML file path as input and returns an array of Signer objects @@ -17,6 +17,7 @@ function Get-SignerInfo { .PARAMETER XmlFilePath The XML file path that the user selected for WDAC simulation. #> + [CmdletBinding()] param( [Parameter(Mandatory = $true)][System.IO.FileInfo]$XmlFilePath ) @@ -50,7 +51,7 @@ function Get-SignerInfo { } } -function Get-TBSCertificate { +Function Get-TBSCertificate { <# .SYNOPSIS Function to calculate the TBS value of a certificate @@ -61,6 +62,7 @@ function Get-TBSCertificate { .PARAMETER Cert The certificate that is going to be used to retrieve its TBS value #> + [CmdletBinding()] param ( [System.Security.Cryptography.X509Certificates.X509Certificate2]$Cert ) @@ -113,7 +115,7 @@ function Get-TBSCertificate { return $HexStringOutput } -function Get-AuthenticodeSignatureEx { +Function Get-AuthenticodeSignatureEx { <# .SYNOPSIS Helps to get the 2nd aka nested signer/signature of the dual signed files @@ -129,9 +131,7 @@ function Get-AuthenticodeSignatureEx { .OUTPUTS System.Management.Automation.Signature #> - [CmdletBinding()] - param( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.String[]]$FilePath @@ -309,7 +309,7 @@ function Get-AuthenticodeSignatureEx { end {} } -function Get-SignedFileCertificates { +Function Get-SignedFileCertificates { <# .SYNOPSIS A function to get all the certificates from a signed file or a certificate object and output a Collection @@ -323,6 +323,7 @@ function Get-SignedFileCertificates { .OUTPUTS System.Security.Cryptography.X509Certificates.X509Certificate2Collection #> + [CmdletBinding()] param ( [Parameter()] [System.String]$FilePath, @@ -353,7 +354,7 @@ function Get-SignedFileCertificates { } } -function Get-CertificateDetails { +Function Get-CertificateDetails { <# .SYNOPSIS A function to detect Root, Intermediate and Leaf certificates @@ -373,6 +374,7 @@ function Get-CertificateDetails { .PARAMETER LeafCNOfTheNestedCertificate This is used only for when -X509Certificate2 parameter is used, so that we can filter out the Leaf certificate and only get the Intermediate certificates at the end of this function #> + [CmdletBinding()] param ( [Parameter(ParameterSetName = 'Based on File Path', Mandatory = $true)] [System.String]$FilePath, @@ -499,7 +501,7 @@ function Get-CertificateDetails { } } -function Compare-SignerAndCertificate { +Function Compare-SignerAndCertificate { <# .SYNOPSIS a function that takes WDAC XML policy file path and a Signed file path as inputs and compares the output of the Get-SignerInfo and Get-CertificateDetails functions @@ -512,6 +514,7 @@ function Compare-SignerAndCertificate { .PARAMETER SignedFilePath Path to a signed file #> + [CmdletBinding()] param( [Parameter(Mandatory = $true)][System.String]$XmlFilePath, [Parameter(Mandatory = $true)][System.String]$SignedFilePath @@ -689,7 +692,7 @@ function Compare-SignerAndCertificate { return $ComparisonResults } -function Get-FileRuleOutput { +Function Get-FileRuleOutput { <# .SYNOPSIS a function to load an xml file and create an output array of custom objects that contain the file rules that are based on file hashes @@ -700,6 +703,7 @@ function Get-FileRuleOutput { .OUTPUTS System.Object[] #> + [CmdletBinding()] param( [parameter(Mandatory = $true)] [System.IO.FileInfo]$XmlPath From 2bd94a2bcf277f9ce3973df0cf330e03ce26f1a7 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 02:42:16 -0930 Subject: [PATCH 094/178] Passing Verbose properly to the internal functions --- .../Core/Deploy-SignedWDACConfig.psm1 | 6 ++--- .../Core/Edit-SignedWDACConfig.psm1 | 24 +++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 3012aae29..50e3a8ae7 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -66,10 +66,10 @@ Function Deploy-SignedWDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose } # If CertPath parameter wasn't provided by user @@ -93,7 +93,7 @@ Function Deploy-SignedWDACConfig { if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName) -Verbose:$Verbose) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 941c85e9c..8f42794fb 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -158,10 +158,10 @@ Function Edit-SignedWDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose } # If CertPath parameter wasn't provided by user @@ -185,7 +185,7 @@ Function Edit-SignedWDACConfig { if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName) -Verbose:$Verbose) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } @@ -255,7 +255,7 @@ Function Edit-SignedWDACConfig { # Remove Enforced Mode CIP Remove-Item -Path ".\$PolicyID.cip" -Force } - [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives + [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives -Verbose:$Verbose } process { @@ -263,7 +263,7 @@ Function Edit-SignedWDACConfig { if ($AllowNewAppsAuditEvents) { # Change Code Integrity event logs size - if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize } + if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } # Make sure there is no leftover from previous runs Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue @@ -381,14 +381,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function - $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date + $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date -Verbose:$Verbose # Only create policy for files that are available on the disk based on Event viewer logs but weren't in user-selected program path(s), if there are any if ($AuditEventLogsProcessingResults.AvailableFilesPaths) { # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those # this prevents duplicate rule creation and double file copying - $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique + $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths -Verbose:$Verbose).path | Select-Object -Unique Write-Verbose -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." @@ -441,10 +441,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath FileRulesAndFileRefs.txt -Force + (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) | Out-File -FilePath FileRulesAndFileRefs.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force # adding the policy file that consists of rules from audit even logs, to the array $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' @@ -540,10 +540,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($KernelProtectedHashesBlockResults) { # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath KernelProtectedFiles.txt -Force + (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) | Out-File -FilePath KernelProtectedFiles.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath .\KernelProtectedFiles.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\KernelProtectedFiles.xml -Force # adding the policy file to the array of xml files $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' @@ -897,7 +897,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($UpdateBasePolicy) { # First get the Microsoft recommended block rules - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta -Verbose:$Verbose | Out-Null switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { From bd0a89520c75d44413aaaffc4ba12d7af5c6396c Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 02:46:28 -0930 Subject: [PATCH 095/178] Passing Verbose property to the internal functions in Edit-WDACConfig --- .../Core/Edit-WDACConfig.psm1 | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 23a83ad64..cece561da 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -192,7 +192,7 @@ Function Edit-WDACConfig { Remove-Item -Path ".\$PolicyID.cip" -Force } - [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives + [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives -Verbose:$Verbose } process { @@ -398,7 +398,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($AllowNewAppsAuditEvents) { # Change Code Integrity event logs size - if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize } + if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } # Make sure there is no leftover from previous runs Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue @@ -494,14 +494,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function - $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date + $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date -Verbose:$Verbose # Only create policy for files that are available on the disk based on Event viewer logs but weren't in user-selected program path(s), if there are any if ($AuditEventLogsProcessingResults.AvailableFilesPaths) { # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those # this prevents duplicate rule creation and double file copying - $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique + $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths -Verbose:$Verbose).path | Select-Object -Unique Write-Verbose -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." @@ -554,10 +554,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - ((Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes)).Trim() | Out-File -FilePath FileRulesAndFileRefs.txt -Force + ((Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose)).Trim() | Out-File -FilePath FileRulesAndFileRefs.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force # adding the policy file that consists of rules from audit even logs, to the array $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' @@ -653,10 +653,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($KernelProtectedHashesBlockResults) { # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath KernelProtectedFiles.txt -Force + (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) | Out-File -FilePath KernelProtectedFiles.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath .\KernelProtectedFiles.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\KernelProtectedFiles.xml -Force # adding the policy file to the array of xml files $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' @@ -767,7 +767,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($UpdateBasePolicy) { # First get the Microsoft recommended block rules - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta -Verbose:$Verbose | Out-Null switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { From 2cf463118090d48c4b1bff9e8524a925b4c0c99f Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 03:04:25 -0930 Subject: [PATCH 096/178] Passing Verbose property to the internal functions --- .../Core/Edit-SignedWDACConfig.psm1 | 12 +++++++++- .../Core/New-KernelModeWDACConfig.psm1 | 5 ++-- .../Core/New-WDACConfig.psm1 | 23 ++++++++++--------- .../Core/Remove-WDACConfig.psm1 | 6 ++--- 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 8f42794fb..c968e86aa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -245,8 +245,18 @@ Function Edit-SignedWDACConfig { } } - #Re-Deploy Basepolicy in Enforced mode function Update-BasePolicyToEnforced { + <# + .SYNOPSIS + Re-Deploy Basepolicy in Enforced mode + .INPUTS + System.Void + .OUTPUTS + System.String + #> + [CmdletBinding()] + param() + # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:" diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 1b35e2b0b..20bbb8a4a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -56,6 +56,7 @@ Function New-KernelModeWDACConfig { .SYNOPSIS Function to swap GUIDs in a WDAC policy XML file #> + [CmdletBinding()] param( [System.String]$PolicyIDInput, [System.String]$PolicyFilePathInput @@ -208,7 +209,7 @@ Function New-KernelModeWDACConfig { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel.xml' -Force # Move all AllowedSigners from Usermode to Kernel mode signing scenario - Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null + Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Verbose:$Verbose | Out-Null # Set the GUIDs for the XML policy file Edit-GUIDs -PolicyIDInput $PolicyID -PolicyFilePathInput '.\Final_DefaultWindows_Enforced_Kernel.xml' @@ -306,7 +307,7 @@ Function New-KernelModeWDACConfig { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' -Force # Move all AllowedSigners from Usermode to Kernel mode signing scenario - Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null + Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Verbose:$Verbose | Out-Null # Set the GUIDs for the XML policy file Edit-GUIDs -PolicyIDInput $PolicyID -PolicyFilePathInput '.\Final_DefaultWindows_Enforced_Kernel.xml' diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index ce3790b06..08f3c02e2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -111,10 +111,10 @@ Function New-WDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. elseif ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose } #endregion User-Configurations-Processing-Validation @@ -149,6 +149,7 @@ Function New-WDACConfig { .PARAMETER Deploy Indicates that the function will deploy the latest Microsoft recommended drivers block list #> + [CmdletBinding()] param ( [System.Management.Automation.SwitchParameter]$Deploy ) @@ -220,7 +221,7 @@ Function New-WDACConfig { param([System.Boolean]$NoCIP) # Get the latest Microsoft recommended block rules - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta -Verbose:$Verbose | Out-Null Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\AllowMicrosoftPlusBlockRules.xml | Out-Null [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoftPlusBlockRules.xml -PolicyName "Allow Microsoft Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID @@ -253,7 +254,7 @@ Function New-WDACConfig { [System.Management.Automation.ScriptBlock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { param([System.Boolean]$NoCIP) - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta -Verbose:$Verbose | Out-Null Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' [System.Boolean]$global:MergeSignToolPolicy = $false @@ -360,7 +361,7 @@ Function New-WDACConfig { } [System.Management.Automation.ScriptBlock]$PrepMSFTOnlyAuditSCRIPTBLOCK = { - if ($PrepMSFTOnlyAudit -and $LogSize) { Set-LogSize -LogSize $LogSize } + if ($PrepMSFTOnlyAudit -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml -Destination .\AllowMicrosoft.xml Set-RuleOption -FilePath .\AllowMicrosoft.xml -Option 3 [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoft.xml -ResetPolicyID @@ -378,7 +379,7 @@ Function New-WDACConfig { } [System.Management.Automation.ScriptBlock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { - if ($PrepDefaultWindowsAudit -and $LogSize) { Set-LogSize -LogSize $LogSize } + if ($PrepDefaultWindowsAudit -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml -Destination .\DefaultWindows_Audit.xml -Force # Making Sure neither PowerShell core nor WDACConfig module files are added to the Supplemental policy created by -MakePolicyFromAuditLogs parameter @@ -410,7 +411,7 @@ Function New-WDACConfig { } [System.Management.Automation.ScriptBlock]$MakePolicyFromAuditLogsSCRIPTBLOCK = { - if ($MakePolicyFromAuditLogs -and $LogSize) { Set-LogSize -LogSize $LogSize } + if ($MakePolicyFromAuditLogs -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } # Make sure there is no leftover files from previous operations of this same command Remove-Item -Path "$home\WDAC\*" -Recurse -Force -ErrorAction SilentlyContinue # Create a working directory in user's folder @@ -497,10 +498,10 @@ Function New-WDACConfig { if ($DeletedFileHashesArray -and !$NoDeletedFiles) { # Save the the File Rules and File Rule Refs to the Out-File FileRulesAndFileRefs.txt in the current working directory - (Get-FileRules -HashesArray $DeletedFileHashesArray) + (Get-RuleRefs -HashesArray $DeletedFileHashesArray) | Out-File -FilePath FileRulesAndFileRefs.txt -Force + (Get-FileRules -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) | Out-File -FilePath FileRulesAndFileRefs.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $DeletedFileHashesArray) -RuleRefsContent (Get-RuleRefs -HashesArray $DeletedFileHashesArray) | Out-File -FilePath .\DeletedFilesHashes.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\DeletedFilesHashes.xml -Force # Merge the policy file we created at first using Event Viewer logs, with the policy file we created for Hash of the files no longer available on the disk Merge-CIPolicy -PolicyPaths 'AuditLogsPolicy_NoDeletedFiles.xml', .\DeletedFilesHashes.xml -OutputFilePath .\SupplementalPolicy.xml | Out-Null @@ -605,7 +606,7 @@ Function New-WDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } - [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives + [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives -Verbose:$Verbose } process { @@ -614,7 +615,7 @@ Function New-WDACConfig { # Deploy the latest block rules { $GetBlockRules -and $Deploy } { & $DeployLatestBlockRulesSCRIPTBLOCK; break } # Get the latest block rules - $GetBlockRules { Get-BlockRulesMeta ; break } + $GetBlockRules { Get-BlockRulesMeta -Verbose:$Verbose ; break } # Get the latest driver block rules and Deploy them if New-WDACConfig -GetDriverBlockRules was called with -Deploy parameter { $GetDriverBlockRules } { Get-DriverBlockRules -Deploy:$Deploy ; break } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 4b507af2b..7b1aa5552 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -151,17 +151,17 @@ Function Remove-WDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose } # If CertCN was not provided by user if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName) -Verbose:$Verbose) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } From b1563377fb8baa6bc7acf558f6f3104736ef6f22 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 03:14:50 -0930 Subject: [PATCH 097/178] Making sure copy-items have -force --- .../Core/Edit-SignedWDACConfig.psm1 | 6 +++--- .../Core/Edit-WDACConfig.psm1 | 6 +++--- .../Core/New-WDACConfig.psm1 | 21 +++++++++++-------- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index c968e86aa..8186d598a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -911,14 +911,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } @@ -928,7 +928,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow } 'DefaultWindows_WithBlockRules' { - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force # Allowing SignTool to be able to run after Default Windows base policy is deployed Write-ColorfulText -Color TeaGreen -InputText "`nCreating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy." diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index cece561da..7d801afab 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -771,14 +771,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" @(0, 2, 5, 6, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } @@ -788,7 +788,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow } 'DefaultWindows_WithBlockRules' { - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { Write-Host -Object 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 08f3c02e2..b9d6d5d59 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -217,12 +217,15 @@ Function New-WDACConfig { } } - [System.Management.Automation.ScriptBlock]$MakeAllowMSFTWithBlockRulesSCRIPTBLOCK = { - param([System.Boolean]$NoCIP) + Function Build-AllowMSFTWithBlockRules { + [CmdletBinding()] + param( + [System.Boolean]$NoCIP + ) # Get the latest Microsoft recommended block rules Get-BlockRulesMeta -Verbose:$Verbose | Out-Null - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' -Force Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\AllowMicrosoftPlusBlockRules.xml | Out-Null [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoftPlusBlockRules.xml -PolicyName "Allow Microsoft Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) @@ -255,7 +258,7 @@ Function New-WDACConfig { [System.Management.Automation.ScriptBlock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { param([System.Boolean]$NoCIP) Get-BlockRulesMeta -Verbose:$Verbose | Out-Null - Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' -Force [System.Boolean]$global:MergeSignToolPolicy = $false @@ -362,7 +365,7 @@ Function New-WDACConfig { [System.Management.Automation.ScriptBlock]$PrepMSFTOnlyAuditSCRIPTBLOCK = { if ($PrepMSFTOnlyAudit -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } - Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml -Destination .\AllowMicrosoft.xml + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination .\AllowMicrosoft.xml -Force Set-RuleOption -FilePath .\AllowMicrosoft.xml -Option 3 [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoft.xml -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) @@ -380,7 +383,7 @@ Function New-WDACConfig { [System.Management.Automation.ScriptBlock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { if ($PrepDefaultWindowsAudit -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } - Copy-Item -Path C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml -Destination .\DefaultWindows_Audit.xml -Force + Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml' -Destination .\DefaultWindows_Audit.xml -Force # Making Sure neither PowerShell core nor WDACConfig module files are added to the Supplemental policy created by -MakePolicyFromAuditLogs parameter # by adding them first to the deployed Default Windows policy in Audit mode. Because WDACConfig module files don't need to be allowed to run since they are *.ps1 and .*psm1 files @@ -422,7 +425,7 @@ Function New-WDACConfig { switch ($BasePolicyType) { 'Allow Microsoft Base' { - Invoke-Command -ScriptBlock $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK | Out-Null + Build-AllowMSFTWithBlockRules | Out-Null $xml = [System.Xml.XmlDocument](Get-Content -Path .\AllowMicrosoftPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy @@ -556,7 +559,7 @@ Function New-WDACConfig { [System.Management.Automation.ScriptBlock]$MakeLightPolicySCRIPTBLOCK = { # Delete the any policy with the same name in the current working directory Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue - Invoke-Command -ScriptBlock $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK -ArgumentList $true | Out-Null + Build-AllowMSFTWithBlockRules -NoCIP $true Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } if ($TestMode -and $MakeLightPolicy) { @@ -620,7 +623,7 @@ Function New-WDACConfig { { $GetDriverBlockRules } { Get-DriverBlockRules -Deploy:$Deploy ; break } $SetAutoUpdateDriverBlockRules { & $SetAutoUpdateDriverBlockRulesSCRIPTBLOCK; break } - $MakeAllowMSFTWithBlockRules { & $MakeAllowMSFTWithBlockRulesSCRIPTBLOCK; break } + $MakeAllowMSFTWithBlockRules { Build-AllowMSFTWithBlockRules ; break } $MakePolicyFromAuditLogs { & $MakePolicyFromAuditLogsSCRIPTBLOCK; break } $PrepMSFTOnlyAudit { & $PrepMSFTOnlyAuditSCRIPTBLOCK; break } $MakeLightPolicy { & $MakeLightPolicySCRIPTBLOCK; break } From 83c1098b92468f682b3dfdb0f3a8ba0bb00efff1 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 03:32:24 -0930 Subject: [PATCH 098/178] Added proper verbose msgs to the newly created Build-AllowMSFTWithBlockRules function --- .../Core/New-WDACConfig.psm1 | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index b9d6d5d59..c8258b6d0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -136,7 +136,6 @@ Function New-WDACConfig { return [System.String[]]$Levelz } } - Function Get-DriverBlockRules { <# .SYNOPSIS @@ -217,46 +216,81 @@ Function New-WDACConfig { } } - Function Build-AllowMSFTWithBlockRules { + <# + .SYNOPSIS + A helper function that downloads the latest Microsoft recommended block rules + and merges them with the Allow Microsoft template policy. + It can also deploy the policy on the system. + .PARAMETER NoCIP + Indicates that the created .CIP binary file must be deleted at the end. + It's usually used when calling this function from other functions that don't need the .CIP output of this function. + #> [CmdletBinding()] param( - [System.Boolean]$NoCIP + [System.Management.Automation.SwitchParameter]$NoCIP ) # Get the latest Microsoft recommended block rules + Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' Get-BlockRulesMeta -Verbose:$Verbose | Out-Null + + Write-Verbose -Message 'Copying the AllowMicrosoft.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' -Force + + Write-Verbose -Message 'Merging the AllowMicrosoft.xml with Microsoft Recommended Block rules.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\AllowMicrosoftPlusBlockRules.xml | Out-Null + + Write-Verbose -Message 'Resetting the policy ID and setting a name for AllowMicrosoftPlusBlockRules.xml' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoftPlusBlockRules.xml -PolicyName "Allow Microsoft Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) + + Write-Verbose -Message 'Setting AllowMicrosoftPlusBlockRules.xml policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath .\AllowMicrosoftPlusBlockRules.xml -Version '1.0.0.0' + + Write-Verbose -Message 'Configuring the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ -Delete } + if ($TestMode -and $MakeAllowMSFTWithBlockRules) { + Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options for the AllowMicrosoftPlusBlockRules.xml policy because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } } if ($RequireEVSigners -and $MakeAllowMSFTWithBlockRules) { + Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option for the AllowMicrosoftPlusBlockRules.xml policy because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option 8 } + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\AllowMicrosoftPlusBlockRules.xml + + Write-Verbose -Message 'Converting the AllowMicrosoftPlusBlockRules.xml policy file to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null + # Remove the extra files that were created during module operation and are no longer needed + Write-Verbose -Message 'Removing the extra files that were created during module operation and are no longer needed' Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force + + Write-Verbose -Message 'Displaying the outout' [PSCustomObject]@{ PolicyFile = 'AllowMicrosoftPlusBlockRules.xml' BinaryFile = "$PolicyID.cip" } + if ($Deploy -and $MakeAllowMSFTWithBlockRules) { + Write-Verbose -Message 'Deploying the AllowMicrosoftPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } - if ($NoCIP) - { Remove-Item -Path "$PolicyID.cip" -Force } + + if ($NoCIP) { + Write-Verbose -Message 'Removing the generated .CIP binary file because -NoCIP parameter was used' + Remove-Item -Path "$PolicyID.cip" -Force + } } [System.Management.Automation.ScriptBlock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { - param([System.Boolean]$NoCIP) + Get-BlockRulesMeta -Verbose:$Verbose | Out-Null Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' -Force @@ -323,7 +357,6 @@ Function New-WDACConfig { Write-Host -Object "`n" Remove-Item -Path "$PolicyID.cip" -Force } - if ($NoCIP) { Remove-Item -Path "$PolicyID.cip" -Force } } [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { @@ -559,7 +592,7 @@ Function New-WDACConfig { [System.Management.Automation.ScriptBlock]$MakeLightPolicySCRIPTBLOCK = { # Delete the any policy with the same name in the current working directory Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue - Build-AllowMSFTWithBlockRules -NoCIP $true + Build-AllowMSFTWithBlockRules -NoCIP Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } if ($TestMode -and $MakeLightPolicy) { From 9c2800450f6b17b6f2a444177cc6609e8eb88084 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 03:56:41 -0930 Subject: [PATCH 099/178] Created a new function Build-DefaultWindowsWithBlockRules --- .../Core/New-WDACConfig.psm1 | 94 +++++++++++++++---- 1 file changed, 75 insertions(+), 19 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index c8258b6d0..d5e9c1c9b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -280,6 +280,8 @@ Function New-WDACConfig { Write-Verbose -Message 'Deploying the AllowMicrosoftPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" + + Write-Verbose -Message 'Removing the generated .CIP binary file after deploying it' Remove-Item -Path "$PolicyID.cip" -Force } @@ -289,72 +291,126 @@ Function New-WDACConfig { } } - [System.Management.Automation.ScriptBlock]$MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK = { - + Function Build-DefaultWindowsWithBlockRules { + <# + .SYNOPSIS + A helper function that downloads the latest Microsoft recommended block rules + and merges them with the DefaultWindows_Enforced template policy. + It can also deploy the policy on the system. + .INPUTS + System.Void + .OUTPUTS + System.String + #> + [CmdletBinding()] + param() + + Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' Get-BlockRulesMeta -Verbose:$Verbose | Out-Null + + Write-Verbose -Message 'Copying the DefaultWindows_Enforced.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' -Force - - [System.Boolean]$global:MergeSignToolPolicy = $false - + + # Setting a flag for Scanning the SignTool.exe and merging it with the final base policy + [System.Boolean]$MergeSignToolPolicy = $false + if ($SignToolPathFinal) { # Allowing SignTool to be able to run after Default Windows base policy is deployed in Signed scenario Write-ColorfulText -Color TeaGreen -InputText "`nCreating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy." + + Write-Verbose -Message 'Creating a new temporary directory in the temp directory' New-Item -Path "$UserTempDirectoryPath\TemporarySignToolFile" -ItemType Directory -Force | Out-Null + + Write-Verbose -Message 'Copying the SignTool.exe to the newly created directory in the temp directory' Copy-Item -Path $SignToolPathFinal -Destination "$UserTempDirectoryPath\TemporarySignToolFile" -Force + + Write-Verbose -Message 'Scanning the SignTool.exe in the temp directory and generating the SignTool.xml policy' New-CIPolicy -ScanPath "$UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml + # Delete the Temporary folder in the TEMP folder - if (!$Debug) { Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporarySignToolFile" -Force } - - [System.Boolean]$global:MergeSignToolPolicy = $true + if (!$Debug) { + Write-Verbose -Message 'Debug parameter was not used, removing the files created in the temp directory' + Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporarySignToolFile" -Force + } + + # Setting the flag to true so that the SignTool.xml file will be merged with the final policy + [System.Boolean]$MergeSignToolPolicy = $true } - + # Scan PowerShell core directory and allow its files in the Default Windows base policy so that module can still be used once it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { + Write-ColorfulText -Color Lavender -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml - - if ($global:MergeSignToolPolicy) { + + if ($MergeSignToolPolicy) { + Write-Verbose -Message 'Merging the policy files, including SignTool.xml, to create the final DefaultWindowsPlusBlockRules.xml policy' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, 'Microsoft recommended block rules.xml', .\SignTool.xml -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } else { + Write-Verbose -Message 'Merging the policy files to create the final DefaultWindowsPlusBlockRules.xml policy' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } } else { - if ($global:MergeSignToolPolicy) { + if ($MergeSignToolPolicy) { + Write-Verbose -Message 'Merging the policy files, including SignTool.xml, to create the final DefaultWindowsPlusBlockRules.xml policy' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, 'Microsoft recommended block rules.xml', .\SignTool.xml -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } else { + Write-Verbose -Message 'Merging the policy files to create the final DefaultWindowsPlusBlockRules.xml policy' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } } - + + Write-Verbose -Message 'Resetting the policy ID and setting a name for DefaultWindowsPlusBlockRules.xml' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindowsPlusBlockRules.xml -PolicyName "Default Windows Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) + + Write-Verbose -Message 'Setting the version of DefaultWindowsPlusBlockRules.xml policy to 1.0.0.0' Set-CIPolicyVersion -FilePath .\DefaultWindowsPlusBlockRules.xml -Version '1.0.0.0' + + Write-Verbose -Message 'Configuring the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ -Delete } + if ($TestMode -and $MakeDefaultWindowsWithBlockRules) { + Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options for the DefaultWindowsPlusBlockRules.xml policy because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } } + if ($RequireEVSigners -and $MakeDefaultWindowsWithBlockRules) { + Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option for the DefaultWindowsPlusBlockRules.xml policy because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option 8 } + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\DefaultWindowsPlusBlockRules.xml + + Write-Verbose -Message 'Converting the DefaultWindowsPlusBlockRules.xml policy file to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindowsPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - + + Write-Verbose -Message 'Removing the extra files that were created during module operation and are no longer needed' Remove-Item -Path .\AllowPowerShell.xml -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\DefaultWindows_Enforced.xml', 'Microsoft recommended block rules.xml' -Force - if ($global:MergeSignToolPolicy -and !$Debug) { Remove-Item -Path .\SignTool.xml -Force } - + + if ($MergeSignToolPolicy -and !$Debug) { + Write-Verbose -Message 'Deleting SignTool.xml' + Remove-Item -Path .\SignTool.xml -Force + } + + Write-Verbose -Message 'Displaying the output' [PSCustomObject]@{ PolicyFile = 'DefaultWindowsPlusBlockRules.xml' BinaryFile = "$PolicyID.cip" } - + if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { + Write-Verbose -Message 'Deploying the DefaultWindowsPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" + + Write-Verbose -Message 'Removing the generated .CIP binary file after deploying it' Remove-Item -Path "$PolicyID.cip" -Force } } @@ -465,7 +521,7 @@ Function New-WDACConfig { $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' } 'Default Windows Base' { - Invoke-Command -ScriptBlock $MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK | Out-Null + Build-DefaultWindowsWithBlockRules | Out-Null $xml = [System.Xml.XmlDocument](Get-Content -Path .\DefaultWindowsPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID # define the location of the base policy @@ -660,7 +716,7 @@ Function New-WDACConfig { $MakePolicyFromAuditLogs { & $MakePolicyFromAuditLogsSCRIPTBLOCK; break } $PrepMSFTOnlyAudit { & $PrepMSFTOnlyAuditSCRIPTBLOCK; break } $MakeLightPolicy { & $MakeLightPolicySCRIPTBLOCK; break } - $MakeDefaultWindowsWithBlockRules { & $MakeDefaultWindowsWithBlockRulesSCRIPTBLOCK; break } + $MakeDefaultWindowsWithBlockRules { Build-DefaultWindowsWithBlockRules ; break } $PrepDefaultWindowsAudit { & $PrepDefaultWindowsAuditSCRIPTBLOCK; break } default { Write-Warning 'None of the main parameters were selected.'; break } } From c7ae3a33cd963a2b29a43baefca2b7316a1fd68c Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 03:57:37 -0930 Subject: [PATCH 100/178] Update New-WDACConfig.psm1 --- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index d5e9c1c9b..d8f2189cd 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -334,7 +334,7 @@ Function New-WDACConfig { } # Setting the flag to true so that the SignTool.xml file will be merged with the final policy - [System.Boolean]$MergeSignToolPolicy = $true + $MergeSignToolPolicy = $true } # Scan PowerShell core directory and allow its files in the Default Windows base policy so that module can still be used once it's been deployed From e37748f3fe082e33c35c003f1fb1191e82f2ac07 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 04:13:57 -0930 Subject: [PATCH 101/178] Update the Scheduled task logic and converted it to function --- .../Core/New-WDACConfig.psm1 | 64 +++++++++++++------ 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index d8f2189cd..e77dd6c3d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -430,25 +430,53 @@ Function New-WDACConfig { Write-ColorfulText -Color Lavender -InputText 'The Microsoft recommended block rules policy has been deployed in enforced mode.' Remove-Item -Path "$PolicyID.cip" -Force } + + Function Set-AutoUpdateDriverBlockRules { + <# + .SYNOPSIS + A helper function that creates a scheduled task to keep the Microsoft Recommended Driver Block rules + In Windows up to date quickly ahead of its official release schedule. It does this by downloading and applying + The latest block list every 7 days on the system. + .INPUTS + System.Void + .OUTPUTS + System.Void + #> + [CmdletBinding()] + param() - [System.Management.Automation.ScriptBlock]$SetAutoUpdateDriverBlockRulesSCRIPTBLOCK = { - # create a scheduled task that runs every 7 days - if (-NOT (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath '\MSFT Driver Block list update\' -ErrorAction SilentlyContinue)) { + # Get the state of fast weekly Microsoft recommended driver block list update scheduled task + Write-Verbose -Message 'Getting the state of MSFT Driver Block list update Scheduled task' + [System.String]$BlockListScheduledTaskState = (Get-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath '\MSFT Driver Block list update\' -ErrorAction SilentlyContinue).State + + # Create scheduled task for fast weekly Microsoft recommended driver block list update if it doesn't exist or exists but is not Ready/Running + if (-NOT (($BlockListScheduledTaskState -eq 'Ready' -or $BlockListScheduledTaskState -eq 'Running'))) { + + Write-Verbose -Message "Creating the MSFT Driver Block list update task because its state is neither Running nor Ready, it's $BlockListScheduledTaskState" # Get the SID of the SYSTEM account. It is a well-known SID, but still querying it, going to use it to create the scheduled task - $SYSTEMSID = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null) - # create a scheduled task that runs every 7 days - $Action = New-ScheduledTaskAction -Execute 'Powershell.exe' ` - -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' - $TaskPrincipal = New-ScheduledTaskPrincipal -LogonType S4U -UserId $($SYSTEMSID.Value) -RunLevel Highest - # trigger - $Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) - # register the task - Register-ScheduledTask -Action $Action -Trigger $Time -Principal $TaskPrincipal -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Description 'Microsoft Recommended Driver Block List update' - # define advanced settings for the task - $TaskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Compatibility Win8 -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 3) - # add advanced settings we defined to the task - Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings - } + [System.Security.Principal.SecurityIdentifier]$SYSTEMSID = New-Object -TypeName System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null) + + # Create a scheduled task action, this defines how to download and install the latest Microsoft Recommended Driver Block Rules + [Microsoft.Management.Infrastructure.CimInstance]$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' ` + -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' + + # Create a scheduled task principal and assign the SYSTEM account's SID to it so that the task will run under its context + [Microsoft.Management.Infrastructure.CimInstance]$TaskPrincipal = New-ScheduledTaskPrincipal -LogonType S4U -UserId $($SYSTEMSID.Value) -RunLevel Highest + + # Create a trigger for the scheduled task. The task will first run one hour after its creation and from then on will run every 7 days, indefinitely + [Microsoft.Management.Infrastructure.CimInstance]$Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) + + # Register the scheduled task. If the task's state is disabled, it will be overwritten with a new task that is enabled + Register-ScheduledTask -Action $Action -Trigger $Time -Principal $TaskPrincipal -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Description 'Microsoft Recommended Driver Block List update' -Force + + # Define advanced settings for the scheduled task + [Microsoft.Management.Infrastructure.CimInstance]$TaskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Compatibility 'Win8' -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -RestartCount 4 -RestartInterval (New-TimeSpan -Hours 6) -RunOnlyIfNetworkAvailable + + # Add the advanced settings we defined above to the scheduled task + Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings + } + + Write-Verbose -Message 'Displaying extra info about the Microsoft recommended Drivers block list' Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } @@ -711,7 +739,7 @@ Function New-WDACConfig { # Get the latest driver block rules and Deploy them if New-WDACConfig -GetDriverBlockRules was called with -Deploy parameter { $GetDriverBlockRules } { Get-DriverBlockRules -Deploy:$Deploy ; break } - $SetAutoUpdateDriverBlockRules { & $SetAutoUpdateDriverBlockRulesSCRIPTBLOCK; break } + $SetAutoUpdateDriverBlockRules { Set-AutoUpdateDriverBlockRules ; break } $MakeAllowMSFTWithBlockRules { Build-AllowMSFTWithBlockRules ; break } $MakePolicyFromAuditLogs { & $MakePolicyFromAuditLogsSCRIPTBLOCK; break } $PrepMSFTOnlyAudit { & $PrepMSFTOnlyAuditSCRIPTBLOCK; break } From 16362598e6b2a1f60b7c90b365c8568c3ef90c5c Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 04:15:07 -0930 Subject: [PATCH 102/178] Removed the unnecessary trailing spaces --- .../Core/New-WDACConfig.psm1 | 96 +++++++++---------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index e77dd6c3d..231f31d51 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -233,24 +233,24 @@ Function New-WDACConfig { # Get the latest Microsoft recommended block rules Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' Get-BlockRulesMeta -Verbose:$Verbose | Out-Null - + Write-Verbose -Message 'Copying the AllowMicrosoft.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' -Force - + Write-Verbose -Message 'Merging the AllowMicrosoft.xml with Microsoft Recommended Block rules.xml' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\AllowMicrosoftPlusBlockRules.xml | Out-Null - + Write-Verbose -Message 'Resetting the policy ID and setting a name for AllowMicrosoftPlusBlockRules.xml' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoftPlusBlockRules.xml -PolicyName "Allow Microsoft Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) - + Write-Verbose -Message 'Setting AllowMicrosoftPlusBlockRules.xml policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath .\AllowMicrosoftPlusBlockRules.xml -Version '1.0.0.0' - + Write-Verbose -Message 'Configuring the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ -Delete } - + if ($TestMode -and $MakeAllowMSFTWithBlockRules) { Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options for the AllowMicrosoftPlusBlockRules.xml policy because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option $_ } @@ -259,23 +259,23 @@ Function New-WDACConfig { Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option for the AllowMicrosoftPlusBlockRules.xml policy because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\AllowMicrosoftPlusBlockRules.xml -Option 8 } - + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\AllowMicrosoftPlusBlockRules.xml Write-Verbose -Message 'Converting the AllowMicrosoftPlusBlockRules.xml policy file to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoftPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - + # Remove the extra files that were created during module operation and are no longer needed Write-Verbose -Message 'Removing the extra files that were created during module operation and are no longer needed' Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force - + Write-Verbose -Message 'Displaying the outout' [PSCustomObject]@{ PolicyFile = 'AllowMicrosoftPlusBlockRules.xml' BinaryFile = "$PolicyID.cip" } - + if ($Deploy -and $MakeAllowMSFTWithBlockRules) { Write-Verbose -Message 'Deploying the AllowMicrosoftPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null @@ -284,7 +284,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Removing the generated .CIP binary file after deploying it' Remove-Item -Path "$PolicyID.cip" -Force } - + if ($NoCIP) { Write-Verbose -Message 'Removing the generated .CIP binary file because -NoCIP parameter was used' Remove-Item -Path "$PolicyID.cip" -Force @@ -304,45 +304,45 @@ Function New-WDACConfig { #> [CmdletBinding()] param() - + Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' Get-BlockRulesMeta -Verbose:$Verbose | Out-Null - + Write-Verbose -Message 'Copying the DefaultWindows_Enforced.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' -Force - + # Setting a flag for Scanning the SignTool.exe and merging it with the final base policy [System.Boolean]$MergeSignToolPolicy = $false - + if ($SignToolPathFinal) { # Allowing SignTool to be able to run after Default Windows base policy is deployed in Signed scenario Write-ColorfulText -Color TeaGreen -InputText "`nCreating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy." - + Write-Verbose -Message 'Creating a new temporary directory in the temp directory' New-Item -Path "$UserTempDirectoryPath\TemporarySignToolFile" -ItemType Directory -Force | Out-Null - + Write-Verbose -Message 'Copying the SignTool.exe to the newly created directory in the temp directory' Copy-Item -Path $SignToolPathFinal -Destination "$UserTempDirectoryPath\TemporarySignToolFile" -Force - + Write-Verbose -Message 'Scanning the SignTool.exe in the temp directory and generating the SignTool.xml policy' New-CIPolicy -ScanPath "$UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml - + # Delete the Temporary folder in the TEMP folder - if (!$Debug) { + if (!$Debug) { Write-Verbose -Message 'Debug parameter was not used, removing the files created in the temp directory' Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporarySignToolFile" -Force } - + # Setting the flag to true so that the SignTool.xml file will be merged with the final policy $MergeSignToolPolicy = $true } - + # Scan PowerShell core directory and allow its files in the Default Windows base policy so that module can still be used once it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { - + Write-ColorfulText -Color Lavender -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml - + if ($MergeSignToolPolicy) { Write-Verbose -Message 'Merging the policy files, including SignTool.xml, to create the final DefaultWindowsPlusBlockRules.xml policy' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, 'Microsoft recommended block rules.xml', .\SignTool.xml -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null @@ -362,54 +362,54 @@ Function New-WDACConfig { Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, 'Microsoft recommended block rules.xml' -OutputFilePath .\DefaultWindowsPlusBlockRules.xml | Out-Null } } - + Write-Verbose -Message 'Resetting the policy ID and setting a name for DefaultWindowsPlusBlockRules.xml' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindowsPlusBlockRules.xml -PolicyName "Default Windows Plus Block Rules - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) - + Write-Verbose -Message 'Setting the version of DefaultWindowsPlusBlockRules.xml policy to 1.0.0.0' Set-CIPolicyVersion -FilePath .\DefaultWindowsPlusBlockRules.xml -Version '1.0.0.0' - + Write-Verbose -Message 'Configuring the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ -Delete } - + if ($TestMode -and $MakeDefaultWindowsWithBlockRules) { Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options for the DefaultWindowsPlusBlockRules.xml policy because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option $_ } } - + if ($RequireEVSigners -and $MakeDefaultWindowsWithBlockRules) { Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option for the DefaultWindowsPlusBlockRules.xml policy because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\DefaultWindowsPlusBlockRules.xml -Option 8 } - + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\DefaultWindowsPlusBlockRules.xml - + Write-Verbose -Message 'Converting the DefaultWindowsPlusBlockRules.xml policy file to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindowsPlusBlockRules.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - + Write-Verbose -Message 'Removing the extra files that were created during module operation and are no longer needed' Remove-Item -Path .\AllowPowerShell.xml -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\DefaultWindows_Enforced.xml', 'Microsoft recommended block rules.xml' -Force - + if ($MergeSignToolPolicy -and !$Debug) { Write-Verbose -Message 'Deleting SignTool.xml' - Remove-Item -Path .\SignTool.xml -Force + Remove-Item -Path .\SignTool.xml -Force } - + Write-Verbose -Message 'Displaying the output' [PSCustomObject]@{ PolicyFile = 'DefaultWindowsPlusBlockRules.xml' BinaryFile = "$PolicyID.cip" } - + if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { Write-Verbose -Message 'Deploying the DefaultWindowsPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-Host -Object "`n" - + Write-Verbose -Message 'Removing the generated .CIP binary file after deploying it' Remove-Item -Path "$PolicyID.cip" -Force } @@ -430,7 +430,7 @@ Function New-WDACConfig { Write-ColorfulText -Color Lavender -InputText 'The Microsoft recommended block rules policy has been deployed in enforced mode.' Remove-Item -Path "$PolicyID.cip" -Force } - + Function Set-AutoUpdateDriverBlockRules { <# .SYNOPSIS @@ -455,25 +455,25 @@ Function New-WDACConfig { Write-Verbose -Message "Creating the MSFT Driver Block list update task because its state is neither Running nor Ready, it's $BlockListScheduledTaskState" # Get the SID of the SYSTEM account. It is a well-known SID, but still querying it, going to use it to create the scheduled task [System.Security.Principal.SecurityIdentifier]$SYSTEMSID = New-Object -TypeName System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null) - - # Create a scheduled task action, this defines how to download and install the latest Microsoft Recommended Driver Block Rules + + # Create a scheduled task action, this defines how to download and install the latest Microsoft Recommended Driver Block Rules [Microsoft.Management.Infrastructure.CimInstance]$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' ` - -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' - + -Argument '-NoProfile -WindowStyle Hidden -command "& {try {Invoke-WebRequest -Uri "https://aka.ms/VulnerableDriverBlockList" -OutFile VulnerableDriverBlockList.zip -ErrorAction Stop}catch{exit};Expand-Archive .\VulnerableDriverBlockList.zip -DestinationPath "VulnerableDriverBlockList" -Force;Rename-Item .\VulnerableDriverBlockList\SiPolicy_Enforced.p7b -NewName "SiPolicy.p7b" -Force;Copy-Item .\VulnerableDriverBlockList\SiPolicy.p7b -Destination "C:\Windows\System32\CodeIntegrity";citool --refresh -json;Remove-Item .\VulnerableDriverBlockList -Recurse -Force;Remove-Item .\VulnerableDriverBlockList.zip -Force;}"' + # Create a scheduled task principal and assign the SYSTEM account's SID to it so that the task will run under its context [Microsoft.Management.Infrastructure.CimInstance]$TaskPrincipal = New-ScheduledTaskPrincipal -LogonType S4U -UserId $($SYSTEMSID.Value) -RunLevel Highest - + # Create a trigger for the scheduled task. The task will first run one hour after its creation and from then on will run every 7 days, indefinitely - [Microsoft.Management.Infrastructure.CimInstance]$Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) - + [Microsoft.Management.Infrastructure.CimInstance]$Time = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Days 7) + # Register the scheduled task. If the task's state is disabled, it will be overwritten with a new task that is enabled Register-ScheduledTask -Action $Action -Trigger $Time -Principal $TaskPrincipal -TaskPath 'MSFT Driver Block list update' -TaskName 'MSFT Driver Block list update' -Description 'Microsoft Recommended Driver Block List update' -Force - + # Define advanced settings for the scheduled task [Microsoft.Management.Infrastructure.CimInstance]$TaskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Compatibility 'Win8' -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -RestartCount 4 -RestartInterval (New-TimeSpan -Hours 6) -RunOnlyIfNetworkAvailable - + # Add the advanced settings we defined above to the scheduled task - Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings + Set-ScheduledTask -TaskName 'MSFT Driver Block list update' -TaskPath 'MSFT Driver Block list update' -Settings $TaskSettings } Write-Verbose -Message 'Displaying extra info about the Microsoft recommended Drivers block list' From 8344b4cc877d4fcd2fd2b950fe4ae48092ac7d3a Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 06:27:58 -0930 Subject: [PATCH 103/178] Update New-WDACConfig.psm1 --- .../Core/New-WDACConfig.psm1 | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 231f31d51..149661a1a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -415,10 +415,23 @@ Function New-WDACConfig { } } - [System.Management.Automation.ScriptBlock]$DeployLatestBlockRulesSCRIPTBLOCK = { + Function Deploy-LatestBlockRules { + <# + .SYNOPSIS + A helper function that downloads the latest Microsoft recommended block rules + .INPUTS + System.Void + .OUTPUTS + System.String + #> + + Write-Verbose -Message 'Downloading the latest Microsoft recommended block rules and creating Microsoft recommended block rules TEMP.xml' (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force + # Remove empty lines from the policy file + Write-Verbose -Message 'Removing any empty lines from the Temp policy file and generating the Microsoft recommended block rules.xml' Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath '.\Microsoft recommended block rules.xml' -Force + Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' @@ -733,7 +746,7 @@ Function New-WDACConfig { switch ($true) { # Deploy the latest block rules - { $GetBlockRules -and $Deploy } { & $DeployLatestBlockRulesSCRIPTBLOCK; break } + { $GetBlockRules -and $Deploy } { Deploy-LatestBlockRules ; break } # Get the latest block rules $GetBlockRules { Get-BlockRulesMeta -Verbose:$Verbose ; break } # Get the latest driver block rules and Deploy them if New-WDACConfig -GetDriverBlockRules was called with -Deploy parameter From aefda4b3ffa9dd988f939318f07ad67424be3b65 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 06:48:19 -0930 Subject: [PATCH 104/178] Created new function: Build-MSFTOnlyAudit --- .../Core/New-WDACConfig.psm1 | 33 +++++++++++++++++-- .../Shared/Set-LogSize.psm1 | 1 + 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 149661a1a..d85223bc6 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -493,15 +493,42 @@ Function New-WDACConfig { Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK } - [System.Management.Automation.ScriptBlock]$PrepMSFTOnlyAuditSCRIPTBLOCK = { - if ($PrepMSFTOnlyAudit -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } + Function Build-MSFTOnlyAudit { + <# + .SYNOPSIS + A helper function that creates a WDAC policy based on AllowMicrosoft template policy. + It has audit policy rule option. + It can also call the Set-LogSize function to modify the size of Code Integrity Operational event log + It uses the $LogSize variable available in the New-WDACConfig's scope to do that. + .INPUTS + System.Void + .OUTPUTS + System.Void + #> + + if ($PrepMSFTOnlyAudit -and $LogSize) { + Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' + Set-LogSize -LogSize $LogSize -Verbose:$Verbose + } + + Write-Verbose -Message 'Copying AllowMicrosoft.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination .\AllowMicrosoft.xml -Force + + Write-Verbose -Message 'Enabling Audit mode' Set-RuleOption -FilePath .\AllowMicrosoft.xml -Option 3 + + Write-Verbose -Message 'Resetting the Policy ID' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\AllowMicrosoft.xml -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) + + Write-Verbose -Message 'Assigning "PrepMSFTOnlyAudit" as the policy name' Set-CIPolicyIdInfo -PolicyName 'PrepMSFTOnlyAudit' -FilePath .\AllowMicrosoft.xml + + Write-Verbose -Message 'Converting AllowMicrosoft.xml to .CIP Binary' ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoft.xml -BinaryFilePath "$PolicyID.cip" | Out-Null + if ($Deploy) { + Write-Verbose -Message 'Deploying the AllowMicrosoft.xml policy on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color HotPink -InputText 'The default AllowMicrosoft policy has been deployed in Audit mode. No reboot required.' Remove-Item -Path 'AllowMicrosoft.xml', "$PolicyID.cip" -Force @@ -755,7 +782,7 @@ Function New-WDACConfig { $SetAutoUpdateDriverBlockRules { Set-AutoUpdateDriverBlockRules ; break } $MakeAllowMSFTWithBlockRules { Build-AllowMSFTWithBlockRules ; break } $MakePolicyFromAuditLogs { & $MakePolicyFromAuditLogsSCRIPTBLOCK; break } - $PrepMSFTOnlyAudit { & $PrepMSFTOnlyAuditSCRIPTBLOCK; break } + $PrepMSFTOnlyAudit { Build-MSFTOnlyAudit ; break } $MakeLightPolicy { & $MakeLightPolicySCRIPTBLOCK; break } $MakeDefaultWindowsWithBlockRules { Build-DefaultWindowsWithBlockRules ; break } $PrepDefaultWindowsAudit { & $PrepDefaultWindowsAuditSCRIPTBLOCK; break } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 index 47e658a1e..0bfd6148b 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 @@ -13,6 +13,7 @@ Function Set-LogSize { param ( [System.Int64]$LogSize ) + Write-Verbose -Message "Setting 'Microsoft-Windows-CodeIntegrity/Operational' log size to $LogSize" [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' [System.Diagnostics.Eventing.Reader.EventLogConfiguration]$Log = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogConfiguration -ArgumentList $LogName $Log.MaximumSizeInBytes = $LogSize From c02a432886e151f8884bac29365dbf1316edd5d9 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 08:48:36 -0930 Subject: [PATCH 105/178] Created new Build-PolicyFromAuditLogs function --- .../Core/New-WDACConfig.psm1 | 65 ++++++++++++++++--- 1 file changed, 56 insertions(+), 9 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index d85223bc6..59c5cb5bc 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -539,7 +539,10 @@ Function New-WDACConfig { } [System.Management.Automation.ScriptBlock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { - if ($PrepDefaultWindowsAudit -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } + if ($PrepDefaultWindowsAudit -and $LogSize) { + Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' + Set-LogSize -LogSize $LogSize -Verbose:$Verbose + } Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml' -Destination .\DefaultWindows_Audit.xml -Force # Making Sure neither PowerShell core nor WDACConfig module files are added to the Supplemental policy created by -MakePolicyFromAuditLogs parameter @@ -570,18 +573,35 @@ Function New-WDACConfig { } } - [System.Management.Automation.ScriptBlock]$MakePolicyFromAuditLogsSCRIPTBLOCK = { - if ($MakePolicyFromAuditLogs -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } + Function Build-PolicyFromAuditLogs { + <# + .SYNOPSIS + A helper function that creates 2 WDAC policies. A bas policy from one of the standard templates + and a Supplemental policy based on the Code Integrity Operational audit logs + .INPUTS + System.Void + .OUTPUTS + System.Void + #> + + if ($MakePolicyFromAuditLogs -and $LogSize) { + Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' + Set-LogSize -LogSize $LogSize -Verbose:$Verbose + } + # Make sure there is no leftover files from previous operations of this same command + Write-Verbose -Message 'Make sure there is no leftover files from previous operations of this same command' Remove-Item -Path "$home\WDAC\*" -Recurse -Force -ErrorAction SilentlyContinue + # Create a working directory in user's folder + Write-Verbose -Message 'Create a working directory in user folder' New-Item -Type Directory -Path "$home\WDAC" -Force | Out-Null Set-Location "$home\WDAC" - ############################### Base Policy Processing ############################### - + #Region Base-Policy-Processing switch ($BasePolicyType) { 'Allow Microsoft Base' { + Write-Verbose -Message 'Creating Allow Microsoft Base policy' Build-AllowMSFTWithBlockRules | Out-Null $xml = [System.Xml.XmlDocument](Get-Content -Path .\AllowMicrosoftPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID @@ -589,6 +609,7 @@ Function New-WDACConfig { $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' } 'Default Windows Base' { + Write-Verbose -Message 'Creating Default Windows Base policy' Build-DefaultWindowsWithBlockRules | Out-Null $xml = [System.Xml.XmlDocument](Get-Content -Path .\DefaultWindowsPlusBlockRules.xml) $BasePolicyID = $xml.SiPolicy.PolicyID @@ -596,15 +617,19 @@ Function New-WDACConfig { $BasePolicy = 'DefaultWindowsPlusBlockRules.xml' } } + if ($TestMode -and $MakePolicyFromAuditLogs) { + Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath $BasePolicy -Option $_ } } + if ($RequireEVSigners -and $MakePolicyFromAuditLogs) { + Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option because RequireEVSigners parameter was used' Set-RuleOption -FilePath $BasePolicy -Option 8 } + #Endregion Base-Policy-Processing - ############################### Supplemental Processing ############################### - + #Region Supplemental-Policy-Processing # Produce a policy xml file from event viewer logs Write-ColorfulText -Color Lavender -InputText 'Scanning Windows Event logs and creating a policy file, please wait...' @@ -627,6 +652,7 @@ Function New-WDACConfig { Write-ColorfulText -Color HotPink -InputText "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable Write-Host -Object "`n" + # Create the supplemental policy via parameter splatting for files in event viewer that are currently on the disk New-CIPolicy @PolicyMakerHashTable @@ -670,18 +696,29 @@ Function New-WDACConfig { else { Rename-Item -Path 'AuditLogsPolicy_NoDeletedFiles.xml' -NewName 'SupplementalPolicy.xml' -Force } - # Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy + + Write-Verbose -Message 'Setting the version for SupplementalPolicy.xml policy to 1.0.0.0' Set-CIPolicyVersion -FilePath 'SupplementalPolicy.xml' -Version '1.0.0.0' + + # Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy + Write-Verbose -Message 'Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath 'SupplementalPolicy.xml' -PolicyName "Supplemental Policy made from Audit Event Logs on $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $BasePolicy [System.String]$PolicyID = $PolicyID.Substring(11) + # Make sure policy rule options that don't belong to a Supplemental policy don't exit + Write-Verbose -Message 'Setting the policy rule options for the Supplemental policy by making sure policy rule options that do not belong to a Supplemental policy do not exit' @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath 'SupplementalPolicy.xml' -Option $_ -Delete } # Set the hypervisor Code Integrity option for Supplemental policy to Strict + Write-Verbose -Message 'Setting HVCI to strict for SupplementalPolicy.xml' Set-HVCIOptions -Strict -FilePath 'SupplementalPolicy.xml' + # convert the Supplemental Policy file to .cip binary file + Write-Verbose -Message 'Converting SupplementalPolicy.xml policy to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$policyID.cip" | Out-Null + #Endregion Supplemental-Policy-Processing + [PSCustomObject]@{ BasePolicyFile = $BasePolicy BasePolicyGUID = $BasePolicyID @@ -696,18 +733,26 @@ Function New-WDACConfig { } if ($Deploy -and $MakePolicyFromAuditLogs) { + + Write-Verbose -Message 'Deploying the Base policy and Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null + Write-ColorfulText -Color Pink -InputText "`nBase policy and Supplemental Policies deployed and activated.`n" + # Get the correct Prep mode Audit policy ID to remove from the system + Write-Verbose -Message 'Getting the correct Prep mode Audit policy ID to remove from the system' switch ($BasePolicyType) { 'Allow Microsoft Base' { + Write-Verbose -Message 'Going to remove the AllowMicrosoft policy from the system because Allow Microsoft Base was used' $IDToRemove = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepMSFTOnlyAudit' }).PolicyID } 'Default Windows Base' { + Write-Verbose -Message 'Going to remove the DefaultWindows policy from the system because Default Windows Base was used' $IDToRemove = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.FriendlyName -eq 'PrepDefaultWindows' }).PolicyID } } + &'C:\Windows\System32\CiTool.exe' --remove-policy "{$IDToRemove}" -json | Out-Null Write-ColorfulText -Color Lavender -InputText "`nSystem restart required to finish removing the Audit mode Prep policy" } @@ -720,9 +765,11 @@ Function New-WDACConfig { Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } if ($TestMode -and $MakeLightPolicy) { + Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } } if ($RequireEVSigners -and $MakeLightPolicy) { + Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\SignedAndReputable.xml -Option 8 } $BasePolicyID = Set-CIPolicyIdInfo -FilePath .\SignedAndReputable.xml -ResetPolicyID -PolicyName "Signed And Reputable policy - $(Get-Date -Format 'MM-dd-yyyy')" @@ -781,7 +828,7 @@ Function New-WDACConfig { $SetAutoUpdateDriverBlockRules { Set-AutoUpdateDriverBlockRules ; break } $MakeAllowMSFTWithBlockRules { Build-AllowMSFTWithBlockRules ; break } - $MakePolicyFromAuditLogs { & $MakePolicyFromAuditLogsSCRIPTBLOCK; break } + $MakePolicyFromAuditLogs { Build-PolicyFromAuditLogs ; break } $PrepMSFTOnlyAudit { Build-MSFTOnlyAudit ; break } $MakeLightPolicy { & $MakeLightPolicySCRIPTBLOCK; break } $MakeDefaultWindowsWithBlockRules { Build-DefaultWindowsWithBlockRules ; break } From ccaca81b48e21d8ae93bd4ab9885825238bd1c5f Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 09:14:21 -0930 Subject: [PATCH 106/178] Created new Build-LightPolicy function --- .../Core/New-WDACConfig.psm1 | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 59c5cb5bc..c4854bdd4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -652,7 +652,7 @@ Function New-WDACConfig { Write-ColorfulText -Color HotPink -InputText "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable Write-Host -Object "`n" - + # Create the supplemental policy via parameter splatting for files in event viewer that are currently on the disk New-CIPolicy @PolicyMakerHashTable @@ -758,12 +758,31 @@ Function New-WDACConfig { } } - [System.Management.Automation.ScriptBlock]$MakeLightPolicySCRIPTBLOCK = { - # Delete the any policy with the same name in the current working directory + Function Build-LightPolicy { + <# + .SYNOPSIS + A helper function that created SignedAndReputable WDAC policy + which is based on AllowMicrosoft template policy. + It includes Microsoft Recommended Block rules. + It uses ISG to authorize files with good reputation. + .INPUTS + System.Void + .OUTPUTS + System.Void + #> + + # Delete any policy with the same name in the current working directory Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue + + Write-Verbose -Message 'Calling Build-AllowMSFTWithBlockRules function to create AllowMicrosoftPlusBlockRules.xml policy' Build-AllowMSFTWithBlockRules -NoCIP + + Write-Verbose -Message 'Renaming AllowMicrosoftPlusBlockRules.xml to SignedAndReputable.xml' Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force + + Write-Verbose -Message 'Setting the policy rule options for the SignedAndReputable.xml policy' @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } + if ($TestMode -and $MakeLightPolicy) { Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } @@ -772,17 +791,31 @@ Function New-WDACConfig { Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\SignedAndReputable.xml -Option 8 } + + Write-Verbose -Message 'Resetting the policy ID and setting a name for SignedAndReputable.xml' $BasePolicyID = Set-CIPolicyIdInfo -FilePath .\SignedAndReputable.xml -ResetPolicyID -PolicyName "Signed And Reputable policy - $(Get-Date -Format 'MM-dd-yyyy')" $BasePolicyID = $BasePolicyID.Substring(11) + + Write-Verbose -Message 'Setting the version of SignedAndReputable.xml policy to 1.0.0.0' Set-CIPolicyVersion -FilePath .\SignedAndReputable.xml -Version '1.0.0.0' + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\SignedAndReputable.xml + + Write-Verbose -Message 'Converting SignedAndReputable.xml policy to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath .\SignedAndReputable.xml -BinaryFilePath "$BasePolicyID.cip" | Out-Null + # Configure required services for ISG authorization + Write-Verbose -Message 'Configuring required services for ISG authorization' Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow + if ($Deploy -and $MakeLightPolicy) { + Write-Verbose -Message 'Deploying the SignedAndReputable.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null } + + Write-Verbose -Message 'Displaying the output' [PSCustomObject]@{ BasePolicyFile = 'SignedAndReputable.xml' BasePolicyGUID = $BasePolicyID @@ -830,7 +863,7 @@ Function New-WDACConfig { $MakeAllowMSFTWithBlockRules { Build-AllowMSFTWithBlockRules ; break } $MakePolicyFromAuditLogs { Build-PolicyFromAuditLogs ; break } $PrepMSFTOnlyAudit { Build-MSFTOnlyAudit ; break } - $MakeLightPolicy { & $MakeLightPolicySCRIPTBLOCK; break } + $MakeLightPolicy { Build-LightPolicy ; break } $MakeDefaultWindowsWithBlockRules { Build-DefaultWindowsWithBlockRules ; break } $PrepDefaultWindowsAudit { & $PrepDefaultWindowsAuditSCRIPTBLOCK; break } default { Write-Warning 'None of the main parameters were selected.'; break } From 6396db84526ae88a672dfcca2f27592f1510b19d Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 09:25:15 -0930 Subject: [PATCH 107/178] Created a new function: Build-DefaultWindowsAudit --- .../Core/New-WDACConfig.psm1 | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index c4854bdd4..4d2e94723 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -538,34 +538,70 @@ Function New-WDACConfig { } } - [System.Management.Automation.ScriptBlock]$PrepDefaultWindowsAuditSCRIPTBLOCK = { + Function Build-DefaultWindowsAudit { + <# + .SYNOPSIS + A helper function that creates a WDAC policy based on DefaultWindows template policy. + It has audit policy rule option. + It can also call the Set-LogSize function to modify the size of Code Integrity Operational event log + It uses the $LogSize variable available in the New-WDACConfig's scope to do that. + .INPUTS + System.Void + .OUTPUTS + System.Void + #> + if ($PrepDefaultWindowsAudit -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' Set-LogSize -LogSize $LogSize -Verbose:$Verbose } + + Write-Verbose -Message 'Copying DefaultWindows_Audit.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Audit.xml' -Destination .\DefaultWindows_Audit.xml -Force # Making Sure neither PowerShell core nor WDACConfig module files are added to the Supplemental policy created by -MakePolicyFromAuditLogs parameter # by adding them first to the deployed Default Windows policy in Audit mode. Because WDACConfig module files don't need to be allowed to run since they are *.ps1 and .*psm1 files # And PowerShell core files will be added to the DefaultWindows Base policy anyway if (Test-Path -Path 'C:\Program Files\PowerShell') { + Write-Verbose -Message 'Scanning PowerShell core directory and creating a policy file' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml + + Write-Verbose -Message 'Scanning WDACConfig module directory and creating a policy file' New-CIPolicy -ScanPath "$ModuleRootPath" -Level hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\WDACConfigModule.xml + + Write-Verbose -Message 'Merging the policy files for PowerShell core and WDACConfig module with the DefaultWindows_Audit.xml policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Audit.xml, .\AllowPowerShell.xml, .\WDACConfigModule.xml -OutputFilePath .\DefaultWindows_Audit_temp.xml | Out-Null + Write-Verbose -Message 'removing DefaultWindows_Audit.xml policy' Remove-Item -Path DefaultWindows_Audit.xml -Force + + Write-Verbose -Message 'Renaming DefaultWindows_Audit_temp.xml to DefaultWindows_Audit.xml' Rename-Item -Path .\DefaultWindows_Audit_temp.xml -NewName 'DefaultWindows_Audit.xml' -Force + + Write-Verbose -Message 'Removing AllowPowerShell.xml and WDACConfigModule.xml policies' Remove-Item -Path 'WDACConfigModule.xml', 'AllowPowerShell.xml' -Force } + Write-Verbose -Message 'Enabling Audit mode' Set-RuleOption -FilePath .\DefaultWindows_Audit.xml -Option 3 + + Write-Verbose -Message 'Resetting the Policy ID' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath .\DefaultWindows_Audit.xml -ResetPolicyID [System.String]$PolicyID = $PolicyID.Substring(11) + + Write-Verbose -Message 'Assigning "PrepDefaultWindowsAudit" as the policy name' Set-CIPolicyIdInfo -PolicyName 'PrepDefaultWindows' -FilePath .\DefaultWindows_Audit.xml + + Write-Verbose -Message 'Converting DefaultWindows_Audit.xml to .CIP Binary' ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Audit.xml -BinaryFilePath "$PolicyID.cip" | Out-Null + if ($Deploy) { + Write-Verbose -Message 'Deploying the DefaultWindows_Audit.xml policy on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null + Write-ColorfulText -Color Lavender -InputText 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' + + Write-Verbose -Message 'Removing the generated .CIP files' Remove-Item -Path 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force } else { @@ -865,7 +901,7 @@ Function New-WDACConfig { $PrepMSFTOnlyAudit { Build-MSFTOnlyAudit ; break } $MakeLightPolicy { Build-LightPolicy ; break } $MakeDefaultWindowsWithBlockRules { Build-DefaultWindowsWithBlockRules ; break } - $PrepDefaultWindowsAudit { & $PrepDefaultWindowsAuditSCRIPTBLOCK; break } + $PrepDefaultWindowsAudit { Build-DefaultWindowsAudit ; break } default { Write-Warning 'None of the main parameters were selected.'; break } } } From 8d7710b0c6ae8507444c410c49673408c121fefc Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 09:27:53 -0930 Subject: [PATCH 108/178] Added Cmdletbinding to the functions --- .../WDACConfig Module Files/Core/New-WDACConfig.psm1 | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 4d2e94723..b195ba735 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -505,6 +505,8 @@ Function New-WDACConfig { .OUTPUTS System.Void #> + [CmdletBinding()] + param() if ($PrepMSFTOnlyAudit -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' @@ -550,6 +552,8 @@ Function New-WDACConfig { .OUTPUTS System.Void #> + [CmdletBinding()] + param() if ($PrepDefaultWindowsAudit -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' @@ -619,7 +623,9 @@ Function New-WDACConfig { .OUTPUTS System.Void #> - + [CmdletBinding()] + param() + if ($MakePolicyFromAuditLogs -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' Set-LogSize -LogSize $LogSize -Verbose:$Verbose @@ -806,6 +812,8 @@ Function New-WDACConfig { .OUTPUTS System.Void #> + [CmdletBinding()] + param() # Delete any policy with the same name in the current working directory Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue From 3e683397af6f764cf0fa0ff450b83d067a079cfa Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 10:29:10 -0930 Subject: [PATCH 109/178] Improved main cmdlets function helps --- .../Core/Confirm-WDACConfig.psm1 | 6 ++++++ .../Core/Deploy-SignedWDACConfig.psm1 | 3 +++ .../Core/Edit-SignedWDACConfig.psm1 | 4 ++++ .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 4 ++++ .../Core/Get-CommonWDACConfig.psm1 | 5 +++++ .../Core/New-DenyWDACConfig.psm1 | 4 ++++ .../Core/New-KernelModeWDACConfig.psm1 | 2 ++ .../Core/New-SupplementalWDACConfig.psm1 | 3 +++ .../WDACConfig Module Files/Core/New-WDACConfig.psm1 | 10 +++++++--- 9 files changed, 38 insertions(+), 3 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index b3bb043ea..0660719db 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -168,5 +168,11 @@ Function Confirm-WDACConfig { .EXAMPLE Confirm-WDACConfig -ListActivePolicies +.INPUTS + System.Void + +.OUTPUTS + System.String + System.Object #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 50e3a8ae7..8c1298fc1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -255,6 +255,9 @@ Function Deploy-SignedWDACConfig { .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases +.INPUTS + System.String + System.String[] #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 8186d598a..b4ecbc3ab 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1057,6 +1057,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item The fallback level(s) that determine how the selected folder will be scanned. The default value for it is Hash. +.INPUTS + System.Int64 + System.String + System.String[] #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 7d801afab..3cfa943ee 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -885,6 +885,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item The accepted values are between 1024 KB and 18014398509481983 KB The max range is the maximum allowed log size by Windows Event viewer +.INPUTS + System.Int64 + System.String[] + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index a9d2f9f6f..ea5113999 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -115,4 +115,9 @@ Function Get-CommonWDACConfig { .PARAMETER StrictKernelNoFlightRootsPolicyGUID Shows the GUID of the Strict Kernel no Flights root mode policy +.INPUTS + System.Void + +.OUTPUTS + System.Object[] #> diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 976346d7b..28ec5a2ce 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -316,6 +316,10 @@ Function New-DenyWDACConfig { .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases It's used by the entire Cmdlet. + +.INPUTS + System.String[] + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 20bbb8a4a..4f0fef0f0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -383,5 +383,7 @@ Function New-KernelModeWDACConfig { .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases +.INPUTS + System.Void #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 33225f957..0f310d51c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -332,6 +332,9 @@ Function New-SupplementalWDACConfig { .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases +.INPUTS + System.String[] + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index b195ba735..c652a3632 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -64,13 +64,12 @@ Function New-WDACConfig { [ValidateSet([Levelz])] [parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] - [System.String]$Level = 'FilePublisher', # Setting the default value for the Level parameter + [System.String]$Level = 'FilePublisher', [ValidateSet([Fallbackz])] [parameter(Mandatory = $false, ParameterSetName = 'Make Policy From Audit Logs')] - [System.String[]]$Fallbacks = 'Hash', # Setting the default value for the Fallbacks parameter + [System.String[]]$Fallbacks = 'Hash', - # Setting the maxim range to the maximum allowed log size by Windows Event viewer [ValidateRange(1024KB, 18014398509481983KB)] [Parameter(Mandatory = $false, ParameterSetName = 'Prep MSFT Only Audit')] [Parameter(Mandatory = $false, ParameterSetName = 'Prep Default Windows Audit')] @@ -995,10 +994,15 @@ Function New-WDACConfig { .PARAMETER LogSize Specifies the log size for Microsoft-Windows-CodeIntegrity/Operational events. The values must be in the form of . e.g., 2MB, 10MB, 1GB, 1TB. The minimum accepted value is 1MB which is the default. + The maximum range is the maximum allowed log size by Windows Event viewer .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases +.INPUTS + System.Int64 + System.String[] + System.String #> } From 6c8d7b438a21f777e87ccad0cb68ddb098ceb0a0 Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 12:16:00 -0930 Subject: [PATCH 110/178] Implemented a central cmdlet parameter management Using PSDefaultParameterValues.ps1 --- .../Remove-ZerosFromIDs.psm1 | 2 +- .../Core/Confirm-WDACConfig.psm1 | 6 +++-- .../Core/Deploy-SignedWDACConfig.psm1 | 10 ++++--- .../Core/Edit-SignedWDACConfig.psm1 | 26 ++++++++++--------- .../Core/Edit-WDACConfig.psm1 | 22 +++++++++------- .../Core/Get-CommonWDACConfig.psm1 | 4 ++- .../Core/Invoke-WDACSimulation.psm1 | 6 +++-- .../Core/New-DenyWDACConfig.psm1 | 6 +++-- .../Core/New-KernelModeWDACConfig.psm1 | 8 +++--- .../Core/New-SupplementalWDACConfig.psm1 | 6 +++-- .../Core/New-WDACConfig.psm1 | 20 +++++++------- .../Core/Remove-CommonWDACConfig.psm1 | 4 ++- .../Core/Remove-WDACConfig.psm1 | 10 ++++--- .../Core/Set-CommonWDACConfig.psm1 | 4 ++- .../CoreExt/PSDefaultParameterValues.ps1 | 11 ++++++++ .../Resources/ArgumentCompleters.ps1 | 13 ++++++---- .../Resources/Resources2.ps1 | 7 +++-- .../Shared/Confirm-CertCN.psm1 | 5 +++- .../Shared/Get-AuditEventLogsProcessing.psm1 | 6 +++-- .../Shared/Get-BlockRulesMeta.psm1 | 4 ++- .../Shared/Get-FileRules.psm1 | 5 +++- .../Shared/Get-GlobalRootDrives.psm1 | 6 +++-- .../Shared/Get-RuleRefs.psm1 | 5 +++- .../Shared/Get-SignTool.psm1 | 5 +++- .../Shared/Move-UserModeToKernelMode.psm1 | 4 ++- .../Shared/New-EmptyPolicy.psm1 | 5 +++- .../Shared/Set-LogSize.psm1 | 5 +++- .../Shared/Test-FilePath.psm1 | 4 ++- .../Shared/Update-self.psm1 | 7 ++--- .../Shared/Write-ColorfulText.psm1 | 5 +++- .../WDACConfig Module Files/WDACConfig.psd1 | 1 + 31 files changed, 154 insertions(+), 78 deletions(-) create mode 100644 WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 diff --git a/WDACConfig/Utilities/Functions no longer in use/Remove-ZerosFromIDs.psm1 b/WDACConfig/Utilities/Functions no longer in use/Remove-ZerosFromIDs.psm1 index b84bf2d0c..d2301aa87 100644 --- a/WDACConfig/Utilities/Functions no longer in use/Remove-ZerosFromIDs.psm1 +++ b/WDACConfig/Utilities/Functions no longer in use/Remove-ZerosFromIDs.psm1 @@ -46,4 +46,4 @@ Function Remove-ZerosFromIDs { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Remove-ZerosFromIDs' -Verbose:$false +Export-ModuleMember -Function 'Remove-ZerosFromIDs' diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 0660719db..7af5eece3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -63,10 +63,12 @@ Function Confirm-WDACConfig { } begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Regular parameters are automatically bound to variables in the function scope # Dynamic parameters however, are only available in the parameter dictionary, which is why we have to access them using $PSBoundParameters diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 8c1298fc1..9f1c195da 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -30,12 +30,14 @@ Function Deploy-SignedWDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index b4ecbc3ab..8bf032921 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -117,20 +117,22 @@ Function Edit-SignedWDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Test-FilePath.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-AuditEventLogsProcessing.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Test-FilePath.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-AuditEventLogsProcessing.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 3cfa943ee..e6917eb44 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -97,18 +97,20 @@ Function Edit-WDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Test-FilePath.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-AuditEventLogsProcessing.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Test-FilePath.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-AuditEventLogsProcessing.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index ea5113999..d5f5ea4ee 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -12,9 +12,11 @@ Function Get-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 0de1befa2..23864576d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -14,13 +14,15 @@ Function Invoke-WDACSimulation { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$ModuleRootPath\Resources\Resources2.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 28ec5a2ce..87263af0d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -53,10 +53,12 @@ Function New-DenyWDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 4f0fef0f0..54d9a3f3a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -28,11 +28,13 @@ Function New-KernelModeWDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Move-UserModeToKernelMode.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Move-UserModeToKernelMode.psm1" -Force # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 0f310d51c..0f31fc98f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -59,10 +59,12 @@ Function New-SupplementalWDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # argument tab auto-completion and ValidateSet for Fallbacks Class Fallbackz : System.Management.Automation.IValidateSetValuesGenerator { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index c652a3632..a16d6fa59 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -80,17 +80,19 @@ Function New-WDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Set-LogSize.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-EmptyPolicy.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force #region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index 69495d78a..68fc1bec7 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -11,9 +11,11 @@ Function Remove-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck # DontShow prevents common parameters from being displayed too ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 7b1aa5552..16ba79098 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -114,12 +114,14 @@ Function Remove-WDACConfig { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force -Verbose:$false - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 87c2a20d8..efefa2922 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -52,9 +52,11 @@ Function Set-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.DateTime]$LastUpdateCheck ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 new file mode 100644 index 000000000..7952312cd --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -0,0 +1,11 @@ +# $PSDefaultParameterValues only get read from scope where invocation occurs +# This is why this file is dot-sourced in every other component of the WDACConfig module at the beginning +$PSDefaultParameterValues = @{ + 'Invoke-WebRequest:HttpVersion' = '3.0' + 'Invoke-WebRequest:SslProtocol' = 'Tls12,Tls13' + 'Invoke-RestMethod:HttpVersion' = '3.0' + 'Invoke-RestMethod:SslProtocol' = 'Tls12,Tls13' + 'Import-Module:Verbose' = $false + 'Export-ModuleMember:Verbose' = $false + 'Add-Type:Verbose' = $false +} \ No newline at end of file diff --git a/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 b/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 index 3d67cf713..ddf7117c4 100644 --- a/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 +++ b/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 @@ -11,6 +11,9 @@ } #> +# Importing the $PSDefaultParameterValues to the current session, prior to everything else +. "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # argument tab auto-completion for Policy Paths to show only .xml files and only suggest files that haven't been already selected by user # https://stackoverflow.com/questions/76141864/how-to-make-a-powershell-argument-completer-that-only-suggests-files-not-already/76142865 [System.Management.Automation.ScriptBlock]$ArgumentCompleterPolicyPaths = { @@ -116,7 +119,7 @@ # Opens Folder picker GUI so that user can select folders to be processed [System.Management.Automation.ScriptBlock]$ArgumentCompleterFolderPathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName 'System.Windows.Forms' -Verbose:$false + Add-Type -AssemblyName 'System.Windows.Forms' # non-top-most, works better with window focus [System.Windows.Forms.FolderBrowserDialog]$Browser = New-Object -TypeName 'System.Windows.Forms.FolderBrowserDialog' $null = $Browser.ShowDialog() @@ -127,7 +130,7 @@ # Opens File picker GUI so that user can select an .exe file - for SignTool.exe [System.Management.Automation.ScriptBlock]$ArgumentCompleterExeFilePathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName 'System.Windows.Forms' -Verbose:$false + Add-Type -AssemblyName 'System.Windows.Forms' # Create a new OpenFileDialog object [System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog' # Set the filter to show only executable files @@ -143,7 +146,7 @@ # Opens File picker GUI so that user can select a .cer file [System.Management.Automation.ScriptBlock]$ArgumentCompleterCerFilePathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName 'System.Windows.Forms' -Verbose:$false + Add-Type -AssemblyName 'System.Windows.Forms' # Create a new OpenFileDialog object [System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog' # Set the filter to show only certificate files @@ -159,7 +162,7 @@ # Opens File picker GUI so that user can select a .xml file [System.Management.Automation.ScriptBlock]$ArgumentCompleterXmlFilePathsPicker = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName 'System.Windows.Forms' -Verbose:$false + Add-Type -AssemblyName 'System.Windows.Forms' # Create a new OpenFileDialog object [System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog' # Set the filter to show only XML files @@ -176,7 +179,7 @@ # WildCard file paths [System.Management.Automation.ScriptBlock]$ArgumentCompleterFolderPathsPickerWildCards = { # Load the System.Windows.Forms assembly - Add-Type -AssemblyName 'System.Windows.Forms' -Verbose:$false + Add-Type -AssemblyName 'System.Windows.Forms' # non-top-most, works better with window focus [System.Windows.Forms.FolderBrowserDialog]$Browser = New-Object -TypeName 'System.Windows.Forms.FolderBrowserDialog' $null = $Browser.ShowDialog() diff --git a/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 b/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 index c9c77f216..1a6a683d6 100644 --- a/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 +++ b/WDACConfig/WDACConfig Module Files/Resources/Resources2.ps1 @@ -1,3 +1,6 @@ +# Importing the $PSDefaultParameterValues to the current session, prior to everything else +. "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Defining a custom object to store the signer information class Signer { [System.String]$ID @@ -176,9 +179,9 @@ Function Get-AuthenticodeSignatureEx { '@ # Load the System.Security assembly to use the SignedCms class - Add-Type -AssemblyName 'System.Security' -ErrorAction SilentlyContinue -Verbose:$false + Add-Type -AssemblyName 'System.Security' -ErrorAction SilentlyContinue # Add the Crypt32.dll library functions as a type - Add-Type -MemberDefinition $Signature -Namespace 'PKI' -Name 'Crypt32' -ErrorAction SilentlyContinue -Verbose:$false + Add-Type -MemberDefinition $Signature -Namespace 'PKI' -Name 'Crypt32' -ErrorAction SilentlyContinue # Define some constants for the CryptQueryObject function parameters [System.Int16]$CERT_QUERY_OBJECT_FILE = 0x1 diff --git a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 index 9b1bd979d..3a41a424b 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 @@ -11,6 +11,9 @@ Function Confirm-CertCN { param ( [System.String]$CN ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } @@ -18,4 +21,4 @@ Function Confirm-CertCN { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Confirm-CertCN' -Verbose:$false +Export-ModuleMember -Function 'Confirm-CertCN' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 index 657cd2744..251be4431 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -13,8 +13,10 @@ Function Get-AuditEventLogsProcessing { ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-GlobalRootDrives.psm1" -Force # Get the local disks mappings [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives @@ -67,4 +69,4 @@ Function Get-AuditEventLogsProcessing { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Get-AuditEventLogsProcessing' -Verbose:$false +Export-ModuleMember -Function 'Get-AuditEventLogsProcessing' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 5f85cee4a..cff90c24b 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -9,6 +9,8 @@ Function Get-BlockRulesMeta { #> [CmdletBinding()] param () + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force @@ -23,4 +25,4 @@ Function Get-BlockRulesMeta { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Get-BlockRulesMeta' -Verbose:$false +Export-ModuleMember -Function 'Get-BlockRulesMeta' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 index e29f233ad..8879d8de0 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -5,6 +5,9 @@ Function Get-FileRules { #> [CmdletBinding()] param ($HashesArray) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $Rules += Write-Output -InputObject "`n" $Rules += Write-Output -InputObject "`n" @@ -16,4 +19,4 @@ Function Get-FileRules { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Get-FileRules' -Verbose:$false +Export-ModuleMember -Function 'Get-FileRules' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 index 6c078e271..d24bbc6cc 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 @@ -12,6 +12,8 @@ Function Get-GlobalRootDrives { #> [CmdletBinding()] param () + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Import the kernel32.dll functions using P/Invoke [System.String]$Signature = @' @@ -33,7 +35,7 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa '@ # Add the signature to the current session as a new type - Add-Type -ErrorAction SilentlyContinue -MemberDefinition $Signature -Name 'Win32Utils' -Namespace 'PInvoke' -Using PInvoke, System.Text -Verbose:$false + Add-Type -ErrorAction SilentlyContinue -MemberDefinition $Signature -Name 'Win32Utils' -Namespace 'PInvoke' -Using PInvoke, System.Text # Initialize some variables for storing the volume names, paths, and mount points [System.UInt32]$lpcchReturnLength = 0 @@ -74,4 +76,4 @@ public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTa } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Get-GlobalRootDrives' -Verbose:$false +Export-ModuleMember -Function 'Get-GlobalRootDrives' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 index 4f62787ac..e00120e63 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -5,6 +5,9 @@ Function Get-RuleRefs { #> [CmdletBinding()] param ($HashesArray) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $RulesRefs += Write-Output -InputObject "`n" $RulesRefs += Write-Output -InputObject "`n" @@ -16,4 +19,4 @@ Function Get-RuleRefs { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Get-RuleRefs' -Verbose:$false +Export-ModuleMember -Function 'Get-RuleRefs' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 index b0666861f..8c7df1101 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -13,6 +13,9 @@ Function Get-SignTool { param( [parameter(Mandatory = $false)][System.String]$SignToolExePath ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # If Sign tool path wasn't provided by parameter, try to detect it automatically, if fails, stop the operation if (!$SignToolExePath) { if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64') { @@ -54,4 +57,4 @@ Function Get-SignTool { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Get-SignTool' -Verbose:$false +Export-ModuleMember -Function 'Get-SignTool' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 index 185821052..6acbc2c63 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 @@ -10,6 +10,8 @@ Function Move-UserModeToKernelMode { [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [System.String]$FilePath ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Load the XML file as an XmlDocument object $Xml = [System.Xml.XmlDocument](Get-Content -Path $FilePath) @@ -56,4 +58,4 @@ Function Move-UserModeToKernelMode { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Move-UserModeToKernelMode' -Verbose:$false +Export-ModuleMember -Function 'Move-UserModeToKernelMode' diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 index 2b6951bdd..0ffa288bf 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 @@ -8,6 +8,9 @@ Function New-EmptyPolicy { $RulesContent, $RuleRefsContent ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + [System.String]$EmptyPolicy = @" @@ -59,4 +62,4 @@ $RuleRefsContent } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'New-EmptyPolicy' -Verbose:$false +Export-ModuleMember -Function 'New-EmptyPolicy' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 index 0bfd6148b..0fbf0da0d 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 @@ -13,6 +13,9 @@ Function Set-LogSize { param ( [System.Int64]$LogSize ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + Write-Verbose -Message "Setting 'Microsoft-Windows-CodeIntegrity/Operational' log size to $LogSize" [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' [System.Diagnostics.Eventing.Reader.EventLogConfiguration]$Log = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogConfiguration -ArgumentList $LogName @@ -22,4 +25,4 @@ Function Set-LogSize { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Set-LogSize' -Verbose:$false +Export-ModuleMember -Function 'Set-LogSize' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 index 046e31fc8..f9bc17e81 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 @@ -12,6 +12,8 @@ Function Test-FilePath { [Parameter(Mandatory = $true)] [System.String[]]$DirectoryPath ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Loop through each file path foreach ($file in $FilePath) { @@ -56,4 +58,4 @@ Function Test-FilePath { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Test-FilePath' -Verbose:$false +Export-ModuleMember -Function 'Test-FilePath' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index 0b9c26ed6..eba75988e 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -9,9 +9,10 @@ Function Update-self { #> [CmdletBinding()] param() - + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force -Verbose:$false + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force try { # Get the last update check time @@ -79,4 +80,4 @@ Function Update-self { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Update-self' -Verbose:$false +Export-ModuleMember -Function 'Update-self' diff --git a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 index d1a845f5b..065b851a6 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 @@ -20,6 +20,9 @@ Function Write-ColorfulText { [Alias('I')] [System.String]$InputText ) + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + switch ($Color) { 'Fuchsia' { Write-Host "$($PSStyle.Foreground.FromRGB(236,68,155))$InputText$($PSStyle.Reset)"; break } 'Orange' { Write-Host "$($PSStyle.Foreground.FromRGB(255,165,0))$InputText$($PSStyle.Reset)"; break } @@ -63,4 +66,4 @@ Function Write-ColorfulText { } # Export external facing functions only, prevent internal functions from getting exported -Export-ModuleMember -Function 'Write-ColorfulText' -Verbose:$false +Export-ModuleMember -Function 'Write-ColorfulText' diff --git a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 index b67d11a7e..e949dadda 100644 --- a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 @@ -183,6 +183,7 @@ To get help and syntax on PowerShell console, type: 'Core\Invoke-WDACSimulation.psm1', 'Core\Get-CommonWDACConfig.psm1', 'Core\Remove-CommonWDACConfig.psm1', + 'CoreExt\PSDefaultParameterValues.ps1', 'Resources\Resources2.ps1', 'Resources\ArgumentCompleters.ps1' 'Resources\WDAC Policies\DefaultWindows_Enforced_Kernel.xml', From 39fa8ca76bdb1530db84771d13a591483e17e4bc Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 12:16:48 -0930 Subject: [PATCH 111/178] Removed unnecessary trailing whitespace --- .../Core/New-WDACConfig.psm1 | 54 +++++++++---------- .../Shared/Confirm-CertCN.psm1 | 2 +- .../Shared/Get-FileRules.psm1 | 2 +- .../Shared/Get-RuleRefs.psm1 | 2 +- .../Shared/Get-SignTool.psm1 | 2 +- .../Shared/New-EmptyPolicy.psm1 | 2 +- .../Shared/Set-LogSize.psm1 | 2 +- .../Shared/Write-ColorfulText.psm1 | 2 +- 8 files changed, 34 insertions(+), 34 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index a16d6fa59..bd06c2079 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -428,11 +428,11 @@ Function New-WDACConfig { Write-Verbose -Message 'Downloading the latest Microsoft recommended block rules and creating Microsoft recommended block rules TEMP.xml' (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force - + # Remove empty lines from the policy file Write-Verbose -Message 'Removing any empty lines from the Temp policy file and generating the Microsoft recommended block rules.xml' Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath '.\Microsoft recommended block rules.xml' -Force - + Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete @(0, 2, 6, 11, 12, 16, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option $_ } Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' @@ -513,10 +513,10 @@ Function New-WDACConfig { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' Set-LogSize -LogSize $LogSize -Verbose:$Verbose } - + Write-Verbose -Message 'Copying AllowMicrosoft.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination .\AllowMicrosoft.xml -Force - + Write-Verbose -Message 'Enabling Audit mode' Set-RuleOption -FilePath .\AllowMicrosoft.xml -Option 3 @@ -529,7 +529,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Converting AllowMicrosoft.xml to .CIP Binary' ConvertFrom-CIPolicy -XmlFilePath .\AllowMicrosoft.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - + if ($Deploy) { Write-Verbose -Message 'Deploying the AllowMicrosoft.xml policy on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null @@ -555,7 +555,7 @@ Function New-WDACConfig { #> [CmdletBinding()] param() - + if ($PrepDefaultWindowsAudit -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' Set-LogSize -LogSize $LogSize -Verbose:$Verbose @@ -570,10 +570,10 @@ Function New-WDACConfig { if (Test-Path -Path 'C:\Program Files\PowerShell') { Write-Verbose -Message 'Scanning PowerShell core directory and creating a policy file' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml - - Write-Verbose -Message 'Scanning WDACConfig module directory and creating a policy file' + + Write-Verbose -Message 'Scanning WDACConfig module directory and creating a policy file' New-CIPolicy -ScanPath "$ModuleRootPath" -Level hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\WDACConfigModule.xml - + Write-Verbose -Message 'Merging the policy files for PowerShell core and WDACConfig module with the DefaultWindows_Audit.xml policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Audit.xml, .\AllowPowerShell.xml, .\WDACConfigModule.xml -OutputFilePath .\DefaultWindows_Audit_temp.xml | Out-Null @@ -582,7 +582,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Renaming DefaultWindows_Audit_temp.xml to DefaultWindows_Audit.xml' Rename-Item -Path .\DefaultWindows_Audit_temp.xml -NewName 'DefaultWindows_Audit.xml' -Force - + Write-Verbose -Message 'Removing AllowPowerShell.xml and WDACConfigModule.xml policies' Remove-Item -Path 'WDACConfigModule.xml', 'AllowPowerShell.xml' -Force } @@ -596,16 +596,16 @@ Function New-WDACConfig { Write-Verbose -Message 'Assigning "PrepDefaultWindowsAudit" as the policy name' Set-CIPolicyIdInfo -PolicyName 'PrepDefaultWindows' -FilePath .\DefaultWindows_Audit.xml - + Write-Verbose -Message 'Converting DefaultWindows_Audit.xml to .CIP Binary' ConvertFrom-CIPolicy -XmlFilePath .\DefaultWindows_Audit.xml -BinaryFilePath "$PolicyID.cip" | Out-Null - + if ($Deploy) { Write-Verbose -Message 'Deploying the DefaultWindows_Audit.xml policy on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color Lavender -InputText 'The defaultWindows policy has been deployed in Audit mode. No reboot required.' - + Write-Verbose -Message 'Removing the generated .CIP files' Remove-Item -Path 'DefaultWindows_Audit.xml', "$PolicyID.cip" -Force } @@ -626,7 +626,7 @@ Function New-WDACConfig { #> [CmdletBinding()] param() - + if ($MakePolicyFromAuditLogs -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' Set-LogSize -LogSize $LogSize -Verbose:$Verbose @@ -635,7 +635,7 @@ Function New-WDACConfig { # Make sure there is no leftover files from previous operations of this same command Write-Verbose -Message 'Make sure there is no leftover files from previous operations of this same command' Remove-Item -Path "$home\WDAC\*" -Recurse -Force -ErrorAction SilentlyContinue - + # Create a working directory in user's folder Write-Verbose -Message 'Create a working directory in user folder' New-Item -Type Directory -Path "$home\WDAC" -Force | Out-Null @@ -742,12 +742,12 @@ Function New-WDACConfig { Write-Verbose -Message 'Setting the version for SupplementalPolicy.xml policy to 1.0.0.0' Set-CIPolicyVersion -FilePath 'SupplementalPolicy.xml' -Version '1.0.0.0' - + # Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy Write-Verbose -Message 'Convert the SupplementalPolicy.xml policy file from base policy to supplemental policy of our base policy' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath 'SupplementalPolicy.xml' -PolicyName "Supplemental Policy made from Audit Event Logs on $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $BasePolicy [System.String]$PolicyID = $PolicyID.Substring(11) - + # Make sure policy rule options that don't belong to a Supplemental policy don't exit Write-Verbose -Message 'Setting the policy rule options for the Supplemental policy by making sure policy rule options that do not belong to a Supplemental policy do not exit' @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath 'SupplementalPolicy.xml' -Option $_ -Delete } @@ -780,9 +780,9 @@ Function New-WDACConfig { Write-Verbose -Message 'Deploying the Base policy and Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null - + Write-ColorfulText -Color Pink -InputText "`nBase policy and Supplemental Policies deployed and activated.`n" - + # Get the correct Prep mode Audit policy ID to remove from the system Write-Verbose -Message 'Getting the correct Prep mode Audit policy ID to remove from the system' switch ($BasePolicyType) { @@ -824,10 +824,10 @@ Function New-WDACConfig { Write-Verbose -Message 'Renaming AllowMicrosoftPlusBlockRules.xml to SignedAndReputable.xml' Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force - + Write-Verbose -Message 'Setting the policy rule options for the SignedAndReputable.xml policy' @(14, 15) | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } - + if ($TestMode -and $MakeLightPolicy) { Write-Verbose -Message 'Setting "Boot Audit on Failure" and "Advanced Boot Options Menu" policy rule options because TestMode parameter was used' 9..10 | ForEach-Object -Process { Set-RuleOption -FilePath .\SignedAndReputable.xml -Option $_ } @@ -836,25 +836,25 @@ Function New-WDACConfig { Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option because RequireEVSigners parameter was used' Set-RuleOption -FilePath .\SignedAndReputable.xml -Option 8 } - + Write-Verbose -Message 'Resetting the policy ID and setting a name for SignedAndReputable.xml' $BasePolicyID = Set-CIPolicyIdInfo -FilePath .\SignedAndReputable.xml -ResetPolicyID -PolicyName "Signed And Reputable policy - $(Get-Date -Format 'MM-dd-yyyy')" $BasePolicyID = $BasePolicyID.Substring(11) - + Write-Verbose -Message 'Setting the version of SignedAndReputable.xml policy to 1.0.0.0' Set-CIPolicyVersion -FilePath .\SignedAndReputable.xml -Version '1.0.0.0' - + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\SignedAndReputable.xml Write-Verbose -Message 'Converting SignedAndReputable.xml policy to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath .\SignedAndReputable.xml -BinaryFilePath "$BasePolicyID.cip" | Out-Null - + # Configure required services for ISG authorization Write-Verbose -Message 'Configuring required services for ISG authorization' Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow - + if ($Deploy -and $MakeLightPolicy) { Write-Verbose -Message 'Deploying the SignedAndReputable.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 index 3a41a424b..7d64d6435 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 @@ -13,7 +13,7 @@ Function Confirm-CertCN { ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + [System.String[]]$Certificates = foreach ($cert in (Get-ChildItem -Path 'Cert:\CurrentUser\my')) { (($cert.Subject -split ',' | Select-Object -First 1) -replace 'CN=', '').Trim() } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 index 8879d8de0..e766f0886 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -7,7 +7,7 @@ Function Get-FileRules { param ($HashesArray) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $Rules += Write-Output -InputObject "`n" $Rules += Write-Output -InputObject "`n" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 index e00120e63..36a7c6328 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -7,7 +7,7 @@ Function Get-RuleRefs { param ($HashesArray) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + $HashesArray | ForEach-Object -Begin { $i = 1 } -Process { $RulesRefs += Write-Output -InputObject "`n" $RulesRefs += Write-Output -InputObject "`n" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 index 8c7df1101..1b9548d11 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -15,7 +15,7 @@ Function Get-SignTool { ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # If Sign tool path wasn't provided by parameter, try to detect it automatically, if fails, stop the operation if (!$SignToolExePath) { if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64') { diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 index 0ffa288bf..43658607b 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-EmptyPolicy.psm1 @@ -10,7 +10,7 @@ Function New-EmptyPolicy { ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + [System.String]$EmptyPolicy = @" diff --git a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 index 0fbf0da0d..7e1325c33 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Set-LogSize.psm1 @@ -15,7 +15,7 @@ Function Set-LogSize { ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + Write-Verbose -Message "Setting 'Microsoft-Windows-CodeIntegrity/Operational' log size to $LogSize" [System.String]$LogName = 'Microsoft-Windows-CodeIntegrity/Operational' [System.Diagnostics.Eventing.Reader.EventLogConfiguration]$Log = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogConfiguration -ArgumentList $LogName diff --git a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 index 065b851a6..908b03d66 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Write-ColorfulText.psm1 @@ -22,7 +22,7 @@ Function Write-ColorfulText { ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + switch ($Color) { 'Fuchsia' { Write-Host "$($PSStyle.Foreground.FromRGB(236,68,155))$InputText$($PSStyle.Reset)"; break } 'Orange' { Write-Host "$($PSStyle.Foreground.FromRGB(255,165,0))$InputText$($PSStyle.Reset)"; break } From 4ab4bcfd5e1014ca708ccde0034b6e059d378efb Mon Sep 17 00:00:00 2001 From: Violet Date: Fri, 8 Dec 2023 21:37:12 -0930 Subject: [PATCH 112/178] Fixed typo in the comment --- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 4 ++-- .../Core/New-SupplementalWDACConfig.psm1 | 6 +++--- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 8bf032921..722b5f2eb 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -611,7 +611,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $SuppPolicyID = $SuppPolicyID.Substring(11) Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath $SuppPolicyPath @@ -821,7 +821,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $SuppPolicyID = $SuppPolicyID.Substring(11) Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath $SuppPolicyPath diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 0f31fc98f..4092dedb8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -160,7 +160,7 @@ Function New-SupplementalWDACConfig { [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" @@ -190,7 +190,7 @@ Function New-SupplementalWDACConfig { [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } @@ -249,7 +249,7 @@ Function New-SupplementalWDACConfig { [System.String]$policyID = $policyID.Substring(11) Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index bd06c2079..c428ef8ef 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -748,8 +748,8 @@ Function New-WDACConfig { [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath 'SupplementalPolicy.xml' -PolicyName "Supplemental Policy made from Audit Event Logs on $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $BasePolicy [System.String]$PolicyID = $PolicyID.Substring(11) - # Make sure policy rule options that don't belong to a Supplemental policy don't exit - Write-Verbose -Message 'Setting the policy rule options for the Supplemental policy by making sure policy rule options that do not belong to a Supplemental policy do not exit' + # Make sure policy rule options that don't belong to a Supplemental policy don't exist + Write-Verbose -Message 'Setting the policy rule options for the Supplemental policy by making sure policy rule options that do not belong to a Supplemental policy do not exist' @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath 'SupplementalPolicy.xml' -Option $_ -Delete } # Set the hypervisor Code Integrity option for Supplemental policy to Strict From e48dce68ec3bd7194d49d4f7abe31b6e72395137 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 02:34:39 -0930 Subject: [PATCH 113/178] Substantially improved Edit-WDACConfig --- .../Core/Edit-SignedWDACConfig.psm1 | 3 +- .../Core/Edit-WDACConfig.psm1 | 292 ++++++++++++------ .../Core/New-WDACConfig.psm1 | 4 +- .../CoreExt/PSDefaultParameterValues.ps1 | 1 + 4 files changed, 202 insertions(+), 98 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 722b5f2eb..dfeb3bcfe 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -267,7 +267,6 @@ Function Edit-SignedWDACConfig { # Remove Enforced Mode CIP Remove-Item -Path ".\$PolicyID.cip" -Force } - [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives -Verbose:$Verbose } process { @@ -532,7 +531,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = Get-GlobalRootDrives -Verbose:$Verbose | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index e6917eb44..f2564bb92 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -182,27 +182,30 @@ Function Edit-WDACConfig { return [System.String[]]$Levelz } } - - # Redeploy the base policy in Enforced mode + function Update-BasePolicyToEnforced { + <# + .SYNOPSIS + A helper function used to redeploy the base policy in Enforced mode + #> # Deploy Enforced mode CIP - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force + Remove-Item -Path '.\EnforcedMode.cip' -Force } - - [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives -Verbose:$Verbose } process { if ($AllowNewApps) { # remove any possible files from previous runs + Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() @@ -210,28 +213,36 @@ Function Edit-WDACConfig { foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected - $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' + # Get the policy file name + [System.String]$PolicyFileName = Split-Path $PolicyPath -Leaf + # make sure no file with the same name already exists in Temp folder + Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force - $PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" + [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" - # Defining Base policy + Write-Verbose -Message 'Retrieving the Base policy name and ID' $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any + Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue + Write-Verbose -Message 'Creating Audit Mode CIP' + # Add Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 # Create CIP for Audit Mode - Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null + Write-Verbose -Message 'Creating Enforced Mode CIP' + # Remove Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Create CIP for Enforced Mode - Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - ################# Snap back guarantee ################# + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' <# @@ -253,50 +264,56 @@ REM Deleting this CMD file itself del "%~f0" "@ #> - # PowerShell and RunOnce Method + # Using PowerShell and RunOnce Method - $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - $command = @" -CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force + # Defining the registry path for RunOnce key + [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' + # Defining the command that will be executed by the RunOnce key in case of a reboot + [System.String]$Command = @" +CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force "@ - $command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - # Deploy Audit mode CIP - Write-Verbose -Message 'Deploying Audit mode CIP' - Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + # Saving the command to a file that will be executed by the RunOnce key in case of a reboot + $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force + # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key + New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null + + Write-Verbose -Message 'Deploying the Audit mode CIP' + # Deploy the Audit mode CIP + &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" + # Remove Audit Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force - # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + Remove-Item -Path '.\AuditMode.cip' -Force + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - ################################### User Interaction #################################### + #Region User-Interaction Write-ColorfulText -Color Pink -InputText "`nAudit mode deployed, start installing your programs now" Write-ColorfulText -Color HotPink -InputText "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" Pause # Store the program paths that user browses for in an array - [System.Object[]]$ProgramsPaths = @() + [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object "`nSelect program directories to scan" -ForegroundColor Cyan + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null - $OBJ = New-Object System.Windows.Forms.FolderBrowserDialog + [System.Windows.Forms.FolderBrowserDialog]$OBJ = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog $OBJ.InitialDirectory = "$env:SystemDrive" $OBJ.Description = $Description - $Spawn = New-Object System.Windows.Forms.Form -Property @{TopMost = $true } - $Show = $OBJ.ShowDialog($Spawn) + [System.Windows.Forms.Form]$Spawn = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true } + [System.String]$Show = $OBJ.ShowDialog($Spawn) If ($Show -eq 'OK') { $ProgramsPaths += $OBJ.SelectedPath } Else { break } } while ($true) - + #Endregion User-Interaction + # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { @@ -336,11 +353,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object -Process { $_ } - - #Process Program Folders From User input + $ProgramsPaths | ForEach-Object -Process { $_.FullName } # Scan each of the folder paths that user selected + Write-Verbose -Message 'Scanning each of the folder paths that user selected' for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -359,11 +375,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message "Currently scanning: $($ProgramsPaths[$i])" New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + # merge-cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' + + [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -372,113 +391,155 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } # Merge all of the policy XML files in the array into the final Supplemental policy + Write-Verbose -Message 'Merging all of the policy XML files in the array into the final Supplemental policy' Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null + Write-Verbose -Message 'Removing the ProgramDir_ScanResults* xml files' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - #################### Supplemental-policy-processing-and-deployment ############################ + #Region Supplemental-policy-processing-and-deployment + Write-Verbose -Message 'Supplemental policy processing and deployment' - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" - $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath + Write-Verbose -Message 'Getting the path of the Supplemental policy' + [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' + [System.String]$SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist + Write-Verbose -Message 'Making sure policy rule options that do not belong to a Supplemental policy do not exist' @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + + Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + + Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + + # Remove the policy xml file in Temp folder we created earlier + Write-Verbose -Message 'Removing the policy xml file in Temp folder we created earlier' + Remove-Item -Path $PolicyPath -Force + + #Endregion Supplemental-policy-processing-and-deployment } } if ($AllowNewAppsAuditEvents) { # Change Code Integrity event logs size - if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } + if ($AllowNewAppsAuditEvents -and $LogSize) { + Write-Verbose -Message 'Changing Code Integrity event logs size' + Set-LogSize -LogSize $LogSize -Verbose:$Verbose + } + # Make sure there is no leftover from previous runs + Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue + # Get the current date so that instead of the entire event viewer logs, only audit logs created after running this module will be captured - # The notice about variable being assigned and never used should be ignored - it's being dot-sourced from Resources file + Write-Verbose -Message 'Getting the current date' [System.DateTime]$Date = Get-Date + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() - ################################### Initiate Live Audit Mode ################################### - + #Initiate Live Audit Mode + foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected - $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' + # Get the policy file name + [System.String]$PolicyFileName = Split-Path $PolicyPath -Leaf + # make sure no file with the same name already exists in Temp folder + Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force - $PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" + [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" - # Defining Base policy + Write-Verbose -Message 'Retrieving the Base policy name and ID' $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any + Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue + Write-Verbose -Message 'Creating Audit Mode CIP' + # Add Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 # Create CIP for Audit Mode - Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null + Write-Verbose -Message 'Creating Enforced Mode CIP' + # Remove Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Create CIP for Enforced Mode - Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - ################# Snap back guarantee ################# + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' - $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - $command = @" -CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force + # Defining the registry path for RunOnce key + [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' + # Defining the command that will be executed by the RunOnce key in case of a reboot + [System.String]$Command = @" +CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force "@ - $command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - # Deploy Audit mode CIP - Write-Verbose -Message 'Deploying Audit mode CIP' - Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + # Saving the command to a file that will be executed by the RunOnce key in case of a reboot + $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force + # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key + New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null + + Write-Verbose -Message 'Deploying the Audit mode CIP' + # Deploy the Audit mode CIP + &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" + # Remove Audit Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force - # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + Remove-Item -Path '.\AuditMode.cip' -Force + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - ################################### User Interaction #################################### + #Region User-Interaction Write-ColorfulText -Color Pink -InputText "`nAudit mode deployed, start installing your programs now" Write-ColorfulText -Color HotPink -InputText "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" Pause # Store the program paths that user browses for in an array - [System.Object[]]$ProgramsPaths = @() + [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object "`nSelect program directories to scan`n" -ForegroundColor Cyan + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null - $OBJ = New-Object System.Windows.Forms.FolderBrowserDialog + [System.Windows.Forms.FolderBrowserDialog]$OBJ = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog $OBJ.InitialDirectory = "$env:SystemDrive" $OBJ.Description = $Description - $Spawn = New-Object System.Windows.Forms.Form -Property @{TopMost = $true } - $Show = $OBJ.ShowDialog($Spawn) + [System.Windows.Forms.Form]$Spawn = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true } + [System.String]$Show = $OBJ.ShowDialog($Spawn) If ($Show -eq 'OK') { $ProgramsPaths += $OBJ.SelectedPath } Else { break } } while ($true) + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -489,19 +550,20 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object -Process { $_ } + $ProgramsPaths | ForEach-Object -Process { $_.FullName } - ################################### EventCapturing ################################ + #Region EventCapturing Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date -Verbose:$Verbose - # Only create policy for files that are available on the disk based on Event viewer logs but weren't in user-selected program path(s), if there are any + # Only create policy for files that are available on the disk (based on Event viewer logs) + # but weren't in user-selected program path(s), if there are any if ($AuditEventLogsProcessingResults.AvailableFilesPaths) { - # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those + # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those by first copying them to another directory # this prevents duplicate rule creation and double file copying $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths -Verbose:$Verbose).path | Select-Object -Unique @@ -509,14 +571,15 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Another check to make sure there were indeed files found in Event viewer logs but weren't in any of the user-selected path(s) if ($TestFilePathResults) { + # Create a folder in Temp directory to copy the files that are not included in user-selected program path(s) # but detected in Event viewer audit logs, scan that folder, and in the end delete it - New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null + New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory -Force | Out-Null Write-Verbose -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" $TestFilePathResults | ForEach-Object -Process { Write-Verbose -Message "$_" - Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue + Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force -ErrorAction SilentlyContinue } # Create a policy XML file for available files on the disk @@ -537,11 +600,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$NoUserPEs) { $AvailableFilesOnDiskPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message 'Creating a policy file for files that are available on the disk but were not in user-selected program path(s)' New-CIPolicy @AvailableFilesOnDiskPolicyMakerHashTable # Add the policy XML file to the array that holds policy XML files $PolicyXMLFilesArray += '.\RulesForFilesNotInUserSelectedPaths.xml' + # Delete the Temporary folder in the TEMP folder + Write-Verbose -Message 'Deleting the Temporary folder in the TEMP folder' Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force } } @@ -550,22 +616,34 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # if user chose to include deleted files in the final supplemental policy if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { + Write-Verbose -Message 'Attempting to create a policy for files that are no longer available on the disk but were detected in event viewer logs' + Write-Verbose -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { Write-Verbose -Message "$($_.'File Name')" } + Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' + $FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose + $RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose).Trim() + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - ((Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose)).Trim() | Out-File -FilePath FileRulesAndFileRefs.txt -Force + Write-Verbose -Message 'Saving the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes' + $FileRulesHashesResults + $RuleRefsHashesResults | Out-File -FilePath FileRulesAndFileRefs.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force + Write-Verbose -Message 'Putting the Rules and RulesRefs in an empty policy file' + New-EmptyPolicy -RulesContent $FileRulesHashesResults -RuleRefsContent $RuleRefsHashesResults -Verbose:$Verbose | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force # adding the policy file that consists of rules from audit even logs, to the array + Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } + #Endregion EventCapturing + + #Region Process-Program-Folders-From-User-input + Write-Verbose -Message 'Scanning each of the folder paths that user selected' - ######################## Process Program Folders From User input ##################### for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -584,41 +662,50 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message "Currently scanning: $($ProgramsPaths[$i])" New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } + + # Merge-cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' - # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } + #Endregion Process-Program-Folders-From-User-input #region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them + Write-Verbose -Message 'Checking for Kernel protected files' + # Finding the file(s) first and storing them in an array [System.Object[]]$ExesWithNoHash = @() + # looping through each user-selected path(s) foreach ($ProgramsPath in $ProgramsPaths) { + # Making sure the currently processing path has any .exe in it - $AnyAvailableExes = (Get-ChildItem -Recurse -Path $ProgramsPath -Filter '*.exe').FullName + $AnyAvailableExes = (Get-ChildItem -File -Recurse -Path $ProgramsPath -Filter '*.exe').FullName + # if any .exe was found then continue testing them if ($AnyAvailableExes) { - $AnyAvailableExes | ForEach-Object -Process { - $CurrentExeWithNoHash = $_ + foreach ($CurrentExeWithNoHash in $AnyAvailableExes) { try { # Testing each executable to find the protected ones Get-FileHash -Path $CurrentExeWithNoHash -ErrorAction Stop | Out-Null } + # If the executable is protected, it will throw an exception and the script will continue to the next one # Making sure only the right file is captured by narrowing down the error type. # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException catch [System.UnauthorizedAccessException] { $ExesWithNoHash += $CurrentExeWithNoHash } } - } + } } # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { @@ -635,7 +722,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = Get-GlobalRootDrives -Verbose:$Verbose | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk @@ -701,31 +788,50 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Enforced mode CIP Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced + # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + } - #################### Supplemental-policy-processing-and-deployment ############################ + #Region Supplemental-policy-processing-and-deployment - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" - $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath + Write-Verbose -Message 'Supplemental policy processing and deployment' + [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' + [System.String]$SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) - # Make sure policy rule options that don't belong to a Supplemental policy don't exit + # Make sure policy rule options that don't belong to a Supplemental policy don't exist + Write-Verbose -Message 'Making sure policy rule options that do not belong to a Supplemental policy do not exist' @(0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + + Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + + Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + + # Remove the policy xml file in Temp folder we created earlier + Remove-Item -Path $PolicyPath -Force + + #Endregion Supplemental-policy-processing-and-deployment } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index c428ef8ef..c41275edf 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -710,7 +710,7 @@ Function New-WDACConfig { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = $DriveLettersGlobalRootFix | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = Get-GlobalRootDrives -Verbose:$Verbose | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } @@ -890,8 +890,6 @@ Function New-WDACConfig { # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } - - [System.Object[]]$DriveLettersGlobalRootFix = Get-GlobalRootDrives -Verbose:$Verbose } process { diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 7952312cd..69b355f6b 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -8,4 +8,5 @@ $PSDefaultParameterValues = @{ 'Import-Module:Verbose' = $false 'Export-ModuleMember:Verbose' = $false 'Add-Type:Verbose' = $false + 'Get-WinEvent:Verbose' = $false } \ No newline at end of file From 25e46c52797f356b12b8d18601589839daed368e Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 04:31:29 -0930 Subject: [PATCH 114/178] Improved error handling in Edit-WDACConfig --- .../Core/Edit-WDACConfig.psm1 | 31 ++++--------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index f2564bb92..38a73b383 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -324,16 +324,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } catch { # Show any extra info about any possible error that might've occurred - $_ - $_.CategoryInfo - $_.ErrorDetails - $_.Exception - $_.FullyQualifiedErrorId - $_.InvocationInfo - $_.PipelineIterationInfo - $_.PSMessageDetails - $_.ScriptStackTrace - $_.TargetObject + Throw $_ } finally { # Deploy Enforced mode CIP @@ -683,13 +674,13 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Checking for Kernel protected files' # Finding the file(s) first and storing them in an array - [System.Object[]]$ExesWithNoHash = @() + [System.String[]]$ExesWithNoHash = @() # looping through each user-selected path(s) foreach ($ProgramsPath in $ProgramsPaths) { # Making sure the currently processing path has any .exe in it - $AnyAvailableExes = (Get-ChildItem -File -Recurse -Path $ProgramsPath -Filter '*.exe').FullName + [System.String[]]$AnyAvailableExes = (Get-ChildItem -File -Recurse -Path $ProgramsPath -Filter '*.exe').FullName # if any .exe was found then continue testing them if ($AnyAvailableExes) { @@ -710,7 +701,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { - Write-Verbose -Message "The following Kernel protected files detected, creating allow rules for them:`n" + Write-Verbose -Message 'The following Kernel protected files detected, creating allow rules for them:' $ExesWithNoHash | ForEach-Object -Process { Write-Verbose -Message "$_" } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { @@ -773,16 +764,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Unlike AllowNewApps parameter, AllowNewAppsAuditEvents parameter performs Event viewer scanning and kernel protected files detection # So the base policy enforced mode snap back can't happen any sooner than this point catch { - $_ - $_.CategoryInfo - $_.ErrorDetails - $_.Exception - $_.FullyQualifiedErrorId - $_.InvocationInfo - $_.PipelineIterationInfo - $_.PSMessageDetails - $_.ScriptStackTrace - $_.TargetObject + Throw $_ } finally { # Deploy Enforced mode CIP @@ -793,7 +775,6 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - } #Region Supplemental-policy-processing-and-deployment @@ -830,7 +811,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - + #Endregion Supplemental-policy-processing-and-deployment } } From 7510dabd27988eca176d84d564875c78373aac03 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 04:36:51 -0930 Subject: [PATCH 115/178] Improved error handling in Edit-SignedWDACConfig --- .../Core/Edit-SignedWDACConfig.psm1 | 29 +++++-------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index dfeb3bcfe..2ee55fbd6 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -495,11 +495,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them # Finding the file(s) first and storing them in an array - [System.Object[]]$ExesWithNoHash = @() + [System.String[]]$ExesWithNoHash = @() + # looping through each user-selected path(s) foreach ($ProgramsPath in $ProgramsPaths) { + # Making sure the currently processing path has any .exe in it - $AnyAvailableExes = (Get-ChildItem -Recurse -Path $ProgramsPath -Filter '*.exe').FullName + [System.String[]]$AnyAvailableExes = (Get-ChildItem -Recurse -Path $ProgramsPath -Filter '*.exe').FullName # if any .exe was found then continue testing them if ($AnyAvailableExes) { $AnyAvailableExes | ForEach-Object -Process { @@ -582,21 +584,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Unlike AllowNewApps parameter, AllowNewAppsAuditEvents parameter performs Event viewer scanning and kernel protected files detection # So the base policy enforced mode snap back can't happen any sooner than this point catch { - $_ - $_.CategoryInfo - $_.ErrorDetails - $_.Exception - $_.FullyQualifiedErrorId - $_.InvocationInfo - $_.PipelineIterationInfo - $_.PSMessageDetails - $_.ScriptStackTrace - $_.TargetObject + Throw $_ } finally { # Deploy Enforced mode CIP Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced + # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force @@ -751,16 +745,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } catch { # Show any extra info about any possible error that might've occurred - $_ - $_.CategoryInfo - $_.ErrorDetails - $_.Exception - $_.FullyQualifiedErrorId - $_.InvocationInfo - $_.PipelineIterationInfo - $_.PSMessageDetails - $_.ScriptStackTrace - $_.TargetObject + Throw $_ } finally { # Deploy Enforced mode CIP From 1cccf9d3def3a6f18e9fff18b7f01b9d7ab8198e Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 05:45:31 -0930 Subject: [PATCH 116/178] Fixed function help Inputs sections with System.Void --- .../Core/Confirm-WDACConfig.psm1 | 3 +-- .../Core/Edit-SignedWDACConfig.psm1 | 2 +- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/New-KernelModeWDACConfig.psm1 | 2 +- .../Core/New-WDACConfig.psm1 | 22 +++++++++---------- .../Shared/Get-BlockRulesMeta.psm1 | 2 +- .../Shared/Get-GlobalRootDrives.psm1 | 2 +- .../Shared/Update-self.psm1 | 2 +- 8 files changed, 17 insertions(+), 20 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 7af5eece3..5d2cb0577 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -171,8 +171,7 @@ Function Confirm-WDACConfig { Confirm-WDACConfig -ListActivePolicies .INPUTS - System.Void - + None. You cannot pipe objects to this function. .OUTPUTS System.String System.Object diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 2ee55fbd6..c2c337172 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -252,7 +252,7 @@ Function Edit-SignedWDACConfig { .SYNOPSIS Re-Deploy Basepolicy in Enforced mode .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.String #> diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index d5f5ea4ee..903c82907 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -118,7 +118,7 @@ Function Get-CommonWDACConfig { Shows the GUID of the Strict Kernel no Flights root mode policy .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Object[] diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 54d9a3f3a..fdc0071d6 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -386,6 +386,6 @@ Function New-KernelModeWDACConfig { Can be used with any parameter to bypass the online version check - only to be used in rare cases .INPUTS - System.Void + None. You cannot pipe objects to this function. #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index c41275edf..a7547c3dd 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -143,9 +143,9 @@ Function New-WDACConfig { Gets the latest Microsoft Recommended Driver Block rules and processes them Can optionally deploy them .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS - PSCustomObject + System.String .PARAMETER Deploy Indicates that the function will deploy the latest Microsoft recommended drivers block list #> @@ -211,9 +211,7 @@ Function New-WDACConfig { Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK # Display the result as object - [PSCustomObject]@{ - PolicyFile = 'Microsoft recommended driver block rules.xml' - } + Write-Output -InputObject 'PolicyFile = Microsoft recommended driver block rules.xml' } } @@ -299,7 +297,7 @@ Function New-WDACConfig { and merges them with the DefaultWindows_Enforced template policy. It can also deploy the policy on the system. .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.String #> @@ -421,7 +419,7 @@ Function New-WDACConfig { .SYNOPSIS A helper function that downloads the latest Microsoft recommended block rules .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.String #> @@ -452,7 +450,7 @@ Function New-WDACConfig { In Windows up to date quickly ahead of its official release schedule. It does this by downloading and applying The latest block list every 7 days on the system. .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Void #> @@ -502,7 +500,7 @@ Function New-WDACConfig { It can also call the Set-LogSize function to modify the size of Code Integrity Operational event log It uses the $LogSize variable available in the New-WDACConfig's scope to do that. .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Void #> @@ -549,7 +547,7 @@ Function New-WDACConfig { It can also call the Set-LogSize function to modify the size of Code Integrity Operational event log It uses the $LogSize variable available in the New-WDACConfig's scope to do that. .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Void #> @@ -620,7 +618,7 @@ Function New-WDACConfig { A helper function that creates 2 WDAC policies. A bas policy from one of the standard templates and a Supplemental policy based on the Code Integrity Operational audit logs .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Void #> @@ -809,7 +807,7 @@ Function New-WDACConfig { It includes Microsoft Recommended Block rules. It uses ISG to authorize files with good reputation. .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Void #> diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index cff90c24b..75fb7c8ed 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -3,7 +3,7 @@ Function Get-BlockRulesMeta { .SYNOPSIS Gets the latest Microsoft Recommended block rules, removes its allow all rules and sets HVCI to strict .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS PSCustomObject #> diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 index d24bbc6cc..95a8149c7 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-GlobalRootDrives.psm1 @@ -6,7 +6,7 @@ Function Get-GlobalRootDrives { .LINK https://superuser.com/questions/1058217/list-every-device-harddiskvolume .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Objects[] #> diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index eba75988e..49b369f5e 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -3,7 +3,7 @@ Function Update-self { .SYNOPSIS Make sure the latest version of the module is installed and if not, automatically update it, clean up any old versions .INPUTS - System.Void + None. You cannot pipe objects to this function. .OUTPUTS System.Void #> From 42e5f5b7aab4de41ee6c2228b0ddc9e49021bd64 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 06:00:37 -0930 Subject: [PATCH 117/178] Improved function outputs and help sections --- .../Core/Confirm-WDACConfig.psm1 | 2 +- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 20 ++++----- .../Core/New-KernelModeWDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 22 +++++----- .../Core/New-WDACConfig.psm1 | 43 +++++++++---------- 6 files changed, 41 insertions(+), 50 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 5d2cb0577..5aab53811 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -171,7 +171,7 @@ Function Confirm-WDACConfig { Confirm-WDACConfig -ListActivePolicies .INPUTS - None. You cannot pipe objects to this function. + System.Management.Automation.SwitchParameter .OUTPUTS System.String System.Object diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 903c82907..847af074b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -118,7 +118,7 @@ Function Get-CommonWDACConfig { Shows the GUID of the Strict Kernel no Flights root mode policy .INPUTS - None. You cannot pipe objects to this function. + System.Management.Automation.SwitchParameter .OUTPUTS System.Object[] diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 87263af0d..6700f4461 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -148,10 +148,9 @@ Function New-DenyWDACConfig { Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - [PSCustomObject]@{ - DenyPolicyFile = "DenyPolicy $PolicyName.xml" - DenyPolicyGUID = $PolicyID - } + + Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" + Write-Output -InputObject "DenyPolicyGUID = $PolicyID" if (!$Debug) { Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force @@ -208,10 +207,9 @@ Function New-DenyWDACConfig { Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - [PSCustomObject]@{ - DenyPolicyFile = "DenyPolicy $PolicyName.xml" - DenyPolicyGUID = $PolicyID - } + Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" + Write-Output -InputObject "DenyPolicyGUID = $PolicyID" + if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green @@ -263,10 +261,8 @@ Function New-DenyWDACConfig { Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\AppxDenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - [PSCustomObject]@{ - DenyPolicyFile = ".\AppxDenyPolicy $PolicyName.xml" - DenyPolicyGUID = $PolicyID - } + Write-Output -InputObject "DenyPolicyFile = AppxDenyPolicy $PolicyName.xml" + Write-Output -InputObject "DenyPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index fdc0071d6..0a34dfddf 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -386,6 +386,6 @@ Function New-KernelModeWDACConfig { Can be used with any parameter to bypass the online version check - only to be used in rare cases .INPUTS - None. You cannot pipe objects to this function. + System.Management.Automation.SwitchParameter #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 4092dedb8..5a21bf3b0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -165,10 +165,10 @@ Function New-SupplementalWDACConfig { Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - [PSCustomObject]@{ - SupplementalPolicyFile = "SupplementalPolicy $SuppPolicyName.xml" - SupplementalPolicyGUID = $PolicyID - } + + Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" + Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" + if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." @@ -199,10 +199,9 @@ Function New-SupplementalWDACConfig { Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - [PSCustomObject]@{ - SupplementalPolicyFile = ".\SupplementalPolicy $SuppPolicyName.xml" - SupplementalPolicyGUID = $PolicyID - } + + Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" + Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null @@ -255,10 +254,9 @@ Function New-SupplementalWDACConfig { Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - [PSCustomObject]@{ - SupplementalPolicyFile = ".\SupplementalPolicy $SuppPolicyName.xml" - SupplementalPolicyGUID = $PolicyID - } + + Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" + Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index a7547c3dd..14aa6e217 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -143,7 +143,7 @@ Function New-WDACConfig { Gets the latest Microsoft Recommended Driver Block rules and processes them Can optionally deploy them .INPUTS - None. You cannot pipe objects to this function. + System.Management.Automation.SwitchParameter .OUTPUTS System.String .PARAMETER Deploy @@ -224,6 +224,10 @@ Function New-WDACConfig { .PARAMETER NoCIP Indicates that the created .CIP binary file must be deleted at the end. It's usually used when calling this function from other functions that don't need the .CIP output of this function. + .INPUTS + System.Management.Automation.SwitchParameter + .OUTPUTS + System.String #> [CmdletBinding()] param( @@ -270,10 +274,8 @@ Function New-WDACConfig { Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force Write-Verbose -Message 'Displaying the outout' - [PSCustomObject]@{ - PolicyFile = 'AllowMicrosoftPlusBlockRules.xml' - BinaryFile = "$PolicyID.cip" - } + Write-Output -InputObject 'PolicyFile = AllowMicrosoftPlusBlockRules.xml' + Write-Output -InputObject "BinaryFile = $PolicyID.cip" if ($Deploy -and $MakeAllowMSFTWithBlockRules) { Write-Verbose -Message 'Deploying the AllowMicrosoftPlusBlockRules.xml policy' @@ -399,10 +401,8 @@ Function New-WDACConfig { } Write-Verbose -Message 'Displaying the output' - [PSCustomObject]@{ - PolicyFile = 'DefaultWindowsPlusBlockRules.xml' - BinaryFile = "$PolicyID.cip" - } + Write-Output -InputObject 'PolicyFile = DefaultWindowsPlusBlockRules.xml' + Write-Output -InputObject "BinaryFile = $PolicyID.cip" if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { Write-Verbose -Message 'Deploying the DefaultWindowsPlusBlockRules.xml policy' @@ -423,6 +423,8 @@ Function New-WDACConfig { .OUTPUTS System.String #> + [CmdletBinding()] + param() Write-Verbose -Message 'Downloading the latest Microsoft recommended block rules and creating Microsoft recommended block rules TEMP.xml' (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force @@ -620,7 +622,7 @@ Function New-WDACConfig { .INPUTS None. You cannot pipe objects to this function. .OUTPUTS - System.Void + System.String #> [CmdletBinding()] param() @@ -760,14 +762,11 @@ Function New-WDACConfig { #Endregion Supplemental-Policy-Processing - [PSCustomObject]@{ - BasePolicyFile = $BasePolicy - BasePolicyGUID = $BasePolicyID - } - [PSCustomObject]@{ - SupplementalPolicyFile = 'SupplementalPolicy.xml' - SupplementalPolicyGUID = $PolicyID - } + Write-Output -InputObject "BasePolicyFile = $BasePolicy" + Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" + + Write-Output -InputObject 'SupplementalPolicyFile = SupplementalPolicy.xml' + Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" if (-NOT $Debug) { Remove-Item -Path 'AuditLogsPolicy_NoDeletedFiles.xml', 'FileRulesAndFileRefs.txt', 'DeletedFilesHashes.xml' -Force -ErrorAction SilentlyContinue @@ -809,7 +808,7 @@ Function New-WDACConfig { .INPUTS None. You cannot pipe objects to this function. .OUTPUTS - System.Void + System.String #> [CmdletBinding()] param() @@ -859,10 +858,8 @@ Function New-WDACConfig { } Write-Verbose -Message 'Displaying the output' - [PSCustomObject]@{ - BasePolicyFile = 'SignedAndReputable.xml' - BasePolicyGUID = $BasePolicyID - } + Write-Output -InputObject 'BasePolicyFile = SignedAndReputable.xml' + Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" } # Script block that is used to supply extra information regarding Microsoft recommended driver block rules in commands that use them From 1c11f20b69246f9dabf11675c053f154deea61f3 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 06:04:57 -0930 Subject: [PATCH 118/178] Improved Update-BasePolicyToEnforced function help --- .../Core/Edit-SignedWDACConfig.psm1 | 4 ++-- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index c2c337172..3347919f4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -250,9 +250,9 @@ Function Edit-SignedWDACConfig { function Update-BasePolicyToEnforced { <# .SYNOPSIS - Re-Deploy Basepolicy in Enforced mode + A helper function used to redeploy the base policy in Enforced mode .INPUTS - None. You cannot pipe objects to this function. + None. This function uses the global variables $PolicyName and $PolicyID .OUTPUTS System.String #> diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 38a73b383..591fc73be 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -187,7 +187,14 @@ Function Edit-WDACConfig { <# .SYNOPSIS A helper function used to redeploy the base policy in Enforced mode + .INPUTS + None. This function uses the global variables $PolicyName and $PolicyID + .OUTPUTS + System.String #> + [CmdletBinding()] + param() + # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" From cd5c0171211d68dde438d1012a5cc44a65d7107e Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 06:15:57 -0930 Subject: [PATCH 119/178] Converted many expandable strings into literal str Improves code security --- .../Core/Deploy-SignedWDACConfig.psm1 | 4 ++-- .../Core/Edit-SignedWDACConfig.psm1 | 8 ++++---- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 4 ++-- .../Core/Get-CommonWDACConfig.psm1 | 4 ++-- .../Core/New-SupplementalWDACConfig.psm1 | 4 ++-- .../Core/Remove-CommonWDACConfig.psm1 | 4 ++-- .../Core/Set-CommonWDACConfig.psm1 | 4 ++-- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 9f1c195da..a8d6fba29 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -87,7 +87,7 @@ Function Deploy-SignedWDACConfig { } } else { - throw "CertPath parameter can't be empty and no valid configuration was found for it." + throw 'CertPath parameter cannot be empty and no valid configuration was found for it.' } } @@ -104,7 +104,7 @@ Function Deploy-SignedWDACConfig { } } else { - throw "CertCN parameter can't be empty and no valid configuration was found for it." + throw 'CertCN parameter cannot be empty and no valid configuration was found for it.' } } #endregion User-Configurations-Processing-Validation diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 3347919f4..fa7dc0ae3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -179,7 +179,7 @@ Function Edit-SignedWDACConfig { } } else { - throw "CertPath parameter can't be empty and no valid configuration was found for it." + throw 'CertPath parameter cannot be empty and no valid configuration was found for it.' } } @@ -196,7 +196,7 @@ Function Edit-SignedWDACConfig { } } else { - throw "CertCN parameter can't be empty and no valid configuration was found for it." + throw 'CertCN parameter cannot be empty and no valid configuration was found for it.' } } @@ -214,7 +214,7 @@ Function Edit-SignedWDACConfig { } } else { - throw "PolicyPaths parameter can't be empty and no valid configuration was found for SignedPolicyPath." + throw 'PolicyPaths parameter cannot be empty and no valid configuration was found for SignedPolicyPath.' } } } @@ -409,7 +409,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # but detected in Event viewer audit logs, scan that folder, and in the end delete it New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null - Write-Verbose -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" + Write-Verbose -Message 'The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but did not exist in any of the user-selected paths:' $TestFilePathResults | ForEach-Object -Process { Write-Verbose -Message "$_" Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 591fc73be..952368885 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -152,7 +152,7 @@ Function Edit-WDACConfig { } } else { - throw "PolicyPaths parameter can't be empty and no valid configuration was found for UnsignedPolicyPath." + throw 'PolicyPaths parameter cannot be empty and no valid configuration was found for UnsignedPolicyPath.' } } } @@ -574,7 +574,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # but detected in Event viewer audit logs, scan that folder, and in the end delete it New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory -Force | Out-Null - Write-Verbose -Message "The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but didn't exist in any of the user-selected paths:" + Write-Verbose -Message 'The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but did not exist in any of the user-selected paths:' $TestFilePathResults | ForEach-Object -Process { Write-Verbose -Message "$_" Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force -ErrorAction SilentlyContinue diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 847af074b..0ea090d4d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -21,13 +21,13 @@ Function Get-CommonWDACConfig { # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null - Write-Debug -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." + Write-Debug -Message 'The .WDACConfig folder in the current user folder has been created because it did not exist.' } # Create User configuration file if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null - Write-Debug -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." + Write-Debug -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' } if ($Open) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 5a21bf3b0..a5e73be7b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -21,7 +21,7 @@ Function New-SupplementalWDACConfig { [parameter(Mandatory = $true, ParameterSetName = 'Normal', ValueFromPipelineByPropertyName = $true)] [System.String]$ScanLocation, - [ValidatePattern('\*', ErrorMessage = "You didn't supply a path that contains wildcard character '*' .")] + [ValidatePattern('\*', ErrorMessage = 'You did not supply a path that contains wildcard character (*) .')] [parameter(Mandatory = $true, ParameterSetName = 'Folder Path With WildCards', ValueFromPipelineByPropertyName = $true)] [System.String]$FolderPath, @@ -116,7 +116,7 @@ Function New-SupplementalWDACConfig { } } else { - throw "PolicyPath parameter can't be empty and no valid configuration was found for UnsignedPolicyPath." + throw 'PolicyPath parameter cannot be empty and no valid configuration was found for UnsignedPolicyPath.' } } #endregion User-Configurations-Processing-Validation diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index 68fc1bec7..52a4f4c3f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -20,13 +20,13 @@ Function Remove-CommonWDACConfig { # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null - Write-Verbose -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." + Write-Verbose -Message 'The .WDACConfig folder in the current user folder has been created because it did not exist.' } # Create User configuration file if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null - Write-Verbose -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." + Write-Verbose -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' } # Delete the entire User Configs if a more specific parameter wasn't used diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index efefa2922..bea1e3a5c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -61,13 +61,13 @@ Function Set-CommonWDACConfig { # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null - Write-Verbose -Message "The .WDACConfig folder in current user's folder has been created because it didn't exist." + Write-Verbose -Message 'The .WDACConfig folder in the current user folder has been created because it did not exist.' } # Create User configuration file if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null - Write-Verbose -Message "The UserConfigurations.json file in \.WDACConfig\ folder has been created because it didn't exist." + Write-Verbose -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' } if ($PSBoundParameters.Count -eq 0) { From 2e14021591fd520ebcb870077c0d3c596d44e520 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 08:23:10 -0930 Subject: [PATCH 120/178] Centrally managing Verbosity of the shared modules --- .../Core/Confirm-WDACConfig.psm1 | 2 +- .../Core/Deploy-SignedWDACConfig.psm1 | 8 ++--- .../Core/Edit-SignedWDACConfig.psm1 | 26 +++++++-------- .../Core/Edit-WDACConfig.psm1 | 22 ++++++------- .../Core/Invoke-WDACSimulation.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 2 +- .../Core/New-KernelModeWDACConfig.psm1 | 6 ++-- .../Core/New-SupplementalWDACConfig.psm1 | 2 +- .../Core/New-WDACConfig.psm1 | 26 +++++++-------- .../Core/Remove-WDACConfig.psm1 | 8 ++--- .../CoreExt/PSDefaultParameterValues.ps1 | 33 ++++++++++++++----- 11 files changed, 76 insertions(+), 61 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 5aab53811..e9c9a9981 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -83,7 +83,7 @@ Function Confirm-WDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } # Script block to show only non-system Base policies [System.Management.Automation.ScriptBlock]$OnlyBasePoliciesBLOCK = { diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index a8d6fba29..dd61f3e5d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -45,7 +45,7 @@ Function Deploy-SignedWDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -68,10 +68,10 @@ Function Deploy-SignedWDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } # If CertPath parameter wasn't provided by user @@ -95,7 +95,7 @@ Function Deploy-SignedWDACConfig { if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName) -Verbose:$Verbose) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index fa7dc0ae3..cc60ae32e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -140,7 +140,7 @@ Function Edit-SignedWDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user @@ -160,10 +160,10 @@ Function Edit-SignedWDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } # If CertPath parameter wasn't provided by user @@ -187,7 +187,7 @@ Function Edit-SignedWDACConfig { if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName) -Verbose:$Verbose) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } @@ -274,7 +274,7 @@ Function Edit-SignedWDACConfig { if ($AllowNewAppsAuditEvents) { # Change Code Integrity event logs size - if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize -Verbose:$Verbose } + if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize } # Make sure there is no leftover from previous runs Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue @@ -392,14 +392,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function - $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date -Verbose:$Verbose + $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date # Only create policy for files that are available on the disk based on Event viewer logs but weren't in user-selected program path(s), if there are any if ($AuditEventLogsProcessingResults.AvailableFilesPaths) { # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those # this prevents duplicate rule creation and double file copying - $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths -Verbose:$Verbose).path | Select-Object -Unique + $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique Write-Verbose -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." @@ -452,10 +452,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) | Out-File -FilePath FileRulesAndFileRefs.txt -Force + (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath FileRulesAndFileRefs.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force # adding the policy file that consists of rules from audit even logs, to the array $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' @@ -533,7 +533,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = Get-GlobalRootDrives -Verbose:$Verbose | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = Get-GlobalRootDrives | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk @@ -553,10 +553,10 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($KernelProtectedHashesBlockResults) { # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) | Out-File -FilePath KernelProtectedFiles.txt -Force + (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath KernelProtectedFiles.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\KernelProtectedFiles.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath .\KernelProtectedFiles.xml -Force # adding the policy file to the array of xml files $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' @@ -893,7 +893,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if ($UpdateBasePolicy) { # First get the Microsoft recommended block rules - Get-BlockRulesMeta -Verbose:$Verbose | Out-Null + Get-BlockRulesMeta | Out-Null switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 952368885..608edaceb 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -118,7 +118,7 @@ Function Edit-WDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -440,7 +440,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Change Code Integrity event logs size if ($AllowNewAppsAuditEvents -and $LogSize) { Write-Verbose -Message 'Changing Code Integrity event logs size' - Set-LogSize -LogSize $LogSize -Verbose:$Verbose + Set-LogSize -LogSize $LogSize } # Make sure there is no leftover from previous runs @@ -555,7 +555,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function - $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date -Verbose:$Verbose + $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date # Only create policy for files that are available on the disk (based on Event viewer logs) # but weren't in user-selected program path(s), if there are any @@ -563,7 +563,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those by first copying them to another directory # this prevents duplicate rule creation and double file copying - $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths -Verbose:$Verbose).path | Select-Object -Unique + $TestFilePathResults = (Test-FilePath -FilePath $AuditEventLogsProcessingResults.AvailableFilesPaths -DirectoryPath $ProgramsPaths).path | Select-Object -Unique Write-Verbose -Message "$($TestFilePathResults.count) file(s) have been found in event viewer logs that don't exist in any of the folder paths you selected." @@ -622,8 +622,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' - $FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose - $RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes -Verbose:$Verbose).Trim() + $FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes + $RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes Write-Verbose -Message 'Saving the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes' @@ -631,7 +631,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Put the Rules and RulesRefs in an empty policy file Write-Verbose -Message 'Putting the Rules and RulesRefs in an empty policy file' - New-EmptyPolicy -RulesContent $FileRulesHashesResults -RuleRefsContent $RuleRefsHashesResults -Verbose:$Verbose | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force + New-EmptyPolicy -RulesContent $FileRulesHashesResults -RuleRefsContent $RuleRefsHashesResults | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force # adding the policy file that consists of rules from audit even logs, to the array Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' @@ -720,7 +720,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = Get-GlobalRootDrives -Verbose:$Verbose | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = Get-GlobalRootDrives | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } # Check if file is currently on the disk @@ -740,10 +740,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if ($KernelProtectedHashesBlockResults) { # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) | Out-File -FilePath KernelProtectedFiles.txt -Force + (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath KernelProtectedFiles.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\KernelProtectedFiles.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath .\KernelProtectedFiles.xml -Force # adding the policy file to the array of xml files $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' @@ -863,7 +863,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if ($UpdateBasePolicy) { # First get the Microsoft recommended block rules - Get-BlockRulesMeta -Verbose:$Verbose | Out-Null + Get-BlockRulesMeta | Out-Null switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 23864576d..7c85ae2b4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -30,7 +30,7 @@ Function Invoke-WDACSimulation { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } # The total number of the main steps for the progress bar to render [System.Int16]$TotalSteps = 4 diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 6700f4461..3c6aa3400 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -87,7 +87,7 @@ Function New-DenyWDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } } process { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 0a34dfddf..d88f9dcfd 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -45,7 +45,7 @@ Function New-KernelModeWDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } # Check if the PrepMode and AuditAndEnforce parameters are used together and ensure one of them is used if (-not ($PSBoundParameters.ContainsKey('PrepMode') -xor $PSBoundParameters.ContainsKey('AuditAndEnforce'))) { @@ -211,7 +211,7 @@ Function New-KernelModeWDACConfig { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel.xml' -Force # Move all AllowedSigners from Usermode to Kernel mode signing scenario - Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Verbose:$Verbose | Out-Null + Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null # Set the GUIDs for the XML policy file Edit-GUIDs -PolicyIDInput $PolicyID -PolicyFilePathInput '.\Final_DefaultWindows_Enforced_Kernel.xml' @@ -309,7 +309,7 @@ Function New-KernelModeWDACConfig { Remove-Item -Path '.\DefaultWindows_Enforced_Kernel_NoFlights.xml' -Force # Move all AllowedSigners from Usermode to Kernel mode signing scenario - Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' -Verbose:$Verbose | Out-Null + Move-UserModeToKernelMode -FilePath '.\Final_DefaultWindows_Enforced_Kernel.xml' | Out-Null # Set the GUIDs for the XML policy file Edit-GUIDs -PolicyIDInput $PolicyID -PolicyFilePathInput '.\Final_DefaultWindows_Enforced_Kernel.xml' diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index a5e73be7b..cebb1f349 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -87,7 +87,7 @@ Function New-SupplementalWDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } #region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 14aa6e217..e70a86af0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -81,7 +81,7 @@ Function New-WDACConfig { begin { # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -112,10 +112,10 @@ Function New-WDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. elseif ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } #endregion User-Configurations-Processing-Validation @@ -235,7 +235,7 @@ Function New-WDACConfig { ) # Get the latest Microsoft recommended block rules Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' - Get-BlockRulesMeta -Verbose:$Verbose | Out-Null + Get-BlockRulesMeta | Out-Null Write-Verbose -Message 'Copying the AllowMicrosoft.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' -Force @@ -307,7 +307,7 @@ Function New-WDACConfig { param() Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' - Get-BlockRulesMeta -Verbose:$Verbose | Out-Null + Get-BlockRulesMeta | Out-Null Write-Verbose -Message 'Copying the DefaultWindows_Enforced.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' -Force @@ -511,7 +511,7 @@ Function New-WDACConfig { if ($PrepMSFTOnlyAudit -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' - Set-LogSize -LogSize $LogSize -Verbose:$Verbose + Set-LogSize -LogSize $LogSize } Write-Verbose -Message 'Copying AllowMicrosoft.xml from Windows directory to the current working directory' @@ -558,7 +558,7 @@ Function New-WDACConfig { if ($PrepDefaultWindowsAudit -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' - Set-LogSize -LogSize $LogSize -Verbose:$Verbose + Set-LogSize -LogSize $LogSize } Write-Verbose -Message 'Copying DefaultWindows_Audit.xml from Windows directory to the current working directory' @@ -629,7 +629,7 @@ Function New-WDACConfig { if ($MakePolicyFromAuditLogs -and $LogSize) { Write-Verbose -Message 'Changing the Log size of Code Integrity Operational event log' - Set-LogSize -LogSize $LogSize -Verbose:$Verbose + Set-LogSize -LogSize $LogSize } # Make sure there is no leftover files from previous operations of this same command @@ -710,7 +710,7 @@ Function New-WDACConfig { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { $hardDiskVolumeNumber = $Matches[1] $remainingPath = $Matches[2] - $getletter = Get-GlobalRootDrives -Verbose:$Verbose | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } + $getletter = Get-GlobalRootDrives | Where-Object -FilterScript { $_.devicepath -eq "\Device\HarddiskVolume$hardDiskVolumeNumber" } $usablePath = "$($getletter.DriveLetter)$remainingPath" $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } @@ -727,10 +727,10 @@ Function New-WDACConfig { if ($DeletedFileHashesArray -and !$NoDeletedFiles) { # Save the the File Rules and File Rule Refs to the Out-File FileRulesAndFileRefs.txt in the current working directory - (Get-FileRules -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) + (Get-RuleRefs -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) | Out-File -FilePath FileRulesAndFileRefs.txt -Force + (Get-FileRules -HashesArray $DeletedFileHashesArray) + (Get-RuleRefs -HashesArray $DeletedFileHashesArray) | Out-File -FilePath FileRulesAndFileRefs.txt -Force # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) -RuleRefsContent (Get-RuleRefs -HashesArray $DeletedFileHashesArray -Verbose:$Verbose) -Verbose:$Verbose | Out-File -FilePath .\DeletedFilesHashes.xml -Force + New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $DeletedFileHashesArray) -RuleRefsContent (Get-RuleRefs -HashesArray $DeletedFileHashesArray) | Out-File -FilePath .\DeletedFilesHashes.xml -Force # Merge the policy file we created at first using Event Viewer logs, with the policy file we created for Hash of the files no longer available on the disk Merge-CIPolicy -PolicyPaths 'AuditLogsPolicy_NoDeletedFiles.xml', .\DeletedFilesHashes.xml -OutputFilePath .\SupplementalPolicy.xml | Out-Null @@ -884,7 +884,7 @@ Function New-WDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } } process { @@ -893,7 +893,7 @@ Function New-WDACConfig { # Deploy the latest block rules { $GetBlockRules -and $Deploy } { Deploy-LatestBlockRules ; break } # Get the latest block rules - $GetBlockRules { Get-BlockRulesMeta -Verbose:$Verbose ; break } + $GetBlockRules { Get-BlockRulesMeta ; break } # Get the latest driver block rules and Deploy them if New-WDACConfig -GetDriverBlockRules was called with -Deploy parameter { $GetDriverBlockRules } { Get-DriverBlockRules -Deploy:$Deploy ; break } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 16ba79098..3caff9869 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -129,7 +129,7 @@ Function Remove-WDACConfig { # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console - if (-NOT $SkipVersionCheck) { Update-self -Verbose:$Verbose 6> $null } + if (-NOT $SkipVersionCheck) { Update-self 6> $null } #region User-Configurations-Processing-Validation @@ -153,17 +153,17 @@ Function Remove-WDACConfig { # Get SignToolPath from user parameter or user config file or auto-detect it if ($SignToolPath) { - $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath $SignToolPath } # If it is null, then Get-SignTool will behave the same as if it was called without any arguments. else { - $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) -Verbose:$Verbose + $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } # If CertCN was not provided by user if (!$CertCN) { if ($UserConfig.CertificateCommonName) { # Check if the value in the User configuration file exists and is valid - if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName) -Verbose:$Verbose) { + if (Confirm-CertCN -CN $($UserConfig.CertificateCommonName)) { # if it's valid then use it $CertCN = $UserConfig.CertificateCommonName } diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 69b355f6b..89576a55d 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -1,12 +1,27 @@ # $PSDefaultParameterValues only get read from scope where invocation occurs # This is why this file is dot-sourced in every other component of the WDACConfig module at the beginning $PSDefaultParameterValues = @{ - 'Invoke-WebRequest:HttpVersion' = '3.0' - 'Invoke-WebRequest:SslProtocol' = 'Tls12,Tls13' - 'Invoke-RestMethod:HttpVersion' = '3.0' - 'Invoke-RestMethod:SslProtocol' = 'Tls12,Tls13' - 'Import-Module:Verbose' = $false - 'Export-ModuleMember:Verbose' = $false - 'Add-Type:Verbose' = $false - 'Get-WinEvent:Verbose' = $false -} \ No newline at end of file + 'Invoke-WebRequest:HttpVersion' = '3.0' + 'Invoke-WebRequest:SslProtocol' = 'Tls12,Tls13' + 'Invoke-RestMethod:HttpVersion' = '3.0' + 'Invoke-RestMethod:SslProtocol' = 'Tls12,Tls13' + 'Import-Module:Verbose' = $false + 'Export-ModuleMember:Verbose' = $false + 'Add-Type:Verbose' = $false + 'Get-WinEvent:Verbose' = $false + 'Confirm-CertCN:Verbose' = $Verbose + 'Get-AuditEventLogsProcessing:Verbose' = $Verbose + 'Get-FileRules:Verbose' = $Verbose + 'Get-BlockRulesMeta:Verbose' = $Verbose + 'Get-GlobalRootDrives:Verbose' = $Verbose + 'Get-RuleRefs:Verbose' = $Verbose + 'Get-SignTool:Verbose' = $Verbose + 'Move-UserModeToKernelMode:Verbose' = $Verbose + 'New-EmptyPolicy:Verbose' = $Verbose + 'Remove-ZerosFromIDs:Verbose' = $Verbose + 'Set-LogSize:Verbose' = $Verbose + 'Test-FilePath:Verbose' = $Verbose + 'Update-self:Verbose' = $Verbose + 'Write-ColorfulText:Verbose' = $Verbose +} + From 69f2d4299f3e9ef13605a267309135ca436830c3 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 09:11:30 -0930 Subject: [PATCH 121/178] Properly relocated module helps --- .../WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 | 7 +++---- .../WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- .../Core/Remove-CommonWDACConfig.psm1 | 6 +++--- .../WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 | 6 +++--- 4 files changed, 10 insertions(+), 11 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 0ea090d4d..b82f91d7a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -75,9 +75,7 @@ Function Get-CommonWDACConfig { $LastUpdateCheck.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.LastUpdateCheck } } } -} - -<# + <# .SYNOPSIS Query and Read common values for parameters used by WDACConfig module @@ -122,4 +120,5 @@ Function Get-CommonWDACConfig { .OUTPUTS System.Object[] -#> +#> +} diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index e70a86af0..e7a492ec8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -81,7 +81,7 @@ Function New-WDACConfig { begin { # Importing the $PSDefaultParameterValues to the current session, prior to everything else - # . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index 52a4f4c3f..2b000b30c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -129,8 +129,7 @@ Function Remove-CommonWDACConfig { Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" } -} -<# + <# .SYNOPSIS Removes common values for parameters used by WDACConfig module @@ -167,4 +166,5 @@ Function Remove-CommonWDACConfig { .PARAMETER StrictKernelNoFlightRootsPolicyGUID Removes the StrictKernelNoFlightRootsPolicyGUID from User Configs -#> +#> +} diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index bea1e3a5c..678f41e81 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -184,8 +184,7 @@ Function Set-CommonWDACConfig { Write-Verbose -Message 'Displaying the current user configurations' Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } -} -<# + <# .SYNOPSIS Add/Change common values for parameters used by WDACConfig module @@ -229,7 +228,8 @@ Function Set-CommonWDACConfig { .OUTPUTS System.Object[] -#> +#> +} # Importing argument completer ScriptBlocks . "$ModuleRootPath\Resources\ArgumentCompleters.ps1" From ec602d94e39221a1f16c9db7096128d54d8f881c Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 09:31:23 -0930 Subject: [PATCH 122/178] Removed unnecessary import of SDefaultParameterVal When ScriptBlock Argument Completers ps1 file is already imported in a cmdlet/function then it's not necessary to import the SDefaultParameterValues.ps1 again --- .../WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 | 2 -- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 -- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 -- .../WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 | 2 -- WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 2 -- .../Core/New-SupplementalWDACConfig.psm1 | 2 -- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 -- WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 2 -- .../WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 | 2 -- 9 files changed, 18 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index dd61f3e5d..4dfd45c1c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -30,8 +30,6 @@ Function Deploy-SignedWDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index cc60ae32e..4d6f43e62 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -117,8 +117,6 @@ Function Edit-SignedWDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 608edaceb..7b3a72cc2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -97,8 +97,6 @@ Function Edit-WDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 7c85ae2b4..5c5023715 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -14,8 +14,6 @@ Function Invoke-WDACSimulation { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$ModuleRootPath\Resources\Resources2.ps1" diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 3c6aa3400..25ed71d22 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -53,8 +53,6 @@ Function New-DenyWDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index cebb1f349..1d109b391 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -59,8 +59,6 @@ Function New-SupplementalWDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index e7a492ec8..dbc5dcef3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -80,8 +80,6 @@ Function New-WDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 3caff9869..afc73cd3d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -114,8 +114,6 @@ Function Remove-WDACConfig { ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 678f41e81..cce73ec43 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -52,8 +52,6 @@ Function Set-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.DateTime]$LastUpdateCheck ) begin { - # Importing the $PSDefaultParameterValues to the current session, prior to everything else - . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force From 173ea558ca2f681dc6385e6781c5c96805760b87 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 09:34:56 -0930 Subject: [PATCH 123/178] Update PSDefaultParameterValues.ps1 --- .../CoreExt/PSDefaultParameterValues.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 89576a55d..6a9418bb5 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -1,5 +1,7 @@ # $PSDefaultParameterValues only get read from scope where invocation occurs # This is why this file is dot-sourced in every other component of the WDACConfig module at the beginning +# With the exception of the cmdlets where ArgumentCompleters.ps1 is dot-sourced at the end +# Because PSDefaultParameterValues.ps1 is already dot-sourced in ArgumentCompleters.ps1 $PSDefaultParameterValues = @{ 'Invoke-WebRequest:HttpVersion' = '3.0' 'Invoke-WebRequest:SslProtocol' = 'Tls12,Tls13' From c34e7dadb65f13611749f567feb4fc8cc21eb3e5 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 11:53:16 -0930 Subject: [PATCH 124/178] Improved Edit-WDACConfig cmdlet And also fixed Verbosities across the cmdlets --- .../Core/Confirm-WDACConfig.psm1 | 7 +-- .../Core/Deploy-SignedWDACConfig.psm1 | 11 ++-- .../Core/Edit-SignedWDACConfig.psm1 | 9 ++-- .../Core/Edit-WDACConfig.psm1 | 53 ++++++++++--------- .../Core/Invoke-WDACSimulation.psm1 | 9 ++-- .../Core/New-DenyWDACConfig.psm1 | 9 ++-- .../Core/New-KernelModeWDACConfig.psm1 | 7 +-- .../Core/New-SupplementalWDACConfig.psm1 | 9 ++-- .../Core/New-WDACConfig.psm1 | 9 ++-- .../Core/Remove-WDACConfig.psm1 | 9 ++-- .../Core/Set-CommonWDACConfig.psm1 | 3 ++ .../CoreExt/PSDefaultParameterValues.ps1 | 1 - .../Shared/Get-FileRules.psm1 | 11 +++- .../Shared/Get-RuleRefs.psm1 | 11 +++- 14 files changed, 101 insertions(+), 57 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index e9c9a9981..5cff656c5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -63,8 +63,12 @@ Function Confirm-WDACConfig { } begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -77,9 +81,6 @@ Function Confirm-WDACConfig { [System.Management.Automation.SwitchParameter]$OnlySupplementalPolicies = $($PSBoundParameters['OnlySupplementalPolicies']) [System.Management.Automation.SwitchParameter]$SkipVersionCheck = $($PSBoundParameters['SkipVersionCheck']) - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 4dfd45c1c..4883bd8e8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -30,16 +30,19 @@ Function Deploy-SignedWDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force - - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 4d6f43e62..263c2db97 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -117,6 +117,12 @@ Function Edit-SignedWDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -132,9 +138,6 @@ Function Edit-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 7b3a72cc2..1dabec042 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -97,6 +97,12 @@ Function Edit-WDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -110,9 +116,6 @@ Function Edit-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console @@ -195,7 +198,7 @@ Function Edit-WDACConfig { # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Enforced Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Enforced Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP @@ -286,7 +289,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Deploy the Audit mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -297,13 +300,13 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { #Region User-Interaction - Write-ColorfulText -Color Pink -InputText "`nAudit mode deployed, start installing your programs now" - Write-ColorfulText -Color HotPink -InputText "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" + Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' + Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause # Store the program paths that user browses for in an array [System.IO.DirectoryInfo[]]$ProgramsPaths = @() - Write-Host -Object "`nSelect program directories to scan" -ForegroundColor Cyan + Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { @@ -348,7 +351,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove-Item -Path 'c:\EnforcedModeSnapBack.cmd' -Force } - Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_.FullName } # Scan each of the folder paths that user selected @@ -419,7 +422,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" @@ -504,7 +507,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Deploy the Audit mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Deployed in Audit Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -515,13 +518,13 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { #Region User-Interaction - Write-ColorfulText -Color Pink -InputText "`nAudit mode deployed, start installing your programs now" - Write-ColorfulText -Color HotPink -InputText "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" + Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' + Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause # Store the program paths that user browses for in an array [System.IO.DirectoryInfo[]]$ProgramsPaths = @() - Write-Host -Object "`nSelect program directories to scan`n" -ForegroundColor Cyan + Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { @@ -540,7 +543,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object 'No program folder was selected, reverting the changes and quitting...' -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } @@ -614,14 +617,16 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Attempting to create a policy for files that are no longer available on the disk but were detected in event viewer logs' - Write-Verbose -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" - $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { - Write-Verbose -Message "$($_.'File Name')" + # Displaying the unique values and count. Even though the DeletedFileHashesEventsPolicy.xml will have many duplicates, the final supplemental policy that will be deployed on the system won't have any duplicates + # Because Merge-CiPolicy will automatically take care of removing them + Write-Verbose -Message "$(($AuditEventLogsProcessingResults.DeletedFileHashes.'File Name' | Select-Object -Unique).count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" + $AuditEventLogsProcessingResults.DeletedFileHashes.'File Name' | Select-Object -Unique | ForEach-Object -Process { + Write-Verbose -Message "$_" } Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' - $FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes - $RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() + [System.String]$FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes + [System.String]$RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes Write-Verbose -Message 'Saving the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes' @@ -689,16 +694,16 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # if any .exe was found then continue testing them if ($AnyAvailableExes) { - foreach ($CurrentExeWithNoHash in $AnyAvailableExes) { + foreach ($Exe in $AnyAvailableExes) { try { # Testing each executable to find the protected ones - Get-FileHash -Path $CurrentExeWithNoHash -ErrorAction Stop | Out-Null + Get-FileHash -Path $Exe -ErrorAction Stop | Out-Null } # If the executable is protected, it will throw an exception and the script will continue to the next one # Making sure only the right file is captured by narrowing down the error type. # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException catch [System.UnauthorizedAccessException] { - $ExesWithNoHash += $CurrentExeWithNoHash + $ExesWithNoHash += $Exe } } } @@ -807,7 +812,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Deployed in Enforced Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 5c5023715..6ab62f4b5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -14,6 +14,12 @@ Function Invoke-WDACSimulation { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$ModuleRootPath\Resources\Resources2.ps1" @@ -22,9 +28,6 @@ Function Invoke-WDACSimulation { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 25ed71d22..c31982d7c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -53,6 +53,12 @@ Function New-DenyWDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -79,9 +85,6 @@ Function New-DenyWDACConfig { } } - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index d88f9dcfd..91a948af8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -28,8 +28,12 @@ Function New-KernelModeWDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -39,9 +43,6 @@ Function New-KernelModeWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 1d109b391..2c34fbc0a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -59,6 +59,12 @@ Function New-SupplementalWDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -79,9 +85,6 @@ Function New-SupplementalWDACConfig { } } - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index dbc5dcef3..35de76e65 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -80,6 +80,12 @@ Function New-WDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -876,9 +882,6 @@ Function New-WDACConfig { Write-ColorfulText -Color Pink -InputText "The current version of Microsoft recommended drivers block list is $($Matches[1])" } - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index afc73cd3d..5c428ef6a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -114,6 +114,12 @@ Function Remove-WDACConfig { ) begin { + # Detecting if Verbose switch is used + $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null + + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -121,9 +127,6 @@ Function Remove-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force - # Detecting if Verbose switch is used - $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index cce73ec43..9d61e420b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -52,6 +52,9 @@ Function Set-CommonWDACConfig { [parameter(Mandatory = $false, DontShow = $true)][System.DateTime]$LastUpdateCheck ) begin { + # Importing the $PSDefaultParameterValues to the current session, prior to everything else + . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 6a9418bb5..ebbb87773 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -26,4 +26,3 @@ $PSDefaultParameterValues = @{ 'Update-self:Verbose' = $Verbose 'Write-ColorfulText:Verbose' = $Verbose } - diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 index e766f0886..1d1c524a5 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-FileRules.psm1 @@ -2,9 +2,16 @@ Function Get-FileRules { <# .SYNOPSIS Create File Rules based on hash of the files no longer available on the disk and store them in the $Rules variable + .INPUTS + System.Object[] + .OUTPUTS + System.String #> [CmdletBinding()] - param ($HashesArray) + param ( + [parameter(Mandatory = $true)] + [System.Object[]]$HashesArray + ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" @@ -15,7 +22,7 @@ Function Get-FileRules { $Rules += Write-Output -InputObject "`n" $i++ } - return ($Rules.Trim()) + return [System.String]($Rules.Trim()) } # Export external facing functions only, prevent internal functions from getting exported diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 index 36a7c6328..5ba0c7281 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-RuleRefs.psm1 @@ -2,9 +2,16 @@ Function Get-RuleRefs { <# .SYNOPSIS Create File Rule Refs based on the ID of the File Rules above and store them in the $RulesRefs variable + .INPUTS + System.Object[] + .OUTPUTS + System.String #> [CmdletBinding()] - param ($HashesArray) + param ( + [parameter(Mandatory = $true)] + [System.Object[]]$HashesArray + ) # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" @@ -15,7 +22,7 @@ Function Get-RuleRefs { $RulesRefs += Write-Output -InputObject "`n" $i++ } - return ($RulesRefs.Trim()) + return [System.String]($RulesRefs.Trim()) } # Export external facing functions only, prevent internal functions from getting exported From 77bae23f38a3dbdb86ae084963bd2c0292909fa5 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 11:53:58 -0930 Subject: [PATCH 125/178] Update PSDefaultParameterValues.ps1 --- .../CoreExt/PSDefaultParameterValues.ps1 | 2 -- 1 file changed, 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index ebbb87773..3c1fdb4fe 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -1,7 +1,5 @@ # $PSDefaultParameterValues only get read from scope where invocation occurs # This is why this file is dot-sourced in every other component of the WDACConfig module at the beginning -# With the exception of the cmdlets where ArgumentCompleters.ps1 is dot-sourced at the end -# Because PSDefaultParameterValues.ps1 is already dot-sourced in ArgumentCompleters.ps1 $PSDefaultParameterValues = @{ 'Invoke-WebRequest:HttpVersion' = '3.0' 'Invoke-WebRequest:SslProtocol' = 'Tls12,Tls13' From 2581aa363f9a6350dd6a721c486a2c8a0f08683c Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 12:04:37 -0930 Subject: [PATCH 126/178] Changing some Write-Output to Write-Host This helps displaying them when finally block is running in certain situations --- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 1dabec042..437129847 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -199,8 +199,8 @@ Function Edit-WDACConfig { # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Enforced Mode:' - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" + Write-Host -Object "PolicyName = $PolicyName" + Write-Host -Object "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item -Path '.\EnforcedMode.cip' -Force } @@ -325,7 +325,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object 'No program folder was selected, reverting the changes and quitting...' -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } From 7f97e4d7554a7f58dc6638db5274011cbd223bb7 Mon Sep 17 00:00:00 2001 From: Violet Date: Sat, 9 Dec 2023 12:34:31 -0930 Subject: [PATCH 127/178] Reduced string interpolations when not necessary --- .../Core/Edit-SignedWDACConfig.psm1 | 42 +++++++++---------- .../Core/Edit-WDACConfig.psm1 | 4 +- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 263c2db97..e1c65703b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -262,9 +262,9 @@ Function Edit-SignedWDACConfig { # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:" - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:' + Write-Host -Object "PolicyName = $PolicyName" + Write-Host -Object "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item -Path ".\$PolicyID.cip" -Force } @@ -346,7 +346,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Verbose -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP @@ -357,13 +357,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { ################################### User Interaction #################################### - Write-ColorfulText -Color Pink -InputText "`nAudit mode deployed, start installing your programs now" - Write-ColorfulText -Color HotPink -InputText "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" + Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' + Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() - Write-Host -Object "`nSelect program directories to scan" -ForegroundColor Cyan + Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -380,7 +380,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object 'No program folder was selected, reverting the changes and quitting...' -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } @@ -522,7 +522,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { - Write-Verbose -Message "The following Kernel protected files detected, creating allow rules for them:`n" + Write-Verbose -Message 'The following Kernel protected files detected, creating allow rules for them:' $ExesWithNoHash | ForEach-Object -Process { Write-Verbose -Message "$_" } [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { @@ -563,7 +563,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' } else { - Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on.`n" + Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on." $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } @@ -628,7 +628,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item -Path ".\$SuppPolicyID.cip" -Force @@ -705,7 +705,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Verbose -Message 'Deploying Audit mode CIP' Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" # Remove Audit Mode CIP @@ -716,13 +716,13 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { ################################### User Interaction #################################### - Write-ColorfulText -Color Pink -InputText "`nAudit mode deployed, start installing your programs now" - Write-ColorfulText -Color HotPink -InputText "When you've finished installing programs, Press Enter to start selecting program directories to scan`n" + Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' + Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause # Store the program paths that user browses for in an array [System.Object[]]$ProgramsPaths = @() - Write-Host -Object "`nSelect program directories to scan`n" -ForegroundColor Cyan + Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -739,7 +739,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { - Write-Host -Object "`nNo program folder was selected, reverting the changes and quitting...`n" -ForegroundColor Red + Write-Host -Object 'No program folder was selected, reverting the changes and quitting...' -ForegroundColor Red # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode break } @@ -758,7 +758,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - Write-Host -Object "`nHere are the paths you selected:" -ForegroundColor Yellow + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_ } #Process Program Folders From User input @@ -829,7 +829,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nSupplemental policy with the following details has been Signed and Deployed in Enforced Mode:" + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" Remove-Item -Path ".\$SuppPolicyID.cip" -Force @@ -887,7 +887,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Remove-Item -Path ".\$SuppPolicyID.cip" -Force Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + Write-ColorfulText -Color TeaGreen -InputText "The Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force } } @@ -918,7 +918,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force # Allowing SignTool to be able to run after Default Windows base policy is deployed - Write-ColorfulText -Color TeaGreen -InputText "`nCreating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy." + Write-ColorfulText -Color TeaGreen -InputText 'Creating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy.' New-Item -Path "$UserTempDirectoryPath\TemporarySignToolFile" -ItemType Directory -Force | Out-Null Copy-Item -Path $SignToolPathFinal -Destination "$UserTempDirectoryPath\TemporarySignToolFile" -Force New-CIPolicy -ScanPath "$UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml @@ -927,7 +927,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { - Write-ColorfulText -Color HotPink -InputText "`nCreating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it." + Write-ColorfulText -Color HotPink -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 437129847..236e621bc 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -752,7 +752,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' } else { - Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on.`n" + Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on." $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } @@ -859,7 +859,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "`nThe Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + Write-ColorfulText -Color TeaGreen -InputText "The Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." Remove-Item -Path "$SuppPolicyID.cip" -Force } } From 821e5265d6a32b8831f68f114e535a6386e08c62 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 02:35:27 -0930 Subject: [PATCH 128/178] Improved Edit-SignedWDACConfig --- .../Core/Edit-SignedWDACConfig.psm1 | 64 +++++++++++++------ 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index e1c65703b..42f6d3dcf 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -261,59 +261,75 @@ Function Edit-SignedWDACConfig { param() # Deploy Enforced mode CIP - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:' Write-Host -Object "PolicyName = $PolicyName" Write-Host -Object "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force - } + Remove-Item -Path '.\EnforcedMode.cip' -Force + } } process { if ($AllowNewAppsAuditEvents) { - # Change Code Integrity event logs size - if ($AllowNewAppsAuditEvents -and $LogSize) { Set-LogSize -LogSize $LogSize } + if ($AllowNewAppsAuditEvents -and $LogSize) { + Write-Verbose -Message 'Changing Code Integrity event logs size' + Set-LogSize -LogSize $LogSize + } + # Make sure there is no leftover from previous runs + Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue + # Get the current date so that instead of the entire event viewer logs, only audit logs created after running this module will be captured - # The notice about variable being assigned and never used should be ignored - it's being dot-sourced from Resources file + Write-Verbose -Message 'Getting the current date' [System.DateTime]$Date = Get-Date + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() - ################################### Initiate Live Audit Mode ################################### + #Initiate Live Audit Mode foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected - $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' + # Get the policy file name + [System.String]$PolicyFileName = Split-Path $PolicyPath -Leaf + # make sure no file with the same name already exists in Temp folder + Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force - $PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" + [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" - # Defining Base policy + Write-Verbose -Message 'Retrieving the Base policy name and ID' $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any + Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue - + + Write-Verbose -Message 'Creating Audit Mode CIP' + # Remove Unsigned policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete + # Add Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 # Create CIP for Audit Mode - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null + Write-Verbose -Message 'Creating Enforced Mode CIP' + # Remove Unsigned policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete + # Remove Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Create CIP for Enforced Mode - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null # Sign both CIPs - '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { + '.\AuditMode.cip', '.\EnforcedMode.cip' | ForEach-Object -Process { # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', "`"$_`"" @@ -329,8 +345,14 @@ Function Edit-SignedWDACConfig { # After creating signed .p7 files for each CIP, remove the old Unsigned ones Remove-Item -Path $_ -Force } - Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force - Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force + + Write-Verbose -Message 'Removing the unsigned CIPs' + Remove-Item -Path '.\EnforcedMode.cip' -Force + Remove-Item -Path '.\AuditMode.cip' -Force + + Write-Verbose -Message 'Renaming the signed CIPs to remove the .p7 extension' + Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force + Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force ################# Snap back guarantee ################# Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' From fa72e7b7b2be96ffb0bc88505264cc55a1138b31 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 03:00:38 -0930 Subject: [PATCH 129/178] Improving event viewer capturing section --- .../Core/Edit-SignedWDACConfig.psm1 | 91 ++++++++++++------- 1 file changed, 58 insertions(+), 33 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 42f6d3dcf..e588257e9 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -354,50 +354,55 @@ Function Edit-SignedWDACConfig { Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force - ################# Snap back guarantee ################# + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' - $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - $command = @" -CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force + # Defining the registry path for RunOnce key + [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' + # Defining the command that will be executed by the RunOnce key in case of a reboot + [System.String]$Command = @" +CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force "@ - $command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - # Deploy Audit mode CIP - Write-Verbose -Message 'Deploying Audit mode CIP' - Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' + # Saving the command to a file that will be executed by the RunOnce key in case of a reboot + $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force + # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key + New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null + + Write-Verbose -Message 'Deploying the Audit mode CIP' + # Deploy the Audit mode CIP + &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null + Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" - # Remove Audit Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force - # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + + # Remove the Audit Mode CIP + Remove-Item -Path '.\AuditMode.cip' -Force + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - ################################### User Interaction #################################### + #Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause # Store the program paths that user browses for in an array - [System.Object[]]$ProgramsPaths = @() + [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null - $OBJ = New-Object System.Windows.Forms.FolderBrowserDialog + [System.Windows.Forms.FolderBrowserDialog]$OBJ = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog $OBJ.InitialDirectory = "$env:SystemDrive" $OBJ.Description = $Description - $Spawn = New-Object System.Windows.Forms.Form -Property @{TopMost = $true } - $Show = $OBJ.ShowDialog($Spawn) + [System.Windows.Forms.Form]$Spawn = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true } + [System.String]$Show = $OBJ.ShowDialog($Spawn) If ($Show -eq 'OK') { $ProgramsPaths += $OBJ.SelectedPath } Else { break } } while ($true) + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -408,16 +413,17 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item } Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object -Process { $_ } + $ProgramsPaths | ForEach-Object -Process { $_.FullName } - ################################### EventCapturing ################################ + #Region EventCapturing Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan # Extracting the array content from Get-AuditEventLogsProcessing function $AuditEventLogsProcessingResults = Get-AuditEventLogsProcessing -Date $Date - # Only create policy for files that are available on the disk based on Event viewer logs but weren't in user-selected program path(s), if there are any + # Only create policy for files that are available on the disk (based on Event viewer logs) + # but weren't in user-selected program path(s), if there are any if ($AuditEventLogsProcessingResults.AvailableFilesPaths) { # Using the function to find out which files are not in the user-selected path(s), if any, to only scan those @@ -428,14 +434,15 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Another check to make sure there were indeed files found in Event viewer logs but weren't in any of the user-selected path(s) if ($TestFilePathResults) { + # Create a folder in Temp directory to copy the files that are not included in user-selected program path(s) # but detected in Event viewer audit logs, scan that folder, and in the end delete it - New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory | Out-Null + New-Item -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles" -ItemType Directory -Force | Out-Null Write-Verbose -Message 'The following file(s) are being copied to the TEMP directory for scanning because they were found in event logs but did not exist in any of the user-selected paths:' $TestFilePathResults | ForEach-Object -Process { Write-Verbose -Message "$_" - Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -ErrorAction SilentlyContinue + Copy-Item -Path $_ -Destination "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force -ErrorAction SilentlyContinue } # Create a policy XML file for available files on the disk @@ -456,11 +463,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$NoUserPEs) { $AvailableFilesOnDiskPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message 'Creating a policy file for files that are available on the disk but were not in user-selected program path(s)' New-CIPolicy @AvailableFilesOnDiskPolicyMakerHashTable # Add the policy XML file to the array that holds policy XML files $PolicyXMLFilesArray += '.\RulesForFilesNotInUserSelectedPaths.xml' + # Delete the Temporary folder in the TEMP folder + Write-Verbose -Message 'Deleting the Temporary folder in the TEMP folder' Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporaryScanFolderForEventViewerFiles\" -Force } } @@ -469,22 +479,36 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # if user chose to include deleted files in the final supplemental policy if ($AuditEventLogsProcessingResults.DeletedFileHashes -and $IncludeDeletedFiles) { - Write-Verbose -Message "$($AuditEventLogsProcessingResults.DeletedFileHashes.count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" - $AuditEventLogsProcessingResults.DeletedFileHashes | ForEach-Object -Process { - Write-Verbose -Message "$($_.'File Name')" + Write-Verbose -Message 'Attempting to create a policy for files that are no longer available on the disk but were detected in event viewer logs' + + # Displaying the unique values and count. Even though the DeletedFileHashesEventsPolicy.xml will have many duplicates, the final supplemental policy that will be deployed on the system won't have any duplicates + # Because Merge-CiPolicy will automatically take care of removing them + Write-Verbose -Message "$(($AuditEventLogsProcessingResults.DeletedFileHashes.'File Name' | Select-Object -Unique).count) file(s) have been found in event viewer logs that were run during Audit phase but are no longer on the disk, they are as follows:" + $AuditEventLogsProcessingResults.DeletedFileHashes.'File Name' | Select-Object -Unique | ForEach-Object -Process { + Write-Verbose -Message "$_" } + Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' + [System.String]$FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes + [System.String]$RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes - (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) + (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath FileRulesAndFileRefs.txt -Force - + Write-Verbose -Message 'Saving the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes' + $FileRulesHashesResults + $RuleRefsHashesResults | Out-File -FilePath FileRulesAndFileRefs.txt -Force + # Put the Rules and RulesRefs in an empty policy file - New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) -RuleRefsContent (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes) | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force + Write-Verbose -Message 'Putting the Rules and RulesRefs in an empty policy file' + New-EmptyPolicy -RulesContent $FileRulesHashesResults -RuleRefsContent $RuleRefsHashesResults | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force # adding the policy file that consists of rules from audit even logs, to the array + Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } + #Endregion EventCapturing - ######################## Process Program Folders From User input ##################### + #Region Process-Program-Folders-From-User-input + Write-Verbose -Message 'Scanning each of the folder paths that user selected' + for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -503,6 +527,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message "Currently scanning: $($ProgramsPaths[$i])" New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } From 54bee461722addd21f5b2957b718109ffbecb8c4 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 03:44:06 -0930 Subject: [PATCH 130/178] Improved Edit-SignedWDACConfig event capture --- .../Core/Edit-SignedWDACConfig.psm1 | 78 +++++++++++++------ .../Core/Edit-WDACConfig.psm1 | 4 +- 2 files changed, 59 insertions(+), 23 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index e588257e9..afd4a603d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -531,17 +531,22 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + # Merge-Cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' + + [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } + #Endregion Process-Program-Folders-From-User-input #region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them + Write-Verbose -Message 'Checking for Kernel protected files' + # Finding the file(s) first and storing them in an array [System.String[]]$ExesWithNoHash = @() @@ -549,23 +554,25 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I foreach ($ProgramsPath in $ProgramsPaths) { # Making sure the currently processing path has any .exe in it - [System.String[]]$AnyAvailableExes = (Get-ChildItem -Recurse -Path $ProgramsPath -Filter '*.exe').FullName + [System.String[]]$AnyAvailableExes = (Get-ChildItem -File -Recurse -Path $ProgramsPath -Filter '*.exe').FullName + # if any .exe was found then continue testing them if ($AnyAvailableExes) { - $AnyAvailableExes | ForEach-Object -Process { - $CurrentExeWithNoHash = $_ + foreach ($Exe in $AnyAvailableExes) { try { # Testing each executable to find the protected ones - Get-FileHash -Path $CurrentExeWithNoHash -ErrorAction Stop | Out-Null + Get-FileHash -Path $Exe -ErrorAction Stop | Out-Null } + # If the executable is protected, it will throw an exception and the script will continue to the next one # Making sure only the right file is captured by narrowing down the error type. # E.g., when get-filehash can't get a file's hash because its open by another program, the exception is different: System.IO.IOException catch [System.UnauthorizedAccessException] { - $ExesWithNoHash += $CurrentExeWithNoHash + $ExesWithNoHash += $Exe } } - } + } } + # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { @@ -594,12 +601,13 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } } } + $KernelProtectedHashesBlockResults = Invoke-Command -ScriptBlock $KernelProtectedHashesBlock # Only proceed further if any hashes belonging to the detected kernel protected files were found in Event viewer # If none is found then skip this part, because user didn't run those files/programs when audit mode was turned on in base policy, so no hash was found in audit logs if ($KernelProtectedHashesBlockResults) { - + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath KernelProtectedFiles.txt -Force @@ -607,7 +615,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath .\KernelProtectedFiles.xml -Force # adding the policy file to the array of xml files - $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' + $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' } else { Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on." @@ -621,12 +629,12 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null - + # Delete these extra files unless user uses -Debug parameter if (-NOT $Debug) { - Remove-Item -Path '.\FileRulesAndFileRefs.txt', '.\DeletedFileHashesEventsPolicy.xml' -Force -ErrorAction SilentlyContinue - Remove-Item -Path '.\ProgramDir_ScanResults*.xml', '.\RulesForFilesNotInUserSelectedPaths.xml' -Force -ErrorAction SilentlyContinue - Remove-Item -Path '.\KernelProtectedFiles.txt', '.\KernelProtectedFiles.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\RulesForFilesNotInUserSelectedPaths.xml', '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\KernelProtectedFiles.xml', '.\DeletedFileHashesEventsPolicy.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\KernelProtectedFiles.txt', '.\FileRulesAndFileRefs.txt' -Force -ErrorAction SilentlyContinue } } # Unlike AllowNewApps parameter, AllowNewAppsAuditEvents parameter performs Event viewer scanning and kernel protected files detection @@ -643,23 +651,33 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - } + } - #################### Supplemental-policy-processing-and-deployment ############################ + #Region Supplemental-policy-processing-and-deployment - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" - $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath + Write-Verbose -Message 'Supplemental policy processing and deployment' + [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' + [System.String]$SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) + + Write-Verbose -Message 'Adding signer rule to the Supplemental policy' Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel # Make sure policy rule options that don't belong to a Supplemental policy don't exist + Write-Verbose -Message 'Making sure policy rule options that do not belong to a Supplemental policy do not exist' @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath $SuppPolicyPath - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" @@ -667,19 +685,35 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used + } + # Only show the output of SignTool if Debug switch is used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' Start-Process @ProcessParams + Write-Verbose -Message 'Removing the unsigned Supplemental policy file' Remove-Item -Path ".\$SuppPolicyID.cip" -Force + + Write-Verbose -Message 'Renaming the signed Supplemental policy file to remove the .p7 extension' Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + + Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + + # Remove the policy xml file in Temp folder we created earlier + Remove-Item -Path $PolicyPath -Force + + #Endregion Supplemental-policy-processing-and-deployment } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 236e621bc..d5af478fa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -667,7 +667,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # Merge-cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + # Merge-Cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' @@ -708,6 +708,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } } } + # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) if ($ExesWithNoHash) { @@ -736,6 +737,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } } } + $KernelProtectedHashesBlockResults = Invoke-Command -ScriptBlock $KernelProtectedHashesBlock # Only proceed further if any hashes belonging to the detected kernel protected files were found in Event viewer From 400250fa3dcd0579af10fd12ff0ffe34baa6983a Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 03:47:19 -0930 Subject: [PATCH 131/178] Relocated $AllowNewApps block for consistency Now the block is in the same place in Edit-SignedWDACConfig and Edit-WDACConfig --- .../Core/Edit-SignedWDACConfig.psm1 | 402 +++++++++--------- 1 file changed, 201 insertions(+), 201 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index afd4a603d..1f7e29725 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -272,6 +272,207 @@ Function Edit-SignedWDACConfig { process { + if ($AllowNewApps) { + + # remove any possible files from previous runs + Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy + [System.Object[]]$PolicyXMLFilesArray = @() + + #Initiate Live Audit Mode + + foreach ($PolicyPath in $PolicyPaths) { + # Creating a copy of the original policy in Temp folder so that the original one will be unaffected + $PolicyFileName = Split-Path $PolicyPath -Leaf + Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force + $PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" + + # Defining Base policy + $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + [System.String]$PolicyID = $xml.SiPolicy.PolicyID + [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + + # Remove any cip file if there is any + Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue + + # Create CIP for Audit Mode + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null + + # Create CIP for Enforced Mode + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null + + # Sign both CIPs + '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { + # Configure the parameter splat + $ProcessParams = @{ + 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', "`"$_`"" + 'FilePath' = $SignToolPathFinal + 'NoNewWindow' = $true + 'Wait' = $true + 'ErrorAction' = 'Stop' + } # Only show the output of SignTool if Debug switch is used + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Start-Process @ProcessParams + + # After creating signed .p7 files for each CIP, remove the old Unsigned ones + Remove-Item -Path $_ -Force + } + Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force + Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force + + ################# Snap back guarantee ################# + Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' + + $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' + $command = @" +CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force +"@ + $command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force + New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null + + # Deploy Audit mode CIP + Write-Verbose -Message 'Deploying Audit mode CIP' + Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' + Write-Output -InputObject "PolicyName = $PolicyName" + Write-Output -InputObject "PolicyGUID = $PolicyID" + # Remove Audit Mode CIP + Remove-Item -Path ".\$PolicyID.cip" -Force + # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time + Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + + # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode + Try { + ################################### User Interaction #################################### + Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' + Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' + Pause + + # Store the program paths that user browses for in an array + [System.Object[]]$ProgramsPaths = @() + Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan + # Showing folder picker GUI to the user for folder path selection + do { + [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null + $OBJ = New-Object System.Windows.Forms.FolderBrowserDialog + $OBJ.InitialDirectory = "$env:SystemDrive" + $OBJ.Description = $Description + $Spawn = New-Object System.Windows.Forms.Form -Property @{TopMost = $true } + $Show = $OBJ.ShowDialog($Spawn) + If ($Show -eq 'OK') { $ProgramsPaths += $OBJ.SelectedPath } + Else { break } + } + while ($true) + + # Make sure User browsed for at least 1 directory + # Exit the operation if user didn't select any folder paths + if ($ProgramsPaths.count -eq 0) { + Write-Host -Object 'No program folder was selected, reverting the changes and quitting...' -ForegroundColor Red + # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode + break + } + } + catch { + # Show any extra info about any possible error that might've occurred + Throw $_ + } + finally { + # Deploy Enforced mode CIP + Write-Verbose -Message 'Finally Block Running' + Update-BasePolicyToEnforced + # Enforced Mode Snapback removal after base policy has already been successfully re-enforced + Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' + Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force + Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + } + + Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow + $ProgramsPaths | ForEach-Object -Process { $_ } + + #Process Program Folders From User input + + # Scan each of the folder paths that user selected + for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { + + # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet + [System.Collections.Hashtable]$UserInputProgramFoldersPolicyMakerHashTable = @{ + FilePath = ".\ProgramDir_ScanResults$($i).xml" + ScanPath = $ProgramsPaths[$i] + Level = $Level + Fallback = $Fallbacks + MultiplePolicyFormat = $true + UserWriteablePaths = $true + AllowFileNameFallbacks = $true + } + # Assess user input parameters and add the required parameters to the hash table + if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } + if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } + if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } + + # Create the supplemental policy via parameter splatting + New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable + } + + # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders + $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + foreach ($file in $ProgramDir_ScanResults) { + $PolicyXMLFilesArray += $file.FullName + } + + Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' + $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } + + # Merge all of the policy XML files in the array into the final Supplemental policy + Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null + + Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force + + #################### Supplemental-policy-processing-and-deployment ############################ + + $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath + $SuppPolicyID = $SuppPolicyID.Substring(11) + Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel + + # Make sure policy rule options that don't belong to a Supplemental policy don't exist + @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + + Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + + ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + + # Configure the parameter splat + $ProcessParams = @{ + 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" + 'FilePath' = $SignToolPathFinal + 'NoNewWindow' = $true + 'Wait' = $true + 'ErrorAction' = 'Stop' + } # Only show the output of SignTool if Debug switch is used + if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Start-Process @ProcessParams + + Remove-Item -Path ".\$SuppPolicyID.cip" -Force + Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' + Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" + Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + Remove-Item -Path ".\$SuppPolicyID.cip" -Force + Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + } + } + if ($AllowNewAppsAuditEvents) { # Change Code Integrity event logs size if ($AllowNewAppsAuditEvents -and $LogSize) { @@ -717,207 +918,6 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } } - if ($AllowNewApps) { - - # remove any possible files from previous runs - Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue - Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue - # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy - [System.Object[]]$PolicyXMLFilesArray = @() - - #Initiate Live Audit Mode - - foreach ($PolicyPath in $PolicyPaths) { - # Creating a copy of the original policy in Temp folder so that the original one will be unaffected - $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder - Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force - $PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" - - # Defining Base policy - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string - - # Remove any cip file if there is any - Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue - - # Create CIP for Audit Mode - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null - - # Create CIP for Enforced Mode - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null - - # Sign both CIPs - '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { - # Configure the parameter splat - $ProcessParams = @{ - 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', "`"$_`"" - 'FilePath' = $SignToolPathFinal - 'NoNewWindow' = $true - 'Wait' = $true - 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } - # Sign the files with the specified cert - Start-Process @ProcessParams - - # After creating signed .p7 files for each CIP, remove the old Unsigned ones - Remove-Item -Path $_ -Force - } - Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force - Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force - - ################# Snap back guarantee ################# - Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' - - $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - $command = @" -CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force -"@ - $command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - # Deploy Audit mode CIP - Write-Verbose -Message 'Deploying Audit mode CIP' - Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" - # Remove Audit Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force - # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force - - # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode - Try { - ################################### User Interaction #################################### - Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' - Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' - Pause - - # Store the program paths that user browses for in an array - [System.Object[]]$ProgramsPaths = @() - Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan - # Showing folder picker GUI to the user for folder path selection - do { - [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null - $OBJ = New-Object System.Windows.Forms.FolderBrowserDialog - $OBJ.InitialDirectory = "$env:SystemDrive" - $OBJ.Description = $Description - $Spawn = New-Object System.Windows.Forms.Form -Property @{TopMost = $true } - $Show = $OBJ.ShowDialog($Spawn) - If ($Show -eq 'OK') { $ProgramsPaths += $OBJ.SelectedPath } - Else { break } - } - while ($true) - - # Make sure User browsed for at least 1 directory - # Exit the operation if user didn't select any folder paths - if ($ProgramsPaths.count -eq 0) { - Write-Host -Object 'No program folder was selected, reverting the changes and quitting...' -ForegroundColor Red - # Causing break here to stop operation. Finally block will be triggered to Re-Deploy Base policy in Enforced mode - break - } - } - catch { - # Show any extra info about any possible error that might've occurred - Throw $_ - } - finally { - # Deploy Enforced mode CIP - Write-Verbose -Message 'Finally Block Running' - Update-BasePolicyToEnforced - # Enforced Mode Snapback removal after base policy has already been successfully re-enforced - Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - } - - Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object -Process { $_ } - - #Process Program Folders From User input - - # Scan each of the folder paths that user selected - for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { - - # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet - [System.Collections.Hashtable]$UserInputProgramFoldersPolicyMakerHashTable = @{ - FilePath = ".\ProgramDir_ScanResults$($i).xml" - ScanPath = $ProgramsPaths[$i] - Level = $Level - Fallback = $Fallbacks - MultiplePolicyFormat = $true - UserWriteablePaths = $true - AllowFileNameFallbacks = $true - } - # Assess user input parameters and add the required parameters to the hash table - if ($SpecificFileNameLevel) { $UserInputProgramFoldersPolicyMakerHashTable['SpecificFileNameLevel'] = $SpecificFileNameLevel } - if ($NoScript) { $UserInputProgramFoldersPolicyMakerHashTable['NoScript'] = $true } - if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } - - # Create the supplemental policy via parameter splatting - New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable - } - - # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } - foreach ($file in $ProgramDir_ScanResults) { - $PolicyXMLFilesArray += $file.FullName - } - - Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' - $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } - - # Merge all of the policy XML files in the array into the final Supplemental policy - Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null - - Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - - #################### Supplemental-policy-processing-and-deployment ############################ - - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" - $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath - $SuppPolicyID = $SuppPolicyID.Substring(11) - Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel - - # Make sure policy rule options that don't belong to a Supplemental policy don't exist - @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } - - Set-HVCIOptions -Strict -FilePath $SuppPolicyPath - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - - ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - - # Configure the parameter splat - $ProcessParams = @{ - 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" - 'FilePath' = $SignToolPathFinal - 'NoNewWindow' = $true - 'Wait' = $true - 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } - # Sign the files with the specified cert - Start-Process @ProcessParams - - Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' - Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" - Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" - Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier - } - } - if ($MergeSupplementalPolicies) { foreach ($PolicyPath in $PolicyPaths) { ############ Input policy verification prior to doing anything ############ From b7a2ad09c53fa9d8365703c9e1f13f876305e841 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 03:48:14 -0930 Subject: [PATCH 132/178] Removed trailing whitespaces --- .../Core/Confirm-WDACConfig.psm1 | 4 +- .../Core/Deploy-SignedWDACConfig.psm1 | 4 +- .../Core/Edit-SignedWDACConfig.psm1 | 50 ++++++++-------- .../Core/Edit-WDACConfig.psm1 | 60 +++++++++---------- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/Invoke-WDACSimulation.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 2 +- .../Core/New-KernelModeWDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 6 +- .../Core/New-WDACConfig.psm1 | 4 +- .../Core/Remove-CommonWDACConfig.psm1 | 2 +- .../Core/Remove-WDACConfig.psm1 | 2 +- .../Core/Set-CommonWDACConfig.psm1 | 4 +- 13 files changed, 72 insertions(+), 72 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index 5cff656c5..c1c83e040 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -65,10 +65,10 @@ Function Confirm-WDACConfig { begin { # Detecting if Verbose switch is used $PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null - + # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 4883bd8e8..1faa7fd95 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -35,14 +35,14 @@ Function Deploy-SignedWDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-SignTool.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Confirm-CertCN.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force - + # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 1f7e29725..1e998c0b0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -122,7 +122,7 @@ Function Edit-SignedWDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -267,7 +267,7 @@ Function Edit-SignedWDACConfig { Write-Host -Object "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item -Path '.\EnforcedMode.cip' -Force - } + } } process { @@ -484,11 +484,11 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue - + # Get the current date so that instead of the entire event viewer logs, only audit logs created after running this module will be captured Write-Verbose -Message 'Getting the current date' [System.DateTime]$Date = Get-Date - + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() @@ -512,7 +512,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Remove any cip file if there is any Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue - + Write-Verbose -Message 'Creating Audit Mode CIP' # Remove Unsigned policy rule option Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete @@ -523,7 +523,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Verbose -Message 'Creating Enforced Mode CIP' # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Audit mode policy rule option Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Create CIP for Enforced Mode @@ -549,8 +549,8 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item Write-Verbose -Message 'Removing the unsigned CIPs' Remove-Item -Path '.\EnforcedMode.cip' -Force - Remove-Item -Path '.\AuditMode.cip' -Force - + Remove-Item -Path '.\AuditMode.cip' -Force + Write-Verbose -Message 'Renaming the signed CIPs to remove the .p7 extension' Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force @@ -572,7 +572,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - + Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -590,7 +590,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Store the program paths that user browses for in an array [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan - + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -692,11 +692,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' [System.String]$FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes [System.String]$RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() - + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes Write-Verbose -Message 'Saving the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes' $FileRulesHashesResults + $RuleRefsHashesResults | Out-File -FilePath FileRulesAndFileRefs.txt -Force - + # Put the Rules and RulesRefs in an empty policy file Write-Verbose -Message 'Putting the Rules and RulesRefs in an empty policy file' New-EmptyPolicy -RulesContent $FileRulesHashesResults -RuleRefsContent $RuleRefsHashesResults | Out-File -FilePath .\DeletedFileHashesEventsPolicy.xml -Force @@ -709,7 +709,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I #Region Process-Program-Folders-From-User-input Write-Verbose -Message 'Scanning each of the folder paths that user selected' - + for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -739,7 +739,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } - #Endregion Process-Program-Folders-From-User-input + #Endregion Process-Program-Folders-From-User-input #region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app @@ -756,7 +756,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Making sure the currently processing path has any .exe in it [System.String[]]$AnyAvailableExes = (Get-ChildItem -File -Recurse -Path $ProgramsPath -Filter '*.exe').FullName - + # if any .exe was found then continue testing them if ($AnyAvailableExes) { foreach ($Exe in $AnyAvailableExes) { @@ -771,7 +771,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash += $Exe } } - } + } } # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) @@ -808,7 +808,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Only proceed further if any hashes belonging to the detected kernel protected files were found in Event viewer # If none is found then skip this part, because user didn't run those files/programs when audit mode was turned on in base policy, so no hash was found in audit logs if ($KernelProtectedHashesBlockResults) { - + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) + (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath KernelProtectedFiles.txt -Force @@ -816,7 +816,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-EmptyPolicy -RulesContent (Get-FileRules -HashesArray $KernelProtectedHashesBlockResults) -RuleRefsContent (Get-RuleRefs -HashesArray $KernelProtectedHashesBlockResults) | Out-File -FilePath .\KernelProtectedFiles.xml -Force # adding the policy file to the array of xml files - $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' + $PolicyXMLFilesArray += '.\KernelProtectedFiles.xml' } else { Write-Warning -Message "The following Kernel protected files detected, but no hash was found for them in Event viewer logs.`nThis means you didn't run those files/programs when Audit mode was turned on." @@ -830,7 +830,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Merge all of the policy XML files in the array into the final Supplemental policy Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null - + # Delete these extra files unless user uses -Debug parameter if (-NOT $Debug) { Remove-Item -Path '.\RulesForFilesNotInUserSelectedPaths.xml', '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue @@ -847,12 +847,12 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Deploy Enforced mode CIP Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced - + # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - } + } #Region Supplemental-policy-processing-and-deployment @@ -874,11 +874,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Set-HVCIOptions -Strict -FilePath $SuppPolicyPath Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' - Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', ".\$SuppPolicyID.cip" @@ -886,7 +886,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } + } # Only show the output of SignTool if Debug switch is used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } @@ -910,7 +910,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - + # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index d5af478fa..9023af0e3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -102,7 +102,7 @@ Function Edit-WDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -183,7 +183,7 @@ Function Edit-WDACConfig { return [System.String[]]$Levelz } } - + function Update-BasePolicyToEnforced { <# .SYNOPSIS @@ -213,7 +213,7 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue - + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() @@ -284,15 +284,15 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - + Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" - + # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force #Endregion Snap-Back-Guarantee @@ -307,7 +307,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Store the program paths that user browses for in an array [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan - + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -321,7 +321,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } while ($true) #Endregion User-Interaction - + # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths if ($ProgramsPaths.count -eq 0) { @@ -418,17 +418,17 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" - + Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - + # Remove the policy xml file in Temp folder we created earlier Write-Verbose -Message 'Removing the policy xml file in Temp folder we created earlier' Remove-Item -Path $PolicyPath -Force @@ -443,21 +443,21 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Changing Code Integrity event logs size' Set-LogSize -LogSize $LogSize } - + # Make sure there is no leftover from previous runs Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue - + # Get the current date so that instead of the entire event viewer logs, only audit logs created after running this module will be captured Write-Verbose -Message 'Getting the current date' [System.DateTime]$Date = Get-Date - + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() #Initiate Live Audit Mode - + foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' @@ -502,11 +502,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - + Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -525,7 +525,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Store the program paths that user browses for in an array [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan - + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null @@ -627,7 +627,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' [System.String]$FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes [System.String]$RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() - + # Save the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes Write-Verbose -Message 'Saving the File Rules and File Rule Refs in the FileRulesAndFileRefs.txt in the current working directory for debugging purposes' $FileRulesHashesResults + $RuleRefsHashesResults | Out-File -FilePath FileRulesAndFileRefs.txt -Force @@ -666,7 +666,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message "Currently scanning: $($ProgramsPaths[$i])" New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - + # Merge-Cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' @@ -685,13 +685,13 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Finding the file(s) first and storing them in an array [System.String[]]$ExesWithNoHash = @() - + # looping through each user-selected path(s) foreach ($ProgramsPath in $ProgramsPaths) { # Making sure the currently processing path has any .exe in it [System.String[]]$AnyAvailableExes = (Get-ChildItem -File -Recurse -Path $ProgramsPath -Filter '*.exe').FullName - + # if any .exe was found then continue testing them if ($AnyAvailableExes) { foreach ($Exe in $AnyAvailableExes) { @@ -706,7 +706,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash += $Exe } } - } + } } # Only proceed if any kernel protected file(s) were found in any of the user-selected directory path(s) @@ -737,7 +737,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } } } - + $KernelProtectedHashesBlockResults = Invoke-Command -ScriptBlock $KernelProtectedHashesBlock # Only proceed further if any hashes belonging to the detected kernel protected files were found in Event viewer @@ -793,7 +793,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Supplemental policy processing and deployment' [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" - + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' [System.String]$SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) @@ -810,17 +810,17 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" - + Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - + # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index b82f91d7a..ece00593f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -120,5 +120,5 @@ Function Get-CommonWDACConfig { .OUTPUTS System.Object[] -#> +#> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 6ab62f4b5..7b31d6e10 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -19,7 +19,7 @@ Function Invoke-WDACSimulation { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing resources such as functions by dot-sourcing so that they will run in the same scope and their variables will be usable . "$ModuleRootPath\Resources\Resources2.ps1" diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index c31982d7c..504b6845b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -58,7 +58,7 @@ Function New-DenyWDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 91a948af8..389603359 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -33,7 +33,7 @@ Function New-KernelModeWDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 2c34fbc0a..d15c6da6a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -64,7 +64,7 @@ Function New-SupplementalWDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -169,7 +169,7 @@ Function New-SupplementalWDACConfig { Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" - + if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." @@ -200,7 +200,7 @@ Function New-SupplementalWDACConfig { Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null - + Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 35de76e65..cc894e0bf 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -85,7 +85,7 @@ Function New-WDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force @@ -768,7 +768,7 @@ Function New-WDACConfig { Write-Output -InputObject "BasePolicyFile = $BasePolicy" Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" - + Write-Output -InputObject 'SupplementalPolicyFile = SupplementalPolicy.xml' Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index 2b000b30c..cea97fff9 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -166,5 +166,5 @@ Function Remove-CommonWDACConfig { .PARAMETER StrictKernelNoFlightRootsPolicyGUID Removes the StrictKernelNoFlightRootsPolicyGUID from User Configs -#> +#> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 5c428ef6a..17bb76b34 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -119,7 +119,7 @@ Function Remove-WDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Update-self.psm1" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 9d61e420b..bb1f1e278 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -54,7 +54,7 @@ Function Set-CommonWDACConfig { begin { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - + # Importing the required sub-modules Write-Verbose -Message 'Importing the required sub-modules' Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force @@ -229,7 +229,7 @@ Function Set-CommonWDACConfig { .OUTPUTS System.Object[] -#> +#> } # Importing argument completer ScriptBlocks From 238db4d6e57e4a040b7f3b4cf8b58b40b04c2028 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 10:08:00 -0930 Subject: [PATCH 133/178] Improved AllowNewApps param of Edit-SignedWDACConf --- .../Core/Edit-SignedWDACConfig.psm1 | 144 ++++++++++++------ .../Core/Edit-WDACConfig.psm1 | 8 +- 2 files changed, 104 insertions(+), 48 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 1e998c0b0..30b5e11c1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -273,10 +273,11 @@ Function Edit-SignedWDACConfig { process { if ($AllowNewApps) { - # remove any possible files from previous runs + Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path ".\SupplementalPolicy $SuppPolicyName.xml" -Force -ErrorAction SilentlyContinue + # An empty array that holds the Policy XML files - This array will eventually be used to create the final Supplemental policy [System.Object[]]$PolicyXMLFilesArray = @() @@ -284,31 +285,41 @@ Function Edit-SignedWDACConfig { foreach ($PolicyPath in $PolicyPaths) { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected - $PolicyFileName = Split-Path $PolicyPath -Leaf - Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue # make sure no file with the same name already exists in Temp folder + Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' + # Get the policy file name + [System.String]$PolicyFileName = Split-Path -Path $PolicyPath -Leaf + # make sure no file with the same name already exists in Temp folder + Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force - $PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" + [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" - # Defining Base policy + Write-Verbose -Message 'Retrieving the Base policy name and ID' $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyID = $xml.SiPolicy.PolicyID [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any + Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' Remove-Item -Path '.\*.cip' -Force -ErrorAction SilentlyContinue + Write-Verbose -Message 'Creating Audit Mode CIP' + # Remove Unsigned policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete + # Add Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 # Create CIP for Audit Mode - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 3 # Add Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\AuditMode.cip' | Out-Null + Write-Verbose -Message 'Creating Enforced Mode CIP' + # Remove Unsigned policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete + # Remove Audit mode policy rule option + Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Create CIP for Enforced Mode - Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete # Remove Unsigned policy rule option - Set-RuleOption -FilePath $PolicyPath -Option 3 -Delete # Remove Audit mode policy rule option - ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedModeTemp.cip' | Out-Null + ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null # Sign both CIPs - '.\AuditModeTemp.cip', '.\EnforcedModeTemp.cip' | ForEach-Object -Process { + '.\AuditMode.cip', '.\EnforcedMode.cip' | ForEach-Object -Process { # Configure the parameter splat $ProcessParams = @{ 'ArgumentList' = 'sign', '/v' , '/n', "`"$CertCN`"", '/p7', '.', '/p7co', '1.3.6.1.4.1.311.79.1', '/fd', 'certHash', "`"$_`"" @@ -324,53 +335,65 @@ Function Edit-SignedWDACConfig { # After creating signed .p7 files for each CIP, remove the old Unsigned ones Remove-Item -Path $_ -Force } - Rename-Item -Path '.\EnforcedModeTemp.cip.p7' -NewName '.\EnforcedMode.cip' -Force - Rename-Item -Path '.\AuditModeTemp.cip.p7' -NewName '.\AuditMode.cip' -Force - ################# Snap back guarantee ################# + Write-Verbose -Message 'Removing the unsigned CIPs' + Remove-Item -Path '.\EnforcedMode.cip' -Force + Remove-Item -Path '.\AuditMode.cip' -Force + + Write-Verbose -Message 'Renaming the signed CIPs to remove the .p7 extension' + Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force + Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force + + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' - $registryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - $command = @" -CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item -Path "$((Get-Location).Path)\$PolicyID.cip" -Force + # Defining the registry path for RunOnce key + [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' + # Defining the command that will be executed by the RunOnce key in case of a reboot + [System.String]$Command = @" +CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force "@ - $command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - New-ItemProperty -Path $registryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null + # Saving the command to a file that will be executed by the RunOnce key in case of a reboot + $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force + # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key + New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null + + Write-Verbose -Message 'Deploying the Audit mode CIP' + # Deploy the Audit mode CIP + &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - # Deploy Audit mode CIP - Write-Verbose -Message 'Deploying Audit mode CIP' - Rename-Item -Path '.\AuditMode.cip' -NewName ".\$PolicyID.cip" -Force - &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" - # Remove Audit Mode CIP - Remove-Item -Path ".\$PolicyID.cip" -Force - # Prepare Enforced Mode CIP for Deployment - waiting to be Re-deployed at the right time - Rename-Item -Path '.\EnforcedMode.cip' -NewName ".\$PolicyID.cip" -Force + + # Remove the Audit Mode CIP + Remove-Item -Path '.\AuditMode.cip' -Force + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - ################################### User Interaction #################################### + #Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause # Store the program paths that user browses for in an array - [System.Object[]]$ProgramsPaths = @() + [System.IO.DirectoryInfo[]]$ProgramsPaths = @() Write-Host -Object 'Select program directories to scan' -ForegroundColor Cyan + # Showing folder picker GUI to the user for folder path selection do { [System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null - $OBJ = New-Object System.Windows.Forms.FolderBrowserDialog + [System.Windows.Forms.FolderBrowserDialog]$OBJ = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog $OBJ.InitialDirectory = "$env:SystemDrive" $OBJ.Description = $Description - $Spawn = New-Object System.Windows.Forms.Form -Property @{TopMost = $true } - $Show = $OBJ.ShowDialog($Spawn) + [System.Windows.Forms.Form]$Spawn = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true } + [System.String]$Show = $OBJ.ShowDialog($Spawn) If ($Show -eq 'OK') { $ProgramsPaths += $OBJ.SelectedPath } Else { break } } while ($true) + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -388,18 +411,20 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Deploy Enforced mode CIP Write-Verbose -Message 'Finally Block Running' Update-BasePolicyToEnforced + # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' + + # For PowerShell Method Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow - $ProgramsPaths | ForEach-Object -Process { $_ } - - #Process Program Folders From User input + $ProgramsPaths | ForEach-Object -Process { $_.FullName } # Scan each of the folder paths that user selected + Write-Verbose -Message 'Scanning each of the folder paths that user selected' for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -418,11 +443,14 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message "Currently scanning: $($ProgramsPaths[$i])" New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } + # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders + Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' + + [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' foreach ($file in $ProgramDir_ScanResults) { $PolicyXMLFilesArray += $file.FullName } @@ -431,23 +459,36 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } # Merge all of the policy XML files in the array into the final Supplemental policy + Write-Verbose -Message 'Merging all of the policy XML files in the array into the final Supplemental policy' Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null + Write-Verbose -Message 'Removing the ProgramDir_ScanResults* xml files' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - #################### Supplemental-policy-processing-and-deployment ############################ + #Region Supplemental-policy-processing-and-deployment + Write-Verbose -Message 'Supplemental policy processing and deployment' - $SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" - $SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath + Write-Verbose -Message 'Getting the path of the Supplemental policy' + [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" + + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' + [System.String]$SuppPolicyID = Set-CIPolicyIdInfo -FilePath $SuppPolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) + + Write-Verbose -Message 'Adding signer rule to the Supplemental policy' Add-SignerRule -FilePath $SuppPolicyPath -CertificatePath $CertPath -Update -User -Kernel # Make sure policy rule options that don't belong to a Supplemental policy don't exist + Write-Verbose -Message 'Making sure policy rule options that do not belong to a Supplemental policy do not exist' @(0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath $SuppPolicyPath -Option $_ -Delete } + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath $SuppPolicyPath + + Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' + Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat @@ -459,17 +500,31 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' Start-Process @ProcessParams + Write-Verbose -Message 'Removing the unsigned Supplemental policy file' Remove-Item -Path ".\$SuppPolicyID.cip" -Force + + Write-Verbose -Message 'Renaming the signed Supplemental policy file to remove the .p7 extension' Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + + Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force - Remove-Item -Path $PolicyPath -Force # Remove the policy xml file in Temp folder we created earlier + + # Remove the policy xml file in Temp folder we created earlier + Remove-Item -Path $PolicyPath -Force + + #Endregion Supplemental-policy-processing-and-deployment } } @@ -498,7 +553,7 @@ CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json; Remove-Item # Creating a copy of the original policy in Temp folder so that the original one will be unaffected Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' # Get the policy file name - [System.String]$PolicyFileName = Split-Path $PolicyPath -Leaf + [System.String]$PolicyFileName = Split-Path -Path $PolicyPath -Leaf # make sure no file with the same name already exists in Temp folder Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force @@ -573,6 +628,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Deploy the Audit mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID" @@ -732,7 +788,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # Merge-Cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 9023af0e3..1a46339bb 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -223,7 +223,7 @@ Function Edit-WDACConfig { # Creating a copy of the original policy in Temp folder so that the original one will be unaffected Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' # Get the policy file name - [System.String]$PolicyFileName = Split-Path $PolicyPath -Leaf + [System.String]$PolicyFileName = Split-Path -Path $PolicyPath -Leaf # make sure no file with the same name already exists in Temp folder Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force @@ -378,7 +378,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # merge-cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' @@ -462,7 +462,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Creating a copy of the original policy in Temp folder so that the original one will be unaffected Write-Verbose -Message 'Creating a copy of the original policy in Temp folder so that the original one will be unaffected' # Get the policy file name - [System.String]$PolicyFileName = Split-Path $PolicyPath -Leaf + [System.String]$PolicyFileName = Split-Path -Path $PolicyPath -Leaf # make sure no file with the same name already exists in Temp folder Remove-Item -Path "$UserTempDirectoryPath\$PolicyFileName" -Force -ErrorAction SilentlyContinue Copy-Item -Path $PolicyPath -Destination $UserTempDirectoryPath -Force @@ -667,7 +667,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - # Merge-Cipolicy accepts arrays - collecting all the policy files created by scanning user specified folders + # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' From cbf42fbf0a29a587cfca2637a54b3176e09d41da Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 10:34:35 -0930 Subject: [PATCH 134/178] Simplified some foreach loops --- .../Core/Edit-SignedWDACConfig.psm1 | 7 ++----- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 6 ++---- .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 6 ++---- 3 files changed, 6 insertions(+), 13 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 30b5e11c1..2d7049988 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -450,8 +450,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' - [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' - foreach ($file in $ProgramDir_ScanResults) { + foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } @@ -791,8 +790,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' - [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' - foreach ($file in $ProgramDir_ScanResults) { + foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } #Endregion Process-Program-Folders-From-User-input @@ -959,7 +957,6 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 1a46339bb..68d16415a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -381,8 +381,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' - [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' - foreach ($file in $ProgramDir_ScanResults) { + foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } @@ -670,8 +669,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' - [System.IO.FileInfo[]]$ProgramDir_ScanResults = Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml' - foreach ($file in $ProgramDir_ScanResults) { + foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } #Endregion Process-Program-Folders-From-User-input diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 504b6845b..6d8b4e1e9 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -125,11 +125,9 @@ Function New-DenyWDACConfig { Write-Debug -Message 'The Deny policy with the following configuration is being created' if ($Debug) { $UserInputProgramFoldersPolicyMakerHashTable } - # Merge-cipolicy accept arrays - collecting all the policy files created by scanning user specified folders - $ProgramDir_ScanResults = Get-ChildItem -Path '.\' | Where-Object -FilterScript { $_.Name -like 'ProgramDir_ScanResults*.xml' } - foreach ($file in $ProgramDir_ScanResults) { + # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders + foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName - } # Adding the AllowAll default policy path to the array of policy paths From a6d599f26e2c95a4158ce176a0f46d8d5c6fde65 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 10:41:25 -0930 Subject: [PATCH 135/178] Improved variable casings and added named params --- .../Core/Deploy-SignedWDACConfig.psm1 | 22 +++++----- .../Core/Edit-SignedWDACConfig.psm1 | 32 +++++++------- .../Core/Edit-WDACConfig.psm1 | 32 +++++++------- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 38 ++++++++-------- .../Core/New-KernelModeWDACConfig.psm1 | 8 ++-- .../Core/New-SupplementalWDACConfig.psm1 | 44 +++++++++---------- .../Core/New-WDACConfig.psm1 | 18 ++++---- .../Core/Remove-WDACConfig.psm1 | 14 +++--- .../Core/Set-CommonWDACConfig.psm1 | 12 ++--- .../Resources/ArgumentCompleters.ps1 | 8 ++-- .../Shared/Test-FilePath.psm1 | 4 +- 12 files changed, 117 insertions(+), 117 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 1faa7fd95..ed13ee2be 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -115,11 +115,11 @@ Function Deploy-SignedWDACConfig { foreach ($PolicyPath in $PolicyPaths) { # Gather policy details - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyType = $xml.SiPolicy.PolicyType - [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string - [System.String[]]$PolicyRuleOptions = $xml.SiPolicy.Rules.Rule.Option + $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + [System.String]$PolicyType = $Xml.SiPolicy.PolicyType + [System.String]$PolicyID = $Xml.SiPolicy.PolicyID + [System.String]$PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + [System.String[]]$PolicyRuleOptions = $Xml.SiPolicy.Rules.Rule.Option # Remove the .CIP file of the same policy being signed and deployed if any in the current working directory Remove-Item -Path ".\$PolicyID.cip" -ErrorAction SilentlyContinue @@ -199,18 +199,18 @@ Function Deploy-SignedWDACConfig { if (($PolicyType -ne 'Supplemental Policy') -and ($PolicyName -notlike '*Strict Kernel*')) { # Ask user question about whether or not to add the Signed policy xml file to the User Config Json for easier usage later - $userInput = '' - while ($userInput -notin 1, 2) { - $userInput = $(Write-Host -Object 'Add the Signed policy xml file path just created to the User Configurations? Please enter 1 to Confirm or 2 to Skip.' -ForegroundColor Cyan ; Read-Host) - if ($userInput -eq 1) { + $UserInput = '' + while ($UserInput -notin 1, 2) { + $UserInput = $(Write-Host -Object 'Add the Signed policy xml file path just created to the User Configurations? Please enter 1 to Confirm or 2 to Skip.' -ForegroundColor Cyan ; Read-Host) + if ($UserInput -eq 1) { Set-CommonWDACConfig -SignedPolicyPath $PolicyPath Write-ColorfulText -Color HotPink -InputText "Added $PolicyPath to the User Configuration file." } - elseif ($userInput -eq 2) { + elseif ($UserInput -eq 2) { Write-ColorfulText -Color Pink -InputText 'Skipping...' } else { - Write-Warning 'Invalid input. Please enter 1 or 2 only.' + Write-Warning -Message 'Invalid input. Please enter 1 or 2 only.' } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 2d7049988..9c607a7a7 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -47,10 +47,10 @@ Function Edit-SignedWDACConfig { # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit an Unsigned policy using Edit-SignedWDACConfig cmdlet which is only made for Signed policies $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) - $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId - $RedFlag3 = $xmlTest.SiPolicy.PolicyID + $XmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) + $RedFlag1 = $XmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $RedFlag2 = $XmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + $RedFlag3 = $XmlTest.SiPolicy.PolicyID $CurrentPolicyIDs = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if ($RedFlag1 -or $RedFlag2) { # Ensure the selected base policy xml file is deployed @@ -294,9 +294,9 @@ Function Edit-SignedWDACConfig { [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" Write-Verbose -Message 'Retrieving the Base policy name and ID' - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + [System.String]$PolicyID = $Xml.SiPolicy.PolicyID + [System.String]$PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' @@ -559,9 +559,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" Write-Verbose -Message 'Retrieving the Base policy name and ID' - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + [System.String]$PolicyID = $Xml.SiPolicy.PolicyID + [System.String]$PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' @@ -836,8 +836,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { - $xml = [System.Xml.XmlDocument]$event.toxml() - $xml.event.eventdata.data | + $Xml = [System.Xml.XmlDocument]$event.toxml() + $Xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | ForEach-Object -Process { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { @@ -1087,10 +1087,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $CurrentID = "{$CurrentID}" Remove-Item -Path ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue - [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' - $xml.SiPolicy.PolicyID = $CurrentID - $xml.SiPolicy.BasePolicyID = $CurrentID - $xml.Save('.\BasePolicy.xml') + [System.Xml.XmlDocument]$Xml = Get-Content -Path '.\BasePolicy.xml' + $Xml.SiPolicy.PolicyID = $CurrentID + $Xml.SiPolicy.BasePolicyID = $CurrentID + $Xml.Save('.\BasePolicy.xml') Add-SignerRule -FilePath .\BasePolicy.xml -CertificatePath $CertPath -Update -User -Kernel -Supplemental diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 68d16415a..330ed620b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -26,10 +26,10 @@ Function Edit-WDACConfig { # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to # Edit a Signed policy using Edit-WDACConfig cmdlet which is only made for Unsigned policies $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) - $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId - $RedFlag3 = $xmlTest.SiPolicy.PolicyID + $XmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) + $RedFlag1 = $XmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $RedFlag2 = $XmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + $RedFlag3 = $XmlTest.SiPolicy.PolicyID $CurrentPolicyIDs = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' }).policyID | ForEach-Object -Process { "{$_}" } if (!$RedFlag1 -and !$RedFlag2) { # Ensure the selected base policy xml file is deployed @@ -230,9 +230,9 @@ Function Edit-WDACConfig { [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" Write-Verbose -Message 'Retrieving the Base policy name and ID' - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + [System.String]$PolicyID = $Xml.SiPolicy.PolicyID + [System.String]$PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' @@ -468,9 +468,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I [System.String]$PolicyPath = "$UserTempDirectoryPath\$PolicyFileName" Write-Verbose -Message 'Retrieving the Base policy name and ID' - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - [System.String]$PolicyID = $xml.SiPolicy.PolicyID - [System.String]$PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + [System.String]$PolicyID = $Xml.SiPolicy.PolicyID + [System.String]$PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string # Remove any cip file if there is any Write-Verbose -Message 'Removing any cip file if there is any in the current working directory' @@ -715,8 +715,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I [System.Management.Automation.ScriptBlock]$KernelProtectedHashesBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 } -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.TimeCreated -ge $Date } ) { - $xml = [System.Xml.XmlDocument]$event.toxml() - $xml.event.eventdata.data | + $Xml = [System.Xml.XmlDocument]$event.toxml() + $Xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | ForEach-Object -Process { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { @@ -916,10 +916,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" Write-Verbose -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" - [System.Xml.XmlDocument]$xml = Get-Content -Path '.\BasePolicy.xml' - $xml.SiPolicy.PolicyID = $CurrentID - $xml.SiPolicy.BasePolicyID = $CurrentID - $xml.Save('.\BasePolicy.xml') + [System.Xml.XmlDocument]$Xml = Get-Content -Path '.\BasePolicy.xml' + $Xml.SiPolicy.PolicyID = $CurrentID + $Xml.SiPolicy.BasePolicyID = $CurrentID + $Xml.Save('.\BasePolicy.xml') ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null # Deploy the new base policy with the same GUID on the system &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index ece00593f..ea6c3bf30 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -55,7 +55,7 @@ Function Get-CommonWDACConfig { $CurrentUserConfigurations = $CurrentUserConfigurations | ConvertFrom-Json } catch { - Write-Warning 'The UserConfigurations.json was corrupted, clearing it.' + Write-Warning -Message 'The UserConfigurations.json was corrupted, clearing it.' Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" -Value '' } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 6d8b4e1e9..eec74b611 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -135,8 +135,8 @@ Function New-DenyWDACConfig { # creating the final Deny base policy from the xml files in the paths array Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\DenyPolicy $PolicyName.xml" | Out-Null - [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" - [System.String]$policyID = $policyID.Substring(11) + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" + [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { @@ -146,7 +146,7 @@ Function New-DenyWDACConfig { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" - ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" Write-Output -InputObject "DenyPolicyGUID = $PolicyID" @@ -156,11 +156,11 @@ Function New-DenyWDACConfig { } if ($Deploy) { - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null - Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null + Write-Host -NoNewline -Object "`n$PolicyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta Write-Host -Object ' has been deployed.' -ForegroundColor Green - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } } # Create Deny base policy for Driver files @@ -193,8 +193,8 @@ Function New-DenyWDACConfig { Merge-CIPolicy -PolicyPaths 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowAll.xml', '.\DenyPolicy Temp.xml' -OutputFilePath ".\DenyPolicy $PolicyName.xml" | Out-Null Remove-Item -Path '.\DenyPolicy Temp.xml' -Force - [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" - [System.String]$policyID = $policyID.Substring(11) + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" + [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { @@ -204,17 +204,17 @@ Function New-DenyWDACConfig { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" - ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" Write-Output -InputObject "DenyPolicyGUID = $PolicyID" if ($Deploy) { - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null - Write-Host -NoNewline -Object "`n$policyID.cip for " -ForegroundColor Green + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null + Write-Host -NoNewline -Object "`n$PolicyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta Write-Host -Object ' has been deployed.' -ForegroundColor Green - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } } @@ -234,8 +234,8 @@ Function New-DenyWDACConfig { $Package = Get-AppxPackage -Name $args[0] # Create rules for each package - foreach ($item in $Package) { - $Rules += New-CIPolicyRule -Deny -Package $item + foreach ($Item in $Package) { + $Rules += New-CIPolicyRule -Deny -Package $Item } # Generate the supplemental policy xml file @@ -247,8 +247,8 @@ Function New-DenyWDACConfig { # Removing the temp deny policy Remove-Item -Path '.\AppxDenyPolicyTemp.xml' -Force - [System.String]$policyID = Set-CIPolicyIdInfo -FilePath ".\AppxDenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" - [System.String]$policyID = $policyID.Substring(11) + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath ".\AppxDenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" + [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Version '1.0.0.0' @(0, 2, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { @@ -258,15 +258,15 @@ Function New-DenyWDACConfig { Set-RuleOption -FilePath ".\AppxDenyPolicy $PolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" - ConvertFrom-CIPolicy -XmlFilePath ".\AppxDenyPolicy $PolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath ".\AppxDenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "DenyPolicyFile = AppxDenyPolicy $PolicyName.xml" Write-Output -InputObject "DenyPolicyGUID = $PolicyID" if ($Deploy) { - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 389603359..db60a0bfa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -68,18 +68,18 @@ Function New-KernelModeWDACConfig { [System.String]$PolicyID = "{$PolicyIDInput}" # Read the xml file as an xml object - [System.Xml.XmlDocument]$xml = Get-Content -Path $PolicyFilePathInput + [System.Xml.XmlDocument]$Xml = Get-Content -Path $PolicyFilePathInput # Define the new values for PolicyID and BasePolicyID [System.String]$newPolicyID = $PolicyID [System.String]$newBasePolicyID = $PolicyID # Replace the old values with the new ones - $xml.SiPolicy.PolicyID = $newPolicyID - $xml.SiPolicy.BasePolicyID = $newBasePolicyID + $Xml.SiPolicy.PolicyID = $newPolicyID + $Xml.SiPolicy.BasePolicyID = $newBasePolicyID # Save the modified xml file - $xml.Save($PolicyFilePathInput) + $Xml.Save($PolicyFilePathInput) } Function Build-PrepModeStrictKernelPolicy { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index d15c6da6a..9f3a59914 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -124,9 +124,9 @@ Function New-SupplementalWDACConfig { # Ensure when user selects the -Deploy parameter, the base policy is not signed if ($Deploy) { - $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) - $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + $XmlTest = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + $RedFlag1 = $XmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $RedFlag2 = $XmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { Write-Error -Message 'You are using -Deploy parameter and the selected base policy is Signed. Please use Deploy-SignedWDACConfig to deploy it.' } @@ -158,22 +158,22 @@ Function New-SupplementalWDACConfig { # Create the supplemental policy via parameter splatting New-CIPolicy @PolicyMakerHashTable - [System.String]$policyID = Set-CIPolicyIdInfo -FilePath "SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" - [System.String]$policyID = $policyID.Substring(11) + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath "SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" + [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' # Make sure policy rule options that don't belong to a Supplemental policy don't exist @(0, 1, 2, 3, 4, 9, 10, 11, 12, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" - ConvertFrom-CIPolicy -XmlFilePath "SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath "SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } } @@ -187,8 +187,8 @@ Function New-SupplementalWDACConfig { } -args $FolderPath, $SuppPolicyName # Giving the Supplemental policy the correct properties - [System.String]$policyID = Set-CIPolicyIdInfo -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" - [System.String]$policyID = $policyID.Substring(11) + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" + [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' # Make sure policy rule options that don't belong to a Supplemental policy don't exist @@ -199,15 +199,15 @@ Function New-SupplementalWDACConfig { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option 18 Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" - ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } } @@ -228,14 +228,14 @@ Function New-SupplementalWDACConfig { $PackageDependencies = $Package.Dependencies # Create rules for each package - foreach ($item in $Package) { - $Rules += New-CIPolicyRule -Package $item + foreach ($Item in $Package) { + $Rules += New-CIPolicyRule -Package $Item } # Create rules for each pacakge dependency, if any if ($PackageDependencies) { - foreach ($item in $PackageDependencies) { - $Rules += New-CIPolicyRule -Package $item + foreach ($Item in $PackageDependencies) { + $Rules += New-CIPolicyRule -Package $Item } } @@ -245,8 +245,8 @@ Function New-SupplementalWDACConfig { # Giving the Supplemental policy the correct properties - [System.String]$policyID = Set-CIPolicyIdInfo -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" - [System.String]$policyID = $policyID.Substring(11) + [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -ResetPolicyID -BasePolicyToSupplementPath $PolicyPath -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" + [System.String]$PolicyID = $PolicyID.Substring(11) Set-CIPolicyVersion -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Version '1.0.0.0' # Make sure policy rule options that don't belong to a Supplemental policy don't exist @@ -254,15 +254,15 @@ Function New-SupplementalWDACConfig { Set-RuleOption -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" -Option $_ -Delete } Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" - ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "A Supplemental policy with the name $SuppPolicyName has been deployed." - Remove-Item -Path "$policyID.cip" -Force + Remove-Item -Path "$PolicyID.cip" -Force } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index cc894e0bf..410da869f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -650,16 +650,16 @@ Function New-WDACConfig { 'Allow Microsoft Base' { Write-Verbose -Message 'Creating Allow Microsoft Base policy' Build-AllowMSFTWithBlockRules | Out-Null - $xml = [System.Xml.XmlDocument](Get-Content -Path .\AllowMicrosoftPlusBlockRules.xml) - $BasePolicyID = $xml.SiPolicy.PolicyID + $Xml = [System.Xml.XmlDocument](Get-Content -Path .\AllowMicrosoftPlusBlockRules.xml) + $BasePolicyID = $Xml.SiPolicy.PolicyID # define the location of the base policy $BasePolicy = 'AllowMicrosoftPlusBlockRules.xml' } 'Default Windows Base' { Write-Verbose -Message 'Creating Default Windows Base policy' Build-DefaultWindowsWithBlockRules | Out-Null - $xml = [System.Xml.XmlDocument](Get-Content -Path .\DefaultWindowsPlusBlockRules.xml) - $BasePolicyID = $xml.SiPolicy.PolicyID + $Xml = [System.Xml.XmlDocument](Get-Content -Path .\DefaultWindowsPlusBlockRules.xml) + $BasePolicyID = $Xml.SiPolicy.PolicyID # define the location of the base policy $BasePolicy = 'DefaultWindowsPlusBlockRules.xml' } @@ -707,8 +707,8 @@ Function New-WDACConfig { # Get Event viewer logs for code integrity - check the file path of all of the files in the log, resolve them using the command above - show files that are no longer available on the disk [System.Management.Automation.ScriptBlock]$AuditEventLogsDeletedFilesScriptBlock = { foreach ($event in Get-WinEvent -FilterHashtable @{LogName = 'Microsoft-Windows-CodeIntegrity/Operational'; ID = 3076 }) { - $xml = [System.Xml.XmlDocument]$event.toxml() - $xml.event.eventdata.data | + $Xml = [System.Xml.XmlDocument]$event.toxml() + $Xml.event.eventdata.data | ForEach-Object -Begin { $Hash = @{} } -Process { $hash[$_.name] = $_.'#text' } -End { [pscustomobject]$hash } | ForEach-Object -Process { if ($_.'File Name' -match ($pattern = '\\Device\\HarddiskVolume(\d+)\\(.*)$')) { @@ -762,7 +762,7 @@ Function New-WDACConfig { # convert the Supplemental Policy file to .cip binary file Write-Verbose -Message 'Converting SupplementalPolicy.xml policy to .CIP binary' - ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$policyID.cip" | Out-Null + ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null #Endregion Supplemental-Policy-Processing @@ -780,7 +780,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Deploying the Base policy and Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$BasePolicyID.cip" -json | Out-Null - &'C:\Windows\System32\CiTool.exe' --update-policy "$policyID.cip" -json | Out-Null + &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null Write-ColorfulText -Color Pink -InputText "`nBase policy and Supplemental Policies deployed and activated.`n" @@ -905,7 +905,7 @@ Function New-WDACConfig { $MakeLightPolicy { Build-LightPolicy ; break } $MakeDefaultWindowsWithBlockRules { Build-DefaultWindowsWithBlockRules ; break } $PrepDefaultWindowsAudit { Build-DefaultWindowsAudit ; break } - default { Write-Warning 'None of the main parameters were selected.'; break } + default { Write-Warning -Message 'None of the main parameters were selected.'; break } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 17bb76b34..436102d78 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -15,9 +15,9 @@ Function Remove-WDACConfig { [ValidateScript({ # Validate each Policy file in PolicyPaths parameter to make sure the user isn't accidentally trying to remove an Unsigned policy $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) - $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + $XmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) + $RedFlag1 = $XmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $RedFlag2 = $XmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { return $True } } }, ErrorMessage = 'The policy XML file(s) you chose are Unsigned policies. Please use Remove-WDACConfig cmdlet with -UnsignedOrSupplemental parameter instead.')] @@ -252,11 +252,11 @@ Function Remove-WDACConfig { # Convert the XML file into an XML object Write-Verbose -Message 'Converting the XML file to an XML object' - $xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) + $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) # Extract the Policy ID from the XML object Write-Verbose -Message 'Extracting the Policy ID from the XML object' - [System.String]$PolicyID = $xml.SiPolicy.PolicyID + [System.String]$PolicyID = $Xml.SiPolicy.PolicyID Write-Verbose -Message "The policy ID of the currently processing xml file is $PolicyID" # Prevent users from accidentally attempting to remove policies that aren't even deployed on the system @@ -270,9 +270,9 @@ Function Remove-WDACConfig { Write-Verbose -Message 'Sanitizing the XML policy file by removing SupplementalPolicySigners from it' # Extracting the SupplementalPolicySigner ID from the selected XML policy file, if any - $SuppSingerIDs = $xml.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $SuppSingerIDs = $Xml.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId # Extracting the policy name from the selected XML policy file - $PolicyName = ($xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string + $PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string if ($SuppSingerIDs) { Write-Verbose -Message "`n$($SuppSingerIDs.count) SupplementalPolicySigners have been found in $PolicyName policy, removing them now..." diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index bb1f1e278..e973503ca 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -20,9 +20,9 @@ Function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) - $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + $XmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) + $RedFlag1 = $XmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $RedFlag2 = $XmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if (!$RedFlag1 -and !$RedFlag2) { return $True } @@ -34,9 +34,9 @@ Function Set-CommonWDACConfig { [ValidatePattern('\.xml$')] [ValidateScript({ $_ | ForEach-Object -Process { - $xmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) - $RedFlag1 = $xmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId - $RedFlag2 = $xmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId + $XmlTest = [System.Xml.XmlDocument](Get-Content -Path $_) + $RedFlag1 = $XmlTest.SiPolicy.SupplementalPolicySigners.SupplementalPolicySigner.SignerId + $RedFlag2 = $XmlTest.SiPolicy.UpdatePolicySigners.UpdatePolicySigner.SignerId if ($RedFlag1 -or $RedFlag2) { return $True } diff --git a/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 b/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 index ddf7117c4..fe12fc34e 100644 --- a/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 +++ b/WDACConfig/WDACConfig Module Files/Resources/ArgumentCompleters.ps1 @@ -72,8 +72,8 @@ # Get the xml files in the current directory Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { - $XMLItem = [System.Xml.XmlDocument](Get-Content -Path $_) - $PolicyType = $XMLItem.SiPolicy.PolicyType + $XmlItem = [System.Xml.XmlDocument](Get-Content -Path $_) + $PolicyType = $XmlItem.SiPolicy.PolicyType if ($PolicyType -eq 'Base Policy') { @@ -102,8 +102,8 @@ # Get the xml files in the current directory Get-ChildItem -File | Where-Object -FilterScript { $_.extension -like '*.xml' } | ForEach-Object -Process { - $XMLItem = [System.Xml.XmlDocument](Get-Content -Path $_) - $PolicyType = $XMLItem.SiPolicy.PolicyType + $XmlItem = [System.Xml.XmlDocument](Get-Content -Path $_) + $PolicyType = $XmlItem.SiPolicy.PolicyType if ($PolicyType -eq 'Supplemental Policy') { diff --git a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 index f9bc17e81..a6bf4c7d4 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 @@ -41,7 +41,7 @@ Function Test-FilePath { } else { # The directory path is not valid - Write-Warning "The directory path '$Directory' is not valid." + Write-Warning -Message "The directory path '$Directory' is not valid." } } @@ -52,7 +52,7 @@ Function Test-FilePath { } else { # The file path is not valid - Write-Warning "The file path '$file' is not valid." + Write-Warning -Message "The file path '$file' is not valid." } } } From bf2c2e054139f62ee042db0a4de625c50beda8a6 Mon Sep 17 00:00:00 2001 From: Violet Date: Sun, 10 Dec 2023 10:47:44 -0930 Subject: [PATCH 136/178] Added missing position 0 named parameters --- .../WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 | 6 +++--- .../Core/New-KernelModeWDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index eec74b611..d1b1bc181 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -166,7 +166,7 @@ Function New-DenyWDACConfig { # Create Deny base policy for Driver files elseif ($Drivers) { - powershell.exe { + powershell.exe -Command { [System.Object[]]$DriverFilesObject = @() # loop through each user-selected folder paths foreach ($ScanLocation in $args[0]) { @@ -223,13 +223,13 @@ Function New-DenyWDACConfig { do { Get-AppxPackage -Name $PackageName Write-Debug -Message "This is the Selected package name $PackageName" - $Question = Read-Host "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit`n" + $Question = Read-Host -Prompt "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit`n" } until ( (($Question -eq 1) -or ($Question -eq 2)) ) if ($Question -eq 2) { break } - powershell.exe { + powershell.exe -Command { # Get all the packages based on the supplied name $Package = Get-AppxPackage -Name $args[0] diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index db60a0bfa..0ca63144e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -195,7 +195,7 @@ Function New-KernelModeWDACConfig { Write-Error -Message 'Invalid or nonexistent GUID in User Configs for Audit mode policy, Use the -PrepMode parameter first.' } - powershell.exe { + powershell.exe -Command { # Scan Event viewer logs for drivers $DriverFilesObj = Get-SystemDriver -Audit # Create a policy xml file from the driver files diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 9f3a59914..e579c6471 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -181,7 +181,7 @@ Function New-SupplementalWDACConfig { # Using Windows PowerShell to handle serialized data since PowerShell core throws an error # Creating the Supplemental policy file - powershell.exe { + powershell.exe -Command { $RulesWildCards = New-CIPolicyRule -FilePathRule $args[0] New-CIPolicy -MultiplePolicyFormat -FilePath ".\SupplementalPolicy $($args[1]).xml" -Rules $RulesWildCards } -args $FolderPath, $SuppPolicyName @@ -215,13 +215,13 @@ Function New-SupplementalWDACConfig { do { Get-AppxPackage -Name $PackageName Write-Debug -Message "This is the Selected package name $PackageName" - $Question = Read-Host "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit" + $Question = Read-Host -Prompt "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit" } until ( (($Question -eq 1) -or ($Question -eq 2)) ) if ($Question -eq 2) { break } - powershell.exe { + powershell.exe -Command { # Get all the packages based on the supplied name $Package = Get-AppxPackage -Name $args[0] # Get package dependencies if any From d4507a60bc4cb7969754a15581af6945e2fc525f Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 01:15:04 -0930 Subject: [PATCH 137/178] Improved function help sections --- .../Core/Confirm-WDACConfig.psm1 | 16 ++-------- .../Core/Deploy-SignedWDACConfig.psm1 | 14 ++------- .../Core/Edit-SignedWDACConfig.psm1 | 17 ++-------- .../Core/Edit-WDACConfig.psm1 | 16 ++-------- .../Core/Get-CommonWDACConfig.psm1 | 16 +--------- .../Core/Invoke-WDACSimulation.psm1 | 11 ++----- .../Core/New-DenyWDACConfig.psm1 | 16 ++-------- .../Core/New-KernelModeWDACConfig.psm1 | 14 ++------- .../Core/New-SupplementalWDACConfig.psm1 | 23 ++------------ .../Core/New-WDACConfig.psm1 | 31 ++----------------- .../Core/Remove-CommonWDACConfig.psm1 | 20 +++++------- .../Core/Remove-WDACConfig.psm1 | 30 +++++++++--------- .../Core/Set-CommonWDACConfig.psm1 | 13 -------- .../Shared/Confirm-CertCN.psm1 | 2 +- .../Shared/Move-UserModeToKernelMode.psm1 | 4 +++ .../Shared/Test-FilePath.psm1 | 5 ++- 16 files changed, 58 insertions(+), 190 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 index c1c83e040..93426b3c5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Confirm-WDACConfig.psm1 @@ -8,7 +8,7 @@ Function Confirm-WDACConfig { [Alias('S')] [Parameter(Mandatory = $false, ParameterSetName = 'Check SmartAppControl Status')][System.Management.Automation.SwitchParameter]$CheckSmartAppControlStatus, - [Parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$DummyParameter # To hide common parameters + [Parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$DummyParameter ) DynamicParam { @@ -137,40 +137,30 @@ Function Confirm-WDACConfig { .SYNOPSIS Shows the status of WDAC on the system, lists the currently deployed policies and shows the details about each of them. It can also show the status of Smart App Control. - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Confirm-WDACConfig - .DESCRIPTION Using official Microsoft methods, Show the status of WDAC (Windows Defender Application Control) on the system, list the current deployed policies and show details about each of them. - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Using official Microsoft methods, Show the status of WDAC (Windows Defender Application Control) on the system, list the current deployed policies and show details about each of them. - .PARAMETER ListActivePolicies Lists the currently deployed policies and shows details about each of them - .PARAMETER VerifyWDACStatus Shows the status of WDAC (Windows Defender Application Control) on the system - .PARAMETER CheckSmartAppControlStatus Checks the status of Smart App Control and reports the results on the console - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases - +.PARAMETER DummyParameter + To hide the common parameters .EXAMPLE Confirm-WDACConfig -ListActivePolicies -OnlyBasePolicies - .EXAMPLE Confirm-WDACConfig -ListActivePolicies -OnlySupplementalPolicies - .EXAMPLE Confirm-WDACConfig -ListActivePolicies - .INPUTS System.Management.Automation.SwitchParameter .OUTPUTS diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index ed13ee2be..1baac2d6d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -227,40 +227,32 @@ Function Deploy-SignedWDACConfig { <# .SYNOPSIS Signs and Deploys WDAC policies, accepts signed or unsigned policies and deploys them - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Deploy-SignedWDACConfig - .DESCRIPTION Using official Microsoft methods, Signs and Deploys WDAC policies, accepts signed or unsigned policies and deploys them (Windows Defender Application Control) - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Using official Microsoft methods, Signs and Deploys WDAC policies, accepts signed or unsigned policies and deploys them (Windows Defender Application Control) - .PARAMETER CertPath Path to the certificate .cer file - .PARAMETER PolicyPaths Path to the policy xml files that are going to be signed - .PARAMETER CertCN Certificate common name - .PARAMETER SignToolPath Path to the SignTool.exe - optional parameter - .PARAMETER Deploy Indicates that the cmdlet will deploy the signed policy on the current system - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases - .INPUTS System.String System.String[] + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 9c607a7a7..900a276db 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1132,56 +1132,45 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I <# .SYNOPSIS Edits Signed WDAC policies deployed on the system (Windows Defender Application Control) - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Edit-SignedWDACConfig - .DESCRIPTION Using official Microsoft methods, Edits Signed WDAC policies deployed on the system (Windows Defender Application Control) - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Using official Microsoft methods, Edits Signed WDAC policies deployed on the system (Windows Defender Application Control) - .PARAMETER AllowNewAppsAuditEvents Rebootlessly install new apps/programs when Signed policy is already deployed, use audit events to capture installation files, scan their directories for new Supplemental policy, Sign and deploy thew Supplemental policy. - .PARAMETER AllowNewApps Rebootlessly install new apps/programs when Signed policy is already deployed, scan their directories for new Supplemental policy, Sign and deploy thew Supplemental policy. - .PARAMETER MergeSupplementalPolicies Merges multiple Signed deployed supplemental policies into 1 single supplemental policy, removes the old ones, deploys the new one. System restart needed to take effect. - .PARAMETER UpdateBasePolicy It can rebootlessly change the type of the deployed signed base policy. It can update the recommended block rules and/or change policy rule options in the deployed base policy. - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases It is used by the entire Cmdlet. - .PARAMETER LogSize The log size to set for Code Integrity/Operational event logs The accepted values are between 1024 KB and 18014398509481983 KB The max range is the maximum allowed log size by Windows Event viewer - .PARAMETER CertCN Common name of the certificate used to sign the deployed Signed WDAC policy It is Used by the entire Cmdlet - .PARAMETER Level The level that determines how the selected folder will be scanned. The default value for it is FilePublisher. - .PARAMETER Fallbacks The fallback level(s) that determine how the selected folder will be scanned. The default value for it is Hash. - .INPUTS System.Int64 System.String System.String[] + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 330ed620b..d355b91db 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -942,52 +942,42 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I <# .SYNOPSIS Edits Unsigned WDAC policies deployed on the system - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Edit-WDACConfig - .DESCRIPTION Using official Microsoft methods, Edits non-signed WDAC policies deployed on the system - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Using official Microsoft methods, Edits non-signed WDAC policies deployed on the system - .PARAMETER AllowNewApps While an unsigned WDAC policy is already deployed on the system, rebootlessly turn on Audit mode in it, which will allow you to install a new app that was otherwise getting blocked. - .PARAMETER AllowNewAppsAuditEvents While an unsigned WDAC policy is already deployed on the system, rebootlessly turn on Audit mode in it, which will allow you to install a new app that was otherwise getting blocked. - .PARAMETER MergeSupplementalPolicies Merges multiple deployed supplemental policies into 1 single supplemental policy, removes the old ones, deploys the new one. System restart needed to take effect. - .PARAMETER UpdateBasePolicy It can rebootlessly change the type of the deployed base policy. It can update the recommended block rules and/or change policy rule options in the deployed base policy. - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases It is used by the entire Cmdlet. - .PARAMETER Level The level that determines how the selected folder will be scanned. The default value for it is FilePublisher. - .PARAMETER Fallbacks The fallback level(s) that determine how the selected folder will be scanned. The default value for it is Hash. - .PARAMETER LogSize The log size to set for Code Integrity/Operational event logs The accepted values are between 1024 KB and 18014398509481983 KB The max range is the maximum allowed log size by Windows Event viewer - .INPUTS System.Int64 System.String[] System.String + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index ea6c3bf30..ef08e8eb8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -6,7 +6,7 @@ Function Get-CommonWDACConfig { [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignToolPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$UnsignedPolicyPath, - [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, # DontShow prevents common parameters from being displayed too + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$Open, [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck @@ -78,46 +78,32 @@ Function Get-CommonWDACConfig { <# .SYNOPSIS Query and Read common values for parameters used by WDACConfig module - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Get-CommonWDACConfig - .DESCRIPTION Reads and gets the values from the User Config Json file, used by the module internally and also to display the values on the console for the user - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module, WDACConfig module - .FUNCTIONALITY Reads and gets the values from the User Config Json file, used by the module internally and also to display the values on the console for the user - .PARAMETER SignedPolicyPath Shows the path to a Signed WDAC xml policy - .PARAMETER UnsignedPolicyPath Shows the path to an Unsigned WDAC xml policy - .PARAMETER CertCN Shows the certificate common name - .PARAMETER SignToolPath Shows the path to the SignTool.exe - .PARAMETER CertPath Shows the path to a .cer certificate file - .PARAMETER Open Opens the User Configuration file with the default app assigned to open Json files - .PARAMETER StrictKernelPolicyGUID Shows the GUID of the Strict Kernel mode policy - .PARAMETER StrictKernelNoFlightRootsPolicyGUID Shows the GUID of the Strict Kernel no Flights root mode policy - .INPUTS System.Management.Automation.SwitchParameter - .OUTPUTS System.Object[] #> diff --git a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 index 7b31d6e10..bb69678e5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Invoke-WDACSimulation.psm1 @@ -282,35 +282,28 @@ Function Invoke-WDACSimulation { <# .SYNOPSIS Simulates the deployment of the WDAC policy. - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Invoke-WDACSimulation - .DESCRIPTION Simulates the deployment of the WDAC policy by analyzing a folder and checking which of the files in the folder are allowed by a user selected policy xml file - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Simulates the deployment of the WDAC policy - .PARAMETER FolderPath Provide path to a folder where you want WDAC simulation to take place - .PARAMETER XmlFilePath Provide path to a policy xml file that you want the cmdlet to simulate its deployment and running files against it - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases It is used by the entire Cmdlet. - .INPUTS System.IO.FileInfo System.IO.DirectoryInfo + System.Management.Automation.SwitchParameter .OUTPUTS System.Object[] - + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index d1b1bc181..e8c96d54d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -274,49 +274,39 @@ Function New-DenyWDACConfig { <# .SYNOPSIS Creates Deny base policies (Windows Defender Application Control) - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/New-DenyWDACConfig - .DESCRIPTION Using official Microsoft methods to create Deny base policies (Windows Defender Application Control) - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Using official Microsoft methods, Removes Signed and unsigned deployed WDAC policies (Windows Defender Application Control) - .PARAMETER PolicyName It's used by the entire Cmdlet. It is the name of the base policy that will be created. - .PARAMETER Normal Creates a Deny standalone base policy by scanning a directory for files. The base policy created by this parameter can be deployed side by side any other base/supplemental policy. - .PARAMETER Level The level that determines how the selected folder will be scanned. The default value for it is FilePublisher. - .PARAMETER Fallbacks The fallback level(s) that determine how the selected folder will be scanned. The default value for it is Hash. - .PARAMETER Deploy It's used by the entire Cmdlet. Indicates that the created Base deny policy will be deployed on the system. - .PARAMETER Drivers Creates a Deny standalone base policy for drivers only by scanning a directory for driver files. The base policy created by this parameter can be deployed side by side any other base/supplemental policy. - .PARAMETER InstalledAppXPackages Creates a Deny standalone base policy for an installed App based on Appx package family names - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases It's used by the entire Cmdlet. - .INPUTS System.String[] System.String + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 index 0ca63144e..cb9511400 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-KernelModeWDACConfig.psm1 @@ -352,41 +352,31 @@ Function New-KernelModeWDACConfig { <# .SYNOPSIS Creates Kernel only mode WDAC policy capable of protecting against BYOVD attacks category - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/New%E2%80%90KernelModeWDACConfig - .DESCRIPTION Using official Microsoft methods, configure and use Windows Defender Application Control - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Creates Kernel only mode WDAC policy capable of protecting against BYOVD attacks category - .PARAMETER Default Creates the strict Kernel mode WDAC policy based off of the default Windows WDAC example policy. - .PARAMETER NoFlightRoots Creates the strict Kernel mode WDAC policy based off of the default Windows WDAC example policy, doesn't allow flighting/insider builds. - .PARAMETER PrepMode Deploys the Kernel mode WDAC policy in Audit mode so that you can restart your system and start capturing any blocked drivers to be automatically allowed. - .PARAMETER AuditAndEnforce Deploys the final Kernel mode WDAC policy in Enforced mode - .PARAMETER EVSigners Adds EVSigners policy rule option to the deployed policy. Applicable for both Audit and Enforced modes. Drivers not EV (Extended Validation) signed cannot run nor can they be allowed in a Supplemental policy. - .PARAMETER Deploy Deploys the selected policy type instead of just creating it - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases - .INPUTS System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index e579c6471..65e086167 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -270,72 +270,55 @@ Function New-SupplementalWDACConfig { <# .SYNOPSIS Automate a lot of tasks related to WDAC (Windows Defender Application Control) - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/New-SupplementalWDACConfig - .DESCRIPTION Using official Microsoft methods, configure and use Windows Defender Application Control - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Automate various tasks related to Windows Defender Application Control (WDAC) - .PARAMETER Normal Make a Supplemental policy by scanning a directory, you can optionally use other parameters too to fine tune the scan process - .PARAMETER PathWildCards Make a Supplemental policy by scanning a directory and creating a wildcard FilePath rules for all of the files inside that directory, recursively - .PARAMETER InstalledAppXPackages Make a Supplemental policy based on the Package Family Name of an installed Windows app (Appx) - .PARAMETER PackageName Enter the package name of an installed app. Supports wildcard * character. e.g., *Edge* or "*Microsoft*". - .PARAMETER ScanLocation The directory or drive that you want to scan for files that will be allowed to run by the Supplemental policy. - .PARAMETER FolderPath Path of a folder that you want to allow using wildcards *. - .PARAMETER SuppPolicyName Add a descriptive name for the Supplemental policy. Accepts only alphanumeric and space characters. It is used by the entire Cmdlet. - .PARAMETER PolicyPath Browse for the xml file of the Base policy this Supplemental policy is going to expand. Supports tab completion by showing only .xml files with Base Policy Type. It is used by the entire Cmdlet. - .PARAMETER Deploy Indicates that the module will automatically deploy the Supplemental policy after creation. It is used by the entire Cmdlet. - .PARAMETER SpecificFileNameLevel You can choose one of the following options: "OriginalFileName", "InternalName", "FileDescription", "ProductName", "PackageFamilyName", "FilePath" - .PARAMETER NoUserPEs By default the module includes user PEs in the scan, but when you use this switch parameter, they won't be included. - .PARAMETER NoScript Refer to this page for more info: https://learn.microsoft.com/en-us/powershell/module/configci/new-cipolicy#-noscript - .PARAMETER Level The level that determines how the selected folder will be scanned. The default value for it is FilePublisher. - .PARAMETER Fallbacks The fallback level(s) that determine how the selected folder will be scanned. The default value for it is Hash. - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases - .INPUTS System.String[] System.String + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 410da869f..358625c44 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -912,93 +912,68 @@ Function New-WDACConfig { <# .SYNOPSIS Automate a lot of tasks related to WDAC (Windows Defender Application Control) - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/New-WDACConfig - .DESCRIPTION Using official Microsoft methods, configure and use Windows Defender Application Control - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Automate various tasks related to Windows Defender Application Control (WDAC) - .PARAMETER GetBlockRules Create Microsoft recommended block rules xml policy and remove the allow rules - .PARAMETER GetDriverBlockRules Create Microsoft recommended driver block rules xml policy and remove the allow rules - .PARAMETER MakeAllowMSFTWithBlockRules Make WDAC policy by merging AllowMicrosoft policy with the recommended block rules - .PARAMETER SetAutoUpdateDriverBlockRules Make a Scheduled Task that automatically runs every 7 days to download the newest Microsoft Recommended driver block rules - .PARAMETER PrepMSFTOnlyAudit Prepare the system for Audit mode using AllowMicrosoft default policy - .PARAMETER PrepDefaultWindowsAudit Prepare the system for Audit mode using DefaultWindows policy - .PARAMETER MakePolicyFromAuditLogs Make a WDAC Policy from Audit event logs that also covers files no longer on disk - .PARAMETER MakeLightPolicy Make a WDAC Policy with ISG for Lightly Managed system - .PARAMETER MakeDefaultWindowsWithBlockRules Make a WDAC policy by merging DefaultWindows policy with the recommended block rules - .PARAMETER BasePolicyType Select the Base Policy Type - .PARAMETER Deploy Deploys the policy that is being created - .PARAMETER IncludeSignTool Indicates that the Default Windows policy that is being created must include Allow rules for SignTool.exe - This parameter must be used when you intend to Sign and Deploy the Default Windows policy. - .PARAMETER SignToolPath Path to the SignTool.exe file - Optional - .PARAMETER TestMode Indicates that the created/deployed policy will have Enabled:Boot Audit on Failure and Enabled:Advanced Boot Options Menu policy rule options - .PARAMETER RequireEVSigners Indicates that the created/deployed policy will have Require EV Signers policy rule option. - .PARAMETER NoDeletedFiles Indicates that files that were run during program installations but then were deleted and are no longer on the disk, won't be added to the supplemental policy. This can mean the programs you installed will be allowed to run but installation/reinstallation might not be allowed once the policies are deployed. - .PARAMETER SpecificFileNameLevel You can choose one of the following options: "OriginalFileName", "InternalName", "FileDescription", "ProductName", "PackageFamilyName", "FilePath". More info available on Microsoft Learn - .PARAMETER NoUserPEs By default, the module includes user PEs in the scan. When you use this switch parameter, they won't be included. - .PARAMETER NoScript Won't scan script files - .PARAMETER Level Offers the same official Levels for scanning of event logs. If no level is specified the default, which is set to FilePublisher in this module, will be used. - .PARAMETER Fallbacks Offers the same official Fallbacks for scanning of event logs. If no fallbacks are specified the default, which is set to Hash in this module, will be used. - .PARAMETER LogSize Specifies the log size for Microsoft-Windows-CodeIntegrity/Operational events. The values must be in the form of . e.g., 2MB, 10MB, 1GB, 1TB. The minimum accepted value is 1MB which is the default. The maximum range is the maximum allowed log size by Windows Event viewer - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases - .INPUTS System.Int64 System.String[] System.String + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index cea97fff9..835869c15 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -8,7 +8,7 @@ Function Remove-CommonWDACConfig { [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SignedPolicyPath, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelPolicyGUID, [parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$StrictKernelNoFlightRootsPolicyGUID, - [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck # DontShow prevents common parameters from being displayed too + [parameter(Mandatory = $false, DontShow = $true)][System.Management.Automation.SwitchParameter]$LastUpdateCheck ) begin { # Importing the $PSDefaultParameterValues to the current session, prior to everything else @@ -132,39 +132,33 @@ Function Remove-CommonWDACConfig { <# .SYNOPSIS Removes common values for parameters used by WDACConfig module - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Remove-CommonWDACConfig - .DESCRIPTION Removes common values for parameters used by WDACConfig module from the User Configurations JSON file. If you don't use it with any parameters, then all User Configs will be deleted. - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module, WDACConfig module - .FUNCTIONALITY Removes common values for parameters used by WDACConfig module from the User Configurations JSON file. If you don't use it with any parameters, then all User Configs will be deleted. - .PARAMETER SignedPolicyPath Removes the SignedPolicyPath from User Configs - .PARAMETER UnsignedPolicyPath Removes the UnsignedPolicyPath from User Configs - .PARAMETER CertCN Removes the CertCN from User Configs - .PARAMETER SignToolPath Removes the SignToolPath from User Configs - .PARAMETER CertPath Removes the CertPath from User Configs - .PARAMETER StrictKernelPolicyGUID Removes the StrictKernelPolicyGUID from User Configs - .PARAMETER StrictKernelNoFlightRootsPolicyGUID Removes the StrictKernelNoFlightRootsPolicyGUID from User Configs - +.PARAMETER LastUpdateCheck + Using DontShow for this parameter which prevents common parameters from being displayed too +.INPUTS + System.Management.Automation.SwitchParameter +.OUTPUTS + System.String #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 436102d78..a9de861d3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -33,8 +33,6 @@ Function Remove-WDACConfig { [parameter(Mandatory = $false, ParameterSetName = 'Signed Base', ValueFromPipelineByPropertyName = $true)] [System.String]$CertCN, - # https://stackoverflow.com/questions/76143006/how-to-prevent-powershell-validateset-argument-completer-from-suggesting-the-sam/76143269 - # https://stackoverflow.com/questions/76267235/powershell-how-to-cross-reference-parameters-between-2-argument-completers [ArgumentCompleter({ # Define the parameters that this script block will accept. param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) @@ -74,9 +72,7 @@ Function Remove-WDACConfig { })] [Parameter(Mandatory = $false, ParameterSetName = 'Unsigned Or Supplemental')] [System.String[]]$PolicyNames, - - # https://stackoverflow.com/questions/76143006/how-to-prevent-powershell-validateset-argument-completer-from-suggesting-the-sam/76143269 - # https://stackoverflow.com/questions/76267235/powershell-how-to-cross-reference-parameters-between-2-argument-completers + [ArgumentCompleter({ param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) @@ -361,32 +357,38 @@ Function Remove-WDACConfig { <# .SYNOPSIS Removes Signed and unsigned deployed WDAC policies (Windows Defender Application Control) - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Remove-WDACConfig - .DESCRIPTION Using official Microsoft methods, Removes Signed and unsigned deployed WDAC policies (Windows Defender Application Control) - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module - .FUNCTIONALITY Using official Microsoft methods, Removes Signed and unsigned deployed WDAC policies (Windows Defender Application Control) - +.PARAMETER PolicyNames + Names of the deployed policies to be removed + https://stackoverflow.com/questions/76143006/how-to-prevent-powershell-validateset-argument-completer-from-suggesting-the-sam/76143269 + https://stackoverflow.com/questions/76267235/powershell-how-to-cross-reference-parameters-between-2-argument-completers +.PARAMETER PolicyIDs + IDs of the deployed policies to be removed + https://stackoverflow.com/questions/76143006/how-to-prevent-powershell-validateset-argument-completer-from-suggesting-the-sam/76143269 + https://stackoverflow.com/questions/76267235/powershell-how-to-cross-reference-parameters-between-2-argument-completers .PARAMETER SignedBase Remove Signed Base WDAC Policies - +.PARAMETER PolicyPaths + Path to the XML policy file(s) of the deployed policies to be removed +.PARAMETER CertCN + Certificate common name to be used to sign the policy file(s) that are going to be removed in unsigned mode +.PARAMETER SignToolPath + Path to the SignTool.exe .PARAMETER UnsignedOrSupplemental Remove Unsigned deployed WDAC policies as well as Signed deployed Supplemental WDAC policies - .PARAMETER SkipVersionCheck Can be used with any parameter to bypass the online version check - only to be used in rare cases - .INPUTS System.String System.String[] - + System.Management.Automation.SwitchParameter .OUTPUTS System.String #> diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index e973503ca..9c609c64e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -188,45 +188,32 @@ Function Set-CommonWDACConfig { <# .SYNOPSIS Add/Change common values for parameters used by WDACConfig module - .LINK https://github.com/HotCakeX/Harden-Windows-Security/wiki/Set-CommonWDACConfig - .DESCRIPTION Add/Change common values for parameters used by WDACConfig module so that you won't have to provide values for those repetitive parameters each time you need to use the WDACConfig module cmdlets. - .COMPONENT Windows Defender Application Control, ConfigCI PowerShell module, WDACConfig module - .FUNCTIONALITY Add/Change common values for parameters used by WDACConfig module so that you won't have to provide values for those repetitive parameters each time you need to use the WDACConfig module cmdlets. - .PARAMETER SignedPolicyPath Path to a Signed WDAC xml policy - .PARAMETER UnsignedPolicyPath Path to an Unsigned WDAC xml policy - .PARAMETER CertCN Certificate common name - .PARAMETER SignToolPath Path to the SignTool.exe - .PARAMETER CertPath Path to a .cer certificate file - .PARAMETER StrictKernelPolicyGUID GUID of the Strict Kernel mode policy - .PARAMETER StrictKernelNoFlightRootsPolicyGUID GUID of the Strict Kernel no Flights root mode policy - .INPUTS System.DateTime System.Guid System.String - .OUTPUTS System.Object[] #> diff --git a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 index 7d64d6435..139514698 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Confirm-CertCN.psm1 @@ -1,7 +1,7 @@ Function Confirm-CertCN { <# .SYNOPSIS - Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json + Function to check Certificate Common name - used mostly to validate values in UserConfigurations.json .INPUTS System.String .OUTPUTS diff --git a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 index 6acbc2c63..b822db967 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Move-UserModeToKernelMode.psm1 @@ -3,6 +3,10 @@ Function Move-UserModeToKernelMode { .SYNOPSIS Moves all User mode AllowedSigners in the User mode signing scenario to the Kernel mode signing scenario and then deletes the entire User mode signing scenario block + .INPUTS + System.String + .OUTPUTS + System.Void #> [CmdletBinding()] param( diff --git a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 index a6bf4c7d4..6382d2a5d 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Test-FilePath.psm1 @@ -3,7 +3,10 @@ Function Test-FilePath { .SYNOPSIS function that takes 2 arrays, one contains file paths and the other contains folder paths. It checks them and shows file paths that are not in any of the folder paths. Performs this check recursively too so works if the filepath is in a sub-directory of a folder path - + .INPUTS + System.String[] + .OUTPUTS + System.String[] #> [CmdletBinding()] param ( From c61f9e869cd27b97b6d924e46697f70ac53c3573 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 01:17:33 -0930 Subject: [PATCH 138/178] Improved position 0 named parameters --- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- .../Shared/Get-AuditEventLogsProcessing.psm1 | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 900a276db..119c4b11a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -850,7 +850,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if (Test-Path -Path $_.'File Name') { # Check if the file exits in the $ExesWithNoHash array if ($ExesWithNoHash -contains $_.'File Name') { - $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + $_ | Select-Object -Property FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index d355b91db..7b87d363d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -729,7 +729,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if (Test-Path -Path $_.'File Name') { # Check if the file exits in the $ExesWithNoHash array if ($ExesWithNoHash -contains $_.'File Name') { - $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + $_ | Select-Object -Property FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 358625c44..da38097c8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -719,7 +719,7 @@ Function New-WDACConfig { $_.'File Name' = $_.'File Name' -replace $pattern, $usablePath } if (-NOT (Test-Path -Path $_.'File Name')) { - $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + $_ | Select-Object -Property FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } } } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 index 251be4431..1bd7be292 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-AuditEventLogsProcessing.psm1 @@ -56,7 +56,7 @@ Function Get-AuditEventLogsProcessing { # If the file is not currently on the disk, extract its hashes from event log else { - $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' + $AuditEventLogsProcessingResults.DeletedFileHashes += $_ | Select-Object -Property FileVersion, 'File Name', PolicyGUID, 'SHA256 Hash', 'SHA256 Flat Hash', 'SHA1 Hash', 'SHA1 Flat Hash' } } } From e3583d9662dfc3947be201dd588a704afed5de33 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 02:01:48 -0930 Subject: [PATCH 139/178] Changed region comment texts for better visibility --- .../Core/Deploy-SignedWDACConfig.psm1 | 8 ++-- .../Core/Edit-SignedWDACConfig.psm1 | 45 ++++++++++--------- .../Core/Edit-WDACConfig.psm1 | 40 ++++++++--------- .../Core/New-SupplementalWDACConfig.psm1 | 4 +- .../Core/New-WDACConfig.psm1 | 12 ++--- .../Core/Remove-WDACConfig.psm1 | 4 +- 6 files changed, 58 insertions(+), 55 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 1baac2d6d..906bfe160 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -51,7 +51,7 @@ Function Deploy-SignedWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - #region User-Configurations-Processing-Validation + # Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertPath -or !$CertCN) { # Read User configuration file if it exists @@ -108,7 +108,7 @@ Function Deploy-SignedWDACConfig { throw 'CertCN parameter cannot be empty and no valid configuration was found for it.' } } - #endregion User-Configurations-Processing-Validation + # Endregion User-Configurations-Processing-Validation } process { @@ -171,7 +171,7 @@ Function Deploy-SignedWDACConfig { Write-Output -InputObject "PolicyGUID = $PolicyID`n" Remove-Item -Path ".\$PolicyID.cip" -Force - #region Detecting Strict Kernel mode policy and removing it from User Configs + # Region Detecting Strict Kernel mode policy and removing it from User Configs if ('Enabled:UMCI' -notin $PolicyRuleOptions) { [System.String]$StrictKernelPolicyGUID = Get-CommonWDACConfig -StrictKernelPolicyGUID @@ -193,7 +193,7 @@ Function Deploy-SignedWDACConfig { } } } - #endregion Detecting Strict Kernel mode policy and removing it from User Configs + # Endregion Detecting Strict Kernel mode policy and removing it from User Configs # Show the question only for base policies. Don't show it for Strict kernel mode policies if (($PolicyType -ne 'Supplemental Policy') -and ($PolicyName -notlike '*Strict Kernel*')) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 119c4b11a..b79076e8c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -143,7 +143,7 @@ Function Edit-SignedWDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - #region User-Configurations-Processing-Validation + # Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPaths -or !$SignToolPath -or !$CertPath -or !$CertCN) { # Read User configuration file if it exists @@ -219,7 +219,7 @@ Function Edit-SignedWDACConfig { } } } - #endregion User-Configurations-Processing-Validation + # Endregion User-Configurations-Processing-Validation # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -344,7 +344,7 @@ Function Edit-SignedWDACConfig { Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force - #Region Snap-Back-Guarantee + # Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' # Defining the registry path for RunOnce key @@ -368,11 +368,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - #Endregion Snap-Back-Guarantee + # Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - #Region User-Interaction + # Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -393,7 +393,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - #Endregion User-Interaction + # Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -464,7 +464,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the ProgramDir_ScanResults* xml files' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - #Region Supplemental-policy-processing-and-deployment + # Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' Write-Verbose -Message 'Getting the path of the Supplemental policy' @@ -523,7 +523,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - #Endregion Supplemental-policy-processing-and-deployment + # Endregion Supplemental-policy-processing-and-deployment } } @@ -609,7 +609,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force - #Region Snap-Back-Guarantee + # Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' # Defining the registry path for RunOnce key @@ -633,11 +633,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - #Endregion Snap-Back-Guarantee + # Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - #Region User-Interaction + # Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -658,7 +658,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - #Endregion User-Interaction + # Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -671,7 +671,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_.FullName } - #Region EventCapturing + # Region EventCapturing Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan @@ -760,9 +760,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } - #Endregion EventCapturing + # Endregion EventCapturing - #Region Process-Program-Folders-From-User-input + # Region Process-Program-Folders-From-User-input Write-Verbose -Message 'Scanning each of the folder paths that user selected' for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -793,9 +793,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } - #Endregion Process-Program-Folders-From-User-input + # Endregion Process-Program-Folders-From-User-input - #region Kernel-protected-files-automatic-detection-and-allow-rule-creation + # Region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them @@ -877,7 +877,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } - #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation + # Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } @@ -908,7 +908,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - #Region Supplemental-policy-processing-and-deployment + # Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" @@ -967,13 +967,14 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - #Endregion Supplemental-policy-processing-and-deployment + # Endregion Supplemental-policy-processing-and-deployment } } if ($MergeSupplementalPolicies) { foreach ($PolicyPath in $PolicyPaths) { - ############ Input policy verification prior to doing anything ############ + + # Region Input-policy-verification foreach ($SuppPolicyPath in $SuppPolicyPaths) { $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID @@ -988,6 +989,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Error -Message "The Selected Supplemental XML file with GUID $SupplementalPolicyID isn't deployed on the system." } } + # Endregion Input-policy-verification + # Perform the merge Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 7b87d363d..764cbfcdb 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -124,7 +124,7 @@ Function Edit-WDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - #region User-Configurations-Processing-Validation + # Region User-Configurations-Processing-Validation # make sure the ParameterSet being used has PolicyPaths parameter - Then enforces "mandatory" attribute for the parameter if ($PSCmdlet.ParameterSetName -in 'Allow New Apps Audit Events', 'Allow New Apps', 'Merge Supplemental Policies') { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user @@ -157,7 +157,7 @@ Function Edit-WDACConfig { } } } - #endregion User-Configurations-Processing-Validation + # Endregion User-Configurations-Processing-Validation # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { @@ -250,7 +250,7 @@ Function Edit-WDACConfig { # Create CIP for Enforced Mode ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - #Region Snap-Back-Guarantee + # Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' <# @@ -295,11 +295,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - #Endregion Snap-Back-Guarantee + # Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - #Region User-Interaction + # Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -320,7 +320,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - #Endregion User-Interaction + # Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -395,7 +395,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the ProgramDir_ScanResults* xml files' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - #Region Supplemental-policy-processing-and-deployment + # Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' Write-Verbose -Message 'Getting the path of the Supplemental policy' @@ -432,7 +432,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the policy xml file in Temp folder we created earlier' Remove-Item -Path $PolicyPath -Force - #Endregion Supplemental-policy-processing-and-deployment + # Endregion Supplemental-policy-processing-and-deployment } } @@ -488,7 +488,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Create CIP for Enforced Mode ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - #Region Snap-Back-Guarantee + # Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' # Defining the registry path for RunOnce key @@ -512,11 +512,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - #Endregion Snap-Back-Guarantee + # Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - #Region User-Interaction + # Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -537,7 +537,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - #Endregion User-Interaction + # Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -550,7 +550,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_.FullName } - #Region EventCapturing + # Region EventCapturing Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan @@ -639,9 +639,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } - #Endregion EventCapturing + # Endregion EventCapturing - #Region Process-Program-Folders-From-User-input + # Region Process-Program-Folders-From-User-input Write-Verbose -Message 'Scanning each of the folder paths that user selected' for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -672,9 +672,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } - #Endregion Process-Program-Folders-From-User-input + # Endregion Process-Program-Folders-From-User-input - #region Kernel-protected-files-automatic-detection-and-allow-rule-creation + # Region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them @@ -756,7 +756,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } - #endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation + # Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } @@ -787,7 +787,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - #Region Supplemental-policy-processing-and-deployment + # Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" @@ -822,7 +822,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - #Endregion Supplemental-policy-processing-and-deployment + # Endregion Supplemental-policy-processing-and-deployment } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 65e086167..d74bd77fa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -90,7 +90,7 @@ Function New-SupplementalWDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - #region User-Configurations-Processing-Validation + # Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPath) { # Read User configuration file if it exists @@ -120,7 +120,7 @@ Function New-SupplementalWDACConfig { throw 'PolicyPath parameter cannot be empty and no valid configuration was found for UnsignedPolicyPath.' } } - #endregion User-Configurations-Processing-Validation + # Endregion User-Configurations-Processing-Validation # Ensure when user selects the -Deploy parameter, the base policy is not signed if ($Deploy) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index da38097c8..37fd4d248 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -98,7 +98,7 @@ Function New-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force - #region User-Configurations-Processing-Validation + # Region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path if ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { # Read User configuration file if it exists @@ -121,7 +121,7 @@ Function New-WDACConfig { elseif ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } - #endregion User-Configurations-Processing-Validation + # Endregion User-Configurations-Processing-Validation # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -645,7 +645,7 @@ Function New-WDACConfig { New-Item -Type Directory -Path "$home\WDAC" -Force | Out-Null Set-Location "$home\WDAC" - #Region Base-Policy-Processing + # Region Base-Policy-Processing switch ($BasePolicyType) { 'Allow Microsoft Base' { Write-Verbose -Message 'Creating Allow Microsoft Base policy' @@ -674,9 +674,9 @@ Function New-WDACConfig { Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option because RequireEVSigners parameter was used' Set-RuleOption -FilePath $BasePolicy -Option 8 } - #Endregion Base-Policy-Processing + # Endregion Base-Policy-Processing - #Region Supplemental-Policy-Processing + # Region Supplemental-Policy-Processing # Produce a policy xml file from event viewer logs Write-ColorfulText -Color Lavender -InputText 'Scanning Windows Event logs and creating a policy file, please wait...' @@ -764,7 +764,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Converting SupplementalPolicy.xml policy to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null - #Endregion Supplemental-Policy-Processing + # Endregion Supplemental-Policy-Processing Write-Output -InputObject "BasePolicyFile = $BasePolicy" Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index a9de861d3..f69af2e89 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -128,7 +128,7 @@ Function Remove-WDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - #region User-Configurations-Processing-Validation + # Region User-Configurations-Processing-Validation Write-Verbose -Message 'Validating and processing user configurations' @@ -173,7 +173,7 @@ Function Remove-WDACConfig { } } } - #endregion User-Configurations-Processing-Validation + # Endregion User-Configurations-Processing-Validation # ValidateSet for Policy names Class PolicyNamezx : System.Management.Automation.IValidateSetValuesGenerator { From e189dbce868d81cf50b59a620545834b45a0a947 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 02:11:11 -0930 Subject: [PATCH 140/178] Reverted region keyword spacing and added verbose Added verbose messages to the Edit-SignedWDACConfig cmdlet for the MergeSupplementalPolicies parameter Also reverted the change of putting a space between # and Region/Endregion --- .../Core/Deploy-SignedWDACConfig.psm1 | 8 +-- .../Core/Edit-SignedWDACConfig.psm1 | 63 +++++++++++-------- .../Core/Edit-WDACConfig.psm1 | 40 ++++++------ .../Core/New-SupplementalWDACConfig.psm1 | 4 +- .../Core/New-WDACConfig.psm1 | 12 ++-- .../Core/Remove-WDACConfig.psm1 | 4 +- 6 files changed, 70 insertions(+), 61 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 906bfe160..66ffb40c8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -51,7 +51,7 @@ Function Deploy-SignedWDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - # Region User-Configurations-Processing-Validation + #Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertPath -or !$CertCN) { # Read User configuration file if it exists @@ -108,7 +108,7 @@ Function Deploy-SignedWDACConfig { throw 'CertCN parameter cannot be empty and no valid configuration was found for it.' } } - # Endregion User-Configurations-Processing-Validation + #Endregion User-Configurations-Processing-Validation } process { @@ -171,7 +171,7 @@ Function Deploy-SignedWDACConfig { Write-Output -InputObject "PolicyGUID = $PolicyID`n" Remove-Item -Path ".\$PolicyID.cip" -Force - # Region Detecting Strict Kernel mode policy and removing it from User Configs + #Region Detecting Strict Kernel mode policy and removing it from User Configs if ('Enabled:UMCI' -notin $PolicyRuleOptions) { [System.String]$StrictKernelPolicyGUID = Get-CommonWDACConfig -StrictKernelPolicyGUID @@ -193,7 +193,7 @@ Function Deploy-SignedWDACConfig { } } } - # Endregion Detecting Strict Kernel mode policy and removing it from User Configs + #Endregion Detecting Strict Kernel mode policy and removing it from User Configs # Show the question only for base policies. Don't show it for Strict kernel mode policies if (($PolicyType -ne 'Supplemental Policy') -and ($PolicyName -notlike '*Strict Kernel*')) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index b79076e8c..94da388e0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -143,7 +143,7 @@ Function Edit-SignedWDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - # Region User-Configurations-Processing-Validation + #Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPaths -or !$SignToolPath -or !$CertPath -or !$CertCN) { # Read User configuration file if it exists @@ -219,7 +219,7 @@ Function Edit-SignedWDACConfig { } } } - # Endregion User-Configurations-Processing-Validation + #Endregion User-Configurations-Processing-Validation # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -344,7 +344,7 @@ Function Edit-SignedWDACConfig { Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force - # Region Snap-Back-Guarantee + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' # Defining the registry path for RunOnce key @@ -368,11 +368,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - # Endregion Snap-Back-Guarantee + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - # Region User-Interaction + #Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -393,7 +393,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - # Endregion User-Interaction + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -464,7 +464,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the ProgramDir_ScanResults* xml files' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - # Region Supplemental-policy-processing-and-deployment + #Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' Write-Verbose -Message 'Getting the path of the Supplemental policy' @@ -523,7 +523,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - # Endregion Supplemental-policy-processing-and-deployment + #Endregion Supplemental-policy-processing-and-deployment } } @@ -609,7 +609,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Rename-Item -Path '.\EnforcedMode.cip.p7' -NewName '.\EnforcedMode.cip' -Force Rename-Item -Path '.\AuditMode.cip.p7' -NewName '.\AuditMode.cip' -Force - # Region Snap-Back-Guarantee + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' # Defining the registry path for RunOnce key @@ -633,11 +633,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - # Endregion Snap-Back-Guarantee + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - # Region User-Interaction + #Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -658,7 +658,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - # Endregion User-Interaction + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -671,7 +671,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_.FullName } - # Region EventCapturing + #Region EventCapturing Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan @@ -760,9 +760,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } - # Endregion EventCapturing + #Endregion EventCapturing - # Region Process-Program-Folders-From-User-input + #Region Process-Program-Folders-From-User-input Write-Verbose -Message 'Scanning each of the folder paths that user selected' for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -793,9 +793,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } - # Endregion Process-Program-Folders-From-User-input + #Endregion Process-Program-Folders-From-User-input - # Region Kernel-protected-files-automatic-detection-and-allow-rule-creation + #Region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them @@ -877,7 +877,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } - # Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation + #Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } @@ -908,7 +908,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - # Region Supplemental-policy-processing-and-deployment + #Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" @@ -967,29 +967,38 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - # Endregion Supplemental-policy-processing-and-deployment + #Endregion Supplemental-policy-processing-and-deployment } } if ($MergeSupplementalPolicies) { foreach ($PolicyPath in $PolicyPaths) { - # Region Input-policy-verification + #Region Input-policy-verification + Write-Verbose -Message 'Verifying the input policy files' foreach ($SuppPolicyPath in $SuppPolicyPaths) { + + Write-Verbose -Message "Getting policy ID and type of: $SuppPolicyPath" $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) - $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID - $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + [System.String]$SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType + + Write-Verbose -Message 'Getting the IDs of the currently deployed policies on the system' + [System.String[]]$DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies + Write-Verbose -Message 'Checking the type of the policy' if ($SupplementalPolicyType -ne 'Supplemental Policy') { - Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." + Throw "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." } + # Check to make sure the user selected Supplemental policy XML files are deployed on the system + Write-Verbose -Message 'Checking the deployment status of the policy' if ($DeployedPoliciesIDs -notcontains $SupplementalPolicyID) { - Write-Error -Message "The Selected Supplemental XML file with GUID $SupplementalPolicyID isn't deployed on the system." + Throw "The Selected Supplemental XML file with GUID $SupplementalPolicyID isn't deployed on the system." } } - # Endregion Input-policy-verification + #Endregion Input-policy-verification # Perform the merge Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 764cbfcdb..550727190 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -124,7 +124,7 @@ Function Edit-WDACConfig { # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - # Region User-Configurations-Processing-Validation + #Region User-Configurations-Processing-Validation # make sure the ParameterSet being used has PolicyPaths parameter - Then enforces "mandatory" attribute for the parameter if ($PSCmdlet.ParameterSetName -in 'Allow New Apps Audit Events', 'Allow New Apps', 'Merge Supplemental Policies') { # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user @@ -157,7 +157,7 @@ Function Edit-WDACConfig { } } } - # Endregion User-Configurations-Processing-Validation + #Endregion User-Configurations-Processing-Validation # argument tab auto-completion and ValidateSet for Policy names Class BasePolicyNamez : System.Management.Automation.IValidateSetValuesGenerator { @@ -250,7 +250,7 @@ Function Edit-WDACConfig { # Create CIP for Enforced Mode ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - # Region Snap-Back-Guarantee + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' <# @@ -295,11 +295,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - # Endregion Snap-Back-Guarantee + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - # Region User-Interaction + #Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -320,7 +320,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - # Endregion User-Interaction + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -395,7 +395,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the ProgramDir_ScanResults* xml files' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force - # Region Supplemental-policy-processing-and-deployment + #Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' Write-Verbose -Message 'Getting the path of the Supplemental policy' @@ -432,7 +432,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the policy xml file in Temp folder we created earlier' Remove-Item -Path $PolicyPath -Force - # Endregion Supplemental-policy-processing-and-deployment + #Endregion Supplemental-policy-processing-and-deployment } } @@ -488,7 +488,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Create CIP for Enforced Mode ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath '.\EnforcedMode.cip' | Out-Null - # Region Snap-Back-Guarantee + #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' # Defining the registry path for RunOnce key @@ -512,11 +512,11 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force - # Endregion Snap-Back-Guarantee + #Endregion Snap-Back-Guarantee # A Try-Catch-Finally block so that if any errors occur, the Base policy will be Re-deployed in enforced mode Try { - # Region User-Interaction + #Region User-Interaction Write-ColorfulText -Color Pink -InputText 'Audit mode deployed, start installing your programs now' Write-ColorfulText -Color HotPink -InputText 'When you have finished installing programs, Press Enter to start selecting program directories to scan' Pause @@ -537,7 +537,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Else { break } } while ($true) - # Endregion User-Interaction + #Endregion User-Interaction # Make sure User browsed for at least 1 directory # Exit the operation if user didn't select any folder paths @@ -550,7 +550,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow $ProgramsPaths | ForEach-Object -Process { $_.FullName } - # Region EventCapturing + #Region EventCapturing Write-Host -Object 'Scanning Windows Event logs and creating a policy file, please wait...' -ForegroundColor Cyan @@ -639,9 +639,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Adding the policy file (DeletedFileHashesEventsPolicy.xml) that consists of rules from audit even logs, to the array of XML files' $PolicyXMLFilesArray += '.\DeletedFileHashesEventsPolicy.xml' } - # Endregion EventCapturing + #Endregion EventCapturing - # Region Process-Program-Folders-From-User-input + #Region Process-Program-Folders-From-User-input Write-Verbose -Message 'Scanning each of the folder paths that user selected' for ($i = 0; $i -lt $ProgramsPaths.Count; $i++) { @@ -672,9 +672,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } - # Endregion Process-Program-Folders-From-User-input + #Endregion Process-Program-Folders-From-User-input - # Region Kernel-protected-files-automatic-detection-and-allow-rule-creation + #Region Kernel-protected-files-automatic-detection-and-allow-rule-creation # This part takes care of Kernel protected files such as the main executable of the games installed through Xbox app # For these files, only Kernel can get their hashes, it passes them to event viewer and we take them from event viewer logs # Any other attempts such as "Get-FileHash" or "Get-AuthenticodeSignature" fail and ConfigCI Module cmdlets totally ignore these files and do not create allow rules for them @@ -756,7 +756,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } - # Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation + #Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' $PolicyXMLFilesArray | ForEach-Object -Process { Write-Verbose -Message "$_" } @@ -787,7 +787,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force } - # Region Supplemental-policy-processing-and-deployment + #Region Supplemental-policy-processing-and-deployment Write-Verbose -Message 'Supplemental policy processing and deployment' [System.String]$SuppPolicyPath = ".\SupplementalPolicy $SuppPolicyName.xml" @@ -822,7 +822,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Remove the policy xml file in Temp folder we created earlier Remove-Item -Path $PolicyPath -Force - # Endregion Supplemental-policy-processing-and-deployment + #Endregion Supplemental-policy-processing-and-deployment } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index d74bd77fa..cd5203229 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -90,7 +90,7 @@ Function New-SupplementalWDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - # Region User-Configurations-Processing-Validation + #Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$PolicyPath) { # Read User configuration file if it exists @@ -120,7 +120,7 @@ Function New-SupplementalWDACConfig { throw 'PolicyPath parameter cannot be empty and no valid configuration was found for UnsignedPolicyPath.' } } - # Endregion User-Configurations-Processing-Validation + #Endregion User-Configurations-Processing-Validation # Ensure when user selects the -Deploy parameter, the base policy is not signed if ($Deploy) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 37fd4d248..a49f50944 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -98,7 +98,7 @@ Function New-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force - # Region User-Configurations-Processing-Validation + #Region User-Configurations-Processing-Validation # If User is creating Default Windows policy and including SignTool path if ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { # Read User configuration file if it exists @@ -121,7 +121,7 @@ Function New-WDACConfig { elseif ($IncludeSignTool -and $MakeDefaultWindowsWithBlockRules) { $SignToolPathFinal = Get-SignTool -SignToolExePath ($UserConfig.SignToolCustomPath ?? $null) } - # Endregion User-Configurations-Processing-Validation + #Endregion User-Configurations-Processing-Validation # Detecting if Debug switch is used, will do debugging actions based on that $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null @@ -645,7 +645,7 @@ Function New-WDACConfig { New-Item -Type Directory -Path "$home\WDAC" -Force | Out-Null Set-Location "$home\WDAC" - # Region Base-Policy-Processing + #Region Base-Policy-Processing switch ($BasePolicyType) { 'Allow Microsoft Base' { Write-Verbose -Message 'Creating Allow Microsoft Base policy' @@ -674,9 +674,9 @@ Function New-WDACConfig { Write-Verbose -Message 'Setting "Required:EV Signers" policy rule option because RequireEVSigners parameter was used' Set-RuleOption -FilePath $BasePolicy -Option 8 } - # Endregion Base-Policy-Processing + #Endregion Base-Policy-Processing - # Region Supplemental-Policy-Processing + #Region Supplemental-Policy-Processing # Produce a policy xml file from event viewer logs Write-ColorfulText -Color Lavender -InputText 'Scanning Windows Event logs and creating a policy file, please wait...' @@ -764,7 +764,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Converting SupplementalPolicy.xml policy to .CIP binary' ConvertFrom-CIPolicy -XmlFilePath 'SupplementalPolicy.xml' -BinaryFilePath "$PolicyID.cip" | Out-Null - # Endregion Supplemental-Policy-Processing + #Endregion Supplemental-Policy-Processing Write-Output -InputObject "BasePolicyFile = $BasePolicy" Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index f69af2e89..b7f7ef007 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -128,7 +128,7 @@ Function Remove-WDACConfig { # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - # Region User-Configurations-Processing-Validation + #Region User-Configurations-Processing-Validation Write-Verbose -Message 'Validating and processing user configurations' @@ -173,7 +173,7 @@ Function Remove-WDACConfig { } } } - # Endregion User-Configurations-Processing-Validation + #Endregion User-Configurations-Processing-Validation # ValidateSet for Policy names Class PolicyNamezx : System.Management.Automation.IValidateSetValuesGenerator { From c821afb8b0622d4e35c4166c99dcfc43c0cd0883 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 03:56:16 -0930 Subject: [PATCH 141/178] Added more verbose messages --- .../Core/Edit-SignedWDACConfig.psm1 | 135 ++++++++++++++++-- .../Core/Edit-WDACConfig.psm1 | 2 +- 2 files changed, 123 insertions(+), 14 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 94da388e0..5187d2a02 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1000,22 +1000,42 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } #Endregion Input-policy-verification - # Perform the merge + Write-Verbose -Message 'Merging the Supplemental policies into a single policy file' Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null - # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them + + # Remove the deployed Supplemental policies that user selected from the system, because we're going to deploy the new merged policy that contains all of them + Write-Verbose -Message 'Removing the deployed Supplemental policies that user selected from the system' foreach ($SuppPolicyPath in $SuppPolicyPaths) { + + # Get the policy ID of the currently selected Supplemental policy $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) - $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + + Write-Verbose -Message "Removing policy with ID: $SupplementalPolicyID" &'C:\Windows\System32\CiTool.exe' --remove-policy $SupplementalPolicyID -json | Out-Null + # remove the old policy files unless user chose to keep them - if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } + if (!$KeepOldSupplementalPolicies) { + Write-Verbose -Message "Removing the old policy file: $SuppPolicyPath" + Remove-Item -Path $SuppPolicyPath -Force + } } - # Prepare the final merged Supplemental policy for deployment + + Write-Verbose -Message 'Preparing the final merged Supplemental policy for deployment' + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) + + Write-Verbose -Message 'Adding signer rules to the Supplemental policy' Add-SignerRule -FilePath "$SuppPolicyName.xml" -CertificatePath $CertPath -Update -User -Kernel + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" + + Write-Verbose -Message 'Removing the Unsigned mode policy rule option' Set-RuleOption -FilePath "$SuppPolicyName.xml" -Option 6 -Delete + + Write-Verbose -Message 'Converting the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat @@ -1027,66 +1047,132 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' Start-Process @ProcessParams + Write-Verbose -Message 'Removing the unsigned Supplemental policy file' Remove-Item -Path ".\$SuppPolicyID.cip" -Force + + Write-Verbose -Message 'Renaming the signed Supplemental policy file to remove the .p7 extension' Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force + + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText "The Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + + Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path "$SuppPolicyID.cip" -Force } } if ($UpdateBasePolicy) { - # First get the Microsoft recommended block rules + + Write-Verbose -Message 'Getting the Microsoft recommended block rules by calling the Get-BlockRulesMeta function' Get-BlockRulesMeta | Out-Null + Write-Verbose -Message 'Determining the type of the new base policy' switch ($NewBasePolicyType) { + 'AllowMicrosoft_Plus_Block_Rules' { + Write-Verbose -Message 'The new base policy type is AllowMicrosoft_Plus_Block_Rules' + + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force + + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null + + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" + + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } + 'Lightly_Managed_system_Policy' { + Write-Verbose -Message 'The new base policy type is Lightly_Managed_system_Policy' + + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force + + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null + + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" + + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + # Configure required services for ISG authorization + Write-Verbose -Message 'Configuring required services for ISG authorization' Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow } + 'DefaultWindows_WithBlockRules' { + Write-Verbose -Message 'The new base policy type is DefaultWindows_WithBlockRules' + + Write-Verbose -Message 'Copying the DefaultWindows.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force # Allowing SignTool to be able to run after Default Windows base policy is deployed Write-ColorfulText -Color TeaGreen -InputText 'Creating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy.' + + Write-Verbose -Message 'Creating a new folder in the TEMP directory to copy SignTool.exe to it' New-Item -Path "$UserTempDirectoryPath\TemporarySignToolFile" -ItemType Directory -Force | Out-Null + + Write-Verbose -Message 'Copying SignTool.exe to the folder in the TEMP directory' Copy-Item -Path $SignToolPathFinal -Destination "$UserTempDirectoryPath\TemporarySignToolFile" -Force + + Write-Verbose -Message 'Scanning the folder in the TEMP directory to create a policy for SignTool.exe' New-CIPolicy -ScanPath "$UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml + # Delete the Temporary folder in the TEMP folder - if (!$Debug) { Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporarySignToolFile" -Force } + if (!$Debug) { + Write-Verbose -Message 'Deleting the Temporary folder in the TEMP directory' + Remove-Item -Recurse -Path "$UserTempDirectoryPath\TemporarySignToolFile" -Force + } - # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed if (Test-Path -Path 'C:\Program Files\PowerShell') { + Write-Verbose -Message 'Scanning the PowerShell core directory ' + Write-ColorfulText -Color HotPink -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml + + Write-Verbose -Message 'Merging the DefaultWindows.xml, AllowPowerShell.xml, SignTool.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } else { + Write-Verbose -Message 'Not including the PowerShell core directory in the policy' + Write-Verbose -Message 'Merging the DefaultWindows.xml, SignTool.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } + + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" + + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } } - if ($UpdateBasePolicy -and $RequireEVSigners) { Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 } + if ($UpdateBasePolicy -and $RequireEVSigners) { + Write-Verbose -Message 'Adding the EV Signers rule option to the base policy' + Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 + } # Remove the extra files create during module operation that are no longer necessary if (!$Debug) { @@ -1094,21 +1180,33 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force } - # Get the policy ID of the currently deployed base policy based on the policy name that user selected - $CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID + Write-Verbose -Message 'Getting the policy ID of the currently deployed base policy based on the policy name that user selected' + [System.String]$CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID $CurrentID = "{$CurrentID}" + + Write-Verbose -Message 'Making sure there is not a .CIP file with the same name as the current base policy ID in the current working directory' Remove-Item -Path ".\$CurrentID.cip" -Force -ErrorAction SilentlyContinue + Write-Verbose -Message 'Reading the current base policy XML file' [System.Xml.XmlDocument]$Xml = Get-Content -Path '.\BasePolicy.xml' + + Write-Verbose -Message 'Setting the policy ID and Base policy ID to the current base policy ID in the generated XML file' $Xml.SiPolicy.PolicyID = $CurrentID $Xml.SiPolicy.BasePolicyID = $CurrentID + + Write-Verbose -Message 'Saving the updated XML file' $Xml.Save('.\BasePolicy.xml') + Write-Verbose -Message 'Adding signer rules to the base policy' Add-SignerRule -FilePath .\BasePolicy.xml -CertificatePath $CertPath -Update -User -Kernel -Supplemental + Write-Verbose -Message 'Setting the policy version to 1.0.0.1' Set-CIPolicyVersion -FilePath .\BasePolicy.xml -Version '1.0.0.1' + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml + Write-Verbose -Message 'Converting the base policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null # Configure the parameter splat @@ -1120,20 +1218,31 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Write-Verbose -Message 'Signing the base policy with the specified cert' Start-Process @ProcessParams + Write-Verbose -Message 'Removing the unsigned base policy file' Remove-Item -Path ".\$CurrentID.cip" -Force + + Write-Verbose -Message 'Renaming the signed base policy file to remove the .p7 extension' Rename-Item -Path "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force - # Deploy the new base policy with the same GUID on the system + + Write-Verbose -Message 'Deploying the new base policy with the same GUID on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null + # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later - $PolicyFiles = @{ + # Defining a hashtable that contains the policy names and their corresponding XML file names + [System.Collections.Hashtable]$PolicyFiles = @{ 'AllowMicrosoft_Plus_Block_Rules' = 'AllowMicrosoftPlusBlockRules.xml' 'Lightly_Managed_system_Policy' = 'SignedAndReputable.xml' 'DefaultWindows_WithBlockRules' = 'DefaultWindowsPlusBlockRules.xml' } + + Write-Verbose -Message 'Removing the signed base policy CIP file after deployment' Remove-Item -Path ".\$CurrentID.cip" -Force + Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 550727190..9c248807f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -927,7 +927,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Remove-Item -Path "$CurrentID.cip" -Force # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later - $PolicyFiles = @{ + [System.Collections.Hashtable]$PolicyFiles = @{ 'AllowMicrosoft_Plus_Block_Rules' = 'AllowMicrosoftPlusBlockRules.xml' 'Lightly_Managed_system_Policy' = 'SignedAndReputable.xml' 'DefaultWindows_WithBlockRules' = 'DefaultWindowsPlusBlockRules.xml' From 6a895e7d1807fee61018f24e0a1b4b3e34b740d4 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 04:25:12 -0930 Subject: [PATCH 142/178] Added a lot more verbose messages --- .../Core/Edit-SignedWDACConfig.psm1 | 8 +- .../Core/Edit-WDACConfig.psm1 | 155 +++++++++++++++--- 2 files changed, 134 insertions(+), 29 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 5187d2a02..cad75b03f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1243,10 +1243,14 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the signed base policy CIP file after deployment' Remove-Item -Path ".\$CurrentID.cip" -Force + Write-Verbose -Message 'Making sure a policy file with the same name as the current base policy does not exist in the current working directory' Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue - Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] + + Write-Verbose -Message 'Renaming the base policy XML file to match the new base policy type' + Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force + Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" - Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations is no longer valid as you just changed your Base policy.' + Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations (if any) is no longer valid as you just changed your Base policy.' } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 9c248807f..371955bd1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -828,114 +828,215 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if ($MergeSupplementalPolicies) { foreach ($PolicyPath in $PolicyPaths) { - ############ Input policy verification prior to doing anything ############ + + #Region Input-policy-verification + Write-Verbose -Message 'Verifying the input policy files' foreach ($SuppPolicyPath in $SuppPolicyPaths) { + + Write-Verbose -Message "Getting policy ID and type of: $SuppPolicyPath" $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) - $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID - $SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - $DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + [System.String]$SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType + + Write-Verbose -Message 'Getting the IDs of the currently deployed policies on the system' + [System.String[]]$DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } + # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies + Write-Verbose -Message 'Checking the type of the policy' if ($SupplementalPolicyType -ne 'Supplemental Policy') { - Write-Error -Message "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." + Throw "The Selected XML file with GUID $SupplementalPolicyID isn't a Supplemental Policy." } + # Check to make sure the user selected Supplemental policy XML files are deployed on the system + Write-Verbose -Message 'Checking the deployment status of the policy' if ($DeployedPoliciesIDs -notcontains $SupplementalPolicyID) { - Write-Error -Message "The Selected Supplemental XML file with GUID $SupplementalPolicyID isn't deployed on the system." + Throw "The Selected Supplemental XML file with GUID $SupplementalPolicyID isn't deployed on the system." } - } - # Perform the merge + } + #Endregion Input-policy-verification + + Write-Verbose -Message 'Merging the Supplemental policies into a single policy file' Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null - # Delete the deployed Supplemental policies that user selected from the system because we're going to deploy the new merged policy that contains all of them + + # Remove the deployed Supplemental policies that user selected from the system, because we're going to deploy the new merged policy that contains all of them + Write-Verbose -Message 'Removing the deployed Supplemental policies that user selected from the system' foreach ($SuppPolicyPath in $SuppPolicyPaths) { + + # Get the policy ID of the currently selected Supplemental policy $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) - $SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID + + Write-Verbose -Message "Removing policy with ID: $SupplementalPolicyID" &'C:\Windows\System32\CiTool.exe' --remove-policy $SupplementalPolicyID -json | Out-Null + # remove the old policy files unless user chose to keep them - if (!$KeepOldSupplementalPolicies) { Remove-Item -Path $SuppPolicyPath -Force } + if (!$KeepOldSupplementalPolicies) { + Write-Verbose -Message "Removing the old policy file: $SuppPolicyPath" + Remove-Item -Path $SuppPolicyPath -Force + } } - # Prepare the final merged Supplemental policy for deployment + + Write-Verbose -Message 'Preparing the final merged Supplemental policy for deployment' + Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" + + Write-Verbose -Message 'Converting the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null + + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null + Write-ColorfulText -Color TeaGreen -InputText "The Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + + Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path "$SuppPolicyID.cip" -Force } } if ($UpdateBasePolicy) { - # First get the Microsoft recommended block rules + + Write-Verbose -Message 'Getting the Microsoft recommended block rules by calling the Get-BlockRulesMeta function' Get-BlockRulesMeta | Out-Null + Write-Verbose -Message 'Determining the type of the new base policy' switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { + Write-Verbose -Message 'The new base policy type is AllowMicrosoft_Plus_Block_Rules' + + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force + + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null + + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" + + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { + Write-Verbose -Message 'The new base policy type is Lightly_Managed_system_Policy' + + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force + + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null + + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" + + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } + # Configure required services for ISG authorization + Write-Verbose -Message 'Configuring required services for ISG authorization' Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow Start-Process -FilePath 'C:\Windows\System32\sc.exe' -ArgumentList 'config', 'appidsvc', 'start= auto' -Wait -NoNewWindow } 'DefaultWindows_WithBlockRules' { + Write-Verbose -Message 'The new base policy type is DefaultWindows_WithBlockRules' + + Write-Verbose -Message 'Copying the DefaultWindows.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force - # Scan PowerShell core directory and add them to the Default Windows base policy so that the module can be used after it's been deployed + + if (Test-Path -Path 'C:\Program Files\PowerShell') { - Write-Host -Object 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' -ForegroundColor Blue - New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -FilePath .\AllowPowerShell.xml + Write-Verbose -Message 'Scanning the PowerShell core directory ' + + Write-ColorfulText -Color HotPink -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' + + New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml + + Write-Verbose -Message 'Merging the DefaultWindows.xml, AllowPowerShell.xml, SignTool.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } else { + Write-Verbose -Message 'Not including the PowerShell core directory in the policy' + Write-Verbose -Message 'Merging the DefaultWindows.xml, SignTool.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } + + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" + + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } + + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } } - if ($UpdateBasePolicy -and $RequireEVSigners) { Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 } - - Set-CIPolicyVersion -FilePath .\BasePolicy.xml -Version '1.0.0.1' - Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml + if ($UpdateBasePolicy -and $RequireEVSigners) { + Write-Verbose -Message 'Adding the EV Signers rule option to the base policy' + Set-RuleOption -FilePath .\BasePolicy.xml -Option 8 + } # Remove the extra files create during module operation that are no longer necessary - Remove-Item -Path '.\AllowPowerShell.xml', '.\DefaultWindows_Enforced.xml', '.\AllowMicrosoft.xml' -Force -ErrorAction SilentlyContinue - Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force + if (!$Debug) { + Remove-Item -Path '.\AllowPowerShell.xml', '.\DefaultWindows_Enforced.xml', '.\AllowMicrosoft.xml' -Force -ErrorAction SilentlyContinue + Remove-Item -Path '.\Microsoft recommended block rules.xml' -Force + } # Get the policy ID of the currently deployed base policy based on the policy name that user selected - $CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID - $CurrentID = "{$CurrentID}" + Write-Verbose -Message 'Getting the policy ID of the currently deployed base policy based on the policy name that user selected' + [System.String]$CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID + $CurrentID = "{$CurrentID}" + Write-Verbose -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" + Write-Verbose -Message 'Reading the current base policy XML file' [System.Xml.XmlDocument]$Xml = Get-Content -Path '.\BasePolicy.xml' + + Write-Verbose -Message 'Setting the policy ID and Base policy ID to the current base policy ID in the generated XML file' $Xml.SiPolicy.PolicyID = $CurrentID $Xml.SiPolicy.BasePolicyID = $CurrentID + + Write-Verbose -Message 'Saving the updated XML file' $Xml.Save('.\BasePolicy.xml') + + Write-Verbose -Message 'Setting the policy version to 1.0.0.1' + Set-CIPolicyVersion -FilePath .\BasePolicy.xml -Version '1.0.0.1' + + Write-Verbose -Message 'Setting HVCI to Strict' + Set-HVCIOptions -Strict -FilePath .\BasePolicy.xml + + Write-Verbose -Message 'Converting the base policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null - # Deploy the new base policy with the same GUID on the system + + Write-Verbose -Message 'Deploying the new base policy with the same GUID on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null - # Remove the policy binary after it's been deployed + + Write-Verbose -Message 'Removing the base policy CIP file after deployment' Remove-Item -Path "$CurrentID.cip" -Force # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later + # Defining a hashtable that contains the policy names and their corresponding XML file names [System.Collections.Hashtable]$PolicyFiles = @{ 'AllowMicrosoft_Plus_Block_Rules' = 'AllowMicrosoftPlusBlockRules.xml' 'Lightly_Managed_system_Policy' = 'SignedAndReputable.xml' 'DefaultWindows_WithBlockRules' = 'DefaultWindowsPlusBlockRules.xml' } + + Write-Verbose -Message 'Making sure a policy file with the same name as the current base policy does not exist in the current working directory' Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue + + Write-Verbose -Message 'Renaming the base policy XML file to match the new base policy type' Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force + Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" - Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations is no longer valid as you just changed your Base policy.' + Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations (if any) is no longer valid as you just changed your Base policy.' } } From 80188270be2e0b94e4fedd4c47935e17a6a466c4 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 04:26:48 -0930 Subject: [PATCH 143/178] Removed unnecessary trailing spaces --- .../Core/Edit-SignedWDACConfig.psm1 | 80 +++++++++---------- .../Core/Edit-WDACConfig.psm1 | 69 ++++++++-------- .../Core/Remove-WDACConfig.psm1 | 2 +- 3 files changed, 75 insertions(+), 76 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index cad75b03f..954ae55f1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -973,7 +973,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if ($MergeSupplementalPolicies) { foreach ($PolicyPath in $PolicyPaths) { - + #Region Input-policy-verification Write-Verbose -Message 'Verifying the input policy files' foreach ($SuppPolicyPath in $SuppPolicyPaths) { @@ -982,10 +982,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID [System.String]$SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - + Write-Verbose -Message 'Getting the IDs of the currently deployed policies on the system' [System.String[]]$DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } - + # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies Write-Verbose -Message 'Checking the type of the policy' if ($SupplementalPolicyType -ne 'Supplemental Policy') { @@ -1002,7 +1002,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Merging the Supplemental policies into a single policy file' Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null - + # Remove the deployed Supplemental policies that user selected from the system, because we're going to deploy the new merged policy that contains all of them Write-Verbose -Message 'Removing the deployed Supplemental policies that user selected from the system' foreach ($SuppPolicyPath in $SuppPolicyPaths) { @@ -1010,10 +1010,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Get the policy ID of the currently selected Supplemental policy $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID - + Write-Verbose -Message "Removing policy with ID: $SupplementalPolicyID" &'C:\Windows\System32\CiTool.exe' --remove-policy $SupplementalPolicyID -json | Out-Null - + # remove the old policy files unless user chose to keep them if (!$KeepOldSupplementalPolicies) { Write-Verbose -Message "Removing the old policy file: $SuppPolicyPath" @@ -1025,16 +1025,16 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) - + Write-Verbose -Message 'Adding signer rules to the Supplemental policy' Add-SignerRule -FilePath "$SuppPolicyName.xml" -CertificatePath $CertPath -Update -User -Kernel - + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" - + Write-Verbose -Message 'Removing the Unsigned mode policy rule option' Set-RuleOption -FilePath "$SuppPolicyName.xml" -Option 6 -Delete - + Write-Verbose -Message 'Converting the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null @@ -1047,7 +1047,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'ErrorAction' = 'Stop' } # Only show the output of SignTool if Debug switch is used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } - + # Sign the files with the specified cert Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' Start-Process @ProcessParams @@ -1057,12 +1057,12 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Renaming the signed Supplemental policy file to remove the .p7 extension' Rename-Item -Path "$SuppPolicyID.cip.p7" -NewName "$SuppPolicyID.cip" -Force - + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color TeaGreen -InputText "The Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." - + Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path "$SuppPolicyID.cip" -Force } @@ -1078,41 +1078,41 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'AllowMicrosoft_Plus_Block_Rules' { Write-Verbose -Message 'The new base policy type is AllowMicrosoft_Plus_Block_Rules' - + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force - + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null - + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { Write-Verbose -Message 'The new base policy type is Lightly_Managed_system_Policy' - + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force - + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null - + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" - + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } - + # Configure required services for ISG authorization Write-Verbose -Message 'Configuring required services for ISG authorization' Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow @@ -1121,22 +1121,22 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I 'DefaultWindows_WithBlockRules' { Write-Verbose -Message 'The new base policy type is DefaultWindows_WithBlockRules' - + Write-Verbose -Message 'Copying the DefaultWindows.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force # Allowing SignTool to be able to run after Default Windows base policy is deployed Write-ColorfulText -Color TeaGreen -InputText 'Creating allow rules for SignTool.exe in the DefaultWindows base policy so you can continue using it after deploying the DefaultWindows base policy.' - + Write-Verbose -Message 'Creating a new folder in the TEMP directory to copy SignTool.exe to it' New-Item -Path "$UserTempDirectoryPath\TemporarySignToolFile" -ItemType Directory -Force | Out-Null - + Write-Verbose -Message 'Copying SignTool.exe to the folder in the TEMP directory' Copy-Item -Path $SignToolPathFinal -Destination "$UserTempDirectoryPath\TemporarySignToolFile" -Force - + Write-Verbose -Message 'Scanning the folder in the TEMP directory to create a policy for SignTool.exe' New-CIPolicy -ScanPath "$UserTempDirectoryPath\TemporarySignToolFile" -Level FilePublisher -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\SignTool.xml - + # Delete the Temporary folder in the TEMP folder if (!$Debug) { Write-Verbose -Message 'Deleting the Temporary folder in the TEMP directory' @@ -1145,10 +1145,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if (Test-Path -Path 'C:\Program Files\PowerShell') { Write-Verbose -Message 'Scanning the PowerShell core directory ' - + Write-ColorfulText -Color HotPink -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml - + Write-Verbose -Message 'Merging the DefaultWindows.xml, AllowPowerShell.xml, SignTool.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\DefaultWindows_Enforced.xml, .\AllowPowerShell.xml, .\SignTool.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null } @@ -1160,10 +1160,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 6, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } @@ -1189,7 +1189,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Reading the current base policy XML file' [System.Xml.XmlDocument]$Xml = Get-Content -Path '.\BasePolicy.xml' - + Write-Verbose -Message 'Setting the policy ID and Base policy ID to the current base policy ID in the generated XML file' $Xml.SiPolicy.PolicyID = $CurrentID $Xml.SiPolicy.BasePolicyID = $CurrentID @@ -1228,10 +1228,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Renaming the signed base policy file to remove the .p7 extension' Rename-Item -Path "$CurrentID.cip.p7" -NewName "$CurrentID.cip" -Force - + Write-Verbose -Message 'Deploying the new base policy with the same GUID on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null - + # Keep the new base policy XML file that was just deployed, in the current directory, so user can keep it for later # Defining a hashtable that contains the policy names and their corresponding XML file names [System.Collections.Hashtable]$PolicyFiles = @{ @@ -1242,13 +1242,13 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Removing the signed base policy CIP file after deployment' Remove-Item -Path ".\$CurrentID.cip" -Force - + Write-Verbose -Message 'Making sure a policy file with the same name as the current base policy does not exist in the current working directory' Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue - + Write-Verbose -Message 'Renaming the base policy XML file to match the new base policy type' Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force - + Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations (if any) is no longer valid as you just changed your Base policy.' } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 371955bd1..beb2c421a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -837,10 +837,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID [System.String]$SupplementalPolicyType = $Supplementalxml.SiPolicy.PolicyType - + Write-Verbose -Message 'Getting the IDs of the currently deployed policies on the system' [System.String[]]$DeployedPoliciesIDs = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies.PolicyID | ForEach-Object -Process { return "{$_}" } - + # Check the type of the user selected Supplemental policy XML files to make sure they are indeed Supplemental policies Write-Verbose -Message 'Checking the type of the policy' if ($SupplementalPolicyType -ne 'Supplemental Policy') { @@ -852,23 +852,23 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if ($DeployedPoliciesIDs -notcontains $SupplementalPolicyID) { Throw "The Selected Supplemental XML file with GUID $SupplementalPolicyID isn't deployed on the system." } - } + } #Endregion Input-policy-verification Write-Verbose -Message 'Merging the Supplemental policies into a single policy file' Merge-CIPolicy -PolicyPaths $SuppPolicyPaths -OutputFilePath "$SuppPolicyName.xml" | Out-Null - + # Remove the deployed Supplemental policies that user selected from the system, because we're going to deploy the new merged policy that contains all of them Write-Verbose -Message 'Removing the deployed Supplemental policies that user selected from the system' foreach ($SuppPolicyPath in $SuppPolicyPaths) { - + # Get the policy ID of the currently selected Supplemental policy $Supplementalxml = [System.Xml.XmlDocument](Get-Content -Path $SuppPolicyPath) [System.String]$SupplementalPolicyID = $Supplementalxml.SiPolicy.PolicyID - + Write-Verbose -Message "Removing policy with ID: $SupplementalPolicyID" &'C:\Windows\System32\CiTool.exe' --remove-policy $SupplementalPolicyID -json | Out-Null - + # remove the old policy files unless user chose to keep them if (!$KeepOldSupplementalPolicies) { Write-Verbose -Message "Removing the old policy file: $SuppPolicyPath" @@ -880,18 +880,18 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Converting the policy to a Supplemental policy type and resetting its ID' $SuppPolicyID = Set-CIPolicyIdInfo -FilePath "$SuppPolicyName.xml" -ResetPolicyID -PolicyName "$SuppPolicyName - $(Get-Date -Format 'MM-dd-yyyy')" -BasePolicyToSupplementPath $PolicyPath $SuppPolicyID = $SuppPolicyID.Substring(11) - + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath "$SuppPolicyName.xml" Write-Verbose -Message 'Converting the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath "$SuppPolicyName.xml" -BinaryFilePath "$SuppPolicyID.cip" | Out-Null - + Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color TeaGreen -InputText "The Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." - + Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path "$SuppPolicyID.cip" -Force } @@ -906,40 +906,40 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I switch ($NewBasePolicyType) { 'AllowMicrosoft_Plus_Block_Rules' { Write-Verbose -Message 'The new base policy type is AllowMicrosoft_Plus_Block_Rules' - + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force - + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null - + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Allow Microsoft Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } 'Lightly_Managed_system_Policy' { Write-Verbose -Message 'The new base policy type is Lightly_Managed_system_Policy' - + Write-Verbose -Message 'Copying the AllowMicrosoft.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination '.\AllowMicrosoft.xml' -Force - + Write-Verbose -Message 'Merging the AllowMicrosoft.xml and Microsoft recommended block rules into a single policy file' Merge-CIPolicy -PolicyPaths .\AllowMicrosoft.xml, '.\Microsoft recommended block rules.xml' -OutputFilePath .\BasePolicy.xml | Out-Null - + Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Signed And Reputable policy refreshed on $(Get-Date -Format 'MM-dd-yyyy')" - + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 14, 15, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } - + # Configure required services for ISG authorization Write-Verbose -Message 'Configuring required services for ISG authorization' Start-Process -FilePath 'C:\Windows\System32\appidtel.exe' -ArgumentList 'start' -Wait -NoNewWindow @@ -947,16 +947,15 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I } 'DefaultWindows_WithBlockRules' { Write-Verbose -Message 'The new base policy type is DefaultWindows_WithBlockRules' - + Write-Verbose -Message 'Copying the DefaultWindows.xml template policy file to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination '.\DefaultWindows_Enforced.xml' -Force - - + if (Test-Path -Path 'C:\Program Files\PowerShell') { Write-Verbose -Message 'Scanning the PowerShell core directory ' - + Write-ColorfulText -Color HotPink -InputText 'Creating allow rules for PowerShell in the DefaultWindows base policy so you can continue using this module after deploying it.' - + New-CIPolicy -ScanPath 'C:\Program Files\PowerShell' -Level FilePublisher -NoScript -Fallback Hash -UserPEs -UserWriteablePaths -MultiplePolicyFormat -AllowFileNameFallbacks -FilePath .\AllowPowerShell.xml Write-Verbose -Message 'Merging the DefaultWindows.xml, AllowPowerShell.xml, SignTool.xml and Microsoft recommended block rules into a single policy file' @@ -970,10 +969,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Setting the policy name' Set-CIPolicyIdInfo -FilePath .\BasePolicy.xml -PolicyName "Default Windows Plus Block Rules refreshed On $(Get-Date -Format 'MM-dd-yyyy')" - + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ } - + Write-Verbose -Message 'Removing the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath .\BasePolicy.xml -Option $_ -Delete } } @@ -993,8 +992,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Get the policy ID of the currently deployed base policy based on the policy name that user selected Write-Verbose -Message 'Getting the policy ID of the currently deployed base policy based on the policy name that user selected' [System.String]$CurrentID = ((&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.Friendlyname -eq $CurrentBasePolicyName }).BasePolicyID - $CurrentID = "{$CurrentID}" - + $CurrentID = "{$CurrentID}" + Write-Verbose -Message "This is the current ID of deployed base policy that is going to be used in the new base policy: $CurrentID" Write-Verbose -Message 'Reading the current base policy XML file' [System.Xml.XmlDocument]$Xml = Get-Content -Path '.\BasePolicy.xml' @@ -1014,10 +1013,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Converting the base policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath '.\BasePolicy.xml' -BinaryFilePath "$CurrentID.cip" | Out-Null - + Write-Verbose -Message 'Deploying the new base policy with the same GUID on the system' &'C:\Windows\System32\CiTool.exe' --update-policy "$CurrentID.cip" -json | Out-Null - + Write-Verbose -Message 'Removing the base policy CIP file after deployment' Remove-Item -Path "$CurrentID.cip" -Force @@ -1031,10 +1030,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Making sure a policy file with the same name as the current base policy does not exist in the current working directory' Remove-Item -Path $PolicyFiles[$NewBasePolicyType] -Force -ErrorAction SilentlyContinue - + Write-Verbose -Message 'Renaming the base policy XML file to match the new base policy type' Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force - + Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations (if any) is no longer valid as you just changed your Base policy.' } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index b7f7ef007..cc36d5108 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -72,7 +72,7 @@ Function Remove-WDACConfig { })] [Parameter(Mandatory = $false, ParameterSetName = 'Unsigned Or Supplemental')] [System.String[]]$PolicyNames, - + [ArgumentCompleter({ param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) From d1b373cc565dec8c93759f56de0c6a97f065b17e Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 04:44:59 -0930 Subject: [PATCH 144/178] Added verbose messages to Deploy-SignedWDACConfig --- .../Core/Deploy-SignedWDACConfig.psm1 | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 66ffb40c8..6d2924474 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -114,37 +114,51 @@ Function Deploy-SignedWDACConfig { process { foreach ($PolicyPath in $PolicyPaths) { - # Gather policy details + Write-Verbose -Message "Gathering policy details from: $PolicyPath" $Xml = [System.Xml.XmlDocument](Get-Content -Path $PolicyPath) [System.String]$PolicyType = $Xml.SiPolicy.PolicyType [System.String]$PolicyID = $Xml.SiPolicy.PolicyID [System.String]$PolicyName = ($Xml.SiPolicy.Settings.Setting | Where-Object -FilterScript { $_.provider -eq 'PolicyInfo' -and $_.valuename -eq 'Name' -and $_.key -eq 'Information' }).value.string [System.String[]]$PolicyRuleOptions = $Xml.SiPolicy.Rules.Rule.Option - # Remove the .CIP file of the same policy being signed and deployed if any in the current working directory + Write-Verbose -Message 'Removing any existing .CIP file of the same policy being signed and deployed if any in the current working directory' Remove-Item -Path ".\$PolicyID.cip" -ErrorAction SilentlyContinue - # Ensure -Supplemental is not used when the policy type is supplemental + Write-Verbose -Message 'Checking if the policy type is Supplemental and if so, removing the -Supplemental parameter from the SignerRule command' if ($PolicyType -eq 'Supplemental Policy') { + + Write-Verbose -Message 'Policy type is Supplemental' + # Make sure -User is not added if the UMCI policy rule option doesn't exist in the policy, typically for Strict kernel mode policies if ('Enabled:UMCI' -in $PolicyRuleOptions) { Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -User -Kernel } else { + Write-Verbose -Message 'UMCI policy rule option does not exist in the policy, typically for Strict kernel mode policies' Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -Kernel } } else { + + Write-Verbose -Message 'Policy type is Base' + # Make sure -User is not added if the UMCI policy rule option doesn't exist in the policy, typically for Strict kernel mode policies if ('Enabled:UMCI' -in $PolicyRuleOptions) { Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -User -Kernel -Supplemental } else { + Write-Verbose -Message 'UMCI policy rule option does not exist in the policy, typically for Strict kernel mode policies' Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -Kernel -Supplemental } } + + Write-Verbose -Message 'Setting HVCI to Strict' Set-HVCIOptions -Strict -FilePath $PolicyPath + + Write-Verbose -Message 'Removing the Unsigned mode option from the policy rules' Set-RuleOption -FilePath $PolicyPath -Option 6 -Delete + + Write-Verbose -Message 'Converting the policy to .CIP file' ConvertFrom-CIPolicy -XmlFilePath $PolicyPath -BinaryFilePath "$PolicyID.cip" | Out-Null # Configure the parameter splat @@ -157,18 +171,27 @@ Function Deploy-SignedWDACConfig { } # Hide the SignTool.exe's normal output unless -Debug parameter was used if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Sign the files with the specified cert + Write-Verbose -Message 'Signing the policy with the specified certificate' Start-Process @ProcessParams + Write-Verbose -Message 'Making sure a .CIP file with the same name is not present in the current working directory' Remove-Item -Path ".\$PolicyID.cip" -Force + + Write-Verbose -Message 'Renaming the .p7 file to .cip' Rename-Item -Path "$PolicyID.cip.p7" -NewName "$PolicyID.cip" -Force if ($Deploy) { + Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null + Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" + + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path ".\$PolicyID.cip" -Force #Region Detecting Strict Kernel mode policy and removing it from User Configs @@ -178,16 +201,26 @@ Function Deploy-SignedWDACConfig { [System.String]$StrictKernelNoFlightRootsPolicyGUID = Get-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID if (($PolicyName -like '*Strict Kernel mode policy Enforced*')) { + + Write-Verbose -Message 'The deployed policy is Strict Kernel mode' + if ($StrictKernelPolicyGUID) { if ($($PolicyID.TrimStart('{').TrimEnd('}')) -eq $StrictKernelPolicyGUID) { + + Write-Verbose -Message 'Removing the GUID of the deployed Strict Kernel mode policy from the User Configs' Remove-CommonWDACConfig -StrictKernelPolicyGUID | Out-Null } } } elseif (($PolicyName -like '*Strict Kernel No Flights mode policy Enforced*')) { + + Write-Verbose -Message 'The deployed policy is Strict Kernel No Flights mode' + if ($StrictKernelNoFlightRootsPolicyGUID) { if ($($PolicyID.TrimStart('{').TrimEnd('}')) -eq $StrictKernelNoFlightRootsPolicyGUID) { + + Write-Verbose -Message 'Removing the GUID of the deployed Strict Kernel No Flights mode policy from the User Configs' Remove-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID | Out-Null } } @@ -195,7 +228,7 @@ Function Deploy-SignedWDACConfig { } #Endregion Detecting Strict Kernel mode policy and removing it from User Configs - # Show the question only for base policies. Don't show it for Strict kernel mode policies + # Show the question only for base policies. Don't show it for Strict kernel mode policies either if (($PolicyType -ne 'Supplemental Policy') -and ($PolicyName -notlike '*Strict Kernel*')) { # Ask user question about whether or not to add the Signed policy xml file to the User Config Json for easier usage later From d67aabd9abf697be93a72af240ff0da716fdd6fa Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 04:55:07 -0930 Subject: [PATCH 145/178] Added verbose messages to New-DenyWDACConfig --- .../Core/New-DenyWDACConfig.psm1 | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index e8c96d54d..7c02e05cc 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -92,14 +92,17 @@ Function New-DenyWDACConfig { } process { + # Create deny supplemental policy for general files, apps etc. if ($Normal) { - # remove any possible files from previous runs + + Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue + # An array to hold the temporary xml files of each user-selected folders [System.Object[]]$PolicyXMLFilesArray = @() - ######################## Process Program Folders From User input ##################### + Write-Verbose -Message 'Processing Program Folders From User input' for ($i = 0; $i -lt $ScanLocations.Count; $i++) { # Creating a hash table to dynamically add parameters based on user input and pass them to New-Cipolicy cmdlet @@ -119,33 +122,44 @@ Function New-DenyWDACConfig { if (!$NoUserPEs) { $UserInputProgramFoldersPolicyMakerHashTable['UserPEs'] = $true } # Create the supplemental policy via parameter splatting + Write-Verbose -Message "Currently scanning and creating a deny policy for the folder: $($ScanLocations[$i])" New-CIPolicy @UserInputProgramFoldersPolicyMakerHashTable } - Write-Debug -Message 'The Deny policy with the following configuration is being created' - if ($Debug) { $UserInputProgramFoldersPolicyMakerHashTable } + Write-ColorfulText -Color Pink -InputText 'The Deny policy with the following configuration is being created' + $UserInputProgramFoldersPolicyMakerHashTable # Merge-CiPolicy accepts arrays - collecting all the policy files created by scanning user specified folders + Write-Verbose -Message 'Collecting all the policy files created by scanning user specified folders' foreach ($file in (Get-ChildItem -File -Path '.\' -Filter 'ProgramDir_ScanResults*.xml')) { $PolicyXMLFilesArray += $file.FullName } - # Adding the AllowAll default policy path to the array of policy paths + Write-Verbose -Message 'Adding the AllowAll default template policy path to the array of policy paths to merge' $PolicyXMLFilesArray += 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowAll.xml' - # creating the final Deny base policy from the xml files in the paths array + + Write-Verbose -Message 'Creating the final Deny base policy from the xml files in the paths array' Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\DenyPolicy $PolicyName.xml" | Out-Null + Write-Verbose -Message 'Assigning a name and resetting the policy ID' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" [System.String]$PolicyID = $PolicyID.Substring(11) + + Write-Verbose -Message 'Setting the policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' + Write-Verbose -Message 'Setting the policy rule options' @(0, 2, 5, 6, 11, 12, 16, 17, 19, 20) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ } + Write-Verbose -Message 'Deleting the unnecessary policy rule options' @(3, 4, 9, 10, 13, 18) | ForEach-Object -Process { Set-RuleOption -FilePath "DenyPolicy $PolicyName.xml" -Option $_ -Delete } + Write-Verbose -Message 'Setting the HVCI to Strict' Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" + + Write-Verbose -Message 'Converting the policy XML to .CIP' ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" @@ -156,15 +170,20 @@ Function New-DenyWDACConfig { } if ($Deploy) { + Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null + Write-Host -NoNewline -Object "`n$PolicyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta Write-Host -Object ' has been deployed.' -ForegroundColor Green + + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } } + # Create Deny base policy for Driver files - elseif ($Drivers) { + if ($Drivers) { powershell.exe -Command { [System.Object[]]$DriverFilesObject = @() From 6e5a935f6f84b7b96995ae9905469a984e4046a1 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 05:13:53 -0930 Subject: [PATCH 146/178] Increasing the required minimum SignTool version New required version is 10.0.22621.2428 which is available in the latest SDK --- WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 index 1b9548d11..4e8a3f009 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-SignTool.psm1 @@ -37,7 +37,8 @@ Function Get-SignTool { } try { # Validate the SignTool executable - [System.Version]$WindowsSdkVersion = '10.0.22621.755' # Setting the minimum version of SignTool that is allowed to be executed + # Setting the minimum version of SignTool that is allowed to be executed + [System.Version]$WindowsSdkVersion = '10.0.22621.2428' [System.Boolean]$GreenFlag1 = (((Get-Item -Path $SignToolExePath).VersionInfo).ProductVersionRaw -ge $WindowsSdkVersion) [System.Boolean]$GreenFlag2 = (((Get-Item -Path $SignToolExePath).VersionInfo).FileVersionRaw -ge $WindowsSdkVersion) [System.Boolean]$GreenFlag3 = ((Get-Item -Path $SignToolExePath).VersionInfo).CompanyName -eq 'Microsoft Corporation' From 3e9d2bae66fc6bd868597494beba5d3eced68626 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 08:12:52 -0930 Subject: [PATCH 147/178] Improved Get-CommonWDACConfig cmdlet --- .../Core/Deploy-SignedWDACConfig.psm1 | 10 +++--- .../Core/Get-CommonWDACConfig.psm1 | 32 ++++++++++--------- .../Core/New-DenyWDACConfig.psm1 | 12 +++---- .../Core/Set-CommonWDACConfig.psm1 | 6 ++-- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 6d2924474..0ca7d1878 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -128,7 +128,7 @@ Function Deploy-SignedWDACConfig { if ($PolicyType -eq 'Supplemental Policy') { Write-Verbose -Message 'Policy type is Supplemental' - + # Make sure -User is not added if the UMCI policy rule option doesn't exist in the policy, typically for Strict kernel mode policies if ('Enabled:UMCI' -in $PolicyRuleOptions) { Add-SignerRule -FilePath $PolicyPath -CertificatePath $CertPath -Update -User -Kernel @@ -186,7 +186,7 @@ Function Deploy-SignedWDACConfig { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - + Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green Write-Output -InputObject "PolicyName = $PolicyName" Write-Output -InputObject "PolicyGUID = $PolicyID`n" @@ -214,12 +214,12 @@ Function Deploy-SignedWDACConfig { } elseif (($PolicyName -like '*Strict Kernel No Flights mode policy Enforced*')) { - + Write-Verbose -Message 'The deployed policy is Strict Kernel No Flights mode' - + if ($StrictKernelNoFlightRootsPolicyGUID) { if ($($PolicyID.TrimStart('{').TrimEnd('}')) -eq $StrictKernelNoFlightRootsPolicyGUID) { - + Write-Verbose -Message 'Removing the GUID of the deployed Strict Kernel No Flights mode policy from the User Configs' Remove-CommonWDACConfig -StrictKernelNoFlightRootsPolicyGUID | Out-Null } diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index ef08e8eb8..78315f38f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -21,13 +21,13 @@ Function Get-CommonWDACConfig { # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null - Write-Debug -Message 'The .WDACConfig folder in the current user folder has been created because it did not exist.' + Write-Verbose -Message 'The .WDACConfig folder in the current user folder has been created because it did not exist.' } # Create User configuration file if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { New-Item -ItemType File -Path "$UserAccountDirectoryPath\.WDACConfig\" -Name 'UserConfigurations.json' -Force -ErrorAction Stop | Out-Null - Write-Debug -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' + Write-Verbose -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' } if ($Open) { @@ -35,21 +35,15 @@ Function Get-CommonWDACConfig { break } - if ($PSBoundParameters.Count -eq 0) { - # Display this message if User Configuration file is empty - if ($null -eq (Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { - Write-ColorfulText -Color Pink -InputText "`nYour current WDAC User Configurations is empty." - } - # Display this message if User Configuration file has content - else { - Write-ColorfulText -Color Pink -InputText "`nThis is your current WDAC User Configurations: " - Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * - } + # Display this message if User Configuration file is empty + if ($null -eq (Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { + Write-ColorfulText -Color Pink -InputText "`nYour current WDAC User Configurations is empty." break } - # Read the current user configurations + Write-Verbose -Message 'Reading the current user configurations' [PSCustomObject]$CurrentUserConfigurations = Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" + # If the file exists but is corrupted and has bad values, rewrite it try { $CurrentUserConfigurations = $CurrentUserConfigurations | ConvertFrom-Json @@ -73,6 +67,11 @@ Function Get-CommonWDACConfig { $StrictKernelNoFlightRootsPolicyGUID.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.StrictKernelNoFlightRootsPolicyGUID } $CertPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.CertificatePath } $LastUpdateCheck.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.LastUpdateCheck } + Default { + # If no parameter is present, display all the values + Write-ColorfulText -Color Pink -InputText "`nThis is your current WDAC User Configurations: " + Write-Output -InputObject $CurrentUserConfigurations + } } } <# @@ -89,11 +88,11 @@ Function Get-CommonWDACConfig { .PARAMETER SignedPolicyPath Shows the path to a Signed WDAC xml policy .PARAMETER UnsignedPolicyPath - Shows the path to an Unsigned WDAC xml policy + Shows the path to an Unsigned WDAC xml policy .PARAMETER CertCN Shows the certificate common name .PARAMETER SignToolPath - Shows the path to the SignTool.exe + Shows the path to the SignTool.exe .PARAMETER CertPath Shows the path to a .cer certificate file .PARAMETER Open @@ -106,5 +105,8 @@ Function Get-CommonWDACConfig { System.Management.Automation.SwitchParameter .OUTPUTS System.Object[] + System.DateTime + System.String + System.Guid #> } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 7c02e05cc..a6db1b3f5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -98,7 +98,7 @@ Function New-DenyWDACConfig { Write-Verbose -Message 'Removing any possible files from previous runs' Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue - + # An array to hold the temporary xml files of each user-selected folders [System.Object[]]$PolicyXMLFilesArray = @() @@ -137,14 +137,14 @@ Function New-DenyWDACConfig { Write-Verbose -Message 'Adding the AllowAll default template policy path to the array of policy paths to merge' $PolicyXMLFilesArray += 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowAll.xml' - + Write-Verbose -Message 'Creating the final Deny base policy from the xml files in the paths array' Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\DenyPolicy $PolicyName.xml" | Out-Null Write-Verbose -Message 'Assigning a name and resetting the policy ID' [System.String]$PolicyID = Set-CIPolicyIdInfo -FilePath "DenyPolicy $PolicyName.xml" -ResetPolicyID -PolicyName "$PolicyName" [System.String]$PolicyID = $PolicyID.Substring(11) - + Write-Verbose -Message 'Setting the policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath "DenyPolicy $PolicyName.xml" -Version '1.0.0.0' @@ -158,7 +158,7 @@ Function New-DenyWDACConfig { Write-Verbose -Message 'Setting the HVCI to Strict' Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" - + Write-Verbose -Message 'Converting the policy XML to .CIP' ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null @@ -172,11 +172,11 @@ Function New-DenyWDACConfig { if ($Deploy) { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - + Write-Host -NoNewline -Object "`n$PolicyID.cip for " -ForegroundColor Green Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta Write-Host -Object ' has been deployed.' -ForegroundColor Green - + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 9c609c64e..f78e92fb1 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -45,10 +45,8 @@ Function Set-CommonWDACConfig { }, ErrorMessage = 'The selected policy xml file is Unsigned, Please select a Signed policy.')] [parameter(Mandatory = $false)][System.String]$SignedPolicyPath, - [parameter(Mandatory = $false, DontShow = $true)][System.Guid]$StrictKernelPolicyGUID, # DontShow prevents common parameters from being displayed too - + [parameter(Mandatory = $false, DontShow = $true)][System.Guid]$StrictKernelPolicyGUID, [parameter(Mandatory = $false, DontShow = $true)][System.Guid]$StrictKernelNoFlightRootsPolicyGUID, - [parameter(Mandatory = $false, DontShow = $true)][System.DateTime]$LastUpdateCheck ) begin { @@ -180,8 +178,8 @@ Function Set-CommonWDACConfig { # Update the User Configurations file Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" - Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " + Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " Write-Verbose -Message 'Displaying the current user configurations' Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } From 671dd42204ea5c887ffbdb8cbf7cb44ba2c1542e Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 10:37:27 -0930 Subject: [PATCH 148/178] Fixed some issues in Edit-SignedWDACConfig cmdlet --- .../Core/Edit-SignedWDACConfig.psm1 | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 954ae55f1..663a79dc6 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -331,9 +331,6 @@ Function Edit-SignedWDACConfig { if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - - # After creating signed .p7 files for each CIP, remove the old Unsigned ones - Remove-Item -Path $_ -Force } Write-Verbose -Message 'Removing the unsigned CIPs' @@ -487,7 +484,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' + Write-Verbose -Message 'Converting the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat @@ -596,9 +593,6 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams - - # After creating signed .p7 files for each CIP, remove the old Unsigned ones - Remove-Item -Path $_ -Force } Write-Verbose -Message 'Removing the unsigned CIPs' @@ -930,7 +924,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I Write-Verbose -Message 'Setting the Supplemental policy version to 1.0.0.0' Set-CIPolicyVersion -FilePath $SuppPolicyPath -Version '1.0.0.0' - Write-Verbose -Message 'Convert the Supplemental policy to a CIP file' + Write-Verbose -Message 'Converting the Supplemental policy to a CIP file' ConvertFrom-CIPolicy -XmlFilePath $SuppPolicyPath -BinaryFilePath "$SuppPolicyID.cip" | Out-Null # Configure the parameter splat From 41beb49714b6f35104976574f2b973223c058e11 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 12:49:52 -0930 Subject: [PATCH 149/178] Added verbose messages --- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 3 +++ WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 3 +++ 2 files changed, 6 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 663a79dc6..9be873a6a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -871,6 +871,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } + else { + Write-Verbose -Message 'No Kernel protected files in the user selected paths were detected.' + } #Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index beb2c421a..0ffbe1951 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -756,6 +756,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $ExesWithNoHash | ForEach-Object -Process { Write-Warning -Message "$_" } } } + else { + Write-Verbose -Message 'No Kernel protected files in the user selected paths were detected.' + } #Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation Write-Verbose -Message 'The following policy xml files are going to be merged into the final Supplemental policy and be deployed on the system:' From c8ece6cb0aebb7a7f296aea535a0708bf50c7f10 Mon Sep 17 00:00:00 2001 From: Violet Date: Mon, 11 Dec 2023 12:57:06 -0930 Subject: [PATCH 150/178] Updated alternative snapback guarantee procedure --- .../Core/Edit-WDACConfig.psm1 | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 0ffbe1951..defe63534 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -254,20 +254,23 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' <# - # CMD and Scheduled Task Method - $taskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c c:\EnforcedModeSnapBack.cmd' - $taskTrigger = New-ScheduledTaskTrigger -AtLogOn - $principal = New-ScheduledTaskPrincipal -GroupId 'BUILTIN\Administrators' -RunLevel Highest - $TaskSettings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8 -DontStopIfGoingOnBatteries -Priority 0 -AllowStartIfOnBatteries - Register-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Action $taskAction -Trigger $taskTrigger -Principal $principal -Settings $TaskSettings -Force | Out-Null - - Set-Content -Force "c:\EnforcedModeSnapBack.cmd" -Value @" +# CMD and Scheduled Task Method +$taskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c C:\EnforcedModeSnapBack.cmd' +$taskTrigger = New-ScheduledTaskTrigger -AtLogOn +# Run the task under the system account +$principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -RunLevel Highest +# Run the task with the highest priority +$TaskSettings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8 -DontStopIfGoingOnBatteries -Priority 0 -AllowStartIfOnBatteries +# Register the task +Register-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Action $taskAction -Trigger $taskTrigger -Principal $principal -Settings $TaskSettings -Force | Out-Null + +Set-Content -Force 'C:\EnforcedModeSnapBack.cmd' -Value @" REM Deploying the Enforced Mode SnapBack CI Policy -CiTool --update-policy "$((Get-Location).Path)\$PolicyID.cip" -json +CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json REM Deleting the Scheduled task responsible for running this CMD file schtasks /Delete /TN EnforcedModeSnapBack /F REM Deleting the CI Policy file -del /f /q "$((Get-Location).Path)\$PolicyID.cip" +del /f /q "$((Get-Location).Path)\EnforcedMode.cip" REM Deleting this CMD file itself del "%~f0" "@ From b11665a11fc8a59754c7cdaf18df38573962a9d7 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 00:25:18 -0930 Subject: [PATCH 151/178] Created a function out of snapback guarantee --- .../Core/Edit-SignedWDACConfig.psm1 | 39 +++------- .../Core/Edit-WDACConfig.psm1 | 65 +++-------------- .../Shared/New-SnapBackGuarantee.psm1 | 73 +++++++++++++++++++ .../WDACConfig Module Files/WDACConfig.psd1 | 3 +- 4 files changed, 93 insertions(+), 87 deletions(-) create mode 100644 WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 9be873a6a..43a9c3485 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -137,6 +137,7 @@ Function Edit-SignedWDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-SnapBackGuarantee.psm1" -Force # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host @@ -343,20 +344,10 @@ Function Edit-SignedWDACConfig { #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' + New-SnapBackGuarantee -Location (Get-Location).Path - # Defining the registry path for RunOnce key - [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - # Defining the command that will be executed by the RunOnce key in case of a reboot - [System.String]$Command = @" -CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force -"@ - # Saving the command to a file that will be executed by the RunOnce key in case of a reboot - $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key - New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' @@ -411,10 +402,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - - # For PowerShell Method - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + Unregister-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Confirm:$false + Remove-Item -Path 'C:\EnforcedModeSnapBack.cmd' -Force } Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow @@ -605,20 +594,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' + New-SnapBackGuarantee -Location (Get-Location).Path - # Defining the registry path for RunOnce key - [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - # Defining the command that will be executed by the RunOnce key in case of a reboot - [System.String]$Command = @" -CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force -"@ - # Saving the command to a file that will be executed by the RunOnce key in case of a reboot - $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key - New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' @@ -901,8 +880,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + Unregister-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Confirm:$false + Remove-Item -Path 'C:\EnforcedModeSnapBack.cmd' -Force } #Region Supplemental-policy-processing-and-deployment diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index defe63534..7dc36486a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -115,6 +115,7 @@ Function Edit-WDACConfig { Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-RuleRefs.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-FileRules.psm1" -Force Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Get-BlockRulesMeta.psm1" -Force + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\New-SnapBackGuarantee.psm1" -Force # if -SkipVersionCheck wasn't passed, run the updater # Redirecting the Update-Self function's information Stream to $null because Write-Host @@ -252,44 +253,10 @@ Function Edit-WDACConfig { #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' + New-SnapBackGuarantee -Location (Get-Location).Path - <# -# CMD and Scheduled Task Method -$taskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c C:\EnforcedModeSnapBack.cmd' -$taskTrigger = New-ScheduledTaskTrigger -AtLogOn -# Run the task under the system account -$principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -RunLevel Highest -# Run the task with the highest priority -$TaskSettings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8 -DontStopIfGoingOnBatteries -Priority 0 -AllowStartIfOnBatteries -# Register the task -Register-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Action $taskAction -Trigger $taskTrigger -Principal $principal -Settings $TaskSettings -Force | Out-Null - -Set-Content -Force 'C:\EnforcedModeSnapBack.cmd' -Value @" -REM Deploying the Enforced Mode SnapBack CI Policy -CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json -REM Deleting the Scheduled task responsible for running this CMD file -schtasks /Delete /TN EnforcedModeSnapBack /F -REM Deleting the CI Policy file -del /f /q "$((Get-Location).Path)\EnforcedMode.cip" -REM Deleting this CMD file itself -del "%~f0" -"@ -#> - # Using PowerShell and RunOnce Method - - # Defining the registry path for RunOnce key - [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - # Defining the command that will be executed by the RunOnce key in case of a reboot - [System.String]$Command = @" -CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force -"@ - # Saving the command to a file that will be executed by the RunOnce key in case of a reboot - $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key - New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' @@ -345,13 +312,9 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - # For PowerShell Method - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force - # For CMD Method - # Unregister-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Confirm:$false - # Remove-Item -Path 'c:\EnforcedModeSnapBack.cmd' -Force + Unregister-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Confirm:$false + Remove-Item -Path 'C:\EnforcedModeSnapBack.cmd' -Force } Write-Host -Object 'Here are the paths you selected:' -ForegroundColor Yellow @@ -493,20 +456,10 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I #Region Snap-Back-Guarantee Write-Verbose -Message 'Creating Enforced Mode SnapBack guarantee' + New-SnapBackGuarantee -Location (Get-Location).Path - # Defining the registry path for RunOnce key - [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' - # Defining the command that will be executed by the RunOnce key in case of a reboot - [System.String]$Command = @" -CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force -"@ - # Saving the command to a file that will be executed by the RunOnce key in case of a reboot - $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force - # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key - New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null - - Write-Verbose -Message 'Deploying the Audit mode CIP' # Deploy the Audit mode CIP + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' @@ -789,8 +742,8 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I # Enforced Mode Snapback removal after base policy has already been successfully re-enforced Write-Verbose -Message 'Removing the SnapBack guarantee because the base policy has been successfully re-enforced' - Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force - Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force + Unregister-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Confirm:$false + Remove-Item -Path 'C:\EnforcedModeSnapBack.cmd' -Force } #Region Supplemental-policy-processing-and-deployment diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 new file mode 100644 index 000000000..eab858590 --- /dev/null +++ b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 @@ -0,0 +1,73 @@ +Function New-SnapBackGuarantee { + <# + .SYNOPSIS + A function that arms the system with a snapback guarantee in case of a reboot during the base policy enforcement process. + This will help prevent the system from being stuck in audit mode in case of a power outage or a reboot during the base policy enforcement process. + .PARAMETER Location + The directory location of the base policy file that will be enforced. + .INPUTS + System.IO.DirectoryInfo + .OUTPUTS + System.Void + #> + [CmdletBinding()] + Param( + [parameter(Mandatory = $true)] + [System.IO.DirectoryInfo]$Location + ) + + # Using CMD and Scheduled Task Method + + # Creating the scheduled task action + [Microsoft.Management.Infrastructure.CimInstance]$TaskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c C:\EnforcedModeSnapBack.cmd' + # Creating the scheduled task trigger + [Microsoft.Management.Infrastructure.CimInstance]$TaskTrigger = New-ScheduledTaskTrigger -AtLogOn + # Creating the scheduled task principal, will run the task under the system account using its well-known SID + [Microsoft.Management.Infrastructure.CimInstance]$Principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -RunLevel Highest + # Setting the task to run with the highest priority + [Microsoft.Management.Infrastructure.CimInstance]$TaskSettings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8 -DontStopIfGoingOnBatteries -Priority 0 -AllowStartIfOnBatteries + # Register the scheduled task + Register-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Action $TaskAction -Trigger $TaskTrigger -Principal $Principal -Settings $TaskSettings -Force | Out-Null + + # Saving the EnforcedModeSnapBack.cmd file to the root of C drive + # It contains the instructions to revert the base policy to enforced mode + Set-Content -Force 'C:\EnforcedModeSnapBack.cmd' -Value @" +REM Deploying the Enforced Mode SnapBack CI Policy +CiTool --update-policy "$Location\EnforcedMode.cip" -json +REM Deleting the Scheduled task responsible for running this CMD file +schtasks /Delete /TN EnforcedModeSnapBack /F +REM Deleting the CI Policy file +del /f /q "$Location\EnforcedMode.cip" +REM Deleting this CMD file itself +del "%~f0" +"@ + +} + +# Export external facing functions only, prevent internal functions from getting exported +Export-ModuleMember -Function 'New-SnapBackGuarantee' + +# An alternative way to do this which is less reliable because RunOnce key can be deleted by 3rd party programs during installation etc. +<# + # Using PowerShell and RunOnce Method + + # Defining the registry path for RunOnce key + [System.String]$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' + # Defining the command that will be executed by the RunOnce key in case of a reboot + [System.String]$Command = @" +CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-Item -Path "$((Get-Location).Path)\EnforcedMode.cip" -Force +"@ + # Saving the command to a file that will be executed by the RunOnce key in case of a reboot + $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force + # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key + New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null +#> + +# If the alternative way is used, this should be added to the Finally block under the: +# Enforced Mode Snapback removal after base policy has already been successfully re-enforced + +<# +# For PowerShell Method +# Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force +# Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' -Name '*CIPolicySnapBack' -Force +#> \ No newline at end of file diff --git a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 index e949dadda..ce73f0e0c 100644 --- a/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 +++ b/WDACConfig/WDACConfig Module Files/WDACConfig.psd1 @@ -200,7 +200,8 @@ To get help and syntax on PowerShell console, type: 'Shared\Set-LogSize.psm1', 'Shared\Test-FilePath.psm1', 'Shared\Update-self.psm1', - 'Shared\Write-ColorfulText.psm1' + 'Shared\Write-ColorfulText.psm1', + 'Shared\New-SnapBackGuarantee.psm1' ) # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. From b6be5f263c88fca5613b575b22991b851bfbecb2 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 00:33:19 -0930 Subject: [PATCH 152/178] Adde new function to PSDefaultParameterValues --- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- .../CoreExt/PSDefaultParameterValues.ps1 | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 43a9c3485..442f5705e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -851,7 +851,7 @@ Function Edit-SignedWDACConfig { } } else { - Write-Verbose -Message 'No Kernel protected files in the user selected paths were detected.' + Write-Verbose -Message 'No Kernel protected files in the user selected paths were detected' } #Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 7dc36486a..5efa2048f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -713,7 +713,7 @@ Function Edit-WDACConfig { } } else { - Write-Verbose -Message 'No Kernel protected files in the user selected paths were detected.' + Write-Verbose -Message 'No Kernel protected files in the user selected paths were detected' } #Endregion Kernel-protected-files-automatic-detection-and-allow-rule-creation diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 3c1fdb4fe..35edf526f 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -23,4 +23,5 @@ $PSDefaultParameterValues = @{ 'Test-FilePath:Verbose' = $Verbose 'Update-self:Verbose' = $Verbose 'Write-ColorfulText:Verbose' = $Verbose + 'New-SnapBackGuarantee:Verbose' = $Verbose } From 88a454cc68631706f78e28c03f2e833531739dff Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 00:34:35 -0930 Subject: [PATCH 153/178] Added verbose message to the new function --- .../WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 index eab858590..e675c1b9f 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 @@ -18,6 +18,8 @@ Function New-SnapBackGuarantee { # Using CMD and Scheduled Task Method + Write-Verbose -Message 'Creating the scheduled task for Snap Back Guarantee' + # Creating the scheduled task action [Microsoft.Management.Infrastructure.CimInstance]$TaskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c C:\EnforcedModeSnapBack.cmd' # Creating the scheduled task trigger From f1daa8844dcaf346fe2c4428eb497dc2e871781e Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 00:36:21 -0930 Subject: [PATCH 154/178] Removed unused function from PSDefaultParameterValues --- .../WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 35edf526f..60e32d340 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -18,7 +18,6 @@ $PSDefaultParameterValues = @{ 'Get-SignTool:Verbose' = $Verbose 'Move-UserModeToKernelMode:Verbose' = $Verbose 'New-EmptyPolicy:Verbose' = $Verbose - 'Remove-ZerosFromIDs:Verbose' = $Verbose 'Set-LogSize:Verbose' = $Verbose 'Test-FilePath:Verbose' = $Verbose 'Update-self:Verbose' = $Verbose From 0f0fbb799dbe68eec5b2276d873b0232574503c4 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 00:53:46 -0930 Subject: [PATCH 155/178] improved wording --- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 442f5705e..3e8c48fa2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1037,7 +1037,7 @@ Function Edit-SignedWDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "The Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + Write-ColorfulText -Color TeaGreen -InputText "The Signed Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart is not immediately needed but eventually required to finish the removal of the previous individual Supplemental policies." Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path "$SuppPolicyID.cip" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 5efa2048f..d74d0813d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -849,7 +849,7 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText "The Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart Not immediately needed but eventually required to finish the removal of previous individual Supplemental policies." + Write-ColorfulText -Color TeaGreen -InputText "The Supplemental policy $SuppPolicyName has been deployed on the system, replacing the old ones.`nSystem Restart is not immediately needed but eventually required to finish the removal of the previous individual Supplemental policies." Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path "$SuppPolicyID.cip" -Force From 7ac6b2527bad001b4b53eb88f8e5ac57d6b85e93 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 02:49:11 -0930 Subject: [PATCH 156/178] Improved User configurations internals --- .../Core/Deploy-SignedWDACConfig.psm1 | 3 +-- .../Core/Edit-SignedWDACConfig.psm1 | 11 +++++++---- .../Core/Edit-WDACConfig.psm1 | 13 ++++++++----- .../Core/New-SupplementalWDACConfig.psm1 | 3 +-- .../Core/New-WDACConfig.psm1 | 3 +-- .../Core/Remove-CommonWDACConfig.psm1 | 5 +---- .../Core/Remove-WDACConfig.psm1 | 4 ++-- .../Core/Set-CommonWDACConfig.psm1 | 6 ------ .../CoreExt/PSDefaultParameterValues.ps1 | 3 +++ .../Shared/New-SnapBackGuarantee.psm1 | 2 +- 10 files changed, 25 insertions(+), 28 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 0ca7d1878..67ebcd435 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -61,8 +61,7 @@ Function Deploy-SignedWDACConfig { try { $UserConfig = $UserConfig | ConvertFrom-Json } catch { Write-Error -Message 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue - # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig + Remove-CommonWDACConfig } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 3e8c48fa2..d6c886412 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -154,8 +154,7 @@ Function Edit-SignedWDACConfig { try { $UserConfig = $UserConfig | ConvertFrom-Json } catch { Write-Error -Message 'User Configurations Json file is corrupted, deleting it...' -ErrorAction Continue - # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig + Remove-CommonWDACConfig } } } @@ -347,7 +346,7 @@ Function Edit-SignedWDACConfig { New-SnapBackGuarantee -Location (Get-Location).Path # Deploy the Audit mode CIP - Write-Verbose -Message 'Deploying the Audit mode CIP' + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' @@ -1226,7 +1225,11 @@ Function Edit-SignedWDACConfig { Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" - Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations (if any) is no longer valid as you just changed your Base policy.' + + if (Get-CommonWDACConfig -SignedPolicyPath) { + Write-Verbose -Message 'Replacing the old signed policy path in User Configurations with the new one' + Set-CommonWDACConfig -SignedPolicyPath (Get-ChildItem -Path $PolicyFiles[$NewBasePolicyType]).FullName | Out-Null + } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index d74d0813d..a47401507 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -137,8 +137,7 @@ Function Edit-WDACConfig { try { $UserConfig = $UserConfig | ConvertFrom-Json } catch { Write-Error -Message 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue - # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig + Remove-CommonWDACConfig } } } @@ -256,7 +255,7 @@ Function Edit-WDACConfig { New-SnapBackGuarantee -Location (Get-Location).Path # Deploy the Audit mode CIP - Write-Verbose -Message 'Deploying the Audit mode CIP' + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' @@ -459,7 +458,7 @@ Function Edit-WDACConfig { New-SnapBackGuarantee -Location (Get-Location).Path # Deploy the Audit mode CIP - Write-Verbose -Message 'Deploying the Audit mode CIP' + Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' @@ -994,7 +993,11 @@ Function Edit-WDACConfig { Rename-Item -Path '.\BasePolicy.xml' -NewName $PolicyFiles[$NewBasePolicyType] -Force Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" - Write-ColorfulText -Color Lavender -InputText 'Keep in mind that your previous policy path saved in User Configurations (if any) is no longer valid as you just changed your Base policy.' + + if (Get-CommonWDACConfig -SignedPolicyPath) { + Write-Verbose -Message 'Replacing the old signed policy path in User Configurations with the new one' + Set-CommonWDACConfig -SignedPolicyPath (Get-ChildItem -Path $PolicyFiles[$NewBasePolicyType]).FullName | Out-Null + } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index cd5203229..2b3205f7f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -100,8 +100,7 @@ Function New-SupplementalWDACConfig { try { $UserConfig = $UserConfig | ConvertFrom-Json } catch { Write-Error -Message 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue - # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig + Remove-CommonWDACConfig } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index a49f50944..ab4ade1b0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -108,8 +108,7 @@ Function New-WDACConfig { try { $UserConfig = $UserConfig | ConvertFrom-Json } catch { Write-Error -Message 'User Configurations Json file is corrupted, deleting it...' -ErrorAction Continue - # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig + Remove-CommonWDACConfig } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index 835869c15..8df8aa4f0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -13,9 +13,6 @@ Function Remove-CommonWDACConfig { begin { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - # Importing the required sub-modules - Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { @@ -32,7 +29,7 @@ Function Remove-CommonWDACConfig { # Delete the entire User Configs if a more specific parameter wasn't used if ($PSBoundParameters.Count -eq 0) { Remove-Item -Path "$UserAccountDirectoryPath\.WDACConfig\" -Recurse -Force - Write-ColorfulText -Color Pink -InputText 'User Configurations for WDACConfig module have been deleted.' + Write-verbfose -Message 'User Configurations for WDACConfig module have been deleted.' break } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index cc36d5108..3897d4bf9 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -142,8 +142,8 @@ Function Remove-WDACConfig { try { $UserConfig = $UserConfig | ConvertFrom-Json } catch { Write-Error -Message 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue - # Calling this function with this parameter automatically does its job and breaks/stops the operation - Set-CommonWDACConfig -DeleteUserConfig + Remove-CommonWDACConfig + break } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index f78e92fb1..83b7bbfa2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -53,10 +53,6 @@ Function Set-CommonWDACConfig { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" - # Importing the required sub-modules - Write-Verbose -Message 'Importing the required sub-modules' - Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force - # Create User configuration folder if it doesn't already exist if (-NOT (Test-Path -Path "$UserAccountDirectoryPath\.WDACConfig\")) { New-Item -ItemType Directory -Path "$UserAccountDirectoryPath\.WDACConfig\" -Force -ErrorAction Stop | Out-Null @@ -179,8 +175,6 @@ Function Set-CommonWDACConfig { Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" - Write-ColorfulText -Color Pink -InputText "`nThis is your new WDAC User Configurations: " - Write-Verbose -Message 'Displaying the current user configurations' Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" | ConvertFrom-Json | Format-List -Property * } <# diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 60e32d340..29383e2c1 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -23,4 +23,7 @@ $PSDefaultParameterValues = @{ 'Update-self:Verbose' = $Verbose 'Write-ColorfulText:Verbose' = $Verbose 'New-SnapBackGuarantee:Verbose' = $Verbose + 'Set-CommonWDACConfig:Verbose' = $Verbose + 'Get-CommonWDACConfig:Verbose' = $Verbose + 'Remove-CommonWDACConfig:Verbose' = $Verbose } diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 index e675c1b9f..286f84e23 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 @@ -63,7 +63,7 @@ CiTool --update-policy "$((Get-Location).Path)\EnforcedMode.cip" -json; Remove-I $Command | Out-File -FilePath 'C:\EnforcedModeSnapBack.ps1' -Force # Saving the command that runs the EnforcedModeSnapBack.ps1 file in the next reboot to the RunOnce key New-ItemProperty -Path $RegistryPath -Name '*CIPolicySnapBack' -Value "powershell.exe -WindowStyle `"Hidden`" -ExecutionPolicy `"Bypass`" -Command `"& {&`"C:\EnforcedModeSnapBack.ps1`";Remove-Item -Path 'C:\EnforcedModeSnapBack.ps1' -Force}`"" -PropertyType String -Force | Out-Null -#> +#> # If the alternative way is used, this should be added to the Finally block under the: # Enforced Mode Snapback removal after base policy has already been successfully re-enforced From 25530957b28f28ba4f4b3c9bc2684725f0ec4e7a Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 02:57:35 -0930 Subject: [PATCH 157/178] Update PSDefaultParameterValues.ps1 --- .../CoreExt/PSDefaultParameterValues.ps1 | 3 --- 1 file changed, 3 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 index 29383e2c1..60e32d340 100644 --- a/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 +++ b/WDACConfig/WDACConfig Module Files/CoreExt/PSDefaultParameterValues.ps1 @@ -23,7 +23,4 @@ $PSDefaultParameterValues = @{ 'Update-self:Verbose' = $Verbose 'Write-ColorfulText:Verbose' = $Verbose 'New-SnapBackGuarantee:Verbose' = $Verbose - 'Set-CommonWDACConfig:Verbose' = $Verbose - 'Get-CommonWDACConfig:Verbose' = $Verbose - 'Remove-CommonWDACConfig:Verbose' = $Verbose } From 6eb8165c2221b159f1b7ee030ea9b92c4bad8476 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 03:03:28 -0930 Subject: [PATCH 158/178] Improved new lines --- .../Core/New-SupplementalWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 2b3205f7f..9c437405a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -153,7 +153,7 @@ Function New-SupplementalWDACConfig { Write-ColorfulText -Color HotPink -InputText "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable - Write-Host -Object "`n" + Write-Host -Object '' # Create the supplemental policy via parameter splatting New-CIPolicy @PolicyMakerHashTable diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index ab4ade1b0..0345bf93f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -283,7 +283,6 @@ Function New-WDACConfig { if ($Deploy -and $MakeAllowMSFTWithBlockRules) { Write-Verbose -Message 'Deploying the AllowMicrosoftPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - Write-Host -Object "`n" Write-Verbose -Message 'Removing the generated .CIP binary file after deploying it' Remove-Item -Path "$PolicyID.cip" -Force @@ -410,7 +409,6 @@ Function New-WDACConfig { if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { Write-Verbose -Message 'Deploying the DefaultWindowsPlusBlockRules.xml policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - Write-Host -Object "`n" Write-Verbose -Message 'Removing the generated .CIP binary file after deploying it' Remove-Item -Path "$PolicyID.cip" -Force @@ -697,7 +695,7 @@ Function New-WDACConfig { Write-ColorfulText -Color HotPink -InputText "`nGenerating Supplemental policy with the following specifications:" $PolicyMakerHashTable - Write-Host -Object "`n" + Write-Host -Object '' # Create the supplemental policy via parameter splatting for files in event viewer that are currently on the disk New-CIPolicy @PolicyMakerHashTable From 2f0195fd77b5382908fcad50bfc80de1b1d2df38 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 03:22:49 -0930 Subject: [PATCH 159/178] Update Edit-WDACConfig.psm1 --- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index a47401507..41db37131 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -386,7 +386,7 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Deployed in Enforced Mode:' + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" @@ -770,7 +770,7 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Deployed in Enforced Mode:' + Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been deployed in Enforced Mode:' Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" From cd545da54018787e1326a2f523478da39a3da3a6 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 03:42:44 -0930 Subject: [PATCH 160/178] Update New-SnapBackGuarantee.psm1 --- .../WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 index 286f84e23..139cd8932 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/New-SnapBackGuarantee.psm1 @@ -26,7 +26,7 @@ Function New-SnapBackGuarantee { [Microsoft.Management.Infrastructure.CimInstance]$TaskTrigger = New-ScheduledTaskTrigger -AtLogOn # Creating the scheduled task principal, will run the task under the system account using its well-known SID [Microsoft.Management.Infrastructure.CimInstance]$Principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -RunLevel Highest - # Setting the task to run with the highest priority + # Setting the task to run with the highest priority. This is to ensure that the task runs as soon as possible after the reboot. It runs even on logon screen before user logs on too. [Microsoft.Management.Infrastructure.CimInstance]$TaskSettings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8 -DontStopIfGoingOnBatteries -Priority 0 -AllowStartIfOnBatteries # Register the scheduled task Register-ScheduledTask -TaskName 'EnforcedModeSnapBack' -Action $TaskAction -Trigger $TaskTrigger -Principal $Principal -Settings $TaskSettings -Force | Out-Null From a5fd26d013accf3be886fbac83ff9f52cd09213f Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 03:45:10 -0930 Subject: [PATCH 161/178] Fixed Signed/Unsigned parameter --- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 41db37131..77670ca1d 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -994,9 +994,9 @@ Function Edit-WDACConfig { Write-ColorfulText -Color Pink -InputText "Base Policy has been successfully updated to $NewBasePolicyType" - if (Get-CommonWDACConfig -SignedPolicyPath) { - Write-Verbose -Message 'Replacing the old signed policy path in User Configurations with the new one' - Set-CommonWDACConfig -SignedPolicyPath (Get-ChildItem -Path $PolicyFiles[$NewBasePolicyType]).FullName | Out-Null + if (Get-CommonWDACConfig -UnsignedPolicyPath) { + Write-Verbose -Message 'Replacing the old unsigned policy path in User Configurations with the new one' + Set-CommonWDACConfig -UnsignedPolicyPath (Get-ChildItem -Path $PolicyFiles[$NewBasePolicyType]).FullName | Out-Null } } } From 1d1351e7b8f1d355242f55c674b6178ff6094b6f Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 03:52:31 -0930 Subject: [PATCH 162/178] Changed output type of Get-BlockRulesMeta function --- .../WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- .../Shared/Get-BlockRulesMeta.psm1 | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 0345bf93f..b87bb9722 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -213,7 +213,7 @@ Function New-WDACConfig { Write-Verbose -Message 'Displaying extra info about the Microsoft recommended Drivers block list' Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK - # Display the result as object + # Display the result Write-Output -InputObject 'PolicyFile = Microsoft recommended driver block rules.xml' } } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 75fb7c8ed..0023a7117 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -5,7 +5,7 @@ Function Get-BlockRulesMeta { .INPUTS None. You cannot pipe objects to this function. .OUTPUTS - PSCustomObject + System.String #> [CmdletBinding()] param () @@ -19,9 +19,9 @@ Function Get-BlockRulesMeta { Remove-Item -Path '.\Microsoft recommended block rules TEMP.xml' -Force Set-RuleOption -FilePath '.\Microsoft recommended block rules.xml' -Option 3 -Delete Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' - return [PSCustomObject]@{ - PolicyFile = 'Microsoft recommended block rules.xml' - } + + # Display the result + Write-Output -InputObject 'PolicyFile = Microsoft recommended block rules.xml' } # Export external facing functions only, prevent internal functions from getting exported From 748be5cb0b226d31379607f0a08ef90c84ed8d4c Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 04:12:30 -0930 Subject: [PATCH 163/178] Minor fixes --- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index b87bb9722..1a6f319e3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -818,7 +818,7 @@ Function New-WDACConfig { Remove-Item -Path 'SignedAndReputable.xml' -Force -ErrorAction SilentlyContinue Write-Verbose -Message 'Calling Build-AllowMSFTWithBlockRules function to create AllowMicrosoftPlusBlockRules.xml policy' - Build-AllowMSFTWithBlockRules -NoCIP + Build-AllowMSFTWithBlockRules -NoCIP | Out-Null Write-Verbose -Message 'Renaming AllowMicrosoftPlusBlockRules.xml to SignedAndReputable.xml' Rename-Item -Path 'AllowMicrosoftPlusBlockRules.xml' -NewName 'SignedAndReputable.xml' -Force diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 0023a7117..9f183b05d 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -21,7 +21,7 @@ Function Get-BlockRulesMeta { Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' # Display the result - Write-Output -InputObject 'PolicyFile = Microsoft recommended block rules.xml' + Write-Output -InputObject 'PolicyFile = Microsoft recommended block rules.xml' } # Export external facing functions only, prevent internal functions from getting exported From 3cdf33644aa558ef0a6eb7b2d6207cf5cfbc0766 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 04:38:19 -0930 Subject: [PATCH 164/178] Improved variable names and User Config function --- WDACConfig/Utilities/Invoke-WDACConfig.ps1 | 2 +- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/Remove-CommonWDACConfig.psm1 | 14 ++++++-- .../Core/Remove-WDACConfig.psm1 | 32 +++++++++---------- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/WDACConfig/Utilities/Invoke-WDACConfig.ps1 b/WDACConfig/Utilities/Invoke-WDACConfig.ps1 index b34d5335e..9a116a9fd 100644 --- a/WDACConfig/Utilities/Invoke-WDACConfig.ps1 +++ b/WDACConfig/Utilities/Invoke-WDACConfig.ps1 @@ -7,4 +7,4 @@ Import-Module -FullyQualifiedName "$ScriptFilePath\..\WDACConfig Module Files\WDACConfig.psd1" -Force # Uncomment and replace with any cmdlet of the WDACConfig module that is going to be debugged -Invoke-WDACSimulation -FolderPath '' -XmlFilePath '' -Verbose +Confirm-WDACConfig diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 78315f38f..9ea3e1e92 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -37,7 +37,7 @@ Function Get-CommonWDACConfig { # Display this message if User Configuration file is empty if ($null -eq (Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { - Write-ColorfulText -Color Pink -InputText "`nYour current WDAC User Configurations is empty." + Write-ColorfulText -Color Pink -InputText 'Your current WDAC User Configurations is empty.' break } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index 8df8aa4f0..f4f39bd30 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -29,8 +29,12 @@ Function Remove-CommonWDACConfig { # Delete the entire User Configs if a more specific parameter wasn't used if ($PSBoundParameters.Count -eq 0) { Remove-Item -Path "$UserAccountDirectoryPath\.WDACConfig\" -Recurse -Force - Write-verbfose -Message 'User Configurations for WDACConfig module have been deleted.' - break + Write-Verbose -Message 'User Configurations for WDACConfig module have been deleted.' + + # set a boolean value that returns from the Process and End blocks as well + [System.Boolean]$ReturnAndDone = $true + + Return } # Read the current user configurations @@ -57,6 +61,9 @@ Function Remove-CommonWDACConfig { } } process { + + if ($true -eq $ReturnAndDone) { return } + if ($SignedPolicyPath) { Write-Verbose -Message 'Removing the SignedPolicyPath' $UserConfigurationsObject.SignedPolicyPath = '' @@ -122,6 +129,9 @@ Function Remove-CommonWDACConfig { } } end { + + if ($true -eq $ReturnAndDone) { return } + # Update the User Configurations file Write-Verbose -Message 'Saving the changes' $UserConfigurationsObject | ConvertTo-Json | Set-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json" diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 3897d4bf9..215470bd7 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -43,27 +43,27 @@ Function Remove-WDACConfig { # Create a hashtable mapping policy names to policy IDs. This will be used later to check if a policy ID already exists. $NameIDMap = @{} - foreach ($policy in $policies) { - $NameIDMap[$policy.Friendlyname] = $policy.policyID + foreach ($Policy in $policies) { + $NameIDMap[$Policy.Friendlyname] = $Policy.policyID } # Get the IDs of existing policies that are already being used in the current command. - $existingIDs = $fakeBoundParameters['PolicyIDs'] + $ExistingIDs = $fakeBoundParameters['PolicyIDs'] # Get the policy names that are currently being used in the command. This is done by looking at the abstract syntax tree (AST) # of the command and finding all string literals, which are assumed to be policy names. - $existing = $commandAst.FindAll({ + $Existing = $commandAst.FindAll({ $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] }, $false).Value # Filter out the policy names that are already being used or whose corresponding policy IDs are already being used. # The resulting list of policy names is what will be shown as autocomplete suggestions. - $candidates = $policies.Friendlyname | Where-Object -FilterScript { $_ -notin $existing -and $NameIDMap[$_] -notin $existingIDs } + $Candidates = $policies.Friendlyname | Where-Object -FilterScript { $_ -notin $Existing -and $NameIDMap[$_] -notin $ExistingIDs } # Additionally, if the policy name contains spaces, it's enclosed in single quotes to ensure it's treated as a single argument. # This is achieved using the Compare-Object cmdlet to compare the existing and candidate values, and outputting the resulting matches. # For each resulting match, it checks if the match contains a space, if so, it's enclosed in single quotes, if not, it's returned as is. - (Compare-Object -PassThru $candidates $existing | Where-Object -FilterScript { SideIndicator -EQ '<=' }). + (Compare-Object -PassThru $Candidates $Existing | Where-Object -FilterScript { SideIndicator -EQ '<=' }). ForEach({ if ($_ -match ' ') { "'{0}'" -f $_ } else { $_ } }) })] [ValidateScript({ @@ -80,21 +80,21 @@ Function Remove-WDACConfig { $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } # Create a hashtable mapping policy IDs to policy names. This will be used later to check if a policy name already exists. $IDNameMap = @{} - foreach ($policy in $policies) { - $IDNameMap[$policy.policyID] = $policy.Friendlyname + foreach ($Policy in $policies) { + $IDNameMap[$Policy.policyID] = $Policy.Friendlyname } # Get the names of existing policies that are already being used in the current command. - $existingNames = $fakeBoundParameters['PolicyNames'] + $ExistingNames = $fakeBoundParameters['PolicyNames'] # Get the policy IDs that are currently being used in the command. This is done by looking at the abstract syntax tree (AST) # of the command and finding all string literals, which are assumed to be policy IDs. - $existing = $commandAst.FindAll({ + $Existing = $commandAst.FindAll({ $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] }, $false).Value # Filter out the policy IDs that are already being used or whose corresponding policy names are already being used. # The resulting list of policy IDs is what will be shown as autocomplete suggestions. - $candidates = $policies.policyID | Where-Object -FilterScript { $_ -notin $existing -and $IDNameMap[$_] -notin $existingNames } + $Candidates = $policies.policyID | Where-Object -FilterScript { $_ -notin $Existing -and $IDNameMap[$_] -notin $ExistingNames } # Return the candidates. - return $candidates + return $Candidates })] [ValidateScript({ if ($_ -notin [PolicyIDzx]::new().GetValidValues()) { throw "Invalid policy ID: $_" } @@ -203,8 +203,8 @@ Function Remove-WDACConfig { [System.String[]] GetValidValues() { $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$IDNameMap = @{} - foreach ($policy in $policies) { - self::$IDNameMap[$policy.policyID] = $policy.Friendlyname + foreach ($Policy in $policies) { + self::$IDNameMap[$Policy.policyID] = $Policy.Friendlyname } # Returns an array of unique policy names. return [System.String[]]($policies.Friendlyname | Select-Object -Unique) @@ -225,8 +225,8 @@ Function Remove-WDACConfig { [System.String[]] GetValidValues() { $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$NameIDMap = @{} - foreach ($policy in $policies) { - self::$NameIDMap[$policy.Friendlyname] = $policy.policyID + foreach ($Policy in $policies) { + self::$NameIDMap[$Policy.Friendlyname] = $Policy.policyID } # Returns an array of unique policy IDs. return [System.String[]]($policies.policyID | Select-Object -Unique) From 782986d6843be38cb74484da03c8b872ca10312a Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 04:51:50 -0930 Subject: [PATCH 165/178] Improved Get-CommonWDACConfig function Also added verbose message to Update-Self function --- .../Core/Get-CommonWDACConfig.psm1 | 8 +++++++- .../WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 1 - .../WDACConfig Module Files/Shared/Update-self.psm1 | 3 +++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 9ea3e1e92..69317b0fa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -38,7 +38,10 @@ Function Get-CommonWDACConfig { # Display this message if User Configuration file is empty if ($null -eq (Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { Write-ColorfulText -Color Pink -InputText 'Your current WDAC User Configurations is empty.' - break + # set a boolean value that returns from the Process and End blocks as well + [System.Boolean]$ReturnAndDone = $true + + Return } Write-Verbose -Message 'Reading the current user configurations' @@ -57,6 +60,9 @@ Function Get-CommonWDACConfig { process {} end { + + if ($true -eq $ReturnAndDone) { return } + # Use a switch statement to check which parameter is present and output the corresponding value from the json file switch ($true) { $SignedPolicyPath.IsPresent { Write-Output -InputObject $CurrentUserConfigurations.SignedPolicyPath } diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 215470bd7..248e66979 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -143,7 +143,6 @@ Function Remove-WDACConfig { catch { Write-Error -Message 'User Configuration Json file is corrupted, deleting it...' -ErrorAction Continue Remove-CommonWDACConfig - break } } } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 index 49b369f5e..9e5234dfb 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Update-self.psm1 @@ -77,6 +77,9 @@ Function Update-self { Write-Verbose -Message 'Resetting the last update timer to the current time' Set-CommonWDACConfig -LastUpdateCheck $(Get-Date) | Out-Null } + else { + Write-Verbose -Message "Skipping online update check because the last update check was performed $TimeDiff minutes ago" + } } # Export external facing functions only, prevent internal functions from getting exported From 5f57cb85f5b05a93edab6734684edb05d8f668b0 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 05:17:35 -0930 Subject: [PATCH 166/178] Make sure the OS is Windows --- WDACConfig/WDACConfig Module Files/Preloader.ps1 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/WDACConfig/WDACConfig Module Files/Preloader.ps1 b/WDACConfig/WDACConfig Module Files/Preloader.ps1 index d85f69e6f..675dc9dfb 100644 --- a/WDACConfig/WDACConfig Module Files/Preloader.ps1 +++ b/WDACConfig/WDACConfig Module Files/Preloader.ps1 @@ -1,3 +1,7 @@ +if (!$IsWindows) { + Throw 'The WDACConfig module only runs on Windows operation systems.' +} + # Specifies that the WDACConfig module requires Administrator privileges #Requires -RunAsAdministrator From ed276d29e7f9070aaeda1f6a3813f1e2193af0ce Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 06:00:54 -0930 Subject: [PATCH 167/178] Improvements to detecting parameters --- .../Core/Remove-CommonWDACConfig.psm1 | 12 +++++++++++- .../Core/Set-CommonWDACConfig.psm1 | 11 ++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index f4f39bd30..c27204096 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -27,7 +27,17 @@ Function Remove-CommonWDACConfig { } # Delete the entire User Configs if a more specific parameter wasn't used - if ($PSBoundParameters.Count -eq 0) { + # This method is better than $PSBoundParameters since it also contains common parameters + if ( + !$CertCN, + !$CertPath, + !$SignToolPath, + !$UnsignedPolicyPath, + !$SignedPolicyPath, + !$StrictKernelPolicyGUID, + !$StrictKernelNoFlightRootsPolicyGUID, + !$LastUpdateCheck + ) { Remove-Item -Path "$UserAccountDirectoryPath\.WDACConfig\" -Recurse -Force Write-Verbose -Message 'User Configurations for WDACConfig module have been deleted.' diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 83b7bbfa2..1cfcf71b0 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -65,7 +65,16 @@ Function Set-CommonWDACConfig { Write-Verbose -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' } - if ($PSBoundParameters.Count -eq 0) { + if ( + !$CertCN, + !$CertPath, + !$SignToolPath, + !$UnsignedPolicyPath, + !$SignedPolicyPath, + !$StrictKernelPolicyGUID, + !$StrictKernelNoFlightRootsPolicyGUID, + !$LastUpdateCheck + ) { Throw 'No parameter was selected.' } From aed3f518acbe4895308ed7e996576a37fe9c6429 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 06:05:13 -0930 Subject: [PATCH 168/178] Fixed parameter detection --- .../Core/Remove-CommonWDACConfig.psm1 | 11 +---------- .../Core/Set-CommonWDACConfig.psm1 | 11 +---------- 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 index c27204096..a0bad647a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-CommonWDACConfig.psm1 @@ -28,16 +28,7 @@ Function Remove-CommonWDACConfig { # Delete the entire User Configs if a more specific parameter wasn't used # This method is better than $PSBoundParameters since it also contains common parameters - if ( - !$CertCN, - !$CertPath, - !$SignToolPath, - !$UnsignedPolicyPath, - !$SignedPolicyPath, - !$StrictKernelPolicyGUID, - !$StrictKernelNoFlightRootsPolicyGUID, - !$LastUpdateCheck - ) { + if (!$CertCN -And !$CertPath -And !$SignToolPath -And !$UnsignedPolicyPath -And !$SignedPolicyPath -And !$StrictKernelPolicyGUID -And !$StrictKernelNoFlightRootsPolicyGUID -And !$LastUpdateCheck) { Remove-Item -Path "$UserAccountDirectoryPath\.WDACConfig\" -Recurse -Force Write-Verbose -Message 'User Configurations for WDACConfig module have been deleted.' diff --git a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 index 1cfcf71b0..0f70cd233 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Set-CommonWDACConfig.psm1 @@ -65,16 +65,7 @@ Function Set-CommonWDACConfig { Write-Verbose -Message 'The UserConfigurations.json file in \.WDACConfig\ folder has been created because it did not exist.' } - if ( - !$CertCN, - !$CertPath, - !$SignToolPath, - !$UnsignedPolicyPath, - !$SignedPolicyPath, - !$StrictKernelPolicyGUID, - !$StrictKernelNoFlightRootsPolicyGUID, - !$LastUpdateCheck - ) { + if (!$CertCN -And !$CertPath -And !$SignToolPath -And !$UnsignedPolicyPath -And !$SignedPolicyPath -And !$StrictKernelPolicyGUID -And !$StrictKernelNoFlightRootsPolicyGUID -And !$LastUpdateCheck) { Throw 'No parameter was selected.' } From e22b61923018276e925f30ed0d0c178b01c7c804 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 06:44:00 -0930 Subject: [PATCH 169/178] Improved text colors --- .../Core/Deploy-SignedWDACConfig.psm1 | 12 ++++---- .../Core/Edit-SignedWDACConfig.psm1 | 30 +++++++++---------- .../Core/Edit-WDACConfig.psm1 | 30 +++++++++---------- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 12 ++++---- .../Core/New-SupplementalWDACConfig.psm1 | 12 ++++---- .../Core/New-WDACConfig.psm1 | 22 +++++++------- .../Core/Remove-WDACConfig.psm1 | 6 ++-- .../Shared/Get-BlockRulesMeta.psm1 | 2 +- 9 files changed, 64 insertions(+), 64 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index 67ebcd435..a3786b126 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -186,9 +186,9 @@ Function Deploy-SignedWDACConfig { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-Host -Object "`npolicy with the following details has been Signed and Deployed in Enforced Mode:" -ForegroundColor Green - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID`n" + Write-Host -Object 'policy with the following details has been Signed and Deployed in Enforced Mode:' -ForegroundColor Green + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path ".\$PolicyID.cip" -Force @@ -249,9 +249,9 @@ Function Deploy-SignedWDACConfig { } else { - Write-Host -Object "`npolicy with the following details has been Signed and is ready for deployment:" -ForegroundColor Green - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID`n" + Write-Host -Object 'policy with the following details has been Signed and is ready for deployment:' -ForegroundColor Green + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID`n" } } } diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index d6c886412..24e4c222a 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -262,9 +262,9 @@ Function Edit-SignedWDACConfig { # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:' - Write-Host -Object "PolicyName = $PolicyName" - Write-Host -Object "PolicyGUID = $PolicyID" + Write-ColorfulText -Color Lavender -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Enforced Mode:' + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item -Path '.\EnforcedMode.cip' -Force } @@ -349,9 +349,9 @@ Function Edit-SignedWDACConfig { Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" + Write-ColorfulText -Color Lavender -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" # Remove the Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force @@ -498,9 +498,9 @@ Function Edit-SignedWDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' - Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" - Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + Write-ColorfulText -Color Lavender -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyName = $SuppPolicyName" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $SuppPolicyID" Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force @@ -599,9 +599,9 @@ Function Edit-SignedWDACConfig { Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" + Write-ColorfulText -Color Lavender -InputText 'The Base policy with the following details has been Re-Signed and Re-Deployed in Audit Mode:' + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" # Remove the Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force @@ -932,9 +932,9 @@ Function Edit-SignedWDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' - Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" - Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + Write-ColorfulText -Color Lavender -InputText 'Supplemental policy with the following details has been Signed and Deployed in Enforced Mode:' + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyName = $SuppPolicyName" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $SuppPolicyID" Write-Verbose -Message 'Removing the signed Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 77670ca1d..9484a586e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -198,9 +198,9 @@ Function Edit-WDACConfig { # Deploy Enforced mode CIP &'C:\Windows\System32\CiTool.exe' --update-policy '.\EnforcedMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Enforced Mode:' - Write-Host -Object "PolicyName = $PolicyName" - Write-Host -Object "PolicyGUID = $PolicyID" + Write-ColorfulText -Color Lavender -InputText 'The Base policy with the following details has been Re-Deployed in Enforced Mode:' + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" # Remove Enforced Mode CIP Remove-Item -Path '.\EnforcedMode.cip' -Force } @@ -258,9 +258,9 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" + Write-ColorfulText -Color Lavender -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force @@ -386,9 +386,9 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been deployed in Enforced Mode:' - Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" - Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + Write-ColorfulText -Color Lavender -InputText 'Supplemental policy with the following details has been deployed in Enforced Mode:' + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyName = $SuppPolicyName" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $SuppPolicyID" Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force @@ -461,9 +461,9 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Audit mode CIP' &'C:\Windows\System32\CiTool.exe' --update-policy '.\AuditMode.cip' -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID" + Write-ColorfulText -Color Lavender -InputText 'The Base policy with the following details has been Re-Deployed in Audit Mode:' + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" # Remove Audit Mode CIP Remove-Item -Path '.\AuditMode.cip' -Force @@ -770,9 +770,9 @@ Function Edit-WDACConfig { Write-Verbose -Message 'Deploying the Supplemental policy' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$SuppPolicyID.cip" -json | Out-Null - Write-ColorfulText -Color TeaGreen -InputText 'Supplemental policy with the following details has been deployed in Enforced Mode:' - Write-Output -InputObject "SupplementalPolicyName = $SuppPolicyName" - Write-Output -InputObject "SupplementalPolicyGUID = $SuppPolicyID" + Write-ColorfulText -Color Lavender -InputText 'Supplemental policy with the following details has been deployed in Enforced Mode:' + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyName = $SuppPolicyName" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $SuppPolicyID" Write-Verbose -Message 'Removing the Supplemental policy CIP file after deployment' Remove-Item -Path ".\$SuppPolicyID.cip" -Force diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index 69317b0fa..e732f1e9b 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -37,7 +37,7 @@ Function Get-CommonWDACConfig { # Display this message if User Configuration file is empty if ($null -eq (Get-Content -Path "$UserAccountDirectoryPath\.WDACConfig\UserConfigurations.json")) { - Write-ColorfulText -Color Pink -InputText 'Your current WDAC User Configurations is empty.' + Write-Verbose -Message 'Your current WDAC User Configurations is empty.' # set a boolean value that returns from the Process and End blocks as well [System.Boolean]$ReturnAndDone = $true diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index a6db1b3f5..86120daaa 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -162,8 +162,8 @@ Function New-DenyWDACConfig { Write-Verbose -Message 'Converting the policy XML to .CIP' ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null - Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" - Write-Output -InputObject "DenyPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText "DenyPolicyFile = DenyPolicy $PolicyName.xml" + Write-ColorfulText -Color MintGreen -InputText "DenyPolicyGUID = $PolicyID" if (!$Debug) { Remove-Item -Path '.\ProgramDir_ScanResults*.xml' -Force @@ -225,8 +225,8 @@ Function New-DenyWDACConfig { Set-HVCIOptions -Strict -FilePath "DenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "DenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null - Write-Output -InputObject "DenyPolicyFile = DenyPolicy $PolicyName.xml" - Write-Output -InputObject "DenyPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText "DenyPolicyFile = DenyPolicy $PolicyName.xml" + Write-ColorfulText -Color MintGreen -InputText "DenyPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null @@ -279,8 +279,8 @@ Function New-DenyWDACConfig { Set-HVCIOptions -Strict -FilePath ".\AppxDenyPolicy $PolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\AppxDenyPolicy $PolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null - Write-Output -InputObject "DenyPolicyFile = AppxDenyPolicy $PolicyName.xml" - Write-Output -InputObject "DenyPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText "DenyPolicyFile = AppxDenyPolicy $PolicyName.xml" + Write-ColorfulText -Color MintGreen -InputText "DenyPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 9c437405a..d3927b078 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -166,8 +166,8 @@ Function New-SupplementalWDACConfig { Set-HVCIOptions -Strict -FilePath "SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath "SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null - Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" - Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null @@ -200,8 +200,8 @@ Function New-SupplementalWDACConfig { Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null - Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" - Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null @@ -255,8 +255,8 @@ Function New-SupplementalWDACConfig { Set-HVCIOptions -Strict -FilePath ".\SupplementalPolicy $SuppPolicyName.xml" ConvertFrom-CIPolicy -XmlFilePath ".\SupplementalPolicy $SuppPolicyName.xml" -BinaryFilePath "$PolicyID.cip" | Out-Null - Write-Output -InputObject "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" - Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyFile = SupplementalPolicy $SuppPolicyName.xml" + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $PolicyID" if ($Deploy) { &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 1a6f319e3..4ad2f9925 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -214,7 +214,7 @@ Function New-WDACConfig { Invoke-Command -ScriptBlock $DriversBlockListInfoGatheringSCRIPTBLOCK # Display the result - Write-Output -InputObject 'PolicyFile = Microsoft recommended driver block rules.xml' + Write-ColorfulText -Color MintGreen -InputText 'PolicyFile = Microsoft recommended driver block rules.xml' } } @@ -277,8 +277,8 @@ Function New-WDACConfig { Remove-Item -Path '.\AllowMicrosoft.xml', 'Microsoft recommended block rules.xml' -Force Write-Verbose -Message 'Displaying the outout' - Write-Output -InputObject 'PolicyFile = AllowMicrosoftPlusBlockRules.xml' - Write-Output -InputObject "BinaryFile = $PolicyID.cip" + Write-ColorfulText -Color MintGreen -InputText 'PolicyFile = AllowMicrosoftPlusBlockRules.xml' + Write-ColorfulText -Color MintGreen -InputText "BinaryFile = $PolicyID.cip" if ($Deploy -and $MakeAllowMSFTWithBlockRules) { Write-Verbose -Message 'Deploying the AllowMicrosoftPlusBlockRules.xml policy' @@ -403,8 +403,8 @@ Function New-WDACConfig { } Write-Verbose -Message 'Displaying the output' - Write-Output -InputObject 'PolicyFile = DefaultWindowsPlusBlockRules.xml' - Write-Output -InputObject "BinaryFile = $PolicyID.cip" + Write-ColorfulText -Color MintGreen -InputText 'PolicyFile = DefaultWindowsPlusBlockRules.xml' + Write-ColorfulText -Color MintGreen -InputText "BinaryFile = $PolicyID.cip" if ($Deploy -and $MakeDefaultWindowsWithBlockRules) { Write-Verbose -Message 'Deploying the DefaultWindowsPlusBlockRules.xml policy' @@ -763,11 +763,11 @@ Function New-WDACConfig { #Endregion Supplemental-Policy-Processing - Write-Output -InputObject "BasePolicyFile = $BasePolicy" - Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" + Write-ColorfulText -Color MintGreen -InputText "BasePolicyFile = $BasePolicy" + Write-ColorfulText -Color MintGreen -InputText "BasePolicyGUID = $BasePolicyID" - Write-Output -InputObject 'SupplementalPolicyFile = SupplementalPolicy.xml' - Write-Output -InputObject "SupplementalPolicyGUID = $PolicyID" + Write-ColorfulText -Color MintGreen -InputText 'SupplementalPolicyFile = SupplementalPolicy.xml' + Write-ColorfulText -Color MintGreen -InputText "SupplementalPolicyGUID = $PolicyID" if (-NOT $Debug) { Remove-Item -Path 'AuditLogsPolicy_NoDeletedFiles.xml', 'FileRulesAndFileRefs.txt', 'DeletedFilesHashes.xml' -Force -ErrorAction SilentlyContinue @@ -859,8 +859,8 @@ Function New-WDACConfig { } Write-Verbose -Message 'Displaying the output' - Write-Output -InputObject 'BasePolicyFile = SignedAndReputable.xml' - Write-Output -InputObject "BasePolicyGUID = $BasePolicyID" + Write-ColorfulText -Color MintGreen -InputText 'BasePolicyFile = SignedAndReputable.xml' + Write-ColorfulText -Color MintGreen -InputText "BasePolicyGUID = $BasePolicyID" } # Script block that is used to supply extra information regarding Microsoft recommended driver block rules in commands that use them diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 248e66979..8b2f8831c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -321,9 +321,9 @@ Function Remove-WDACConfig { Write-Verbose -Message 'Deploying the newly signed CIP file' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-Host -Object "`nPolicy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green - Write-Output -InputObject "PolicyName = $PolicyName" - Write-Output -InputObject "PolicyGUID = $PolicyID`n" + Write-Host -Object "Policy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green + Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" + Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" } } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 9f183b05d..4eb74049f 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -21,7 +21,7 @@ Function Get-BlockRulesMeta { Set-HVCIOptions -Strict -FilePath '.\Microsoft recommended block rules.xml' # Display the result - Write-Output -InputObject 'PolicyFile = Microsoft recommended block rules.xml' + Write-ColorfulText -Color MintGreen -InputText 'PolicyFile = Microsoft recommended block rules.xml' } # Export external facing functions only, prevent internal functions from getting exported From 1655a6d5a4aeb8190f390eb25b2d423f6f315e0a Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 06:48:27 -0930 Subject: [PATCH 170/178] Imported missing module in Get-BlockRulesMeta --- WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 8b2f8831c..77c6695b3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -321,7 +321,7 @@ Function Remove-WDACConfig { Write-Verbose -Message 'Deploying the newly signed CIP file' &'C:\Windows\System32\CiTool.exe' --update-policy ".\$PolicyID.cip" -json | Out-Null - Write-Host -Object "Policy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." -ForegroundColor Green + Write-ColorfulText -Color Lavender -InputText "Policy with the following details has been Re-signed and Re-deployed in Unsigned mode.`nPlease restart your system." Write-ColorfulText -Color MintGreen -InputText "PolicyName = $PolicyName" Write-ColorfulText -Color MintGreen -InputText "PolicyGUID = $PolicyID" } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 4eb74049f..34eab8008 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -12,6 +12,9 @@ Function Get-BlockRulesMeta { # Importing the $PSDefaultParameterValues to the current session, prior to everything else . "$ModuleRootPath\CoreExt\PSDefaultParameterValues.ps1" + # Importing the required sub-modules + Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force + [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force # Removing empty lines from policy file From 3da6f5780b200083ecdebff16f8a70b718a7ca65 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 08:19:51 -0930 Subject: [PATCH 171/178] Fixed a bug in Policynames detection --- WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 77c6695b3..09aebd083 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -63,7 +63,7 @@ Function Remove-WDACConfig { # Additionally, if the policy name contains spaces, it's enclosed in single quotes to ensure it's treated as a single argument. # This is achieved using the Compare-Object cmdlet to compare the existing and candidate values, and outputting the resulting matches. # For each resulting match, it checks if the match contains a space, if so, it's enclosed in single quotes, if not, it's returned as is. - (Compare-Object -PassThru $Candidates $Existing | Where-Object -FilterScript { SideIndicator -EQ '<=' }). + (Compare-Object -PassThru $Candidates $Existing | Where-Object -Property SideIndicator -EQ '<=' ). ForEach({ if ($_ -match ' ') { "'{0}'" -f $_ } else { $_ } }) })] [ValidateScript({ From fa902564557c451298bf8aa2049ab9d6af5b2340 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 08:29:21 -0930 Subject: [PATCH 172/178] Improved cmdlet parameters --- .../Core/Remove-WDACConfig.psm1 | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index 09aebd083..df859a3e4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -39,11 +39,11 @@ Function Remove-WDACConfig { # Get a list of policies using the CiTool, excluding system policies and policies that aren't on disk. # by adding "| Where-Object -FilterScript { $_.FriendlyName }" we make sure the auto completion works when at least one of the policies doesn't have a friendly name - $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.FriendlyName } + $Policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } | Where-Object -FilterScript { $_.FriendlyName } # Create a hashtable mapping policy names to policy IDs. This will be used later to check if a policy ID already exists. $NameIDMap = @{} - foreach ($Policy in $policies) { + foreach ($Policy in $Policies) { $NameIDMap[$Policy.Friendlyname] = $Policy.policyID } @@ -58,12 +58,12 @@ Function Remove-WDACConfig { # Filter out the policy names that are already being used or whose corresponding policy IDs are already being used. # The resulting list of policy names is what will be shown as autocomplete suggestions. - $Candidates = $policies.Friendlyname | Where-Object -FilterScript { $_ -notin $Existing -and $NameIDMap[$_] -notin $ExistingIDs } + $Candidates = $Policies.Friendlyname | Where-Object -FilterScript { $_ -notin $Existing -and $NameIDMap[$_] -notin $ExistingIDs } # Additionally, if the policy name contains spaces, it's enclosed in single quotes to ensure it's treated as a single argument. # This is achieved using the Compare-Object cmdlet to compare the existing and candidate values, and outputting the resulting matches. # For each resulting match, it checks if the match contains a space, if so, it's enclosed in single quotes, if not, it's returned as is. - (Compare-Object -PassThru $Candidates $Existing | Where-Object -Property SideIndicator -EQ '<=' ). + (Compare-Object -ReferenceObject $Candidates -DifferenceObject $Existing -PassThru | Where-Object -Property SideIndicator -EQ '<=' ). ForEach({ if ($_ -match ' ') { "'{0}'" -f $_ } else { $_ } }) })] [ValidateScript({ @@ -77,10 +77,10 @@ Function Remove-WDACConfig { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters) # Get a list of policies using the CiTool, excluding system policies and policies that aren't on disk. - $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } + $Policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } # Create a hashtable mapping policy IDs to policy names. This will be used later to check if a policy name already exists. $IDNameMap = @{} - foreach ($Policy in $policies) { + foreach ($Policy in $Policies) { $IDNameMap[$Policy.policyID] = $Policy.Friendlyname } # Get the names of existing policies that are already being used in the current command. @@ -92,7 +92,7 @@ Function Remove-WDACConfig { }, $false).Value # Filter out the policy IDs that are already being used or whose corresponding policy names are already being used. # The resulting list of policy IDs is what will be shown as autocomplete suggestions. - $Candidates = $policies.policyID | Where-Object -FilterScript { $_ -notin $Existing -and $IDNameMap[$_] -notin $ExistingNames } + $Candidates = $Policies.policyID | Where-Object -FilterScript { $_ -notin $Existing -and $IDNameMap[$_] -notin $ExistingNames } # Return the candidates. return $Candidates })] @@ -200,13 +200,13 @@ Function Remove-WDACConfig { # Defines a method to get valid policy names from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { - $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } + $Policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$IDNameMap = @{} - foreach ($Policy in $policies) { + foreach ($Policy in $Policies) { self::$IDNameMap[$Policy.policyID] = $Policy.Friendlyname } # Returns an array of unique policy names. - return [System.String[]]($policies.Friendlyname | Select-Object -Unique) + return [System.String[]]($Policies.Friendlyname | Select-Object -Unique) } # Defines a static method to get a policy name by its ID. This method will be used to check if a policy ID is already in use. @@ -222,13 +222,13 @@ Function Remove-WDACConfig { # Defines a method to get valid policy IDs from the policies on disk that aren't system policies. [System.String[]] GetValidValues() { - $policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } + $Policies = (&'C:\Windows\System32\CiTool.exe' -lp -json | ConvertFrom-Json).Policies | Where-Object -FilterScript { $_.IsOnDisk -eq 'True' } | Where-Object -FilterScript { $_.IsSystemPolicy -ne 'True' } self::$NameIDMap = @{} - foreach ($Policy in $policies) { + foreach ($Policy in $Policies) { self::$NameIDMap[$Policy.Friendlyname] = $Policy.policyID } # Returns an array of unique policy IDs. - return [System.String[]]($policies.policyID | Select-Object -Unique) + return [System.String[]]($Policies.policyID | Select-Object -Unique) } # Defines a static method to get a policy ID by its name. This method will be used to check if a policy name is already in use. From d6d9592332d44afcd1c5e93ed163cf2c67b60411 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 10:42:27 -0930 Subject: [PATCH 173/178] Fixed Get-BlockRulesMeta's output --- .../WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 24e4c222a..6f352934f 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -1046,7 +1046,7 @@ Function Edit-SignedWDACConfig { if ($UpdateBasePolicy) { Write-Verbose -Message 'Getting the Microsoft recommended block rules by calling the Get-BlockRulesMeta function' - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta 6> $null Write-Verbose -Message 'Determining the type of the new base policy' switch ($NewBasePolicyType) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index 9484a586e..f5b78aeb4 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -858,7 +858,7 @@ Function Edit-WDACConfig { if ($UpdateBasePolicy) { Write-Verbose -Message 'Getting the Microsoft recommended block rules by calling the Get-BlockRulesMeta function' - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta 6> $null Write-Verbose -Message 'Determining the type of the new base policy' switch ($NewBasePolicyType) { diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 4ad2f9925..1f56e3c9e 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -238,7 +238,7 @@ Function New-WDACConfig { ) # Get the latest Microsoft recommended block rules Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta 6> $null Write-Verbose -Message 'Copying the AllowMicrosoft.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\AllowMicrosoft.xml' -Destination 'AllowMicrosoft.xml' -Force @@ -309,7 +309,7 @@ Function New-WDACConfig { param() Write-Verbose -Message 'Getting the latest Microsoft recommended block rules' - Get-BlockRulesMeta | Out-Null + Get-BlockRulesMeta 6> $null Write-Verbose -Message 'Copying the DefaultWindows_Enforced.xml from Windows directory to the current working directory' Copy-Item -Path 'C:\Windows\schemas\CodeIntegrity\ExamplePolicies\DefaultWindows_Enforced.xml' -Destination 'DefaultWindows_Enforced.xml' -Force From e2b8c4c9db0da537bc44793380102d3dfd8f6970 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 11:13:12 -0930 Subject: [PATCH 174/178] Fixed double parameter names --- WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 index df859a3e4..dfc5ca9cc 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Remove-WDACConfig.psm1 @@ -274,7 +274,7 @@ Function Remove-WDACConfig { # Looping over each SupplementalPolicySigner and removing it $SuppSingerIDs | ForEach-Object -Process { - $PolContent = Get-Content -Path -Raw -Path $PolicyPath + $PolContent = Get-Content -Raw -Path $PolicyPath $PolContent -match "" | Out-Null $PolContent = $PolContent -replace $Matches[0], '' Set-Content -Value $PolContent -Path $PolicyPath From c4cd70a83b3f4062b6ed7f8a5980aabe84daf39f Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 11:31:46 -0930 Subject: [PATCH 175/178] Improved verbosity of New-DenyWDACConfig --- .../Core/New-DenyWDACConfig.psm1 | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 86120daaa..0b9ec46d2 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -172,11 +172,9 @@ Function New-DenyWDACConfig { if ($Deploy) { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - - Write-Host -NoNewline -Object "`n$PolicyID.cip for " -ForegroundColor Green - Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta - Write-Host -Object ' has been deployed.' -ForegroundColor Green - + + Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } @@ -229,10 +227,12 @@ Function New-DenyWDACConfig { Write-ColorfulText -Color MintGreen -InputText "DenyPolicyGUID = $PolicyID" if ($Deploy) { + Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - Write-Host -NoNewline -Object "`n$PolicyID.cip for " -ForegroundColor Green - Write-Host -NoNewline -Object "$PolicyName" -ForegroundColor Magenta - Write-Host -Object ' has been deployed.' -ForegroundColor Green + + Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." + + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } } @@ -283,8 +283,12 @@ Function New-DenyWDACConfig { Write-ColorfulText -Color MintGreen -InputText "DenyPolicyGUID = $PolicyID" if ($Deploy) { + Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null + Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." + + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } } From d26dd7748632b77a01e8826916261c6f7cefb218 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 11:32:33 -0930 Subject: [PATCH 176/178] Removed trailing whitespaces --- .../Core/Get-CommonWDACConfig.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 index e732f1e9b..66fd80281 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Get-CommonWDACConfig.psm1 @@ -60,7 +60,7 @@ Function Get-CommonWDACConfig { process {} end { - + if ($true -eq $ReturnAndDone) { return } # Use a switch statement to check which parameter is present and output the corresponding value from the json file diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 0b9ec46d2..8f81fc2e5 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -172,9 +172,9 @@ Function New-DenyWDACConfig { if ($Deploy) { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." - + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } @@ -229,7 +229,7 @@ Function New-DenyWDACConfig { if ($Deploy) { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." Write-Verbose -Message 'Removing the .CIP file after deployment' @@ -285,9 +285,9 @@ Function New-DenyWDACConfig { if ($Deploy) { Write-Verbose -Message 'Deploying the policy' &'C:\Windows\System32\CiTool.exe' --update-policy "$PolicyID.cip" -json | Out-Null - + Write-ColorfulText -Color Pink -InputText "A Deny Base policy with the name $PolicyName has been deployed." - + Write-Verbose -Message 'Removing the .CIP file after deployment' Remove-Item -Path "$PolicyID.cip" -Force } From c50cdeb1531626e4f62ba5fe53818f246bb2f60b Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 11:43:54 -0930 Subject: [PATCH 177/178] Changed a bunch of Debug messages to Verbose --- .../Core/Deploy-SignedWDACConfig.psm1 | 9 +++---- .../Core/Edit-SignedWDACConfig.psm1 | 26 +++++++++---------- .../Core/Edit-WDACConfig.psm1 | 2 +- .../Core/New-DenyWDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 2 +- 5 files changed, 19 insertions(+), 22 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index a3786b126..ea37bea22 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -47,10 +47,7 @@ Function Deploy-SignedWDACConfig { # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - - # Detecting if Debug switch is used, will do debugging actions based on that - $PSBoundParameters.Debug.IsPresent ? ([System.Boolean]$Debug = $true) : ([System.Boolean]$Debug = $false) | Out-Null - + #Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertPath -or !$CertCN) { @@ -168,8 +165,8 @@ Function Deploy-SignedWDACConfig { 'Wait' = $true 'ErrorAction' = 'Stop' } - # Hide the SignTool.exe's normal output unless -Debug parameter was used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Hide the SignTool.exe's normal output unless -Verbose parameter was used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Write-Verbose -Message 'Signing the policy with the specified certificate' diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index 6f352934f..e9b1275e8 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -327,8 +327,8 @@ Function Edit-SignedWDACConfig { 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + } # Only show the output of SignTool if Verbose switch is used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams } @@ -482,8 +482,8 @@ Function Edit-SignedWDACConfig { 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + } # Only show the output of SignTool if Verbose switch is used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' @@ -577,8 +577,8 @@ Function Edit-SignedWDACConfig { 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + } # Only show the output of SignTool if Verbose switch is used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Start-Process @ProcessParams } @@ -861,7 +861,7 @@ Function Edit-SignedWDACConfig { Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null # Delete these extra files unless user uses -Debug parameter - if (-NOT $Debug) { + if (!$Debug) { Remove-Item -Path '.\RulesForFilesNotInUserSelectedPaths.xml', '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\KernelProtectedFiles.xml', '.\DeletedFileHashesEventsPolicy.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\KernelProtectedFiles.txt', '.\FileRulesAndFileRefs.txt' -Force -ErrorAction SilentlyContinue @@ -916,8 +916,8 @@ Function Edit-SignedWDACConfig { 'Wait' = $true 'ErrorAction' = 'Stop' } - # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + # Only show the output of SignTool if Verbose switch is used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' @@ -1020,8 +1020,8 @@ Function Edit-SignedWDACConfig { 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + } # Only show the output of SignTool if Verbose switch is used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Write-Verbose -Message 'Signing the Supplemental policy with the specified cert' @@ -1191,8 +1191,8 @@ Function Edit-SignedWDACConfig { 'NoNewWindow' = $true 'Wait' = $true 'ErrorAction' = 'Stop' - } # Only show the output of SignTool if Debug switch is used - if (!$Debug) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } + } # Only show the output of SignTool if Verbose switch is used + if (!$Verbose) { $ProcessParams['RedirectStandardOutput'] = 'NUL' } # Sign the files with the specified cert Write-Verbose -Message 'Signing the base policy with the specified cert' diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index f5b78aeb4..d8e825963 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -723,7 +723,7 @@ Function Edit-WDACConfig { Merge-CIPolicy -PolicyPaths $PolicyXMLFilesArray -OutputFilePath ".\SupplementalPolicy $SuppPolicyName.xml" | Out-Null # Delete these extra files unless user uses -Debug parameter - if (-NOT $Debug) { + if (!$Debug) { Remove-Item -Path '.\RulesForFilesNotInUserSelectedPaths.xml', '.\ProgramDir_ScanResults*.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\KernelProtectedFiles.xml', '.\DeletedFileHashesEventsPolicy.xml' -Force -ErrorAction SilentlyContinue Remove-Item -Path '.\KernelProtectedFiles.txt', '.\FileRulesAndFileRefs.txt' -Force -ErrorAction SilentlyContinue diff --git a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 index 8f81fc2e5..9cefed301 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-DenyWDACConfig.psm1 @@ -241,7 +241,7 @@ Function New-DenyWDACConfig { if ($InstalledAppXPackages) { do { Get-AppxPackage -Name $PackageName - Write-Debug -Message "This is the Selected package name $PackageName" + Write-Verbose -Message "This is the Selected package name $PackageName" $Question = Read-Host -Prompt "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit`n" } until ( (($Question -eq 1) -or ($Question -eq 2)) diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index d3927b078..3f8108d07 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -213,7 +213,7 @@ Function New-SupplementalWDACConfig { if ($InstalledAppXPackages) { do { Get-AppxPackage -Name $PackageName - Write-Debug -Message "This is the Selected package name $PackageName" + Write-Verbose -Message "This is the Selected package name $PackageName" $Question = Read-Host -Prompt "`nIs this the intended results based on your Installed Appx packages? Enter 1 to continue, Enter 2 to exit" } until ( (($Question -eq 1) -or ($Question -eq 2)) From 446a2ae3d867da0e388cd217074201d0494d5a77 Mon Sep 17 00:00:00 2001 From: Violet Date: Tue, 12 Dec 2023 12:19:20 -0930 Subject: [PATCH 178/178] Final optimizations before release of v0.2.7 --- .../Core/Deploy-SignedWDACConfig.psm1 | 2 +- .../Core/Edit-SignedWDACConfig.psm1 | 2 +- .../WDACConfig Module Files/Core/Edit-WDACConfig.psm1 | 2 +- .../Core/New-SupplementalWDACConfig.psm1 | 4 ++-- .../WDACConfig Module Files/Core/New-WDACConfig.psm1 | 8 ++++---- WDACConfig/WDACConfig Module Files/Preloader.ps1 | 4 ++-- .../Shared/Get-BlockRulesMeta.psm1 | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 index ea37bea22..bcd9cb3b3 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Deploy-SignedWDACConfig.psm1 @@ -47,7 +47,7 @@ Function Deploy-SignedWDACConfig { # Redirecting the Update-Self function's information Stream to $null because Write-Host # Used by Write-ColorfulText outputs to both information stream and host console if (-NOT $SkipVersionCheck) { Update-self 6> $null } - + #Region User-Configurations-Processing-Validation # If any of these parameters, that are mandatory for all of the position 0 parameters, isn't supplied by user if (!$SignToolPath -or !$CertPath -or !$CertCN) { diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 index e9b1275e8..e74616e87 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-SignedWDACConfig.psm1 @@ -716,7 +716,7 @@ Function Edit-SignedWDACConfig { Write-Verbose -Message "$_" } - Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' + Write-Verbose -Message 'Creating FileRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' [System.String]$FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes [System.String]$RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() diff --git a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 index d8e825963..ab6236142 100644 --- a/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/Edit-WDACConfig.psm1 @@ -578,7 +578,7 @@ Function Edit-WDACConfig { Write-Verbose -Message "$_" } - Write-Verbose -Message 'Creating FuleRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' + Write-Verbose -Message 'Creating FileRules and RuleRefs for files that are no longer available on the disk but were detected in event viewer logs' [System.String]$FileRulesHashesResults = Get-FileRules -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes [System.String]$RuleRefsHashesResults = (Get-RuleRefs -HashesArray $AuditEventLogsProcessingResults.DeletedFileHashes).Trim() diff --git a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 index 3f8108d07..e7e40005c 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-SupplementalWDACConfig.psm1 @@ -151,7 +151,7 @@ Function New-SupplementalWDACConfig { if ($NoScript) { $PolicyMakerHashTable['NoScript'] = $true } if (!$NoUserPEs) { $PolicyMakerHashTable['UserPEs'] = $true } - Write-ColorfulText -Color HotPink -InputText "`nGenerating Supplemental policy with the following specifications:" + Write-ColorfulText -Color HotPink -InputText 'Generating Supplemental policy with the following specifications:' $PolicyMakerHashTable Write-Host -Object '' # Create the supplemental policy via parameter splatting @@ -231,7 +231,7 @@ Function New-SupplementalWDACConfig { $Rules += New-CIPolicyRule -Package $Item } - # Create rules for each pacakge dependency, if any + # Create rules for each package dependency, if any if ($PackageDependencies) { foreach ($Item in $PackageDependencies) { $Rules += New-CIPolicyRule -Package $Item diff --git a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 index 1f56e3c9e..e70fc9887 100644 --- a/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 +++ b/WDACConfig/WDACConfig Module Files/Core/New-WDACConfig.psm1 @@ -184,7 +184,7 @@ Function New-WDACConfig { else { # Downloading the latest Microsoft Recommended Driver Block Rules from the official source Write-Verbose -Message 'Downloading the latest Microsoft Recommended Driver Block Rules from the official source' - [System.String]$DriverRules = (Invoke-WebRequest -Uri $MSFTRecommendeDriverBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' + [System.String]$DriverRules = (Invoke-WebRequest -Uri $MSFTRecommendedDriverBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' # Remove the unnecessary rules and elements - not using this one because then during the merge there will be error - The reason is that "" is the only FileruleRef in the xml and after removing it, the element will be empty Write-Verbose -Message 'Removing the allow all rules and rule refs from the policy' @@ -428,7 +428,7 @@ Function New-WDACConfig { param() Write-Verbose -Message 'Downloading the latest Microsoft recommended block rules and creating Microsoft recommended block rules TEMP.xml' - (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force + (Invoke-WebRequest -Uri $MSFTRecommendedBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force # Remove empty lines from the policy file Write-Verbose -Message 'Removing any empty lines from the Temp policy file and generating the Microsoft recommended block rules.xml' @@ -693,7 +693,7 @@ Function New-WDACConfig { if ($NoScript) { $PolicyMakerHashTable['NoScript'] = $true } if (!$NoUserPEs) { $PolicyMakerHashTable['UserPEs'] = $true } - Write-ColorfulText -Color HotPink -InputText "`nGenerating Supplemental policy with the following specifications:" + Write-ColorfulText -Color HotPink -InputText 'Generating Supplemental policy with the following specifications:' $PolicyMakerHashTable Write-Host -Object '' @@ -874,7 +874,7 @@ Function New-WDACConfig { [System.DateTime]$Date = $Response[0].commit.author.date Write-ColorfulText -Color Lavender -InputText "The document containing the drivers block list on GitHub was last updated on $Date" - [System.String]$MicrosoftRecommendeDriverBlockRules = (Invoke-WebRequest -Uri $MSFTRecommendeDriverBlockRulesURL -ProgressAction SilentlyContinue).Content + [System.String]$MicrosoftRecommendeDriverBlockRules = (Invoke-WebRequest -Uri $MSFTRecommendedDriverBlockRulesURL -ProgressAction SilentlyContinue).Content $MicrosoftRecommendeDriverBlockRules -match '(.*)' | Out-Null Write-ColorfulText -Color Pink -InputText "The current version of Microsoft recommended drivers block list is $($Matches[1])" } diff --git a/WDACConfig/WDACConfig Module Files/Preloader.ps1 b/WDACConfig/WDACConfig Module Files/Preloader.ps1 index 675dc9dfb..9873f6c99 100644 --- a/WDACConfig/WDACConfig Module Files/Preloader.ps1 +++ b/WDACConfig/WDACConfig Module Files/Preloader.ps1 @@ -7,8 +7,8 @@ if (!$IsWindows) { # Create tamper resistant global variables (if they don't already exist) try { - if ((Test-Path -Path 'Variable:\MSFTRecommendeBlockRulesURL') -eq $false) { New-Variable -Name 'MSFTRecommendeBlockRulesURL' -Value 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -Option 'Constant' -Scope 'Global' -Description 'User Mode block rules' -Force } - if ((Test-Path -Path 'Variable:\MSFTRecommendeDriverBlockRulesURL') -eq $false) { New-Variable -Name 'MSFTRecommendeDriverBlockRulesURL' -Value 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -Option 'Constant' -Scope 'Global' -Description 'Kernel Mode block rules' -Force } + if ((Test-Path -Path 'Variable:\MSFTRecommendedBlockRulesURL') -eq $false) { New-Variable -Name 'MSFTRecommendedBlockRulesURL' -Value 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/applications-that-can-bypass-wdac.md' -Option 'Constant' -Scope 'Global' -Description 'User Mode block rules' -Force } + if ((Test-Path -Path 'Variable:\MSFTRecommendedDriverBlockRulesURL') -eq $false) { New-Variable -Name 'MSFTRecommendedDriverBlockRulesURL' -Value 'https://raw.githubusercontent.com/MicrosoftDocs/windows-itpro-docs/public/windows/security/application-security/application-control/windows-defender-application-control/design/microsoft-recommended-driver-block-rules.md' -Option 'Constant' -Scope 'Global' -Description 'Kernel Mode block rules' -Force } if ((Test-Path -Path 'Variable:\UserTempDirectoryPath') -eq $false) { New-Variable -Name 'UserTempDirectoryPath' -Value ([System.IO.Path]::GetTempPath()) -Option 'Constant' -Scope 'Global' -Description 'Properly and securely retrieved Temp Directory' -Force } if ((Test-Path -Path 'Variable:\UserAccountDirectoryPath') -eq $false) { New-Variable -Name 'UserAccountDirectoryPath' -Value ((Get-CimInstance Win32_UserProfile -Filter "SID = '$([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value)'").LocalPath) -Option 'Constant' -Scope 'Global' -Description 'Securely retrieved User profile directory' -Force } if ((Test-Path -Path 'Variable:\Requiredbuild') -eq $false) { New-Variable -Name 'Requiredbuild' -Value '22621.2428' -Option 'Constant' -Scope 'Script' -Description 'Minimum required OS build number' -Force } diff --git a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 index 34eab8008..37ac18b46 100644 --- a/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 +++ b/WDACConfig/WDACConfig Module Files/Shared/Get-BlockRulesMeta.psm1 @@ -15,7 +15,7 @@ Function Get-BlockRulesMeta { # Importing the required sub-modules Import-Module -FullyQualifiedName "$ModuleRootPath\Shared\Write-ColorfulText.psm1" -Force - [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendeBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' + [System.String]$Rules = (Invoke-WebRequest -Uri $MSFTRecommendedBlockRulesURL -ProgressAction SilentlyContinue).Content -replace "(?s).*``````xml(.*)``````.*", '$1' -replace '|', '' $Rules | Out-File -FilePath '.\Microsoft recommended block rules TEMP.xml' -Force # Removing empty lines from policy file Get-Content -Path '.\Microsoft recommended block rules TEMP.xml' | Where-Object -FilterScript { $_.trim() -ne '' } | Out-File -FilePath '.\Microsoft recommended block rules.xml' -Force