PkiExtension.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\PkiExtension.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName PkiExtension.Import.DoDotSource -Fallback $false
if ($PkiExtension_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName PkiExtension.Import.IndividualFiles -Fallback $false
if ($PkiExtension_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'PkiExtension' -Language 'en-US'

function Get-LdapObject {
    <#
        .SYNOPSIS
            Use LDAP to search in Active Directory
 
        .DESCRIPTION
            Utilizes LDAP to perform swift and efficient LDAP Queries.
 
        .PARAMETER LdapFilter
            The search filter to use when searching for objects.
            Must be a valid LDAP filter.
 
        .PARAMETER Property
            The properties to retrieve.
            Keep bandwidth in mind and only request what is needed.
 
        .PARAMETER SearchRoot
            The root path to search in.
            This generally expects either the distinguished name of the Organizational unit or the DNS name of the domain.
            Alternatively, any legal LDAP protocol address can be specified.
 
        .PARAMETER Configuration
            Rather than searching in a specified path, switch to the configuration naming context.
 
        .PARAMETER Raw
            Return the raw AD object without processing it for PowerShell convenience.
 
        .PARAMETER PageSize
            Rather than searching in a specified path, switch to the schema naming context.
 
        .PARAMETER MaxSize
            The maximum number of items to return.
 
        .PARAMETER SearchScope
            Whether to search all OUs beneath the target root, only directly beneath it or only the root itself.
     
        .PARAMETER AddProperty
            Add additional properties to the output object.
            Use to optimize performance, avoiding needing to use Add-Member.
 
        .PARAMETER Server
            The server to contact for this query.
 
        .PARAMETER Credential
            The credentials to use for authenticating this query.
     
        .PARAMETER TypeName
            The name to give the output object
 
        .EXAMPLE
            PS C:\> Get-LdapObject -LdapFilter '(PrimaryGroupID=516)'
             
            Searches for all objects with primary group ID 516 (hint: Domain Controllers).
    #>

    [Alias('ldap')]
    [CmdletBinding(DefaultParameterSetName = 'SearchRoot')]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $LdapFilter,
        
        [Alias('Properties')]
        [string[]]
        $Property = "*",
        
        [Parameter(ParameterSetName = 'SearchRoot')]
        [Alias('SearchBase')]
        [string]
        $SearchRoot,
        
        [Parameter(ParameterSetName = 'Configuration')]
        [switch]
        $Configuration,
        
        [switch]
        $Raw,
        
        [ValidateRange(1, 1000)]
        [int]
        $PageSize = 1000,
        
        [Alias('SizeLimit')]
        [int]
        $MaxSize,
        
        [System.DirectoryServices.SearchScope]
        $SearchScope = 'Subtree',
        
        [System.Collections.Hashtable]
        $AddProperty,
        
        [string]
        $Server,
        
        [PSCredential]
        $Credential,
        
        [Parameter(DontShow = $true)]
        [string]
        $TypeName
    )
    
    begin {
        #region Utility Functions
        function Get-PropertyName {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [string]
                $Key,
                
                [string[]]
                $Property
            )
            
            if ($hit = @($Property).Where{ $_ -eq $Key }) { return $hit[0] }
            if ($Key -eq 'ObjectClass') { return 'ObjectClass' }
            if ($Key -eq 'ObjectGuid') { return 'ObjectGuid' }
            if ($Key -eq 'ObjectSID') { return 'ObjectSID' }
            if ($Key -eq 'DistinguishedName') { return 'DistinguishedName' }
            if ($Key -eq 'SamAccountName') { return 'SamAccountName' }
            $script:culture.TextInfo.ToTitleCase($Key)
        }
        
        function New-DirectoryEntry {
            <#
        .SYNOPSIS
            Generates a new directoryy entry object.
         
        .DESCRIPTION
            Generates a new directoryy entry object.
         
        .PARAMETER Path
            The LDAP path to bind to.
         
        .PARAMETER Server
            The server to connect to.
         
        .PARAMETER Credential
            The credentials to use for the connection.
         
        .EXAMPLE
            PS C:\> New-DirectoryEntry
 
            Creates a directory entry in the default context.
 
        .EXAMPLE
            PS C:\> New-DirectoryEntry -Server dc1.contoso.com -Credential $cred
 
            Creates a directory entry in the default context of the target server.
            The connection is established to just that server using the specified credentials.
    #>

            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            [CmdletBinding()]
            param (
                [string]
                $Path,
        
                [AllowEmptyString()]
                [string]
                $Server,
        
                [PSCredential]
                [AllowNull()]
                $Credential
            )
    
            if (-not $Path) { $resolvedPath = '' }
            elseif ($Path -like "LDAP://*") { $resolvedPath = $Path }
            elseif ($Path -notlike "*=*") { $resolvedPath = "LDAP://DC={0}" -f ($Path -split "\." -join ",DC=") }
            else { $resolvedPath = "LDAP://$($Path)" }
    
            if ($Server -and ($resolvedPath -notlike "LDAP://$($Server)/*")) {
                $resolvedPath = ("LDAP://{0}/{1}" -f $Server, $resolvedPath.Replace("LDAP://", "")).Trim("/")
            }
    
            if (($null -eq $Credential) -or ($Credential -eq [PSCredential]::Empty)) {
                if ($resolvedPath) { New-Object System.DirectoryServices.DirectoryEntry($resolvedPath) }
                else {
                    $entry = New-Object System.DirectoryServices.DirectoryEntry
                    New-Object System.DirectoryServices.DirectoryEntry(('LDAP://{0}' -f $entry.distinguishedName[0]))
                }
            }
            else {
                if ($resolvedPath) { New-Object System.DirectoryServices.DirectoryEntry($resolvedPath, $Credential.UserName, $Credential.GetNetworkCredential().Password) }
                else { New-Object System.DirectoryServices.DirectoryEntry(("LDAP://DC={0}" -f ($env:USERDNSDOMAIN -split "\." -join ",DC=")), $Credential.UserName, $Credential.GetNetworkCredential().Password) }
            }
        }
        #endregion Utility Functions
        
        $script:culture = Get-Culture

        #region Prepare Searcher
        $searcher = New-Object system.directoryservices.directorysearcher
        $searcher.PageSize = $PageSize
        $searcher.SearchScope = $SearchScope
        
        if ($MaxSize -gt 0) {
            $Searcher.SizeLimit = $MaxSize
        }
        
        if ($SearchRoot) {
            $searcher.SearchRoot = New-DirectoryEntry -Path $SearchRoot -Server $Server -Credential $Credential
        }
        else {
            $searcher.SearchRoot = New-DirectoryEntry -Server $Server -Credential $Credential
        }
        if ($Configuration) {
            $searcher.SearchRoot = New-DirectoryEntry -Path ("LDAP://CN=Configuration,{0}" -f $searcher.SearchRoot.distinguishedName[0]) -Server $Server -Credential $Credential
        }
        
        Write-PSFMessage -Level InternalComment -String 'Get-LdapObject.Search' -StringValues $SearchScope, $searcher.SearchRoot.Path
        
        if ($Credential) {
            $searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry($searcher.SearchRoot.Path, $Credential.UserName, $Credential.GetNetworkCredential().Password)
        }
        
        $searcher.Filter = $LdapFilter
        
        foreach ($propertyName in $Property) {
            $null = $searcher.PropertiesToLoad.Add($propertyName)
        }
        
        Write-PSFMessage -String 'Get-LdapObject.Filter' -StringValues $ldapFilter
        #endregion Prepare Searcher
    }
    process {
        try {
            $ldapObjects = $searcher.FindAll()
        }
        catch {
            throw
        }
        foreach ($ldapobject in $ldapObjects) {
            if ($Raw) {
                $ldapobject
                continue
            }
            #region Process/Refine Output Object
            $resultHash = @{ }
            foreach ($key in $ldapobject.Properties.Keys) {
                $resultHash[(Get-PropertyName -Key $key -Property $Property)] = switch ($key) {
                    'ObjectClass' { $ldapobject.Properties[$key][@($ldapobject.Properties[$key]).Count - 1] }
                    'ObjectGuid' { [guid]::new(([byte[]]($($ldapobject.Properties[$key])))) }
                    'ObjectSID' { [System.Security.Principal.SecurityIdentifier]::new(([byte[]]$($ldapobject.Properties[$key])), 0) }
                        
                    default { $($ldapobject.Properties[$key]) }
                }
            }
            if ($resultHash.ContainsKey("ObjectClass")) { $resultHash["PSTypeName"] = $resultHash["ObjectClass"] }
            if ($TypeName) { $resultHash["PSTypeName"] = $TypeName }
            if ($AddProperty) { $resultHash += $AddProperty }
            $item = [pscustomobject]$resultHash
            Add-Member -InputObject $item -MemberType ScriptMethod -Name ToString -Value {
                if ($this.DistinguishedName) { $this.DistinguishedName }
                else { $this.AdsPath }
            } -Force -PassThru
            #endregion Process/Refine Output Object
        }
    }
}

function Resolve-Fqca {
    <#
    .SYNOPSIS
        Resolves the fully qualified CA Name of the specified CA.
     
    .DESCRIPTION
        Resolves the fully qualified CA Name of the specified CA.
        If an FQCA is specified, it will just return it without verification.
        Otherwise it will try to use the ComputerName and PSRemoting to read the CA name from the service configuration.
 
        This command will never generate an error.
     
    .PARAMETER ComputerName
        Name of the computer hosting the CA
     
    .PARAMETER Credential
        Credentials to use for the remoting lookup.
     
    .PARAMETER FQCAName
        The fully qualified CA Name.
     
    .EXAMPLE
        PS C:\> Resolve-Fqca -ComputerName $ComputerName -Credential $Credential -FQCAName $FQCAName
 
        Resolves the FQCA of the specified CA.
    #>

    [CmdletBinding()]
    param (
        [AllowNull()]
        [PSFComputer]
        $ComputerName,

        [AllowNull()]
        [PSCredential]
        $Credential,

        [AllowEmptyString()]
        [string]
        $FQCAName
    )
    process {
        if (-not ($ComputerName -or $FQCAName)) {
            [PSCustomObject]@{
                Success = $false
                Name    = $null
                FQCA    = $null
                Error   = 'Neither ComputerName nor FQCA were specified!'
            }
            return
        }

        if ($FQCAName) {
            [PSCustomObject]@{
                Success = $true
                Name    = $FQCAName -replace '^.+?\\'
                FQCA    = $FQCAName
                Error   = $null
            }
            return
        }

        $code = {
            $result = [PSCustomObject]@{
                Success = $false
                Name    = $null
                FQCA    = $null
                Error   = $null
            }
            try { $result.Name = (Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\CertSvc\Configuration' -Name Active -ErrorAction Stop).Active }
            catch {
                $result.Error = $_
                return $result
            }
            $result.FQCA = "$($env:COMPUTERNAME)\$($result.Name)"
            $result.Success = $true
            $result
        }

        $param = @{ }
        if ($ComputerName) { $param.ComputerName = $ComputerName }
        if ($Credential) { $param.Credential = $Credential }
        
        try { Invoke-PSFCommand @param -ErrorAction Stop -ScriptBlock $code }
        catch {
            [PSCustomObject]@{
                Success = $false
                Name    = $null
                FQCA    = $null
                Error   = $_
            }
        }
    }
}

function Get-PkiCaExpiringCertificate {
    <#
    .SYNOPSIS
        Retrieve a list of certificates about to expire.
     
    .DESCRIPTION
        Retrieve a list of certificates about to expire.
        Also includes information, whether the certificate has already been renewed or not.
     
    .PARAMETER ComputerName
        The computername of the CA (automatically detects the CA name)
        Specifying this will cause the command to use PowerShell remoting.
 
    .PARAMETER Credential
        The credentials to use when connecting to the server.
        Only used in combination with -ComputerName.
         
    .PARAMETER FQCAName
        The fully qualified name of the CA.
        Specifying this allows remote access to the target CA.
        '<Computername>\<CA Name>'
     
    .PARAMETER DaysExpirationThreshold
        Only certificates that are still valid but will expire in the specified number of days will be returned.
        Defaults to: 14
     
    .PARAMETER TemplateName
        Only certificates of the specified template are being returned.
     
    .EXAMPLE
        PS C:\> Get-PkiCaExpiringCertificate
 
        Get all issued certificates that will expire in the next 14 days.
    #>

    
    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PSFComputer[]]
        $ComputerName,

        [pscredential]
        $Credential,

        [string]
        $FQCAName,
        
        [int]
        $DaysExpirationThreshold = 14,
        
        [PsfArgumentCompleter('PkiExtension.TemplateName')]
        [string]
        $TemplateName
    
    )
    
    begin {
        $ThresholdDate = (Get-Date).AddDays($DaysExpirationThreshold)
    }
    process {
        $param = $PSBoundParameters | ConvertTo-PSFHashtable -ReferenceCommand Get-PkiCaIssuedCertificate
        $allCerts = Get-PkiCaIssuedCertificate @param | Select-PSFObject -KeepInputObject -TypeName PkiExtension.ExpiringCertificate

        $expiredCerts = $allCerts | Where-Object {
            ($_.CertificateExpirationdate -lt $ThresholdDate) -and
            (
                (-not $TemplateName) -or
                ($_.CertificateTemplate -eq $TemplateName) -or
                ($_.TemplateDisplayName -eq $TemplateName)
            )
        }

        $notExpiredCerts = $allCerts | Where-Object CertificateExpirationDate -GE $ThresholdDate | Where-Object {
            (-not $TemplateName) -or
            ($_.CertificateTemplate -eq $TemplateName) -or
            ($_.TemplateDisplayName -eq $TemplateName)
        }
        $alreadyRenewedExpiredCerts = $expiredCerts | Where-Object IssuedCommonname -In $notExpiredCerts.IssuedCommonname
        $renewalPendingCerts = $expiredCerts | Where-Object IssuedCommonname -NotIn $notExpiredCerts.IssuedCommonname
        $alreadyRenewedExpiredCerts | Add-Member -MemberType NoteProperty -Name CertStatus -Value Renewed -PassThru
        $renewalPendingCerts | Add-Member -MemberType NoteProperty -Name CertStatus -Value RenewalPending -PassThru
    }
}

function Get-PkiCaIssuedCertificate {
    <#
    .SYNOPSIS
        Lists issued certificates.
     
    .DESCRIPTION
        Lists issued certificates.
     
    .PARAMETER ComputerName
        The computername of the CA (automatically detects the CA name)
        Specifying this will cause the command to use PowerShell remoting.
 
    .PARAMETER Credential
        The credentials to use when connecting to the server.
        Only used in combination with -ComputerName.
         
    .PARAMETER FQCAName
        The fully qualified name of the CA.
        Specifying this allows remote access to the target CA.
        '<Computername>\<CA Name>'
 
    .PARAMETER CommonName
        Filter by common name.
 
    .PARAMETER RequestID
        Search for a certificate by its specific request ID.
 
    .PARAMETER Requester
        Search for certificates by who requested them.
 
    .PARAMETER TemplateName
        Search for certificates by the template they were made from.
     
    .PARAMETER Properties
        The properties to retrieve.
        These are the headers as shown in the CA mmc console on an English languaged device.
        The result objects will have the same properties, but without the whitespace.
 
    .PARAMETER Server
        The active directory server to contact using LDAP.
        Used to resolve the templates used.
     
    .EXAMPLE
        PS C:\> Get-PkiCaIssuedCertificate
     
        Returns all issued certificates from the current computer (assumes localhost is a CA)
 
    .EXAMPLE
        PS C:\> Get-PkiCaIssuedCertificate -FQCAName "ca.contoso.com\MS-CA-01"
 
        Returns all issued certificates from the CA "ca.contoso.com\MS-CA-01"
        Requires the local computer to have the CA management tools installed
 
    .EXAMPLE
        PS C:\> Get-PkiCaIssuedCertificate -Computername ca.contoso.com
 
        Returns all issued certificate from ca.contoso.com.
        Requires PS remoting access to the target computerh osting the CA service.
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")]
    [CmdletBinding()]
    param (
        [PSFComputer[]]
        $ComputerName,

        [PSCredential]
        $Credential,
        
        [string]
        $FQCAName,

        [string]
        $CommonName,

        [int]
        $RequestID,

        [string]
        $Requester,

        [PsfArgumentCompleter('PkiExtension.TemplateName')]
        [string]
        $TemplateName,
        
        [String[]]
        $Properties = (
            'Issued Common Name',
            'Certificate Expiration Date',
            'Certificate Effective Date',
            'Certificate Template',
            'Issued Request ID',
            'Certificate Hash',
            'Request Disposition Message',
            'Requester Name',
            'Binary Certificate'
        ),

        [string]
        $Server
    )
    begin {
        $tmplParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        $templates = Get-PkiTemplate @tmplParam
        
        $data = @{
            FQCAName     = $FQCAName
            Properties   = $Properties
            Templates    = $templates
            CommonName   = $CommonName
            RequestID    = $RequestID
            Requester    = $Requester
            TemplateName = $TemplateName
        }

        $parameters = @{
            ArgumentList = $data
        }
        if ($ComputerName) {
            $parameters["HideComputerName"] = $true
            $parameters["ComputerName"] = $ComputerName
            if ($Credential) {
                $parameters['Credential'] = $Credential
            }
        }
    }
    process {
        Invoke-PSFCommand @parameters -ScriptBlock {
            param (
                $Data
            )

            # Copy variables over
            foreach ($pair in $Data.GetEnumerator()) {
                Set-Variable -Name $pair.Key -Value $pair.Value
            }

            $ErrorActionPreference = 'Stop'
            trap {
                Write-Warning "Error retrieving Certificate information: $_"
                throw $_
            }
            
            #region Preparation CA Connect
            try { $caView = New-Object -ComObject CertificateAuthority.View }
            catch { throw "Unable to create Certificate Authority View. $env:COMPUTERNAME does not have ADSC Installed" }
            
            if ($FQCAName) {
                $null = $CaView.OpenConnection($FQCAName)
            }
            else {
                $caName = (Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\CertSvc\Configuration' -Name Active).Active
                $null = $caView.OpenConnection("$($env:COMPUTERNAME)\$($caName)")
            }
            $CaView.SetResultColumnCount($Properties.Count)
            
            foreach ($item in $Properties) {
                $index = $caView.GetColumnIndex($false, $item)
                $caView.SetResultColumn($index)
            }
            
            # https://learn.microsoft.com/en-us/windows/win32/api/certview/nf-certview-icertview-setrestriction
            $CVR_SEEK_EQ = 1
            # $CVR_SEEL_LE = 2
            # $CVR_SEEK_LT = 4
            # $CVR_SEEK_GE = 8
            # $CVR_SEEK_GT = 16

            $CVR_SORT_NONE = 0
            
            # 20 - issued certificates
            $caView.SetRestriction($caView.GetColumnIndex($false, 'Request Disposition'), $CVR_SEEK_EQ, $CVR_SORT_NONE, 20)
            if ($CommonName) { $caView.SetRestriction($caView.GetColumnIndex($false, 'Issued Common Name'), $CVR_SEEK_EQ, $CVR_SORT_NONE, $CommonName) }
            if ($RequestID) { $caView.SetRestriction($caView.GetColumnIndex($false, 'Issued Request ID'), $CVR_SEEK_EQ, $CVR_SORT_NONE, $RequestID) }
            if ($Requester) { $caView.SetRestriction($caView.GetColumnIndex($false, 'Requester Name'), $CVR_SEEK_EQ, $CVR_SORT_NONE, $Requester) }
            if ($TemplateName) {
                $templateID = ($Templates | Where-Object DisplayName -EQ $TemplateName).'msPKI-Cert-Template-OID'
                if (-not $templateID) { $templateID = $TemplateName }
                $caView.SetRestriction($caView.GetColumnIndex($false, 'Certificate Template'), $CVR_SEEK_EQ, $CVR_SORT_NONE, $templateID)
            }

            
            $CV_OUT_BASE64HEADER = 0
            $CV_OUT_BASE64 = 1
            $RowObj = $caView.OpenView()
            #endregion Preparation CA Connect
            
            #region Process Certificates
            while ($RowObj.Next() -ne -1) {
                #region Process Properties
                $Cert = @{
                    PSTypeName = "PkiExtension.IssuedCertificate"
                }
                $ColObj = $RowObj.EnumCertViewColumn()
                $null = $ColObj.Next()
                do {
                    $displayName = $ColObj.GetDisplayName()
                    # format Binary Certificate in a savable format.
                    if ($displayName -eq 'Binary Certificate') {
                        $Cert[$displayName.Replace(" ", "")] = $ColObj.GetValue($CV_OUT_BASE64HEADER)
                        $Cert['Certificate'] = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(([System.Text.Encoding]::UTF8.GetBytes($Cert[$displayName.Replace(" ", "")])))
                    }
                    else { $Cert[$displayName.Replace(" ", "")] = $ColObj.GetValue($CV_OUT_BASE64) }
                }
                until ($ColObj.Next() -eq -1)
                Clear-Variable -Name ColObj
                #endregion Process Properties
                
                #region Process Template Name
                $Cert['TemplateDisplayName'] = $null
                if ($Cert.CertificateTemplate) {
                    try {
                        $Cert['TemplateDisplayName'] = ($Templates | Where-Object msPKI-Cert-Template-OID -EQ $Cert.CertificateTemplate).DisplayName
                        if (-not $Cert['TemplateDisplayName']) {
                            $Cert['TemplateDisplayName'] = ($Templates | Where-Object Name -EQ $Cert.CertificateTemplate).DisplayName
                        }
                        if (-not $Cert['TemplateDisplayName']) { $Cert['TemplateDisplayName'] = $Cert.CertificateTemplate }
                        if ($Cert['Certificate']) { Add-Member -InputObject $Cert['Certificate'] -MemberType NoteProperty -Name TemplateDisplayName -Value $Cert['TemplateDisplayName'] }
                    }
                    catch { }
                }
                #endregion Process Template Name
                
                [pscustomobject]$Cert | Add-Member -MemberType ScriptMethod -Name ToString -Value { $this.IssuedCommonName } -Force -PassThru
            }
            #endregion Process Certificates
        } | Select-PSFObject -KeepInputObject -TypeName 'PkiExtension.IssuedCertificate'
    }
}

function Revoke-PkiCaCertificate {
    <#
    .SYNOPSIS
        Revokes a certificate.
     
    .DESCRIPTION
        Revokes a certificate.
     
    .PARAMETER ComputerName
        The computername of the CA (automatically detects the CA name)
        Specifying this will cause the command to use PowerShell remoting.
 
    .PARAMETER Credential
        The credentials to use when connecting to the server.
        Only used in combination with -ComputerName.
         
    .PARAMETER FQCAName
        The fully qualified name of the CA.
        Specifying this allows remote access to the target CA.
        '<Computername>\<CA Name>'
     
    .PARAMETER Certificate
        The certificate to revoke.
        Can be a plain certificate object (X509Certificate2) or the result of Get-PkiCaIssuedCertificate.
     
    .PARAMETER Reason
        Why the certificate is being revoked.
        Defaults to "Unspecified"
 
    .PARAMETER RevocationDate
        Starting when the certificate is considered invalid.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
 
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .EXAMPLE
        PS C:\> Get-PkiCaIssuedCertificate | Revoke-PkiCaCertificate
 
        Create havoc.
        Revokes all issued certificates from the local CA.
        NOTE: THIS IS USUALLY A BAD IDEA!
 
    .EXAMPLE
        PS C:\> Revoke-PkiCaCertificate -Certificate $cert -Computername ca.contoso.com
 
        Revokes the certificate stored from the CA on ca.contoso.com
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
    Param (
        [PSFComputer]
        $ComputerName = $env:COMPUTERNAME,

        [pscredential]
        $Credential,

        [string]
        $FQCAName,
      
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $Certificate,

        [ValidateSet('Unspecified', 'KeyCompromise', 'CACompromise', 'AffiliationChanged', 'Superseded', 'CessationOfOperation', 'CertificateHold')]
        [string]
        $Reason = 'Unspecified',

        [DateTime]
        $RevocationDate = [DateTime]::Now,

        [switch]
        $EnableException
    )

    begin {
        $reasonCodes = @{
            Unspecified          = 0
            KeyCompromise        = 1
            CACompromise         = 2
            AffiliationChanged   = 3
            Superseded           = 4
            CessationOfOperation = 5
            CertificateHold      = 6
        }

        $param = $PSBoundParameters | ConvertTo-PSFHashtable -Include ComputerName, Credential

        $result = Resolve-Fqca -ComputerName $ComputerName -Credential $Credential -FQCAName $FQCAName
        if (-not $result.Success) {
            Stop-PSFFunction -String 'Revoke-PkiCaCertificate.Error.FqcaNotResolved' -StringValues $ComputerName, $result.Error -Cmdlet $PSCmdlet -EnableException $EnableException -Category ObjectNotFound
            return
        }
        $caName = $result.FQCA
    }
    process {
        if (Test-PSFFunctionInterrupt) { return }

        ForEach ($certificateObject in $Certificate) {
            $currentItem = $null
            if ($certificateObject -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
                $currentItem = $certificateObject
            }
            elseif ($certificateObject.certificate -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
                $currentItem = $certificateObject.Certificate
            }
            else {
                Stop-PSFFunction -String "Revoke-PkiCaCertificate.Error.NotACertificate" -StringValues $certificateObject -EnableException $EnableException -Continue -Target $certificateObject
            }

            $config = @{
                FQCA           = $caName
                SerialNumber   = $currentItem.SerialNumber
                Reason         = $reasonCodes[$Reason]
                RevocationDate = $RevocationDate.ToUniversalTime()
            }

            Invoke-PSFProtectedCommand -ActionString 'Revoke-PkiCaCertificate.Revoking' -ActionStringValues $currentItem.Subject, $currentItem.NotAfter, $caName -Target $currentItem -ScriptBlock {
                Invoke-PSFCommand @param -ErrorAction Stop -ScriptBlock {
                    param ($Config)
                    try { $COMcertAdmin = New-Object -ComObject CertificateAuthority.Admin }
                    catch { throw "Failed to load PKI Com Object. Ensure the PKI Admin tools are installed correctly! $_" }
                    try { $COMcertAdmin.RevokeCertificate($Config.FQCA, $Config.SerialNumber, $Config.Reason, $Config.RevocationDate) }
                    catch { throw "Failed to revoke certificate $($Config.SerialNumber) against $($Config.FQCA)"}
                    finally { $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($COMcertAdmin) }
                } -ArgumentList $config
            } -EnableException $EnableException -PSCmdlet $PSCmdlet -Continue
        }
    }
}

function Get-PkiTemplate {
    <#
    .SYNOPSIS
        Retrieve templates from Active Directory.
     
    .DESCRIPTION
        Retrieve templates from Active Directory.
        Templates are stored forest-wide and selectively made available to CAs.
        This command retrieves the global list.
     
    .PARAMETER Server
        The domain or server to contact.
     
    .PARAMETER Credential
        The credential to use for the request.
     
    .EXAMPLE
        PS C:\> Get-PkiTemplate
 
        Retrieve all templates from the current forest.
    #>

    [CmdletBinding()]
    param (
        [string]
        $Server,

        [PSCredential]
        $Credential
    )
    process {
        $param = $PSBoundParameters | ConvertTo-PSFHashtable -ReferenceCommand Get-LdapObject
        $param.LdapFilter = '(objectClass=pKICertificateTemplate)'
        $param.TypeName = 'PkiExtension.Template'
        $param.Configuration = $true
        $param.TypeName = 'PkiExtension.Template'
        Get-LdapObject @param
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'PkiExtension' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'PkiExtension' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'PkiExtension' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'PkiExtension.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "PkiExtension.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


Register-PSFTeppScriptblock -Name 'PkiExtension.TemplateName' -ScriptBlock {
    $param = @{ }
    if ($fakeBoundParameter.Server) { $param.Server = $fakeBoundParameter.Server }
    elseif ($fakeBoundParameter.ComputerName -match '\.') {
        $param.Server = $fakeBoundParameter.ComputerName -replace '^.+?\.'
    }
    if ($fakeBoundParameter.Credential) { $param.Credential = $Credential }

    (Get-PkiTemplate @param).DIsplayName
} -Global

<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name PkiExtension.alcohol
#>


New-PSFLicense -Product 'PkiExtension' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2023-10-07") -Text @"
Copyright (c) 2023 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code