10

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?

lfurini
  • 3,729
  • 4
  • 30
  • 48
Scott Lee
  • 101
  • 1
  • 1
  • 4

4 Answers4

12

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/'
Mikel V.
  • 351
  • 2
  • 8
  • I added `using System;` and `Console.WriteLine(certificate.ToString(true));` and discovered a proxy performing a MITM on my WebRequest. – davenpcj May 15 '23 at 16:55
1

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

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
Nir Yossef
  • 191
  • 1
  • 8
0

You should try this:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
$url = "https://X.X.X.X:4343/officescan/console/html/cgi/cgiChkMasterPwd.exe"
$r = Invoke-WebRequest $url -SessionVariable office
PollusB
  • 1,726
  • 2
  • 22
  • 31
0

You can also try bypassing the PowerShell profile, in case there's something weird in there (my issue).

powershell -noprofile
KERR
  • 1,312
  • 18
  • 13