Modules/businessdev.ALbuild.Containers/Private/Get-BcRemoteCertificate.ps1
|
function Get-BcRemoteCertificate { <# .SYNOPSIS Retrieves the TLS server certificate presented by a host, without validating it. .DESCRIPTION Opens a TLS connection to the host and returns the server's certificate. Validation is intentionally bypassed so a self-signed BC container certificate can be read in order to trust it. Pure read - performs no changes. .PARAMETER DnsName Host name to connect to (also used for SNI). .PARAMETER Port TLS port (default 443). .PARAMETER TimeoutMs Connection timeout in milliseconds (default 10000). .OUTPUTS [System.Security.Cryptography.X509Certificates.X509Certificate2] #> [CmdletBinding()] [OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])] param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $DnsName, [int] $Port = 443, [int] $TimeoutMs = 10000 ) $client = [System.Net.Sockets.TcpClient]::new() try { $connect = $client.BeginConnect($DnsName, $Port, $null, $null) if (-not $connect.AsyncWaitHandle.WaitOne($TimeoutMs)) { throw "Timed out connecting to ${DnsName}:$Port." } $client.EndConnect($connect) $callback = [System.Net.Security.RemoteCertificateValidationCallback] { param($s, $c, $ch, $e) $true } $ssl = [System.Net.Security.SslStream]::new($client.GetStream(), $false, $callback) try { $ssl.AuthenticateAsClient($DnsName) return [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($ssl.RemoteCertificate) } finally { $ssl.Dispose() } } finally { $client.Dispose() } } |