Загрузка данных


<#
.SYNOPSIS
    Поиск сертификатов, развернутых через групповые политики (GPO),
    с фильтрацией по слабым RSA-ключам.
.DESCRIPTION
    Скрипт обращается к веткам реестра Policies\Microsoft\SystemCertificates
    для LocalMachine и CurrentUser, извлекает сертификаты и применяет
    условия:
      1) RSA KeySize <= 2048 и NotAfter >= 2030-01-01
      2) RSA KeySize <= 1024 (любая дата)
#>

# --- Пороговые значения ---
$maxKeySizeLongLived = 2048
$maxKeySizeAnyDate   = 1024
$thresholdDate       = Get-Date "2030-01-01 00:00:00"

# --- Пути к GPO-хранилищам в реестре ---
$gpoRegistryPaths = @(
    @{ Path = "HKLM:\SOFTWARE\Policies\Microsoft\SystemCertificates"; Scope = "LocalMachine (GPO)"; CertProvider = "Cert:\LocalMachine" },
    @{ Path = "HKCU:\SOFTWARE\Policies\Microsoft\SystemCertificates"; Scope = "CurrentUser (GPO)";  CertProvider = "Cert:\CurrentUser" }
)

# --- Функция проверки условий ---
function Test-WeakRsaCert {
    param(
        [Parameter(Mandatory)] [System.Security.Cryptography.X509Certificates.X509Certificate2] $Cert
    )

    if ($Cert.PublicKey.Oid.Value -ne "1.2.840.113549.1.1.1") { return $false }  # только RSA

    $keySize  = $Cert.PublicKey.Key.KeySize
    $notAfter = $Cert.NotAfter

    $cond1 = ($keySize -le $maxKeySizeLongLived) -and ($notAfter -ge $thresholdDate)
    $cond2 = ($keySize -le $maxKeySizeAnyDate)

    return ($cond1 -or $cond2)
}

# --- Сбор сертификатов из GPO-хранилищ ---
$gpoCerts = foreach ($gpo in $gpoRegistryPaths) {
    if (-not (Test-Path $gpo.Path)) {
        Write-Verbose "Путь не существует: $($gpo.Path)"
        continue
    }

    # Перебираем подразделы (Root, CA, Trust и т.д.)
    Get-ChildItem -Path $gpo.Path -ErrorAction SilentlyContinue | ForEach-Object {
        $storeName = $_.PSChildName
        $certKeyPath = Join-Path $_.PSPath "Certificates"

        if (-not (Test-Path $certKeyPath)) { return }

        Get-ChildItem -Path $certKeyPath -ErrorAction SilentlyContinue | ForEach-Object {
            $thumbprint = $_.PSChildName

            # Ищем сертификат в логическом хранилище по отпечатку
            $cert = Get-ChildItem -Path "$($gpo.CertProvider)\$storeName" -ErrorAction SilentlyContinue |
                    Where-Object { $_.Thumbprint -eq $thumbprint }

            if ($cert -and (Test-WeakRsaCert -Cert $cert)) {
                $keySize = $cert.PublicKey.Key.KeySize
                $matched = if ($keySize -le $maxKeySizeAnyDate) {
                    "KeySize<=1024 (any date)"
                } else {
                    "KeySize<=2048 & NotAfter>=2030"
                }

                [PSCustomObject]@{
                    Source        = $gpo.Scope
                    StoreName     = $storeName
                    Subject       = $cert.Subject
                    Thumbprint    = $thumbprint
                    KeySize       = $keySize
                    NotAfter      = $cert.NotAfter
                    HasPrivateKey = $cert.HasPrivateKey
                    MatchedRule   = $matched
                }
            }
        }
    }
}

# --- Вывод результатов ---
if ($gpoCerts) {
    Write-Host "`nНайдены сертификаты GPO с weak RSA-ключами:" -ForegroundColor Yellow
    $gpoCerts | Format-Table -AutoSize -Wrap
    $gpoCerts | Export-Csv -Path ".\GPO_WeakRSA_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv" -NoTypeInformation -Encoding UTF8
    Write-Host "`nРезультаты сохранены в CSV." -ForegroundColor Green
} else {
    Write-Host "`nСертификаты GPO, удовлетворяющие условиям, не найдены." -ForegroundColor Green
}