* scd/app-piv.c (writekey_ecc): Left-pad the secret with zeroes to the
size of the curve.

--

writekey_ecc strips leading zero bytes from the secret D but the
import command expects D with the full size of the curve. Thus the
import failed for about one in 256 keys.

Tested by importing a P-256 key whose secret starts with a zero byte:

  Card                    Before this patch   With this patch
  ----------------------  ------------------  -------------------
  YubiKey 5C NFC (5.7.1)  6A80, not imported  imported; key signs
  TOKEN2 PIN+ R3.3        6A80, not imported  imported; key signs

Signed-off-by: David Seifert <[email protected]>
---
 scd/app-piv.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/scd/app-piv.c b/scd/app-piv.c
index f251606ad..e6cd2b6b9 100644
--- a/scd/app-piv.c
+++ b/scd/app-piv.c
@@ -2985,6 +2985,8 @@ writekey_ecc (app_t app, data_object_t dobj, int keyref,
   const unsigned char *ecc_q = NULL;
   const unsigned char *ecc_d = NULL;
   size_t ecc_q_len, ecc_d_len;
+  unsigned char dbuf[48] = { 0 };
+  size_t dlen;
   unsigned char *apdudata = NULL;
   size_t apdudatalen;
   unsigned char tmpl[1];
@@ -3081,9 +3083,20 @@ writekey_ecc (app_t app, data_object_t dobj, int keyref,
   if (opt.verbose)
     log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
 
+  /* The card expects D with the full length of the curve but leading
+   * zero bytes have been stripped above.  */
+  dlen = mechanism == PIV_ALGORITHM_ECC_P256? 32 : 48;
+  if (ecc_d_len > dlen)
+    {
+      err = gpg_error (GPG_ERR_BAD_SECKEY);
+      goto leave;
+    }
+  memcpy (dbuf + dlen - ecc_d_len, ecc_d, ecc_d_len);
+
   err = concat_tlv_list (1, &apdudata, &apdudatalen,
-                         (int)0x06, (size_t)ecc_d_len, ecc_d,
+                         (int)0x06, dlen, dbuf,
                          (int)0, (size_t)0, NULL);
+  wipememory (dbuf, sizeof dbuf);
   if (err)
     goto leave;
 
-- 
2.56.1


_______________________________________________
Gnupg-devel mailing list
[email protected]
https://lists.gnupg.org/mailman/listinfo/gnupg-devel

Reply via email to