VPS Secrets Management: Storing API Keys Without Leaks
VPS secrets management in practice: where API keys and passwords leak on Linux, and how systemd credentials, sops and file permissions actually help.
Most secrets on a VPS don't leak because someone broke your encryption. They leak through shell history, process arguments, a .env file committed to git, or a backup that copied everything. Good VPS secrets management means closing those everyday leak paths first. Then you use tools like systemd credentials or sops to keep each API key, database password and token readable only by the service that needs it.
This guide covers where secrets actually leak on a Linux server, the main options for storing them, how to check your setup, and what no method on a single server can protect against.
Start With a Realistic Threat Model
Before choosing a tool, be clear about who you are defending against. On a typical self-managed VPS there are four realistic threats:
- Accidental exposure. A secret ends up in a public repo, a pasted log, a screenshot or an unencrypted backup. This is by far the most common.
- A compromised application. An attacker gets code execution as your web app's user and reads whatever that user can read.
- A compromised root account. Once someone has root, they can read every file, every process's memory and every decrypted credential. Secret storage on the same machine stops helping at this point. Your options shrink to limiting what each key can do and rotating fast.
- The infrastructure layer. Any VPS host has hypervisor-level access to your disk and RAM. Paying anonymously changes what the provider knows about you, not what it can technically access on the machine. We break that down in what your VPS provider can actually see.
The practical goal is to fully solve threat 1, contain threat 2, and limit the damage from 3 and 4 by scoping and rotating keys.
Where Secrets Actually Leak on a Linux Server
Command-line arguments
On Linux, any local user can see every process's full command line by default, through /proc/<pid>/cmdline or simply ps aux. So a command like this exposes the password to every account on the box for as long as it runs:
mysql -u app -p'SuperSecret123' appdb
Use option files instead. For MySQL/MariaDB, put the credentials in ~/.my.cnf with mode 0600. For curl, read headers from a file with curl -H @headers.txt (supported since curl 7.55). Most well-designed CLIs offer a file or stdin alternative to passing a password as an argument.
Shell history
Anything you type with a secret inline lands in ~/.bash_history. Two habits help:
# Prompt for the secret without echoing it or writing it to history
read -rs DB_PASS && export DB_PASS
# In ~/.bashrc: commands starting with a space are not saved
HISTCONTROL=ignoreboth
If a secret already made it into history, remove that line from the file and rotate the secret. Editing history doesn't undo copies already captured in backups.
Environment variables
Environment variables are better than arguments but weaker than most people assume. /proc/<pid>/environ is readable by the process owner and root. Child processes inherit the whole environment. And many frameworks dump environment variables into error pages or debug logs. docker inspect also shows a container's environment in plain text to anyone who can talk to the Docker socket.
Environment variables are acceptable for low-value configuration. For real secrets, prefer files that are loaded at runtime. Many official container images support a *_FILE convention for this, for example POSTGRES_PASSWORD_FILE.
Git, backups and core dumps
- Git: a
.envfile committed once stays in history even after you delete it. Add secret files to.gitignorebefore the first commit, and scan old repositories with a tool such as gitleaks. - Backups: a full-filesystem backup copies
/etc, app directories and home folders, secrets included. Encrypt the backup repository and keep its password somewhere other than the server it protects. Our restic and Borg backup guide covers key handling in detail. - Core dumps: a crashing process can write its memory, including decrypted keys, to disk. For sensitive services, set
LimitCORE=0in the systemd unit.
Option 1: Plain Files With Correct Ownership
The simplest approach is still a solid one. Store each secret in a file that only the service account can read:
sudo install -d -m 0750 -o root -g myapp /etc/myapp
sudo install -m 0640 -o root -g myapp /dev/null /etc/myapp/db_password
sudoedit /etc/myapp/db_password
With this layout, root owns the file, the myapp group can read it, and nobody else can. sudoedit keeps the secret out of your command line and shell history.
The weakness is that the secret sits in plaintext on disk. Any backup, disk image or compromise of the myapp user exposes it.
Option 2: systemd Credentials
systemd can hand secrets to a service at startup without the service needing permission to read the source file. This feature arrived in systemd 247. Encrypted credentials (LoadCredentialEncrypted=) require systemd 250 or newer. Debian 12, Ubuntu 24.04 and AlmaLinux 10 qualify; Ubuntu 22.04 ships 249. Check your version with systemctl --version.
To encrypt a credential:
sudo mkdir -p /etc/credstore.encrypted
sudo systemd-ask-password -n "DB password:" \
| sudo systemd-creds encrypt --name=db_password - /etc/credstore.encrypted/db_password.cred
Then reference it in the unit file:
[Service]
User=myapp
LoadCredentialEncrypted=db_password:/etc/credstore.encrypted/db_password.cred
LimitCORE=0
At startup, systemd decrypts the file and places it at $CREDENTIALS_DIRECTORY/db_password, usually under /run/credentials/myapp.service/. That location is readable only by the service and lives in memory rather than on disk. Your application reads the secret from that path.
What the encryption actually protects. Most VPSes have no TPM chip, so systemd-creds falls back to a host key stored at /var/lib/systemd/credential.secret. This means:
- A
.credfile copied off the server on its own, through a leaked repo or a partial backup, is useless without that host key. - Root on the server can still decrypt everything, because the key sits on the same disk.
- A full-disk snapshot contains both the encrypted files and the key.
It is a real improvement over plaintext files. It is not protection against someone who controls the machine. systemd credentials pair well with the sandboxing options covered in our systemd service hardening guide.
Option 3: sops + age for Secrets You Keep in Git
If you manage configuration in a repository, sops lets you commit encrypted secret files safely. With YAML or JSON, sops encrypts only the values, so the keys stay readable and diffs stay meaningful. age is a modern, small encryption tool that sops can use for the actual encryption.
# Generate a key pair; keep the private key off shared machines
age-keygen -o ~/.config/sops/age/keys.txt
# Encrypt for that public key (age1...)
sops --encrypt --age age1yourpublickey... secrets.yaml > secrets.enc.yaml
# Decrypt at deploy time
sops --decrypt secrets.enc.yaml > /etc/myapp/secrets.yaml
You can encrypt for several recipients at once, such as your laptop and the server, so either can decrypt.
The trade-off: the server still needs a private key to decrypt at deploy time, so this mainly protects the repository and your collaborators' copies, not the running server. If you deploy from your own machine and push only the decrypted files, the server never holds the age key at all.
Docker and Compose Secrets
In plain Docker Compose (without Swarm), secrets: mounts a file from the host into the container at /run/secrets/<name>:
services:
db:
image: postgres:17
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txt
This keeps the password out of docker inspect and the environment. It is still a bind-mounted plaintext file on the host, so apply the same file permissions as in Option 1. Also remember that access to the Docker socket is effectively root.
Reduce What a Stolen Key Can Do
Storage only goes so far. Assume any secret on an internet-facing server may eventually leak, and limit the damage in advance:
- Use one key per service. Never share credentials between apps, so one compromise doesn't unlock everything.
- Scope keys tightly. Exchange API keys should have withdrawals disabled and an IP allowlist pointing at your VPS's dedicated IPv4. See the trading bot guide for details. Database users should get only the grants they need.
- Write down a rotation procedure before you need it: where each key lives, how to revoke it, and what to restart. After a suspected compromise, rotation matters more than forensics. Our incident response guide covers the wider rebuild process.
Verify Your Setup
Run a few checks after any change:
# Any secrets visible in process arguments?
ps -eo user,args | grep -iE 'pass|token|secret|key=' | grep -v grep
# What environment does the service actually have? (as root)
sudo cat /proc/$(pgrep -f myapp | head -1)/environ | tr '\0' '\n'
# Credential is present and private to the unit
sudo ls -l /run/credentials/myapp.service/
# Secret files readable by anyone else?
sudo find /etc /srv /opt -type f -perm -o+r -iname '*secret*' 2>/dev/null
Optionally, mounting /proc with hidepid=invisible stops users from seeing each other's processes. Test it carefully first: some setups involving polkit or monitoring agents break with it.
What This Can't Fix
No storage method protects a running secret from root on the same machine or from the infrastructure underneath it. A service must hold its secret in memory to use it. Encrypting at rest, restricting files and isolating services reduce accidental exposure and contain an application-level compromise. Scoping, rotation and off-server backups of your keys cover the rest.
If you're setting up a fresh server to apply this, an IronBalkans VPS gives you full-root KVM in Romania, paid in Monero, Bitcoin or Litecoin with no email or ID at signup. The same principles apply on any Linux host.
