reworked "lf em 4x50 chk" to use dynamic memory for dictionary
[RRG-proxmark3.git] / armsrc / hitag2.c
blob8aa7178cbddf09bfa56b94aa46c981bdaa437b7e
1 //-----------------------------------------------------------------------------
2 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
3 // at your option, any later version. See the LICENSE.txt file for the text of
4 // the license.
5 //-----------------------------------------------------------------------------
6 // Hitag2 emulation
7 //
8 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
9 //-----------------------------------------------------------------------------
10 // Hitag2 complete rewrite of the code
11 // - Fixed modulation/encoding issues
12 // - Rewrote code for transponder emulation
13 // - Added sniffing of transponder communication
14 // - Added reader functionality
16 // (c) 2012 Roel Verdult
17 //-----------------------------------------------------------------------------
18 // Piwi, 2019
19 // Iceman, 2019
20 // Anon, 2019
21 // Doegox, 2020
23 #define DBG if (DBGLEVEL >= DBG_EXTENDED)
25 #include "hitag2.h"
26 #include "hitag2_crypto.h"
27 #include "string.h"
28 #include "proxmark3_arm.h"
29 #include "cmd.h"
30 #include "BigBuf.h"
31 #include "fpgaloader.h"
32 #include "ticks.h"
33 #include "dbprint.h"
34 #include "util.h"
35 #include "lfadc.h"
36 #include "lfsampling.h"
37 #include "lfdemod.h"
38 #include "commonutil.h"
39 #include "appmain.h"
41 #define test_bit(data, i) (*(data + (i/8)) >> (7-(i % 8))) & 1
42 #define set_bit(data, i) *(data + (i/8)) |= (1 << (7-(i % 8)))
43 #define clear_bit(data, i) *(data + (i/8)) &= ~(1 << (7-(i % 8)))
44 #define flip_bit(data, i) *(data + (i/8)) ^= (1 << (7-(i % 8)))
46 // Successful crypto auth
47 static bool bCrypto;
48 // Is in auth stage
49 static bool bAuthenticating;
50 // Successful password auth
51 static bool bSelecting;
52 static bool bCollision;
53 static bool bPwd;
54 static bool bSuccessful;
57 Password Mode : 0x06 - 0000 0110
58 Crypto Mode : 0x0E - 0000 1110
59 Public Mode A : 0x02 - 0000 0010
60 Public Mode B : 0x00 - 0000 0000
61 Public Mode C : 0x04 - 0000 0100
64 static struct hitag2_tag tag = {
65 .state = TAG_STATE_RESET,
66 .sectors = { // Password mode: | Crypto mode:
67 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
68 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
69 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
70 [3] = { 0x06, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
71 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
72 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
73 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
74 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
75 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
76 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
77 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
78 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
79 // up to index 15 reserved for HITAG1/HITAGS public data
83 static enum {
84 WRITE_STATE_START = 0x0,
85 WRITE_STATE_PAGENUM_WRITTEN,
86 WRITE_STATE_PROG
87 } writestate;
89 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
90 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
91 #define AUTH_TABLE_LENGTH 2744
92 static uint8_t *auth_table;
93 static size_t auth_table_pos = 0;
94 static size_t auth_table_len = AUTH_TABLE_LENGTH;
96 static uint8_t password[4];
97 static uint8_t NrAr[8];
98 static uint8_t key[8];
99 static uint8_t writedata[4];
100 static uint8_t logdata_0[4], logdata_1[4];
101 static uint8_t nonce[4];
102 static uint8_t key_no;
103 static uint64_t cipher_state;
105 static int16_t blocknr;
106 static size_t flipped_bit = 0;
107 static uint32_t byte_value = 0;
109 static void hitag2_reset(void) {
110 tag.state = TAG_STATE_RESET;
111 tag.crypto_active = 0;
114 static void hitag2_init(void) {
115 hitag2_reset();
118 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
119 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
120 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
121 // T0 = TIMER_CLOCK1 / 125000 = 192
122 #ifndef HITAG_T0
123 #define HITAG_T0 192
124 #endif
126 #define HITAG_FRAME_LEN 20
127 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
128 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
129 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
130 #define HITAG_T_0 20 /* T[0] should be 18..22 */
131 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
132 #define HITAG_T_1 30 /* T[1] should be 26..30 */
133 #define HITAG_T_EOF 80 /* T_EOF should be > 36 and must be larger than HITAG_T_TAG_CAPTURE_FOUR_HALF */
134 #define HITAG_T_WAIT_1_MIN 199 /* T_wresp should be 199..206 */
135 #define HITAG_T_WAIT_2_MIN 90 /* T_wait2 should be at least 90 */
136 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
137 #define HITAG_T_PROG 614
138 #define HITAG_T_WAIT_POWERUP 313 /* transponder internal powerup time is 312.5 */
139 #define HITAG_T_WAIT_START_AUTH_MAX 232 /* transponder waiting time to receive the START_AUTH command is 232.5, then it enters public mode */
141 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
142 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
143 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
144 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
146 #define HITAG_T_TAG_HALF_PERIOD 16
147 #define HITAG_T_TAG_FULL_PERIOD 32
149 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
150 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
151 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
152 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
155 // sim
156 static void hitag_send_bit(int bit) {
157 LED_A_ON();
159 // Reset clock for the next bit
160 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
162 // Fixed modulation, earlier proxmark version used inverted signal
163 // check datasheet if reader uses BiPhase?
164 if (bit == 0) {
165 // Manchester: Unloaded, then loaded |__--|
166 LOW(GPIO_SSC_DOUT);
167 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_HALF_PERIOD);
168 HIGH(GPIO_SSC_DOUT);
169 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_FULL_PERIOD);
170 } else {
171 // Manchester: Loaded, then unloaded |--__|
172 HIGH(GPIO_SSC_DOUT);
173 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_HALF_PERIOD);
174 LOW(GPIO_SSC_DOUT);
175 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_FULL_PERIOD);
177 LED_A_OFF();
180 // sim
181 static void hitag_send_frame(const uint8_t *frame, size_t frame_len) {
182 // SOF - send start of frame
183 hitag_send_bit(1);
184 hitag_send_bit(1);
185 hitag_send_bit(1);
186 hitag_send_bit(1);
187 hitag_send_bit(1);
189 // Send the content of the frame
190 for (size_t i = 0; i < frame_len; i++) {
191 hitag_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1);
194 // Drop the modulation
195 LOW(GPIO_SSC_DOUT);
199 // sim
200 static void hitag2_handle_reader_command(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
201 uint8_t rx_air[HITAG_FRAME_LEN];
203 // Copy the (original) received frame how it is send over the air
204 memcpy(rx_air, rx, nbytes(rxlen));
206 if (tag.crypto_active) {
207 hitag2_cipher_transcrypt(&(tag.cs), rx, rxlen / 8, rxlen % 8);
210 // Reset the transmission frame length
211 *txlen = 0;
213 // Try to find out which command was send by selecting on length (in bits)
214 switch (rxlen) {
215 // Received 11000 from the reader, request for UID, send UID
216 case 05: {
217 // Always send over the air in the clear plaintext mode
218 if (rx_air[0] != 0xC0) {
219 // Unknown frame ?
220 return;
222 *txlen = 32;
223 memcpy(tx, tag.sectors[0], 4);
224 tag.crypto_active = 0;
226 break;
228 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
229 case 10: {
230 uint16_t sector = (~(((rx[0] << 2) & 0x04) | ((rx[1] >> 6) & 0x03)) & 0x07);
232 // Verify complement of sector index
233 if (sector != ((rx[0] >> 3) & 0x07)) {
234 DbpString("Transmission error (read/write)");
235 return;
238 switch (rx[0] & 0xC6) {
239 // Read command: 11xx x00y
240 case 0xC0: {
241 memcpy(tx, tag.sectors[sector], 4);
242 *txlen = 32;
243 break;
245 // Inverted Read command: 01xx x10y
246 case 0x44: {
247 for (size_t i = 0; i < 4; i++) {
248 tx[i] = tag.sectors[sector][i] ^ 0xff;
250 *txlen = 32;
251 break;
253 // Write command: 10xx x01y
254 case 0x82: {
255 // Prepare write, acknowledge by repeating command
256 memcpy(tx, rx, nbytes(rxlen));
257 *txlen = rxlen;
258 tag.active_sector = sector;
259 tag.state = TAG_STATE_WRITING;
260 break;
262 // Unknown command
263 default: {
264 Dbprintf("Unknown command: %02x %02x", rx[0], rx[1]);
265 return;
269 break;
271 // Writing data or Reader password
272 case 32: {
273 if (tag.state == TAG_STATE_WRITING) {
274 // These are the sector contents to be written. We don't have to do anything else.
275 memcpy(tag.sectors[tag.active_sector], rx, nbytes(rxlen));
276 tag.state = TAG_STATE_RESET;
277 return;
278 } else {
279 // Received RWD password, respond with configuration and our password
280 if (memcmp(rx, tag.sectors[1], 4) != 0) {
281 DbpString("Reader password is wrong");
282 return;
284 *txlen = 32;
285 memcpy(tx, tag.sectors[3], 4);
288 break;
290 // Received RWD authentication challenge and respnse
291 case 64: {
292 // Store the authentication attempt
293 if (auth_table_len < (AUTH_TABLE_LENGTH - 8)) {
294 memcpy(auth_table + auth_table_len, rx, 8);
295 auth_table_len += 8;
298 // Reset the cipher state
299 hitag2_cipher_reset(&tag, rx);
301 // Check if the authentication was correct
302 if (!hitag2_cipher_authenticate(&(tag.cs), rx + 4)) {
303 // The reader failed to authenticate, do nothing
304 Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed!", rx[0], rx[1], rx[2], rx[3], rx[4], rx[5], rx[6], rx[7]);
305 return;
307 // Activate encryption algorithm for all further communication
308 tag.crypto_active = 1;
310 // Use the tag password as response
311 memcpy(tx, tag.sectors[3], 4);
312 *txlen = 32;
314 break;
317 // LogTrace(rx, nbytes(rxlen), 0, 0, NULL, false);
318 // LogTrace(tx, nbytes(txlen), 0, 0, NULL, true);
320 if (tag.crypto_active) {
321 hitag2_cipher_transcrypt(&(tag.cs), tx, *txlen / 8, *txlen % 8);
325 // reader/writer
326 // returns how long it took
327 static uint32_t hitag_reader_send_bit(int bit) {
328 uint32_t wait = 0;
329 LED_A_ON();
330 // Binary pulse length modulation (BPLM) is used to encode the data stream
331 // This means that a transmission of a one takes longer than that of a zero
333 // Enable modulation, which means, drop the field
334 lf_modulation(true);
336 // Wait for 4-10 times the carrier period
337 lf_wait_periods(8); // wait for 4-10 times the carrier period
338 wait += 8;
340 // Disable modulation, just activates the field again
341 lf_modulation(false);
343 if (bit == 0) {
344 // Zero bit: |_-|
345 lf_wait_periods(HITAG_T_0 - HITAG_T_LOW); // wait for 18-22 times the carrier period
346 wait += HITAG_T_0 - HITAG_T_LOW;
347 } else {
348 // One bit: |_--|
349 lf_wait_periods(HITAG_T_1 - HITAG_T_LOW); // wait for 26-32 times the carrier period
350 wait += HITAG_T_1 - HITAG_T_LOW;
353 LED_A_OFF();
354 return wait;
357 // reader / writer commands
358 static uint32_t hitag_reader_send_frame(const uint8_t *frame, size_t frame_len) {
360 uint32_t wait = 0;
361 // Send the content of the frame
362 for (size_t i = 0; i < frame_len; i++) {
363 wait += hitag_reader_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1);
366 // Enable modulation, which means, drop the field
367 lf_modulation(true);
369 // Wait for 4-10 times the carrier period
370 lf_wait_periods(HITAG_T_LOW);
371 wait += HITAG_T_LOW;
373 // Disable modulation, just activates the field again
374 lf_modulation(false);
376 // t_stop, high field for stop condition (> 36)
377 lf_wait_periods(HITAG_T_STOP);
378 wait += HITAG_T_STOP;
380 return wait;
383 static uint8_t hitag_crc(uint8_t *data, size_t n) {
384 uint8_t crc = 0xFF;
385 for (size_t i = 0; i < ((n + 7) / 8); i++) {
386 crc ^= *(data + i);
387 uint8_t bit = n < (8 * (i + 1)) ? (n % 8) : 8;
388 while (bit--) {
389 if (crc & 0x80) {
390 crc <<= 1;
391 crc ^= 0x1D;
392 } else {
393 crc <<= 1;
397 return crc;
401 void fix_ac_decoding(uint8_t *input, size_t len) {
402 // Reader routine tries to decode AC data after Manchester decoding
403 // AC has double the bitrate, extract data from bit-pairs
404 uint8_t temp[len / 16];
405 memset(temp, 0, sizeof(temp));
407 for (size_t i = 1; i < len; i += 2) {
408 if (test_bit(input, i) && test_bit(input, (i + 1))) {
409 set_bit(temp, (i / 2));
412 memcpy(input, temp, sizeof(temp));
417 // looks at number of received bits.
418 // 0 = collision?
419 // 32 = good response
420 static bool hitag_plain(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen, bool hitag_s) {
421 *txlen = 0;
422 switch (rxlen) {
423 case 0: {
424 // retry waking up card
425 /*tx[0] = 0xb0; // Rev 3.0*/
426 tx[0] = 0x30; // Rev 2.0
427 *txlen = 5;
428 if (!bCollision) blocknr--;
429 if (blocknr < 0) {
430 blocknr = 0;
432 if (!hitag_s) {
433 if (blocknr > 1 && blocknr < 31) {
434 blocknr = 31;
437 bCollision = true;
438 return true;
440 case 32: {
441 uint8_t crc;
442 if (bCollision) {
443 // Select card by serial from response
444 tx[0] = 0x00 | rx[0] >> 5;
445 tx[1] = rx[0] << 3 | rx[1] >> 5;
446 tx[2] = rx[1] << 3 | rx[2] >> 5;
447 tx[3] = rx[2] << 3 | rx[3] >> 5;
448 tx[4] = rx[3] << 3;
449 crc = hitag_crc(tx, 37);
450 tx[4] |= crc >> 5;
451 tx[5] = crc << 3;
452 *txlen = 45;
453 bCollision = false;
454 } else {
455 memcpy(tag.sectors[blocknr], rx, 4);
456 blocknr++;
457 if (!hitag_s) {
458 if (blocknr > 1 && blocknr < 31) {
459 blocknr = 31;
462 if (blocknr > 63) {
463 DbpString("Read succesful!");
464 *txlen = 0;
465 bSuccessful = true;
466 return false;
468 // read next page of card until done
469 Dbprintf("Reading page %02u", blocknr);
470 tx[0] = 0xc0 | blocknr >> 4; // RDPPAGE
471 tx[1] = blocknr << 4;
472 crc = hitag_crc(tx, 12);
473 tx[1] |= crc >> 4;
474 tx[2] = crc << 4;
475 *txlen = 20;
478 break;
479 default: {
480 Dbprintf("Uknown frame length: %d", rxlen);
481 return false;
483 break;
485 return true;
489 static bool hitag1_authenticate(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
490 uint8_t crc;
491 *txlen = 0;
492 switch (rxlen) {
493 case 0: {
494 // retry waking up card
495 /*tx[0] = 0xb0; // Rev 3.0*/
496 tx[0] = 0x30; // Rev 2.0
497 *txlen = 5;
498 if (bCrypto && byte_value <= 0xff) {
499 // to retry
500 bCrypto = false;
502 if (!bCollision) blocknr--;
503 if (blocknr < 0) {
504 blocknr = 0;
506 bCollision = true;
507 // will receive 32-bit UID
509 break;
510 case 2: {
511 if (bAuthenticating) {
512 // received Auth init ACK, send nonce
513 // TODO Roel, bit-manipulation goes here
514 /*nonce[0] = 0x2d;*/
515 /*nonce[1] = 0x74;*/
516 /*nonce[2] = 0x80;*/
517 /*nonce[3] = 0xa5;*/
518 nonce[0] = byte_value;
519 byte_value++;
520 /*set_bit(nonce,flipped_bit);*/
521 memcpy(tx, nonce, 4);
522 *txlen = 32;
523 // will receive 32 bit encrypted Logdata
524 } else if (bCrypto) {
525 // authed, start reading
526 tx[0] = 0xe0 | blocknr >> 4; // RDCPAGE
527 tx[1] = blocknr << 4;
528 crc = hitag_crc(tx, 12);
529 tx[1] |= crc >> 4;
530 tx[2] = crc << 4;
531 *txlen = 20;
532 // will receive 32-bit encrypted page
535 break;
536 case 32: {
537 if (bCollision) {
538 // Select card by serial from response
539 tx[0] = 0x00 | rx[0] >> 5;
540 tx[1] = rx[0] << 3 | rx[1] >> 5;
541 tx[2] = rx[1] << 3 | rx[2] >> 5;
542 tx[3] = rx[2] << 3 | rx[3] >> 5;
543 tx[4] = rx[3] << 3;
544 crc = hitag_crc(tx, 37);
545 tx[4] |= crc >> 5;
546 tx[5] = crc << 3;
547 *txlen = 45;
548 bCollision = false;
549 bSelecting = true;
550 // will receive 32-bit configuration page
551 } else if (bSelecting) {
552 // Initiate auth
553 tx[0] = 0xa0 | (key_no); // WRCPAGE
554 tx[1] = blocknr << 4;
555 crc = hitag_crc(tx, 12);
556 tx[1] |= crc >> 4;
557 tx[2] = crc << 4;
558 *txlen = 20;
559 bSelecting = false;
560 bAuthenticating = true;
561 // will receive 2-bit ACK
562 } else if (bAuthenticating) {
563 // received 32-bit logdata 0
564 // TODO decrypt logdata 0, verify against logdata_0
565 memcpy(tag.sectors[0], rx, 4);
566 memcpy(tag.sectors[1], tx, 4);
567 Dbprintf("%02x%02x%02x%02x %02x%02x%02x%02x", rx[0], rx[1], rx[2], rx[3], tx[0], tx[1], tx[2], tx[3]);
568 // TODO replace with secret data stream
569 // TODO encrypt logdata_1
570 memcpy(tx, logdata_1, 4);
571 *txlen = 32;
572 bAuthenticating = false;
573 bCrypto = true;
574 // will receive 2-bit ACK
575 } else if (bCrypto) {
576 // received 32-bit encrypted page
577 // TODO decrypt rx
578 memcpy(tag.sectors[blocknr], rx, 4);
579 blocknr++;
580 if (blocknr > 63) {
581 DbpString("Read succesful!");
582 bSuccessful = true;
583 return false;
586 // TEST
587 Dbprintf("Succesfully authenticated with logdata:");
588 Dbhexdump(4, logdata_1, false);
589 bSuccessful = true;
590 return false;
592 // read next page of card until done
593 tx[0] = 0xe0 | blocknr >> 4; // RDCPAGE
594 tx[1] = blocknr << 4;
595 crc = hitag_crc(tx, 12);
596 tx[1] |= crc >> 4;
597 tx[2] = crc << 4;
598 *txlen = 20;
602 break;
603 default: {
604 Dbprintf("Uknown frame length: %d", rxlen);
605 return false;
607 break;
610 return true;
613 //-----------------------------------------------------------------------------
614 // Hitag2 operations
615 //-----------------------------------------------------------------------------
617 static bool hitag2_write_page(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
618 switch (writestate) {
619 case WRITE_STATE_START:
620 *txlen = 10;
621 tx[0] = 0x82 | (blocknr << 3) | ((blocknr ^ 7) >> 2);
622 tx[1] = ((blocknr ^ 7) << 6);
623 writestate = WRITE_STATE_PAGENUM_WRITTEN;
624 break;
625 case WRITE_STATE_PAGENUM_WRITTEN:
626 // Check if page number was received correctly
627 if ((rxlen == 10)
628 && (rx[0] == (0x82 | (blocknr << 3) | ((blocknr ^ 7) >> 2)))
629 && (rx[1] == (((blocknr & 0x3) ^ 0x3) << 6))) {
631 *txlen = 32;
632 memset(tx, 0, HITAG_FRAME_LEN);
633 memcpy(tx, writedata, 4);
634 writestate = WRITE_STATE_PROG;
635 } else {
636 Dbprintf("hitag2_write_page: Page number was not received correctly: rxlen=%d rx=%02x%02x%02x%02x",
637 rxlen, rx[0], rx[1], rx[2], rx[3]);
638 bSuccessful = false;
639 return false;
641 break;
642 case WRITE_STATE_PROG:
643 if (rxlen == 0) {
644 bSuccessful = true;
645 } else {
646 bSuccessful = false;
647 Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen);
649 return false;
650 default:
651 DbpString("hitag2_write_page: Unknown state %d");
652 bSuccessful = false;
653 return false;
656 return true;
659 static bool hitag2_password(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen, bool write) {
660 // Reset the transmission frame length
661 *txlen = 0;
663 if (bPwd && !bAuthenticating && write) {
664 if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
665 return false;
667 } else {
668 // Try to find out which command was send by selecting on length (in bits)
669 switch (rxlen) {
670 // No answer, try to resurrect
671 case 0: {
672 // Stop if there is no answer (after sending password)
673 if (bPwd) {
674 DbpString("Password failed!");
675 return false;
677 *txlen = 5;
678 memcpy(tx, "\xC0", nbytes(*txlen));
680 break;
682 // Received UID, tag password
683 case 32: {
684 // stage 1, got UID
685 if (!bPwd) {
686 bPwd = true;
687 bAuthenticating = true;
688 memcpy(tx, password, 4);
689 *txlen = 32;
690 } else {
691 // stage 2, got config byte+password TAG, discard as will read later
692 if (bAuthenticating) {
693 bAuthenticating = false;
694 if (write) {
695 if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
696 return false;
698 break;
701 // stage 2+, got data block
702 else {
703 memcpy(tag.sectors[blocknr], rx, 4);
704 blocknr++;
707 if (blocknr > 7) {
708 bSuccessful = true;
709 return false;
712 *txlen = 10;
713 tx[0] = 0xC0 | (blocknr << 3) | ((blocknr ^ 7) >> 2);
714 tx[1] = ((blocknr ^ 7) << 6);
717 break;
719 // Unexpected response
720 default: {
721 Dbprintf("Unknown frame length: %d", rxlen);
722 return false;
724 break;
728 return true;
731 static bool hitag2_crypto(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen, bool write) {
732 // Reset the transmission frame length
733 *txlen = 0;
735 if (bCrypto) {
736 hitag2_cipher_transcrypt(&cipher_state, rx, rxlen / 8, rxlen % 8);
739 if (bCrypto && !bAuthenticating && write) {
740 if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
741 return false;
743 } else {
745 // Try to find out which command was send by selecting on length (in bits)
746 switch (rxlen) {
747 // No answer, try to resurrect
748 case 0: {
749 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
750 if (bCrypto) {
751 // Failed during authentication
752 if (bAuthenticating) {
753 DbpString("Authentication failed!");
754 return false;
755 } else {
756 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
757 if (blocknr == 1) {
758 // Write the low part of the key in memory
759 memcpy(tag.sectors[1], key + 2, 4);
760 } else if (blocknr == 2) {
761 // Write the high part of the key in memory
762 tag.sectors[2][0] = 0x00;
763 tag.sectors[2][1] = 0x00;
764 tag.sectors[2][2] = key[0];
765 tag.sectors[2][3] = key[1];
766 } else {
767 // Just put zero's in the memory (of the unreadable block)
768 memset(tag.sectors[blocknr], 0x00, 4);
770 blocknr++;
771 bCrypto = false;
773 } else {
774 *txlen = 5;
775 memcpy(tx, "\xc0", nbytes(*txlen));
777 break;
779 // Received UID, crypto tag answer
780 case 32: {
781 // stage 1, got UID
782 if (!bCrypto) {
783 uint64_t ui64key = key[0] | ((uint64_t)key[1]) << 8 | ((uint64_t)key[2]) << 16 | ((uint64_t)key[3]) << 24 | ((uint64_t)key[4]) << 32 | ((uint64_t)key[5]) << 40;
784 uint32_t ui32uid = rx[0] | ((uint32_t)rx[1]) << 8 | ((uint32_t)rx[2]) << 16 | ((uint32_t)rx[3]) << 24;
785 Dbprintf("hitag2_crypto: key=0x%x%x uid=0x%x", (uint32_t)((REV64(ui64key)) >> 32), (uint32_t)((REV64(ui64key)) & 0xffffffff), REV32(ui32uid));
786 cipher_state = _hitag2_init(REV64(ui64key), REV32(ui32uid), 0);
787 // PRN
788 memset(tx, 0x00, 4);
789 // Secret data
790 memset(tx + 4, 0xff, 4);
791 hitag2_cipher_transcrypt(&cipher_state, tx + 4, 4, 0);
792 *txlen = 64;
793 bCrypto = true;
794 bAuthenticating = true;
795 } else {
796 // stage 2, got config byte+password TAG, discard as will read later
797 if (bAuthenticating) {
798 bAuthenticating = false;
799 if (write) {
800 if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
801 return false;
803 break;
806 // stage 2+, got data block
807 else {
808 // Store the received block
809 memcpy(tag.sectors[blocknr], rx, 4);
810 blocknr++;
812 if (blocknr > 7) {
813 DbpString("Read successful!");
814 bSuccessful = true;
815 return false;
816 } else {
817 *txlen = 10;
818 tx[0] = 0xc0 | (blocknr << 3) | ((blocknr ^ 7) >> 2);
819 tx[1] = ((blocknr ^ 7) << 6);
823 break;
825 // Unexpected response
826 default: {
827 Dbprintf("Unknown frame length: %d", rxlen);
828 return false;
830 break;
834 if (bCrypto) {
835 // We have to return now to avoid double encryption
836 if (!bAuthenticating) {
837 hitag2_cipher_transcrypt(&cipher_state, tx, *txlen / 8, *txlen % 8);
841 return true;
844 static bool hitag2_authenticate(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
845 // Reset the transmission frame length
846 *txlen = 0;
848 // Try to find out which command was send by selecting on length (in bits)
849 switch (rxlen) {
850 // No answer, try to resurrect
851 case 0: {
852 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
853 if (bCrypto) {
854 DbpString("Authentication failed!");
855 return false;
857 *txlen = 5;
858 memcpy(tx, "\xC0", nbytes(*txlen));
860 break;
862 // Received UID, crypto tag answer
863 case 32: {
864 if (!bCrypto) {
865 *txlen = 64;
866 memcpy(tx, NrAr, 8);
867 bCrypto = true;
868 } else {
869 DbpString("Authentication successful!");
870 return true;
873 break;
875 // Unexpected response
876 default: {
877 Dbprintf("Unknown frame length: %d", rxlen);
878 return false;
880 break;
883 return true;
886 static bool hitag2_test_auth_attempts(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
888 // Reset the transmission frame length
889 *txlen = 0;
891 // Try to find out which command was send by selecting on length (in bits)
892 switch (rxlen) {
893 // No answer, try to resurrect
894 case 0: {
895 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
896 if (bCrypto) {
897 Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed, removed entry!", NrAr[0], NrAr[1], NrAr[2], NrAr[3], NrAr[4], NrAr[5], NrAr[6], NrAr[7]);
899 // Removing failed entry from authentiations table
900 memcpy(auth_table + auth_table_pos, auth_table + auth_table_pos + 8, 8);
901 auth_table_len -= 8;
903 // Return if we reached the end of the authentications table
904 bCrypto = false;
905 if (auth_table_pos == auth_table_len) {
906 return false;
909 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
910 memcpy(NrAr, auth_table + auth_table_pos, 8);
912 *txlen = 5;
913 memcpy(tx, "\xc0", nbytes(*txlen));
915 break;
917 // Received UID, crypto tag answer, or read block response
918 case 32: {
919 if (!bCrypto) {
920 *txlen = 64;
921 memcpy(tx, NrAr, 8);
922 bCrypto = true;
923 } else {
924 Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x OK", NrAr[0], NrAr[1], NrAr[2], NrAr[3], NrAr[4], NrAr[5], NrAr[6], NrAr[7]);
925 bCrypto = false;
926 if ((auth_table_pos + 8) == auth_table_len) {
927 return false;
929 auth_table_pos += 8;
930 memcpy(NrAr, auth_table + auth_table_pos, 8);
933 break;
935 default: {
936 Dbprintf("Unknown frame length: %d", rxlen);
937 return false;
939 break;
942 return true;
945 static bool hitag2_read_uid(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
946 // Reset the transmission frame length
947 *txlen = 0;
949 // Try to find out which command was send by selecting on length (in bits)
950 switch (rxlen) {
951 // No answer, try to resurrect
952 case 0: {
953 // Just starting or if there is no answer
954 *txlen = 5;
955 memcpy(tx, "\xC0", nbytes(*txlen));
957 break;
958 // Received UID
959 case 32: {
960 // Check if we received answer tag (at)
961 if (bAuthenticating) {
962 bAuthenticating = false;
963 } else {
964 // Store the received block
965 memcpy(tag.sectors[blocknr], rx, 4);
966 blocknr++;
968 DBG Dbhexdump(4, rx, false);
970 if (blocknr > 0) {
971 DBG DbpString("Read successful!");
972 bSuccessful = true;
973 return true;
976 break;
977 // Unexpected response
978 default: {
979 DBG Dbprintf("Unknown frame length: %d", rxlen);
980 return false;
982 break;
984 return true;
987 void EloadHitag(uint8_t *data, uint16_t len) {
988 memcpy(tag.sectors, data, sizeof(tag.sectors));
991 // Hitag2 Sniffing
993 // T0 18-22 fc (total time ZERO)
994 // T1 26-32 fc (total time ONE)
995 // Tstop 36 > fc (high field stop limit)
996 // Tlow 4-10 fc (reader field low time)
997 void SniffHitag2(void) {
998 DbpString("Starting Hitag2 sniffing");
999 LED_D_ON();
1001 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1003 BigBuf_free();
1004 BigBuf_Clear_ext(false);
1005 clear_trace();
1006 set_tracing(true);
1009 lf_init(false, false);
1011 // no logging of the raw signal
1012 g_logging = lf_get_reader_modulation();
1013 uint32_t total_count = 0;
1015 uint8_t rx[20 * 8 * 2];
1016 while (BUTTON_PRESS() == false) {
1018 lf_reset_counter();
1020 WDT_HIT();
1022 size_t periods = 0;
1023 uint16_t rxlen = 0;
1024 memset(rx, 0x00, sizeof(rx));
1026 // Use the current modulation state as starting point
1027 uint8_t mod_state = lf_get_reader_modulation();
1029 while (rxlen < sizeof(rx)) {
1030 periods = lf_count_edge_periods(64);
1031 // Evaluate the number of periods before the next edge
1032 if (periods >= 24 && periods < 64) {
1033 // Detected two sequential equal bits and a modulation switch
1034 // NRZ modulation: (11 => --|) or (11 __|)
1035 rx[rxlen++] = mod_state;
1036 rx[rxlen++] = mod_state;
1037 // toggle tag modulation state
1038 mod_state ^= 1;
1039 } else if (periods > 0 && periods < 24) {
1040 // Detected one bit and a modulation switch
1041 // NRZ modulation: (1 => -|) or (0 _|)
1042 rx[rxlen++] = mod_state;
1043 mod_state ^= 1;
1044 } else {
1045 mod_state ^= 1;
1046 break;
1050 if (rxlen == 0)
1051 continue;
1053 // tag sends 11111 + uid,
1054 bool got_tag = ((memcmp(rx, "\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00", 10) == 0));
1056 if (got_tag) {
1057 // mqnchester decode
1058 bool bad_man = false;
1059 uint16_t bitnum = 0;
1060 for (uint16_t i = 0; i < rxlen; i += 2) {
1061 if (rx[i] == 1 && (rx[i + 1] == 0)) {
1062 rx[bitnum++] = 0;
1063 } else if ((rx[i] == 0) && rx[i + 1] == 1) {
1064 rx[bitnum++] = 1;
1065 } else {
1066 bad_man = true;
1070 if (bad_man) {
1071 DBG DbpString("bad manchester");
1072 continue;
1075 if (bitnum < 5) {
1076 DBG DbpString("too few bits");
1077 continue;
1080 // skip header 11111
1081 uint16_t i = 0;
1082 if (got_tag) {
1083 i = 5;
1086 // Pack the response into a byte array
1087 rxlen = 0;
1088 for (; i < bitnum; i++) {
1089 uint8_t b = rx[i];
1090 rx[rxlen >> 3] |= b << (7 - (rxlen % 8));
1091 rxlen++;
1094 // skip spurious bit
1095 if (rxlen % 8 == 1) {
1096 rxlen--;
1099 // nothing to log
1100 if (rxlen == 0)
1101 continue;
1103 LogTrace(rx, nbytes(rxlen), 0, 0, NULL, false);
1104 total_count += nbytes(rxlen);
1105 } else {
1106 // decode reader comms
1107 LogTrace(rx, rxlen, 0, 0, NULL, true);
1108 total_count += rxlen;
1109 // Pack the response into a byte array
1111 // LogTrace(rx, nbytes(rdr), 0, 0, NULL, true);
1112 // total_count += nbytes(rdr);
1114 LED_A_INV();
1117 lf_finalize();
1119 Dbprintf("Collected %u bytes", total_count);
1123 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
1124 // and analog mux selection.
1125 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE);
1126 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); // 125Khz
1127 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
1128 RELAY_OFF();
1130 // Configure output pin that is connected to the FPGA (for modulating)
1131 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
1132 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
1134 // Disable modulation, we are going to eavesdrop, not modulate ;)
1135 LOW(GPIO_SSC_DOUT);
1137 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
1138 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
1139 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
1141 // Disable timer during configuration
1142 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1144 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1145 // external trigger rising edge, load RA on rising edge of TIOA.
1146 AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_BOTH | AT91C_TC_ABETRG | AT91C_TC_LDRA_BOTH;
1148 // Enable and reset counter
1149 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1151 // Assert a sync signal. This sets all timers to 0 on next active clock edge
1152 AT91C_BASE_TCB->TCB_BCR = 1;
1154 int frame_count = 0, response = 0, overflow = 0, lastbit = 1, tag_sof = 4;
1155 bool rising_edge = false, reader_frame = false, bSkip = true;
1156 uint8_t rx[HITAG_FRAME_LEN];
1157 size_t rxlen = 0;
1159 auth_table_len = 0;
1160 auth_table_pos = 0;
1162 // Reset the received frame, frame count and timing info
1163 memset(rx, 0x00, sizeof(rx));
1165 auth_table = (uint8_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
1166 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
1168 while (BUTTON_PRESS() == false) {
1170 WDT_HIT();
1171 memset(rx, 0x00, sizeof(rx));
1173 // Receive frame, watch for at most T0 * EOF periods
1174 while (AT91C_BASE_TC1->TC_CV < (HITAG_T0 * HITAG_T_EOF)) {
1175 // Check if rising edge in modulation is detected
1176 if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
1177 // Retrieve the new timing values
1178 int ra = (AT91C_BASE_TC1->TC_RA / HITAG_T0);
1180 // Find out if we are dealing with a rising or falling edge
1181 rising_edge = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME) > 0;
1183 // Shorter periods will only happen with reader frames
1184 if (reader_frame == false && rising_edge && ra < HITAG_T_TAG_CAPTURE_ONE_HALF) {
1185 // Switch from tag to reader capture
1186 LED_C_OFF();
1187 reader_frame = true;
1188 rxlen = 0;
1191 // Only handle if reader frame and rising edge, or tag frame and falling edge
1192 if (reader_frame == rising_edge) {
1193 overflow += ra;
1194 continue;
1197 // Add the buffered timing values of earlier captured edges which were skipped
1198 ra += overflow;
1199 overflow = 0;
1201 if (reader_frame) {
1202 LED_B_ON();
1203 // Capture reader frame
1204 if (ra >= HITAG_T_STOP) {
1205 // if (rxlen != 0) {
1206 //DbpString("wierd0?");
1207 // }
1208 // Capture the T0 periods that have passed since last communication or field drop (reset)
1209 response = (ra - HITAG_T_LOW);
1210 } else if (ra >= HITAG_T_1_MIN) {
1211 // '1' bit
1212 rx[rxlen / 8] |= 1 << (7 - (rxlen % 8));
1213 rxlen++;
1214 } else if (ra >= HITAG_T_0_MIN) {
1215 // '0' bit
1216 rx[rxlen / 8] |= 0 << (7 - (rxlen % 8));
1217 rxlen++;
1220 } else {
1221 LED_C_ON();
1222 // Capture tag frame (manchester decoding using only falling edges)
1223 if (ra >= HITAG_T_EOF) {
1224 // if (rxlen != 0) {
1225 //DbpString("wierd1?");
1226 // }
1227 // Capture the T0 periods that have passed since last communication or field drop (reset)
1228 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1229 response = ra - HITAG_T_TAG_HALF_PERIOD;
1231 } else if (ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
1232 // Manchester coding example |-_|_-|-_| (101)
1233 rx[rxlen / 8] |= 0 << (7 - (rxlen % 8));
1234 rxlen++;
1235 rx[rxlen / 8] |= 1 << (7 - (rxlen % 8));
1236 rxlen++;
1238 } else if (ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
1239 // Manchester coding example |_-|...|_-|-_| (0...01)
1240 rx[rxlen / 8] |= 0 << (7 - (rxlen % 8));
1241 rxlen++;
1242 // We have to skip this half period at start and add the 'one' the second time
1243 if (bSkip == false) {
1244 rx[rxlen / 8] |= 1 << (7 - (rxlen % 8));
1245 rxlen++;
1247 lastbit = !lastbit;
1248 bSkip = !bSkip;
1250 } else if (ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
1251 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1252 if (tag_sof) {
1253 // Ignore bits that are transmitted during SOF
1254 tag_sof--;
1255 } else {
1256 // bit is same as last bit
1257 rx[rxlen / 8] |= lastbit << (7 - (rxlen % 8));
1258 rxlen++;
1265 // Check if frame was captured
1266 if (rxlen) {
1267 frame_count++;
1268 LogTrace(rx, nbytes(rxlen), response, 0, NULL, reader_frame);
1270 // Check if we recognize a valid authentication attempt
1271 if (nbytes(rxlen) == 8) {
1272 // Store the authentication attempt
1273 if (auth_table_len < (AUTH_TABLE_LENGTH - 8)) {
1274 memcpy(auth_table + auth_table_len, rx, 8);
1275 auth_table_len += 8;
1279 // Reset the received frame and response timing info
1280 memset(rx, 0x00, sizeof(rx));
1281 response = 0;
1282 reader_frame = false;
1283 lastbit = 1;
1284 bSkip = true;
1285 tag_sof = 4;
1286 overflow = 0;
1288 LED_B_OFF();
1289 LED_C_OFF();
1290 } else {
1291 // Save the timer overflow, will be 0 when frame was received
1292 overflow += (AT91C_BASE_TC1->TC_CV / HITAG_T0);
1294 // Reset the frame length
1295 rxlen = 0;
1296 // Reset the timer to restart while-loop that receives frames
1297 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
1298 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
1300 // Assert a sync signal. This sets all timers to 0 on next active clock edge
1301 AT91C_BASE_TCB->TCB_BCR = 1;
1304 LEDsoff();
1305 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1306 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1308 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1309 set_tracing(false);
1311 Dbprintf("frame received: %d", frame_count);
1312 Dbprintf("Authentication Attempts: %d", (auth_table_len / 8));
1316 // Hitag2 simulation
1317 void SimulateHitag2(void) {
1319 BigBuf_free();
1320 BigBuf_Clear_ext(false);
1321 clear_trace();
1322 set_tracing(true);
1324 // empties bigbuff etc
1325 lf_init(false, true);
1327 int response = 0;
1328 uint8_t rx[HITAG_FRAME_LEN] = {0};
1329 uint8_t tx[HITAG_FRAME_LEN] = {0};
1331 auth_table_len = 0;
1332 auth_table_pos = 0;
1333 // auth_table = BigBuf_malloc(AUTH_TABLE_LENGTH);
1334 // memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
1336 // Reset the received frame, frame count and timing info
1337 // memset(rx, 0x00, sizeof(rx));
1338 // memset(tx, 0x00, sizeof(tx));
1340 DbpString("Starting Hitag2 simulation");
1342 // hitag2 state machine?
1343 hitag2_init();
1345 // printing
1346 uint32_t block = 0;
1347 for (size_t i = 0; i < 12; i++) {
1349 // num2bytes?
1350 for (size_t j = 0; j < 4; j++) {
1351 block <<= 8;
1352 block |= tag.sectors[i][j];
1354 Dbprintf("| %d | %08x |", i, block);
1357 size_t max_nrzs = 8 * HITAG_FRAME_LEN + 5;
1358 uint8_t nrz_samples[max_nrzs];
1360 // uint32_t command_start = 0, command_duration = 0;
1361 // int16_t checked = 0;
1363 // SIMULATE
1364 uint32_t signal_size = 10000;
1365 while (BUTTON_PRESS() == false) {
1367 // use malloc
1368 initSampleBufferEx(&signal_size, true);
1370 LED_D_ON();
1372 // lf_reset_counter();
1373 LED_A_OFF();
1374 WDT_HIT();
1377 // only every 1000th times, in order to save time when collecting samples.
1378 if (checked == 100) {
1379 if (data_available()) {
1380 checked = -1;
1381 break;
1382 } else {
1383 checked = 0;
1386 ++checked;
1388 size_t rxlen = 0, txlen = 0;
1390 // Keep administration of the first edge detection
1391 bool waiting_for_first_edge = true;
1393 // Did we detected any modulaiton at all
1394 bool detected_modulation = false;
1396 // Use the current modulation state as starting point
1397 uint8_t reader_modulation = lf_get_reader_modulation();
1399 // Receive frame, watch for at most max_nrzs periods
1400 // Reset the number of NRZ samples and use edge detection to detect them
1401 size_t nrzs = 0;
1402 while (nrzs < max_nrzs) {
1403 // Get the timing of the next edge in number of wave periods
1404 size_t periods = lf_count_edge_periods(128);
1406 // Just break out of loop after an initial time-out (tag is probably not available)
1407 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1408 if (periods == 0) {
1409 break;
1412 LED_A_ON();
1414 // Are we dealing with the first incoming edge
1415 if (waiting_for_first_edge) {
1417 // Register the number of periods that have passed
1418 response = periods;
1420 // Indicate that we have dealt with the first edge
1421 waiting_for_first_edge = false;
1423 // The first edge is always a single NRZ bit, force periods on 16
1424 periods = 16;
1426 // We have received more than 0 periods, so we have detected a tag response
1427 detected_modulation = true;
1430 // Evaluate the number of periods before the next edge
1431 if (periods > 24 && periods <= 64) {
1432 // Detected two sequential equal bits and a modulation switch
1433 // NRZ modulation: (11 => --|) or (11 __|)
1434 nrz_samples[nrzs++] = reader_modulation;
1435 nrz_samples[nrzs++] = reader_modulation;
1436 // Invert tag modulation state
1437 reader_modulation ^= 1;
1438 } else if (periods > 0 && periods <= 24) {
1439 // Detected one bit and a modulation switch
1440 // NRZ modulation: (1 => -|) or (0 _|)
1441 nrz_samples[nrzs++] = reader_modulation;
1442 reader_modulation ^= 1;
1443 } else {
1444 reader_modulation ^= 1;
1445 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1446 Dbprintf("Detected unexpected period count: %d", periods);
1447 break;
1451 LED_D_OFF();
1453 // If there is no response, just repeat the loop
1454 if (!detected_modulation) continue;
1456 LED_A_OFF();
1458 // Make sure we always have an even number of samples. This fixes the problem
1459 // of ending the manchester decoding with a zero. See the example below where
1460 // the '|' character is end of modulation
1461 // One at the end: ..._-|_____...
1462 // Zero at the end: ...-_|_____...
1463 // The last modulation change of a zero is not detected, but we should take
1464 // the half period in account, otherwise the demodulator will fail.
1465 if ((nrzs % 2) != 0) {
1466 nrz_samples[nrzs++] = reader_modulation;
1469 LED_B_ON();
1471 // decode bitstream
1472 manrawdecode((uint8_t *)nrz_samples, &nrzs, true, 0);
1474 // Verify if the header consists of five consecutive ones
1475 if (nrzs < 5) {
1476 Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs);
1477 continue;
1478 } else {
1479 for (size_t i = 0; i < 5; i++) {
1480 if (nrz_samples[i] != 1) {
1481 Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one", i);
1486 // Pack the response into a byte array
1487 for (size_t i = 5; i < 37; i++) {
1488 uint8_t bit = nrz_samples[i];
1489 rx[rxlen / 8] |= bit << (7 - (rxlen % 8));
1490 rxlen++;
1493 // Check if frame was captured
1494 if (rxlen > 4) {
1496 LogTrace(rx, nbytes(rxlen), response, response, NULL, true);
1498 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1499 hitag2_handle_reader_command(rx, rxlen, tx, &txlen);
1501 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1502 // not that since the clock counts since the rising edge, but T_Wait1 is
1503 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1504 // periods. The gap time T_Low varies (4..10). All timer values are in
1505 // terms of T0 units (HITAG_T_WAIT_1_MIN - HITAG_T_LOW )
1506 lf_wait_periods(HITAG_T_WAIT_1_MIN);
1508 // Send and store the tag answer (if there is any)
1509 if (txlen) {
1510 // Transmit the tag frame
1511 //hitag_send_frame(tx, txlen);
1512 lf_manchester_send_bytes(tx, txlen);
1514 // Store the frame in the trace
1515 LogTrace(tx, nbytes(txlen), 0, 0, NULL, false);
1518 // Reset the received frame and response timing info
1519 memset(rx, 0x00, sizeof(rx));
1520 response = 0;
1522 LED_B_OFF();
1526 lf_finalize();
1528 // release allocated memory from BigBuff.
1529 BigBuf_free();
1531 DbpString("Sim stopped");
1533 // reply_ng(CMD_LF_HITAG_SIMULATE, (checked == -1) ? PM3_EOPABORTED : PM3_SUCCESS, (uint8_t *)tag.sectors, tag_size);
1536 void ReaderHitag(hitag_function htf, hitag_data *htd) {
1538 uint32_t command_start = 0, command_duration = 0;
1539 uint32_t response_start = 0, response_duration = 0;
1541 uint8_t rx[HITAG_FRAME_LEN] = {0};
1542 size_t rxlen = 0;
1543 uint8_t txbuf[HITAG_FRAME_LEN] = {0};
1544 uint8_t *tx = txbuf;
1545 size_t txlen = 0;
1547 int t_wait_1 = 204;
1548 int t_wait_1_guard = 8;
1549 int t_wait_2 = 128;
1550 size_t tag_size = 48;
1551 bool bStop = false;
1553 // Raw demodulation/decoding by sampling edge periods
1554 size_t periods = 0;
1556 // Reset the return status
1557 bSuccessful = false;
1558 bCrypto = false;
1560 // Clean up trace and prepare it for storing frames
1561 set_tracing(true);
1562 clear_trace();
1564 // Check configuration
1565 switch (htf) {
1566 case RHT1F_PLAIN: {
1567 DBG Dbprintf("Read public blocks in plain mode");
1568 // this part will be unreadable
1569 memset(tag.sectors + 2, 0x0, 30);
1570 blocknr = 0;
1571 break;
1573 case RHT1F_AUTHENTICATE: {
1574 DBG Dbprintf("Read all blocks in authed mode");
1575 memcpy(nonce, htd->ht1auth.nonce, 4);
1576 memcpy(key, htd->ht1auth.key, 4);
1577 memcpy(logdata_0, htd->ht1auth.logdata_0, 4);
1578 memcpy(logdata_1, htd->ht1auth.logdata_1, 4);
1579 // TEST
1580 memset(nonce, 0x0, 4);
1581 memset(logdata_1, 0x00, 4);
1582 byte_value = 0;
1583 key_no = htd->ht1auth.key_no;
1584 DBG Dbprintf("Authenticating using key #%u :", key_no);
1585 DBG Dbhexdump(4, key, false);
1586 DBG DbpString("Nonce:");
1587 DBG Dbhexdump(4, nonce, false);
1588 DBG DbpString("Logdata_0:");
1589 DBG Dbhexdump(4, logdata_0, false);
1590 DBG DbpString("Logdata_1:");
1591 DBG Dbhexdump(4, logdata_1, false);
1592 blocknr = 0;
1593 break;
1595 case RHT2F_PASSWORD: {
1596 DBG Dbprintf("List identifier in password mode");
1597 if (memcmp(htd->pwd.password, "\x00\x00\x00\x00", 4) == 0)
1598 memcpy(password, tag.sectors[1], sizeof(password));
1599 else
1600 memcpy(password, htd->pwd.password, sizeof(password));
1602 blocknr = 0;
1603 bPwd = false;
1604 bAuthenticating = false;
1605 break;
1607 case RHT2F_AUTHENTICATE: {
1608 DBG DbpString("Authenticating using nr,ar pair:");
1609 memcpy(NrAr, htd->auth.NrAr, 8);
1610 DBG Dbhexdump(8, NrAr, false);
1611 bCrypto = false;
1612 bAuthenticating = false;
1613 break;
1615 case RHT2F_CRYPTO: {
1616 DBG DbpString("Authenticating using key:");
1617 memcpy(key, htd->crypto.key, 6); //HACK; 4 or 6?? I read both in the code.
1618 DBG Dbhexdump(6, key, false);
1619 DBG DbpString("Nonce:");
1620 DBG Dbhexdump(4, nonce, false);
1621 memcpy(nonce, htd->crypto.data, 4);
1622 blocknr = 0;
1623 bCrypto = false;
1624 bAuthenticating = false;
1625 break;
1627 case RHT2F_TEST_AUTH_ATTEMPTS: {
1628 DBG Dbprintf("Testing %d authentication attempts", (auth_table_len / 8));
1629 auth_table_pos = 0;
1630 memcpy(NrAr, auth_table, 8);
1631 bCrypto = false;
1632 break;
1634 case RHT2F_UID_ONLY: {
1635 blocknr = 0;
1636 bCrypto = false;
1637 bAuthenticating = false;
1638 break;
1640 default: {
1641 DBG Dbprintf("Error, unknown function: %d", htf);
1642 set_tracing(false);
1643 return;
1647 LED_D_ON();
1649 // hitag2 state machine?
1650 hitag2_init();
1652 uint8_t attempt_count = 0;
1654 // Tag specific configuration settings (sof, timings, etc.)
1655 // TODO HTS
1656 /* if (htf <= HTS_LAST_CMD) {
1657 // hitagS settings
1658 t_wait_1 = 204;
1659 t_wait_2 = 128;
1660 flipped_bit = 0;
1661 tag_size = 8;
1662 DBG DbpString("Configured for hitagS reader");
1663 } else */
1664 if (htf <= HT1_LAST_CMD) {
1665 // hitag1 settings
1666 t_wait_1 = 204;
1667 t_wait_2 = 128;
1668 tag_size = 256;
1669 flipped_bit = 0;
1670 DBG DbpString("Configured for hitag1 reader");
1671 } else if (htf <= HT2_LAST_CMD) {
1672 // hitag2 settings
1673 t_wait_1 = HITAG_T_WAIT_1_MIN;
1674 t_wait_2 = HITAG_T_WAIT_2_MIN;
1675 tag_size = 48;
1676 DBG DbpString("Configured for hitag2 reader");
1679 // init as reader
1680 lf_init(true, false);
1681 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1683 uint8_t tag_modulation;
1684 size_t max_nrzs = (8 * HITAG_FRAME_LEN + 5) * 2; // up to 2 nrzs per bit
1685 uint8_t nrz_samples[max_nrzs];
1686 bool turn_on = true;
1687 size_t nrzs = 0;
1688 int16_t checked = 0;
1689 uint32_t signal_size = 10000;
1691 while (bStop == false && BUTTON_PRESS() == false) {
1693 // use malloc
1694 initSampleBufferEx(&signal_size, true);
1696 WDT_HIT();
1698 // only every 1000th times, in order to save time when collecting samples.
1699 if (checked == 4000) {
1700 if (data_available()) {
1701 checked = -1;
1702 break;
1703 } else {
1704 checked = 0;
1707 ++checked;
1709 // By default reset the transmission buffer
1710 tx = txbuf;
1711 switch (htf) {
1712 case RHT1F_PLAIN: {
1713 bStop = !hitag_plain(rx, rxlen, tx, &txlen, false);
1714 break;
1716 case RHT1F_AUTHENTICATE: {
1717 bStop = !hitag1_authenticate(rx, rxlen, tx, &txlen);
1718 break;
1720 case RHT2F_PASSWORD: {
1721 bStop = !hitag2_password(rx, rxlen, tx, &txlen, false);
1722 break;
1724 case RHT2F_AUTHENTICATE: {
1725 bStop = !hitag2_authenticate(rx, rxlen, tx, &txlen);
1726 break;
1728 case RHT2F_CRYPTO: {
1729 bStop = !hitag2_crypto(rx, rxlen, tx, &txlen, false);
1730 break;
1732 case RHT2F_TEST_AUTH_ATTEMPTS: {
1733 bStop = !hitag2_test_auth_attempts(rx, rxlen, tx, &txlen);
1734 break;
1736 case RHT2F_UID_ONLY: {
1737 bStop = !hitag2_read_uid(rx, rxlen, tx, &txlen);
1738 if (bSuccessful) bStop = true;
1739 attempt_count++; //attempt 3 times to get uid then quit
1740 if (!bStop && attempt_count == 3)
1741 bStop = true;
1743 break;
1745 default: {
1746 DBG Dbprintf("Error, unknown function: %d", htf);
1747 goto out;
1750 if (bStop) break;
1751 if (turn_on) {
1752 // Wait 50ms with field off to be sure the transponder gets reset
1753 SpinDelay(50);
1754 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
1755 turn_on = false;
1756 // Wait with field on to be in "Wait for START_AUTH" timeframe
1757 lf_wait_periods(HITAG_T_WAIT_POWERUP + HITAG_T_WAIT_START_AUTH_MAX / 4);
1758 command_start += HITAG_T_WAIT_POWERUP + HITAG_T_WAIT_START_AUTH_MAX / 4;
1759 } else {
1760 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
1761 lf_wait_periods(t_wait_2);
1762 command_start += t_wait_2;
1764 // Transmit the reader frame
1765 command_duration = hitag_reader_send_frame(tx, txlen);
1766 response_start = command_start + command_duration;
1768 // Let the antenna and ADC values settle
1769 // And find the position where edge sampling should start
1770 lf_wait_periods(t_wait_1 - t_wait_1_guard);
1771 response_start += t_wait_1 - t_wait_1_guard;
1773 // Keep administration of the first edge detection
1774 bool waiting_for_first_edge = true;
1776 // Did we detected any modulaiton at all
1777 bool detected_tag_modulation = false;
1779 // Use the current modulation state as starting point
1780 tag_modulation = lf_get_tag_modulation();
1782 // Reset the number of NRZ samples and use edge detection to detect them
1783 nrzs = 0;
1784 while (nrzs < max_nrzs) {
1785 // Get the timing of the next edge in number of wave periods
1786 periods = lf_count_edge_periods(128);
1788 // Are we dealing with the first incoming edge
1789 if (waiting_for_first_edge) {
1790 // Just break out of loop after an initial time-out (tag is probably not available)
1791 if (periods == 0) break;
1792 if (tag_modulation == 0) {
1793 // hitag replies always start with 11111 == 1010101010, if we see 0
1794 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
1795 // so let's add it:
1796 nrz_samples[nrzs++] = tag_modulation ^ 1;
1797 // Register the number of periods that have passed
1798 // we missed the begin of response but we know it happened one period of 16 earlier
1799 response_start += periods - 16;
1800 response_duration = response_start;
1801 } else {
1802 // Register the number of periods that have passed
1803 response_start += periods;
1804 response_duration = response_start;
1806 // Indicate that we have dealt with the first edge
1807 waiting_for_first_edge = false;
1808 // The first edge is always a single NRZ bit, force periods on 16
1809 periods = 16;
1810 // We have received more than 0 periods, so we have detected a tag response
1811 detected_tag_modulation = true;
1812 } else {
1813 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1814 if (periods == 0) {
1815 DBG Dbprintf("Detected timeout after [%d] nrz samples", nrzs);
1816 break;
1819 // Evaluate the number of periods before the next edge
1820 if (periods > 24 && periods <= 64) {
1821 // Detected two sequential equal bits and a modulation switch
1822 // NRZ modulation: (11 => --|) or (11 __|)
1823 nrz_samples[nrzs++] = tag_modulation;
1824 nrz_samples[nrzs++] = tag_modulation;
1825 response_duration += periods;
1826 // Invert tag modulation state
1827 tag_modulation ^= 1;
1828 } else if (periods > 0 && periods <= 24) {
1829 // Detected one bit and a modulation switch
1830 // NRZ modulation: (1 => -|) or (0 _|)
1831 nrz_samples[nrzs++] = tag_modulation;
1832 response_duration += periods;
1833 tag_modulation ^= 1;
1834 } else {
1835 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1836 DBG Dbprintf("Detected unexpected period count: %d", periods);
1837 break;
1841 // Store the TX frame, we do this now at this point, to avoid delay in processing
1842 // and to be able to overwrite the first samples with the trace (since they currently
1843 // still use the same memory space)
1844 if (txlen > 0) {
1845 LogTrace(tx, nbytes(txlen), command_start, command_start + command_duration, NULL, true);
1848 // Reset values for receiving frames
1849 memset(rx, 0x00, sizeof(rx));
1850 rxlen = 0;
1852 // If there is no response, just repeat the loop
1853 if (!detected_tag_modulation) continue;
1855 // Make sure we always have an even number of samples. This fixes the problem
1856 // of ending the manchester decoding with a zero. See the example below where
1857 // the '|' character is end of modulation
1858 // One at the end: ..._-|_____...
1859 // Zero at the end: ...-_|_____...
1860 // The last modulation change of a zero is not detected, but we should take
1861 // the half period in account, otherwise the demodulator will fail.
1862 if ((nrzs % 2) != 0) {
1863 nrz_samples[nrzs++] = tag_modulation;
1866 LED_B_ON();
1868 // decode bitstream
1869 manrawdecode((uint8_t *)nrz_samples, &nrzs, true, 0);
1871 // decode frame
1873 // Verify if the header consists of five consecutive ones
1874 if (nrzs < 5) {
1875 DBG Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs);
1876 break;
1877 } else {
1878 size_t i;
1879 for (i = 0; i < 5; i++) {
1880 if (nrz_samples[i] != 1) {
1881 DBG Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one, abort", i);
1882 break;
1885 if (i < 5) break;
1888 // Pack the response into a byte array
1889 for (size_t i = 5; i < nrzs && rxlen < (sizeof(rx) << 3); i++) {
1890 uint8_t bit = nrz_samples[i];
1891 if (bit > 1) { // When Manchester detects impossible symbol it writes "7"
1892 DBG Dbprintf("Error in Manchester decoding, abort");
1893 break;
1895 rx[rxlen >> 3] |= bit << (7 - (rxlen % 8));
1896 rxlen++;
1899 if (rxlen % 8 == 1) // skip spurious bit
1900 rxlen--;
1902 // Check if frame was captured and store it
1903 if (rxlen > 0) {
1905 LogTrace(rx, nbytes(rxlen), response_start, response_start + response_duration, NULL, false);
1907 // TODO when using cumulative time for command_start, pm3 doesn't reply anymore, e.g. on lf hitag reader --23 -k 4F4E4D494B52
1908 // Use delta time?
1909 // command_start = response_start + response_duration;
1910 command_start = 0;
1911 nrzs = 0;
1915 out:
1916 lf_finalize();
1918 // release allocated memory from BigBuff.
1919 BigBuf_free();
1921 if (bSuccessful)
1922 reply_mix(CMD_ACK, bSuccessful, 0, 0, (uint8_t *)tag.sectors, tag_size);
1923 else
1924 reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0);
1927 void WriterHitag(hitag_function htf, hitag_data *htd, int page) {
1929 uint32_t command_start = 0;
1930 uint32_t command_duration = 0;
1931 uint32_t response_start = 0;
1932 uint32_t response_duration = 0;
1933 uint8_t rx[HITAG_FRAME_LEN];
1934 size_t rxlen = 0;
1935 uint8_t txbuf[HITAG_FRAME_LEN];
1936 uint8_t *tx = txbuf;
1937 size_t txlen = 0;
1939 int t_wait_1 = 204;
1940 int t_wait_1_guard = 8;
1941 int t_wait_2 = 128;
1942 size_t tag_size = 48;
1944 bool bStop = false;
1946 // Raw demodulation/decoding by sampling edge periods
1947 size_t periods = 0;
1949 // Reset the return status
1950 bSuccessful = false;
1951 bCrypto = false;
1953 // Clean up trace and prepare it for storing frames
1954 set_tracing(true);
1955 clear_trace();
1958 // Check configuration
1959 switch (htf) {
1960 case WHT2F_CRYPTO: {
1961 DbpString("Authenticating using key:");
1962 memcpy(key, htd->crypto.key, 6); //HACK; 4 or 6?? I read both in the code.
1963 memcpy(writedata, htd->crypto.data, 4);
1964 Dbhexdump(6, key, false);
1965 blocknr = page;
1966 bCrypto = false;
1967 bAuthenticating = false;
1968 writestate = WRITE_STATE_START;
1970 break;
1971 case WHT2F_PASSWORD: {
1972 DbpString("Authenticating using password:");
1973 memcpy(password, htd->pwd.password, 4);
1974 memcpy(writedata, htd->crypto.data, 4);
1975 Dbhexdump(4, password, false);
1976 blocknr = page;
1977 bPwd = false;
1978 bAuthenticating = false;
1979 writestate = WRITE_STATE_START;
1981 break;
1982 default: {
1983 Dbprintf("Error, unknown function: %d", htf);
1984 return;
1986 break;
1989 LED_D_ON();
1991 hitag2_init();
1993 // init as reader
1994 lf_init(true, false);
1995 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1997 // Tag specific configuration settings (sof, timings, etc.)
1998 // TODO HTS
1999 /* if (htf <= HTS_LAST_CMD) {
2000 // hitagS settings
2001 t_wait_1 = 204;
2002 t_wait_2 = 128;
2003 //tag_size = 256;
2004 flipped_bit = 0;
2005 tag_size = 8;
2006 DbpString("Configured for hitagS writer");
2007 } else */
2008 // TODO HT1
2009 /* if (htf <= HT1_LAST_CMD) {
2010 // hitag1 settings
2011 t_wait_1 = 204;
2012 t_wait_2 = 128;
2013 tag_size = 256;
2014 flipped_bit = 0;
2015 DbpString("Configured for hitag1 writer");
2016 } else */
2017 // if (htf <= HT2_LAST_CMD) {
2018 // hitag2 settings
2019 t_wait_1 = HITAG_T_WAIT_1_MIN;
2020 t_wait_2 = HITAG_T_WAIT_2_MIN;
2021 tag_size = 48;
2022 DbpString("Configured for hitag2 writer");
2023 // }
2025 uint8_t tag_modulation;
2026 size_t max_nrzs = (8 * HITAG_FRAME_LEN + 5) * 2; // up to 2 nrzs per bit
2027 uint8_t nrz_samples[max_nrzs];
2028 size_t nrzs = 0;
2029 int16_t checked = 0;
2030 uint32_t signal_size = 10000;
2031 bool turn_on = true;
2033 while (bStop == false && BUTTON_PRESS() == false) {
2035 // use malloc
2036 initSampleBufferEx(&signal_size, true);
2038 // only every 4000th times, in order to save time when collecting samples.
2039 if (checked == 4000) {
2040 if (data_available()) {
2041 checked = -1;
2042 break;
2043 } else {
2044 checked = 0;
2047 ++checked;
2049 WDT_HIT();
2051 // By default reset the transmission buffer
2052 tx = txbuf;
2053 switch (htf) {
2054 case WHT2F_CRYPTO: {
2055 bStop = !hitag2_crypto(rx, rxlen, tx, &txlen, true);
2056 break;
2058 case WHT2F_PASSWORD: {
2059 bStop = !hitag2_password(rx, rxlen, tx, &txlen, true);
2060 break;
2062 default: {
2063 Dbprintf("Error, unknown function: %d", htf);
2064 goto out;
2068 if (bStop) break;
2069 if (turn_on) {
2070 // Wait 50ms with field off to be sure the transponder gets reset
2071 SpinDelay(50);
2072 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
2073 turn_on = false;
2074 // Wait with field on to be in "Wait for START_AUTH" timeframe
2075 lf_wait_periods(HITAG_T_WAIT_POWERUP + HITAG_T_WAIT_START_AUTH_MAX / 4);
2076 command_start += HITAG_T_WAIT_POWERUP + HITAG_T_WAIT_START_AUTH_MAX / 4;
2077 } else {
2078 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
2079 lf_wait_periods(t_wait_2);
2080 command_start += t_wait_2;
2083 // Transmit the reader frame
2084 command_duration = hitag_reader_send_frame(tx, txlen);
2086 response_start = command_start + command_duration;
2088 // Let the antenna and ADC values settle
2089 // And find the position where edge sampling should start
2090 lf_wait_periods(t_wait_1 - t_wait_1_guard);
2091 response_start += t_wait_1 - t_wait_1_guard;
2093 // Keep administration of the first edge detection
2094 bool waiting_for_first_edge = true;
2096 // Did we detected any modulaiton at all
2097 bool detected_tag_modulation = false;
2099 // Use the current modulation state as starting point
2100 tag_modulation = lf_get_tag_modulation();
2102 // Reset the number of NRZ samples and use edge detection to detect them
2103 nrzs = 0;
2104 while (nrzs < max_nrzs) {
2105 // Get the timing of the next edge in number of wave periods
2106 periods = lf_count_edge_periods(128);
2108 // Are we dealing with the first incoming edge
2109 if (waiting_for_first_edge) {
2110 // Just break out of loop after an initial time-out (tag is probably not available)
2111 if (periods == 0) break;
2112 if (tag_modulation == 0) {
2113 // hitag replies always start with 11111 == 1010101010, if we see 0
2114 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
2115 // so let's add it:
2116 nrz_samples[nrzs++] = tag_modulation ^ 1;
2117 // Register the number of periods that have passed
2118 // we missed the begin of response but we know it happened one period of 16 earlier
2119 response_start += periods - 16;
2120 response_duration = response_start;
2121 } else {
2122 // Register the number of periods that have passed
2123 response_start += periods;
2124 response_duration = response_start;
2126 // Indicate that we have dealt with the first edge
2127 waiting_for_first_edge = false;
2128 // The first edge is always a single NRZ bit, force periods on 16
2129 periods = 16;
2130 // We have received more than 0 periods, so we have detected a tag response
2131 detected_tag_modulation = true;
2132 } else {
2133 // The function lf_count_edge_periods() returns 0 when a time-out occurs
2134 if (periods == 0) {
2135 //Dbprintf("Detected timeout after [%d] nrz samples", nrzs);
2136 break;
2139 // Evaluate the number of periods before the next edge
2140 if (periods > 24 && periods <= 64) {
2141 // Detected two sequential equal bits and a modulation switch
2142 // NRZ modulation: (11 => --|) or (11 __|)
2143 nrz_samples[nrzs++] = tag_modulation;
2144 nrz_samples[nrzs++] = tag_modulation;
2145 response_duration += periods;
2146 // Invert tag modulation state
2147 tag_modulation ^= 1;
2148 } else if (periods > 0 && periods <= 24) {
2149 // Detected one bit and a modulation switch
2150 // NRZ modulation: (1 => -|) or (0 _|)
2151 nrz_samples[nrzs++] = tag_modulation;
2152 response_duration += periods;
2153 tag_modulation ^= 1;
2154 } else {
2155 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
2156 //Dbprintf("Detected unexpected period count: %d", periods);
2157 break;
2161 // Wait some extra time for flash to be programmed
2164 // Store the TX frame, we do this now at this point, to avoid delay in processing
2165 // and to be able to overwrite the first samples with the trace (since they currently
2166 // still use the same memory space)
2167 if (txlen > 0) {
2168 LogTrace(tx, nbytes(txlen), command_start, command_start + command_duration, NULL, true);
2171 // Reset values for receiving frames
2172 memset(rx, 0x00, sizeof(rx));
2173 rxlen = 0;
2175 // If there is no response, just repeat the loop
2176 if (!detected_tag_modulation) continue;
2178 // Make sure we always have an even number of samples. This fixes the problem
2179 // of ending the manchester decoding with a zero. See the example below where
2180 // the '|' character is end of modulation
2181 // One at the end: ..._-|_____...
2182 // Zero at the end: ...-_|_____...
2183 // The last modulation change of a zero is not detected, but we should take
2184 // the half period in account, otherwise the demodulator will fail.
2185 if ((nrzs % 2) != 0) {
2186 nrz_samples[nrzs++] = tag_modulation;
2189 LED_B_ON();
2191 // decode bitstream
2192 manrawdecode((uint8_t *)nrz_samples, &nrzs, true, 0);
2194 // decode frame
2196 // Verify if the header consists of five consecutive ones
2197 if (nrzs < 5) {
2198 break;
2199 } else {
2200 size_t i;
2201 for (i = 0; i < 5; i++) {
2202 if (nrz_samples[i] != 1) {
2203 Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one, abort", i);
2204 break;
2207 if (i < 5) break;
2210 // Pack the response into a byte array
2211 for (size_t i = 5; i < nrzs && rxlen < (sizeof(rx) << 3); i++) {
2212 uint8_t bit = nrz_samples[i];
2213 if (bit > 1) { // When Manchester detects impossible symbol it writes "7"
2214 break;
2216 // >> 3 instead of div by 8
2217 rx[rxlen >> 3] |= bit << (7 - (rxlen % 8));
2218 rxlen++;
2221 if (rxlen % 8 == 1) // skip spurious bit
2222 rxlen--;
2224 // Check if frame was captured and store it
2225 if (rxlen > 0) {
2226 LogTrace(rx, nbytes(rxlen), response_start, response_start + response_duration, NULL, false);
2227 command_start = 0;
2232 out:
2233 lf_finalize();
2235 // release allocated memory from BigBuff.
2236 BigBuf_free();
2238 reply_mix(CMD_ACK, bSuccessful, 0, 0, (uint8_t *)tag.sectors, tag_size);