aboutsummaryrefslogtreecommitdiff
path: root/ready_se/google/keymint/KM300/Applet/src/com/android/javacard/keymaster/KMKeymintDataStore.java
blob: 65117ebb4141a6562dd9e1ae04ba4ec384480869 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
package com.android.javacard.keymaster;

import com.android.javacard.seprovider.KMDataStoreConstants;
import com.android.javacard.seprovider.KMException;
import com.android.javacard.seprovider.KMKey;
import com.android.javacard.seprovider.KMSEProvider;
import com.android.javacard.seprovider.KMUpgradable;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.Util;
import org.globalplatform.upgrade.Element;

/**
 * This is a storage class which helps in storing the provisioned data, ROT, OS version, Boot patch
 * level, Vendor Patchlevel, HMAC nonce, computed shared secret, 8 auth tags, device-locked,
 * device-locked timestamp and device-locked password only. Only the provisioned data is restored
 * back during applet upgrades and the remaining data is flushed.
 */
public class KMKeymintDataStore implements KMUpgradable {

  // Data table configuration
  public static final short KM_APPLET_PACKAGE_VERSION_1 = 0x0100;
  public static final short KM_APPLET_PACKAGE_VERSION_2 = 0x0200;
  public static final short KM_APPLET_PACKAGE_VERSION_3 = 0x0300;
  public static final short KM_APPLET_PACKAGE_VERSION_4 = 0x0400;
  public static final byte DATA_INDEX_SIZE = 17;
  public static final byte DATA_INDEX_ENTRY_SIZE = 4;
  public static final byte DATA_INDEX_ENTRY_LENGTH = 0;
  public static final byte DATA_INDEX_ENTRY_OFFSET = 2;
  public static final short DATA_MEM_SIZE = 300;
  // Data table offsets
  public static final byte HMAC_NONCE = 0;
  public static final byte BOOT_OS_VERSION = 1;
  public static final byte BOOT_OS_PATCH_LEVEL = 2;
  public static final byte VENDOR_PATCH_LEVEL = 3;
  public static final byte DEVICE_LOCKED_TIME = 4;
  public static final byte DEVICE_LOCKED = 5;
  public static final byte DEVICE_LOCKED_PASSWORD_ONLY = 6;
  // Total 8 auth tags, so the next offset is AUTH_TAG_1 + 8
  public static final byte AUTH_TAG_1 = 7;
  public static final byte DEVICE_STATUS_FLAG = 15;
  public static final byte EARLY_BOOT_ENDED_FLAG = 16;
  // Data Item sizes
  public static final byte HMAC_SEED_NONCE_SIZE = 32;
  public static final byte COMPUTED_HMAC_KEY_SIZE = 32;
  public static final byte OS_VERSION_SIZE = 4;
  public static final byte OS_PATCH_SIZE = 4;
  public static final byte VENDOR_PATCH_SIZE = 4;
  public static final byte DEVICE_LOCK_TS_SIZE = 8;
  public static final byte MAX_BLOB_STORAGE = 8;
  public static final byte AUTH_TAG_LENGTH = 16;
  public static final byte AUTH_TAG_COUNTER_SIZE = 4;
  public static final byte AUTH_TAG_ENTRY_SIZE = (AUTH_TAG_LENGTH + AUTH_TAG_COUNTER_SIZE + 1);
  // Device boot states. Applet starts executing the
  // core commands once all the states are set. The commands
  // that are allowed irrespective of these states are:
  // All the provision commands
  // INS_GET_HW_INFO_CMD
  // INS_ADD_RNG_ENTROPY_CMD
  // INS_COMPUTE_SHARED_HMAC_CMD
  // INS_GET_HMAC_SHARING_PARAM_CMD
  public static final byte SET_BOOT_PARAMS_SUCCESS = 0x01;
  public static final byte SET_SYSTEM_PROPERTIES_SUCCESS = 0x02;
  public static final byte NEGOTIATED_SHARED_SECRET_SUCCESS = 0x04;
  // Old Data table offsets
  private static final byte OLD_PROVISIONED_STATUS_OFFSET = 18;
  private static final byte SHARED_SECRET_KEY_SIZE = 32;
  private static final byte DEVICE_STATUS_FLAG_SIZE = 1;
  private static final short UDS_CERT_CHAIN_MAX_SIZE = 2500; // First 2 bytes for length.
  private static final short DICE_CERT_CHAIN_MAX_SIZE = 512;
  private static KMKeymintDataStore kmDataStore;
  // Secure Boot Mode
  public byte secureBootMode;
  // Data - originally was in repository
  private byte[] attIdBrand;
  private byte[] attIdDevice;
  private byte[] attIdProduct;
  private byte[] attIdSerial;
  private byte[] attIdImei;
  private byte[] attIdSecondImei;
  private byte[] attIdMeId;
  private byte[] attIdManufacturer;
  private byte[] attIdModel;
  // Boot parameters
  private byte[] verifiedHash;
  private byte[] bootKey;
  private byte[] bootPatchLevel;
  private boolean deviceBootLocked;
  private short bootState;
  // Challenge for Root of trust
  private byte[] challenge;

  /*
   * Applets upgrading to KeyMint3.0 may not have the second imei provisioned.
   * So this flag is used to ignore the SECOND_IMEI tag if the previous Applet's
   * KeyMint version is less than 3.0.
   */
  public boolean ignoreSecondImei;
  private short dataIndex;
  private byte[] dataTable;
  private KMSEProvider seProvider;
  private KMRepository repository;
  private byte[] udsCertChain;
  private byte[] diceCertChain;
  private KMKey masterKey;
  private KMKey deviceUniqueKeyPair;
  private KMKey preSharedKey;
  private KMKey computedHmacKey;
  private KMKey rkpMacKey;
  private byte[] oemRootPublicKey;
  private short provisionStatus;

  public KMKeymintDataStore(KMSEProvider provider, KMRepository repo) {
    seProvider = provider;
    repository = repo;
    boolean isUpgrading = provider.isUpgrading();
    initDataTable();
    // Initialize the device locked status
    if (!isUpgrading) {
      udsCertChain = new byte[UDS_CERT_CHAIN_MAX_SIZE];
      diceCertChain = new byte[DICE_CERT_CHAIN_MAX_SIZE];
      oemRootPublicKey = new byte[65];
    }
    setDeviceLockPasswordOnly(false);
    setDeviceLock(false);
    kmDataStore = this;
  }

  public static KMKeymintDataStore instance() {
    return kmDataStore;
  }

  private void initDataTable() {
    if (dataTable == null) {
      dataTable = new byte[DATA_MEM_SIZE];
      dataIndex = (short) (DATA_INDEX_SIZE * DATA_INDEX_ENTRY_SIZE);
    }
  }

  private short dataAlloc(short length) {
    if (((short) (dataIndex + length)) > dataTable.length) {
      ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    dataIndex += length;
    return (short) (dataIndex - length);
  }

  private void clearDataEntry(short id) {
    id = (short) (id * DATA_INDEX_ENTRY_SIZE);
    short dataLen = Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_LENGTH));
    if (dataLen != 0) {
      short dataPtr = Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_OFFSET));
      JCSystem.beginTransaction();
      Util.arrayFillNonAtomic(dataTable, dataPtr, dataLen, (byte) 0);
      JCSystem.commitTransaction();
    }
  }

  private void writeDataEntry(short id, byte[] buf, short offset, short len) {
    short dataPtr;
    id = (short) (id * DATA_INDEX_ENTRY_SIZE);
    short dataLen = Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_LENGTH));
    if (dataLen == 0) {
      dataPtr = dataAlloc(len);
      JCSystem.beginTransaction();
      Util.setShort(dataTable, (short) (id + DATA_INDEX_ENTRY_OFFSET), dataPtr);
      Util.setShort(dataTable, (short) (id + DATA_INDEX_ENTRY_LENGTH), len);
      Util.arrayCopyNonAtomic(buf, offset, dataTable, dataPtr, len);
      JCSystem.commitTransaction();
    } else {
      if (len != dataLen) {
        KMException.throwIt(KMError.UNKNOWN_ERROR);
      }
      dataPtr = Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_OFFSET));
      JCSystem.beginTransaction();
      Util.arrayCopyNonAtomic(buf, offset, dataTable, dataPtr, len);
      JCSystem.commitTransaction();
    }
  }

  private short readDataEntry(short id, byte[] buf, short offset) {
    id = (short) (id * DATA_INDEX_ENTRY_SIZE);
    short len = Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_LENGTH));
    if (len != 0) {
      Util.arrayCopyNonAtomic(
          dataTable,
          Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_OFFSET)),
          buf,
          offset,
          len);
    }
    return len;
  }

  private short readDataEntry(byte[] dataTable, short id, byte[] buf, short offset) {
    id = (short) (id * DATA_INDEX_ENTRY_SIZE);
    short len = Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_LENGTH));
    if (len != 0) {
      Util.arrayCopyNonAtomic(
          dataTable,
          Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_OFFSET)),
          buf,
          offset,
          len);
    }
    return len;
  }

  private short dataLength(short id) {
    id = (short) (id * DATA_INDEX_ENTRY_SIZE);
    return Util.getShort(dataTable, (short) (id + DATA_INDEX_ENTRY_LENGTH));
  }

  public short readData(short id) {
    short len = dataLength(id);
    if (len != 0) {
      short blob = KMByteBlob.instance(dataLength(id));
      readDataEntry(id, KMByteBlob.cast(blob).getBuffer(), KMByteBlob.cast(blob).getStartOff());
      return blob;
    }
    return KMType.INVALID_VALUE;
  }

  public short getHmacNonce() {
    return readData(HMAC_NONCE);
  }

  public short getOsVersion() {
    short blob = readData(BOOT_OS_VERSION);
    if (blob == KMType.INVALID_VALUE) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return KMInteger.uint_32(
        KMByteBlob.cast(blob).getBuffer(), KMByteBlob.cast(blob).getStartOff());
  }

  public short getVendorPatchLevel() {
    short blob = readData(VENDOR_PATCH_LEVEL);
    if (blob == KMType.INVALID_VALUE) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return KMInteger.uint_32(
        KMByteBlob.cast(blob).getBuffer(), KMByteBlob.cast(blob).getStartOff());
  }

  public short getOsPatch() {
    short blob = readData(BOOT_OS_PATCH_LEVEL);
    if (blob == KMType.INVALID_VALUE) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return KMInteger.uint_32(
        KMByteBlob.cast(blob).getBuffer(), KMByteBlob.cast(blob).getStartOff());
  }

  private boolean readBoolean(short id) {
    short blob = readData(id);
    if (blob == KMType.INVALID_VALUE) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return (byte) ((repository.getHeap())[KMByteBlob.cast(blob).getStartOff()]) == 0x01;
  }

  public boolean getDeviceLock() {
    return readBoolean(DEVICE_LOCKED);
  }

  public void setDeviceLock(boolean flag) {
    writeBoolean(DEVICE_LOCKED, flag);
  }

  public boolean getDeviceLockPasswordOnly() {
    return readBoolean(DEVICE_LOCKED_PASSWORD_ONLY);
  }

  public void setDeviceLockPasswordOnly(boolean flag) {
    writeBoolean(DEVICE_LOCKED_PASSWORD_ONLY, flag);
  }

  public boolean getEarlyBootEndedStatus() {
    return readBoolean(EARLY_BOOT_ENDED_FLAG);
  }

  public void setEarlyBootEndedStatus(boolean flag) {
    writeBoolean(EARLY_BOOT_ENDED_FLAG, flag);
  }

  public short getDeviceTimeStamp() {
    short blob = readData(DEVICE_LOCKED_TIME);
    if (blob == KMType.INVALID_VALUE) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return KMInteger.uint_64(
        KMByteBlob.cast(blob).getBuffer(), KMByteBlob.cast(blob).getStartOff());
  }

  public void setOsVersion(byte[] buf, short start, short len) {
    if (len != OS_VERSION_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    writeDataEntry(BOOT_OS_VERSION, buf, start, len);
  }

  public void setVendorPatchLevel(byte[] buf, short start, short len) {
    if (len != VENDOR_PATCH_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    writeDataEntry(VENDOR_PATCH_LEVEL, buf, start, len);
  }

  private void writeBoolean(short id, boolean flag) {
    short start = repository.alloc((short) 1);
    if (flag) {
      (repository.getHeap())[start] = (byte) 0x01;
    } else {
      (repository.getHeap())[start] = (byte) 0x00;
    }
    writeDataEntry(id, repository.getHeap(), start, (short) 1);
  }

  public void setDeviceLockTimestamp(byte[] buf, short start, short len) {
    if (len != DEVICE_LOCK_TS_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    writeDataEntry(DEVICE_LOCKED_TIME, buf, start, len);
  }

  public void clearDeviceBootStatus() {
    clearDataEntry(DEVICE_STATUS_FLAG);
  }

  public void setDeviceBootStatus(byte initStatus) {
    short offset = repository.allocReclaimableMemory(DEVICE_STATUS_FLAG_SIZE);
    byte[] buf = repository.getHeap();
    getDeviceBootStatus(buf, offset);
    buf[offset] |= initStatus;
    writeDataEntry(DEVICE_STATUS_FLAG, buf, offset, DEVICE_STATUS_FLAG_SIZE);
    repository.reclaimMemory(DEVICE_STATUS_FLAG_SIZE);
  }

  public boolean isDeviceReady() {
    boolean result = false;
    short offset = repository.allocReclaimableMemory(DEVICE_STATUS_FLAG_SIZE);
    byte[] buf = repository.getHeap();
    getDeviceBootStatus(buf, offset);
    byte bootCompleteStatus =
        (SET_BOOT_PARAMS_SUCCESS
            | SET_SYSTEM_PROPERTIES_SUCCESS
            | NEGOTIATED_SHARED_SECRET_SUCCESS);
    if (bootCompleteStatus == (buf[offset] & bootCompleteStatus)) {
      result = true;
    }
    repository.reclaimMemory(DEVICE_STATUS_FLAG_SIZE);
    return result;
  }

  public short getDeviceBootStatus(byte[] scratchpad, short offset) {
    scratchpad[offset] = 0;
    return readDataEntry(DEVICE_STATUS_FLAG, scratchpad, offset);
  }

  public void clearDeviceLockTimeStamp() {
    clearDataEntry(DEVICE_LOCKED_TIME);
  }

  public void setOsPatch(byte[] buf, short start, short len) {
    if (len != OS_PATCH_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    writeDataEntry(BOOT_OS_PATCH_LEVEL, buf, start, len);
  }

  private boolean isAuthTagSlotAvailable(short tagId, byte[] buf, short offset) {
    readDataEntry(tagId, buf, offset);
    return (0 == buf[offset]);
  }

  public void initHmacNonce(byte[] nonce, short offset, short len) {
    if (len != HMAC_SEED_NONCE_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    writeDataEntry(HMAC_NONCE, nonce, offset, len);
  }

  public void clearHmacNonce() {
    clearDataEntry(HMAC_NONCE);
  }

  public boolean persistAuthTag(short authTag) {

    if (KMByteBlob.cast(authTag).length() != AUTH_TAG_LENGTH) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }

    short authTagEntry = repository.alloc(AUTH_TAG_ENTRY_SIZE);
    short scratchPadOff = repository.alloc(AUTH_TAG_ENTRY_SIZE);
    byte[] scratchPad = repository.getHeap();
    writeAuthTagState(repository.getHeap(), authTagEntry, (byte) 1);
    Util.arrayCopyNonAtomic(
        KMByteBlob.cast(authTag).getBuffer(),
        KMByteBlob.cast(authTag).getStartOff(),
        repository.getHeap(),
        (short) (authTagEntry + 1),
        AUTH_TAG_LENGTH);
    Util.setShort(
        repository.getHeap(), (short) (authTagEntry + AUTH_TAG_LENGTH + 1 + 2), (short) 1);
    short index = 0;
    while (index < MAX_BLOB_STORAGE) {
      if ((dataLength((short) (index + AUTH_TAG_1)) == 0)
          || isAuthTagSlotAvailable((short) (index + AUTH_TAG_1), scratchPad, scratchPadOff)) {

        writeDataEntry(
            (short) (index + AUTH_TAG_1), repository.getHeap(), authTagEntry, AUTH_TAG_ENTRY_SIZE);
        return true;
      }
      index++;
    }
    return false;
  }

  public void removeAllAuthTags() {
    short index = 0;
    while (index < MAX_BLOB_STORAGE) {
      clearDataEntry((short) (index + AUTH_TAG_1));
      index++;
    }
  }

  public boolean isAuthTagPersisted(short authTag) {
    return (KMType.INVALID_VALUE != findTag(authTag));
  }

  private short findTag(short authTag) {
    if (KMByteBlob.cast(authTag).length() != AUTH_TAG_LENGTH) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    short index = 0;
    short found;
    short offset = repository.alloc(AUTH_TAG_ENTRY_SIZE);
    while (index < MAX_BLOB_STORAGE) {
      if (dataLength((short) (index + AUTH_TAG_1)) != 0) {
        readDataEntry((short) (index + AUTH_TAG_1), repository.getHeap(), offset);
        found =
            Util.arrayCompare(
                repository.getHeap(),
                (short) (offset + 1),
                KMByteBlob.cast(authTag).getBuffer(),
                KMByteBlob.cast(authTag).getStartOff(),
                AUTH_TAG_LENGTH);
        if (found == 0) {
          return (short) (index + AUTH_TAG_1);
        }
      }
      index++;
    }
    return KMType.INVALID_VALUE;
  }

  public short getRateLimitedKeyCount(short authTag, byte[] out, short outOff) {
    short tag = findTag(authTag);
    short blob;
    if (tag != KMType.INVALID_VALUE) {
      blob = readData(tag);
      Util.arrayCopyNonAtomic(
          KMByteBlob.cast(blob).getBuffer(),
          (short) (KMByteBlob.cast(blob).getStartOff() + AUTH_TAG_LENGTH + 1),
          out,
          outOff,
          AUTH_TAG_COUNTER_SIZE);
      return AUTH_TAG_COUNTER_SIZE;
    }
    return (short) 0;
  }

  public void setRateLimitedKeyCount(short authTag, byte[] buf, short off, short len) {
    short tag = findTag(authTag);
    if (tag != KMType.INVALID_VALUE) {
      short dataPtr = readData(tag);
      Util.arrayCopyNonAtomic(
          buf,
          off,
          KMByteBlob.cast(dataPtr).getBuffer(),
          (short) (KMByteBlob.cast(dataPtr).getStartOff() + AUTH_TAG_LENGTH + 1),
          len);
      writeDataEntry(
          tag,
          KMByteBlob.cast(dataPtr).getBuffer(),
          KMByteBlob.cast(dataPtr).getStartOff(),
          KMByteBlob.cast(dataPtr).length());
    }
  }

  public void persistUdsCertChain(byte[] buf, short offset, short len) {
    // Input buffer contains encoded Uds certificate chain as shown below.
    //    UdsDKSignatures = {
    //      + SignerName => DKCertChain
    //    }
    //    SignerName = tstr
    //    DKCertChain = [
    //      2* Certificate // Root -> Leaf. Root is the vendo r
    //            // self-signed cert, leaf contains DK_pu b
    //    ]
    //    Certificate = COSE_Sign1 of a public key
    if ((short) (len + 2) > UDS_CERT_CHAIN_MAX_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    JCSystem.beginTransaction();
    Util.setShort(udsCertChain, (short) 0, (short) len);
    Util.arrayCopyNonAtomic(buf, offset, udsCertChain, (short) 2, len);
    JCSystem.commitTransaction();
  }

  public short getUdsCertChainLength() {
    return Util.getShort(udsCertChain, (short) 0);
  }

  public byte[] getUdsCertChain() {
    return udsCertChain;
  }

  public byte[] getDiceCertificateChain() {
    return diceCertChain;
  }

  public void persistBootCertificateChain(byte[] buf, short offset, short len) {
    if ((short) (len + 2) > DICE_CERT_CHAIN_MAX_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    JCSystem.beginTransaction();
    Util.setShort(diceCertChain, (short) 0, (short) len);
    Util.arrayCopyNonAtomic(buf, offset, diceCertChain, (short) 2, len);
    JCSystem.commitTransaction();
  }

  private void writeAuthTagState(byte[] buf, short offset, byte state) {
    buf[offset] = state;
  }

  // The master key should only be generated during applet installation and
  // during a device factory reset event.
  public KMKey createMasterKey(short keySizeBits) {
    if (masterKey == null) {
      masterKey = seProvider.createMasterKey(masterKey, keySizeBits);
    }
    return (KMKey) masterKey;
  }

  public KMKey regenerateMasterKey() {
    return seProvider.createMasterKey(masterKey, KMKeymasterApplet.MASTER_KEY_SIZE);
  }

  public KMKey getMasterKey() {
    return masterKey;
  }

  public void createPresharedKey(byte[] keyData, short offset, short length) {
    if (length != SHARED_SECRET_KEY_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    if (preSharedKey == null) {
      preSharedKey = seProvider.createPreSharedKey(preSharedKey, keyData, offset, length);
    }
  }

  public KMKey getPresharedKey() {
    if (preSharedKey == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return preSharedKey;
  }

  public void createComputedHmacKey(byte[] keyData, short offset, short length) {
    if (length != COMPUTED_HMAC_KEY_SIZE) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    if (computedHmacKey == null) {
      computedHmacKey = seProvider.createComputedHmacKey(computedHmacKey, keyData, offset, length);
    } else {
      seProvider.createComputedHmacKey(computedHmacKey, keyData, offset, length);
    }
  }

  public KMKey getComputedHmacKey() {
    if (computedHmacKey == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return computedHmacKey;
  }

  public KMKey createRkpDeviceUniqueKeyPair(
      byte[] pubKey,
      short pubKeyOff,
      short pubKeyLen,
      byte[] privKey,
      short privKeyOff,
      short privKeyLen) {
    if (deviceUniqueKeyPair == null) {
      deviceUniqueKeyPair =
          seProvider.createRkpDeviceUniqueKeyPair(
              deviceUniqueKeyPair, pubKey, pubKeyOff, pubKeyLen, privKey, privKeyOff, privKeyLen);
    } else {
      seProvider.createRkpDeviceUniqueKeyPair(
          deviceUniqueKeyPair, pubKey, pubKeyOff, pubKeyLen, privKey, privKeyOff, privKeyLen);
    }
    return deviceUniqueKeyPair;
  }

  public KMKey getRkpDeviceUniqueKeyPair() {
    return ((KMKey) deviceUniqueKeyPair);
  }

  public void createRkpMacKey(byte[] keydata, short offset, short length) {
    if (rkpMacKey == null) {
      rkpMacKey = seProvider.createRkpMacKey(rkpMacKey, keydata, offset, length);
    } else {
      seProvider.createRkpMacKey(rkpMacKey, keydata, offset, length);
    }
  }

  public KMKey getRkpMacKey() {
    if (rkpMacKey == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return rkpMacKey;
  }

  public short getAttestationId(short tag, byte[] buffer, short start) {
    byte[] attestId = null;
    switch (tag) {
        // Attestation Id Brand
      case KMType.ATTESTATION_ID_BRAND:
        attestId = attIdBrand;
        break;
        // Attestation Id Device
      case KMType.ATTESTATION_ID_DEVICE:
        attestId = attIdDevice;
        break;
        // Attestation Id Product
      case KMType.ATTESTATION_ID_PRODUCT:
        attestId = attIdProduct;
        break;
        // Attestation Id Serial
      case KMType.ATTESTATION_ID_SERIAL:
        attestId = attIdSerial;
        break;
        // Attestation Id IMEI
      case KMType.ATTESTATION_ID_IMEI:
        attestId = attIdImei;
        break;
        // Attestation Id SECOND IMEI
      case KMType.ATTESTATION_ID_SECOND_IMEI:
        attestId = attIdSecondImei;
        break;
        // Attestation Id MEID
      case KMType.ATTESTATION_ID_MEID:
        attestId = attIdMeId;
        break;
        // Attestation Id Manufacturer
      case KMType.ATTESTATION_ID_MANUFACTURER:
        attestId = attIdManufacturer;
        break;
        // Attestation Id Model
      case KMType.ATTESTATION_ID_MODEL:
        attestId = attIdModel;
        break;
    }
    if (attestId == null) {
      /* Ignore the SECOND_IMEI tag if the previous Applet's KeyMint version is less than 3.0 and
       * no SECOND_IMEI is provisioned.
       */
      if (kmDataStore.ignoreSecondImei && tag == KMType.ATTESTATION_ID_SECOND_IMEI) {
        return (short) 0;
      }
      KMException.throwIt(KMError.CANNOT_ATTEST_IDS);
    }
    Util.arrayCopyNonAtomic(attestId, (short) 0, buffer, start, (short) attestId.length);
    return (short) attestId.length;
  }

  public void setAttestationId(short tag, byte[] buffer, short start, short length) {
    switch (tag) {
        // Attestation Id Brand
      case KMType.ATTESTATION_ID_BRAND:
        JCSystem.beginTransaction();
        attIdBrand = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdBrand, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id Device
      case KMType.ATTESTATION_ID_DEVICE:
        JCSystem.beginTransaction();
        attIdDevice = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdDevice, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id Product
      case KMType.ATTESTATION_ID_PRODUCT:
        JCSystem.beginTransaction();
        attIdProduct = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdProduct, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id Serial
      case KMType.ATTESTATION_ID_SERIAL:
        JCSystem.beginTransaction();
        attIdSerial = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdSerial, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id IMEI
      case KMType.ATTESTATION_ID_IMEI:
        JCSystem.beginTransaction();
        attIdImei = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdImei, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id SECOND IMEI
      case KMType.ATTESTATION_ID_SECOND_IMEI:
        JCSystem.beginTransaction();
        attIdSecondImei = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdSecondImei, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id MEID
      case KMType.ATTESTATION_ID_MEID:
        JCSystem.beginTransaction();
        attIdMeId = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdMeId, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id Manufacturer
      case KMType.ATTESTATION_ID_MANUFACTURER:
        JCSystem.beginTransaction();
        attIdManufacturer = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdManufacturer, (short) 0, length);
        JCSystem.commitTransaction();
        break;
        // Attestation Id Model
      case KMType.ATTESTATION_ID_MODEL:
        JCSystem.beginTransaction();
        attIdModel = new byte[length];
        Util.arrayCopyNonAtomic(buffer, (short) start, attIdModel, (short) 0, length);
        JCSystem.commitTransaction();
        break;
    }
  }

  public void deleteAttestationIds() {
    attIdBrand = null;
    attIdDevice = null;
    attIdProduct = null;
    attIdSerial = null;
    attIdImei = null;
    attIdSecondImei = null;
    attIdMeId = null;
    attIdManufacturer = null;
    attIdModel = null;
    // Trigger garbage collection.
    JCSystem.requestObjectDeletion();
  }

  public short getVerifiedBootHash(byte[] buffer, short start) {
    if (verifiedHash == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    Util.arrayCopyNonAtomic(verifiedHash, (short) 0, buffer, start, (short) verifiedHash.length);
    return (short) verifiedHash.length;
  }

  public short getBootKey(byte[] buffer, short start) {
    if (bootKey == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    Util.arrayCopyNonAtomic(bootKey, (short) 0, buffer, start, (short) bootKey.length);
    return (short) bootKey.length;
  }

  public short getBootState() {
    return bootState;
  }

  public void setBootState(short state) {
    bootState = state;
  }

  public boolean isDeviceBootLocked() {
    return deviceBootLocked;
  }

  public short getBootPatchLevel() {
    if (bootPatchLevel == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return KMInteger.uint_32(bootPatchLevel, (short) 0);
  }

  public void setVerifiedBootHash(byte[] buffer, short start, short length) {
    if (verifiedHash == null) {
      verifiedHash = new byte[32];
    }
    if (length != KMKeymasterApplet.VERIFIED_BOOT_HASH_SIZE) {
      KMException.throwIt(KMError.UNKNOWN_ERROR);
    }
    Util.arrayCopy(buffer, start, verifiedHash, (short) 0, (short) 32);
  }

  public void setBootKey(byte[] buffer, short start, short length) {
    if (bootKey == null) {
      bootKey = new byte[32];
    }
    if (length != KMKeymasterApplet.VERIFIED_BOOT_KEY_SIZE) {
      KMException.throwIt(KMError.UNKNOWN_ERROR);
    }
    Util.arrayCopy(buffer, start, bootKey, (short) 0, (short) 32);
  }

  public void setDeviceLocked(boolean state) {
    deviceBootLocked = state;
  }

  public void setBootPatchLevel(byte[] buffer, short start, short length) {
    if (bootPatchLevel == null) {
      bootPatchLevel = new byte[4];
    }
    if (length > 4 || length < 0) {
      KMException.throwIt(KMError.UNKNOWN_ERROR);
    }
    Util.arrayCopy(buffer, start, bootPatchLevel, (short) 0, (short) length);
  }

  public void setChallenge(byte[] buf, short start, short length) {
    if (challenge == null) {
      challenge = new byte[16];
    }
    if (length != 16) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    Util.arrayCopy(buf, start, challenge, (short) 0, (short) length);
  }

  public short getChallenge(byte[] buffer, short start) {
    if (challenge == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    Util.arrayCopyNonAtomic(challenge, (short) 0, buffer, start, (short) challenge.length);
    return (short) challenge.length;
  }

  public boolean isProvisionLocked() {
    if (0 != (provisionStatus & KMKeymasterApplet.PROVISION_STATUS_PROVISIONING_LOCKED)) {
      return true;
    }
    return false;
  }

  public short getProvisionStatus() {
    return provisionStatus;
  }

  public void setProvisionStatus(short pStatus) {
    JCSystem.beginTransaction();
    provisionStatus |= pStatus;
    JCSystem.commitTransaction();
  }

  public void unlockProvision() {
    JCSystem.beginTransaction();
    provisionStatus &= ~KMKeymasterApplet.PROVISION_STATUS_PROVISIONING_LOCKED;
    JCSystem.commitTransaction();
  }

  public void persistOEMRootPublicKey(byte[] inBuff, short inOffset, short inLength) {
    if (inLength != 65) {
      KMException.throwIt(KMError.INVALID_INPUT_LENGTH);
    }
    if (oemRootPublicKey == null) {
      oemRootPublicKey = new byte[65];
    }
    Util.arrayCopy(inBuff, inOffset, oemRootPublicKey, (short) 0, inLength);
  }

  public byte[] getOEMRootPublicKey() {
    if (oemRootPublicKey == null) {
      KMException.throwIt(KMError.INVALID_DATA);
    }
    return oemRootPublicKey;
  }

  @Override
  public void onSave(Element element) {
    // Prmitives
    element.write(provisionStatus);
    element.write(secureBootMode);
    element.write(ignoreSecondImei);
    // Objects
    element.write(attIdBrand);
    element.write(attIdDevice);
    element.write(attIdProduct);
    element.write(attIdSerial);
    element.write(attIdImei);
    element.write(attIdSecondImei);
    element.write(attIdMeId);
    element.write(attIdManufacturer);
    element.write(attIdModel);
    element.write(udsCertChain);
    element.write(diceCertChain);
    element.write(oemRootPublicKey);

    // Key Objects
    seProvider.onSave(element, KMDataStoreConstants.INTERFACE_TYPE_MASTER_KEY, masterKey);
    seProvider.onSave(element, KMDataStoreConstants.INTERFACE_TYPE_PRE_SHARED_KEY, preSharedKey);
    seProvider.onSave(
        element, KMDataStoreConstants.INTERFACE_TYPE_DEVICE_UNIQUE_KEY_PAIR, deviceUniqueKeyPair);
    seProvider.onSave(element, KMDataStoreConstants.INTERFACE_TYPE_RKP_MAC_KEY, rkpMacKey);
  }

  @Override
  public void onRestore(Element element, short oldVersion, short currentVersion) {
    if (oldVersion <= KM_APPLET_PACKAGE_VERSION_1) {
      // 1.0 to 4.0 Upgrade happens here.
      handlePreviousVersionUpgrade(element);
      return;
    } else if (oldVersion == KM_APPLET_PACKAGE_VERSION_2) {
      handleUpgrade(element, oldVersion);
      JCSystem.beginTransaction();
      // While upgrading Secure Boot Mode flag from 2.0 to 4.0, implementations
      // have to update the secureBootMode with the correct input.
      secureBootMode = 0;
      provisionStatus |= KMKeymasterApplet.PROVISION_STATUS_SECURE_BOOT_MODE;
      // Applet package Versions till 2 had CoseSign1 for additionalCertificateChain.
      // From package version 3, the additionalCertificateChain is in X.509 format.
      // So Unreference the old address and allocate new persistent memory.
      udsCertChain = new byte[UDS_CERT_CHAIN_MAX_SIZE];
      JCSystem.commitTransaction();
      // Request for ObjectDeletion for unreferenced address of additionalCertChain.
      JCSystem.requestObjectDeletion();
      return;
    }
    handleUpgrade(element, oldVersion);
  }

  private void handlePreviousVersionUpgrade(Element element) {
    // set ignore Imei flag to true.
    ignoreSecondImei = true;
    // Read Primitives
    // restore old data table index
    short oldDataIndex = element.readShort();
    element.readBoolean(); // pop deviceBootLocked
    element.readShort(); // pop bootState

    // Read Objects
    // restore old data table
    byte[] oldDataTable = (byte[]) element.readObject();

    attIdBrand = (byte[]) element.readObject();
    attIdDevice = (byte[]) element.readObject();
    attIdProduct = (byte[]) element.readObject();
    attIdSerial = (byte[]) element.readObject();
    attIdImei = (byte[]) element.readObject();
    attIdMeId = (byte[]) element.readObject();
    attIdManufacturer = (byte[]) element.readObject();
    attIdModel = (byte[]) element.readObject();
    element.readObject(); // pop verifiedHash
    element.readObject(); // pop bootKey
    element.readObject(); // pop bootPatchLevel
    udsCertChain = (byte[]) element.readObject();
    diceCertChain = (byte[]) element.readObject();

    // Read Key Objects
    masterKey = (KMKey) seProvider.onRestore(element);
    seProvider.onRestore(element); // pop computedHmacKey
    preSharedKey = (KMKey) seProvider.onRestore(element);
    deviceUniqueKeyPair = (KMKey) seProvider.onRestore(element);
    rkpMacKey = (KMKey) seProvider.onRestore(element);
    handleProvisionStatusUpgrade(oldDataTable, oldDataIndex);
  }

  private void handleUpgrade(Element element, short oldVersion) {
    // Read Primitives
    provisionStatus = element.readShort();
    if (oldVersion >= KM_APPLET_PACKAGE_VERSION_3) {
      secureBootMode = element.readByte();
    }
    /* check if KeyMint is upgrading from older HAL version to KM300
     * and set the ignore second Imei flag
     */
    if (oldVersion < KM_APPLET_PACKAGE_VERSION_4) {
      ignoreSecondImei = true;
    } else {
      ignoreSecondImei = element.readBoolean();
    }
    // Read Objects
    attIdBrand = (byte[]) element.readObject();
    attIdDevice = (byte[]) element.readObject();
    attIdProduct = (byte[]) element.readObject();
    attIdSerial = (byte[]) element.readObject();
    attIdImei = (byte[]) element.readObject();
    if (oldVersion >= KM_APPLET_PACKAGE_VERSION_4) {
      attIdSecondImei = (byte[]) element.readObject();
    }
    attIdMeId = (byte[]) element.readObject();
    attIdManufacturer = (byte[]) element.readObject();
    attIdModel = (byte[]) element.readObject();
    udsCertChain = (byte[]) element.readObject();
    diceCertChain = (byte[]) element.readObject();
    oemRootPublicKey = (byte[]) element.readObject();
    // Read Key Objects
    masterKey = (KMKey) seProvider.onRestore(element);
    preSharedKey = (KMKey) seProvider.onRestore(element);
    deviceUniqueKeyPair = (KMKey) seProvider.onRestore(element);
    rkpMacKey = (KMKey) seProvider.onRestore(element);
  }

  public void getProvisionStatus(byte[] dataTable, byte[] scratchpad, short offset) {
    Util.setShort(scratchpad, offset, (short) 0);
    readDataEntry(dataTable, OLD_PROVISIONED_STATUS_OFFSET, scratchpad, offset);
  }

  void handleProvisionStatusUpgrade(byte[] dataTable, short dataTableIndex) {
    short dInex = repository.allocReclaimableMemory((short) 2);
    byte data[] = repository.getHeap();
    getProvisionStatus(dataTable, data, dInex);
    short pStatus = (short) (data[dInex] & 0x00ff);
    if (KMKeymasterApplet.PROVISION_STATUS_PROVISIONING_LOCKED
        == (pStatus & KMKeymasterApplet.PROVISION_STATUS_PROVISIONING_LOCKED)) {
      pStatus |=
          KMKeymasterApplet.PROVISION_STATUS_SE_LOCKED
              | KMKeymasterApplet.PROVISION_STATUS_SECURE_BOOT_MODE;
    }
    JCSystem.beginTransaction();
    // While upgrading Secure Boot Mode flag from 1.0 to 4.0, implementations
    // have to update the secureBootMode with the correct input.
    secureBootMode = 0;
    provisionStatus = pStatus;
    // Applet package Versions till 2 had CoseSign1 for additionalCertificateChain.
    // From package version 3, the additionalCertificateChain is in X.509 format.
    // So Unreference the old address and allocate new persistent memory.
    udsCertChain = new byte[UDS_CERT_CHAIN_MAX_SIZE];
    JCSystem.commitTransaction();
    repository.reclaimMemory((short) 2);
    // Request object deletion for unreferenced address for additionalCertChain
    JCSystem.requestObjectDeletion();
  }

  @Override
  public short getBackupPrimitiveByteCount() {
    // provisionStatus - 2 bytes
    // secureBootMode - 1 byte
    // Flag for ignore second Imei- 1 byte
    return (short)
        (4
            + seProvider.getBackupPrimitiveByteCount(KMDataStoreConstants.INTERFACE_TYPE_MASTER_KEY)
            + seProvider.getBackupPrimitiveByteCount(
                KMDataStoreConstants.INTERFACE_TYPE_PRE_SHARED_KEY)
            + seProvider.getBackupPrimitiveByteCount(
                KMDataStoreConstants.INTERFACE_TYPE_DEVICE_UNIQUE_KEY_PAIR)
            + seProvider.getBackupPrimitiveByteCount(
                KMDataStoreConstants.INTERFACE_TYPE_RKP_MAC_KEY));
  }

  @Override
  public short getBackupObjectCount() {
    // AttestationIds - 9
    // UdsCertificateChain - 1
    // diceCertificateChain - 1
    // oemRootPublicKey - 1
    return (short)
        (12
            + seProvider.getBackupObjectCount(KMDataStoreConstants.INTERFACE_TYPE_MASTER_KEY)
            + seProvider.getBackupObjectCount(KMDataStoreConstants.INTERFACE_TYPE_PRE_SHARED_KEY)
            + seProvider.getBackupObjectCount(
                KMDataStoreConstants.INTERFACE_TYPE_DEVICE_UNIQUE_KEY_PAIR)
            + seProvider.getBackupObjectCount(KMDataStoreConstants.INTERFACE_TYPE_RKP_MAC_KEY));
  }
}