ansible-gpg-vault/vault.sh

96 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
set -e -u
# Keyserver to use. You need to trust this keyserver that the uid is not spoofed when receiving keys
KEYSERVER=""
REPO_BASE_PATH="`dirname "$0"`/../ansible-gpg-vault-store"
# File in which the passphrase for the gpg vault is encrypted
VAULT_PASS_FILE="$REPO_BASE_PATH/vault_passphrase.gpg"
# File which contains a list of fingerprints to receive and encrypt the vault for
KEY_FILE="$REPO_BASE_PATH/gpg_ids.list"
VAULT_PASS_RAW_FILE="$REPO_BASE_PATH/vault_passphrase"
# Length of the generated passphrase
VAULT_PASS_LENGTH="128"
# Default action is vault decrypt
if [ $# -eq 0 ]; then
ACTION="decrypt"
else
ACTION="$1"
fi;
addUser() {
USER="$1"
echo "grep for user $USER"
grep "$USER" $KEY_FILE
echo "rc=$?"
if ! grep -q "$USER" $KEY_FILE; then
echo "$USER" >> $KEY_FILE
else
echo "WARNING: user '$USER' already in key file"
fi;
reencrypt
}
reencrypt() {
gpg2 --batch --use-agent --output "$VAULT_PASS_RAW_FILE" --decrypt "$VAULT_PASS_FILE"
rm -v $VAULT_PASS_FILE
CMD="gpg2 --batch --use-agent --armor --output $VAULT_PASS_FILE"
for ID in $(cat $KEY_FILE); do
CMD="$CMD --recipient $ID";
done
CMD="$CMD --encrypt $VAULT_PASS_RAW_FILE"
$($CMD)
RC=$?
rm -v $VAULT_PASS_RAW_FILE
return "$RC"
}
decrypt() {
if [[ ! -f "$VAULT_PASS_FILE" ]]; then
echo "ERROR: vault script not initialised"
exit -1;
fi;
gpg2 --batch --use-agent --decrypt $VAULT_PASS_FILE 2>/dev/null
}
case "$ACTION" in
"decrypt")
decrypt
;;
"reencrypt")
reencrypt
;;
"init")
mkdir $REPO_BASE_PATH
if [[ ! -e "$VAULT_PASS_RAW_FILE" ]] && [[ ! -s "$VAULT_PASS_FILE" ]]; then
dd if=/dev/random bs=1 count=$VAULT_PASS_LENGTH 2>/dev/null \
| base64 -w 0 | rev | cut -b 2- | rev \
> $VAULT_PASS_RAW_FILE
else
echo "WARNING: File not empty, not overwriting potential existing keyphrase"
exit -1;
fi;
touch $KEY_FILE
echo "Specify the inital user who may access the vault"
read -p "GPG user id: " GPG_USER
echo "$GPG_USER" >> $KEY_FILE
CMD="gpg2 --batch --use-agent --armor --output $VAULT_PASS_FILE --recipient $GPG_USER --encrypt $VAULT_PASS_RAW_FILE"
$($CMD)
rm -v $VAULT_PASS_RAW_FILE
;;
"add")
if [ $# -eq 2 ]; then
USER="$2"
else
read -p "GPG user id to add: " GPG_USER
fi;
addUser $USER
esac