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 int frame_count
= 0, response
= 0, overflow
= 0, lastbit
= 1, tag_sof
= 4;
1152 bool rising_edge
= false, reader_frame
= false, bSkip
= true;
1153 uint8_t rx
[HITAG_FRAME_LEN
];
1159 // Reset the received frame, frame count and timing info
1160 memset(rx
, 0x00, sizeof(rx
));
1162 auth_table
= (uint8_t *)BigBuf_malloc(AUTH_TABLE_LENGTH
);
1163 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
1165 while (BUTTON_PRESS() == false) {
1168 memset(rx
, 0x00, sizeof(rx
));
1170 // Receive frame, watch for at most T0 * EOF periods
1171 while (AT91C_BASE_TC1
->TC_CV
< (HITAG_T0
* HITAG_T_EOF
)) {
1172 // Check if rising edge in modulation is detected
1173 if (AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1174 // Retrieve the new timing values
1175 int ra
= (AT91C_BASE_TC1
->TC_RA
/ HITAG_T0
);
1177 // Find out if we are dealing with a rising or falling edge
1178 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
1180 // Shorter periods will only happen with reader frames
1181 if (reader_frame
== false && rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
1182 // Switch from tag to reader capture
1184 reader_frame
= true;
1188 // Only handle if reader frame and rising edge, or tag frame and falling edge
1189 if (reader_frame
== rising_edge
) {
1194 // Add the buffered timing values of earlier captured edges which were skipped
1200 // Capture reader frame
1201 if (ra
>= HITAG_T_STOP
) {
1202 // if (rxlen != 0) {
1203 //DbpString("wierd0?");
1205 // Capture the T0 periods that have passed since last communication or field drop (reset)
1206 response
= (ra
- HITAG_T_LOW
);
1207 } else if (ra
>= HITAG_T_1_MIN
) {
1209 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1211 } else if (ra
>= HITAG_T_0_MIN
) {
1213 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1219 // Capture tag frame (manchester decoding using only falling edges)
1220 if (ra
>= HITAG_T_EOF
) {
1221 // if (rxlen != 0) {
1222 //DbpString("wierd1?");
1224 // Capture the T0 periods that have passed since last communication or field drop (reset)
1225 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1226 response
= ra
- HITAG_T_TAG_HALF_PERIOD
;
1228 } else if (ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1229 // Manchester coding example |-_|_-|-_| (101)
1230 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1232 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1235 } else if (ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1236 // Manchester coding example |_-|...|_-|-_| (0...01)
1237 rx
[rxlen
/ 8] |= 0 << (7 - (rxlen
% 8));
1239 // We have to skip this half period at start and add the 'one' the second time
1240 if (bSkip
== false) {
1241 rx
[rxlen
/ 8] |= 1 << (7 - (rxlen
% 8));
1247 } else if (ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1248 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1250 // Ignore bits that are transmitted during SOF
1253 // bit is same as last bit
1254 rx
[rxlen
/ 8] |= lastbit
<< (7 - (rxlen
% 8));
1262 // Check if frame was captured
1265 LogTrace(rx
, nbytes(rxlen
), response
, 0, NULL
, reader_frame
);
1267 // Check if we recognize a valid authentication attempt
1268 if (nbytes(rxlen
) == 8) {
1269 // Store the authentication attempt
1270 if (auth_table_len
< (AUTH_TABLE_LENGTH
- 8)) {
1271 memcpy(auth_table
+ auth_table_len
, rx
, 8);
1272 auth_table_len
+= 8;
1276 // Reset the received frame and response timing info
1277 memset(rx
, 0x00, sizeof(rx
));
1279 reader_frame
= false;
1288 // Save the timer overflow, will be 0 when frame was received
1289 overflow
+= (AT91C_BASE_TC1
->TC_CV
/ HITAG_T0
);
1291 // Reset the frame length
1293 // Reset the timer to restart while-loop that receives frames
1294 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1295 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1299 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1300 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1301 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1304 Dbprintf("frame received: %d", frame_count
);
1305 Dbprintf("Authentication Attempts: %d", (auth_table_len
/ 8));
1309 // Hitag2 simulation
1310 void SimulateHitag2(void) {
1313 BigBuf_Clear_ext(false);
1317 // empties bigbuff etc
1318 lf_init(false, true);
1321 uint8_t rx
[HITAG_FRAME_LEN
] = {0};
1322 uint8_t tx
[HITAG_FRAME_LEN
] = {0};
1326 // auth_table = BigBuf_malloc(AUTH_TABLE_LENGTH);
1327 // memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
1329 // Reset the received frame, frame count and timing info
1330 // memset(rx, 0x00, sizeof(rx));
1331 // memset(tx, 0x00, sizeof(tx));
1333 DbpString("Starting Hitag2 simulation");
1335 // hitag2 state machine?
1340 for (size_t i
= 0; i
< 12; i
++) {
1343 for (size_t j
= 0; j
< 4; j
++) {
1345 block
|= tag
.sectors
[i
][j
];
1347 Dbprintf("| %d | %08x |", i
, block
);
1350 size_t max_nrzs
= 8 * HITAG_FRAME_LEN
+ 5;
1351 uint8_t nrz_samples
[max_nrzs
];
1353 // uint32_t command_start = 0, command_duration = 0;
1354 // int16_t checked = 0;
1357 uint32_t signal_size
= 10000;
1358 while (BUTTON_PRESS() == false) {
1361 initSampleBufferEx(&signal_size
, true);
1365 // lf_reset_counter();
1370 // only every 1000th times, in order to save time when collecting samples.
1371 if (checked == 100) {
1372 if (data_available()) {
1381 size_t rxlen
= 0, txlen
= 0;
1383 // Keep administration of the first edge detection
1384 bool waiting_for_first_edge
= true;
1386 // Did we detected any modulaiton at all
1387 bool detected_modulation
= false;
1389 // Use the current modulation state as starting point
1390 uint8_t reader_modulation
= lf_get_reader_modulation();
1392 // Receive frame, watch for at most max_nrzs periods
1393 // Reset the number of NRZ samples and use edge detection to detect them
1395 while (nrzs
< max_nrzs
) {
1396 // Get the timing of the next edge in number of wave periods
1397 size_t periods
= lf_count_edge_periods(128);
1399 // Just break out of loop after an initial time-out (tag is probably not available)
1400 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1407 // Are we dealing with the first incoming edge
1408 if (waiting_for_first_edge
) {
1410 // Register the number of periods that have passed
1413 // Indicate that we have dealt with the first edge
1414 waiting_for_first_edge
= false;
1416 // The first edge is always a single NRZ bit, force periods on 16
1419 // We have received more than 0 periods, so we have detected a tag response
1420 detected_modulation
= true;
1423 // Evaluate the number of periods before the next edge
1424 if (periods
> 24 && periods
<= 64) {
1425 // Detected two sequential equal bits and a modulation switch
1426 // NRZ modulation: (11 => --|) or (11 __|)
1427 nrz_samples
[nrzs
++] = reader_modulation
;
1428 nrz_samples
[nrzs
++] = reader_modulation
;
1429 // Invert tag modulation state
1430 reader_modulation
^= 1;
1431 } else if (periods
> 0 && periods
<= 24) {
1432 // Detected one bit and a modulation switch
1433 // NRZ modulation: (1 => -|) or (0 _|)
1434 nrz_samples
[nrzs
++] = reader_modulation
;
1435 reader_modulation
^= 1;
1437 reader_modulation
^= 1;
1438 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1439 Dbprintf("Detected unexpected period count: %d", periods
);
1446 // If there is no response, just repeat the loop
1447 if (!detected_modulation
) continue;
1451 // Make sure we always have an even number of samples. This fixes the problem
1452 // of ending the manchester decoding with a zero. See the example below where
1453 // the '|' character is end of modulation
1454 // One at the end: ..._-|_____...
1455 // Zero at the end: ...-_|_____...
1456 // The last modulation change of a zero is not detected, but we should take
1457 // the half period in account, otherwise the demodulator will fail.
1458 if ((nrzs
% 2) != 0) {
1459 nrz_samples
[nrzs
++] = reader_modulation
;
1465 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
1467 // Verify if the header consists of five consecutive ones
1469 Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs
);
1472 for (size_t i
= 0; i
< 5; i
++) {
1473 if (nrz_samples
[i
] != 1) {
1474 Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one", i
);
1479 // Pack the response into a byte array
1480 for (size_t i
= 5; i
< 37; i
++) {
1481 uint8_t bit
= nrz_samples
[i
];
1482 rx
[rxlen
/ 8] |= bit
<< (7 - (rxlen
% 8));
1486 // Check if frame was captured
1489 LogTrace(rx
, nbytes(rxlen
), response
, response
, NULL
, true);
1491 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1492 hitag2_handle_reader_command(rx
, rxlen
, tx
, &txlen
);
1494 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1495 // not that since the clock counts since the rising edge, but T_Wait1 is
1496 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1497 // periods. The gap time T_Low varies (4..10). All timer values are in
1498 // terms of T0 units (HITAG_T_WAIT_1_MIN - HITAG_T_LOW )
1499 lf_wait_periods(HITAG_T_WAIT_1_MIN
);
1501 // Send and store the tag answer (if there is any)
1503 // Transmit the tag frame
1504 //hitag_send_frame(tx, txlen);
1505 lf_manchester_send_bytes(tx
, txlen
);
1507 // Store the frame in the trace
1508 LogTrace(tx
, nbytes(txlen
), 0, 0, NULL
, false);
1511 // Reset the received frame and response timing info
1512 memset(rx
, 0x00, sizeof(rx
));
1521 // release allocated memory from BigBuff.
1524 DbpString("Sim stopped");
1526 // reply_ng(CMD_LF_HITAG_SIMULATE, (checked == -1) ? PM3_EOPABORTED : PM3_SUCCESS, (uint8_t *)tag.sectors, tag_size);
1529 void ReaderHitag(hitag_function htf
, hitag_data
*htd
) {
1531 uint32_t command_start
= 0, command_duration
= 0;
1532 uint32_t response_start
= 0, response_duration
= 0;
1534 uint8_t rx
[HITAG_FRAME_LEN
] = {0};
1536 uint8_t txbuf
[HITAG_FRAME_LEN
] = {0};
1537 uint8_t *tx
= txbuf
;
1541 int t_wait_1_guard
= 8;
1543 size_t tag_size
= 48;
1546 // Raw demodulation/decoding by sampling edge periods
1549 // Reset the return status
1550 bSuccessful
= false;
1553 // Clean up trace and prepare it for storing frames
1557 // Check configuration
1560 DBG
Dbprintf("Read public blocks in plain mode");
1561 // this part will be unreadable
1562 memset(tag
.sectors
+ 2, 0x0, 30);
1566 case RHT1F_AUTHENTICATE
: {
1567 DBG
Dbprintf("Read all blocks in authed mode");
1568 memcpy(nonce
, htd
->ht1auth
.nonce
, 4);
1569 memcpy(key
, htd
->ht1auth
.key
, 4);
1570 memcpy(logdata_0
, htd
->ht1auth
.logdata_0
, 4);
1571 memcpy(logdata_1
, htd
->ht1auth
.logdata_1
, 4);
1573 memset(nonce
, 0x0, 4);
1574 memset(logdata_1
, 0x00, 4);
1576 key_no
= htd
->ht1auth
.key_no
;
1577 DBG
Dbprintf("Authenticating using key #%u :", key_no
);
1578 DBG
Dbhexdump(4, key
, false);
1579 DBG
DbpString("Nonce:");
1580 DBG
Dbhexdump(4, nonce
, false);
1581 DBG
DbpString("Logdata_0:");
1582 DBG
Dbhexdump(4, logdata_0
, false);
1583 DBG
DbpString("Logdata_1:");
1584 DBG
Dbhexdump(4, logdata_1
, false);
1588 case RHT2F_PASSWORD
: {
1589 DBG
Dbprintf("List identifier in password mode");
1590 if (memcmp(htd
->pwd
.password
, "\x00\x00\x00\x00", 4) == 0)
1591 memcpy(password
, tag
.sectors
[1], sizeof(password
));
1593 memcpy(password
, htd
->pwd
.password
, sizeof(password
));
1597 bAuthenticating
= false;
1600 case RHT2F_AUTHENTICATE
: {
1601 DBG
DbpString("Authenticating using nr,ar pair:");
1602 memcpy(NrAr
, htd
->auth
.NrAr
, 8);
1603 DBG
Dbhexdump(8, NrAr
, false);
1605 bAuthenticating
= false;
1608 case RHT2F_CRYPTO
: {
1609 DBG
DbpString("Authenticating using key:");
1610 memcpy(key
, htd
->crypto
.key
, 6); //HACK; 4 or 6?? I read both in the code.
1611 DBG
Dbhexdump(6, key
, false);
1612 DBG
DbpString("Nonce:");
1613 DBG
Dbhexdump(4, nonce
, false);
1614 memcpy(nonce
, htd
->crypto
.data
, 4);
1617 bAuthenticating
= false;
1620 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1621 DBG
Dbprintf("Testing %d authentication attempts", (auth_table_len
/ 8));
1623 memcpy(NrAr
, auth_table
, 8);
1627 case RHT2F_UID_ONLY
: {
1630 bAuthenticating
= false;
1634 DBG
Dbprintf("Error, unknown function: %d", htf
);
1642 // hitag2 state machine?
1645 uint8_t attempt_count
= 0;
1647 // Tag specific configuration settings (sof, timings, etc.)
1649 /* if (htf <= HTS_LAST_CMD) {
1655 DBG DbpString("Configured for hitagS reader");
1657 if (htf
<= HT1_LAST_CMD
) {
1663 DBG
DbpString("Configured for hitag1 reader");
1664 } else if (htf
<= HT2_LAST_CMD
) {
1666 t_wait_1
= HITAG_T_WAIT_1_MIN
;
1667 t_wait_2
= HITAG_T_WAIT_2_MIN
;
1669 DBG
DbpString("Configured for hitag2 reader");
1673 lf_init(true, false);
1674 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1676 uint8_t tag_modulation
;
1677 size_t max_nrzs
= (8 * HITAG_FRAME_LEN
+ 5) * 2; // up to 2 nrzs per bit
1678 uint8_t nrz_samples
[max_nrzs
];
1679 bool turn_on
= true;
1681 int16_t checked
= 0;
1682 uint32_t signal_size
= 10000;
1684 while (bStop
== false && BUTTON_PRESS() == false) {
1687 initSampleBufferEx(&signal_size
, true);
1691 // only every 1000th times, in order to save time when collecting samples.
1692 if (checked
== 4000) {
1693 if (data_available()) {
1702 // By default reset the transmission buffer
1706 bStop
= !hitag_plain(rx
, rxlen
, tx
, &txlen
, false);
1709 case RHT1F_AUTHENTICATE
: {
1710 bStop
= !hitag1_authenticate(rx
, rxlen
, tx
, &txlen
);
1713 case RHT2F_PASSWORD
: {
1714 bStop
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, false);
1717 case RHT2F_AUTHENTICATE
: {
1718 bStop
= !hitag2_authenticate(rx
, rxlen
, tx
, &txlen
);
1721 case RHT2F_CRYPTO
: {
1722 bStop
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, false);
1725 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1726 bStop
= !hitag2_test_auth_attempts(rx
, rxlen
, tx
, &txlen
);
1729 case RHT2F_UID_ONLY
: {
1730 bStop
= !hitag2_read_uid(rx
, rxlen
, tx
, &txlen
);
1731 if (bSuccessful
) bStop
= true;
1732 attempt_count
++; //attempt 3 times to get uid then quit
1733 if (!bStop
&& attempt_count
== 3)
1739 DBG
Dbprintf("Error, unknown function: %d", htf
);
1745 // Wait 50ms with field off to be sure the transponder gets reset
1747 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
1749 // Wait with field on to be in "Wait for START_AUTH" timeframe
1750 lf_wait_periods(HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4);
1751 command_start
+= HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4;
1753 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
1754 lf_wait_periods(t_wait_2
);
1755 command_start
+= t_wait_2
;
1757 // Transmit the reader frame
1758 command_duration
= hitag_reader_send_frame(tx
, txlen
);
1759 response_start
= command_start
+ command_duration
;
1761 // Let the antenna and ADC values settle
1762 // And find the position where edge sampling should start
1763 lf_wait_periods(t_wait_1
- t_wait_1_guard
);
1764 response_start
+= t_wait_1
- t_wait_1_guard
;
1766 // Keep administration of the first edge detection
1767 bool waiting_for_first_edge
= true;
1769 // Did we detected any modulaiton at all
1770 bool detected_tag_modulation
= false;
1772 // Use the current modulation state as starting point
1773 tag_modulation
= lf_get_tag_modulation();
1775 // Reset the number of NRZ samples and use edge detection to detect them
1777 while (nrzs
< max_nrzs
) {
1778 // Get the timing of the next edge in number of wave periods
1779 periods
= lf_count_edge_periods(128);
1781 // Are we dealing with the first incoming edge
1782 if (waiting_for_first_edge
) {
1783 // Just break out of loop after an initial time-out (tag is probably not available)
1784 if (periods
== 0) break;
1785 if (tag_modulation
== 0) {
1786 // hitag replies always start with 11111 == 1010101010, if we see 0
1787 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
1789 nrz_samples
[nrzs
++] = tag_modulation
^ 1;
1790 // Register the number of periods that have passed
1791 // we missed the begin of response but we know it happened one period of 16 earlier
1792 response_start
+= periods
- 16;
1793 response_duration
= response_start
;
1795 // Register the number of periods that have passed
1796 response_start
+= periods
;
1797 response_duration
= response_start
;
1799 // Indicate that we have dealt with the first edge
1800 waiting_for_first_edge
= false;
1801 // The first edge is always a single NRZ bit, force periods on 16
1803 // We have received more than 0 periods, so we have detected a tag response
1804 detected_tag_modulation
= true;
1806 // The function lf_count_edge_periods() returns 0 when a time-out occurs
1808 DBG
Dbprintf("Detected timeout after [%d] nrz samples", nrzs
);
1812 // Evaluate the number of periods before the next edge
1813 if (periods
> 24 && periods
<= 64) {
1814 // Detected two sequential equal bits and a modulation switch
1815 // NRZ modulation: (11 => --|) or (11 __|)
1816 nrz_samples
[nrzs
++] = tag_modulation
;
1817 nrz_samples
[nrzs
++] = tag_modulation
;
1818 response_duration
+= periods
;
1819 // Invert tag modulation state
1820 tag_modulation
^= 1;
1821 } else if (periods
> 0 && periods
<= 24) {
1822 // Detected one bit and a modulation switch
1823 // NRZ modulation: (1 => -|) or (0 _|)
1824 nrz_samples
[nrzs
++] = tag_modulation
;
1825 response_duration
+= periods
;
1826 tag_modulation
^= 1;
1828 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
1829 DBG
Dbprintf("Detected unexpected period count: %d", periods
);
1834 // Store the TX frame, we do this now at this point, to avoid delay in processing
1835 // and to be able to overwrite the first samples with the trace (since they currently
1836 // still use the same memory space)
1838 LogTrace(tx
, nbytes(txlen
), command_start
, command_start
+ command_duration
, NULL
, true);
1841 // Reset values for receiving frames
1842 memset(rx
, 0x00, sizeof(rx
));
1845 // If there is no response, just repeat the loop
1846 if (!detected_tag_modulation
) continue;
1848 // Make sure we always have an even number of samples. This fixes the problem
1849 // of ending the manchester decoding with a zero. See the example below where
1850 // the '|' character is end of modulation
1851 // One at the end: ..._-|_____...
1852 // Zero at the end: ...-_|_____...
1853 // The last modulation change of a zero is not detected, but we should take
1854 // the half period in account, otherwise the demodulator will fail.
1855 if ((nrzs
% 2) != 0) {
1856 nrz_samples
[nrzs
++] = tag_modulation
;
1862 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
1866 // Verify if the header consists of five consecutive ones
1868 DBG
Dbprintf("Detected unexpected number of manchester decoded samples [%d]", nrzs
);
1872 for (i
= 0; i
< 5; i
++) {
1873 if (nrz_samples
[i
] != 1) {
1874 DBG
Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one, abort", i
);
1881 // Pack the response into a byte array
1882 for (size_t i
= 5; i
< nrzs
&& rxlen
< (sizeof(rx
) << 3); i
++) {
1883 uint8_t bit
= nrz_samples
[i
];
1884 if (bit
> 1) { // When Manchester detects impossible symbol it writes "7"
1885 DBG
Dbprintf("Error in Manchester decoding, abort");
1888 rx
[rxlen
>> 3] |= bit
<< (7 - (rxlen
% 8));
1892 if (rxlen
% 8 == 1) // skip spurious bit
1895 // Check if frame was captured and store it
1898 LogTrace(rx
, nbytes(rxlen
), response_start
, response_start
+ response_duration
, NULL
, false);
1900 // TODO when using cumulative time for command_start, pm3 doesn't reply anymore, e.g. on lf hitag reader --23 -k 4F4E4D494B52
1902 // command_start = response_start + response_duration;
1911 // release allocated memory from BigBuff.
1915 reply_mix(CMD_ACK
, bSuccessful
, 0, 0, (uint8_t *)tag
.sectors
, tag_size
);
1917 reply_mix(CMD_ACK
, bSuccessful
, 0, 0, 0, 0);
1920 void WriterHitag(hitag_function htf
, hitag_data
*htd
, int page
) {
1922 uint32_t command_start
= 0;
1923 uint32_t command_duration
= 0;
1924 uint32_t response_start
= 0;
1925 uint32_t response_duration
= 0;
1926 uint8_t rx
[HITAG_FRAME_LEN
];
1928 uint8_t txbuf
[HITAG_FRAME_LEN
];
1929 uint8_t *tx
= txbuf
;
1933 int t_wait_1_guard
= 8;
1935 size_t tag_size
= 48;
1939 // Raw demodulation/decoding by sampling edge periods
1942 // Reset the return status
1943 bSuccessful
= false;
1946 // Clean up trace and prepare it for storing frames
1951 // Check configuration
1953 case WHT2F_CRYPTO
: {
1954 DbpString("Authenticating using key:");
1955 memcpy(key
, htd
->crypto
.key
, 6); //HACK; 4 or 6?? I read both in the code.
1956 memcpy(writedata
, htd
->crypto
.data
, 4);
1957 Dbhexdump(6, key
, false);
1960 bAuthenticating
= false;
1961 writestate
= WRITE_STATE_START
;
1964 case WHT2F_PASSWORD
: {
1965 DbpString("Authenticating using password:");
1966 memcpy(password
, htd
->pwd
.password
, 4);
1967 memcpy(writedata
, htd
->crypto
.data
, 4);
1968 Dbhexdump(4, password
, false);
1971 bAuthenticating
= false;
1972 writestate
= WRITE_STATE_START
;
1976 Dbprintf("Error, unknown function: %d", htf
);
1987 lf_init(true, false);
1988 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1990 // Tag specific configuration settings (sof, timings, etc.)
1992 /* if (htf <= HTS_LAST_CMD) {
1999 DbpString("Configured for hitagS writer");
2002 /* if (htf <= HT1_LAST_CMD) {
2008 DbpString("Configured for hitag1 writer");
2010 // if (htf <= HT2_LAST_CMD) {
2012 t_wait_1
= HITAG_T_WAIT_1_MIN
;
2013 t_wait_2
= HITAG_T_WAIT_2_MIN
;
2015 DbpString("Configured for hitag2 writer");
2018 uint8_t tag_modulation
;
2019 size_t max_nrzs
= (8 * HITAG_FRAME_LEN
+ 5) * 2; // up to 2 nrzs per bit
2020 uint8_t nrz_samples
[max_nrzs
];
2022 int16_t checked
= 0;
2023 uint32_t signal_size
= 10000;
2024 bool turn_on
= true;
2026 while (bStop
== false && BUTTON_PRESS() == false) {
2029 initSampleBufferEx(&signal_size
, true);
2031 // only every 4000th times, in order to save time when collecting samples.
2032 if (checked
== 4000) {
2033 if (data_available()) {
2044 // By default reset the transmission buffer
2047 case WHT2F_CRYPTO
: {
2048 bStop
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, true);
2051 case WHT2F_PASSWORD
: {
2052 bStop
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, true);
2056 Dbprintf("Error, unknown function: %d", htf
);
2063 // Wait 50ms with field off to be sure the transponder gets reset
2065 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC
| FPGA_LF_ADC_READER_FIELD
);
2067 // Wait with field on to be in "Wait for START_AUTH" timeframe
2068 lf_wait_periods(HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4);
2069 command_start
+= HITAG_T_WAIT_POWERUP
+ HITAG_T_WAIT_START_AUTH_MAX
/ 4;
2071 // Wait for t_wait_2 carrier periods after the last tag bit before transmitting,
2072 lf_wait_periods(t_wait_2
);
2073 command_start
+= t_wait_2
;
2076 // Transmit the reader frame
2077 command_duration
= hitag_reader_send_frame(tx
, txlen
);
2079 response_start
= command_start
+ command_duration
;
2081 // Let the antenna and ADC values settle
2082 // And find the position where edge sampling should start
2083 lf_wait_periods(t_wait_1
- t_wait_1_guard
);
2084 response_start
+= t_wait_1
- t_wait_1_guard
;
2086 // Keep administration of the first edge detection
2087 bool waiting_for_first_edge
= true;
2089 // Did we detected any modulaiton at all
2090 bool detected_tag_modulation
= false;
2092 // Use the current modulation state as starting point
2093 tag_modulation
= lf_get_tag_modulation();
2095 // Reset the number of NRZ samples and use edge detection to detect them
2097 while (nrzs
< max_nrzs
) {
2098 // Get the timing of the next edge in number of wave periods
2099 periods
= lf_count_edge_periods(128);
2101 // Are we dealing with the first incoming edge
2102 if (waiting_for_first_edge
) {
2103 // Just break out of loop after an initial time-out (tag is probably not available)
2104 if (periods
== 0) break;
2105 if (tag_modulation
== 0) {
2106 // hitag replies always start with 11111 == 1010101010, if we see 0
2107 // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal
2109 nrz_samples
[nrzs
++] = tag_modulation
^ 1;
2110 // Register the number of periods that have passed
2111 // we missed the begin of response but we know it happened one period of 16 earlier
2112 response_start
+= periods
- 16;
2113 response_duration
= response_start
;
2115 // Register the number of periods that have passed
2116 response_start
+= periods
;
2117 response_duration
= response_start
;
2119 // Indicate that we have dealt with the first edge
2120 waiting_for_first_edge
= false;
2121 // The first edge is always a single NRZ bit, force periods on 16
2123 // We have received more than 0 periods, so we have detected a tag response
2124 detected_tag_modulation
= true;
2126 // The function lf_count_edge_periods() returns 0 when a time-out occurs
2128 //Dbprintf("Detected timeout after [%d] nrz samples", nrzs);
2132 // Evaluate the number of periods before the next edge
2133 if (periods
> 24 && periods
<= 64) {
2134 // Detected two sequential equal bits and a modulation switch
2135 // NRZ modulation: (11 => --|) or (11 __|)
2136 nrz_samples
[nrzs
++] = tag_modulation
;
2137 nrz_samples
[nrzs
++] = tag_modulation
;
2138 response_duration
+= periods
;
2139 // Invert tag modulation state
2140 tag_modulation
^= 1;
2141 } else if (periods
> 0 && periods
<= 24) {
2142 // Detected one bit and a modulation switch
2143 // NRZ modulation: (1 => -|) or (0 _|)
2144 nrz_samples
[nrzs
++] = tag_modulation
;
2145 response_duration
+= periods
;
2146 tag_modulation
^= 1;
2148 // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods
2149 //Dbprintf("Detected unexpected period count: %d", periods);
2154 // Wait some extra time for flash to be programmed
2157 // Store the TX frame, we do this now at this point, to avoid delay in processing
2158 // and to be able to overwrite the first samples with the trace (since they currently
2159 // still use the same memory space)
2161 LogTrace(tx
, nbytes(txlen
), command_start
, command_start
+ command_duration
, NULL
, true);
2164 // Reset values for receiving frames
2165 memset(rx
, 0x00, sizeof(rx
));
2168 // If there is no response, just repeat the loop
2169 if (!detected_tag_modulation
) continue;
2171 // Make sure we always have an even number of samples. This fixes the problem
2172 // of ending the manchester decoding with a zero. See the example below where
2173 // the '|' character is end of modulation
2174 // One at the end: ..._-|_____...
2175 // Zero at the end: ...-_|_____...
2176 // The last modulation change of a zero is not detected, but we should take
2177 // the half period in account, otherwise the demodulator will fail.
2178 if ((nrzs
% 2) != 0) {
2179 nrz_samples
[nrzs
++] = tag_modulation
;
2185 manrawdecode((uint8_t *)nrz_samples
, &nrzs
, true, 0);
2189 // Verify if the header consists of five consecutive ones
2194 for (i
= 0; i
< 5; i
++) {
2195 if (nrz_samples
[i
] != 1) {
2196 Dbprintf("Detected incorrect header, the bit [%d] is zero instead of one, abort", i
);
2203 // Pack the response into a byte array
2204 for (size_t i
= 5; i
< nrzs
&& rxlen
< (sizeof(rx
) << 3); i
++) {
2205 uint8_t bit
= nrz_samples
[i
];
2206 if (bit
> 1) { // When Manchester detects impossible symbol it writes "7"
2209 // >> 3 instead of div by 8
2210 rx
[rxlen
>> 3] |= bit
<< (7 - (rxlen
% 8));
2214 if (rxlen
% 8 == 1) // skip spurious bit
2217 // Check if frame was captured and store it
2219 LogTrace(rx
, nbytes(rxlen
), response_start
, response_start
+ response_duration
, NULL
, false);
2228 // release allocated memory from BigBuff.
2231 reply_mix(CMD_ACK
, bSuccessful
, 0, 0, (uint8_t *)tag
.sectors
, tag_size
);