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"
35 TAG_STATE_RESET
= 0x01, // Just powered up, awaiting GetSnr
36 TAG_STATE_ACTIVATING
= 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
37 TAG_STATE_ACTIVATED
= 0x03, // Activation complete, awaiting read/write commands
38 TAG_STATE_WRITING
= 0x04, // In write command, awaiting sector contents to be written
40 unsigned int active_sector
;
43 byte_t sectors
[12][4];
46 static struct hitag2_tag tag
= {
47 .state
= TAG_STATE_RESET
,
48 .sectors
= { // Password mode: | Crypto mode:
49 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
50 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
51 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
52 [3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
53 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
54 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
55 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
56 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
57 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
58 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
59 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
60 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
64 //#define TRACE_LENGTH 3000
65 //uint8_t *trace = (uint8_t *) BigBuf;
69 #define AUTH_TABLE_OFFSET FREE_BUFFER_OFFSET
70 #define AUTH_TABLE_LENGTH FREE_BUFFER_SIZE
71 byte_t
* auth_table
= (byte_t
*)BigBuf
+AUTH_TABLE_OFFSET
;
72 size_t auth_table_pos
= 0;
73 size_t auth_table_len
= AUTH_TABLE_LENGTH
;
78 uint64_t cipher_state
;
80 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
81 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
82 // For educational purposes only.
83 // No warranties or guarantees of any kind.
84 // This code is released into the public domain by its author.
91 #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))
92 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
93 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
94 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
95 #define bit(x,n) (((x)>>(n))&1)
96 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
97 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
98 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
100 // Single bit Hitag2 functions:
102 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
104 static const u32 ht2_f4a
= 0x2C79; // 0010 1100 0111 1001
105 static const u32 ht2_f4b
= 0x6671; // 0110 0110 0111 0001
106 static const u32 ht2_f5c
= 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
108 static u32
_f20 (const u64 x
)
112 i5
= ((ht2_f4a
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1
113 + ((ht2_f4b
>> i4 (x
, 7,11,13,14)) & 1)* 2
114 + ((ht2_f4b
>> i4 (x
,16,20,22,25)) & 1)* 4
115 + ((ht2_f4b
>> i4 (x
,27,28,30,32)) & 1)* 8
116 + ((ht2_f4a
>> i4 (x
,33,42,43,45)) & 1)*16;
118 return (ht2_f5c
>> i5
) & 1;
121 static u64
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
)
124 u64 x
= ((key
& 0xFFFF) << 32) + serial
;
126 for (i
= 0; i
< 32; i
++)
129 x
+= (u64
) (_f20 (x
) ^ (((IV
>> i
) ^ (key
>> (i
+16))) & 1)) << 47;
134 static u64
_hitag2_round (u64
*state
)
139 ((((x
>> 0) ^ (x
>> 2) ^ (x
>> 3) ^ (x
>> 6)
140 ^ (x
>> 7) ^ (x
>> 8) ^ (x
>> 16) ^ (x
>> 22)
141 ^ (x
>> 23) ^ (x
>> 26) ^ (x
>> 30) ^ (x
>> 41)
142 ^ (x
>> 42) ^ (x
>> 43) ^ (x
>> 46) ^ (x
>> 47)) & 1) << 47);
148 static u32
_hitag2_byte (u64
* x
)
152 for (i
= 0, c
= 0; i
< 8; i
++) c
+= (u32
) _hitag2_round (x
) << (i
^7);
156 size_t nbytes(size_t nbits
) {
157 return (nbits
/8)+((nbits
%8)>0);
160 int hitag2_reset(void)
162 tag
.state
= TAG_STATE_RESET
;
163 tag
.crypto_active
= 0;
167 int hitag2_init(void)
169 // memcpy(&tag, &resetdata, sizeof(tag));
174 static void hitag2_cipher_reset(struct hitag2_tag
*tag
, const byte_t
*iv
)
176 uint64_t key
= ((uint64_t)tag
->sectors
[2][2]) |
177 ((uint64_t)tag
->sectors
[2][3] << 8) |
178 ((uint64_t)tag
->sectors
[1][0] << 16) |
179 ((uint64_t)tag
->sectors
[1][1] << 24) |
180 ((uint64_t)tag
->sectors
[1][2] << 32) |
181 ((uint64_t)tag
->sectors
[1][3] << 40);
182 uint32_t uid
= ((uint32_t)tag
->sectors
[0][0]) |
183 ((uint32_t)tag
->sectors
[0][1] << 8) |
184 ((uint32_t)tag
->sectors
[0][2] << 16) |
185 ((uint32_t)tag
->sectors
[0][3] << 24);
186 uint32_t iv_
= (((uint32_t)(iv
[0]))) |
187 (((uint32_t)(iv
[1])) << 8) |
188 (((uint32_t)(iv
[2])) << 16) |
189 (((uint32_t)(iv
[3])) << 24);
190 tag
->cs
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
));
193 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t
*authenticator_is
)
195 byte_t authenticator_should
[4];
196 authenticator_should
[0] = ~_hitag2_byte(cs
);
197 authenticator_should
[1] = ~_hitag2_byte(cs
);
198 authenticator_should
[2] = ~_hitag2_byte(cs
);
199 authenticator_should
[3] = ~_hitag2_byte(cs
);
200 return (memcmp(authenticator_should
, authenticator_is
, 4) == 0);
203 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t
*data
, unsigned int bytes
, unsigned int bits
)
206 for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
);
207 for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
);
211 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
212 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
213 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
214 // T0 = TIMER_CLOCK1 / 125000 = 192
217 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
218 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
220 #define HITAG_FRAME_LEN 20
221 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
222 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
223 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
224 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
225 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
226 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
227 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
228 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
229 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
231 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
232 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
233 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
234 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
236 #define HITAG_T_TAG_HALF_PERIOD 16
237 #define HITAG_T_TAG_FULL_PERIOD 32
239 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
240 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
241 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
242 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
245 static void hitag_send_bit(int bit
) {
247 // Reset clock for the next bit
248 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
250 // Fixed modulation, earlier proxmark version used inverted signal
252 // Manchester: Unloaded, then loaded |__--|
254 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
256 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
258 // Manchester: Loaded, then unloaded |--__|
260 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
262 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
267 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
)
269 // Send start of frame
270 for(size_t i
=0; i
<5; i
++) {
274 // Send the content of the frame
275 for(size_t i
=0; i
<frame_len
; i
++) {
276 hitag_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
279 // Drop the modulation
283 void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
285 byte_t rx_air
[HITAG_FRAME_LEN
];
287 // Copy the (original) received frame how it is send over the air
288 memcpy(rx_air
,rx
,nbytes(rxlen
));
290 if(tag
.crypto_active
) {
291 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen
%8);
294 // Reset the transmission frame length
297 // Try to find out which command was send by selecting on length (in bits)
299 // Received 11000 from the reader, request for UID, send UID
301 // Always send over the air in the clear plaintext mode
302 if(rx_air
[0] != 0xC0) {
307 memcpy(tx
,tag
.sectors
[0],4);
308 tag
.crypto_active
= 0;
312 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
314 unsigned int sector
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07);
315 // Verify complement of sector index
316 if(sector
!= ((rx
[0]>>3)&0x07)) {
317 //DbpString("Transmission error (read/write)");
321 switch (rx
[0] & 0xC6) {
322 // Read command: 11xx x00y
324 memcpy(tx
,tag
.sectors
[sector
],4);
328 // Inverted Read command: 01xx x10y
330 for (size_t i
=0; i
<4; i
++) {
331 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
336 // Write command: 10xx x01y
338 // Prepare write, acknowledge by repeating command
339 memcpy(tx
,rx
,nbytes(rxlen
));
341 tag
.active_sector
= sector
;
342 tag
.state
=TAG_STATE_WRITING
;
347 Dbprintf("Uknown command: %02x %02x",rx
[0],rx
[1]);
354 // Writing data or Reader password
356 if(tag
.state
== TAG_STATE_WRITING
) {
357 // These are the sector contents to be written. We don't have to do anything else.
358 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
));
359 tag
.state
=TAG_STATE_RESET
;
362 // Received RWD password, respond with configuration and our password
363 if(memcmp(rx
,tag
.sectors
[1],4) != 0) {
364 DbpString("Reader password is wrong");
368 memcpy(tx
,tag
.sectors
[3],4);
373 // Received RWD authentication challenge and respnse
375 // Store the authentication attempt
376 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
377 memcpy(auth_table
+auth_table_len
,rx
,8);
381 // Reset the cipher state
382 hitag2_cipher_reset(&tag
,rx
);
383 // Check if the authentication was correct
384 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) {
385 // The reader failed to authenticate, do nothing
386 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]);
389 // Succesful, but commented out reporting back to the Host, this may delay to much.
390 // 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]);
392 // Activate encryption algorithm for all further communication
393 tag
.crypto_active
= 1;
395 // Use the tag password as response
396 memcpy(tx
,tag
.sectors
[3],4);
402 // LogTrace(rx,nbytes(rxlen),0,0,false);
403 // LogTrace(tx,nbytes(*txlen),0,0,true);
405 if(tag
.crypto_active
) {
406 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen
%8);
410 static void hitag_reader_send_bit(int bit
) {
412 // Reset clock for the next bit
413 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
415 // Binary puls length modulation (BPLM) is used to encode the data stream
416 // This means that a transmission of a one takes longer than that of a zero
418 // Enable modulation, which means, drop the the field
421 // Wait for 4-10 times the carrier period
422 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
425 // Disable modulation, just activates the field again
430 while(AT91C_BASE_TC0
->TC_CV
< T0
*22);
431 // SpinDelayUs(16*8);
434 while(AT91C_BASE_TC0
->TC_CV
< T0
*28);
435 // SpinDelayUs(22*8);
440 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
)
442 // Send the content of the frame
443 for(size_t i
=0; i
<frame_len
; i
++) {
444 hitag_reader_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
447 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
448 // Enable modulation, which means, drop the the field
450 // Wait for 4-10 times the carrier period
451 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
452 // Disable modulation, just activates the field again
458 bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
459 // Reset the transmission frame length
462 // Try to find out which command was send by selecting on length (in bits)
464 // No answer, try to resurrect
466 // Stop if there is no answer (after sending password)
468 DbpString("Password failed!");
472 memcpy(tx
,"\xc0",nbytes(*txlen
));
475 // Received UID, tag password
479 memcpy(tx
,password
,4);
481 memcpy(tag
.sectors
[blocknr
],rx
,4);
486 //store password in block1, the TAG answers with Block3, but we need the password in memory
487 memcpy(tag
.sectors
[blocknr
],tx
,4);
489 memcpy(tag
.sectors
[blocknr
],rx
,4);
494 DbpString("Read succesful!");
499 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
500 tx
[1] = ((blocknr
^7) << 6);
504 // Unexpected response
506 Dbprintf("Uknown frame length: %d",rxlen
);
513 bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
514 // Reset the transmission frame length
518 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen
%8);
521 // Try to find out which command was send by selecting on length (in bits)
523 // No answer, try to resurrect
525 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
527 // Failed during authentication
528 if (bAuthenticating
) {
529 DbpString("Authentication failed!");
532 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
534 // Write the low part of the key in memory
535 memcpy(tag
.sectors
[1],key
+2,4);
536 } else if (blocknr
== 2) {
537 // Write the high part of the key in memory
538 tag
.sectors
[2][0] = 0x00;
539 tag
.sectors
[2][1] = 0x00;
540 tag
.sectors
[2][2] = key
[0];
541 tag
.sectors
[2][3] = key
[1];
543 // Just put zero's in the memory (of the unreadable block)
544 memset(tag
.sectors
[blocknr
],0x00,4);
551 memcpy(tx
,"\xc0",nbytes(*txlen
));
555 // Received UID, crypto tag answer
558 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;
559 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
560 cipher_state
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0);
563 hitag2_cipher_transcrypt(&cipher_state
,tx
+4,4,0);
566 bAuthenticating
= true;
568 // Check if we received answer tag (at)
569 if (bAuthenticating
) {
570 bAuthenticating
= false;
572 // Store the received block
573 memcpy(tag
.sectors
[blocknr
],rx
,4);
577 DbpString("Read succesful!");
582 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
583 tx
[1] = ((blocknr
^7) << 6);
587 // Unexpected response
589 Dbprintf("Uknown frame length: %d",rxlen
);
596 // We have to return now to avoid double encryption
597 if (!bAuthenticating
) {
598 hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen
%8);
606 bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
607 // Reset the transmission frame length
610 // Try to find out which command was send by selecting on length (in bits)
612 // No answer, try to resurrect
614 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
616 DbpString("Authentication failed!");
620 memcpy(tx
,"\xc0",nbytes(*txlen
));
623 // Received UID, crypto tag answer
630 DbpString("Authentication succesful!");
631 // We are done... for now
636 // Unexpected response
638 Dbprintf("Uknown frame length: %d",rxlen
);
646 bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
647 // Reset the transmission frame length
650 // Try to find out which command was send by selecting on length (in bits)
652 // No answer, try to resurrect
654 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
656 Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed!",NrAr
[0],NrAr
[1],NrAr
[2],NrAr
[3],NrAr
[4],NrAr
[5],NrAr
[6],NrAr
[7]);
658 if ((auth_table_pos
+8) == auth_table_len
) {
662 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
665 memcpy(tx
,"\xc0",nbytes(*txlen
));
668 // Received UID, crypto tag answer, or read block response
675 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]);
677 if ((auth_table_pos
+8) == auth_table_len
) {
681 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
686 Dbprintf("Uknown frame length: %d",rxlen
);
694 void SnoopHitag(uint32_t type
) {
703 byte_t rx
[HITAG_FRAME_LEN
];
706 // Clean up trace and prepare it for storing frames
707 iso14a_set_tracing(TRUE
);
708 iso14a_clear_trace();
712 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
714 DbpString("Starting Hitag2 snoop");
717 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
718 // and analog mux selection.
719 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
720 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
721 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
724 // Configure output pin that is connected to the FPGA (for modulating)
725 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
726 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
728 // Disable modulation, we are going to eavesdrop, not modulate ;)
731 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
732 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
733 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
735 // Disable timer during configuration
736 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
738 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
739 // external trigger rising edge, load RA on rising edge of TIOA.
740 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
741 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
743 // Enable and reset counter
744 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
746 // Reset the received frame, frame count and timing info
747 memset(rx
,0x00,sizeof(rx
));
751 reader_frame
= false;
756 while(!BUTTON_PRESS()) {
760 // Receive frame, watch for at most T0*EOF periods
761 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
762 // Check if rising edge in modulation is detected
763 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
764 // Retrieve the new timing values
765 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
767 // Find out if we are dealing with a rising or falling edge
768 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
770 // Shorter periods will only happen with reader frames
771 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
772 // Switch from tag to reader capture
775 memset(rx
,0x00,sizeof(rx
));
779 // Only handle if reader frame and rising edge, or tag frame and falling edge
780 if (reader_frame
!= rising_edge
) {
785 // Add the buffered timing values of earlier captured edges which were skipped
791 // Capture reader frame
792 if(ra
>= HITAG_T_STOP
) {
794 //DbpString("wierd0?");
796 // Capture the T0 periods that have passed since last communication or field drop (reset)
797 response
= (ra
- HITAG_T_LOW
);
798 } else if(ra
>= HITAG_T_1_MIN
) {
800 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
802 } else if(ra
>= HITAG_T_0_MIN
) {
804 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
807 // Ignore wierd value, is to small to mean anything
811 // Capture tag frame (manchester decoding using only falling edges)
812 if(ra
>= HITAG_T_EOF
) {
814 //DbpString("wierd1?");
816 // Capture the T0 periods that have passed since last communication or field drop (reset)
817 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
818 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
819 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
820 // Manchester coding example |-_|_-|-_| (101)
821 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
823 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
825 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
826 // Manchester coding example |_-|...|_-|-_| (0...01)
827 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
829 // We have to skip this half period at start and add the 'one' the second time
831 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
836 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
837 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
839 // Ignore bits that are transmitted during SOF
842 // bit is same as last bit
843 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
847 // Ignore wierd value, is to small to mean anything
853 // Check if frame was captured
856 if (!LogTrace(rx
,nbytes(rxlen
),response
,0,reader_frame
)) {
857 DbpString("Trace full");
861 // Check if we recognize a valid authentication attempt
862 if (nbytes(rxlen
) == 8) {
863 // Store the authentication attempt
864 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
865 memcpy(auth_table
+auth_table_len
,rx
,8);
870 // Reset the received frame and response timing info
871 memset(rx
,0x00,sizeof(rx
));
873 reader_frame
= false;
882 // Save the timer overflow, will be 0 when frame was received
883 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
885 // Reset the frame length
887 // Reset the timer to restart while-loop that receives frames
888 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
894 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
895 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
896 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
899 // Dbprintf("frame received: %d",frame_count);
900 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
901 // DbpString("All done");
904 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
908 byte_t rx
[HITAG_FRAME_LEN
];
910 byte_t tx
[HITAG_FRAME_LEN
];
912 bool bQuitTraceFull
= false;
915 // Clean up trace and prepare it for storing frames
916 iso14a_set_tracing(TRUE
);
917 iso14a_clear_trace();
920 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
922 DbpString("Starting Hitag2 simulation");
926 if (tag_mem_supplied
) {
927 DbpString("Loading hitag2 memory...");
928 memcpy((byte_t
*)tag
.sectors
,data
,48);
932 for (size_t i
=0; i
<12; i
++) {
933 for (size_t j
=0; j
<4; j
++) {
935 block
|= tag
.sectors
[i
][j
];
937 Dbprintf("| %d | %08x |",i
,block
);
940 // Set up simulator mode, frequency divisor which will drive the FPGA
941 // and analog mux selection.
942 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
943 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
944 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
947 // Configure output pin that is connected to the FPGA (for modulating)
948 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
949 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
951 // Disable modulation at default, which means release resistance
954 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
955 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
957 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
958 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
959 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
961 // Disable timer during configuration
962 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
964 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
965 // external trigger rising edge, load RA on rising edge of TIOA.
966 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
968 // Enable and reset counter
969 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
971 // Reset the received frame, frame count and timing info
972 memset(rx
,0x00,sizeof(rx
));
977 while(!BUTTON_PRESS()) {
981 // Receive frame, watch for at most T0*EOF periods
982 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
983 // Check if rising edge in modulation is detected
984 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
985 // Retrieve the new timing values
986 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
989 // Reset timer every frame, we have to capture the last edge for timing
990 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
994 // Capture reader frame
995 if(ra
>= HITAG_T_STOP
) {
997 //DbpString("wierd0?");
999 // Capture the T0 periods that have passed since last communication or field drop (reset)
1000 response
= (ra
- HITAG_T_LOW
);
1001 } else if(ra
>= HITAG_T_1_MIN
) {
1003 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1005 } else if(ra
>= HITAG_T_0_MIN
) {
1007 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1010 // Ignore wierd value, is to small to mean anything
1015 // Check if frame was captured
1019 if (!LogTrace(rx
,nbytes(rxlen
),response
,0,true)) {
1020 DbpString("Trace full");
1021 if (bQuitTraceFull
) {
1029 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1030 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1032 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1033 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1035 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1036 // not that since the clock counts since the rising edge, but T_Wait1 is
1037 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1038 // periods. The gap time T_Low varies (4..10). All timer values are in
1039 // terms of T0 units
1040 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1042 // Send and store the tag answer (if there is any)
1044 // Transmit the tag frame
1045 hitag_send_frame(tx
,txlen
);
1046 // Store the frame in the trace
1048 if (!LogTrace(tx
,nbytes(txlen
),0,0,false)) {
1049 DbpString("Trace full");
1050 if (bQuitTraceFull
) {
1059 // Reset the received frame and response timing info
1060 memset(rx
,0x00,sizeof(rx
));
1063 // Enable and reset external trigger in timer for capturing future frames
1064 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1067 // Reset the frame length
1069 // Save the timer overflow, will be 0 when frame was received
1070 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1071 // Reset the timer to restart while-loop that receives frames
1072 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1076 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1077 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1078 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1079 // Dbprintf("frame received: %d",frame_count);
1080 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1081 // DbpString("All done");
1084 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1087 byte_t rx
[HITAG_FRAME_LEN
];
1089 byte_t txbuf
[HITAG_FRAME_LEN
];
1096 int t_wait
= HITAG_T_WAIT_MAX
;
1098 bool bQuitTraceFull
= false;
1100 // Reset the return status
1101 bSuccessful
= false;
1103 // Clean up trace and prepare it for storing frames
1104 iso14a_set_tracing(TRUE
);
1105 iso14a_clear_trace();
1106 DbpString("Starting Hitag reader family");
1108 // Check configuration
1110 case RHT2F_PASSWORD
: {
1111 Dbprintf("List identifier in password mode");
1112 memcpy(password
,htd
->pwd
.password
,4);
1114 bQuitTraceFull
= false;
1119 case RHT2F_AUTHENTICATE
: {
1120 DbpString("Authenticating using nr,ar pair:");
1121 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1122 Dbhexdump(8,NrAr
,false);
1125 bAuthenticating
= false;
1126 bQuitTraceFull
= true;
1129 case RHT2F_CRYPTO
: {
1130 DbpString("Authenticating using key:");
1131 memcpy(key
,htd
->crypto
.key
,6);
1132 Dbhexdump(6,key
,false);
1136 bAuthenticating
= false;
1137 bQuitTraceFull
= true;
1140 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1141 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1143 memcpy(NrAr
,auth_table
,8);
1144 bQuitTraceFull
= false;
1150 Dbprintf("Error, unknown function: %d",htf
);
1158 // Configure output and enable pin that is connected to the FPGA (for modulating)
1159 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1160 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1162 // Set fpga in edge detect with reader field, we can modulate as reader now
1163 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1165 // Set Frequency divisor which will drive the FPGA and analog mux selection
1166 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1167 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1170 // Disable modulation at default, which means enable the field
1173 // Give it a bit of time for the resonant antenna to settle.
1176 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1177 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1179 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1180 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1181 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1183 // Disable timer during configuration
1184 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1186 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1187 // external trigger rising edge, load RA on falling edge of TIOA.
1188 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1190 // Enable and reset counters
1191 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1192 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1194 // Reset the received frame, frame count and timing info
1200 // Tag specific configuration settings (sof, timings, etc.)
1205 DbpString("Configured for hitagS reader");
1206 } else if (htf
< 20) {
1210 DbpString("Configured for hitag1 reader");
1211 } else if (htf
< 30) {
1214 t_wait
= HITAG_T_WAIT_2
;
1215 DbpString("Configured for hitag2 reader");
1217 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1221 while(!bStop
&& !BUTTON_PRESS()) {
1225 // Check if frame was captured and store it
1229 if (!LogTrace(rx
,nbytes(rxlen
),response
,0,false)) {
1230 DbpString("Trace full");
1231 if (bQuitTraceFull
) {
1240 // By default reset the transmission buffer
1243 case RHT2F_PASSWORD
: {
1244 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1246 case RHT2F_AUTHENTICATE
: {
1247 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1249 case RHT2F_CRYPTO
: {
1250 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
);
1252 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1253 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1256 Dbprintf("Error, unknown function: %d",htf
);
1261 // Send and store the reader command
1262 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1263 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1265 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1266 // Since the clock counts since the last falling edge, a 'one' means that the
1267 // falling edge occured halfway the period. with respect to this falling edge,
1268 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1269 // All timer values are in terms of T0 units
1270 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1272 // Transmit the reader frame
1273 hitag_reader_send_frame(tx
,txlen
);
1275 // Enable and reset external trigger in timer for capturing future frames
1276 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1278 // Add transmitted frame to total count
1282 // Store the frame in the trace
1283 if (!LogTrace(tx
,nbytes(txlen
),HITAG_T_WAIT_2
,0,true)) {
1284 if (bQuitTraceFull
) {
1293 // Reset values for receiving frames
1294 memset(rx
,0x00,sizeof(rx
));
1298 tag_sof
= reset_sof
;
1301 // Receive frame, watch for at most T0*EOF periods
1302 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1303 // Check if falling edge in tag modulation is detected
1304 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1305 // Retrieve the new timing values
1306 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1308 // Reset timer every frame, we have to capture the last edge for timing
1309 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1313 // Capture tag frame (manchester decoding using only falling edges)
1314 if(ra
>= HITAG_T_EOF
) {
1316 //DbpString("wierd1?");
1318 // Capture the T0 periods that have passed since last communication or field drop (reset)
1319 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1320 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1321 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1322 // Manchester coding example |-_|_-|-_| (101)
1323 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1325 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1327 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1328 // Manchester coding example |_-|...|_-|-_| (0...01)
1329 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1331 // We have to skip this half period at start and add the 'one' the second time
1333 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1338 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1339 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1341 // Ignore bits that are transmitted during SOF
1344 // bit is same as last bit
1345 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1349 // Ignore wierd value, is to small to mean anything
1353 // We can break this loop if we received the last bit from a frame
1354 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1361 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1362 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1363 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1364 Dbprintf("frame received: %d",frame_count
);
1365 DbpString("All done");
1366 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);