如何检查部署到网站的证书链中包含哪些证书

问题描述

许多站点提供工具来帮助检查部署到站点的证书是否有效;包括检查是否安装了完整的链,而不仅仅是客户端证书。下面的一些例子:

我想通过 PowerShell 脚本模拟此检查(注意:目的是检查第三方站点;因此我们无法访问服务器端的任何内容),因此想出了以下内容

Function Get-CertificateChain {
    [OutputType([System.Security.Cryptography.X509Certificates.X509ChainElement])]
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [string]$ComputerName,[Parameter()]
        [Int32]$Port = 443,[Parameter()]
        [System.Security.Authentication.SslProtocols]$SslProtocol = [System.Security.Authentication.SslProtocols]::Tls12 # NB: The enum value Default is considered deprecated,[Parameter()]
        [Switch]$CertificateInfoOnly
    )
    [System.Net.sockets.socket]$socket = [System.Net.sockets.socket]::new([System.Net.sockets.socketType]::Stream,[System.Net.sockets.ProtocolType]::Tcp)
    $socket.Connect($ComputerName,$Port)
    try {
        [System.Net.sockets.NetworkStream]$networkStream = [System.Net.sockets.NetworkStream]::new($socket,$true)
        [System.Net.Security.SslStream]$sslStream = [System.Net.Security.SslStream]::new($networkStream,$true)
        $sslStream.AuthenticateAsClient( $ComputerName,$null,$SslProtocol,$false )
        [System.Security.Cryptography.X509Certificates.X509Certificate2]$remoteCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]($sslStream.RemoteCertificate)
        [System.Security.Cryptography.X509Certificates.X509Chain]$chain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
        $chain.Build($remoteCertificate) | Out-Null
        Write-Verbose "Chain status length is: $($chain.ChainStatus.Length)" # Gives 0 every time :/
        foreach ($chainElement in $chain.ChainElements) {
            #[System.Security.Cryptography.X509Certificates.X509ChainElement]
            if ($CertificateInfoOnly.IsPresent) {
                $chainElement | Select-Object -ExpandProperty Certificate
            } else {
                $chainElement
            }
            
        }
    } finally {
        $socket.Close()
    }
}

然而,即使在缺少完整链的站点上,这也会检索完整链;我猜是因为 BUILD 太有用了,可以获取它可以找到的任何丢失的中间证书或根证书。

我在一个类似的答案中找到了关于 ChainStatus 的信息,这似乎是一个更好的解决方案;但是,当我在调用 Build 之后调用 $chain.ChainStatus.Length 时(参见 Write-Verbose 调用),我得到的结果为 0

查看第三方返回的证书链是否有效(即包括在不自动解决丢失或无序证书链的客户端上)或获取有关哪些证书的信息的正确方法是什么?实际返回,使用 .net 框架?

解决方法

不幸的是,您不能(使用 SslStream)。 .NET 将使用本地缓存和网络检索的组合来尝试完成链,并且没有什么地方可以真正阻止它(此外,您通常希望它把根放在最上面,因为通常认为是正确的TLS Server 配置是除root权限外的整个链条)。

由于 .NET 具有 TCP 套接字支持,您可以通过自己编写 TLS 握手代码在 .NET 中实现,然后查看线路上的实际内容......但我并不真正建议这样做。