Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CertificatePolicy obsolete in PowerShell 7.1 #4

Open
oleahy opened this issue May 12, 2021 · 4 comments
Open

CertificatePolicy obsolete in PowerShell 7.1 #4

oleahy opened this issue May 12, 2021 · 4 comments

Comments

@oleahy
Copy link

oleahy commented May 12, 2021

Thank you for this useful module.

We have been using it successfully with PowerShell version 5.1, but it appears that the switch -SkipCertificateCheck on the cmdlet Connect-VIMobServer does not work with powershell version 7.1

Searching online I see that ICertificatePolicy and CertificatePolicy are obsolete, https://docs.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.certificatepolicy?view=netframework-4.7.2

Is there a work around or an alternative way of using this module?

This is the error we get:

    PS /scripts> Import-Module -Name "VIPerms"
    PS /scripts> [securestring]$secStringPassword = ConvertTo-SecureString "*******" -AsPlainText -Force
    PS /scripts> [pscredential]$credObject = New-Object System.Management.Automation.PSCredential ("*****", $secStringPassword)
    PS /scripts> Connect-VIMobServer -Server "10.0.0.10" -Credential $credObject -SkipCertificateCheck
    Add-Type: /home/host/.local/share/powershell/Modules/VIPerms/0.0.6/Private/Set-CertPolicy.ps1:24
    Line |
      24 |                      Add-Type -TypeDefinition  @"
         |                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         | (3,56): error CS0246: The type or namespace name 'ICertificatePolicy' could not be found (are you
         | missing a using directive or an assembly reference?)                     public class
         | TrustAllCertsPolicy : ICertificatePolicy {                                                        ^

    Add-Type: /home/host/.local/share/powershell/Modules/VIPerms/0.0.6/Private/Set-CertPolicy.ps1:24
    Line |
      24 |                      Add-Type -TypeDefinition  @"
          |                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          | Cannot add type. Compilation errors occurred.

The version of Powershell that fails is 7.1.0

    PS /scripts> $PSVersionTable.PSVersion
    Major  Minor  Patch  PreReleaseLabel BuildLabel
    -----  -----  -----  --------------- ----------
    7      1      0
@alvxyz111
Copy link

Hello I had the same error when I try to use it

PS /root> Connect-VIMobServer -Server "vc-test.corp" -SkipCertificateCheck

cmdlet Connect-VIMobServer at command pipeline position 1
Supply values for the following parameters:
Credential
User: [email protected]
Password for user [email protected]: *******

Add-Type: /root/.local/share/powershell/Modules/VIPerms/0.0.6/Private/Set-CertPolicy.ps1:24
Line |
24 | Add-Type -TypeDefinition @"
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| (3,56): error CS0246: The type or namespace name 'ICertificatePolicy' could not be found (are you missing a using directive or an assembly reference?) public class TrustAllCertsPolicy : ICertificatePolicy {
| ^

Add-Type: /root/.local/share/powershell/Modules/VIPerms/0.0.6/Private/Set-CertPolicy.ps1:24
Line |
24 | Add-Type -TypeDefinition @"
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot add type. Compilation errors occurred.

PS /root> VIGlobalPermission
Add-Type: /root/.local/share/powershell/Modules/VIPerms/0.0.6/Private/Set-CertPolicy.ps1:24
Line |
24 | Add-Type -TypeDefinition @"
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| (3,56): error CS0246: The type or namespace name 'ICertificatePolicy' could not be found (are you missing a using directive or an assembly reference?) public class TrustAllCertsPolicy : ICertificatePolicy {
| ^

Add-Type: /root/.local/share/powershell/Modules/VIPerms/0.0.6/Private/Set-CertPolicy.ps1:24
Line |
24 | Add-Type -TypeDefinition @"
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot add type. Compilation errors occurred.

did you find the solution on this? thanks and regards

@ssamantasinghar
Copy link

similar issue which I am also facing!
I am trying to reuse this powershell script which performs smoketest post deployment. The script works just fine when I run locally on the build server but when I try to run through my gitlab pipeline it fails with error: add-type @"(3,36): error CS0246: The type or namespace name 'ICertificatePolicy' could not be found (are you missing a using directive or an assembly reference?) public class TrustAllCertsPolicy : ICertificatePolicy {

Code that is erroring out:

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;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$HTTP_Status_Timeout = 0
$HTTP_Request = [System.Net.WebRequest]::Create($url)

My understanding so far: Based on my research I tried to compare the Powershell version of my build server vs gitlab pipeline

Build server

Name                           Value
----                           -----
PSVersion                      5.1.14393.4583
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.4583
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3

gitlab pipeline

PSVersion                      7.2.4
PSEdition                      Core
GitCommitId                    7.2.4
OS                             Microsoft Windows 10.0.14393
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0.}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

As I understand the piece of code does not work in powershell 7

Any suggestions which can resolve this issue

@butch7903
Copy link

Solution to Set-CertPolicy is below. Can we please request this be updated in the module?

function Set-CertPolicy {
<#
.SYNOPSIS
Ignore SSL verification.

.DESCRIPTION
Using a custom .NET type, override SSL verification policies.

#>

param (
    [Switch] $SkipCertificateCheck,
    [Switch] $ResetToDefault
)

try {
    if ($SkipCertificateCheck) {
        if ($PSVersionTable.PSEdition -eq 'Core') {
            # Invoke-restmethod provide Skip certcheck param in powershell core
            $Script:PSDefaultParameterValues = @{
                "invoke-restmethod:SkipCertificateCheck" = $true
                "invoke-webrequest:SkipCertificateCheck" = $true
            }
        }else{
                Add-Type -TypeDefinition  @"
                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;
                    }
                }

"@
}
[Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}
} catch {
$Err = $_
throw $Err
}
}

@andre-m-faria
Copy link

andre-m-faria commented Jan 31, 2024

Hello,

I just want to make clear that I used ChatGPT to fix my problem, therefore, I will not be able to help with any questions regarding the code below.

Okay, that said.

@butch7903, thank you for you code, it really helped me to fix the error CS0246: The type or namespace name 'ICertificatePolicy' could not be found.

But I stumbled in another error.

After inserting my credentials, it trowed the following error.
Cannot find type [TrustAllCertsPolicy]: verify that the assembly containing this type is loaded.

Okay, as I don't know much about PowerShell, I appealed to ChatGPT, in the code below ChatGPT added a step to verify if "System.Net.Http" (that contains the type TrustAllCertsPolicy) is already loaded, and if not it will load itself.

    <#
    .SYNOPSIS
    Ignore SSL verification.

    .DESCRIPTION
    Using a custom .NET type, override SSL verification policies.
    #>

    param (
        [Switch] $SkipCertificateCheck,
        [Switch] $ResetToDefault
    )

    try {
        if ($SkipCertificateCheck) {
            if ($PSVersionTable.PSEdition -eq 'Core') {
                # Invoke-restmethod provide Skip certcheck param in PowerShell Core
                $Script:PSDefaultParameterValues = @{
                    "invoke-restmethod:SkipCertificateCheck" = $true
                    "invoke-webrequest:SkipCertificateCheck" = $true
                }
            } else {
                # Load the assembly containing TrustAllCertsPolicy if not already loaded
                $assemblyName = 'System.Net.Http'
                $loadedAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object { $_.GetName().Name }

                if (-not $loadedAssemblies.Contains($assemblyName)) {
                    Add-Type -AssemblyName $assemblyName
                }

                Add-Type -TypeDefinition  @"
                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;
                    }
                }
"@
                [Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
            }
        }
    } catch {
        $Err = $_
        throw $Err
    }
}
Name                           Value
----                           -----
PSVersion                      7.4.1
PSEdition                      Core
GitCommitId                    7.4.1
OS                             Microsoft Windows 10.0.20348
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants