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 "../include/proxmark3.h"
22 #include "../include/hitag2.h"
28 static bool bAuthenticating
;
30 static bool bSuccessful
;
33 static int LogTraceHitag(const uint8_t * btBytes
, int iBits
, int iSamples
, uint32_t dwParity
, int bReader
)
35 static uint16_t traceLen
= 0;
36 uint8_t *trace
= BigBuf_get_addr();
38 // Return when trace is full
39 if (traceLen
+ sizeof(rsamples
) + sizeof(dwParity
) + sizeof(iBits
) + nbytes(iBits
) > BigBuf_max_traceLen()) return FALSE
;
41 // Trace the random, i'm curious
43 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
44 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
45 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
46 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
48 trace
[traceLen
- 1] |= 0x80;
50 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
51 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
52 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
53 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
54 trace
[traceLen
++] = iBits
;
55 memcpy(trace
+ traceLen
, btBytes
, nbytes(iBits
));
56 traceLen
+= nbytes(iBits
);
63 TAG_STATE_RESET
= 0x01, // Just powered up, awaiting GetSnr
64 TAG_STATE_ACTIVATING
= 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
65 TAG_STATE_ACTIVATED
= 0x03, // Activation complete, awaiting read/write commands
66 TAG_STATE_WRITING
= 0x04, // In write command, awaiting sector contents to be written
68 unsigned int active_sector
;
71 byte_t sectors
[12][4];
74 static struct hitag2_tag tag
= {
75 .state
= TAG_STATE_RESET
,
76 .sectors
= { // Password mode: | Crypto mode:
77 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
78 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
79 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
80 [3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
81 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
82 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
83 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
84 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
85 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
86 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
87 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
88 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
92 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
93 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
94 #define AUTH_TABLE_LENGTH 2744
95 static byte_t
* auth_table
;
96 static size_t auth_table_pos
= 0;
97 static size_t auth_table_len
= AUTH_TABLE_LENGTH
;
99 static byte_t password
[4];
100 static byte_t NrAr
[8];
101 static byte_t key
[8];
102 static 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 static int hitag2_reset(void)
182 tag
.state
= TAG_STATE_RESET
;
183 tag
.crypto_active
= 0;
187 static 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
304 static void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
306 byte_t rx_air
[HITAG_FRAME_LEN
];
308 // Copy the (original) received frame how it is send over the air
309 memcpy(rx_air
,rx
,nbytes(rxlen
));
311 if(tag
.crypto_active
) {
312 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen
%8);
315 // Reset the transmission frame length
318 // Try to find out which command was send by selecting on length (in bits)
320 // Received 11000 from the reader, request for UID, send UID
322 // Always send over the air in the clear plaintext mode
323 if(rx_air
[0] != 0xC0) {
328 memcpy(tx
,tag
.sectors
[0],4);
329 tag
.crypto_active
= 0;
333 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
335 unsigned int sector
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07);
336 // Verify complement of sector index
337 if(sector
!= ((rx
[0]>>3)&0x07)) {
338 //DbpString("Transmission error (read/write)");
342 switch (rx
[0] & 0xC6) {
343 // Read command: 11xx x00y
345 memcpy(tx
,tag
.sectors
[sector
],4);
349 // Inverted Read command: 01xx x10y
351 for (size_t i
=0; i
<4; i
++) {
352 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
357 // Write command: 10xx x01y
359 // Prepare write, acknowledge by repeating command
360 memcpy(tx
,rx
,nbytes(rxlen
));
362 tag
.active_sector
= sector
;
363 tag
.state
=TAG_STATE_WRITING
;
368 Dbprintf("Uknown command: %02x %02x",rx
[0],rx
[1]);
375 // Writing data or Reader password
377 if(tag
.state
== TAG_STATE_WRITING
) {
378 // These are the sector contents to be written. We don't have to do anything else.
379 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
));
380 tag
.state
=TAG_STATE_RESET
;
383 // Received RWD password, respond with configuration and our password
384 if(memcmp(rx
,tag
.sectors
[1],4) != 0) {
385 DbpString("Reader password is wrong");
389 memcpy(tx
,tag
.sectors
[3],4);
394 // Received RWD authentication challenge and respnse
396 // Store the authentication attempt
397 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
398 memcpy(auth_table
+auth_table_len
,rx
,8);
402 // Reset the cipher state
403 hitag2_cipher_reset(&tag
,rx
);
404 // Check if the authentication was correct
405 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) {
406 // The reader failed to authenticate, do nothing
407 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]);
410 // Succesful, but commented out reporting back to the Host, this may delay to much.
411 // 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]);
413 // Activate encryption algorithm for all further communication
414 tag
.crypto_active
= 1;
416 // Use the tag password as response
417 memcpy(tx
,tag
.sectors
[3],4);
423 // LogTraceHitag(rx,rxlen,0,0,false);
424 // LogTraceHitag(tx,*txlen,0,0,true);
426 if(tag
.crypto_active
) {
427 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen
%8);
431 static void hitag_reader_send_bit(int bit
) {
433 // Reset clock for the next bit
434 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
436 // Binary puls length modulation (BPLM) is used to encode the data stream
437 // This means that a transmission of a one takes longer than that of a zero
439 // Enable modulation, which means, drop the the field
442 // Wait for 4-10 times the carrier period
443 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
446 // Disable modulation, just activates the field again
451 while(AT91C_BASE_TC0
->TC_CV
< T0
*22);
452 // SpinDelayUs(16*8);
455 while(AT91C_BASE_TC0
->TC_CV
< T0
*28);
456 // SpinDelayUs(22*8);
462 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
)
464 // Send the content of the frame
465 for(size_t i
=0; i
<frame_len
; i
++) {
466 hitag_reader_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
469 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
470 // Enable modulation, which means, drop the the field
472 // Wait for 4-10 times the carrier period
473 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
474 // Disable modulation, just activates the field again
480 static bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
481 // Reset the transmission frame length
484 // Try to find out which command was send by selecting on length (in bits)
486 // No answer, try to resurrect
488 // Stop if there is no answer (after sending password)
490 DbpString("Password failed!");
494 memcpy(tx
,"\xc0",nbytes(*txlen
));
497 // Received UID, tag password
501 memcpy(tx
,password
,4);
503 memcpy(tag
.sectors
[blocknr
],rx
,4);
508 //store password in block1, the TAG answers with Block3, but we need the password in memory
509 memcpy(tag
.sectors
[blocknr
],tx
,4);
511 memcpy(tag
.sectors
[blocknr
],rx
,4);
516 DbpString("Read succesful!");
521 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
522 tx
[1] = ((blocknr
^7) << 6);
526 // Unexpected response
528 Dbprintf("Uknown frame length: %d",rxlen
);
535 static bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
536 // Reset the transmission frame length
540 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen
%8);
543 // Try to find out which command was send by selecting on length (in bits)
545 // No answer, try to resurrect
547 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
549 // Failed during authentication
550 if (bAuthenticating
) {
551 DbpString("Authentication failed!");
554 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
556 // Write the low part of the key in memory
557 memcpy(tag
.sectors
[1],key
+2,4);
558 } else if (blocknr
== 2) {
559 // Write the high part of the key in memory
560 tag
.sectors
[2][0] = 0x00;
561 tag
.sectors
[2][1] = 0x00;
562 tag
.sectors
[2][2] = key
[0];
563 tag
.sectors
[2][3] = key
[1];
565 // Just put zero's in the memory (of the unreadable block)
566 memset(tag
.sectors
[blocknr
],0x00,4);
573 memcpy(tx
,"\xc0",nbytes(*txlen
));
577 // Received UID, crypto tag answer
580 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;
581 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
582 cipher_state
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0);
585 hitag2_cipher_transcrypt(&cipher_state
,tx
+4,4,0);
588 bAuthenticating
= true;
590 // Check if we received answer tag (at)
591 if (bAuthenticating
) {
592 bAuthenticating
= false;
594 // Store the received block
595 memcpy(tag
.sectors
[blocknr
],rx
,4);
599 DbpString("Read succesful!");
604 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
605 tx
[1] = ((blocknr
^7) << 6);
609 // Unexpected response
611 Dbprintf("Uknown frame length: %d",rxlen
);
618 // We have to return now to avoid double encryption
619 if (!bAuthenticating
) {
620 hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen
%8);
628 static bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
629 // Reset the transmission frame length
632 // Try to find out which command was send by selecting on length (in bits)
634 // No answer, try to resurrect
636 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
638 DbpString("Authentication failed!");
642 memcpy(tx
,"\xc0",nbytes(*txlen
));
645 // Received UID, crypto tag answer
652 DbpString("Authentication succesful!");
653 // We are done... for now
658 // Unexpected response
660 Dbprintf("Uknown frame length: %d",rxlen
);
669 static bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
671 // Reset the transmission frame length
674 // Try to find out which command was send by selecting on length (in bits)
676 // No answer, try to resurrect
678 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
680 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]);
682 // Removing failed entry from authentiations table
683 memcpy(auth_table
+auth_table_pos
,auth_table
+auth_table_pos
+8,8);
686 // Return if we reached the end of the authentications table
688 if (auth_table_pos
== auth_table_len
) {
692 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
693 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
696 memcpy(tx
,"\xc0",nbytes(*txlen
));
699 // Received UID, crypto tag answer, or read block response
706 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]);
708 if ((auth_table_pos
+8) == auth_table_len
) {
712 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
717 Dbprintf("Uknown frame length: %d",rxlen
);
726 void SnoopHitag(uint32_t type
) {
735 byte_t rx
[HITAG_FRAME_LEN
];
741 auth_table
= (byte_t
*)BigBuf_malloc(AUTH_TABLE_LENGTH
);
742 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
744 // Clean up trace and prepare it for storing frames
745 iso14a_set_tracing(TRUE
);
746 iso14a_clear_trace();
748 DbpString("Starting Hitag2 snoop");
751 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
752 // and analog mux selection.
753 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
754 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
);
755 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
756 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
759 // Configure output pin that is connected to the FPGA (for modulating)
760 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
761 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
763 // Disable modulation, we are going to eavesdrop, not modulate ;)
766 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
767 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
768 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
770 // Disable timer during configuration
771 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
773 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
774 // external trigger rising edge, load RA on rising edge of TIOA.
775 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
776 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
778 // Enable and reset counter
779 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
781 // Reset the received frame, frame count and timing info
782 memset(rx
,0x00,sizeof(rx
));
786 reader_frame
= false;
791 while(!BUTTON_PRESS()) {
795 // Receive frame, watch for at most T0*EOF periods
796 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
797 // Check if rising edge in modulation is detected
798 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
799 // Retrieve the new timing values
800 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
802 // Find out if we are dealing with a rising or falling edge
803 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
805 // Shorter periods will only happen with reader frames
806 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
807 // Switch from tag to reader capture
810 memset(rx
,0x00,sizeof(rx
));
814 // Only handle if reader frame and rising edge, or tag frame and falling edge
815 if (reader_frame
!= rising_edge
) {
820 // Add the buffered timing values of earlier captured edges which were skipped
826 // Capture reader frame
827 if(ra
>= HITAG_T_STOP
) {
829 //DbpString("wierd0?");
831 // Capture the T0 periods that have passed since last communication or field drop (reset)
832 response
= (ra
- HITAG_T_LOW
);
833 } else if(ra
>= HITAG_T_1_MIN
) {
835 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
837 } else if(ra
>= HITAG_T_0_MIN
) {
839 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
842 // Ignore wierd value, is to small to mean anything
846 // Capture tag frame (manchester decoding using only falling edges)
847 if(ra
>= HITAG_T_EOF
) {
849 //DbpString("wierd1?");
851 // Capture the T0 periods that have passed since last communication or field drop (reset)
852 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
853 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
854 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
855 // Manchester coding example |-_|_-|-_| (101)
856 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
858 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
860 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
861 // Manchester coding example |_-|...|_-|-_| (0...01)
862 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
864 // We have to skip this half period at start and add the 'one' the second time
866 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
871 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
872 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
874 // Ignore bits that are transmitted during SOF
877 // bit is same as last bit
878 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
882 // Ignore wierd value, is to small to mean anything
888 // Check if frame was captured
891 if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) {
892 DbpString("Trace full");
896 // Check if we recognize a valid authentication attempt
897 if (nbytes(rxlen
) == 8) {
898 // Store the authentication attempt
899 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
900 memcpy(auth_table
+auth_table_len
,rx
,8);
905 // Reset the received frame and response timing info
906 memset(rx
,0x00,sizeof(rx
));
908 reader_frame
= false;
917 // Save the timer overflow, will be 0 when frame was received
918 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
920 // Reset the frame length
922 // Reset the timer to restart while-loop that receives frames
923 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
929 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
930 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
931 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
934 // Dbprintf("frame received: %d",frame_count);
935 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
936 // DbpString("All done");
939 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
943 byte_t rx
[HITAG_FRAME_LEN
];
945 byte_t tx
[HITAG_FRAME_LEN
];
947 bool bQuitTraceFull
= false;
954 auth_table
= (byte_t
*)BigBuf_malloc(AUTH_TABLE_LENGTH
);
955 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
957 // Clean up trace and prepare it for storing frames
958 iso14a_set_tracing(TRUE
);
959 iso14a_clear_trace();
961 DbpString("Starting Hitag2 simulation");
965 if (tag_mem_supplied
) {
966 DbpString("Loading hitag2 memory...");
967 memcpy((byte_t
*)tag
.sectors
,data
,48);
971 for (size_t i
=0; i
<12; i
++) {
972 for (size_t j
=0; j
<4; j
++) {
974 block
|= tag
.sectors
[i
][j
];
976 Dbprintf("| %d | %08x |",i
,block
);
979 // Set up simulator mode, frequency divisor which will drive the FPGA
980 // and analog mux selection.
981 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
982 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
983 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
984 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
987 // Configure output pin that is connected to the FPGA (for modulating)
988 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
989 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
991 // Disable modulation at default, which means release resistance
994 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
995 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
997 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
998 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
999 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1001 // Disable timer during configuration
1002 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1004 // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1005 // external trigger rising edge, load RA on rising edge of TIOA.
1006 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
1008 // Reset the received frame, frame count and timing info
1009 memset(rx
,0x00,sizeof(rx
));
1014 // Enable and reset counter
1015 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1017 while(!BUTTON_PRESS()) {
1021 // Receive frame, watch for at most T0*EOF periods
1022 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
1023 // Check if rising edge in modulation is detected
1024 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1025 // Retrieve the new timing values
1026 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
1029 // Reset timer every frame, we have to capture the last edge for timing
1030 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1034 // Capture reader frame
1035 if(ra
>= HITAG_T_STOP
) {
1037 //DbpString("wierd0?");
1039 // Capture the T0 periods that have passed since last communication or field drop (reset)
1040 response
= (ra
- HITAG_T_LOW
);
1041 } else if(ra
>= HITAG_T_1_MIN
) {
1043 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1045 } else if(ra
>= HITAG_T_0_MIN
) {
1047 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1050 // Ignore wierd value, is to small to mean anything
1055 // Check if frame was captured
1059 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) {
1060 DbpString("Trace full");
1061 if (bQuitTraceFull
) {
1069 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1070 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1072 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1073 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1075 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1076 // not that since the clock counts since the rising edge, but T_Wait1 is
1077 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1078 // periods. The gap time T_Low varies (4..10). All timer values are in
1079 // terms of T0 units
1080 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1082 // Send and store the tag answer (if there is any)
1084 // Transmit the tag frame
1085 hitag_send_frame(tx
,txlen
);
1086 // Store the frame in the trace
1088 if (!LogTraceHitag(tx
,txlen
,0,0,false)) {
1089 DbpString("Trace full");
1090 if (bQuitTraceFull
) {
1099 // Reset the received frame and response timing info
1100 memset(rx
,0x00,sizeof(rx
));
1103 // Enable and reset external trigger in timer for capturing future frames
1104 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1107 // Reset the frame length
1109 // Save the timer overflow, will be 0 when frame was received
1110 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1111 // Reset the timer to restart while-loop that receives frames
1112 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1116 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1117 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1118 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1120 DbpString("Sim Stopped");
1124 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1127 byte_t rx
[HITAG_FRAME_LEN
];
1129 byte_t txbuf
[HITAG_FRAME_LEN
];
1136 int t_wait
= HITAG_T_WAIT_MAX
;
1138 bool bQuitTraceFull
= false;
1140 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1141 // Reset the return status
1142 bSuccessful
= false;
1144 // Clean up trace and prepare it for storing frames
1145 iso14a_set_tracing(TRUE
);
1146 iso14a_clear_trace();
1148 DbpString("Starting Hitag reader family");
1150 // Check configuration
1152 case RHT2F_PASSWORD
: {
1153 Dbprintf("List identifier in password mode");
1154 memcpy(password
,htd
->pwd
.password
,4);
1156 bQuitTraceFull
= false;
1161 case RHT2F_AUTHENTICATE
: {
1162 DbpString("Authenticating using nr,ar pair:");
1163 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1164 Dbhexdump(8,NrAr
,false);
1167 bAuthenticating
= false;
1168 bQuitTraceFull
= true;
1171 case RHT2F_CRYPTO
: {
1172 DbpString("Authenticating using key:");
1173 memcpy(key
,htd
->crypto
.key
,4); //HACK; 4 or 6?? I read both in the code.
1174 Dbhexdump(6,key
,false);
1178 bAuthenticating
= false;
1179 bQuitTraceFull
= true;
1182 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1183 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1185 memcpy(NrAr
, auth_table
, 8);
1186 bQuitTraceFull
= false;
1192 Dbprintf("Error, unknown function: %d",htf
);
1200 // Configure output and enable pin that is connected to the FPGA (for modulating)
1201 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1202 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1204 // Set fpga in edge detect with reader field, we can modulate as reader now
1205 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1207 // Set Frequency divisor which will drive the FPGA and analog mux selection
1208 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1209 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1212 // Disable modulation at default, which means enable the field
1215 // Give it a bit of time for the resonant antenna to settle.
1218 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1219 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1221 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1222 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1223 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1225 // Disable timer during configuration
1226 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1228 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1229 // external trigger rising edge, load RA on falling edge of TIOA.
1230 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1232 // Enable and reset counters
1233 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1234 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1236 // Reset the received frame, frame count and timing info
1242 // Tag specific configuration settings (sof, timings, etc.)
1247 DbpString("Configured for hitagS reader");
1248 } else if (htf
< 20) {
1252 DbpString("Configured for hitag1 reader");
1253 } else if (htf
< 30) {
1256 t_wait
= HITAG_T_WAIT_2
;
1257 DbpString("Configured for hitag2 reader");
1259 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1263 while(!bStop
&& !BUTTON_PRESS()) {
1267 // Check if frame was captured and store it
1271 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) {
1272 DbpString("Trace full");
1273 if (bQuitTraceFull
) {
1282 // By default reset the transmission buffer
1285 case RHT2F_PASSWORD
: {
1286 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1288 case RHT2F_AUTHENTICATE
: {
1289 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1291 case RHT2F_CRYPTO
: {
1292 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
);
1294 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1295 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1298 Dbprintf("Error, unknown function: %d",htf
);
1303 // Send and store the reader command
1304 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1305 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1307 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1308 // Since the clock counts since the last falling edge, a 'one' means that the
1309 // falling edge occured halfway the period. with respect to this falling edge,
1310 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1311 // All timer values are in terms of T0 units
1312 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1314 // Transmit the reader frame
1315 hitag_reader_send_frame(tx
,txlen
);
1317 // Enable and reset external trigger in timer for capturing future frames
1318 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1320 // Add transmitted frame to total count
1324 // Store the frame in the trace
1325 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) {
1326 if (bQuitTraceFull
) {
1335 // Reset values for receiving frames
1336 memset(rx
,0x00,sizeof(rx
));
1340 tag_sof
= reset_sof
;
1343 // Receive frame, watch for at most T0*EOF periods
1344 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1345 // Check if falling edge in tag modulation is detected
1346 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1347 // Retrieve the new timing values
1348 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1350 // Reset timer every frame, we have to capture the last edge for timing
1351 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1355 // Capture tag frame (manchester decoding using only falling edges)
1356 if(ra
>= HITAG_T_EOF
) {
1358 //DbpString("wierd1?");
1360 // Capture the T0 periods that have passed since last communication or field drop (reset)
1361 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1362 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1363 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1364 // Manchester coding example |-_|_-|-_| (101)
1365 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1367 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1369 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1370 // Manchester coding example |_-|...|_-|-_| (0...01)
1371 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1373 // We have to skip this half period at start and add the 'one' the second time
1375 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1380 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1381 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1383 // Ignore bits that are transmitted during SOF
1386 // bit is same as last bit
1387 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1391 // Ignore wierd value, is to small to mean anything
1395 // We can break this loop if we received the last bit from a frame
1396 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1403 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1404 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1405 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1406 Dbprintf("frame received: %d",frame_count
);
1407 DbpString("All done");
1408 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);