Generate a 10-year root CA in entrypoint.sh and sign the server leaf with it. Only the root CA is distributed to clients (including GPO); the leaf is served by the app and is reissued automatically when CERT_HOSTNAMES changes. Update the Windows installer, ZIP package, settings UI and docs for the two-tier scheme.
223 lines
9.5 KiB
PowerShell
223 lines
9.5 KiB
PowerShell
# Script: install-whatido-cert.ps1
|
||
# Импортирует корневой сертификат WhatIDo в локальное хранилище
|
||
# "Доверенные корневые центры сертификации" (Root), чтобы браузер перестал
|
||
# показывать предупреждение о небезопасном подключении.
|
||
#
|
||
# Обычный запуск — двойной клик по install-whatido-cert.cmd в этой же папке.
|
||
# Из PowerShell:
|
||
# .\install-whatido-cert.ps1
|
||
# .\install-whatido-cert.ps1 -StoreLocation CurrentUser
|
||
# .\install-whatido-cert.ps1 -CheckHost 192.168.88.55
|
||
# Удаление:
|
||
# .\install-whatido-cert.ps1 -Uninstall
|
||
|
||
param(
|
||
[ValidateSet('LocalMachine', 'CurrentUser')]
|
||
[string] $StoreLocation = 'LocalMachine',
|
||
|
||
[string] $CertPath = '',
|
||
|
||
[string] $CertUrl = 'http://127.0.0.1:3003/certs/root-ca.pem',
|
||
|
||
[string] $CheckHost = '',
|
||
|
||
[switch] $Uninstall
|
||
)
|
||
|
||
$ErrorActionPreference = 'Stop'
|
||
$storePath = "Cert:\$StoreLocation\Root"
|
||
|
||
function ConvertFrom-PemToDer([byte[]] $Bytes) {
|
||
$text = [System.Text.Encoding]::ASCII.GetString($Bytes)
|
||
if ($text -notmatch '-----BEGIN CERTIFICATE-----') { return $Bytes }
|
||
$body = ($text -split "`r?`n" | Where-Object { $_ -and $_ -notmatch '-----' }) -join ''
|
||
return [Convert]::FromBase64String($body.Trim())
|
||
}
|
||
|
||
function Get-SanValues($Cert) {
|
||
$ext = $Cert.Extensions | Where-Object { $_.Oid.FriendlyName -eq 'Subject Alternative Name' }
|
||
if (-not $ext) { return @() }
|
||
return @($ext.Format($false) -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||
}
|
||
|
||
function Get-HostInSan($Cert, [string] $HostName) {
|
||
if (-not $HostName) { return $null }
|
||
$h = $HostName.Trim()
|
||
foreach ($s in (Get-SanValues $Cert)) {
|
||
$v = ($s -split ':', 2)[1]
|
||
if ($null -eq $v) { continue }
|
||
if ($v -ieq $h) { return $s }
|
||
}
|
||
return $null
|
||
}
|
||
|
||
function Test-CertTrusted($Cert) {
|
||
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
|
||
$chain.ChainPolicy.RevocationMode = [System.Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck
|
||
$ok = $chain.Build($Cert)
|
||
if (-not $ok) {
|
||
foreach ($s in $chain.ChainStatus) {
|
||
Write-Warning ("Цепочка: " + $s.Status + " - " + $s.StatusInformation.Trim())
|
||
}
|
||
}
|
||
return $ok
|
||
}
|
||
|
||
if (-not (Test-Path $storePath)) {
|
||
Write-Error "Хранилище не найдено: $storePath"
|
||
exit 1
|
||
}
|
||
|
||
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', $StoreLocation)
|
||
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
|
||
|
||
# --- 1. Получаем сертификат: файл рядом со скриптом, потом - загрузка по URL ---
|
||
$bytes = $null
|
||
$source = ''
|
||
|
||
if ($CertPath) {
|
||
if (-not (Test-Path $CertPath)) { Write-Error "Файл не найден: $CertPath"; $store.Close(); exit 1 }
|
||
$bytes = [System.IO.File]::ReadAllBytes((Resolve-Path $CertPath))
|
||
$source = $CertPath
|
||
} else {
|
||
$here = $PSScriptRoot
|
||
if (-not $here) { $here = Split-Path -Parent $MyInvocation.MyCommand.Path }
|
||
foreach ($name in @('whatido-root-ca.cer', 'whatido-root-ca.pem', 'whatido-cert.cer', 'whatido-cert.pem', 'cert.pem')) {
|
||
$candidate = Join-Path $here $name
|
||
if (Test-Path $candidate) {
|
||
$bytes = [System.IO.File]::ReadAllBytes($candidate)
|
||
$source = $candidate
|
||
break
|
||
}
|
||
}
|
||
if (-not $bytes) {
|
||
Write-Host "Рядом со скриптом сертификата нет, скачиваем из $CertUrl" -ForegroundColor Cyan
|
||
try {
|
||
$dl = Invoke-WebRequest -Uri $CertUrl -UseBasicParsing -TimeoutSec 30
|
||
$bytes = [byte[]] $dl.Content
|
||
if ($bytes.Length -ge 2 -and [char] $bytes[0] -eq '{') { $bytes = [System.Text.Encoding]::UTF8.GetBytes($dl.Content) }
|
||
$source = $CertUrl
|
||
} catch {
|
||
Write-Error "Не удалось скачать сертификат: $_"
|
||
$store.Close()
|
||
exit 1
|
||
}
|
||
}
|
||
}
|
||
|
||
$bytes = ConvertFrom-PemToDer $bytes
|
||
if (-not $bytes -or $bytes.Length -lt 100) {
|
||
Write-Error "Полученные данные не похожи на сертификат (источник: $source)"
|
||
$store.Close()
|
||
exit 1
|
||
}
|
||
|
||
# --- 2. Показываем, что именно ставим ---
|
||
try {
|
||
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes)
|
||
} catch {
|
||
Write-Error "Не удалось разобрать сертификат: $_"
|
||
$store.Close()
|
||
exit 1
|
||
}
|
||
|
||
Write-Host "Источник: $source" -ForegroundColor Cyan
|
||
Write-Host "Тема: $($cert.Subject)" -ForegroundColor Yellow
|
||
Write-Host "Издатель: $($cert.Issuer)" -ForegroundColor Yellow
|
||
Write-Host "Срок: $($cert.NotBefore) - $($cert.NotAfter)" -ForegroundColor Yellow
|
||
Write-Host "Отпечаток: $($cert.Thumbprint)" -ForegroundColor DarkGray
|
||
|
||
$san = @(Get-SanValues $cert)
|
||
if ($san.Count -gt 0) {
|
||
Write-Host "Адреса в сертификате: $($san.Count)" -ForegroundColor Yellow
|
||
foreach ($s in ($san | Select-Object -First 12)) { Write-Host " $s" -ForegroundColor DarkGray }
|
||
if ($san.Count -gt 12) { Write-Host " ... и ещё $($san.Count - 12)" -ForegroundColor DarkGray }
|
||
} else {
|
||
Write-Host "Это корневой сертификат: списка адресов у него нет." -ForegroundColor DarkGray
|
||
}
|
||
|
||
if ($cert.Subject -match 'whatido' -and $cert.Issuer -ne $cert.Subject) {
|
||
Write-Warning "Сертификат выпущен не самим собой. Продолжайте, только если доверяете его издателю."
|
||
}
|
||
|
||
if ($CheckHost) {
|
||
if ($san.Count -eq 0) {
|
||
Write-Host "В этом сертификате нет списка адресов: это корневой CA. Адреса сервера смотрите в whatido-server.pem или в разделе «Сертификат» настроек." -ForegroundColor DarkGray
|
||
} else {
|
||
$hit = Get-HostInSan $cert $CheckHost
|
||
if ($hit) {
|
||
Write-Host "Адрес $CheckHost покрыт сертификатом ($hit) - предупреждение браузера исчезнет." -ForegroundColor Green
|
||
} else {
|
||
Write-Warning "Адрес $CheckHost НЕ входит в сертификат. После установки предупреждение останется. Добавьте адрес в CERT_HOSTNAMES в .env и пересоздайте сертификат."
|
||
}
|
||
}
|
||
}
|
||
|
||
if ($Uninstall) {
|
||
$targets = @($store.Certificates | Where-Object {
|
||
$_.Thumbprint -eq $cert.Thumbprint -or $_.Subject -eq $cert.Subject -or $_.Subject -match 'O=WhatIDo'
|
||
})
|
||
if (-not $targets) {
|
||
Write-Host "В хранилище $storePath нет сертификатов WhatIDo." -ForegroundColor Green
|
||
} else {
|
||
foreach ($t in $targets) {
|
||
$store.Remove($t)
|
||
Write-Host "Удалён: $($t.Subject) ($($t.Thumbprint))" -ForegroundColor Yellow
|
||
}
|
||
}
|
||
$store.Close()
|
||
Write-Host "Готово. Перезапустите браузер." -ForegroundColor Cyan
|
||
exit 0
|
||
}
|
||
|
||
$stale = @($store.Certificates | Where-Object {
|
||
$_.Thumbprint -ne $cert.Thumbprint -and ($_.Subject -eq $cert.Subject -or $_.Subject -match 'O=WhatIDo')
|
||
})
|
||
foreach ($s in $stale) {
|
||
$store.Remove($s)
|
||
Write-Host "Удалён устаревший сертификат: $($s.Subject) ($($s.Thumbprint))" -ForegroundColor Yellow
|
||
}
|
||
|
||
# --- 3. Идемпотентность: если такой сертификат уже есть - ничего не делаем ---
|
||
$existing = $store.Certificates | Where-Object { $_.Thumbprint -eq $cert.Thumbprint }
|
||
if ($existing) {
|
||
Write-Host "Сертификат уже установлен в $storePath" -ForegroundColor Green
|
||
if (Test-CertTrusted $cert) {
|
||
Write-Host "Проверка цепочки: сертификат доверенный." -ForegroundColor Green
|
||
} else {
|
||
Write-Warning "Сертификат есть в хранилище, но проверка цепочки не прошла."
|
||
}
|
||
$store.Close()
|
||
Write-Host "Перезапустите браузер." -ForegroundColor Cyan
|
||
exit 0
|
||
}
|
||
|
||
# --- 4. Импорт ---
|
||
try {
|
||
$store.Add($cert)
|
||
} catch {
|
||
Write-Error "Не удалось добавить сертификат: $_"
|
||
$store.Close()
|
||
exit 1
|
||
}
|
||
|
||
Write-Host "Корневой сертификат добавлен в хранилище $storePath" -ForegroundColor Green
|
||
|
||
# --- 5. Проверка цепочки ---
|
||
if (Test-CertTrusted $cert) {
|
||
Write-Host "Проверка цепочки: сертификат доверенный." -ForegroundColor Green
|
||
} else {
|
||
Write-Warning "Проверка цепочки не прошла: система всё ещё не доверяет сертификату."
|
||
}
|
||
|
||
# --- 6. Итог ---
|
||
Write-Host "Теперь в хранилище:" -ForegroundColor Cyan
|
||
$store.Certificates |
|
||
Where-Object { $_.NotAfter -gt (Get-Date) -and ($_.Subject -match 'O=WhatIDo' -or $_.Thumbprint -eq $cert.Thumbprint) } |
|
||
Select-Object -First 5 Subject, NotAfter, Thumbprint |
|
||
Format-Table -AutoSize
|
||
|
||
$store.Close()
|
||
Write-Host "Перезапустите браузер полностью и откройте приложение по адресу из сертификата." -ForegroundColor Cyan
|
||
Write-Host "Откат: .\install-whatido-cert.ps1 -Uninstall" -ForegroundColor Gray
|