brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: systemd-creds encrypt keeps a service secret encrypted on disk

Systemd
~/tips/tip-systemd-creds-encrypt-loadcredentialencrypted

printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass - dbpass.cred

Encrypts a secret into a file that only systemd can decrypt for a named credential.

A plain secret file on disk bothers me more than it should, even with strict permissions. systemd can store it encrypted and decrypt it only when the service starts.

printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass - dbpass.cred

The syntax is systemd-creds encrypt input output, and - means standard input or output. --name= puts the credential name inside the encrypted data, so a file cannot be renamed and reused for another purpose. The result can be read back like this:

sudo systemd-creds decrypt --name=dbpass dbpass.cred -

That prints the secret. With --name=other it refuses with Embedded credential name 'dbpass' does not match filename 'other', refusing.

In a unit, LoadCredentialEncrypted=dbpass:/etc/credstore.encrypted/dbpass.cred decrypts it for the service. Per systemd.exec(5) it works like LoadCredential=, but the data is decrypted first, and /etc/credstore.encrypted/ is one of the folders searched. The service reads the result as a file in $CREDENTIALS_DIRECTORY.

The key is chosen with --with-key=: host, tpm2 or host+tpm2. The default auto uses TPM2 if there is a device, otherwise the host key when /var/lib/systemd/ is on persistent media.

The caveat comes from the manual: the host key lives in /var/lib/systemd/credential.secret, readable only by root, and anyone with enough privileges on the file system can decrypt. systemd can also warn that the secret file is not located on encrypted media. Encrypting protects a copied file, not a compromised root.

Further reading: systemd-creds, systemd.exec: LoadCredentialEncrypted=

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] systemd-analyze timespan 1h30min sudo bootctl set-oneshot ID All Systemd tips (88) All topics

Link