Pass 7-Zip Passwords Securely from Env Vars

Using command-line flags to pass passwords directly into 7-Zip exposes credentials to system process logs, process monitoring utilities, and shell histories. This guide details how to securely pass password credentials stored in environment variables to 7-Zip on both Linux and Windows by piping values into standard input (stdin) using the bare -p switch.


The Security Risk of the -p Flag

Normally, 7-Zip allows passing a password inline:

7z a secure.7z /path/to/files/ -p"$MY_PASSWORD"

When evaluated, the shell expands the variable into the command string. Consequently, any unprivileged user running ps aux on Linux or inspecting Task Manager and process creation events (Event ID 4688) on Windows can read the plaintext password.

The Secure Approach: Standard Input (stdin)

When you specify the -p switch without appending a password, 7-Zip prompts for the credential via standard input instead of accepting it as a command-line parameter. By pairing this behavior with built-in shell piping, the secret never enters the process command-line arguments.


Implementation on Linux and macOS (Bash/Zsh)

Use the shell built-in printf command to pipe the environment variable directly to 7-Zip's input stream. Because printf is a shell built-in rather than an external binary, it does not spawn an external process that exposes arguments in the process tree.

Archiving Files

export ARCHIVE_PASS="YourSuperSecretPassword"

printf '%s\n' "$ARCHIVE_PASS" | 7z a secure.7z /path/to/data/ -p

Extracting Files

printf '%s\n' "$ARCHIVE_PASS" | 7z x secure.7z -p

Implementation on Windows

PowerShell

In PowerShell, stream the environment variable to 7z.exe through the pipeline:

$env:ARCHIVE_PASS = "YourSuperSecretPassword"

$env:ARCHIVE_PASS | & "C:\Program Files\7-Zip\7z.exe" a secure.7z C:\path\to\data -p

For extraction:

$env:ARCHIVE_PASS | & "C:\Program Files\7-Zip\7z.exe" x secure.7z -p

Command Prompt (CMD)

In standard Windows batch scripts or CMD sessions, use the internal echo command without a space before the pipe operator:

set ARCHIVE_PASS=YourSuperSecretPassword

echo %ARCHIVE_PASS%| "C:\Program Files\7-Zip\7z.exe" a secure.7z C:\path\to\data -p

Note: Avoid adding a space between %ARCHIVE_PASS% and |, as CMD will append that space to the password string.


Additional Security Precautions

  1. Unset Credentials After Execution: Clear the variable from memory immediately after the compression or extraction finishes:
    • Linux: unset ARCHIVE_PASS
    • PowerShell: Remove-Item env:ARCHIVE_PASS
    • CMD: set ARCHIVE_PASS=
  2. Prevent History Logging: If defining the environment variable interactively in Bash, prefix the command with a leading space (with HISTCONTROL=ignorespace configured) to keep the password out of ~/.bash_history.