Skip to content

Commit

Permalink
Allow setup-gpg.sh --import to receive, trust, and add to configure m…
Browse files Browse the repository at this point in the history
…ultiple public keys at once
  • Loading branch information
P-EB authored and speed47 committed Oct 27, 2023
1 parent 6d5255d commit 35d4841
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
32 changes: 18 additions & 14 deletions bin/admin/setup-gpg.sh
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ EOF

do_import()
{
local -a new_keys=()

rsync_conf="$BASTION_ETC_DIR/osh-encrypt-rsync.conf.d/50-gpg-admins-key.conf"
if [ -e "$rsync_conf" ]; then
if [ "$1" = "--overwrite" ]; then
Expand Down Expand Up @@ -121,28 +123,30 @@ do_import()
gpg --import
newkey=''
for key in $(gpg --with-colons --list-keys | grep ^pub: | awk -F: '{print $5}'); do
grep -qw "$key" "$keys_before" || newkey="$key"
grep -qw "$key" "$keys_before" && continue || newkey="$key"
echo "Found generated key with ID: $newkey"
fpr=$(gpg --with-colons --fingerprint --list-keys "$newkey" | awk -F: '/^fpr:/ {print $10 ; exit}')
if [ -z "$fpr" ]; then
echo "Couldn't find the fingerprint of the generated key $newkey, skipping" >&2
continue
fi
echo "Found generated key fingerprint: $fpr"
echo "Trusting this key..."
gpg --import-ownertrust <<< "$fpr:6:"
new_keys+=("${newkey}")
done
if [ -z "$newkey" ]; then
if [ "${#new_keys[@]}" -lt 1 ]; then
echo "Couldn't find which key you imported (did it exist already?), aborting" >&2
return 1
else
echo "Parsed and added ${#new_keys[@]} keys."
fi
echo "Found generated key with ID: $newkey"
fpr=$(gpg --with-colons --fingerprint --list-keys "$newkey" | awk -F: '/^fpr:/ {print $10 ; exit}')
if [ -z "$fpr" ]; then
echo "Couldn't find the fingerprint of the generated key $newkey, aborting" >&2
return 1
fi
echo "Found generated key fingerprint: $fpr"
echo "Trusting this key..."
gpg --import-ownertrust <<< "$fpr:6:"

cat > "$rsync_conf" <<EOF
# autogenerated with $0 at $(date)
# using: $(gpg --version 2>&1 | head -n1)
{
"recipients": [
[ "$newkey" ]
[ "$(join_by "\", \"" "${new_keys[@]}")" ]
]
}
EOF
Expand All @@ -158,7 +162,7 @@ EOF
cat > "$backup_conf" <<EOF
# autogenerated with $0 at $(date)
# using: $(gpg --version 2>&1 | head -n1)
GPGKEYS='$newkey'
GPGKEYS='$(join_by " " "${new_keys[@]}")'
EOF
chown "$UID0":"$GID0" "$backup_conf"
chmod 600 "$backup_conf"
Expand Down
9 changes: 9 additions & 0 deletions lib/shell/functions.inc
Original file line number Diff line number Diff line change
Expand Up @@ -464,3 +464,12 @@ script_init() {
exit_success "Script is disabled"
fi
}

# .join is practical to avoid messy stuff with bash variables
join_by(){
local delim="${1-}"
local first="${2-}"
if shift 2; then
printf "%s" "${first}" "${@/#/$delim}"
fi
}

0 comments on commit 35d4841

Please sign in to comment.