PoshCode Archive  Artifact [a8aea9a62e]

Artifact a8aea9a62ef970fb74ea084558db0ab9381b2d74013783ab0b360f2c4dd5a3ae:

  • File Disable-SSLValidation.ps1 — part of check-in [5cb40bb314] at 2018-06-10 13:28:18 on branch trunk — Disable-SSLValidation is built as a workaround for Invoke-WebRequest errors when attempting to get content from a site using a self-signed SSL certificate. (user: Matthew Graeber size: 2517)

# encoding: ascii
# api: powershell
# title: Disable-SSLValidation
# description: Disable-SSLValidation is built as a workaround for Invoke-WebRequest errors when attempting to get content from a site using a self-signed SSL certificate.
# version: 0.1
# type: function
# author: Matthew Graeber 
# license: CC0
# function: Disable-SSLValidation
# x-poshcode-id: 3625
# x-archived: 2016-07-13T12:37:12
# x-published: 2013-09-06T07:30:00
#
#
function Disable-SSLValidation
{
<#
.SYNOPSIS
    Disables SSL certificate validation
.DESCRIPTION
    Disable-SSLValidation disables SSL certificate validation by using reflection to implement the System.Net.ICertificatePolicy class.

    Author: Matthew Graeber (@mattifestation)
    License: BSD 3-Clause
.NOTES
    Reflection is ideal in situations when a script executes in an environment in which you cannot call csc.ese to compile source code. If compiling code is an option, then implementing System.Net.ICertificatePolicy in C# and Add-Type is trivial.
.LINK
    http://www.exploit-monday.com
#>

    Set-StrictMode -Version 2

    # You have already run this function
    if ([System.Net.ServicePointManager]::CertificatePolicy.ToString() -eq 'IgnoreCerts') { Return }

    $Domain = [AppDomain]::CurrentDomain
    $DynAssembly = New-Object System.Reflection.AssemblyName('IgnoreCerts')
    $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
    $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('IgnoreCerts', $false)
    $TypeBuilder = $ModuleBuilder.DefineType('IgnoreCerts', 'AutoLayout, AnsiClass, Class, Public, BeforeFieldInit', [System.Object], [System.Net.ICertificatePolicy])
    $TypeBuilder.DefineDefaultConstructor('PrivateScope, Public, HideBySig, SpecialName, RTSpecialName') | Out-Null
    $MethodInfo = [System.Net.ICertificatePolicy].GetMethod('CheckValidationResult')
    $MethodBuilder = $TypeBuilder.DefineMethod($MethodInfo.Name, 'PrivateScope, Public, Virtual, HideBySig, VtableLayoutMask', $MethodInfo.CallingConvention, $MethodInfo.ReturnType, ([Type[]] ($MethodInfo.GetParameters() | % {$_.ParameterType})))
    $ILGen = $MethodBuilder.GetILGenerator()
    $ILGen.Emit([Reflection.Emit.Opcodes]::Ldc_I4_1)
    $ILGen.Emit([Reflection.Emit.Opcodes]::Ret)
    $TypeBuilder.CreateType() | Out-Null

    # Disable SSL certificate validation
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object IgnoreCerts
}