arekinath / PivApplet

PIV applet for JavaCard 2.2.2 and 3.0.4+ with full ECDSA/ECDH support
111 stars 37 forks source link

Unable to import ECCP256 key #36

Closed vuori closed 4 years ago

vuori commented 4 years ago

I'm trying to import an ECCP256 key to a J3H145 card running the latest PivApplet release (PivApplet-0.8.1-jc304-REePSAx.cap). Importing RSA keys works fine, but importing EC keys fails with yubico-piv-tool:

$ yubico-piv-tool -r '' -a import-key -i ec.key -s 82 -A ECCP256 -v2
Connect reader 'Alcor Micro AU9560 00 00' matching ''.
> 00 a4 04 00 05 a0 00 00 03 08 
< 61 71 4f 0b a0 00 00 03 08 00 00 10 00 01 00 79 0d 4f 0b a0 00 00 03 08 00 00 10 00 01 00 50 17 50 69 76 41 70 70 6c 65 74 20 76 30 2e 38 2e 31 2f 52 45 65 50 53 41 5f 50 26 68 74 74 70 73 3a 2f 2f 67 69 74 68 75 62 2e 63 6f 6d 2f 61 72 65 6b 69 6e 61 74 68 2f 50 69 76 41 70 70 6c 65 74 ac 11 80 01 03 80 01 06 80 01 07 80 01 11 80 01 14 06 00 90 00 
> 00 fd 00 00 00 
< 05 03 00 90 00 
> 00 f8 00 00 00 
< 98 b0 9a fb 90 00 
Authenticating since action 'import-key' needs that.
<censored>
Successful application authentication.
Now processing for action 'import-key'.
Going to send 34 bytes in this go.
> <censored>
< 6a 80 
Unable to import private key

pivy-tool fails in a similar manner:

$ pivy-tool -a eccp256 import 82 < ec.key
pivy-tool: error occurred while executing 'import'
  Caused by cmd_import: failed to import key
    in cmd_import() at pivy-tool.c:1354
  Caused by APDUError: Card replied with SW=6a80 (WRONG_DATA) to INS_IMPORT_ASYM(82)
    in ykpiv_import() at piv.c:2532

Meanwhile pivy-tool -a eccp256 generate 82 works. However, the import attempt leaves the slot in a wonky state: if an RSA key is not generated first in the same slot, the ECC generate fails with APDUError: Card replied with SW=6a81 (FUNC_NOT_SUPPORTED) to INS_GEN_ASYM. After generating an RSA key in the slot first an eccp256 key can be generated on the card.

ssh-keygen -f ec.key -y on the private key I'm attempting to import produces the expected public key. openssl ec output:

ASN1 OID: prime256v1
NIST CURVE: P-256

Is there something wrong with my key or PivApplet? (This key has been successfully imported to a Yubikey 5 with ykman.)

arekinath commented 4 years ago

It looks like during the work to add support for P-384 the setCurveParameters() calls got moved around and now EC import doesn't work. Should be an easy fix, and I'll add an auto-test to avoid regressions with it in future (there's an auto-test for RSA import but not EC import currently).

Re: the import attempt leaving the slot in a wonky state, that looks like a closely related bug -- the same swapping around of the order of those calls vs. clearKey() / key slot setup should fix that too.

arekinath commented 4 years ago

Fix for this will be in 0.8.2

vuori commented 4 years ago

Thanks, built the applet from master, imported the EC key, wrote a history object and it's working in pivy-agent.