Protect private key files on disk
A key is only as safe as the worst place it was ever echoed. This skill keeps key material in 0600 files or encrypted keystores and injects it through the process environment, never through a command line that lands in shell history or ps.
Procedure
- Set a restrictive umask before creating key material so nothing is world-readable by accident:
umask 077 - Create the key file at mode 600 and confirm it:
install -m 600 /dev/null ~/.keys/deployer.key - Prefer an encrypted keystore over a raw hex file on any shared machine. Import interactively so the key never appears in argv:
cast wallet import deployer --interactiveKeystores land in~/.foundry/keystores/and decrypt only with your passphrase. - When a raw key is unavoidable, load it from the file into the environment, not onto a command line:
export DEPLOYER_KEY="$(tr -d '\n' < ~/.keys/deployer.key)"Read it in code, never as a flag:import os from eth_account import Account print(Account.from_key(os.environ["DEPLOYER_KEY"]).address) - Stop the shell recording the command that touches the secret:
set +o historyin bash, or prefix the line with a space and setHISTCONTROL=ignorespace. - Never pass a key as
--private-key 0x.... That writes it into~/.bash_historyand exposes it inps auxto every user on the host. Use--account deployeror--ledger. - Audit for leaks before you finish.
Pitfalls
- A single
set -xduring debugging dumps everyexportto stderr and into CI logs; keep it off in any script that loads keys. .envfiles get committed. Add.env,*.key, andkeystores/to.gitignorebefore the first commit, not after an incident.- Docker
ENVandARGpersist in image layers; pass secrets at runtime with--env-fileor a mounted secret. - macOS uses
stat -fand Linux usesstat -c; the permission check silently does nothing if you use the wrong one.
Verification
stat -f "%Lp %N" ~/.keys/*.key && grep -c "DEPLOYER_KEY=0x" ~/.zsh_history
# expect mode 600 on every key, and grep to print 0
Report the observed file mode and the zero-match leak scan, quoting the commands run.