When PowerShell cmdlets download data via HTTPS:, they check whether the server certificate is valid, and if it is not, you receive an exception:

# this URL always produces an SSL error:
$url = 'https://expired.badssl.com/'

# fails
$result = Invoke-RestMethod -Uri $url -UseBasicParsing  

In automation and administration, though, it occasionally becomes necessary to contact servers with invalid SSL certificates, either because you are the Admin that is supposed to fix the certificate, or because the target server is an internal management web frontend, i.e. as part of printers or NAS, and you know it is trustworthy regardless of expired certificates.

To trust all HTTPS: servers, simply overwrite the logic that does the validity check, and always return $true:

# derive new class from ICertificatePolicy...
class TrustAllCert : System.Net.ICertificatePolicy
{
    [bool]CheckValidationResult([System.Net.ServicePoint]$srvPoint, 
                                [System.Security.Cryptography.X509Certificates.X509Certificate]$cert,
                                [System.Net.WebRequest]$request,
                                [int]$certProblem
                                )
    {
        # and make sure CheckValidationResult() always returns $true:
        return $true
    }
}

# use your new object as CertificatePolicy:
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCert]::new()

Once you run this code, you now can contact and download data from any HTTPS server regardless of validity of certificate. This previously failed, now it works:

# this URL always produces a SSL error:
$url = 'https://expired.badssl.com/'

# works
$result = Invoke-RestMethod -Uri $url -UseBasicParsing

Side note: https://badssl.com/ provides you with all kinds of SSL-related error conditions to play with.




Twitter This Tip! ReTweet this Tip!

Anonymous