Защитник Windows Device Guard и средство подготовки оборудования Защитник Windows Credential Guard

# Script to find out if a machine is Device Guard compliant.
# The script requires a driver verifier present on the system.

param([switch]$Capable, [switch]$Ready, [switch]$Enable, [switch]$Disable, $SIPolicyPath, [switch]$AutoReboot, [switch]$DG, [switch]$CG, [switch]$HVCI, [switch]$HLK, [switch]$Clear, [switch]$ResetVerifier)

Set-StrictMode -Version Latest

$path = "C:\DGLogs\"
$LogFile = $path + "DeviceGuardCheckLog.txt"

$CompatibleModules = New-Object System.Text.StringBuilder
$FailingModules = New-Object System.Text.StringBuilder
$FailingExecuteWriteCheck = New-Object System.Text.StringBuilder

$DGVerifyCrit = New-Object System.Text.StringBuilder
$DGVerifyWarn = New-Object System.Text.StringBuilder
$DGVerifySuccess = New-Object System.Text.StringBuilder


$Sys32Path = "$env:windir\system32"
$DriverPath = "$env:windir\system32\drivers"

#generated by certutil -encode
$SIPolicy_Encoded = "BQAAAA43RKLJRAZMtVH2AW5WMHbk9wcuTBkgTbfJb0SmxaI0BACNkAgAAAAAAAAA
HQAAAAIAAAAAAAAAAAAKAEAAAAAMAAAAAQorBgEEAYI3CgMGDAAAAAEKKwYBBAGC
NwoDBQwAAAABCisGAQQBgjc9BAEMAAAAAQorBgEEAYI3PQUBDAAAAAEKKwYBBAGC
NwoDFQwAAAABCisGAQQBgjdMAwEMAAAAAQorBgEEAYI3TAUBDAAAAAEKKwYBBAGC
N0wLAQEAAAAGAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AQAAAAYAAAABAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA
BgAAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAGAAAA
AQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAUAAAABAAAA
AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="

function Log($message)
{
    $message | Out-File $LogFile -Append -Force
}

function LogAndConsole($message)
{
    Write-Host $message
    Log $message
}

function LogAndConsoleWarning($message)
{
    Write-Host $message -foregroundcolor "Yellow"
    Log $message
}

function LogAndConsoleSuccess($message)
{
    Write-Host $message -foregroundcolor "Green"
    Log $message
}

function LogAndConsoleError($message)
{
    Write-Host $message -foregroundcolor "Red"
    Log $message
}

function IsExempted([System.IO.FileInfo] $item)
{
    $cert = (Get-AuthenticodeSignature $item.FullName).SignerCertificate
    if($cert.ToString().Contains("CN=Microsoft Windows, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"))
    {
        Log $item.FullName + "MS Exempted"
        return 1
    }
    else
    {
        Log $item.FullName + "Not-exempted"
        Log $cert.ToString()
        return 0
    }
}

function CheckExemption($_ModName)
{
    $mod1 = Get-ChildItem $Sys32Path $_ModName
    $mod2 = Get-ChildItem $DriverPath $_ModName
    if($mod1)
    {
        Log "NonDriver module" + $mod1.FullName
        return IsExempted($mod1)
    }
    elseif($mod2)
    {
        Log "Driver Module" + $mod2.FullName
        return IsExempted($mod2)
    }

}

function CheckFailedDriver($_ModName, $CIStats)
{
    Log "Module: " $_ModName.Trim()
    if(CheckExemption($_ModName.Trim()) - eq 1)
    {
        $CompatibleModules.AppendLine("Windows Signed: " + $_ModName.Trim()) | Out-Null
        return
    }
    $index = $CIStats.IndexOf("execute pool type count:".ToLower())
    if($index -eq -1)
    {
        return
    }
    $_tempStr = $CIStats.Substring($index)
    $Result = "PASS"
    $separator = "`r`n",""
    $option = [System.StringSplitOptions]::RemoveEmptyEntries
    $stats = $_tempStr.Split($separator,$option)
    Log $stats.Count

    $FailingStat = ""
    foreach( $stat in $stats)
    {
        $_t =$stat.Split(":")
        if($_t.Count -eq 2 -and $_t[1].trim() -ne "0")
        {
            $Result = "FAIL"
            $FailingStat = $stat
            break
        }
    }
    if($Result.Contains("PASS"))
    {
        $CompatibleModules.AppendLine($_ModName.Trim()) | Out-Null
    }
    elseif($FailingStat.Trim().Contains("execute-write"))
    {
        $FailingExecuteWriteCheck.AppendLine("Module: "+ $_ModName.Trim() + "`r`n`tReason: " + $FailingStat.Trim() ) | Out-Null
    }
    else
    {
        $FailingModules.AppendLine("Module: "+ $_ModName.Trim() + "`r`n`tReason: " + $FailingStat.Trim() ) | Out-Null
    }
    Log "Result: " $Result
}

function ListCIStats($_ModName, $str1)
{
    $i1 = $str1.IndexOf("Code Integrity Statistics:".ToLower())
    if($i1 -eq -1 )
    {
        Log "String := " $str1
        Log "Warning! CI Stats are missing for " $_ModName
        return
    }
    $temp_str1 = $str1.Substring($i1)
    $CIStats = $temp_str1.Substring(0).Trim()

    CheckFailedDriver $_ModName $CIStats
}

function ListDrivers($str)
{
    $_tempStr= $str

    $separator = "module:",""
    $option = [System.StringSplitOptions]::RemoveEmptyEntries
    $index1 = $_tempStr.IndexOf("MODULE:".ToLower())
    if($index1 -lt 0)
    {
        return
    }
    $_tempStr = $_tempStr.Substring($Index1)
    $_SplitStr = $_tempStr.Split($separator,$option)


    Log $_SplitStr.Count
    LogAndConsole "Verifying each module please wait ... "
    foreach($ModuleDetail in $_Splitstr)
    {
        #LogAndConsole $Module
        $Index2 = $ModuleDetail.IndexOf("(")
        if($Index2 -eq -1)
        {
            "Skipping .."
            continue
        }
        $ModName = $ModuleDetail.Substring(0,$Index2-1)
        Log "Driver: " $ModName
        Log "Processing module: " $ModName
        ListCIStats $ModName $ModuleDetail
    }

    $DriverScanCompletedMessage = "Completed scan. List of Compatible Modules can be found at " + $LogFile
    LogAndConsole $DriverScanCompletedMessage

    if($FailingModules.Length -gt 0 -or $FailingExecuteWriteCheck.Length -gt 0 )
    {
        $WarningMessage = "Incompatible HVCI Kernel Driver Modules found"
        if($HLK)
        {
            LogAndConsoleError $WarningMessage
        }
        else
        {
            LogAndConsoleWarning $WarningMessage
        }

        LogAndConsoleError $FailingExecuteWriteCheck.ToString()
        if($HLK)
        {
            LogAndConsoleError $FailingModules.ToString()
        }
        else
        {
            LogAndConsoleWarning $FailingModules.ToString()
        }
        if($FailingModules.Length -ne 0 -or $FailingExecuteWriteCheck.Length -ne 0 )
        {
            if($HLK)
            {
                $DGVerifyCrit.AppendLine($WarningMessage) | Out-Null
            }
            else
            {
                $DGVerifyWarn.AppendLine($WarningMessage) | Out-Null
            }
        }
    }
    else
    {
        LogAndConsoleSuccess "No Incompatible Drivers found"
    }
}

function ListSummary()
{
    if($DGVerifyCrit.Length -ne 0 )
    {
        LogAndConsoleError "Machine is not Device Guard / Credential Guard compatible because of the following:"
        LogAndConsoleError $DGVerifyCrit.ToString()
        LogAndConsoleWarning $DGVerifyWarn.ToString()
        if(!$HVCI -and !$DG)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "CG_Capable" /t REG_DWORD /d 0 /f '
        }
        if(!$CG)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "DG_Capable" /t REG_DWORD /d 0 /f '
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "HVCI_Capable" /t REG_DWORD /d 0 /f '
        }

    }
    elseif ($DGVerifyWarn.Length -ne 0 )
    {
        LogAndConsoleSuccess "Device Guard / Credential Guard can be enabled on this machine.`n"
        LogAndConsoleWarning "The following additional qualifications, if present, can enhance the security of Device Guard / Credential Guard on this system:"
        LogAndConsoleWarning $DGVerifyWarn.ToString()
        if(!$HVCI -and !$DG)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "CG_Capable" /t REG_DWORD /d 1 /f '
        }
        if(!$CG)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "DG_Capable" /t REG_DWORD /d 1 /f '
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "HVCI_Capable" /t REG_DWORD /d 1 /f '
        }
    }
    else
    {
        LogAndConsoleSuccess "Machine is Device Guard / Credential Guard Ready.`n"
        if(!$HVCI -and !$DG)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "CG_Capable" /t REG_DWORD /d 2 /f '
        }
        if(!$CG)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "DG_Capable" /t REG_DWORD /d 2 /f '
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "HVCI_Capable" /t REG_DWORD /d 2 /f '
        }
    }
}


function Instantiate-Kernel32 {
    try
    {
        Add-Type -TypeDefinition @"
        using System;
        using System.Diagnostics;
        using System.Runtime.InteropServices;

        public static class Kernel32
        {
            [DllImport("kernel32", SetLastError=true, CharSet = CharSet.Ansi)]
                public static extern IntPtr LoadLibrary(
                    [MarshalAs(UnmanagedType.LPStr)]string lpFileName);

            [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
                public static extern IntPtr GetProcAddress(
                    IntPtr hModule,
                    string procName);
        }

"@
    }
    catch
    {
        Log $_.Exception.Message
        LogAndConsole "Instantiate-Kernel32 failed"
    }
}

function Instantiate-HSTI {
    try
    {
        Add-Type -TypeDefinition @"
        using System;
        using System.Diagnostics;
        using System.Runtime.InteropServices;
        using System.Net;

        public static class HstiTest3
        {
            [DllImport("hstitest.dll", CharSet = CharSet.Unicode)]
            public static extern int QueryHSTIdetails(
                ref HstiOverallError pHstiOverallError,
                [In, Out] HstiProviderErrorDuple[] pHstiProviderErrors,
                ref uint pHstiProviderErrorsCount,
                byte[] hstiPlatformSecurityBlob,
                ref uint pHstiPlatformSecurityBlobBytes);

            [DllImport("hstitest.dll", CharSet = CharSet.Unicode)]
            public static extern int QueryHSTI(ref bool Pass);

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            public struct HstiProviderErrorDuple
            {
                internal uint protocolError;
                internal uint role;
                internal HstiProviderErrors providerError;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
                internal string ID;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)]
                internal string ErrorString;
            }

            [FlagsAttribute]
            public enum HstiProviderErrors : int
            {
                None              = 0x00000000,
                VersionMismatch   = 0x00000001,
                RoleUnknown       = 0x00000002,
                RoleDuplicated    = 0x00000004,
                SecurityFeatureSizeMismatch   = 0x00000008,
                SizeTooSmall      = 0x00000010,
                VerifiedMoreThanImplemented   = 0x00000020,
                VerifiedNotMatchImplemented   = 0x00000040
            }

            [FlagsAttribute]
            public enum HstiOverallError : int
            {
                None                               = 0x00000000,
                RoleTooManyPlatformReference       = 0x00000001,
                RoleTooManyIbv                     = 0x00000002,
                RoleTooManyOem                     = 0x00000004,
                RoleTooManyOdm                     = 0x00000008,
                RoleMissingPlatformReference       = 0x00000010,
                VerifiedIncomplete                 = 0x00000020,
                ProtocolErrors                     = 0x00000040,
                BlobVersionMismatch                = 0x00000080,
                PlatformSecurityVersionMismatch    = 0x00000100,
                ProviderError                      = 0x00000200
            }

        }
"@

        $LibHandle = [Kernel32]::LoadLibrary("C:\Windows\System32\hstitest.dll")
        $FuncHandle = [Kernel32]::GetProcAddress($LibHandle, "QueryHSTIdetails")
        $FuncHandle2 = [Kernel32]::GetProcAddress($LibHandle, "QueryHSTI")

        if ([System.IntPtr]::Size -eq 8)
        {
            #assuming 64 bit
            Log "`nKernel32::LoadLibrary   64bit --> 0x$("{0:X16}" -f $LibHandle.ToInt64())"
            Log "HstiTest2::QueryHSTIdetails  64bit --> 0x$("{0:X16}" -f $FuncHandle.ToInt64())"
        }
        else
        {
            return
        }
        $overallError = New-Object HstiTest3+HstiOverallError
        $providerErrorDupleCount = New-Object int
        $blobByteSize = New-Object int
        $hr = [HstiTest3]::QueryHSTIdetails([ref] $overallError, $null, [ref] $providerErrorDupleCount, $null, [ref] $blobByteSize)

        [byte[]]$blob = New-Object byte[] $blobByteSize
        [HstiTest3+HstiProviderErrorDuple[]]$providerErrors = New-Object HstiTest3+HstiProviderErrorDuple[] $providerErrorDupleCount
        $hr = [HstiTest3]::QueryHSTIdetails([ref] $overallError, $providerErrors, [ref] $providerErrorDupleCount, $blob, [ref] $blobByteSize)
        $string = $null
        $blob | foreach { $string = $string + $_.ToString("X2")+"," }

        $hstiStatus = New-Object bool
        $hr = [HstiTest3]::QueryHSTI([ref] $hstiStatus)

        LogAndConsole "HSTI Duple Count: $providerErrorDupleCount"
        LogAndConsole "HSTI Blob size: $blobByteSize"
        LogAndConsole "String: $string"
        LogAndConsole "HSTIStatus: $hstiStatus"
        if(($blobByteSize -gt 512) -and ($providerErrorDupleCount -gt 0) -and $hstiStatus)
        {
            LogAndConsoleSuccess "HSTI validation successful"
        }
        elseif(($providerErrorDupleCount -eq 0) -or ($blobByteSize -le 512))
        {
            LogAndConsoleWarning "HSTI is absent"
            $DGVerifyWarn.AppendLine("HSTI is absent") | Out-Null
        }
        else
        {
            $ErrorMessage = "HSTI validation failed"
            if($HLK)
            {
                LogAndConsoleError $ErrorMessage
                $DGVerifyCrit.AppendLine($ErrorMessage) | Out-Null
            }
            else
            {
                LogAndConsoleWarning $ErrorMessage
                $DGVerifyWarn.AppendLine("HSTI is absent") | Out-Null
            }
        }

    }
    catch
    {
        LogAndConsoleError $_.Exception.Message
        LogAndConsoleError "Instantiate-HSTI failed"
    }
}


function CheckDGRunning($_val)
{
    $DGObj = Get-CimInstance -classname Win32_DeviceGuard -namespace root\Microsoft\Windows\DeviceGuard
    for($i=0; $i -lt $DGObj.SecurityServicesRunning.length; $i++)
    {
        if($DGObj.SecurityServicesRunning[$i] -eq $_val)
        {
            return 1
        }

    }
    return 0
}

function CheckDGFeatures($_val)
{
    $DGObj = Get-CimInstance -classname Win32_DeviceGuard -namespace root\Microsoft\Windows\DeviceGuard
    Log "DG_obj $DG_obj"
    Log "DG_obj.AvailableSecurityProperties.length $DG_obj.AvailableSecurityProperties.length"
    for($i=0; $i -lt $DGObj.AvailableSecurityProperties.length; $i++)
    {
        if($DGObj.AvailableSecurityProperties[$i] -eq $_val)
        {
            return 1
        }

    }
    return 0
}

function PrintConfigCIDetails($_ConfigCIState)
{
    $_ConfigCIRunning = "Config-CI is enabled and running."
    $_ConfigCIDisabled = "Config-CI is not running."
    $_ConfigCIMode = "Not Enabled"
    switch ($_ConfigCIState)
    {
        0 { $_ConfigCIMode = "Not Enabled" }
        1 { $_ConfigCIMode = "Audit mode" }
        2 { $_ConfigCIMode = "Enforced mode" }
        default { $_ConfigCIMode = "Not Enabled" }
    }

    if($_ConfigCIState -ge 1)
    {
        LogAndConsoleSuccess "$_ConfigCIRunning ($_ConfigCIMode)"
    }
    else
    {
        LogAndConsoleWarning "$_ConfigCIDisabled ($_ConfigCIMode)"
    }
}

function PrintHVCIDetails($_HVCIState)
{
    $_HvciRunning = "HVCI is enabled and running."
    $_HvciDisabled = "HVCI is not running."

    if($_HVCIState)
    {
        LogAndConsoleSuccess $_HvciRunning
    }
    else
    {
        LogAndConsoleWarning $_HvciDisabled
    }
}

function PrintCGDetails ($_CGState)
{
    $_CGRunning = "Credential-Guard is enabled and running."
    $_CGDisabled = "Credential-Guard is not running."

    if($_CGState)
    {
        LogAndConsoleSuccess $_CGRunning
    }
    else
    {
        LogAndConsoleWarning $_CGDisabled
    }
}

if(![IO.Directory]::Exists($path))
{
    New-Item -ItemType directory -Path $path
}
else
{
    #Do Nothing!!
}

function IsRedstone
{
    $_osVersion = [environment]::OSVersion.Version
    Log $_osVersion
    #Check if build Major is Windows 10
    if($_osVersion.Major -lt 10)
    {
        return 0
    }
    #Check if the build is post Threshold2 (1511 release) => Redstone
    if($_osVersion.Build -gt 10586)
    {
        return 1
    }
    #default return False
    return 0
}

function ExecuteCommandAndLog($_cmd)
{
    try
    {
        Log "Executing: $_cmd"
        $CmdOutput = Invoke-Expression $_cmd | Out-String
        Log "Output: $CmdOutput"
    }
    catch
    {
        Log "Exception while exectuing $_cmd"
        Log $_.Exception.Message
    }


}

function PrintRebootWarning
{
    LogAndConsoleWarning "Please reboot the machine, for settings to be applied."
}

function AutoRebootHelper
{
    if($AutoReboot)
    {
        LogAndConsole "PC will restart in 30 seconds"
        ExecuteCommandAndLog 'shutdown /r /t 30'
    }
    else
    {
        PrintRebootWarning
    }

}

function VerifierReset
{
    $verifier_state = verifier /query | Out-String
    if(!$verifier_state.ToString().Contains("No drivers are currently verified."))
    {
        ExecuteCommandAndLog 'verifier.exe /reset'
    }
    AutoRebootHelper
}

function PrintHardwareReq
{
    LogAndConsole "###########################################################################"
    LogAndConsole "OS and Hardware requirements for enabling Device Guard and Credential Guard"
    LogAndConsole " 1. OS SKUs: Available only on these OS Skus - Enterprise, Server, Education and Enterprise IoT"
    LogAndConsole " 2. Hardware: Recent hardware that supports virtualization extension with SLAT"
    LogAndConsole "To learn more please visit: https://aka.ms/dgwhcr"
    LogAndConsole "########################################################################### `n"
}

function CheckDriverCompat
{
    $_HVCIState = CheckDGRunning(2)
    if($_HVCIState)
    {
        LogAndConsoleWarning "HVCI is already enabled on this machine, driver compat list might not be complete."
        LogAndConsoleWarning "Please disable HVCI and run the script again..."
    }
    $verifier_state = verifier /query | Out-String
    if($verifier_state.ToString().Contains("No drivers are currently verified."))
    {
        LogAndConsole "Enabling Driver verifier"
        verifier.exe /flags 0x02000000 /all /bootmode oneboot /log.code_integrity

        LogAndConsole "Enabling Driver Verifier and Rebooting system"
        Log $verifier_state
        LogAndConsole "Please re-execute this script after reboot...."
        if($AutoReboot)
        {
            LogAndConsole "PC will restart in 30 seconds"
            ExecuteCommandAndLog 'shutdown /r /t 30'
        }
        else
        {
            LogAndConsole "Please reboot manually and run the script again...."
        }
        exit
    }
    else
    {
        LogAndConsole "Driver verifier already enabled"
        Log $verifier_state
        ListDrivers($verifier_state.Trim().ToLowerInvariant())
    }
}
function IsDomainController
{
    $_isDC = 0
    $CompConfig = Get-WmiObject Win32_ComputerSystem
    foreach ($ObjItem in $CompConfig)
    {
        $Role = $ObjItem.DomainRole
        Log "Role=$Role"
        Switch ($Role)
        {
            0 { Log "Standalone Workstation" }
            1 { Log "Member Workstation" }
            2 { Log "Standalone Server" }
            3 { Log "Member Server" }
            4
            {
                Log "Backup Domain Controller"
                $_isDC=1
                break
            }
            5
            {
                Log "Primary Domain Controller"
                $_isDC=1
                break
            }
            default { Log "Unknown Domain Role" }
        }
    }
    return $_isDC
}

function CheckOSSKU
{
    $osname = $((Get-ComputerInfo).WindowsProductName).ToLower()
    $_SKUSupported = 0
    Log "OSNAME:$osname"
    $SKUarray = @("Enterprise", "Education", "IoT", "Windows Server")
    $HLKAllowed = @("windows 10 pro")
    foreach ($SKUent in $SKUarray)
    {
        if($osname.ToString().Contains($SKUent.ToLower()))
        {
            $_SKUSupported = 1
            break
        }
    }

    # For running HLK tests only, professional SKU's are marked as supported.
    if($HLK)
    {
        if($osname.ToString().Contains($HLKAllowed.ToLower()))
        {
            $_SKUSupported = 1
        }
    }
    $_isDomainController = IsDomainController
    if($_SKUSupported)
    {
        LogAndConsoleSuccess "This PC edition is Supported for DeviceGuard";
        if(($_isDomainController -eq 1) -and !$HVCI -and !$DG)
        {
            LogAndConsoleError "This PC is configured as a Domain Controller, Credential Guard is not supported on DC."
        }
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "OSSKU" /t REG_DWORD /d 2 /f '
    }
    else
    {
        LogAndConsoleError "This PC edition is Unsupported for Device Guard"
        $DGVerifyCrit.AppendLine("OS SKU unsupported") | Out-Null
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "OSSKU" /t REG_DWORD /d 0 /f '
    }
}

function CheckOSArchitecture
{
    $OSArch = $(Get-WmiObject win32_operatingsystem).OSArchitecture.ToLower()
    Log $OSArch
    if($OSArch -match ("^64\-?\s?bit"))
    {
        LogAndConsoleSuccess "64 bit architecture"
    }
    elseif($OSArch -match ("^32\-?\s?bit"))
    {
        LogAndConsoleError "32 bit architecture"
        $DGVerifyCrit.AppendLine("32 Bit OS, OS Architecture failure.") | Out-Null
    }
    else
    {
        LogAndConsoleError "Unknown architecture"
        $DGVerifyCrit.AppendLine("Unknown OS, OS Architecture failure.") | Out-Null
    }
}

function CheckSecureBootState
{
    try { 
        $_secureBoot = Confirm-SecureBootUEFI
    }
    catch
    {
        $_secureBoot = $false
    }
    Log $_secureBoot
    if($_secureBoot)
    {
        LogAndConsoleSuccess "Secure Boot is present"
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "SecureBoot" /t REG_DWORD /d 2 /f '
    }
    else
    {
        LogAndConsoleError "Secure Boot is absent / not enabled."
        LogAndConsoleError "If Secure Boot is supported on the system, enable Secure Boot in the BIOS and run the script again."
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "SecureBoot" /t REG_DWORD /d 0 /f '
        $DGVerifyCrit.AppendLine("Secure boot validation failed.") | Out-Null
    }
}

function CheckVirtualization
{
    $_vmmExtension = $(Get-WMIObject -Class Win32_processor).VMMonitorModeExtensions
    $_vmFirmwareExtension = $(Get-WMIObject -Class Win32_processor).VirtualizationFirmwareEnabled
    $_vmHyperVPresent =  (Get-CimInstance -Class Win32_ComputerSystem).HypervisorPresent
    Log "VMMonitorModeExtensions $_vmmExtension"
    Log "VirtualizationFirmwareEnabled $_vmFirmwareExtension"
    Log "HyperVisorPresent $_vmHyperVPresent"

    #success if either processor supports and enabled or if hyper-v is present
    if(($_vmmExtension -and $_vmFirmwareExtension) -or $_vmHyperVPresent )
    {
        LogAndConsoleSuccess "Virtualization firmware check passed"
         ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "Virtualization" /t REG_DWORD /d 2 /f '
    }
    else
    {
        LogAndConsoleError "Virtualization firmware check failed."
        LogAndConsoleError "If Virtualization extensions are supported on the system, enable hardware virtualization (Intel Virtualization Technology, Intel VT-x, Virtualization Extensions, or similar) in the BIOS and run the script again."
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "Virtualization" /t REG_DWORD /d 0 /f '
        $DGVerifyCrit.AppendLine("Virtualization firmware check failed.") | Out-Null
    }
}

function CheckTPM
{
    $TPMLockout = $(get-tpm).LockoutCount

    if($TPMLockout)
    {

        if($TPMLockout.ToString().Contains("Not Supported for TPM 1.2"))
        {
            if($HLK)
            {
                LogAndConsoleSuccess "TPM 1.2 is present."
            }
            else
            {
                $WarningMsg = "TPM 1.2 is Present. TPM 2.0 is Preferred."
                LogAndConsoleWarning $WarningMsg
                $DGVerifyWarn.AppendLine($WarningMsg) | Out-Null
            }
        }
        else
        {
            LogAndConsoleSuccess "TPM 2.0 is present."
        }
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "TPM" /t REG_DWORD /d 2 /f '
    }
    else
    {
        $WarningMsg = "TPM is absent or not ready for use"
        if($HLK)
        {
            LogAndConsoleError $WarningMsg
            $DGVerifyCrit.AppendLine($WarningMsg) | Out-Null
        }
        else
        {
            LogAndConsoleWarning $WarningMsg
            $DGVerifyWarn.AppendLine($WarningMsg) | Out-Null
        }
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "TPM" /t REG_DWORD /d 0 /f '
    }
}

function CheckSecureMOR
{
    $isSecureMOR = CheckDGFeatures(4)
    Log "isSecureMOR= $isSecureMOR "
    if($isSecureMOR -eq 1)
    {
        LogAndConsoleSuccess "Secure MOR is available"
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "SecureMOR" /t REG_DWORD /d 2 /f '
    }
    else
    {
        $WarningMsg = "Secure MOR is absent"
        if($HLK)
        {
            LogAndConsoleError $WarningMsg
            $DGVerifyCrit.AppendLine($WarningMsg) | Out-Null
        }
        else
        {
            LogAndConsoleWarning $WarningMsg
            $DGVerifyWarn.AppendLine($WarningMsg) | Out-Null
        }
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "SecureMOR" /t REG_DWORD /d 0 /f '
    }
}

function CheckNXProtection
{
    $isNXProtected = CheckDGFeatures(5)
    Log "isNXProtected= $isNXProtected "
    if($isNXProtected -eq 1)
    {
        LogAndConsoleSuccess "NX Protector is available"
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "UEFINX" /t REG_DWORD /d 2 /f '
    }
    else
    {
        LogAndConsoleWarning "NX Protector is absent"
        $DGVerifyWarn.AppendLine("NX Protector is absent") | Out-Null
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "UEFINX" /t REG_DWORD /d 0 /f '
    }
}

function CheckSMMProtection
{
    $isSMMMitigated = CheckDGFeatures(6)
    Log "isSMMMitigated= $isSMMMitigated "
    if($isSMMMitigated -eq 1)
    {
        LogAndConsoleSuccess "SMM Mitigation is available"
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "SMMProtections" /t REG_DWORD /d 2 /f '
    }
    else
    {
        LogAndConsoleWarning "SMM Mitigation is absent"
        $DGVerifyWarn.AppendLine("SMM Mitigation is absent") | Out-Null
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "SMMProtections" /t REG_DWORD /d 0 /f '
    }
}

function CheckHSTI
{
    LogAndConsole "Copying HSTITest.dll"
    try
    {
        $HSTITest_Decoded = [System.Convert]::FromBase64String($HSTITest_Encoded)
        [System.IO.File]::WriteAllBytes("$env:windir\System32\hstitest.dll",$HSTITest_Decoded)

    }
    catch
    {
        LogAndConsole $_.Exception.Message
        LogAndConsole "Copying and loading HSTITest.dll failed"
    }

    Instantiate-Kernel32
    Instantiate-HSTI
}

function PrintToolVersion
{
    LogAndConsole ""
    LogAndConsole "###########################################################################"
    LogAndConsole ""
    LogAndConsole "Readiness Tool Version 3.7.2 Release. `nTool to check if your device is capable to run Device Guard and Credential Guard."
    LogAndConsole ""
    LogAndConsole "###########################################################################"
    LogAndConsole ""

}

PrintToolVersion

if(!($Ready) -and !($Capable) -and !($Enable) -and !($Disable) -and !($Clear) -and !($ResetVerifier))
{
    #Print Usage if none of the options are specified
    LogAndConsoleWarning "How to read the output:"
    LogAndConsoleWarning ""
    LogAndConsoleWarning " 1. Red Errors: Basic things are missing that will prevent enabling and using DG/CG"
    LogAndConsoleWarning " 2. Yellow Warnings: This device can be used to enable and use DG/CG, but `n    additional security benefits will be absent. To learn more please go through: https://aka.ms/dgwhcr"
    LogAndConsoleWarning " 3. Green Messages: This device is fully compliant with DG/CG requirements`n"

    LogAndConsoleWarning "###########################################################################"
    LogAndConsoleWarning ""
    LogAndConsoleWarning "Hardware requirements for enabling Device Guard and Credential Guard"
    LogAndConsoleWarning " 1. Hardware: Recent hardware that supports virtualization extension with SLAT"
    LogAndConsoleWarning ""
    LogAndConsoleWarning "########################################################################### `n"

    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -[Capable/Ready/Enable/Disable/Clear] -[DG/CG/HVCI] -[AutoReboot] -Path"
    LogAndConsoleWarning "Log file with details is found here: C:\DGLogs `n"

    LogAndConsoleWarning "To Enable DG/CG. If you have a custom SIPolicy.p7b then use the -Path parameter else the hardcoded default policy is used"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Enable OR DG_Readiness.ps1 -Enable -Path <full path to the SIPolicy.p7b> `n"

    LogAndConsoleWarning "To Enable only HVCI"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Enable -HVCI `n"

    LogAndConsoleWarning "To Enable only CG"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Enable -CG `n"

    LogAndConsoleWarning "To Verify if DG/CG is enabled"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Ready `n"

    LogAndConsoleWarning "To Disable DG/CG."
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Disable `n"

    LogAndConsoleWarning "To Verify if DG/CG is disabled"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Ready `n"

    LogAndConsoleWarning "To Verify if this device is DG/CG Capable"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Capable`n"

    LogAndConsoleWarning "To Verify if this device is HVCI Capable"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -Capable -HVCI`n"

    LogAndConsoleWarning "To Auto reboot with each option"
    LogAndConsoleWarning "Usage: DG_Readiness.ps1 -[Capable/Enable/Disable] -AutoReboot`n"
    LogAndConsoleWarning "###########################################################################"
    LogAndConsoleWarning ""
    LogAndConsoleWarning "When the Readiness Tool with '-capable' is run the following RegKey values are set:"
    LogAndConsoleWarning ""
    LogAndConsoleWarning "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities"
    LogAndConsoleWarning "CG_Capable"
    LogAndConsoleWarning "DG_Capable"
    LogAndConsoleWarning "HVCI_Capable"
    LogAndConsoleWarning ""
    LogAndConsoleWarning "Value 0 = not possible to enable DG/CG/HVCI on this device"
    LogAndConsoleWarning "Value 1 = not fully compatible but has sufficient firmware/hardware/software features to enable DG/CG/HVCI"
    LogAndConsoleWarning "Value 2 = fully compatible for DG/CG/HVCI"
    LogAndConsoleWarning ""
    LogAndConsoleWarning "########################################################################### `n"
}

$user = [Security.Principal.WindowsIdentity]::GetCurrent();
$TestForAdmin = (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)

if(!$TestForAdmin)
{
    LogAndConsoleError "This script requires local administrator privileges. Please execute this script as a local administrator."
    exit
}

$isRunningOnVM = (Get-WmiObject win32_computersystem).model
if($isRunningOnVM.Contains("Virtual"))
{
    LogAndConsoleWarning "Running on a Virtual Machine. DG/CG is supported only if both guest VM and host machine are running with Windows 10, version 1703 or later with English localization."
}


<# Check the DG status if enabled or disabled, meaning if the device is ready or not #>
if($Ready)
{
    PrintHardwareReq

    $DGRunning = $(Get-CimInstance -classname Win32_DeviceGuard -namespace root\Microsoft\Windows\DeviceGuard).SecurityServicesRunning
    $_ConfigCIState = $(Get-CimInstance -classname Win32_DeviceGuard -namespace root\Microsoft\Windows\DeviceGuard).CodeIntegrityPolicyEnforcementStatus
    Log "Current DGRunning = $DGRunning, ConfigCI= $_ConfigCIState"
    $_HVCIState = CheckDGRunning(2)
    $_CGState = CheckDGRunning(1)

    if($HVCI)
    {
        Log "_HVCIState: $_HVCIState"
        PrintHVCIDetails $_HVCIState
    }
    elseif($CG)
    {
        Log "_CGState: $_CGState"
        PrintCGDetails $_CGState

        if($_CGState)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "CG_Running" /t REG_DWORD /d 1 /f'
        }
        else
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "CG_Running" /t REG_DWORD /d 0 /f'
        }
    }
    elseif($DG)
    {
        Log "_HVCIState: $_HVCIState, _ConfigCIState: $_ConfigCIState"

        PrintHVCIDetails $_HVCIState
        PrintConfigCIDetails $_ConfigCIState

        if($_ConfigCIState -and $_HVCIState)
        {
            LogAndConsoleSuccess "HVCI, and Config-CI are enabled and running."

            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "DG_Running" /t REG_DWORD /d 1 /f'
        }
        else
        {
            LogAndConsoleWarning "Not all services are running."

            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "DG_Running" /t REG_DWORD /d 0 /f'
        }
    }
    else
    {
        Log "_CGState: $_CGState, _HVCIState: $_HVCIState, _ConfigCIState: $_ConfigCIState"

        PrintCGDetails $_CGState
        PrintHVCIDetails $_HVCIState
        PrintConfigCIDetails $_ConfigCIState

        if(($DGRunning.Length -ge 2) -and ($_CGState) -and ($_HVCIState) -and ($_ConfigCIState -ge 1))
        {
            LogAndConsoleSuccess "HVCI, Credential Guard, and Config CI are enabled and running."
        }
        else
        {
            LogAndConsoleWarning "Not all services are running."
        }
    }
}

<# Enable and Disable #>
if($Enable)
{
    PrintHardwareReq

    LogAndConsole "Enabling Device Guard and Credential Guard"
    LogAndConsole "Setting RegKeys to enable DG/CG"

    ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "EnableVirtualizationBasedSecurity" /t REG_DWORD /d 1 /f'
    #Only SecureBoot is required as part of RequirePlatformSecurityFeatures
    ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "RequirePlatformSecurityFeatures" /t REG_DWORD /d 1 /f'

    $_isRedstone = IsRedstone
    if(!$_isRedstone)
    {
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "Unlocked" /t REG_DWORD /d 1 /f'
    }
    else
    {
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "Locked" /t REG_DWORD /d 0 /f'
    }

    if(!$HVCI -and !$DG)
    {
        # value is 2 for both Th2 and RS1
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "LsaCfgFlags" /t REG_DWORD /d 2 /f'
    }
    if(!$CG)
    {
        if(!$_isRedstone)
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "HypervisorEnforcedCodeIntegrity" /t REG_DWORD /d 1 /f'
        }
        else
        {
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity" /v "Enabled" /t REG_DWORD /d 1 /f'
            ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity" /v "Locked" /t REG_DWORD /d 0 /f'
        }
    }

    try
    {
        if(!$HVCI -and !$CG)
        {
            if(!$SIPolicyPath)
            {
                Log "Writing Decoded SIPolicy.p7b"
                $SIPolicy_Decoded = [System.Convert]::FromBase64String($SIPolicy_Encoded)
                [System.IO.File]::WriteAllBytes("$env:windir\System32\CodeIntegrity\SIPolicy.p7b",$SIPolicy_Decoded)
            }
            else
            {
                LogAndConsole "Copying user provided SIpolicy.p7b"
                $CmdOutput = Copy-Item $SIPolicyPath "$env:windir\System32\CodeIntegrity\SIPolicy.p7b" | Out-String
                Log $CmdOutput
            }
        }
    }
    catch
    {
        LogAndConsole "Writing SIPolicy.p7b file failed"
    }

    LogAndConsole "Enabling Hyper-V and IOMMU"
    $_isRedstone = IsRedstone
    if(!$_isRedstone)
    {
        LogAndConsole "OS Not Redstone, enabling IsolatedUserMode separately"
        #Enable/Disable IOMMU separately
        ExecuteCommandAndLog 'DISM.EXE /Online /Enable-Feature:IsolatedUserMode /NoRestart'
    }
    $CmdOutput =  DISM.EXE /Online /Enable-Feature:Microsoft-Hyper-V-Hypervisor /All /NoRestart | Out-String
    if(!$CmdOutput.Contains("The operation completed successfully."))
    {
        $CmdOutput =  DISM.EXE /Online /Enable-Feature:Microsoft-Hyper-V-Online /All /NoRestart | Out-String
    }

    Log $CmdOutput
    if($CmdOutput.Contains("The operation completed successfully."))
    {
        LogAndConsoleSuccess "Enabling Hyper-V and IOMMU successful"
        #Reg key for HLK validation of DISM.EXE step
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "HyperVEnabled" /t REG_DWORD /d 1 /f'
    }
    else
    {
        LogAndConsoleWarning "Enabling Hyper-V failed please check the log file"
        #Reg key for HLK validation of DISM.EXE step
        ExecuteCommandAndLog 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities\" /v "HyperVEnabled" /t REG_DWORD /d 0 /f'
    }
    AutoRebootHelper
}

if($Disable)
{
    LogAndConsole "Disabling Device Guard and Credential Guard"
    LogAndConsole "Deleting RegKeys to disable DG/CG"

    ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "EnableVirtualizationBasedSecurity" /f'
    ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "RequirePlatformSecurityFeatures" /f'

    $_isRedstone = IsRedstone
    if(!$_isRedstone)
    {
        ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "NoLock" /f'
    }
    else
    {
        ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "Locked" /f'
    }

    if(!$CG)
    {
        ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" /v "HypervisorEnforcedCodeIntegrity" /f'
        if($_isRedstone)
        {
            ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity" /f'
        }
    }

    if(!$HVCI -and !$DG)
    {
        ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v "LsaCfgFlags" /f'
    }

    if(!$HVCI -and !$CG)
    {
        ExecuteCommandAndLog 'del  "$env:windir\System32\CodeIntegrity\SIPolicy.p7b"'
    }

    if(!$HVCI -and !$DG -and !$CG)
    {
        LogAndConsole "Disabling Hyper-V and IOMMU"
        $_isRedstone = IsRedstone
        if(!$_isRedstone)
        {
            LogAndConsole "OS Not Redstone, disabling IsolatedUserMode separately"
            #Enable/Disable IOMMU separately
            ExecuteCommandAndLog 'DISM.EXE /Online /disable-Feature /FeatureName:IsolatedUserMode /NoRestart'
        }
        $CmdOutput =  DISM.EXE /Online /disable-Feature /FeatureName:Microsoft-Hyper-V-Hypervisor /NoRestart | Out-String
        if(!$CmdOutput.Contains("The operation completed successfully."))
        {
            $CmdOutput =  DISM.EXE /Online /disable-Feature /FeatureName:Microsoft-Hyper-V-Online /NoRestart | Out-String
        }
        Log $CmdOutput
        if($CmdOutput.Contains("The operation completed successfully."))
        {
            LogAndConsoleSuccess "Disabling Hyper-V and IOMMU successful"
        }
        else
        {
            LogAndConsoleWarning "Disabling Hyper-V failed please check the log file"
        }

        #set of commands to run SecConfig.efi to delete UEFI variables if were set in pre OS
        #these steps can be performed even if the UEFI variables were not set - if not set it will lead to No-Op but this can be run in general always
        #this requires a reboot and accepting the prompt in the Pre-OS which is self explanatory in the message that is displayed in pre-OS
        $FreeDrive = ls function:[s-z]: -n | ?{ !(test-path $_) } | random
        Log "FreeDrive=$FreeDrive"
        ExecuteCommandAndLog 'mountvol $FreeDrive /s'
        $CmdOutput = Copy-Item "$env:windir\System32\SecConfig.efi" $FreeDrive\EFI\Microsoft\Boot\SecConfig.efi -Force | Out-String
        LogAndConsole $CmdOutput
        ExecuteCommandAndLog 'bcdedit /create "{0cb3b571-2f2e-4343-a879-d86a476d7215}" /d DGOptOut /application osloader'
        ExecuteCommandAndLog 'bcdedit /set "{0cb3b571-2f2e-4343-a879-d86a476d7215}" path \EFI\Microsoft\Boot\SecConfig.efi'
        ExecuteCommandAndLog 'bcdedit /set "{bootmgr}" bootsequence "{0cb3b571-2f2e-4343-a879-d86a476d7215}"'
        ExecuteCommandAndLog 'bcdedit /set "{0cb3b571-2f2e-4343-a879-d86a476d7215}" loadoptions DISABLE-LSA-ISO,DISABLE-VBS'
        ExecuteCommandAndLog 'bcdedit /set "{0cb3b571-2f2e-4343-a879-d86a476d7215}" device partition=$FreeDrive'
        ExecuteCommandAndLog 'mountvol $FreeDrive /d'
        #steps complete

    }
    AutoRebootHelper
}

if($Clear)
{
    ExecuteCommandAndLog 'REG DELETE "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard\Capabilities" /f'
    VerifierReset
}

if($ResetVerifier)
{
    VerifierReset
}

<# Is machine Device Guard / Cred Guard Capable and Verify #>
if($Capable)
{
    PrintHardwareReq

    LogAndConsole "Checking if the device is DG/CG Capable"

    $_isRedstone = IsRedstone
    if(!$_isRedstone)
    {
        LogAndConsoleWarning "Capable is currently fully supported in Redstone only.."
    }
    $_StepCount = 1
    if(!$CG)
    {
        LogAndConsole " ====================== Step $_StepCount Driver Compat ====================== "
        $_StepCount++
        CheckDriverCompat
    }

    LogAndConsole " ====================== Step $_StepCount Secure boot present ====================== "
    $_StepCount++
    CheckSecureBootState

    if(!$HVCI -and !$DG -and !$CG)
    {
        #check only if sub-options are absent
        LogAndConsole " ====================== Step $_StepCount MS UEFI HSTI tests ====================== "
        $_StepCount++
        CheckHSTI
    }

    LogAndConsole " ====================== Step $_StepCount OS Architecture ====================== "
    $_StepCount++
    CheckOSArchitecture

    LogAndConsole " ====================== Step $_StepCount Supported OS SKU ====================== "
    $_StepCount++
    CheckOSSKU

    LogAndConsole " ====================== Step $_StepCount Virtualization Firmware ====================== "
    $_StepCount++
    CheckVirtualization

    if(!$HVCI -and !$DG)
    {
        LogAndConsole " ====================== Step $_StepCount TPM version ====================== "
        $_StepCount++
        CheckTPM

        LogAndConsole " ====================== Step $_StepCount Secure MOR ====================== "
        $_StepCount++
        CheckSecureMOR
    }

    LogAndConsole " ====================== Step $_StepCount NX Protector ====================== "
    $_StepCount++
    CheckNXProtection

    LogAndConsole " ====================== Step $_StepCount SMM Mitigation ====================== "
    $_StepCount++
    CheckSMMProtection

    LogAndConsole " ====================== End Check ====================== "

    LogAndConsole " ====================== Summary ====================== "
    ListSummary
    LogAndConsole "To learn more about required hardware and software please visit: https://aka.ms/dgwhcr"
}


# SIG # Begin signature block
## REPLACE
# SIG # End signature block