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
5 //-----------------------------------------------------------------------------
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 //-----------------------------------------------------------------------------
23 #define DBG if (DBGLEVEL >= DBG_EXTENDED)
26 #include "hitag2_crypto.h"
28 #include "proxmark3_arm.h"
31 #include "fpgaloader.h"
36 #include "lfsampling.h"
38 #include "commonutil.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
49 static bool bAuthenticating
;
50 // Successful password auth
51 static bool bSelecting
;
52 static bool bCollision
;
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
84 WRITE_STATE_START
= 0x0,
85 WRITE_STATE_PAGENUM_WRITTEN
,
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) {
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
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
156 static void hitag_send_bit(int bit) {
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?
165 // Manchester: Unloaded, then loaded |__--|
167 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_HALF_PERIOD);
169 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_FULL_PERIOD);
171 // Manchester: Loaded, then unloaded |--__|
173 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_HALF_PERIOD);
175 while (AT91C_BASE_TC0->TC_CV < HITAG_T0 * HITAG_T_TAG_FULL_PERIOD);
181 static void hitag_send_frame(const uint8_t *frame, size_t frame_len) {
182 // SOF - send start of frame
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
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
213 // Try to find out which command was send by selecting on length (in bits)
215 // Received 11000 from the reader, request for UID, send UID
217 // Always send over the air in the clear plaintext mode
218 if (rx_air
[0] != 0xC0) {
223 memcpy(tx
, tag
.sectors
[0], 4);
224 tag
.crypto_active
= 0;
228 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
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)");
238 switch (rx
[0] & 0xC6) {
239 // Read command: 11xx x00y
241 memcpy(tx
, tag
.sectors
[sector
], 4);
245 // Inverted Read command: 01xx x10y
247 for (size_t i
= 0; i
< 4; i
++) {
248 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
253 // Write command: 10xx x01y
255 // Prepare write, acknowledge by repeating command
256 memcpy(tx
, rx
, nbytes(rxlen
));
258 tag
.active_sector
= sector
;
259 tag
.state
= TAG_STATE_WRITING
;
264 Dbprintf("Unknown command: %02x %02x", rx
[0], rx
[1]);
271 // Writing data or Reader password
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
;
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");
285 memcpy(tx
, tag
.sectors
[3], 4);
290 // Received RWD authentication challenge and respnse
292 // Store the authentication attempt
293 if (auth_table_len
< (AUTH_TABLE_LENGTH
- 8)) {
294 memcpy(auth_table
+ auth_table_len
, rx
, 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]);
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);
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);
326 // returns how long it took
327 static uint32_t hitag_reader_send_bit(int bit
) {
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
336 // Wait for 4-10 times the carrier period
337 lf_wait_periods(8); // wait for 4-10 times the carrier period
340 // Disable modulation, just activates the field again
341 lf_modulation(false);
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
;
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
;
357 // reader / writer commands
358 static uint32_t hitag_reader_send_frame(const uint8_t *frame
, size_t frame_len
) {
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
369 // Wait for 4-10 times the carrier period
370 lf_wait_periods(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
;
383 static uint8_t hitag_crc(uint8_t *data
, size_t n
) {
385 for (size_t i
= 0; i
< ((n
+ 7) / 8); i
++) {
387 uint8_t bit
= n
< (8 * (i
+ 1)) ? (n
% 8) : 8;
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.
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
) {
424 // retry waking up card
425 /*tx[0] = 0xb0; // Rev 3.0*/
426 tx
[0] = 0x30; // Rev 2.0
428 if (!bCollision
) blocknr
--;
433 if (blocknr
> 1 && blocknr
< 31) {
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;
449 crc
= hitag_crc(tx
, 37);
455 memcpy(tag
.sectors
[blocknr
], rx
, 4);
458 if (blocknr
> 1 && blocknr
< 31) {
463 DbpString("Read succesful!");
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);
480 Dbprintf("Uknown frame length: %d", rxlen
);
489 static bool hitag1_authenticate(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) {
494 // retry waking up card
495 /*tx[0] = 0xb0; // Rev 3.0*/
496 tx
[0] = 0x30; // Rev 2.0
498 if (bCrypto
&& byte_value
<= 0xff) {
502 if (!bCollision
) blocknr
--;
507 // will receive 32-bit UID
511 if (bAuthenticating
) {
512 // received Auth init ACK, send nonce
513 // TODO Roel, bit-manipulation goes here
518 nonce
[0] = byte_value
;
520 /*set_bit(nonce,flipped_bit);*/
521 memcpy(tx
, nonce
, 4);
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);
532 // will receive 32-bit encrypted page
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;
544 crc
= hitag_crc(tx
, 37);
550 // will receive 32-bit configuration page
551 } else if (bSelecting
) {
553 tx
[0] = 0xa0 | (key_no
); // WRCPAGE
554 tx
[1] = blocknr
<< 4;
555 crc
= hitag_crc(tx
, 12);
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);
572 bAuthenticating
= false;
574 // will receive 2-bit ACK
575 } else if (bCrypto
) {
576 // received 32-bit encrypted page
578 memcpy(tag
.sectors
[blocknr
], rx
, 4);
581 DbpString("Read succesful!");
587 Dbprintf("Succesfully authenticated with logdata:");
588 Dbhexdump(4, logdata_1
, 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);
604 Dbprintf("Uknown frame length: %d", rxlen
);
613 //-----------------------------------------------------------------------------
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
:
621 tx
[0] = 0x82 | (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
622 tx
[1] = ((blocknr
^ 7) << 6);
623 writestate
= WRITE_STATE_PAGENUM_WRITTEN
;
625 case WRITE_STATE_PAGENUM_WRITTEN
:
626 // Check if page number was received correctly
628 && (rx
[0] == (0x82 | (blocknr
<< 3) | ((blocknr
^ 7) >> 2)))
629 && (rx
[1] == (((blocknr
& 0x3) ^ 0x3) << 6))) {
632 memset(tx
, 0, HITAG_FRAME_LEN
);
633 memcpy(tx
, writedata
, 4);
634 writestate
= WRITE_STATE_PROG
;
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]);
642 case WRITE_STATE_PROG
:
647 Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen
);
651 DbpString("hitag2_write_page: Unknown state %d");
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
663 if (bPwd
&& !bAuthenticating
&& write
) {
664 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) {
668 // Try to find out which command was send by selecting on length (in bits)
670 // No answer, try to resurrect
672 // Stop if there is no answer (after sending password)
674 DbpString("Password failed!");
678 memcpy(tx
, "\xC0", nbytes(*txlen
));
682 // Received UID, tag password
687 bAuthenticating
= true;
688 memcpy(tx
, password
, 4);
691 // stage 2, got config byte+password TAG, discard as will read later
692 if (bAuthenticating
) {
693 bAuthenticating
= false;
695 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) {
701 // stage 2+, got data block
703 memcpy(tag
.sectors
[blocknr
], rx
, 4);
713 tx
[0] = 0xC0 | (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
714 tx
[1] = ((blocknr
^ 7) << 6);
719 // Unexpected response
721 Dbprintf("Unknown frame length: %d", rxlen
);
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
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
)) {
745 // Try to find out which command was send by selecting on length (in bits)
747 // No answer, try to resurrect
749 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
751 // Failed during authentication
752 if (bAuthenticating
) {
753 DbpString("Authentication failed!");
756 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
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];
767 // Just put zero's in the memory (of the unreadable block)
768 memset(tag
.sectors
[blocknr
], 0x00, 4);
775 memcpy(tx
, "\xc0", nbytes(*txlen
));
779 // Received UID, crypto tag answer
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);
790 memset(tx
+ 4, 0xff, 4);
791 hitag2_cipher_transcrypt(&cipher_state
, tx
+ 4, 4, 0);
794 bAuthenticating
= true;
796 // stage 2, got config byte+password TAG, discard as will read later
797 if (bAuthenticating
) {
798 bAuthenticating
= false;
800 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) {
806 // stage 2+, got data block
808 // Store the received block
809 memcpy(tag
.sectors
[blocknr
], rx
, 4);
813 DbpString("Read successful!");
818 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^ 7) >> 2);
819 tx
[1] = ((blocknr
^ 7) << 6);
825 // Unexpected response
827 Dbprintf("Unknown frame length: %d", rxlen
);
835 // We have to return now to avoid double encryption
836 if (!bAuthenticating
) {
837 hitag2_cipher_transcrypt(&cipher_state
, tx
, *txlen
/ 8, *txlen
% 8);
844 static bool hitag2_authenticate(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) {
845 // Reset the transmission frame length
848 // Try to find out which command was send by selecting on length (in bits)
850 // No answer, try to resurrect
852 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
854 DbpString("Authentication failed!");
858 memcpy(tx
, "\xC0", nbytes(*txlen
));
862 // Received UID, crypto tag answer
869 DbpString("Authentication successful!");
875 // Unexpected response
877 Dbprintf("Unknown frame length: %d", rxlen
);
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
891 // Try to find out which command was send by selecting on length (in bits)
893 // No answer, try to resurrect
895 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
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);
903 // Return if we reached the end of the authentications table
905 if (auth_table_pos
== auth_table_len
) {
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);
913 memcpy(tx
, "\xc0", nbytes(*txlen
));
917 // Received UID, crypto tag answer, or read block response
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]);
926 if ((auth_table_pos
+ 8) == auth_table_len
) {
930 memcpy(NrAr
, auth_table
+ auth_table_pos
, 8);
936 Dbprintf("Unknown frame length: %d", rxlen
);
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
949 // Try to find out which command was send by selecting on length (in bits)
951 // No answer, try to resurrect
953 // Just starting or if there is no answer
955 memcpy(tx
, "\xC0", nbytes(*txlen
));
960 // Check if we received answer tag (at)
961 if (bAuthenticating
) {
962 bAuthenticating
= false;
964 // Store the received block
965 memcpy(tag
.sectors
[blocknr
], rx
, 4);
968 DBG
Dbhexdump(4, rx
, false);
971 DBG
DbpString("Read successful!");
977 // Unexpected response
979 DBG
Dbprintf("Unknown frame length: %d", rxlen
);
987 void EloadHitag(uint8_t *data
, uint16_t len
) {
988 memcpy(tag
.sectors
, data
, sizeof(tag
.sectors
));
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");
1001 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1004 BigBuf_Clear_ext(false);
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) {
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
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;
1053 // tag sends 11111 + uid,
1054 bool got_tag = ((memcmp(rx, "\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00", 10) == 0));
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)) {
1063 } else if ((rx[i] == 0) && rx[i + 1] == 1) {
1071 DBG DbpString("bad manchester");
1076 DBG DbpString("too few bits");
1080 // skip header 11111
1086 // Pack the response into a byte array
1088 for (; i < bitnum; i++) {
1090 rx[rxlen >> 3] |= b << (7 - (rxlen % 8));
1094 // skip spurious bit
1095 if (rxlen % 8 == 1) {
1103 LogTrace(rx, nbytes(rxlen), 0, 0, NULL, false);
1104 total_count += nbytes(rxlen);
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);
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
);
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 ;)
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
];
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) {
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
1187 reader_frame
= true;
1191 // Only handle if reader frame and rising edge, or tag frame and falling edge
1192 if (reader_frame
== rising_edge
) {
1197 // Add the buffered timing values of earlier captured edges which were skipped
1203 // Capture reader frame
1204 if (ra
>= HITAG_T_STOP
) {
1205 // if (rxlen != 0) {
1206 //DbpString("wierd0?");
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
) {
1212 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1214 } else if (ra
>= HITAG_T_0_MIN
) {
1216 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1222 // Capture tag frame (manchester decoding using only falling edges)
1223 if (ra
>= HITAG_T_EOF
) {
1224 // if (rxlen != 0) {
1225 //DbpString("wierd1?");
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));
1235 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1238 } else if (ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1239 // Manchester coding example |_-|...|_-|-_| (0...01)
1240 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
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));
1250 } else if (ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1251 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1253 // Ignore bits that are transmitted during SOF
1256 // bit is same as last bit
1257 rx
[rxlen
/ 8] |= lastbit
<< (7 - (rxlen
% 8));
1265 // Check if frame was captured
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
));
1282 reader_frame
= false;
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
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;
1305 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1306 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1308 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1311 Dbprintf("frame received: %d", frame_count
);
1312 Dbprintf("Authentication Attempts: %d", (auth_table_len
/ 8));
1316 // Hitag2 simulation
1317 void SimulateHitag2(void) {
1320 BigBuf_Clear_ext(false);
1324 // empties bigbuff etc
1325 lf_init(false, true);
1328 uint8_t rx
[HITAG_FRAME_LEN
] = {0};
1329 uint8_t tx
[HITAG_FRAME_LEN
] = {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?
1347 for (size_t i
= 0; i
< 12; i
++) {
1350 for (size_t j
= 0; j
< 4; j
++) {
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;
1364 uint32_t signal_size
= 10000;
1365 while (BUTTON_PRESS() == false) {
1368 initSampleBufferEx(&signal_size
, true);
1372 // lf_reset_counter();
1377 // only every 1000th times, in order to save time when collecting samples.
1378 if (checked == 100) {
1379 if (data_available()) {
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
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
1414 // Are we dealing with the first incoming edge
1415 if (waiting_for_first_edge
) {
1417 // Register the number of periods that have passed
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
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;
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
);
1453 // If there is no response, just repeat the loop
1454 if (!detected_modulation
) continue;
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
;
1472 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
1474 // Verify if the header consists of five consecutive ones
1476 Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs
);
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));
1493 // Check if frame was captured
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)
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
));
1528 // release allocated memory from BigBuff.
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};
1543 uint8_t txbuf
[HITAG_FRAME_LEN
] = {0};
1544 uint8_t *tx
= txbuf
;
1548 int t_wait_1_guard
= 8;
1550 size_t tag_size
= 48;
1553 // Raw demodulation/decoding by sampling edge periods
1556 // Reset the return status
1557 bSuccessful
= false;
1560 // Clean up trace and prepare it for storing frames
1564 // Check configuration
1567 DBG
Dbprintf("Read public blocks in plain mode");
1568 // this part will be unreadable
1569 memset(tag
.sectors
+ 2, 0x0, 30);
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);
1580 memset(nonce
, 0x0, 4);
1581 memset(logdata_1
, 0x00, 4);
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);
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
));
1600 memcpy(password
, htd
->pwd
.password
, sizeof(password
));
1604 bAuthenticating
= false;
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);
1612 bAuthenticating
= false;
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);
1624 bAuthenticating
= false;
1627 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1628 DBG
Dbprintf("Testing %d authentication attempts", (auth_table_len
/ 8));
1630 memcpy(NrAr
, auth_table
, 8);
1634 case RHT2F_UID_ONLY
: {
1637 bAuthenticating
= false;
1641 DBG
Dbprintf("Error, unknown function: %d", htf
);
1649 // hitag2 state machine?
1652 uint8_t attempt_count
= 0;
1654 // Tag specific configuration settings (sof, timings, etc.)
1656 /* if (htf <= HTS_LAST_CMD) {
1662 DBG DbpString("Configured for hitagS reader");
1664 if (htf
<= HT1_LAST_CMD
) {
1670 DBG
DbpString("Configured for hitag1 reader");
1671 } else if (htf
<= HT2_LAST_CMD
) {
1673 t_wait_1
= HITAG_T_WAIT_1_MIN
;
1674 t_wait_2
= HITAG_T_WAIT_2_MIN
;
1676 DBG
DbpString("Configured for hitag2 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;
1688 int16_t checked
= 0;
1689 uint32_t signal_size
= 10000;
1691 while (bStop
== false && BUTTON_PRESS() == false) {
1694 initSampleBufferEx(&signal_size
, true);
1698 // only every 1000th times, in order to save time when collecting samples.
1699 if (checked
== 4000) {
1700 if (data_available()) {
1709 // By default reset the transmission buffer
1713 bStop
= !hitag_plain(rx
, rxlen
, tx
, &txlen
, false);
1716 case RHT1F_AUTHENTICATE
: {
1717 bStop
= !hitag1_authenticate(rx
, rxlen
, tx
, &txlen
);
1720 case RHT2F_PASSWORD
: {
1721 bStop
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, false);
1724 case RHT2F_AUTHENTICATE
: {
1725 bStop
= !hitag2_authenticate(rx
, rxlen
, tx
, &txlen
);
1728 case RHT2F_CRYPTO
: {
1729 bStop
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, false);
1732 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1733 bStop
= !hitag2_test_auth_attempts(rx
, rxlen
, tx
, &txlen
);
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)
1746 DBG
Dbprintf("Error, unknown function: %d", htf
);
1752 // Wait 50ms with field off to be sure the transponder gets reset
1754 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
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;
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
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
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
;
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
1810 // We have received more than 0 periods, so we have detected a tag response
1811 detected_tag_modulation
= true;
1813 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1815 DBG
Dbprintf("Detected timeout after [%d] nrz samples", nrzs
);
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;
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
);
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)
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
));
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
;
1869 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
1873 // Verify if the header consists of five consecutive ones
1875 DBG
Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs
);
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
);
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");
1895 rx
[rxlen
>> 3] |= bit
<< (7 - (rxlen
% 8));
1899 if (rxlen
% 8 == 1) // skip spurious bit
1902 // Check if frame was captured and store it
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
1909 // command_start = response_start + response_duration;
1918 // release allocated memory from BigBuff.
1922 reply_mix(CMD_ACK
, bSuccessful
, 0, 0, (uint8_t *)tag
.sectors
, tag_size
);
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
];
1935 uint8_t txbuf
[HITAG_FRAME_LEN
];
1936 uint8_t *tx
= txbuf
;
1940 int t_wait_1_guard
= 8;
1942 size_t tag_size
= 48;
1946 // Raw demodulation/decoding by sampling edge periods
1949 // Reset the return status
1950 bSuccessful
= false;
1953 // Clean up trace and prepare it for storing frames
1958 // Check configuration
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);
1967 bAuthenticating
= false;
1968 writestate
= WRITE_STATE_START
;
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);
1978 bAuthenticating
= false;
1979 writestate
= WRITE_STATE_START
;
1983 Dbprintf("Error, unknown function: %d", htf
);
1994 lf_init(true, false);
1995 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1997 // Tag specific configuration settings (sof, timings, etc.)
1999 /* if (htf <= HTS_LAST_CMD) {
2006 DbpString("Configured for hitagS writer");
2009 /* if (htf <= HT1_LAST_CMD) {
2015 DbpString("Configured for hitag1 writer");
2017 // if (htf <= HT2_LAST_CMD) {
2019 t_wait_1
= HITAG_T_WAIT_1_MIN
;
2020 t_wait_2
= HITAG_T_WAIT_2_MIN
;
2022 DbpString("Configured for hitag2 writer");
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
];
2029 int16_t checked
= 0;
2030 uint32_t signal_size
= 10000;
2031 bool turn_on
= true;
2033 while (bStop
== false && BUTTON_PRESS() == false) {
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()) {
2051 // By default reset the transmission buffer
2054 case WHT2F_CRYPTO
: {
2055 bStop
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, true);
2058 case WHT2F_PASSWORD
: {
2059 bStop
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, true);
2063 Dbprintf("Error, unknown function: %d", htf
);
2070 // Wait 50ms with field off to be sure the transponder gets reset
2072 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
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;
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
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
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
;
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
2130 // We have received more than 0 periods, so we have detected a tag response
2131 detected_tag_modulation
= true;
2133 // The function lf_count_edge_periods() returns 0 when a time-out occurs
2135 //Dbprintf("Detected timeout after [%d] nrz samples", nrzs);
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;
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);
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)
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
));
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
;
2192 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
2196 // Verify if the header consists of five consecutive ones
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
);
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"
2216 // >> 3 instead of div by 8
2217 rx
[rxlen
>> 3] |= bit
<< (7 - (rxlen
% 8));
2221 if (rxlen
% 8 == 1) // skip spurious bit
2224 // Check if frame was captured and store it
2226 LogTrace(rx
, nbytes(rxlen
), response_start
, response_start
+ response_duration
, NULL
, false);
2235 // release allocated memory from BigBuff.
2238 reply_mix(CMD_ACK
, bSuccessful
, 0, 0, (uint8_t *)tag
.sectors
, tag_size
);