-
Notifications
You must be signed in to change notification settings - Fork 37
/
PivApplet.java
3616 lines (3210 loc) · 85.6 KB
/
PivApplet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http:https://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2017, Alex Wilson <[email protected]>
*/
package net.cooperi.pivapplet;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.OwnerPIN;
import javacard.framework.SystemException;
import javacard.framework.Util;
import javacard.security.CryptoException;
import javacard.security.DESKey;
import javacard.security.AESKey;
import javacard.security.ECPrivateKey;
import javacard.security.ECPublicKey;
import javacard.security.KeyAgreement;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;
import javacard.security.PrivateKey;
import javacard.security.PublicKey;
import javacard.security.RSAPrivateCrtKey;
import javacard.security.RSAPublicKey;
import javacard.security.RandomData;
import javacard.security.Signature;
import javacardx.crypto.Cipher;
//#if APPLET_EXTLEN
import javacardx.apdu.ExtendedLength;
//#endif
//#if APPLET_EXTLEN
public class PivApplet extends Applet implements ExtendedLength
{
/*#else
public class PivApplet extends Applet
{
#endif*/
private static final byte[] PIV_AID = {
(byte)0xa0, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x08,
(byte)0x00, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x01,
(byte)0x00
};
private static final byte[] APP_NAME = {
'P', 'i', 'v', 'A', 'p', 'p', 'l', 'e', 't', ' ',
'v', '0', '.', '9', '.', '0', '/',
//#if PIV_SUPPORT_RSA
'R',
//#endif
//#if PIV_SUPPORT_EC
'E',
//#endif
//#if PIV_SUPPORT_ECCP384
'e',
//#endif
//#if PIV_STRICT_CONTACTLESS
'S',
//#endif
//#if YKPIV_ATTESTATION
'A',
//#endif
//#if APPLET_EXTLEN
'x',
//#endif
//#if APPLET_LOW_TRANSIENT
'L',
//#endif
//#if APPLET_USE_RESET_MEM
'r',
//#endif
//#if PIV_SUPPORT_AES
'a',
//#endif
//#if PIV_SUPPORT_3DES
'D',
//#endif
};
private static final byte[] APP_URI = {
'g', 'i', 't', 'h', 'u', 'b', '.', 'c', 'o', 'm', '/',
'a', 'r', 'e', 'k', 'i', 'n', 'a', 't', 'h', '/',
'P', 'i', 'v', 'A', 'p', 'p', 'l', 'e', 't'
};
private static final byte[] DEFAULT_ADMIN_KEY = {
(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
(byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08,
(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
(byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08,
(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
(byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08
};
private static final byte[] DEFAULT_PIN = {
'1', '2', '3', '4', '5', '6', (byte)0xFF, (byte)0xFF
};
private static final byte[] DEFAULT_PUK = {
'1', '2', '3', '4', '5', '6', '7', '8'
};
private static final byte[] CARD_ID_FIXED = {
/* GSC-RID: GSC-IS data model */
(byte)0xa0, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x16,
/* Manufacturer: ff (unknown) */
(byte)0xff,
/* Card type: JavaCard */
(byte)0x02
};
private static final byte[] YKPIV_VERSION = {
(byte)5, (byte)4, (byte)0
};
/* Standard PIV commands we support. */
private static final byte INS_VERIFY = (byte)0x20;
private static final byte INS_CHANGE_PIN = (byte)0x24;
private static final byte INS_RESET_PIN = (byte)0x2C;
private static final byte INS_GEN_AUTH = (byte)0x87;
private static final byte INS_GET_DATA = (byte)0xCB;
private static final byte INS_PUT_DATA = (byte)0xDB;
private static final byte INS_GEN_ASYM = (byte)0x47;
private static final byte INS_GET_RESPONSE = (byte)0xC0;
/* YubicoPIV extensions we support. */
private static final byte INS_SET_MGMT = (byte)0xff;
private static final byte INS_IMPORT_ASYM = (byte)0xfe;
private static final byte INS_GET_VER = (byte)0xfd;
private static final byte INS_RESET = (byte)0xfb;
private static final byte INS_SET_PIN_RETRIES = (byte)0xfa;
private static final byte INS_ATTEST = (byte)0xf9;
private static final byte INS_GET_SERIAL = (byte)0xf8;
private static final byte INS_GET_MDATA = (byte)0xf7;
/* Our own private extensions. */
private static final byte INS_SG_DEBUG = (byte)0xe0;
/* ASSERT: tag.end() was called but tag has bytes left. */
protected static final short SW_TAG_END_ASSERT = (short)0x6F60;
protected static final short SW_DATA_END_ASSERT = (short)0x6F63;
/* ASSERT: SGList#startReserve() ran out of Buffers. */
protected static final short SW_RESERVE_FAILURE = (short)0x6F61;
/* ASSERT: SGList#skip */
protected static final short SW_SKIPPED_OVER_WPTR = (short)0x6F62;
/* ASSERT: TransientBuffer#write, SGList#writes */
protected static final short SW_WRITE_OVER_END = (short)0x6F65;
protected static final short SW_BAD_REWRITE = (short)0x6F64;
private static final boolean USE_EXT_LEN = false;
private BufferManager bufmgr = null;
private SGList incoming = null;
private SGList outgoing = null;
private APDUStream apduStream = null;
private TransientBuffer tempBuf = null;
private TransientBuffer outBuf = null;
private short outgoingLe = 0;
private byte[] challenge = null;
private boolean[] chalValid = null;
private byte[] iv = null;
private byte[] certSerial = null;
private byte[] guid = null;
private byte[] cardId = null;
private byte[] serial = null;
private byte[] fascn = null;
private byte[] expiry = null;
private TlvReader tlv = null;
private TlvWriter wtlv = null;
private OwnerPIN pivPin = null;
private OwnerPIN pukPin = null;
private boolean pivPinIsDefault = true;
private boolean pukPinIsDefault = true;
private boolean mgmtKeyIsDefault = true;
private byte pinRetries;
private byte pukRetries;
private RandomData randData = null;
private Cipher tripleDes = null;
private Cipher aes = null;
private Cipher rsaPkcs1 = null;
private Signature ecdsaSha = null;
private Signature ecdsaSha256 = null;
private Signature ecdsaSha384 = null;
private Signature rsaSha = null;
private Signature rsaSha256 = null;
private KeyAgreement ecdh = null;
private KeyAgreement ecdhSha = null;
private static final byte MAX_SLOTS = (byte)17;
private static final byte SLOT_9A = (byte)0;
private static final byte SLOT_9B = (byte)1;
private static final byte SLOT_9C = (byte)2;
private static final byte SLOT_9D = (byte)3;
private static final byte SLOT_9E = (byte)4;
private static final byte SLOT_82 = (byte)5;
private static final byte SLOT_8C = (byte)15;
private static final byte SLOT_F9 = (byte)16;
private PivSlot[] slots = null;
private byte retiredKeys = 0;
private static final byte SLOT_MIN_HIST = SLOT_82;
private static final byte MIN_HIST_SLOT = (byte)0x82;
private static final byte MAX_HIST_SLOT = (byte)0x8C;
private static final byte PIV_ALG_DEFAULT = (byte)0x00;
private static final byte PIV_ALG_3DES = (byte)0x03;
private static final byte PIV_ALG_RSA1024 = (byte)0x06;
private static final byte PIV_ALG_RSA2048 = (byte)0x07;
private static final byte PIV_ALG_AES128 = (byte)0x08;
private static final byte PIV_ALG_AES192 = (byte)0x0A;
private static final byte PIV_ALG_AES256 = (byte)0x0C;
private static final byte PIV_ALG_ECCP256 = (byte)0x11;
private static final byte PIV_ALG_ECCP384 = (byte)0x14;
private static final byte GA_TAG_WITNESS = (byte)0x80;
private static final byte GA_TAG_CHALLENGE = (byte)0x81;
private static final byte GA_TAG_RESPONSE = (byte)0x82;
private static final byte GA_TAG_EXP = (byte)0x85;
private static final byte TAG_CERT_9E = (byte)0x01;
private static final byte TAG_CHUID = (byte)0x02;
private static final byte TAG_FINGERPRINTS = (byte)0x03;
private static final byte TAG_CERT_9A = (byte)0x05;
private static final byte TAG_SECOBJ = (byte)0x06;
private static final byte TAG_CARDCAP = (byte)0x07;
private static final byte TAG_FACE = (byte)0x08;
private static final byte TAG_PRINTED_INFO = (byte)0x09;
private static final byte TAG_CERT_9C = (byte)0x0A;
private static final byte TAG_CERT_9D = (byte)0x0B;
private static final byte TAG_KEYHIST = (byte)0x0C;
private static final byte TAG_CERT_82 = (byte)0x0D;
private static final byte TAG_CERT_8C = (byte)0x17;
private static final byte TAG_MAX = TAG_CERT_8C;
private File[] files = null;
private static final byte TAG_YK_PIVMAN = (byte)0x00;
private static final byte TAG_YK_ATTEST = (byte)0x01;
private static final byte YK_TAG_MAX = TAG_YK_ATTEST;
private File[] ykFiles = null;
private static final byte ALG_EC_SVDP_DH_PLAIN = (byte)3;
private static final byte ALG_EC_SVDP_DHC_PLAIN = (byte)4;
private static final byte ALG_EC_SVDP_DH_PLAIN_XY = (byte)6;
private static final byte ALG_RSA_SHA_256_PKCS1 = (byte)40;
public static void
install(byte[] info, short off, byte len)
{
final PivApplet applet = new PivApplet();
applet.register();
}
/*#if APPLET_USE_RESET_MEM
private static final boolean useResetMem = true;
#else*/
private static final boolean useResetMem = false;
//#endif
protected
PivApplet()
{
randData = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
//#if PIV_SUPPORT_3DES
tripleDes = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
//#endif
//#if PIV_SUPPORT_AES
aes = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD,
false);
//#endif
//#if PIV_SUPPORT_RSA
rsaPkcs1 = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, useResetMem);
//#if YKPIV_ATTESTATION
try {
rsaSha = Signature.getInstance(
Signature.ALG_RSA_SHA_PKCS1, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() != CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
try {
rsaSha256 = Signature.getInstance(
ALG_RSA_SHA_256_PKCS1, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() != CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
//#endif
//#endif
//#if PIV_SUPPORT_EC
try {
ecdh = KeyAgreement.getInstance(ALG_EC_SVDP_DH_PLAIN,
useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() != CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
if (ecdh == null) {
try {
ecdh = KeyAgreement.getInstance(
ALG_EC_SVDP_DHC_PLAIN, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() !=
CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
}
if (ecdh == null) {
try {
ecdh = KeyAgreement.getInstance(
ALG_EC_SVDP_DH_PLAIN_XY, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() !=
CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
}
if (ecdh == null) {
try {
ecdhSha = KeyAgreement.getInstance(
KeyAgreement.ALG_EC_SVDP_DH, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() !=
CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
}
try {
ecdsaSha = Signature.getInstance(
Signature.ALG_ECDSA_SHA, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() != CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
try {
ecdsaSha256 = Signature.getInstance(
ECParams.ALG_ECDSA_SHA_256, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() != CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
//#if PIV_SUPPORT_ECCP384
try {
ecdsaSha384 = Signature.getInstance(
ECParams.ALG_ECDSA_SHA_384, useResetMem);
} catch (CryptoException ex) {
if (ex.getReason() != CryptoException.NO_SUCH_ALGORITHM)
throw (ex);
}
//#endif
//#endif
challenge = JCSystem.makeTransientByteArray((short)16,
JCSystem.CLEAR_ON_DESELECT);
chalValid = JCSystem.makeTransientBooleanArray((short)1,
JCSystem.CLEAR_ON_DESELECT);
iv = JCSystem.makeTransientByteArray((short)16,
JCSystem.CLEAR_ON_DESELECT);
guid = new byte[16];
randData.generateData(guid, (short)0, (short)16);
cardId = new byte[21];
Util.arrayCopy(CARD_ID_FIXED, (short)0, cardId, (short)0,
(short)CARD_ID_FIXED.length);
randData.generateData(cardId, (short)CARD_ID_FIXED.length,
(short)(21 - (short)CARD_ID_FIXED.length));
serial = new byte[4];
randData.generateData(serial, (short)0, (short)4);
serial[0] |= (byte)0x80;
certSerial = new byte[16];
fascn = new byte[25];
expiry = new byte[] { '2', '0', '5', '0', '0', '1', '0', '1' };
slots = new PivSlot[MAX_SLOTS];
for (byte i = SLOT_9A; i <= SLOT_9E; ++i)
slots[i] = new PivSlot((byte)((byte)0x9A + i));
for (byte i = SLOT_82; i <= SLOT_8C; ++i)
slots[i] = new PivSlot((byte)((byte)0x82 + i));
//#if YKPIV_ATTESTATION
slots[SLOT_F9] = new PivSlot((byte)0xF9);
//#endif
files = new File[TAG_MAX + 1];
ykFiles = new File[YK_TAG_MAX + 1];
bufmgr = new BufferManager();
incoming = new SGList(bufmgr);
outgoing = new SGList(bufmgr);
apduStream = new APDUStream();
tempBuf = new TransientBuffer();
outBuf = new TransientBuffer();
tlv = new TlvReader();
wtlv = new TlvWriter(bufmgr);
/* Initialize the admin key */
//#if PIV_SUPPORT_3DES
final DESKey dk = (DESKey)KeyBuilder.buildKey(
KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
slots[SLOT_9B].sym = dk;
dk.setKey(DEFAULT_ADMIN_KEY, (short)0);
slots[SLOT_9B].symAlg = PIV_ALG_3DES;
/*#else
final AESKey ak = (AESKey)KeyBuilder.buildKey(
KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_192, false);
slots[SLOT_9B].sym = ak;
ak.setKey(DEFAULT_ADMIN_KEY, (short)0);
slots[SLOT_9B].symAlg = PIV_ALG_AES192;
#endif*/
/*
* Allow the admin key to be "used" (for auth) without a
* PIN VERIFY command first.
*/
slots[SLOT_9B].pinPolicy = PivSlot.P_NEVER;
pinRetries = (byte)5;
pivPin = new OwnerPIN(pinRetries, (byte)8);
pivPin.update(DEFAULT_PIN, (short)0, (byte)8);
pukRetries = (byte)3;
pukPin = new OwnerPIN(pukRetries, (byte)8);
pukPin.update(DEFAULT_PUK, (short)0, (byte)8);
files[TAG_CERT_9A] = new File();
slots[SLOT_9A].cert = files[TAG_CERT_9A];
files[TAG_CERT_9C] = new File();
slots[SLOT_9C].cert = files[TAG_CERT_9C];
slots[SLOT_9C].pinPolicy = PivSlot.P_ALWAYS;
files[TAG_CERT_9D] = new File();
slots[SLOT_9D].cert = files[TAG_CERT_9D];
files[TAG_CERT_9E] = new File();
slots[SLOT_9E].cert = files[TAG_CERT_9E];
slots[SLOT_9E].pinPolicy = PivSlot.P_NEVER;
files[TAG_FINGERPRINTS] = new File();
files[TAG_FINGERPRINTS].contact = File.P_PIN;
files[TAG_FACE] = new File();
files[TAG_FACE].contact = File.P_PIN;
files[TAG_PRINTED_INFO] = new File();
files[TAG_PRINTED_INFO].contact = File.P_PIN;
//#if YKPIV_ATTESTATION
ykFiles[TAG_YK_ATTEST] = new File();
slots[SLOT_F9].cert = ykFiles[TAG_YK_ATTEST];
//#endif
//#if PIV_STRICT_CONTACTLESS
files[TAG_CERT_9A].contactless = File.P_NEVER;
files[TAG_CERT_9C].contactless = File.P_NEVER;
files[TAG_CERT_9D].contactless = File.P_NEVER;
files[TAG_FINGERPRINTS].contactless = File.P_NEVER;
files[TAG_PRINTED_INFO].contactless = File.P_PIN;
files[TAG_FACE].contactless = File.P_PIN;
//#endif
initCARDCAP();
initCHUID();
initKEYHIST();
//#if YKPIV_ATTESTATION
initAttestation();
//#endif
}
public void
process(APDU apdu)
{
final byte[] buffer = apdu.getBuffer();
final byte ins = buffer[ISO7816.OFFSET_INS];
final byte chainBit =
(byte)(buffer[ISO7816.OFFSET_CLA] & (byte)0x10);
//#if APPLET_EXTLEN
if (!apdu.isISOInterindustryCLA()) {
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
return;
}
/*#else
final byte isoInterBit =
(byte)(buffer[ISO7816.OFFSET_CLA] & (byte)0x80);
if (isoInterBit != 0) {
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
return;
}
#endif*/
if (selectingApplet()) {
sendSelectResponse(apdu);
return;
}
/*
* Slots that are marked as "PIN always" only work when the
* APDU directly before them was VERIFY.
*
* If we process any other type of APDU, we set the flag
* AFTER_VERIFY and then before the next APDU we lock them
* here. The VERIFY command unsets the flag.
*/
if (chainBit == 0)
lockPINAlwaysSlots();
switch (ins) {
case INS_GET_DATA:
processGetData(apdu);
break;
case INS_GEN_AUTH:
processGeneralAuth(apdu);
break;
case INS_PUT_DATA:
processPutData(apdu);
break;
case INS_CHANGE_PIN:
processChangePin(apdu);
break;
case INS_VERIFY:
processVerify(apdu);
break;
case INS_GEN_ASYM:
processGenAsym(apdu);
break;
case INS_RESET_PIN:
processResetPin(apdu);
break;
case INS_SET_PIN_RETRIES:
processSetPinRetries(apdu);
break;
case INS_RESET:
processReset(apdu);
break;
case INS_GET_VER:
processGetVersion(apdu);
break;
case INS_IMPORT_ASYM:
processImportAsym(apdu);
break;
case INS_SET_MGMT:
processSetMgmtKey(apdu);
break;
case INS_SG_DEBUG:
processSGDebug(apdu);
break;
case INS_GET_RESPONSE:
continueResponse(apdu);
break;
//#if YKPIV_ATTESTATION
case INS_ATTEST:
processAttest(apdu);
break;
//#endif
case INS_GET_SERIAL:
processGetSerial(apdu);
break;
case INS_GET_MDATA:
processGetMetadata(apdu);
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private boolean
isContact()
{
final byte media = (byte)(
APDU.getProtocol() & APDU.PROTOCOL_MEDIA_MASK);
if (media == APDU.PROTOCOL_MEDIA_DEFAULT)
return (true);
if (media == APDU.PROTOCOL_MEDIA_USB)
return (true);
return (false);
}
/*#if !APPLET_EXTLEN
private short
getIncomingLengthCompat(final APDU apdu)
{
final byte[] buf = apdu.getBuffer();
return ((short)((short)buf[ISO7816.OFFSET_LC] & 0x00FF));
}
#endif*/
private void
lockPINAlwaysSlots()
{
for (short idx = (short)0; idx < MAX_SLOTS; ++idx) {
final PivSlot slot = slots[idx];
if (slot == null)
continue;
if (slot.pinPolicy != PivSlot.P_ALWAYS)
continue;
if (slot.flags[PivSlot.F_UNLOCKED] &&
slot.flags[PivSlot.F_AFTER_VERIFY]) {
slot.flags[PivSlot.F_UNLOCKED] = false;
} else if (slot.flags[PivSlot.F_UNLOCKED]) {
slot.flags[PivSlot.F_AFTER_VERIFY] = true;
}
}
}
private void
processGetVersion(APDU apdu)
{
short len = 0;
final short le;
final byte[] buffer = apdu.getBuffer();
le = apdu.setOutgoing();
buffer[len++] = YKPIV_VERSION[0];
buffer[len++] = YKPIV_VERSION[1];
buffer[len++] = YKPIV_VERSION[2];
len = le > 0 ? (le > len ? len : le) : len;
apdu.setOutgoingLength(len);
apdu.sendBytes((short)0, len);
}
private void
processGetSerial(APDU apdu)
{
short len = 0;
final short le;
final byte[] buffer = apdu.getBuffer();
le = apdu.setOutgoing();
buffer[len++] = serial[0];
buffer[len++] = serial[1];
buffer[len++] = serial[2];
buffer[len++] = serial[3];
len = le > 0 ? (le > len ? len : le) : len;
apdu.setOutgoingLength(len);
apdu.sendBytes((short)0, len);
}
private void
processGetMetadata(APDU apdu)
{
final byte[] buffer = apdu.getBuffer();
final byte key = buffer[ISO7816.OFFSET_P2];
final PivSlot slot;
// PIN_P2 || PUK_P2
if (key == (byte)0x80 || key == (byte)0x81) {
outgoing.reset();
wtlv.start(outgoing);
outgoingLe = apdu.setOutgoing();
wtlv.useApdu((short)0, outgoingLe);
// Tag 0x05, one byte, whether the PIN or PUK is default
wtlv.writeTagRealLen((byte)0x05, (short)1);
if (key == (byte)0x80 && pivPinIsDefault)
wtlv.writeByte((byte)1);
else if (key == (byte)0x81 && pukPinIsDefault)
wtlv.writeByte((byte)1);
else
wtlv.writeByte((byte)0);
// Tag 0x06, two bytes, [total number of retries] [remaining retries]
wtlv.writeTagRealLen((byte)0x06, (short)2);
if (key == (byte)0x80) {
wtlv.writeByte(pinRetries);
wtlv.writeByte(pivPin.getTriesRemaining());
} else if (key == (byte)0x81) {
wtlv.writeByte(pukRetries);
wtlv.writeByte(pukPin.getTriesRemaining());
}
wtlv.end();
sendOutgoing(apdu);
return;
}
if (key >= (byte)0x9A && key <= (byte)0x9E) {
final byte idx = (byte)(key - (byte)0x9A);
slot = slots[idx];
} else if (key >= MIN_HIST_SLOT && key <= MAX_HIST_SLOT) {
final byte idx = (byte)(SLOT_MIN_HIST +
(byte)(key - MIN_HIST_SLOT));
slot = slots[idx];
} else {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
return;
}
if (slot == null) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
return;
}
if (buffer[ISO7816.OFFSET_P1] != (byte)0x00) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
return;
}
outgoing.reset();
wtlv.start(outgoing);
outgoingLe = apdu.setOutgoing();
wtlv.useApdu((short)0, outgoingLe);
// Tag 0x01, one byte, [algo]
if (slot.asym != null) {
wtlv.writeTagRealLen((byte)0x01, (short)1);
wtlv.writeByte(slot.asymAlg);
} else if (slot.sym != null) {
wtlv.writeTagRealLen((byte)0x01, (short)1);
wtlv.writeByte(slot.symAlg);
}
if (key == (byte)0x9B) {
// Tag 0x05, one byte, whether the management key is default
wtlv.writeTagRealLen((byte)0x05, (short)1);
if (mgmtKeyIsDefault)
wtlv.writeByte((byte)1);
else
wtlv.writeByte((byte)0);
}
// Tag 0x02, two bytes, PIN and touch policy (never)
wtlv.writeTagRealLen((byte)0x02, (short)2);
wtlv.writeByte(slot.pinPolicy);
wtlv.writeByte((byte)0x01);
wtlv.writeTagRealLen((byte)0x03, (short)1);
if (slot.imported)
wtlv.writeByte((byte)1);
else
wtlv.writeByte((byte)0);
if (slot.asym != null) {
short len;
switch (slot.asymAlg) {
//#if PIV_SUPPORT_RSA
case PIV_ALG_RSA1024:
case PIV_ALG_RSA2048:
RSAPublicKey rpubk =
(RSAPublicKey)slot.asym.getPublic();
final short rsalen = (short)(rpubk.getSize() / 8);
wtlv.push((byte)0x04, (short)(rsalen + 12));
wtlv.push((byte)0x81, (short)(rsalen + 1));
wtlv.startReserve((short)(rsalen + 1), tempBuf);
len = rpubk.getModulus(tempBuf.data(), tempBuf.wpos());
wtlv.endReserve(len);
wtlv.pop();
wtlv.push((byte)0x82);
wtlv.startReserve((short)9, tempBuf);
len = rpubk.getExponent(tempBuf.data(), tempBuf.wpos());
wtlv.endReserve(len);
wtlv.pop();
break;
//#endif
//#if PIV_SUPPORT_EC
case PIV_ALG_ECCP256:
case PIV_ALG_ECCP384:
ECPublicKey epubk =
(ECPublicKey)slot.asym.getPublic();
final short eclen = (short)(epubk.getSize() / 2);
wtlv.push((byte)0x04, (short)(eclen + 4));
wtlv.push((byte)0x86, (short)(eclen + 1));
wtlv.startReserve((short)(eclen + 1), tempBuf);
len = epubk.getW(tempBuf.data(), tempBuf.wpos());
wtlv.endReserve(len);
wtlv.pop();
break;
//#endif
default:
return;
}
wtlv.pop();
}
wtlv.end();
sendOutgoing(apdu);
return;
}
//#if YKPIV_ATTESTATION
private void
processAttest(APDU apdu)
{
final byte[] buffer = apdu.getBuffer();
final byte key = buffer[ISO7816.OFFSET_P1];
final PivSlot slot;
if (key >= (byte)0x9A && key <= (byte)0x9E) {
final byte idx = (byte)(key - (byte)0x9A);
slot = slots[idx];
} else if (key >= MIN_HIST_SLOT && key <= MAX_HIST_SLOT) {
final byte idx = (byte)(SLOT_MIN_HIST +
(byte)(key - MIN_HIST_SLOT));
slot = slots[idx];
} else {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
return;
}
if (slot == null) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
return;
}
if (buffer[ISO7816.OFFSET_P2] != (byte)0x00) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
return;
}
writeAttestationCert(slot);
sendOutgoing(apdu);
}
//#endif
private void
processSGDebug(APDU apdu)
{
short len = (short)0;
final short le;
final byte[] buffer = apdu.getBuffer();
le = apdu.setOutgoing();
len = incoming.writeDebugInfo(buffer, len);
len = le > 0 ? (le > len ? len : le) : len;
apdu.setOutgoingLength(len);
apdu.sendBytes((short)0, len);
}
private void
pushAlgorithm(byte algid)
{
wtlv.push((byte)0xAC);
wtlv.writeTagRealLen((byte)0x80, (short)1);
wtlv.writeByte(algid);
/*
* SP 800-83-4 part 2, 3.1 says: "Its value is set to 0x00"
* regarding this 0x06 tag. Previous PivApplet releases
* interpreted this as an empty 0x06 tag with no contents
* (length = 0), but it seems more logical that it should
* contain a single zero byte.
*/
wtlv.writeTagRealLen((byte)0x06, (short)1);
wtlv.writeByte((byte)0x00);
wtlv.pop();
}
private void
sendSelectResponse(APDU apdu)
{
outgoing.reset();
wtlv.start(outgoing);
outgoingLe = apdu.setOutgoing();
wtlv.useApdu((short)0, outgoingLe);
wtlv.push256((byte)0x61);
wtlv.writeTagRealLen((byte)0x4F, (short)PIV_AID.length);
wtlv.write(PIV_AID, (short)0, (short)PIV_AID.length);
/*
* The NIST demo cards only return the first 5 bytes of the AID
* here (the NIST RID). The spec is not especially explicit
* about it, but we'll go with that.
*/
wtlv.push((byte)0x79);
wtlv.writeTagRealLen((byte)0x4F, (short)5);
wtlv.write(PIV_AID, (short)0, (short)5);
wtlv.pop();
wtlv.writeTagRealLen((byte)0x50, (short)APP_NAME.length);
wtlv.write(APP_NAME, (short)0, (short)APP_NAME.length);
wtlv.writeTagRealLen((short)0x5F50, (short)APP_URI.length);
wtlv.write(APP_URI, (short)0, (short)APP_URI.length);
/*
* Small spec divergence: PIV doesn't require us to list all
* of the algorithms we support here in 'AC' '80' tags. We
* do, though, so that client impls specifically aware of
* PivApplet can work out which ones this build/card supports.
*
* Normally, this 'AC' tags would be expected to only contain
* any supported PIV SM algorihtms. The specs allow multiple
* 'AC' tags, however, and don't seem to explicitly outlaw
* what we're doing.
*
* If we eventually support PIV SM, we should put the SM algos
* first here so that client/middlware impls which stop at the
* first 'AC' tag correctly find our SM algo.
*/
//#if PIV_SUPPORT_3DES
pushAlgorithm(PIV_ALG_3DES);
//#endif
//#if PIV_SUPPORT_AES
/*
* Just write AES256 to indicate AES support. No need to be
* too verbose.
*/
pushAlgorithm(PIV_ALG_AES256);
//#endif
//#if PIV_SUPPORT_RSA
/*
* Similar to AES, just write RSA2048 if we support RSA. Let
* RSA1024 support be implied.
*/
pushAlgorithm(PIV_ALG_RSA2048);
//#endif
//#if PIV_SUPPORT_EC
if (ecdsaSha != null || ecdsaSha256 != null) {
pushAlgorithm(PIV_ALG_ECCP256);
}
if (ecdsaSha384 != null) {
pushAlgorithm(PIV_ALG_ECCP384);
}
//#endif
wtlv.pop();
wtlv.end();
sendOutgoing(apdu);
}
private void
sendOutgoing(APDU apdu)
{
final short len = outgoing.available();
if (len < 1) {
ISOException.throwIt(
ISO7816.SW_CONDITIONS_NOT_SATISFIED);
return;
}
final short le;
if (apdu.getCurrentState() == APDU.STATE_OUTGOING)
le = outgoingLe;
else
le = apdu.setOutgoing();
short toSend = len;
if (le > 0 && toSend > le)
toSend = le;
if (toSend > (short)0xFF)
toSend = (short)0xFF;
final short rem = (short)(len - toSend);
final byte wantNext =
rem > (short)0xFF ? (byte)0xFF : (byte)rem;
apdu.setOutgoingLength(toSend);
outgoing.readToApdu((short)0, toSend);
apdu.sendBytes((short)0, toSend);
if (rem > 0) {
ISOException.throwIt(
(short)(ISO7816.SW_BYTES_REMAINING_00 |
((short)wantNext & (short)0x00ff)));
} else {
outgoing.reset();
ISOException.throwIt(ISO7816.SW_NO_ERROR);
}
}
private void
continueResponse(APDU apdu)
{
sendOutgoing(apdu);
}
private Readable
receiveChain(APDU apdu)
{
final byte[] buf = apdu.getBuffer();
final byte chainBit =