-
-
Notifications
You must be signed in to change notification settings - Fork 973
/
desfirecore.c
3110 lines (2583 loc) · 110 KB
/
desfirecore.c
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
//-----------------------------------------------------------------------------
// Borrowed initially from https://github.com/nfc-tools/libfreefare
// Copyright (C) 2010, Romain Tartiere.
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// High frequency Desfire core functions
//-----------------------------------------------------------------------------
// Info from here and many other sources from the public internet sites
// https://github.com/revk/DESFireAES
// https://github.com/step21/desfire_rfid
// https://github.com/patsys/desfire-python/blob/master/Desfire/DESFire.py
//-----------------------------------------------------------------------------
#include "desfirecore.h"
#include <stdlib.h>
#include <string.h>
#include <util.h>
#include "commonutil.h"
#include "generator.h"
#include "aes.h"
#include "ui.h"
#include "crc.h"
#include "crc16.h" // crc16 ccitt
#include "crc32.h"
#include "protocols.h" // ISO7816 APDU return codes
#include "cmdhf14a.h"
#include "iso7816/apduinfo.h" // APDU manipulation / errorcodes
#include "iso7816/iso7816core.h" // APDU logging
#include "util_posix.h" // msleep
#include "desfiresecurechan.h"
#include "mifare/mad.h"
#include "mifare/aiddesfire.h"
const CLIParserOption DesfireAlgoOpts[] = {
{T_DES, "des"},
{T_3DES, "2tdea"},
{T_3K3DES, "3tdea"},
{T_AES, "aes"},
{0, NULL},
};
const size_t DesfireAlgoOptsLen = ARRAYLEN(DesfireAlgoOpts);
const CLIParserOption DesfireKDFAlgoOpts[] = {
{MFDES_KDF_ALGO_NONE, "none"},
{MFDES_KDF_ALGO_AN10922, "an10922"},
{MFDES_KDF_ALGO_GALLAGHER, "gallagher"},
{0, NULL},
};
const size_t DesfireKDFAlgoOptsLen = ARRAYLEN(DesfireKDFAlgoOpts);
const CLIParserOption DesfireCommunicationModeOpts[] = {
{DCMPlain, "plain"},
{DCMMACed, "mac"},
{DCMEncrypted, "encrypt"},
{0, NULL},
};
const size_t DesfireCommunicationModeOptsLen = ARRAYLEN(DesfireCommunicationModeOpts);
const CLIParserOption DesfireCommandSetOpts[] = {
{DCCNative, "native"},
{DCCNativeISO, "niso"},
{DCCISO, "iso"},
{0, NULL},
};
const size_t DesfireCommandSetOptsLen = ARRAYLEN(DesfireCommandSetOpts);
const CLIParserOption DesfireSecureChannelOpts[] = {
{DACd40, "d40"},
{DACEV1, "ev1"},
{DACEV2, "ev2"},
{DACLRP, "lrp"},
{0, NULL},
};
const size_t DesfireSecureChannelOptsLen = ARRAYLEN(DesfireSecureChannelOpts);
const CLIParserOption DesfireFileAccessModeOpts[] = {
{0x00, "key0"},
{0x01, "key1"},
{0x02, "key2"},
{0x03, "key3"},
{0x04, "key4"},
{0x05, "key5"},
{0x06, "key6"},
{0x07, "key7"},
{0x08, "key8"},
{0x09, "key9"},
{0x0a, "key10"},
{0x0b, "key11"},
{0x0c, "key12"},
{0x0d, "key13"},
{0x0e, "free"},
{0x0f, "deny"},
{0, NULL},
};
const CLIParserOption DesfireValueFileOperOpts[] = {
{MFDES_GET_VALUE, "get"},
{MFDES_CREDIT, "credit"},
{MFDES_LIMITED_CREDIT, "limcredit"},
{MFDES_DEBIT, "debit"},
{0xff, "clear"},
{0, NULL},
};
const CLIParserOption DesfireReadFileTypeOpts[] = {
{RFTAuto, "auto"},
{RFTData, "data"},
{RFTValue, "value"},
{RFTRecord, "record"},
{RFTMAC, "mac"},
{0, NULL},
};
static const char *getstatus(const uint16_t *sw) {
if (sw == NULL) return "--> sw argument error. This should never happen !";
if (((*sw >> 8) & 0xFF) == 0x91) {
switch (*sw & 0xFF) {
case MFDES_E_OUT_OF_EEPROM:
return "Out of Eeprom, insufficient NV-Memory to complete command";
case MFDES_E_ILLEGAL_COMMAND_CODE:
return "Command code not supported";
case MFDES_E_INTEGRITY_ERROR:
return "CRC or MAC does not match data / Padding bytes invalid";
case MFDES_E_NO_SUCH_KEY:
return "Invalid key number specified";
case MFDES_E_LENGTH:
return "Length of command string invalid";
case MFDES_E_PERMISSION_DENIED:
return "Current configuration/status does not allow the requested command";
case MFDES_E_PARAMETER_ERROR:
return "Value of the parameter(s) invalid";
case MFDES_E_APPLICATION_NOT_FOUND:
return "Requested AID not present on PICC";
case MFDES_E_APPL_INTEGRITY:
return "Application integrity error, application will be disabled";
case MFDES_E_AUTHENTICATION_ERROR:
return "Current authentication status does not allow the requested command";
case MFDES_E_BOUNDARY:
return "Attempted to read/write data from/to beyond the file's/record's limit";
case MFDES_E_PICC_INTEGRITY:
return "PICC integrity error, PICC will be disabled";
case MFDES_E_COMMAND_ABORTED:
return "Previous command was not fully completed / Not all Frames were requested or provided by the PCD";
case MFDES_E_PICC_DISABLED:
return "PICC was disabled by an unrecoverable error";
case MFDES_E_COUNT:
return "Application count is limited to 28, not addition CreateApplication possible";
case MFDES_E_DUPLICATE:
return "Duplicate entry: File/Application/ISO Text does already exist";
case MFDES_E_EEPROM:
return "Eeprom error due to loss of power, internal backup/rollback mechanism activated";
case MFDES_E_FILE_NOT_FOUND:
return "Specified file number does not exist";
case MFDES_E_FILE_INTEGRITY:
return "File integrity error, file will be disabled";
default:
return "Unknown error";
}
}
return "Unknown error";
}
const char *DesfireGetErrorString(int res, uint16_t *sw) {
switch (res) {
case PM3_EAPDU_FAIL:
return getstatus(sw);
case PM3_EUNDEF:
return "Undefined error";
case PM3_EINVARG:
return "Invalid argument(s)";
case PM3_EDEVNOTSUPP:
return "Operation not supported by device";
case PM3_ETIMEOUT:
return "Operation timed out";
case PM3_EOPABORTED:
return "Operation aborted (by user)";
case PM3_ENOTIMPL:
return "Not (yet) implemented";
case PM3_ERFTRANS:
return "Error while RF transmission";
case PM3_EIO:
return "Input / output error";
case PM3_EOVFLOW:
return "Buffer overflow";
case PM3_ESOFT:
return "Software error";
case PM3_EFLASH:
return "Flash error";
case PM3_EMALLOC:
return "Memory allocation error";
case PM3_EFILE:
return "File error";
case PM3_ENOTTY:
return "Generic TTY error";
case PM3_EINIT:
return "Initialization error";
case PM3_EWRONGANSWER:
return "Expected a different answer error";
case PM3_EOUTOFBOUND:
return "Memory out-of-bounds error";
case PM3_ECARDEXCHANGE:
return "Exchange with card error";
case PM3_EAPDU_ENCODEFAIL:
return "Failed to create APDU";
case PM3_ENODATA:
return "No data";
case PM3_EFATAL:
return "Fatal error";
default:
break;
}
return "";
}
const char *DesfireAuthErrorToStr(int error) {
switch (error) {
case 1:
return "Sending auth command failed";
case 2:
return "Authentication failed. No data received";
case 3:
return "Authentication failed. Invalid key number.";
case 4:
return "Authentication failed. Length of answer doesn't match algo length";
case 5:
return "mbedtls_aes_setkey_dec failed";
case 6:
return "mbedtls_aes_setkey_enc failed";
case 7:
return "Sending auth command failed";
case 8:
return "Authentication failed. Card timeout.";
case 9:
return "Authentication failed.";
case 10:
return "mbedtls_aes_setkey_dec failed";
case 11:
return "Authentication failed. Cannot verify Session Key.";
case 12:
return "Authentication failed. Cannot verify CMAC.";
case 50:
return "PICC returned not an AES answer";
case 51:
return "PICC returned not an LRP answer";
case 100:
return "Can't find auth method for provided channel parameters.";
case 200:
return "Can't select application.";
case 201:
return "Authentication returned no error but channel not authenticated.";
case 202:
return "Can't select application by ISO ID.";
case 203:
return "Can't select file by ISO ID.";
case 301:
return "ISO Get challenge error.";
case 302:
return "ISO Get challenge returned wrong length.";
case 303:
return "Crypto encode piccrnd1 error.";
case 304:
return "External authenticate error.";
case 305:
return "Internal authenticate error.";
case 306:
return "Internal authenticate returned wrong length.";
case 307:
return "Crypto decode piccrnd2 error.";
case 308:
return "Random numbers don't match. Authentication failed.";
default:
break;
}
return "";
}
const char *DesfireSelectWayToStr(DesfireISOSelectWay way) {
switch (way) {
case ISW6bAID:
return "AID";
case ISWMF:
return "MF";
case ISWIsoID:
return "ISO ID";
case ISWDFName:
return "DF Name";
default:
break;
}
return "";
}
char *DesfireWayIDStr(DesfireISOSelectWay way, uint32_t id) {
static char str[200] = {0};
if (way == ISWMF || way == ISWDFName)
snprintf(str, sizeof(str), "%s", DesfireSelectWayToStr(way));
else
snprintf(str, sizeof(str), "%s %0*x", DesfireSelectWayToStr(way), (way == ISW6bAID) ? 6 : 4, id);
return str;
}
bool DesfireMFSelected(DesfireISOSelectWay way, uint32_t id) {
switch (way) {
case ISW6bAID:
return (id == 0x000000);
case ISWMF:
return true;
case ISWIsoID:
return (id == 0x3f00);
case ISWDFName:
return false;
default:
break;
}
return false;
}
// iceman todo: use commonutil.c instead
uint32_t DesfireAIDByteToUint(const uint8_t *data) {
return data[0] + (data[1] << 8) + (data[2] << 16);
}
void DesfireAIDUintToByte(uint32_t aid, uint8_t *data) {
data[0] = aid & 0xff;
data[1] = (aid >> 8) & 0xff;
data[2] = (aid >> 16) & 0xff;
}
static uint8_t DesfireKeyToISOKey(DesfireCryptoAlgorithm keytype) {
switch (keytype) {
case T_DES:
return 0x02;
case T_3DES:
return 0x02;
case T_3K3DES:
return 0x04;
case T_AES:
return 0x09;
}
return 0x00;
}
static uint8_t DesfireGetRndLenForKey(DesfireCryptoAlgorithm keytype) {
switch (keytype) {
case T_DES:
return 0x08;
case T_3DES:
return 0x08;
case T_3K3DES:
return 0x10;
case T_AES:
return 0x10;
}
return 0x00;
}
void DesfirePrintContext(DesfireContext_t *ctx) {
PrintAndLogEx(INFO, "Key num: %d Key algo: %s Key[%d]: %s",
ctx->keyNum,
CLIGetOptionListStr(DesfireAlgoOpts, ctx->keyType),
desfire_get_key_length(ctx->keyType),
sprint_hex(ctx->key,
desfire_get_key_length(ctx->keyType)));
if (ctx->kdfAlgo != MFDES_KDF_ALGO_NONE) {
PrintAndLogEx(INFO, "KDF algo: %s KDF input[%d]: %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, ctx->kdfAlgo), ctx->kdfInputLen, sprint_hex(ctx->kdfInput, ctx->kdfInputLen));
PrintAndLogEx(INFO, "AID: %06x UID[%d]: %s", ctx->selectedAID, ctx->uidlen, sprint_hex(ctx->uid, ctx->uidlen));
}
PrintAndLogEx(INFO, "Secure channel: %s Command set: %s Communication mode: %s",
CLIGetOptionListStr(DesfireSecureChannelOpts, ctx->secureChannel),
CLIGetOptionListStr(DesfireCommandSetOpts, ctx->cmdSet),
CLIGetOptionListStr(DesfireCommunicationModeOpts, ctx->commMode));
if (DesfireIsAuthenticated(ctx)) {
if (memcmp(ctx->sessionKeyMAC, ctx->sessionKeyEnc, desfire_get_key_length(ctx->keyType)) == 0) {
PrintAndLogEx(INFO, "Session key [%d]: %s ",
desfire_get_key_length(ctx->keyType),
sprint_hex(ctx->sessionKeyEnc, desfire_get_key_length(ctx->keyType)));
} else {
PrintAndLogEx(INFO, "Session key MAC [%d]: %s ",
desfire_get_key_length(ctx->keyType),
sprint_hex(ctx->sessionKeyMAC, desfire_get_key_length(ctx->keyType)));
PrintAndLogEx(INFO, " ENC: %s",
sprint_hex(ctx->sessionKeyEnc, desfire_get_key_length(ctx->keyType)));
}
PrintAndLogEx(INFO, " IV [%zu]: %s",
desfire_get_key_block_length(ctx->keyType),
sprint_hex(ctx->IV, desfire_get_key_block_length(ctx->keyType)));
if (ctx->secureChannel == DACEV2) {
PrintAndLogEx(INFO, " TI: %s cmdCntr: 0x%04x",
sprint_hex(ctx->TI, 4),
ctx->cmdCntr);
}
}
}
static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) {
if (result_len) *result_len = 0;
if (sw) *sw = 0;
uint16_t isw = 0;
int res = 0;
if (activate_field) {
DropField();
msleep(50);
}
uint8_t data[APDU_RES_LEN] = {0};
// COMPUTE APDU
int datalen = 0;
if (APDUEncodeS(&apdu, false, le, data, &datalen)) { // 100 == with Le
PrintAndLogEx(ERR, "APDU encoding error.");
return PM3_EAPDU_ENCODEFAIL;
}
if (GetAPDULogging())
PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, datalen));
res = ExchangeAPDU14a(data, datalen, activate_field, true, result, max_result_len, (int *)result_len);
if (res != PM3_SUCCESS) {
return res;
}
if (GetAPDULogging())
PrintAndLogEx(SUCCESS, "<<<< %s", sprint_hex(result, *result_len));
if (*result_len < 2) {
return PM3_SUCCESS;
}
*result_len -= 2;
isw = (result[*result_len] << 8) + result[*result_len + 1];
if (sw)
*sw = isw;
if (isw != ISO7816_OK &&
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_OPERATION_OK) &&
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_SIGNATURE) &&
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_ADDITIONAL_FRAME) &&
isw != DESFIRE_GET_ISO_STATUS(MFDES_S_NO_CHANGES)) {
if (GetAPDULogging()) {
if (isw >> 8 == 0x61) {
PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff);
} else {
PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [0x%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff));
return PM3_EAPDU_FAIL;
}
}
return PM3_EAPDU_FAIL;
}
return PM3_SUCCESS;
}
static int DESFIRESendApdu(bool activate_field, sAPDU_t apdu, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) {
return DESFIRESendApduEx(activate_field, apdu, APDU_INCLUDE_LE_00, result, max_result_len, result_len, sw);
}
static int DESFIRESendRaw(bool activate_field, uint8_t *data, size_t datalen, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint8_t *respcode) {
*result_len = 0;
if (respcode) {
*respcode = 0xff;
}
if (activate_field) {
DropField();
msleep(50);
}
if (GetAPDULogging()) {
PrintAndLogEx(SUCCESS, "raw>> %s", sprint_hex(data, datalen));
}
int res = ExchangeRAW14a(data, datalen, activate_field, true, result, max_result_len, (int *)result_len, true);
if (res != PM3_SUCCESS) {
return res;
}
if (GetAPDULogging()) {
PrintAndLogEx(SUCCESS, "raw<< %s", sprint_hex(result, *result_len));
}
if (*result_len < 1) {
return PM3_SUCCESS;
}
*result_len -= (1 + 2);
uint8_t rcode = result[0];
if (respcode) {
*respcode = rcode;
}
memmove(&result[0], &result[1], *result_len);
if (rcode != MFDES_S_OPERATION_OK &&
rcode != MFDES_S_SIGNATURE &&
rcode != MFDES_S_ADDITIONAL_FRAME &&
rcode != MFDES_S_NO_CHANGES) {
if (GetAPDULogging()) {
PrintAndLogEx(ERR, "Command (%02x) ERROR: 0x%02x", data[0], rcode);
}
return PM3_EAPDU_FAIL;
}
return PM3_SUCCESS;
}
static int DesfireExchangeNative(bool activate_field, DesfireContext_t *ctx, uint8_t cmd, uint8_t *data, size_t datalen, uint8_t *respcode, uint8_t *resp, size_t *resplen, bool enable_chaining, size_t splitbysize) {
if (resplen) {
*resplen = 0;
}
if (respcode) {
*respcode = 0xff;
}
uint8_t *buf = calloc(DESFIRE_BUFFER_SIZE, 1);
if (buf == NULL) {
return PM3_EMALLOC;
}
uint32_t buflen = 0;
uint32_t pos = 0;
uint32_t i = 1;
uint8_t rcode = 0xff;
uint8_t cdata[1024] = {0};
uint32_t cdatalen = 0;
cdata[0] = cmd;
memcpy(&cdata[1], data, datalen);
cdatalen = datalen + 1;
int res;
size_t len;
// tx chaining
size_t sentdatalen = 0;
while (cdatalen >= sentdatalen) {
if ((cdatalen - sentdatalen) > DESFIRE_TX_FRAME_MAX_LEN)
len = DESFIRE_TX_FRAME_MAX_LEN;
else
len = cdatalen - sentdatalen;
size_t sendindx = sentdatalen;
size_t sendlen = len;
if (sentdatalen > 0) {
sendindx--;
sendlen++;
cdata[sendindx] = MFDES_ADDITIONAL_FRAME;
}
res = DESFIRESendRaw(activate_field, &cdata[sendindx], sendlen, buf, DESFIRE_BUFFER_SIZE, &buflen, &rcode);
if (res != PM3_SUCCESS) {
uint16_t ssw = DESFIRE_GET_ISO_STATUS(rcode);
PrintAndLogEx(DEBUG, "error DESFIRESendRaw %s", DesfireGetErrorString(res, &ssw));
free(buf);
return res;
}
sentdatalen += len;
if ((rcode != MFDES_ADDITIONAL_FRAME) || (buflen > 0)) {
if (sentdatalen != cdatalen) {
PrintAndLogEx(WARNING, "Tx chaining error. Needs to send: %d but sent: %zu", cdatalen, sentdatalen);
}
break;
}
}
// rx
if (resp) {
if (splitbysize) {
resp[0] = buflen;
memcpy(&resp[1], buf, buflen);
} else {
memcpy(resp, buf, buflen);
}
}
if (respcode != NULL) {
*respcode = rcode;
}
pos += buflen;
if (enable_chaining == false) {
if (rcode == MFDES_S_OPERATION_OK ||
rcode == MFDES_ADDITIONAL_FRAME) {
if (resplen) {
*resplen = pos;
}
}
free(buf);
return PM3_SUCCESS;
}
while (rcode == MFDES_ADDITIONAL_FRAME) {
cdata[0] = MFDES_ADDITIONAL_FRAME; //0xAF
res = DESFIRESendRaw(false, cdata, 1, buf, DESFIRE_BUFFER_SIZE, &buflen, &rcode);
if (res != PM3_SUCCESS) {
uint16_t ssw = DESFIRE_GET_ISO_STATUS(rcode);
PrintAndLogEx(DEBUG, "error DESFIRESendRaw %s", DesfireGetErrorString(res, &ssw));
return res;
}
if (respcode != NULL) {
*respcode = rcode;
}
if (resp != NULL) {
if (splitbysize) {
resp[i * splitbysize] = buflen;
memcpy(&resp[i * splitbysize + 1], buf, buflen);
i += 1;
} else {
memcpy(&resp[pos], buf, buflen);
}
}
pos += buflen;
if (rcode != MFDES_ADDITIONAL_FRAME)
break;
}
if (resplen) {
*resplen = (splitbysize) ? i : pos;
}
free(buf);
return PM3_SUCCESS;
}
static int DesfireExchangeISONative(bool activate_field, DesfireContext_t *ctx, uint8_t cmd, uint8_t *data, size_t datalen, uint8_t *respcode, uint8_t *resp, size_t *resplen, bool enable_chaining, size_t splitbysize) {
if (resplen) {
*resplen = 0;
}
if (respcode) {
*respcode = 0xFF;
}
uint16_t sw = 0;
uint8_t *buf = calloc(DESFIRE_BUFFER_SIZE, 1);
if (buf == NULL) {
return PM3_EMALLOC;
}
uint32_t buflen = 0;
uint32_t pos = 0;
uint32_t i = 1;
sAPDU_t apdu = {
.CLA = MFDES_NATIVE_ISO7816_WRAP_CLA, //0x90
.INS = cmd,
.P1 = 0,
.P2 = 0,
};
int res;
// tx chaining
size_t sentdatalen = 0;
while (datalen >= sentdatalen) {
if (datalen - sentdatalen > DESFIRE_TX_FRAME_MAX_LEN) {
apdu.Lc = DESFIRE_TX_FRAME_MAX_LEN;
} else {
apdu.Lc = datalen - sentdatalen;
}
apdu.data = &data[sentdatalen];
if (sentdatalen > 0) {
apdu.INS = MFDES_ADDITIONAL_FRAME;
}
res = DESFIRESendApdu(activate_field, apdu, buf, DESFIRE_BUFFER_SIZE, &buflen, &sw);
if (res != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "error DESFIRESendApdu %s", DesfireGetErrorString(res, &sw));
free(buf);
return res;
}
sentdatalen += apdu.Lc;
if (sw != DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME) || buflen > 0) {
if (sentdatalen != datalen) {
PrintAndLogEx(WARNING, "Tx chaining error. Needs to send: %zu but sent: %zu", datalen, sentdatalen);
}
break;
}
}
if (respcode != NULL && ((sw & 0xFF00) == 0x9100)) {
*respcode = sw & 0xFF;
}
if (resp) {
if (splitbysize) {
resp[0] = buflen;
memcpy(&resp[1], buf, buflen);
} else {
memcpy(resp, buf, buflen);
}
}
pos += buflen;
if (enable_chaining == false) {
if (sw == DESFIRE_GET_ISO_STATUS(MFDES_S_OPERATION_OK) ||
sw == DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) {
if (resplen) {
*resplen = pos;
}
}
free(buf);
return PM3_SUCCESS;
}
while (sw == DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) {
apdu.CLA = MFDES_NATIVE_ISO7816_WRAP_CLA; //0x90
apdu.INS = MFDES_ADDITIONAL_FRAME; //0xAF
apdu.Lc = 0;
apdu.P1 = 0;
apdu.P2 = 0;
apdu.data = NULL;
buflen = 0;
res = DESFIRESendApdu(false, apdu, buf, DESFIRE_BUFFER_SIZE, &buflen, &sw);
if (res != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "error DESFIRESendApdu %s", DesfireGetErrorString(res, &sw));
free(buf);
return res;
}
if (respcode != NULL && ((sw & 0xFF00) == 0x9100)) {
*respcode = sw & 0xFF;
}
if (resp != NULL) {
if (splitbysize) {
resp[i * splitbysize] = buflen;
memcpy(&resp[i * splitbysize + 1], buf, buflen);
i += 1;
} else {
memcpy(resp + (pos), buf, buflen);
}
}
pos += buflen;
if (sw != DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) {
break;
}
}
if (resplen) {
*resplen = (splitbysize) ? i : pos;
}
free(buf);
return PM3_SUCCESS;
}
static int DesfireExchangeISO(bool activate_field, DesfireContext_t *ctx, sAPDU_t apdu, uint16_t le, uint8_t *resp, size_t *resplen, uint16_t *sw) {
uint8_t *data = calloc(DESFIRE_BUFFER_SIZE, 1);
if (data == NULL) {
return PM3_EMALLOC;
}
uint32_t datalen = 0;
int res = DESFIRESendApduEx(activate_field, apdu, le, data, DESFIRE_BUFFER_SIZE, &datalen, sw);
if (res == PM3_SUCCESS) {
DesfireSecureChannelDecode(ctx, data, datalen, 0, resp, resplen);
}
free(data);
return res;
}
// move data from blockdata [format: <length, data><length, data>...] to single data block
static void DesfireJoinBlockToBytes(uint8_t *blockdata, size_t blockdatacount, size_t blockdatasize, uint8_t *dstdata, size_t *dstdatalen) {
*dstdatalen = 0;
for (int i = 0; i < blockdatacount; i++) {
memcpy(&dstdata[*dstdatalen], &blockdata[i * blockdatasize + 1], blockdata[i * blockdatasize]);
*dstdatalen += blockdata[i * blockdatasize];
}
}
// move data from single data block to blockdata [format: <length, data><length, data>...]
// lengths in the blockdata is not changed. result - in the blockdata
static void DesfireSplitBytesToBlock(uint8_t *blockdata, size_t *blockdatacount, size_t blockdatasize, uint8_t *dstdata, size_t dstdatalen) {
size_t len = 0;
for (int i = 0; i < *blockdatacount; i++) {
memset(&blockdata[i * blockdatasize + 1], 0, blockdatasize - 1);
size_t tlen = len + blockdata[i * blockdatasize];
if (tlen > dstdatalen) {
tlen = dstdatalen;
if (tlen >= len)
blockdata[i * blockdatasize] = tlen - len;
else
blockdata[i * blockdatasize] = 0;
}
if (len == tlen) {
*blockdatacount = i;
break;
}
memcpy(&blockdata[i * blockdatasize + 1], &dstdata[len], tlen - len);
len = tlen;
}
}
int DesfireExchangeEx(bool activate_field, DesfireContext_t *ctx, uint8_t cmd, uint8_t *data, size_t datalen, uint8_t *respcode,
uint8_t *resp, size_t *resplen, bool enable_chaining, size_t splitbysize) {
int res = PM3_SUCCESS;
if (PrintChannelModeWarning(cmd, ctx->secureChannel, ctx->cmdSet, ctx->commMode) == false) {
DesfirePrintContext(ctx);
}
uint8_t *databuf = calloc(DESFIRE_BUFFER_SIZE, 1);
if (databuf == NULL) {
return PM3_EMALLOC;
}
size_t databuflen = 0;
switch (ctx->cmdSet) {
case DCCNative:
case DCCNativeISO:
DesfireSecureChannelEncode(ctx, cmd, data, datalen, databuf, &databuflen);
if (ctx->cmdSet == DCCNative) {
res = DesfireExchangeNative(activate_field, ctx, cmd, databuf, databuflen, respcode, databuf, &databuflen, enable_chaining, splitbysize);
} else {
res = DesfireExchangeISONative(activate_field, ctx, cmd, databuf, databuflen, respcode, databuf, &databuflen, enable_chaining, splitbysize);
}
if (splitbysize) {
uint8_t sdata[DESFIRE_BUFFER_SIZE] = {0};
size_t sdatalen = 0;
DesfireJoinBlockToBytes(databuf, databuflen, splitbysize, sdata, &sdatalen);
//PrintAndLogEx(INFO, "block : %s", sprint_hex(sdata, sdatalen));
DesfireSecureChannelDecode(ctx, sdata, sdatalen, *respcode, resp, resplen);
DesfireSplitBytesToBlock(databuf, &databuflen, splitbysize, resp, *resplen);
memcpy(resp, databuf, databuflen * splitbysize);
*resplen = databuflen;
} else {
DesfireSecureChannelDecode(ctx, databuf, databuflen, *respcode, resp, resplen);
}
break;
case DCCISO:
free(databuf);
return PM3_EAPDU_FAIL;
break;
}
free(databuf);
return res;
}
int DesfireExchange(DesfireContext_t *ctx, uint8_t cmd, uint8_t *data, size_t datalen, uint8_t *respcode, uint8_t *resp, size_t *resplen) {
return DesfireExchangeEx(false, ctx, cmd, data, datalen, respcode, resp, resplen, true, 0);
}
int DesfireSelectAID(DesfireContext_t *ctx, uint8_t *aid1, uint8_t *aid2) {
if (aid1 == NULL) {
return PM3_EINVARG;
}
uint8_t data[6] = {0};
memcpy(data, aid1, 3);
if (aid2 != NULL) {
memcpy(&data[3], aid2, 3);
}
uint8_t resp[257] = {0};
size_t resplen = 0;
uint8_t respcode = 0;
ctx->secureChannel = DACNone;
int res = DesfireExchangeEx(true, ctx, MFDES_SELECT_APPLICATION, data, (aid2 == NULL) ? 3 : 6, &respcode, resp, &resplen, true, 0);
if (res == PM3_SUCCESS) {
if (resplen != 0) {
return PM3_ECARDEXCHANGE;
}
// select operation fail
if (respcode != MFDES_S_OPERATION_OK) {
return PM3_EAPDU_FAIL;
}
DesfireClearSession(ctx);
ctx->appSelected = (aid1[0] != 0x00 || aid1[1] != 0x00 || aid1[2] != 0x00);
ctx->selectedAID = DesfireAIDByteToUint(aid1);
return PM3_SUCCESS;
}
return res;
}
int DesfireSelectAIDHex(DesfireContext_t *ctx, uint32_t aid1, bool select_two, uint32_t aid2) {
uint8_t data[6] = {0};
DesfireAIDUintToByte(aid1, data);
DesfireAIDUintToByte(aid2, &data[3]);
return DesfireSelectAID(ctx, data, (select_two) ? &data[3] : NULL);
}
int DesfireSelectAIDHexNoFieldOn(DesfireContext_t *ctx, uint32_t aid) {
uint8_t data[3] = {0};
DesfireAIDUintToByte(aid, data);
uint8_t resp[257] = {0};
size_t resplen = 0;
uint8_t respcode = 0;
ctx->secureChannel = DACNone;
int res = DesfireExchangeEx(false, ctx, MFDES_SELECT_APPLICATION, data, 3, &respcode, resp, &resplen, true, 0);
if (res == PM3_SUCCESS) {
if (resplen != 0)
return PM3_ECARDEXCHANGE;
// select operation fail
if (respcode != MFDES_S_OPERATION_OK)
return PM3_EAPDU_FAIL;
DesfireClearSession(ctx);
ctx->appSelected = (aid != 0x000000);
ctx->selectedAID = aid;
return PM3_SUCCESS;
}
return res;
}
void DesfirePrintMADAID(uint32_t appid, bool verbose) {
uint8_t aid[3] = {0};
DesfireAIDUintToByte(appid, aid);
if ((aid[2] >> 4) != 0xF)
return;
uint16_t short_aid = ((aid[2] & 0xF) << 12) | (aid[1] << 4) | (aid[0] >> 4);
PrintAndLogEx(SUCCESS, "MIFARE Classic ID (MAD): " _YELLOW_("%04X") " ver: " _YELLOW_("%01X") " AID: " _YELLOW_("%06x") " MAD AID Cluster[0x%02X]: " _YELLOW_("%s"),
short_aid,
appid & 0x0f,
appid,
short_aid >> 8,
nxp_cluster_to_text(short_aid >> 8));
if (verbose) {
if (appid == 0xffffff)
PrintAndLogEx(SUCCESS, " Card issuer information application");
else