]> git.saurik.com Git - apt.git/blobdiff - cmdline/apt-key.in
part revert, part redo 'which' replacement
[apt.git] / cmdline / apt-key.in
index b8fdfe121b32c6692cfacb7f746bcc34abe98fc6..f1d021e8ac2236031f49d0b0f458b5f8fa2c0e5a 100644 (file)
@@ -2,6 +2,7 @@
 
 set -e
 unset GREP_OPTIONS
+export IFS="$(printf "\n\b")"
 
 APT_DIR="/"
 eval $(apt-config shell APT_DIR Dir)
@@ -14,7 +15,6 @@ REMOVED_KEYS='&keyring-removed-filename;'
 eval $(apt-config shell REMOVED_KEYS APT::Key::RemovedKeys)
 ARCHIVE_KEYRING_URI='&keyring-uri;'
 eval $(apt-config shell ARCHIVE_KEYRING_URI APT::Key::ArchiveKeyringURI)
-TMP_KEYRING=${APT_DIR}/var/lib/apt/keyrings/maybe-import-keyring.gpg
 
 aptkey_echo() { echo "$@"; }
 
@@ -25,6 +25,35 @@ requires_root() {
        fi
 }
 
+command_available() {
+    # command -v "$1" >/dev/null 2>&1 # not required by policy, see #747320
+    # which "$1" >/dev/null 2>&1 # is in debianutils (essential) but not on non-debian systems
+    local OLDIFS="$IFS"
+    IFS=:
+    for p in $PATH; do
+       if [ -x "${p}/${1}" ]; then
+           IFS="$OLDIFS"
+           return 0
+       fi
+    done
+    IFS="$OLDIFS"
+    return 1
+}
+
+get_fingerprints_of_keyring() {
+    aptkey_execute "$GPG_SH" --keyring "$1" --with-colons --fingerprint | while read publine; do
+       # search for a public key
+       if [ "${publine%%:*}" != 'pub' ]; then continue; fi
+       # search for the associated fingerprint (should be the very next line)
+       while read fprline; do
+          if [ "${fprline%%:*}" = 'sub' ]; then break; # should never happen
+          elif [ "${fprline%%:*}" != 'fpr' ]; then continue; fi
+          echo "$fprline" | cut -d':' -f 10
+       done
+       # order in the keyring shouldn't be important
+    done | sort
+}
+
 add_keys_with_verify_against_master_keyring() {
     ADD_KEYRING=$1
     MASTER=$2
@@ -42,9 +71,9 @@ add_keys_with_verify_against_master_keyring() {
     # is honored. so:
     #   all keys that are exported must have a valid signature
     #   from a key in the $distro-master-keyring
-    add_keys=`$GPG_CMD --keyring $ADD_KEYRING --with-colons --list-keys | grep ^pub | cut -d: -f5`
-    all_add_keys=`$GPG_CMD --keyring $ADD_KEYRING --with-colons --list-keys | grep ^[ps]ub | cut -d: -f5`
-    master_keys=`$GPG_CMD --keyring $MASTER --with-colons --list-keys | grep ^pub | cut -d: -f5`
+    add_keys="$(get_fingerprints_of_keyring "$ADD_KEYRING")"
+    all_add_keys=`aptkey_execute "$GPG_SH" --keyring "$ADD_KEYRING" --with-colons --list-keys | grep ^[ps]ub | cut -d: -f5`
+    master_keys=`aptkey_execute "$GPG_SH" --keyring "$MASTER" --with-colons --list-keys | grep ^pub | cut -d: -f5`
 
     # ensure there are no colisions LP: #857472
     for all_add_key in $all_add_keys; do
@@ -55,24 +84,30 @@ add_keys_with_verify_against_master_keyring() {
             fi
         done
     done
-    
+
     for add_key in $add_keys; do
         # export the add keyring one-by-one
-        rm -f $TMP_KEYRING
-        $GPG_CMD --keyring $ADD_KEYRING --output $TMP_KEYRING --export $add_key 
-        # check if signed with the master key and only add in this case
-        ADDED=0
+       local TMP_KEYRING="${GPGHOMEDIR}/tmp-keyring.gpg"
+       aptkey_execute "$GPG_SH" --batch --yes --keyring "$ADD_KEYRING" --output "$TMP_KEYRING" --export "$add_key"
+       if ! aptkey_execute "$GPG_SH" --batch --yes --keyring "$TMP_KEYRING" --import "$MASTER" > "${GPGHOMEDIR}/gpgoutput.log" 2>&1; then
+           cat >&2 "${GPGHOMEDIR}/gpgoutput.log"
+           false
+       fi
+       # check if signed with the master key and only add in this case
+       ADDED=0
        for master_key in $master_keys; do
-           if $GPG_CMD --keyring $MASTER --keyring $TMP_KEYRING --check-sigs --with-colons $add_key | grep '^sig:!:' | cut -d: -f5 | grep -q $master_key; then
-               $GPG --import $TMP_KEYRING
+           if aptkey_execute "$GPG_SH" --keyring "$TMP_KEYRING" --check-sigs --with-colons "$add_key" \
+              | grep '^sig:!:' | cut -d: -f5 | grep -q "$master_key"; then
+               aptkey_execute "$GPG_SH" --batch --yes --keyring "$ADD_KEYRING" --export "$add_key" \
+                  | aptkey_execute "$GPG" --batch --yes --import
                ADDED=1
            fi
        done
        if [ $ADDED = 0 ]; then
            echo >&2 "Key '$add_key' not added. It is not signed with a master key"
        fi
+       rm -f "${TMP_KEYRING}"
     done
-    rm -f $TMP_KEYRING
 }
 
 # update the current archive signing keyring from a network URI
@@ -92,31 +127,31 @@ net_update() {
     fi
     # in theory we would need to depend on wget for this, but this feature
     # isn't useable in debian anyway as we have no keyring uri nor a master key
-    if ! which wget >/dev/null 2>&1; then
+    if ! command_available 'wget'; then
        echo >&2 "ERROR: an installed wget is required for a network-based update"
        exit 1
     fi
-    if [ ! -d ${APT_DIR}/var/lib/apt/keyrings ]; then
-       mkdir -p ${APT_DIR}/var/lib/apt/keyrings
+    if [ ! -d "${APT_DIR}/var/lib/apt/keyrings" ]; then
+       mkdir -p "${APT_DIR}/var/lib/apt/keyrings"
     fi
-    keyring=${APT_DIR}/var/lib/apt/keyrings/$(basename $ARCHIVE_KEYRING_URI)
+    keyring="${APT_DIR}/var/lib/apt/keyrings/$(basename "$ARCHIVE_KEYRING_URI")"
     old_mtime=0
     if [ -e $keyring ]; then
        old_mtime=$(stat -c %Y $keyring)
     fi
-    (cd  ${APT_DIR}/var/lib/apt/keyrings; wget --timeout=90 -q -N $ARCHIVE_KEYRING_URI)
-    if [ ! -e $keyring ]; then
+    (cd  "${APT_DIR}/var/lib/apt/keyrings"; wget --timeout=90 -q -N "$ARCHIVE_KEYRING_URI")
+    if [ ! -e "$keyring" ]; then
        return
     fi
-    new_mtime=$(stat -c %Y $keyring)
+    new_mtime=$(stat -c %Y "$keyring")
     if [ $new_mtime -ne $old_mtime ]; then
        aptkey_echo "Checking for new archive signing keys now"
-       add_keys_with_verify_against_master_keyring $keyring $MASTER_KEYRING
+       add_keys_with_verify_against_master_keyring "$keyring" "$MASTER_KEYRING"
     fi
 }
 
 update() {
-    if [ ! -f $ARCHIVE_KEYRING ]; then
+    if [ ! -f "$ARCHIVE_KEYRING" ]; then
        echo >&2 "ERROR: Can't find the archive-keyring"
        echo >&2 "Is the &keyring-package; package installed?"
        exit 1
@@ -129,11 +164,11 @@ update() {
     # attacker might as well replace the master-archive-keyring file
     # in the package and add his own keys. so this check wouldn't
     # add any security. we *need* this check on net-update though
-    $GPG_CMD --quiet --batch --keyring $ARCHIVE_KEYRING --export | $GPG --import
+    import_keyring_into_keyring "$ARCHIVE_KEYRING" '' && cat "${GPGHOMEDIR}/gpgoutput.log"
 
     if [ -r "$REMOVED_KEYS" ]; then
        # remove no-longer supported/used keys
-       $GPG_CMD --keyring $REMOVED_KEYS --with-colons --list-keys | grep ^pub | cut -d: -f5 | while read key; do
+       get_fingerprints_of_keyring "$REMOVED_KEYS" | while read key; do
            foreach_keyring_do 'remove_key_from_keyring' "$key"
        done
     else
@@ -149,12 +184,11 @@ remove_key_from_keyring() {
        return
     fi
 
-    local GPG="$GPG_CMD --keyring $KEYRINGFILE"
-    while [ -n "$1" ]; do
-       local KEY="$1"
-       shift
-       # check if the key is in this keyring: the key id is in the 5 column at the end
-       if ! $GPG --with-colons --list-keys 2>&1 | grep -q "^pub:[^:]*:[^:]*:[^:]*:[0-9A-F]*${KEY}:"; then
+    for KEY in "$@"; do
+       local FINGERPRINTS="${GPGHOMEDIR}/keyringfile.keylst"
+       get_fingerprints_of_keyring "$KEYRINGFILE" > "$FINGERPRINTS"
+       # check if the key is in this keyring
+       if ! grep -iq "^[0-9A-F]*${KEY}$" "$FINGERPRINTS"; then
            continue
        fi
        if [ ! -w "$KEYRINGFILE" ]; then
@@ -162,7 +196,7 @@ remove_key_from_keyring() {
            continue
        fi
        # check if it is the only key in the keyring and if so remove the keyring altogether
-       if [ '1' = "$($GPG --with-colons --list-keys | grep "^pub:[^:]*:[^:]*:[^:]*:[0-9A-F]\+:" | wc -l)" ]; then
+       if [ '1' = "$(uniq "$FINGERPRINTS" | wc -l)" ]; then
            mv -f "$KEYRINGFILE" "${KEYRINGFILE}~" # behave like gpg
            return
        fi
@@ -174,7 +208,7 @@ remove_key_from_keyring() {
            cp -a "$REALTARGET" "$KEYRINGFILE"
        fi
        # delete the key from the keyring
-       $GPG --batch --delete-key --yes "$KEY"
+       aptkey_execute "$GPG_SH" --keyring "$KEYRINGFILE" --batch --delete-keys --yes "$KEY"
        if [ -n "$REALTARGET" ]; then
            # the real backup is the old link, not the copy we made
            mv -f "${KEYRINGFILE}.dpkg-tmp" "${KEYRINGFILE}~"
@@ -185,7 +219,7 @@ remove_key_from_keyring() {
 foreach_keyring_do() {
    local ACTION="$1"
    shift
-   # if a --keyring was given, just remove from there
+   # if a --keyring was given, just work on this one
    if [ -n "$FORCED_KEYRING" ]; then
        $ACTION "$FORCED_KEYRING" "$@"
    else
@@ -201,7 +235,7 @@ foreach_keyring_do() {
            if [ "${STRIPPED_TRUSTEDPARTS}/" = "$TRUSTEDPARTS" ]; then
                TRUSTEDPARTS="$STRIPPED_TRUSTEDPARTS"
            fi
-           for trusted in $(run-parts --list "$TRUSTEDPARTS" --regex '^.*\.gpg$'); do
+           for trusted in $(find "$TRUSTEDPARTS" -mindepth 1 -maxdepth 1 -regex '^.*\.gpg$' | sort); do
                if [ -s "$trusted" ]; then
                    $ACTION "$trusted" "$@"
                fi
@@ -210,41 +244,155 @@ foreach_keyring_do() {
    fi
 }
 
-list_keys_from_keyring() {
+run_cmd_on_keyring() {
     local KEYRINGFILE="$1"
     shift
-    # don't show the error message if this keyring doesn't include the key
-    $GPG_CMD --keyring "$KEYRINGFILE" --batch --list-keys "$@" 2>/dev/null || true
+    # fingerprint and co will fail if key isn't in this keyring
+    aptkey_execute "$GPG_SH" --keyring "$KEYRINGFILE" --batch "$@" 2>/dev/null || true
 }
 
-fingerprint_keys_from_keyring() {
-    local KEYRINGFILE="$1"
-    shift
-    # don't show the error message if this keyring doesn't include the fingerprint
-    $GPG_CMD --keyring "$KEYRINGFILE" --batch --fingerprint "$@" 2>/dev/null || true
+import_keyring_into_keyring() {
+    local FROM="${1:-${GPGHOMEDIR}/pubring.gpg}"
+    local TO="${2:-${GPGHOMEDIR}/pubring.gpg}"
+    shift 2
+    rm -f "${GPGHOMEDIR}/gpgoutput.log"
+    # the idea is simple: We take keys from one keyring and copy it to another
+    # we do this with so many checks in between to ensure that WE control the
+    # creation, so we know that the (potentially) created $TO keyring is a
+    # simple keyring rather than a keybox as gpg2 would create it which in turn
+    # can't be read by gpgv.
+    # BEWARE: This is designed more in the way to work with the current
+    # callers, than to have a well defined it would be easy to add new callers to.
+    if [ ! -s "$TO" ]; then
+       if [ -s "$FROM" ]; then
+           if [ -z "$2" ]; then
+               if ! aptkey_execute "$GPG_SH" --keyring "$FROM" --export ${1:+"$1"} > "$TO" 2> "${GPGHOMEDIR}/gpgoutput.log"; then
+                   cat >&2 "${GPGHOMEDIR}/gpgoutput.log"
+                   false
+               else
+                   chmod 0644 -- "$TO"
+               fi
+           else
+               create_new_keyring "$TO"
+           fi
+       else
+           create_new_keyring "$TO"
+       fi
+    elif [ -s "$FROM" ]; then
+       local EXPORTLIMIT="$1"
+       if [ -n "$1$2" ]; then shift; fi
+       if ! aptkey_execute "$GPG_SH" --keyring "$FROM" --export ${EXPORTLIMIT:+"$EXPORTLIMIT"} \
+          | aptkey_execute "$GPG_SH" --keyring "$TO" --batch --import "$@" > "${GPGHOMEDIR}/gpgoutput.log" 2>&1; then
+           cat >&2 "${GPGHOMEDIR}/gpgoutput.log"
+           false
+       fi
+    fi
+}
+
+merge_all_trusted_keyrings_into_pubring() {
+    # does the same as:
+    # foreach_keyring_do 'import_keys_from_keyring' "${GPGHOMEDIR}/pubring.gpg"
+    # but without using gpg, just cat and find
+    local PUBRING="${GPGHOMEDIR}/pubring.gpg"
+    # if a --keyring was given, just use this one
+    if [ -n "$FORCED_KEYRING" ]; then
+       if [ -s "$FORCED_KEYRING" ]; then
+           cp --dereference "$FORCED_KEYRING" "$PUBRING"
+       fi
+    else
+       # otherwise all known keyrings are merged
+       local TRUSTEDPARTS="/etc/apt/trusted.gpg.d"
+       eval $(apt-config shell TRUSTEDPARTS Dir::Etc::TrustedParts/d)
+       if [ -d "$TRUSTEDPARTS" ]; then
+           # ignore errors mostly for non-existing $TRUSTEDFILE
+           {
+              cat "$TRUSTEDFILE" || true
+              for parts in $(find -L "$TRUSTEDPARTS" -type f -name '*.gpg'); do
+                 cat "$parts" || true
+              done
+           } > "$PUBRING" 2>/dev/null
+       elif [ -s "$TRUSTEDFILE" ]; then
+           cp --dereference "$TRUSTEDFILE" "$PUBRING"
+       fi
+    fi
+
+    if [ ! -s "$PUBRING" ]; then
+       touch "$PUBRING"
+    fi
 }
 
 import_keys_from_keyring() {
-    local IMPORT="$1"
-    local KEYRINGFILE="$2"
-    $GPG_CMD --keyring "$KEYRINGFILE" --batch --import "$IMPORT" >/dev/null 2>&1
+    import_keyring_into_keyring "$1" "$2"
+}
+
+merge_keys_into_keyrings() {
+    import_keyring_into_keyring "$2" "$1" '' --import-options 'merge-only'
+}
+
+merge_back_changes() {
+    if [ -n "$FORCED_KEYRING" ]; then
+       # if the keyring was forced merge is already done
+       return
+    fi
+    if [ -s "${GPGHOMEDIR}/pubring.gpg" ]; then
+       # merge all updated keys
+       foreach_keyring_do 'merge_keys_into_keyrings' "${GPGHOMEDIR}/pubring.gpg"
+    fi
+    # look for keys which were added or removed
+    get_fingerprints_of_keyring "${GPGHOMEDIR}/pubring.orig.gpg" > "${GPGHOMEDIR}/pubring.orig.keylst"
+    get_fingerprints_of_keyring "${GPGHOMEDIR}/pubring.gpg" > "${GPGHOMEDIR}/pubring.keylst"
+    comm -3 "${GPGHOMEDIR}/pubring.keylst" "${GPGHOMEDIR}/pubring.orig.keylst" > "${GPGHOMEDIR}/pubring.diff"
+    # key isn't part of new keyring, so remove
+    cut -f 2 "${GPGHOMEDIR}/pubring.diff" | while read key; do
+       if [ -z "$key" ]; then continue; fi
+       foreach_keyring_do 'remove_key_from_keyring' "$key"
+    done
+    # key is only part of new keyring, so we need to import it
+    cut -f 1 "${GPGHOMEDIR}/pubring.diff" | while read key; do
+       if [ -z "$key" ]; then continue; fi
+       import_keyring_into_keyring '' "$TRUSTEDFILE" "$key"
+    done
 }
 
 setup_merged_keyring() {
-    local TRUSTEDFILE_BAK="$TRUSTEDFILE"
-    TRUSTEDFILE='/dev/null'
-    foreach_keyring_do 'import_keys_from_keyring' "${GPGHOMEDIR}/trusted.gpg"
-    TRUSTEDFILE="$TRUSTEDFILE_BAK"
-    # mark it as non-writeable so users get errors if gnupg tries to modify it
-    if [ -s "${GPGHOMEDIR}/trusted.gpg" ]; then
-       chmod -w "${GPGHOMEDIR}/trusted.gpg"
-       GPG="$GPG --keyring ${GPGHOMEDIR}/trusted.gpg"
+    if [ -n "$FORCED_KEYID" ]; then
+       merge_all_trusted_keyrings_into_pubring
+       FORCED_KEYRING="${GPGHOMEDIR}/forcedkeyid.gpg"
+       TRUSTEDFILE="${FORCED_KEYRING}"
+       echo "#!/bin/sh
+exec sh \"${GPG}\" --keyring \"${TRUSTEDFILE}\" \"\$@\"" > "${GPGHOMEDIR}/gpg.1.sh"
+       GPG="${GPGHOMEDIR}/gpg.1.sh"
+       # ignore error as this "just" means we haven't found the forced keyid and the keyring will be empty
+       import_keyring_into_keyring '' "$TRUSTEDFILE" "$FORCED_KEYID" || true
+    elif [ -z "$FORCED_KEYRING" ]; then
+       merge_all_trusted_keyrings_into_pubring
+       if [ -r "${GPGHOMEDIR}/pubring.gpg" ]; then
+           cp -a "${GPGHOMEDIR}/pubring.gpg" "${GPGHOMEDIR}/pubring.orig.gpg"
+       else
+          touch "${GPGHOMEDIR}/pubring.gpg" "${GPGHOMEDIR}/pubring.orig.gpg"
+       fi
+       echo "#!/bin/sh
+exec sh \"${GPG}\" --keyring \"${GPGHOMEDIR}/pubring.gpg\" \"\$@\"" > "${GPGHOMEDIR}/gpg.1.sh"
+       GPG="${GPGHOMEDIR}/gpg.1.sh"
+    else
+       create_new_keyring "$TRUSTEDFILE"
+       echo "#!/bin/sh
+exec sh \"${GPG}\" --keyring \"${TRUSTEDFILE}\" \"\$@\"" > "${GPGHOMEDIR}/gpg.1.sh"
+       GPG="${GPGHOMEDIR}/gpg.1.sh"
     fi
-    if [ -r "$TRUSTEDFILE" ]; then
-       GPG="$GPG --keyring $TRUSTEDFILE --primary-keyring $TRUSTEDFILE"
+}
+
+create_new_keyring() {
+    # gpg defaults to mode 0600 for new keyrings. Create one with 0644 instead.
+    if ! [ -e "$TRUSTEDFILE" ]; then
+       if [ -w "$(dirname "$TRUSTEDFILE")" ]; then
+           touch -- "$TRUSTEDFILE"
+           chmod 0644 -- "$TRUSTEDFILE"
+       fi
     fi
 }
 
+aptkey_execute() { sh "$@"; }
 
 usage() {
     echo "Usage: apt-key [--keyring file] [command] [arguments]"
@@ -270,16 +418,33 @@ while [ -n "$1" ]; do
         shift
         TRUSTEDFILE="$1"
         FORCED_KEYRING="$1"
+        ;;
+      --keyid)
+        shift
+        FORCED_KEYID="$1"
+        ;;
+      --secret-keyring)
         shift
+        FORCED_SECRET_KEYRING="$1"
+        ;;
+      --readonly)
+        merge_back_changes() { true; }
+        create_new_keyring() { if [ ! -r "$FORCED_KEYRING" ]; then TRUSTEDFILE='/dev/null'; FORCED_KEYRING="$TRUSTEDFILE"; fi; }
         ;;
       --fakeroot)
         requires_root() { true; }
-        shift
         ;;
       --quiet)
         aptkey_echo() { true; }
-        shift
         ;;
+      --debug1)
+        # some cmds like finger redirect stderr to /dev/null …
+       aptkey_execute() { echo 'EXEC:' "$@"; sh "$@"; }
+       ;;
+      --debug2)
+        # … other more complicated ones pipe gpg into gpg.
+       aptkey_execute() { echo >&2 'EXEC:' "$@"; sh "$@"; }
+       ;;
       --*)
         echo >&2 "Unknown option: $1"
         usage
@@ -287,6 +452,7 @@ while [ -n "$1" ]; do
       *)
         break;;
    esac
+   shift
 done
 
 if [ -z "$TRUSTEDFILE" ]; then
@@ -302,49 +468,84 @@ if [ -z "$command" ]; then
 fi
 shift
 
-if [ "$command" != "help" ]; then
-    if ! which gpg >/dev/null 2>&1; then
-       echo >&2 "Warning: gnupg does not seem to be installed."
-       echo >&2 "Warning: apt-key requires gnupg for most operations."
-       echo >&2
-    fi
-
-    GPG_CMD="gpg --ignore-time-conflict --no-options --no-default-keyring"
-
+create_gpg_home() {
     # gpg needs (in different versions more or less) files to function correctly,
-    # so we give it its own homedir and generate some valid content for it
+    # so we give it its own homedir and generate some valid content for it later on
+    if [ -n "$TMPDIR" ]; then
+       # tmpdir is a directory and current user has rwx access to it
+       # same tests as in apt-pkg/contrib/fileutl.cc GetTempDir()
+       if [ ! -d "$TMPDIR" ] || [ ! -r "$TMPDIR" ] || [ ! -w "$TMPDIR" ] || [ ! -x "$TMPDIR" ]; then
+           unset TMPDIR
+       fi
+    fi
     GPGHOMEDIR="$(mktemp -d)"
     CURRENTTRAP="${CURRENTTRAP} rm -rf '${GPGHOMEDIR}';"
     trap "${CURRENTTRAP}" 0 HUP INT QUIT ILL ABRT FPE SEGV PIPE TERM
     chmod 700 "$GPGHOMEDIR"
+}
+
+prepare_gpg_home() {
+    eval $(apt-config shell GPG_EXE Apt::Key::gpgcommand)
+
+    if [ -n "$GPG_EXE" ] && command_available "$GPG_EXE"; then
+       true
+    elif command_available 'gpg'; then
+       GPG_EXE="gpg"
+    elif command_available 'gpg2'; then
+       GPG_EXE="gpg2"
+    else
+       echo >&2 "Error: gnupg or gnupg2 do not seem to be installed,"
+       echo >&2 "Error: but apt-key requires gnupg or gnupg2 for this operation."
+       echo >&2
+       exit 255
+    fi
+
+    create_gpg_home
+
     # We don't use a secret keyring, of course, but gpg panics and
     # implodes if there isn't one available - and writeable for imports
     SECRETKEYRING="${GPGHOMEDIR}/secring.gpg"
-    touch $SECRETKEYRING
-    GPG_CMD="$GPG_CMD --homedir $GPGHOMEDIR"
+    touch "$SECRETKEYRING"
+
     # create the trustdb with an (empty) dummy keyring
     # older gpgs required it, newer gpgs even warn that it isn't needed,
     # but require it nonetheless for some commands, so we just play safe
     # here for the foreseeable future and create a dummy one
-    $GPG_CMD --quiet --check-trustdb --keyring $SECRETKEYRING >/dev/null 2>&1
+    if ! "$GPG_EXE" --ignore-time-conflict --no-options --no-default-keyring \
+       --homedir "$GPGHOMEDIR" --quiet --check-trustdb --keyring "$SECRETKEYRING" >"${GPGHOMEDIR}/gpgoutput.log" 2>&1; then
+       cat >&2 "${GPGHOMEDIR}/gpgoutput.log"
+       false
+    fi
     # tell gpg that it shouldn't try to maintain a trustdb file
-    GPG_CMD="$GPG_CMD --no-auto-check-trustdb --trust-model always"
-    GPG="$GPG_CMD"
-
-    # gpg defaults to mode 0600 for new keyrings. Create one with 0644 instead.
-    if ! [ -e "$TRUSTEDFILE" ]; then
-       if [ -w "$(dirname "$TRUSTEDFILE")" ]; then
-          touch -- "$TRUSTEDFILE"
-          chmod 0644 -- "$TRUSTEDFILE"
-       fi
+    echo "#!/bin/sh
+exec \"${GPG_EXE}\" --ignore-time-conflict --no-options --no-default-keyring \\
+   --homedir \"${GPGHOMEDIR}\" --no-auto-check-trustdb --trust-model always \"\$@\"" > "${GPGHOMEDIR}/gpg.0.sh"
+    GPG_SH="${GPGHOMEDIR}/gpg.0.sh"
+    GPG="$GPG_SH"
+
+    # for advanced operations, we might really need a secret keyring after all
+    if [ -n "$FORCED_SECRET_KEYRING" ] && [ -r "$FORCED_SECRET_KEYRING" ]; then
+       rm -f "$SECRETKEYRING"
+       cp -a "$FORCED_SECRET_KEYRING" "$SECRETKEYRING"
     fi
+
+    # older gpg versions need a secring file, but newer versions take it as
+    # a hint to start a migration from earlier versions. The file is empty
+    # anyhow, so nothing actually happens, but its three lines of output
+    # nobody expects to see in apt-key context, so trigger it in silence
+    echo -n | aptkey_execute "$GPG" --batch --import >/dev/null 2>&1 || true
+}
+
+if [ "$command" != 'help' ] && [ "$command" != 'verify' ]; then
+    prepare_gpg_home
 fi
 
 case "$command" in
     add)
        requires_root
        setup_merged_keyring
-       $GPG --quiet --batch --import "$@"
+       aptkey_execute "$GPG" --quiet --batch --import "$@"
+       merge_back_changes
        aptkey_echo "OK"
         ;;
     del|rm|remove)
@@ -356,26 +557,52 @@ case "$command" in
        requires_root
        setup_merged_keyring
        update
+       merge_back_changes
        ;;
     net-update)
        requires_root
        setup_merged_keyring
        net_update
+       merge_back_changes
        ;;
     list)
-       foreach_keyring_do 'list_keys_from_keyring' "$@"
+       foreach_keyring_do 'run_cmd_on_keyring' --list-keys "$@"
        ;;
     finger*)
-       foreach_keyring_do 'fingerprint_keys_from_keyring' "$@"
+       foreach_keyring_do 'run_cmd_on_keyring' --fingerprint "$@"
        ;;
     export|exportall)
-       foreach_keyring_do 'import_keys_from_keyring' "${GPGHOMEDIR}/trusted.gpg"
-       $GPG_CMD --keyring "${GPGHOMEDIR}/trusted.gpg" --armor --export "$@"
+       merge_all_trusted_keyrings_into_pubring
+       aptkey_execute "$GPG_SH" --keyring "${GPGHOMEDIR}/pubring.gpg" --armor --export "$@"
        ;;
     adv*)
        setup_merged_keyring
        aptkey_echo "Executing: $GPG $*"
-       $GPG "$@"
+       aptkey_execute "$GPG" "$@"
+       merge_back_changes
+       ;;
+    verify)
+       GPGV=''
+       eval $(apt-config shell GPGV Apt::Key::gpgvcommand)
+       if [ -n "$GPGV" ] && command_available "$GPGV"; then true;
+       elif command_available 'gpgv'; then GPGV='gpgv';
+       elif command_available 'gpgv2'; then GPGV='gpgv2';
+       else
+          echo >&2 'ERROR: gpgv or gpgv2 required for verification'
+          exit 29
+       fi
+       # for a forced keyid we need gpg --export, so full wrapping required
+       if [ -n "$FORCED_KEYID" ]; then
+           prepare_gpg_home
+       else
+           create_gpg_home
+       fi
+       setup_merged_keyring
+       if [ -n "$FORCED_KEYRING" ]; then
+           "$GPGV" --homedir "${GPGHOMEDIR}" --keyring "${FORCED_KEYRING}" --ignore-time-conflict "$@"
+       else
+           "$GPGV" --homedir "${GPGHOMEDIR}" --keyring "${GPGHOMEDIR}/pubring.gpg" --ignore-time-conflict "$@"
+       fi
        ;;
     help)
         usage