Compose with TLS
Run the server with a certificate you control, so clients can verify they reached your server instead of just encrypting to whoever answers. Use it whenever clients connect over a network you do not fully trust.
Without this recipe the server makes a new self-signed certificate at every start. Clients can encrypt to it (sslmode=require) but cannot check it.
What you get
- The PostgreSQL protocol on 5432 with TLS required and your certificate.
- The native protocol on 61170 with the same certificate.
- A script that makes a private certificate authority (CA) and a server certificate for
localhost,127.0.0.1, the service namerasterizeddband any names you add. - Everything from Compose basic: named volume, healthcheck, restart policy.
Prerequisites
- Docker with the Compose plugin.
opensslto make certificates. On Windows, Git for Windows includes one. Skip the script if you already have a certificate and key in PEM format.psqlto check the result.
What to edit
-
Copy
.env.exampleto.envand setRASTERIZEDDB_PG_PASSWORD. -
Make the certificates. Add every host name or IP address clients will use to reach the server:
sh./make-certs.sh db.example.compowershell.\make-certs.ps1 db.example.comThis writes
certs/ca.crt,certs/ca.key,certs/server.crtandcerts/server.key. Keep both keys private. Clients getca.crtonly.To use a certificate from your own CA or a public one instead, put the chain in
certs/server.crt(the server's certificate first, then any intermediates) and the private key incerts/server.key. The key can be PKCS#8, PKCS#1 (RSA) or SEC1 (EC) PEM. -
On Linux, the server runs as uid 10001 and has to be able to read the key:
shsudo chown 10001:10001 certs/server.keyThe certificate files are world-readable and need nothing.
The flags that use the files are in compose.yaml:
| Flag | What it does |
|---|---|
--pg-tls require | Refuse PostgreSQL clients that do not use TLS. prefer also accepts cleartext; disable turns TLS off. require is the default, written out here. |
--pg-cert, --pg-key | The certificate chain and key for the PostgreSQL protocol. Give both or neither. |
--rdb-cert, --rdb-key | The certificate chain and key for the native protocol. |
The MySQL, SQL Server and Redis-compatible listeners, when you turn them on, use --pg-cert and --pg-key unless given their own (see All protocols).
Run it
docker compose up -d
docker compose psIf the container restarts in a loop, read the log. A key the server cannot read shows up there:
docker compose logs rasterizeddbCheck that it works
Connect with full verification. verify-full checks that the certificate was signed by your CA and names the host you connected to:
psql "host=localhost port=5432 user=rasterized dbname=postgres sslmode=verify-full sslrootcert=certs/ca.crt" \
-c "SELECT 1 AS ok" ok
----
1
(1 row)A connection by a name the certificate does not list fails with a host name mismatch. Make a new certificate with that name added.
Applications:
- libpq-based drivers (
psql, psycopg, Npgsql, JDBC withsslmode=verify-full) take the CA file assslrootcertor the driver's own equivalent. rasterizeddb_client(native protocol): passrasterizeddb_client::load_ca("certs/ca.crt")?toOptions::trust. See Connecting.
Replace a certificate
Put the new files in certs/ under the same names and restart. The server reads them at start-up only:
docker compose restart rasterizeddbStop and clean up
docker compose down # keeps the data volume
docker compose down -v # deletes the data volume toocerts/ is a folder on your host and stays until you delete it.
Limits
- The PostgreSQL listener does not ask clients for certificates. Clients log in with a password over the encrypted connection.
- Certificates are read at start-up. A renewed certificate takes effect after a restart.
The files
# RasterizedDB with your own TLS certificate on the PostgreSQL and native
# protocols. Make the certificates with make-certs.sh (or make-certs.ps1),
# or put your own in ./certs, then copy .env.example to .env.
name: rasterizeddb-tls
services:
rasterizeddb:
image: ${RASTERIZEDDB_IMAGE:-milendenev/rasterizeddb:1.1.0}
environment:
RASTERIZEDDB_PG_PASSWORD: ${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD in .env}
command:
- --pg-tls
- require # refuse cleartext PostgreSQL connections
- --pg-cert
- /certs/server.crt
- --pg-key
- /certs/server.key
- --rdb-cert
- /certs/server.crt
- --rdb-key
- /certs/server.key
- --log-level
- warn
ports:
- "127.0.0.1:5432:5432"
- "127.0.0.1:61170:61170"
volumes:
- data:/var/lib/rasterizeddb
- ./certs:/certs:ro
restart: unless-stopped
stop_grace_period: 60s
healthcheck:
test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/5432"]
interval: 10s
timeout: 5s
retries: 6
start_period: 30s
volumes:
data:#!/usr/bin/env bash
# Makes a private certificate authority and a server certificate signed by it,
# in ./certs next to this script:
#
# certs/ca.crt give this to clients (sslrootcert=certs/ca.crt)
# certs/ca.key keep it private; it signs new server certificates
# certs/server.crt the server's certificate (--pg-cert, --rdb-cert)
# certs/server.key the server's private key (--pg-key, --rdb-key)
#
# usage: ./make-certs.sh [extra host name or IP ...]
# The certificate always names localhost, 127.0.0.1 and rasterizeddb (the
# Compose service name). Add the names clients use to reach the server:
# ./make-certs.sh db.example.com 10.0.0.5
#
# Needs openssl. Refuses to overwrite an existing certs/ directory.
set -euo pipefail
cd "$(dirname "$0")"
DIR=certs
DAYS="${DAYS:-825}"
if [ -e "$DIR" ]; then
echo "$DIR/ already exists; move it away to make new certificates." >&2
exit 1
fi
command -v openssl >/dev/null || { echo "openssl is not installed." >&2; exit 1; }
san="DNS:localhost,IP:127.0.0.1,DNS:rasterizeddb"
for name in "$@"; do
if [[ "$name" =~ ^[0-9.]+$ || "$name" == *:* ]]; then
san="$san,IP:$name"
else
san="$san,DNS:$name"
fi
done
mkdir -m 700 "$DIR"
umask 077
# Own configuration files, so the result does not depend on the system's
# openssl.cnf.
cat > "$DIR/ca.cnf" <<'EOF'
[req]
prompt = no
distinguished_name = dn
x509_extensions = v3_ca
[dn]
CN = RasterizedDB local CA
[v3_ca]
basicConstraints = critical, CA:TRUE
keyUsage = critical, keyCertSign, cRLSign
subjectKeyIdentifier = hash
EOF
cat > "$DIR/server.cnf" <<'EOF'
[req]
prompt = no
distinguished_name = dn
[dn]
CN = rasterizeddb
EOF
cat > "$DIR/server.ext" <<EOF
basicConstraints = critical, CA:FALSE
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = $san
EOF
openssl req -x509 -new -newkey rsa:3072 -nodes -sha256 -days 3650 \
-config "$DIR/ca.cnf" -keyout "$DIR/ca.key" -out "$DIR/ca.crt"
openssl req -new -newkey rsa:3072 -nodes -sha256 \
-config "$DIR/server.cnf" -keyout "$DIR/server.key" -out "$DIR/server.csr"
openssl x509 -req -sha256 -days "$DAYS" \
-in "$DIR/server.csr" -CA "$DIR/ca.crt" -CAkey "$DIR/ca.key" -CAcreateserial \
-extfile "$DIR/server.ext" -out "$DIR/server.crt"
rm -f "$DIR/ca.cnf" "$DIR/server.cnf" "$DIR/server.ext" "$DIR/server.csr" "$DIR/ca.srl"
chmod 755 "$DIR"
chmod 644 "$DIR/ca.crt" "$DIR/server.crt"
chmod 600 "$DIR/ca.key" "$DIR/server.key"
echo
echo "Wrote $DIR/ca.crt and $DIR/server.crt (with their keys) for: $san"
echo
echo "The server runs as uid 10001 and must be able to read $DIR/server.key."
echo "On Linux, hand the key to that uid (you then need sudo to read it yourself):"
echo " sudo chown 10001:10001 $DIR/server.key"# Makes a private certificate authority and a server certificate signed by it,
# in .\certs next to this script:
#
# certs\ca.crt give this to clients (sslrootcert=certs/ca.crt)
# certs\ca.key keep it private; it signs new server certificates
# certs\server.crt the server's certificate (--pg-cert, --rdb-cert)
# certs\server.key the server's private key (--pg-key, --rdb-key)
#
# usage: .\make-certs.ps1 [extra host name or IP ...]
# The certificate always names localhost, 127.0.0.1 and rasterizeddb (the
# Compose service name). Add the names clients use to reach the server:
# .\make-certs.ps1 db.example.com 10.0.0.5
#
# Needs openssl on PATH (Git for Windows ships one in its usr\bin folder).
# Refuses to overwrite an existing certs folder.
param(
[Parameter(ValueFromRemainingArguments = $true)]
[string[]] $Names,
[int] $Days = 825
)
$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot
$dir = 'certs'
if (Test-Path $dir) { throw "$dir already exists; move it away to make new certificates." }
if (-not (Get-Command openssl -ErrorAction SilentlyContinue)) { throw 'openssl is not on PATH.' }
$san = 'DNS:localhost,IP:127.0.0.1,DNS:rasterizeddb'
foreach ($name in $Names) {
if ($name -match '^[0-9.]+$' -or $name -like '*:*') { $san += ",IP:$name" } else { $san += ",DNS:$name" }
}
New-Item -ItemType Directory -Path $dir | Out-Null
function Invoke-OpenSsl {
& openssl @args
if ($LASTEXITCODE -ne 0) { throw "openssl $($args[0]) failed" }
}
# Own configuration files, so the result does not depend on the system's
# openssl.cnf.
@'
[req]
prompt = no
distinguished_name = dn
x509_extensions = v3_ca
[dn]
CN = RasterizedDB local CA
[v3_ca]
basicConstraints = critical, CA:TRUE
keyUsage = critical, keyCertSign, cRLSign
subjectKeyIdentifier = hash
'@ | Set-Content -Encoding ascii "$dir\ca.cnf"
@'
[req]
prompt = no
distinguished_name = dn
[dn]
CN = rasterizeddb
'@ | Set-Content -Encoding ascii "$dir\server.cnf"
@"
basicConstraints = critical, CA:FALSE
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = $san
"@ | Set-Content -Encoding ascii "$dir\server.ext"
Invoke-OpenSsl req -x509 -new -newkey rsa:3072 -nodes -sha256 -days 3650 `
-config "$dir/ca.cnf" -keyout "$dir/ca.key" -out "$dir/ca.crt"
Invoke-OpenSsl req -new -newkey rsa:3072 -nodes -sha256 `
-config "$dir/server.cnf" -keyout "$dir/server.key" -out "$dir/server.csr"
Invoke-OpenSsl x509 -req -sha256 -days $Days `
-in "$dir/server.csr" -CA "$dir/ca.crt" -CAkey "$dir/ca.key" -CAcreateserial `
-extfile "$dir/server.ext" -out "$dir/server.crt"
Remove-Item -Force -ErrorAction SilentlyContinue "$dir\ca.cnf", "$dir\server.cnf", "$dir\server.ext", "$dir\server.csr", "$dir\ca.srl"
Write-Host ''
Write-Host "Wrote $dir\ca.crt and $dir\server.crt (with their keys) for: $san"
Write-Host "Keep $dir\ca.key and $dir\server.key private."# Copy to .env next to compose.yaml and change the password.
# The password of the role `rasterized`, used on the first start only.
RASTERIZEDDB_PG_PASSWORD=change-me-to-a-long-random-password
# The image and tag. Pin a full version.
RASTERIZEDDB_IMAGE=milendenev/rasterizeddb:1.1.0