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" 
  33 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 
>= 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 size_t auth_table_pos 
= 0; 
 100 size_t auth_table_len 
= AUTH_TABLE_LENGTH
; 
 105 uint64_t cipher_state
; 
 107 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */ 
 108 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007. 
 109 // For educational purposes only. 
 110 // No warranties or guarantees of any kind. 
 111 // This code is released into the public domain by its author. 
 118 #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)) 
 119 #define rev16(x)                (rev8 (x)+(rev8 (x>> 8)<< 8)) 
 120 #define rev32(x)                (rev16(x)+(rev16(x>>16)<<16)) 
 121 #define rev64(x)                (rev32(x)+(rev32(x>>32)<<32)) 
 122 #define bit(x,n)                (((x)>>(n))&1) 
 123 #define bit32(x,n)              ((((x)[(n)>>5])>>((n)))&1) 
 124 #define inv32(x,i,n)    ((x)[(i)>>5]^=((u32)(n))<<((i)&31)) 
 125 #define rotl64(x, n)    ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63))) 
 127 // Single bit Hitag2 functions: 
 129 #define i4(x,a,b,c,d)   ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8)) 
 131 static const u32 ht2_f4a 
= 0x2C79;              // 0010 1100 0111 1001 
 132 static const u32 ht2_f4b 
= 0x6671;              // 0110 0110 0111 0001 
 133 static const u32 ht2_f5c 
= 0x7907287B;  // 0111 1001 0000 0111 0010 1000 0111 1011 
 135 static u32 
_f20 (const u64 x
) 
 139         i5 
= ((ht2_f4a 
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1 
 140            + ((ht2_f4b 
>> i4 (x
, 7,11,13,14)) & 1)* 2 
 141            + ((ht2_f4b 
>> i4 (x
,16,20,22,25)) & 1)* 4 
 142            + ((ht2_f4b 
>> i4 (x
,27,28,30,32)) & 1)* 8 
 143            + ((ht2_f4a 
>> i4 (x
,33,42,43,45)) & 1)*16; 
 145         return (ht2_f5c 
>> i5
) & 1; 
 148 static u64 
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
) 
 151         u64                                     x 
= ((key 
& 0xFFFF) << 32) + serial
; 
 153         for (i 
= 0; i 
< 32; i
++) 
 156                 x 
+= (u64
) (_f20 (x
) ^ (((IV 
>> i
) ^ (key 
>> (i
+16))) & 1)) << 47; 
 161 static u64 
_hitag2_round (u64 
*state
) 
 166          ((((x 
>>  0) ^ (x 
>>  2) ^ (x 
>>  3) ^ (x 
>>  6) 
 167           ^ (x 
>>  7) ^ (x 
>>  8) ^ (x 
>> 16) ^ (x 
>> 22) 
 168           ^ (x 
>> 23) ^ (x 
>> 26) ^ (x 
>> 30) ^ (x 
>> 41) 
 169           ^ (x 
>> 42) ^ (x 
>> 43) ^ (x 
>> 46) ^ (x 
>> 47)) & 1) << 47); 
 175 static u32 
_hitag2_byte (u64 
* x
) 
 179         for (i 
= 0, c 
= 0; i 
< 8; i
++) c 
+= (u32
) _hitag2_round (x
) << (i
^7); 
 183 int hitag2_reset(void) 
 185         tag
.state 
= TAG_STATE_RESET
; 
 186         tag
.crypto_active 
= 0; 
 190 int hitag2_init(void) 
 192 //      memcpy(&tag, &resetdata, sizeof(tag)); 
 197 static void hitag2_cipher_reset(struct hitag2_tag 
*tag
, const byte_t 
*iv
) 
 199         uint64_t key 
=  ((uint64_t)tag
->sectors
[2][2]) | 
 200                   ((uint64_t)tag
->sectors
[2][3] << 8) | 
 201                   ((uint64_t)tag
->sectors
[1][0] << 16) | 
 202                   ((uint64_t)tag
->sectors
[1][1] << 24) | 
 203                   ((uint64_t)tag
->sectors
[1][2] << 32) | 
 204                   ((uint64_t)tag
->sectors
[1][3] << 40); 
 205         uint32_t uid 
=  ((uint32_t)tag
->sectors
[0][0]) | 
 206                   ((uint32_t)tag
->sectors
[0][1] << 8) | 
 207                   ((uint32_t)tag
->sectors
[0][2] << 16) | 
 208                   ((uint32_t)tag
->sectors
[0][3] << 24); 
 209         uint32_t iv_ 
= (((uint32_t)(iv
[0]))) | 
 210                         (((uint32_t)(iv
[1])) << 8) | 
 211                         (((uint32_t)(iv
[2])) << 16) | 
 212                         (((uint32_t)(iv
[3])) << 24); 
 213         tag
->cs 
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
)); 
 216 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t 
*authenticator_is
) 
 218         byte_t authenticator_should
[4]; 
 219         authenticator_should
[0] = ~_hitag2_byte(cs
); 
 220         authenticator_should
[1] = ~_hitag2_byte(cs
); 
 221         authenticator_should
[2] = ~_hitag2_byte(cs
); 
 222         authenticator_should
[3] = ~_hitag2_byte(cs
); 
 223         return (memcmp(authenticator_should
, authenticator_is
, 4) == 0); 
 226 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t 
*data
, unsigned int bytes
, unsigned int bits
) 
 229         for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
); 
 230         for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
); 
 234 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK) 
 235 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz 
 236 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier) 
 237 // T0 = TIMER_CLOCK1 / 125000 = 192 
 240 #define SHORT_COIL()    LOW(GPIO_SSC_DOUT) 
 241 #define OPEN_COIL()             HIGH(GPIO_SSC_DOUT) 
 243 #define HITAG_FRAME_LEN 20 
 244 #define HITAG_T_STOP  36 /* T_EOF should be > 36 */ 
 245 #define HITAG_T_LOW             8  /* T_LOW should be 4..10 */ 
 246 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */ 
 247 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */ 
 248 //#define HITAG_T_EOF   40 /* T_EOF should be > 36 */ 
 249 #define HITAG_T_EOF   80         /* T_EOF should be > 36 */ 
 250 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */ 
 251 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */ 
 252 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */ 
 254 #define HITAG_T_TAG_ONE_HALF_PERIOD                     10 
 255 #define HITAG_T_TAG_TWO_HALF_PERIOD                     25 
 256 #define HITAG_T_TAG_THREE_HALF_PERIOD           41  
 257 #define HITAG_T_TAG_FOUR_HALF_PERIOD    57  
 259 #define HITAG_T_TAG_HALF_PERIOD                                 16 
 260 #define HITAG_T_TAG_FULL_PERIOD                                 32 
 262 #define HITAG_T_TAG_CAPTURE_ONE_HALF            13 
 263 #define HITAG_T_TAG_CAPTURE_TWO_HALF            25 
 264 #define HITAG_T_TAG_CAPTURE_THREE_HALF  41  
 265 #define HITAG_T_TAG_CAPTURE_FOUR_HALF   57  
 268 static void hitag_send_bit(int bit
) { 
 270         // Reset clock for the next bit  
 271         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 273         // Fixed modulation, earlier proxmark version used inverted signal 
 275                 // Manchester: Unloaded, then loaded |__--| 
 277                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_HALF_PERIOD
); 
 279                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_FULL_PERIOD
); 
 281                 // Manchester: Loaded, then unloaded |--__| 
 283                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_HALF_PERIOD
); 
 285                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_FULL_PERIOD
); 
 290 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
) 
 292         // Send start of frame 
 293         for(size_t i
=0; i
<5; i
++) { 
 297         // Send the content of the frame 
 298         for(size_t i
=0; i
<frame_len
; i
++) { 
 299                 hitag_send_bit((frame
[i
/8] >> (7-(i%8
)))&1); 
 302         // Drop the modulation 
 306 void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) 
 309     auth_table 
= (byte_t 
*)BigBuf_get_addr() + AUTH_TABLE_OFFSET
; 
 310         byte_t rx_air
[HITAG_FRAME_LEN
]; 
 312         // Copy the (original) received frame how it is send over the air 
 313         memcpy(rx_air
,rx
,nbytes(rxlen
)); 
 315         if(tag
.crypto_active
) { 
 316                 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen%8
); 
 319         // Reset the transmission frame length  
 322         // Try to find out which command was send by selecting on length (in bits) 
 324                 // Received 11000 from the reader, request for UID, send UID  
 326                         // Always send over the air in the clear plaintext mode 
 327                         if(rx_air
[0] != 0xC0) { 
 332                         memcpy(tx
,tag
.sectors
[0],4); 
 333                         tag
.crypto_active 
= 0; 
 337                 // Read/Write command: ..xx x..y  yy with yyy == ~xxx, xxx is sector number  
 339                         unsigned int sector 
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07); 
 340                         // Verify complement of sector index 
 341                         if(sector 
!= ((rx
[0]>>3)&0x07)) { 
 342                                 //DbpString("Transmission error (read/write)"); 
 346                         switch (rx
[0] & 0xC6) { 
 347                                 // Read command: 11xx x00y 
 349                                         memcpy(tx
,tag
.sectors
[sector
],4); 
 353                                  // Inverted Read command: 01xx x10y 
 355                                         for (size_t i
=0; i
<4; i
++) { 
 356                                                 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff; 
 361                                 // Write command: 10xx x01y 
 363                                         // Prepare write, acknowledge by repeating command 
 364                                         memcpy(tx
,rx
,nbytes(rxlen
)); 
 366                                         tag
.active_sector 
= sector
; 
 367                                         tag
.state
=TAG_STATE_WRITING
; 
 372                                         Dbprintf("Uknown command: %02x %02x",rx
[0],rx
[1]); 
 379                 // Writing data or Reader password 
 381                         if(tag
.state 
== TAG_STATE_WRITING
) { 
 382                                 // These are the sector contents to be written. We don't have to do anything else. 
 383                                 memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
)); 
 384                                 tag
.state
=TAG_STATE_RESET
; 
 387                                 // Received RWD password, respond with configuration and our password 
 388                                 if(memcmp(rx
,tag
.sectors
[1],4) != 0) { 
 389                                         DbpString("Reader password is wrong"); 
 393                                 memcpy(tx
,tag
.sectors
[3],4); 
 398                 // Received RWD authentication challenge and respnse 
 400                         // Store the authentication attempt 
 401                         if (auth_table_len 
< (AUTH_TABLE_LENGTH
-8)) { 
 402                                 memcpy(auth_table
+auth_table_len
,rx
,8); 
 406                         // Reset the cipher state 
 407                         hitag2_cipher_reset(&tag
,rx
); 
 408                         // Check if the authentication was correct 
 409                         if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) { 
 410                                 // The reader failed to authenticate, do nothing 
 411                                 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]); 
 414                         // Succesful, but commented out reporting back to the Host, this may delay to much. 
 415                         // 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]); 
 417                         // Activate encryption algorithm for all further communication 
 418                         tag
.crypto_active 
= 1; 
 420                         // Use the tag password as response 
 421                         memcpy(tx
,tag
.sectors
[3],4); 
 427 //      LogTraceHitag(rx,rxlen,0,0,false); 
 428 //      LogTraceHitag(tx,*txlen,0,0,true); 
 430         if(tag
.crypto_active
) { 
 431                 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen%8
); 
 435 static void hitag_reader_send_bit(int bit
) { 
 437         // Reset clock for the next bit  
 438         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 440         // Binary puls length modulation (BPLM) is used to encode the data stream 
 441         // This means that a transmission of a one takes longer than that of a zero 
 443         // Enable modulation, which means, drop the the field 
 446         // Wait for 4-10 times the carrier period 
 447         while(AT91C_BASE_TC0
->TC_CV 
< T0
*6); 
 450         // Disable modulation, just activates the field again 
 455                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*22); 
 456                 //              SpinDelayUs(16*8); 
 459                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*28); 
 460                 //              SpinDelayUs(22*8); 
 465 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
) 
 467         // Send the content of the frame 
 468         for(size_t i
=0; i
<frame_len
; i
++) { 
 469                 hitag_reader_send_bit((frame
[i
/8] >> (7-(i%8
)))&1); 
 472         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 473         // Enable modulation, which means, drop the the field 
 475         // Wait for 4-10 times the carrier period 
 476         while(AT91C_BASE_TC0
->TC_CV 
< T0
*6); 
 477         // Disable modulation, just activates the field again 
 483 bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 484         // Reset the transmission frame length 
 487         // Try to find out which command was send by selecting on length (in bits) 
 489                 // No answer, try to resurrect 
 491                         // Stop if there is no answer (after sending password) 
 493                                 DbpString("Password failed!"); 
 497                         memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 500                 // Received UID, tag password 
 504                                 memcpy(tx
,password
,4); 
 506         memcpy(tag
.sectors
[blocknr
],rx
,4); 
 511                                 //store password in block1, the TAG answers with Block3, but we need the password in memory 
 512                                 memcpy(tag
.sectors
[blocknr
],tx
,4); 
 514                                 memcpy(tag
.sectors
[blocknr
],rx
,4); 
 519                           DbpString("Read succesful!"); 
 524                         tx
[0] = 0xc0 | (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 525                         tx
[1] = ((blocknr
^7) << 6); 
 529                 // Unexpected response 
 531                         Dbprintf("Uknown frame length: %d",rxlen
); 
 538 bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 539         // Reset the transmission frame length 
 543                 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen%8
); 
 546         // Try to find out which command was send by selecting on length (in bits) 
 548       // No answer, try to resurrect 
 550                         // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 552         // Failed during authentication 
 553         if (bAuthenticating
) { 
 554           DbpString("Authentication failed!"); 
 557           // Failed reading a block, could be (read/write) locked, skip block and re-authenticate 
 559             // Write the low part of the key in memory 
 560             memcpy(tag
.sectors
[1],key
+2,4); 
 561           } else if (blocknr 
== 2) { 
 562             // Write the high part of the key in memory 
 563             tag
.sectors
[2][0] = 0x00; 
 564             tag
.sectors
[2][1] = 0x00; 
 565             tag
.sectors
[2][2] = key
[0]; 
 566             tag
.sectors
[2][3] = key
[1]; 
 568             // Just put zero's in the memory (of the unreadable block) 
 569             memset(tag
.sectors
[blocknr
],0x00,4); 
 576         memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 580       // Received UID, crypto tag answer 
 583         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; 
 584         uint32_t ui32uid 
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24; 
 585         cipher_state 
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0); 
 588         hitag2_cipher_transcrypt(&cipher_state
,tx
+4,4,0); 
 591         bAuthenticating 
= true; 
 593         // Check if we received answer tag (at) 
 594         if (bAuthenticating
) { 
 595           bAuthenticating 
= false; 
 597           // Store the received block 
 598           memcpy(tag
.sectors
[blocknr
],rx
,4); 
 602           DbpString("Read succesful!"); 
 607         tx
[0] = 0xc0 | (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 608         tx
[1] = ((blocknr
^7) << 6); 
 612       // Unexpected response 
 614                         Dbprintf("Uknown frame length: %d",rxlen
); 
 621     // We have to return now to avoid double encryption 
 622     if (!bAuthenticating
) { 
 623       hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen%8
); 
 631 bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 632         // Reset the transmission frame length  
 635         // Try to find out which command was send by selecting on length (in bits) 
 637                 // No answer, try to resurrect 
 639                         // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 641                                 DbpString("Authentication failed!"); 
 645                         memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 648                 // Received UID, crypto tag answer 
 655                                 DbpString("Authentication succesful!"); 
 656                                 // We are done... for now 
 661                 // Unexpected response 
 663                         Dbprintf("Uknown frame length: %d",rxlen
); 
 671 bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 674     auth_table 
= (byte_t 
*)BigBuf_get_addr() + AUTH_TABLE_OFFSET
; 
 676         // Reset the transmission frame length  
 679         // Try to find out which command was send by selecting on length (in bits) 
 681                         // No answer, try to resurrect 
 683                         // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 685                                 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]); 
 687         // Removing failed entry from authentiations table 
 688         memcpy(auth_table
+auth_table_pos
,auth_table
+auth_table_pos
+8,8); 
 691         // Return if we reached the end of the authentiactions table 
 693                                 if (auth_table_pos 
== auth_table_len
) { 
 697         // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry) 
 698                                 memcpy(NrAr
,auth_table
+auth_table_pos
,8); 
 701                         memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 704                         // Received UID, crypto tag answer, or read block response 
 711                                 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]); 
 713                                 if ((auth_table_pos
+8) == auth_table_len
) { 
 717                                 memcpy(NrAr
,auth_table
+auth_table_pos
,8); 
 722                         Dbprintf("Uknown frame length: %d",rxlen
); 
 730 void SnoopHitag(uint32_t type
) { 
 739         byte_t rx
[HITAG_FRAME_LEN
]; 
 742         // Clean up trace and prepare it for storing frames 
 743         iso14a_set_tracing(TRUE
); 
 744         iso14a_clear_trace(); 
 749     auth_table 
= (byte_t 
*)BigBuf_get_addr() + AUTH_TABLE_OFFSET
; 
 750         memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
); 
 752         DbpString("Starting Hitag2 snoop"); 
 755         // Set up eavesdropping mode, frequency divisor which will drive the FPGA 
 756         // and analog mux selection. 
 757         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
 758         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT  
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
); 
 759         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
 760         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
 763         // Configure output pin that is connected to the FPGA (for modulating) 
 764         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 765         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 767         // Disable modulation, we are going to eavesdrop, not modulate ;) 
 770         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames 
 771         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
 772         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
 774   // Disable timer during configuration  
 775         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
 777         // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
 778         // external trigger rising edge, load RA on rising edge of TIOA. 
 779         uint32_t t1_channel_mode 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_BOTH 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_BOTH
; 
 780         AT91C_BASE_TC1
->TC_CMR 
= t1_channel_mode
; 
 782         // Enable and reset counter 
 783         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
 785         // Reset the received frame, frame count and timing info 
 786         memset(rx
,0x00,sizeof(rx
)); 
 790         reader_frame 
= false; 
 795         while(!BUTTON_PRESS()) { 
 799                 // Receive frame, watch for at most T0*EOF periods 
 800                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_EOF
) { 
 801                         // Check if rising edge in modulation is detected 
 802                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
 803                                 // Retrieve the new timing values  
 804                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
 806                                 // Find out if we are dealing with a rising or falling edge 
 807                                 rising_edge 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_FRAME
) > 0; 
 809                                 // Shorter periods will only happen with reader frames 
 810                                 if (!reader_frame 
&& rising_edge 
&& ra 
< HITAG_T_TAG_CAPTURE_ONE_HALF
) { 
 811                                         // Switch from tag to reader capture 
 814                                         memset(rx
,0x00,sizeof(rx
)); 
 818                                 // Only handle if reader frame and rising edge, or tag frame and falling edge 
 819                                 if (reader_frame 
!= rising_edge
) { 
 824                                 // Add the buffered timing values of earlier captured edges which were skipped 
 830                                         // Capture reader frame 
 831                                         if(ra 
>= HITAG_T_STOP
) { 
 833                                                         //DbpString("wierd0?"); 
 835                                                 // Capture the T0 periods that have passed since last communication or field drop (reset) 
 836                                                 response 
= (ra 
- HITAG_T_LOW
); 
 837                                         } else if(ra 
>= HITAG_T_1_MIN 
) { 
 839                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 841                                         } else if(ra 
>= HITAG_T_0_MIN
) { 
 843                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 846                                                 // Ignore wierd value, is to small to mean anything 
 850                                         // Capture tag frame (manchester decoding using only falling edges) 
 851                                         if(ra 
>= HITAG_T_EOF
) { 
 853                                                         //DbpString("wierd1?"); 
 855                                                 // Capture the T0 periods that have passed since last communication or field drop (reset) 
 856                                                 // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
 857                                                 response 
= ra
-HITAG_T_TAG_HALF_PERIOD
; 
 858                                         } else if(ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
 859                                                 // Manchester coding example |-_|_-|-_| (101) 
 860                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 862                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 864                                         } else if(ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
 865                                                 // Manchester coding example |_-|...|_-|-_| (0...01) 
 866                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 868                                                 // We have to skip this half period at start and add the 'one' the second time  
 870                                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 875                                         } else if(ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
 876                                                 // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
 878                                                         // Ignore bits that are transmitted during SOF 
 881                                                         // bit is same as last bit 
 882                                                         rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
 886                                                 // Ignore wierd value, is to small to mean anything 
 892                 // Check if frame was captured 
 895                         if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) { 
 896                                 DbpString("Trace full"); 
 900                         // Check if we recognize a valid authentication attempt 
 901                         if (nbytes(rxlen
) == 8) { 
 902                                 // Store the authentication attempt 
 903                                 if (auth_table_len 
< (AUTH_TABLE_LENGTH
-8)) { 
 904                                         memcpy(auth_table
+auth_table_len
,rx
,8); 
 909                         // Reset the received frame and response timing info 
 910                         memset(rx
,0x00,sizeof(rx
)); 
 912                         reader_frame 
= false; 
 921                         // Save the timer overflow, will be 0 when frame was received 
 922                         overflow 
+= (AT91C_BASE_TC1
->TC_CV
/T0
); 
 924                 // Reset the frame length 
 926                 // Reset the timer to restart while-loop that receives frames 
 927                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_SWTRG
; 
 933         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
 934     AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
 935         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
 938 //      Dbprintf("frame received: %d",frame_count); 
 939 //      Dbprintf("Authentication Attempts: %d",(auth_table_len/8)); 
 940 //      DbpString("All done"); 
 943 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) { 
 947         byte_t rx
[HITAG_FRAME_LEN
]; 
 949         byte_t tx
[HITAG_FRAME_LEN
]; 
 951         bool bQuitTraceFull 
= false; 
 954         // Clean up trace and prepare it for storing frames 
 955         iso14a_set_tracing(TRUE
); 
 956         iso14a_clear_trace(); 
 960     auth_table 
= (byte_t 
*)BigBuf_get_addr() + AUTH_TABLE_OFFSET
; 
 961         memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
); 
 963         DbpString("Starting Hitag2 simulation"); 
 967         if (tag_mem_supplied
) { 
 968                 DbpString("Loading hitag2 memory..."); 
 969                 memcpy((byte_t
*)tag
.sectors
,data
,48); 
 973         for (size_t i
=0; i
<12; i
++) { 
 974                 for (size_t j
=0; j
<4; j
++) { 
 976                         block 
|= tag
.sectors
[i
][j
]; 
 978                 Dbprintf("| %d | %08x |",i
,block
); 
 981         // Set up simulator mode, frequency divisor which will drive the FPGA 
 982         // and analog mux selection. 
 983         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
 984         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT 
| FPGA_LF_EDGE_DETECT_READER_FIELD
); 
 985         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
 986         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
 989         // Configure output pin that is connected to the FPGA (for modulating) 
 990         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 991         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 993         // Disable modulation at default, which means release resistance 
 996         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
 997         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
 999         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames 
1000         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1001         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1003   // Disable timer during configuration  
1004         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1006         // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1007         // external trigger rising edge, load RA on rising edge of TIOA. 
1008         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_RISING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_RISING
; 
1010         // Reset the received frame, frame count and timing info 
1011         memset(rx
,0x00,sizeof(rx
)); 
1016         // Enable and reset counter 
1017         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1019         while(!BUTTON_PRESS()) { 
1023                 // Receive frame, watch for at most T0*EOF periods 
1024                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_EOF
) { 
1025                         // Check if rising edge in modulation is detected 
1026                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1027                                 // Retrieve the new timing values  
1028                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
; 
1031                                 // Reset timer every frame, we have to capture the last edge for timing 
1032                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1036                                 // Capture reader frame 
1037                                 if(ra 
>= HITAG_T_STOP
) { 
1039                                                 //DbpString("wierd0?"); 
1041                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1042                                         response 
= (ra 
- HITAG_T_LOW
); 
1043                                 } else if(ra 
>= HITAG_T_1_MIN 
) { 
1045                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1047                                 } else if(ra 
>= HITAG_T_0_MIN
) { 
1049                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1052                                         // Ignore wierd value, is to small to mean anything 
1057                 // Check if frame was captured 
1061                                 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) { 
1062                                         DbpString("Trace full"); 
1063                                         if (bQuitTraceFull
) { 
1071                         // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1072                         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1074                         // Process the incoming frame (rx) and prepare the outgoing frame (tx) 
1075                         hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
); 
1077                         // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit, 
1078                         // not that since the clock counts since the rising edge, but T_Wait1 is 
1079                         // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low) 
1080                         // periods. The gap time T_Low varies (4..10). All timer values are in  
1081                         // terms of T0 units 
1082                         while(AT91C_BASE_TC0
->TC_CV 
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
)); 
1084                         // Send and store the tag answer (if there is any) 
1086                                 // Transmit the tag frame 
1087                                 hitag_send_frame(tx
,txlen
); 
1088                                 // Store the frame in the trace 
1090                                         if (!LogTraceHitag(tx
,txlen
,0,0,false)) { 
1091                                                 DbpString("Trace full"); 
1092                                                 if (bQuitTraceFull
) { 
1101                         // Reset the received frame and response timing info 
1102                         memset(rx
,0x00,sizeof(rx
)); 
1105                         // Enable and reset external trigger in timer for capturing future frames 
1106                         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1109                 // Reset the frame length 
1111                 // Save the timer overflow, will be 0 when frame was received 
1112                 overflow 
+= (AT91C_BASE_TC1
->TC_CV
/T0
); 
1113                 // Reset the timer to restart while-loop that receives frames 
1114                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_SWTRG
; 
1118         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1119         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1120         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1122         DbpString("Sim Stopped"); 
1126 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) { 
1129         byte_t rx
[HITAG_FRAME_LEN
]; 
1131         byte_t txbuf
[HITAG_FRAME_LEN
]; 
1138         int t_wait 
= HITAG_T_WAIT_MAX
; 
1140         bool bQuitTraceFull 
= false; 
1142   FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1143   // Reset the return status 
1144   bSuccessful 
= false; 
1146         // Clean up trace and prepare it for storing frames 
1147         iso14a_set_tracing(TRUE
); 
1148         iso14a_clear_trace(); 
1150     auth_table 
= (byte_t 
*)BigBuf_get_addr() + AUTH_TABLE_OFFSET
; 
1152         DbpString("Starting Hitag reader family"); 
1154         // Check configuration 
1156                 case RHT2F_PASSWORD
: { 
1157       Dbprintf("List identifier in password mode"); 
1158                         memcpy(password
,htd
->pwd
.password
,4); 
1160                         bQuitTraceFull 
= false; 
1165                 case RHT2F_AUTHENTICATE
: { 
1166                         DbpString("Authenticating using nr,ar pair:"); 
1167                         memcpy(NrAr
,htd
->auth
.NrAr
,8); 
1168                         Dbhexdump(8,NrAr
,false); 
1171       bAuthenticating 
= false; 
1172                         bQuitTraceFull 
= true; 
1175                 case RHT2F_CRYPTO
: { 
1176                         DbpString("Authenticating using key:"); 
1177                         memcpy(key
,htd
->crypto
.key
,4);    //HACK; 4 or 6??  I read both in the code. 
1178                         Dbhexdump(6,key
,false); 
1182       bAuthenticating 
= false; 
1183                         bQuitTraceFull 
= true; 
1186                 case RHT2F_TEST_AUTH_ATTEMPTS
: { 
1187                         Dbprintf("Testing %d authentication attempts",(auth_table_len
/8)); 
1189                         memcpy(NrAr
,auth_table
,8); 
1190                         bQuitTraceFull 
= false; 
1196                         Dbprintf("Error, unknown function: %d",htf
); 
1204         // Configure output and enable pin that is connected to the FPGA (for modulating) 
1205         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1206         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1208         // Set fpga in edge detect with reader field, we can modulate as reader now 
1209         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT 
| FPGA_LF_EDGE_DETECT_READER_FIELD
); 
1211         // Set Frequency divisor which will drive the FPGA and analog mux selection 
1212         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1213         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1216         // Disable modulation at default, which means enable the field 
1219         // Give it a bit of time for the resonant antenna to settle. 
1222         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1223         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1225         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames 
1226         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1227         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1229     // Disable timer during configuration        
1230         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1232         // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1233         // external trigger rising edge, load RA on falling edge of TIOA. 
1234         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_FALLING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_FALLING
; 
1236         // Enable and reset counters 
1237         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1238         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1240         // Reset the received frame, frame count and timing info 
1246   // Tag specific configuration settings (sof, timings, etc.) 
1251     DbpString("Configured for hitagS reader"); 
1252   } else if (htf 
< 20) { 
1256     DbpString("Configured for hitag1 reader"); 
1257   } else if (htf 
< 30) { 
1260     t_wait 
= HITAG_T_WAIT_2
; 
1261     DbpString("Configured for hitag2 reader"); 
1263     Dbprintf("Error, unknown hitag reader type: %d",htf
); 
1267         while(!bStop 
&& !BUTTON_PRESS()) { 
1271                 // Check if frame was captured and store it 
1275                                 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) { 
1276                                         DbpString("Trace full"); 
1277                                         if (bQuitTraceFull
) { 
1286                 // By default reset the transmission buffer 
1289                         case RHT2F_PASSWORD
: { 
1290                                 bStop 
= !hitag2_password(rx
,rxlen
,tx
,&txlen
); 
1292                         case RHT2F_AUTHENTICATE
: { 
1293                                 bStop 
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
); 
1295                         case RHT2F_CRYPTO
: { 
1296                                 bStop 
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
); 
1298                         case RHT2F_TEST_AUTH_ATTEMPTS
: { 
1299                                 bStop 
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
); 
1302                                 Dbprintf("Error, unknown function: %d",htf
); 
1307                 // Send and store the reader command 
1308                 // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1309                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1311                 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, 
1312                 // Since the clock counts since the last falling edge, a 'one' means that the 
1313                 // falling edge occured halfway the period. with respect to this falling edge, 
1314                 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. 
1315                 // All timer values are in terms of T0 units 
1316                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
))); 
1318                 // Transmit the reader frame 
1319                 hitag_reader_send_frame(tx
,txlen
); 
1321                 // Enable and reset external trigger in timer for capturing future frames 
1322                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1324                 // Add transmitted frame to total count 
1328                                 // Store the frame in the trace 
1329                                 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) { 
1330                                         if (bQuitTraceFull
) { 
1339                 // Reset values for receiving frames 
1340                 memset(rx
,0x00,sizeof(rx
)); 
1344                 tag_sof 
= reset_sof
; 
1347                 // Receive frame, watch for at most T0*EOF periods 
1348                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_WAIT_MAX
) { 
1349                         // Check if falling edge in tag modulation is detected 
1350                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1351                                 // Retrieve the new timing values  
1352                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
1354                                 // Reset timer every frame, we have to capture the last edge for timing 
1355                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1359                                 // Capture tag frame (manchester decoding using only falling edges) 
1360                                 if(ra 
>= HITAG_T_EOF
) { 
1362                                                 //DbpString("wierd1?"); 
1364                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1365                                         // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
1366                                         response 
= ra
-HITAG_T_TAG_HALF_PERIOD
; 
1367                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
1368                                         // Manchester coding example |-_|_-|-_| (101) 
1369                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1371                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1373                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
1374                                         // Manchester coding example |_-|...|_-|-_| (0...01) 
1375                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1377                                         // We have to skip this half period at start and add the 'one' the second time  
1379                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1384                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
1385                                         // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
1387                                                 // Ignore bits that are transmitted during SOF 
1390                                                 // bit is same as last bit 
1391                                                 rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
1395                                         // Ignore wierd value, is to small to mean anything 
1399                         // We can break this loop if we received the last bit from a frame 
1400                         if (AT91C_BASE_TC1
->TC_CV 
> T0
*HITAG_T_EOF
) { 
1407         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1408         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1409         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1410         Dbprintf("frame received: %d",frame_count
); 
1411   DbpString("All done"); 
1412   cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);