Skip to content

Instantly share code, notes, and snippets.

@bender-the-greatest
Last active September 17, 2020 13:34
Show Gist options
  • Save bender-the-greatest/26e758cd1ad7b8ae87c688301cac697e to your computer and use it in GitHub Desktop.
Save bender-the-greatest/26e758cd1ad7b8ae87c688301cac697e to your computer and use it in GitHub Desktop.
Code snippet to ignore SSL errors when making HTTPS requests in Powershell. Originally sourced from https://www.reddit.com/r/PowerShell/comments/6emjly/ignoring_ssltls_errors_using_invokewebrequest/
# DISCLAIMER - This is provided as a method to interface with HTTPS endpoints configured
# with an invalid certificate as is common during the development process. This is not
# intended or recommended to be used in a production scenario for obvious security reasons.
#
# Also, I did not write the C# code. Props to kd0shk and the Powershell subreddit for the C# snippet.
# Both of these approaches won't work in PowerShell core and is not required as built-in
# request cmdlets now have the -SkipCertificateCheck parameter
# (e.g. Invoke-WebRequest -SkipCertificateCheck https://server.withbadcert.domain.tld)
# Compile the required C# code to create a custom certificate policy
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
# You can also define a PowerShell class for this with PowerShell 5.0 and later
class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
[bool] CheckValidationResult(
[System.Net.ServicePoint]$srvPoint, [System.Security.Cryptography.X509Certificates.X509Certificate]$certificate,
[System.Net.WebRequest]$request, [int]$certificateProblem
) {
return $true
}
}
# Set the CertificatePolicy to our new TrustAllCertsPolicy we compiled above.
# Note that this is a GLOBAL setting. It is prudent to save off the old value
# and re-set it after you invoke a web request against any endpoints known to
# be using invalid certs. Otherwise, all subsequent web requests made in that
# Powershell session will skip certificate validation
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment