PowerShell function to suppress HTTPS self-signed certificate errors

I’ve been working frequently with the Invoke-WebRequest and Invoke-RestMethod functions recently against my SolarWinds Orion infrastructure.  I’d normally use the Swis Snapin, but instead wanted to get a little more experience with JSON and XML.

Now, when I try to make that call to port 17778 on any machine except the Orion server itself, I get a certificate error.  So, I can either install a self-signed certificate to a different machine (bad idea) or temporarily allow the self-signed certificates (better).

I found that I wasn’t the only person who had this issue and PoSH Code #624 shows the core of the function that I crafted.  That article was the seed for this function.  I just dot-include this script and call the function for any other scripts that make calls against using the above functions.

<#
.Synopsis
   Allows insecure HTTPS communications
.DESCRIPTION
   Changes any web call (Invoke-RestMethod or Invoke-WebRequest) to allow insecure HTTPS communications (like self-signed certificates)
.EXAMPLE
   Trust-AllWebCertificates
.NOTES
   Heavily influenced by code From http://poshcode.org/624
#>
function Trust-AllWebCertificates
{
    ## Create a compilation environment
    $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler = $Provider.CreateCompiler()
    $Params = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable = $False
    $Params.GenerateInMemory = $True
    $Params.IncludeDebugInformation = $False
    $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly

    ## We now create an instance of the TrustAll and attach it to the ServicePointManager
    $TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy = $TrustAll
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.