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 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
747 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
748 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
749 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
752 // Configure output pin that is connected to the FPGA (for modulating)
753 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
754 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
756 // Disable modulation, we are going to eavesdrop, not modulate ;)
759 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
760 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
761 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
763 // Disable timer during configuration
764 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
766 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
767 // external trigger rising edge, load RA on rising edge of TIOA.
768 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
769 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
771 // Enable and reset counter
772 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
774 // Reset the received frame, frame count and timing info
775 memset(rx
,0x00,sizeof(rx
));
779 reader_frame
= false;
784 while(!BUTTON_PRESS()) {
788 // Receive frame, watch for at most T0*EOF periods
789 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
790 // Check if rising edge in modulation is detected
791 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
792 // Retrieve the new timing values
793 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
795 // Find out if we are dealing with a rising or falling edge
796 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
798 // Shorter periods will only happen with reader frames
799 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
800 // Switch from tag to reader capture
803 memset(rx
,0x00,sizeof(rx
));
807 // Only handle if reader frame and rising edge, or tag frame and falling edge
808 if (reader_frame
!= rising_edge
) {
813 // Add the buffered timing values of earlier captured edges which were skipped
819 // Capture reader frame
820 if(ra
>= HITAG_T_STOP
) {
822 //DbpString("wierd0?");
824 // Capture the T0 periods that have passed since last communication or field drop (reset)
825 response
= (ra
- HITAG_T_LOW
);
826 } else if(ra
>= HITAG_T_1_MIN
) {
828 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
830 } else if(ra
>= HITAG_T_0_MIN
) {
832 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
835 // Ignore wierd value, is to small to mean anything
839 // Capture tag frame (manchester decoding using only falling edges)
840 if(ra
>= HITAG_T_EOF
) {
842 //DbpString("wierd1?");
844 // Capture the T0 periods that have passed since last communication or field drop (reset)
845 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
846 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
847 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
848 // Manchester coding example |-_|_-|-_| (101)
849 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
851 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
853 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
854 // Manchester coding example |_-|...|_-|-_| (0...01)
855 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
857 // We have to skip this half period at start and add the 'one' the second time
859 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
864 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
865 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
867 // Ignore bits that are transmitted during SOF
870 // bit is same as last bit
871 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
875 // Ignore wierd value, is to small to mean anything
881 // Check if frame was captured
884 if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) {
885 DbpString("Trace full");
889 // Check if we recognize a valid authentication attempt
890 if (nbytes(rxlen
) == 8) {
891 // Store the authentication attempt
892 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
893 memcpy(auth_table
+auth_table_len
,rx
,8);
898 // Reset the received frame and response timing info
899 memset(rx
,0x00,sizeof(rx
));
901 reader_frame
= false;
910 // Save the timer overflow, will be 0 when frame was received
911 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
913 // Reset the frame length
915 // Reset the timer to restart while-loop that receives frames
916 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
922 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
923 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
924 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
927 // Dbprintf("frame received: %d",frame_count);
928 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
929 // DbpString("All done");
932 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
936 byte_t rx
[HITAG_FRAME_LEN
];
938 byte_t tx
[HITAG_FRAME_LEN
];
940 bool bQuitTraceFull
= false;
943 // Clean up trace and prepare it for storing frames
944 iso14a_set_tracing(TRUE
);
945 iso14a_clear_trace();
948 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
950 DbpString("Starting Hitag2 simulation");
954 if (tag_mem_supplied
) {
955 DbpString("Loading hitag2 memory...");
956 memcpy((byte_t
*)tag
.sectors
,data
,48);
960 for (size_t i
=0; i
<12; i
++) {
961 for (size_t j
=0; j
<4; j
++) {
963 block
|= tag
.sectors
[i
][j
];
965 Dbprintf("| %d | %08x |",i
,block
);
968 // Set up simulator mode, frequency divisor which will drive the FPGA
969 // and analog mux selection.
970 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
971 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
972 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
973 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
976 // Configure output pin that is connected to the FPGA (for modulating)
977 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
978 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
980 // Disable modulation at default, which means release resistance
983 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
984 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
986 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
987 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
988 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
990 // Disable timer during configuration
991 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
993 // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
994 // external trigger rising edge, load RA on rising edge of TIOA.
995 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
997 // Reset the received frame, frame count and timing info
998 memset(rx
,0x00,sizeof(rx
));
1003 // Enable and reset counter
1004 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1006 while(!BUTTON_PRESS()) {
1010 // Receive frame, watch for at most T0*EOF periods
1011 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
1012 // Check if rising edge in modulation is detected
1013 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1014 // Retrieve the new timing values
1015 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
1018 // Reset timer every frame, we have to capture the last edge for timing
1019 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1023 // Capture reader frame
1024 if(ra
>= HITAG_T_STOP
) {
1026 //DbpString("wierd0?");
1028 // Capture the T0 periods that have passed since last communication or field drop (reset)
1029 response
= (ra
- HITAG_T_LOW
);
1030 } else if(ra
>= HITAG_T_1_MIN
) {
1032 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1034 } else if(ra
>= HITAG_T_0_MIN
) {
1036 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1039 // Ignore wierd value, is to small to mean anything
1044 // Check if frame was captured
1048 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) {
1049 DbpString("Trace full");
1050 if (bQuitTraceFull
) {
1058 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1059 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1061 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1062 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1064 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1065 // not that since the clock counts since the rising edge, but T_Wait1 is
1066 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1067 // periods. The gap time T_Low varies (4..10). All timer values are in
1068 // terms of T0 units
1069 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1071 // Send and store the tag answer (if there is any)
1073 // Transmit the tag frame
1074 hitag_send_frame(tx
,txlen
);
1075 // Store the frame in the trace
1077 if (!LogTraceHitag(tx
,txlen
,0,0,false)) {
1078 DbpString("Trace full");
1079 if (bQuitTraceFull
) {
1088 // Reset the received frame and response timing info
1089 memset(rx
,0x00,sizeof(rx
));
1092 // Enable and reset external trigger in timer for capturing future frames
1093 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1096 // Reset the frame length
1098 // Save the timer overflow, will be 0 when frame was received
1099 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1100 // Reset the timer to restart while-loop that receives frames
1101 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1105 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1106 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1107 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1109 DbpString("Sim Stopped");
1113 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1116 byte_t rx
[HITAG_FRAME_LEN
];
1118 byte_t txbuf
[HITAG_FRAME_LEN
];
1125 int t_wait
= HITAG_T_WAIT_MAX
;
1127 bool bQuitTraceFull
= false;
1129 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1130 // Reset the return status
1131 bSuccessful
= false;
1133 // Clean up trace and prepare it for storing frames
1134 iso14a_set_tracing(TRUE
);
1135 iso14a_clear_trace();
1136 DbpString("Starting Hitag reader family");
1138 // Check configuration
1140 case RHT2F_PASSWORD
: {
1141 Dbprintf("List identifier in password mode");
1142 memcpy(password
,htd
->pwd
.password
,4);
1144 bQuitTraceFull
= false;
1149 case RHT2F_AUTHENTICATE
: {
1150 DbpString("Authenticating using nr,ar pair:");
1151 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1152 Dbhexdump(8,NrAr
,false);
1155 bAuthenticating
= false;
1156 bQuitTraceFull
= true;
1159 case RHT2F_CRYPTO
: {
1160 DbpString("Authenticating using key:");
1161 memcpy(key
,htd
->crypto
.key
,4); //HACK; 4 or 6?? I read both in the code.
1162 Dbhexdump(6,key
,false);
1166 bAuthenticating
= false;
1167 bQuitTraceFull
= true;
1170 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1171 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1173 memcpy(NrAr
,auth_table
,8);
1174 bQuitTraceFull
= false;
1180 Dbprintf("Error, unknown function: %d",htf
);
1188 // Configure output and enable pin that is connected to the FPGA (for modulating)
1189 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1190 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1192 // Set fpga in edge detect with reader field, we can modulate as reader now
1193 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1195 // Set Frequency divisor which will drive the FPGA and analog mux selection
1196 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1197 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1200 // Disable modulation at default, which means enable the field
1203 // Give it a bit of time for the resonant antenna to settle.
1206 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1207 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1209 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1210 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1211 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1213 // Disable timer during configuration
1214 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1216 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1217 // external trigger rising edge, load RA on falling edge of TIOA.
1218 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1220 // Enable and reset counters
1221 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1222 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1224 // Reset the received frame, frame count and timing info
1230 // Tag specific configuration settings (sof, timings, etc.)
1235 DbpString("Configured for hitagS reader");
1236 } else if (htf
< 20) {
1240 DbpString("Configured for hitag1 reader");
1241 } else if (htf
< 30) {
1244 t_wait
= HITAG_T_WAIT_2
;
1245 DbpString("Configured for hitag2 reader");
1247 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1251 while(!bStop
&& !BUTTON_PRESS()) {
1255 // Check if frame was captured and store it
1259 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) {
1260 DbpString("Trace full");
1261 if (bQuitTraceFull
) {
1270 // By default reset the transmission buffer
1273 case RHT2F_PASSWORD
: {
1274 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1276 case RHT2F_AUTHENTICATE
: {
1277 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1279 case RHT2F_CRYPTO
: {
1280 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
);
1282 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1283 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1286 Dbprintf("Error, unknown function: %d",htf
);
1291 // Send and store the reader command
1292 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1293 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1295 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1296 // Since the clock counts since the last falling edge, a 'one' means that the
1297 // falling edge occured halfway the period. with respect to this falling edge,
1298 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1299 // All timer values are in terms of T0 units
1300 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1302 // Transmit the reader frame
1303 hitag_reader_send_frame(tx
,txlen
);
1305 // Enable and reset external trigger in timer for capturing future frames
1306 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1308 // Add transmitted frame to total count
1312 // Store the frame in the trace
1313 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) {
1314 if (bQuitTraceFull
) {
1323 // Reset values for receiving frames
1324 memset(rx
,0x00,sizeof(rx
));
1328 tag_sof
= reset_sof
;
1331 // Receive frame, watch for at most T0*EOF periods
1332 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1333 // Check if falling edge in tag modulation is detected
1334 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1335 // Retrieve the new timing values
1336 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1338 // Reset timer every frame, we have to capture the last edge for timing
1339 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1343 // Capture tag frame (manchester decoding using only falling edges)
1344 if(ra
>= HITAG_T_EOF
) {
1346 //DbpString("wierd1?");
1348 // Capture the T0 periods that have passed since last communication or field drop (reset)
1349 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1350 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1351 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1352 // Manchester coding example |-_|_-|-_| (101)
1353 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1355 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1357 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1358 // Manchester coding example |_-|...|_-|-_| (0...01)
1359 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1361 // We have to skip this half period at start and add the 'one' the second time
1363 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1368 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1369 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1371 // Ignore bits that are transmitted during SOF
1374 // bit is same as last bit
1375 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1379 // Ignore wierd value, is to small to mean anything
1383 // We can break this loop if we received the last bit from a frame
1384 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1391 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1392 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1393 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1394 Dbprintf("frame received: %d",frame_count
);
1395 DbpString("All done");
1396 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);