1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
18 #include "hitag2/hitag2_crypto.h"
20 #include "proxmark3_arm.h"
23 #include "fpgaloader.h"
28 #include "lfsampling.h"
30 #include "commonutil.h"
32 #include "protocols.h"
34 #define test_bit(data, i) (*(data + (i/8)) >> (7-(i % 8))) & 1
35 #define set_bit(data, i) *(data + (i/8)) |= (1 << (7-(i % 8)))
36 #define clear_bit(data, i) *(data + (i/8)) &= ~(1 << (7-(i % 8)))
37 #define flip_bit(data, i) *(data + (i/8)) ^= (1 << (7-(i % 8)))
39 // Successful crypto auth
42 static bool bAuthenticating
;
43 // Successful password auth
44 static bool bSelecting
;
45 static bool bCollision
;
47 static bool bSuccessful
;
50 Password Mode : 0x06 - 0000 0110
51 Crypto Mode : 0x0E - 0000 1110
52 Public Mode A : 0x02 - 0000 0010
53 Public Mode B : 0x00 - 0000 0000
54 Public Mode C : 0x04 - 0000 0100
57 static hitag2_t tag
= {
58 .state
= TAG_STATE_RESET
,
59 .sectors
= { // Password mode: | Crypto mode:
60 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
61 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
62 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
63 [3] = { 0x06, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
64 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
65 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
66 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
67 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
68 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
69 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
70 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
71 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
72 // up to index 15 reserved for HITAG 1/HITAG S public data
77 WRITE_STATE_START
= 0x0,
78 WRITE_STATE_PAGENUM_WRITTEN
,
82 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
83 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
84 #define AUTH_TABLE_LENGTH 2744
85 static uint8_t *auth_table
;
86 static size_t auth_table_pos
= 0;
87 static size_t auth_table_len
= AUTH_TABLE_LENGTH
;
89 static uint8_t password
[4];
90 static uint8_t NrAr
[8];
91 static uint8_t key
[8];
92 static uint8_t writedata
[4];
93 static uint8_t logdata_0
[4], logdata_1
[4];
94 static uint8_t nonce
[4];
95 static uint8_t key_no
;
96 static uint64_t cipher_state
;
98 static int16_t blocknr
;
99 static size_t flipped_bit
= 0;
100 static uint32_t byte_value
= 0;
102 static void hitag2_reset(void) {
103 tag
.state
= TAG_STATE_RESET
;
104 tag
.crypto_active
= 0;
107 static void hitag2_init(void) {
111 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
112 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
113 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
114 // T0 = TIMER_CLOCK1 / 125000 = 192
119 #define HITAG_FRAME_LEN 20
120 #define HITAG_FRAME_BIT_COUNT (8 * HITAG_FRAME_LEN)
121 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
122 #define HITAG_T_LOW 6 /* T_LOW should be 4..10 */
123 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
124 #define HITAG_T_0 20 /* T[0] should be 18..22 */
125 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
126 #define HITAG_T_1 30 /* T[1] should be 26..30 */
127 #define HITAG_T_EOF 80 /* T_EOF should be > 36 and must be larger than HITAG_T_TAG_CAPTURE_FOUR_HALF */
128 #define HITAG_T_WAIT_1_MIN 199 /* T_wresp should be 199..206 */
129 #define HITAG_T_WAIT_2_MIN 90 /* T_wait2 should be at least 90 */
130 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
131 #define HITAG_T_PROG 614
132 #define HITAG_T_WAIT_POWERUP 313 /* transponder internal powerup time is 312.5 */
133 #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 */
135 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
136 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
137 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
138 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
140 #define HITAG_T_TAG_HALF_PERIOD 16
141 #define HITAG_T_TAG_FULL_PERIOD 32
143 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
144 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
145 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
146 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
148 #define HT2_MAX_NRSZ ((8 * HITAG_FRAME_LEN + 5) * 2)
152 static void hitag_send_bit(int bit, bool ledcontrol) {
153 if (ledcontrol) LED_A_ON();
155 // Reset clock for the next bit
156 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
158 // Fixed modulation, earlier proxmark version used inverted signal
159 // check datasheet if reader uses BiPhase?
161 // Manchester: Unloaded, then loaded |__--|
163 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_HALF_PERIOD);
165 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_FULL_PERIOD);
167 // Manchester: Loaded, then unloaded |--__|
169 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_HALF_PERIOD);
171 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_FULL_PERIOD);
173 if (ledcontrol) LED_A_OFF();
177 static void hitag_send_frame(const uint8_t *frame, size_t frame_len) {
178 // SOF - send start of frame
185 // Send the content of the frame
186 for (size_t i = 0; i < frame_len; i++) {
187 hitag_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1);
190 // Drop the modulation
196 static void hitag2_handle_reader_command(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) {
197 uint8_t rx_air
[HITAG_FRAME_LEN
];
199 // Copy the (original) received frame how it is send over the air
200 memcpy(rx_air
, rx
, nbytes(rxlen
));
202 if (tag
.crypto_active
) {
203 ht2_hitag2_cipher_transcrypt(&(tag
.cs
), rx
, rxlen
/ 8, rxlen
% 8);
206 // Reset the transmission frame length
209 // Try to find out which command was send by selecting on length (in bits)
211 // Received 11000 from the reader, request for UID, send UID
213 // Always send over the air in the clear plaintext mode
214 if (rx_air
[0] != HITAG2_START_AUTH
) {
219 memcpy(tx
, tag
.sectors
[0], 4);
220 tag
.crypto_active
= 0;
224 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
226 uint16_t sector
= (~(((rx
[0] << 2) & 0x04) | ((rx
[1] >> 6) & 0x03)) & 0x07);
228 // Verify complement of sector index
229 if (sector
!= ((rx
[0] >> 3) & 0x07)) {
230 DBG
DbpString("Transmission error (read/write)");
234 switch (rx
[0] & 0xC6) {
235 // Read command: 11xx x00y
236 case HITAG2_READ_PAGE
: {
237 memcpy(tx
, tag
.sectors
[sector
], 4);
241 // Inverted Read command: 01xx x10y
242 case HITAG2_READ_PAGE_INVERTED
: {
243 for (size_t i
= 0; i
< 4; i
++) {
244 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
249 // Write command: 10xx x01y
250 case HITAG2_WRITE_PAGE
: {
251 // Prepare write, acknowledge by repeating command
252 memcpy(tx
, rx
, nbytes(rxlen
));
254 tag
.active_sector
= sector
;
255 tag
.state
= TAG_STATE_WRITING
;
260 DBG
Dbprintf("Unknown command: %02x %02x", rx
[0], rx
[1]);
267 // Writing data or Reader password
269 if (tag
.state
== TAG_STATE_WRITING
) {
270 // These are the sector contents to be written. We don't have to do anything else.
271 memcpy(tag
.sectors
[tag
.active_sector
], rx
, nbytes(rxlen
));
272 tag
.state
= TAG_STATE_RESET
;
275 // Received RWD password, respond with configuration and our password
276 if (memcmp(rx
, tag
.sectors
[1], 4) != 0) {
277 DBG
DbpString("Reader password is wrong");
281 memcpy(tx
, tag
.sectors
[3], 4);
286 // Received RWD authentication challenge and response
288 // Store the authentication attempt
289 if (auth_table_len
< (AUTH_TABLE_LENGTH
- 8)) {
290 memcpy(auth_table
+ auth_table_len
, rx
, 8);
294 // Reset the cipher state
295 ht2_hitag2_cipher_reset(&tag
, rx
);
297 // Check if the authentication was correct
298 if (!ht2_hitag2_cipher_authenticate(&(tag
.cs
), rx
+ 4)) {
299 // The reader failed to authenticate, do nothing
300 DBG
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]);
303 // Activate encryption algorithm for all further communication
304 tag
.crypto_active
= 1;
306 // Use the tag password as response
307 memcpy(tx
, tag
.sectors
[3], 4);
313 // LogTraceBits(rx, rxlen, 0, 0, false);
314 // LogTraceBits(tx, txlen, 0, 0, true);
316 if (tag
.crypto_active
) {
317 ht2_hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/ 8, *txlen
% 8);
322 // returns how long it took
323 static uint32_t hitag_reader_send_bit(int bit
) {
324 // Binary pulse length modulation (BPLM) is used to encode the data stream
325 // This means that a transmission of a one takes longer than that of a zero
327 // Enable modulation, which means, drop the field
330 // Wait for 4-10 times the carrier period
331 lf_wait_periods(HITAG_T_LOW
); // wait for 4-10 times the carrier period
332 uint32_t wait
= HITAG_T_LOW
;
334 // Disable modulation, just activates the field again
335 lf_modulation(false);
339 lf_wait_periods(HITAG_T_0
- HITAG_T_LOW
); // wait for 18-22 times the carrier period
340 wait
+= HITAG_T_0
- HITAG_T_LOW
;
343 lf_wait_periods(HITAG_T_1
- HITAG_T_LOW
); // wait for 26-32 times the carrier period
344 wait
+= HITAG_T_1
- HITAG_T_LOW
;
350 // reader / writer commands
351 // frame_len is in number of bits?
352 static uint32_t hitag_reader_send_frame(const uint8_t *frame
, size_t frame_len
) {
356 // Send the content of the frame
357 for (size_t i
= 0; i
< frame_len
; i
++) {
358 wait
+= hitag_reader_send_bit((frame
[i
/ 8] >> (7 - (i
% 8))) & 1);
362 // Enable modulation, which means, drop the field
365 // Wait for 4-10 times the carrier period
366 lf_wait_periods(HITAG_T_LOW
);
369 // Disable modulation, just activates the field again
370 lf_modulation(false);
372 // t_stop, high field for stop condition (> 36)
373 lf_wait_periods(HITAG_T_STOP
);
374 wait
+= HITAG_T_STOP
;
379 // reader / writer commands
380 // frame_len is in number of bits?
381 static uint32_t hitag_reader_send_framebits(const uint8_t *frame
, size_t frame_len
) {
386 // Send the content of the frame
387 for (size_t i
= 0; i
< frame_len
; i
++) {
388 wait
+= hitag_reader_send_bit(frame
[i
]);
392 // Enable modulation, which means, drop the field
393 // set GPIO_SSC_DOUT to HIGH
396 // Wait for 4-10 times the carrier period
397 lf_wait_periods(HITAG_T_LOW
);
400 // Disable modulation, just activates the field again
401 // set GPIO_SSC_DOUT to LOW
402 lf_modulation(false);
404 // t_stop, high field for stop condition (> 36)
405 lf_wait_periods(HITAG_T_STOP
);
406 wait
+= HITAG_T_STOP
;
412 static uint8_t hitag_crc(uint8_t *data
, size_t n
) {
414 for (size_t i
= 0; i
< ((n
+ 7) / 8); i
++) {
416 uint8_t bit
= n
< (8 * (i
+ 1)) ? (n
% 8) : 8;
430 void fix_ac_decoding(uint8_t *input, size_t len) {
431 // Reader routine tries to decode AC data after Manchester decoding
432 // AC has double the bitrate, extract data from bit-pairs
433 uint8_t temp[len / 16];
434 memset(temp, 0, sizeof(temp));
436 for (size_t i = 1; i < len; i += 2) {
437 if (test_bit(input, i) && test_bit(input, (i + 1))) {
438 set_bit(temp, (i / 2));
441 memcpy(input, temp, sizeof(temp));
446 // looks at number of received bits.
448 // 32 = good response
449 static bool hitag1_plain(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
, bool hitag_s
) {
453 // retry waking up card
454 /*tx[0] = 0xb0; // Rev 3.0*/
455 tx
[0] = HITAG1_SET_CC
; // Rev 2.0
457 if (!bCollision
) blocknr
--;
462 if (blocknr
> 1 && blocknr
< 31) {
472 // Select card by serial from response
473 tx
[0] = HITAG1_SELECT
| rx
[0] >> 5;
474 tx
[1] = rx
[0] << 3 | rx
[1] >> 5;
475 tx
[2] = rx
[1] << 3 | rx
[2] >> 5;
476 tx
[3] = rx
[2] << 3 | rx
[3] >> 5;
478 crc
= hitag_crc(tx
, 37);
484 memcpy(tag
.sectors
[blocknr
], rx
, 4);
487 if (blocknr
> 1 && blocknr
< 31) {
492 DbpString("Read successful!");
497 // read next page of card until done
498 Dbprintf("Reading page %02u", blocknr
);
499 tx
[0] = HITAG1_RDPPAGE
| blocknr
>> 4; // RDPPAGE
500 tx
[1] = blocknr
<< 4;
501 crc
= hitag_crc(tx
, 12);
509 Dbprintf("Unknown frame length: %d", rxlen
);
518 static bool hitag1_authenticate(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) {
523 // retry waking up card
524 /*tx[0] = 0xb0; // Rev 3.0*/
525 tx
[0] = HITAG1_SELECT
; // Rev 2.0
527 if (bCrypto
&& byte_value
<= 0xff) {
531 if (!bCollision
) blocknr
--;
536 // will receive 32-bit UID
540 if (bAuthenticating
) {
541 // received Auth init ACK, send nonce
542 // TODO Roel, bit-manipulation goes here
547 nonce
[0] = byte_value
;
549 /*set_bit(nonce,flipped_bit);*/
550 memcpy(tx
, nonce
, 4);
552 // will receive 32 bit encrypted Logdata
553 } else if (bCrypto
) {
554 // authed, start reading
555 tx
[0] = HITAG1_RDCPAGE
| blocknr
>> 4; // RDCPAGE
556 tx
[1] = blocknr
<< 4;
557 crc
= hitag_crc(tx
, 12);
561 // will receive 32-bit encrypted page
567 // Select card by serial from response
568 tx
[0] = HITAG1_SELECT
| rx
[0] >> 5;
569 tx
[1] = rx
[0] << 3 | rx
[1] >> 5;
570 tx
[2] = rx
[1] << 3 | rx
[2] >> 5;
571 tx
[3] = rx
[2] << 3 | rx
[3] >> 5;
573 crc
= hitag_crc(tx
, 37);
579 // will receive 32-bit configuration page
580 } else if (bSelecting
) {
582 tx
[0] = HITAG1_WRCPAGE
| (key_no
); // WRCPAGE
583 tx
[1] = blocknr
<< 4;
584 crc
= hitag_crc(tx
, 12);
589 bAuthenticating
= true;
590 // will receive 2-bit ACK
591 } else if (bAuthenticating
) {
592 // received 32-bit logdata 0
593 // TODO decrypt logdata 0, verify against logdata_0
594 memcpy(tag
.sectors
[0], rx
, 4);
595 memcpy(tag
.sectors
[1], tx
, 4);
596 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]);
597 // TODO replace with secret data stream
598 // TODO encrypt logdata_1
599 memcpy(tx
, logdata_1
, 4);
601 bAuthenticating
= false;
603 // will receive 2-bit ACK
604 } else if (bCrypto
) {
605 // received 32-bit encrypted page
607 memcpy(tag
.sectors
[blocknr
], rx
, 4);
610 DbpString("Read successful!");
616 Dbprintf("Successfully authenticated with logdata:");
617 Dbhexdump(4, logdata_1
, false);
621 // read next page of card until done
622 tx[0] = HITAG1_RDCPAGE | blocknr >> 4; // RDCPAGE
623 tx[1] = blocknr << 4;
624 crc = hitag_crc(tx, 12);
633 Dbprintf("Unknown frame length: %d", rxlen
);
642 //-----------------------------------------------------------------------------
643 // Hitag 2 operations
644 //-----------------------------------------------------------------------------
646 static bool hitag2_write_page(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) {
647 switch (writestate
) {
648 case WRITE_STATE_START
: {
650 tx
[0] = HITAG2_WRITE_PAGE
| (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
651 tx
[1] = ((blocknr
^ 7) << 6);
652 writestate
= WRITE_STATE_PAGENUM_WRITTEN
;
655 case WRITE_STATE_PAGENUM_WRITTEN
: {
656 // Check if page number was received correctly
658 && (rx
[0] == (HITAG2_WRITE_PAGE
| (blocknr
<< 3) | ((blocknr
^ 7) >> 2)))
659 && (rx
[1] == (((blocknr
& 0x3) ^ 0x3) << 6))) {
662 memset(tx
, 0, HITAG_FRAME_LEN
);
663 memcpy(tx
, writedata
, 4);
664 writestate
= WRITE_STATE_PROG
;
666 Dbprintf("hitag2_write_page: Page number was not received correctly: rxlen %d rx %02x%02x%02x%02x"
668 , rx
[0], rx
[1], rx
[2], rx
[3]
675 case WRITE_STATE_PROG
: {
680 Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen
);
685 Dbprintf("hitag2_write_page: Unknown state " _RED_("%d"), writestate
);
693 static bool hitag2_password(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
, bool write
) {
694 // Reset the transmission frame length
697 if (bPwd
&& (bAuthenticating
== false) && write
) {
700 if (hitag2_write_page(rx
, rxlen
, tx
, txlen
) == false) {
705 // Try to find out which command was send by selecting on length (in bits)
707 // No answer, try to resurrect
709 // Stop if there is no answer (after sending password)
711 DBG
DbpString("Password failed!");
715 memcpy(tx
, "\xC0", nbytes(*txlen
));
719 // Received UID, tag password
724 bAuthenticating
= true;
725 memcpy(tx
, password
, 4);
728 // stage 2, got config byte+password TAG, discard as will read later
729 if (bAuthenticating
) {
730 bAuthenticating
= false;
732 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) {
738 // stage 2+, got data block
740 memcpy(tag
.sectors
[blocknr
], rx
, 4);
750 tx
[0] = HITAG2_READ_PAGE
| (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
751 tx
[1] = ((blocknr
^ 7) << 6);
756 // Unexpected response
758 DBG
Dbprintf("Unknown frame length: " _RED_("%d"), rxlen
);
768 static bool hitag2_crypto(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
, bool write
) {
769 // Reset the transmission frame length
773 ht2_hitag2_cipher_transcrypt(&cipher_state
, rx
, rxlen
/ 8, rxlen
% 8);
776 if (bCrypto
&& (bAuthenticating
== false) && write
) {
779 if (hitag2_write_page(rx
, rxlen
, tx
, txlen
) == false) {
785 // Try to find out which command was send by selecting on length (in bits)
787 // No answer, try to resurrect
789 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
791 // Failed during authentication
792 if (bAuthenticating
) {
793 DBG
DbpString("Authentication failed!");
796 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
798 // Write the low part of the key in memory
799 memcpy(tag
.sectors
[1], key
+ 2, 4);
800 } else if (blocknr
== 2) {
801 // Write the high part of the key in memory
802 tag
.sectors
[2][0] = 0x00;
803 tag
.sectors
[2][1] = 0x00;
804 tag
.sectors
[2][2] = key
[0];
805 tag
.sectors
[2][3] = key
[1];
807 // Just put zero's in the memory (of the unreadable block)
808 memset(tag
.sectors
[blocknr
], 0x00, 4);
815 memcpy(tx
, "\xc0", nbytes(*txlen
));
819 // Received UID, crypto tag answer
822 if (bCrypto
== false) {
824 DBG
Dbprintf("hitag2_crypto: key array ");
825 DBG
Dbhexdump(6, key
, false);
827 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;
829 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
830 DBG
Dbprintf("hitag2_crypto: key=0x%x%x uid=0x%x"
831 , (uint32_t)((REV64(ui64key
)) >> 32)
832 , (uint32_t)((REV64(ui64key
)) & 0xffffffff)
836 cipher_state
= ht2_hitag2_init(REV64(ui64key
), REV32(ui32uid
), 0);
840 // Secret data FF FF FF FF
841 memset(tx
+ 4, 0xff, 4);
842 ht2_hitag2_cipher_transcrypt(&cipher_state
, tx
+ 4, 4, 0);
845 bAuthenticating
= true;
848 // stage 2, got config byte+password TAG, discard as will read later
849 if (bAuthenticating
) {
851 bAuthenticating
= false;
854 if (hitag2_write_page(rx
, rxlen
, tx
, txlen
) == false) {
860 } else { // stage 2+, got data block
862 // Store the received block
863 memcpy(tag
.sectors
[blocknr
], rx
, 4);
868 DBG
DbpString("Read successful!");
873 tx
[0] = HITAG2_READ_PAGE
| (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
874 tx
[1] = ((blocknr
^ 7) << 6);
880 DBG
Dbprintf("Unknown frame length: " _RED_("%d"), rxlen
);
886 // try to avoid double encryption calls
887 if (bCrypto
&& bAuthenticating
== false) {
888 ht2_hitag2_cipher_transcrypt(&cipher_state
, tx
, *txlen
/ 8, *txlen
% 8);
894 static bool hitag2_authenticate(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
, bool write
) {
895 // Reset the transmission frame length
898 // Try to find out which command was send by selecting on length (in bits)
901 // No answer, try to resurrect
902 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
904 DBG
DbpString("No answer after sending NrAr!");
908 // Failed during authentication
909 if (bAuthenticating
) {
910 DBG
DbpString("Authentication - failed!");
914 DBG
DbpString("Authenticating - send 0xC0");
916 memcpy(tx
, "\xC0", nbytes(*txlen
));
921 // Received UID or crypto tag answer
922 if (bCrypto
== false) {
924 memcpy(tx
, NrAr
, sizeof(NrAr
));
926 bAuthenticating
= true;
927 DBG
DbpString("Authenticating sending NrAr");
929 DBG
DbpString("Authentication successful!");
931 // stage 2, got config byte+password TAG, discard as will read later
932 if (bAuthenticating
) {
934 bAuthenticating
= false;
937 if (hitag2_write_page(rx
, rxlen
, tx
, txlen
) == false) {
943 } else { // stage 2+, got data block
945 // Store the received block
946 memcpy(tag
.sectors
[blocknr
], rx
, 4);
951 DBG
DbpString("Read successful!");
956 DBG
Dbprintf("Sending read block %u", blocknr
);
959 tx
[0] = HITAG2_READ_PAGE
| (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
960 tx
[1] = ((blocknr
^ 7) << 6);
966 DBG
Dbprintf("Unknown frame length: " _RED_("%d"), rxlen
);
973 static bool hitag2_test_auth_attempts(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) {
975 // Reset the transmission frame length
978 // Try to find out which command was send by selecting on length (in bits)
980 // No answer, try to resurrect
982 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
984 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]);
986 // Removing failed entry from authentications table
987 memcpy(auth_table
+ auth_table_pos
, auth_table
+ auth_table_pos
+ 8, 8);
990 // Return if we reached the end of the authentications table
992 if (auth_table_pos
== auth_table_len
) {
996 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
997 memcpy(NrAr
, auth_table
+ auth_table_pos
, 8);
1000 memcpy(tx
, "\xc0", nbytes(*txlen
));
1004 // Received UID, crypto tag answer, or read block response
1006 if (bCrypto
== false) {
1008 memcpy(tx
, NrAr
, 8);
1011 Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x ( " _GREEN_("ok") " )", NrAr
[0], NrAr
[1], NrAr
[2], NrAr
[3], NrAr
[4], NrAr
[5], NrAr
[6], NrAr
[7]);
1013 if ((auth_table_pos
+ 8) == auth_table_len
) {
1016 auth_table_pos
+= 8;
1017 memcpy(NrAr
, auth_table
+ auth_table_pos
, 8);
1023 Dbprintf("Unknown frame length: " _RED_("%d"), rxlen
);
1033 void hitag_sniff(void) {
1035 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1038 BigBuf_Clear_ext(false);
1042 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
1043 // and analog mux selection.
1044 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
);
1045 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); // 125Khz
1046 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1052 // T0 18-22 fc (total time ZERO)
1053 // T1 26-32 fc (total time ONE)
1054 // Tstop 36 > fc (high field stop limit)
1055 // Tlow 4-10 fc (reader field low time)
1056 void SniffHitag2(bool ledcontrol
) {
1058 if (ledcontrol
) LED_D_ON();
1060 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1063 BigBuf_Clear_ext(false);
1068 lf_init(false, false, ledcontrol);
1070 // no logging of the raw signal
1072 uint32_t total_count = 0;
1074 uint8_t rx[HITAG_FRAME_BIT_COUNT * 2];
1076 while (BUTTON_PRESS() == false) {
1084 memset(rx, 0x00, sizeof(rx));
1086 // Use the current modulation state as starting point
1087 uint8_t mod_state = lf_get_reader_modulation();
1089 while (rxlen < sizeof(rx)) {
1090 periods = lf_count_edge_periods(64);
1091 // Evaluate the number of periods before the next edge
1092 if (periods >= 24 && periods < 64) {
1093 // Detected two sequential equal bits and a modulation switch
1094 // NRZ modulation: (11 => --|) or (11 __|)
1095 rx[rxlen++] = mod_state;
1096 if (rxlen < sizeof(rx)) {
1097 rx[rxlen++] = mod_state;
1099 // toggle tag modulation state
1102 } else if (periods > 0 && periods < 24) {
1103 // Detected one bit and a modulation switch
1104 // NRZ modulation: (1 => -|) or (0 _|)
1105 rx[rxlen++] = mod_state;
1109 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1110 Dbprintf("Detected unexpected period count... " _YELLOW_("%zu"), periods);
1120 // tag sends 11111 + uid,
1121 bool got_tag = (memcmp(rx, "\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00", 10) == 0);
1123 Dbprintf("periods... %zu rxlen... %u", periods, rxlen);
1124 Dbhexdump(rxlen, rx, false);
1128 bool bad_man = false;
1129 uint16_t bitnum = 0;
1130 // mqnchester decode
1131 for (uint16_t i = 0; i < rxlen; i += 2) {
1133 if (rx[i] == 1 && (rx[i + 1] == 0)) {
1135 } else if ((rx[i] == 0) && rx[i + 1] == 1) {
1142 // Dbprintf(_YELLOW_("TAG") " rxlen... %u bitnum... %u", rxlen, bitnum);
1144 Dbprintf("bad manchester ( bitnum %u )", bitnum);
1149 DbpString("too few bits");
1153 // Pack the response into a byte array,
1154 // and skip header 11111 (start at idx 5)
1157 for (uint16_t i = 5; i < bitnum; i++) {
1159 rx[rxlen >> 3] |= b << (7 - (rxlen % 8));
1163 // skip spurious bit
1164 if (rxlen % 8 == 1) {
1170 if (ledcontrol) LED_A_INV();
1174 LogTraceBits(rx, rxlen, 0, periods, false);
1175 total_count += nbytes(rxlen);
1181 if (ledcontrol) LED_A_INV();
1186 for (uint16_t i = 0; i < rxlen; i++) {
1188 rx[n >> 3] |= b << (7 - (n % 8));
1192 // decode reader comms
1193 LogTraceBits(rx, n, 0, periods, true);
1194 total_count += nbytes(n);
1196 if (ledcontrol) LED_A_INV();
1199 lf_finalize(ledcontrol);
1200 Dbprintf("Collected %u bytes", total_count);
1206 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
1207 // and analog mux selection.
1208 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
);
1209 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); // 125Khz
1210 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1213 // Configure output pin that is connected to the FPGA (for modulating)
1214 // AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
1215 // AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
1217 // Disable modulation, we are going to eavesdrop, not modulate ;)
1218 // LOW(GPIO_SSC_DOUT);
1220 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
1221 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1222 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1224 // Disable timer during configuration
1225 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1227 // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1228 // external trigger rising edge, load RA on rising edge of TIOA.
1229 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
1231 // Enable and reset counter
1232 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1234 // Assert a sync signal. This sets all timers to 0 on next active clock edge
1235 AT91C_BASE_TCB
->TCB_BCR
= 1;
1237 int frame_count
= 0, response
= 0, lastbit
= 1, tag_sof
= 4;
1239 bool rising_edge
, reader_frame
= false, bSkip
= true;
1241 // bool exit_due_to_overflow;
1242 // HACK -- add one byte to avoid rewriting manchester decoder for edge case
1243 uint8_t rx
[HITAG_FRAME_LEN
+ 1];
1249 auth_table
= (uint8_t *)BigBuf_calloc(AUTH_TABLE_LENGTH
);
1251 while (BUTTON_PRESS() == false) {
1255 // bool exit_due_to_overflow = false;
1257 // Receive frame, watch for at most T0 * EOF periods
1258 while (AT91C_BASE_TC1
->TC_CV
< (HITAG_T0
* HITAG_T_EOF
)) {
1260 // Check if rising edge in modulation is detected
1261 if (AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1263 // Retrieve the new timing values
1264 int ra
= (AT91C_BASE_TC1
->TC_RA
/ HITAG_T0
) + overflow
;
1267 // Find out if we are dealing with a rising or falling edge
1268 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
1270 // Shorter periods will only happen with reader frames
1271 if (reader_frame
== false && rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
1272 // Switch from tag to reader capture
1273 if (ledcontrol
) LED_C_OFF();
1274 reader_frame
= true;
1278 // Only handle if reader frame and rising edge, or tag frame and falling edge
1279 if (reader_frame
!= rising_edge
) {
1284 // Add the buffered timing values of earlier captured edges which were skipped
1290 if (ledcontrol
) LED_B_ON();
1291 // Capture reader frame
1292 if (ra
>= HITAG_T_STOP
) {
1293 // if (rxlen != 0) {
1294 //DbpString("wierd0?");
1296 // Capture the T0 periods that have passed since last communication or field drop (reset)
1297 response
= (ra
- HITAG_T_LOW
);
1298 if (rxlen
!= 0) { Dbprintf("ra - HITAG_T_LOW... %i", response
); }
1300 } else if (ra
>= HITAG_T_1_MIN
) {
1302 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1305 } else if (ra
>= HITAG_T_0_MIN
) {
1307 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1312 if (ledcontrol
) LED_C_ON();
1313 // Capture tag frame (manchester decoding using only falling edges)
1314 if (ra
>= HITAG_T_EOF
) {
1315 // if (rxlen != 0) {
1316 //DbpString("wierd1?");
1318 // Capture the T0 periods that have passed since last communication or field drop (reset)
1319 // We always receive a 'one' first, which has the falling edge after a half period |-_|
1320 response
= ra
- HITAG_T_TAG_HALF_PERIOD
;
1322 } else if (ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1323 // Manchester coding example |-_|_-|-_| (101)
1324 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1326 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1329 } else if (ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1330 // Manchester coding example |_-|...|_-|-_| (0...01)
1331 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1333 // We have to skip this half period at start and add the 'one' the second time
1334 if (bSkip
== false) {
1335 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1341 } else if (ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1342 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1344 // Ignore bits that are transmitted during SOF
1347 // bit is same as last bit
1348 rx
[rxlen
/ 8] |= lastbit
<< (7 - (rxlen
% 8));
1356 // Check if frame was captured
1360 LogTraceBits(rx
, rxlen
, response
, 0, reader_frame
);
1362 // Check if we recognize a valid authentication attempt
1364 // Store the authentication attempt
1365 if (auth_table_len
< (AUTH_TABLE_LENGTH
- 8)) {
1366 memcpy(auth_table
+ auth_table_len
, rx
, 8);
1367 auth_table_len
+= 8;
1377 reader_frame
= false;
1389 // Save the timer overflow, will be 0 when frame was received
1390 overflow
+= (AT91C_BASE_TC1
->TC_CV
/ HITAG_T0
);
1393 // Reset the frame length
1396 // Reset the timer to restart while-loop that receives frames
1397 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1399 // Assert a sync signal. This sets all timers to 0 on next active clock edge
1400 AT91C_BASE_TCB
->TCB_BCR
= 1;
1403 if (ledcontrol
) LEDsoff();
1405 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1406 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1408 DBG
Dbprintf("frames.......... %d", frame_count
);
1409 Dbprintf("Auth attempts... %d", (auth_table_len
/ 8));
1416 // Hitag 2 simulation
1417 void SimulateHitag2(bool ledcontrol
) {
1420 BigBuf_Clear_ext(false);
1424 // empties bigbuff etc
1425 lf_init(false, true, ledcontrol
);
1428 uint8_t rx
[HITAG_FRAME_LEN
] = {0};
1429 uint8_t tx
[HITAG_FRAME_LEN
] = {0};
1433 // auth_table = BigBuf_calloc(AUTH_TABLE_LENGTH);
1435 DbpString("Starting Hitag 2 simulation");
1437 // hitag2 state machine?
1442 for (size_t i
= 0; i
< 12; i
++) {
1445 for (size_t j
= 0; j
< 4; j
++) {
1447 block
|= tag
.sectors
[i
][j
];
1449 Dbprintf("| %d | %08x |", i
, block
);
1452 size_t max_nrzs
= 8 * HITAG_FRAME_LEN
+ 5;
1453 uint8_t nrz_samples
[max_nrzs
];
1455 // uint32_t command_start = 0, command_duration = 0;
1456 // int16_t checked = 0;
1459 uint32_t signal_size
= 10000;
1460 while (BUTTON_PRESS() == false) {
1463 initSampleBufferEx(&signal_size
, true);
1470 // lf_reset_counter();
1474 // only every 1000th times, in order to save time when collecting samples.
1475 if (checked == 100) {
1476 if (data_available()) {
1485 size_t rxlen
= 0, txlen
= 0;
1487 // Keep administration of the first edge detection
1488 bool waiting_for_first_edge
= true;
1490 // Did we detected any modulaiton at all
1491 bool detected_modulation
= false;
1493 // Use the current modulation state as starting point
1494 uint8_t reader_modulation
= lf_get_reader_modulation();
1496 // Receive frame, watch for at most max_nrzs periods
1497 // Reset the number of NRZ samples and use edge detection to detect them
1499 while (nrzs
< max_nrzs
) {
1500 // Get the timing of the next edge in number of wave periods
1501 size_t periods
= lf_count_edge_periods(128);
1503 // Just break out of loop after an initial time-out (tag is probably not available)
1504 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1509 if (ledcontrol
) LED_A_ON();
1511 // Are we dealing with the first incoming edge
1512 if (waiting_for_first_edge
) {
1514 // Register the number of periods that have passed
1517 // Indicate that we have dealt with the first edge
1518 waiting_for_first_edge
= false;
1520 // The first edge is always a single NRZ bit, force periods on 16
1523 // We have received more than 0 periods, so we have detected a tag response
1524 detected_modulation
= true;
1527 // Evaluate the number of periods before the next edge
1528 if (periods
> 24 && periods
<= 64) {
1529 // Detected two sequential equal bits and a modulation switch
1530 // NRZ modulation: (11 => --|) or (11 __|)
1531 nrz_samples
[nrzs
++] = reader_modulation
;
1532 if (nrzs
< max_nrzs
) {
1533 nrz_samples
[nrzs
++] = reader_modulation
;
1535 // Invert tag modulation state
1536 reader_modulation
^= 1;
1537 } else if (periods
> 0 && periods
<= 24) {
1538 // Detected one bit and a modulation switch
1539 // NRZ modulation: (1 => -|) or (0 _|)
1540 nrz_samples
[nrzs
++] = reader_modulation
;
1541 reader_modulation
^= 1;
1543 reader_modulation
^= 1;
1544 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1545 Dbprintf("Detected unexpected period count: %zu", periods
);
1550 if (ledcontrol
) LED_D_OFF();
1552 // If there is no response, just repeat the loop
1553 if (!detected_modulation
) continue;
1555 if (ledcontrol
) LED_A_OFF();
1557 // Make sure we always have an even number of samples. This fixes the problem
1558 // of ending the manchester decoding with a zero. See the example below where
1559 // the '|' character is end of modulation
1560 // One at the end: ..._-|_____...
1561 // Zero at the end: ...-_|_____...
1562 // The last modulation change of a zero is not detected, but we should take
1563 // the half period in account, otherwise the demodulator will fail.
1564 if ((nrzs
% 2) != 0) {
1565 if (nrzs
>= max_nrzs
) {
1566 Dbprintf("max_nrzs (%d) is odd? Must be even!", max_nrzs
); // should be a static assert above
1569 nrz_samples
[nrzs
++] = reader_modulation
;
1572 if (ledcontrol
) LED_B_ON();
1575 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
1577 // Verify if the header consists of five consecutive ones
1579 Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs
);
1582 for (size_t i
= 0; i
< 5; i
++) {
1583 if (nrz_samples
[i
] != 1) {
1584 Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one", i
);
1589 // Pack the response into a byte array
1590 for (size_t i
= 5; i
< 37; i
++) {
1591 uint8_t bit
= nrz_samples
[i
];
1592 rx
[rxlen
/ 8] |= bit
<< (7 - (rxlen
% 8));
1596 // Check if frame was captured
1599 LogTraceBits(rx
, rxlen
, response
, response
, true);
1601 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1602 hitag2_handle_reader_command(rx
, rxlen
, tx
, &txlen
);
1604 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1605 // not that since the clock counts since the rising edge, but T_Wait1 is
1606 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1607 // periods. The gap time T_Low varies (4..10). All timer values are in
1608 // terms of T0 units (HITAG_T_WAIT_1_MIN - HITAG_T_LOW )
1609 lf_wait_periods(HITAG_T_WAIT_1_MIN
);
1611 // Send and store the tag answer (if there is any)
1613 // Transmit the tag frame
1614 //hitag_send_frame(tx, txlen);
1615 lf_manchester_send_bytes(tx
, txlen
, ledcontrol
);
1617 // Store the frame in the trace
1618 LogTraceBits(tx
, txlen
, 0, 0, false);
1621 // Reset the received frame and response timing info
1622 memset(rx
, 0x00, sizeof(rx
));
1625 if (ledcontrol
) LED_B_OFF();
1629 lf_finalize(ledcontrol
);
1631 // release allocated memory from BigBuff.
1634 DbpString("Sim stopped");
1636 // reply_ng(CMD_LF_HITAG_SIMULATE, (checked == -1) ? PM3_EOPABORTED : PM3_SUCCESS, (uint8_t *)tag.sectors, tag_size);
1639 void ReaderHitag(const lf_hitag_data_t
*payload
, bool ledcontrol
) {
1641 uint32_t command_start
= 0, command_duration
= 0;
1642 uint32_t response_start
= 0, response_duration
= 0;
1644 uint8_t rx
[HITAG_FRAME_LEN
] = {0};
1646 uint8_t txbuf
[HITAG_FRAME_LEN
] = {0};
1647 uint8_t *tx
= txbuf
;
1651 int t_wait_1_guard
= 8;
1653 size_t tag_size
= 48;
1656 // Raw demodulation/decoding by sampling edge periods
1659 // Reset the return status
1660 bSuccessful
= false;
1663 // Clean up trace and prepare it for storing frames
1667 // Check configuration
1668 switch (payload
->cmd
) {
1670 DBG
Dbprintf("Read public blocks in plain mode");
1671 // this part will be unreadable
1672 memset(tag
.sectors
+ 2, 0x0, 30);
1676 case HT1F_AUTHENTICATE
: {
1677 DBG
Dbprintf("Read all blocks in authed mode");
1679 memcpy(nonce
, payload
->nonce
, 4);
1680 memcpy(key
, payload
->key
, 4);
1681 memcpy(logdata_0
, payload
->logdata_0
, 4);
1682 memcpy(logdata_1
, payload
->logdata_1
, 4);
1685 memset(nonce
, 0x0, 4);
1686 memset(logdata_1
, 0x00, 4);
1689 key_no
= payload
->key_no
;
1691 DBG
Dbprintf("Authenticating using key #%u :", key_no
);
1692 DBG
Dbhexdump(4, key
, false);
1693 DBG
DbpString("Nonce:");
1694 DBG
Dbhexdump(4, nonce
, false);
1695 DBG
DbpString("Logdata_0:");
1696 DBG
Dbhexdump(4, logdata_0
, false);
1697 DBG
DbpString("Logdata_1:");
1698 DBG
Dbhexdump(4, logdata_1
, false);
1702 case HT2F_PASSWORD
: {
1703 DBG
Dbprintf("List identifier in password mode");
1704 if (memcmp(payload
->pwd
, "\x00\x00\x00\x00", 4) == 0) {
1705 memcpy(password
, tag
.sectors
[1], sizeof(password
));
1707 memcpy(password
, payload
->pwd
, sizeof(password
));
1711 bAuthenticating
= false;
1714 case HT2F_AUTHENTICATE
: {
1715 DBG
DbpString("Authenticating using NrAr pair:");
1716 memcpy(NrAr
, payload
->NrAr
, 8);
1717 DBG
Dbhexdump(8, NrAr
, false);
1718 // We can't read block 0, 1, 2..
1722 bAuthenticating
= false;
1726 DBG
DbpString("Authenticating using key:");
1727 memcpy(key
, payload
->key
, 6); //HACK; 4 or 6?? I read both in the code.
1728 DBG
Dbhexdump(6, key
, false);
1729 DBG
DbpString("Nonce:");
1730 DBG
Dbhexdump(4, nonce
, false);
1731 memcpy(nonce
, payload
->data
, 4);
1734 bAuthenticating
= false;
1737 case HT2F_TEST_AUTH_ATTEMPTS
: {
1738 DBG
Dbprintf("Testing " _YELLOW_("%d") " authentication attempts", (auth_table_len
/ 8));
1740 memcpy(NrAr
, auth_table
, 8);
1745 DBG
Dbprintf("Error, unknown function: " _RED_("%d"), payload
->cmd
);
1747 reply_ng(CMD_LF_HITAG_READER
, PM3_ESOFT
, NULL
, 0);
1752 if (ledcontrol
) LED_D_ON();
1754 // hitag 2 state machine?
1757 // Tag specific configuration settings (sof, timings, etc.)
1759 /* if (payload->cmd <= HTS_LAST_CMD) {
1765 DBG DbpString("Configured for " _YELLOW_("Hitag S") " reader");
1767 if (payload
->cmd
<= HT1_LAST_CMD
) {
1773 DBG
DbpString("Configured for " _YELLOW_("Hitag 1") " reader");
1774 } else if (payload
->cmd
<= HT2_LAST_CMD
) {
1776 t_wait_1
= HITAG_T_WAIT_1_MIN
;
1777 t_wait_2
= HITAG_T_WAIT_2_MIN
;
1779 DBG
DbpString("Configured for " _YELLOW_("Hitag 2") " reader");
1783 lf_init(true, false, ledcontrol
);
1784 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1786 uint8_t tag_modulation
;
1787 size_t max_nrzs
= (8 * HITAG_FRAME_LEN
+ 5) * 2; // up to 2 nrzs per bit
1788 uint8_t nrz_samples
[max_nrzs
];
1789 bool turn_on
= true;
1791 int16_t checked
= 0;
1792 uint32_t signal_size
= 10000;
1794 while (bStop
== false && BUTTON_PRESS() == false) {
1797 initSampleBufferEx(&signal_size
, true);
1801 // only every 1000th times, in order to save time when collecting samples.
1802 if (checked
== 4000) {
1803 if (data_available()) {
1812 // By default reset the transmission buffer
1814 switch (payload
->cmd
) {
1816 bStop
= !hitag1_plain(rx
, rxlen
, tx
, &txlen
, false);
1819 case HT1F_AUTHENTICATE
: {
1820 bStop
= !hitag1_authenticate(rx
, rxlen
, tx
, &txlen
);
1823 case HT2F_PASSWORD
: {
1824 bStop
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, false);
1827 case HT2F_AUTHENTICATE
: {
1828 bStop
= !hitag2_authenticate(rx
, rxlen
, tx
, &txlen
, false);
1832 bStop
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, false);
1835 case HT2F_TEST_AUTH_ATTEMPTS
: {
1836 bStop
= !hitag2_test_auth_attempts(rx
, rxlen
, tx
, &txlen
);
1840 DBG
Dbprintf("Error, unknown function: " _RED_("%d"), payload
->cmd
);
1850 // Wait 50ms with field off to be sure the transponder gets reset
1852 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
1854 // Wait with field on to be in "Wait for START_AUTH" timeframe
1855 lf_wait_periods(HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4);
1856 command_start
+= HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4;
1858 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
1859 lf_wait_periods(t_wait_2
);
1860 command_start
+= t_wait_2
;
1863 // Transmit the reader frame
1864 command_duration
= hitag_reader_send_frame(tx
, txlen
);
1865 response_start
= command_start
+ command_duration
;
1867 // Let the antenna and ADC values settle
1868 // And find the position where edge sampling should start
1869 lf_wait_periods(t_wait_1
- t_wait_1_guard
);
1871 response_start
+= t_wait_1
- t_wait_1_guard
;
1873 // Keep administration of the first edge detection
1874 bool waiting_for_first_edge
= true;
1876 // Did we detected any modulaiton at all
1877 bool detected_tag_modulation
= false;
1879 // Use the current modulation state as starting point
1880 tag_modulation
= lf_get_tag_modulation();
1882 // Reset the number of NRZ samples and use edge detection to detect them
1885 while (nrzs
< max_nrzs
) {
1886 // Get the timing of the next edge in number of wave periods
1887 periods
= lf_count_edge_periods(128);
1889 // Are we dealing with the first incoming edge
1890 if (waiting_for_first_edge
) {
1891 // Just break out of loop after an initial time-out (tag is probably not available)
1896 if (tag_modulation
== 0) {
1897 // hitag replies always start with 11111 == 1010101010, if we see 0
1898 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
1900 nrz_samples
[nrzs
++] = tag_modulation
^ 1;
1901 // Register the number of periods that have passed
1902 // we missed the begin of response but we know it happened one period of 16 earlier
1903 response_start
+= periods
- 16;
1904 response_duration
= response_start
;
1906 // Register the number of periods that have passed
1907 response_start
+= periods
;
1908 response_duration
= response_start
;
1910 // Indicate that we have dealt with the first edge
1911 waiting_for_first_edge
= false;
1912 // The first edge is always a single NRZ bit, force periods on 16
1914 // We have received more than 0 periods, so we have detected a tag response
1915 detected_tag_modulation
= true;
1917 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1919 DBG
Dbprintf("Detected timeout after [" _YELLOW_("%zu") "] nrz samples", nrzs
);
1923 // Evaluate the number of periods before the next edge
1924 if (periods
> 24 && periods
<= 64) {
1925 // Detected two sequential equal bits and a modulation switch
1926 // NRZ modulation: (11 => --|) or (11 __|)
1927 nrz_samples
[nrzs
++] = tag_modulation
;
1928 if (nrzs
< max_nrzs
) {
1929 nrz_samples
[nrzs
++] = tag_modulation
;
1931 response_duration
+= periods
;
1932 // Invert tag modulation state
1933 tag_modulation
^= 1;
1934 } else if (periods
> 0 && periods
<= 24) {
1935 // Detected one bit and a modulation switch
1936 // NRZ modulation: (1 => -|) or (0 _|)
1937 nrz_samples
[nrzs
++] = tag_modulation
;
1938 response_duration
+= periods
;
1939 tag_modulation
^= 1;
1941 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1942 DBG
Dbprintf("Detected unexpected period count: " _RED_("%zu"), periods
);
1947 // Store the TX frame, we do this now at this point, to avoid delay in processing
1948 // and to be able to overwrite the first samples with the trace (since they currently
1949 // still use the same memory space)
1950 LogTraceBits(tx
, txlen
, command_start
, command_start
+ command_duration
, true);
1952 // Reset values for receiving frames
1953 memset(rx
, 0x00, sizeof(rx
));
1956 // If there is no response
1957 if (detected_tag_modulation
== false) {
1962 // Make sure we always have an even number of samples. This fixes the problem
1963 // of ending the manchester decoding with a zero. See the example below where
1964 // the '|' character is end of modulation
1965 // One at the end: ..._-|_____...
1966 // Zero at the end: ...-_|_____...
1967 // The last modulation change of a zero is not detected, but we should take
1968 // the half period in account, otherwise the demodulator will fail.
1969 if ((nrzs
% 2) != 0) {
1971 if (nrzs
>= max_nrzs
) {
1972 DBG
Dbprintf("max_nrzs ( " _YELLOW_("%zu") " ) is odd? Must be even!", max_nrzs
);
1975 nrz_samples
[nrzs
++] = tag_modulation
;
1978 if (ledcontrol
) LED_B_ON();
1981 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
1985 // Verify if the header consists of five consecutive ones
1987 DBG
Dbprintf("Detected unexpected number of manchester decoded samples [%zu]", nrzs
);
1992 for (i
= 0; i
< 5; i
++) {
1993 if (nrz_samples
[i
] != 1) {
1994 DBG
Dbprintf("Detected incorrect header, the bit [%zu] is zero instead of one, abort", i
);
2003 // Pack the response into a byte array
2004 for (size_t i
= 5; i
< nrzs
&& rxlen
< (sizeof(rx
) << 3); i
++) {
2006 uint8_t bit
= nrz_samples
[i
];
2007 if (bit
> 1) { // When Manchester detects impossible symbol it writes "7"
2008 DBG
Dbprintf("Error in Manchester decoding, abort");
2012 rx
[rxlen
>> 3] |= bit
<< (7 - (rxlen
% 8));
2016 // skip spurious bit
2017 if (rxlen
% 8 == 1) {
2021 // Check if frame was captured and store it
2022 LogTraceBits(rx
, rxlen
, response_start
, response_start
+ response_duration
, false);
2024 // TODO when using cumulative time for command_start, pm3 doesn't reply anymore, e.g. on lf hitag reader --23 -k 4F4E4D494B52
2026 // command_start = response_start + response_duration;
2032 lf_finalize(ledcontrol
);
2034 // release allocated memory from BigBuff.
2037 if (checked
== -1) {
2038 reply_ng(CMD_LF_HITAG_READER
, PM3_ESOFT
, NULL
, 0);
2041 reply_ng(CMD_LF_HITAG_READER
2042 , (bSuccessful
) ? PM3_SUCCESS
: PM3_EFAILED
2043 , (uint8_t *)tag
.sectors
2048 void WriterHitag(const lf_hitag_data_t
*payload
, bool ledcontrol
) {
2050 uint32_t command_start
= 0;
2051 uint32_t command_duration
= 0;
2052 uint32_t response_start
= 0;
2053 uint32_t response_duration
= 0;
2055 uint8_t rx
[HITAG_FRAME_LEN
];
2058 uint8_t txbuf
[HITAG_FRAME_LEN
];
2059 uint8_t *tx
= txbuf
;
2063 int t_wait_1_guard
= 8;
2065 size_t tag_size
= 48;
2069 // Raw demodulation/decoding by sampling edge periods
2072 // iceman: Hitag2 is filled with static global vars.
2073 // these following are globals status indicator :-|
2074 // Reset the return status
2075 bSuccessful
= false;
2077 writestate
= WRITE_STATE_START
;
2080 // Clean up trace and prepare it for storing frames
2084 // Check configuration
2085 switch (payload
->cmd
) {
2087 DBG
DbpString("Authenticating using key:");
2088 memcpy(key
, payload
->key
, 6); //HACK; 4 or 6?? I read both in the code.
2089 memcpy(writedata
, payload
->data
, 4);
2090 Dbhexdump(6, key
, false);
2091 blocknr
= payload
->page
;
2093 bAuthenticating
= false;
2096 case HT2F_PASSWORD
: {
2097 DBG
DbpString("Authenticating using password:");
2098 if (memcmp(payload
->pwd
, "\x00\x00\x00\x00", 4) == 0) {
2099 memcpy(password
, tag
.sectors
[1], sizeof(password
));
2101 memcpy(password
, payload
->pwd
, sizeof(password
));
2103 memcpy(writedata
, payload
->data
, 4);
2104 DBG
Dbhexdump(4, password
, false);
2105 blocknr
= payload
->page
;
2107 bAuthenticating
= false;
2111 DBG
Dbprintf("Error, unknown function: " _RED_("%d"), payload
->cmd
);
2112 reply_ng(CMD_LF_HITAG2_WRITE
, PM3_ESOFT
, NULL
, 0);
2118 if (ledcontrol
) LED_D_ON();
2123 lf_init(true, false, ledcontrol
);
2124 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2126 // Tag specific configuration settings (sof, timings, etc.)
2128 /* if (payload->cmd <= HTS_LAST_CMD) {
2135 DBG DbpString("Configured for " _YELLOW_("Hitag S") " writer");
2138 if (payload
->cmd
<= HT1_LAST_CMD
) {
2144 DBG
DbpString("Configured for " _YELLOW_("Hitag 1") " writer");
2145 } else if (payload
->cmd
<= HT2_LAST_CMD
) {
2147 t_wait_1
= HITAG_T_WAIT_1_MIN
;
2148 t_wait_2
= HITAG_T_WAIT_2_MIN
;
2150 DBG
DbpString("Configured for " _YELLOW_("Hitag 2") " writer");
2153 uint8_t tag_modulation
;
2154 size_t max_nrzs
= (8 * HITAG_FRAME_LEN
+ 5) * 2; // up to 2 nrzs per bit
2155 uint8_t nrz_samples
[max_nrzs
];
2157 int16_t checked
= 0;
2158 uint32_t signal_size
= 10000;
2159 bool turn_on
= true;
2161 while (bStop
== false && BUTTON_PRESS() == false) {
2164 initSampleBufferEx(&signal_size
, true);
2166 // only every 4000th times, in order to save time when collecting samples.
2167 if (checked
== 4000) {
2168 if (data_available()) {
2179 // By default reset the transmission buffer
2182 switch (payload
->cmd
) {
2184 bStop
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, true);
2187 case HT2F_PASSWORD
: {
2188 bStop
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, true);
2201 // Wait 50ms with field off to be sure the transponder gets reset
2203 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
2205 // Wait with field on to be in "Wait for START_AUTH" timeframe
2206 lf_wait_periods(HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4);
2207 command_start
+= HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4;
2209 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
2210 lf_wait_periods(t_wait_2
);
2211 command_start
+= t_wait_2
;
2214 // Transmit the reader frame
2215 command_duration
= hitag_reader_send_frame(tx
, txlen
);
2217 // global write state variable used
2219 if ((writestate
== WRITE_STATE_PROG
) && (tearoff_hook() == PM3_ETEAROFF
)) {
2220 reply_ng(CMD_LF_HITAG2_WRITE
, PM3_ETEAROFF
, NULL
, 0);
2221 lf_finalize(ledcontrol
);
2226 response_start
= command_start
+ command_duration
;
2228 // Let the antenna and ADC values settle
2229 // And find the position where edge sampling should start
2230 lf_wait_periods(t_wait_1
- t_wait_1_guard
);
2232 response_start
+= t_wait_1
- t_wait_1_guard
;
2234 // Keep administration of the first edge detection
2235 bool waiting_for_first_edge
= true;
2237 // Did we detected any modulaiton at all
2238 bool detected_tag_modulation
= false;
2240 // Use the current modulation state as starting point
2241 tag_modulation
= lf_get_tag_modulation();
2243 // Reset the number of NRZ samples and use edge detection to detect them
2245 while (nrzs
< max_nrzs
) {
2246 // Get the timing of the next edge in number of wave periods
2247 periods
= lf_count_edge_periods(128);
2249 // Are we dealing with the first incoming edge
2250 if (waiting_for_first_edge
) {
2251 // Just break out of loop after an initial time-out (tag is probably not available)
2256 if (tag_modulation
== 0) {
2257 // hitag replies always start with 11111 == 1010101010, if we see 0
2258 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
2260 nrz_samples
[nrzs
++] = tag_modulation
^ 1;
2261 // Register the number of periods that have passed
2262 // we missed the begin of response but we know it happened one period of 16 earlier
2263 response_start
+= periods
- 16;
2264 response_duration
= response_start
;
2266 // Register the number of periods that have passed
2267 response_start
+= periods
;
2268 response_duration
= response_start
;
2270 // Indicate that we have dealt with the first edge
2271 waiting_for_first_edge
= false;
2272 // The first edge is always a single NRZ bit, force periods on 16
2274 // We have received more than 0 periods, so we have detected a tag response
2275 detected_tag_modulation
= true;
2277 // The function lf_count_edge_periods() returns 0 when a time-out occurs
2279 DBG
Dbprintf("Detected timeout after [" _YELLOW_("%zu") "] nrz samples", nrzs
);
2283 // Evaluate the number of periods before the next edge
2284 if (periods
> 24 && periods
<= 64) {
2285 // Detected two sequential equal bits and a modulation switch
2286 // NRZ modulation: (11 => --|) or (11 __|)
2287 nrz_samples
[nrzs
++] = tag_modulation
;
2288 if (nrzs
< max_nrzs
) {
2289 nrz_samples
[nrzs
++] = tag_modulation
;
2291 response_duration
+= periods
;
2292 // Invert tag modulation state
2293 tag_modulation
^= 1;
2294 } else if (periods
> 0 && periods
<= 24) {
2295 // Detected one bit and a modulation switch
2296 // NRZ modulation: (1 => -|) or (0 _|)
2297 nrz_samples
[nrzs
++] = tag_modulation
;
2298 response_duration
+= periods
;
2299 tag_modulation
^= 1;
2301 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
2302 DBG
Dbprintf("Detected unexpected period count: " _RED_("%zu"), periods
);
2307 // Wait some extra time for flash to be programmed
2309 // Store the TX frame, we do this now at this point, to avoid delay in processing
2310 // and to be able to overwrite the first samples with the trace (since they currently
2311 // still use the same memory space)
2312 LogTraceBits(tx
, txlen
, command_start
, command_start
+ command_duration
, true);
2314 // Reset values for receiving frames
2315 memset(rx
, 0x00, sizeof(rx
));
2318 // If there is no response, just repeat the loop
2319 if (detected_tag_modulation
== false) {
2323 // Make sure we always have an even number of samples. This fixes the problem
2324 // of ending the manchester decoding with a zero. See the example below where
2325 // the '|' character is end of modulation
2326 // One at the end: ..._-|_____...
2327 // Zero at the end: ...-_|_____...
2328 // The last modulation change of a zero is not detected, but we should take
2329 // the half period in account, otherwise the demodulator will fail.
2330 if ((nrzs
% 2) != 0) {
2332 if (nrzs
>= max_nrzs
) {
2333 Dbprintf("max_nrzs ( " _YELLOW_("%zu") " ) is odd? Must be even!", max_nrzs
);
2336 nrz_samples
[nrzs
++] = tag_modulation
;
2340 if (ledcontrol
) LED_B_ON();
2343 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
2347 // Verify if the header consists of five consecutive ones
2349 DBG
Dbprintf("Detected unexpected number of manchester decoded samples [%zu]", nrzs
);
2354 for (i
= 0; i
< 5; i
++) {
2355 if (nrz_samples
[i
] != 1) {
2356 DBG
Dbprintf("Detected incorrect header, the bit " _YELLOW_("%zu") " is zero instead of one, abort", i
);
2366 // Pack the response into a byte array
2367 for (size_t i
= 5; i
< nrzs
&& rxlen
< (sizeof(rx
) << 3); i
++) {
2369 uint8_t bit
= nrz_samples
[i
];
2371 // When Manchester detects impossible symbol it writes "7"
2373 DBG
Dbprintf("Error in Manchester decoding, abort");
2377 // >> 3 instead of div by 8
2378 rx
[rxlen
>> 3] |= bit
<< (7 - (rxlen
% 8));
2382 // skip spurious bit
2383 if (rxlen
% 8 == 1) {
2387 // Check if frame was captured and store it
2388 LogTraceBits(rx
, rxlen
, response_start
, response_start
+ response_duration
, false);
2394 lf_finalize(ledcontrol
);
2396 // release allocated memory from BigBuff.
2399 if (checked
== -1) {
2400 reply_ng(CMD_LF_HITAG2_WRITE
, PM3_ESOFT
, NULL
, 0);
2403 reply_ng(CMD_LF_HITAG2_WRITE
2404 , (bSuccessful
) ? PM3_SUCCESS
: PM3_EFAILED
2405 , (uint8_t *)tag
.sectors
2411 static void ht2_send(bool turn_on
, uint32_t *cmd_start
2412 , uint32_t *cmd_duration
, uint32_t *resp_start
2413 , uint8_t *tx
, size_t txlen
, bool send_bits
) {
2415 // Tag specific configuration settings (sof, timings, etc.) HITAG2 Settings
2416 #define T_WAIT_1_GUARD 7
2419 // Wait 50ms with field off to be sure the transponder gets reset
2421 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
2423 // Wait with field on to be in "Wait for START_AUTH" timeframe
2424 lf_wait_periods(HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4);
2425 *cmd_start
+= HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4;
2428 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
2429 lf_wait_periods(HITAG_T_WAIT_2_MIN
+ HITAG_T_WAIT_2_MIN
);
2430 *cmd_start
+= (HITAG_T_WAIT_2_MIN
+ HITAG_T_WAIT_2_MIN
);
2433 // Transmit the reader frame
2435 *cmd_duration
= hitag_reader_send_framebits(tx
, txlen
);
2437 *cmd_duration
= hitag_reader_send_frame(tx
, txlen
);
2440 *resp_start
= (*cmd_start
+ *cmd_duration
);
2442 *resp_start
+= (HITAG_T_WAIT_1_MIN
- T_WAIT_1_GUARD
);
2443 // Let the antenna and ADC values settle
2444 // And find the position where edge sampling should start
2445 lf_wait_periods(HITAG_T_WAIT_1_MIN
- T_WAIT_1_GUARD
);
2448 static bool ht2_receive(uint32_t *resp_start
, uint32_t *resp_duration
, uint8_t *nrz_samples
, size_t *samples
) {
2450 // Keep administration of the first edge detection
2451 bool waiting_for_first_edge
= true;
2453 // Did we detected any modulaiton at all
2454 bool detected_tag_modulation
= false;
2456 // Reset the number of NRZ samples and use edge detection to detect them
2459 // Use the current modulation state as starting point
2460 uint8_t tag_modulation
= lf_get_tag_modulation();
2462 // Raw demodulation/decoding by sampling edge periods
2464 while (nrzs
< HT2_MAX_NRSZ
) {
2466 // Get the timing of the next edge in number of wave periods
2467 size_t periods
= lf_count_edge_periods(128);
2469 // Are we dealing with the first incoming edge
2470 if (waiting_for_first_edge
) {
2472 // Just break out of loop after an initial time-out (tag is probably not available)
2477 if (tag_modulation
== 0) {
2478 // hitag replies always start with 11111 == 1010101010, if we see 0
2479 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
2481 nrz_samples
[nrzs
++] = tag_modulation
^ 1;
2482 // Register the number of periods that have passed
2483 // we missed the begin of response but we know it happened one period of 16 earlier
2484 resp_start
+= (periods
- 16);
2485 resp_duration
= resp_start
;
2488 // Register the number of periods that have passed
2489 resp_start
+= periods
;
2490 resp_duration
= resp_start
;
2493 // Indicate that we have dealt with the first edge
2494 waiting_for_first_edge
= false;
2495 // The first edge is always a single NRZ bit, force periods on 16
2497 // We have received more than 0 periods, so we have detected a tag response
2498 detected_tag_modulation
= true;
2501 // The function lf_count_edge_periods() returns 0 when a time-out occurs
2506 // Evaluate the number of periods before the next edge
2507 if (periods
> 24 && periods
<= 64) {
2508 // Detected two sequential equal bits and a modulation switch
2509 // NRZ modulation: (11 => --|) or (11 __|)
2510 nrz_samples
[nrzs
++] = tag_modulation
;
2512 if (nrzs
< HT2_MAX_NRSZ
) {
2513 nrz_samples
[nrzs
++] = tag_modulation
;
2516 resp_duration
+= periods
;
2517 // Invert tag modulation state
2518 tag_modulation
^= 1;
2520 } else if (periods
> 0 && periods
<= 24) {
2521 // Detected one bit and a modulation switch
2522 // NRZ modulation: (1 => -|) or (0 _|)
2523 nrz_samples
[nrzs
++] = tag_modulation
;
2525 resp_duration
+= periods
;
2527 tag_modulation
^= 1;
2530 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
2535 // Make sure we always have an even number of samples. This fixes the problem
2536 // of ending the manchester decoding with a zero. See the example below where
2537 // the '|' character is end of modulation
2538 // One at the end: ..._-|_____...
2539 // Zero at the end: ...-_|_____...
2540 // The last modulation change of a zero is not detected, but we should take
2541 // the half period in account, otherwise the demodulator will fail.
2542 if ((nrzs
% 2) != 0) {
2544 if (nrzs
>= HT2_MAX_NRSZ
) {
2548 nrz_samples
[nrzs
++] = tag_modulation
;
2553 return detected_tag_modulation
;
2556 bool ht2_packbits(uint8_t *nrz_samples
, size_t nrzs
, uint8_t *rx
, size_t *rxlen
) {
2557 // Verify if the header consists of five consecutive ones
2562 // detect hitag 2 header
2563 if (memcmp(nrz_samples
, "\x01\x01\x01\x01\x01", 5)) {
2567 // Pack the response into a byte array
2568 for (size_t i
= 5; i
< nrzs
&& *rxlen
< (HITAG_FRAME_LEN
<< 3); i
++) {
2570 uint8_t bit
= nrz_samples
[i
];
2572 // When Manchester detects impossible symbol it writes "7"
2577 rx
[*rxlen
>> 3] |= bit
<< (7 - (*rxlen
% 8));
2578 *rxlen
= *rxlen
+ 1;
2581 // skip spurious bit
2582 if (*rxlen
% 8 == 1) {
2583 *rxlen
= *rxlen
- 1;
2587 int ht2_read_uid(uint8_t *uid
, bool ledcontrol
, bool send_answer
, bool keep_field_up
) {
2591 // keep field up indicates there are more traffic to be done.
2592 if (keep_field_up
== false) {
2597 // hitag 2 state machine?
2601 lf_init(true, false, true);
2603 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2605 uint8_t rx
[HITAG_FRAME_LEN
] = {0};
2606 size_t rxlen
= 0; // In number of bits
2608 uint8_t nrz_samples
[HT2_MAX_NRSZ
];
2610 uint8_t attempt_count
= 3;
2612 int res
= PM3_EFAILED
;
2613 bool turn_on
= true;
2615 while (attempt_count
&& BUTTON_PRESS() == false) {
2621 uint32_t command_start
= 0, command_duration
= 0;
2622 uint32_t response_start
= 0, response_duration
= 0;
2624 // start AUTH command
2626 uint8_t tx
[] = {HITAG2_START_AUTH
};
2628 // Transmit as reader
2629 ht2_send(turn_on
, &command_start
, &command_duration
, &response_start
, tx
, txlen
, false);
2633 // Reset the number of NRZ samples and use edge detection to detect them
2636 // receive raw samples
2637 if (ht2_receive(&response_start
, &response_duration
, nrz_samples
, &nrzs
) == false) {
2641 // Store the transmit frame ( TX ), we do this now at this point, to avoid delay in processing
2642 // and to be able to overwrite the first samples with the trace (since they currently
2643 // still use the same memory space)
2644 LogTraceBits(tx
, txlen
, command_start
, command_start
+ command_duration
, true);
2646 // decode raw samples from Manchester Encoded to bits
2647 manrawdecode(nrz_samples
, &nrzs
, true, 0);
2649 // pack bits to bytes
2650 if (ht2_packbits(nrz_samples
, nrzs
, rx
, &rxlen
) == false) {
2655 LogTraceBits(rx
, rxlen
, response_start
, response_start
+ response_duration
, false);
2661 // Store received UID
2662 memcpy(tag
.sectors
[0], rx
, 4);
2670 if (keep_field_up
== false) {
2672 BigBuf_free_keep_EM();
2676 reply_ng(CMD_LF_HITAG_READER
, res
, (uint8_t *)tag
.sectors
, 4);
2682 // This function assumes you have called hitag2_read_uid before to turn on the field :)
2683 // tx = expects bin arrays 0,1 i
2684 // txlen = number of bits to send
2685 // rx = return bin arrys
2686 // rxlen = number of bits returned
2687 int ht2_tx_rx(uint8_t *tx
, size_t txlen
, uint8_t *rx
, size_t *rxlen
, bool ledcontrol
, bool keep_field_up
) {
2689 int res
= PM3_EFAILED
;
2691 uint8_t samples
[HT2_MAX_NRSZ
] = {0};
2693 uint32_t command_start
= 0, command_duration
= 0;
2694 uint32_t response_start
= 0, response_duration
= 0;
2696 // Transmit as reader
2697 ht2_send(false, &command_start
, &command_duration
, &response_start
, tx
, txlen
, true);
2699 // receive raw samples
2700 if (ht2_receive(&response_start
, &response_duration
, samples
, &nrzs
) == false) {
2704 // decode raw samples from Manchester Encoded to bits
2705 if (manrawdecode(samples
, &nrzs
, true, 0)) {
2709 // pack bits to bytes
2710 if (rx
&& (ht2_packbits(samples
, nrzs
, rx
, rxlen
) == false)) {
2717 if (keep_field_up
== false) {