Skip to content

Commit

Permalink
Add command Find-Certificate (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
hollanjs authored and johlju committed Apr 6, 2023
1 parent bdcb533 commit e817645
Show file tree
Hide file tree
Showing 5 changed files with 797 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Added public function `Find-Certificate` that returns one or more
certificates using certificate selector parameters - [Issue #100](https://github.com/dsccommunity/DscResource.Common/issues/100)
- Related to [CertificateDsc Issue #272](https://github.com/dsccommunity/CertificateDsc/issues/272).

## [0.14.0] - 2022-12-31

### Added
Expand Down
76 changes: 76 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,82 @@ ConvertTo-HashTable -CimInstance $cimInstance
This creates a array om CimInstances of the class name MSFT_KeyValuePair
and passes it to ConvertTo-HashTable which returns a hashtable.

### `Find-Certificate`

A common function to find certificates based on multiple search filters,
including, but not limited to: Thumbprint, Friendly Name, DNS Names,
Key Usage, Issuers, etc.

Locates one or more certificates using the passed certificate selector
parameters.

If more than one certificate is found matching the selector criteria,
they will be returned in order of descending expiration date.

#### Syntax

```plaintext
Find-Certificate [[-Thumbprint] <String>] [[-FriendlyName] <String>]
[[-Subject] <String>] [[-DNSName] <String[]>] [[-Issuer] <String>]
[[-KeyUsage] <String[]>] [[-EnhancedKeyUsage] <String[]>] [[-Store] <String>]
[[-AllowExpired] <Boolean>] [<CommonParameters>]
```

### Outputs

**System.Security.Cryptography.X509Certificates.X509Certificate2**

### Example

```PowerShell
Find-Certificate -Thumbprint '1111111111111111111111111111111111111111'
```

Return certificate that matches thumbprint.

```PowerShell
Find-Certificate -KeyUsage 'DataEncipherment', 'DigitalSignature'
```

Return certificate(s) that have specific key usage.

```PowerShell
Find-Certificate -DNSName 'www.fabrikam.com', 'www.contoso.com'
```

Return certificate(s) filtered on specific DNS Names.

```PowerShell
find-certificate -Subject 'CN=contoso, DC=com'
```

Return certificate(s) with specific subject.

```PowerShell
find-certificate -Issuer 'CN=contoso-ca, DC=com' -AllowExpired $true
```

Return all certificates from specific issuer, including expired certificates.

```PowerShell
$findCertSplat = @{
EnhancedKeyUsage = @('Client authentication','Server Authentication')
AllowExpired = $true
}
Find-Certificate @findCertSplat
```

Return all certificates that can be used for server or client authentication,
including expired certificates.

```PowerShell
Find-Certificate -FriendlyName 'My SSL Cert'
```

Return certificate based on FriendlyName.


### `Get-ComputerName`

Returns the computer name cross-plattform. The variable `$env:COMPUTERNAME`
Expand Down
189 changes: 189 additions & 0 deletions source/Public/Find-Certificate.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
<#
.SYNOPSIS
Locates one or more certificates using the passed certificate selector parameters.
If more than one certificate is found matching the selector criteria, they will be
returned in order of descending expiration date.
.DESCRIPTION
A common function to find certificates based on multiple search filters, including,
but not limited to: Thumbprint, Friendly Name, DNS Names, Key Usage, Issuers, etc.
.PARAMETER Thumbprint
The thumbprint of the certificate to find.
.PARAMETER FriendlyName
The friendly name of the certificate to find.
.PARAMETER Subject
The subject of the certificate to find.
.PARAMETER DNSName
The subject alternative name of the certificate to export must contain these values.
.PARAMETER Issuer
The issuer of the certificate to find.
.PARAMETER KeyUsage
The key usage of the certificate to find must contain these values.
.PARAMETER EnhancedKeyUsage
The enhanced key usage of the certificate to find must contain these values.
.PARAMETER Store
The Windows Certificate Store Name to search for the certificate in.
Defaults to 'My'.
.PARAMETER AllowExpired
Allows expired certificates to be returned.
.EXAMPLE
Find-Certificate -Thumbprint '1111111111111111111111111111111111111111'
Return certificate that matches thumbprint.
.EXAMPLE
Find-Certificate -KeyUsage 'DataEncipherment', 'DigitalSignature'
Return certificate(s) that have specific key usage.
.EXAMPLE
Find-Certificate -DNSName 'www.fabrikam.com', 'www.contoso.com'
Return certificate(s) filtered on specific DNS Names.
.EXAMPLE
find-certificate -Subject 'CN=contoso, DC=com'
Return certificate(s) with specific subject.
.EXAMPLE
find-certificate -Issuer 'CN=contoso-ca, DC=com' -AllowExpired $true
Return all certificates from specific issuer, including expired certificates.
.EXAMPLE
Find-Certificate -EnhancedKeyUsage 'Server Authentication' -AllowExpired $true
Return all certificates that can be used for "Server Authentication", including expired certificates.
.EXAMPLE
Find-Certificate -FriendlyName 'My IIS Site SSL Cert'
Return certificate based on FriendlyName.
#>
function Find-Certificate
{
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2[]])]
param
(
[Parameter()]
[System.String]
$Thumbprint,

[Parameter()]
[System.String]
$FriendlyName,

[Parameter()]
[System.String]
$Subject,

[Parameter()]
[System.String[]]
$DNSName,

[Parameter()]
[System.String]
$Issuer,

[Parameter()]
[System.String[]]
$KeyUsage,

[Parameter()]
[System.String[]]
$EnhancedKeyUsage,

[Parameter()]
[System.String]
$Store = 'My',

[Parameter()]
[Boolean]
$AllowExpired = $false
)

$certPath = Join-Path -Path 'Cert:\LocalMachine' -ChildPath $Store

if (-not (Test-Path -Path $certPath))
{
# The Certificte Path is not valid
New-InvalidArgumentException `
-Message ($script:localizedData.CertificatePathError -f $certPath) `
-ArgumentName 'Store'
} # if

# Assemble the filter to use to select the certificate
$certFilters = @()

if ($PSBoundParameters.ContainsKey('Thumbprint'))
{
$certFilters += @('($_.Thumbprint -eq $Thumbprint)')
} # if

if ($PSBoundParameters.ContainsKey('FriendlyName'))
{
$certFilters += @('($_.FriendlyName -eq $FriendlyName)')
} # if

if ($PSBoundParameters.ContainsKey('Subject'))
{
$certFilters += @('($_.Subject -eq $Subject)')
} # if

if ($PSBoundParameters.ContainsKey('Issuer'))
{
$certFilters += @('($_.Issuer -eq $Issuer)')
} # if

if (-not $AllowExpired)
{
$certFilters += @('(((Get-Date) -le $_.NotAfter) -and ((Get-Date) -ge $_.NotBefore))')
} # if

if ($PSBoundParameters.ContainsKey('DNSName'))
{
$certFilters += @('(@(Compare-Object -ReferenceObject $_.DNSNameList.Unicode -DifferenceObject $DNSName | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)')
} # if

if ($PSBoundParameters.ContainsKey('KeyUsage'))
{
$certFilters += @('(@(Compare-Object -ReferenceObject ($_.Extensions.KeyUsages -split ", ") -DifferenceObject $KeyUsage | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)')
} # if

if ($PSBoundParameters.ContainsKey('EnhancedKeyUsage'))
{
$certFilters += @('(@(Compare-Object -ReferenceObject ($_.EnhancedKeyUsageList.FriendlyName) -DifferenceObject $EnhancedKeyUsage | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)')
} # if

# Join all the filters together
$certFilterScript = '(' + ($certFilters -join ' -and ') + ')'

Write-Verbose `
-Message ($script:localizedData.SearchingForCertificateUsingFilters -f $store, $certFilterScript) `
-Verbose

$certs = Get-ChildItem -Path $certPath |
Where-Object -FilterScript ([ScriptBlock]::Create($certFilterScript))

# Sort the certificates
if ($certs.count -gt 1)
{
$certs = $certs | Sort-Object -Descending -Property 'NotAfter'
} # if

return $certs
} # end function Find-Certificate
4 changes: 4 additions & 0 deletions source/en-US/DscResource.Common.strings.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,8 @@ ConvertFrom-StringData @'
## Assert-RequiredCommandParameter
RequiredCommandParameter_SpecificParametersMustAllBeSet = The parameters '{0}' must all be specified. (DRC0044)
RequiredCommandParameter_SpecificParametersMustAllBeSetWhenParameterExist = The parameters '{0}' must all be specified if either parameter '{1}' is specified. (DRC0045)
## Find-Certificate
CertificatePathError = Certificate Path '{0}' is not valid. (DRC0046)
SearchingForCertificateUsingFilters = Looking for certificate in Store '{0}' using filter '{1}'. (DRC0047)
'@
Loading

0 comments on commit e817645

Please sign in to comment.