recover_pk.py: replace secp192r1 by prime192v1
[RRG-proxmark3.git] / armsrc / hitagS.c
blobb247d802a142977c0047818a5859b1915e6432c9
1 //-----------------------------------------------------------------------------
2 // Borrowed initially from https://github.com/Proxmark/proxmark3/pull/167/files
3 // Copyright (C) 2016 Oguzhan Cicek, Hendrik Schwartke, Ralf Spenneberg
4 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
5 //
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // See LICENSE.txt for the text of the license.
17 //-----------------------------------------------------------------------------
18 // Hitag S emulation (preliminary test version)
19 //-----------------------------------------------------------------------------
21 #include "hitagS.h"
23 #include "proxmark3_arm.h"
24 #include "cmd.h"
25 #include "BigBuf.h"
26 #include "fpgaloader.h"
27 #include "ticks.h"
28 #include "dbprint.h"
29 #include "util.h"
30 #include "string.h"
31 #include "commonutil.h"
32 #include "hitag2/hitag2_crypto.h"
33 #include "lfadc.h"
34 #include "crc.h"
35 #include "protocols.h"
36 #include "hitag.h"
37 #include "appmain.h" // tearoff_hook()
39 #define CRC_PRESET 0xFF
40 #define CRC_POLYNOM 0x1D
42 static struct hitagS_tag tag = {
43 .data.pages = {
44 // Plain mode: | Authentication mode:
45 [0] = {0x5F, 0xC2, 0x11, 0x84}, // UID | UID
46 // HITAG S 2048
47 [1] = {0xCA, 0x00, 0x00, 0xAA}, // CON0 CON1 CON2 Reserved | CON0 CON1 CON2 PWDH0
48 [2] = {0x48, 0x54, 0x4F, 0x4E}, // Data | PWDL0 PWDL1 KEYH0 KEYH1
49 [3] = {0x4D, 0x49, 0x4B, 0x52}, // Data | KEYL0 KEYL1 KEYL2 KEYL3
50 [4] = {0xFF, 0x80, 0x00, 0x00}, // Data
51 [5] = {0x00, 0x00, 0x00, 0x00}, // Data
52 [6] = {0x00, 0x00, 0x00, 0x00}, // Data
53 [7] = {0x57, 0x5F, 0x4F, 0x48}, // Data
54 // up to index 63 for HITAG S2048 public data
57 static uint8_t page_to_be_written = 0;
58 static int block_data_left = 0;
59 static bool enable_page_tearoff = false;
61 typedef enum modulation {
62 AC2K = 0,
63 AC4K,
64 MC4K,
65 MC8K
66 } MOD;
68 static uint8_t protocol_mode = HITAGS_UID_REQ_ADV1;
69 static MOD m = AC2K; // used modulation
70 static uint32_t reader_selected_uid;
71 static int rotate_uid = 0;
72 static int sof_bits; // number of start-of-frame bits
73 static uint8_t pwdh0, pwdl0, pwdl1; // password bytes
74 static uint8_t rnd[] = {0x85, 0x44, 0x12, 0x74}; // random number
75 static uint16_t timestamp_high = 0; // Timer Counter 2 overflow count, ~47min
77 #define TIMESTAMP (AT91C_BASE_TC2->TC_SR &AT91C_TC_COVFS ? timestamp_high += 1 : 0, ((timestamp_high << 16) + AT91C_BASE_TC2->TC_CV) / T0)
79 //#define SENDBIT_TEST
81 /* array index 3 2 1 0 // bytes in sim.bin file are 0 1 2 3
82 UID is 0 1 2 3 // tag.data.s.uid_le is 3210
83 datasheet HitagS_V11.pdf bytes in tables printed 3 2 1 0
85 #db# UID: 5F C2 11 84
86 #db# conf0: C9 conf1: 00 conf2: 00
87 3 2 1 0
88 #db# Page[ 0]: 84 11 C2 5F uid
89 #db# Page[ 1]: AA 00 00 C9 conf, HITAG S 256
90 #db# Page[ 2]: 4E 4F 54 48
91 #db# Page[ 3]: 52 4B 49 4D
92 #db# Page[ 4]: 00 00 00 00
93 #db# Page[ 5]: 00 00 00 00
94 #db# Page[ 6]: 00 00 00 00
95 #db# Page[ 7]: 4B 4F 5F 57 */
97 #define ht2bs_4a(a,b,c,d) (~(((a|b)&c)^(a|d)^b))
98 #define ht2bs_4b(a,b,c,d) (~(((d|c)&(a^b))^(d|a|b)))
99 #define ht2bs_5c(a,b,c,d,e) (~((((((c^e)|d)&a)^b)&(c^b))^(((d^e)|a)&((d^b)|c))))
101 // Sam7s has several timers, we will use the source TIMER_CLOCK3 (aka AT91C_TC_CLKS_TIMER_DIV3_CLOCK)
102 // TIMER_CLOCK3 = MCK/32, MCK is running at 48 MHz, Timer is running at 48MHz/32 = 1500 KHz
103 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
104 // T0 = TIMER_CLOCK3 / 125000 = 12
106 #define T0 12
108 #define HITAG_FRAME_LEN 20
110 // TC0 and TC1 are 16-bit counters and will overflow after 5461 * T0
111 // Ensure not to set these timings above 5461 (~43ms) when comparing without considering overflow, as they will never reach that value.
113 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
114 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
115 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
116 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
117 #define HITAG_T_0 20 /* T[0] should be 18..22 */
118 #define HITAG_T_1 28 /* T[1] should be 26..30 */
119 // #define HITAG_T_EOF 40 /* T_EOF should be > 36 */
120 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
121 #define HITAG_T_WAIT_RESP 200 /* T_wresp should be 204..212 */
122 #define HITAG_T_WAIT_SC 200 /* T_wsc should be 90..5000 */
123 #define HITAG_T_WAIT_FIRST 300 /* T_wfc should be 280..565 (T_ttf) */
124 #define HITAG_T_PROG_MAX 750 /* T_prog should be 716..726 */
126 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
127 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
128 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
129 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
131 #define HITAG_T_TAG_HALF_PERIOD 16
132 #define HITAG_T_TAG_FULL_PERIOD 32
134 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
135 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
136 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
137 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
140 * Implementation of the crc8 calculation from Hitag S
141 * from http://www.proxmark.org/files/Documents/125%20kHz%20-%20Hitag/HitagS.V11.pdf
143 static void calc_crc(unsigned char *crc, unsigned char data, unsigned char Bitcount) {
144 *crc ^= data; // crc = crc (exor) data
145 do {
146 if (*crc & 0x80) { // if (MSB-CRC == 1)
147 *crc <<= 1; // CRC = CRC Bit-shift left
148 *crc ^= CRC_POLYNOM; // CRC = CRC (exor) CRC_POLYNOM
149 } else {
150 *crc <<= 1; // CRC = CRC Bit-shift left
152 } while (--Bitcount);
155 static void update_tag_max_page(void) {
156 //check which memorysize this tag has
157 if (tag.data.s.config.MEMT == 0x00) {
158 tag.max_page = 32 / (HITAGS_PAGE_SIZE * 8) - 1;
159 } else if (tag.data.s.config.MEMT == 0x1) {
160 tag.max_page = 256 / (HITAGS_PAGE_SIZE * 8) - 1;
161 } else if (tag.data.s.config.MEMT == 0x2) {
162 tag.max_page = 2048 / (HITAGS_PAGE_SIZE * 8) - 1;
163 } else {
164 tag.max_page = HITAGS_MAX_PAGES - 1;
168 static void hitag_send_bit(int bit, bool ledcontrol) {
170 if (ledcontrol) LED_A_ON();
171 // Reset clock for the next bit
172 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
174 switch (m) {
175 case AC2K: {
176 if (bit == 0) {
177 // AC Coding --__
178 HIGH(GPIO_SSC_DOUT);
179 while (AT91C_BASE_TC0->TC_CV < T0 * 32) {};
181 LOW(GPIO_SSC_DOUT);
182 while (AT91C_BASE_TC0->TC_CV < T0 * 64) {};
184 } else {
185 // AC coding -_-_
186 HIGH(GPIO_SSC_DOUT);
187 while (AT91C_BASE_TC0->TC_CV < T0 * 16) {};
189 LOW(GPIO_SSC_DOUT);
190 while (AT91C_BASE_TC0->TC_CV < T0 * 32) {};
192 HIGH(GPIO_SSC_DOUT);
193 while (AT91C_BASE_TC0->TC_CV < T0 * 48) {};
195 LOW(GPIO_SSC_DOUT);
196 while (AT91C_BASE_TC0->TC_CV < T0 * 64) {};
199 if (ledcontrol) LED_A_OFF();
200 break;
202 case AC4K: {
203 if (bit == 0) {
204 // AC Coding --__
205 HIGH(GPIO_SSC_DOUT);
206 while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_TAG_HALF_PERIOD) {};
208 LOW(GPIO_SSC_DOUT);
209 while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_TAG_FULL_PERIOD) {};
211 } else {
212 // AC coding -_-_
213 HIGH(GPIO_SSC_DOUT);
214 while (AT91C_BASE_TC0->TC_CV < T0 * 8) {};
216 LOW(GPIO_SSC_DOUT);
217 while (AT91C_BASE_TC0->TC_CV < T0 * 16) {};
219 HIGH(GPIO_SSC_DOUT);
220 while (AT91C_BASE_TC0->TC_CV < T0 * 24) {};
222 LOW(GPIO_SSC_DOUT);
223 while (AT91C_BASE_TC0->TC_CV < T0 * 32) {};
225 if (ledcontrol) LED_A_OFF();
226 break;
228 case MC4K: {
229 if (bit == 0) {
230 // Manchester: Unloaded, then loaded |__--|
231 LOW(GPIO_SSC_DOUT);
232 while (AT91C_BASE_TC0->TC_CV < T0 * 16) {};
234 HIGH(GPIO_SSC_DOUT);
235 while (AT91C_BASE_TC0->TC_CV < T0 * 32) {};
237 } else {
238 // Manchester: Loaded, then unloaded |--__|
239 HIGH(GPIO_SSC_DOUT);
240 while (AT91C_BASE_TC0->TC_CV < T0 * 16) {};
242 LOW(GPIO_SSC_DOUT);
243 while (AT91C_BASE_TC0->TC_CV < T0 * 32) {};
246 if (ledcontrol) LED_A_OFF();
247 break;
249 case MC8K: {
250 if (bit == 0) {
251 // Manchester: Unloaded, then loaded |__--|
252 LOW(GPIO_SSC_DOUT);
253 while (AT91C_BASE_TC0->TC_CV < T0 * 8) {};
255 HIGH(GPIO_SSC_DOUT);
256 while (AT91C_BASE_TC0->TC_CV < T0 * 16) {};
258 } else {
259 // Manchester: Loaded, then unloaded |--__|
260 HIGH(GPIO_SSC_DOUT);
261 while (AT91C_BASE_TC0->TC_CV < T0 * 8) {};
263 LOW(GPIO_SSC_DOUT);
264 while (AT91C_BASE_TC0->TC_CV < T0 * 16) {};
267 if (ledcontrol) LED_A_OFF();
268 break;
270 default: {
271 break;
276 static void hitag_send_frame(const uint8_t *frame, size_t frame_len, bool ledcontrol) {
278 DBG Dbprintf("hitag_send_frame: (%i) %02X %02X %02X %02X", frame_len, frame[0], frame[1], frame[2], frame[3]);
280 // The beginning of the frame is hidden in some high level; pause until our bits will have an effect
281 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
282 HIGH(GPIO_SSC_DOUT);
283 switch (m) {
284 case AC4K:
285 case MC8K: {
286 while (AT91C_BASE_TC0->TC_CV < T0 * 40) {}; //FADV
287 break;
289 case AC2K:
290 case MC4K: {
291 while (AT91C_BASE_TC0->TC_CV < T0 * 20) {}; //STD + ADV
292 break;
296 // SOF - send start of frame
297 for (size_t i = 0; i < sof_bits; i++) {
298 hitag_send_bit(1, ledcontrol);
301 // Send the content of the frame
302 for (size_t i = 0; i < frame_len; i++) {
303 hitag_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1, ledcontrol);
306 LOW(GPIO_SSC_DOUT);
309 static void hitag_reader_send_bit(int bit, bool ledcontrol) {
311 if (ledcontrol) LED_A_ON();
312 // Reset clock for the next bit
313 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
314 while (AT91C_BASE_TC0->TC_CV != 0) {};
316 // Binary puls length modulation (BPLM) is used to encode the data stream
317 // This means that a transmission of a one takes longer than that of a zero
319 HIGH(GPIO_SSC_DOUT);
321 #ifdef SENDBIT_TEST
322 // Wait for 4-10 times the carrier period
323 while (AT91C_BASE_TC0->TC_CV < T0 * 6) {};
325 LOW(GPIO_SSC_DOUT);
327 if (bit == 0) {
328 // Zero bit: |_-|
329 while (AT91C_BASE_TC0->TC_CV < T0 * 11) {};
330 } else {
331 // One bit: |_--|
332 while (AT91C_BASE_TC0->TC_CV < T0 * 14) {};
334 #else
335 // Wait for 4-10 times the carrier period
336 while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_LOW) {};
338 LOW(GPIO_SSC_DOUT);
340 if (bit == 0) {
341 // Zero bit: |_-|
342 while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_0) {};
343 } else {
344 // One bit: |_--|
345 while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_1) {};
347 #endif
349 if (ledcontrol) LED_A_OFF();
352 static void hitag_reader_send_frame(const uint8_t *frame, size_t frame_len, bool ledcontrol) {
353 // Send the content of the frame
354 for (size_t i = 0; i < frame_len; i++) {
355 hitag_reader_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1, ledcontrol);
357 // send EOF
358 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
359 while (AT91C_BASE_TC0->TC_CV != 0) {};
361 HIGH(GPIO_SSC_DOUT);
363 // Wait for 4-10 times the carrier period
364 while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_LOW) {};
366 LOW(GPIO_SSC_DOUT);
369 static void hts_stop_clock(void) {
370 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
371 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
372 AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKDIS;
375 static void hts_init_clock(void) {
376 // Enable Peripheral Clock for
377 // Timer Counter 0, used to measure exact timing before answering
378 // Timer Counter 1, used to capture edges of the tag frames
379 // Timer Counter 2, used to log trace time
380 AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1) | (1 << AT91C_ID_TC2);
382 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
384 // Disable timer during configuration
385 hts_stop_clock();
387 // TC0: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), no triggers
388 AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
390 // TC1: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), TIOA is external trigger,
391 AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK // use MCK/32 (TIMER_CLOCK3)
392 | AT91C_TC_ABETRG // TIOA is used as an external trigger
393 | AT91C_TC_ETRGEDG_FALLING // external trigger on falling edge
394 | AT91C_TC_LDRA_RISING // load RA on on rising edge of TIOA
395 | AT91C_TC_LDRB_FALLING; // load RB on on falling edge of TIOA
397 // TC2: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), no triggers
398 AT91C_BASE_TC2->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
400 // Enable and reset counters
401 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
402 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
403 AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
405 // Assert a sync signal. This sets all timers to 0 on next active clock edge
406 AT91C_BASE_TCB->TCB_BCR = 1;
408 // synchronized startup procedure
409 // In theory, with MCK/32, we shouldn't be waiting longer than 32 instruction statements, right?
410 while (AT91C_BASE_TC0->TC_CV != 0) {}; // wait until TC0 returned to zero
412 // reset timestamp
413 timestamp_high = 0;
417 * to check if the right uid was selected
419 static int check_select(const uint8_t *rx, uint32_t uid) {
421 // global var?
422 concatbits((uint8_t *)&reader_selected_uid, 0, rx, 5, 32);
423 reader_selected_uid = BSWAP_32(reader_selected_uid);
425 if (reader_selected_uid == uid) {
426 return 1;
429 return 0;
432 static void hts_set_frame_modulation(uint8_t mode, bool ac_seq) {
433 switch (mode) {
434 case HITAGS_UID_REQ_STD: {
435 sof_bits = 1;
436 if (ac_seq)
437 m = AC2K;
438 else
439 m = MC4K;
440 break;
442 case HITAGS_UID_REQ_ADV1:
443 case HITAGS_UID_REQ_ADV2: {
444 if (ac_seq) {
445 sof_bits = 3;
446 m = AC2K;
447 } else {
448 sof_bits = 6;
449 m = MC4K;
451 break;
453 case HITAGS_UID_REQ_FADV: {
454 if (ac_seq) {
455 sof_bits = 3;
456 m = AC4K;
457 } else {
458 sof_bits = 6;
459 m = MC8K;
461 break;
467 * handles all commands from a reader
469 static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen,
470 uint8_t *tx, size_t *txlen) {
471 uint64_t state;
472 unsigned char crc;
474 // Reset the transmission frame length
475 *txlen = 0;
476 // Reset the frame modulation
477 hts_set_frame_modulation(protocol_mode, false);
479 // Try to find out which command was send by selecting on length (in bits)
480 switch (rxlen) {
481 case 5: {
482 //UID request with a selected response protocol mode
483 DBG Dbprintf("UID request: length: %i first byte: %02x", rxlen, rx[0]);
484 tag.pstate = HT_READY;
485 tag.tstate = HT_NO_OP;
487 if (rx[0] == HITAGS_UID_REQ_STD) {
488 DBG Dbprintf("HT_STANDARD");
489 } else if (rx[0] == HITAGS_UID_REQ_ADV1 || rx[0] == HITAGS_UID_REQ_ADV2) {
490 DBG Dbprintf("HT_ADVANCED");
491 } else if (rx[0] == HITAGS_UID_REQ_FADV) {
492 DBG Dbprintf("HT_FAST_ADVANCED");
495 protocol_mode = rx[0];
496 hts_set_frame_modulation(protocol_mode, true);
498 //send uid as a response
499 *txlen = 32;
500 memcpy(tx, tag.data.pages[HITAGS_UID_PADR], HITAGS_PAGE_SIZE);
501 break;
503 // case 14 to 44 AC SEQUENCE
504 case 45: {
505 //select command from reader received
506 DBG DbpString("SELECT");
508 if ((rx[0] & 0xf8) == HITAGS_SELECT && check_select(rx, BSWAP_32(tag.data.s.uid_le)) == 1) {
510 DBG DbpString("SELECT match");
512 //if the right tag was selected
513 *txlen = 32;
515 //send configuration
516 memcpy(tx, tag.data.pages[HITAGS_CONFIG_PADR], HITAGS_PAGE_SIZE - 1);
518 tx[3] = 0xff;
520 if (protocol_mode != HITAGS_UID_REQ_STD) {
521 //add crc8
522 *txlen += 8;
523 crc = CRC_PRESET;
525 for (int i = 0; i < 4; i++) {
526 calc_crc(&crc, tx[i], 8);
529 tx[4] = crc;
532 break;
534 case 64: {
535 //challenge message received
536 DBG Dbprintf("Challenge for UID: %X", reader_selected_uid);
538 rotate_uid++;
539 *txlen = 32;
540 // init crypt engine
541 state = ht2_hitag2_init(REV64(tag.data.s.key), REV32(tag.data.s.uid_le), REV32(*(uint32_t *)rx));
542 DBG Dbhexdump(8, tx, false);
544 for (int i = 0; i < 4; i++) {
545 ht2_hitag2_byte(&state);
548 //send con2, pwdh0, pwdl0, pwdl1 encrypted as a response
549 tx[0] = ht2_hitag2_byte(&state) ^ tag.data.pages[HITAGS_CONFIG_PADR][2];
550 tx[1] = ht2_hitag2_byte(&state) ^ tag.data.s.config.pwdh0;
551 tx[2] = ht2_hitag2_byte(&state) ^ tag.data.s.pwdl0;
552 tx[3] = ht2_hitag2_byte(&state) ^ tag.data.s.pwdl1;
554 if (protocol_mode != HITAGS_UID_REQ_STD) {
555 //add crc8
556 *txlen += 8;
557 crc = CRC_PRESET;
558 calc_crc(&crc, tag.data.pages[HITAGS_CONFIG_PADR][2], 8);
559 calc_crc(&crc, tag.data.s.config.pwdh0, 8);
560 calc_crc(&crc, tag.data.s.pwdl0, 8);
561 calc_crc(&crc, tag.data.s.pwdl1, 8);
562 tx[4] = (crc ^ ht2_hitag2_byte(&state));
565 * some readers do not allow to authenticate multiple times in a row with the same tag.
566 * use this to change the uid between authentications.
568 if (rotate_uid % 2 == 0) {
569 tag.data.s.uid_le = 0x44332211;
570 } else {
571 tag.data.s.uid_le = 0x88776655;
574 break;
576 case 40: {
577 DBG Dbprintf("WRITE DATA");
579 //data received to be written
580 if (tag.tstate == HT_WRITING_PAGE_DATA) {
581 tag.tstate = HT_NO_OP;
582 memcpy(tag.data.pages[page_to_be_written], rx, HITAGS_PAGE_SIZE);
583 //send ack
584 *txlen = 2;
585 tx[0] = 0x40;
586 page_to_be_written = 0;
588 } else if (tag.tstate == HT_WRITING_BLOCK_DATA) {
589 memcpy(tag.data.pages[page_to_be_written], rx, HITAGS_PAGE_SIZE);
590 //send ack
591 *txlen = 2;
592 tx[0] = 0x40;
593 page_to_be_written++;
594 block_data_left--;
596 if (block_data_left == 0) {
597 tag.tstate = HT_NO_OP;
598 page_to_be_written = 0;
601 break;
603 case 20: {
604 //write page, write block, read page or read block command received
605 uint8_t page = ((rx[0] & 0x0f) << 4) + ((rx[1] & 0xf0) >> 4);
606 // TODO: handle over max_page readonly to 00000000. 82xx mode
607 if (page > tag.max_page) {
608 *txlen = 0;
609 break;
612 if ((rx[0] & 0xf0) == HITAGS_READ_PAGE) { //read page
613 //send page data
614 *txlen = 32;
615 memcpy(tx, tag.data.pages[page], HITAGS_PAGE_SIZE);
617 if (tag.data.s.config.auth && page == HITAGS_CONFIG_PADR) {
618 tx[3] = 0xFF;
621 if (protocol_mode != HITAGS_UID_REQ_STD) {
622 //add crc8
623 *txlen += 8;
624 crc = CRC_PRESET;
625 for (int i = 0; i < 4; i++) {
626 calc_crc(&crc, tx[i], 8);
628 tx[4] = crc;
631 if (tag.data.s.config.auth && tag.data.s.config.LKP && (page == 2 || page == 3)) {
632 //if reader asks for key or password and the LKP-mark is set do not respond
633 *txlen = 0;
636 } else if ((rx[0] & 0xf0) == HITAGS_READ_BLOCK) { //read block
637 // TODO: handle auth LKP
638 *txlen = (HITAGS_BLOCK_SIZE - (page % 4) * HITAGS_PAGE_SIZE) * 8;
640 //send page,...,page+3 data
641 memcpy(tx, tag.data.pages[page], *txlen / 8);
643 if (protocol_mode != HITAGS_UID_REQ_STD) {
644 //add crc8
645 crc = CRC_PRESET;
646 for (int i = 0; i < *txlen / 8; i++) {
647 calc_crc(&crc, tx[i], 8);
649 *txlen += 8;
650 tx[16] = crc;
653 } else if ((rx[0] & 0xf0) == HITAGS_WRITE_PAGE) { //write page
654 // TODO: handle con2 LCK*
655 if ((tag.data.s.config.LCON && page == 1)
656 || (tag.data.s.config.LKP && (page == 2 || page == 3))) {
657 //deny
658 *txlen = 0;
659 } else {
660 //allow
661 *txlen = 2;
662 tx[0] = 0x40;
663 page_to_be_written = page;
664 tag.tstate = HT_WRITING_PAGE_DATA;
667 } else if ((rx[0] & 0xf0) == HITAGS_WRITE_BLOCK) { //write block
668 // TODO: handle LCON con2 LCK*
669 if ((tag.data.s.config.LCON && page == 1)
670 || (tag.data.s.config.LKP && (page == 2 || page == 3))) {
671 //deny
672 *txlen = 0;
673 } else {
674 //allow
675 *txlen = 2;
676 tx[0] = 0x40;
677 page_to_be_written = page;
678 block_data_left = 4 - (page % 4);
679 tag.tstate = HT_WRITING_BLOCK_DATA;
682 break;
684 default: {
685 DBG Dbprintf("unknown rxlen: (%i) %02X %02X %02X %02X ...", rxlen, rx[0], rx[1], rx[2], rx[3]);
686 break;
692 * Emulates a Hitag S Tag with the given data from the .hts file
694 void hts_simulate(bool tag_mem_supplied, const uint8_t *data, bool ledcontrol) {
696 StopTicks();
698 int overflow = 0;
699 uint8_t rx[HITAG_FRAME_LEN];
700 size_t rxlen = 0;
701 uint8_t tx[HITAG_FRAME_LEN];
702 size_t txlen = 0;
704 // Reset the received frame, frame count and timing info
705 memset(rx, 0x00, sizeof(rx));
707 // free eventually allocated BigBuf memory
708 BigBuf_free();
709 BigBuf_Clear_ext(false);
711 // Clean up trace and prepare it for storing frames
712 set_tracing(true);
713 clear_trace();
715 DbpString("Starting Hitag S simulation");
717 tag.pstate = HT_READY;
718 tag.tstate = HT_NO_OP;
720 // read tag data into memory
721 if (tag_mem_supplied) {
722 DbpString("Loading hitag S memory...");
723 memcpy(tag.data.pages, data, HITAGS_MAX_BYTE_SIZE);
724 } else {
725 // use the last read tag
728 // max_page
729 update_tag_max_page();
731 for (int i = 0; i < tag.max_page; i++) {
732 DBG Dbprintf("Page[%2d]: %02X %02X %02X %02X",
734 tag.data.pages[i][3],
735 tag.data.pages[i][2],
736 tag.data.pages[i][1],
737 tag.data.pages[i][0]
742 // Set up simulator mode, frequency divisor which will drive the FPGA
743 // and analog mux selection.
744 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
745 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT);
746 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125); //125kHz
747 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
749 // Configure output pin that is connected to the FPGA (for modulating)
750 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
751 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
753 // Disable modulation at default, which means release resistance
754 LOW(GPIO_SSC_DOUT);
756 hts_init_clock();
758 if (ledcontrol) LED_D_ON();
760 while ((BUTTON_PRESS() == false) && (data_available() == false)) {
761 uint32_t start_time = 0;
763 WDT_HIT();
765 // Receive frame, watch for at most T0*EOF periods
766 while (AT91C_BASE_TC1->TC_CV < T0 * HITAG_T_EOF) {
768 // Check if rising edge in modulation is detected
769 if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
771 // Retrieve the new timing values
772 int rb = (AT91C_BASE_TC1->TC_RB / T0) + overflow;
773 overflow = 0;
775 // Reset timer every frame, we have to capture the last edge for timing
776 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
778 if (ledcontrol) LED_B_ON();
779 // Capture reader cmd start timestamp
780 if (start_time == 0) start_time = TIMESTAMP - HITAG_T_LOW;
782 // Capture reader frame
783 if (rb >= HITAG_T_STOP) {
784 if (rxlen != 0) {
785 //DbpString("weird0?");
787 } else if (rb >= HITAG_T_1_MIN) {
788 // '1' bit
789 rx[rxlen / 8] |= 1 << (7 - (rxlen % 8));
790 rxlen++;
791 } else if (rb >= HITAG_T_0_MIN) {
792 // '0' bit
793 rx[rxlen / 8] |= 0 << (7 - (rxlen % 8));
794 rxlen++;
795 } else {
796 // Ignore weird value, is to small to mean anything
801 // Check if frame was captured
802 if (rxlen > 0) {
803 LogTraceBits(rx, rxlen, start_time, TIMESTAMP, true);
805 // Disable timer 1 with external trigger to avoid triggers during our own modulation
806 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
808 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
809 hts_handle_reader_command(rx, rxlen, tx, &txlen);
811 // Wait for HITAG_T_WAIT_RESP carrier periods after the last reader bit,
812 // not that since the clock counts since the rising edge, but T_Wait1 is
813 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
814 // periods. The gap time T_Low varies (4..10). All timer values are in
815 // terms of T0 units
816 while (AT91C_BASE_TC0->TC_CV < T0 * (HITAG_T_WAIT_RESP - HITAG_T_LOW)) {};
818 // Send and store the tag answer (if there is any)
819 if (txlen > 0) {
820 // Transmit the tag frame
821 start_time = TIMESTAMP;
822 hitag_send_frame(tx, txlen, ledcontrol);
823 LogTraceBits(tx, txlen, start_time, TIMESTAMP, false);
826 // Enable and reset external trigger in timer for capturing future frames
827 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
829 // Reset the received frame and response timing info
830 memset(rx, 0x00, sizeof(rx));
832 if (ledcontrol) LED_B_OFF();
834 // Reset the frame length
835 rxlen = 0;
836 // Save the timer overflow, will be 0 when frame was received
837 overflow += (AT91C_BASE_TC1->TC_CV / T0);
838 // Reset the timer to restart while-loop that receives frames
839 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
843 hts_stop_clock();
844 set_tracing(false);
845 lf_finalize(ledcontrol);
846 // release allocated memory from BigBuff.
847 BigBuf_free();
849 DbpString("Sim stopped");
852 static void hts_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint32_t *resptime, bool ledcontrol) {
854 // Reset values for receiving frames
855 memset(rx, 0x00, sizeofrx);
856 *rxlen = 0;
858 int lastbit = 1;
859 bool bSkip = true;
860 uint32_t errorCount = 0;
861 bool bStarted = false;
862 uint16_t next_edge_event = AT91C_TC_LDRBS;
863 int double_speed = (m == AC4K || m == MC8K) ? 2 : 1;
865 uint32_t rb_i = 0, h2 = 0, h3 = 0, h4 = 0;
866 uint8_t edges[160] = {0};
868 // Dbprintf("TC0_CV:%i TC1_CV:%i TC1_RB:%i TIMESTAMP:%u", AT91C_BASE_TC0->TC_CV, AT91C_BASE_TC1->TC_CV,
869 // AT91C_BASE_TC1->TC_RB, TIMESTAMP);
871 // Receive tag frame, watch for at most T0*HITAG_T_PROG_MAX periods
872 while (AT91C_BASE_TC0->TC_CV < (T0 * HITAG_T_PROG_MAX)) {
874 // Check if edge in tag modulation is detected
875 if (AT91C_BASE_TC1->TC_SR & next_edge_event) {
877 next_edge_event = next_edge_event ^ (AT91C_TC_LDRAS | AT91C_TC_LDRBS);
879 // only use AT91C_TC_LDRBS falling edge for now
880 if (next_edge_event == AT91C_TC_LDRBS) continue;
882 // Retrieve the new timing values
883 uint32_t rb = AT91C_BASE_TC1->TC_RB / T0;
884 edges[rb_i++] = rb;
885 // Reset timer every frame, we have to capture the last edge for timing
886 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
888 if (ledcontrol) LED_B_ON();
890 // Capture tag response timestamp
891 if (*rxlen == 0) *resptime = TIMESTAMP;
893 // Capture tag frame (manchester decoding using only falling edges)
894 if (bStarted == false) {
896 if (rb >= HITAG_T_WAIT_RESP) {
897 bStarted = true;
899 // We always receive a 'one' first, which has the falling edge after a half period |-_|
900 rx[0] = 0x80;
901 (*rxlen)++;
902 } else {
903 errorCount++;
906 } else {
907 // Anticollision Coding
908 if (m == AC2K || m == AC4K) {
909 if (rb >= HITAG_T_TAG_CAPTURE_FOUR_HALF / double_speed) {
910 // Anticollision Coding example |--__|--__| (00)
911 lastbit = 0;
912 rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8));
913 (*rxlen)++;
914 } else if (rb >= HITAG_T_TAG_CAPTURE_THREE_HALF / double_speed) {
915 // Anticollision Coding example |-_-_|--__| (10) or |--__|-_-_| (01)
916 lastbit = !lastbit;
917 rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8));
918 (*rxlen)++;
920 bSkip = !!lastbit;
921 } else if (rb >= HITAG_T_TAG_CAPTURE_TWO_HALF / double_speed) {
922 // Anticollision Coding example |-_-_| (1)
923 if (bSkip == false) {
924 lastbit = 1;
925 rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8));
926 (*rxlen)++;
929 bSkip = !bSkip;
930 } else {
931 // Ignore weird value, is to small to mean anything
932 errorCount++;
934 } else {
935 // Manchester coding
936 if (rb >= HITAG_T_TAG_CAPTURE_FOUR_HALF / double_speed) {
937 // Manchester coding example |-_|_-|-_| (101)
938 rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8));
939 (*rxlen)++;
941 rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8));
942 (*rxlen)++;
943 h4++;
944 } else if (rb >= HITAG_T_TAG_CAPTURE_THREE_HALF / double_speed) {
945 // Manchester coding example |_-|...|_-|-_| (0...01)
946 rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8));
947 (*rxlen)++;
949 // We have to skip this half period at start and add the 'one' the second time
950 if (bSkip == false) {
951 rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8));
952 (*rxlen)++;
955 lastbit = !lastbit;
956 bSkip = !bSkip;
957 h3++;
958 } else if (rb >= HITAG_T_TAG_CAPTURE_TWO_HALF / double_speed) {
959 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
960 // bit is same as last bit
961 rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8));
962 (*rxlen)++;
963 h2++;
964 } else {
965 // Ignore weird value, is to small to mean anything
966 errorCount++;
972 // if we saw over 100 weird values break it probably isn't hitag...
973 if (errorCount > 100 || (*rxlen) / 8 >= sizeofrx) {
974 break;
977 // We can break this loop if we received the last bit from a frame
978 // max periods between 2 falling edge
979 // RTF AC64 |--__|--__| (00) 64 * T0
980 // RTF MC32 |_-|-_|_-| (010) 48 * T0
981 if (AT91C_BASE_TC1->TC_CV > (T0 * 80)) {
982 if ((*rxlen)) {
983 break;
988 DBG Dbprintf("RX0 %i:%02X.. err:%i resptime:%i h2:%i h3:%i h4:%i edges:", *rxlen, rx[0], errorCount, *resptime, h2, h3, h4);
989 DBG Dbhexdump(rb_i, edges, false);
992 static int hts_send_receive(const uint8_t *tx, size_t txlen, uint8_t *rx, size_t sizeofrx, size_t *rxlen, int t_wait, bool ledcontrol, bool ac_seq) {
993 uint32_t start_time;
995 // Send and store the reader command
996 // Disable timer 1 with external trigger to avoid triggers during our own modulation
997 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
999 // Wait for HITAG_T_WAIT_SC carrier periods after the last tag bit before transmitting,
1000 // Since the clock counts since the last falling edge, a 'one' means that the
1001 // falling edge occurred halfway the period. with respect to this falling edge,
1002 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1003 // All timer values are in terms of T0 units
1004 while (AT91C_BASE_TC0->TC_CV < T0 * t_wait) {};
1006 start_time = TIMESTAMP;
1008 // Transmit the reader frame
1009 hitag_reader_send_frame(tx, txlen, ledcontrol);
1011 if (enable_page_tearoff && tearoff_hook() == PM3_ETEAROFF) {
1012 return PM3_ETEAROFF;
1015 LogTraceBits(tx, txlen, start_time, TIMESTAMP, true);
1017 // Enable and reset external trigger in timer for capturing future frames
1018 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1020 hts_set_frame_modulation(protocol_mode, ac_seq);
1022 hts_receive_frame(rx, sizeofrx, rxlen, &start_time, ledcontrol);
1024 // Check if frame was captured and store it
1025 if (*rxlen > 0) {
1026 DBG {
1027 uint8_t response_bit[sizeofrx * 8];
1029 for (size_t i = 0; i < *rxlen; i++) {
1030 response_bit[i] = (rx[i / 8] >> (7 - (i % 8))) & 1;
1033 Dbprintf("htS: rxlen...... %zu", *rxlen);
1034 Dbprintf("htS: sizeofrx... %zu", sizeofrx);
1035 DbpString("htS: response_bit:");
1036 Dbhexdump(*rxlen, response_bit, false);
1037 Dbprintf("htS: skipping %d bit SOF", sof_bits);
1038 if ((rx[0] >> (8 - sof_bits)) != ((1 << sof_bits) - 1)) {
1039 DbpString("htS: Warning, not all bits of SOF are 1");
1043 // remove first sof_bits bits SOF
1044 for (size_t i = 0; i < (*rxlen + 8) / 8; i++) {
1045 rx[i] <<= sof_bits;
1046 if (i + 1 < (*rxlen + 8) / 8) {
1047 rx[i] |= (rx[i + 1] >> (8 - sof_bits));
1051 *rxlen -= sof_bits;
1053 LogTraceBits(rx, *rxlen, start_time, TIMESTAMP, false);
1056 return PM3_SUCCESS;
1059 static int hts_select_tag(const lf_hitag_data_t *packet, uint8_t *tx, size_t sizeoftx, uint8_t *rx, size_t sizeofrx, int t_wait, bool ledcontrol) {
1061 StopTicks();
1063 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1065 // Clean up trace and prepare it for storing frames
1066 set_tracing(true);
1067 clear_trace();
1069 if (ledcontrol) LED_D_ON();
1071 hts_init_clock();
1073 // Set fpga in edge detect with reader field, we can modulate as reader now
1074 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD);
1075 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125); //125kHz
1076 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
1078 // Configure output and enable pin that is connected to the FPGA (for modulating)
1079 AT91C_BASE_PIOA->PIO_OER |= GPIO_SSC_DOUT;
1080 AT91C_BASE_PIOA->PIO_PER |= GPIO_SSC_DOUT;
1082 // Disable modulation at default, which means enable the field
1083 LOW(GPIO_SSC_DOUT);
1085 // UID request standard 00110
1086 // UID request Advanced 1100x
1087 // UID request FAdvanced 11010
1088 size_t txlen = 0;
1089 size_t rxlen = 0;
1091 protocol_mode = packet->mode;
1092 uint8_t cmd = protocol_mode;
1093 txlen = concatbits(tx, txlen, &cmd, 0, 5);
1094 hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, t_wait, ledcontrol, true);
1096 if (rxlen != 32) {
1097 // DbpString("UID Request failed!");
1098 return -2;
1101 memcpy(tag.data.pages[HITAGS_UID_PADR], rx, HITAGS_PAGE_SIZE);
1103 DBG Dbprintf("UID... %02X%02X%02X%02X", rx[0], rx[1], rx[2], rx[3]);
1105 // select uid
1106 txlen = 0;
1107 cmd = HITAGS_SELECT;
1108 txlen = concatbits(tx, txlen, &cmd, 0, 5);
1109 txlen = concatbits(tx, txlen, rx, 0, 32);
1110 uint8_t crc = CRC8Hitag1Bits(tx, txlen);
1111 txlen = concatbits(tx, txlen, &crc, 0, 8);
1113 hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, HITAG_T_WAIT_SC, ledcontrol, false);
1115 if (rxlen != 32 + (protocol_mode == HITAGS_UID_REQ_STD ? 0 : 8)) {
1116 DBG Dbprintf("Select UID failed! %i", rxlen);
1117 return -3;
1120 memcpy(tag.data.pages[HITAGS_CONFIG_PADR], rx, HITAGS_PAGE_SIZE - 1);
1122 update_tag_max_page();
1124 DBG Dbprintf("conf 0: %02X conf 1: %02X conf 2: %02X", tag.data.pages[HITAGS_CONFIG_PADR][0], tag.data.pages[HITAGS_CONFIG_PADR][1], tag.data.pages[HITAGS_CONFIG_PADR][2]);
1126 if (tag.data.s.config.auth == 1) {
1128 uint64_t key_le = 0;
1129 // if the tag is in authentication mode try the key or challenge
1130 if (packet->cmd == HTSF_KEY) {
1132 DBG DbpString("Authenticating using key:");
1133 DBG Dbhexdump(6, packet->key, false);
1135 key_le = *(uint64_t *)packet->key;
1137 uint64_t state = ht2_hitag2_init(REV64(key_le), REV32(tag.data.s.uid_le), REV32(*(uint32_t *)rnd));
1139 uint8_t auth_ks[4];
1140 for (int i = 0; i < 4; i++) {
1141 auth_ks[i] = ht2_hitag2_byte(&state) ^ 0xff;
1144 txlen = 0;
1145 txlen = concatbits(tx, txlen, rnd, 0, 32);
1146 txlen = concatbits(tx, txlen, auth_ks, 0, 32);
1148 DBG Dbprintf("%02X %02X %02X %02X %02X %02X %02X %02X", tx[0], tx[1], tx[2], tx[3], tx[4], tx[5], tx[6], tx[7]);
1150 } else if (packet->cmd == HTSF_CHALLENGE) {
1152 DBG DbpString("Authenticating using nr,ar pair:");
1153 DBG Dbhexdump(8, packet->NrAr, false);
1155 uint64_t NrAr = 0;
1156 NrAr = ((uint64_t)packet->NrAr[7]) << 0 |
1157 ((uint64_t)packet->NrAr[6]) << 8 |
1158 ((uint64_t)packet->NrAr[5]) << 16 |
1159 ((uint64_t)packet->NrAr[4]) << 24 |
1160 ((uint64_t)packet->NrAr[3]) << 32 |
1161 ((uint64_t)packet->NrAr[2]) << 40 |
1162 ((uint64_t)packet->NrAr[1]) << 48 |
1163 ((uint64_t)packet->NrAr[0]) << 56;
1165 txlen = 64;
1166 for (int i = 0; i < 8; i++) {
1167 tx[i] = ((NrAr >> (56 - (i * 8))) & 0xFF);
1170 } else if (packet->cmd == HTSF_82xx) {
1171 // 8268/8310 Authentication by writing password to block 64
1173 // send write page request
1174 txlen = 0;
1175 cmd = HITAGS_WRITE_PAGE;
1176 txlen = concatbits(tx, txlen, &cmd, 0, 4);
1178 uint8_t addr = 64;
1179 txlen = concatbits(tx, txlen, &addr, 0, 8);
1181 crc = CRC8Hitag1Bits(tx, txlen);
1182 txlen = concatbits(tx, txlen, &crc, 0, 8);
1184 hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, HITAG_T_WAIT_SC, ledcontrol, false);
1186 if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x01)) {
1187 // Dbprintf("no write access on page " _YELLOW_("64") ". not 82xx?");
1188 return -4;
1191 txlen = 0;
1192 txlen = concatbits(tx, txlen, packet->pwd, 0, 32);
1193 crc = CRC8Hitag1Bits(tx, txlen);
1194 txlen = concatbits(tx, txlen, &crc, 0, 8);
1196 hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, HITAG_T_WAIT_SC, ledcontrol, false);
1198 if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x01)) {
1199 // Dbprintf("write to page " _YELLOW_("64") " failed! wrong password?");
1200 return -5;
1203 return 0;
1204 } else if (packet->cmd == HTSF_PLAIN) {
1205 // Dbprintf("Error, " _YELLOW_("AUT=1") " This tag is configured in Authentication Mode");
1206 return -6;
1207 } else {
1208 DBG Dbprintf("Error, unknown function: " _RED_("%d"), packet->cmd);
1209 return -7;
1212 hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, HITAG_T_WAIT_SC, ledcontrol, false);
1214 if (rxlen != 32 + (protocol_mode == HITAGS_UID_REQ_STD ? 0 : 8)) {
1215 DBG Dbprintf("Authenticate failed! " _RED_("%i"), rxlen);
1216 return -8;
1219 //encrypted con2,password received.
1220 DBG Dbprintf("UID... %08X", BSWAP_32(tag.data.s.uid_le));
1221 DBG Dbprintf("RND... %02X%02X%02X%02X", rnd[0], rnd[1], rnd[2], rnd[3]);
1223 //decrypt password
1224 pwdh0 = 0;
1225 pwdl0 = 0;
1226 pwdl1 = 0;
1227 if (packet->cmd == HTSF_KEY) {
1229 uint64_t state = ht2_hitag2_init(REV64(key_le), REV32(tag.data.s.uid_le), REV32(*(uint32_t *)rnd));
1230 for (int i = 0; i < 4; i++) {
1231 ht2_hitag2_byte(&state);
1234 uint8_t con2 = rx[0] ^ ht2_hitag2_byte(&state);
1235 pwdh0 = rx[1] ^ ht2_hitag2_byte(&state);
1236 pwdl0 = rx[2] ^ ht2_hitag2_byte(&state);
1237 pwdl1 = rx[3] ^ ht2_hitag2_byte(&state);
1239 DBG Dbprintf("con2 %02X pwdh0 %02X pwdl0 %02X pwdl1 %02X", con2, pwdh0, pwdl0, pwdl1);
1242 return 0;
1246 * Authenticates to the Tag with the given key or challenge.
1247 * If the key was given the password will be decrypted.
1248 * Reads every page of a hitag S transpoder.
1250 void hts_read(const lf_hitag_data_t *payload, bool ledcontrol) {
1252 uint8_t rx[HITAG_FRAME_LEN] = { 0x00 };
1253 uint8_t tx[HITAG_FRAME_LEN] = { 0x00 };
1255 int status = PM3_SUCCESS, reason = -1;
1256 reason = hts_select_tag(payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), HITAG_T_WAIT_FIRST, ledcontrol);
1257 if (reason != 0) {
1258 status = PM3_ERFTRANS;
1259 goto read_end;
1263 if (payload->page >= tag.max_page) {
1264 DBG Dbprintf("Warning, read page "_YELLOW_("%d") " > max page("_YELLOW_("%d") ") ", payload->page, tag.max_page);
1267 int page_addr = payload->page;
1268 int page_index = 0;
1269 lf_hts_read_response_t card = {0};
1271 memcpy(card.config_page.asBytes, tag.data.pages[HITAGS_CONFIG_PADR], HITAGS_PAGE_SIZE);
1273 while ((BUTTON_PRESS() == false) && (data_available() == false)) {
1275 if (payload->page_count == 0) {
1276 if (page_addr > tag.max_page) break;
1277 } else if (page_addr > 255 || page_addr >= payload->page + payload->page_count) {
1278 break;
1281 WDT_HIT();
1283 size_t rxlen = 0;
1285 //send read request
1286 size_t txlen = 0;
1287 uint8_t cmd = HITAGS_READ_PAGE;
1288 txlen = concatbits(tx, txlen, &cmd, 0, 4);
1289 uint8_t addr = page_addr;
1290 txlen = concatbits(tx, txlen, &addr, 0, 8);
1291 uint8_t crc = CRC8Hitag1Bits(tx, txlen);
1292 txlen = concatbits(tx, txlen, &crc, 0, 8);
1294 hts_send_receive(tx, txlen, rx, ARRAYLEN(rx), &rxlen, HITAG_T_WAIT_SC, ledcontrol, false);
1296 if (rxlen != 32 + (protocol_mode == HITAGS_UID_REQ_STD ? 0 : 8)) {
1297 DBG Dbprintf("Read page failed!");
1298 card.pages_reason[page_index] = -11;
1299 // status = PM3_ERFTRANS;
1300 // goto read_end;
1301 page_addr++;
1302 page_index++;
1303 continue;
1306 //save received data - 40 bits
1307 memcpy(card.pages[page_index], rx, HITAGS_PAGE_SIZE);
1309 if (g_dbglevel >= DBG_EXTENDED) {
1310 if (page_addr == 1 && (payload->cmd == HTSF_KEY || payload->cmd == HTSF_CHALLENGE) && card.config_page.s.auth == 1) {
1311 DBG Dbprintf("Page[%2d]: %02X %02X %02X %02X", page_addr,
1312 card.pages[page_index][0],
1313 card.pages[page_index][1],
1314 card.pages[page_index][2],
1315 pwdh0);
1316 } else { // HTSF_PLAIN or HTSF_82xx can read the full page
1317 DBG Dbprintf("Page[%2d]: %02X %02X %02X %02X", page_addr,
1318 card.pages[page_index][0],
1319 card.pages[page_index][1],
1320 card.pages[page_index][2],
1321 card.pages[page_index][3]);
1325 page_addr++;
1326 page_index++;
1327 //display key and password if possible
1328 if (page_addr == 2 && card.config_page.s.auth == 1 && card.config_page.s.LKP) {
1329 if (payload->cmd == HTSF_KEY) {
1330 DBG Dbprintf("Page[ 2]: %02X %02X %02X %02X",
1331 payload->key[1],
1332 payload->key[0],
1333 pwdl1,
1334 pwdl0
1336 DBG Dbprintf("Page[ 3]: %02X %02X %02X %02X",
1337 payload->key[5],
1338 payload->key[4],
1339 payload->key[3],
1340 payload->key[2]
1342 card.pages_reason[page_index++] = 1;
1343 card.pages_reason[page_index++] = 1;
1344 } else {
1345 //if the authentication is done with a challenge the key and password are unknown
1346 DBG Dbprintf("Page[ 2]: __ __ __ __");
1347 DBG Dbprintf("Page[ 3]: __ __ __ __");
1348 card.pages_reason[page_index++] = -11;
1349 card.pages_reason[page_index++] = -11;
1351 // since page 2+3 are not accessible when LKP == 1 and AUT == 1 fastforward to next readable page
1352 page_addr = 4;
1356 read_end:
1357 hts_stop_clock();
1358 set_tracing(false);
1359 lf_finalize(ledcontrol);
1360 reply_reason(CMD_LF_HITAGS_READ, status, reason, (uint8_t *)&card, sizeof(card));
1364 * Authenticates to the Tag with the given Key or Challenge.
1365 * Writes the given 32Bit data into page_
1367 void hts_write_page(const lf_hitag_data_t *payload, bool ledcontrol) {
1369 //check for valid input
1370 if (payload->page == 0) {
1371 DBG Dbprintf("Warning, write page 0");
1374 uint8_t rx[HITAG_FRAME_LEN];
1375 size_t rxlen = 0;
1377 uint8_t tx[HITAG_FRAME_LEN];
1378 size_t txlen = 0;
1380 int status = PM3_ESOFT, reason = -1;
1381 reason = hts_select_tag(payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), HITAG_T_WAIT_FIRST, ledcontrol);
1382 if (reason != 0) {
1383 status = PM3_ERFTRANS;
1384 goto write_end;
1387 //check if the given page exists
1388 if (payload->page > tag.max_page) {
1389 DBG Dbprintf("Warning, page number too large");
1390 // 82xx CON0 is fully modifiable
1393 //send write page request
1394 txlen = 0;
1396 uint8_t cmd = HITAGS_WRITE_PAGE;
1397 txlen = concatbits(tx, txlen, &cmd, 0, 4);
1399 uint8_t addr = payload->page;
1400 txlen = concatbits(tx, txlen, &addr, 0, 8);
1402 uint8_t crc = CRC8Hitag1Bits(tx, txlen);
1403 txlen = concatbits(tx, txlen, &crc, 0, 8);
1405 hts_send_receive(tx, txlen, rx, ARRAYLEN(rx), &rxlen, HITAG_T_WAIT_SC, ledcontrol, false);
1407 if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x01)) {
1408 DBG Dbprintf("no write access on page " _YELLOW_("%d"), payload->page);
1409 reason = -9;
1410 goto write_end;
1413 // //ACK received to write the page. send data
1414 // uint8_t data[4] = {0, 0, 0, 0};
1415 // switch (payload->cmd) {
1416 // case HTSF_PLAIN:
1417 // case HTSF_CHALLENGE:
1418 // case HTSF_KEY:
1419 // data[0] = payload->data[3];
1420 // data[1] = payload->data[2];
1421 // data[2] = payload->data[1];
1422 // data[3] = payload->data[0];
1423 // break;
1424 // default: {
1425 // res = PM3_EINVARG;
1426 // goto write_end;
1427 // }
1428 // }
1430 txlen = 0;
1431 txlen = concatbits(tx, txlen, payload->data, 0, 32);
1432 crc = CRC8Hitag1Bits(tx, txlen);
1433 txlen = concatbits(tx, txlen, &crc, 0, 8);
1435 enable_page_tearoff = g_tearoff_enabled;
1437 if (hts_send_receive(tx, txlen, rx, ARRAYLEN(rx), &rxlen, HITAG_T_WAIT_SC, ledcontrol, false) == PM3_ETEAROFF) {
1438 status = PM3_ETEAROFF;
1439 enable_page_tearoff = false;
1440 goto write_end;
1443 if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x01)) {
1444 reason = -10; // write failed
1445 } else {
1446 status = PM3_SUCCESS;
1449 write_end:
1450 hts_stop_clock();
1451 set_tracing(false);
1452 lf_finalize(ledcontrol);
1453 reply_reason(CMD_LF_HITAGS_WRITE, status, reason, NULL, 0);
1456 int hts_read_uid(uint32_t *uid, bool ledcontrol, bool send_answer) {
1458 StopTicks();
1460 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1462 // Clean up trace and prepare it for storing frames
1463 set_tracing(true);
1464 clear_trace();
1466 if (ledcontrol) LED_D_ON();
1468 hts_init_clock();
1470 // Set fpga in edge detect with reader field, we can modulate as reader now
1471 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD);
1472 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125); //125kHz
1473 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
1475 // Configure output and enable pin that is connected to the FPGA (for modulating)
1476 AT91C_BASE_PIOA->PIO_OER |= GPIO_SSC_DOUT;
1477 AT91C_BASE_PIOA->PIO_PER |= GPIO_SSC_DOUT;
1479 // Disable modulation at default, which means enable the field
1480 LOW(GPIO_SSC_DOUT);
1482 // UID request standard 00110
1483 // UID request Advanced 1100x
1484 // UID request FAdvanced 11010
1485 protocol_mode = HITAGS_UID_REQ_ADV1;
1486 uint8_t cmd = protocol_mode;
1488 size_t rxlen = 0;
1489 uint8_t rx[HITAG_FRAME_LEN] = { 0x00 };
1491 size_t txlen = 0;
1492 uint8_t tx[HITAG_FRAME_LEN] = { 0x00 };
1494 txlen = concatbits(tx, txlen, &cmd, 0, 5);
1496 hts_send_receive(tx, txlen, rx, ARRAYLEN(rx), &rxlen, HITAG_T_WAIT_FIRST, ledcontrol, true);
1498 int status = PM3_SUCCESS;
1499 if (rxlen == 32) {
1501 memcpy(tag.data.pages[0], rx, HITAGS_PAGE_SIZE);
1503 if (uid) {
1504 *uid = BSWAP_32(tag.data.s.uid_le);
1507 } else {
1508 DBG DbpString("UID Request failed!");
1509 status = PM3_ERFTRANS;
1512 hts_stop_clock();
1513 set_tracing(false);
1514 lf_finalize(ledcontrol);
1515 reply_ng(CMD_LF_HITAGS_UID, status, (uint8_t *)tag.data.pages, sizeof(tag.data.pages));
1516 return status;
1520 * Tries to authenticate to a Hitag S Transponder with the given challenges from a .cc file.
1521 * Displays all Challenges that failed.
1522 * When collecting Challenges to break the key it is possible that some data
1523 * is not received correctly due to Antenna problems. This function
1524 * detects these challenges.
1526 void hts_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontrol) {
1528 //check for valid input
1529 if (datalen < 8) {
1530 DBG Dbprintf("Error, missing challenges");
1531 reply_ng(CMD_LF_HITAGS_TEST_TRACES, PM3_EINVARG, NULL, 0);
1532 return;
1534 uint32_t dataoffset = 0;
1536 uint8_t rx[HITAG_FRAME_LEN];
1537 uint8_t tx[HITAG_FRAME_LEN];
1539 while ((BUTTON_PRESS() == false) && (data_available() == false)) {
1540 // Watchdog hit
1541 WDT_HIT();
1543 lf_hitag_data_t payload;
1544 memset(&payload, 0, sizeof(payload));
1545 payload.cmd = HTSF_CHALLENGE;
1547 memcpy(payload.NrAr, data + dataoffset, 8);
1549 int reason = hts_select_tag(&payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), HITAG_T_WAIT_FIRST, ledcontrol);
1551 DBG Dbprintf("Challenge %s: %02X %02X %02X %02X %02X %02X %02X %02X",
1552 reason != 0 ? "failed " : "success",
1553 payload.NrAr[0], payload.NrAr[1],
1554 payload.NrAr[2], payload.NrAr[3],
1555 payload.NrAr[4], payload.NrAr[5],
1556 payload.NrAr[6], payload.NrAr[7]
1559 if (reason != 0) {
1560 // Need to do a dummy UID select that will fail
1561 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1562 SpinDelay(2);
1563 hts_select_tag(&payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), HITAG_T_WAIT_FIRST, ledcontrol);
1566 dataoffset += 8;
1567 if (dataoffset >= datalen - 8) {
1568 break;
1570 // reset field
1571 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1573 // min t_reset = 2ms
1574 SpinDelay(2);
1577 hts_stop_clock();
1578 set_tracing(false);
1579 lf_finalize(ledcontrol);
1580 reply_ng(CMD_LF_HITAGS_TEST_TRACES, PM3_SUCCESS, NULL, 0);
1581 return;