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" 
  28 #include "fpgaloader.h" 
  29 #include "protocols.h" 
  34 static bool bAuthenticating
; 
  36 static bool bSuccessful
; 
  43                 TAG_STATE_RESET      
= 0x01,       // Just powered up, awaiting GetSnr 
  44                 TAG_STATE_ACTIVATING 
= 0x02 ,      // In activation phase (password mode), sent UID, awaiting reader password 
  45                 TAG_STATE_ACTIVATED  
= 0x03,       // Activation complete, awaiting read/write commands 
  46                 TAG_STATE_WRITING    
= 0x04,       // In write command, awaiting sector contents to be written 
  48         unsigned int active_sector
; 
  49         uint8_t crypto_active
; 
  51         uint8_t sectors
[12][4]; 
  54 static struct hitag2_tag tag 
= { 
  55         .state 
= TAG_STATE_RESET
, 
  56         .sectors 
= {                         // Password mode:               | Crypto mode: 
  57                 [0]  = { 0x02, 0x4e, 0x02, 0x20}, // UID                          | UID 
  58                 [1]  = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD                 | 32 bit LSB key 
  59                 [2]  = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved                     | 16 bit MSB key, 16 bit reserved 
  60                 [3]  = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG  | Configuration, password TAG 
  61                 [4]  = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK 
  62                 [5]  = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU 
  63                 [6]  = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: .... 
  64                 [7]  = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU 
  65                 [8]  = { 0x00, 0x00, 0x00, 0x00}, // RSK Low 
  66                 [9]  = { 0x00, 0x00, 0x00, 0x00}, // RSK High 
  67                 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF 
  68                 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC 
  73         WRITE_STATE_START 
= 0x0, 
  74         WRITE_STATE_PAGENUM_WRITTEN
, 
  79 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces. 
  80 // Historically it used to be FREE_BUFFER_SIZE, which was 2744. 
  81 #define AUTH_TABLE_LENGTH 2744 
  82 static uint8_t *auth_table
; 
  83 static size_t auth_table_pos 
= 0; 
  84 static size_t auth_table_len 
= AUTH_TABLE_LENGTH
; 
  86 static uint8_t password
[4]; 
  87 static uint8_t NrAr
[8]; 
  88 static uint8_t key
[8]; 
  89 static uint8_t writedata
[4]; 
  90 static uint64_t cipher_state
; 
  92 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */ 
  93 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007. 
  94 // For educational purposes only. 
  95 // No warranties or guarantees of any kind. 
  96 // This code is released into the public domain by its author. 
  98 // Single bit Hitag2 functions: 
 100 #define i4(x,a,b,c,d)    ((uint32_t)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8)) 
 102 static const uint32_t ht2_f4a 
= 0x2C79;      // 0010 1100 0111 1001 
 103 static const uint32_t ht2_f4b 
= 0x6671;      // 0110 0110 0111 0001 
 104 static const uint32_t ht2_f5c 
= 0x7907287B;  // 0111 1001 0000 0111 0010 1000 0111 1011 
 106 static uint32_t _f20(const uint64_t x
) { 
 109         i5 
= ((ht2_f4a 
>> i4(x
, 1, 2, 4, 5)) & 1) * 1 
 110                 + ((ht2_f4b 
>> i4(x
, 7,11,13,14)) & 1) * 2 
 111                 + ((ht2_f4b 
>> i4(x
,16,20,22,25)) & 1) * 4 
 112                 + ((ht2_f4b 
>> i4(x
,27,28,30,32)) & 1) * 8 
 113                 + ((ht2_f4a 
>> i4(x
,33,42,43,45)) & 1) * 16; 
 115         return (ht2_f5c 
>> i5
) & 1; 
 118 static uint64_t _hitag2_init(const uint64_t key
, const uint32_t serial
, const uint32_t IV
) { 
 120         uint64_t x 
= ((key 
& 0xFFFF) << 32) + serial
; 
 122         for (i 
= 0; i 
< 32; i
++) { 
 124                 x 
+= (uint64_t)(_f20(x
) ^ (((IV 
>> i
) ^ (key 
>> (i
+16))) & 1)) << 47; 
 129 static uint64_t _hitag2_round(uint64_t *state
) { 
 133                 ((((x 
>>  0) ^ (x 
>>  2) ^ (x 
>>  3) ^ (x 
>>  6) 
 134                    ^ (x 
>>  7) ^ (x 
>>  8) ^ (x 
>> 16) ^ (x 
>> 22) 
 135                    ^ (x 
>> 23) ^ (x 
>> 26) ^ (x 
>> 30) ^ (x 
>> 41) 
 136                    ^ (x 
>> 42) ^ (x 
>> 43) ^ (x 
>> 46) ^ (x 
>> 47)) & 1) << 47); 
 142 static uint32_t _hitag2_byte(uint64_t *x
) { 
 144         for (i 
= 0, c 
= 0; i 
< 8; i
++) { 
 145                 c 
+= (uint32_t) _hitag2_round(x
) << (i
^7); 
 150 static int hitag2_reset(void) { 
 151         tag
.state 
= TAG_STATE_RESET
; 
 152         tag
.crypto_active 
= 0; 
 156 static int hitag2_init(void) { 
 161 static void hitag2_cipher_reset(struct hitag2_tag 
*tag
, const uint8_t *iv
) { 
 162         uint64_t key 
= ((uint64_t)tag
->sectors
[2][2]) | 
 163                 ((uint64_t)tag
->sectors
[2][3] << 8) | 
 164                 ((uint64_t)tag
->sectors
[1][0] << 16) | 
 165                 ((uint64_t)tag
->sectors
[1][1] << 24) | 
 166                 ((uint64_t)tag
->sectors
[1][2] << 32) | 
 167                 ((uint64_t)tag
->sectors
[1][3] << 40); 
 168         uint32_t uid 
= ((uint32_t)tag
->sectors
[0][0]) | 
 169                 ((uint32_t)tag
->sectors
[0][1] << 8) | 
 170                 ((uint32_t)tag
->sectors
[0][2] << 16) | 
 171                 ((uint32_t)tag
->sectors
[0][3] << 24); 
 172         uint32_t iv_ 
= (((uint32_t)(iv
[0]))) | 
 173                 (((uint32_t)(iv
[1])) << 8) | 
 174                 (((uint32_t)(iv
[2])) << 16) | 
 175                 (((uint32_t)(iv
[3])) << 24); 
 176         tag
->cs 
= _hitag2_init(REV64(key
), REV32(uid
), REV32(iv_
)); 
 179 static int hitag2_cipher_authenticate(uint64_t *cs
, const uint8_t *authenticator_is
) { 
 180         uint8_t authenticator_should
[4]; 
 181         authenticator_should
[0] = ~_hitag2_byte(cs
); 
 182         authenticator_should
[1] = ~_hitag2_byte(cs
); 
 183         authenticator_should
[2] = ~_hitag2_byte(cs
); 
 184         authenticator_should
[3] = ~_hitag2_byte(cs
); 
 185         return (memcmp(authenticator_should
, authenticator_is
, 4) == 0); 
 188 static int hitag2_cipher_transcrypt(uint64_t *cs
, uint8_t *data
, unsigned int bytes
, unsigned int bits
) { 
 190         for (i 
= 0; i 
< bytes
; i
++) data
[i
] ^= _hitag2_byte(cs
); 
 191         for (i 
= 0; i 
< bits
; i
++) data
[bytes
] ^= _hitag2_round(cs
) << (7-i
); 
 195 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK) 
 196 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz 
 197 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier) 
 198 // T0 = TIMER_CLOCK1 / 125000 = 192 
 201 #define HITAG_FRAME_LEN   20 
 202 #define HITAG_T_STOP      36 /* T_EOF should be > 36 */ 
 203 #define HITAG_T_LOW        8 /* T_LOW should be 4..10 */ 
 204 #define HITAG_T_0_MIN     15 /* T[0] should be 18..22 */ 
 205 #define HITAG_T_1_MIN     25 /* T[1] should be 26..30 */ 
 206 //#define HITAG_T_EOF     40 /* T_EOF should be > 36 */ 
 207 #define HITAG_T_EOF       80 /* T_EOF should be > 36 */ 
 208 #define HITAG_T_WAIT_1   200 /* T_wresp should be 199..206 */ 
 209 #define HITAG_T_WAIT_2    90 /* T_wresp should be 199..206 */ 
 210 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */ 
 211 #define HITAG_T_PROG     614 
 213 #define HITAG_T_TAG_ONE_HALF_PERIOD     10 
 214 #define HITAG_T_TAG_TWO_HALF_PERIOD     25 
 215 #define HITAG_T_TAG_THREE_HALF_PERIOD   41 
 216 #define HITAG_T_TAG_FOUR_HALF_PERIOD    57 
 218 #define HITAG_T_TAG_HALF_PERIOD         16 
 219 #define HITAG_T_TAG_FULL_PERIOD         32 
 221 #define HITAG_T_TAG_CAPTURE_ONE_HALF    13 
 222 #define HITAG_T_TAG_CAPTURE_TWO_HALF    25 
 223 #define HITAG_T_TAG_CAPTURE_THREE_HALF  41 
 224 #define HITAG_T_TAG_CAPTURE_FOUR_HALF   57 
 226 static void hitag_send_bit(int bit
) { 
 228         // Reset clock for the next bit 
 229         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 231         // Fixed modulation, earlier proxmark version used inverted signal 
 233                 // Manchester: Unloaded, then loaded |__--| 
 235                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_HALF_PERIOD
); 
 237                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_FULL_PERIOD
); 
 239                 // Manchester: Loaded, then unloaded |--__| 
 241                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_HALF_PERIOD
); 
 243                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*HITAG_T_TAG_FULL_PERIOD
); 
 248 static void hitag_send_frame(const uint8_t *frame
, size_t frame_len
) 
 250         // Send start of frame 
 251         for(size_t i 
= 0; i 
< 5; i
++) { 
 255         // Send the content of the frame 
 256         for (size_t i 
= 0; i 
< frame_len
; i
++) { 
 257                 hitag_send_bit((frame
[i
/8] >> (7-(i%8
))) & 0x01); 
 260         // Drop the modulation 
 264 static void hitag2_handle_reader_command(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) { 
 265         uint8_t rx_air
[HITAG_FRAME_LEN
]; 
 267         // Copy the (original) received frame how it is send over the air 
 268         memcpy(rx_air
, rx
, nbytes(rxlen
)); 
 270         if (tag
.crypto_active
) { 
 271                 hitag2_cipher_transcrypt(&(tag
.cs
), rx
, rxlen
/8, rxlen%8
); 
 274         // Reset the transmission frame length 
 277         // Try to find out which command was send by selecting on length (in bits) 
 279                 // Received 11000 from the reader, request for UID, send UID 
 281                         // Always send over the air in the clear plaintext mode 
 282                         if (rx_air
[0] != HITAG2_START_AUTH
) { 
 287                         memcpy(tx
, tag
.sectors
[0], 4); 
 288                         tag
.crypto_active 
= 0; 
 292                 // Read/Write command: ..xx x..y  yy with yyy == ~xxx, xxx is sector number 
 294                         unsigned int sector 
= (~( ((rx
[0]<<2) & 0x04) | ((rx
[1]>>6) & 0x03) ) & 0x07); 
 295                         // Verify complement of sector index 
 296                         if (sector 
!= ((rx
[0]>>3) & 0x07)) { 
 297                                 //DbpString("Transmission error (read/write)"); 
 301                         switch (rx
[0] & 0xC6) { 
 302                                 // Read command: 11xx x00y 
 303                                 case HITAG2_READ_PAGE
: 
 304                                         memcpy(tx
, tag
.sectors
[sector
], 4); 
 308                                 // Inverted Read command: 01xx x10y 
 309                                 case HITAG2_READ_PAGE_INVERTED
: 
 310                                         for (size_t i 
= 0; i 
< 4; i
++) { 
 311                                                 tx
[i
] = tag
.sectors
[sector
][i
] ^ 0xff; 
 316                                 // Write command: 10xx x01y 
 317                                 case HITAG2_WRITE_PAGE
: 
 318                                         // Prepare write, acknowledge by repeating command 
 319                                         memcpy(tx
, rx
, nbytes(rxlen
)); 
 321                                         tag
.active_sector 
= sector
; 
 322                                         tag
.state 
= TAG_STATE_WRITING
; 
 327                                         Dbprintf("Unknown command: %02x %02x", rx
[0], rx
[1]); 
 334                 // Writing data or Reader password 
 336                         if (tag
.state 
== TAG_STATE_WRITING
) { 
 337                                 // These are the sector contents to be written. We don't have to do anything else. 
 338                                 memcpy(tag
.sectors
[tag
.active_sector
], rx
, nbytes(rxlen
)); 
 339                                 tag
.state 
= TAG_STATE_RESET
; 
 342                                 // Received RWD password, respond with configuration and our password 
 343                                 if (memcmp(rx
, tag
.sectors
[1], 4) != 0) { 
 344                                         DbpString("Reader password is wrong"); 
 348                                 memcpy(tx
, tag
.sectors
[3], 4); 
 353                 // Received RWD authentication challenge and respnse 
 355                         // Store the authentication attempt 
 356                         if (auth_table_len 
< (AUTH_TABLE_LENGTH
-8)) { 
 357                                 memcpy(auth_table
+auth_table_len
, rx
, 8); 
 361                         // Reset the cipher state 
 362                         hitag2_cipher_reset(&tag
, rx
); 
 363                         // Check if the authentication was correct 
 364                         if (!hitag2_cipher_authenticate(&(tag
.cs
), rx
+4)) { 
 365                                 // The reader failed to authenticate, do nothing 
 366                                 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]); 
 369                         // Succesful, but commented out reporting back to the Host, this may delay to much. 
 370                         // 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]); 
 372                         // Activate encryption algorithm for all further communication 
 373                         tag
.crypto_active 
= 1; 
 375                         // Use the tag password as response 
 376                         memcpy(tx
, tag
.sectors
[3], 4); 
 382         //  LogTraceHitag(rx, rxlen, 0, 0, false); 
 383         //  LogTraceHitag(tx, *txlen, 0, 0, true); 
 385         if (tag
.crypto_active
) { 
 386                 hitag2_cipher_transcrypt(&(tag
.cs
), tx
, *txlen
/8, *txlen%8
); 
 390 static void hitag_reader_send_bit(int bit
) { 
 392         // Reset clock for the next bit 
 393         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 395         // Binary puls length modulation (BPLM) is used to encode the data stream 
 396         // This means that a transmission of a one takes longer than that of a zero 
 398         // Enable modulation, which means, drop the field 
 401         // t_low = 4...10 carrier periods 
 402         while (AT91C_BASE_TC0
->TC_CV 
< T0
*6); 
 404         // Disable modulation, just activates the field again 
 408                 // Zero bit: |_-|, T[0] = 18...22 carrier periods 
 409                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*22); 
 411                 // One bit: |_--|, T[1] = 26...32 carrier periods 
 412                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*28); 
 418 static void hitag_reader_send_frame(const uint8_t *frame
, size_t frame_len
) 
 420         // Send the content of the frame 
 421         for(size_t i 
= 0; i 
< frame_len
; i
++) { 
 422                 hitag_reader_send_bit((frame
[i
/8] >> (7-(i%8
))) & 0x01); 
 425         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
 426         // Enable modulation, which means, drop the field 
 428         // t_low = 4...10 carrier periods 
 429         while (AT91C_BASE_TC0
->TC_CV 
< T0
*6); 
 430         // Disable modulation, just activates the field again 
 432         // t_stop > 36 carrier periods 
 433         while (AT91C_BASE_TC0
->TC_CV 
< T0
*36); 
 438 //----------------------------------------------------------------------------- 
 440 //----------------------------------------------------------------------------- 
 442 static bool hitag2_write_page(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) { 
 443         switch (writestate
) { 
 444                 case WRITE_STATE_START
: 
 445                         tx
[0] = HITAG2_WRITE_PAGE 
| (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 446                         tx
[1] = ((blocknr
^7) << 6); 
 448                         writestate 
= WRITE_STATE_PAGENUM_WRITTEN
; 
 450                 case WRITE_STATE_PAGENUM_WRITTEN
: 
 451                         // Check if page number was received correctly 
 453                                         && (rx
[0] == (HITAG2_WRITE_PAGE 
| (blocknr 
<< 3) | ((blocknr
^7) >> 2))) 
 454                                         && (rx
[1] == (((blocknr 
& 0x3) ^ 0x3) << 6))) { 
 456                                 memset(tx
, 0, HITAG_FRAME_LEN
); 
 457                                 memcpy(tx
, writedata
, 4); 
 458                                 writestate 
= WRITE_STATE_PROG
; 
 460                                 Dbprintf("hitag2_write_page: Page number was not received correctly: rxlen=%d rx=%02x%02x%02x%02x", 
 461                                                 rxlen
, rx
[0], rx
[1], rx
[2], rx
[3]); 
 466                 case WRITE_STATE_PROG
: 
 471                                 Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen
); 
 475                         DbpString("hitag2_write_page: Unknown state %d"); 
 483 static bool hitag2_password(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
, bool write
) { 
 484         // Reset the transmission frame length 
 487         if (bPwd 
&& !bAuthenticating 
&& write
) { 
 488                 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) { 
 492                 // Try to find out which command was send by selecting on length (in bits) 
 494                         // No answer, try to resurrect 
 496                                 // Stop if there is no answer (after sending password) 
 498                                         DbpString("Password failed!"); 
 501                                 tx
[0] = HITAG2_START_AUTH
; 
 506                         // Received UID, tag password 
 510                                         bAuthenticating 
= true; 
 511                                         memcpy(tx
, password
, 4); 
 514                                         if (bAuthenticating
) { 
 515                                                 bAuthenticating 
= false; 
 517                                                         if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) { 
 523                                                 memcpy(tag
.sectors
[blocknr
], rx
, 4); 
 528                                                 DbpString("Read successful!"); 
 532                                         tx
[0] = HITAG2_READ_PAGE 
| (blocknr 
<< 3) | ((blocknr
^7) >> 2); 
 533                                         tx
[1] = ((blocknr
^7) << 6); 
 539                         // Unexpected response 
 541                                 Dbprintf("Unknown frame length: %d", rxlen
); 
 551 static bool hitag2_crypto(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
, bool write
) { 
 552         // Reset the transmission frame length 
 556                 hitag2_cipher_transcrypt(&cipher_state
, rx
, rxlen
/8, rxlen%8
); 
 559         if (bCrypto 
&& !bAuthenticating 
&& write
) { 
 560                 if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) { 
 565                 // Try to find out which command was send by selecting on length (in bits) 
 567                         // No answer, try to resurrect 
 569                                 // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 571                                         // Failed during authentication 
 572                                         if (bAuthenticating
) { 
 573                                                 DbpString("Authentication failed!"); 
 576                                                 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate 
 578                                                         // Write the low part of the key in memory 
 579                                                         memcpy(tag
.sectors
[1], key
+2, 4); 
 580                                                 } else if (blocknr 
== 2) { 
 581                                                         // Write the high part of the key in memory 
 582                                                         tag
.sectors
[2][0] = 0x00; 
 583                                                         tag
.sectors
[2][1] = 0x00; 
 584                                                         tag
.sectors
[2][2] = key
[0]; 
 585                                                         tag
.sectors
[2][3] = key
[1]; 
 587                                                         // Just put zero's in the memory (of the unreadable block) 
 588                                                         memset(tag
.sectors
[blocknr
], 0x00, 4); 
 594                                         tx
[0] = HITAG2_START_AUTH
; 
 599                         // Received UID, crypto tag answer 
 602                                         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; 
 603                                         uint32_t ui32uid 
= rx
[0] | ((uint32_t)rx
[1]) << 8 | ((uint32_t)rx
[2]) << 16 | ((uint32_t)rx
[3]) << 24; 
 604                                         Dbprintf("hitag2_crypto: key=0x%x%x uid=0x%x", (uint32_t) ((REV64(ui64key
)) >> 32), (uint32_t) ((REV64(ui64key
)) & 0xffffffff), REV32(ui32uid
)); 
 605                                         cipher_state 
= _hitag2_init(REV64(ui64key
), REV32(ui32uid
), 0); 
 607                                         memset(tx
+4, 0xff, 4); 
 608                                         hitag2_cipher_transcrypt(&cipher_state
, tx
+4, 4, 0); 
 611                                         bAuthenticating 
= true; 
 613                                         // Check if we received answer tag (at) 
 614                                         if (bAuthenticating
) { 
 615                                                 bAuthenticating 
= false; 
 617                                                         if (!hitag2_write_page(rx
, rxlen
, tx
, txlen
)) { 
 623                                         // stage 2+, got data block 
 625                                                 // Store the received block 
 626                                                 memcpy(tag
.sectors
[blocknr
], rx
, 4); 
 630                                                 DbpString("Read successful!"); 
 634                                                 tx
[0] = HITAG2_READ_PAGE 
| (blocknr 
<< 3) | ((blocknr 
^ 7) >> 2); 
 635                                                 tx
[1] = ((blocknr 
^ 7) << 6); 
 642                         // Unexpected response 
 644                                 Dbprintf("Unknown frame length: %d",rxlen
); 
 652                 // We have to return now to avoid double encryption 
 653                 if (!bAuthenticating
) { 
 654                         hitag2_cipher_transcrypt(&cipher_state
, tx
, *txlen
/8, *txlen%8
); 
 661 static bool hitag2_authenticate(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) { 
 662         // Reset the transmission frame length 
 665         // Try to find out which command was send by selecting on length (in bits) 
 667                 // No answer, try to resurrect 
 669                         // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 671                                 DbpString("Authentication failed!"); 
 674                         tx
[0] = HITAG2_START_AUTH
; 
 679                 // Received UID, crypto tag answer 
 686                                 DbpString("Authentication successful!"); 
 687                                 // We are done... for now 
 693                 // Unexpected response 
 695                         Dbprintf("Unknown frame length: %d",rxlen
); 
 704 static bool hitag2_test_auth_attempts(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) { 
 706         // Reset the transmission frame length 
 709         // Try to find out which command was send by selecting on length (in bits) 
 711                 // No answer, try to resurrect 
 713                         // Stop if there is no answer while we are in crypto mode (after sending NrAr) 
 715                                 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]); 
 717                                 // Removing failed entry from authentiations table 
 718                                 memcpy(auth_table
+auth_table_pos
, auth_table
+auth_table_pos
+8, 8); 
 721                                 // Return if we reached the end of the authentications table 
 723                                 if (auth_table_pos 
== auth_table_len
) { 
 727                                 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry) 
 728                                 memcpy(NrAr
, auth_table
+auth_table_pos
, 8); 
 730                         tx
[0] = HITAG2_START_AUTH
; 
 735                 // Received UID, crypto tag answer, or read block response 
 742                                 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]); 
 744                                 if ((auth_table_pos
+8) == auth_table_len
) { 
 748                                 memcpy(NrAr
, auth_table
+auth_table_pos
, 8); 
 754                         Dbprintf("Unknown frame length: %d",rxlen
); 
 763 static bool hitag2_read_uid(uint8_t *rx
, const size_t rxlen
, uint8_t *tx
, size_t *txlen
) { 
 764         // Reset the transmission frame length 
 767         // Try to find out which command was send by selecting on length (in bits) 
 769                 // No answer, try to resurrect 
 771                         // Just starting or if there is no answer 
 772                         tx
[0] = HITAG2_START_AUTH
; 
 778                         // Check if we received answer tag (at) 
 779                         if (bAuthenticating
) { 
 780                                 bAuthenticating 
= false; 
 782                                 // Store the received block 
 783                                 memcpy(tag
.sectors
[blocknr
], rx
, 4); 
 787                                 //DbpString("Read successful!"); 
 793                 // Unexpected response 
 795                         Dbprintf("Unknown frame length: %d",rxlen
); 
 803 void SnoopHitag(uint32_t type
) { 
 812         uint8_t rx
[HITAG_FRAME_LEN
] = {0}; 
 815         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
 817         // Clean up trace and prepare it for storing frames 
 825         auth_table 
= (uint8_t *)BigBuf_malloc(AUTH_TABLE_LENGTH
); 
 826         memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
); 
 828         DbpString("Starting Hitag2 snoop"); 
 831         // Set up eavesdropping mode, frequency divisor which will drive the FPGA 
 832         // and analog mux selection. 
 833         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT  
| FPGA_LF_EDGE_DETECT_TOGGLE_MODE
); 
 834         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
 835         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
 837         // Configure output pin that is connected to the FPGA (for modulating) 
 838         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 839         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 841         // Disable modulation, we are going to eavesdrop, not modulate ;) 
 844         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames 
 845         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
 846         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
 848         // Disable timer during configuration 
 849         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
 851         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
 852         // external trigger rising edge, load RA on rising edge of TIOA. 
 853         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_BOTH 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_BOTH
; 
 855         // Enable and reset counter 
 856         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
 858         // Reset the received frame, frame count and timing info 
 862         reader_frame 
= false; 
 867         while (!BUTTON_PRESS()) { 
 871                 // Receive frame, watch for at most T0*EOF periods 
 872                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_EOF
) { 
 873                         // Check if rising edge in modulation is detected 
 874                         if (AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
 875                                 // Retrieve the new timing values 
 876                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
 878                                 // Find out if we are dealing with a rising or falling edge 
 879                                 rising_edge 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_FRAME
) > 0; 
 881                                 // Shorter periods will only happen with reader frames 
 882                                 if (!reader_frame 
&& rising_edge 
&& ra 
< HITAG_T_TAG_CAPTURE_ONE_HALF
) { 
 883                                         // Switch from tag to reader capture 
 886                                         memset(rx
, 0x00, sizeof(rx
)); 
 890                                 // Only handle if reader frame and rising edge, or tag frame and falling edge 
 891                                 if (reader_frame 
!= rising_edge
) { 
 896                                 // Add the buffered timing values of earlier captured edges which were skipped 
 902                                         // Capture reader frame 
 903                                         if (ra 
>= HITAG_T_STOP
) { 
 905                                                         //DbpString("wierd0?"); 
 907                                                 // Capture the T0 periods that have passed since last communication or field drop (reset) 
 908                                                 response 
= (ra 
- HITAG_T_LOW
); 
 909                                         } else if (ra 
>= HITAG_T_1_MIN
) { 
 911                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 913                                         } else if (ra 
>= HITAG_T_0_MIN
) { 
 915                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 918                                                 // Ignore wierd value, is to small to mean anything 
 922                                         // Capture tag frame (manchester decoding using only falling edges) 
 923                                         if (ra 
>= HITAG_T_EOF
) { 
 925                                                         //DbpString("wierd1?"); 
 927                                                 // Capture the T0 periods that have passed since last communication or field drop (reset) 
 928                                                 // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
 929                                                 response 
= ra 
- HITAG_T_TAG_HALF_PERIOD
; 
 930                                         } else if (ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
 931                                                 // Manchester coding example |-_|_-|-_| (101) 
 932                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 934                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 936                                         } else if (ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
 937                                                 // Manchester coding example |_-|...|_-|-_| (0...01) 
 938                                                 rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
 940                                                 // We have to skip this half period at start and add the 'one' the second time 
 942                                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
 947                                         } else if (ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
 948                                                 // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
 950                                                         // Ignore bits that are transmitted during SOF 
 953                                                         // bit is same as last bit 
 954                                                         rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
 958                                                 // Ignore wierd value, is to small to mean anything 
 964                 // Check if frame was captured 
 967                         if (!LogTraceHitag(rx
, rxlen
, response
, 0, reader_frame
)) { 
 968                                 DbpString("Trace full"); 
 972                         // Check if we recognize a valid authentication attempt 
 973                         if (nbytes(rxlen
) == 8) { 
 974                                 // Store the authentication attempt 
 975                                 if (auth_table_len 
< (AUTH_TABLE_LENGTH
-8)) { 
 976                                         memcpy(auth_table
+auth_table_len
,rx
,8); 
 981                         // Reset the received frame and response timing info 
 982                         memset(rx
, 0x00, sizeof(rx
)); 
 984                         reader_frame 
= false; 
 993                         // Save the timer overflow, will be 0 when frame was received 
 994                         overflow 
+= (AT91C_BASE_TC1
->TC_CV
/T0
); 
 996                 // Reset the frame length 
 998                 // Reset the timer to restart while-loop that receives frames 
 999                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_SWTRG
; 
1005         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1006         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1007         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1010 //  Dbprintf("frame received: %d",frame_count); 
1011 //  Dbprintf("Authentication Attempts: %d",(auth_table_len/8)); 
1012 //  DbpString("All done"); 
1015 void SimulateHitagTag(bool tag_mem_supplied
, uint8_t *data
) { 
1019         uint8_t rx
[HITAG_FRAME_LEN
]; 
1021         uint8_t tx
[HITAG_FRAME_LEN
]; 
1023         bool bQuitTraceFull 
= false; 
1026         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1028         // Clean up trace and prepare it for storing frames 
1034         uint8_t *auth_table
; 
1036         auth_table 
= BigBuf_malloc(AUTH_TABLE_LENGTH
); 
1037         memset(auth_table
, 0x00, AUTH_TABLE_LENGTH
); 
1039         DbpString("Starting Hitag2 simulation"); 
1043         if (tag_mem_supplied
) { 
1044                 DbpString("Loading hitag2 memory..."); 
1045                 memcpy((uint8_t*)tag
.sectors
, data
, 48); 
1049         for (size_t i 
= 0; i 
< 12; i
++) { 
1050                 for (size_t j 
= 0; j 
< 4; j
++) { 
1052                         block 
|= tag
.sectors
[i
][j
]; 
1054                 Dbprintf("| %d | %08x |", i
, block
); 
1057         // Set up simulator mode, frequency divisor which will drive the FPGA 
1058         // and analog mux selection. 
1059         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
); 
1060         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1061         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1063         // Configure output pin that is connected to the FPGA (for modulating) 
1064         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1065         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1067         // Disable modulation at default, which means release resistance 
1070         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1071         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1073         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames 
1074         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1075         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1077         // Disable timer during configuration 
1078         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1079         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1081         // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers 
1082         AT91C_BASE_TC0
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
; 
1084         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1085         // external trigger rising edge, load RA on rising edge of TIOA. 
1086         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_RISING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_RISING
; 
1088         // Reset the received frame, frame count and timing info 
1089         memset(rx
, 0x00, sizeof(rx
)); 
1094         // Enable and reset counter 
1095         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1097         while (!BUTTON_PRESS()) { 
1101                 // Receive frame, watch for at most T0*EOF periods 
1102                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_EOF
) { 
1103                         // Check if rising edge in modulation is detected 
1104                         if (AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1105                                 // Retrieve the new timing values 
1106                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
) + overflow
; 
1109                                 // Reset timer every frame, we have to capture the last edge for timing 
1110                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1114                                 // Capture reader frame 
1115                                 if (ra 
>= HITAG_T_STOP
) { 
1117                                                 //DbpString("wierd0?"); 
1119                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1120                                         response 
= (ra 
- HITAG_T_LOW
); 
1121                                 } else if (ra 
>= HITAG_T_1_MIN
) { 
1123                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1125                                 } else if (ra 
>= HITAG_T_0_MIN
) { 
1127                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1130                                         // Ignore wierd value, is to small to mean anything 
1135                 // Check if frame was captured 
1139                                 if (!LogTraceHitag(rx
, rxlen
, response
, 0, true)) { 
1140                                         DbpString("Trace full"); 
1141                                         if (bQuitTraceFull
) { 
1149                         // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1150                         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1152                         // Process the incoming frame (rx) and prepare the outgoing frame (tx) 
1153                         hitag2_handle_reader_command(rx
, rxlen
, tx
, &txlen
); 
1155                         // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit, 
1156                         // not that since the clock counts since the rising edge, but T_Wait1 is 
1157                         // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low) 
1158                         // periods. The gap time T_Low varies (4..10). All timer values are in 
1159                         // terms of T0 units 
1160                         while (AT91C_BASE_TC0
->TC_CV 
< T0
*(HITAG_T_WAIT_1
-HITAG_T_LOW
)); 
1162                         // Send and store the tag answer (if there is any) 
1164                                 // Transmit the tag frame 
1165                                 hitag_send_frame(tx
, txlen
); 
1166                                 // Store the frame in the trace 
1168                                         if (!LogTraceHitag(tx
, txlen
, 0, 0, false)) { 
1169                                                 DbpString("Trace full"); 
1170                                                 if (bQuitTraceFull
) { 
1179                         // Reset the received frame and response timing info 
1180                         memset(rx
, 0x00, sizeof(rx
)); 
1183                         // Enable and reset external trigger in timer for capturing future frames 
1184                         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1187                 // Reset the frame length 
1189                 // Save the timer overflow, will be 0 when frame was received 
1190                 overflow 
+= (AT91C_BASE_TC1
->TC_CV
/T0
); 
1191                 // Reset the timer to restart while-loop that receives frames 
1192                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_SWTRG
; 
1196         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1197         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1198         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1200         DbpString("Sim Stopped"); 
1204 void ReaderHitag(hitag_function htf
, hitag_data 
*htd
) { 
1207         uint8_t rx
[HITAG_FRAME_LEN
]; 
1209         uint8_t txbuf
[HITAG_FRAME_LEN
]; 
1210         uint8_t *tx 
= txbuf
; 
1216         int t_wait 
= HITAG_T_WAIT_MAX
; 
1218         bool bQuitTraceFull 
= false; 
1220         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1221         // Reset the return status 
1222         bSuccessful 
= false; 
1224         // Clean up trace and prepare it for storing frames 
1228         //DbpString("Starting Hitag reader family"); 
1230         // Check configuration 
1232                 case RHT2F_PASSWORD
: { 
1233                         Dbprintf("List identifier in password mode"); 
1234                         memcpy(password
, htd
->pwd
.password
, 4); 
1236                         bQuitTraceFull 
= false; 
1239                         bAuthenticating 
= false; 
1242                 case RHT2F_AUTHENTICATE
: { 
1243                         DbpString("Authenticating using nr,ar pair:"); 
1244                         memcpy(NrAr
, htd
->auth
.NrAr
, 8); 
1245                         Dbhexdump(8, NrAr
, false); 
1248                         bAuthenticating 
= false; 
1249                         bQuitTraceFull 
= true; 
1254                         DbpString("Authenticating using key:"); 
1255                         memcpy(key
, htd
->crypto
.key
, 6);    //HACK; 4 or 6??  I read both in the code. 
1256                         Dbhexdump(6, key
, false); 
1260                         bAuthenticating 
= false; 
1261                         bQuitTraceFull 
= true; 
1264                 case RHT2F_TEST_AUTH_ATTEMPTS
: { 
1265                         Dbprintf("Testing %d authentication attempts", (auth_table_len
/8)); 
1267                         memcpy(NrAr
, auth_table
, 8); 
1268                         bQuitTraceFull 
= false; 
1273                 case RHT2F_UID_ONLY
: { 
1277                         bAuthenticating 
= false; 
1278                         bQuitTraceFull 
= true; 
1282                         Dbprintf("Error, unknown function: %d", htf
); 
1291         // Configure output and enable pin that is connected to the FPGA (for modulating) 
1292         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1293         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1295         // Set fpga in edge detect with reader field, we can modulate as reader now 
1296         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT 
| FPGA_LF_EDGE_DETECT_READER_FIELD
); 
1298         // Set Frequency divisor which will drive the FPGA and analog mux selection 
1299         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1300         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1302         // Disable modulation at default, which means enable the field 
1305         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1306         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1308         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames 
1309         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1310         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1312         // Disable timer during configuration 
1313         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1314         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1316         // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers 
1317         AT91C_BASE_TC0
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
; 
1319         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1320         // external trigger rising edge, load RA on falling edge of TIOA. 
1321         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_FALLING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_FALLING
; 
1323         // Enable and reset counters 
1324         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1325         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1327         // Reset the received frame, frame count and timing info 
1332         // Tag specific configuration settings (sof, timings, etc.) 
1337                 //DbpString("Configured for hitagS reader"); 
1338         } else if (htf 
< 20) { 
1342                 //DbpString("Configured for hitag1 reader"); 
1343         } else if (htf 
< 30) { 
1346                 t_wait 
= HITAG_T_WAIT_2
; 
1347                 //DbpString("Configured for hitag2 reader"); 
1349                 Dbprintf("Error, unknown hitag reader type: %d", htf
); 
1353         // wait for tag to power up 
1354         // t_PowerUp = 312,5 carrier periods 
1355         while (AT91C_BASE_TC0
->TC_CV 
< T0
*(312-t_wait
)); 
1357         uint8_t attempt_count 
= 0; 
1358         while (!bStop 
&& !BUTTON_PRESS()) { 
1361                 // Check if frame was captured and store it 
1365                                 if (!LogTraceHitag(rx
, rxlen
, response
, 0, false)) { 
1366                                         DbpString("Trace full"); 
1367                                         if (bQuitTraceFull
) { 
1376                 // By default reset the transmission buffer 
1379                         case RHT2F_PASSWORD
: { 
1380                                 bStop 
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, false); 
1383                         case RHT2F_AUTHENTICATE
: { 
1384                                 bStop 
= !hitag2_authenticate(rx
, rxlen
, tx
, &txlen
); 
1387                         case RHT2F_CRYPTO
: { 
1388                                 bStop 
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, false); 
1391                         case RHT2F_TEST_AUTH_ATTEMPTS
: { 
1392                                 bStop 
= !hitag2_test_auth_attempts(rx
, rxlen
, tx
, &txlen
); 
1395                         case RHT2F_UID_ONLY
: { 
1396                                 bStop 
= !hitag2_read_uid(rx
, rxlen
, tx
, &txlen
); 
1397                                 attempt_count
++; //attempt 3 times to get uid then quit 
1398                                 if (!bStop 
&& attempt_count 
== 3) 
1403                                 Dbprintf("Error, unknown function: %d", htf
); 
1408                 // Send and store the reader command 
1409                 // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1410                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1412                 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, 
1413                 // Since the clock counts since the last falling edge, a 'one' means that the 
1414                 // falling edge occured halfway the period. with respect to this falling edge, 
1415                 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. 
1416                 // All timer values are in terms of T0 units 
1417                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
))); 
1419                 //Dbprintf("DEBUG: Sending reader frame"); 
1421                 // Transmit the reader frame 
1422                 hitag_reader_send_frame(tx
, txlen
); 
1424                 // Enable and reset external trigger in timer for capturing future frames 
1425                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1427                 // Add transmitted frame to total count 
1431                                 // Store the frame in the trace 
1432                                 if (!LogTraceHitag(tx
, txlen
, HITAG_T_WAIT_2
, 0, true)) { 
1433                                         if (bQuitTraceFull
) { 
1442                 // Reset values for receiving frames 
1443                 memset(rx
, 0x00, sizeof(rx
)); 
1447                 tag_sof 
= reset_sof
; 
1449                 //Dbprintf("DEBUG: Waiting to receive frame"); 
1450                 uint32_t errorCount 
= 0; 
1452                 // Receive frame, watch for at most T0*EOF periods 
1453                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_WAIT_MAX
) { 
1454                         // Check if falling edge in tag modulation is detected 
1455                         if (AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1456                                 // Retrieve the new timing values 
1457                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
1459                                 // Reset timer every frame, we have to capture the last edge for timing 
1460                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1464                                 // Capture tag frame (manchester decoding using only falling edges) 
1465                                 if (ra 
>= HITAG_T_EOF
) { 
1467                                                 //Dbprintf("DEBUG: Wierd1"); 
1469                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1470                                         // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
1471                                         response 
= ra 
- HITAG_T_TAG_HALF_PERIOD
; 
1472                                 } else if (ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
1473                                         // Manchester coding example |-_|_-|-_| (101) 
1475                                         //need to test to verify we don't exceed memory... 
1476                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1479                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1481                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1483                                 } else if (ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
1484                                         // Manchester coding example |_-|...|_-|-_| (0...01) 
1486                                         //need to test to verify we don't exceed memory... 
1487                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1490                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1492                                         // We have to skip this half period at start and add the 'one' the second time 
1494                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1499                                 } else if (ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
1500                                         // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
1502                                         //need to test to verify we don't exceed memory... 
1503                                         //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1507                                                 // Ignore bits that are transmitted during SOF 
1510                                                 // bit is same as last bit 
1511                                                 rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
1515                                         //Dbprintf("DEBUG: Wierd2"); 
1517                                         // Ignore wierd value, is to small to mean anything 
1520                         //if we saw over 100 wierd values break it probably isn't hitag... 
1521                         if (errorCount 
> 100) break; 
1522                         // We can break this loop if we received the last bit from a frame 
1523                         if (AT91C_BASE_TC1
->TC_CV 
> T0
*HITAG_T_EOF
) { 
1524                                 if (rxlen 
> 0) break; 
1530         //Dbprintf("DEBUG: Done waiting for frame"); 
1534         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1535         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1536         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1537         //Dbprintf("frame received: %d",frame_count); 
1538         //DbpString("All done"); 
1540                 cmd_send(CMD_ACK
, bSuccessful
, 0, 0, (uint8_t*)tag
.sectors
, 48); 
1542                 cmd_send(CMD_ACK
, bSuccessful
, 0, 0, 0, 0); 
1545 void WriterHitag(hitag_function htf
, hitag_data 
*htd
, int page
) { 
1548         uint8_t rx
[HITAG_FRAME_LEN
]; 
1550         uint8_t txbuf
[HITAG_FRAME_LEN
]; 
1551         uint8_t *tx 
= txbuf
; 
1557         int t_wait 
= HITAG_T_WAIT_MAX
; 
1559         bool bQuitTraceFull 
= false; 
1561         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1562         // Reset the return status 
1563         bSuccessful 
= false; 
1565         // Clean up trace and prepare it for storing frames 
1569         //DbpString("Starting Hitag reader family"); 
1571         // Check configuration 
1573                 case WHT2F_CRYPTO
: { 
1574                         DbpString("Authenticating using key:"); 
1575                         memcpy(key
, htd
->crypto
.key
, 6);    //HACK; 4 or 6??  I read both in the code. 
1576                         memcpy(writedata
, htd
->crypto
.data
, 4); 
1577                         Dbhexdump(6, key
, false); 
1581                         bAuthenticating 
= false; 
1582                         bQuitTraceFull 
= true; 
1583                         writestate 
= WRITE_STATE_START
; 
1586                 case WHT2F_PASSWORD
: { 
1587                         DbpString("Authenticating using password:"); 
1588                         memcpy(password
, htd
->pwd
.password
, 4); 
1589                         memcpy(writedata
, htd
->crypto
.data
, 4); 
1590                         Dbhexdump(4, password
, false); 
1593                         bAuthenticating 
= false; 
1594                         writestate 
= WRITE_STATE_START
; 
1598                         Dbprintf("Error, unknown function: %d", htf
); 
1607         // Configure output and enable pin that is connected to the FPGA (for modulating) 
1608         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
1609         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
1611         // Set fpga in edge detect with reader field, we can modulate as reader now 
1612         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT 
| FPGA_LF_EDGE_DETECT_READER_FIELD
); 
1614         // Set Frequency divisor which will drive the FPGA and analog mux selection 
1615         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, 95); //125Khz 
1616         SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); 
1618         // Disable modulation at default, which means enable the field 
1621         // Give it a bit of time for the resonant antenna to settle. 
1624         // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering 
1625         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC0
); 
1627         // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames 
1628         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
1629         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_SSC_FRAME
; 
1631         // Disable timer during configuration 
1632         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1633         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1635         // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers 
1636         AT91C_BASE_TC0
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK
; 
1638         // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, 
1639         // external trigger rising edge, load RA on falling edge of TIOA. 
1640         AT91C_BASE_TC1
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV1_CLOCK 
| AT91C_TC_ETRGEDG_FALLING 
| AT91C_TC_ABETRG 
| AT91C_TC_LDRA_FALLING
; 
1642         // Enable and reset counters 
1643         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1644         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1646         // Reset the received frame, frame count and timing info 
1652         // Tag specific configuration settings (sof, timings, etc.) 
1657                 //DbpString("Configured for hitagS reader"); 
1658         } else if (htf 
< 20) { 
1662                 //DbpString("Configured for hitag1 reader"); 
1663         } else if (htf 
< 30) { 
1666                 t_wait 
= HITAG_T_WAIT_2
; 
1667                 //DbpString("Configured for hitag2 reader"); 
1669                 Dbprintf("Error, unknown hitag reader type: %d", htf
); 
1672         while (!bStop 
&& !BUTTON_PRESS()) { 
1676                 // Check if frame was captured and store it 
1680                                 if (!LogTraceHitag(rx
, rxlen
, response
, 0, false)) { 
1681                                         DbpString("Trace full"); 
1682                                         if (bQuitTraceFull
) { 
1691                 // By default reset the transmission buffer 
1694                         case WHT2F_CRYPTO
: { 
1695                                 bStop 
= !hitag2_crypto(rx
, rxlen
, tx
, &txlen
, true); 
1698                         case WHT2F_PASSWORD
: { 
1699                                 bStop 
= !hitag2_password(rx
, rxlen
, tx
, &txlen
, true); 
1703                                 Dbprintf("Error, unknown function: %d", htf
); 
1709                 // Send and store the reader command 
1710                 // Disable timer 1 with external trigger to avoid triggers during our own modulation 
1711                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1713                 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, 
1714                 // Since the clock counts since the last falling edge, a 'one' means that the 
1715                 // falling edge occured halfway the period. with respect to this falling edge, 
1716                 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. 
1717                 // All timer values are in terms of T0 units 
1718                 while (AT91C_BASE_TC0
->TC_CV 
< T0
*(t_wait
+(HITAG_T_TAG_HALF_PERIOD
*lastbit
))); 
1720                 //Dbprintf("DEBUG: Sending reader frame"); 
1722                 // Transmit the reader frame 
1723                 hitag_reader_send_frame(tx
, txlen
); 
1725                 // Enable and reset external trigger in timer for capturing future frames 
1726                 AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
1728                 // Add transmitted frame to total count 
1732                                 // Store the frame in the trace 
1733                                 if (!LogTraceHitag(tx
, txlen
, HITAG_T_WAIT_2
, 0, true)) { 
1734                                         if (bQuitTraceFull
) { 
1743                 // Reset values for receiving frames 
1744                 memset(rx
, 0x00, sizeof(rx
)); 
1748                 tag_sof 
= reset_sof
; 
1750                 //Dbprintf("DEBUG: Waiting to receive frame"); 
1751                 uint32_t errorCount 
= 0; 
1753                 // Receive frame, watch for at most T0*EOF periods 
1754                 while (AT91C_BASE_TC1
->TC_CV 
< T0
*HITAG_T_WAIT_MAX
) { 
1755                         // Check if falling edge in tag modulation is detected 
1756                         if (AT91C_BASE_TC1
->TC_SR 
& AT91C_TC_LDRAS
) { 
1757                                 // Retrieve the new timing values 
1758                                 int ra 
= (AT91C_BASE_TC1
->TC_RA
/T0
); 
1760                                 // Reset timer every frame, we have to capture the last edge for timing 
1761                                 AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1765                                 // Capture tag frame (manchester decoding using only falling edges) 
1766                                 if (ra 
>= HITAG_T_EOF
) { 
1768                                                 //Dbprintf("DEBUG: Wierd1"); 
1770                                         // Capture the T0 periods that have passed since last communication or field drop (reset) 
1771                                         // We always recieve a 'one' first, which has the falling edge after a half period |-_| 
1772                                         response 
= ra 
- HITAG_T_TAG_HALF_PERIOD
; 
1773                                 } else if (ra 
>= HITAG_T_TAG_CAPTURE_FOUR_HALF
) { 
1774                                         // Manchester coding example |-_|_-|-_| (101) 
1776                                         // need to test to verify we don't exceed memory... 
1777                                         // if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1780                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1782                                         rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1784                                 } else if (ra 
>= HITAG_T_TAG_CAPTURE_THREE_HALF
) { 
1785                                         // Manchester coding example |_-|...|_-|-_| (0...01) 
1787                                         // need to test to verify we don't exceed memory... 
1788                                         // if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1791                                         rx
[rxlen 
/ 8] |= 0 << (7-(rxlen%8
)); 
1793                                         // We have to skip this half period at start and add the 'one' the second time 
1795                                                 rx
[rxlen 
/ 8] |= 1 << (7-(rxlen%8
)); 
1800                                 } else if (ra 
>= HITAG_T_TAG_CAPTURE_TWO_HALF
) { 
1801                                         // Manchester coding example |_-|_-| (00) or |-_|-_| (11) 
1803                                         // need to test to verify we don't exceed memory... 
1804                                         // if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { 
1808                                                 // Ignore bits that are transmitted during SOF 
1811                                                 // bit is same as last bit 
1812                                                 rx
[rxlen 
/ 8] |= lastbit 
<< (7-(rxlen%8
)); 
1816                                         // Dbprintf("DEBUG: Wierd2"); 
1818                                         // Ignore wierd value, it is too small to mean anything 
1821                         // if we saw over 100 wierd values break it probably isn't hitag... 
1822                         if (errorCount 
> 100) break; 
1823                         // We can break this loop if we received the last bit from a frame 
1824                         if (AT91C_BASE_TC1
->TC_CV 
> T0
*HITAG_T_EOF
) { 
1825                                 if (rxlen 
> 0) break; 
1829                 // Wait some extra time for flash to be programmed 
1830                 if ((rxlen 
== 0) && (writestate 
== WRITE_STATE_PROG
)) { 
1831                         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_SWTRG
; 
1832                         while (AT91C_BASE_TC0
->TC_CV 
< T0
*(HITAG_T_PROG 
- HITAG_T_WAIT_MAX
)); 
1835         //Dbprintf("DEBUG: Done waiting for frame"); 
1839         AT91C_BASE_TC1
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1840         AT91C_BASE_TC0
->TC_CCR 
= AT91C_TC_CLKDIS
; 
1841         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1842         //Dbprintf("frame received: %d",frame_count); 
1843         //DbpString("All done"); 
1844         cmd_send(CMD_ACK
, bSuccessful
, 0, 0, (uint8_t*)tag
.sectors
, 48);