[PATCH GnuPG 1/2] scd:piv: Keep the public key if a key import fails
David Seifert
soap at gentoo.org
Thu Nov 12 10:22:05 CET 2026
* scd/app-piv.c (do_writekey): Do not clear the cert DO before
importing the key.
--
do_writekey cleared the cert DO before handing the key to
writekey_rsa or writekey_ecc. If the import then failed, the card
still had the old private key, but scdaemon had lost its public key
and READKEY returned "No public key" for the slot. For a key
generated on the card there is no copy to import again.
The import can fail in scdaemon, for example for an Ed25519 key,
which is rejected with "Unknown elliptic curve" before any APDU is
sent. It can also fail on the card, for example for a 4096 bit RSA
key on a YubiKey before firmware 5.7.
Clearing is not needed: writekey_rsa and writekey_ecc overwrite the
cert DO with the new public key after the card accepted the key.
do_genkey does the same.
Tested with --force imports into a slot holding an RSA-2048 key:
Card Slot Failed import Slot afterwards
---------------------- ---- --------------------- ---------------
YubiKey 5C NFC (5.7.1) 9E Ed25519 (scdaemon) key kept
YubiKey 5 NFC (5.1.2) 95 Ed25519 (scdaemon) key kept
RSA-4096 (card, 6A80) key kept, signs
YubiKey 4 (4.3.7) 95 Ed25519 (scdaemon) key kept
RSA-4096 (card, 6A80) key kept
Without this patch READKEY returned "No public key" after each of
these failed imports. On the YubiKey 5C NFC, importing RSA-2048,
RSA-4096 and P-256 keys with --force still replaces the key, and
READKEY returns the keygrip of the new key.
Signed-off-by: David Seifert <soap at gentoo.org>
---
scd/app-piv.c | 17 ++++-------------
1 file changed, 4 insertions(+), 13 deletions(-)
diff --git a/scd/app-piv.c b/scd/app-piv.c
index baa9b187a..f26203e67 100644
--- a/scd/app-piv.c
+++ b/scd/app-piv.c
@@ -3186,20 +3186,11 @@ do_writekey (app_t app, ctrl_t ctrl,
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
goto leave;
- /* First clear an existing key. We do this by writing an empty 7f49
- * tag. This will return GPG_ERR_NO_PUBKEY on a later read. */
+ /* Divert to the algo specific implementation. The cert DO is not
+ * cleared beforehand: the implementations overwrite it only after
+ * the card accepted the key, so a failed import keeps the public
+ * key of the existing key. */
flush_cached_data (app, dobj->tag);
- err = put_data (app_get_slot (app), dobj->tag,
- (int)0x7f49, (size_t)0, "",
- (int)0, (size_t)0, NULL);
- if (err)
- {
- log_error ("piv: failed to clear the cert DO %s: %s\n",
- dobj->keyref, gpg_strerror (err));
- goto leave;
- }
-
- /* Divert to the algo specific implementation. */
if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
err = writekey_rsa (app, dobj, keyref, buf, buflen, depth);
else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
--
2.56.0
More information about the Gnupg-devel
mailing list