Course contentsShow
← Linux
Lesson 870 of 1,8198. User Management and Pluggable Authentication ModulesFree lesson

Encrypting Sensitive Environment Variables

You will protect environment variables containing secrets from being inspected by other users.

In this lesson, you will learn how to protect sensitive environment variables from being inspected by unauthorized users on your Linux system.

The Problem with Plaintext Variables

By default, environment variables are stored in plaintext within a process's memory space. On a multi-user system, any user with sufficient privileges—or even a user sharing the same group—can potentially inspect these values using tools like ps e or by examining the /proc/[pid]/environ file of a running process. If you store sensitive data like API keys, database credentials, or secret tokens in ~/.bashrc or ~/.profile, you are effectively exposing them to anyone who can peek at your process environment.

Securing Secrets with Memory-Only Encryption

To solve this, we shift away from static environment variables stored in plaintext files. Instead, we use a technique where the secret is stored in an encrypted state at rest and is only decrypted into memory within the process's runtime environment when needed.

One effective approach is to use a "vault" or a helper utility that reads an encrypted file and exports the secret directly into the memory of your application, rather than as a global system environment variable.

Consider a scenario where you use an encrypted file (secrets.gpg) and a small wrapper script:

# Decrypting into a temporary memory-backed variable
# This avoids writing the secret to a persistent environment config
SECRET=$(gpg --decrypt --quiet ~/secrets.gpg)
export API_KEY="$SECRET"
# Execute the application
./my_secure_app
# Unset immediately after execution
unset API_KEY

Minimizing the Attack Surface

Even with encryption, keep these security principles in mind:

  1. Never use .bashrc for secrets: Avoid placing variables in files that are globally readable or frequently backed up in plaintext.
  2. Short-lived variables: Use the unset command as soon as your application has initialized to clear the variable from your shell’s memory.
  3. Restrict /proc access: Ensure your system is configured to restrict access to /proc/[pid]/environ so that users cannot view the environment of processes they do not own.

By decoupling your configuration from your secrets, you prevent sensitive data from becoming a permanent, discoverable fixture of your shell environment.

Key Takeaway: Never store raw secrets in shell configuration files; instead, decrypt them into memory at runtime and unset them immediately after use to prevent unauthorized inspection via /proc.