2

I am invoking a library in Powershell that using the .NET HttpClient to make a POST request. The client call runs on a background thread. It works fine for HTTP. When I use HTTPS however I run into issues. The server is not using a valid signed cert. I disabled that check properly using:

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

only to be met by this error related to runspaces:

System.Management.Automation.PSInvalidOperationException: There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: $true

From a bit of research it appears to be related to the fact that the API is async / using tasks.

Any help would be greatly appreciated.

Glenn Block
  • 8,463
  • 1
  • 32
  • 34

2 Answers2

4

Try and use a cert policy instead?

add-type @" 
    using System.Net; 
    using System.Security.Cryptography.X509Certificates; 

    public class NoSSLCheckPolicy : ICertificatePolicy { 
        public NoSSLCheckPolicy() {} 
        public bool CheckValidationResult( 
            ServicePoint sPoint, X509Certificate cert, 
            WebRequest wRequest, int certProb) { 
            return true; 
        } 
    } 
"@ 
[System.Net.ServicePointManager]::CertificatePolicy = new-object NoSSLCheckPolicy 
Trondh
  • 3,221
  • 1
  • 25
  • 34
1

Beware that when you turn off validation, you're turning it off for everything -- I'd write a validator like a bit more carefully than what @Trondh's recommending -- don't just return true, makes sure the cert is at least valid (even if self-signed), and only allows self-signed certs only for specific domains.

FWIW, I wrote a Tuneable SSL Validator for .Net while working at Splunk to deal with the fact the Splunk uses self-signed certs by default. It has a PowerShell module with commands to let you trust a cert for a session, or just disable certificate chain validation (so you can trust valid self-signed certs with no cert chain) ... and it has wrappers around Invoke-WebRequest and Invoke-RestMethod and even Export-ODataEndpointProxy to add an Insecure switch so you can disable SSL for just a single request.

https://github.com/Jaykul/Tunable-SSL-Validator

Jaykul
  • 15,370
  • 8
  • 61
  • 70