如何使用 cacert 文件在 Powershell (Invoke-WebRequest) 中执行等效的 cUrl?

jav*_*iaf 2 windows powershell curl

基本上,我想将命令 curl 转换为与当前在 linux 服务器中相同的参数,但在 Powershell 中,以便上传文件:

curl -v -T $file -u user:password http://myurl --cacert /opt/keystores/ca_cert.pem
Run Code Online (Sandbox Code Playgroud)

我找到了执行此任务的等效命令:PowerShell 3.0+ 的“Invoke-WebRequest”,但问题是我不知道如何使用 CA 证书文件 (.pem) 调用它,而且我还没有找到互联网上的任何样本。

谢谢!

Mat*_*sen 6

当您TLS在 .NET 中建立连接时,对等证书将根据受相关 AppDomain管理的RemoteCertificateValidationCallback函数进行验证ServicePointManager

大多数有关如何在 PowerShell 中覆盖默认验证的示例都会告诉您只需执行以下操作:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
Run Code Online (Sandbox Code Playgroud)

不要那样做!- 它将完全绕过验证。

可以做的是实现适当的回调函数并手动调用链验证。在执行此操作之前,您可以将不在机器或用户证书存储中的证书添加到您可以验证的链列表中:

$callback = {
    param(
        $sender,
        [System.Security.Cryptography.X509Certificates.X509Certificate]$certificate,
        [System.Security.Cryptography.X509Certificates.X509Chain]$chain,
        [System.Net.Security.SslPolicyErrors]$sslPolicyErrors
    )

    # No need to retype this long type name
    $CertificateType = [System.Security.Cryptography.X509Certificates.X509Certificate2]

    # Read the CA cert from file
    $CACert = $CertificateType::CreateFromCertFile("C:\path\to\ca.crt") -as $CertificateType

    # Add the CA cert from the file to the ExtraStore on the Chain object
    $null = $chain.ChainPolicy.ExtraStore.Add($CACert)

    # return the result of chain validation
    return $chain.Build($certificate)
}

# Assign your delegate to the ServicePointManager callback
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $callback

# Do your Invoke-WebRequest or WebClient call here
Run Code Online (Sandbox Code Playgroud)

我不知道如何从一个 PEM 文件中读取多个证书到一个证书集合中,所以你必须一个一个地添加每个 ca 证书,抱歉