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 //-----------------------------------------------------------------------------
6 // Hitag2 emulation (preliminary test version)
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 snooping of transponder communication
14 // - Added reader functionality
16 // (c) 2012 Roel Verdult
17 //-----------------------------------------------------------------------------
19 #include "proxmark3.h"
29 static bool bAuthenticating
;
31 static bool bSuccessful
;
38 TAG_STATE_RESET
= 0x01, // Just powered up, awaiting GetSnr
39 TAG_STATE_ACTIVATING
= 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
40 TAG_STATE_ACTIVATED
= 0x03, // Activation complete, awaiting read/write commands
41 TAG_STATE_WRITING
= 0x04, // In write command, awaiting sector contents to be written
43 unsigned int active_sector
;
46 byte_t sectors
[12][4];
49 static struct hitag2_tag tag
= {
50 .state
= TAG_STATE_RESET
,
51 .sectors
= { // Password mode: | Crypto mode:
52 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
53 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
54 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
55 [3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
56 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
57 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
58 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
59 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
60 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
61 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
62 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
63 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
68 WRITE_STATE_START
= 0x0,
69 WRITE_STATE_PAGENUM_WRITTEN
,
74 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
75 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
76 #define AUTH_TABLE_LENGTH 2744
77 static byte_t
* auth_table
;
78 static size_t auth_table_pos
= 0;
79 static size_t auth_table_len
= AUTH_TABLE_LENGTH
;
81 static byte_t password
[4];
82 static byte_t NrAr
[8];
84 static byte_t writedata
[4];
85 static uint64_t cipher_state
;
87 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
88 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
89 // For educational purposes only.
90 // No warranties or guarantees of any kind.
91 // This code is released into the public domain by its author.
98 #define rev8(x) ((((x)>>7)&1)+((((x)>>6)&1)<<1)+((((x)>>5)&1)<<2)+((((x)>>4)&1)<<3)+((((x)>>3)&1)<<4)+((((x)>>2)&1)<<5)+((((x)>>1)&1)<<6)+(((x)&1)<<7))
99 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
100 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
101 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
102 #define bit(x,n) (((x)>>(n))&1)
103 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
104 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
105 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
107 // Single bit Hitag2 functions:
109 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
111 static const u32 ht2_f4a
= 0x2C79; // 0010 1100 0111 1001
112 static const u32 ht2_f4b
= 0x6671; // 0110 0110 0111 0001
113 static const u32 ht2_f5c
= 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
115 static u32
_f20 (const u64 x
)
119 i5
= ((ht2_f4a
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1
120 + ((ht2_f4b
>> i4 (x
, 7,11,13,14)) & 1)* 2
121 + ((ht2_f4b
>> i4 (x
,16,20,22,25)) & 1)* 4
122 + ((ht2_f4b
>> i4 (x
,27,28,30,32)) & 1)* 8
123 + ((ht2_f4a
>> i4 (x
,33,42,43,45)) & 1)*16;
125 return (ht2_f5c
>> i5
) & 1;
128 static u64
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
)
131 u64 x
= ((key
& 0xFFFF) << 32) + serial
;
133 for (i
= 0; i
< 32; i
++)
136 x
+= (u64
) (_f20 (x
) ^ (((IV
>> i
) ^ (key
>> (i
+16))) & 1)) << 47;
141 static u64
_hitag2_round (u64
*state
)
146 ((((x
>> 0) ^ (x
>> 2) ^ (x
>> 3) ^ (x
>> 6)
147 ^ (x
>> 7) ^ (x
>> 8) ^ (x
>> 16) ^ (x
>> 22)
148 ^ (x
>> 23) ^ (x
>> 26) ^ (x
>> 30) ^ (x
>> 41)
149 ^ (x
>> 42) ^ (x
>> 43) ^ (x
>> 46) ^ (x
>> 47)) & 1) << 47);
155 static u32
_hitag2_byte (u64
* x
)
159 for (i
= 0, c
= 0; i
< 8; i
++) c
+= (u32
) _hitag2_round (x
) << (i
^7);
163 static int hitag2_reset(void)
165 tag
.state
= TAG_STATE_RESET
;
166 tag
.crypto_active
= 0;
170 static int hitag2_init(void)
172 // memcpy(&tag, &resetdata, sizeof(tag));
177 static void hitag2_cipher_reset(struct hitag2_tag
*tag
, const byte_t
*iv
)
179 uint64_t key
= ((uint64_t)tag
->sectors
[2][2]) |
180 ((uint64_t)tag
->sectors
[2][3] << 8) |
181 ((uint64_t)tag
->sectors
[1][0] << 16) |
182 ((uint64_t)tag
->sectors
[1][1] << 24) |
183 ((uint64_t)tag
->sectors
[1][2] << 32) |
184 ((uint64_t)tag
->sectors
[1][3] << 40);
185 uint32_t uid
= ((uint32_t)tag
->sectors
[0][0]) |
186 ((uint32_t)tag
->sectors
[0][1] << 8) |
187 ((uint32_t)tag
->sectors
[0][2] << 16) |
188 ((uint32_t)tag
->sectors
[0][3] << 24);
189 uint32_t iv_
= (((uint32_t)(iv
[0]))) |
190 (((uint32_t)(iv
[1])) << 8) |
191 (((uint32_t)(iv
[2])) << 16) |
192 (((uint32_t)(iv
[3])) << 24);
193 tag
->cs
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
));
196 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t
*authenticator_is
)
198 byte_t authenticator_should
[4];
199 authenticator_should
[0] = ~_hitag2_byte(cs
);
200 authenticator_should
[1] = ~_hitag2_byte(cs
);
201 authenticator_should
[2] = ~_hitag2_byte(cs
);
202 authenticator_should
[3] = ~_hitag2_byte(cs
);
203 return (memcmp(authenticator_should
, authenticator_is
, 4) == 0);
206 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t
*data
, unsigned int bytes
, unsigned int bits
)
209 for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
);
210 for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
);
214 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
215 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
216 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
217 // T0 = TIMER_CLOCK1 / 125000 = 192
220 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
221 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
223 #define HITAG_FRAME_LEN 20
224 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
225 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
226 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
227 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
228 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
229 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
230 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
231 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
232 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
233 #define HITAG_T_PROG 614
235 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
236 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
237 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
238 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
240 #define HITAG_T_TAG_HALF_PERIOD 16
241 #define HITAG_T_TAG_FULL_PERIOD 32
243 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
244 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
245 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
246 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
249 static void hitag_send_bit(int bit
) {
251 // Reset clock for the next bit
252 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
254 // Fixed modulation, earlier proxmark version used inverted signal
256 // Manchester: Unloaded, then loaded |__--|
258 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
260 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
262 // Manchester: Loaded, then unloaded |--__|
264 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
266 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
271 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
)
273 // Send start of frame
274 for(size_t i
=0; i
<5; i
++) {
278 // Send the content of the frame
279 for(size_t i
=0; i
<frame_len
; i
++) {
280 hitag_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
283 // Drop the modulation
288 static void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
290 byte_t rx_air
[HITAG_FRAME_LEN
];
292 // Copy the (original) received frame how it is send over the air
293 memcpy(rx_air
,rx
,nbytes(rxlen
));
295 if(tag
.crypto_active
) {
296 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen
%8);
299 // Reset the transmission frame length
302 // Try to find out which command was send by selecting on length (in bits)
304 // Received 11000 from the reader, request for UID, send UID
306 // Always send over the air in the clear plaintext mode
307 if(rx_air
[0] != 0xC0) {
312 memcpy(tx
,tag
.sectors
[0],4);
313 tag
.crypto_active
= 0;
317 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
319 unsigned int sector
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07);
320 // Verify complement of sector index
321 if(sector
!= ((rx
[0]>>3)&0x07)) {
322 //DbpString("Transmission error (read/write)");
326 switch (rx
[0] & 0xC6) {
327 // Read command: 11xx x00y
329 memcpy(tx
,tag
.sectors
[sector
],4);
333 // Inverted Read command: 01xx x10y
335 for (size_t i
=0; i
<4; i
++) {
336 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
341 // Write command: 10xx x01y
343 // Prepare write, acknowledge by repeating command
344 memcpy(tx
,rx
,nbytes(rxlen
));
346 tag
.active_sector
= sector
;
347 tag
.state
=TAG_STATE_WRITING
;
352 Dbprintf("Unknown command: %02x %02x",rx
[0],rx
[1]);
359 // Writing data or Reader password
361 if(tag
.state
== TAG_STATE_WRITING
) {
362 // These are the sector contents to be written. We don't have to do anything else.
363 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
));
364 tag
.state
=TAG_STATE_RESET
;
367 // Received RWD password, respond with configuration and our password
368 if(memcmp(rx
,tag
.sectors
[1],4) != 0) {
369 DbpString("Reader password is wrong");
373 memcpy(tx
,tag
.sectors
[3],4);
378 // Received RWD authentication challenge and respnse
380 // Store the authentication attempt
381 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
382 memcpy(auth_table
+auth_table_len
,rx
,8);
386 // Reset the cipher state
387 hitag2_cipher_reset(&tag
,rx
);
388 // Check if the authentication was correct
389 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) {
390 // The reader failed to authenticate, do nothing
391 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]);
394 // Succesful, but commented out reporting back to the Host, this may delay to much.
395 // Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x OK!",rx[0],rx[1],rx[2],rx[3],rx[4],rx[5],rx[6],rx[7]);
397 // Activate encryption algorithm for all further communication
398 tag
.crypto_active
= 1;
400 // Use the tag password as response
401 memcpy(tx
,tag
.sectors
[3],4);
407 // LogTraceHitag(rx,rxlen,0,0,false);
408 // LogTraceHitag(tx,*txlen,0,0,true);
410 if(tag
.crypto_active
) {
411 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen
%8);
415 static void hitag_reader_send_bit(int bit
) {
417 // Reset clock for the next bit
418 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
420 // Binary puls length modulation (BPLM) is used to encode the data stream
421 // This means that a transmission of a one takes longer than that of a zero
423 // Enable modulation, which means, drop the field
426 // Wait for 4-10 times the carrier period
427 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
430 // Disable modulation, just activates the field again
435 while(AT91C_BASE_TC0
->TC_CV
< T0
*22);
436 // SpinDelayUs(16*8);
439 while(AT91C_BASE_TC0
->TC_CV
< T0
*28);
440 // SpinDelayUs(22*8);
446 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
)
448 // Send the content of the frame
449 for(size_t i
=0; i
<frame_len
; i
++) {
450 hitag_reader_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
453 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
454 // Enable modulation, which means, drop the field
456 // Wait for 4-10 times the carrier period
457 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
458 // Disable modulation, just activates the field again
464 static bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
465 // Reset the transmission frame length
468 // Try to find out which command was send by selecting on length (in bits)
470 // No answer, try to resurrect
472 // Stop if there is no answer (after sending password)
474 DbpString("Password failed!");
478 memcpy(tx
,"\xc0",nbytes(*txlen
));
481 // Received UID, tag password
485 memcpy(tx
,password
,4);
487 memcpy(tag
.sectors
[blocknr
],rx
,4);
492 //store password in block1, the TAG answers with Block3, but we need the password in memory
493 memcpy(tag
.sectors
[blocknr
],tx
,4);
495 memcpy(tag
.sectors
[blocknr
],rx
,4);
500 DbpString("Read succesful!");
505 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
506 tx
[1] = ((blocknr
^7) << 6);
510 // Unexpected response
512 Dbprintf("Uknown frame length: %d",rxlen
);
519 static bool hitag2_write_page(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
521 switch (writestate
) {
522 case WRITE_STATE_START
:
524 tx
[0] = 0x82 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
525 tx
[1] = ((blocknr
^7) << 6);
526 writestate
= WRITE_STATE_PAGENUM_WRITTEN
;
528 case WRITE_STATE_PAGENUM_WRITTEN
:
529 // Check if page number was received correctly
531 (rx
[0] == (0x82 | (blocknr
<< 3) | ((blocknr
^7) >> 2))) &&
532 (rx
[1] == (((blocknr
& 0x3) ^ 0x3) << 6))) {
534 memset(tx
, 0, HITAG_FRAME_LEN
);
535 memcpy(tx
, writedata
, 4);
536 writestate
= WRITE_STATE_PROG
;
538 Dbprintf("hitag2_write_page: Page number was not received correctly: rxlen=%d rx=%02x%02x%02x%02x",
539 rxlen
, rx
[0], rx
[1], rx
[2], rx
[3]);
544 case WRITE_STATE_PROG
:
549 Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen
);
553 DbpString("hitag2_write_page: Unknown state %d");
561 static bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
, bool write
) {
562 // Reset the transmission frame length
566 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen
%8);
570 if (bCrypto
&& !bAuthenticating
&& write
) {
571 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) {
578 // Try to find out which command was send by selecting on length (in bits)
580 // No answer, try to resurrect
583 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
585 // Failed during authentication
586 if (bAuthenticating
) {
587 DbpString("Authentication failed!");
590 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
592 // Write the low part of the key in memory
593 memcpy(tag
.sectors
[1],key
+2,4);
594 } else if (blocknr
== 2) {
595 // Write the high part of the key in memory
596 tag
.sectors
[2][0] = 0x00;
597 tag
.sectors
[2][1] = 0x00;
598 tag
.sectors
[2][2] = key
[0];
599 tag
.sectors
[2][3] = key
[1];
601 // Just put zero's in the memory (of the unreadable block)
602 memset(tag
.sectors
[blocknr
],0x00,4);
609 memcpy(tx
,"\xc0",nbytes(*txlen
));
613 // Received UID, crypto tag answer
616 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;
617 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
618 Dbprintf("hitag2_crypto: key=0x%x%x uid=0x%x", (uint32_t) ((rev64(ui64key
)) >> 32), (uint32_t) ((rev64(ui64key
)) & 0xffffffff), rev32(ui32uid
));
619 cipher_state
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0);
622 hitag2_cipher_transcrypt(&cipher_state
, tx
+4, 4, 0);
625 bAuthenticating
= true;
627 // Check if we received answer tag (at)
628 if (bAuthenticating
) {
629 bAuthenticating
= false;
631 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) {
637 // Store the received block
638 memcpy(tag
.sectors
[blocknr
],rx
,4);
643 DbpString("Read succesful!");
648 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
649 tx
[1] = ((blocknr
^7) << 6);
654 // Unexpected response
656 Dbprintf("Uknown frame length: %d",rxlen
);
663 // We have to return now to avoid double encryption
664 if (!bAuthenticating
) {
665 hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen
%8);
673 static bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
674 // Reset the transmission frame length
677 // Try to find out which command was send by selecting on length (in bits)
679 // No answer, try to resurrect
681 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
683 DbpString("Authentication failed!");
687 memcpy(tx
,"\xc0",nbytes(*txlen
));
690 // Received UID, crypto tag answer
697 DbpString("Authentication succesful!");
698 // We are done... for now
703 // Unexpected response
705 Dbprintf("Uknown frame length: %d",rxlen
);
714 static bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
716 // Reset the transmission frame length
719 // Try to find out which command was send by selecting on length (in bits)
721 // No answer, try to resurrect
723 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
725 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]);
727 // Removing failed entry from authentiations table
728 memcpy(auth_table
+auth_table_pos
,auth_table
+auth_table_pos
+8,8);
731 // Return if we reached the end of the authentications table
733 if (auth_table_pos
== auth_table_len
) {
737 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
738 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
741 memcpy(tx
,"\xc0",nbytes(*txlen
));
744 // Received UID, crypto tag answer, or read block response
751 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]);
753 if ((auth_table_pos
+8) == auth_table_len
) {
757 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
762 Dbprintf("Uknown frame length: %d",rxlen
);
770 static bool hitag2_read_uid(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
771 // Reset the transmission frame length
774 // Try to find out which command was send by selecting on length (in bits)
776 // No answer, try to resurrect
778 // Just starting or if there is no answer
780 memcpy(tx
,"\xc0",nbytes(*txlen
));
784 // Check if we received answer tag (at)
785 if (bAuthenticating
) {
786 bAuthenticating
= false;
788 // Store the received block
789 memcpy(tag
.sectors
[blocknr
],rx
,4);
793 //DbpString("Read successful!");
798 // Unexpected response
800 Dbprintf("Uknown frame length: %d",rxlen
);
807 void SnoopHitag(uint32_t type
) {
816 byte_t rx
[HITAG_FRAME_LEN
] = {0};
819 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
821 // Clean up trace and prepare it for storing frames
829 auth_table
= (byte_t
*)BigBuf_malloc(AUTH_TABLE_LENGTH
);
830 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
832 DbpString("Starting Hitag2 snoop");
835 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
836 // and analog mux selection.
837 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
);
838 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
839 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
842 // Configure output pin that is connected to the FPGA (for modulating)
843 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
844 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
846 // Disable modulation, we are going to eavesdrop, not modulate ;)
849 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
850 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
851 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
853 // Disable timer during configuration
854 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
856 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
857 // external trigger rising edge, load RA on rising edge of TIOA.
858 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
859 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
861 // Enable and reset counter
862 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
864 // Reset the received frame, frame count and timing info
868 reader_frame
= false;
873 while(!BUTTON_PRESS()) {
877 // Receive frame, watch for at most T0*EOF periods
878 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
879 // Check if rising edge in modulation is detected
880 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
881 // Retrieve the new timing values
882 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
884 // Find out if we are dealing with a rising or falling edge
885 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
887 // Shorter periods will only happen with reader frames
888 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
889 // Switch from tag to reader capture
892 memset(rx
,0x00,sizeof(rx
));
896 // Only handle if reader frame and rising edge, or tag frame and falling edge
897 if (reader_frame
!= rising_edge
) {
902 // Add the buffered timing values of earlier captured edges which were skipped
908 // Capture reader frame
909 if(ra
>= HITAG_T_STOP
) {
911 //DbpString("wierd0?");
913 // Capture the T0 periods that have passed since last communication or field drop (reset)
914 response
= (ra
- HITAG_T_LOW
);
915 } else if(ra
>= HITAG_T_1_MIN
) {
917 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
919 } else if(ra
>= HITAG_T_0_MIN
) {
921 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
924 // Ignore wierd value, is to small to mean anything
928 // Capture tag frame (manchester decoding using only falling edges)
929 if(ra
>= HITAG_T_EOF
) {
931 //DbpString("wierd1?");
933 // Capture the T0 periods that have passed since last communication or field drop (reset)
934 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
935 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
936 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
937 // Manchester coding example |-_|_-|-_| (101)
938 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
940 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
942 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
943 // Manchester coding example |_-|...|_-|-_| (0...01)
944 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
946 // We have to skip this half period at start and add the 'one' the second time
948 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
953 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
954 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
956 // Ignore bits that are transmitted during SOF
959 // bit is same as last bit
960 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
964 // Ignore wierd value, is to small to mean anything
970 // Check if frame was captured
973 if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) {
974 DbpString("Trace full");
978 // Check if we recognize a valid authentication attempt
979 if (nbytes(rxlen
) == 8) {
980 // Store the authentication attempt
981 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
982 memcpy(auth_table
+auth_table_len
,rx
,8);
987 // Reset the received frame and response timing info
988 memset(rx
,0x00,sizeof(rx
));
990 reader_frame
= false;
999 // Save the timer overflow, will be 0 when frame was received
1000 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1002 // Reset the frame length
1004 // Reset the timer to restart while-loop that receives frames
1005 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1011 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1012 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1013 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1016 // Dbprintf("frame received: %d",frame_count);
1017 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1018 // DbpString("All done");
1021 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
1025 byte_t rx
[HITAG_FRAME_LEN
];
1027 byte_t tx
[HITAG_FRAME_LEN
];
1029 bool bQuitTraceFull
= false;
1032 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1034 // Clean up trace and prepare it for storing frames
1042 auth_table
= (byte_t
*)BigBuf_malloc(AUTH_TABLE_LENGTH
);
1043 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
1045 DbpString("Starting Hitag2 simulation");
1049 if (tag_mem_supplied
) {
1050 DbpString("Loading hitag2 memory...");
1051 memcpy((byte_t
*)tag
.sectors
,data
,48);
1055 for (size_t i
=0; i
<12; i
++) {
1056 for (size_t j
=0; j
<4; j
++) {
1058 block
|= tag
.sectors
[i
][j
];
1060 Dbprintf("| %d | %08x |",i
,block
);
1063 // Set up simulator mode, frequency divisor which will drive the FPGA
1064 // and analog mux selection.
1065 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
1066 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1067 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1070 // Configure output pin that is connected to the FPGA (for modulating)
1071 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1072 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1074 // Disable modulation at default, which means release resistance
1077 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1078 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1080 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
1081 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1082 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1084 // Disable timer during configuration
1085 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1087 // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1088 // external trigger rising edge, load RA on rising edge of TIOA.
1089 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
1091 // Reset the received frame, frame count and timing info
1092 memset(rx
,0x00,sizeof(rx
));
1097 // Enable and reset counter
1098 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1100 while(!BUTTON_PRESS()) {
1104 // Receive frame, watch for at most T0*EOF periods
1105 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
1106 // Check if rising edge in modulation is detected
1107 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1108 // Retrieve the new timing values
1109 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
1112 // Reset timer every frame, we have to capture the last edge for timing
1113 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1117 // Capture reader frame
1118 if(ra
>= HITAG_T_STOP
) {
1120 //DbpString("wierd0?");
1122 // Capture the T0 periods that have passed since last communication or field drop (reset)
1123 response
= (ra
- HITAG_T_LOW
);
1124 } else if(ra
>= HITAG_T_1_MIN
) {
1126 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1128 } else if(ra
>= HITAG_T_0_MIN
) {
1130 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1133 // Ignore wierd value, is to small to mean anything
1138 // Check if frame was captured
1142 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) {
1143 DbpString("Trace full");
1144 if (bQuitTraceFull
) {
1152 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1153 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1155 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1156 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1158 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1159 // not that since the clock counts since the rising edge, but T_Wait1 is
1160 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1161 // periods. The gap time T_Low varies (4..10). All timer values are in
1162 // terms of T0 units
1163 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1165 // Send and store the tag answer (if there is any)
1167 // Transmit the tag frame
1168 hitag_send_frame(tx
,txlen
);
1169 // Store the frame in the trace
1171 if (!LogTraceHitag(tx
,txlen
,0,0,false)) {
1172 DbpString("Trace full");
1173 if (bQuitTraceFull
) {
1182 // Reset the received frame and response timing info
1183 memset(rx
,0x00,sizeof(rx
));
1186 // Enable and reset external trigger in timer for capturing future frames
1187 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1190 // Reset the frame length
1192 // Save the timer overflow, will be 0 when frame was received
1193 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1194 // Reset the timer to restart while-loop that receives frames
1195 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1199 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1200 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1201 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1203 DbpString("Sim Stopped");
1207 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1210 byte_t rx
[HITAG_FRAME_LEN
];
1212 byte_t txbuf
[HITAG_FRAME_LEN
];
1219 int t_wait
= HITAG_T_WAIT_MAX
;
1221 bool bQuitTraceFull
= false;
1223 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1224 // Reset the return status
1225 bSuccessful
= false;
1227 // Clean up trace and prepare it for storing frames
1231 //DbpString("Starting Hitag reader family");
1233 // Check configuration
1235 case RHT2F_PASSWORD
: {
1236 Dbprintf("List identifier in password mode");
1237 memcpy(password
,htd
->pwd
.password
,4);
1239 bQuitTraceFull
= false;
1243 case RHT2F_AUTHENTICATE
: {
1244 DbpString("Authenticating using nr,ar pair:");
1245 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1246 Dbhexdump(8,NrAr
,false);
1249 bAuthenticating
= false;
1250 bQuitTraceFull
= true;
1254 DbpString("Authenticating using key:");
1255 memcpy(key
,htd
->crypto
.key
,6); //HACK; 4 or 6?? I read both in the code.
1256 Dbhexdump(6,key
,false);
1260 bAuthenticating
= false;
1261 bQuitTraceFull
= true;
1263 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1264 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1266 memcpy(NrAr
, auth_table
, 8);
1267 bQuitTraceFull
= false;
1271 case RHT2F_UID_ONLY
: {
1275 bAuthenticating
= false;
1276 bQuitTraceFull
= true;
1279 Dbprintf("Error, unknown function: %d",htf
);
1287 // Configure output and enable pin that is connected to the FPGA (for modulating)
1288 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1289 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1291 // Set fpga in edge detect with reader field, we can modulate as reader now
1292 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1294 // Set Frequency divisor which will drive the FPGA and analog mux selection
1295 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1296 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1299 // Disable modulation at default, which means enable the field
1302 // Give it a bit of time for the resonant antenna to settle.
1305 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1306 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1308 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1309 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1310 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1312 // Disable timer during configuration
1313 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1315 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1316 // external trigger rising edge, load RA on falling edge of TIOA.
1317 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1319 // Enable and reset counters
1320 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1321 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1323 // Reset the received frame, frame count and timing info
1328 // Tag specific configuration settings (sof, timings, etc.)
1333 //DbpString("Configured for hitagS reader");
1334 } else if (htf
< 20) {
1338 //DbpString("Configured for hitag1 reader");
1339 } else if (htf
< 30) {
1342 t_wait
= HITAG_T_WAIT_2
;
1343 //DbpString("Configured for hitag2 reader");
1345 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1348 uint8_t attempt_count
=0;
1349 while(!bStop
&& !BUTTON_PRESS()) {
1353 // Check if frame was captured and store it
1357 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) {
1358 DbpString("Trace full");
1359 if (bQuitTraceFull
) {
1368 // By default reset the transmission buffer
1371 case RHT2F_PASSWORD
: {
1372 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1374 case RHT2F_AUTHENTICATE
: {
1375 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1377 case RHT2F_CRYPTO
: {
1378 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
, false);
1380 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1381 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1383 case RHT2F_UID_ONLY
: {
1384 bStop
= !hitag2_read_uid(rx
, rxlen
, tx
, &txlen
);
1385 attempt_count
++; //attempt 3 times to get uid then quit
1386 if (!bStop
&& attempt_count
== 3) bStop
= true;
1389 Dbprintf("Error, unknown function: %d",htf
);
1394 // Send and store the reader command
1395 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1396 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1398 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1399 // Since the clock counts since the last falling edge, a 'one' means that the
1400 // falling edge occured halfway the period. with respect to this falling edge,
1401 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1402 // All timer values are in terms of T0 units
1403 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1405 //Dbprintf("DEBUG: Sending reader frame");
1407 // Transmit the reader frame
1408 hitag_reader_send_frame(tx
,txlen
);
1410 // Enable and reset external trigger in timer for capturing future frames
1411 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1413 // Add transmitted frame to total count
1417 // Store the frame in the trace
1418 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) {
1419 if (bQuitTraceFull
) {
1428 // Reset values for receiving frames
1429 memset(rx
,0x00,sizeof(rx
));
1433 tag_sof
= reset_sof
;
1435 //Dbprintf("DEBUG: Waiting to receive frame");
1436 uint32_t errorCount
= 0;
1438 // Receive frame, watch for at most T0*EOF periods
1439 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1440 // Check if falling edge in tag modulation is detected
1441 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1442 // Retrieve the new timing values
1443 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1445 // Reset timer every frame, we have to capture the last edge for timing
1446 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1450 // Capture tag frame (manchester decoding using only falling edges)
1451 if(ra
>= HITAG_T_EOF
) {
1453 //Dbprintf("DEBUG: Wierd1");
1455 // Capture the T0 periods that have passed since last communication or field drop (reset)
1456 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1457 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1458 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1459 // Manchester coding example |-_|_-|-_| (101)
1461 //need to test to verify we don't exceed memory...
1462 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
1465 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1467 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1469 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1470 // Manchester coding example |_-|...|_-|-_| (0...01)
1472 //need to test to verify we don't exceed memory...
1473 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
1476 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1478 // We have to skip this half period at start and add the 'one' the second time
1480 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1485 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1486 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1488 //need to test to verify we don't exceed memory...
1489 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
1493 // Ignore bits that are transmitted during SOF
1496 // bit is same as last bit
1497 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1501 //Dbprintf("DEBUG: Wierd2");
1503 // Ignore wierd value, is to small to mean anything
1506 //if we saw over 100 wierd values break it probably isn't hitag...
1507 if (errorCount
>100) break;
1508 // We can break this loop if we received the last bit from a frame
1509 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1514 //Dbprintf("DEBUG: Done waiting for frame");
1518 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1519 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1520 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1521 //Dbprintf("frame received: %d",frame_count);
1522 //DbpString("All done");
1524 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);
1526 cmd_send(CMD_ACK
,bSuccessful
,0,0,0,0);
1530 void WriterHitag(hitag_function htf
, hitag_data
* htd
, int page
) {
1533 byte_t rx
[HITAG_FRAME_LEN
];
1535 byte_t txbuf
[HITAG_FRAME_LEN
];
1542 int t_wait
= HITAG_T_WAIT_MAX
;
1544 bool bQuitTraceFull
= false;
1546 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1547 // Reset the return status
1548 bSuccessful
= false;
1550 // Clean up trace and prepare it for storing frames
1554 //DbpString("Starting Hitag reader family");
1556 // Check configuration
1560 DbpString("Authenticating using key:");
1561 memcpy(key
,htd
->crypto
.key
,6); //HACK; 4 or 6?? I read both in the code.
1562 memcpy(writedata
, htd
->crypto
.data
, 4);
1563 Dbhexdump(6,key
,false);
1567 bAuthenticating
= false;
1568 bQuitTraceFull
= true;
1569 writestate
= WRITE_STATE_START
;
1572 Dbprintf("Error, unknown function: %d",htf
);
1580 // Configure output and enable pin that is connected to the FPGA (for modulating)
1581 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1582 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1584 // Set fpga in edge detect with reader field, we can modulate as reader now
1585 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1587 // Set Frequency divisor which will drive the FPGA and analog mux selection
1588 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1589 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1592 // Disable modulation at default, which means enable the field
1595 // Give it a bit of time for the resonant antenna to settle.
1598 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1599 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1601 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1602 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1603 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1605 // Disable timer during configuration
1606 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1608 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1609 // external trigger rising edge, load RA on falling edge of TIOA.
1610 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1612 // Enable and reset counters
1613 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1614 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1616 // Reset the received frame, frame count and timing info
1622 // Tag specific configuration settings (sof, timings, etc.)
1627 //DbpString("Configured for hitagS reader");
1628 } else if (htf
< 20) {
1632 //DbpString("Configured for hitag1 reader");
1633 } else if (htf
< 30) {
1636 t_wait
= HITAG_T_WAIT_2
;
1637 //DbpString("Configured for hitag2 reader");
1639 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1642 while(!bStop
&& !BUTTON_PRESS()) {
1646 // Check if frame was captured and store it
1650 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) {
1651 DbpString("Trace full");
1652 if (bQuitTraceFull
) {
1661 // By default reset the transmission buffer
1664 case WHT2F_CRYPTO
: {
1665 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
, true);
1668 Dbprintf("Error, unknown function: %d",htf
);
1673 // Send and store the reader command
1674 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1675 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1677 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1678 // Since the clock counts since the last falling edge, a 'one' means that the
1679 // falling edge occured halfway the period. with respect to this falling edge,
1680 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1681 // All timer values are in terms of T0 units
1682 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1684 //Dbprintf("DEBUG: Sending reader frame");
1686 // Transmit the reader frame
1687 hitag_reader_send_frame(tx
,txlen
);
1689 // Enable and reset external trigger in timer for capturing future frames
1690 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1692 // Add transmitted frame to total count
1696 // Store the frame in the trace
1697 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) {
1698 if (bQuitTraceFull
) {
1707 // Reset values for receiving frames
1708 memset(rx
,0x00,sizeof(rx
));
1712 tag_sof
= reset_sof
;
1714 //Dbprintf("DEBUG: Waiting to receive frame");
1715 uint32_t errorCount
= 0;
1717 // Receive frame, watch for at most T0*EOF periods
1718 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1719 // Check if falling edge in tag modulation is detected
1720 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1721 // Retrieve the new timing values
1722 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1724 // Reset timer every frame, we have to capture the last edge for timing
1725 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1729 // Capture tag frame (manchester decoding using only falling edges)
1730 if(ra
>= HITAG_T_EOF
) {
1732 //Dbprintf("DEBUG: Wierd1");
1734 // Capture the T0 periods that have passed since last communication or field drop (reset)
1735 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1736 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1737 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1738 // Manchester coding example |-_|_-|-_| (101)
1740 //need to test to verify we don't exceed memory...
1741 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
1744 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1746 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1748 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1749 // Manchester coding example |_-|...|_-|-_| (0...01)
1751 //need to test to verify we don't exceed memory...
1752 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
1755 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1757 // We have to skip this half period at start and add the 'one' the second time
1759 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1764 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1765 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1767 //need to test to verify we don't exceed memory...
1768 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
1772 // Ignore bits that are transmitted during SOF
1775 // bit is same as last bit
1776 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1780 //Dbprintf("DEBUG: Wierd2");
1782 // Ignore wierd value, is to small to mean anything
1785 //if we saw over 100 wierd values break it probably isn't hitag...
1786 if (errorCount
>100) break;
1787 // We can break this loop if we received the last bit from a frame
1788 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1793 // Wait some extra time for flash to be programmed
1794 if ((rxlen
== 0) && (writestate
== WRITE_STATE_PROG
))
1796 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1797 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_PROG
- HITAG_T_WAIT_MAX
));
1800 //Dbprintf("DEBUG: Done waiting for frame");
1804 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1805 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1806 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1807 //Dbprintf("frame received: %d",frame_count);
1808 //DbpString("All done");
1809 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);