我知道如果 Web 服务安装了证书,那么在 powershell 中像 Invoke-WebRequest 这样的简单测试连接到该 https 站点就可以告诉我是否可以连接到那里。但是我想知道是否可以在没有证书的情况下测试与该网络的连接,例如由于证书验证原因,连接会因证书而失败但在没有证书的情况下会成功吗?
由于我已经可以使用 Invoke-WebRequest -Uri "https://..." -UseBasicParsing -TimeoutSec 10 连接到该网络,我想知道是否可以以某种方式在没有证书的情况下测试连接。
您可以在 PowerShell 中检查远程证书,如下所示:
# Extracted portion of https://github.com/Mike-Crowley/Public-Scripts/blob/main/OSINT/Request-AdfsCerts.ps1
function Get-SSLCertificate {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Url,
[Parameter(Mandatory = $false)]
[string]$HostHeader
)
begin {
if ($PSVersionTable.PSEdition -ne "Desktop") {
Throw "This function requires Windows PowerShell (Desktop edition)."
}
# If no host header provided, extract from URL
if (-not $HostHeader) {
$uri = [System.Uri]::new($Url)
$HostHeader = $uri.Host
}
}
process {
try {
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
# Make HTTPS connection and get content
$request = [Net.HttpWebRequest]::Create($Url)
$request.Host = $HostHeader
$request.AllowAutoRedirect = $false
$response = $request.GetResponse()
# Extract the certificate from the request
if ($null -ne $request.ServicePoint.Certificate) {
$HttpsCertBytes = $request.ServicePoint.Certificate.GetRawCertData()
# Extract HTTPS cert
$CertInBase64 = [convert]::ToBase64String($HttpsCertBytes)
$Cert_x509 = [Security.Cryptography.X509Certificates.X509Certificate2]([System.Convert]::FromBase64String($CertInBase64))
Write-Output $Cert_x509
}
else {
Write-Warning "No Certificate Found at $Url"
}
}
catch {
Write-Error "Error retrieving certificate: $_"
}
finally {
if ($null -ne $response) {
$response.Close()
}
}
}
}
输出示例:
# Returns:
# WARNING: No Certificate Found at http://example.com
Get-SSLCertificate -Url http://example.com
# In PS 6+ returns an error:
# This function requires Windows PowerShell (Desktop edition).
Get-SSLCertificate -Url https://example.com
# Returns:
# Thumbprint Subject
# ---------- -------
# 4DA25A6D5EF62C5F95C7BD0A73EA3C177B36999D CN=www.example.org, O=Internet Corporation for Assigned Names and Numbers, L=Los Angeles, S=California, C=US
Get-SSLCertificate -Url https://example.com