forked from RfidResearchGroup/proxmark3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmdhfmf.c
More file actions
10165 lines (8606 loc) · 364 KB
/
Copy pathcmdhfmf.c
File metadata and controls
10165 lines (8606 loc) · 364 KB
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
//-----------------------------------------------------------------------------
// 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 MIFARE commands
//-----------------------------------------------------------------------------
#include "cmdhfmf.h"
#include <ctype.h>
#include "bruteforce.h"
#include "cmdparser.h" // command_t
#include "commonutil.h" // ARRAYLEN
#include "comms.h" // clearCommandBuffer
#include "fileutils.h"
#include "cmdtrace.h"
#include "mifare/mifaredefault.h" // mifare default key array
#include "cliparser.h" // argtable
#include "hardnested_bf_core.h" // SetSIMDInstr
#include "mifare/mad.h"
#include "nfc/ndef.h"
#include "protocols.h"
#include "util_posix.h" // msclock
#include "cmdhfmfhard.h"
#include "crapto1/crapto1.h" // prng_successor
#include "cmdhf14a.h" // exchange APDU
#include "crypto/libpcrypto.h"
#include "wiegand_formats.h"
#include "wiegand_formatutils.h"
#include "cmdhw.h" // set_fpga_mode
#include "loclass/cipherutils.h" // BitstreamOut_t
#include "proxendian.h"
#include "preferences.h"
#include "mifare/gen4.h"
#include "generator.h" // keygens.
#include "fpga.h"
#include "mifare/mifarehost.h"
static int CmdHelp(const char *Cmd);
/*
static int usage_hf14_keybrute(void) {
PrintAndLogEx(NORMAL, "J_Run's 2nd phase of multiple sector nested authentication key recovery");
PrintAndLogEx(NORMAL, "You have a known 4 last bytes of a key recovered with mf_nonce_brute tool.");
PrintAndLogEx(NORMAL, "First 2 bytes of key will be bruteforced");
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, " ---[ This attack is obsolete, try hardnested instead ]---");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h this help");
PrintAndLogEx(NORMAL, " <block number> target block number");
PrintAndLogEx(NORMAL, " <A|B> target key type");
PrintAndLogEx(NORMAL, " <key> candidate key from mf_nonce_brute tool");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, _YELLOW_(" hf mf keybrute --blk 1 -k 000011223344"));
return 0;
}
*/
int mfc_ev1_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature, int signature_len) {
// ref: MIFARE Classic EV1 Originality Signature Validation
#define PUBLIC_MFCEV1_ECDA_KEYLEN 33
const ecdsa_publickey_t nxp_mfc_public_keys[] = {
{"NXP MIFARE Classic MFC1C14_x", "044F6D3F294DEA5737F0F46FFEE88A356EED95695DD7E0C27A591E6F6F65962BAF"},
{"MIFARE Classic / QL88", "046F70AC557F5461CE5052C8E4A7838C11C7A236797E8A0730A101837C004039C2"},
{"NXP ICODE DNA, ICODE SLIX2", "048878A2A2D3EEC336B4F261A082BD71F9BE11C4E2E896648B32EFA59CEA6E59F0"},
{"NXP Public key", "04A748B6A632FBEE2C0897702B33BEA1C074998E17B84ACA04FF267E5D2C91F6DC"},
{"NXP Ultralight Ev1", "0490933BDCD6E99B4E255E3DA55389A827564E11718E017292FAF23226A96614B8"},
{"NXP NTAG21x (2013)", "04494E1A386D3D3CFE3DC10E5DE68A499B1C202DB5B132393E89ED19FE5BE8BC61"},
{"MIKRON Public key", "04F971EDA742A4A80D32DCF6A814A707CC3DC396D35902F72929FDCD698B3468F2"},
{"VivoKey Spark1 Public key", "04D64BB732C0D214E7EC580736ACF847284B502C25C0F7F2FA86AACE1DADA4387A"},
{"TruST25 (ST) key 01?", "041D92163650161A2548D33881C235D0FB2315C2C31A442F23C87ACF14497C0CBA"},
{"TruST25 (ST) key 04?", "04101E188A8B4CDDBC62D5BC3E0E6850F0C2730E744B79765A0E079907FBDB01BC"},
};
uint8_t i;
bool is_valid = false;
for (i = 0; i < ARRAYLEN(nxp_mfc_public_keys); i++) {
int dl = 0;
uint8_t key[PUBLIC_MFCEV1_ECDA_KEYLEN];
param_gethex_to_eol(nxp_mfc_public_keys[i].value, 0, key, PUBLIC_MFCEV1_ECDA_KEYLEN, &dl);
int res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP128R1, key, uid, uidlen, signature, signature_len, false);
is_valid = (res == 0);
if (is_valid)
break;
}
PrintAndLogEx(INFO, "");
PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature"));
if (is_valid == false || i == ARRAYLEN(nxp_mfc_public_keys)) {
PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp128r1");
PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 32));
PrintAndLogEx(SUCCESS, " Signature verification: " _RED_("failed"));
return PM3_ESOFT;
}
PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_mfc_public_keys[i].desc);
PrintAndLogEx(INFO, "IC signature public key value: %s", nxp_mfc_public_keys[i].value);
PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp128r1");
PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 32));
PrintAndLogEx(SUCCESS, " Signature verification: " _GREEN_("successful"));
return PM3_SUCCESS;
}
static int mf_read_uid(uint8_t *uid, int *uidlen, int *nxptype) {
clearCommandBuffer();
SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_CONNECT, 0, 0, NULL, 0);
PacketResponseNG resp;
if (WaitForResponseTimeout(CMD_ACK, &resp, 2500) == false) {
PrintAndLogEx(DEBUG, "iso14443a card select failed");
DropField();
return PM3_ERFTRANS;
}
iso14a_card_select_t card;
memcpy(&card, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t));
if (nxptype) {
uint64_t select_status = resp.oldarg[0];
*nxptype = detect_nxp_card(card.sak, ((card.atqa[1] << 8) + card.atqa[0]), select_status);
}
memcpy(uid, card.uid, card.uidlen * sizeof(uint8_t));
*uidlen = card.uidlen;
return PM3_SUCCESS;
}
static char *GenerateFilename(const char *prefix, const char *suffix) {
if (! IfPm3Iso14443a()) {
return NULL;
}
uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int uidlen = 0;
char *fptr = calloc(sizeof(char) * (strlen(prefix) + strlen(suffix)) + sizeof(uid) * 2 + 1, sizeof(uint8_t));
int res = mf_read_uid(uid, &uidlen, NULL);
if (res != PM3_SUCCESS || !uidlen) {
PrintAndLogEx(WARNING, "No tag found.");
free(fptr);
return NULL;
}
strcpy(fptr, prefix);
FillFileNameByUID(fptr, uid, suffix, uidlen);
return fptr;
}
static int initSectorTable(sector_t **src, size_t items) {
(*src) = calloc(items, sizeof(sector_t));
if (*src == NULL)
return PM3_EMALLOC;
// empty e_sector
for (size_t i = 0; i < items; i++) {
for (uint8_t j = 0; j < 2; j++) {
(*src)[i].Key[j] = 0xffffffffffff;
(*src)[i].foundKey[j] = 0;
}
}
return PM3_SUCCESS;
}
static void decode_print_st(uint16_t blockno, uint8_t *data) {
if (mfIsSectorTrailer(blockno)) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "-------------------------- " _CYAN_("Sector trailer decoder") " --------------------------");
PrintAndLogEx(INFO, "key A........ " _GREEN_("%s"), sprint_hex_inrow(data, 6));
PrintAndLogEx(INFO, "acr.......... " _GREEN_("%s"), sprint_hex_inrow(data + 6, 3));
PrintAndLogEx(INFO, "user / gpb... " _GREEN_("%02x"), data[9]);
PrintAndLogEx(INFO, "key B........ " _GREEN_("%s"), sprint_hex_inrow(data + 10, 6));
PrintAndLogEx(INFO, "");
PrintAndLogEx(INFO, " # | access rights");
PrintAndLogEx(INFO, "----+-----------------------------------------------------------------------");
if (mfValidateAccessConditions(&data[6]) == false) {
PrintAndLogEx(WARNING, _RED_("Invalid Access Conditions"));
}
int bln = mfFirstBlockOfSector(mfSectorNum(blockno));
int blinc = (mfNumBlocksPerSector(mfSectorNum(blockno)) > 4) ? 5 : 1;
for (int i = 0; i < 4; i++) {
PrintAndLogEx(INFO, "%3d%c| " _YELLOW_("%s"), bln, ((blinc > 1) && (i < 3) ? '+' : ' '), mfGetAccessConditionsDesc(i, &data[6]));
bln += blinc;
if (i == 3) {
uint8_t cond = mf_get_accesscondition(i, &data[6]);
if (cond == 0 || cond == 1 || cond == 2) {
PrintAndLogEx(INFO, "");
PrintAndLogEx(INFO, "OBS! Key B is readable, it SHALL NOT be able to authenticate on original MFC");
}
}
}
PrintAndLogEx(INFO, "----------------------------------------------------------------------------");
PrintAndLogEx(NORMAL, "");
}
}
static uint8_t NumOfSectors(char card) {
switch (card) {
case '0' :
return MIFARE_MINI_MAXSECTOR;
case '1' :
return MIFARE_1K_MAXSECTOR;
case '2' :
return MIFARE_2K_MAXSECTOR;
case '4' :
return MIFARE_4K_MAXSECTOR;
default :
return 0;
}
}
static char GetFormatFromSector(uint8_t sectors) {
switch (sectors) {
case MIFARE_MINI_MAXSECTOR:
return '0';
case MIFARE_1K_MAXSECTOR:
return '1';
case MIFARE_2K_MAXSECTOR:
return '2';
case MIFARE_4K_MAXSECTOR:
return '4';
default :
return ' ';
}
}
bool mfc_value(const uint8_t *d, int32_t *val) {
// values
int32_t a = (int32_t)MemLeToUint4byte(d);
uint32_t a_inv = MemLeToUint4byte(d + 4);
uint32_t b = MemLeToUint4byte(d + 8);
int val_checks = (
(a == b) && (a == ~a_inv) &&
(d[12] == (~d[13] & 0xFF)) &&
(d[14] == (~d[15] & 0xFF))
);
if (val) {
*val = a;
}
return val_checks;
}
void mf_print_block_one(uint8_t blockno, uint8_t *d, bool verbose) {
if (blockno == 0) {
char ascii[24] = {0};
ascii_to_buffer((uint8_t *)ascii, d, MFBLOCK_SIZE, sizeof(ascii) - 1, 1);
PrintAndLogEx(INFO, "%3d | " _RED_("%s") "| " _RED_("%s"),
blockno,
sprint_hex(d, MFBLOCK_SIZE),
ascii
);
} else if (mfIsSectorTrailer(blockno)) {
char keya[26] = {0};
hex_to_buffer((uint8_t *)keya, d, MIFARE_KEY_SIZE, sizeof(keya) - 1, 0, 1, true);
char acl[20] = {0};
hex_to_buffer((uint8_t *)acl, d + MIFARE_KEY_SIZE, 3, sizeof(acl) - 1, 0, 1, true);
char keyb[26] = {0};
hex_to_buffer((uint8_t *)keyb, d + 10, MIFARE_KEY_SIZE, sizeof(keyb) - 1, 0, 1, true);
char ascii[24] = {0};
ascii_to_buffer((uint8_t *)ascii, d, MFBLOCK_SIZE, sizeof(ascii) - 1, 1);
PrintAndLogEx(INFO, "%3d | " _YELLOW_("%s") _MAGENTA_("%s") "%02X " _YELLOW_("%s") "| " _YELLOW_("%s"),
blockno,
keya,
acl,
d[9],
keyb,
ascii
);
} else {
int32_t value = 0;
if (verbose && mfc_value(d, &value)) {
PrintAndLogEx(INFO, "%3d | " _CYAN_("%s") " %"PRIi32, blockno, sprint_hex_ascii(d, MFBLOCK_SIZE), value);
} else {
PrintAndLogEx(INFO, "%3d | %s ", blockno, sprint_hex_ascii(d, MFBLOCK_SIZE));
}
}
}
static void mf_print_block(uint8_t blockno, uint8_t *d, bool verbose) {
uint8_t sectorno = mfSectorNum(blockno);
char secstr[6] = " ";
if (mfFirstBlockOfSector(sectorno) == blockno) {
sprintf(secstr, " %3d ", sectorno);
}
if (blockno == 0) {
char ascii[24] = {0};
ascii_to_buffer((uint8_t *)ascii, d, MFBLOCK_SIZE, sizeof(ascii) - 1, 1);
PrintAndLogEx(INFO, "%s| %3d | " _RED_("%s") "| " _RED_("%s"),
secstr,
blockno,
sprint_hex(d, MFBLOCK_SIZE),
ascii
);
} else if (mfIsSectorTrailer(blockno)) {
char keya[26] = {0};
hex_to_buffer((uint8_t *)keya, d, MIFARE_KEY_SIZE, sizeof(keya) - 1, 0, 1, true);
char acl[20] = {0};
hex_to_buffer((uint8_t *)acl, d + MIFARE_KEY_SIZE, 3, sizeof(acl) - 1, 0, 1, true);
char keyb[26] = {0};
hex_to_buffer((uint8_t *)keyb, d + 10, MIFARE_KEY_SIZE, sizeof(keyb) - 1, 0, 1, true);
char ascii[24] = {0};
ascii_to_buffer((uint8_t *)ascii, d, MFBLOCK_SIZE, sizeof(ascii) - 1, 1);
PrintAndLogEx(INFO, "%s| %3d | " _YELLOW_("%s") _MAGENTA_("%s") "%02X " _YELLOW_("%s") "| " _YELLOW_("%s"),
secstr,
blockno,
keya,
acl,
d[9],
keyb,
ascii
);
} else {
int32_t value = 0;
if (verbose && mfc_value(d, &value)) {
PrintAndLogEx(INFO, "%s| %3d | " _CYAN_("%s") " %"PRIi32, secstr, blockno, sprint_hex_ascii(d, MFBLOCK_SIZE), value);
} else {
PrintAndLogEx(INFO, "%s| %3d | %s ", secstr, blockno, sprint_hex_ascii(d, MFBLOCK_SIZE));
}
}
}
static void mf_print_blocks(uint16_t n, uint8_t *d, bool verbose) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "-----+-----+-------------------------------------------------+-----------------");
PrintAndLogEx(INFO, " sec | blk | data | ascii");
PrintAndLogEx(INFO, "-----+-----+-------------------------------------------------+-----------------");
for (uint16_t i = 0; i < n; i++) {
mf_print_block(i, d + (i * MFBLOCK_SIZE), verbose);
}
PrintAndLogEx(INFO, "-----+-----+-------------------------------------------------+-----------------");
if (verbose) {
PrintAndLogEx(HINT, _CYAN_("cyan") " = value block with decoded value");
}
// MAD detection
if (HasMADKey(d)) {
PrintAndLogEx(HINT, "MAD key detected. Try " _YELLOW_("`hf mf mad`") " for more details");
}
PrintAndLogEx(NORMAL, "");
}
// assumes n is in number of blocks 0..255
static int mf_print_keys(uint16_t n, uint8_t *d) {
uint8_t sectors = 0;
switch (n) {
case MIFARE_MINI_MAXBLOCK:
sectors = MIFARE_MINI_MAXSECTOR;
break;
case MIFARE_2K_MAXBLOCK:
sectors = MIFARE_2K_MAXSECTOR;
break;
case MIFARE_4K_MAXBLOCK:
sectors = MIFARE_4K_MAXSECTOR;
break;
case MIFARE_1K_MAXBLOCK:
sectors = MIFARE_1K_MAXSECTOR;
break;
default:
sectors = MIFARE_1K_MAXSECTOR;
n = MIFARE_1K_MAXBLOCK;
break;
}
sector_t *e_sector = calloc(sectors, sizeof(sector_t));
if (e_sector == NULL) {
return PM3_EMALLOC;
}
for (uint16_t i = 0; i < n; i++) {
if (mfIsSectorTrailer(i) == false) {
continue;
}
// zero based index...
uint8_t lookup = mfSectorNum(i);
uint8_t sec = MIN(sectors - 1, lookup);
e_sector[sec].foundKey[0] = 1;
e_sector[sec].Key[0] = bytes_to_num(d + (i * MFBLOCK_SIZE), MIFARE_KEY_SIZE);
e_sector[sec].foundKey[1] = 1;
e_sector[sec].Key[1] = bytes_to_num(d + (i * MFBLOCK_SIZE) + 10, MIFARE_KEY_SIZE);
}
printKeyTable(sectors, e_sector);
free(e_sector);
return PM3_SUCCESS;
}
// MFC dump , extract and save the keys to key file
// assumes n is in number of blocks 0..255
static int mf_save_keys_from_arr(uint16_t n, uint8_t *d) {
uint8_t sectors = 0;
switch (n) {
case MIFARE_MINI_MAXBLOCK:
sectors = MIFARE_MINI_MAXSECTOR;
break;
case MIFARE_2K_MAXBLOCK:
sectors = MIFARE_2K_MAXSECTOR;
break;
case MIFARE_4K_MAXBLOCK:
sectors = MIFARE_4K_MAXSECTOR;
break;
case MIFARE_1K_MAXBLOCK:
default:
sectors = MIFARE_1K_MAXSECTOR;
break;
}
uint16_t keysize = 2 * MIFARE_KEY_SIZE * sectors;
uint8_t *keys = calloc(keysize, sizeof(uint8_t));
if (keys == NULL) {
return PM3_EMALLOC;
}
uint8_t sector = 0;
for (uint16_t i = 0; i < n; i++) {
if (mfIsSectorTrailer(i)) {
// key A offset in ST block
memcpy(keys + (MIFARE_KEY_SIZE * sector), d + (i * MFBLOCK_SIZE), MIFARE_KEY_SIZE);
// key B offset in ST block
memcpy(keys + (MIFARE_KEY_SIZE * sectors) + (MIFARE_KEY_SIZE * sector), d + (i * MFBLOCK_SIZE) + 10, MIFARE_KEY_SIZE);
sector++;
}
}
char fn[FILE_PATH_SIZE] = {0};
snprintf(fn, sizeof(fn), "hf-mf-%s-key", sprint_hex_inrow(d, 4));
saveFileEx(fn, ".bin", keys, keysize, spDump);
free(keys);
return PM3_SUCCESS;
}
/*
static void mf_print_values(uint16_t n, uint8_t *d) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "Looking for value blocks...");
PrintAndLogEx(NORMAL, "");
uint8_t cnt = 0;
int32_t value = 0;
for (uint16_t i = 0; i < n; i++) {
if (mfc_value(d + (i * MFBLOCK_SIZE), &value)) {
PrintAndLogEx(INFO, "%03d | " _YELLOW_("%" PRIi32) " " _YELLOW_("0x%" PRIX32), i, value, value);
++cnt;
}
}
if (cnt) {
PrintAndLogEx(INFO, "Found %u value blocks in file", cnt);
PrintAndLogEx(NORMAL, "");
}
}
*/
void mf_print_sector_hdr(uint8_t sector) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, " # | sector " _GREEN_("%02d") " / " _GREEN_("0x%02X") " | ascii", sector, sector);
PrintAndLogEx(INFO, "----+-------------------------------------------------+-----------------");
}
// assumes n is in number of blocks 0..255
static void mf_analyse_acl(uint16_t n, uint8_t *d) {
for (uint16_t b = 3; b < n; b++) {
if (mfIsSectorTrailer(b) == false) {
continue;
}
uint8_t block[MFBLOCK_SIZE] = {0x00};
memcpy(block, d + (b * MFBLOCK_SIZE), MFBLOCK_SIZE);
// ensure access right isn't messed up.
if (mfValidateAccessConditions(&block[6]) == false) {
PrintAndLogEx(WARNING, "Invalid Access Conditions on sector " _YELLOW_("%u"), mfSectorNum(b));
}
// Warn if ACL is strict read-only
uint8_t bar = mfNumBlocksPerSector(mfSectorNum(b));
for (uint8_t foo = 0; foo < bar; foo++) {
if (mfReadOnlyAccessConditions(foo, &block[6])) {
PrintAndLogEx(WARNING, _YELLOW_("s%u / b%u") " - Strict ReadOnly Access Conditions detected", mfSectorNum(b), b - bar + 1 + foo);
}
}
}
}
/*
Sector trailer sanity checks.
Warn if ACL is strict read-only, or invalid ACL.
*/
static int mf_analyse_st_block(uint8_t blockno, uint8_t *block, bool force) {
if (mfIsSectorTrailer(blockno) == false) {
return PM3_SUCCESS;
}
PrintAndLogEx(INFO, "Sector trailer (ST) write detected");
// ensure access right isn't messed up.
if (mfValidateAccessConditions(&block[6]) == false) {
PrintAndLogEx(WARNING, "Invalid Access Conditions detected, replacing with default values");
memcpy(block + 6, "\xFF\x07\x80\x69", 4);
}
bool ro_detected = false;
uint8_t bar = mfNumBlocksPerSector(mfSectorNum(blockno));
for (uint8_t foo = 0; foo < bar; foo++) {
if (mfReadOnlyAccessConditions(foo, &block[6])) {
PrintAndLogEx(WARNING, "Strict ReadOnly Access Conditions on block " _YELLOW_("%u") " detected", blockno - bar + 1 + foo);
ro_detected = true;
}
}
if (ro_detected) {
if (force) {
PrintAndLogEx(WARNING, " --force override, continuing...");
} else {
PrintAndLogEx(INFO, "Exiting, please run `" _YELLOW_("hf mf acl -d %s") "` to understand", sprint_hex_inrow(&block[6], 3));
PrintAndLogEx(INFO, "Use `" _YELLOW_("--force") "` to override and write this data");
return PM3_EINVARG;
}
} else {
PrintAndLogEx(SUCCESS, "ST checks ( " _GREEN_("ok") " )");
}
return PM3_SUCCESS;
}
/* Reads data from tag
* @param card: (output) card info
* @param carddata: (output) card data
* @param numSectors: size of the card
* @param keyFileName: filename containing keys or NULL.
*/
static int mfc_read_tag(iso14a_card_select_t *card, uint8_t *carddata, uint8_t numSectors, char *keyfn) {
// Select card to get UID/UIDLEN/ATQA/SAK information
clearCommandBuffer();
SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_CONNECT, 0, 0, NULL, 0);
PacketResponseNG resp;
if (WaitForResponseTimeout(CMD_ACK, &resp, 1500) == false) {
PrintAndLogEx(DEBUG, "iso14443a card select timeout");
return PM3_ETIMEOUT;
}
uint64_t select_status = resp.oldarg[0];
if (select_status == 0) {
PrintAndLogEx(DEBUG, "iso14443a card select failed");
return PM3_ESOFT;
}
// store card info
memcpy(card, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t));
char *fptr = NULL;
if (keyfn == NULL || keyfn[0] == '\0') {
fptr = GenerateFilename("hf-mf-", "-key.bin");
if (fptr == NULL)
return PM3_ESOFT;
keyfn = fptr ;
}
PrintAndLogEx(INFO, "Using... %s", keyfn);
size_t alen = 0, blen = 0;
uint8_t *keyA, *keyB;
if (loadFileBinaryKey(keyfn, "", (void **)&keyA, (void **)&keyB, &alen, &blen) != PM3_SUCCESS) {
free(fptr);
return PM3_ESOFT;
}
PrintAndLogEx(INFO, "Reading sector access bits...");
PrintAndLogEx(INFO, "." NOLF);
uint8_t rights[40][4] = {0};
mf_readblock_t payload;
uint8_t current_key;
for (uint8_t sectorNo = 0; sectorNo < numSectors; sectorNo++) {
current_key = MF_KEY_A;
for (uint8_t tries = 0; tries < MIFARE_SECTOR_RETRY; tries++) {
PrintAndLogEx(NORMAL, "." NOLF);
fflush(stdout);
if (kbd_enter_pressed()) {
PrintAndLogEx(WARNING, "\naborted via keyboard!\n");
free(fptr);
free(keyA);
free(keyB);
return PM3_EOPABORTED;
}
payload.blockno = mfFirstBlockOfSector(sectorNo) + mfNumBlocksPerSector(sectorNo) - 1;
payload.keytype = current_key;
memcpy(payload.key, (current_key == MF_KEY_A) ? keyA + (sectorNo * MIFARE_KEY_SIZE) : keyB + (sectorNo * MIFARE_KEY_SIZE), MIFARE_KEY_SIZE);
clearCommandBuffer();
SendCommandNG(CMD_HF_MIFARE_READBL, (uint8_t *)&payload, sizeof(mf_readblock_t));
if (WaitForResponseTimeout(CMD_HF_MIFARE_READBL, &resp, 1500)) {
uint8_t *data = resp.data.asBytes;
if (resp.status == PM3_SUCCESS) {
rights[sectorNo][0] = ((data[7] & 0x10) >> 2) | ((data[8] & 0x1) << 1) | ((data[8] & 0x10) >> 4); // C1C2C3 for data area 0
rights[sectorNo][1] = ((data[7] & 0x20) >> 3) | ((data[8] & 0x2) << 0) | ((data[8] & 0x20) >> 5); // C1C2C3 for data area 1
rights[sectorNo][2] = ((data[7] & 0x40) >> 4) | ((data[8] & 0x4) >> 1) | ((data[8] & 0x40) >> 6); // C1C2C3 for data area 2
rights[sectorNo][3] = ((data[7] & 0x80) >> 5) | ((data[8] & 0x8) >> 2) | ((data[8] & 0x80) >> 7); // C1C2C3 for sector trailer
break;
} else if (tries == (MIFARE_SECTOR_RETRY / 2)) { // after half unsuccessful tries, give key B a go
PrintAndLogEx(WARNING, "\nTrying with " _YELLOW_("key B") " instead...");
current_key = MF_KEY_B;
PrintAndLogEx(INFO, "." NOLF);
} else if (tries == (MIFARE_SECTOR_RETRY - 1)) { // on last try set defaults
PrintAndLogEx(FAILED, "\nFailed to read access rights for sector %2d ( fallback to default )", sectorNo);
rights[sectorNo][0] = rights[sectorNo][1] = rights[sectorNo][2] = 0x00;
rights[sectorNo][3] = 0x01;
}
} else {
PrintAndLogEx(FAILED, "\nTimeout reading access rights for sector... %2d ( fallback to default )", sectorNo);
rights[sectorNo][0] = rights[sectorNo][1] = rights[sectorNo][2] = 0x00;
rights[sectorNo][3] = 0x01;
}
}
}
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(SUCCESS, "Finished reading sector access bits");
PrintAndLogEx(INFO, "Dumping all blocks from card...");
for (uint8_t sectorNo = 0; sectorNo < numSectors; sectorNo++) {
for (uint8_t blockNo = 0; blockNo < mfNumBlocksPerSector(sectorNo); blockNo++) {
bool received = false;
current_key = MF_KEY_A;
uint8_t data_area = (sectorNo < 32) ? blockNo : blockNo / 5;
if (rights[sectorNo][data_area] == 0x07) { // no key would work
PrintAndLogEx(WARNING, "Access rights prevent reading sector... " _YELLOW_("%2d") " block... " _YELLOW_("%3d") " ( skip )", sectorNo, blockNo);
continue;
}
for (uint8_t tries = 0; tries < MIFARE_SECTOR_RETRY; tries++) {
if (mfIsSectorTrailerBasedOnBlocks(sectorNo, blockNo)) {
// sector trailer. At least the Access Conditions can always be read with key A.
payload.blockno = mfFirstBlockOfSector(sectorNo) + blockNo;
payload.keytype = current_key;
memcpy(payload.key, (current_key == MF_KEY_A) ? keyA + (sectorNo * MIFARE_KEY_SIZE) : keyB + (sectorNo * MIFARE_KEY_SIZE), MIFARE_KEY_SIZE);
clearCommandBuffer();
SendCommandNG(CMD_HF_MIFARE_READBL, (uint8_t *)&payload, sizeof(mf_readblock_t));
received = WaitForResponseTimeout(CMD_HF_MIFARE_READBL, &resp, 1500);
} else {
// data block. Check if it can be read with key A or key B
if ((rights[sectorNo][data_area] == 0x03) || (rights[sectorNo][data_area] == 0x05)) {
// only key B would work
payload.blockno = mfFirstBlockOfSector(sectorNo) + blockNo;
payload.keytype = MF_KEY_B;
memcpy(payload.key, keyB + (sectorNo * MIFARE_KEY_SIZE), MIFARE_KEY_SIZE);
clearCommandBuffer();
SendCommandNG(CMD_HF_MIFARE_READBL, (uint8_t *)&payload, sizeof(mf_readblock_t));
received = WaitForResponseTimeout(CMD_HF_MIFARE_READBL, &resp, 1500);
} else {
// key A would work
payload.blockno = mfFirstBlockOfSector(sectorNo) + blockNo;
payload.keytype = current_key;
memcpy(payload.key, (current_key == MF_KEY_A) ? keyA + (sectorNo * MIFARE_KEY_SIZE) : keyB + (sectorNo * MIFARE_KEY_SIZE), MIFARE_KEY_SIZE);
clearCommandBuffer();
SendCommandNG(CMD_HF_MIFARE_READBL, (uint8_t *)&payload, sizeof(mf_readblock_t));
received = WaitForResponseTimeout(CMD_HF_MIFARE_READBL, &resp, 1500);
}
}
if (received) {
if (resp.status == PM3_SUCCESS) {
// break the re-try loop
break;
}
if ((current_key == MF_KEY_A) && (tries == (MIFARE_SECTOR_RETRY / 2))) {
// Half the tries failed with key A. Swap for key B
current_key = MF_KEY_B;
// clear out keyA since it failed.
memset(keyA + (sectorNo * MIFARE_KEY_SIZE), 0x00, MIFARE_KEY_SIZE);
}
}
}
if (received) {
if (resp.status == PM3_SUCCESS) {
uint8_t *data = resp.data.asBytes;
if (mfIsSectorTrailerBasedOnBlocks(sectorNo, blockNo)) {
// sector trailer. Fill in the keys.
memcpy(data, keyA + (sectorNo * MIFARE_KEY_SIZE), MIFARE_KEY_SIZE);
memcpy(data + 10, keyB + (sectorNo * MIFARE_KEY_SIZE), MIFARE_KEY_SIZE);
}
memcpy(carddata + (MFBLOCK_SIZE * (mfFirstBlockOfSector(sectorNo) + blockNo)), data, MFBLOCK_SIZE);
PrintAndLogEx(INPLACE, "Sector... " _YELLOW_("%2d") " block..." _YELLOW_("%2d") " ( " _GREEN_("ok") " )", sectorNo, blockNo);
} else {
PrintAndLogEx(FAILED, "\nSector... %2d Block... %2d ( " _RED_("fail") " )", sectorNo, blockNo);
}
} else {
PrintAndLogEx(WARNING, "Timeout reading sector... %2d block... %2d", sectorNo, blockNo);
}
}
}
free(fptr);
free(keyA);
free(keyB);
PrintAndLogEx(SUCCESS, "\nSucceeded in dumping all blocks");
return PM3_SUCCESS ;
}
static int mf_load_keys(uint8_t **pkeyBlock, uint32_t *pkeycnt, uint8_t *userkey, int userkeylen, const char *filename, int fnlen, bool load_default) {
// Handle Keys
*pkeycnt = 0;
*pkeyBlock = NULL;
uint8_t *p;
// Handle user supplied key
// (it considers *pkeycnt and *pkeyBlock as possibly non-null so logic can be easily reordered)
if (userkeylen >= MIFARE_KEY_SIZE) {
int numKeys = userkeylen / MIFARE_KEY_SIZE;
p = realloc(*pkeyBlock, numKeys * MIFARE_KEY_SIZE);
if (!p) {
PrintAndLogEx(FAILED, "cannot allocate memory for Keys");
free(*pkeyBlock);
return PM3_EMALLOC;
}
*pkeyBlock = p;
memcpy(*pkeyBlock, userkey, numKeys * MIFARE_KEY_SIZE);
for (int i = 0; i < numKeys; i++) {
PrintAndLogEx(DEBUG, _YELLOW_("%2d") " - %s", i, sprint_hex(*pkeyBlock + i * MIFARE_KEY_SIZE, MIFARE_KEY_SIZE));
}
*pkeycnt += numKeys;
PrintAndLogEx(SUCCESS, "loaded " _GREEN_("%2d") " user keys", numKeys);
}
if (load_default) {
// Handle default keys
p = realloc(*pkeyBlock, (*pkeycnt + ARRAYLEN(g_mifare_default_keys)) * MIFARE_KEY_SIZE);
if (!p) {
PrintAndLogEx(FAILED, "cannot allocate memory for Keys");
free(*pkeyBlock);
return PM3_EMALLOC;
}
*pkeyBlock = p;
// Copy default keys to list
for (int i = 0; i < ARRAYLEN(g_mifare_default_keys); i++) {
num_to_bytes(g_mifare_default_keys[i], MIFARE_KEY_SIZE, (uint8_t *)(*pkeyBlock + (*pkeycnt + i) * MIFARE_KEY_SIZE));
PrintAndLogEx(DEBUG, _YELLOW_("%2d") " - %s", *pkeycnt + i, sprint_hex(*pkeyBlock + (*pkeycnt + i) * MIFARE_KEY_SIZE, MIFARE_KEY_SIZE));
}
*pkeycnt += ARRAYLEN(g_mifare_default_keys);
PrintAndLogEx(SUCCESS, "loaded " _GREEN_("%zu") " keys from hardcoded default array", ARRAYLEN(g_mifare_default_keys));
}
// Handle user supplied dictionary file
if (fnlen > 0) {
uint32_t loaded_numKeys = 0;
uint8_t *keyBlock_tmp = NULL;
int res = loadFileDICTIONARY_safe(filename, (void **) &keyBlock_tmp, MIFARE_KEY_SIZE, &loaded_numKeys);
if (res != PM3_SUCCESS || loaded_numKeys == 0 || keyBlock_tmp == NULL) {
PrintAndLogEx(FAILED, "An error occurred while loading the dictionary!");
free(keyBlock_tmp);
free(*pkeyBlock);
return PM3_EFILE;
} else {
p = realloc(*pkeyBlock, (*pkeycnt + loaded_numKeys) * MIFARE_KEY_SIZE);
if (!p) {
PrintAndLogEx(FAILED, "cannot allocate memory for Keys");
free(keyBlock_tmp);
free(*pkeyBlock);
return PM3_EMALLOC;
}
*pkeyBlock = p;
memcpy(*pkeyBlock + *pkeycnt * MIFARE_KEY_SIZE, keyBlock_tmp, loaded_numKeys * MIFARE_KEY_SIZE);
*pkeycnt += loaded_numKeys;
free(keyBlock_tmp);
}
}
return PM3_SUCCESS;
}
static int CmdHF14AMfAcl(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mf acl",
"Print decoded MIFARE access rights (ACL), \n"
" A = key A\n"
" B = key B\n"
" AB = both key A and B\n"
" ACCESS = access bytes inside sector trailer block\n"
" Increment, decrement, transfer, restore is for value blocks",
"hf mf acl\n"
"hf mf acl -d FF0780\n");
void *argtable[] = {
arg_param_begin,
arg_str1("d", "data", "<hex>", "ACL bytes specified as 3 hex bytes"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
int acllen = 0;
uint8_t acl[3] = {0};
CLIGetHexWithReturn(ctx, 1, acl, &acllen);
CLIParserFree(ctx);
PrintAndLogEx(NORMAL, "");
// look up common default ACL bytes and print a fingerprint line about it.
if (memcmp(acl, "\xFF\x07\x80", 3) == 0) {
PrintAndLogEx(INFO, "ACL... " _GREEN_("%s") " (transport configuration)", sprint_hex(acl, sizeof(acl)));
}
if (mfValidateAccessConditions(acl) == false) {
PrintAndLogEx(ERR, _RED_("Invalid Access Conditions, NEVER write these on a card!"));
}
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, " # | Access rights");
PrintAndLogEx(INFO, "----+-----------------------------------------------------------------");
for (int i = 0; i < 4; i++) {
PrintAndLogEx(INFO, "%3d | " _YELLOW_("%s"), i, mfGetAccessConditionsDesc(i, acl));
}
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
static int CmdHF14AMfDarkside(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mf darkside",
"Darkside attack",
"hf mf darkside\n"
"hf mf darkside --blk 16\n"
"hf mf darkside --blk 16 -b\n");
void *argtable[] = {
arg_param_begin,
arg_int0(NULL, "blk", "<dec> ", "Target block"),
arg_lit0("b", NULL, "Target key B instead of default key A"),
arg_int0("c", NULL, "<dec>", "Target Auth 6x"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
uint8_t blockno = arg_get_u32_def(ctx, 1, 0) & 0xFF;
uint8_t key_type = MIFARE_AUTH_KEYA;
if (arg_get_lit(ctx, 2)) {
PrintAndLogEx(INFO, "Targeting key B");
key_type = MIFARE_AUTH_KEYB;
}
uint8_t ctype = arg_get_u32_def(ctx, 3, 0) & 0xFF;
if ((ctype & 0x60) == 0x60) {
key_type = ctype;
}
CLIParserFree(ctx);
uint64_t key = 0;
uint64_t t1 = msclock();
int ret = mf_dark_side(blockno, key_type, &key);
t1 = msclock() - t1;
if (ret != PM3_SUCCESS) return ret;
PrintAndLogEx(SUCCESS, "found valid key: " _GREEN_("%012" PRIx64), key);
PrintAndLogEx(SUCCESS, "time in darkside " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0);
return PM3_SUCCESS;
}
static int CmdHF14AMfWrBl(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mf wrbl",
"Write MIFARE Classic block with 16 hex bytes of data\n"
" \n"
"Sector 0 / Block 0 - Manufacturer block\n"
"When writing to block 0 you must use a VALID block 0 data (UID, BCC, SAK, ATQA)\n"
"Writing an invalid block 0 means rendering your Magic GEN2 card undetectable. \n"
"Look in the magic_cards_notes.md file for help to resolve it.\n"
" \n"
"`--force` param is used to override warnings like bad ACL and BLOCK 0 writes.\n"
" if not specified, it will exit if detected",
"hf mf wrbl --blk 1 -d 000102030405060708090a0b0c0d0e0f\n"
"hf mf wrbl --blk 1 -k A0A1A2A3A4A5 -d 000102030405060708090a0b0c0d0e0f\n"
);
void *argtable[] = {
arg_param_begin,
arg_int1(NULL, "blk", "<dec>", "block number"),
arg_lit0("a", NULL, "input key type is key A (def)"),
arg_lit0("b", NULL, "input key type is key B"),
arg_int0("c", NULL, "<dec>", "input key type is key A + offset"),
arg_lit0(NULL, "force", "override warnings"),
arg_str0("k", "key", "<hex>", "key, 6 hex bytes"),
arg_str0("d", "data", "<hex>", "bytes to write, 16 hex bytes"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
int b = arg_get_int_def(ctx, 1, 1);
uint8_t keytype = MF_KEY_A;
if (arg_get_lit(ctx, 2) && arg_get_lit(ctx, 3)) {
CLIParserFree(ctx);
PrintAndLogEx(WARNING, "Choose one single input key type");
return PM3_EINVARG;
} else if (arg_get_lit(ctx, 3)) {
keytype = MF_KEY_B;
}
uint8_t prev_keytype = keytype;
keytype = arg_get_int_def(ctx, 4, keytype);
if ((arg_get_lit(ctx, 2) || arg_get_lit(ctx, 3)) && (keytype != prev_keytype)) {
CLIParserFree(ctx);
PrintAndLogEx(WARNING, "Choose one single input key type");
return PM3_EINVARG;
}
bool force = arg_get_lit(ctx, 5);
int keylen = 0;
uint8_t key[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
CLIGetHexWithReturn(ctx, 6, key, &keylen);
uint8_t block[MFBLOCK_SIZE] = {0x00};
int blen = 0;
CLIGetHexWithReturn(ctx, 7, block, &blen);
CLIParserFree(ctx);
if (keylen && keylen != 6) {
PrintAndLogEx(WARNING, "Key must be 12 hex digits. Got %d", keylen);
return PM3_EINVARG;
}
if (blen != MFBLOCK_SIZE) {
PrintAndLogEx(WARNING, "block data must include 16 HEX bytes. Got %i", blen);
return PM3_EINVARG;
}
if (b > 255) {
return PM3_EINVARG;
}
// BLOCK 0 detection
if (b == 0 && force == false) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "Targeting Sector 0 / Block 0 - Manufacturer block");
PrintAndLogEx(INFO, "Read the helptext for details before writing to this block");
PrintAndLogEx(INFO, "You must use param `" _YELLOW_("--force") "` to write to this block");
PrintAndLogEx(NORMAL, "");
return PM3_EINVARG;
}
uint8_t blockno = (uint8_t)b;