Invoke-RestMethod - Ignore Self Signed Certs

firestarter247 picture firestarter247 · Apr 6, 2016 · Viewed 49.1k times · Source

It seems like this question has been asked and answered, but so far every solution I come across does not help. I'm writing a PowerShell script to run some REST API's to get usage information. My script breaks immediately just trying to communicate to the server. For testing sake, I'm doing a very simplistic command:

Invoke-RestMethod 'https://server:4443/login'

It returns with this error:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.

I can run the same command but with URL google.com and I get a valid return, so I know the command is working generally speaking.

If I run the curl equivalent on the server itself, things complete as expected. Here's a snippet of the verbose output of the curl command:

* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using TLSv1.0 / DHE-RSA-AES256-SHA
* Server certificate:
*        subject: CN=localhost
*        start date: 2016-03-22 21:48:57 GMT
*        expire date: 2026-03-20 21:48:57 GMT
*        issuer: CN=localhost
*        SSL certificate verify result: self signed certificate (18), continuing anyway.

I'm only assuming this is a self signed cert issue based upon searching the fairly generic error PowerShell returns.

I've tried:

[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

and other similar methods (complex functions) to help ignore certificate issues with no luck.

I'm running PowerShell 5 in case that helps.

I'm decent with PowerShell code but this is my first time trying Invoke-RestMethod, so maybe I'm missing something. Any insight is appreciated.

Answer

x0n picture x0n · Sep 6, 2017

This will also work in later versions of powershell with invoke-restmethod/webrequest. It avoids the requirement for a runspace by implementing the handler as native .net:

if (-not("dummy" -as [type])) {
    add-type -TypeDefinition @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public static class Dummy {
    public static bool ReturnTrue(object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; }

    public static RemoteCertificateValidationCallback GetDelegate() {
        return new RemoteCertificateValidationCallback(Dummy.ReturnTrue);
    }
}
"@
}

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [dummy]::GetDelegate()

Hope this helps.