PoshCode Logo PowerShell Code Repository

Get-CACertificateDatabas by DollarUnderscore 26 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/5793"></script>download | new post

Function for retrieving certificates from a CA instance. It can also return the public key, which I use to encrypt credentials in DSC resources (thumbprint is also returned).

Blog post about it is available at:
http://dollarunderscore.azurewebsites.net/?p=4791

  1. function Get-CACertificateDatabase
  2. {
  3.     <#
  4.     .SYNOPSIS
  5.     Retrieves information about certificates from the Certificate Authority Database
  6.  
  7.     .DESCRIPTION
  8.     This function will fetch items from a Certificate Authority Database. It can also
  9.     fetch the public key of the certificates and the thumbprint which could be really
  10.     useful when you want to use the certificates to for example encrypt something
  11.     (like a credential in a DSC resource).
  12.  
  13.     Another useful scenario is to create monitoring of certificate expiration dates.
  14.  
  15.     .EXAMPLE
  16.     Get-CACertificateDatabase -CA "myca.contoso.com\Issuing CA Contoso" -IncludeBinaryCertificate
  17.  
  18.     Fetch certificates from the CA instance and include the public key.
  19.  
  20.     .EXAMPLE
  21.     Get-CACertificateDatabase -CA "myca.contoso.com\Issuing CA Contoso" -ValidTo (Get-Date)
  22.  
  23.     Fetch certificates that expires today.
  24.  
  25.     .PARAMETER CertificationAuthority
  26.     The Certificate Authority instance you want to connect to. For example:
  27.     'myca.contoso.com\Issuing CA Contoso'
  28.  
  29.     .PARAMETER ValidFrom
  30.     Filter what certificates should be returned based on if they are valid at this date.
  31.  
  32.     .PARAMETER ValidTo
  33.     Filter what certificates should be returned based on if they expire before this date.
  34.  
  35.     .PARAMETER Disposition
  36.     Specifies which category to get the certificates from.
  37.  
  38.     Brief disposition code explanation:
  39.     * 9 - pending for approval
  40.     * 15 - CA certificate renewal
  41.     * 16 - CA certificate chain
  42.     * 20 - issued certificates
  43.     * 21 - revoked certificates
  44.     * all other - failed requests
  45.  
  46.     .PARAMETER IncludeBinaryCertificate
  47.     This switch will enable retrieval of the public key of the certificates.
  48.  
  49.     #>
  50.  
  51.     [cmdletbinding()]
  52.     param ([parameter(Mandatory = $true)]
  53.            [string] $CertificationAuthority,
  54.            [parameter(Mandatory = $false)]
  55.            [datetime] $ValidFrom = (Get-Date),
  56.            [parameter(Mandatory = $false)]
  57.            [datetime] $ValidTo = (Get-Date).AddYears(2),
  58.            [parameter(Mandatory = $false)]
  59.            [int] $Disposition = 20,
  60.            [parameter(Mandatory = $false)]
  61.            [switch] $IncludeBinaryCertificate)
  62.  
  63.     BEGIN { }
  64.  
  65.     PROCESS {
  66.  
  67.         Write-Verbose 'Initiating com object'
  68.  
  69.         $CaView = New-Object -Com CertificateAuthority.View
  70.  
  71.         try {
  72.             Write-Verbose "Connecting to $CertificationAuthority..."
  73.             [void] $CaView.OpenConnection($CertificationAuthority)
  74.         }
  75.         catch {
  76.             Write-Error "Failed to connect to the Certificate Authority instance $CA. The error was: $($_.toString())"
  77.             break
  78.         }
  79.  
  80.         $CaView.SetResultColumnCount(8)
  81.  
  82.         $index0 = $CaView.GetColumnIndex($false, "Issued Common Name")
  83.         $index1 = $CaView.GetColumnIndex($false, "Certificate Expiration Date")
  84.         $index2 = $CaView.GetColumnIndex($false, "Issued Email Address")
  85.         $index3 = $CaView.GetColumnIndex($false, "Certificate Template")
  86.         $index4 = $CaView.GetColumnIndex($false, "Request Disposition")
  87.  
  88.         if ($IncludeBinaryCertificate) {
  89.             $index5 = $CaView.GetColumnIndex($false, "Binary Certificate")
  90.         }
  91.  
  92.         $index6 = $CaView.GetColumnIndex($false, "Certificate Hash")
  93.         $index7 = $CaView.GetColumnIndex($false, "Requester Name")
  94.  
  95.         $index0, $index1, $index2, $index3, $index4, $index5, $index6, $index7 | ForEach-Object { $CAView.SetResultColumn($_) }
  96.  
  97.         # CVR_SORT_NONE 0
  98.         # CVR_SEEK_EQ  1
  99.         # CVR_SEEK_LT  2
  100.         # CVR_SEEK_GT  16
  101.  
  102.  
  103.         $index1 = $CaView.GetColumnIndex($false, "Certificate Expiration Date")
  104.         $CAView.SetRestriction($index1,16,0,$ValidFrom)
  105.         $CAView.SetRestriction($index1,2,0,$ValidTo)
  106.  
  107.         # brief disposition code explanation:
  108.         # 9 - pending for approval
  109.         # 15 - CA certificate renewal
  110.         # 16 - CA certificate chain
  111.         # 20 - issued certificates
  112.         # 21 - revoked certificates
  113.         # all other - failed requests
  114.  
  115.         $CAView.SetRestriction($index4,1,0,$Disposition)
  116.  
  117.         $RowObj= $CAView.OpenView()
  118.  
  119.         try {
  120.             Write-Verbose 'Fetching certificates...'
  121.  
  122.             while ($Rowobj.Next() -ne -1) {
  123.                 $Cert = New-Object PsObject
  124.                 $ColObj = $RowObj.EnumCertViewColumn()
  125.                 [void]$ColObj.Next()
  126.  
  127.                 do {
  128.                     $current = $ColObj.GetName()
  129.                     if ($ColObj.GetDisplayName() -eq 'Certificate Hash') {
  130.                         $Cert | Add-Member -MemberType NoteProperty 'Thumbprint' -Value $($ColObj.GetValue(1).ToUpper() -replace "\s") -Force
  131.                     }
  132.                     elseif ($ColObj.GetDisplayName() -eq 'Binary Certificate') {
  133.                         $Cert | Add-Member -MemberType NoteProperty 'BinaryCertificate' -Value "-----BEGIN CERTIFICATE-----`n$($ColObj.GetValue(1))-----END CERTIFICATE-----" -Force
  134.                     }
  135.                     else {
  136.                         $Cert | Add-Member -MemberType NoteProperty $($ColObj.GetDisplayName() -replace '\s') -Value $($ColObj.GetValue(1)) -Force
  137.                     }
  138.  
  139.                 } until ($ColObj.Next() -eq -1)
  140.  
  141.                 Clear-Variable ColObj
  142.  
  143.                 Write-Output $Cert
  144.             }
  145.         }
  146.         catch {
  147.             if ($_.toString() -like '*CEnumCERTVIEWROW::Next: The parameter is incorrect. 0x80070057*') {
  148.                 Write-Verbose "No certificates matched the criteria in the database of $CertificationAuthority"
  149.             }
  150.             else {
  151.                 Write-Error $_.toString()
  152.             }
  153.         }
  154.     }
  155.  
  156.     END {
  157.  
  158.         Write-Verbose 'Cleaning up...'
  159.  
  160.         $RowObj.Reset()
  161.         $CaView = $null
  162.         [GC]::Collect()
  163.  
  164.         Write-Verbose 'Function finished.'
  165.     }
  166. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me