Saritasa.Web.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
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; } } "@ <# .SYNOPSIS Disables SSL check for WebClient requests. #> function Update-SslCheckProcedure() { [CmdletBinding()] param () Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy Write-Information 'SSL certificates validation is turned off.' } <# .SYNOPSIS Installs SSL certificate of remote server to trusted certificate root authorities store. .NOTES Based on code by Robert Westerlund and Michael J. Lyons. http://stackoverflow.com/questions/22233702/how-to-download-the-ssl-certificate-from-a-website-using-powershell #> function Import-TrustedSslCertificate { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $ServerHost, [int] $Port = 443 ) Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $tempFilename = "$env:TEMP\" + [guid]::NewGuid() $webRequest = [Net.WebRequest]::Create("https://${ServerHost}:$Port") try { $webRequest.GetResponse().Dispose() } catch [System.Net.WebException] { if ($_.Exception.Status -EQ [System.Net.WebExceptionStatus]::TrustFailure) { # Trust failure, do nothing. } elseif ($_.Exception.Status -EQ [System.Net.WebExceptionStatus]::ProtocolError -And $_.Exception.Response.StatusCode -EQ 'NotFound') { # Page not found, it's OK. } else { # Unknown error, rethrow it. throw } } $cert = $webRequest.ServicePoint.Certificate $thumbprint = $cert.GetCertHashString() $existingCert = Get-Item "Cert:\LocalMachine\Root\$thumbprint" -ErrorAction SilentlyContinue if ($existingCert) { Write-Information "Certificate $thumbprint is trusted already ($($cert.Subject))." return } if (!(Test-UserIsAdministrator)) { throw 'Administrator permissions are required.' } $bytes = $cert.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert) Set-Content -Value $bytes -Encoding Byte -Path $tempFilename $cmd = Get-Command Import-Certificate -EA SilentlyContinue if ($cmd) # Windows 8+ { Import-Certificate -CertStoreLocation Cert:\LocalMachine\Root $tempFilename } else # Windows 7 { certutil.exe -addstore 'Root' $tempFilename if ($LASTEXITCODE) { throw 'Certutil failed.' } } Write-Information 'SSL certificate is imported.' Remove-Item $tempFilename } |