Feeds:
Записи
Комментарии

Archive for Сентябрь 2017

В наборе  Windows Server 2003 Resource Kit Tools , есть утилита tsctst.exe — Terminal Server Client License Dump , для просмотра клиентских лицензий сервера терминалов. Основное ограничение на системах x64, что tsctst.exe –  читает раздел реестра — HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSLicensing\Store , где отсутствует данная информация.

Если хочется воспользоваться данной утилитой, то можно скопировать/импортировать данные из HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSLicensing\Store и перенести в раздел :  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSLicensing\Store и утилита вновь будет работать.

Нас будет интересовать ключ реестра LicenseXXX\ClientLicense(REG_BINARY), где содержится информация о сертификатах.

Для получения данных о сертификате , воспользуемся(для примера, приведу  два способа):

1) System.Security.Cryptography.Pkcs.SignedCms

Add-Type -AssemblyName System.Security            
$license = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\MSLicensing\Store\LICENSE000" -Name "ClientLicense"            
$cms = New-Object System.Security.Cryptography.Pkcs.SignedCms            
$cms.Decode($license.ClientLicense)            
$cms.Certificates             
            
PS > $cms.Certificates

Thumbprint                                Subject
----------                                -------
785F491C579B6421FE155EFB6E6482F1E44FC266  L=CON + CN=SBTR
B50C54A586ADC8FA249639B7A06E3CE4B2C24070  L=SYSTEM + CN=CL-01 + SERIALNUMBER="1BcKee1dW/BhjacbI9tTm0hPCQ

2) System.Security.Cryptography.X509Certificates.X509Certificate2Collection

$certs = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new()            
$certs.Import($license.ClientLicense)            
$certs            
            
PS > $cms.Certificates

Thumbprint                                Subject
----------                                -------
785F491C579B6421FE155EFB6E6482F1E44FC266  L=CON + CN=SBTR
B50C54A586ADC8FA249639B7A06E3CE4B2C24070  L=SYSTEM + CN=CL-01 + SERIALNUMBER="1BcKee1dW/BhjacbI9tTm0hPCQ

Можно сохранить данные в файл и посмотреть, через оснастку — certmgr.msc:

$license.ClientLicense | Set-Content certs.p7b -Encoding Byte

Утилита tsctst.exe читает следующие OID:

Microsoft Hydra……………………………1.3.6.1.4.1.311.18

     License Info root

        szOID_PKIX_LICENSE_INFO                 1.3.6.1.4.1.311.18.1

     Manufacturer value

        szOID_PKIX_MANUFACTURER                 1.3.6.1.4.1.311.18.2

     Manufacturer Specfic Data

        szOID_PKIX_MANUFACTURER_MS_SPECIFIC     1.3.6.1.4.1.311.18.3

     OID for Certificate Version Stamp

        szOID_PKIX_HYDRA_CERT_VERSION           1.3.6.1.4.1.311.18.4

     OID for License Server to identify licensed product.

        szOID_PKIX_LICENSED_PRODUCT_INFO        1.3.6.1.4.1.311.18.5

     OID for License Server specific info.

        szOID_PKIX_MS_LICENSE_SERVER_INFO       1.3.6.1.4.1.311.18.6

     Extension OID reserved for product policy module — only one is allowed.

        szOID_PKIS_PRODUCT_SPECIFIC_OID         1.3.6.1.4.1.311.18.7

        szOID_PKIS_TLSERVER_SPK_OID             1.3.6.1.4.1.311.18.8

Вывод утилиты:

PS > tsctst.exe /A

*** License # 1 ***

TS Certificate Version — 0x00050001

Licensed Product

        HWID — 0x00000002, 0x7d4eb2c0, 0x37ffa910, 0x75eb542b, 0x87707af6

        Client Platform ID — 0x000000ff

        Company Name — Microsoft Corporation

Issuer — SBTR

Scope — COM

Issued to machine — CL-01

Issued to user — SYSTEM

        TS Locale ID — 0x00000419

        License ID — A02-5.02-S

Licensed Product Version 0005.0002, Flag 0x80d48000

Temporary       RTM

Valid from — 1d30f66 8ff2a100 Mon Aug 07 13:18:50 2017

Expires on — 1d3561f 79202100 Sun Nov 05 13:18:50 2017

Поля:

Issuer,Scope,Issued to machine,Issued to user -  Subject,Issuer

TS Certificate Version — 1.3.6.1.4.1.311.18.4(szOID_PKIX_HYDRA_CERT_VERSION)

Licensed Product — 1.3.6.1.4.1.311.18.2(szOID_PKIX_MANUFACTURER),

                 1.3.6.1.4.1.311.18.6 (szOID_PKIX_MS_LICENSE_SERVER_INFO)

TS Locale ID  -   1.3.6.1.4.1.311.18.5( szOID_PKIX_LICENSED_PRODUCT_INFO)

License ID — 1.3.6.1.4.1.311.18.5( szOID_PKIX_LICENSED_PRODUCT_INFO)

Licensed Product Version — 1.3.6.1.4.1.311.18.5( szOID_PKIX_LICENSED_PRODUCT_INFO)

Valid from – NotBefore

Expires on – NotAfter

Function Get-TSCtst {            
 Param(            
  $Path = "HKLM:\SOFTWARE\Microsoft\MSLicensing\Store"            
 )            
             
 $Certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection            
 $License = Get-ChildItem $Path | Get-ItemProperty -Name ClientLicense             
             
 $LicenseType = @{            
  "A02-5.00-EX" = 'Windows 2000 TS CAL from the "Built-in" pool.'             
  "A02-5.00-S"  = "Windows 2000 TS temporary or permanent CAL."             
  "A02-5.02-S"  = "Windows server 2003 TS temporary or permanent CAL."             
  "A02-6.00-S"  = "Windows server 2008 TS/2008 R2 RDS temporary or permanent CAL."             
 }            
             
 if(-not $License)             
 {            
  "Can't decode license"            
  break            
 }            
             
 foreach($l in $License)             
 {            
  $Certs.Import($l.ClientLicense)            
 }            
             
            
            
 $Certs = $Certs.Where{$_.Subject -match "SERIALNUMBER"}            
 $Number = 1            
             
 foreach($Cert in $Certs)            
 {            
  #Info            
  [byte[]]$info = $Cert.Extensions | Where{$_.Oid.Value -eq '1.3.6.1.4.1.311.18.5'} | Foreach {$_.RawData}             
  #TSVer            
  [byte[]]$btsver = $Cert.Extensions | Where{$_.Oid.Value -eq '1.3.6.1.4.1.311.18.4'} | Foreach {$_.RawData}            
  [Array]::Reverse($btsver)            
  $TSVer = "0x$([BitConverter]::ToString($btsver).replace('-',''))"            
  #Compnay            
  $bcompany = $Cert.Extensions | Where {$_.Oid.Value -eq '1.3.6.1.4.1.311.18.2'} | Foreach {$_.RawData}            
  $Company = [Text.Encoding]::Unicode.GetString($bcompany)            
  #Product            
  $CId = "0x$([BitConverter]::ToString($info[5..8]).Replace('-','').ToLower())"            
  #Issuer,Scope            
  $Scope,$Issuer = $Cert.Issuer -split "\s\+\s" | Foreach {$_.split("=")[1]}            
  #User,Machine Issuer            
  $UIssuer,$MIssuer = $Cert.Subject -split "\s\+\s" -match "^(L|CN)" | Foreach {$_.split("=")[1]}            
  #Locale            
  $bid = $info[12..13]            
  [Array]::Reverse($bid)            
  $TSId = "0x$([BitConverter]::ToString($bid).Replace('-','').PadLeft(8,'0'))"            
  #License            
  [string]$LicStr = [Text.Encoding]::Unicode.GetString($info) -split "\0" -match "A02-"            
  #License Type            
  $LicType = $LicenseType[$LicStr]            
  #Licensed Product Version            
  $LPV = "{0}.{1}, Flag 0x{2}" -f [BitConverter]::ToString($info,58,1).PadLeft(4,'0'),            
   [BitConverter]::ToString($info,60,1).PadLeft(4,'0').ToLower(),            
   [BitConverter]::ToString($info,63,4).Replace('-','').ToLower()            
  #HWID            
  $RegHWID    = "HKLM:\SOFTWARE\Microsoft\MSLicensing\HardwareID"            
  $ClientHWID = (Get-ItemProperty $RegHWID).ClientHWID            
  $HexClientHWID = for($i=0;$i -le $ClientHWID.Count -1 ; $i+=4) {            
   $temp = $ClientHWID[$i..($i+3)]            
   [Array]::Reverse($temp)            
   "0x$([BitConverter]::ToString($temp).Replace('-','').ToLower())"            
  }            
  $HexClientHWID = $HexClientHWID -join ', '            
              
  [PSCustomObject]@{            
   "ID"        = $Number            
   "TS Certificate Version"   = $TSVer            
   "HWID"         = $HexClientHWID            
   "Client Platform ID"       = $CId            
   "Company Name"             = $Company            
   "Issuer"        = $Issuer            
   "Scope"         = $Scope            
   "Issued to machine"     = $MIssuer            
   "Issued to user"      = $UIssuer            
   "TS Locale ID"       = $TSId            
   "License ID"       = $LicStr            
   "License Type"      = $LicType            
   "Licensed Product Version" = $LPV            
   "Valid from"       = $Cert.NotBefore            
   "Expires on"       = $Cert.NotAfter            
  }            
              
  $Number++            
 }            
}            
            

ID                       : 1
TS Certificate Version   : 0x00050001
HWID                     : 0x00000002, 0x7d4eb2c0, 0x37ffa910, 0x75eb542b, 0x87707af6
Client Platform ID       : 0x000000ff
Company Name             : Microsoft Corporation
Issuer                   : SBTR
Scope                    : CON
Issued to machine        : CL-01
Issued to user           : SYSTEM
TS Locale ID             : 0x00000419
License ID               : A02-5.02-S
License Type             : Windows server 2003 TS temporary or permanent CAL.
Licensed Product Version : 0005.0002, Flag 0x80d48000
Valid from               : 8/7/2017 1:18:50 PM
Expires on               : 11/5/2017 1:18:50 PM

PS. Скрипт Get-TSCtst.ps1 .

Реклама

Read Full Post »

Для симуляции различных ошибок  проверки сертификатов, существует прекрасный сайт — https://badssl.com/ , который предоставляет отличный набор тестов. В PowerShell 6.0 у командлетов Invoke-WebRequest/Invoke-RestMethod появился параметр –SkipCertificateCheck . Версия PowerShell v2.0  — Windows PowerShell 2.0 Deprecation. В PowerShell v3-5.1 — отсутствуют параметры для игнорирования ошибок связанных с сертификатами, поэтому воспользуемся сторонними методами.

Быстрый поиск в Google по теме игнорирование ошибок связанный с сертификатами дает большое количество различный способов.

Все примеры для PowerShell v5.1 и https://expired.badssl.com/

1 – 2 – не работают

3 – работает частично

4 – 5 – работают

 

Первоначальная ошибка:

er_06092017

 

 

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

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }            
Invoke-RestMethod https://expired.badssl.com/            
       
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-RestMethod https://expired.badssl.com/
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
            
2. https://blogs.technet.microsoft.com/bshukla/2010/04/12/ignoring-ssl-trust-in-powershell-system-net-webclient/

$netAssembly = [Reflection.Assembly]::GetAssembly([System.Net.Configuration.SettingsSection])            
            
if($netAssembly)            
{            
    $bindingFlags = [Reflection.BindingFlags] "Static,GetProperty,NonPublic"            
    $settingsType = $netAssembly.GetType("System.Net.Configuration.SettingsSectionInternal")            
            
    $instance = $settingsType.InvokeMember("Section", $bindingFlags, $null, $null, @())            
            
 if($instance)            
    {            
        $bindingFlags = "NonPublic","Instance"            
        $useUnsafeHeaderParsingField = $settingsType.GetField("useUnsafeHeaderParsing", $bindingFlags)            
            
  if($useUnsafeHeaderParsingField)            
        {            
          $useUnsafeHeaderParsingField.SetValue($instance, $true)            
        }            
    }            
}            
            
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-RestMethod https://expired.badssl.com/
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
            

3. [Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

Тут странности у меня – в 90% случаев отрабатывает, 10% – после перезапуска сессии, уже не отрабатывало. Проверяйте.

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;
         }
     }
"@            
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy            
Invoke-RestMethod https://expired.badssl.com/

 

С ошибкой:

witherr_06092017

 

Без ошибки:

withouterr_06092017

 

4. https://stackoverflow.com/questions/36456104/invoke-restmethod-ignore-self-signed-certs

if (-not("dummy" -as [type])) {            
    add-type -TypeDefinition @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public static class Dummy {
    public static bool ReturnTrue(object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; }

    public static RemoteCertificateValidationCallback GetDelegate() {
        return new RemoteCertificateValidationCallback(Dummy.ReturnTrue);
    }
}
"@            
}            
            
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [dummy]::GetDelegate()            
            
Invoke-RestMethod https://expired.badssl.com/

 

При использовании Add-Type создается dll с случайным именем, а после удаляется. У тех, кто использует SRP/Aplocker — потребуются дополнительные действия для администратора. Утилита ProcMon – покажет, какие действия с файловой системой производит Add-Type. Сохраним вывод ProcMon в csv формате.


PS > Import-Csv AddType.CSV | Where Path -match "Temp" | Format-Table -Auto Operation,Path,Detail

Operation                     Path                                              Detail
---------                     ----                                              ------
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.tmp     Desired Access: Generic Write, Read Attri
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.tmp
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs    Desired Access: Generic Write, Read Attri
WriteFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs    Offset: 0, Length: 465, Priority: Normal
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     Desired Access: Generic Read/Write, Dispo
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline Desired Access: Generic Write, Read Attri
WriteFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline Offset: 0, Length: 357, Priority: Normal
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.out     Desired Access: Generic Write, Read Attri
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.err     Desired Access: Generic Write, Read Attri
WriteFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.out     Offset: 0, Length: 440, Priority: Normal
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     Desired Access: Generic Read, Disposition
QueryStandardInformationFile  C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     AllocationSize: 4 096, EndOfFile: 3 584,
ReadFile                      C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     Offset: 0, Length: 3 584, Priority: Norma
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.pdb     Desired Access: Read Attributes, Disposit
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.out     Desired Access: Read Attributes, Delete,
QueryAttributeTagFile         C:\Users\user\AppData\Local\Temp\ucp2kjeg.out     Attributes: A, ReparseTag: 0x0
SetDispositionInformationFile C:\Users\user\AppData\Local\Temp\ucp2kjeg.out     Delete: True
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.out
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs    Desired Access: Read Attributes, Delete,
QueryAttributeTagFile         C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs    Attributes: A, ReparseTag: 0x0
SetDispositionInformationFile C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs    Delete: True
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.0.cs
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.tmp     Desired Access: Read Attributes, Delete,
QueryAttributeTagFile         C:\Users\user\AppData\Local\Temp\ucp2kjeg.tmp     Attributes: A, ReparseTag: 0x0
SetDispositionInformationFile C:\Users\user\AppData\Local\Temp\ucp2kjeg.tmp     Delete: True
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.tmp
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.pdb     Desired Access: Read Attributes, Delete,
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.err     Desired Access: Read Attributes, Delete,
QueryAttributeTagFile         C:\Users\user\AppData\Local\Temp\ucp2kjeg.err     Attributes: A, ReparseTag: 0x0
SetDispositionInformationFile C:\Users\user\AppData\Local\Temp\ucp2kjeg.err     Delete: True
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.err
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline Desired Access: Read Attributes, Delete,
QueryAttributeTagFile         C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline Attributes: A, ReparseTag: 0x0
SetDispositionInformationFile C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline Delete: True
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.cmdline
CreateFile                    C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     Desired Access: Read Attributes, Delete,
QueryAttributeTagFile         C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     Attributes: A, ReparseTag: 0x0
SetDispositionInformationFile C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll     Delete: True
CloseFile                     C:\Users\user\AppData\Local\Temp\ucp2kjeg.dll

 

Попробуем сгенерировать динамический код в памяти не используя промежуточный файл. Для этого сначала создадим dll и получим IL код.

Add-Type $code -OutputAssembly cert.dll

Для получение IL-кода — воспользуемся бесплатным продуктом dotPeek (существует большого количество декомпиляторов на любой вкус – ildasm, .Net Reflector, ILSpy и т.д.)

dotPeek – Load — Windows  — IL Viewer

 

dp_06092017

 

Получим код:

il_06092017



Создадим динамический модуль:

https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/25/use-powershell-to-interact-with-the-windows-api-part-1/
https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/26/use-powershell-to-interact-with-the-windows-api-part-2/
https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/27/use-powershell-to-interact-with-the-windows-api-part-3/


# Module Builder            
$Domain = [AppDomain]::CurrentDomain            
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32IC')            
            
# Запускать в памяти [System.Reflection.Emit.AssemblyBuilderAccess]::Run            
$AssemblyBuilder = $Domain.DefineDynamicAssembly(            
    $DynAssembly,             
    [System.Reflection.Emit.AssemblyBuilderAccess]::Run            
)             
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32IC', $False)            
            
# [Dummy]::GetDelegate()            
$TypeBuilder = $ModuleBuilder.DefineType('Dummy', 'Public, Class')            
            
# Определим ReturnTrue метод            
$ReturnTrue = $TypeBuilder.DefineMethod(            
 # Название метода            
 'ReturnTrue',            
 # Атрибуты класса            
 [Reflection.MethodAttributes] 'Public, Static',            
 # Тип возврата            
 [bool],            
 # Тип параметров             
 [Type[]] @(            
  [object],            
  [System.Security.Cryptography.X509Certificates.X509Certificate],            
  [System.Security.Cryptography.X509Certificates.X509Chain],            
  [System.Net.Security.SslPolicyErrors]            
 )            
)             
            
$ilReturnTrue = $ReturnTrue.GetILGenerator()            
$ilReturnTrue.Emit([Reflection.Emit.OpCodes]::Ldc_I4_1)            
$ilReturnTrue.Emit([Reflection.Emit.OpCodes]::Ret)            
            
# Определим GetDelegate метод            
$GetDelegate = $TypeBuilder.DefineMethod(            
 'GetDelegate',            
 [Reflection.MethodAttributes] 'Public, Static',            
 [System.Net.Security.RemoteCertificateValidationCallback],            
 $null            
)            
            
$ctor = [System.Net.Security.RemoteCertificateValidationCallback].GetConstructor(            
 [type[]]@([object],[intptr])            
)            
            
$ilGetDelegate = $GetDelegate.GetILGenerator()            
$ilGetDelegate.Emit([Reflection.Emit.OpCodes]::Ldnull)            
$ilGetDelegate.Emit([Reflection.Emit.OpCodes]::Ldftn,$ReturnTrue)            
$ilGetDelegate.Emit([Reflection.Emit.OpCodes]::Newobj,$ctor)            
$ilGetDelegate.Emit([Reflection.Emit.OpCodes]::Ret)            
            
# Создание типа и вызов метода            
$Dummy = $TypeBuilder.CreateType()            
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $Dummy::GetDelegate()            
            
#  Выполнияем запрос к сайту         
Invoke-RestMethod https://expired.badssl.com/

 

g4_06092017

 

5. Использование модуля Tunable-SSL-Validator

Описание проблемы — http://huddledmasses.org/blog/validating-self-signed-certificates-properly-from-powershell/

Скачать модуль — https://github.com/Jaykul/Tunable-SSL-Validator/archive/master.zip

В данной модуле Invoke-WebRequest/Invoke-RestMethod – переопределены в виде proxy function и добавляют дополнительную диагностическую информацию.


Get-Command -Module TunableSSLValidator -Verb Invoke            
            

CommandType     Name               Version    Source
-----------     ----               -------    ------
Function        Invoke-RestMethod  0.0        TunableSSLValidator
Function        Invoke-WebRequest  0.0        TunableSSLValidator

Дополнительная диагностическая информация:
wir_06092017

 

Добавим сертификат в исключение:

Add-SessionTrustedCertificate -LastFailed

e5_06092017


# Удалим сертификат            
Get-SessionTrustedCertificate | Remove-SessionTrustedCertificate            
            
# Отключим проверку            
Disable-SSLChainValidation            
            
Invoke-RestMethod https://expired.badssl.com/

 

l5_06092017

 

PS. Пример динамического кода из 4 пункта –RemoteCertificateValidationCallback .

Read Full Post »