martinpaljak / GlobalPlatformPro

🌐 🔐 Manage applets and keys on JavaCard-s like a pro
https://javacard.pro/globalplatform
GNU Lesser General Public License v3.0
713 stars 212 forks source link

SCP02: extended length APDUs cause an IllegalArgumentException #318

Open max-lb opened 1 year ago

max-lb commented 1 year ago

With SCP02, trying to send an extended length APDU (> 255 bytes) with GPSession.transmit() always results in IllegalArgumentException:

java.lang.IllegalArgumentException: Invalid APDU: length=261, b1=0, b2||b3=55810
        at apdu4j.CommandAPDU.parse(CommandAPDU.java:337)
        at apdu4j.CommandAPDU.<init>(CommandAPDU.java:92)
        at pro.javacard.gp.SCP02Wrapper.wrap(SCP02Wrapper.java:163)
        at pro.javacard.gp.GPSession.transmit(GPSession.java:514)

With SCP03 everything works fine.

It appears, that the SCP02Wrapper doesn't know how to deal with 3-byte lenghts (Nc) in APDUs. Both when composing a partial APDU for the MAC calculation, and when composing the final APDU, it does this:

            // Construct new APDU
            t.write(newCLA);
            t.write(origINS);
            t.write(origP1);
            t.write(origP2);
            if (newLc > 0) {
                t.write(newLc);            // <-- this works only with single-byte lengths
                t.write(newData);
            }

The code in SCP03Wrapper is aware of extended lengths:

                bo.write(command.getINS());
                bo.write(command.getP1());
                bo.write(command.getP2());
                bo.write(GPUtils.encodeLcLength(lc, command.getNe()));    // <-- encodes Lc properly
                bo.write(data);

Is there a reason to not support extended length APDUs with SCP02?

martinpaljak commented 1 year ago

Not really, other than GP explicitly declaring that all commands being not extended and SCP02 being obsolete as well. As this is supposedly not going to a card manager (which, as said, explicitly requires short apdu-s as per 11.1.5 APDU Message and Data Length) it would require support from on-card SecureChannel.unwrap().

Which card are you using, to be able to test it?

max-lb commented 1 year ago

You are right - it's not with the card manager. We are communicating with one particular applet, which requires using extended APDUs.

The cards are NXP P71 with JCOP4. Do you need some specific details?

martinpaljak commented 1 year ago

That's a card that does SCP03 just fine - why on earth are you using SCP02 these days? :)

max-lb commented 1 year ago

Most of them do work with SCP03 just fine... Unfortunately we've got some cards that come pre-personalized and "locked" to SCP02 (and we can't change this :( ).