Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bixb0012/6ee0c223352bff2b2d8e3c40f767cb34 to your computer and use it in GitHub Desktop.
Save bixb0012/6ee0c223352bff2b2d8e3c40f767cb34 to your computer and use it in GitHub Desktop.
PowerShell: ServicePointManager Customizations
#Requires -Version 5.1
# Reference: 1) https://docs.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager
# Reference: 2) https://docs.microsoft.com/en-us/dotnet/api/system.net.security.remotecertificatevalidationcallback
# Example 1: Force TLS 1.2 connections from client
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Example 2: Ignore all SSL/TLS policy errors, e.g., ignore SSL/TLS secure channel errors
# from self-signed certificates
# Adapted from https://spiderip.com/blog/2018/06/powershell-invoke-webrequest-ignore-certificate-warning
Add-Type -TypeDefinition @"
using System;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback {
public static void IgnoreAllPolicy() {
ServicePointManager.ServerCertificateValidationCallback += delegate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
) {
return true;
};
}
}
"@
[ServerCertificateValidationCallback]::IgnoreAllPolicy()
# Example 3: Ignore SSL/TLS policy errors for certain certificates based on list of SHA1 hashes while
# treating all other certificates as normal
# Adapted from https://spiderip.com/blog/2018/06/powershell-invoke-webrequest-ignore-certificate-warning
# Adapted from https://stackoverflow.com/questions/20914305/best-practices-for-using-servercertificatevalidationcallback
$Hashes = @() # List of SHA1 hashes from X.509v3 certificates
Add-Type -TypeDefinition @"
using System;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback {
public static void IgnoreLookupPolicy() {
ServicePointManager.ServerCertificateValidationCallback += delegate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
) {
if (new string[]{
"$($Hashes -join '",' + [environment]::NewLine + ' '*24 + '"')"
}.Contains(certificate.GetCertHashString())) {
return true;
} else {
return sslPolicyErrors == SslPolicyErrors.None;
}
};
}
}
"@
[ServerCertificateValidationCallback]::IgnoreLookupPolicy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment