Skip to content

Instantly share code, notes, and snippets.

@out0xb2
Forked from mattifestation/UEFISecDatabaseParser.ps1
Last active February 14, 2024 09:02
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save out0xb2/f8e0bae94214889a89ac67fceb37f8c0 to your computer and use it in GitHub Desktop.
Parses signature data from the pk, kek, db, and dbx UEFI variables.
Write-Host "Checking for Administrator permission..."
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "Insufficient permissions to run this script. Open the PowerShell console as administrator and run this script again."
Break
} else {
Write-Host "Running as administrator — continuing execution..." -ForegroundColor Green
}
$patchfile = $args[0]
if ($patchfile -eq $null) {
$patchfile = ".\dbx-2023-JulyKB.bin"
Write-Host "Patchfile not specified, using latest $patchfile`n"
}
$patchfile = (gci $patchfile).FullName
Import-Module -Force .\Get-UEFIDatabaseSignatures.ps1
# Print computer info
$computer = gwmi Win32_ComputerSystem
$bios = gwmi Win32_BIOS
"Manufacturer: " + $computer.Manufacturer
"Model: " + $computer.Model
$biosinfo = $bios.Manufacturer , $bios.Name , $bios.SMBIOSBIOSVersion , $bios.Version -join ", "
"BIOS: " + $biosinfo + "`n"
$DbxRaw = Get-SecureBootUEFI dbx
$DbxFound = $DbxRaw | Get-UEFIDatabaseSignatures
$DbxBytesRequired = [IO.File]::ReadAllBytes($patchfile)
$DbxRequired = Get-UEFIDatabaseSignatures -BytesIn $DbxBytesRequired
# Flatten into an array of required EfiSignatureData data objects
$RequiredArray = foreach ($EfiSignatureList in $DbxRequired) {
Write-Verbose $EfiSignatureList
foreach ($RequiredSignatureData in $EfiSignatureList.SignatureList) {
Write-Verbose $RequiredSignatureData
$RequiredSignatureData.SignatureData
}
}
Write-Information "Required `n" $RequiredArray
# Flatten into an array of EfiSignatureData data objects (read from dbx)
$FoundArray = foreach ($EfiSignatureList in $DbxFound) {
Write-Verbose $EfiSignatureList
foreach ($FoundSignatureData in $EfiSignatureList.SignatureList) {
Write-Verbose $FoundSignatureData
$FoundSignatureData.SignatureData
}
}
Write-Information "Found `n" $FoundArray
$successes = 0
$failures = 0
$requiredCount = $RequiredArray.Count
foreach ($RequiredSig in $RequiredArray) {
if ($FoundArray -contains $RequiredSig) {
Write-Information "FOUND: $RequiredSig"
$successes++
} else {
Write-Error "!!! NOT FOUND`n$RequiredSig`n!!!`n"
$failures++
}
$i = $successes + $failures
Write-Progress -Activity 'Checking if all patches applied' -Status "Checking element $i of $requiredCount" -PercentComplete ($i/$requiredCount *100)
}
if ($failures -ne 0) {
Write-Error "!!! FAIL: $failures failures detected!"
# $DbxRaw.Bytes | sc -encoding Byte dbx_found.bin
} elseif ($successes -ne $RequiredArray.Count) {
Write-Error "!!! Unexpected: $successes != $requiredCount expected successes!"
} elseif ($successes -eq 0) {
Write-Error "!!! Unexpected failure: no successes detected, check command-line usage."
} else {
Write-Host "SUCCESS: dbx.bin patch appears to be successfully applied"
}
function Get-UefiDatabaseSignatures {
<#
.SYNOPSIS
Parses UEFI Signature Databases into logical Powershell objects
.DESCRIPTION
Original Author: Matthew Graeber (@mattifestation)
Modified By: Jeremiah Cox (@int0x6)
Additional Source: https://gist.github.com/mattifestation/991a0bea355ec1dc19402cef1b0e3b6f
License: BSD 3-Clause
.PARAMETER Variable
Specifies a UEFI variable, an instance of which is returned by calling the Get-SecureBootUEFI cmdlet. Only 'db' and 'dbx' are supported.
.PARAMETER BytesIn
Specifies a byte array consisting of the PK, KEK, db, or dbx UEFI vairable contents.
.EXAMPLE
$DbxBytes = [IO.File]::ReadAllBytes('.\dbx.bin')
Get-UEFIDatabaseSignatures -BytesIn $DbxBytes
.EXAMPLE
Get-SecureBootUEFI -Name db | Get-UEFIDatabaseSignatures
.EXAMPLE
Get-SecureBootUEFI -Name dbx | Get-UEFIDatabaseSignatures
.EXAMPLE
Get-SecureBootUEFI -Name pk | Get-UEFIDatabaseSignatures
.EXAMPLE
Get-SecureBootUEFI -Name kek | Get-UEFIDatabaseSignatures
.INPUTS
Microsoft.SecureBoot.Commands.UEFIEnvironmentVariable
Accepts the output of Get-SecureBootUEFI over the pipeline.
.OUTPUTS
UefiSignatureDatabase
Outputs an array of custom powershell objects describing a UEFI Signature Database. "77fa9abd-0359-4d32-bd60-28f4e78f784b" refers to Microsoft as the owner.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'UEFIVariable')]
[ValidateScript({ ($_.GetType().Fullname -eq 'Microsoft.SecureBoot.Commands.UEFIEnvironmentVariable') -and (($_.Name -eq 'kek') -or ($_.Name -eq 'pk') -or ($_.Name -eq 'db') -or ($_.Name -eq 'dbx')) })]
$Variable,
[Parameter(Mandatory, ParameterSetName = 'ByteArray')]
[Byte[]]
[ValidateNotNullOrEmpty()]
$BytesIn
)
$SignatureTypeMapping = @{
'C1C41626-504C-4092-ACA9-41F936934328' = 'EFI_CERT_SHA256_GUID' # Most often used for dbx
'A5C059A1-94E4-4AA7-87B5-AB155C2BF072' = 'EFI_CERT_X509_GUID' # Most often used for db
}
$Bytes = $null
if ($Variable) {
$Bytes = $Variable.Bytes
} else {
$Bytes = $BytesIn
}
try {
$MemoryStream = New-Object -TypeName IO.MemoryStream -ArgumentList @(,$Bytes)
$BinaryReader = New-Object -TypeName IO.BinaryReader -ArgumentList $MemoryStream, ([Text.Encoding]::Unicode)
} catch {
throw $_
return
}
# What follows will be an array of EFI_SIGNATURE_LIST structs
while ($BinaryReader.PeekChar() -ne -1) {
$SignatureType = $SignatureTypeMapping[([Guid][Byte[]] $BinaryReader.ReadBytes(16)).Guid]
$SignatureListSize = $BinaryReader.ReadUInt32()
$SignatureHeaderSize = $BinaryReader.ReadUInt32()
$SignatureSize = $BinaryReader.ReadUInt32()
$SignatureHeader = $BinaryReader.ReadBytes($SignatureHeaderSize)
# 0x1C is the size of the EFI_SIGNATURE_LIST header
$SignatureCount = ($SignatureListSize - 0x1C) / $SignatureSize
$SignatureList = 1..$SignatureCount | ForEach-Object {
$SignatureDataBytes = $BinaryReader.ReadBytes($SignatureSize)
$SignatureOwner = [Guid][Byte[]] $SignatureDataBytes[0..15]
switch ($SignatureType) {
'EFI_CERT_SHA256_GUID' {
$SignatureData = ([Byte[]] $SignatureDataBytes[0x10..0x2F] | ForEach-Object { $_.ToString('X2') }) -join ''
}
'EFI_CERT_X509_GUID' {
$SignatureData = New-Object Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @(,([Byte[]] $SignatureDataBytes[16..($SignatureDataBytes.Count - 1)]))
}
}
[PSCustomObject] @{
PSTypeName = 'EFI.SignatureData'
SignatureOwner = $SignatureOwner
SignatureData = $SignatureData
}
}
[PSCustomObject] @{
PSTypeName = 'EFI.SignatureList'
SignatureType = $SignatureType
SignatureList = $SignatureList
}
}
}
@maffblaster
Copy link

I find it hard to believe this is where Micro$oft links from their official remediation guide. A random GitHub Gist from an individual that appears to have no affiliation with Microsoft proper. Does Micro$oft even have a security team? The lolz.

I arrived here from this page: https://support.microsoft.com/en-us/topic/microsoft-guidance-for-applying-secure-boot-dbx-update-e3b9e4cb-a330-b3ba-a602-15083965d9ca

@out0xb2
Copy link
Author

out0xb2 commented Jan 20, 2022

Hi @maffblaster ,
As an FYI, I was previously employed by Microsoft where I worked on UEFI security, among other things...
You can trust me 👍😉👍

@chrismholmes1
Copy link

Thank you @out0xb2 for the scripts. They have been helpful in validating a number of the Boot Hole findings in multiple environments.
FYI: I have confirmed that there are certain model Dells having trouble with either installing the updates to the DBX or validating the DBX for the July 2020 x64 content.

The models having issues that I have personally validated is Optiplex 7010, Optiplex 7020, and Optiplex 9020.
The certificate hash its having trouble validating is 61341E07697978220EA61E85DCD2421343F2C1BF35CC5B8D0AD2F0226F391479

I am wondering if Dell needs to release an updated BIOS (of course these machines are very dated as well)
Is anyone else running in to this issue?

In the Check-dbx.ps1, I added a global variable to help with passing the success and error messages to other scripts. It did wonders in automating the entire process.

**Side note, McAfee VSE and ENS does not play nice with the Get-UEFIDatabaseSignatures.ps1 script. I have added multiple exclusions for it and yet McAfee still finds a way to hate that script and delete it. I know its McAfee being over zealous but figured I would add a note just in case anyone is having the same trouble.

@out0xb2
Copy link
Author

out0xb2 commented Feb 22, 2022

Hi @chrismholmes1 , happy to hear the script is helping you. With respect to the certificate not being validated, there is a Python tool that might provide more insight, but I won't have time to troubleshoot. If the failure only happens on a subset of machine, yes, I'd ping the vendor for assistance, but those systems sound like they're over 5 years old, so best wishes on that. I could try signing the scripts, but my code sign cert is old, and likely it wouldn't have sufficient reputation to help with McAfee.

@bigwillyg
Copy link

hello. I am getting a set of odd errors when running the check-in.ps1 script. the first error is that it complains about converting value "System.byte[]" to "System.guide" stating that "byte array for GUID must be exactly 16 bytes long"

@out0xb2
Copy link
Author

out0xb2 commented Jun 14, 2022

@bigwillyg

hello. I am getting a set of odd errors when running the check-in.ps1 script. the first error is that it complains about converting value "System.byte[]" to "System.guide" stating that "byte array for GUID must be exactly 16 bytes long"

¯_(ツ)_/¯

Its worked fine for many people. What is the exact error message, and what Powershell version are you running?

@steve6375
Copy link

Is it possible to delete entire dbx from a booted windows or Linux OS, or can it only be deleted from the bios ?

@steve6375
Copy link

Windows updates can add or delete keys from dbx, so it must be possible.
Must the manufacturer kek private key or Microsoft private key be known?

@out0xb2
Copy link
Author

out0xb2 commented Aug 18, 2022

Yes, if you have a public key in the KEK for which you control the private key, this is possible, and that is how Microsoft does it. Read the UEFI died on Authenticated variables.

@toabctl
Copy link

toabctl commented Sep 9, 2022

@out0xb2 is there a tool for linux that does split the DBXUpdate file into data and signature?

@QuantaMichaelChu
Copy link

Hi, will this tool be updated to check for the latest dbx binaries?
Check out the UEFI website, they released 2 versions of the dbx binaries in August and September.
By the way, I tried to create a dbx binary "dbx-September-2022.bin" for the check tool to compare with the dbx used by the system, and this binary is base on the regular dbx binary but removes the CA part,
Is this how you created the comparison dbx binary "dbx-{month}-{year}.bin"?

@toabctl
Copy link

toabctl commented Feb 10, 2023

@out0xb2 is there a tool for linux that does split the DBXUpdate file into data and signature?

https://github.com/canonical/aws-secureboot-blob can do the split . It's a python script so it can be easily used on Linux, too.

@cosmoc
Copy link

cosmoc commented Mar 27, 2023

Are the DBX updates cumulative, do each dbx update need to be checked?

@tmoran2006
Copy link

tmoran2006 commented Apr 20, 2023

Is there a way we could have updated BIN files? I'm working on the March 2023 DBX update and would like to verify the install.

@smithnigelw
Copy link

There were new UEFI Revocation List Files posted on March 14, 2023.
https://uefi.org/revocationlistfile
Use the procedure here:
https://support.microsoft.com/en-us/topic/microsoft-guidance-for-applying-secure-boot-dbx-update-kb4575994-e3b9e4cb-a330-b3ba-a602-15083965d9ca
I downloaded 'x64_DBXUpdate.bin' and used 'SplitDbxContent.ps1' to extract 'content.bin' & 'signature.p7' and then used 'Set-SecureBootUefi' to appy them and reboot.

The PowerShell scripts on this page successfully confirmed the patch was applied, but be sure to do:

PS> .\Check-Dbx.ps1 .\content.bin

If you get the error:

Cannot convert value "System.Byte[]" to type "System.Guid". Error: "Byte array for GUID must be exactly 16 bytes long."

...it's because your passing the wrong '.bin' file, like 'x64_DBXUpdate.bin'.

@novaksam
Copy link

Looks like they just posted some updates on the 9th of May too.

@benocummins
Copy link

Did everyone else use the 2010 date for the -Time parameter like is posted on the MS support article? I looked up why you need to use the -Time parameter but I don't understand why the date is 2010.

https://support.microsoft.com/en-us/topic/microsoft-guidance-for-applying-secure-boot-dbx-update-kb4575994-e3b9e4cb-a330-b3ba-a602-15083965d9ca

@rigareau
Copy link

Trying to find information about the Time parameter but description in documentation is too vague.

For now the timestamp 2010-03-06T19:17:21Z looks like a magic number.

Anyone has an explanation on this?

@tmoran2006
Copy link

tmoran2006 commented May 16, 2023

Trying to find information about the Time parameter but description in documentation is too vague.

For now the timestamp 2010-03-06T19:17:21Z looks like a magic number.

Anyone has an explanation on this?

Looking at the documentation of the Set-SecureBootUEFI, I'm not sure it matters as long as it matches a certain format. See link below.

I have not tested this at this point. I will test on the next needed update.

I also found that, in PowerShell, if you use the Get-Date, you can format the date to match the format like this.

Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"

https://learn.microsoft.com/en-us/powershell/module/secureboot/set-securebootuefi?view=windowsserver2022-ps#-time

@nafai
Copy link

nafai commented May 18, 2023

I modified Get-UEFIDatabaseSignatures.ps1 to make my life a bit easier-- It can accept a filename as input, and doesn't need SplitDbxContent.ps1 anymore.

function Get-UefiDatabaseSignatures {
<#
.SYNOPSIS
Parses UEFI Signature Databases into logical Powershell objects
.DESCRIPTION
Original Author: Matthew Graeber (@mattifestation)
Modified By: Jeremiah Cox (@int0x6)
Modified By: Joel Roth (@nafai)
Additional Source: https://gist.github.com/mattifestation/991a0bea355ec1dc19402cef1b0e3b6f
Additional Source: https://www.powershellgallery.com/packages/SplitDbxContent/1.0
License: BSD 3-Clause
.PARAMETER Variable
Specifies a UEFI variable, an instance of which is returned by calling the Get-SecureBootUEFI cmdlet. Only 'db' and 'dbx' are supported.
.PARAMETER BytesIn
Specifies a byte array consisting of the PK, KEK, db, or dbx UEFI vairable contents.
.EXAMPLE
$DbxBytes = [IO.File]::ReadAllBytes('.\dbx.bin')
Get-UEFIDatabaseSignatures -BytesIn $DbxBytes
.EXAMPLE
Get-UEFIDatabaseSignatures -Filename ".\DBXUpdate-20230314.x64.bin"
.EXAMPLE
Get-SecureBootUEFI -Name db | Get-UEFIDatabaseSignatures
.EXAMPLE
Get-SecureBootUEFI -Name dbx | Get-UEFIDatabaseSignatures
.EXAMPLE
Get-SecureBootUEFI -Name pk | Get-UEFIDatabaseSignatures
.EXAMPLE
Get-SecureBootUEFI -Name kek | Get-UEFIDatabaseSignatures
.INPUTS
Microsoft.SecureBoot.Commands.UEFIEnvironmentVariable
Accepts the output of Get-SecureBootUEFI over the pipeline.
.OUTPUTS
UefiSignatureDatabase
Outputs an array of custom powershell objects describing a UEFI Signature Database. "77fa9abd-0359-4d32-bd60-28f4e78f784b" refers to Microsoft as the owner.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'UEFIVariable')]
        [ValidateScript({ ($_.GetType().Fullname -eq 'Microsoft.SecureBoot.Commands.UEFIEnvironmentVariable') -and ($_.Name -in "kek","pk","db","dbx") })]
        $Variable,

        [Parameter(Mandatory, ParameterSetName = 'ByteArray')]
        [Byte[]]
        [ValidateNotNullOrEmpty()]
        $BytesIn,

        [Parameter(Mandatory, ParameterSetName = 'File')]
        [string]
        [ValidateScript({ (Resolve-Path "$_").where({Test-Path $_}).Path })]
        $Filename
    )
    
    $SignatureTypeMapping = @{
        'C1C41626-504C-4092-ACA9-41F936934328' = 'EFI_CERT_SHA256_GUID' # Most often used for dbx
        'A5C059A1-94E4-4AA7-87B5-AB155C2BF072' = 'EFI_CERT_X509_GUID'   # Most often used for db
    }

    $Bytes = $null

    if ($Filename) 
    {
        $Bytes = Get-Content -Encoding Byte $Filename -ErrorAction Stop
    }
    elseif ($Variable)
    {
        $Bytes = $Variable.Bytes
    }
    else
    {
        $Bytes = $BytesIn
    }

    # Modified from Split-Dbx
    if (($Bytes[40] -eq 0x30) -and ($Bytes[41] -eq 0x82 ))
    {
        Write-Debug "Removing signature."

        # Signature is known to be ASN size plus header of 4 bytes
        $sig_length = $Bytes[42] * 256 + $Bytes[43] + 4
        if ($sig_length -gt ($Bytes.Length + 40)) {
            Write-Error "Signature longer than file size!" -ErrorAction Stop
        }
            
        ## Unsigned db store
        [System.Byte[]]$Bytes = @($Bytes[($sig_length+40)..($Bytes.Length - 1)].Clone())
    }
    else
    {
        Write-Debug "Signature not found. Assuming it's already split."
    }

    try
    {
        $MemoryStream = New-Object -TypeName IO.MemoryStream -ArgumentList @(,$Bytes)
        $BinaryReader = New-Object -TypeName IO.BinaryReader -ArgumentList $MemoryStream, ([Text.Encoding]::Unicode)
    }
    catch
    {
        throw $_
        return
    }

    # What follows will be an array of EFI_SIGNATURE_LIST structs

    while ($BinaryReader.PeekChar() -ne -1) {
        $SignatureType = $SignatureTypeMapping[([Guid][Byte[]] $BinaryReader.ReadBytes(16)).Guid]
        $SignatureListSize = $BinaryReader.ReadUInt32()
        $SignatureHeaderSize = $BinaryReader.ReadUInt32()
        $SignatureSize = $BinaryReader.ReadUInt32()

        $SignatureHeader = $BinaryReader.ReadBytes($SignatureHeaderSize)

        # 0x1C is the size of the EFI_SIGNATURE_LIST header
        $SignatureCount = ($SignatureListSize - 0x1C) / $SignatureSize

        $SignatureList = 1..$SignatureCount | ForEach-Object {
            $SignatureDataBytes = $BinaryReader.ReadBytes($SignatureSize)

            $SignatureOwner = [Guid][Byte[]] $SignatureDataBytes[0..15]

            switch ($SignatureType) {
                'EFI_CERT_SHA256_GUID' {
                    $SignatureData = ([Byte[]] $SignatureDataBytes[0x10..0x2F] | ForEach-Object { $_.ToString('X2') }) -join ''
                }

                'EFI_CERT_X509_GUID' {
                    $SignatureData = New-Object Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @(,([Byte[]] $SignatureDataBytes[16..($SignatureDataBytes.Count - 1)]))
                }
            }

            [PSCustomObject] @{
                PSTypeName = 'EFI.SignatureData'
                SignatureOwner = $SignatureOwner
                SignatureData = $SignatureData
            }
        }

        [PSCustomObject] @{
            PSTypeName = 'EFI.SignatureList'
            SignatureType = $SignatureType
            SignatureList = $SignatureList
        }
    }
}

@out0xb2
Copy link
Author

out0xb2 commented Aug 15, 2023

Are the DBX updates cumulative, do each dbx update need to be checked?

To my knowledge, you should only need to check against the latest update. Sometimes the remove and entry and replace it with a newer signature.

@out0xb2
Copy link
Author

out0xb2 commented Aug 15, 2023

Trying to find information about the Time parameter but description in documentation is too vague.

For now the timestamp 2010-03-06T19:17:21Z looks like a magic number.

Anyone has an explanation on this?

Yes, it is a magic number embedded in the script that is creating the files provided by Microsoft. The parameter supplied to the Powershell cmdlet must match what is already embedded in the files. I think it was the date the I authored the original script that they're still using. So long as "-AppendWrite" mode is being used, its value is meaningless, it just has to match. If -AppendWrite is dropped, well, that probably means that the world is ending, but then they would need to provide a larger value that was used by the BIOS vendor.

@chrismholmes1
Copy link

chrismholmes1 commented Aug 15, 2023 via email

@out0xb2
Copy link
Author

out0xb2 commented Aug 15, 2023

From a security standpoint, it should only be necessary to install the latest, but products like Nessus do not understand these complexities, so you have to waste precious dbx space.

@cjee21
Copy link

cjee21 commented Feb 14, 2024

I've put together the scripts on this page along with some modifications and additional scripts to enable easy (only two clicks required) checking of the UEFI Secure Boot variables. I've also added checks for the new 2023 Microsoft signing certificates that are being added to the DB in phases beginning with this month's cumulative update. I've put the scripts and files here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment