Skip to content
Open
8 changes: 8 additions & 0 deletions changelog.d/6182-empty-tls-key-passphrase.security.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
- **An empty TLS key passphrase counts as none.** At the TLS key loaders (the API listener, MLLP,
the HTTP listener, DICOM, FTPS and SOAP), a `tls_key_password` or `MEFOR_API_TLS_KEY_PASSWORD`
set to the empty string is now treated as no passphrase. An encrypted key with it gets the
key-wrap refusal, which names the empty setting, rather than a raw OpenSSL error. A key wrapped
under an empty passphrase, which loaded before, is now refused: set the real passphrase, re-wrap
the key under a non-empty one, or supply it unencrypted. The Kubernetes example Secret now reads
the store key and passwords from files the operator writes, with `--from-file`, rather than
putting them on a `kubectl` command line. (`BACKLOG #6182`)
44 changes: 38 additions & 6 deletions docker/k8s/secret.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,53 @@
# cert/key from local files (never inline). Notes on the literals (kept OUT of the command so it is
# copy-paste-safe — every continued line ends in a backslash with NO trailing inline comment, so nothing
# is silently dropped):
# - api-tls-key-password: leave "" (or omit the flag) if the API key is unencrypted.
# - api-tls-key-password: omit the flag if the API key is unencrypted. An empty value counts as
# no passphrase, so it adds nothing.
# - store-password: REQUIRED ONLY for the HA manifest (external Postgres / SQL Server); omit it for
# the single-node SQLite statefulset.yaml.
# - tls-revocation-attested: your API revocation attestation (docs/SECURITY.md, API revocation gate).
# Both manifests require the key; without it the kubelet refuses the
# pod (CreateContainerConfigError, at the first container reading it). Set 1 only if your PKI
# enforces revocation.
# enforces revocation. It is not a secret, so it is the one --from-literal.
#
# The store key and the passwords go in through files you write first, never as --from-literal: a
# value on a command line is readable by other local users in the process list while kubectl runs,
# and stays in your shell history. Write the files in a private directory, with no trailing
# newline (--from-file keeps every byte, so a trailing newline would become part of the value),
# and delete them once the Secret exists. Run it in bash on Linux or macOS (start `bash` first if
# your shell is zsh, where read -p means something else), or in WSL on Windows from a directory in
# the Linux file system (for example under ~), not under /mnt: Git Bash's chmod and umask do not
# set Windows file permissions, and a Windows drive under /mnt may ignore them too, so the
# directory there would not be private. It runs in a subshell so the umask and the shell options
# end with it:
#
# (
# set -euo pipefail; umask 077; mkdir -p secrets; chmod 700 secrets
# messagefoundry gen-key | tr -d '\r\n' > secrets/store-encryption-key
# test -s secrets/store-encryption-key
# IFS= read -rs -p 'store password: ' v; echo; printf '%s' "$v" > secrets/store-password
# IFS= read -rs -p 'API key passphrase: ' v; echo; printf '%s' "$v" > secrets/api-tls-key-password
# )
#
# (IFS= read -rs keeps the value whole, off the screen and out of history; printf is a shell
# builtin, so the value never appears in a process's arguments; tr also strips a carriage return;
# pipefail and test -s stop on a gen-key that failed.) Skip the store-password line for the
# single-node manifest, and the passphrase line if the API key is unencrypted, and drop the
# matching --from-file flag and rm path below too.
#
# Before the files go, put a copy of the store key in your key escrow: once they are deleted the
# Secret would be its only copy, and losing the key loses every stored message encrypted under it.
# The files are deleted only if kubectl succeeds. If it fails, fix the cause and run it again, or
# delete the files and the secrets directory by hand.
#
# kubectl create secret generic mefor-secrets \
# --from-file=api.crt=tls/api.crt \
# --from-file=api.key=tls/api.key \
# --from-literal=store-encryption-key="$(messagefoundry gen-key)" \
# --from-literal=api-tls-key-password="" \
# --from-literal=store-password="..." \
# --from-literal=tls-revocation-attested="..."
# --from-file=store-encryption-key=secrets/store-encryption-key \
# --from-file=api-tls-key-password=secrets/api-tls-key-password \
# --from-file=store-password=secrets/store-password \
# --from-literal=tls-revocation-attested="..." \
# && rm -f secrets/store-encryption-key secrets/store-password secrets/api-tls-key-password
#
# The store key is base64 of 32 random bytes (mint with `messagefoundry gen-key`). The MLLP key must be
# UNENCRYPTED unless the MLLP() connection sets tls_key_password (env-sourced).
Expand Down
3 changes: 2 additions & 1 deletion docs/CLOUD-DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,8 @@ and the engine's at-rest encryption does not cover them ([`PHI.md`](PHI.md) §2,
*Residuals / gotchas* in [`docker/README.md`](../docker/README.md#residuals--gotchas).
3. **Create the Secret** ([`docker/k8s/secret.example.yaml`](../docker/k8s/secret.example.yaml)) with
`store-encryption-key`, `store-password`, `tls-revocation-attested`, and the API TLS cert/key (and
optional `api-tls-key-password`). Both manifests, `ha-postgres.yaml` and `statefulset.yaml`, read
optional `api-tls-key-password`). Load the store key and the passwords with `--from-file`, never
`--from-literal`; the example's header says why, and how to write those files. Both manifests, `ha-postgres.yaml` and `statefulset.yaml`, read
`MEFOR_TLS_REVOCATION_ATTESTED` from the `tls-revocation-attested` key, with no default and not
optional, so without it the kubelet refuses each pod with `CreateContainerConfigError`, at the
first container that reads it. The attestation is yours
Expand Down
9 changes: 8 additions & 1 deletion docs/CONNECTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4431,7 +4431,14 @@ scrypt passes at its Appendix C floor.
- PBKDF2 under its floor. **The common tools write 2048 iterations by default**: `openssl req`
without `-nodes`, `openssl genpkey -aes256`, and `cryptography`'s `BestAvailableEncryption`. A key
made any of those ways is refused until you re-wrap it;
- an encrypted key where the loader has no passphrase to give, before any library can prompt.
- an encrypted key where the loader has no passphrase to give, before any library can prompt. At
the TLS loaders an empty passphrase setting (`""`) counts as none, so an encrypted key with an
empty `tls_key_password` or `MEFOR_API_TLS_KEY_PASSWORD` is refused here too, including one
wrapped under an empty passphrase. The remedy is to set the setting to the key's passphrase, or
to re-wrap the key with the command below, giving a **non-empty** passphrase at its prompt, or to
supply the key unencrypted with the setting removed. This differs on purpose from the PKCS#12
rule further down, where an empty `MEFOR_PFX_PASSWORD` is a real empty passphrase: a TLS key's
passphrase setting is usually filled from a Secret or env var whose empty value means "none".

**Re-wrap a PEM or PKCS#8 key** at the floor, then point the setting at the new file:

Expand Down
46 changes: 39 additions & 7 deletions messagefoundry/keywrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,14 +1248,17 @@ def key_wrap_refusal(
setting: str,
unlock_setting: str | None,
passphrase_given: bool,
empty_passphrase: bool = False,
) -> str | None:
"""The refusal text for ``material``, or ``None`` when every key in it may be loaded.

``setting`` names where the key came from, for the message. ``unlock_setting`` names what
carries its passphrase, in the words an operator would use to set it, or is ``None`` for a
loader that takes no passphrase at all. ``passphrase_given`` says whether the loader is about to
pass one. The text holds no key bytes, passphrase or path, so a caller may raise it as its own
error type."""
pass one. ``empty_passphrase`` says the loader was given an empty one, which counts as none,
so the advice names the empty setting rather than only telling the operator to set it
(BACKLOG #6182). The text holds no key bytes, passphrase or path, so a caller may raise it as
its own error type."""
if _too_large(material):
return (
f"{setting}: the key file is over {_MAX_KEY_FILE_BYTES} bytes, too large to check its "
Expand All @@ -1271,29 +1274,47 @@ def key_wrap_refusal(
fix = _REENCODE
else:
fix = _REWRAP
if empty_passphrase:
fix = f"{fix}. {_empty_setting_note(unlock_setting)}"
return f"{setting}: the private key {problem}. It is refused. {fix}"
if encrypted and not passphrase_given:
fix = _DECRYPT if unlock_setting is None else f"Set {unlock_setting}"
if unlock_setting is None:
fix = _DECRYPT
elif empty_passphrase:
fix = _empty_setting_note(unlock_setting)
else:
fix = f"Set {unlock_setting}"
return (
f"{setting}: the private key is encrypted and no passphrase is configured for it. It "
f"is refused before any library can try to open it. {fix}"
)
return None


def _empty_setting_note(unlock_setting: str) -> str:
"""The advice for a key whose passphrase setting is set to ``""``, which counts as none."""
return (
f"{unlock_setting} is set but empty, and an empty passphrase counts as none: set it to the "
"key's passphrase, and wrap a key that has none, or one encrypted under an empty "
"passphrase, under a non-empty one"
)


def refuse_weak_key_wrap(
material: bytes,
*,
setting: str,
unlock_setting: str | None,
passphrase_given: bool,
empty_passphrase: bool = False,
) -> None:
"""Raise :class:`KeyWrapRefused` when :func:`key_wrap_refusal` refuses ``material``."""
reason = key_wrap_refusal(
material,
setting=setting,
unlock_setting=unlock_setting,
passphrase_given=passphrase_given,
empty_passphrase=empty_passphrase,
)
if reason is not None:
raise KeyWrapRefused(reason)
Expand All @@ -1305,6 +1326,7 @@ def refuse_weak_key_file(
setting: str,
unlock_setting: str | None,
passphrase_given: bool,
empty_passphrase: bool = False,
) -> None:
"""Read the key file at ``path`` and refuse it as :func:`refuse_weak_key_wrap` does.

Expand All @@ -1330,6 +1352,7 @@ def refuse_weak_key_file(
setting=setting,
unlock_setting=unlock_setting,
passphrase_given=passphrase_given,
empty_passphrase=empty_passphrase,
)


Expand All @@ -1341,6 +1364,7 @@ def refuse_weak_cert_chain_key(
key_setting: str,
unlock_setting: str | None,
passphrase_given: bool,
empty_passphrase: bool = False,
) -> None:
"""Check the key an ``ssl.SSLContext.load_cert_chain(certfile, keyfile, ...)`` call would load.

Expand All @@ -1351,6 +1375,7 @@ def refuse_weak_cert_chain_key(
setting=key_setting if keyfile else cert_setting,
unlock_setting=unlock_setting,
passphrase_given=passphrase_given,
empty_passphrase=empty_passphrase,
)


Expand All @@ -1373,17 +1398,24 @@ def load_checked_cert_chain(

The check and the load are one call, so a site cannot keep one and drop the other. OpenSSL
reads the file a second time, and a file swapped between the two reads is not caught by the
check; the empty-passphrase callback passed for ``password=None`` is what keeps a swapped-in
encrypted key off a terminal prompt then."""
check; the empty-passphrase callback, passed when ``password`` is ``None`` or empty, is what
keeps a swapped-in encrypted key off a terminal prompt then.

An empty ``password`` counts as none given (BACKLOG #6182): a Kubernetes Secret or an env var
set to ``""`` reads as "no passphrase". So an encrypted key with ``""`` gets the wrap check's
no-passphrase refusal rather than a raw OpenSSL error on a wrong passphrase. A key wrapped
under an empty passphrase, which OpenSSL would load with ``""``, is refused the same way: its
wrap protects nothing. Either refusal names the empty setting."""
refuse_weak_cert_chain_key(
certfile,
keyfile,
cert_setting=cert_setting,
key_setting=key_setting,
unlock_setting=unlock_setting,
passphrase_given=password is not None,
passphrase_given=bool(password),
empty_passphrase=password is not None and not password,
)
ctx.load_cert_chain(certfile, keyfile, password if password is not None else _no_passphrase)
ctx.load_cert_chain(certfile, keyfile, password or _no_passphrase)


def load_connection_cert_chain(
Expand Down
9 changes: 8 additions & 1 deletion tests/test_b532w3_k8s_attestation_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,12 @@ def test_the_example_secret_still_names_every_key() -> None:
if key in {"api.crt", "api.key"}:
assert f"--from-file={key}=" in text, key
continue
assert f"--from-literal={key}=" in text, key
if key == "tls-revocation-attested":
# Not a secret, so the one literal the example command keeps.
assert f"--from-literal={key}=" in text, key
else:
# BACKLOG #6182: a secret value on a command line sits in the process list and in
# shell history, so the example reads it from a file the operator writes.
assert f"--from-file={key}=" in text, key
assert f"--from-literal={key}=" not in text, key
assert f' # {key}: "REPLACE' in text, f"no commented REPLACE entry for {key}"
104 changes: 104 additions & 0 deletions tests/test_keywrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,110 @@ def test_an_encrypted_key_with_no_passphrase_never_reaches_openssl(
assert spy_load_cert_chain == []


@pytest.mark.parametrize("empty", ["", b""])
def test_an_empty_passphrase_counts_as_none_given(
tmp_path: Path, material: Material, empty: str | bytes, spy_load_cert_chain: list[object]
) -> None:
# BACKLOG #6182: a Secret or env var set to "" means no passphrase. Before the fix "" counted
# as given, so an encrypted key went past the refusal into OpenSSL.
combined = _write(tmp_path, "both.pem", material.cert_pem + material.wraps["approved"])
with pytest.raises(KeyWrapRefused, match="no passphrase is configured"):
keywrap.load_checked_cert_chain(
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER),
combined,
None,
empty,
cert_setting="cert",
key_setting="key",
unlock_setting="key password",
)
assert spy_load_cert_chain == []


def test_a_key_wrapped_under_an_empty_passphrase_is_refused_and_says_why(
tmp_path: Path, material: Material
) -> None:
# The one input whose outcome #6182 flips: OpenSSL loads this key with "", and before the fix
# so did load_checked_cert_chain. Its wrap protects nothing, so it is now refused, and the text
# says the setting is empty rather than only "Set it".
wrapped = pkcs8_pem(material.key, "", prf="sha256", iterations=600_000)
combined = _write(tmp_path, "both.pem", material.cert_pem + wrapped)
# Control: the fixture is a real encrypted key OpenSSL opens with the empty passphrase.
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain(combined, None, "")
with pytest.raises(KeyWrapRefused, match="no passphrase is configured") as caught:
keywrap.load_checked_cert_chain(
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER),
combined,
None,
"",
cert_setting="cert",
key_setting="key",
unlock_setting="key password",
)
assert "is set but empty" in str(caught.value)


def test_a_missing_passphrase_refusal_carries_no_empty_setting_note(
tmp_path: Path, material: Material, spy_load_cert_chain: list[object]
) -> None:
combined = _write(tmp_path, "both.pem", material.cert_pem + material.wraps["approved"])
with pytest.raises(KeyWrapRefused, match="no passphrase is configured") as caught:
keywrap.load_checked_cert_chain(
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER),
combined,
None,
None,
cert_setting="cert",
key_setting="key",
unlock_setting="key password",
)
assert "is set but empty" not in str(caught.value)


@pytest.mark.parametrize("site", sorted(_SSL_WITH_PASSPHRASE))
def test_an_ssl_loader_refuses_an_encrypted_key_with_an_empty_passphrase(
tmp_path: Path, material: Material, site: str, spy_load_cert_chain: list[object]
) -> None:
combined = _write(tmp_path, "both.pem", material.cert_pem + material.wraps["approved"])
with pytest.raises(KeyWrapRefused, match="no passphrase is configured") as caught:
_SSL_WITH_PASSPHRASE[site](combined, None, "")
assert spy_load_cert_chain == []
assert "is set but empty" in str(caught.value), site


def test_a_weak_wrap_with_an_empty_passphrase_names_the_empty_setting(
tmp_path: Path, material: Material, spy_load_cert_chain: list[object]
) -> None:
# Re-wrap advice alone would send the operator to a second refusal for the empty setting.
combined = _write(tmp_path, "both.pem", material.cert_pem + _legacy_pem(material.key))
with pytest.raises(KeyWrapRefused, match="legacy OpenSSL PEM encryption") as caught:
keywrap.load_checked_cert_chain(
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER),
combined,
None,
"",
cert_setting="cert",
key_setting="key",
unlock_setting="key password",
)
assert "key password is set but empty" in str(caught.value)
assert spy_load_cert_chain == []


@pytest.mark.parametrize("site", sorted(_SSL_WITH_PASSPHRASE))
def test_an_ssl_loader_still_loads_an_unencrypted_key_with_an_empty_passphrase(
tmp_path: Path, material: Material, site: str
) -> None:
plain = material.key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
cert = _write(tmp_path, "cert.pem", material.cert_pem)
key = _write(tmp_path, "key.pem", plain)
assert _SSL_WITH_PASSPHRASE[site](cert, key, "") is not None


@pytest.mark.parametrize("site", sorted(_SSL_WITHOUT_PASSPHRASE))
def test_a_passphrase_less_loader_refuses_a_weak_wrap(
tmp_path: Path, material: Material, site: str, spy_load_cert_chain: list[object]
Expand Down
Loading