#Requires -Version 5.1 <# .SYNOPSIS RasterizedDB: a private certificate authority and a server certificate it signs, as PEM files the server reads (--pg-cert/--pg-key, --rdb-cert/--rdb-key). .DESCRIPTION Uses .NET's certificate classes under PowerShell 7.3 or newer, and openssl (for example the one that comes with Git for Windows) under Windows PowerShell 5.1. Nothing is put in the Windows certificate store. .EXAMPLE .\setup.ps1 -Names db.example.com,10.0.0.5 #> [CmdletBinding()] param( [string]$TlsDir = $(if ($env:RDB_TLS_DIR) { $env:RDB_TLS_DIR } else { '.\tls' }), # Host names and IP addresses clients connect to. [string[]]$Names = $(if ($env:RDB_TLS_NAMES) { $env:RDB_TLS_NAMES -split ',' } else { @('localhost', '127.0.0.1') }), # Writes .pem and .key. [string]$FileName = $(if ($env:RDB_TLS_FILE) { $env:RDB_TLS_FILE } else { 'server' }), [string]$CaName = $(if ($env:RDB_CA_NAME) { $env:RDB_CA_NAME } else { 'RasterizedDB private CA' }), [int]$CaDays = $(if ($env:RDB_CA_DAYS) { [int]$env:RDB_CA_DAYS } else { 3650 }), [int]$CertDays = $(if ($env:RDB_CERT_DAYS) { [int]$env:RDB_CERT_DAYS } else { 825 }), # Replace an existing server certificate. [switch]$Force = ($env:RDB_TLS_FORCE -eq '1') ) $ErrorActionPreference = 'Stop' New-Item -ItemType Directory -Force -Path $TlsDir | Out-Null $TlsDir = (Resolve-Path -LiteralPath $TlsDir).Path $caPem = Join-Path $TlsDir 'ca.pem' $caKey = Join-Path $TlsDir 'ca.key' $certPem = Join-Path $TlsDir "$FileName.pem" $certKey = Join-Path $TlsDir "$FileName.key" $Names = @($Names | ForEach-Object { $_.Trim() } | Where-Object { $_ }) if ($Names.Count -eq 0) { throw 'Names is empty.' } function Protect-KeyFile([string]$Path) { # Readable by you, SYSTEM and Administrators only. & icacls.exe $Path /inheritance:r /grant:r "$($env:USERNAME):F" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null if ($LASTEXITCODE -ne 0) { throw "icacls could not restrict $Path." } } $useDotNet = $PSVersionTable.PSVersion -ge [version]'7.3' $openssl = Get-Command openssl -ErrorAction SilentlyContinue if (-not $useDotNet -and -not $openssl) { throw 'Run this under PowerShell 7.3 or newer (pwsh), or put openssl.exe on PATH (Git for Windows has one in C:\Program Files\Git\usr\bin).' } $haveCa = (Test-Path -LiteralPath $caPem) -and (Test-Path -LiteralPath $caKey) $haveCert = Test-Path -LiteralPath $certPem if ($useDotNet) { $X = 'System.Security.Cryptography.X509Certificates' $sha256 = [System.Security.Cryptography.HashAlgorithmName]::SHA256 $pkcs1 = [System.Security.Cryptography.RSASignaturePadding]::Pkcs1 $now = [DateTimeOffset]::UtcNow if ($haveCa) { $ca = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromPemFile($caPem, $caKey) Write-Host "Reusing the certificate authority: $caPem" } else { $caRsa = [System.Security.Cryptography.RSA]::Create(3072) $caReq = New-Object "$X.CertificateRequest" ("CN=$CaName", $caRsa, $sha256, $pkcs1) $caReq.CertificateExtensions.Add((New-Object "$X.X509BasicConstraintsExtension" ($true, $false, 0, $true))) $caReq.CertificateExtensions.Add((New-Object "$X.X509KeyUsageExtension" ([System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]'KeyCertSign, CrlSign', $true))) $caReq.CertificateExtensions.Add((New-Object "$X.X509SubjectKeyIdentifierExtension" ($caReq.PublicKey, $false))) $ca = $caReq.CreateSelfSigned($now.AddDays(-1), $now.AddDays($CaDays)) Set-Content -LiteralPath $caPem -Value $ca.ExportCertificatePem() -Encoding ascii Set-Content -LiteralPath $caKey -Value $caRsa.ExportPkcs8PrivateKeyPem() -Encoding ascii Protect-KeyFile $caKey Write-Host "Made the certificate authority: $caPem" } if ($haveCert -and -not $Force) { Write-Host "$certPem already exists; pass -Force to replace it." } else { $rsa = [System.Security.Cryptography.RSA]::Create(2048) $req = New-Object "$X.CertificateRequest" ("CN=$($Names[0])", $rsa, $sha256, $pkcs1) $san = New-Object "$X.SubjectAlternativeNameBuilder" foreach ($n in $Names) { $ip = $null if ([System.Net.IPAddress]::TryParse($n, [ref]$ip)) { $san.AddIpAddress($ip) } else { $san.AddDnsName($n) } } $req.CertificateExtensions.Add($san.Build()) $req.CertificateExtensions.Add((New-Object "$X.X509BasicConstraintsExtension" ($false, $false, 0, $true))) $req.CertificateExtensions.Add((New-Object "$X.X509KeyUsageExtension" ([System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]'DigitalSignature, KeyEncipherment', $true))) $eku = New-Object System.Security.Cryptography.OidCollection [void]$eku.Add((New-Object System.Security.Cryptography.Oid '1.3.6.1.5.5.7.3.1')) # server [void]$eku.Add((New-Object System.Security.Cryptography.Oid '1.3.6.1.5.5.7.3.2')) # client $req.CertificateExtensions.Add((New-Object "$X.X509EnhancedKeyUsageExtension" ($eku, $false))) $serial = [System.Security.Cryptography.RandomNumberGenerator]::GetBytes(16) $serial[0] = $serial[0] -band 0x7F $notAfter = $now.AddDays($CertDays) $caNotAfter = [DateTimeOffset]$ca.NotAfter if ($notAfter -gt $caNotAfter) { $notAfter = $caNotAfter } $cert = $req.Create($ca, $now.AddHours(-1), $notAfter, $serial) Set-Content -LiteralPath $certPem -Value $cert.ExportCertificatePem() -Encoding ascii Set-Content -LiteralPath $certKey -Value $rsa.ExportPkcs8PrivateKeyPem() -Encoding ascii Protect-KeyFile $certKey Write-Host "Made $certPem for $($Names -join ', ')" } } else { Push-Location $TlsDir try { if (-not $haveCa) { & $openssl.Source req -x509 -newkey rsa:3072 -nodes -sha256 -days $CaDays -subj "/CN=$CaName" ` -keyout ca.key -out ca.pem -addext 'basicConstraints=critical,CA:TRUE' -addext 'keyUsage=critical,keyCertSign,cRLSign' if ($LASTEXITCODE -ne 0) { throw 'openssl could not make the certificate authority.' } Protect-KeyFile $caKey Write-Host "Made the certificate authority: $caPem" } else { Write-Host "Reusing the certificate authority: $caPem" } if ($haveCert -and -not $Force) { Write-Host "$certPem already exists; pass -Force to replace it." } else { $san = ($Names | ForEach-Object { $ip = $null if ([System.Net.IPAddress]::TryParse($_, [ref]$ip)) { "IP:$_" } else { "DNS:$_" } }) -join ',' $ext = "subjectAltName=$san`nbasicConstraints=critical,CA:FALSE`nkeyUsage=critical,digitalSignature,keyEncipherment`nextendedKeyUsage=serverAuth,clientAuth`n" Set-Content -LiteralPath "$FileName.ext" -Value $ext -Encoding ascii -NoNewline & $openssl.Source req -newkey rsa:2048 -nodes -sha256 -subj "/CN=$($Names[0])" -keyout "$FileName.key" -out "$FileName.csr" if ($LASTEXITCODE -ne 0) { throw 'openssl could not make the key.' } & $openssl.Source x509 -req -in "$FileName.csr" -CA ca.pem -CAkey ca.key -CAcreateserial ` -days $CertDays -sha256 -extfile "$FileName.ext" -out "$FileName.pem" if ($LASTEXITCODE -ne 0) { throw 'openssl could not sign the certificate.' } Remove-Item -LiteralPath "$FileName.csr", "$FileName.ext" -Force Protect-KeyFile $certKey Write-Host "Made $certPem for $san" } } finally { Pop-Location } } Write-Host '' Write-Host 'Server flags:' Write-Host " --pg-cert $certPem --pg-key $certKey" Write-Host " --rdb-cert $certPem --rdb-key $certKey" Write-Host "Give clients $caPem, for example:" Write-Host " psql `"host=$($Names[0]) dbname=postgres user=rasterized sslmode=verify-full sslrootcert=$caPem`"" Write-Host 'Keep ca.key off the server: it can sign certificates your clients will trust.'