Sanjay Bangalore
Sanjay Bangalore

Reputation: 81

Powershell find webserver certificate expiration with context in URL

need help with Powershell. We need to find server certificate expiration using powershell. These are weblogic console Urls. The URLs have context and port like https://server:7020/context . If I browse URL without context, I get error -

Error 404--Not Found
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.4.5 404 Not Found

I have tried with following code -

Try{
$Conn = New-Object 

System.Net.Sockets.TcpClient($WebsiteURL,$WebsitePort)

Try {
$Stream = New-Object 

System.Net.Security.SslStream($Conn.GetStream(),$false, {

param($sender, $certificate, $chain, $sslPolicyErrors)
return $true
})
$Stream.AuthenticateAsClient($CommonName) 

If I try a server without context it gives following error -

A call to SSPI failed, see inner exception.

What are commands and options to query in powershell? Any help is appreciated.

Upvotes: 0

Views: 551

Answers (1)

CrookedJ
CrookedJ

Reputation: 338

Using Get-RemoteSslCertificate from jstangroome you can simply run the following to return the expiration.

(Get-RemoteSslCertificate -ComputerName server -Port 7020).NotAfter

The Get-RemoteSslCertificate function:

function Get-RemoteSslCertificate {
    # Author: jstangroome https://gist.github.com/jstangroome/5945820
    [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
    }
}

Upvotes: 4

Related Questions