TLS certificates
Makes a private certificate authority (ca.pem, ca.key) and a server certificate signed by it (server.pem, server.key), as the PEM files the server reads. Use them when you have no certificate from a public authority: give the server the certificate and key, and give your clients ca.pem so they can check who they are talking to.
Before you start
- Linux:
openssl1.1.1 or newer. - Windows: PowerShell 7.3 or newer (
pwsh). Windows PowerShell 5.1 works too ifopenssl.exeis onPATH. Git for Windows ships one inC:\Program Files\Git\usr\bin. The PowerShell script does not touch the Windows certificate store. - The names clients will connect with: every host name and IP address goes into the certificate. A client that checks the certificate (
sslmode=verify-full) refuses a name that is not in it.
Settings
| bash variable | PowerShell parameter | Default | What it does |
|---|---|---|---|
RDB_TLS_DIR | -TlsDir | ./tls | Where the files are written. |
RDB_TLS_NAMES | -Names | localhost,127.0.0.1 | Host names and IP addresses for the certificate, comma-separated. The first is also its common name. |
RDB_TLS_FILE | -FileName | server | Base name of the certificate and key files. |
RDB_CA_NAME | -CaName | RasterizedDB private CA | The authority's common name. |
RDB_CA_DAYS | -CaDays | 3650 | How long the authority is valid. |
RDB_CERT_DAYS | -CertDays | 825 | How long the server certificate is valid. |
RDB_TLS_FORCE=1 | -Force | off | Replace an existing server certificate. |
An existing ca.pem and ca.key are always reused. To make more certificates from the same authority, run the script again with a different file name and the same directory, for example RDB_TLS_FILE=node2 RDB_TLS_NAMES=10.0.0.2 ./setup.sh.
Run it
RDB_TLS_NAMES=db.example.com,10.0.0.5 ./setup.sh.\setup.ps1 -Names db.example.com,10.0.0.5The script ends by printing the server flags to use and an example client connection.
Use the files
Start the server with the certificate on the PostgreSQL and native listeners:
export RASTERIZEDDB_PG_PASSWORD='use-a-long-secret'
rasterizeddb --location ./data --protocol both --pg-addr 0.0.0.0 --pg-tls require \
--pg-cert ./tls/server.pem --pg-key ./tls/server.key \
--rdb-cert ./tls/server.pem --rdb-key ./tls/server.keyThe MySQL and SQL Server listeners use --pg-cert and --pg-key unless you give them their own (--mysql-cert, --mssql-cert). So does the Redis port under --kv-tls on.
Check that it works
openssl verify -CAfile tls/ca.pem tls/server.pem
openssl x509 -in tls/server.pem -noout -subject -ext subjectAltNametls/server.pem: OKAgainst a running server, a client that checks the certificate connects without warnings:
PGPASSWORD='use-a-long-secret' psql "host=db.example.com dbname=postgres user=rasterized sslmode=verify-full sslrootcert=tls/ca.pem" -c "SELECT 1"Stop or undo
Delete the directory. Clients that were given ca.pem will then refuse any certificate a new authority signs, so hand out the new ca.pem when you make one.
Limits
- Without
--pg-cert/--pg-keythe server makes a self-signed certificate at every start. Clients can encrypt to it but cannot check it, sosslmode=requireworks andverify-fulldoes not. - Keep
ca.keysomewhere other than the database server. Anyone holding it can make certificates your clients will trust. - The server reads the certificate and key at start. After replacing them, restart the server.
The files
#!/usr/bin/env bash
# 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).
#
# Every setting can be overridden from the environment, for example:
# RDB_TLS_NAMES=db.example.com,10.0.0.5 ./setup.sh
set -euo pipefail
RDB_TLS_DIR="${RDB_TLS_DIR:-./tls}" # where the files go
RDB_TLS_NAMES="${RDB_TLS_NAMES:-localhost,127.0.0.1}" # host names and IPs clients connect to, comma-separated
RDB_TLS_FILE="${RDB_TLS_FILE:-server}" # writes <name>.pem and <name>.key
RDB_CA_NAME="${RDB_CA_NAME:-RasterizedDB private CA}"
RDB_CA_DAYS="${RDB_CA_DAYS:-3650}"
RDB_CERT_DAYS="${RDB_CERT_DAYS:-825}"
RDB_TLS_FORCE="${RDB_TLS_FORCE:-0}" # 1 replaces an existing server certificate
command -v openssl >/dev/null 2>&1 || { echo "error: openssl is needed" >&2; exit 1; }
mkdir -p "$RDB_TLS_DIR"
cd "$RDB_TLS_DIR"
umask 077
# The authority: made once, reused on every later run.
if [ ! -f ca.pem ] || [ ! -f ca.key ]; then
openssl req -x509 -newkey rsa:3072 -nodes -sha256 -days "$RDB_CA_DAYS" \
-subj "/CN=$RDB_CA_NAME" -keyout ca.key -out ca.pem \
-addext "basicConstraints=critical,CA:TRUE" \
-addext "keyUsage=critical,keyCertSign,cRLSign"
echo "Made the certificate authority: $PWD/ca.pem"
else
echo "Reusing the certificate authority: $PWD/ca.pem"
fi
if [ -f "$RDB_TLS_FILE.pem" ] && [ "$RDB_TLS_FORCE" != 1 ]; then
echo "$PWD/$RDB_TLS_FILE.pem already exists; set RDB_TLS_FORCE=1 to replace it"
else
san=""
first=""
IFS=',' read -r -a names <<< "$RDB_TLS_NAMES"
for n in "${names[@]}"; do
n="$(echo "$n" | tr -d '[:space:]')"
[ -n "$n" ] || continue
[ -n "$first" ] || first="$n"
if [[ "$n" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ || "$n" == *:* ]]; then
san="${san:+$san,}IP:$n"
else
san="${san:+$san,}DNS:$n"
fi
done
[ -n "$first" ] || { echo "error: RDB_TLS_NAMES is empty" >&2; exit 1; }
printf 'subjectAltName=%s\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\n' \
"$san" > "$RDB_TLS_FILE.ext"
openssl req -newkey rsa:2048 -nodes -sha256 -subj "/CN=$first" \
-keyout "$RDB_TLS_FILE.key" -out "$RDB_TLS_FILE.csr"
openssl x509 -req -in "$RDB_TLS_FILE.csr" -CA ca.pem -CAkey ca.key -CAcreateserial \
-days "$RDB_CERT_DAYS" -sha256 -extfile "$RDB_TLS_FILE.ext" -out "$RDB_TLS_FILE.pem"
rm -f "$RDB_TLS_FILE.csr" "$RDB_TLS_FILE.ext"
echo "Made $PWD/$RDB_TLS_FILE.pem for $san"
fi
chmod 600 ca.key "$RDB_TLS_FILE.key"
chmod 644 ca.pem "$RDB_TLS_FILE.pem"
echo
echo "Server flags:"
echo " --pg-cert $PWD/$RDB_TLS_FILE.pem --pg-key $PWD/$RDB_TLS_FILE.key"
echo " --rdb-cert $PWD/$RDB_TLS_FILE.pem --rdb-key $PWD/$RDB_TLS_FILE.key"
echo "Give clients $PWD/ca.pem, for example:"
echo " psql \"host=${first:-localhost} dbname=postgres user=rasterized sslmode=verify-full sslrootcert=$PWD/ca.pem\""
echo "Keep ca.key off the server: it can sign certificates your clients will trust."#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 <FileName>.pem and <FileName>.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.'