I want to test if our web server (located on the intranet) is online (1
) or offline (0
) from the server containing it using PowerShell 2.0. For this I have a script that navigates to the page and check if a html-string is available on the page.
function Get-HeartBeat {
$isAlive = $false
try {
$webclient = New-Object WebClient
$userName = "xxx"
$password = "xxx"
$domain = "xxx"
$url = "ourUrl.com"
$html = '<input type="submit">'
$webclient.Credentials = New-Object System.Net.NetworkCredential($userName, $password, $domain)
$webpage = $webclient.DownloadString($url)
$isAlive = $webpage.Contains($html)
} catch {
# A WebException is thrown if the status code is anything but 200 (OK)
Write-Host $_
$isAlive = $false
}
return "$([Int32]$isAlive)"
}
Unfortunately this returns an error:
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
A way to trust our certificate is to create a type with a certificate policy as follows (modification of this answer):
Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustOurCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint servicePoint, X509Certificate certificate,
WebRequest request, int certificateProblem)
{
return certificate.Issuer.Equals("OUR ISSUER")
&& certificate.Subject.Contains("our application");
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustOurCertsPolicy
This still feels a bit "stringly typed" instead of 100% secure.
Is this safe? Is there a better way to create a WebClient that has one certificate accepted? The certificate we should trust is available in cert:LocalMachine\My
.