functions/Get-RemoteCert.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
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
function Get-RemoteCert {
[cmdletbinding()]
param
(
[parameter(Mandatory=$true)][string]$computername,
[parameter(Mandatory=$false)]$port = 443,
$outfile,
[switch][bool]$accept,
$certstorelocation
)
    if ($computername.StartsWith("https")) {
        $uri = new-object Uri $computername
        $computername = $uri.host
        $port = $uri.Port
    }

    if ($port -in "powershell","rps","winrm") {
        $port = 5986
    }
    write-host "connecting to $computername on port $port"
    $tcpsocket = $null
    try {
        #Create a TCP Socket to the computer and a port number
        $tcpsocket = New-Object Net.Sockets.TcpClient($computerName, $port)
    } catch {
        write-error $_
    }

    #test if the socket got connected
    if(!$tcpsocket)
    {
        throw "Error Opening Connection: $port on $computername Unreachable"
    }
    else
    {
        #Socket Got connected get the tcp stream ready to read the certificate
        write-host "Successfully Connected to $computername on $port" -ForegroundColor Green -BackgroundColor Black
        $tcpstream = $tcpsocket.GetStream()
        Write-host "Reading SSL Certificate...." -ForegroundColor Yellow -BackgroundColor Black
        #Create an SSL Connection
        $sslStream = New-Object System.Net.Security.SslStream($tcpstream,$false, {
            param($sender, $certificate, $chain, $sslPolicyErrors) 
            return $true
        })

        try {
        #Force the SSL Connection to send us the certificate
        $sslStream.AuthenticateAsClient($computerName)
        } catch {
            $ex = $_.Exception
            while($ex -ne $null) {
                write-warning $ex.Message
                $ex = $ex.InnerException
            }
            throw
            
        }

        #Read the certificate
        $certinfo = New-Object system.security.cryptography.x509certificates.x509certificate2($sslStream.RemoteCertificate)

        
        if ($accept -and $outfile -eq $null) {
            $outfile = "$computername.crt"
        }
        if ($outfile -ne $null) {
            $certinfo | Export-Certificate -FilePath $outfile -Verbose
        }

        if ($accept) {
        if ($certstorelocation -eq $null) {
           $certstorelocation = "Cert:\CurrentUser\Trust"
        }
            Import-Certificate $outfile -CertStoreLocation $certstorelocation
        }

        return $certinfo
    }

}