lib/TMD.Certificates.ps1

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
function Get-RemoteSSLCertificate {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]
        $ComputerName,
    
        [int]
        $Port = 443
    )
    
    $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('')
            $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
    }
}