Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Last active October 2, 2026 20:29
Show Gist options
  • Select an option

  • Save jstangroome/5945820 to your computer and use it in GitHub Desktop.

Select an option

Save jstangroome/5945820 to your computer and use it in GitHub Desktop.
PowerShell script to retrieve the public X509 certificate from a remote TLS endpoint
[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
}
Write-Output $Certificate
}
@hertus

hertus commented Jan 23, 2020

Copy link
Copy Markdown

thanks

@msajeesh

msajeesh commented Sep 13, 2020 •

Copy link
Copy Markdown

This works perfectly but we have to enter server names manually..how to find out SSL certificate installed servers in a domain ?

ghost commented Nov 5, 2020

Copy link
Copy Markdown

great, thank you!

@euyuil

euyuil commented Jan 7, 2021

Copy link
Copy Markdown

Thanks! Do this work for SNI?

@jstangroome

Copy link
Copy Markdown
Author

@euyuil if line 23 $SslStream.AuthenticateAsClient('') is modified to pass a SNI host name instead of the empty string as its argument, it should work, but I have not verified.

@sahmedz11

Copy link
Copy Markdown

Is there a timeout value or validation of certificate?

@jstangroome

Copy link
Copy Markdown
Author

@sahmedz11 As it is currently written, the script will use default .NET timeouts. You can augment the script to set $TcpClient.ReceiveTimeout or .SendTimeout to manage timeouts during the TLS handshake. There is also $SslStream.ReadTimeout and .WriteTimeout which could be set, but I'm not sure if these apply during the AuthenticateAsClient() call.

To implement a custom TCP connection handshake timeout, significant changes would be required to replace $TcpClient.Connect(...) with $TcpClient.BeginConnect(...) instead and implement an AsyncCallback which is possible in PowerShell but not something I have tried.

The script also very explicitly does not perform any certificate validation, its purpose is to return the certificate for deeper inspection, valid or not. However you can modify the $Callback = { ... } line to capture and report any validation errors, or perform additional custom validation.

@ericcsinger

Copy link
Copy Markdown

Just wanted to say this is awesome, thanks!

@Grundel1979

Copy link
Copy Markdown

Thank you!. This is great!

@richardhicks

Copy link
Copy Markdown

Would it be possible to save the certificate to a file as well?

@jstangroome

Copy link
Copy Markdown
Author

@richardhicks you can call .Export(...) on the returned certificate object, specify the desired certificate file format as the argument, then pass the output bytes to Set-Content, e.g.:

$cert=(Get-RemoteSSLCertificate.ps1 foo.com)
Set-Content file.cer -Encoding Byte -Value $cert.Export('Cert')

Untested.

@richardhicks

Copy link
Copy Markdown

Thanks. I'll give it a try. Also, confirmed that adding the hostname to $SslStream.AuthenticateAsClient('') (e.g., $SslStream.AuthenticateAsClient('foo.example.net') works for sites configured with SNI.

@spawnmarvel

Copy link
Copy Markdown

Thanks

@scarson

scarson commented Sep 26, 2023 •

Copy link
Copy Markdown

I modified my copy of the script to write the certificate to file with:

$CertExportDirectory = 'C:\temp\'
$CertExportName = $ComputerName + '_Port' + $Port.ToString() + '.cer'
$FilePath = Join-Path $CertExportDirectory  -Child $CertExportName
Export-Certificate -Cert $Certificate -FilePath $FilePath

With output like "C:\temp\example.com_Port443.cer"

I also run a validation check with:
Test-Certificate $Certificate

You may want to set some of the non-default Test-Certificate parameters depending on use case.

@goadeff

goadeff commented Nov 1, 2023

Copy link
Copy Markdown

Any ideas how to adapt this for retrieval of the certificate used by a remote SQL server (i.e. port 1433)? The script hangs at $SslStream.AuthenticateAsClient('') when I try to use it this way.

@dmoroney

dmoroney commented Oct 2, 2026 •

Copy link
Copy Markdown

I passed on the callback and used timeouts instead. I also wanted the TCP/SSL exception strings.

function Get-X509RemoteCertificate {
    <#
    .SYNOPSIS
    Get the server certificate presented from a website or server without logging in.
    .DESCRIPTION
    Get the server certificate presented from a website or server without logging in.

    Certificate Exchange Process
    1. ClientHello: The client initiates the handshake by sending a ClientHello message,
    which includes supported cipher suites and SSL/TLS versions.

    2. ServerHello: The server responds with a ServerHello message, selecting the cipher suite and
    SSL/TLS version.

    3. Certificate Message: If certificate-based authentication is used, the server sends its
    certificate immediately after the ServerHello message.

    4. Key Exchange: In TLS 1.2 and earlier, the client encrypts a pre-master secret with the server
    RSA public key. In TLS 1.3, the process is streamlined, and the Certificate message is mandatory
    for authentication.

    This method does not perform the Key Exchange. The connection is closed immediately after receiving
    the Certificate Message, and the server certificate is returned. In the case of an error, then the
    reason for the TCP/SSL/TLS failure is returned.

    The method does not make any provision for choosing a Transport Layer Security protocol, that
    determination is left to the client and server to negotiate.
    .PARAMETER ServerName
    The Remote Server FQDN or a collection of FQDNs to query for their Server Certificates.
    .PARAMETER PortNumber
    The Remote Server port number listening for Server Certificate queries.
    .PARAMETER TimeoutSeconds
    Set the amount of time, expressed in Seconds, the read/write operations block waiting for data.
    This parameter is applied to the TCP client and SSL stream to avoid no time-out states that could
    block indefinitely.
    .EXAMPLE
    Get-X509ServerCertificate -RemoteServers "server.domain.com" -PortNumber 443

    Get the remote Server Certificate from the the provided named parameters.
    .EXAMPLE
    Get-X509ServerCertificate "server.domain.com" 443

    Get the remote Server Certificate from the provided positional parameters.
    .EXAMPLE
    "server.domain.com" | Get-X509ServerCertificate -PortNumber 443

    Get the remote Server Certificate from the provided input pipeline.
    .LINK
    https://gist.github.com/jstangroome/5945820
    .LINK
    https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=net-10.0
    .LINK
    https://learn.microsoft.com/en-us/dotnet/api/system.net.security.sslstream?view=net-10.0
    .INPUTS
    string
    .OUTPUTS
    Ovcerloaded System.Security.Cryptography.X509Certificates.X509Certificate or TCP/SSL exception.
    .NOTES
    Released under the terms of the MIT License.
    #>

    [OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$ServerName,

        [Parameter(Mandatory = $false, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [ValidateRange(0, 65535)]
        [int]$PortNumber = 443,

        [Parameter(Mandatory = $false, Position = 2)]
        [ValidateNotNullOrEmpty()]
        [ValidateRange(0.0, 120.0)]
        [float]$TimeoutSeconds = 5.0
    )

    Process {
        $ServerName | ForEach-Object {
            try {
                $tcpClient = New-Object System.Net.Sockets.TcpClient($_, $PortNumber)
                $tcpClient.ReceiveTimeout = $TimeoutSeconds * 1000
            }
            catch {
                # DNS resolution error or unbound server port
                return "TCP: $($(($_ -split ":", 2)[-1]).Replace('"', '').Trim())"
            }

            # overload certificate with the Server Certificate or the SSL exception string
            $certificate = $null
            try {
                $sslStream = New-Object System.Net.Security.SslStream($tcpClient.GetStream())
                $sslStream.ReadTimeout = $TimeoutSeconds * 1000
                $sslStream.WriteTimeout = $TimeoutSeconds * 1000
                try {
                    $sslStream.AuthenticateAsClient($_)
                    $certificate = $sslStream.RemoteCertificate
                }
                catch {
                    # the remote certificate is invalid...
                    $certificate = "SSL: $($(($_ -split ":", 2)[-1]).Replace('"', '').Trim())"
                }
                finally {
                    $sslStream.Dispose()
                }
            }
            catch {
                # unknown exception
                $certificate = "SSL: $($_)"
            }
            finally {
                $tcpClient.Dispose()
            }
            $certificate
        }
    }
}

Example user code

function Write-X509CertificateStatus {
    <#
    .SYNOPSIS
    Report when a Remote Server Certificate expires.
    .DESCRIPTION
    Report when a Remote Server Certificate expires.
    .PARAMETER ServerName
    One or many Remote Servers to query for its current Server Certificate.
    .PARAMETER PortNumber
    The Remote Server port number listening for Server Certificate queries.
    .EXAMPLE
    $ServersList = @('server1', 'server2')
    Get-CertificateExpiration -ServerName $ServersList

    Get the remote Server Certificate(s) from the the provided named parameter.
    .EXAMPLE
    $ServersList = @('server1', 'server2')
    Get-CertificateExpiration $ServersList

    Get the remote Server Certificate(s) from the the provided positional parameter.
    .EXAMPLE
    $ServersList = @('server1', 'server2')
    $ServersList | Get-CertificateExpiration

    Get the remote Server Certificate(s) from the the provided input pipeline.
    .EXAMPLE
    'server1', 'server2' | Get-CertificateExpiration

    Get the remote Server Certificate(s) from the the provided input pipeline.
    .INPUTS
    Array of strings
    .OUTPUTS
    PSCustomObject
    #>

    [OutputType([PSCustomObject])]
    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string[]]$ServerName,

        [Parameter(Mandatory = $false, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [ValidateRange(0, 65535)]
        [int]$PortNumber = 443
    )

    Process {
        $ServerName | ForEach-Object {
            # $cert is overloaded with the server certificate or a TCP/SSL exception string
            $cert = $_ | Get-X509RemoteCertificate -PortNumber $PortNumber

            if ($cert -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
                $dnsName = (($cert.SubjectName.Name.Split('CN='))[1]).Split(',')[0]
                $notAfter = (Get-Date $cert.NotAfter -Format "yyyy-MM-dd")
                $days = ($cert.NotAfter - (Get-Date)).Days
                $errorReason = $null
            }
            else {
                $dnsName = $_
                $notAfter = $null
                $days = $null
                $errorReason = $cert
            }

            $result = [ordered]@{
                "DNS Name"       = ($dnsName).ToLower()
                "Certificate"    = ($errorReason) ? "FAIL" : "PASS"
                "Expires On"     = $notAfter
                "Days Remaining" = $days
                "Errors"         = $errorReason
            }
            [PSCustomObject]$result
        }
    }
}

Example command lines

'server1.domain', 'server2.domain' | Write-X509CertificateStatus
'sqlserver.domain' | Write-X509CertificateStatus -PortNumber 1433
Write-X509CertificateStatus -ServerName 'sqlserver.domain' -PortNumber 1433

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment