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 //----------------------------------------------------------------------------- 
  21 #include "proxmark3.h" 
  27 #include "fpgaloader.h" 
  32 static bool bAuthenticating
; 
  34 static bool bSuccessful
; 
  41                 TAG_STATE_RESET      
= 0x01,       // Just powered up, awaiting GetSnr 
  42                 TAG_STATE_ACTIVATING 
= 0x02 ,      // In activation phase (password mode), sent UID, awaiting reader password 
  43                 TAG_STATE_ACTIVATED  
= 0x03,       // Activation complete, awaiting read/write commands 
  44                 TAG_STATE_WRITING    
= 0x04,       // In write command, awaiting sector contents to be written 
  46         unsigned int active_sector
; 
  49         byte_t sectors
[12][4]; 
  52 static struct hitag2_tag tag 
= { 
  53         .state 
= TAG_STATE_RESET
, 
  54         .sectors 
= {                         // Password mode:               | Crypto mode: 
  55                 [0]  = { 0x02, 0x4e, 0x02, 0x20}, // UID                          | UID 
  56                 [1]  = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD                 | 32 bit LSB key 
  57                 [2]  = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved                     | 16 bit MSB key, 16 bit reserved 
  58                 [3]  = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG  | Configuration, password TAG 
  59                 [4]  = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK 
  60                 [5]  = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU 
  61                 [6]  = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: .... 
  62                 [7]  = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU 
  63                 [8]  = { 0x00, 0x00, 0x00, 0x00}, // RSK Low 
  64                 [9]  = { 0x00, 0x00, 0x00, 0x00}, // RSK High 
  65                 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF 
  66                 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC 
  71         WRITE_STATE_START 
= 0x0, 
  72         WRITE_STATE_PAGENUM_WRITTEN
, 
  77 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces. 
  78 // Historically it used to be FREE_BUFFER_SIZE, which was 2744. 
  79 #define AUTH_TABLE_LENGTH 2744 
  80 static byte_t
* auth_table
; 
  81 static size_t auth_table_pos 
= 0; 
  82 static size_t auth_table_len 
= AUTH_TABLE_LENGTH
; 
  84 static byte_t password
[4]; 
  85 static byte_t NrAr
[8]; 
  87 static byte_t writedata
[4]; 
  88 static uint64_t cipher_state
; 
  90 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */ 
  91 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007. 
  92 // For educational purposes only. 
  93 // No warranties or guarantees of any kind. 
  94 // This code is released into the public domain by its author. 
 101 #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)) 
 102 #define rev16(x)        (rev8 (x)+(rev8 (x>> 8)<< 8)) 
 103 #define rev32(x)        (rev16(x)+(rev16(x>>16)<<16)) 
 104 #define rev64(x)        (rev32(x)+(rev32(x>>32)<<32)) 
 105 #define bit(x,n)        (((x)>>(n))&1) 
 106 #define bit32(x,n)      ((((x)[(n)>>5])>>((n)))&1) 
 107 #define inv32(x,i,n)    ((x)[(i)>>5]^=((u32)(n))<<((i)&31)) 
 108 #define rotl64(x, n)    ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63))) 
 110 // Single bit Hitag2 functions: 
 112 #define i4(x,a,b,c,d)   ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8)) 
 114 static const u32 ht2_f4a 
= 0x2C79;      // 0010 1100 0111 1001 
 115 static const u32 ht2_f4b 
= 0x6671;      // 0110 0110 0111 0001 
 116 static const u32 ht2_f5c 
= 0x7907287B;  // 0111 1001 0000 0111 0010 1000 0111 1011 
 118 static u32 
_f20 (const u64 x
) 
 122         i5 
= ((ht2_f4a 
>> i4 (x
, 1, 2, 4, 5)) & 1)* 1 
 123                 + ((ht2_f4b 
>> i4 (x
, 7,11,13,14)) & 1)* 2 
 124                 + ((ht2_f4b 
>> i4 (x
,16,20,22,25)) & 1)* 4 
 125                 + ((ht2_f4b 
>> i4 (x
,27,28,30,32)) & 1)* 8 
 126                 + ((ht2_f4a 
>> i4 (x
,33,42,43,45)) & 1)*16; 
 128         return (ht2_f5c 
>> i5
) & 1; 
 131 static u64 
_hitag2_init (const u64 key
, const u32 serial
, const u32 IV
) 
 134         u64                 x 
= ((key 
& 0xFFFF) << 32) + serial
; 
 136         for (i 
= 0; i 
< 32; i
++) 
 139                 x 
+= (u64
) (_f20 (x
) ^ (((IV 
>> i
) ^ (key 
>> (i
+16))) & 1)) << 47; 
 144 static u64 
_hitag2_round (u64 
*state
) 
 149                 ((((x 
>>  0) ^ (x 
>>  2) ^ (x 
>>  3) ^ (x 
>>  6) 
 150                    ^ (x 
>>  7) ^ (x 
>>  8) ^ (x 
>> 16) ^ (x 
>> 22) 
 151                    ^ (x 
>> 23) ^ (x 
>> 26) ^ (x 
>> 30) ^ (x 
>> 41) 
 152                    ^ (x 
>> 42) ^ (x 
>> 43) ^ (x 
>> 46) ^ (x 
>> 47)) & 1) << 47); 
 158 static u32 
_hitag2_byte (u64 
* x
) 
 162         for (i 
= 0, c 
= 0; i 
< 8; i
++) c 
+= (u32
) _hitag2_round (x
) << (i
^7); 
 166 static int hitag2_reset(void) 
 168         tag
.state 
= TAG_STATE_RESET
; 
 169         tag
.crypto_active 
= 0; 
 173 static int hitag2_init(void) 
 175 //  memcpy(&tag, &resetdata, sizeof(tag)); 
 180 static void hitag2_cipher_reset(struct hitag2_tag 
*tag
, const byte_t 
*iv
) 
 182         uint64_t key 
=  ((uint64_t)tag
->sectors
[2][2]) | 
 183                 ((uint64_t)tag
->sectors
[2][3] << 8) | 
 184                 ((uint64_t)tag
->sectors
[1][0] << 16) | 
 185                 ((uint64_t)tag
->sectors
[1][1] << 24) | 
 186                 ((uint64_t)tag
->sectors
[1][2] << 32) | 
 187                 ((uint64_t)tag
->sectors
[1][3] << 40); 
 188         uint32_t uid 
=  ((uint32_t)tag
->sectors
[0][0]) | 
 189                 ((uint32_t)tag
->sectors
[0][1] << 8) | 
 190                 ((uint32_t)tag
->sectors
[0][2] << 16) | 
 191                 ((uint32_t)tag
->sectors
[0][3] << 24); 
 192         uint32_t iv_ 
= (((uint32_t)(iv
[0]))) | 
 193                 (((uint32_t)(iv
[1])) << 8) | 
 194                 (((uint32_t)(iv
[2])) << 16) | 
 195                 (((uint32_t)(iv
[3])) << 24); 
 196         tag
->cs 
= _hitag2_init(rev64(key
), rev32(uid
), rev32(iv_
)); 
 199 static int hitag2_cipher_authenticate(uint64_t* cs
, const byte_t 
*authenticator_is
) 
 201         byte_t authenticator_should
[4]; 
 202         authenticator_should
[0] = ~_hitag2_byte(cs
); 
 203         authenticator_should
[1] = ~_hitag2_byte(cs
); 
 204         authenticator_should
[2] = ~_hitag2_byte(cs
); 
 205         authenticator_should
[3] = ~_hitag2_byte(cs
); 
 206         return (memcmp(authenticator_should
, authenticator_is
, 4) == 0); 
 209 static int hitag2_cipher_transcrypt(uint64_t* cs
, byte_t 
*data
, unsigned int bytes
, unsigned int bits
) 
 212         for(i
=0; i
<bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
); 
 213         for(i
=0; i
<bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
); 
 217 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK) 
 218 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz 
 219 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier) 
 220 // T0 = TIMER_CLOCK1 / 125000 = 192 
 223 #define SHORT_COIL()    LOW(GPIO_SSC_DOUT) 
 224 #define OPEN_COIL()     HIGH(GPIO_SSC_DOUT) 
 226 #define HITAG_FRAME_LEN 20 
 227 #define HITAG_T_STOP  36 /* T_EOF should be > 36 */ 
 228 #define HITAG_T_LOW     8  /* T_LOW should be 4..10 */ 
 229 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */ 
 230 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */ 
 231 //#define HITAG_T_EOF   40 /* T_EOF should be > 36 */ 
 232 #define HITAG_T_EOF   80     /* T_EOF should be > 36 */ 
 233 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */ 
 234 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */ 
 235 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */ 
 236 #define HITAG_T_PROG 614 
 238 #define HITAG_T_TAG_ONE_HALF_PERIOD         10 
 239 #define HITAG_T_TAG_TWO_HALF_PERIOD         25 
 240 #define HITAG_T_TAG_THREE_HALF_PERIOD       41 
 241 #define HITAG_T_TAG_FOUR_HALF_PERIOD    57 
 243 #define HITAG_T_TAG_HALF_PERIOD                 16 
 244 #define HITAG_T_TAG_FULL_PERIOD                 32 
 246 #define HITAG_T_TAG_CAPTURE_ONE_HALF        13 
 247 #define HITAG_T_TAG_CAPTURE_TWO_HALF        25 
 248 #define HITAG_T_TAG_CAPTURE_THREE_HALF  41 
 249 #define HITAG_T_TAG_CAPTURE_FOUR_HALF   57 
 252 static void hitag_send_bit(int bit
) { 
 254         // Reset clock for the next bit 
 255         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 257         // Fixed modulation, earlier proxmark version used inverted signal 
 259                 // Manchester: Unloaded, then loaded |__--| 
 261                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_HALF_PERIOD
); 
 263                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_FULL_PERIOD
); 
 265                 // Manchester: Loaded, then unloaded |--__| 
 267                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_HALF_PERIOD
); 
 269                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_FULL_PERIOD
); 
 274 static void hitag_send_frame(const byte_t
* frame
, size_t frame_len
) 
 276         // Send start of frame 
 277         for(size_t i
=0; i
<5; i
++) { 
 281         // Send the content of the frame 
 282         for(size_t i
=0; i
<frame_len
; i
++) { 
 283                 hitag_send_bit((frame
[i
/8] >> (7-(i%8
)))&1); 
 286         // Drop the modulation 
 291 static void hitag2_handle_reader_command(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) 
 293         byte_t rx_air
[HITAG_FRAME_LEN
]; 
 295         // Copy the (original) received frame how it is send over the air 
 296         memcpy(rx_air
,rx
,nbytes(rxlen
)); 
 298         if(tag
.crypto_active
) { 
 299                 hitag2_cipher_transcrypt(&(tag
.cs
),rx
,rxlen
/8,rxlen%8
); 
 302         // Reset the transmission frame length 
 305         // Try to find out which command was send by selecting on length (in bits) 
 307                 // Received 11000 from the reader, request for UID, send UID 
 309                 // Always send over the air in the clear plaintext mode 
 310                 if(rx_air
[0] != 0xC0) { 
 315                 memcpy(tx
,tag
.sectors
[0],4); 
 316                 tag
.crypto_active 
= 0; 
 320                 // Read/Write command: ..xx x..y  yy with yyy == ~xxx, xxx is sector number 
 322                 unsigned int sector 
= (~( ((rx
[0]<<2)&0x04) | ((rx
[1]>>6)&0x03) ) & 0x07); 
 323                 // Verify complement of sector index 
 324                 if(sector 
!= ((rx
[0]>>3)&0x07)) { 
 325                         //DbpString("Transmission error (read/write)"); 
 329                 switch (rx
[0] & 0xC6) { 
 330                         // Read command: 11xx x00y 
 332                         memcpy(tx
,tag
.sectors
[sector
],4); 
 336                         // Inverted Read command: 01xx x10y 
 338                         for (size_t i
=0; i
<4; i
++) { 
 339                                 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff; 
 344                         // Write command: 10xx x01y 
 346                         // Prepare write, acknowledge by repeating command 
 347                         memcpy(tx
,rx
,nbytes(rxlen
)); 
 349                         tag
.active_sector 
= sector
; 
 350                         tag
.state
=TAG_STATE_WRITING
; 
 355                         Dbprintf("Unknown command: %02x %02x",rx
[0],rx
[1]); 
 362                 // Writing data or Reader password 
 364                 if(tag
.state 
== TAG_STATE_WRITING
) { 
 365                         // These are the sector contents to be written. We don't have to do anything else. 
 366                         memcpy(tag
.sectors
[tag
.active_sector
],rx
,nbytes(rxlen
)); 
 367                         tag
.state
=TAG_STATE_RESET
; 
 370                         // Received RWD password, respond with configuration and our password 
 371                         if(memcmp(rx
,tag
.sectors
[1],4) != 0) { 
 372                                 DbpString("Reader password is wrong"); 
 376                         memcpy(tx
,tag
.sectors
[3],4); 
 381                 // Received RWD authentication challenge and respnse 
 383                 // Store the authentication attempt 
 384                 if (auth_table_len 
< (AUTH_TABLE_LENGTH
-8)) { 
 385                         memcpy(auth_table
+auth_table_len
,rx
,8); 
 389                 // Reset the cipher state 
 390                 hitag2_cipher_reset(&tag
,rx
); 
 391                 // Check if the authentication was correct 
 392                 if(!hitag2_cipher_authenticate(&(tag
.cs
),rx
+4)) { 
 393                         // The reader failed to authenticate, do nothing 
 394                         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]); 
 397                 // Succesful, but commented out reporting back to the Host, this may delay to much. 
 398                 // 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]); 
 400                 // Activate encryption algorithm for all further communication 
 401                 tag
.crypto_active 
= 1; 
 403                 // Use the tag password as response 
 404                 memcpy(tx
,tag
.sectors
[3],4); 
 410 //  LogTraceHitag(rx,rxlen,0,0,false); 
 411 //  LogTraceHitag(tx,*txlen,0,0,true); 
 413         if(tag
.crypto_active
) { 
 414                 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen%8
); 
 418 static void hitag_reader_send_bit(int bit
) { 
 420         // Reset clock for the next bit 
 421         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 423         // Binary puls length modulation (BPLM) is used to encode the data stream 
 424         // This means that a transmission of a one takes longer than that of a zero 
 426         // Enable modulation, which means, drop the field 
 429         // Wait for 4-10 times the carrier period 
 430         while(AT91C_BASE_TC0
->TC_CV 
< T0
*6); 
 433         // Disable modulation, just activates the field again 
 438                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*22); 
 439                 //      SpinDelayUs(16*8); 
 442                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*28); 
 443                 //      SpinDelayUs(22*8); 
 449 static void hitag_reader_send_frame(const byte_t
* frame
, size_t frame_len
) 
 451         // Send the content of the frame 
 452         for(size_t i
=0; i
<frame_len
; i
++) { 
 453                 hitag_reader_send_bit((frame
[i
/8] >> (7-(i%8
)))&1); 
 456         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 457         // Enable modulation, which means, drop the field 
 459         // Wait for 4-10 times the carrier period 
 460         while(AT91C_BASE_TC0
->TC_CV 
< T0
*6); 
 461         // Disable modulation, just activates the field again 
 467 static bool hitag2_password(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 468         // Reset the transmission frame length 
 471         // Try to find out which command was send by selecting on length (in bits) 
 473                 // No answer, try to resurrect 
 475                 // Stop if there is no answer (after sending password) 
 477                         DbpString("Password failed!"); 
 481                 memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 484                 // Received UID, tag password 
 488                         memcpy(tx
,password
,4); 
 490                         memcpy(tag
.sectors
[blocknr
],rx
,4); 
 495                                 //store password in block1, the TAG answers with Block3, but we need the password in memory 
 496                                 memcpy(tag
.sectors
[blocknr
],tx
,4); 
 498                                 memcpy(tag
.sectors
[blocknr
],rx
,4); 
 503                                 DbpString("Read succesful!"); 
 508                         tx
[0] = 0xc0 | (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 509                         tx
[1] = ((blocknr
^7) << 6); 
 513                 // Unexpected response 
 515                 Dbprintf("Uknown frame length: %d",rxlen
); 
 522 static bool hitag2_write_page(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) 
 524         switch (writestate
) { 
 525         case WRITE_STATE_START
: 
 527                 tx
[0] = 0x82 | (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 528                 tx
[1] = ((blocknr
^7) << 6); 
 529                 writestate 
= WRITE_STATE_PAGENUM_WRITTEN
; 
 531         case WRITE_STATE_PAGENUM_WRITTEN
: 
 532                 // Check if page number was received correctly 
 534                         (rx
[0] == (0x82 | (blocknr 
<< 3) | ((blocknr
^7) >> 2))) && 
 535                         (rx
[1] == (((blocknr 
& 0x3) ^ 0x3) << 6))) { 
 537                         memset(tx
, 0, HITAG_FRAME_LEN
); 
 538                         memcpy(tx
, writedata
, 4); 
 539                         writestate 
= WRITE_STATE_PROG
; 
 541                         Dbprintf("hitag2_write_page: Page number was not received correctly: rxlen=%d rx=%02x%02x%02x%02x", 
 542                                  rxlen
, rx
[0], rx
[1], rx
[2], rx
[3]); 
 547         case WRITE_STATE_PROG
: 
 552                         Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen
); 
 556                 DbpString("hitag2_write_page: Unknown state %d"); 
 564 static bool hitag2_crypto(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
, bool write
) { 
 565         // Reset the transmission frame length 
 569                 hitag2_cipher_transcrypt(&cipher_state
,rx
,rxlen
/8,rxlen%8
); 
 573         if (bCrypto 
&& !bAuthenticating 
&& write
) { 
 574                 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) { 
 581         // Try to find out which command was send by selecting on length (in bits) 
 583                 // No answer, try to resurrect 
 586                 // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 588                         // Failed during authentication 
 589                         if (bAuthenticating
) { 
 590                                 DbpString("Authentication failed!"); 
 593                                 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate 
 595                                         // Write the low part of the key in memory 
 596                                         memcpy(tag
.sectors
[1],key
+2,4); 
 597                                 } else if (blocknr 
== 2) { 
 598                                         // Write the high part of the key in memory 
 599                                         tag
.sectors
[2][0] = 0x00; 
 600                                         tag
.sectors
[2][1] = 0x00; 
 601                                         tag
.sectors
[2][2] = key
[0]; 
 602                                         tag
.sectors
[2][3] = key
[1]; 
 604                                         // Just put zero's in the memory (of the unreadable block) 
 605                                         memset(tag
.sectors
[blocknr
],0x00,4); 
 612                         memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 616         // Received UID, crypto tag answer 
 619                         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; 
 620                         uint32_t ui32uid 
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24; 
 621                         Dbprintf("hitag2_crypto: key=0x%x%x uid=0x%x", (uint32_t) ((rev64(ui64key
)) >> 32), (uint32_t) ((rev64(ui64key
)) & 0xffffffff), rev32(ui32uid
)); 
 622                         cipher_state 
= _hitag2_init(rev64(ui64key
), rev32(ui32uid
), 0); 
 625                         hitag2_cipher_transcrypt(&cipher_state
, tx
+4, 4, 0); 
 628                         bAuthenticating 
= true; 
 630                         // Check if we received answer tag (at) 
 631                         if (bAuthenticating
) { 
 632                                 bAuthenticating 
= false; 
 634                                         if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) { 
 640                                 // Store the received block 
 641                                 memcpy(tag
.sectors
[blocknr
],rx
,4); 
 646                                 DbpString("Read succesful!"); 
 651                                 tx
[0] = 0xc0 | (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 652                                 tx
[1] = ((blocknr
^7) << 6); 
 657                 // Unexpected response 
 659                 Dbprintf("Uknown frame length: %d",rxlen
); 
 666                 // We have to return now to avoid double encryption 
 667                 if (!bAuthenticating
) { 
 668                         hitag2_cipher_transcrypt(&cipher_state
,tx
,*txlen
/8,*txlen%8
); 
 676 static bool hitag2_authenticate(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 677         // Reset the transmission frame length 
 680         // Try to find out which command was send by selecting on length (in bits) 
 682                 // No answer, try to resurrect 
 684                 // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 686                         DbpString("Authentication failed!"); 
 690                 memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 693                 // Received UID, crypto tag answer 
 700                         DbpString("Authentication succesful!"); 
 701                         // We are done... for now 
 706                 // Unexpected response 
 708                 Dbprintf("Uknown frame length: %d",rxlen
); 
 717 static bool hitag2_test_auth_attempts(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 719         // Reset the transmission frame length 
 722         // Try to find out which command was send by selecting on length (in bits) 
 724                 // No answer, try to resurrect 
 726                 // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 728                         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]); 
 730                         // Removing failed entry from authentiations table 
 731                         memcpy(auth_table
+auth_table_pos
,auth_table
+auth_table_pos
+8,8); 
 734                         // Return if we reached the end of the authentications table 
 736                         if (auth_table_pos 
== auth_table_len
) { 
 740                         // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry) 
 741                         memcpy(NrAr
,auth_table
+auth_table_pos
,8); 
 744                 memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 747                 // Received UID, crypto tag answer, or read block response 
 754                         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]); 
 756                         if ((auth_table_pos
+8) == auth_table_len
) { 
 760                         memcpy(NrAr
,auth_table
+auth_table_pos
,8); 
 765                 Dbprintf("Uknown frame length: %d",rxlen
); 
 773 static bool hitag2_read_uid(byte_t
* rx
, const size_t rxlen
, byte_t
* tx
, size_t* txlen
) { 
 774         // Reset the transmission frame length 
 777         // Try to find out which command was send by selecting on length (in bits) 
 779                 // No answer, try to resurrect 
 781                 // Just starting or if there is no answer 
 783                 memcpy(tx
,"\xc0",nbytes(*txlen
)); 
 787                 // Check if we received answer tag (at) 
 788                 if (bAuthenticating
) { 
 789                         bAuthenticating 
= false; 
 791                         // Store the received block 
 792                         memcpy(tag
.sectors
[blocknr
],rx
,4); 
 796                         //DbpString("Read successful!"); 
 801                 // Unexpected response 
 803                 Dbprintf("Uknown frame length: %d",rxlen
); 
 810 void SnoopHitag(uint32_t type
) { 
 819         byte_t rx
[HITAG_FRAME_LEN
] = {0}; 
 822         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
 824         // Clean up trace and prepare it for storing frames 
 832         auth_table 
= (byte_t 
*)BigBuf_malloc(AUTH_TABLE_LENGTH
); 
 833         memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
); 
 835         DbpString("Starting Hitag2 snoop"); 
 838         // Set up eavesdropping mode, frequency divisor which will drive the FPGA 
 839         // and analog mux selection. 
 840         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT  
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
); 
 841         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
 842         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
 845         // Configure output pin that is connected to the FPGA (for modulating) 
 846         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 847         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 849         // Disable modulation, we are going to eavesdrop, not modulate ;) 
 852         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames 
 853         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
 854         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
 856         // Disable timer during configuration 
 857         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
 859         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
 860         // external trigger rising edge, load RA on rising edge of TIOA. 
 861         uint32_t t1_channel_mode 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_BOTH 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_BOTH
; 
 862         AT91C_BASE_TC1
->TC_CMR 
= t1_channel_mode
; 
 864         // Enable and reset counter 
 865         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
 867         // Reset the received frame, frame count and timing info 
 871         reader_frame 
= false; 
 876         while(!BUTTON_PRESS()) { 
 880                 // Receive frame, watch for at most T0*EOF periods 
 881                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_EOF
) { 
 882                         // Check if rising edge in modulation is detected 
 883                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
 884                                 // Retrieve the new timing values 
 885                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
 887                                 // Find out if we are dealing with a rising or falling edge 
 888                                 rising_edge 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_FRAME
) > 0; 
 890                                 // Shorter periods will only happen with reader frames 
 891                                 if (!reader_frame 
&& rising_edge 
&& ra 
< HITAG_T_TAG_CAPTURE_ONE_HALF
) { 
 892                                         // Switch from tag to reader capture 
 895                                         memset(rx
,0x00,sizeof(rx
)); 
 899                                 // Only handle if reader frame and rising edge, or tag frame and falling edge 
 900                                 if (reader_frame 
!= rising_edge
) { 
 905                                 // Add the buffered timing values of earlier captured edges which were skipped 
 911                                         // Capture reader frame 
 912                                         if(ra 
>= HITAG_T_STOP
) { 
 914                                                         //DbpString("wierd0?"); 
 916                                                 // Capture the T0 periods that have passed since last communication or field drop (reset) 
 917                                                 response 
= (ra 
- HITAG_T_LOW
); 
 918                                         } else if(ra 
>= HITAG_T_1_MIN 
) { 
 920                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 922                                         } else if(ra 
>= HITAG_T_0_MIN
) { 
 924                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 927                                                 // Ignore wierd value, is to small to mean anything 
 931                                         // Capture tag frame (manchester decoding using only falling edges) 
 932                                         if(ra 
>= HITAG_T_EOF
) { 
 934                                                         //DbpString("wierd1?"); 
 936                                                 // Capture the T0 periods that have passed since last communication or field drop (reset) 
 937                                                 // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
 938                                                 response 
= ra
-HITAG_T_TAG_HALF_PERIOD
; 
 939                                         } else if(ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
 940                                                 // Manchester coding example |-_|_-|-_| (101) 
 941                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 943                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 945                                         } else if(ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
 946                                                 // Manchester coding example |_-|...|_-|-_| (0...01) 
 947                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 949                                                 // We have to skip this half period at start and add the 'one' the second time 
 951                                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 956                                         } else if(ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
 957                                                 // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
 959                                                         // Ignore bits that are transmitted during SOF 
 962                                                         // bit is same as last bit 
 963                                                         rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
 967                                                 // Ignore wierd value, is to small to mean anything 
 973                 // Check if frame was captured 
 976                         if (!LogTraceHitag(rx
,rxlen
,response
,0,reader_frame
)) { 
 977                                 DbpString("Trace full"); 
 981                         // Check if we recognize a valid authentication attempt 
 982                         if (nbytes(rxlen
) == 8) { 
 983                                 // Store the authentication attempt 
 984                                 if (auth_table_len 
< (AUTH_TABLE_LENGTH
-8)) { 
 985                                         memcpy(auth_table
+auth_table_len
,rx
,8); 
 990                         // Reset the received frame and response timing info 
 991                         memset(rx
,0x00,sizeof(rx
)); 
 993                         reader_frame 
= false; 
1002                         // Save the timer overflow, will be 0 when frame was received 
1003                         overflow 
+= (AT91C_BASE_TC1
->TC_CV
/T0
); 
1005                 // Reset the frame length 
1007                 // Reset the timer to restart while-loop that receives frames 
1008                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_SWTRG
; 
1014         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1015         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1016         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1019 //  Dbprintf("frame received: %d",frame_count); 
1020 //  Dbprintf("Authentication Attempts: %d",(auth_table_len/8)); 
1021 //  DbpString("All done"); 
1024 void SimulateHitagTag(bool tag_mem_supplied
, byte_t
* data
) { 
1028         byte_t rx
[HITAG_FRAME_LEN
]; 
1030         byte_t tx
[HITAG_FRAME_LEN
]; 
1032         bool bQuitTraceFull 
= false; 
1035         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1037         // Clean up trace and prepare it for storing frames 
1045         auth_table 
= (byte_t 
*)BigBuf_malloc(AUTH_TABLE_LENGTH
); 
1046         memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
); 
1048         DbpString("Starting Hitag2 simulation"); 
1052         if (tag_mem_supplied
) { 
1053                 DbpString("Loading hitag2 memory..."); 
1054                 memcpy((byte_t
*)tag
.sectors
,data
,48); 
1058         for (size_t i
=0; i
<12; i
++) { 
1059                 for (size_t j
=0; j
<4; j
++) { 
1061                         block 
|= tag
.sectors
[i
][j
]; 
1063                 Dbprintf("| %d | %08x |",i
,block
); 
1066         // Set up simulator mode, frequency divisor which will drive the FPGA 
1067         // and analog mux selection. 
1068         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
); 
1069         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1070         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1073         // Configure output pin that is connected to the FPGA (for modulating) 
1074         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1075         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1077         // Disable modulation at default, which means release resistance 
1080         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1081         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1083         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames 
1084         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1085         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1087         // Disable timer during configuration 
1088         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1089         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1091         // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers 
1092         AT91C_BASE_TC0
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
; 
1094         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1095         // external trigger rising edge, load RA on rising edge of TIOA. 
1096         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_RISING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_RISING
; 
1098         // Reset the received frame, frame count and timing info 
1099         memset(rx
,0x00,sizeof(rx
)); 
1104         // Enable and reset counter 
1105         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1107         while(!BUTTON_PRESS()) { 
1111                 // Receive frame, watch for at most T0*EOF periods 
1112                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_EOF
) { 
1113                         // Check if rising edge in modulation is detected 
1114                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1115                                 // Retrieve the new timing values 
1116                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
; 
1119                                 // Reset timer every frame, we have to capture the last edge for timing 
1120                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1124                                 // Capture reader frame 
1125                                 if(ra 
>= HITAG_T_STOP
) { 
1127                                                 //DbpString("wierd0?"); 
1129                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1130                                         response 
= (ra 
- HITAG_T_LOW
); 
1131                                 } else if(ra 
>= HITAG_T_1_MIN 
) { 
1133                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1135                                 } else if(ra 
>= HITAG_T_0_MIN
) { 
1137                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1140                                         // Ignore wierd value, is to small to mean anything 
1145                 // Check if frame was captured 
1149                                 if (!LogTraceHitag(rx
,rxlen
,response
,0,true)) { 
1150                                         DbpString("Trace full"); 
1151                                         if (bQuitTraceFull
) { 
1159                         // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1160                         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1162                         // Process the incoming frame (rx) and prepare the outgoing frame (tx) 
1163                         hitag2_handle_reader_command(rx
,rxlen
,tx
,&txlen
); 
1165                         // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit, 
1166                         // not that since the clock counts since the rising edge, but T_Wait1 is 
1167                         // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low) 
1168                         // periods. The gap time T_Low varies (4..10). All timer values are in 
1169                         // terms of T0 units 
1170                         while(AT91C_BASE_TC0
->TC_CV 
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
)); 
1172                         // Send and store the tag answer (if there is any) 
1174                                 // Transmit the tag frame 
1175                                 hitag_send_frame(tx
,txlen
); 
1176                                 // Store the frame in the trace 
1178                                         if (!LogTraceHitag(tx
,txlen
,0,0,false)) { 
1179                                                 DbpString("Trace full"); 
1180                                                 if (bQuitTraceFull
) { 
1189                         // Reset the received frame and response timing info 
1190                         memset(rx
,0x00,sizeof(rx
)); 
1193                         // Enable and reset external trigger in timer for capturing future frames 
1194                         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1197                 // Reset the frame length 
1199                 // Save the timer overflow, will be 0 when frame was received 
1200                 overflow 
+= (AT91C_BASE_TC1
->TC_CV
/T0
); 
1201                 // Reset the timer to restart while-loop that receives frames 
1202                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_SWTRG
; 
1206         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1207         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1208         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1210         DbpString("Sim Stopped"); 
1214 void ReaderHitag(hitag_function htf
, hitag_data
* htd
) { 
1217         byte_t rx
[HITAG_FRAME_LEN
]; 
1219         byte_t txbuf
[HITAG_FRAME_LEN
]; 
1226         int t_wait 
= HITAG_T_WAIT_MAX
; 
1228         bool bQuitTraceFull 
= false; 
1230         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1231         // Reset the return status 
1232         bSuccessful 
= false; 
1234         // Clean up trace and prepare it for storing frames 
1238         //DbpString("Starting Hitag reader family"); 
1240         // Check configuration 
1242         case RHT2F_PASSWORD
: { 
1243                 Dbprintf("List identifier in password mode"); 
1244                 memcpy(password
,htd
->pwd
.password
,4); 
1246                 bQuitTraceFull 
= false; 
1250         case RHT2F_AUTHENTICATE
: { 
1251                 DbpString("Authenticating using nr,ar pair:"); 
1252                 memcpy(NrAr
,htd
->auth
.NrAr
,8); 
1253                 Dbhexdump(8,NrAr
,false); 
1256                 bAuthenticating 
= false; 
1257                 bQuitTraceFull 
= true; 
1261                 DbpString("Authenticating using key:"); 
1262                 memcpy(key
,htd
->crypto
.key
,6);    //HACK; 4 or 6??  I read both in the code. 
1263                 Dbhexdump(6,key
,false); 
1267                 bAuthenticating 
= false; 
1268                 bQuitTraceFull 
= true; 
1270         case RHT2F_TEST_AUTH_ATTEMPTS
: { 
1271                 Dbprintf("Testing %d authentication attempts",(auth_table_len
/8)); 
1273                 memcpy(NrAr
, auth_table
, 8); 
1274                 bQuitTraceFull 
= false; 
1278         case RHT2F_UID_ONLY
: { 
1282                 bAuthenticating 
= false; 
1283                 bQuitTraceFull 
= true; 
1286                 Dbprintf("Error, unknown function: %d",htf
); 
1294         // Configure output and enable pin that is connected to the FPGA (for modulating) 
1295         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1296         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1298         // Set fpga in edge detect with reader field, we can modulate as reader now 
1299         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT 
| FPGA_LF_EDGE_DETECT_READER_FIELD
); 
1301         // Set Frequency divisor which will drive the FPGA and analog mux selection 
1302         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1303         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1306         // Disable modulation at default, which means enable the field 
1309         // Give it a bit of time for the resonant antenna to settle. 
1312         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1313         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1315         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames 
1316         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1317         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1319         // Disable timer during configuration 
1320         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1321         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1323         // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers 
1324         AT91C_BASE_TC0
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
; 
1326         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1327         // external trigger rising edge, load RA on falling edge of TIOA. 
1328         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_FALLING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_FALLING
; 
1330         // Enable and reset counters 
1331         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1332         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1334         // Reset the received frame, frame count and timing info 
1339         // Tag specific configuration settings (sof, timings, etc.) 
1344                 //DbpString("Configured for hitagS reader"); 
1345         } else if (htf 
< 20) { 
1349                 //DbpString("Configured for hitag1 reader"); 
1350         } else if (htf 
< 30) { 
1353                 t_wait 
= HITAG_T_WAIT_2
; 
1354                 //DbpString("Configured for hitag2 reader"); 
1356                 Dbprintf("Error, unknown hitag reader type: %d",htf
); 
1359         uint8_t attempt_count
=0; 
1360         while(!bStop 
&& !BUTTON_PRESS()) { 
1364                 // Check if frame was captured and store it 
1368                                 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) { 
1369                                         DbpString("Trace full"); 
1370                                         if (bQuitTraceFull
) { 
1379                 // By default reset the transmission buffer 
1382                         case RHT2F_PASSWORD
: { 
1383                                 bStop 
= !hitag2_password(rx
,rxlen
,tx
,&txlen
); 
1385                         case RHT2F_AUTHENTICATE
: { 
1386                                 bStop 
= !hitag2_authenticate(rx
,rxlen
,tx
,&txlen
); 
1388                         case RHT2F_CRYPTO
: { 
1389                                 bStop 
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
, false); 
1391                         case RHT2F_TEST_AUTH_ATTEMPTS
: { 
1392                                 bStop 
= !hitag2_test_auth_attempts(rx
,rxlen
,tx
,&txlen
); 
1394                         case RHT2F_UID_ONLY
: { 
1395                                 bStop 
= !hitag2_read_uid(rx
, rxlen
, tx
, &txlen
); 
1396                                 attempt_count
++; //attempt 3 times to get uid then quit 
1397                                 if (!bStop 
&& attempt_count 
== 3) bStop 
= true; 
1400                                 Dbprintf("Error, unknown function: %d",htf
); 
1405                 // Send and store the reader command 
1406                 // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1407                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1409                 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, 
1410                 // Since the clock counts since the last falling edge, a 'one' means that the 
1411                 // falling edge occured halfway the period. with respect to this falling edge, 
1412                 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. 
1413                 // All timer values are in terms of T0 units 
1414                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
))); 
1416                 //Dbprintf("DEBUG: Sending reader frame"); 
1418                 // Transmit the reader frame 
1419                 hitag_reader_send_frame(tx
,txlen
); 
1421                 // Enable and reset external trigger in timer for capturing future frames 
1422                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1424                 // Add transmitted frame to total count 
1428                                 // Store the frame in the trace 
1429                                 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) { 
1430                                         if (bQuitTraceFull
) { 
1439                 // Reset values for receiving frames 
1440                 memset(rx
,0x00,sizeof(rx
)); 
1444                 tag_sof 
= reset_sof
; 
1446                 //Dbprintf("DEBUG: Waiting to receive frame"); 
1447                 uint32_t errorCount 
= 0; 
1449                 // Receive frame, watch for at most T0*EOF periods 
1450                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_WAIT_MAX
) { 
1451                         // Check if falling edge in tag modulation is detected 
1452                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1453                                 // Retrieve the new timing values 
1454                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
1456                                 // Reset timer every frame, we have to capture the last edge for timing 
1457                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1461                                 // Capture tag frame (manchester decoding using only falling edges) 
1462                                 if(ra 
>= HITAG_T_EOF
) { 
1464                                                 //Dbprintf("DEBUG: Wierd1"); 
1466                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1467                                         // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
1468                                         response 
= ra
-HITAG_T_TAG_HALF_PERIOD
; 
1469                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
1470                                         // Manchester coding example |-_|_-|-_| (101) 
1472                                         //need to test to verify we don't exceed memory... 
1473                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1476                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1478                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1480                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
1481                                         // Manchester coding example |_-|...|_-|-_| (0...01) 
1483                                         //need to test to verify we don't exceed memory... 
1484                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1487                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1489                                         // We have to skip this half period at start and add the 'one' the second time 
1491                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1496                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
1497                                         // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
1499                                         //need to test to verify we don't exceed memory... 
1500                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1504                                                 // Ignore bits that are transmitted during SOF 
1507                                                 // bit is same as last bit 
1508                                                 rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
1512                                         //Dbprintf("DEBUG: Wierd2"); 
1514                                         // Ignore wierd value, is to small to mean anything 
1517                         //if we saw over 100 wierd values break it probably isn't hitag... 
1518                         if (errorCount 
>100) break; 
1519                         // We can break this loop if we received the last bit from a frame 
1520                         if (AT91C_BASE_TC1
->TC_CV 
> T0
*HITAG_T_EOF
) { 
1525         //Dbprintf("DEBUG: Done waiting for frame"); 
1529         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1530         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1531         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1532         //Dbprintf("frame received: %d",frame_count); 
1533         //DbpString("All done"); 
1535                 cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48); 
1537                 cmd_send(CMD_ACK
,bSuccessful
,0,0,0,0); 
1541 void WriterHitag(hitag_function htf
, hitag_data
* htd
, int page
) { 
1544         byte_t rx
[HITAG_FRAME_LEN
]; 
1546         byte_t txbuf
[HITAG_FRAME_LEN
]; 
1553         int t_wait 
= HITAG_T_WAIT_MAX
; 
1555         bool bQuitTraceFull 
= false; 
1557         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1558         // Reset the return status 
1559         bSuccessful 
= false; 
1561         // Clean up trace and prepare it for storing frames 
1565         //DbpString("Starting Hitag reader family"); 
1567         // Check configuration 
1571                 DbpString("Authenticating using key:"); 
1572                 memcpy(key
,htd
->crypto
.key
,6);    //HACK; 4 or 6??  I read both in the code. 
1573                 memcpy(writedata
, htd
->crypto
.data
, 4); 
1574                 Dbhexdump(6,key
,false); 
1578                 bAuthenticating 
= false; 
1579                 bQuitTraceFull 
= true; 
1580                 writestate 
= WRITE_STATE_START
; 
1583                 Dbprintf("Error, unknown function: %d",htf
); 
1591         // Configure output and enable pin that is connected to the FPGA (for modulating) 
1592         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1593         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1595         // Set fpga in edge detect with reader field, we can modulate as reader now 
1596         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT 
| FPGA_LF_EDGE_DETECT_READER_FIELD
); 
1598         // Set Frequency divisor which will drive the FPGA and analog mux selection 
1599         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1600         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1603         // Disable modulation at default, which means enable the field 
1606         // Give it a bit of time for the resonant antenna to settle. 
1609         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1610         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1612         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames 
1613         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1614         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1616         // Disable timer during configuration 
1617         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1618         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1620         // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers 
1621         AT91C_BASE_TC0
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
; 
1623         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1624         // external trigger rising edge, load RA on falling edge of TIOA. 
1625         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_FALLING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_FALLING
; 
1627         // Enable and reset counters 
1628         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1629         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1631         // Reset the received frame, frame count and timing info 
1637         // Tag specific configuration settings (sof, timings, etc.) 
1642                 //DbpString("Configured for hitagS reader"); 
1643         } else if (htf 
< 20) { 
1647                 //DbpString("Configured for hitag1 reader"); 
1648         } else if (htf 
< 30) { 
1651                 t_wait 
= HITAG_T_WAIT_2
; 
1652                 //DbpString("Configured for hitag2 reader"); 
1654                 Dbprintf("Error, unknown hitag reader type: %d",htf
); 
1657         while(!bStop 
&& !BUTTON_PRESS()) { 
1661                 // Check if frame was captured and store it 
1665                                 if (!LogTraceHitag(rx
,rxlen
,response
,0,false)) { 
1666                                         DbpString("Trace full"); 
1667                                         if (bQuitTraceFull
) { 
1676                 // By default reset the transmission buffer 
1679                 case WHT2F_CRYPTO
: { 
1680                         bStop 
= !hitag2_crypto(rx
,rxlen
,tx
,&txlen
, true); 
1683                         Dbprintf("Error, unknown function: %d",htf
); 
1688                 // Send and store the reader command 
1689                 // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1690                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1692                 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, 
1693                 // Since the clock counts since the last falling edge, a 'one' means that the 
1694                 // falling edge occured halfway the period. with respect to this falling edge, 
1695                 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. 
1696                 // All timer values are in terms of T0 units 
1697                 while(AT91C_BASE_TC0
->TC_CV 
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
))); 
1699                 //Dbprintf("DEBUG: Sending reader frame"); 
1701                 // Transmit the reader frame 
1702                 hitag_reader_send_frame(tx
,txlen
); 
1704                                 // Enable and reset external trigger in timer for capturing future frames 
1705                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1707                 // Add transmitted frame to total count 
1711                                 // Store the frame in the trace 
1712                                 if (!LogTraceHitag(tx
,txlen
,HITAG_T_WAIT_2
,0,true)) { 
1713                                         if (bQuitTraceFull
) { 
1722                 // Reset values for receiving frames 
1723                 memset(rx
,0x00,sizeof(rx
)); 
1727                 tag_sof 
= reset_sof
; 
1729                 //Dbprintf("DEBUG: Waiting to receive frame"); 
1730                 uint32_t errorCount 
= 0; 
1732                 // Receive frame, watch for at most T0*EOF periods 
1733                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_WAIT_MAX
) { 
1734                         // Check if falling edge in tag modulation is detected 
1735                         if(AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1736                                 // Retrieve the new timing values 
1737                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
1739                                 // Reset timer every frame, we have to capture the last edge for timing 
1740                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1744                                 // Capture tag frame (manchester decoding using only falling edges) 
1745                                 if(ra 
>= HITAG_T_EOF
) { 
1747                                                 //Dbprintf("DEBUG: Wierd1"); 
1749                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1750                                         // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
1751                                         response 
= ra
-HITAG_T_TAG_HALF_PERIOD
; 
1752                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
1753                                         // Manchester coding example |-_|_-|-_| (101) 
1755                                         //need to test to verify we don't exceed memory... 
1756                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1759                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1761                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1763                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
1764                                         // Manchester coding example |_-|...|_-|-_| (0...01) 
1766                                         //need to test to verify we don't exceed memory... 
1767                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1770                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1772                                         // We have to skip this half period at start and add the 'one' the second time 
1774                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1779                                 } else if(ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
1780                                         // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
1782                                         //need to test to verify we don't exceed memory... 
1783                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1787                                                 // Ignore bits that are transmitted during SOF 
1790                                                 // bit is same as last bit 
1791                                                 rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
1795                                         //Dbprintf("DEBUG: Wierd2"); 
1797                                         // Ignore wierd value, is to small to mean anything 
1800                         //if we saw over 100 wierd values break it probably isn't hitag... 
1801                         if (errorCount 
>100) break; 
1802                         // We can break this loop if we received the last bit from a frame 
1803                         if (AT91C_BASE_TC1
->TC_CV 
> T0
*HITAG_T_EOF
) { 
1808                 // Wait some extra time for flash to be programmed 
1809                 if ((rxlen 
== 0) && (writestate 
== WRITE_STATE_PROG
)) 
1811                         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1812                         while(AT91C_BASE_TC0
->TC_CV 
< T0
*(HITAG_T_PROG 
- HITAG_T_WAIT_MAX
)); 
1815         //Dbprintf("DEBUG: Done waiting for frame"); 
1819         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1820         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1821         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1822         //Dbprintf("frame received: %d",frame_count); 
1823         //DbpString("All done"); 
1824         cmd_send(CMD_ACK
,bSuccessful
,0,0,(byte_t
*)tag
.sectors
,48);