Monthly Archives: July 2016

Retrieve Certificate from Event log binary data

As I was looking into some errors in my event log I found that I had a number of certificate errors in the event log. In order to investigate this further I wanted to take a look at the certificate in the event log. There are a number of tools available to extract this from the event log but I wanted to be able to automate this in the future so I settled on writing this in PowerShell.

I had the following events in my system event log:

Event

The interesting portion is what is stored in the XML, specifically EventData – Binary:

XMLView

In order to retrieve this event using PowerShell we can run the following code:

1
Get-WinEvent -FilterHashtable @{'Logname' = 'System' ; 'Id' = 36882} -MaxEvents 1

Get-WinEvent

In order to retrieve the binary data we can run the following code:

1
2
3
4
5
([xml](Get-WinEvent -FilterHashtable @{
        'Logname' = 'System'
        'Id' = 36882
    } -MaxEvents 1).ToXml()
).Event.Eventdata.Binary

The binary data is encoded as pairs of hexadecimal numbers, so this needs to be converted before we can write this to disk. In order to do this we split the string into pairs of two and then do a conversion using the ToByte method of the System.Convert class:

1
2
3
4
5
6
7
8
9
10
(
    ([xml](Get-WinEvent -FilterHashtable @{
            'Logname' = 'System'
            'Id'      = 36882
        } -MaxEvents 1).ToXml()
    ).Event.Eventdata.Binary -split '(..)' |
    Where-Object {$_} | ForEach-Object {
        [system.convert]::ToByte($_,16)
    }
)

Now that we have PowerShell output an array of bytes we are ready to write the output of the event log to file. Because we know this should be a certificate all we have to do is write this to a .cer file and we will have a working certificate:

1
2
3
4
5
6
7
8
9
10
11
12
13
[System.IO.File]::WriteAllBytes("$env:USERPROFILE\desktop\EventCert.cer",
    (
        (
            [xml](Get-WinEvent -FilterHashtable @{
                'Logname' = 'System'
                'Id'      = 36882
            } -MaxEvents 1).ToXml()
        ).Event.Eventdata.Binary -split '(..)' |
        Where-Object {$_} | ForEach-Object {
            [system.convert]::ToByte($_,16)
        }
    )
)

Now the following functional certificate will be available on the desktop:

EventCert

So there we have it, in this article we have identified the event that contains a certificate that. Afterwards we went into the xml of this event and retrieved the binary eventdata, converted this to a byte array and then wrote this to file.

Share