Keepassxc
Keepass¶
CLI¶
Create Database:
>>> keepassxc-cli db-create ~/test.kdbx -p
Enter password to encrypt database (optional):
Repeat password:
Successfully created new database.
Add to the database:
#Add a new folder to the database
>>> keepassxc-cli mkdir ~/test.kdbx production
Enter password to unlock /home/generalzero/test.kdbx:
Successfully added group production.
#Add a new entry into the database
>>> keepassxc-cli add --generate ~/test.kdbx "production/test"
Enter password to unlock /home/generalzero/test.kdbx:
Successfully added entry test.
Show Entry:
>>> keepassxc-cli show ~/test.kdbx "production/test" -s
Enter password to unlock /home/generalzero/test.kdbx:
Title: test
UserName:
Password: JFc929e7teFEgXZfXef5YcLrPbPxfTg5
URL:
Notes:
Uuid: {77118fc5-0353-4bd5-8319-0f8b0ea9f337}
Tags:
Script to set env from database¶
Script to use:
#!/bin/bash
#cat ~/kp-run.sh
# Default KeePass database path
KEEPASS_DB="$HOME/test.kdbx"
KEEPASS_CLI="keepassxc-cli"
# Prompt for KeePass password securely
read -s -p "Enter KeePass database password: " KEEPASS_PASS
echo ""
# Function to fetch secrets from KeePass
fetch_secret() {
local entry="$1"
local secret
# Using keepassxc-cli with password input via stdin
secret=$($KEEPASS_CLI show "$KEEPASS_DB" "$entry" -a password <<< "${KEEPASS_PASS}" 2>/dev/null)
# Check if the secret was found
if [[ -z "$secret" ]]; then
echo "Error: Could not find secret for '$entry'" >&2
return 1
fi
echo "$secret"
}
# Load secrets into environment variables
load_env_secrets() {
while IFS='=' read -r key value; do
if [[ "$value" =~ ^kp://(.+) ]]; then
secret_entry="${BASH_REMATCH[1]}"
secret_value=$(fetch_secret "$secret_entry")
export "$key"="$secret_value"
else
export "$key"="$value"
fi
done < <(env | grep -E '^[A-Z0-9_]+=kp://')
}
# Parse arguments for --env-file=<file> and --db=<file>
NEW_ARGS=()
for arg in "$@"; do
if [[ "$arg" == --env-file=* ]]; then
ENV_FILE="${arg#--env-file=}" # Extract filename after '='
if [[ -f "$ENV_FILE" ]]; then
export $(grep -v '^#' "$ENV_FILE" | xargs)
else
echo "Error: .env file '$ENV_FILE' not found!"
exit 1
fi
elif [[ "$arg" == --db=* ]]; then
KEEPASS_DB="${arg#--db=}" # Extract database path after '='
if [[ ! -f "$KEEPASS_DB" ]]; then
echo "Error: KeePass database '$KEEPASS_DB' not found!"
exit 1
fi
else
NEW_ARGS+=("$arg") # Add remaining arguments to NEW_ARGS
fi
done
# Replace env variables with KeePass secrets
load_env_secrets
# Ensure there is a command to execute
if [[ ${#NEW_ARGS[@]} -eq 0 ]]; then
echo "Error: No command provided to execute."
exit 1
fi
# Run the specified command with injected environment
exec "${NEW_ARGS[@]}"
Run example:
>>> cat .env
KEEPASS_TEST_OUTPUT="kp://production/test"
>>> ~/kp-run.sh --db=/home/generalzero/test.kdbx --env-file=".env" -- env G KEE
Enter KeePass database password:
KEEPASS_TEST_OUTPUT=JFc929e7teFEgXZfXef5YcLrPbPxfTg5