Created
November 5, 2024 15:13
-
-
Save mcx808/85257f46e784ad7d96ad9136417f4c3b to your computer and use it in GitHub Desktop.
Get-RemoteCertificate.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-RemoteCertificate { | |
<# | |
.SYNOPSIS | |
Retrieves the SSL certificate from a remote server. | |
.DESCRIPTION | |
The Get-RemoteCertificate function connects to a specified remote server using its URI and retrieves the SSL certificate. It uses a TcpClient to establish the connection and an SslStream to perform the SSL handshake. The function returns the remote server's SSL certificate as an X509Certificate object. | |
.PARAMETER Uri | |
The URI of the remote server from which to retrieve the SSL certificate. This parameter is mandatory and accepts pipeline input. | |
.PARAMETER TimeoutMilliseconds | |
The timeout period in milliseconds for the connection attempt. The default value is 500 milliseconds. | |
.EXAMPLE | |
PS> Get-RemoteCertificate -Uri "https://example.com" | |
This command retrieves the SSL certificate from the server at https://example.com. | |
.EXAMPLE | |
PS> "https://example.com" | Get-RemoteCertificate | |
This command retrieves the SSL certificate from the server at https://example.com using pipeline input. | |
#> | |
[CmdletBinding()] | |
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate])] | |
param ( | |
[Parameter( | |
Mandatory, | |
ValueFromPipeline | |
)] | |
[ValidateNotNull()] | |
[Uri] | |
$Uri, | |
[int] | |
$TimeoutMilliseconds = 500 # Default timeout is 500 milliseconds | |
) | |
process { | |
try { | |
$TcpClient = [System.Net.Sockets.TcpClient]::new() | |
$connectTask = $TcpClient.ConnectAsync($Uri.Host, $Uri.Port) | |
if ($connectTask.Wait($TimeoutMilliseconds)) { | |
$SslStream = [System.Net.Security.SslStream]::new($TcpClient.GetStream(), $false, { $true }) | |
$SslStream.AuthenticateAsClient($Uri.Host) | |
$SslStream.RemoteCertificate | |
} | |
else { | |
Throw "Conenction Timeout" | |
} | |
} | |
catch { | |
Throw "$($_.Exception.Message)" | |
} | |
finally { | |
if ($TcpClient.Connected) { | |
$SslStream.Dispose() | |
} | |
$TcpClient.Close() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment