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 size_t nbytes(size_t nbits
) {
33 return (nbits
/8)+((nbits
%8)>0);
36 int LogTraceHitag(const uint8_t * btBytes
, int iBits
, int iSamples
, uint32_t dwParity
, int bReader
)
38 // Return when trace is full
39 if (traceLen
>= TRACE_SIZE
) 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 //#define TRACE_LENGTH 3000
93 //uint8_t *trace = (uint8_t *) BigBuf;
97 #define AUTH_TABLE_OFFSET FREE_BUFFER_OFFSET
98 #define AUTH_TABLE_LENGTH FREE_BUFFER_SIZE
99 byte_t
* auth_table
= (byte_t
*)BigBuf
+AUTH_TABLE_OFFSET
;
100 size_t auth_table_pos
= 0;
101 size_t auth_table_len
= AUTH_TABLE_LENGTH
;
106 uint64_t cipher_state
;
108 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
109 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
110 // For educational purposes only.
111 // No warranties or guarantees of any kind.
112 // This code is released into the public domain by its author.
119 #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))
120 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
121 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
122 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
123 #define bit(x,n) (((x)>>(n))&1)
124 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
125 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
126 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
128 // Single bit Hitag2 functions:
130 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
132 static const u32 ht2_f4a
= 0x2C79; // 0010 1100 0111 1001
133 static const u32 ht2_f4b
= 0x6671; // 0110 0110 0111 0001
134 static const u32 ht2_f5c
= 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
136 static u32
_f20 (const u64 x
)
140 i5
= ((ht2_f4a
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1
141 + ((ht2_f4b
>> i4 (x
, 7,11,13,14)) & 1)* 2
142 + ((ht2_f4b
>> i4 (x
,16,20,22,25)) & 1)* 4
143 + ((ht2_f4b
>> i4 (x
,27,28,30,32)) & 1)* 8
144 + ((ht2_f4a
>> i4 (x
,33,42,43,45)) & 1)*16;
146 return (ht2_f5c
>> i5
) & 1;
149 static u64
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
)
152 u64 x
= ((key
& 0xFFFF) << 32) + serial
;
154 for (i
= 0; i
< 32; i
++)
157 x
+= (u64
) (_f20 (x
) ^ (((IV
>> i
) ^ (key
>> (i
+16))) & 1)) << 47;
162 static u64
_hitag2_round (u64
*state
)
167 ((((x
>> 0) ^ (x
>> 2) ^ (x
>> 3) ^ (x
>> 6)
168 ^ (x
>> 7) ^ (x
>> 8) ^ (x
>> 16) ^ (x
>> 22)
169 ^ (x
>> 23) ^ (x
>> 26) ^ (x
>> 30) ^ (x
>> 41)
170 ^ (x
>> 42) ^ (x
>> 43) ^ (x
>> 46) ^ (x
>> 47)) & 1) << 47);
176 static u32
_hitag2_byte (u64
* x
)
180 for (i
= 0, c
= 0; i
< 8; i
++) c
+= (u32
) _hitag2_round (x
) << (i
^7);
184 int hitag2_reset(void)
186 tag
.state
= TAG_STATE_RESET
;
187 tag
.crypto_active
= 0;
191 int hitag2_init(void)
193 // memcpy(&tag, &resetdata, sizeof(tag));
198 static void hitag2_cipher_reset(struct hitag2_tag
*tag
, const byte_t
*iv
)
200 uint64_t key
= ((uint64_t)tag
->sectors
[2][2]) |
201 ((uint64_t)tag
->sectors
[2][3] << 8) |
202 ((uint64_t)tag
->sectors
[1][0] << 16) |
203 ((uint64_t)tag
->sectors
[1][1] << 24) |
204 ((uint64_t)tag
->sectors
[1][2] << 32) |
205 ((uint64_t)tag
->sectors
[1][3] << 40);
206 uint32_t uid
= ((uint32_t)tag
->sectors
[0][0]) |
207 ((uint32_t)tag
->sectors
[0][1] << 8) |
208 ((uint32_t)tag
->sectors
[0][2] << 16) |
209 ((uint32_t)tag
->sectors
[0][3] << 24);
210 uint32_t iv_
= (((uint32_t)(iv
[0]))) |
211 (((uint32_t)(iv
[1])) << 8) |
212 (((uint32_t)(iv
[2])) << 16) |
213 (((uint32_t)(iv
[3])) << 24);
214 tag
->cs
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
));
217 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t
*authenticator_is
)
219 byte_t authenticator_should
[4];
220 authenticator_should
[0] = ~_hitag2_byte(cs
);
221 authenticator_should
[1] = ~_hitag2_byte(cs
);
222 authenticator_should
[2] = ~_hitag2_byte(cs
);
223 authenticator_should
[3] = ~_hitag2_byte(cs
);
224 return (memcmp(authenticator_should
, authenticator_is
, 4) == 0);
227 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t
*data
, unsigned int bytes
, unsigned int bits
)
230 for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
);
231 for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
);
235 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
236 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
237 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
238 // T0 = TIMER_CLOCK1 / 125000 = 192
241 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
242 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
244 #define HITAG_FRAME_LEN 20
245 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
246 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
247 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
248 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
249 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
250 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
251 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
252 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
253 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
255 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
256 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
257 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
258 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
260 #define HITAG_T_TAG_HALF_PERIOD 16
261 #define HITAG_T_TAG_FULL_PERIOD 32
263 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
264 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
265 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
266 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
269 static void hitag_send_bit(int bit
) {
271 // Reset clock for the next bit
272 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
274 // Fixed modulation, earlier proxmark version used inverted signal
276 // Manchester: Unloaded, then loaded |__--|
278 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
280 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
282 // Manchester: Loaded, then unloaded |--__|
284 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_HALF_PERIOD
);
286 while(AT91C_BASE_TC0
->TC_CV
< T0
*HITAG_T_TAG_FULL_PERIOD
);
291 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
)
293 // Send start of frame
294 for(size_t i
=0; i
<5; i
++) {
298 // Send the content of the frame
299 for(size_t i
=0; i
<frame_len
; i
++) {
300 hitag_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
303 // Drop the modulation
307 void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
)
309 byte_t rx_air
[HITAG_FRAME_LEN
];
311 // Copy the (original) received frame how it is send over the air
312 memcpy(rx_air
,rx
,nbytes(rxlen
));
314 if(tag
.crypto_active
) {
315 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen
%8);
318 // Reset the transmission frame length
321 // Try to find out which command was send by selecting on length (in bits)
323 // Received 11000 from the reader, request for UID, send UID
325 // Always send over the air in the clear plaintext mode
326 if(rx_air
[0] != 0xC0) {
331 memcpy(tx
,tag
.sectors
[0],4);
332 tag
.crypto_active
= 0;
336 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
338 unsigned int sector
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07);
339 // Verify complement of sector index
340 if(sector
!= ((rx
[0]>>3)&0x07)) {
341 //DbpString("Transmission error (read/write)");
345 switch (rx
[0] & 0xC6) {
346 // Read command: 11xx x00y
348 memcpy(tx
,tag
.sectors
[sector
],4);
352 // Inverted Read command: 01xx x10y
354 for (size_t i
=0; i
<4; i
++) {
355 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff;
360 // Write command: 10xx x01y
362 // Prepare write, acknowledge by repeating command
363 memcpy(tx
,rx
,nbytes(rxlen
));
365 tag
.active_sector
= sector
;
366 tag
.state
=TAG_STATE_WRITING
;
371 Dbprintf("Uknown command: %02x %02x",rx
[0],rx
[1]);
378 // Writing data or Reader password
380 if(tag
.state
== TAG_STATE_WRITING
) {
381 // These are the sector contents to be written. We don't have to do anything else.
382 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
));
383 tag
.state
=TAG_STATE_RESET
;
386 // Received RWD password, respond with configuration and our password
387 if(memcmp(rx
,tag
.sectors
[1],4) != 0) {
388 DbpString("Reader password is wrong");
392 memcpy(tx
,tag
.sectors
[3],4);
397 // Received RWD authentication challenge and respnse
399 // Store the authentication attempt
400 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
401 memcpy(auth_table
+auth_table_len
,rx
,8);
405 // Reset the cipher state
406 hitag2_cipher_reset(&tag
,rx
);
407 // Check if the authentication was correct
408 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) {
409 // The reader failed to authenticate, do nothing
410 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]);
413 // Succesful, but commented out reporting back to the Host, this may delay to much.
414 // 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]);
416 // Activate encryption algorithm for all further communication
417 tag
.crypto_active
= 1;
419 // Use the tag password as response
420 memcpy(tx
,tag
.sectors
[3],4);
426 // LogTraceHitag(rx,rxlen,0,0,false);
427 // LogTraceHitag(tx,*txlen,0,0,true);
429 if(tag
.crypto_active
) {
430 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen
%8);
434 static void hitag_reader_send_bit(int bit
) {
436 // Reset clock for the next bit
437 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
439 // Binary puls length modulation (BPLM) is used to encode the data stream
440 // This means that a transmission of a one takes longer than that of a zero
442 // Enable modulation, which means, drop the the field
445 // Wait for 4-10 times the carrier period
446 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
449 // Disable modulation, just activates the field again
454 while(AT91C_BASE_TC0
->TC_CV
< T0
*22);
455 // SpinDelayUs(16*8);
458 while(AT91C_BASE_TC0
->TC_CV
< T0
*28);
459 // SpinDelayUs(22*8);
464 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
)
466 // Send the content of the frame
467 for(size_t i
=0; i
<frame_len
; i
++) {
468 hitag_reader_send_bit((frame
[i
/8] >> (7-(i
%8)))&1);
471 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
472 // Enable modulation, which means, drop the the field
474 // Wait for 4-10 times the carrier period
475 while(AT91C_BASE_TC0
->TC_CV
< T0
*6);
476 // Disable modulation, just activates the field again
482 bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
483 // Reset the transmission frame length
486 // Try to find out which command was send by selecting on length (in bits)
488 // No answer, try to resurrect
490 // Stop if there is no answer (after sending password)
492 DbpString("Password failed!");
496 memcpy(tx
,"\xc0",nbytes(*txlen
));
499 // Received UID, tag password
503 memcpy(tx
,password
,4);
505 memcpy(tag
.sectors
[blocknr
],rx
,4);
510 //store password in block1, the TAG answers with Block3, but we need the password in memory
511 memcpy(tag
.sectors
[blocknr
],tx
,4);
513 memcpy(tag
.sectors
[blocknr
],rx
,4);
518 DbpString("Read succesful!");
523 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
524 tx
[1] = ((blocknr
^7) << 6);
528 // Unexpected response
530 Dbprintf("Uknown frame length: %d",rxlen
);
537 bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
538 // Reset the transmission frame length
542 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen
%8);
545 // Try to find out which command was send by selecting on length (in bits)
547 // No answer, try to resurrect
549 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
551 // Failed during authentication
552 if (bAuthenticating
) {
553 DbpString("Authentication failed!");
556 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
558 // Write the low part of the key in memory
559 memcpy(tag
.sectors
[1],key
+2,4);
560 } else if (blocknr
== 2) {
561 // Write the high part of the key in memory
562 tag
.sectors
[2][0] = 0x00;
563 tag
.sectors
[2][1] = 0x00;
564 tag
.sectors
[2][2] = key
[0];
565 tag
.sectors
[2][3] = key
[1];
567 // Just put zero's in the memory (of the unreadable block)
568 memset(tag
.sectors
[blocknr
],0x00,4);
575 memcpy(tx
,"\xc0",nbytes(*txlen
));
579 // Received UID, crypto tag answer
582 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;
583 uint32_t ui32uid
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24;
584 cipher_state
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0);
587 hitag2_cipher_transcrypt(&cipher_state
,tx
+4,4,0);
590 bAuthenticating
= true;
592 // Check if we received answer tag (at)
593 if (bAuthenticating
) {
594 bAuthenticating
= false;
596 // Store the received block
597 memcpy(tag
.sectors
[blocknr
],rx
,4);
601 DbpString("Read succesful!");
606 tx
[0] = 0xc0 | (blocknr
<< 3) | ((blocknr
^7) >> 2);
607 tx
[1] = ((blocknr
^7) << 6);
611 // Unexpected response
613 Dbprintf("Uknown frame length: %d",rxlen
);
620 // We have to return now to avoid double encryption
621 if (!bAuthenticating
) {
622 hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen
%8);
630 bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) {
631 // Reset the transmission frame length
634 // Try to find out which command was send by selecting on length (in bits)
636 // No answer, try to resurrect
638 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
640 DbpString("Authentication failed!");
644 memcpy(tx
,"\xc0",nbytes(*txlen
));
647 // Received UID, crypto tag answer
654 DbpString("Authentication succesful!");
655 // We are done... for now
660 // Unexpected response
662 Dbprintf("Uknown frame length: %d",rxlen
);
670 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!",NrAr
[0],NrAr
[1],NrAr
[2],NrAr
[3],NrAr
[4],NrAr
[5],NrAr
[6],NrAr
[7]);
682 if ((auth_table_pos
+8) == auth_table_len
) {
686 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
689 memcpy(tx
,"\xc0",nbytes(*txlen
));
692 // Received UID, crypto tag answer, or read block response
699 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]);
701 if ((auth_table_pos
+8) == auth_table_len
) {
705 memcpy(NrAr
,auth_table
+auth_table_pos
,8);
710 Dbprintf("Uknown frame length: %d",rxlen
);
718 void SnoopHitag(uint32_t type
) {
727 byte_t rx
[HITAG_FRAME_LEN
];
730 // Clean up trace and prepare it for storing frames
731 iso14a_set_tracing(TRUE
);
732 iso14a_clear_trace();
736 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
738 DbpString("Starting Hitag2 snoop");
741 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
742 // and analog mux selection.
743 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
744 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
745 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
748 // Configure output pin that is connected to the FPGA (for modulating)
749 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
750 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
752 // Disable modulation, we are going to eavesdrop, not modulate ;)
755 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
756 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
757 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
759 // Disable timer during configuration
760 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
762 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
763 // external trigger rising edge, load RA on rising edge of TIOA.
764 uint32_t t1_channel_mode
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_BOTH
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_BOTH
;
765 AT91C_BASE_TC1
->TC_CMR
= t1_channel_mode
;
767 // Enable and reset counter
768 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
770 // Reset the received frame, frame count and timing info
771 memset(rx
,0x00,sizeof(rx
));
775 reader_frame
= false;
780 while(!BUTTON_PRESS()) {
784 // Receive frame, watch for at most T0*EOF periods
785 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
786 // Check if rising edge in modulation is detected
787 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
788 // Retrieve the new timing values
789 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
791 // Find out if we are dealing with a rising or falling edge
792 rising_edge
= (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_FRAME
) > 0;
794 // Shorter periods will only happen with reader frames
795 if (!reader_frame
&& rising_edge
&& ra
< HITAG_T_TAG_CAPTURE_ONE_HALF
) {
796 // Switch from tag to reader capture
799 memset(rx
,0x00,sizeof(rx
));
803 // Only handle if reader frame and rising edge, or tag frame and falling edge
804 if (reader_frame
!= rising_edge
) {
809 // Add the buffered timing values of earlier captured edges which were skipped
815 // Capture reader frame
816 if(ra
>= HITAG_T_STOP
) {
818 //DbpString("wierd0?");
820 // Capture the T0 periods that have passed since last communication or field drop (reset)
821 response
= (ra
- HITAG_T_LOW
);
822 } else if(ra
>= HITAG_T_1_MIN
) {
824 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
826 } else if(ra
>= HITAG_T_0_MIN
) {
828 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
831 // Ignore wierd value, is to small to mean anything
835 // Capture tag frame (manchester decoding using only falling edges)
836 if(ra
>= HITAG_T_EOF
) {
838 //DbpString("wierd1?");
840 // Capture the T0 periods that have passed since last communication or field drop (reset)
841 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
842 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
843 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
844 // Manchester coding example |-_|_-|-_| (101)
845 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
847 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
849 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
850 // Manchester coding example |_-|...|_-|-_| (0...01)
851 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
853 // We have to skip this half period at start and add the 'one' the second time
855 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
860 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
861 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
863 // Ignore bits that are transmitted during SOF
866 // bit is same as last bit
867 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
871 // Ignore wierd value, is to small to mean anything
877 // Check if frame was captured
880 if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) {
881 DbpString("Trace full");
885 // Check if we recognize a valid authentication attempt
886 if (nbytes(rxlen
) == 8) {
887 // Store the authentication attempt
888 if (auth_table_len
< (AUTH_TABLE_LENGTH
-8)) {
889 memcpy(auth_table
+auth_table_len
,rx
,8);
894 // Reset the received frame and response timing info
895 memset(rx
,0x00,sizeof(rx
));
897 reader_frame
= false;
906 // Save the timer overflow, will be 0 when frame was received
907 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
909 // Reset the frame length
911 // Reset the timer to restart while-loop that receives frames
912 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
918 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
919 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
920 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
923 // Dbprintf("frame received: %d",frame_count);
924 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
925 // DbpString("All done");
928 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) {
932 byte_t rx
[HITAG_FRAME_LEN
];
934 byte_t tx
[HITAG_FRAME_LEN
];
936 bool bQuitTraceFull
= false;
939 // Clean up trace and prepare it for storing frames
940 iso14a_set_tracing(TRUE
);
941 iso14a_clear_trace();
944 memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
);
946 DbpString("Starting Hitag2 simulation");
950 if (tag_mem_supplied
) {
951 DbpString("Loading hitag2 memory...");
952 memcpy((byte_t
*)tag
.sectors
,data
,48);
956 for (size_t i
=0; i
<12; i
++) {
957 for (size_t j
=0; j
<4; j
++) {
959 block
|= tag
.sectors
[i
][j
];
961 Dbprintf("| %d | %08x |",i
,block
);
964 // Set up simulator mode, frequency divisor which will drive the FPGA
965 // and analog mux selection.
966 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
967 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
968 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
971 // Configure output pin that is connected to the FPGA (for modulating)
972 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
973 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
975 // Disable modulation at default, which means release resistance
978 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
979 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
981 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
982 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
983 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
985 // Disable timer during configuration
986 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
988 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
989 // external trigger rising edge, load RA on rising edge of TIOA.
990 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_RISING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_RISING
;
992 // Enable and reset counter
993 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
995 // Reset the received frame, frame count and timing info
996 memset(rx
,0x00,sizeof(rx
));
1001 while(!BUTTON_PRESS()) {
1005 // Receive frame, watch for at most T0*EOF periods
1006 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_EOF
) {
1007 // Check if rising edge in modulation is detected
1008 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1009 // Retrieve the new timing values
1010 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
;
1013 // Reset timer every frame, we have to capture the last edge for timing
1014 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1018 // Capture reader frame
1019 if(ra
>= HITAG_T_STOP
) {
1021 //DbpString("wierd0?");
1023 // Capture the T0 periods that have passed since last communication or field drop (reset)
1024 response
= (ra
- HITAG_T_LOW
);
1025 } else if(ra
>= HITAG_T_1_MIN
) {
1027 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1029 } else if(ra
>= HITAG_T_0_MIN
) {
1031 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1034 // Ignore wierd value, is to small to mean anything
1039 // Check if frame was captured
1043 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) {
1044 DbpString("Trace full");
1045 if (bQuitTraceFull
) {
1053 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1054 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1056 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1057 hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
);
1059 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1060 // not that since the clock counts since the rising edge, but T_Wait1 is
1061 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1062 // periods. The gap time T_Low varies (4..10). All timer values are in
1063 // terms of T0 units
1064 while(AT91C_BASE_TC0
->TC_CV
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
));
1066 // Send and store the tag answer (if there is any)
1068 // Transmit the tag frame
1069 hitag_send_frame(tx
,txlen
);
1070 // Store the frame in the trace
1072 if (!LogTraceHitag(tx
,txlen
,0,0,false)) {
1073 DbpString("Trace full");
1074 if (bQuitTraceFull
) {
1083 // Reset the received frame and response timing info
1084 memset(rx
,0x00,sizeof(rx
));
1087 // Enable and reset external trigger in timer for capturing future frames
1088 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1091 // Reset the frame length
1093 // Save the timer overflow, will be 0 when frame was received
1094 overflow
+= (AT91C_BASE_TC1
->TC_CV
/T0
);
1095 // Reset the timer to restart while-loop that receives frames
1096 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_SWTRG
;
1100 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1101 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1102 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1103 // Dbprintf("frame received: %d",frame_count);
1104 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1105 // DbpString("All done");
1108 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) {
1111 byte_t rx
[HITAG_FRAME_LEN
];
1113 byte_t txbuf
[HITAG_FRAME_LEN
];
1120 int t_wait
= HITAG_T_WAIT_MAX
;
1122 bool bQuitTraceFull
= false;
1124 // Reset the return status
1125 bSuccessful
= false;
1127 // Clean up trace and prepare it for storing frames
1128 iso14a_set_tracing(TRUE
);
1129 iso14a_clear_trace();
1130 DbpString("Starting Hitag reader family");
1132 // Check configuration
1134 case RHT2F_PASSWORD
: {
1135 Dbprintf("List identifier in password mode");
1136 memcpy(password
,htd
->pwd
.password
,4);
1138 bQuitTraceFull
= false;
1143 case RHT2F_AUTHENTICATE
: {
1144 DbpString("Authenticating using nr,ar pair:");
1145 memcpy(NrAr
,htd
->auth
.NrAr
,8);
1146 Dbhexdump(8,NrAr
,false);
1149 bAuthenticating
= false;
1150 bQuitTraceFull
= true;
1153 case RHT2F_CRYPTO
: {
1154 DbpString("Authenticating using key:");
1155 memcpy(key
,htd
->crypto
.key
,6);
1156 Dbhexdump(6,key
,false);
1160 bAuthenticating
= false;
1161 bQuitTraceFull
= true;
1164 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1165 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8));
1167 memcpy(NrAr
,auth_table
,8);
1168 bQuitTraceFull
= false;
1174 Dbprintf("Error, unknown function: %d",htf
);
1182 // Configure output and enable pin that is connected to the FPGA (for modulating)
1183 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
1184 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
1186 // Set fpga in edge detect with reader field, we can modulate as reader now
1187 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
| FPGA_LF_EDGE_DETECT_READER_FIELD
);
1189 // Set Frequency divisor which will drive the FPGA and analog mux selection
1190 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz
1191 SetAdcMuxFor(GPIO_MUXSEL_LOPKD
);
1194 // Disable modulation at default, which means enable the field
1197 // Give it a bit of time for the resonant antenna to settle.
1200 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1201 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC0
);
1203 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1204 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_TC1
);
1205 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_SSC_FRAME
;
1207 // Disable timer during configuration
1208 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1210 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1211 // external trigger rising edge, load RA on falling edge of TIOA.
1212 AT91C_BASE_TC1
->TC_CMR
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
| AT91C_TC_ETRGEDG_FALLING
| AT91C_TC_ABETRG
| AT91C_TC_LDRA_FALLING
;
1214 // Enable and reset counters
1215 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1216 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1218 // Reset the received frame, frame count and timing info
1224 // Tag specific configuration settings (sof, timings, etc.)
1229 DbpString("Configured for hitagS reader");
1230 } else if (htf
< 20) {
1234 DbpString("Configured for hitag1 reader");
1235 } else if (htf
< 30) {
1238 t_wait
= HITAG_T_WAIT_2
;
1239 DbpString("Configured for hitag2 reader");
1241 Dbprintf("Error, unknown hitag reader type: %d",htf
);
1245 while(!bStop
&& !BUTTON_PRESS()) {
1249 // Check if frame was captured and store it
1253 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) {
1254 DbpString("Trace full");
1255 if (bQuitTraceFull
) {
1264 // By default reset the transmission buffer
1267 case RHT2F_PASSWORD
: {
1268 bStop
= !hitag2_password(rx
,rxlen
,tx
,&txlen
);
1270 case RHT2F_AUTHENTICATE
: {
1271 bStop
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
);
1273 case RHT2F_CRYPTO
: {
1274 bStop
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
);
1276 case RHT2F_TEST_AUTH_ATTEMPTS
: {
1277 bStop
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
);
1280 Dbprintf("Error, unknown function: %d",htf
);
1285 // Send and store the reader command
1286 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1287 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1289 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1290 // Since the clock counts since the last falling edge, a 'one' means that the
1291 // falling edge occured halfway the period. with respect to this falling edge,
1292 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1293 // All timer values are in terms of T0 units
1294 while(AT91C_BASE_TC0
->TC_CV
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
)));
1296 // Transmit the reader frame
1297 hitag_reader_send_frame(tx
,txlen
);
1299 // Enable and reset external trigger in timer for capturing future frames
1300 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKEN
| AT91C_TC_SWTRG
;
1302 // Add transmitted frame to total count
1306 // Store the frame in the trace
1307 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) {
1308 if (bQuitTraceFull
) {
1317 // Reset values for receiving frames
1318 memset(rx
,0x00,sizeof(rx
));
1322 tag_sof
= reset_sof
;
1325 // Receive frame, watch for at most T0*EOF periods
1326 while (AT91C_BASE_TC1
->TC_CV
< T0
*HITAG_T_WAIT_MAX
) {
1327 // Check if falling edge in tag modulation is detected
1328 if(AT91C_BASE_TC1
->TC_SR
& AT91C_TC_LDRAS
) {
1329 // Retrieve the new timing values
1330 int ra
= (AT91C_BASE_TC1
->TC_RA
/T0
);
1332 // Reset timer every frame, we have to capture the last edge for timing
1333 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_SWTRG
;
1337 // Capture tag frame (manchester decoding using only falling edges)
1338 if(ra
>= HITAG_T_EOF
) {
1340 //DbpString("wierd1?");
1342 // Capture the T0 periods that have passed since last communication or field drop (reset)
1343 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1344 response
= ra
-HITAG_T_TAG_HALF_PERIOD
;
1345 } else if(ra
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) {
1346 // Manchester coding example |-_|_-|-_| (101)
1347 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1349 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1351 } else if(ra
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) {
1352 // Manchester coding example |_-|...|_-|-_| (0...01)
1353 rx
[rxlen
/ 8] |= 0 << (7-(rxlen
%8));
1355 // We have to skip this half period at start and add the 'one' the second time
1357 rx
[rxlen
/ 8] |= 1 << (7-(rxlen
%8));
1362 } else if(ra
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) {
1363 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1365 // Ignore bits that are transmitted during SOF
1368 // bit is same as last bit
1369 rx
[rxlen
/ 8] |= lastbit
<< (7-(rxlen
%8));
1373 // Ignore wierd value, is to small to mean anything
1377 // We can break this loop if we received the last bit from a frame
1378 if (AT91C_BASE_TC1
->TC_CV
> T0
*HITAG_T_EOF
) {
1385 AT91C_BASE_TC1
->TC_CCR
= AT91C_TC_CLKDIS
;
1386 AT91C_BASE_TC0
->TC_CCR
= AT91C_TC_CLKDIS
;
1387 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1388 Dbprintf("frame received: %d",frame_count
);
1389 DbpString("All done");
1390 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);