Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ is at [docs.gen0sec.com](https://docs.gen0sec.com).
`SynapseProxy` of the Synapse operator serves an Ingress with a certificate
from cert-manager, and picks up a renewal without a restart. Needs Synapse
operator 0.2.0 (not released yet) and Synapse 0.8.8 or later.
- [TLS keys in an HSM](./use-cases/hsm-tls-keys/): serve certificates whose
private keys live in an HSM or other PKCS#11 token, beside a software key,
with the PIN in a file. The demo runs SoftHSM in docker. Needs Synapse 0.8.9
or later.

### Being updated

Expand Down
25 changes: 24 additions & 1 deletion scripts/check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,17 @@ fi

failed=$orphans
skipped=0

# make_test_pin: make a 0600 test PIN file at "$pin_dir/pin", once per run;
# it is removed on exit. The binary checks only the file, never a token.
pin_dir=
make_test_pin() {
[ -n "$pin_dir" ] && return 0
pin_dir=$(mktemp -d) || return 1
trap 'rm -rf -- "$pin_dir"' EXIT
(umask 077 && printf '1234\n' >"$pin_dir/pin")
}

for dir in "${sets[@]}"; do
args=(--check-config --config config.yaml)
[ -f "$dir/upstreams.yaml" ] && args+=(--upstream-conf upstreams.yaml)
Expand All @@ -106,7 +117,19 @@ for dir in "${sets[@]}"; do
"$dir/make-certs.sh" >/dev/null 2>&1 || { echo "FAIL $dir (make-certs.sh failed)"; failed=$((failed + 1)); continue; }
fi

out=$(cd "$dir" && "$bin" "${args[@]}" 2>&1)
# A set whose hsm block names a pin_file names a path that exists only where
# it is deployed; it gets the test PIN instead. No other set sees a PIN env,
# so a caller's PROXY_HSM_PIN_FILE cannot change a result. Limit: the binary
# does not require pin_file, so a set that omits it passes here and fails
# only when a key loads; every set MUST name one.
env_args=(-u PROXY_HSM_PIN_FILE -u AX_PROXY_HSM_PIN_FILE)
if grep -Eq '^[[:space:]]+hsm:' "$dir/config.yaml" &&
grep -Eq '^[[:space:]]+pin_file:' "$dir/config.yaml"; then
make_test_pin || { echo "FAIL $dir (cannot make a test PIN file)"; failed=$((failed + 1)); continue; }
env_args+=("PROXY_HSM_PIN_FILE=$pin_dir/pin")
fi

out=$(cd "$dir" && env "${env_args[@]}" "$bin" "${args[@]}" 2>&1)
rc=$?

# Warnings that fail the check (all but the absent-rules-file notice).
Expand Down
10 changes: 10 additions & 0 deletions scripts/fixtures/hsm-pin/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Control fixture: an HSM block whose PIN file does not exist here. check.sh
# MUST pass it by pointing PROXY_HSM_PIN_FILE at a test PIN file.
mode: agent
network:
iface: lo
proxy:
hsm:
modules:
- /usr/lib/softhsm/libsofthsm2.so
pin_file: /nonexistent/hsm/pin
10 changes: 10 additions & 0 deletions scripts/test-check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
# typo in upstreams.yaml / security_rules.yaml -> must fail
# orphan upstreams.yaml (no config.yaml beside it) -> must fail
# relative SYNAPSE_BIN -> must still work
# HSM set (hsm-pin) -> fails without a PIN file, passes through check.sh;
# a caller's PROXY_HSM_PIN_FILE does not reach a set without hsm
# ML keys (ml-keys, ml-keys-typo, ml-inner-typo) -> depends on the build,
# which this script detects: a default build skips ml-keys, fails
# ml-keys-typo and fails ml-keys under SYNAPSE_REQUIRE_ML=1; a classifier
Expand Down Expand Up @@ -81,6 +83,14 @@ expect fail "typo in upstreams.yaml fails" "upstreamz" "$check" "$fx/typo-upstre
expect fail "typo in security_rules.yaml fails" "ips" "$check" "$fx/typo-rules"
expect fail "orphan upstreams.yaml fails" "lonely" "$check" "$fx/orphan-root"

# An HSM set names a PIN file that exists only where it is deployed. check.sh
# hands it a test PIN through PROXY_HSM_PIN_FILE; without that it fails.
expect fail "HSM set fails without a test PIN" "proxy.hsm.pin_file" \
bash -c 'cd "$1" && env -u PROXY_HSM_PIN_FILE -u AX_PROXY_HSM_PIN_FILE "$2" --check-config --config config.yaml' _ "$fx/hsm-pin" "$bin"
expect pass "HSM set passes with check.sh's test PIN" "ok " "$check" "$fx/hsm-pin"
expect pass "a caller's PIN env does not reach a set without hsm" "ok " \
env PROXY_HSM_PIN_FILE=/nonexistent/pin "$check" "$fx/valid"

# A relative SYNAPSE_BIN must work: the check runs from each set's directory.
abs_bin=$(command -v "${SYNAPSE_BIN:-synapse}" 2>/dev/null || true)
if [ -n "$abs_bin" ]; then
Expand Down
1 change: 1 addition & 0 deletions use-cases/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ closest to what you want and copy it. Every set uses placeholder values
| [`tcp-mss`](./tcp-mss/) | proxy | no | none: the demo listens on port 8080 | Cap the MSS of the connections a listener accepts; needs Synapse 0.8.9 or later |
| [`edge-headers`](./edge-headers/) | proxy | no | none: the demo listens on ports 8080 and 8443 | `X-Forwarded-For`, `X-Forwarded-Proto`, `Via`, a request ID and HSTS; needs Synapse 0.8.9 or later |
| [`header-rules`](./header-rules/) | proxy | no | none: the demo listens on port 8080 | Add and remove request and response headers, with a script that checks every rule |
| [`hsm-tls-keys`](./hsm-tls-keys/) | proxy | no | none: the demo listens on ports 8085 and 8443 | TLS private keys in an HSM over PKCS#11 (RSA and EC), served beside a software key, with the PIN in a file; the demo uses SoftHSM in docker; needs Synapse 0.8.9 or later |
| [`kubernetes-cert-manager`](./kubernetes-cert-manager/) | proxy | no | a privileged proxy pod, Kubernetes cluster | A `SynapseProxy` of the Synapse operator serving an Ingress with a certificate from cert-manager, and the proxy picking up a renewed certificate without a restart; needs Synapse operator 0.2.0 (not released yet) and Synapse 0.8.8 or later |

"Privileges" lists what the set's own config needs; the installation guide
Expand Down
21 changes: 21 additions & 0 deletions use-cases/hsm-tls-keys/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Two images from one file: `token` provisions a SoftHSM token, `synapse` is the
# Synapse image with the SoftHSM module added. A real HSM needs neither: you
# install your vendor's PKCS#11 module instead.
ARG SYNAPSE_IMAGE=registry.gen0sec.com/gen0sec/synapse:0.8.9

FROM debian:13 AS token
RUN apt-get update \
&& apt-get install -y --no-install-recommends softhsm2 opensc openssl \
&& rm -rf /var/lib/apt/lists/*
ENV SOFTHSM2_CONF=/etc/synapse/softhsm2.conf

FROM debian:13 AS softhsm
RUN apt-get update \
&& apt-get install -y --no-install-recommends softhsm2 \
&& rm -rf /var/lib/apt/lists/*

# The Synapse image has no shell and no package manager, so the module is
# copied in. Its libraries (libcrypto, libstdc++, libz, libzstd) are already there.
FROM ${SYNAPSE_IMAGE} AS synapse
COPY --from=softhsm /usr/lib/softhsm/libsofthsm2.so /usr/lib/softhsm/libsofthsm2.so
ENV SOFTHSM2_CONF=/etc/synapse/softhsm2.conf
177 changes: 177 additions & 0 deletions use-cases/hsm-tls-keys/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# TLS private keys in an HSM

Keep the private keys of your TLS certificates in a hardware security module
(HSM), or any other PKCS#11 token, and have Synapse sign handshakes with them.
The key never leaves the device. **Needs Synapse 0.8.9 or later.**
Earlier releases cannot use a `pkcs11:` key.

```yaml
proxy:
certificates: "/certs"
default_certificate: "www.example.com"
hsm:
modules:
- /usr/lib/softhsm/libsofthsm2.so
pin_file: /hsm/pin
retry_interval_secs: 30
on_failure: fail
```

```yaml
hosts:
www.example.com:
tls:
terminate:
cert: www.example.com
```

The certificates stay on disk. Beside `www.example.com.crt` sits
`www.example.com.key`, and its one line says where the key is:

```
pkcs11:token=synapse;object=www;type=private
```

## Things to know

- A `.key` file whose first line is a `pkcs11:` URI is an HSM key. A PEM key in
a `.key` file is a software key, as before. Both kinds can sit in one
directory, as in the demo (`static.example.com`).
- `cert:` in `upstreams.yaml` is the certificate's **name**, the file stem in
`proxy.certificates`, never a path. There is no `key:` under `terminate`: the
key is found beside the certificate.
- The URI MUST NOT carry the PIN. `pin-value` and `pin-source` are rejected.
The PIN is in `proxy.hsm.pin_file`: a regular, non-empty file, owned by the
service user or root, mode `0600`. Synapse refuses the file otherwise, and
its errors name the path, never the content. With systemd, hand the file over
with `LoadCredential=` and point `pin_file` at
`/run/credentials/<unit>/<name>`. `PROXY_HSM_PIN_FILE` overrides the key.
- `modules` is tried in order, and the first that loads and yields the key
wins. List a second module for failover.
- Synapse reaches the token through the OpenSSL `pkcs11` provider. `provider_dir`
is the directory of its `pkcs11.so`; unset, the usual distribution
directories are probed. On Debian and Ubuntu it is the `pkcs11-provider`
package, which the deb and rpm packages suggest. A container image that ships
it needs nothing more than the vendor's PKCS#11 module.
- A key in the HSM is never read from a file: there is no software fallback.
- `retry_interval_secs` is how often, in seconds, every HSM key signs a test
message. When one cannot, Synapse reloads the certificates through `modules`,
so a recovered HSM is picked up within one interval. `0` turns the probe off.
- `on_failure` is what a host gets when its HSM key cannot be loaded. `fail`
(the default) refuses the TLS handshake for its names. `fallback` serves the
default certificate and logs a warning. During an outage a reload keeps the
last working context until its certificate expires, in both modes.
- The `hsm` block is read at start-up. Changing `modules`, `pin_file` or
`retry_interval_secs` needs a restart. A replaced PIN file is picked up at
the next certificate load.
- The built-in ACME client makes software keys. For a certificate on an HSM
key, make the CSR on the device and have certbot issue from it with
`certbot certonly --csr`. This set does not build that.

## Run

The demo uses SoftHSM, a software PKCS#11 token, so no hardware is needed.
Docker and Compose v2 are needed.

```sh
cd use-cases/hsm-tls-keys
docker compose up -d --build
docker compose run --rm client
```

Or all of it, with the log check, in one go: `./demo.sh`.

What runs:

- `token` (from `Dockerfile`, target `token`) runs `make-token.sh` once: it
initialises a SoftHSM token named `synapse` with a random PIN, puts an RSA
key (`www`) and an EC P-256 key (`api`) on it, and writes a certificate and a
`.key` file with the URI for each. It also writes a plain software key and
certificate (`static`), and the PIN file with mode `0600`.
- `synapse` is the Synapse image plus SoftHSM's module, built from
`Dockerfile`, target `synapse`. The Synapse image has no shell and no
package manager, so `libsofthsm2.so` is copied in from a Debian stage. With a
real HSM you install your vendor's module instead.
- `client` connects to each host with `openssl s_client`, over TLS 1.2 and
TLS 1.3, and sees only the certificates, not the token or the PIN.

`docker-compose.yml` builds on `SYNAPSE_IMAGE`; set it to use a build of your
own. The host maps ports 8085 (HTTP) and 8443 (HTTPS).

### What it prints

```
== www.example.com: key line in www.example.com.key
pkcs11:token=synapse;object=www;type=private
tls1_2: TLSv1.2, rsaEncryption, signature RSA-PSS, verification OK
tls1_3: TLSv1.3, rsaEncryption, signature RSA-PSS, verification OK
request: Host: www.example.com
== api.example.com: key line in api.example.com.key
pkcs11:token=synapse;object=api;type=private
tls1_2: TLSv1.2, id-ecPublicKey, signature ECDSA, verification OK
tls1_3: TLSv1.3, id-ecPublicKey, signature ECDSA, verification OK
request: Host: api.example.com
== static.example.com: key line in static.example.com.key
-----BEGIN PRIVATE KEY-----
tls1_2: TLSv1.2, id-ecPublicKey, signature ECDSA, verification OK
tls1_3: TLSv1.3, id-ecPublicKey, signature ECDSA, verification OK
request: Host: static.example.com
== no SNI: the default certificate
subject=CN=www.example.com
```

The two HSM hosts have no private key on disk, only the URI, so every
handshake for them was signed by the token. `./demo.sh` then looks for the PIN
in the logs of all services and finds none.

To start over, remove the volumes:

```sh
docker compose down -v
```

### What goes wrong

- A `pkcs11:` key with no `proxy.hsm` block is an error at load.
- A PIN file that is group or world readable, empty, or not a regular file is
refused, and the error names the rule that failed.
- With the token unreachable, `on_failure: fail` refuses the handshake with
`unrecognized_name` for the names of that certificate. The software host is
unaffected.

## For production

- **The demo imports its keys.** `make-token.sh` makes each key in software and
imports it with `softhsm2-util --import`, so for a moment a copy of the
private key is on disk. That is a shortcut for the demo. A real HSM makes the
key on the device, non-extractable, and signs the certificate request there
(`pkcs11-tool --keypairgen`, or the vendor's tool). Only the certificate
comes out.
- Replace SoftHSM with your vendor's module in `proxy.hsm.modules`, and use a
certificate from your CA.
- Keep the PIN file out of the configuration directory and out of version
control, mode `0600`, and hand it to the service with `LoadCredential=`.
- **The demo passes the PINs on the command line.** `make-token.sh` gives
`softhsm2-util` and `pkcs11-tool` the PIN and SO PIN as arguments, which
other processes on the host can read. Set up a real token with the vendor's
tool, typing the PINs at its prompt.
- Use your own host names for the `hosts:` keys, for `cert:` and for the
certificate file names.
- Set `provider_dir` if the `pkcs11.so` of the provider is not in a
distribution directory.

## Not checked here

The set was run against SoftHSM only, with RSA and EC keys over TLS 1.2 and
TLS 1.3, using a build of Synapse that has HSM keys. It was not run against a
hardware HSM, nor against a published image.

## Files

- `config.yaml`, `upstreams.yaml`: the Synapse set.
- `softhsm2.conf`: where SoftHSM keeps its token. Not needed with a real HSM.
- `docker-compose.yml`, `Dockerfile`: the token provisioner, Synapse with the
SoftHSM module, a test back-end and the client.
- `make-token.sh`: makes the token, keys, certificates and PIN file.
- `client.sh`: what the `client` service prints.
- `demo.sh`: the demo end to end, with the check that the PIN is in no log.
28 changes: 28 additions & 0 deletions use-cases/hsm-tls-keys/client.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/bin/sh
# Runs in the client container: what Synapse serves for each host, over
# TLS 1.2 and TLS 1.3. The certificates are self-signed, so each host's own
# certificate file is the trust anchor.
get() { printf 'GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n' "$1"; }
fail=0

for host in www.example.com api.example.com static.example.com; do
echo "== $host: key line in $host.key"
head -1 "/certs/$host.key" | cut -c1-60
for v in tls1_2 tls1_3; do
out=$(openssl s_client -connect "$host:443" -servername "$host" -"$v" \
-CAfile "/certs/$host.crt" -verify_hostname "$host" </dev/null 2>&1)
proto=$(echo "$out" | sed -n 's/^New, \(TLSv[0-9.]*\),.*/\1/p' | head -1)
sig=$(echo "$out" | sed -n 's/^Peer signature type: *//p' | head -1)
kind=$(echo "$out" | openssl x509 -noout -text 2>/dev/null | sed -n 's/^ *Public Key Algorithm: *//p')
ver=$(echo "$out" | sed -n 's/^Verification: *//p' | head -1)
echo " $v: ${proto:-no handshake}, $kind, signature ${sig:-?}, verification ${ver:-?}"
[ "$ver" = OK ] && [ -n "$proto" ] || fail=1
done
echo " request: $(get "$host" | openssl s_client -quiet -connect "$host:443" \
-servername "$host" -CAfile "/certs/$host.crt" 2>/dev/null | grep -m1 '^Host:')"
done

echo "== no SNI: the default certificate"
openssl s_client -connect www.example.com:443 </dev/null 2>/dev/null \
| openssl x509 -noout -subject
exit $fail
55 changes: 55 additions & 0 deletions use-cases/hsm-tls-keys/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Proxy mode, no firewall or capture, so the container needs no privileges.
mode: proxy

firewall:
mode: none
capture:
enabled: false

proxy:
listeners:
- { name: http, address: "0.0.0.0:80", mode: http }
- { name: https, address: "0.0.0.0:443", mode: tls }
upstream:
conf: "/etc/synapse/upstreams.yaml"

# Certificates stay on disk. Each <name>.crt has a <name>.key beside it. A
# .key file whose first line is a pkcs11: URI is a key in the HSM; a PEM .key
# file is a software key. Both can sit in the same directory:
#
# www.example.com.crt certificate
# www.example.com.key pkcs11:token=synapse;object=www;type=private
# api.example.com.crt
# api.example.com.key pkcs11:token=synapse;object=api;type=private
# static.example.com.crt
# static.example.com.key an ordinary PEM private key
#
# The URI MUST NOT carry the PIN: pin-value and pin-source are rejected.
certificates: "/certs"

# Served to a client that sends no SNI, or a name no certificate covers.
default_certificate: "www.example.com"

hsm:
# PKCS#11 modules, tried in order; list a second one for failover. This is
# SoftHSM, a software token for demos. Use your vendor's module.
modules:
- /usr/lib/softhsm/libsofthsm2.so
# The token PIN. A regular, non-empty file owned by the service user or
# root, mode 0600. With systemd, hand it over with LoadCredential= and
# point this at /run/credentials/<unit>/<name>. PROXY_HSM_PIN_FILE
# overrides it.
pin_file: /hsm/pin
# How often, in seconds, every HSM key signs a test message. A failure
# reloads the certificates through `modules`, so a recovered HSM is picked
# up within one interval. 0 turns the probe off.
retry_interval_secs: 30
# What a host whose HSM key cannot be loaded gets:
# fail the TLS handshake for its names is refused (default)
# fallback the default certificate is served, with a warning
# During an outage a reload keeps serving the last working context until
# its certificate expires, in both modes.
on_failure: fail

logging:
level: info
16 changes: 16 additions & 0 deletions use-cases/hsm-tls-keys/demo.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/bin/sh
# The whole demo, from the host: start, check each host, and check that the
# PIN reached no log. Needs Docker with Compose v2. Leaves the stack running.
set -eu
cd "$(dirname "$0")"

docker compose up -d --build
docker compose run --rm client

pin=$(docker compose run --rm --no-deps -T --entrypoint cat token /hsm/pin)
[ -n "$pin" ] || { echo "no PIN read"; exit 1; }
if docker compose logs --no-color 2>&1 | grep -qF "$pin"; then
echo "FAIL: the PIN appears in a log"
exit 1
fi
echo "== the PIN appears in no log"
Loading