forked from step21/desfire_rfid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesfire.cpp
1701 lines (1418 loc) · 64.3 KB
/
Desfire.cpp
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
/************************************************************************************
*
* @author Elmü
*
* This library has been tested with Desfire EV1 cards.
* It will surely not work with older Desfire cards (deprecated) because legacy authentication is not implemented.
* I have older code with lagacy authentication. If you are interested contact me on Codeproject.
*
* This library is based on code from the following open source libraries:
* https://github.com/nceruchalu/easypay
* https://github.com/leg0/libfreefare
* http://liblogicalaccess.islog.com
*
* The open source code has been completely rewritten for the Arduino compiler by Elmü.
* Check for a new version on:
* http://www.codeproject.com/Articles/1096861/DIY-electronic-RFID-Door-Lock-with-Battery-Backup
*
*************************************************************************************
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include "Desfire.h"
Desfire::Desfire()
: mi_CmacBuffer(mu8_CmacBuffer_Data, sizeof(mu8_CmacBuffer_Data))
{
mpi_SessionKey = NULL;
mu8_LastAuthKeyNo = NOT_AUTHENTICATED;
mu8_LastPN532Error = 0;
mu32_LastApplication = 0x000000; // No application selected
// The PICC master key on an empty card is a simple DES key filled with 8 zeros
const byte ZERO_KEY[24] = {0};
DES2_DEFAULT_KEY.SetKeyData(ZERO_KEY, 8, 0); // simple DES
DES3_DEFAULT_KEY.SetKeyData(ZERO_KEY, 24, 0); // triple DES
AES_DEFAULT_KEY.SetKeyData(ZERO_KEY, 16, 0);
}
void Desfire::setPiccMasterKey(const byte* key) {
memcpy(SECRET_PICC_MASTER_KEY, key, 24);
}
void Desfire::setApplicationKey(const byte* key) {
memcpy(SECRET_APPLICATION_KEY, key, 24);
}
void Desfire::setStoreValueKey(const byte* key) {
memcpy(SECRET_STORE_VALUE_KEY, key, 24);
}
void Desfire::setCardApplicationId(uint32_t id) {
CARD_APPLICATION_ID = id;
}
void Desfire::setCardFileId(byte id) {
CARD_FILE_ID = id;
}
void Desfire::setCardKeyVersion(byte version) {
CARD_KEY_VERSION = version;
}
// Whenever the RF field is switched off, these variables must be reset
bool Desfire::SwitchOffRfField()
{
mu8_LastAuthKeyNo = NOT_AUTHENTICATED;
mu32_LastApplication = 0x000000; // No application selected
return PN532::SwitchOffRfField();
}
/**************************************************************************
Does an ISO authentication with a 2K3DES key or an AES authentication with an AES key.
pi_Key must be an instance of DES or AES.
The authentication is a 3-pass process where both sides prove that they use the same master key
without ever exposing that key. Only random values are exchanged.
Not all commands require authentication.
If you want to authenticate for an application you must call SelectApplication() first.
If you select application 0x000000 pi_Key must be the PICC master key (set u8_KeyNo = 0),
otherwise one of the up to 14 application keys is chosen with u8_KeyNo.
IMPORTANT: If the card expects the 3K3DES default key you must pass a 3K3DES key full of 24 zeroes,
although this is in reality a simple DES key (K1 == K2 == K3). Otherwise the session key is calculated wrong.
**************************************************************************/
bool Desfire::Authenticate(byte u8_KeyNo, DESFireKey* pi_Key)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** Authenticate(KeyNo= %d, Key= ", u8_KeyNo);
Utils::Print(s8_Buf);
pi_Key->PrintKey();
Utils::Print(")\r\n");
}
byte u8_Command;
switch (pi_Key->GetKeyType())
{
case DF_KEY_AES: u8_Command = DFEV1_INS_AUTHENTICATE_AES; break;
case DF_KEY_2K3DES:
case DF_KEY_3K3DES: u8_Command = DFEV1_INS_AUTHENTICATE_ISO; break;
default:
Utils::Print("Invalid key\r\n");
return false;
}
TX_BUFFER(i_Params, 1);
i_Params.AppendUint8(u8_KeyNo);
// Request a random of 16 byte, but depending of the key the PICC may also return an 8 byte random
DESFireStatus e_Status;
byte u8_RndB_enc[16]; // encrypted random B
int s32_Read = DataExchange(u8_Command, &i_Params, u8_RndB_enc, 16, &e_Status, MAC_None);
if (e_Status != ST_MoreFrames || (s32_Read != 8 && s32_Read != 16))
{
Utils::Print("Authentication failed (1)\r\n");
return false;
}
int s32_RandomSize = s32_Read;
byte u8_RndB[16]; // decrypted random B
pi_Key->ClearIV(); // Fill IV with zeroes !ONLY ONCE HERE!
if (!pi_Key->CryptDataCBC(CBC_RECEIVE, KEY_DECIPHER, u8_RndB, u8_RndB_enc, s32_RandomSize))
return false; // key not set
byte u8_RndB_rot[16]; // rotated random B
Utils::RotateBlockLeft(u8_RndB_rot, u8_RndB, s32_RandomSize);
byte u8_RndA[16];
Utils::GenerateRandom(u8_RndA, s32_RandomSize);
TX_BUFFER(i_RndAB, 32); // (randomA + rotated randomB)
i_RndAB.AppendBuf(u8_RndA, s32_RandomSize);
i_RndAB.AppendBuf(u8_RndB_rot, s32_RandomSize);
TX_BUFFER(i_RndAB_enc, 32); // encrypted (randomA + rotated randomB)
i_RndAB_enc.SetCount(2*s32_RandomSize);
if (!pi_Key->CryptDataCBC(CBC_SEND, KEY_ENCIPHER, i_RndAB_enc, i_RndAB, 2*s32_RandomSize))
return false;
if (mu8_DebugLevel > 0)
{
Utils::Print("* RndB_enc: ");
Utils::PrintHexBuf(u8_RndB_enc, s32_RandomSize, LF);
Utils::Print("* RndB: ");
Utils::PrintHexBuf(u8_RndB, s32_RandomSize, LF);
Utils::Print("* RndB_rot: ");
Utils::PrintHexBuf(u8_RndB_rot, s32_RandomSize, LF);
Utils::Print("* RndA: ");
Utils::PrintHexBuf(u8_RndA, s32_RandomSize, LF);
Utils::Print("* RndAB: ");
Utils::PrintHexBuf(i_RndAB, 2*s32_RandomSize, LF);
Utils::Print("* RndAB_enc: ");
Utils::PrintHexBuf(i_RndAB_enc, 2*s32_RandomSize, LF);
}
byte u8_RndA_enc[16]; // encrypted random A
s32_Read = DataExchange(DF_INS_ADDITIONAL_FRAME, &i_RndAB_enc, u8_RndA_enc, s32_RandomSize, &e_Status, MAC_None);
if (e_Status != ST_Success || s32_Read != s32_RandomSize)
{
Utils::Print("Authentication failed (2)\r\n");
return false;
}
byte u8_RndA_dec[16]; // decrypted random A
if (!pi_Key->CryptDataCBC(CBC_RECEIVE, KEY_DECIPHER, u8_RndA_dec, u8_RndA_enc, s32_RandomSize))
return false;
byte u8_RndA_rot[16]; // rotated random A
Utils::RotateBlockLeft(u8_RndA_rot, u8_RndA, s32_RandomSize);
if (mu8_DebugLevel > 0)
{
Utils::Print("* RndA_enc: ");
Utils::PrintHexBuf(u8_RndA_enc, s32_RandomSize, LF);
Utils::Print("* RndA_dec: ");
Utils::PrintHexBuf(u8_RndA_dec, s32_RandomSize, LF);
Utils::Print("* RndA_rot: ");
Utils::PrintHexBuf(u8_RndA_rot, s32_RandomSize, LF);
}
// Last step: Check if the received random A is equal to the sent random A.
if (memcmp(u8_RndA_dec, u8_RndA_rot, s32_RandomSize) != 0)
{
Utils::Print("Authentication failed (3)\r\n");
return false;
}
// The session key is composed from RandA and RndB
TX_BUFFER(i_SessKey, 24);
i_SessKey.AppendBuf(u8_RndA, 4);
i_SessKey.AppendBuf(u8_RndB, 4);
if (pi_Key->GetKeySize() > 8) // the following block is not required for simple DES
{
switch (pi_Key->GetKeyType())
{
case DF_KEY_2K3DES:
i_SessKey.AppendBuf(u8_RndA + 4, 4);
i_SessKey.AppendBuf(u8_RndB + 4, 4);
break;
case DF_KEY_3K3DES:
i_SessKey.AppendBuf(u8_RndA + 6, 4);
i_SessKey.AppendBuf(u8_RndB + 6, 4);
i_SessKey.AppendBuf(u8_RndA + 12, 4);
i_SessKey.AppendBuf(u8_RndB + 12, 4);
break;
case DF_KEY_AES:
i_SessKey.AppendBuf(u8_RndA + 12, 4);
i_SessKey.AppendBuf(u8_RndB + 12, 4);
break;
default: // avoid stupid gcc compiler warning
break;
}
}
if (pi_Key->GetKeyType() == DF_KEY_AES) mpi_SessionKey = &mi_AesSessionKey;
else mpi_SessionKey = &mi_DesSessionKey;
if (!mpi_SessionKey->SetKeyData(i_SessKey, i_SessKey.GetCount(), 0) ||
!mpi_SessionKey->GenerateCmacSubkeys())
return false;
if (mu8_DebugLevel > 0)
{
Utils::Print("* SessKey: ");
mpi_SessionKey->PrintKey(LF);
}
mu8_LastAuthKeyNo = u8_KeyNo;
return true;
}
/**************************************************************************
ATTENTION:
Be very careful when you change the PICC master key (for application {0x000000})!
If you don't know what you are doing you may have to throw the card into the dustbin!
There is NO way to reanimate the card when you lost the master key.
-----------------------------------------------------------------------
Does a key change. You must first call Authenticate().
To change an application key you must also call SelectApplication().
To make it complicated NXP defines two different procedures:
Changing the same key number that was used for authentication and changing another key.
After changing a key you have to authenticate again with the new key.
pi_CurKey must be the old key (currently stored in u8_KeyNo) that you want to change into pi_NewKey.
pi_CurKey may be NULL if you change the same key number that was used for authetication
or if the current key is the factory default key.
**************************************************************************/
bool Desfire::ChangeKey(byte u8_KeyNo, DESFireKey* pi_NewKey, DESFireKey* pi_CurKey)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** ChangeKey(KeyNo= %d)\r\n", u8_KeyNo);
Utils::Print(s8_Buf);
}
if (mu8_LastAuthKeyNo == NOT_AUTHENTICATED)
{
Utils::Print("Not authenticated\r\n");
return false;
}
if (mu8_DebugLevel > 0)
{
Utils::Print("* SessKey IV: ");
mpi_SessionKey->PrintIV(LF);
Utils::Print("* New Key: ");
pi_NewKey->PrintKey(LF);
}
if (!DESFireKey::CheckValid(pi_NewKey))
return false;
TX_BUFFER(i_Cryptogram, 40);
i_Cryptogram.AppendBuf(pi_NewKey->Data(), pi_NewKey->GetKeySize(16));
bool b_SameKey = (u8_KeyNo == mu8_LastAuthKeyNo); // false -> change another key than the one that was used for authentication
// The type of key can only be changed for the PICC master key.
// Applications must define their key type in CreateApplication().
if (mu32_LastApplication == 0x000000)
u8_KeyNo |= pi_NewKey->GetKeyType();
// The following if() applies only to application keys.
// For the PICC master key b_SameKey is always true because there is only ONE key (#0) at the PICC level.
if (!b_SameKey)
{
if (!DESFireKey::CheckValid(pi_CurKey))
return false;
if (mu8_DebugLevel > 0)
{
Utils::Print("* Cur Key: ");
pi_CurKey->PrintKey(LF);
}
// The current key and the new key must be XORed
Utils::XorDataBlock(i_Cryptogram, pi_CurKey->Data(), pi_CurKey->GetKeySize(16));
}
// While DES stores the key version in bit 0 of the key bytes, AES transmits the version separately
if (pi_NewKey->GetKeyType() == DF_KEY_AES)
{
i_Cryptogram.AppendUint8(pi_NewKey->GetKeyVersion());
}
byte u8_Command[] = { DF_INS_CHANGE_KEY, u8_KeyNo };
uint32_t u32_Crc = Utils::CalcCrc32(u8_Command, 2, i_Cryptogram, i_Cryptogram.GetCount());
i_Cryptogram.AppendUint32(u32_Crc);
if (mu8_DebugLevel > 0)
{
Utils::Print("* CRC Crypto: 0x");
Utils::PrintHex32(u32_Crc, LF);
}
if (!b_SameKey)
{
uint32_t u32_CrcNew = Utils::CalcCrc32(pi_NewKey->Data(), pi_NewKey->GetKeySize(16));
i_Cryptogram.AppendUint32(u32_CrcNew);
if (mu8_DebugLevel > 0)
{
Utils::Print("* CRC New Key: 0x");
Utils::PrintHex32(u32_CrcNew, LF);
}
}
// Get the padded length of the Cryptogram to be encrypted
int s32_CryptoLen = 24;
if (i_Cryptogram.GetCount() > 24) s32_CryptoLen = 32;
if (i_Cryptogram.GetCount() > 32) s32_CryptoLen = 40;
// For a blocksize of 16 byte (AES) the data length 24 is not valid -> increase to 32
s32_CryptoLen = mpi_SessionKey->CalcPaddedBlockSize(s32_CryptoLen);
byte u8_Cryptogram_enc[40] = {0}; // encrypted cryptogram
if (!mpi_SessionKey->CryptDataCBC(CBC_SEND, KEY_ENCIPHER, u8_Cryptogram_enc, i_Cryptogram, s32_CryptoLen))
return false;
if (mu8_DebugLevel > 0)
{
Utils::Print("* Cryptogram: ");
Utils::PrintHexBuf(i_Cryptogram, s32_CryptoLen, LF);
Utils::Print("* Cryptog_enc: ");
Utils::PrintHexBuf(u8_Cryptogram_enc, s32_CryptoLen, LF);
}
TX_BUFFER(i_Params, 41);
i_Params.AppendUint8(u8_KeyNo);
i_Params.AppendBuf (u8_Cryptogram_enc, s32_CryptoLen);
// If the same key has been changed the session key is no longer valid. (Authentication required)
if (b_SameKey) mu8_LastAuthKeyNo = NOT_AUTHENTICATED;
return (0 == DataExchange(DF_INS_CHANGE_KEY, &i_Params, NULL, 0, NULL, MAC_Rmac));
}
/**************************************************************************
Get the version of the key (optional)
To store a version number in the key use DES::SetKeyVersion()
before calling Desfire::ChangeKey()
**************************************************************************/
bool Desfire::GetKeyVersion(byte u8_KeyNo, byte* pu8_Version)
{
char s8_Buf[80];
if (mu8_DebugLevel > 0)
{
sprintf(s8_Buf, "\r\n*** GetKeyVersion(KeyNo= %d)\r\n", u8_KeyNo);
Utils::Print(s8_Buf);
}
TX_BUFFER(i_Params, 1);
i_Params.AppendUint8(u8_KeyNo);
if (1 != DataExchange(DF_INS_GET_KEY_VERSION, &i_Params, pu8_Version, 1, NULL, MAC_TmacRmac))
return false;
if (mu8_DebugLevel > 0)
{
Utils::Print("Version: 0x");
Utils::PrintHex8(*pu8_Version, LF);
}
return true;
}
/**************************************************************************
Reads several production details of the Desfire card
If RandomID mode is active, the UID will be returned as 00 00 00 00 00 00 00
**************************************************************************/
bool Desfire::GetCardVersion(DESFireCardVersion* pk_Version)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetCardVersion()\r\n");
byte* pu8_Ptr = (byte*)pk_Version;
DESFireStatus e_Status;
int s32_Read = DataExchange(DF_INS_GET_VERSION, NULL, pu8_Ptr, 7, &e_Status, MAC_TmacRmac);
if (s32_Read != 7 || e_Status != ST_MoreFrames)
return false;
pu8_Ptr += 7;
s32_Read = DataExchange(DF_INS_ADDITIONAL_FRAME, NULL, pu8_Ptr, 7, &e_Status, MAC_Rmac);
if (s32_Read != 7 || e_Status != ST_MoreFrames)
return false;
pu8_Ptr += 7;
s32_Read = DataExchange(DF_INS_ADDITIONAL_FRAME, NULL, pu8_Ptr, 14, &e_Status, MAC_Rmac);
if (s32_Read != 14 || e_Status != ST_Success)
return false;
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
Utils::Print("--- Desfire Card Details ---\r\n");
sprintf(s8_Buf, "Hardware Version: %d.%d\r\n", pk_Version->hardwareMajVersion, pk_Version->hardwareMinVersion);
Utils::Print(s8_Buf);
sprintf(s8_Buf, "Software Version: %d.%d\r\n", pk_Version->softwareMajVersion, pk_Version->softwareMinVersion);
Utils::Print(s8_Buf);
sprintf(s8_Buf, "EEPROM size: %d byte\r\n", 1 << (pk_Version->hardwareStorageSize / 2));
Utils::Print(s8_Buf);
sprintf(s8_Buf, "Production: week %X, year 20%02X\r\n", pk_Version->cwProd, pk_Version->yearProd);
Utils::Print(s8_Buf);
Utils::Print("UID no: ");
Utils::PrintHexBuf(pk_Version->uid, 7, LF);
Utils::Print("Batch no: ");
Utils::PrintHexBuf(pk_Version->batchNo, 5, LF);
}
return true;
}
/**************************************************************************
Erases all content from the card (all files and all applications)
**************************************************************************/
bool Desfire::FormatCard()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** FormatCard()\r\n");
return (0 == DataExchange(DF_INS_FORMAT_PICC, NULL, NULL, 0, NULL, MAC_TmacRmac));
}
/**************************************************************************
Gets the settings of the master key.
First you must call SelectApplication()
After selecting the application 0x000000 the settings of the PICC master key
will be returned, otherwise the settings of the selected application master key.
pu8_KeyCount will contain the max number of keys for an application.
pu8_KeyCount will be = 1 for the application ID 0x000000.
pe_KeyType returns the type of key for the application (2K3DES / AES)
**************************************************************************/
bool Desfire::GetKeySettings(DESFireKeySettings* pe_Settg, byte* pu8_KeyCount, DESFireKeyType* pe_KeyType)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetKeySettings()\r\n");
byte u8_RetData[2];
if (2 != DataExchange(DF_INS_GET_KEY_SETTINGS, NULL, u8_RetData, 2, NULL, MAC_TmacRmac))
return false;
*pe_Settg = (DESFireKeySettings)u8_RetData[0];
*pu8_KeyCount = u8_RetData[1] & 0x0F;
*pe_KeyType = (DESFireKeyType)(u8_RetData[1] & 0xF0);
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "Settings: 0x%02X, KeyCount: %d, KeyType: %s\r\n", *pe_Settg, *pu8_KeyCount, DESFireKey::GetKeyTypeAsString(*pe_KeyType));
Utils::Print(s8_Buf);
}
return true;
}
/**************************************************************************
Changes the settings of the PICC or application master key.
First you must call SelectApplication() and authenticate with the master key.
**************************************************************************/
bool Desfire::ChangeKeySettings(DESFireKeySettings e_NewSettg)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** ChangeKeySettings(0x%02X)\r\n", e_NewSettg);
Utils::Print(s8_Buf);
}
TX_BUFFER(i_Params, 16);
i_Params.AppendUint8(e_NewSettg);
// The TX CMAC must not be calculated here because a CBC encryption operation has already been executed
return (0 == DataExchange(DF_INS_CHANGE_KEY_SETTINGS, &i_Params, NULL, 0, NULL, MAC_TcryptRmac));
}
/**************************************************************************
Enables random ID mode in which the card sends another UID each time.
In Random UID mode the card sends a 4 byte UID that always starts with 0x80.
To get the real UID of the card call GetRealCardID()
---------------------------------------------------------------------
ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION
---------------------------------------------------------------------
NXP does not provide any way to turn off Random ID mode.
If you once call this funtion the card will send random ID FOREVER!
---------------------------------------------------------------------
ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION
---------------------------------------------------------------------
**************************************************************************/
bool Desfire::EnableRandomIDForever()
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** EnableRandomIDForever()\r\n");
TX_BUFFER(i_Command, 2);
i_Command.AppendUint8(DFEV1_INS_SET_CONFIGURATION);
i_Command.AppendUint8(0x00); // subcommand 00
TX_BUFFER(i_Params, 16);
i_Params.AppendUint8(0x02); // 0x02 = enable random ID, 0x01 = disable format
// The TX CMAC must not be calculated here because a CBC encryption operation has already been executed
return (0 == DataExchange(&i_Command, &i_Params, NULL, 0, NULL, MAC_TcryptRmac));
}
/**************************************************************************
This command makes only sense if the card is in Random UID mode.
It allows to obtain the real UID of the card.
If Random ID mode is not active use ReadPassiveTargetID() or GetCardVersion()
instead to get the UID.
A previous authentication is required.
**************************************************************************/
bool Desfire::GetRealCardID(byte u8_UID[7])
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetRealCardID()\r\n");
if (mu8_LastAuthKeyNo == NOT_AUTHENTICATED)
{
Utils::Print("Not authenticated\r\n");
return false;
}
RX_BUFFER(i_Data, 16);
if (16 != DataExchange(DFEV1_INS_GET_CARD_UID, NULL, i_Data, 16, NULL, MAC_TmacRcrypt))
return false;
// The card returns UID[7] + CRC32[4] encrypted with the session key
// Copy the 7 bytes of the UID to the output buffer
i_Data.ReadBuf(u8_UID, 7);
// Get the CRC sent by the card
uint32_t u32_Crc1 = i_Data.ReadUint32();
// The CRC must be calculated over the UID + the status byte appended
byte u8_Status = ST_Success;
uint32_t u32_Crc2 = Utils::CalcCrc32(u8_UID, 7, &u8_Status, 1);
if (mu8_DebugLevel > 1)
{
Utils::Print("* CRC: 0x");
Utils::PrintHex32(u32_Crc2, LF);
}
if (u32_Crc1 != u32_Crc2)
{
Utils::Print("Invalid CRC\r\n");
return false;
}
if (mu8_DebugLevel > 0)
{
Utils::Print("Real UID: ");
Utils::PrintHexBuf(u8_UID, 7, LF);
}
return true;
}
/**************************************************************************
Get the remaining free memory on the card.
NOTE: This function gives stranges results:
8k Card formatted: EPPROM size: 8192 bytes > Free memory: 7936 bytes.
4k Card formatted: EPPROM size: 4096 bytes < Free memory: 4864 bytes!
**************************************************************************/
bool Desfire::GetFreeMemory(uint32_t* pu32_Memory)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetFreeMemory()\r\n");
*pu32_Memory = 0;
RX_BUFFER(i_Data, 3);
if (3 != DataExchange(DFEV1_INS_FREE_MEM, NULL, i_Data, 3, NULL, MAC_TmacRmac))
return false;
*pu32_Memory = i_Data.ReadUint24();
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "Free memory: %d bytes\r\n", (int)*pu32_Memory);
Utils::Print(s8_Buf);
}
return true;
}
/**************************************************************************
returns all Application ID's (AID) stored on the card. (maximum = 28 / card)
Each application ID is 3 bytes.
pu32_IDlist: Must point to an uint32_t[28] array
ps32_AppCount: The count of DESFireAppId's that have been stored in pk_IDlist.
**************************************************************************/
bool Desfire::GetApplicationIDs(uint32_t u32_IDlist[28], byte* pu8_AppCount)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetApplicationIDs()\r\n");
memset(u32_IDlist, 0, 28 * sizeof(uint32_t));
RX_BUFFER(i_RxBuf, 28*3); // 3 byte per application
byte* pu8_Ptr = i_RxBuf;
DESFireStatus e_Status;
int s32_Read1 = DataExchange(DF_INS_GET_APPLICATION_IDS, NULL, pu8_Ptr, MAX_FRAME_SIZE, &e_Status, MAC_TmacRmac);
if (s32_Read1 < 0)
return false;
// If there are more than 19 applications, they will be sent in two frames
int s32_Read2 = 0;
if (e_Status == ST_MoreFrames)
{
pu8_Ptr += s32_Read1;
s32_Read2 = DataExchange(DF_INS_ADDITIONAL_FRAME, NULL, pu8_Ptr, 28 * 3 - s32_Read1, NULL, MAC_Rmac);
if (s32_Read2 < 0)
return false;
}
i_RxBuf.SetSize (s32_Read1 + s32_Read2);
*pu8_AppCount = (s32_Read1 + s32_Read2) / 3;
// Convert 3 byte array -> 4 byte array
for (byte i=0; i<*pu8_AppCount; i++)
{
u32_IDlist[i] = i_RxBuf.ReadUint24();
}
if (mu8_DebugLevel > 0)
{
if (*pu8_AppCount == 0)
{
Utils::Print("No Application ID's.\r\n");
}
else for (byte i=0; i<*pu8_AppCount; i++)
{
char s8_Buf[80];
sprintf(s8_Buf, "Application %2d: 0x%06X\r\n", i, (unsigned int)u32_IDlist[i]);
Utils::Print(s8_Buf);
}
}
return true;
}
/**************************************************************************
Creates a new application
You must call SelectApplication(0x000000) before and authenticate with the PICC master key!
u32_AppID: The unique ID of the application
e_Settg: The application master key settings
u8_KeyCount: The count of keys to be stored in the application
e_KeyType: Defines the key type for the application (2K3DES / AES)
**************************************************************************/
bool Desfire::CreateApplication(uint32_t u32_AppID, DESFireKeySettings e_Settg, byte u8_KeyCount, DESFireKeyType e_KeyType)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** CreateApplication(App= 0x%06X, KeyCount= %d, Type= %s)\r\n", (unsigned int)u32_AppID, u8_KeyCount, DESFireKey::GetKeyTypeAsString(e_KeyType));
Utils::Print(s8_Buf);
}
if (e_KeyType == DF_KEY_INVALID)
{
Utils::Print("Invalid key type\r\n");
return false;
}
TX_BUFFER(i_Params, 5);
i_Params.AppendUint24(u32_AppID);
i_Params.AppendUint8 (e_Settg);
i_Params.AppendUint8 (u8_KeyCount | e_KeyType);
return (0 == DataExchange(DF_INS_CREATE_APPLICATION, &i_Params, NULL, 0, NULL, MAC_TmacRmac));
}
/**************************************************************************
Deletes an application after checking that it exists.
When you call DeleteApplication() and the application does not exist,
an ST_AppNotFound error is returned and the authentication is invalidated.
To avoid this error, this function calls first GetApplicationIDs()
**************************************************************************/
bool Desfire::DeleteApplicationIfExists(uint32_t u32_AppID)
{
uint32_t u32_IDlist[28];
byte u8_AppCount;
if (!GetApplicationIDs(u32_IDlist, &u8_AppCount))
return false;
bool b_Found = false;
for (byte i=0; i<u8_AppCount; i++)
{
if (u32_IDlist[i] == u32_AppID)
b_Found = true;
}
if (!b_Found)
return true;
return DeleteApplication(u32_AppID);
}
/**************************************************************************
Deletes an application
You must call SelectApplication(0x000000) before and authenticate with the PICC master key!
**************************************************************************/
bool Desfire::DeleteApplication(uint32_t u32_AppID)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** DeleteApplication(0x%06X)\r\n", (unsigned int)u32_AppID);
Utils::Print(s8_Buf);
}
TX_BUFFER(i_Params, 3);
i_Params.AppendUint24(u32_AppID);
return (0 == DataExchange(DF_INS_DELETE_APPLICATION, &i_Params, NULL, 0, NULL, MAC_TmacRmac));
}
/**************************************************************************
Selects an application
If u8_AppID is 0x000000 the PICC level is selected
**************************************************************************/
bool Desfire::SelectApplication(uint32_t u32_AppID)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** SelectApplication(0x%06X)\r\n", (unsigned int)u32_AppID);
Utils::Print(s8_Buf);
}
TX_BUFFER(i_Params, 3);
i_Params.AppendUint24(u32_AppID);
// This command does not return a CMAC because after selecting another application the session key is no longer valid. (Authentication required)
if (0 != DataExchange(DF_INS_SELECT_APPLICATION, &i_Params, NULL, 0, NULL, MAC_None))
return false;
mu8_LastAuthKeyNo = NOT_AUTHENTICATED; // set to invalid value (the selected app requires authentication)
mu32_LastApplication = u32_AppID;
return true;
}
/**************************************************************************
returns all File ID's for the selected application.
Desfire EV1: maximum = 32 files per application.
u8_FileIDs: Buffer of 32 bytes
ps32_FileCount: The count of file Id's that have been written to u8_FileIDs.
**************************************************************************/
bool Desfire::GetFileIDs(byte* u8_FileIDs, byte* pu8_FileCount)
{
if (mu8_DebugLevel > 0) Utils::Print("\r\n*** GetFileIDs()\r\n");
int s32_Read = DataExchange(DF_INS_GET_FILE_IDS, NULL, u8_FileIDs, 32, NULL, MAC_TmacRmac);
if (s32_Read < 0)
return false;
*pu8_FileCount = s32_Read;
if (mu8_DebugLevel > 0)
{
if (*pu8_FileCount == 0)
{
Utils::Print("No files.\r\n");
}
else
{
Utils::Print("File ID's: ");
Utils::PrintHexBuf(u8_FileIDs, s32_Read, LF);
}
}
return true;
}
/**************************************************************************
Gets the settings of a file.
**************************************************************************/
bool Desfire::GetFileSettings(byte u8_FileID, DESFireFileSettings* pk_Settings)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** GetFileSettings(ID= %d)\r\n", u8_FileID);
Utils::Print(s8_Buf);
}
memset(pk_Settings, 0, sizeof(DESFireFileSettings));
TX_BUFFER(i_Params, 1);
i_Params.AppendUint8(u8_FileID);
RX_BUFFER(i_RetData, 20);
int s32_Read = DataExchange(DF_INS_GET_FILE_SETTINGS, &i_Params, i_RetData, 20, NULL, MAC_TmacRmac);
if (s32_Read < 7)
return false;
i_RetData.SetSize(s32_Read);
pk_Settings->e_FileType = (DESFireFileType) i_RetData.ReadUint8();
pk_Settings->e_Encrypt = (DESFireFileEncryption)i_RetData.ReadUint8();
pk_Settings->k_Permis.Unpack (i_RetData.ReadUint16());
char s8_Buf[150];
if (mu8_DebugLevel > 0)
{
sprintf(s8_Buf, "Type: %d, Encrypt: %d, Access Read: 0x%X, Write: 0x%X, Rd+Wr: 0x%X, Change: 0x%X\r\n",
pk_Settings->e_FileType, pk_Settings->e_Encrypt,
pk_Settings->k_Permis.e_ReadAccess, pk_Settings->k_Permis.e_WriteAccess,
pk_Settings->k_Permis.e_ReadAndWriteAccess, pk_Settings->k_Permis.e_ChangeAccess);
Utils::Print(s8_Buf);
}
switch (pk_Settings->e_FileType)
{
case MDFT_STANDARD_DATA_FILE:
case MDFT_BACKUP_DATA_FILE:
pk_Settings->u32_FileSize = i_RetData.ReadUint24();
if (mu8_DebugLevel > 0)
{
sprintf(s8_Buf, "FileSize: %d\r\n", (int)pk_Settings->u32_FileSize);
Utils::Print(s8_Buf);
}
return true;
case MDFT_VALUE_FILE_WITH_BACKUP:
pk_Settings->u32_LowerLimit = i_RetData.ReadUint32();
pk_Settings->u32_UpperLimit = i_RetData.ReadUint32();
pk_Settings->u32_LimitedCreditValue = i_RetData.ReadUint32();
pk_Settings->b_LimitedCreditEnabled = i_RetData.ReadUint8() == 0x01;
if (mu8_DebugLevel > 0)
{
sprintf(s8_Buf, "LowerLimit: %d, UpperLimit: %d, CreditValue: %d, LimitEnabled: %d\r\n",
(int)pk_Settings->u32_LowerLimit, (int)pk_Settings->u32_UpperLimit, (int)pk_Settings->u32_LimitedCreditValue, (int)pk_Settings->b_LimitedCreditEnabled);
Utils::Print(s8_Buf);
}
return true;
case MDFT_LINEAR_RECORD_FILE_WITH_BACKUP:
case MDFT_CYCLIC_RECORD_FILE_WITH_BACKUP:
pk_Settings->u32_RecordSize = i_RetData.ReadUint24();
pk_Settings->u32_MaxNumberRecords = i_RetData.ReadUint24();
pk_Settings->u32_CurrentNumberRecords = i_RetData.ReadUint24();
if (mu8_DebugLevel > 0)
{
sprintf(s8_Buf, "RecordSize: %d, MaxRecords: %d, CurrentRecords: %d\r\n",
(int)pk_Settings->u32_RecordSize, (int)pk_Settings->u32_MaxNumberRecords, (int)pk_Settings->u32_CurrentNumberRecords);
Utils::Print(s8_Buf);
}
return true;
default:
return false; // unknown file type
}
}
/**************************************************************************
Creates a standard data file (a simple binary file) of a fixed size in the selected application.
**************************************************************************/
bool Desfire::CreateStdDataFile(byte u8_FileID, DESFireFilePermissions* pk_Permis, int s32_FileSize)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** CreateStdDataFile(ID= %d, Size= %d)\r\n", u8_FileID, s32_FileSize);
Utils::Print(s8_Buf);
}
uint16_t u16_Permis = pk_Permis->Pack();
TX_BUFFER(i_Params, 7);
i_Params.AppendUint8 (u8_FileID);
i_Params.AppendUint8 (CM_PLAIN);
i_Params.AppendUint16(u16_Permis);
i_Params.AppendUint24(s32_FileSize); // only the low 3 bytes are used
return (0 == DataExchange(DF_INS_CREATE_STD_DATA_FILE, &i_Params, NULL, 0, NULL, MAC_TmacRmac));
}
/**************************************************************************
Deletes a file in the selected application
**************************************************************************/
bool Desfire::DeleteFile(byte u8_FileID)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** DeleteFile(ID= %d)\r\n", u8_FileID);
Utils::Print(s8_Buf);
}
TX_BUFFER(i_Params, 1);
i_Params.AppendUint8(u8_FileID);
return (0 == DataExchange(DF_INS_DELETE_FILE, &i_Params, NULL, 0, NULL, MAC_TmacRmac));
}
/**************************************************************************
Reads a block of data from a Standard Data File or a Backup Data File.
If (s32_Offset + s32_Length > file length) you will get a LimitExceeded error.
If the file permissins are not set to AR_FREE you must authenticate either
with the key in e_ReadAccess or the key in e_ReadAndWriteAccess.
**************************************************************************/
bool Desfire::ReadFileData(byte u8_FileID, int s32_Offset, int s32_Length, byte* u8_DataBuffer)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** ReadFileData(ID= %d, Offset= %d, Length= %d)\r\n", u8_FileID, s32_Offset, s32_Length);
Utils::Print(s8_Buf);
}
// With intention this command does not use DF_INS_ADDITIONAL_FRAME because the CMAC must be calculated over all frames received.
// When reading a lot of data this could lead to a buffer overflow in mi_CmacBuffer.
while (s32_Length > 0)
{
int s32_Count = min(s32_Length, 48); // the maximum that can be transferred in one frame (must be a multiple of 16 if encryption is used)
TX_BUFFER(i_Params, 7);
i_Params.AppendUint8 (u8_FileID);
i_Params.AppendUint24(s32_Offset); // only the low 3 bytes are used
i_Params.AppendUint24(s32_Count); // only the low 3 bytes are used
DESFireStatus e_Status;
int s32_Read = DataExchange(DF_INS_READ_DATA, &i_Params, u8_DataBuffer, s32_Count, &e_Status, MAC_TmacRmac);
if (e_Status != ST_Success || s32_Read <= 0)
return false; // ST_MoreFrames is not allowed here!
s32_Length -= s32_Read;
s32_Offset += s32_Read;
u8_DataBuffer += s32_Read;
}
return true;
}
/**************************************************************************
Writes data to a Standard Data File or a Backup Data File.
If the file permissins are not set to AR_FREE you must authenticate either
with the key in e_WriteAccess or the key in e_ReadAndWriteAccess.
**************************************************************************/
bool Desfire::WriteFileData(byte u8_FileID, int s32_Offset, int s32_Length, const byte* u8_DataBuffer)
{
if (mu8_DebugLevel > 0)
{
char s8_Buf[80];
sprintf(s8_Buf, "\r\n*** WriteFileData(ID= %d, Offset= %d, Length= %d)\r\n", u8_FileID, s32_Offset, s32_Length);
Utils::Print(s8_Buf);
}
// With intention this command does not use DF_INS_ADDITIONAL_FRAME because the CMAC must be calculated over all frames sent.
// When writing a lot of data this could lead to a buffer overflow in mi_CmacBuffer.
while (s32_Length > 0)
{
int s32_Count = min(s32_Length, MAX_FRAME_SIZE - 8); // DF_INS_WRITE_DATA + u8_FileID + s32_Offset + s32_Count = 8 bytes
TX_BUFFER(i_Params, MAX_FRAME_SIZE);
i_Params.AppendUint8 (u8_FileID);
i_Params.AppendUint24(s32_Offset); // only the low 3 bytes are used
i_Params.AppendUint24(s32_Count); // only the low 3 bytes are used
i_Params.AppendBuf(u8_DataBuffer, s32_Count);
DESFireStatus e_Status;
int s32_Read = DataExchange(DF_INS_WRITE_DATA, &i_Params, NULL, 0, &e_Status, MAC_TmacRmac);
if (e_Status != ST_Success || s32_Read != 0)
return false; // ST_MoreFrames is not allowed here!
s32_Length -= s32_Count;
s32_Offset += s32_Count;
u8_DataBuffer += s32_Count;
}