Настройка клиентской машины

Ручная настройка:

  1. Выполните winrm quickconfig, примите изменения "[y/n]?", введите "y".

  2. Выполните winrm get winrm/config/Client/Auth

Результат выполнения:

Auth
Basic = false
Digest = true
Kerberos = true
Negotiate = true
Certificate = true
CredSSP = true [Source="GPO"]

Если в Certificate установлено значение false, ее следует включить с помощью следующей команды:

winrm set winrm/config/client/auth @\{Certificate="true"}

Windows Remoting не поддерживает пересылку событий через незащищенный транспорт (например, HTTP). Поэтому следует отключить обычную аутентификацию:

winrm set winrm/config/client/auth @\{Basic="false"}
  1. Импортируйте корневой сертификат и сертификат клиента:

    1. От имени администратора откройте certlm.msc (в поиске введите certlm.msc, либо через "win+R")

    2. Правой кнопкой мыши по "Trusted Root Certification Authorities" (Доверенные корневые центры сертификации) > "All Tasks" (Все задачи) > "Import…" (Импорт…)

    3. Импортируйте файл client.pfx. Введите пароль закрытого ключа, если он установлен, и убедитесь, что установлен флажок "Include all extended properties" (Включить все расширенные свойства).

    4. Повторите предыдущий шаг, чтобы импортировать сертификат в "Personal" (Личное).

      После завершения импорта разверните Personal > Certificates и дважды щелкните сертификат клиента, чтобы проверить корректность цепочки сертификатов.

  2. Предоставьте учетной записи NetworkService соответствующие разрешения для доступа к сертификату:

    Способ №1:

    Personal > Certificates > правой кнопкой мыши клиентский сертификат > All tasks(все задачи) > Manage private keys(Управление закрытыми ключами) > Group or user names(Группы или пользователи) > Add(Добавить) > введите NETWORK SERVICE > Check Names(Проверить имена) > OK. Убедитесь, что NETWORK SERVICE имеет разрешение “Чтение”.

    Способ №2:

    Предоставление доступа NETWORK SERVICE с помощью WinHttpCertCfg.exe

    path_to_dir_app\winhttpcertcfg -l -c LOCAL_MACHINE\my -s <CN>

    Например:

    path_to_dir_app\winhttpcertcfg -l -c LOCAL_MACHINE\my -s alertix-client.company.local

    Если NETWORK SERVICE не указан в выходных данных, предоставьте ему разрешения, выполнив следующую команду:

    winhttpcertcfg -g -c LOCAL_MACHINE\my -s <CN> -a NetworkService

Настройка powershell скриптом:

В директории с сертификатами создайте файл configure-client.ps1 и скопируйте в него скрипт:

param (
    [string]$CertPfxPath,
    [string]$CertPassword,
  )


if ([IntPtr]::Size -eq 4) {
    $regPath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
    }

else {
    $regPath = @(
        'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
        'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
        )
}

Start-Transcript -Path configure-client-wef.log

if ($CertPfxPath)
{
    # Configure Windows Remote Management service.
    Write-Host("Setting the Windows Remote Management service to automatic startup")
    Set-Service WInRM -StartupType Automatic

    if ((Get-Service "WinRM").Status -ne "Running")
    {
        Write-Host("Starting the Windows Remote Management service")
        Start-Service "WinRM"
        (Get-Service "WinRM").WaitForStatus("Running", '00:00:10')
        if ((Get-Service "WinRM").Status -ne "Running")
        {
            Write-Host("Failed to start service")
        }
        else
        {
            Write-Host("Service started successfully")
        }
    }
    else
    {
         Write-Host("Windows Remote Management service already started")
    }

    Write-Host("Enabling certificate authentication for Windows Remote Management")
    winrm set winrm/config/client/auth '@{Certificate="true"}'

    # Import certificates to the LocalMachine certificate store.
    function Add-Certificate([String]$CertStore, [System.Security.Cryptography.X509Certificates.X509Certificate2]$Cert)
    {
        try {
            $store = [System.Security.Cryptography.X509Certificates.X509Store]::new($certStore, $certRootStore);
            $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite);
            if ($cert.Thumbprint -in @($store.Certificates | % { $_.Thumbprint } )) {
                Write-Warning "Certificate is already in the store, removing..."
                $store.Remove($cert)
            }

            $store.Add($cert);
        } finally {
            if($store) {
                $store.Dispose()
            }
        }
    }

    $certRootStore = "LocalMachine"
    $certFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet `
              -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
    $collection = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new();
    $collection.Import($CertPfxPath, $CertPassword, $certFlags);

    foreach ($cert in $collection) {
        Write-Host ("Importing certificate subject: '{0}'" -f  $cert.Subject  )
        if ($cert.HasPrivateKey)
        {
            # Import client certificate to the Personal store
            Add-Certificate -CertStore "My" -Cert $cert
            # Grant the Network Service account permissions to read the private key
            $rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
            $fileName = $rsaCert.key.UniqueName
            $path = "$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys\$fileName"
            $permissions = Get-Acl -Path $path
            $access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\NETWORK SERVICE", 'Read', 'None', 'None', 'Allow')
            $permissions.AddAccessRule($access_rule)
            Set-Acl -Path $path -AclObject $permissions
        }
        else
        {
            # Import CA certificate to the Trusted Root CA store
            Add-Certificate -CertStore "Root" -Cert $cert
        }
    }

    # Add Network Service user to Event Log Readers group.
    $group = "Event Log Readers"
    $user = "NT AUTHORITY\NETWORK SERVICE"

    if ((Get-LocalGroupMember $group).Name -contains $user)
    {
        Write-Host("Network Service user is already a member of the Event Log Readers Group")
    }
    else
    {
        Write-Host("Adding Network Service user to the Event Log Readers group")
        Add-LocalGroupMember -Group $group -Member $user
    }
}

Stop-Transcript

Пример запуска скрипта:

./configure-client.ps1 -CertPfxPath C:\certs\client.pfx -CertPassword secret