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"
34 TAG_STATE_RESET
= 0x01, // Just powered up, awaiting GetSnr
35 TAG_STATE_ACTIVATING
= 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
36 TAG_STATE_ACTIVATED
= 0x03, // Activation complete, awaiting read/write commands
37 TAG_STATE_WRITING
= 0x04, // In write command, awaiting sector contents to be written
39 unsigned int active_sector
;
42 byte_t sectors
[12][4];
45 static struct hitag2_tag tag
= {
46 .state
= TAG_STATE_RESET
,
47 .sectors
= { // Password mode: | Crypto mode:
48 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
49 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
50 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
51 [3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
52 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
53 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
54 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
55 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
56 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
57 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
58 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
59 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
63 //#define TRACE_LENGTH 3000
64 //uint8_t *trace = (uint8_t *) BigBuf;
68 #define AUTH_TABLE_OFFSET FREE_BUFFER_OFFSET
69 #define AUTH_TABLE_LENGTH FREE_BUFFER_SIZE
70 byte_t
* auth_table
= (byte_t
*)BigBuf
+AUTH_TABLE_OFFSET
;
71 size_t auth_table_pos
= 0;
72 size_t auth_table_len
= AUTH_TABLE_LENGTH
;
77 uint64_t cipher_state
;
79 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
80 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
81 // For educational purposes only.
82 // No warranties or guarantees of any kind.
83 // This code is released into the public domain by its author.
90 #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))
91 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
92 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
93 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
94 #define bit(x,n) (((x)>>(n))&1)
95 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
96 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
97 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
99 // Single bit Hitag2 functions:
101 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
103 static const u32 ht2_f4a
= 0x2C79; // 0010 1100 0111 1001
104 static const u32 ht2_f4b
= 0x6671; // 0110 0110 0111 0001
105 static const u32 ht2_f5c
= 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
107 static u32
_f20 (const u64 x
)
111 i5
= ((ht2_f4a
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1
112 + ((ht2_f4b
>> i4 (x
, 7,11,13,14)) & 1)* 2
113 + ((ht2_f4b
>> i4 (x
,16,20,22,25)) & 1)* 4
114 + ((ht2_f4b
>> i4 (x
,27,28,30,32)) & 1)* 8
115 + ((ht2_f4a
>> i4 (x
,33,42,43,45)) & 1)*16;
117 return (ht2_f5c
>> i5
) & 1;
120 static u64
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
)
123 u64 x
= ((key
& 0xFFFF) << 32) + serial
;
125 for (i
= 0; i
< 32; i
++)
128 x
+= (u64
) (_f20 (x
) ^ (((IV
>> i
) ^ (key
>> (i
+16))) & 1)) << 47;
133 static u64
_hitag2_round (u64
*state
)
138 ((((x
>> 0) ^ (x
>> 2) ^ (x
>> 3) ^ (x
>> 6)
139 ^ (x
>> 7) ^ (x
>> 8) ^ (x
>> 16) ^ (x
>> 22)
140 ^ (x
>> 23) ^ (x
>> 26) ^ (x
>> 30) ^ (x
>> 41)
141 ^ (x
>> 42) ^ (x
>> 43) ^ (x
>> 46) ^ (x
>> 47)) & 1) << 47);
147 static u32
_hitag2_byte (u64
* x
)
151 for (i
= 0, c
= 0; i
< 8; i
++) c
+= (u32
) _hitag2_round (x
) << (i
^7);
155 size_t nbytes(size_t nbits
) {
156 return (nbits
/8)+((nbits
%8)>0);
159 int hitag2_reset(void)
161 tag
.state
= TAG_STATE_RESET
;
162 tag
.crypto_active
= 0;
166 int hitag2_init(void)
168 // memcpy(&tag, &resetdata, sizeof(tag));
173 static void hitag2_cipher_reset(struct hitag2_tag
*tag
, const byte_t
*iv
)
175 uint64_t key
= ((uint64_t)tag
->sectors
[2][2]) |
176 ((uint64_t)tag
->sectors
[2][3] << 8) |
177 ((uint64_t)tag
->sectors
[1][0] << 16) |
178 ((uint64_t)tag
->sectors
[1][1] << 24) |
179 ((uint64_t)tag
->sectors
[1][2] << 32) |
180 ((uint64_t)tag
->sectors
[1][3] << 40);
181 uint32_t uid
= ((uint32_t)tag
->sectors
[0][0]) |
182 ((uint32_t)tag
->sectors
[0][1] << 8) |
183 ((uint32_t)tag
->sectors
[0][2] << 16) |
184 ((uint32_t)tag
->sectors
[0][3] << 24);
185 uint32_t iv_
= (((uint32_t)(iv
[0]))) |
186 (((uint32_t)(iv
[1])) << 8) |
187 (((uint32_t)(iv
[2])) << 16) |
188 (((uint32_t)(iv
[3])) << 24);
189 tag
->cs
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
));
192 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t
*authenticator_is
)
194 byte_t authenticator_should
[4];
195 authenticator_should
[0] = ~_hitag2_byte(cs
);
196 authenticator_should
[1] = ~_hitag2_byte(cs
);
197 authenticator_should
[2] = ~_hitag2_byte(cs
);
198 authenticator_should
[3] = ~_hitag2_byte(cs
);
199 return (memcmp(authenticator_should
, authenticator_is
, 4) == 0);
202 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t
*data
, unsigned int bytes
, unsigned int bits
)
205 for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
);
206 for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
);
210 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
211 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
212 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
213 // T0 = TIMER_CLOCK1 / 125000 = 192
216 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
217 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
219 #define HITAG_FRAME_LEN 20
220 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
221 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
222 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
223 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
224 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
225 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
226 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
227 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
228 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
230 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
231 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
232 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
233 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
235 #define HITAG_T_TAG_HALF_PERIOD 16
236 #define HITAG_T_TAG_FULL_PERIOD 32
238 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
239 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
240 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
241 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
244 static void hitag_send_bit(int bit
) {
246 // Reset clock for the next bit
247 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
249 // Fixed modulation, earlier proxmark version used inverted signal
251 // Manchester: Unloaded, then loaded |__--|
253 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
255 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
257 // Manchester: Loaded, then unloaded |--__|
259 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
261 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
266 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
)
268 // Send start of frame
269 for(size_t i
=0; i
<5; i
++) {
273 // Send the content of the frame
274 for(size_t i
=0; i
<frame_len
; i
++) {
275 hitag_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
278 // Drop the modulation
282 void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
284 byte_t rx_air
[HITAG_FRAME_LEN
];
286 // Copy the (original) received frame how it is send over the air
287 memcpy(rx_air
,rx
,nbytes(rxlen
));
289 if(tag
.crypto_active
) {
290 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen
%8);
293 // Reset the transmission frame length
296 // Try to find out which command was send by selecting on length (in bits)
298 // Received 11000 from the reader, request for UID, send UID
300 // Always send over the air in the clear plaintext mode
301 if(rx_air
[0] != 0xC0) {
306 memcpy(tx
,tag
.sectors
[0],4);
307 tag
.crypto_active
= 0;
311 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
313 unsigned int sector
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07);
314 // Verify complement of sector index
315 if(sector
!= ((rx
[0]>>3)&0x07)) {
316 //DbpString("Transmission error (read/write)");
320 switch (rx
[0] & 0xC6) {
321 // Read command: 11xx x00y
323 memcpy(tx
,tag
.sectors
[sector
],4);
327 // Inverted Read command: 01xx x10y
329 for (size_t i
=0; i
<4; i
++) {
330 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
335 // Write command: 10xx x01y
337 // Prepare write, acknowledge by repeating command
338 memcpy(tx
,rx
,nbytes(rxlen
));
340 tag
.active_sector
= sector
;
341 tag
.state
=TAG_STATE_WRITING
;
346 Dbprintf("Uknown command: %02x %02x",rx
[0],rx
[1]);
353 // Writing data or Reader password
355 if(tag
.state
== TAG_STATE_WRITING
) {
356 // These are the sector contents to be written. We don't have to do anything else.
357 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
));
358 tag
.state
=TAG_STATE_RESET
;
361 // Received RWD password, respond with configuration and our password
362 if(memcmp(rx
,tag
.sectors
[1],4) != 0) {
363 DbpString("Reader password is wrong");
367 memcpy(tx
,tag
.sectors
[3],4);
372 // Received RWD authentication challenge and respnse
374 // Store the authentication attempt
375 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
376 memcpy(auth_table
+auth_table_len
,rx
,8);
380 // Reset the cipher state
381 hitag2_cipher_reset(&tag
,rx
);
382 // Check if the authentication was correct
383 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) {
384 // The reader failed to authenticate, do nothing
385 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]);
388 // Succesful, but commented out reporting back to the Host, this may delay to much.
389 // 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]);
391 // Activate encryption algorithm for all further communication
392 tag
.crypto_active
= 1;
394 // Use the tag password as response
395 memcpy(tx
,tag
.sectors
[3],4);
401 // LogTrace(rx,nbytes(rxlen),0,0,false);
402 // LogTrace(tx,nbytes(*txlen),0,0,true);
404 if(tag
.crypto_active
) {
405 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen
%8);
409 static void hitag_reader_send_bit(int bit
) {
411 // Reset clock for the next bit
412 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
414 // Binary puls length modulation (BPLM) is used to encode the data stream
415 // This means that a transmission of a one takes longer than that of a zero
417 // Enable modulation, which means, drop the the field
420 // Wait for 4-10 times the carrier period
421 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
424 // Disable modulation, just activates the field again
429 while(AT91C_BASE_TC0
->TC_CV
< T0
*22);
430 // SpinDelayUs(16*8);
433 while(AT91C_BASE_TC0
->TC_CV
< T0
*28);
434 // SpinDelayUs(22*8);
439 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
)
441 // Send the content of the frame
442 for(size_t i
=0; i
<frame_len
; i
++) {
443 hitag_reader_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
446 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
447 // Enable modulation, which means, drop the the field
449 // Wait for 4-10 times the carrier period
450 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
451 // Disable modulation, just activates the field again
457 bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
458 // Reset the transmission frame length
461 // Try to find out which command was send by selecting on length (in bits)
463 // No answer, try to resurrect
465 // Stop if there is no answer (after sending password)
467 DbpString("Password failed!");
471 memcpy(tx
,"\xc0",nbytes(*txlen
));
474 // Received UID, tag password
478 memcpy(tx
,password
,4);
482 DbpString("Read succesful!");
483 // We are done... for now
487 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
488 tx
[1] = ((blocknr
^7) << 6);
493 // Unexpected response
495 Dbprintf("Uknown frame length: %d",rxlen
);
502 bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
503 // Reset the transmission frame length
507 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen
%8);
510 // Try to find out which command was send by selecting on length (in bits)
512 // No answer, try to resurrect
514 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
516 DbpString("Authentication failed!");
520 memcpy(tx
,"\xc0",nbytes(*txlen
));
523 // Received UID, crypto tag answer
526 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;
527 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
528 cipher_state
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0);
531 hitag2_cipher_transcrypt(&cipher_state
,tx
+4,4,0);
534 bAuthenticating
= true;
536 // Check if we received answer tag (at)
537 if (bAuthenticating
) {
538 bAuthenticating
= false;
540 // Store the received block
541 memcpy(tag
.sectors
[blocknr
],rx
,4);
545 DbpString("Read succesful!");
546 // We are done... for now
550 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
551 tx
[1] = ((blocknr
^7) << 6);
555 // Unexpected response
557 Dbprintf("Uknown frame length: %d",rxlen
);
564 // We have to return now to avoid double encryption
565 if (!bAuthenticating
) {
566 hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen
%8);
574 bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
575 // Reset the transmission frame length
578 // Try to find out which command was send by selecting on length (in bits)
580 // No answer, try to resurrect
582 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
584 DbpString("Authentication failed!");
588 memcpy(tx
,"\xc0",nbytes(*txlen
));
591 // Received UID, crypto tag answer
598 DbpString("Authentication succesful!");
599 // We are done... for now
604 // Unexpected response
606 Dbprintf("Uknown frame length: %d",rxlen
);
614 bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
615 // Reset the transmission frame length
618 // Try to find out which command was send by selecting on length (in bits)
620 // No answer, try to resurrect
622 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
624 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]);
626 if ((auth_table_pos
+8) == auth_table_len
) {
630 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
633 memcpy(tx
,"\xc0",nbytes(*txlen
));
636 // Received UID, crypto tag answer, or read block response
643 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]);
645 if ((auth_table_pos
+8) == auth_table_len
) {
649 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
654 Dbprintf("Uknown frame length: %d",rxlen
);
662 void SnoopHitag(uint32_t type
) {
671 byte_t rx
[HITAG_FRAME_LEN
];
674 // Clean up trace and prepare it for storing frames
675 iso14a_set_tracing(TRUE
);
676 iso14a_clear_trace();
680 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
682 DbpString("Starting Hitag2 snoop");
685 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
686 // and analog mux selection.
687 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
688 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
689 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
692 // Configure output pin that is connected to the FPGA (for modulating)
693 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
694 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
696 // Disable modulation, we are going to eavesdrop, not modulate ;)
699 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
700 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
701 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
703 // Disable timer during configuration
704 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
706 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
707 // external trigger rising edge, load RA on rising edge of TIOA.
708 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
709 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
711 // Enable and reset counter
712 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
714 // Reset the received frame, frame count and timing info
715 memset(rx
,0x00,sizeof(rx
));
719 reader_frame
= false;
724 while(!BUTTON_PRESS()) {
728 // Receive frame, watch for at most T0*EOF periods
729 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
730 // Check if rising edge in modulation is detected
731 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
732 // Retrieve the new timing values
733 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
735 // Find out if we are dealing with a rising or falling edge
736 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
738 // Shorter periods will only happen with reader frames
739 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
740 // Switch from tag to reader capture
743 memset(rx
,0x00,sizeof(rx
));
747 // Only handle if reader frame and rising edge, or tag frame and falling edge
748 if (reader_frame
!= rising_edge
) {
753 // Add the buffered timing values of earlier captured edges which were skipped
759 // Capture reader frame
760 if(ra
>= HITAG_T_STOP
) {
762 //DbpString("wierd0?");
764 // Capture the T0 periods that have passed since last communication or field drop (reset)
765 response
= (ra
- HITAG_T_LOW
);
766 } else if(ra
>= HITAG_T_1_MIN
) {
768 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
770 } else if(ra
>= HITAG_T_0_MIN
) {
772 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
775 // Ignore wierd value, is to small to mean anything
779 // Capture tag frame (manchester decoding using only falling edges)
780 if(ra
>= HITAG_T_EOF
) {
782 //DbpString("wierd1?");
784 // Capture the T0 periods that have passed since last communication or field drop (reset)
785 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
786 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
787 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
788 // Manchester coding example |-_|_-|-_| (101)
789 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
791 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
793 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
794 // Manchester coding example |_-|...|_-|-_| (0...01)
795 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
797 // We have to skip this half period at start and add the 'one' the second time
799 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
804 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
805 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
807 // Ignore bits that are transmitted during SOF
810 // bit is same as last bit
811 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
815 // Ignore wierd value, is to small to mean anything
821 // Check if frame was captured
824 if (!LogTrace(rx
,nbytes(rxlen
),response
,0,reader_frame
)) {
825 DbpString("Trace full");
829 // Check if we recognize a valid authentication attempt
830 if (nbytes(rxlen
) == 8) {
831 // Store the authentication attempt
832 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
833 memcpy(auth_table
+auth_table_len
,rx
,8);
838 // Reset the received frame and response timing info
839 memset(rx
,0x00,sizeof(rx
));
841 reader_frame
= false;
850 // Save the timer overflow, will be 0 when frame was received
851 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
853 // Reset the frame length
855 // Reset the timer to restart while-loop that receives frames
856 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
862 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
863 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
864 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
867 // Dbprintf("frame received: %d",frame_count);
868 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
869 // DbpString("All done");
872 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
876 byte_t rx
[HITAG_FRAME_LEN
];
878 byte_t tx
[HITAG_FRAME_LEN
];
880 bool bQuitTraceFull
= false;
883 // Clean up trace and prepare it for storing frames
884 iso14a_set_tracing(TRUE
);
885 iso14a_clear_trace();
888 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
890 DbpString("Starting Hitag2 simulation");
894 if (tag_mem_supplied
) {
895 DbpString("Loading hitag2 memory...");
896 memcpy((byte_t
*)tag
.sectors
,data
,48);
900 for (size_t i
=0; i
<12; i
++) {
901 for (size_t j
=0; j
<4; j
++) {
903 block
|= tag
.sectors
[i
][j
];
905 Dbprintf("| %d | %08x |",i
,block
);
908 // Set up simulator mode, frequency divisor which will drive the FPGA
909 // and analog mux selection.
910 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
911 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
912 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
915 // Configure output pin that is connected to the FPGA (for modulating)
916 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
917 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
919 // Disable modulation at default, which means release resistance
922 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
923 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
925 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
926 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
927 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
929 // Disable timer during configuration
930 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
932 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
933 // external trigger rising edge, load RA on rising edge of TIOA.
934 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
936 // Enable and reset counter
937 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
939 // Reset the received frame, frame count and timing info
940 memset(rx
,0x00,sizeof(rx
));
945 while(!BUTTON_PRESS()) {
949 // Receive frame, watch for at most T0*EOF periods
950 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
951 // Check if rising edge in modulation is detected
952 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
953 // Retrieve the new timing values
954 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
957 // Reset timer every frame, we have to capture the last edge for timing
958 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
962 // Capture reader frame
963 if(ra
>= HITAG_T_STOP
) {
965 //DbpString("wierd0?");
967 // Capture the T0 periods that have passed since last communication or field drop (reset)
968 response
= (ra
- HITAG_T_LOW
);
969 } else if(ra
>= HITAG_T_1_MIN
) {
971 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
973 } else if(ra
>= HITAG_T_0_MIN
) {
975 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
978 // Ignore wierd value, is to small to mean anything
983 // Check if frame was captured
987 if (!LogTrace(rx
,nbytes(rxlen
),response
,0,true)) {
988 DbpString("Trace full");
989 if (bQuitTraceFull
) {
997 // Disable timer 1 with external trigger to avoid triggers during our own modulation
998 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1000 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1001 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1003 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1004 // not that since the clock counts since the rising edge, but T_Wait1 is
1005 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1006 // periods. The gap time T_Low varies (4..10). All timer values are in
1007 // terms of T0 units
1008 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1010 // Send and store the tag answer (if there is any)
1012 // Transmit the tag frame
1013 hitag_send_frame(tx
,txlen
);
1014 // Store the frame in the trace
1016 if (!LogTrace(tx
,nbytes(txlen
),0,0,false)) {
1017 DbpString("Trace full");
1018 if (bQuitTraceFull
) {
1027 // Reset the received frame and response timing info
1028 memset(rx
,0x00,sizeof(rx
));
1031 // Enable and reset external trigger in timer for capturing future frames
1032 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1035 // Reset the frame length
1037 // Save the timer overflow, will be 0 when frame was received
1038 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1039 // Reset the timer to restart while-loop that receives frames
1040 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1044 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1045 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1046 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1047 // Dbprintf("frame received: %d",frame_count);
1048 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1049 // DbpString("All done");
1052 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1055 byte_t rx
[HITAG_FRAME_LEN
];
1057 byte_t txbuf
[HITAG_FRAME_LEN
];
1064 int t_wait
= HITAG_T_WAIT_MAX
;
1066 bool bQuitTraceFull
= false;
1068 // Clean up trace and prepare it for storing frames
1069 iso14a_set_tracing(TRUE
);
1070 iso14a_clear_trace();
1071 DbpString("Starting Hitag reader family");
1073 // Check configuration
1075 case RHT2F_PASSWORD
: {
1076 Dbprintf("List identifier in password mode");
1077 memcpy(password
,htd
->pwd
.password
,4);
1079 bQuitTraceFull
= false;
1084 case RHT2F_AUTHENTICATE
: {
1085 DbpString("Authenticating using nr,ar pair:");
1086 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1087 Dbhexdump(8,NrAr
,false);
1090 bAuthenticating
= false;
1091 bQuitTraceFull
= true;
1094 case RHT2F_CRYPTO
: {
1095 DbpString("Authenticating using key:");
1096 memcpy(key
,htd
->crypto
.key
,6);
1097 Dbhexdump(6,key
,false);
1101 bAuthenticating
= false;
1102 bQuitTraceFull
= true;
1105 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1106 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1108 memcpy(NrAr
,auth_table
,8);
1109 bQuitTraceFull
= false;
1115 Dbprintf("Error, unknown function: %d",htf
);
1123 // Configure output and enable pin that is connected to the FPGA (for modulating)
1124 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1125 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1127 // Set fpga in edge detect with reader field, we can modulate as reader now
1128 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1130 // Set Frequency divisor which will drive the FPGA and analog mux selection
1131 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1132 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1135 // Disable modulation at default, which means enable the field
1138 // Give it a bit of time for the resonant antenna to settle.
1141 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1142 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1144 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1145 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1146 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1148 // Disable timer during configuration
1149 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1151 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1152 // external trigger rising edge, load RA on falling edge of TIOA.
1153 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1155 // Enable and reset counters
1156 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1157 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1159 // Reset the received frame, frame count and timing info
1165 // Tag specific configuration settings (sof, timings, etc.)
1170 DbpString("Configured for hitagS reader");
1171 } else if (htf
< 20) {
1175 DbpString("Configured for hitag1 reader");
1176 } else if (htf
< 30) {
1179 t_wait
= HITAG_T_WAIT_2
;
1180 DbpString("Configured for hitag2 reader");
1182 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1186 while(!bStop
&& !BUTTON_PRESS()) {
1190 // Check if frame was captured and store it
1194 if (!LogTrace(rx
,nbytes(rxlen
),response
,0,false)) {
1195 DbpString("Trace full");
1196 if (bQuitTraceFull
) {
1205 // By default reset the transmission buffer
1208 case RHT2F_PASSWORD
: {
1209 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1211 case RHT2F_AUTHENTICATE
: {
1212 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1214 case RHT2F_CRYPTO
: {
1215 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
);
1217 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1218 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1221 Dbprintf("Error, unknown function: %d",htf
);
1226 // Send and store the reader command
1227 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1228 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1230 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1231 // Since the clock counts since the last falling edge, a 'one' means that the
1232 // falling edge occured halfway the period. with respect to this falling edge,
1233 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1234 // All timer values are in terms of T0 units
1235 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1237 // Transmit the reader frame
1238 hitag_reader_send_frame(tx
,txlen
);
1240 // Enable and reset external trigger in timer for capturing future frames
1241 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1243 // Add transmitted frame to total count
1247 // Store the frame in the trace
1248 if (!LogTrace(tx
,nbytes(txlen
),HITAG_T_WAIT_2
,0,true)) {
1249 if (bQuitTraceFull
) {
1258 // Reset values for receiving frames
1259 memset(rx
,0x00,sizeof(rx
));
1263 tag_sof
= reset_sof
;
1266 // Receive frame, watch for at most T0*EOF periods
1267 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1268 // Check if falling edge in tag modulation is detected
1269 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1270 // Retrieve the new timing values
1271 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1273 // Reset timer every frame, we have to capture the last edge for timing
1274 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1278 // Capture tag frame (manchester decoding using only falling edges)
1279 if(ra
>= HITAG_T_EOF
) {
1281 //DbpString("wierd1?");
1283 // Capture the T0 periods that have passed since last communication or field drop (reset)
1284 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1285 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1286 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1287 // Manchester coding example |-_|_-|-_| (101)
1288 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1290 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1292 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1293 // Manchester coding example |_-|...|_-|-_| (0...01)
1294 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1296 // We have to skip this half period at start and add the 'one' the second time
1298 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1303 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1304 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1306 // Ignore bits that are transmitted during SOF
1309 // bit is same as last bit
1310 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1314 // Ignore wierd value, is to small to mean anything
1318 // We can break this loop if we received the last bit from a frame
1319 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1326 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1327 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1328 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1330 // Dbprintf("frame received: %d",frame_count);
1331 // DbpString("All done");