-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCertificates.ps1
More file actions
233 lines (193 loc) · 8.12 KB
/
Certificates.ps1
File metadata and controls
233 lines (193 loc) · 8.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<#
.SYNOPSIS
Find a certificate in the local certificate store
.DESCRIPTION
Different parameters can be supplied to find the certificate in the local certificate store.
All certificate locations are parsed. If several certificates match the search criteria, all are returned.
#>
function Find-Certificate {
[CmdletBinding(DefaultParameterSetName = 'Thumbprint')]
param (
# An X509Certificate2 object to look for in the local certificate store
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
# The thumbprint of the certificate to look for
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Thumbprint')]
[string[]] $Thumbprint,
# The subject of the certificate to look for
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Subject')]
[string[]] $Subject,
# The issuer of the certificate to look for
[Parameter(Mandatory, ParameterSetName = 'Issuer')]
[string[]] $Issuer
)
begin {
try {
$storedCerts = Get-ChildItem -Path Cert:\ -Recurse -ErrorAction SilentlyContinue
} catch {}
}
process {
$matchingCerts = @()
if ($Certificate) {
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
[void] $chain.Build($Certificate)
foreach ($chainElement in $chain.ChainElements) {
$matchingCerts += $storedCerts | Where-Object { $_ -eq $chainElement.Certificate }
}
} elseif ($Thumbprint) {
$matchingCerts = $storedCerts | Where-Object Thumbprint -In $Thumbprint
} elseif ($Subject) {
foreach ($sub in $Subject) {
$matchingCerts += $storedCerts | Where-Object Subject -Match $sub
}
} elseif ($Issuer) {
foreach ($iss in $Issuer) {
$matchingCerts += $storedCerts | Where-Object Issuer -Match $iss
}
}
}
end {
foreach ($matchingCert in $matchingCerts) {
Write-Verbose -Message "Found matching certificate at $(($matchingCert.PSPath -split '::')[-1]) ($($matchingCert.Subject))"
}
$matchingCerts
}
}
<#
.SYNOPSIS
Download a public certificate
.DESCRIPTION
Download a public certificate from a local or remote server and returns it as an X509Certificate2 object
#>
function Get-PublicCertificate {
[CmdletBinding()]
param (
# Host name or FQDN to connect to
[Parameter(Mandatory)]
[string] $ComputerName,
# Port number to connect to. 443 (HTTPS) by default.
[uint16] $Port = 443,
# Server Name Indication
[string] $SNI = ''
)
$certificate = $null
$tcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
try {
$tcpClient.Connect($ComputerName, $Port)
$tcpStream = $tcpClient.GetStream()
$callback = { param($sender, $cert, $chain, $errors) return $true }
$sslStream = New-Object -TypeName System.Net.Security.SslStream -ArgumentList @($tcpStream, $true, $callback)
try {
$sslStream.AuthenticateAsClient($SNI)
$certificate = $sslStream.RemoteCertificate
} finally {
$sslStream.Dispose()
}
} finally {
$tcpClient.Dispose()
}
if ($certificate) {
if ($certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $certificate
}
return $certificate
} else {
Write-Message -Type Warning "No certificate found at ${ComputerName}:$Port"
}
}
<#
.SYNOPSIS
Converts an end-entity certificate to a chained certificate
.DESCRIPTION
Converts a single end-entity certificate to a full chain of intermediary certificates all the way to a trusted root Certificate Authority.
.NOTES
Servers are supposed to present their own certificate as well as all intermediate certificates on the path to a trusted root Certificate Authority.
The root certificate is not required. Including it is inefficient as it increases the size of the SSL handshake.
#>
function ConvertTo-CertificateChain {
[CmdletBinding(DefaultParameterSetName = 'Certificate')]
param (
# The source certificate to convert
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
# The file path of the certificate to convert
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SourceFilePath')]
[string] $SourceFilePath,
# An optional file path where to write the chained certificate
[string] $ExportPath,
# Whether to include the root CA in the exported chained certificate
[switch] $IncludeRoot
)
process {
if ($SourceFilePath) {
$Certificate = if (Test-Path -Path $SourceFilePath) {
$file = Get-Item -Path $SourceFilePath
[System.Security.Cryptography.X509Certificates.X509Certificate2]::new($file.FullName)
} else {
$PSCmdlet.ThrowTerminatingError([System.Management.Automation.ErrorRecord]::new(
([System.IO.FileNotFoundException] "Could not find certificate file `"$SourceFilePath`""),
'PathNotFound',
[System.Management.Automation.ErrorCategory]::ObjectNotFound,
$SourceFilePath)
)
}
}
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
[void] $chain.Build($Certificate)
if ($ExportPath) {
Remove-Item -Path $ExportPath -Force -ErrorAction SilentlyContinue
for ($i = 0; $i -lt $chain.ChainElements.Count; $i++) {
if (!$IncludeRoot -and $i -eq ($chain.ChainElements.Count - 1)) {
break
}
ConvertTo-PemCertificate -Certificate $chain.ChainElements[$i].Certificate -ExportPath $ExportPath -Append
}
} else {
return $chain.ChainElements.Certificate
}
}
}
<#
.SYNOPSIS
Convert a certiticate to the PEM format
.DESCRIPTION
The PEM format is a Base64 ASCII string divided in 64-char long substrings and sandwiched between a standardized header and footer.
#>
function ConvertTo-PemCertificate {
[CmdletBinding(DefaultParameterSetName = 'Certificate')]
param (
# The source certificate to convert
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Certificate')]
[System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
# The file path of the certificate to convert
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SourceFilePath')]
[string] $SourceFilePath,
# An optional file path where to write the PEM certificate
[string] $ExportPath,
# If a file at ExportPath already exists, append the PEM certificate to the same file.
[switch] $Append
)
process {
if ($SourceFilePath) {
$Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($SourceFilePath)
}
$base64String = [System.Convert]::ToBase64String($Certificate.GetRawCertData())
if ($ExportPath) {
$base64String = ($base64String -split '(.{64})' | Where-Object { $_ }) -join "`n"
$params = @{
Path = $ExportPath
Value = "-----BEGIN CERTIFICATE-----`n$base64String`n-----END CERTIFICATE-----`n"
Encoding = 'ASCII'
Force = $true
NoNewline = $true
}
if ($Append) {
Add-Content @params
} else {
Set-Content @params
}
} else {
return $base64String
}
}
}