Skip to content

Instantly share code, notes, and snippets.

@mvastola
Created July 24, 2022 02:13
Show Gist options
  • Save mvastola/7c617dfa2cc78d4896efd2bc5f12bb32 to your computer and use it in GitHub Desktop.
Save mvastola/7c617dfa2cc78d4896efd2bc5f12bb32 to your computer and use it in GitHub Desktop.
A shell script replacement for the (deprecated) `apt-key adv ...` that's even easier to use.
#!/bin/bash
set -e
# Need to be root for this
[ $(/usr/bin/id -ur) -eq 0 ] || exec /usr/bin/sudo -u root -g root -- "$(realpath "$0")" "$@"
KEYS_ROOT=/etc/apt/trusted.gpg.d
KEYSERVERS=( hkp://keys.gnupg.net hkp://pgp.mit.edu hkp://keyserver.ubuntu.com hkp://keyserver.ubuntu.com:80 )
function die() {
echo "$@" 1>&2
echo 1>&2
echo "Usage:" 1>&2
echo -e "\t$0 KEY_ID [KEYSERVERS...]" 1>&2
[ $? -eq 0 ] || exit 1
}
[ $# -ge 1 ] || die "Required arguments missing."
KEY_ID="$1"
shift 1
GNUPGHOME="$(mktemp -d "${TEMPDIR:-/tmp}/apt-import-key.XXXX")"
export GNUPGHOME
trap "rm -Rf '${GNUPGHOME}'" ERR EXIT INT
cd "${GNUPGHOME}"
umask 0133
KEYSERVERS=( "$@" "${KEYSERVERS[@]}" )
for server in "${KEYSERVERS[@]}"; do
echo "keyserver ${server}"
done > "${GNUPGHOME}/dirmngr.conf"
echo
echo "Starting dirmngr"
eval "$(dirmngr --daemon)"
export DIRMNGR_PID="$(sed -r 's/^[^:]+:([[:digit:]]+):.*$/\1/' <<<"${DIRMNGR_INFO}")"
sleep 0.1
trap "dirmngr --shutdown" ERR EXIT INT
kill -n0 "${DIRMNGR_PID}" || die "Dirmngr failed to load."
echo "Attempting to retrieve key"
gpg --verbose --recv-keys "${KEY_ID}" ||\
die "Could not retrieve key ${KEY_ID} from any configured keyservers."
KEY_OWNER="$(gpg --with-colons -k "${KEY_ID}" | grep -E '^uid:' | cut -d ':' -f 10)" || \
die "Could not parse owner of key '${KEY_ID}'."
KEY_OWNER_NAME="$(sed -r 's/\s*<[^>]+>//g;s/[[:cntrl:]]+//g' <<<"${KEY_OWNER}")"
KEY_OWNER_NAME="${KEY_OWNER_NAME// /_}"
KEYFILE_PATH="${KEYS_ROOT}/${KEY_OWNER_NAME}-${KEY_ID}.asc"
KEYFILE_PATH_REAL="$(realpath -sLq "${KEYFILE_PATH}")"
[ -n "${KEYFILE_PATH_REAL}" ] || die "Path to ${KEYFILE_PATH_REAL} does not exist."
if [ -e "${KEYFILE_PATH_REAL}" ] && [ ! -f "${KEYFILE_PATH_REAL}" ]; then
die "A non-file already exists at ${KEYFILE_PATH_REAL}. Aborting."
fi
if [ -e "${KEYFILE_PATH_REAL}" ] && [ -s "${KEYFILE_PATH_REAL}" ]; then
rm -f "${KEYFILE_PATH_REAL}"
echo "NOTE: Auto-deleted blank file at ${KEYFILE_PATH_REAL}." 2>&1
fi
if [ -f "${KEYFILE_PATH_REAL}" ]; then
echo "Keyfile at already exists at ${KEYFILE_PATH_REAL}. You will be prompted for if you'd like to overwrite." 1>&2
fi
if gpg --armor --export "${KEY_ID}" > "${KEY_ID}.asc" && [ -s "${KEY_ID}.asc" ]; then
chmod a+r "${KEY_ID}.asc"
else
die "Failed to export key"
fi
echo "Saving key to ${KEYFILE_PATH_REAL}.."
cp -vi "${KEY_ID}.asc" "${KEYFILE_PATH_REAL}" || \
die "Installing key aborted"
find "${KEYFILE_PATH_REAL}" -ls
echo "Done!"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment