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"
32 int LogTraceHitag(const uint8_t * btBytes
, int iBits
, int iSamples
, uint32_t dwParity
, int bReader
)
34 // Return when trace is full
35 if (traceLen
>= TRACE_SIZE
) return FALSE
;
37 // Trace the random, i'm curious
39 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
40 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
41 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
42 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
44 trace
[traceLen
- 1] |= 0x80;
46 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
47 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
48 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
49 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
50 trace
[traceLen
++] = iBits
;
51 memcpy(trace
+ traceLen
, btBytes
, nbytes(iBits
));
52 traceLen
+= nbytes(iBits
);
59 TAG_STATE_RESET
= 0x01, // Just powered up, awaiting GetSnr
60 TAG_STATE_ACTIVATING
= 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
61 TAG_STATE_ACTIVATED
= 0x03, // Activation complete, awaiting read/write commands
62 TAG_STATE_WRITING
= 0x04, // In write command, awaiting sector contents to be written
64 unsigned int active_sector
;
67 byte_t sectors
[12][4];
70 static struct hitag2_tag tag
= {
71 .state
= TAG_STATE_RESET
,
72 .sectors
= { // Password mode: | Crypto mode:
73 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
74 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
75 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
76 [3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
77 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
78 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
79 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
80 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
81 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
82 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
83 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
84 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
88 //#define TRACE_LENGTH 3000
89 //uint8_t *trace = (uint8_t *) BigBuf;
93 #define AUTH_TABLE_OFFSET FREE_BUFFER_OFFSET
94 #define AUTH_TABLE_LENGTH FREE_BUFFER_SIZE
95 byte_t
* auth_table
= (byte_t
*)BigBuf
+AUTH_TABLE_OFFSET
;
96 size_t auth_table_pos
= 0;
97 size_t auth_table_len
= AUTH_TABLE_LENGTH
;
102 uint64_t cipher_state
;
104 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
105 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
106 // For educational purposes only.
107 // No warranties or guarantees of any kind.
108 // This code is released into the public domain by its author.
115 #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))
116 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
117 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
118 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
119 #define bit(x,n) (((x)>>(n))&1)
120 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
121 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
122 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
124 // Single bit Hitag2 functions:
126 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
128 static const u32 ht2_f4a
= 0x2C79; // 0010 1100 0111 1001
129 static const u32 ht2_f4b
= 0x6671; // 0110 0110 0111 0001
130 static const u32 ht2_f5c
= 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
132 static u32
_f20 (const u64 x
)
136 i5
= ((ht2_f4a
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1
137 + ((ht2_f4b
>> i4 (x
, 7,11,13,14)) & 1)* 2
138 + ((ht2_f4b
>> i4 (x
,16,20,22,25)) & 1)* 4
139 + ((ht2_f4b
>> i4 (x
,27,28,30,32)) & 1)* 8
140 + ((ht2_f4a
>> i4 (x
,33,42,43,45)) & 1)*16;
142 return (ht2_f5c
>> i5
) & 1;
145 static u64
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
)
148 u64 x
= ((key
& 0xFFFF) << 32) + serial
;
150 for (i
= 0; i
< 32; i
++)
153 x
+= (u64
) (_f20 (x
) ^ (((IV
>> i
) ^ (key
>> (i
+16))) & 1)) << 47;
158 static u64
_hitag2_round (u64
*state
)
163 ((((x
>> 0) ^ (x
>> 2) ^ (x
>> 3) ^ (x
>> 6)
164 ^ (x
>> 7) ^ (x
>> 8) ^ (x
>> 16) ^ (x
>> 22)
165 ^ (x
>> 23) ^ (x
>> 26) ^ (x
>> 30) ^ (x
>> 41)
166 ^ (x
>> 42) ^ (x
>> 43) ^ (x
>> 46) ^ (x
>> 47)) & 1) << 47);
172 static u32
_hitag2_byte (u64
* x
)
176 for (i
= 0, c
= 0; i
< 8; i
++) c
+= (u32
) _hitag2_round (x
) << (i
^7);
180 int hitag2_reset(void)
182 tag
.state
= TAG_STATE_RESET
;
183 tag
.crypto_active
= 0;
187 int hitag2_init(void)
189 // memcpy(&tag, &resetdata, sizeof(tag));
194 static void hitag2_cipher_reset(struct hitag2_tag
*tag
, const byte_t
*iv
)
196 uint64_t key
= ((uint64_t)tag
->sectors
[2][2]) |
197 ((uint64_t)tag
->sectors
[2][3] << 8) |
198 ((uint64_t)tag
->sectors
[1][0] << 16) |
199 ((uint64_t)tag
->sectors
[1][1] << 24) |
200 ((uint64_t)tag
->sectors
[1][2] << 32) |
201 ((uint64_t)tag
->sectors
[1][3] << 40);
202 uint32_t uid
= ((uint32_t)tag
->sectors
[0][0]) |
203 ((uint32_t)tag
->sectors
[0][1] << 8) |
204 ((uint32_t)tag
->sectors
[0][2] << 16) |
205 ((uint32_t)tag
->sectors
[0][3] << 24);
206 uint32_t iv_
= (((uint32_t)(iv
[0]))) |
207 (((uint32_t)(iv
[1])) << 8) |
208 (((uint32_t)(iv
[2])) << 16) |
209 (((uint32_t)(iv
[3])) << 24);
210 tag
->cs
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
));
213 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t
*authenticator_is
)
215 byte_t authenticator_should
[4];
216 authenticator_should
[0] = ~_hitag2_byte(cs
);
217 authenticator_should
[1] = ~_hitag2_byte(cs
);
218 authenticator_should
[2] = ~_hitag2_byte(cs
);
219 authenticator_should
[3] = ~_hitag2_byte(cs
);
220 return (memcmp(authenticator_should
, authenticator_is
, 4) == 0);
223 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t
*data
, unsigned int bytes
, unsigned int bits
)
226 for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
);
227 for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
);
231 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
232 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
233 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
234 // T0 = TIMER_CLOCK1 / 125000 = 192
237 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
238 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
240 #define HITAG_FRAME_LEN 20
241 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
242 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
243 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
244 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
245 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
246 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
247 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
248 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
249 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
251 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
252 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
253 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
254 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
256 #define HITAG_T_TAG_HALF_PERIOD 16
257 #define HITAG_T_TAG_FULL_PERIOD 32
259 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
260 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
261 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
262 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
265 static void hitag_send_bit(int bit
) {
267 // Reset clock for the next bit
268 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
270 // Fixed modulation, earlier proxmark version used inverted signal
272 // Manchester: Unloaded, then loaded |__--|
274 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
276 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
278 // Manchester: Loaded, then unloaded |--__|
280 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
282 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
287 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
)
289 // Send start of frame
290 for(size_t i
=0; i
<5; i
++) {
294 // Send the content of the frame
295 for(size_t i
=0; i
<frame_len
; i
++) {
296 hitag_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
299 // Drop the modulation
303 void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
305 byte_t rx_air
[HITAG_FRAME_LEN
];
307 // Copy the (original) received frame how it is send over the air
308 memcpy(rx_air
,rx
,nbytes(rxlen
));
310 if(tag
.crypto_active
) {
311 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen
%8);
314 // Reset the transmission frame length
317 // Try to find out which command was send by selecting on length (in bits)
319 // Received 11000 from the reader, request for UID, send UID
321 // Always send over the air in the clear plaintext mode
322 if(rx_air
[0] != 0xC0) {
327 memcpy(tx
,tag
.sectors
[0],4);
328 tag
.crypto_active
= 0;
332 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
334 unsigned int sector
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07);
335 // Verify complement of sector index
336 if(sector
!= ((rx
[0]>>3)&0x07)) {
337 //DbpString("Transmission error (read/write)");
341 switch (rx
[0] & 0xC6) {
342 // Read command: 11xx x00y
344 memcpy(tx
,tag
.sectors
[sector
],4);
348 // Inverted Read command: 01xx x10y
350 for (size_t i
=0; i
<4; i
++) {
351 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
356 // Write command: 10xx x01y
358 // Prepare write, acknowledge by repeating command
359 memcpy(tx
,rx
,nbytes(rxlen
));
361 tag
.active_sector
= sector
;
362 tag
.state
=TAG_STATE_WRITING
;
367 Dbprintf("Uknown command: %02x %02x",rx
[0],rx
[1]);
374 // Writing data or Reader password
376 if(tag
.state
== TAG_STATE_WRITING
) {
377 // These are the sector contents to be written. We don't have to do anything else.
378 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
));
379 tag
.state
=TAG_STATE_RESET
;
382 // Received RWD password, respond with configuration and our password
383 if(memcmp(rx
,tag
.sectors
[1],4) != 0) {
384 DbpString("Reader password is wrong");
388 memcpy(tx
,tag
.sectors
[3],4);
393 // Received RWD authentication challenge and respnse
395 // Store the authentication attempt
396 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
397 memcpy(auth_table
+auth_table_len
,rx
,8);
401 // Reset the cipher state
402 hitag2_cipher_reset(&tag
,rx
);
403 // Check if the authentication was correct
404 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) {
405 // The reader failed to authenticate, do nothing
406 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]);
409 // Succesful, but commented out reporting back to the Host, this may delay to much.
410 // 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]);
412 // Activate encryption algorithm for all further communication
413 tag
.crypto_active
= 1;
415 // Use the tag password as response
416 memcpy(tx
,tag
.sectors
[3],4);
422 // LogTraceHitag(rx,rxlen,0,0,false);
423 // LogTraceHitag(tx,*txlen,0,0,true);
425 if(tag
.crypto_active
) {
426 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen
%8);
430 static void hitag_reader_send_bit(int bit
) {
432 // Reset clock for the next bit
433 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
435 // Binary puls length modulation (BPLM) is used to encode the data stream
436 // This means that a transmission of a one takes longer than that of a zero
438 // Enable modulation, which means, drop the the field
441 // Wait for 4-10 times the carrier period
442 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
445 // Disable modulation, just activates the field again
450 while(AT91C_BASE_TC0
->TC_CV
< T0
*22);
451 // SpinDelayUs(16*8);
454 while(AT91C_BASE_TC0
->TC_CV
< T0
*28);
455 // SpinDelayUs(22*8);
460 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
)
462 // Send the content of the frame
463 for(size_t i
=0; i
<frame_len
; i
++) {
464 hitag_reader_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
467 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
468 // Enable modulation, which means, drop the the field
470 // Wait for 4-10 times the carrier period
471 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
472 // Disable modulation, just activates the field again
478 bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
479 // Reset the transmission frame length
482 // Try to find out which command was send by selecting on length (in bits)
484 // No answer, try to resurrect
486 // Stop if there is no answer (after sending password)
488 DbpString("Password failed!");
492 memcpy(tx
,"\xc0",nbytes(*txlen
));
495 // Received UID, tag password
499 memcpy(tx
,password
,4);
501 memcpy(tag
.sectors
[blocknr
],rx
,4);
506 //store password in block1, the TAG answers with Block3, but we need the password in memory
507 memcpy(tag
.sectors
[blocknr
],tx
,4);
509 memcpy(tag
.sectors
[blocknr
],rx
,4);
514 DbpString("Read succesful!");
519 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
520 tx
[1] = ((blocknr
^7) << 6);
524 // Unexpected response
526 Dbprintf("Uknown frame length: %d",rxlen
);
533 bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
534 // Reset the transmission frame length
538 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen
%8);
541 // Try to find out which command was send by selecting on length (in bits)
543 // No answer, try to resurrect
545 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
547 // Failed during authentication
548 if (bAuthenticating
) {
549 DbpString("Authentication failed!");
552 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
554 // Write the low part of the key in memory
555 memcpy(tag
.sectors
[1],key
+2,4);
556 } else if (blocknr
== 2) {
557 // Write the high part of the key in memory
558 tag
.sectors
[2][0] = 0x00;
559 tag
.sectors
[2][1] = 0x00;
560 tag
.sectors
[2][2] = key
[0];
561 tag
.sectors
[2][3] = key
[1];
563 // Just put zero's in the memory (of the unreadable block)
564 memset(tag
.sectors
[blocknr
],0x00,4);
571 memcpy(tx
,"\xc0",nbytes(*txlen
));
575 // Received UID, crypto tag answer
578 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;
579 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
580 cipher_state
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0);
583 hitag2_cipher_transcrypt(&cipher_state
,tx
+4,4,0);
586 bAuthenticating
= true;
588 // Check if we received answer tag (at)
589 if (bAuthenticating
) {
590 bAuthenticating
= false;
592 // Store the received block
593 memcpy(tag
.sectors
[blocknr
],rx
,4);
597 DbpString("Read succesful!");
602 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
603 tx
[1] = ((blocknr
^7) << 6);
607 // Unexpected response
609 Dbprintf("Uknown frame length: %d",rxlen
);
616 // We have to return now to avoid double encryption
617 if (!bAuthenticating
) {
618 hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen
%8);
626 bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
627 // Reset the transmission frame length
630 // Try to find out which command was send by selecting on length (in bits)
632 // No answer, try to resurrect
634 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
636 DbpString("Authentication failed!");
640 memcpy(tx
,"\xc0",nbytes(*txlen
));
643 // Received UID, crypto tag answer
650 DbpString("Authentication succesful!");
651 // We are done... for now
656 // Unexpected response
658 Dbprintf("Uknown frame length: %d",rxlen
);
666 bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
667 // Reset the transmission frame length
670 // Try to find out which command was send by selecting on length (in bits)
672 // No answer, try to resurrect
674 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
676 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]);
678 // Removing failed entry from authentiations table
679 memcpy(auth_table
+auth_table_pos
,auth_table
+auth_table_pos
+8,8);
682 // Return if we reached the end of the authentiactions table
684 if (auth_table_pos
== auth_table_len
) {
688 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
689 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
692 memcpy(tx
,"\xc0",nbytes(*txlen
));
695 // Received UID, crypto tag answer, or read block response
702 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]);
704 if ((auth_table_pos
+8) == auth_table_len
) {
708 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
713 Dbprintf("Uknown frame length: %d",rxlen
);
721 void SnoopHitag(uint32_t type
) {
730 byte_t rx
[HITAG_FRAME_LEN
];
733 // Clean up trace and prepare it for storing frames
734 iso14a_set_tracing(TRUE
);
735 iso14a_clear_trace();
739 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
741 DbpString("Starting Hitag2 snoop");
744 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
745 // and analog mux selection.
746 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
747 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
748 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
751 // Configure output pin that is connected to the FPGA (for modulating)
752 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
753 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
755 // Disable modulation, we are going to eavesdrop, not modulate ;)
758 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
759 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
760 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
762 // Disable timer during configuration
763 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
765 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
766 // external trigger rising edge, load RA on rising edge of TIOA.
767 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
768 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
770 // Enable and reset counter
771 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
773 // Reset the received frame, frame count and timing info
774 memset(rx
,0x00,sizeof(rx
));
778 reader_frame
= false;
783 while(!BUTTON_PRESS()) {
787 // Receive frame, watch for at most T0*EOF periods
788 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
789 // Check if rising edge in modulation is detected
790 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
791 // Retrieve the new timing values
792 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
794 // Find out if we are dealing with a rising or falling edge
795 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
797 // Shorter periods will only happen with reader frames
798 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
799 // Switch from tag to reader capture
802 memset(rx
,0x00,sizeof(rx
));
806 // Only handle if reader frame and rising edge, or tag frame and falling edge
807 if (reader_frame
!= rising_edge
) {
812 // Add the buffered timing values of earlier captured edges which were skipped
818 // Capture reader frame
819 if(ra
>= HITAG_T_STOP
) {
821 //DbpString("wierd0?");
823 // Capture the T0 periods that have passed since last communication or field drop (reset)
824 response
= (ra
- HITAG_T_LOW
);
825 } else if(ra
>= HITAG_T_1_MIN
) {
827 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
829 } else if(ra
>= HITAG_T_0_MIN
) {
831 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
834 // Ignore wierd value, is to small to mean anything
838 // Capture tag frame (manchester decoding using only falling edges)
839 if(ra
>= HITAG_T_EOF
) {
841 //DbpString("wierd1?");
843 // Capture the T0 periods that have passed since last communication or field drop (reset)
844 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
845 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
846 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
847 // Manchester coding example |-_|_-|-_| (101)
848 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
850 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
852 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
853 // Manchester coding example |_-|...|_-|-_| (0...01)
854 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
856 // We have to skip this half period at start and add the 'one' the second time
858 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
863 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
864 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
866 // Ignore bits that are transmitted during SOF
869 // bit is same as last bit
870 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
874 // Ignore wierd value, is to small to mean anything
880 // Check if frame was captured
883 if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) {
884 DbpString("Trace full");
888 // Check if we recognize a valid authentication attempt
889 if (nbytes(rxlen
) == 8) {
890 // Store the authentication attempt
891 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
892 memcpy(auth_table
+auth_table_len
,rx
,8);
897 // Reset the received frame and response timing info
898 memset(rx
,0x00,sizeof(rx
));
900 reader_frame
= false;
909 // Save the timer overflow, will be 0 when frame was received
910 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
912 // Reset the frame length
914 // Reset the timer to restart while-loop that receives frames
915 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
921 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
922 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
923 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
926 // Dbprintf("frame received: %d",frame_count);
927 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
928 // DbpString("All done");
931 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
935 byte_t rx
[HITAG_FRAME_LEN
];
937 byte_t tx
[HITAG_FRAME_LEN
];
939 bool bQuitTraceFull
= false;
942 // Clean up trace and prepare it for storing frames
943 iso14a_set_tracing(TRUE
);
944 iso14a_clear_trace();
947 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
949 DbpString("Starting Hitag2 simulation");
953 if (tag_mem_supplied
) {
954 DbpString("Loading hitag2 memory...");
955 memcpy((byte_t
*)tag
.sectors
,data
,48);
959 for (size_t i
=0; i
<12; i
++) {
960 for (size_t j
=0; j
<4; j
++) {
962 block
|= tag
.sectors
[i
][j
];
964 Dbprintf("| %d | %08x |",i
,block
);
967 // Set up simulator mode, frequency divisor which will drive the FPGA
968 // and analog mux selection.
969 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
970 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
971 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
974 // Configure output pin that is connected to the FPGA (for modulating)
975 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
976 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
978 // Disable modulation at default, which means release resistance
981 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
982 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
984 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
985 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
986 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
988 // Disable timer during configuration
989 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
991 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
992 // external trigger rising edge, load RA on rising edge of TIOA.
993 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
995 // Enable and reset counter
996 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
998 // Reset the received frame, frame count and timing info
999 memset(rx
,0x00,sizeof(rx
));
1004 while(!BUTTON_PRESS()) {
1008 // Receive frame, watch for at most T0*EOF periods
1009 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
1010 // Check if rising edge in modulation is detected
1011 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1012 // Retrieve the new timing values
1013 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
1016 // Reset timer every frame, we have to capture the last edge for timing
1017 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1021 // Capture reader frame
1022 if(ra
>= HITAG_T_STOP
) {
1024 //DbpString("wierd0?");
1026 // Capture the T0 periods that have passed since last communication or field drop (reset)
1027 response
= (ra
- HITAG_T_LOW
);
1028 } else if(ra
>= HITAG_T_1_MIN
) {
1030 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1032 } else if(ra
>= HITAG_T_0_MIN
) {
1034 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1037 // Ignore wierd value, is to small to mean anything
1042 // Check if frame was captured
1046 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) {
1047 DbpString("Trace full");
1048 if (bQuitTraceFull
) {
1056 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1057 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1059 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1060 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1062 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1063 // not that since the clock counts since the rising edge, but T_Wait1 is
1064 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1065 // periods. The gap time T_Low varies (4..10). All timer values are in
1066 // terms of T0 units
1067 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1069 // Send and store the tag answer (if there is any)
1071 // Transmit the tag frame
1072 hitag_send_frame(tx
,txlen
);
1073 // Store the frame in the trace
1075 if (!LogTraceHitag(tx
,txlen
,0,0,false)) {
1076 DbpString("Trace full");
1077 if (bQuitTraceFull
) {
1086 // Reset the received frame and response timing info
1087 memset(rx
,0x00,sizeof(rx
));
1090 // Enable and reset external trigger in timer for capturing future frames
1091 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1094 // Reset the frame length
1096 // Save the timer overflow, will be 0 when frame was received
1097 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1098 // Reset the timer to restart while-loop that receives frames
1099 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1103 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1104 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1105 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1106 // Dbprintf("frame received: %d",frame_count);
1107 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1108 // DbpString("All done");
1111 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1114 byte_t rx
[HITAG_FRAME_LEN
];
1116 byte_t txbuf
[HITAG_FRAME_LEN
];
1123 int t_wait
= HITAG_T_WAIT_MAX
;
1125 bool bQuitTraceFull
= false;
1127 // Reset the return status
1128 bSuccessful
= false;
1130 // Clean up trace and prepare it for storing frames
1131 iso14a_set_tracing(TRUE
);
1132 iso14a_clear_trace();
1133 DbpString("Starting Hitag reader family");
1135 // Check configuration
1137 case RHT2F_PASSWORD
: {
1138 Dbprintf("List identifier in password mode");
1139 memcpy(password
,htd
->pwd
.password
,4);
1141 bQuitTraceFull
= false;
1146 case RHT2F_AUTHENTICATE
: {
1147 DbpString("Authenticating using nr,ar pair:");
1148 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1149 Dbhexdump(8,NrAr
,false);
1152 bAuthenticating
= false;
1153 bQuitTraceFull
= true;
1156 case RHT2F_CRYPTO
: {
1157 DbpString("Authenticating using key:");
1158 memcpy(key
,htd
->crypto
.key
,6);
1159 Dbhexdump(6,key
,false);
1163 bAuthenticating
= false;
1164 bQuitTraceFull
= true;
1167 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1168 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1170 memcpy(NrAr
,auth_table
,8);
1171 bQuitTraceFull
= false;
1177 Dbprintf("Error, unknown function: %d",htf
);
1185 // Configure output and enable pin that is connected to the FPGA (for modulating)
1186 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1187 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1189 // Set fpga in edge detect with reader field, we can modulate as reader now
1190 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1192 // Set Frequency divisor which will drive the FPGA and analog mux selection
1193 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1194 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1197 // Disable modulation at default, which means enable the field
1200 // Give it a bit of time for the resonant antenna to settle.
1203 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1204 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1206 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1207 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1208 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1210 // Disable timer during configuration
1211 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1213 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1214 // external trigger rising edge, load RA on falling edge of TIOA.
1215 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1217 // Enable and reset counters
1218 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1219 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1221 // Reset the received frame, frame count and timing info
1227 // Tag specific configuration settings (sof, timings, etc.)
1232 DbpString("Configured for hitagS reader");
1233 } else if (htf
< 20) {
1237 DbpString("Configured for hitag1 reader");
1238 } else if (htf
< 30) {
1241 t_wait
= HITAG_T_WAIT_2
;
1242 DbpString("Configured for hitag2 reader");
1244 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1248 while(!bStop
&& !BUTTON_PRESS()) {
1252 // Check if frame was captured and store it
1256 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) {
1257 DbpString("Trace full");
1258 if (bQuitTraceFull
) {
1267 // By default reset the transmission buffer
1270 case RHT2F_PASSWORD
: {
1271 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1273 case RHT2F_AUTHENTICATE
: {
1274 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1276 case RHT2F_CRYPTO
: {
1277 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
);
1279 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1280 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1283 Dbprintf("Error, unknown function: %d",htf
);
1288 // Send and store the reader command
1289 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1290 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1292 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1293 // Since the clock counts since the last falling edge, a 'one' means that the
1294 // falling edge occured halfway the period. with respect to this falling edge,
1295 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1296 // All timer values are in terms of T0 units
1297 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1299 // Transmit the reader frame
1300 hitag_reader_send_frame(tx
,txlen
);
1302 // Enable and reset external trigger in timer for capturing future frames
1303 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1305 // Add transmitted frame to total count
1309 // Store the frame in the trace
1310 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) {
1311 if (bQuitTraceFull
) {
1320 // Reset values for receiving frames
1321 memset(rx
,0x00,sizeof(rx
));
1325 tag_sof
= reset_sof
;
1328 // Receive frame, watch for at most T0*EOF periods
1329 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1330 // Check if falling edge in tag modulation is detected
1331 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1332 // Retrieve the new timing values
1333 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1335 // Reset timer every frame, we have to capture the last edge for timing
1336 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1340 // Capture tag frame (manchester decoding using only falling edges)
1341 if(ra
>= HITAG_T_EOF
) {
1343 //DbpString("wierd1?");
1345 // Capture the T0 periods that have passed since last communication or field drop (reset)
1346 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1347 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1348 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1349 // Manchester coding example |-_|_-|-_| (101)
1350 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1352 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1354 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1355 // Manchester coding example |_-|...|_-|-_| (0...01)
1356 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1358 // We have to skip this half period at start and add the 'one' the second time
1360 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1365 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1366 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1368 // Ignore bits that are transmitted during SOF
1371 // bit is same as last bit
1372 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1376 // Ignore wierd value, is to small to mean anything
1380 // We can break this loop if we received the last bit from a frame
1381 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1388 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1389 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1390 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1391 Dbprintf("frame received: %d",frame_count
);
1392 DbpString("All done");
1393 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);