Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not establish trust relationship for the SSL/TLS secure channel with Invoke-Webrequest from PowerShell

Tags:

powershell

ssl

When I try to use Invoke-WebRequest on https, I'm getting some weird error:

Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Here is my code:

   [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
    $url = "https://X.X.X.X:4343/officescan/console/html/cgi/cgiChkMasterPwd.exe"
    $r = Invoke-WebRequest $url -SessionVariable office

Any advice for me?

like image 463
Scott Lee Avatar asked Dec 11 '25 23:12

Scott Lee


2 Answers

Of course it is an issue with an invalid certificate (autosigned?, expired?) if using Powershell 7+ simply use the new parameter

Invoke-WebRequest -Uri 'https://trees.com/' -SkipCertificateCheck

if using Powershell 5.1 it is a bit harder:

$code= @"
        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;
            }
        }
"@
Add-Type -TypeDefinition $code -Language CSharp
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
Invoke-WebRequest -Uri 'https://trees.com/'
like image 84
Mikel V. Avatar answered Dec 15 '25 12:12

Mikel V.


A possible solution I have seen is this:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

you can override the certification validation function to always return true.

Its much simpler than overriding CheckValidationResult.

Credit

like image 31
Nir Yossef Avatar answered Dec 15 '25 13:12

Nir Yossef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!