]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/hitag2.c
fix hitag functions (issue #798) (#800)
[proxmark3-svn] / armsrc / hitag2.c
CommitLineData
bd20f8f4 1//-----------------------------------------------------------------------------
bd20f8f4 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
4// the license.
5//-----------------------------------------------------------------------------
d19929cb 6// Hitag2 emulation (preliminary test version)
bd20f8f4 7//
d19929cb 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
15//
16// (c) 2012 Roel Verdult
bd20f8f4 17//-----------------------------------------------------------------------------
3742d905 18
5866c187 19#include "hitag2.h"
20
e30c654b 21#include "proxmark3.h"
3742d905 22#include "apps.h"
f7e3ed82 23#include "util.h"
5866c187 24#include "hitag.h"
9ab7a6c7 25#include "string.h"
aabb719d 26#include "BigBuf.h"
fc52fbd4 27#include "fpgaloader.h"
3742d905 28
d19929cb 29static bool bQuiet;
30
f71f4deb 31static bool bCrypto;
32static bool bAuthenticating;
33static bool bPwd;
34static bool bSuccessful;
3742d905 35
117d9ec2 36
47e18126 37
3742d905 38struct hitag2_tag {
39 uint32_t uid;
e30c654b 40 enum {
d19929cb 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
3742d905 45 } state;
46 unsigned int active_sector;
d19929cb 47 byte_t crypto_active;
48 uint64_t cs;
49 byte_t sectors[12][4];
3742d905 50};
51
bde10a50 52static struct hitag2_tag tag = {
5866c187 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
67 },
3742d905 68};
69
52244230
HJ
70static enum {
71 WRITE_STATE_START = 0x0,
72 WRITE_STATE_PAGENUM_WRITTEN,
73 WRITE_STATE_PROG
74} writestate;
52244230 75
5866c187 76
77// ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
f71f4deb 78// Historically it used to be FREE_BUFFER_SIZE, which was 2744.
79#define AUTH_TABLE_LENGTH 2744
80static byte_t* auth_table;
81static size_t auth_table_pos = 0;
82static size_t auth_table_len = AUTH_TABLE_LENGTH;
e30c654b 83
f71f4deb 84static byte_t password[4];
85static byte_t NrAr[8];
86static byte_t key[8];
52244230 87static byte_t writedata[4];
f71f4deb 88static uint64_t cipher_state;
3742d905 89
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.
95
96// Basic macros:
97
5866c187 98#define u8 uint8_t
99#define u32 uint32_t
100#define u64 uint64_t
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)))
3742d905 109
110// Single bit Hitag2 functions:
111
5866c187 112#define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
3742d905 113
5866c187 114static const u32 ht2_f4a = 0x2C79; // 0010 1100 0111 1001
115static const u32 ht2_f4b = 0x6671; // 0110 0110 0111 0001
116static const u32 ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
3742d905 117
118static u32 _f20 (const u64 x)
119{
5866c187 120 u32 i5;
121
3742d905 122 i5 = ((ht2_f4a >> i4 (x, 1, 2, 4, 5)) & 1)* 1
52244230
HJ
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;
e30c654b 127
3742d905 128 return (ht2_f5c >> i5) & 1;
129}
130
131static u64 _hitag2_init (const u64 key, const u32 serial, const u32 IV)
132{
5866c187 133 u32 i;
134 u64 x = ((key & 0xFFFF) << 32) + serial;
e30c654b 135
3742d905 136 for (i = 0; i < 32; i++)
137 {
138 x >>= 1;
139 x += (u64) (_f20 (x) ^ (((IV >> i) ^ (key >> (i+16))) & 1)) << 47;
140 }
141 return x;
142}
143
144static u64 _hitag2_round (u64 *state)
145{
5866c187 146 u64 x = *state;
e30c654b 147
3742d905 148 x = (x >> 1) +
52244230
HJ
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);
e30c654b 153
3742d905 154 *state = x;
155 return _f20 (x);
156}
157
3742d905 158static u32 _hitag2_byte (u64 * x)
159{
5866c187 160 u32 i, c;
e30c654b 161
3742d905 162 for (i = 0, c = 0; i < 8; i++) c += (u32) _hitag2_round (x) << (i^7);
163 return c;
164}
165
f71f4deb 166static int hitag2_reset(void)
d19929cb 167{
168 tag.state = TAG_STATE_RESET;
169 tag.crypto_active = 0;
170 return 0;
171}
3742d905 172
f71f4deb 173static int hitag2_init(void)
d19929cb 174{
5866c187 175// memcpy(&tag, &resetdata, sizeof(tag));
d19929cb 176 hitag2_reset();
177 return 0;
178}
3742d905 179
d19929cb 180static void hitag2_cipher_reset(struct hitag2_tag *tag, const byte_t *iv)
3742d905 181{
bde10a50 182 uint64_t key = ((uint64_t)tag->sectors[2][2]) |
52244230
HJ
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);
bde10a50 188 uint32_t uid = ((uint32_t)tag->sectors[0][0]) |
52244230
HJ
189 ((uint32_t)tag->sectors[0][1] << 8) |
190 ((uint32_t)tag->sectors[0][2] << 16) |
191 ((uint32_t)tag->sectors[0][3] << 24);
3742d905 192 uint32_t iv_ = (((uint32_t)(iv[0]))) |
52244230
HJ
193 (((uint32_t)(iv[1])) << 8) |
194 (((uint32_t)(iv[2])) << 16) |
195 (((uint32_t)(iv[3])) << 24);
d19929cb 196 tag->cs = _hitag2_init(rev64(key), rev32(uid), rev32(iv_));
3742d905 197}
198
d19929cb 199static int hitag2_cipher_authenticate(uint64_t* cs, const byte_t *authenticator_is)
3742d905 200{
d19929cb 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);
3742d905 207}
208
d19929cb 209static int hitag2_cipher_transcrypt(uint64_t* cs, byte_t *data, unsigned int bytes, unsigned int bits)
3742d905 210{
211 int i;
d19929cb 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);
3742d905 214 return 0;
215}
d19929cb 216
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
221#define T0 192
222
5866c187 223#define SHORT_COIL() LOW(GPIO_SSC_DOUT)
224#define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
d19929cb 225
226#define HITAG_FRAME_LEN 20
227#define HITAG_T_STOP 36 /* T_EOF should be > 36 */
5866c187 228#define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
d19929cb 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 */
5866c187 232#define HITAG_T_EOF 80 /* T_EOF should be > 36 */
d19929cb 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 */
52244230 236#define HITAG_T_PROG 614
d19929cb 237
5866c187 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
d19929cb 242
5866c187 243#define HITAG_T_TAG_HALF_PERIOD 16
244#define HITAG_T_TAG_FULL_PERIOD 32
d19929cb 245
5866c187 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
d19929cb 250
251
252static void hitag_send_bit(int bit) {
253 LED_A_ON();
5866c187 254 // Reset clock for the next bit
d19929cb 255 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
5866c187 256
d19929cb 257 // Fixed modulation, earlier proxmark version used inverted signal
258 if(bit == 0) {
259 // Manchester: Unloaded, then loaded |__--|
260 LOW(GPIO_SSC_DOUT);
261 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
262 HIGH(GPIO_SSC_DOUT);
263 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
264 } else {
265 // Manchester: Loaded, then unloaded |--__|
266 HIGH(GPIO_SSC_DOUT);
267 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
268 LOW(GPIO_SSC_DOUT);
269 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
270 }
271 LED_A_OFF();
272}
273
274static void hitag_send_frame(const byte_t* frame, size_t frame_len)
275{
276 // Send start of frame
277 for(size_t i=0; i<5; i++) {
278 hitag_send_bit(1);
279 }
280
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);
284 }
285
286 // Drop the modulation
287 LOW(GPIO_SSC_DOUT);
288}
289
f71f4deb 290
291static void hitag2_handle_reader_command(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen)
d19929cb 292{
293 byte_t rx_air[HITAG_FRAME_LEN];
5866c187 294
d19929cb 295 // Copy the (original) received frame how it is send over the air
296 memcpy(rx_air,rx,nbytes(rxlen));
297
298 if(tag.crypto_active) {
299 hitag2_cipher_transcrypt(&(tag.cs),rx,rxlen/8,rxlen%8);
300 }
5866c187 301
302 // Reset the transmission frame length
d19929cb 303 *txlen = 0;
5866c187 304
d19929cb 305 // Try to find out which command was send by selecting on length (in bits)
306 switch (rxlen) {
5866c187 307 // Received 11000 from the reader, request for UID, send UID
52244230
HJ
308 case 05: {
309 // Always send over the air in the clear plaintext mode
310 if(rx_air[0] != 0xC0) {
311 // Unknown frame ?
312 return;
d19929cb 313 }
52244230
HJ
314 *txlen = 32;
315 memcpy(tx,tag.sectors[0],4);
316 tag.crypto_active = 0;
317 }
d19929cb 318 break;
319
5866c187 320 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
52244230
HJ
321 case 10: {
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)");
326 return;
327 }
d19929cb 328
52244230
HJ
329 switch (rx[0] & 0xC6) {
330 // Read command: 11xx x00y
331 case 0xC0:
332 memcpy(tx,tag.sectors[sector],4);
333 *txlen = 32;
334 break;
5866c187 335
52244230
HJ
336 // Inverted Read command: 01xx x10y
337 case 0x44:
338 for (size_t i=0; i<4; i++) {
339 tx[i] = tag.sectors[sector][i] ^ 0xff;
d19929cb 340 }
52244230
HJ
341 *txlen = 32;
342 break;
343
344 // Write command: 10xx x01y
345 case 0x82:
346 // Prepare write, acknowledge by repeating command
347 memcpy(tx,rx,nbytes(rxlen));
348 *txlen = rxlen;
349 tag.active_sector = sector;
350 tag.state=TAG_STATE_WRITING;
351 break;
5866c187 352
52244230
HJ
353 // Unknown command
354 default:
355 Dbprintf("Unknown command: %02x %02x",rx[0],rx[1]);
356 return;
357 break;
d19929cb 358 }
52244230 359 }
d19929cb 360 break;
361
362 // Writing data or Reader password
52244230
HJ
363 case 32: {
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;
368 return;
369 } else {
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");
d19929cb 373 return;
d19929cb 374 }
52244230
HJ
375 *txlen = 32;
376 memcpy(tx,tag.sectors[3],4);
d19929cb 377 }
52244230 378 }
d19929cb 379 break;
380
381 // Received RWD authentication challenge and respnse
52244230
HJ
382 case 64: {
383 // Store the authentication attempt
384 if (auth_table_len < (AUTH_TABLE_LENGTH-8)) {
385 memcpy(auth_table+auth_table_len,rx,8);
386 auth_table_len += 8;
387 }
d19929cb 388
52244230
HJ
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]);
395 return;
396 }
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]);
d19929cb 399
52244230
HJ
400 // Activate encryption algorithm for all further communication
401 tag.crypto_active = 1;
d19929cb 402
52244230
HJ
403 // Use the tag password as response
404 memcpy(tx,tag.sectors[3],4);
405 *txlen = 32;
406 }
d19929cb 407 break;
408 }
409
5866c187 410// LogTraceHitag(rx,rxlen,0,0,false);
411// LogTraceHitag(tx,*txlen,0,0,true);
412
d19929cb 413 if(tag.crypto_active) {
414 hitag2_cipher_transcrypt(&(tag.cs), tx, *txlen/8, *txlen%8);
415 }
416}
417
418static void hitag_reader_send_bit(int bit) {
419 LED_A_ON();
5866c187 420 // Reset clock for the next bit
d19929cb 421 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
5866c187 422
d19929cb 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
5866c187 425
b8140ab1 426 // Enable modulation, which means, drop the field
d19929cb 427 HIGH(GPIO_SSC_DOUT);
5866c187 428
d19929cb 429 // Wait for 4-10 times the carrier period
430 while(AT91C_BASE_TC0->TC_CV < T0*6);
5866c187 431 // SpinDelayUs(8*8);
432
d19929cb 433 // Disable modulation, just activates the field again
434 LOW(GPIO_SSC_DOUT);
5866c187 435
d19929cb 436 if(bit == 0) {
437 // Zero bit: |_-|
438 while(AT91C_BASE_TC0->TC_CV < T0*22);
5866c187 439 // SpinDelayUs(16*8);
d19929cb 440 } else {
441 // One bit: |_--|
442 while(AT91C_BASE_TC0->TC_CV < T0*28);
5866c187 443 // SpinDelayUs(22*8);
d19929cb 444 }
445 LED_A_OFF();
446}
447
f71f4deb 448
d19929cb 449static void hitag_reader_send_frame(const byte_t* frame, size_t frame_len)
450{
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);
454 }
5866c187 455 // Send EOF
d19929cb 456 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
b8140ab1 457 // Enable modulation, which means, drop the field
d19929cb 458 HIGH(GPIO_SSC_DOUT);
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
462 LOW(GPIO_SSC_DOUT);
463}
464
ed7bd3a3 465size_t blocknr;
466
f71f4deb 467static bool hitag2_password(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
d19929cb 468 // Reset the transmission frame length
469 *txlen = 0;
5866c187 470
d19929cb 471 // Try to find out which command was send by selecting on length (in bits)
472 switch (rxlen) {
473 // No answer, try to resurrect
52244230
HJ
474 case 0: {
475 // Stop if there is no answer (after sending password)
476 if (bPwd) {
477 DbpString("Password failed!");
478 return false;
479 }
480 *txlen = 5;
481 memcpy(tx,"\xc0",nbytes(*txlen));
482 } break;
5866c187 483
d19929cb 484 // Received UID, tag password
52244230
HJ
485 case 32: {
486 if (!bPwd) {
487 *txlen = 32;
488 memcpy(tx,password,4);
489 bPwd = true;
490 memcpy(tag.sectors[blocknr],rx,4);
491 blocknr++;
492 } else {
5866c187 493
219a334d 494 if(blocknr == 1){
495 //store password in block1, the TAG answers with Block3, but we need the password in memory
496 memcpy(tag.sectors[blocknr],tx,4);
497 }else{
498 memcpy(tag.sectors[blocknr],rx,4);
499 }
5866c187 500
219a334d 501 blocknr++;
502 if (blocknr > 7) {
52244230
HJ
503 DbpString("Read succesful!");
504 bSuccessful = true;
505 return false;
219a334d 506 }
507 *txlen = 10;
508 tx[0] = 0xc0 | (blocknr << 3) | ((blocknr^7) >> 2);
509 tx[1] = ((blocknr^7) << 6);
52244230
HJ
510 }
511 } break;
5866c187 512
d19929cb 513 // Unexpected response
52244230
HJ
514 default: {
515 Dbprintf("Uknown frame length: %d",rxlen);
516 return false;
517 } break;
518 }
519 return true;
520}
521
522static bool hitag2_write_page(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen)
523{
524 switch (writestate) {
525 case WRITE_STATE_START:
526 *txlen = 10;
527 tx[0] = 0x82 | (blocknr << 3) | ((blocknr^7) >> 2);
528 tx[1] = ((blocknr^7) << 6);
529 writestate = WRITE_STATE_PAGENUM_WRITTEN;
530 break;
531 case WRITE_STATE_PAGENUM_WRITTEN:
532 // Check if page number was received correctly
533 if ((rxlen == 10) &&
5866c187 534 (rx[0] == (0x82 | (blocknr << 3) | ((blocknr^7) >> 2))) &&
535 (rx[1] == (((blocknr & 0x3) ^ 0x3) << 6))) {
52244230
HJ
536 *txlen = 32;
537 memset(tx, 0, HITAG_FRAME_LEN);
538 memcpy(tx, writedata, 4);
539 writestate = WRITE_STATE_PROG;
540 } else {
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]);
543 bSuccessful = false;
d19929cb 544 return false;
52244230
HJ
545 }
546 break;
547 case WRITE_STATE_PROG:
548 if (rxlen == 0) {
549 bSuccessful = true;
550 } else {
551 bSuccessful = false;
552 Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen);
553 }
554 return false;
555 default:
556 DbpString("hitag2_write_page: Unknown state %d");
557 bSuccessful = false;
558 return false;
d19929cb 559 }
52244230 560
d19929cb 561 return true;
562}
563
52244230 564static bool hitag2_crypto(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen, bool write) {
bde10a50 565 // Reset the transmission frame length
566 *txlen = 0;
5866c187 567
52244230 568 if(bCrypto) {
bde10a50 569 hitag2_cipher_transcrypt(&cipher_state,rx,rxlen/8,rxlen%8);
52244230
HJ
570
571 }
572
573 if (bCrypto && !bAuthenticating && write) {
574 if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
575 return false;
576 }
bde10a50 577 }
52244230
HJ
578 else
579 {
bde10a50 580
581 // Try to find out which command was send by selecting on length (in bits)
582 switch (rxlen) {
52244230
HJ
583 // No answer, try to resurrect
584 case 0:
585 {
586 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
587 if (bCrypto) {
588 // Failed during authentication
589 if (bAuthenticating) {
590 DbpString("Authentication failed!");
591 return false;
fc8c5cdd 592 } else {
52244230
HJ
593 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
594 if (blocknr == 1) {
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];
603 } else {
604 // Just put zero's in the memory (of the unreadable block)
605 memset(tag.sectors[blocknr],0x00,4);
606 }
607 blocknr++;
608 bCrypto = false;
609 }
610 } else {
611 *txlen = 5;
612 memcpy(tx,"\xc0",nbytes(*txlen));
613 }
614 break;
615 }
616 // Received UID, crypto tag answer
617 case 32: {
618 if (!bCrypto) {
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);
623 memset(tx,0x00,4);
624 memset(tx+4,0xff,4);
625 hitag2_cipher_transcrypt(&cipher_state, tx+4, 4, 0);
626 *txlen = 64;
627 bCrypto = true;
628 bAuthenticating = true;
629 } else {
630 // Check if we received answer tag (at)
631 if (bAuthenticating) {
632 bAuthenticating = false;
633 if (write) {
634 if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
635 return false;
636 }
637 break;
638 }
bde10a50 639 } else {
52244230
HJ
640 // Store the received block
641 memcpy(tag.sectors[blocknr],rx,4);
642 blocknr++;
bde10a50 643 }
52244230
HJ
644
645 if (blocknr > 7) {
646 DbpString("Read succesful!");
647 bSuccessful = true;
648 return false;
649 } else {
650 *txlen = 10;
651 tx[0] = 0xc0 | (blocknr << 3) | ((blocknr^7) >> 2);
652 tx[1] = ((blocknr^7) << 6);
653 }
654 }
655 } break;
5866c187 656
52244230
HJ
657 // Unexpected response
658 default: {
659 Dbprintf("Uknown frame length: %d",rxlen);
660 return false;
661 } break;
662 }
bde10a50 663 }
5866c187 664
52244230
HJ
665 if(bCrypto) {
666 // We have to return now to avoid double encryption
667 if (!bAuthenticating) {
668 hitag2_cipher_transcrypt(&cipher_state,tx,*txlen/8,*txlen%8);
669 }
bde10a50 670 }
671
672 return true;
673}
674
675
f71f4deb 676static bool hitag2_authenticate(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
5866c187 677 // Reset the transmission frame length
d19929cb 678 *txlen = 0;
5866c187 679
d19929cb 680 // Try to find out which command was send by selecting on length (in bits)
681 switch (rxlen) {
682 // No answer, try to resurrect
52244230
HJ
683 case 0: {
684 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
685 if (bCrypto) {
686 DbpString("Authentication failed!");
687 return false;
688 }
689 *txlen = 5;
690 memcpy(tx,"\xc0",nbytes(*txlen));
691 } break;
5866c187 692
d19929cb 693 // Received UID, crypto tag answer
52244230
HJ
694 case 32: {
695 if (!bCrypto) {
696 *txlen = 64;
697 memcpy(tx,NrAr,8);
698 bCrypto = true;
699 } else {
700 DbpString("Authentication succesful!");
701 // We are done... for now
702 return false;
703 }
704 } break;
5866c187 705
d19929cb 706 // Unexpected response
52244230
HJ
707 default: {
708 Dbprintf("Uknown frame length: %d",rxlen);
709 return false;
710 } break;
d19929cb 711 }
5866c187 712
d19929cb 713 return true;
714}
715
117d9ec2 716
f71f4deb 717static bool hitag2_test_auth_attempts(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
117d9ec2 718
5866c187 719 // Reset the transmission frame length
d19929cb 720 *txlen = 0;
5866c187 721
d19929cb 722 // Try to find out which command was send by selecting on length (in bits)
723 switch (rxlen) {
52244230
HJ
724 // No answer, try to resurrect
725 case 0: {
726 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
727 if (bCrypto) {
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]);
43751d2a 729
52244230
HJ
730 // Removing failed entry from authentiations table
731 memcpy(auth_table+auth_table_pos,auth_table+auth_table_pos+8,8);
732 auth_table_len -= 8;
f71f4deb 733
52244230
HJ
734 // Return if we reached the end of the authentications table
735 bCrypto = false;
736 if (auth_table_pos == auth_table_len) {
737 return false;
d19929cb 738 }
52244230
HJ
739
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);
742 }
743 *txlen = 5;
744 memcpy(tx,"\xc0",nbytes(*txlen));
5866c187 745 } break;
746
52244230
HJ
747 // Received UID, crypto tag answer, or read block response
748 case 32: {
749 if (!bCrypto) {
750 *txlen = 64;
751 memcpy(tx,NrAr,8);
752 bCrypto = true;
753 } else {
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]);
755 bCrypto = false;
756 if ((auth_table_pos+8) == auth_table_len) {
757 return false;
d19929cb 758 }
52244230
HJ
759 auth_table_pos += 8;
760 memcpy(NrAr,auth_table+auth_table_pos,8);
761 }
762 } break;
5866c187 763
52244230
HJ
764 default: {
765 Dbprintf("Uknown frame length: %d",rxlen);
766 return false;
767 } break;
d19929cb 768 }
5866c187 769
d19929cb 770 return true;
771}
772
f86d6b55 773static bool hitag2_read_uid(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
774 // Reset the transmission frame length
775 *txlen = 0;
776
777 // Try to find out which command was send by selecting on length (in bits)
778 switch (rxlen) {
779 // No answer, try to resurrect
52244230
HJ
780 case 0: {
781 // Just starting or if there is no answer
782 *txlen = 5;
783 memcpy(tx,"\xc0",nbytes(*txlen));
784 } break;
f86d6b55 785 // Received UID
52244230
HJ
786 case 32: {
787 // Check if we received answer tag (at)
788 if (bAuthenticating) {
789 bAuthenticating = false;
790 } else {
791 // Store the received block
792 memcpy(tag.sectors[blocknr],rx,4);
793 blocknr++;
794 }
795 if (blocknr > 0) {
796 //DbpString("Read successful!");
797 bSuccessful = true;
f86d6b55 798 return false;
52244230
HJ
799 }
800 } break;
801 // Unexpected response
802 default: {
803 Dbprintf("Uknown frame length: %d",rxlen);
804 return false;
805 } break;
f86d6b55 806 }
807 return true;
808}
f71f4deb 809
d19929cb 810void SnoopHitag(uint32_t type) {
811 int frame_count;
812 int response;
813 int overflow;
814 bool rising_edge;
815 bool reader_frame;
816 int lastbit;
817 bool bSkip;
818 int tag_sof;
44964fd1 819 byte_t rx[HITAG_FRAME_LEN] = {0};
d19929cb 820 size_t rxlen=0;
5866c187 821
09ffd16e 822 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
823
824 // Clean up trace and prepare it for storing frames
44964fd1 825 set_tracing(true);
09ffd16e 826 clear_trace();
5866c187 827
d19929cb 828 auth_table_len = 0;
829 auth_table_pos = 0;
09ffd16e 830
f71f4deb 831 BigBuf_free();
52244230 832 auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
d19929cb 833 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
f71f4deb 834
d19929cb 835 DbpString("Starting Hitag2 snoop");
836 LED_D_ON();
5866c187 837
d19929cb 838 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
839 // and analog mux selection.
024b97c5 840 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE);
d19929cb 841 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
842 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
843 RELAY_OFF();
5866c187 844
d19929cb 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;
848
849 // Disable modulation, we are going to eavesdrop, not modulate ;)
850 LOW(GPIO_SSC_DOUT);
5866c187 851
d19929cb 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;
5866c187 855
856 // Disable timer during configuration
d19929cb 857 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
5866c187 858
859 // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
d19929cb 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;
5866c187 863
d19929cb 864 // Enable and reset counter
865 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
5866c187 866
d19929cb 867 // Reset the received frame, frame count and timing info
d19929cb 868 frame_count = 0;
869 response = 0;
870 overflow = 0;
871 reader_frame = false;
872 lastbit = 1;
873 bSkip = true;
874 tag_sof = 4;
5866c187 875
d19929cb 876 while(!BUTTON_PRESS()) {
877 // Watchdog hit
878 WDT_HIT();
5866c187 879
d19929cb 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) {
5866c187 884 // Retrieve the new timing values
d19929cb 885 int ra = (AT91C_BASE_TC1->TC_RA/T0);
5866c187 886
d19929cb 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;
889
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
893 LED_C_OFF();
894 reader_frame = true;
895 memset(rx,0x00,sizeof(rx));
896 rxlen = 0;
897 }
5866c187 898
d19929cb 899 // Only handle if reader frame and rising edge, or tag frame and falling edge
900 if (reader_frame != rising_edge) {
52244230 901 overflow += ra;
d19929cb 902 continue;
903 }
5866c187 904
d19929cb 905 // Add the buffered timing values of earlier captured edges which were skipped
906 ra += overflow;
907 overflow = 0;
5866c187 908
d19929cb 909 if (reader_frame) {
910 LED_B_ON();
911 // Capture reader frame
912 if(ra >= HITAG_T_STOP) {
913 if (rxlen != 0) {
914 //DbpString("wierd0?");
915 }
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 ) {
5866c187 919 // '1' bit
d19929cb 920 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
921 rxlen++;
922 } else if(ra >= HITAG_T_0_MIN) {
5866c187 923 // '0' bit
d19929cb 924 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
925 rxlen++;
926 } else {
927 // Ignore wierd value, is to small to mean anything
928 }
929 } else {
930 LED_C_ON();
931 // Capture tag frame (manchester decoding using only falling edges)
932 if(ra >= HITAG_T_EOF) {
933 if (rxlen != 0) {
934 //DbpString("wierd1?");
935 }
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));
942 rxlen++;
943 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
944 rxlen++;
945 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
946 // Manchester coding example |_-|...|_-|-_| (0...01)
947 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
948 rxlen++;
5866c187 949 // We have to skip this half period at start and add the 'one' the second time
d19929cb 950 if (!bSkip) {
951 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
952 rxlen++;
953 }
954 lastbit = !lastbit;
955 bSkip = !bSkip;
956 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
957 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
958 if (tag_sof) {
959 // Ignore bits that are transmitted during SOF
960 tag_sof--;
961 } else {
962 // bit is same as last bit
963 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
964 rxlen++;
965 }
966 } else {
967 // Ignore wierd value, is to small to mean anything
968 }
969 }
970 }
971 }
5866c187 972
d19929cb 973 // Check if frame was captured
974 if(rxlen > 0) {
975 frame_count++;
47e18126 976 if (!LogTraceHitag(rx,rxlen,response,0,reader_frame)) {
d19929cb 977 DbpString("Trace full");
978 break;
979 }
980
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);
986 auth_table_len += 8;
987 }
988 }
5866c187 989
d19929cb 990 // Reset the received frame and response timing info
991 memset(rx,0x00,sizeof(rx));
992 response = 0;
993 reader_frame = false;
994 lastbit = 1;
995 bSkip = true;
996 tag_sof = 4;
997 overflow = 0;
5866c187 998
d19929cb 999 LED_B_OFF();
1000 LED_C_OFF();
1001 } else {
1002 // Save the timer overflow, will be 0 when frame was received
1003 overflow += (AT91C_BASE_TC1->TC_CV/T0);
1004 }
1005 // Reset the frame length
1006 rxlen = 0;
1007 // Reset the timer to restart while-loop that receives frames
1008 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
1009 }
52244230 1010 LED_A_ON();
d19929cb 1011 LED_B_OFF();
1012 LED_C_OFF();
1013 LED_D_OFF();
1014 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
52244230 1015 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
d19929cb 1016 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
52244230 1017 LED_A_OFF();
5866c187 1018
1019// Dbprintf("frame received: %d",frame_count);
1020// Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1021// DbpString("All done");
d19929cb 1022}
1023
1024void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) {
1025 int frame_count;
1026 int response;
1027 int overflow;
1028 byte_t rx[HITAG_FRAME_LEN];
1029 size_t rxlen=0;
1030 byte_t tx[HITAG_FRAME_LEN];
1031 size_t txlen=0;
1032 bool bQuitTraceFull = false;
1033 bQuiet = false;
5866c187 1034
09ffd16e 1035 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1036
1037 // Clean up trace and prepare it for storing frames
44964fd1 1038 set_tracing(true);
09ffd16e 1039 clear_trace();
1040
d19929cb 1041 auth_table_len = 0;
1042 auth_table_pos = 0;
52244230 1043 byte_t* auth_table;
f71f4deb 1044 BigBuf_free();
52244230 1045 auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
d19929cb 1046 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
1047
1048 DbpString("Starting Hitag2 simulation");
1049 LED_D_ON();
1050 hitag2_init();
5866c187 1051
d19929cb 1052 if (tag_mem_supplied) {
1053 DbpString("Loading hitag2 memory...");
1054 memcpy((byte_t*)tag.sectors,data,48);
1055 }
1056
1057 uint32_t block = 0;
1058 for (size_t i=0; i<12; i++) {
1059 for (size_t j=0; j<4; j++) {
1060 block <<= 8;
1061 block |= tag.sectors[i][j];
1062 }
1063 Dbprintf("| %d | %08x |",i,block);
1064 }
5866c187 1065
d19929cb 1066 // Set up simulator mode, frequency divisor which will drive the FPGA
1067 // and analog mux selection.
28598e80 1068 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT);
d19929cb 1069 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
1070 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
1071 RELAY_OFF();
1072
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;
1076
1077 // Disable modulation at default, which means release resistance
1078 LOW(GPIO_SSC_DOUT);
5866c187 1079
d19929cb 1080 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1081 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
5866c187 1082
d19929cb 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;
5866c187 1086
1087 // Disable timer during configuration
1088 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
d19929cb 1089 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1090
5866c187 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;
1093
1094 // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
d19929cb 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;
5866c187 1097
d19929cb 1098 // Reset the received frame, frame count and timing info
1099 memset(rx,0x00,sizeof(rx));
1100 frame_count = 0;
1101 response = 0;
1102 overflow = 0;
3fe4ff4f 1103
1104 // Enable and reset counter
1105 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
5866c187 1106
d19929cb 1107 while(!BUTTON_PRESS()) {
1108 // Watchdog hit
1109 WDT_HIT();
5866c187 1110
d19929cb 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) {
5866c187 1115 // Retrieve the new timing values
d19929cb 1116 int ra = (AT91C_BASE_TC1->TC_RA/T0) + overflow;
1117 overflow = 0;
1118
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;
5866c187 1121
d19929cb 1122 LED_B_ON();
5866c187 1123
d19929cb 1124 // Capture reader frame
1125 if(ra >= HITAG_T_STOP) {
1126 if (rxlen != 0) {
1127 //DbpString("wierd0?");
1128 }
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 ) {
5866c187 1132 // '1' bit
d19929cb 1133 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1134 rxlen++;
1135 } else if(ra >= HITAG_T_0_MIN) {
5866c187 1136 // '0' bit
d19929cb 1137 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1138 rxlen++;
1139 } else {
1140 // Ignore wierd value, is to small to mean anything
1141 }
1142 }
1143 }
5866c187 1144
d19929cb 1145 // Check if frame was captured
1146 if(rxlen > 4) {
1147 frame_count++;
1148 if (!bQuiet) {
47e18126 1149 if (!LogTraceHitag(rx,rxlen,response,0,true)) {
d19929cb 1150 DbpString("Trace full");
1151 if (bQuitTraceFull) {
1152 break;
1153 } else {
1154 bQuiet = true;
1155 }
1156 }
1157 }
5866c187 1158
d19929cb 1159 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1160 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1161
1162 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1163 hitag2_handle_reader_command(rx,rxlen,tx,&txlen);
5866c187 1164
d19929cb 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)
5866c187 1168 // periods. The gap time T_Low varies (4..10). All timer values are in
d19929cb 1169 // terms of T0 units
1170 while(AT91C_BASE_TC0->TC_CV < T0*(HITAG_T_WAIT_1-HITAG_T_LOW));
1171
1172 // Send and store the tag answer (if there is any)
1173 if (txlen) {
1174 // Transmit the tag frame
1175 hitag_send_frame(tx,txlen);
1176 // Store the frame in the trace
1177 if (!bQuiet) {
47e18126 1178 if (!LogTraceHitag(tx,txlen,0,0,false)) {
d19929cb 1179 DbpString("Trace full");
1180 if (bQuitTraceFull) {
1181 break;
1182 } else {
1183 bQuiet = true;
1184 }
1185 }
1186 }
1187 }
5866c187 1188
d19929cb 1189 // Reset the received frame and response timing info
1190 memset(rx,0x00,sizeof(rx));
1191 response = 0;
5866c187 1192
d19929cb 1193 // Enable and reset external trigger in timer for capturing future frames
1194 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1195 LED_B_OFF();
1196 }
1197 // Reset the frame length
1198 rxlen = 0;
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;
1203 }
1204 LED_B_OFF();
1205 LED_D_OFF();
1206 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1207 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1208 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
5866c187 1209
3fe4ff4f 1210 DbpString("Sim Stopped");
5866c187 1211
d19929cb 1212}
1213
1214void ReaderHitag(hitag_function htf, hitag_data* htd) {
1215 int frame_count;
1216 int response;
1217 byte_t rx[HITAG_FRAME_LEN];
1218 size_t rxlen=0;
1219 byte_t txbuf[HITAG_FRAME_LEN];
1220 byte_t* tx = txbuf;
1221 size_t txlen=0;
1222 int lastbit;
1223 bool bSkip;
5866c187 1224 int reset_sof;
d19929cb 1225 int tag_sof;
1226 int t_wait = HITAG_T_WAIT_MAX;
217cfb6b 1227 bool bStop = false;
d19929cb 1228 bool bQuitTraceFull = false;
5866c187 1229
f71f4deb 1230 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1231 // Reset the return status
1232 bSuccessful = false;
5866c187 1233
d19929cb 1234 // Clean up trace and prepare it for storing frames
44964fd1 1235 set_tracing(true);
3000dc4e 1236 clear_trace();
117d9ec2 1237
f86d6b55 1238 //DbpString("Starting Hitag reader family");
d19929cb 1239
1240 // Check configuration
1241 switch(htf) {
52244230
HJ
1242 case RHT2F_PASSWORD: {
1243 Dbprintf("List identifier in password mode");
1244 memcpy(password,htd->pwd.password,4);
1245 blocknr = 0;
1246 bQuitTraceFull = false;
1247 bQuiet = false;
1248 bPwd = false;
1249 } break;
1250 case RHT2F_AUTHENTICATE: {
1251 DbpString("Authenticating using nr,ar pair:");
1252 memcpy(NrAr,htd->auth.NrAr,8);
1253 Dbhexdump(8,NrAr,false);
1254 bQuiet = false;
1255 bCrypto = false;
1256 bAuthenticating = false;
1257 bQuitTraceFull = true;
1258 } break;
5866c187 1259 case RHT2F_CRYPTO:
52244230
HJ
1260 {
1261 DbpString("Authenticating using key:");
5866c187 1262 memcpy(key,htd->crypto.key,6); //HACK; 4 or 6?? I read both in the code.
52244230
HJ
1263 Dbhexdump(6,key,false);
1264 blocknr = 0;
1265 bQuiet = false;
1266 bCrypto = false;
1267 bAuthenticating = false;
1268 bQuitTraceFull = true;
1269 } break;
1270 case RHT2F_TEST_AUTH_ATTEMPTS: {
1271 Dbprintf("Testing %d authentication attempts",(auth_table_len/8));
1272 auth_table_pos = 0;
1273 memcpy(NrAr, auth_table, 8);
1274 bQuitTraceFull = false;
1275 bQuiet = false;
1276 bCrypto = false;
1277 } break;
1278 case RHT2F_UID_ONLY: {
1279 blocknr = 0;
1280 bQuiet = false;
1281 bCrypto = false;
1282 bAuthenticating = false;
1283 bQuitTraceFull = true;
1284 } break;
1285 default: {
1286 Dbprintf("Error, unknown function: %d",htf);
1287 return;
1288 } break;
1289 }
5866c187 1290
52244230
HJ
1291 LED_D_ON();
1292 hitag2_init();
5866c187 1293
52244230
HJ
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;
5866c187 1297
52244230
HJ
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);
1300
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);
1304 RELAY_OFF();
1305
1306 // Disable modulation at default, which means enable the field
1307 LOW(GPIO_SSC_DOUT);
1308
1309 // Give it a bit of time for the resonant antenna to settle.
1310 SpinDelay(30);
5866c187 1311
52244230
HJ
1312 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1313 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
1314
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;
5866c187 1318
1319 // Disable timer during configuration
1320 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
52244230 1321 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
5866c187 1322
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;
1325
1326 // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
52244230
HJ
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;
5866c187 1329
52244230
HJ
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;
1333
1334 // Reset the received frame, frame count and timing info
1335 frame_count = 0;
1336 response = 0;
1337 lastbit = 1;
52244230
HJ
1338
1339 // Tag specific configuration settings (sof, timings, etc.)
1340 if (htf < 10){
1341 // hitagS settings
1342 reset_sof = 1;
1343 t_wait = 200;
1344 //DbpString("Configured for hitagS reader");
1345 } else if (htf < 20) {
1346 // hitag1 settings
1347 reset_sof = 1;
1348 t_wait = 200;
1349 //DbpString("Configured for hitag1 reader");
1350 } else if (htf < 30) {
1351 // hitag2 settings
1352 reset_sof = 4;
1353 t_wait = HITAG_T_WAIT_2;
1354 //DbpString("Configured for hitag2 reader");
1355 } else {
1356 Dbprintf("Error, unknown hitag reader type: %d",htf);
1357 return;
1358 }
1359 uint8_t attempt_count=0;
1360 while(!bStop && !BUTTON_PRESS()) {
1361 // Watchdog hit
1362 WDT_HIT();
5866c187 1363
52244230
HJ
1364 // Check if frame was captured and store it
1365 if(rxlen > 0) {
1366 frame_count++;
1367 if (!bQuiet) {
1368 if (!LogTraceHitag(rx,rxlen,response,0,false)) {
1369 DbpString("Trace full");
1370 if (bQuitTraceFull) {
1371 break;
1372 } else {
1373 bQuiet = true;
1374 }
1375 }
1376 }
1377 }
5866c187 1378
52244230
HJ
1379 // By default reset the transmission buffer
1380 tx = txbuf;
1381 switch(htf) {
217cfb6b 1382 case RHT2F_PASSWORD: {
1383 bStop = !hitag2_password(rx,rxlen,tx,&txlen);
1384 } break;
1385 case RHT2F_AUTHENTICATE: {
1386 bStop = !hitag2_authenticate(rx,rxlen,tx,&txlen);
1387 } break;
1388 case RHT2F_CRYPTO: {
1389 bStop = !hitag2_crypto(rx,rxlen,tx,&txlen, false);
1390 } break;
1391 case RHT2F_TEST_AUTH_ATTEMPTS: {
1392 bStop = !hitag2_test_auth_attempts(rx,rxlen,tx,&txlen);
1393 } break;
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;
1398 } break;
1399 default: {
1400 Dbprintf("Error, unknown function: %d",htf);
1401 return;
1402 } break;
52244230 1403 }
217cfb6b 1404
52244230
HJ
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;
217cfb6b 1408
52244230
HJ
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)));
217cfb6b 1415
52244230 1416 //Dbprintf("DEBUG: Sending reader frame");
5866c187 1417
52244230
HJ
1418 // Transmit the reader frame
1419 hitag_reader_send_frame(tx,txlen);
1420
217cfb6b 1421 // Enable and reset external trigger in timer for capturing future frames
52244230
HJ
1422 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1423
1424 // Add transmitted frame to total count
1425 if(txlen > 0) {
1426 frame_count++;
1427 if (!bQuiet) {
1428 // Store the frame in the trace
1429 if (!LogTraceHitag(tx,txlen,HITAG_T_WAIT_2,0,true)) {
1430 if (bQuitTraceFull) {
1431 break;
1432 } else {
1433 bQuiet = true;
1434 }
1435 }
1436 }
1437 }
1438
1439 // Reset values for receiving frames
1440 memset(rx,0x00,sizeof(rx));
1441 rxlen = 0;
1442 lastbit = 1;
1443 bSkip = true;
1444 tag_sof = reset_sof;
1445 response = 0;
1446 //Dbprintf("DEBUG: Waiting to receive frame");
1447 uint32_t errorCount = 0;
1448
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) {
5866c187 1453 // Retrieve the new timing values
52244230 1454 int ra = (AT91C_BASE_TC1->TC_RA/T0);
5866c187 1455
52244230
HJ
1456 // Reset timer every frame, we have to capture the last edge for timing
1457 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
5866c187 1458
52244230 1459 LED_B_ON();
5866c187 1460
52244230
HJ
1461 // Capture tag frame (manchester decoding using only falling edges)
1462 if(ra >= HITAG_T_EOF) {
1463 if (rxlen != 0) {
1464 //Dbprintf("DEBUG: Wierd1");
1465 }
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)
1471
1472 //need to test to verify we don't exceed memory...
1473 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
5866c187 1474 // break;
52244230
HJ
1475 //}
1476 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1477 rxlen++;
1478 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1479 rxlen++;
1480 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
1481 // Manchester coding example |_-|...|_-|-_| (0...01)
5866c187 1482
52244230
HJ
1483 //need to test to verify we don't exceed memory...
1484 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
5866c187 1485 // break;
52244230
HJ
1486 //}
1487 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1488 rxlen++;
5866c187 1489 // We have to skip this half period at start and add the 'one' the second time
52244230
HJ
1490 if (!bSkip) {
1491 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1492 rxlen++;
1493 }
1494 lastbit = !lastbit;
1495 bSkip = !bSkip;
1496 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
1497 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1498
1499 //need to test to verify we don't exceed memory...
1500 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
5866c187 1501 // break;
52244230
HJ
1502 //}
1503 if (tag_sof) {
1504 // Ignore bits that are transmitted during SOF
1505 tag_sof--;
1506 } else {
1507 // bit is same as last bit
1508 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
1509 rxlen++;
1510 }
1511 } else {
1512 //Dbprintf("DEBUG: Wierd2");
1513 errorCount++;
1514 // Ignore wierd value, is to small to mean anything
1515 }
1516 }
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) {
1521 if (rxlen>0) break;
1522 }
1523 }
1524 }
1525 //Dbprintf("DEBUG: Done waiting for frame");
5866c187 1526
52244230
HJ
1527 LED_B_OFF();
1528 LED_D_OFF();
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");
217cfb6b 1534 if (bSuccessful)
1535 cmd_send(CMD_ACK,bSuccessful,0,0,(byte_t*)tag.sectors,48);
1536 else
1537 cmd_send(CMD_ACK,bSuccessful,0,0,0,0);
1538
52244230
HJ
1539}
1540
1541void WriterHitag(hitag_function htf, hitag_data* htd, int page) {
1542 int frame_count;
1543 int response;
1544 byte_t rx[HITAG_FRAME_LEN];
1545 size_t rxlen=0;
1546 byte_t txbuf[HITAG_FRAME_LEN];
1547 byte_t* tx = txbuf;
1548 size_t txlen=0;
1549 int lastbit;
1550 bool bSkip;
5866c187 1551 int reset_sof;
52244230
HJ
1552 int tag_sof;
1553 int t_wait = HITAG_T_WAIT_MAX;
1554 bool bStop;
1555 bool bQuitTraceFull = false;
5866c187 1556
52244230
HJ
1557 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1558 // Reset the return status
1559 bSuccessful = false;
5866c187 1560
52244230 1561 // Clean up trace and prepare it for storing frames
44964fd1 1562 set_tracing(true);
52244230
HJ
1563 clear_trace();
1564
1565 //DbpString("Starting Hitag reader family");
1566
1567 // Check configuration
1568 switch(htf) {
1569 case WHT2F_CRYPTO:
1570 {
1571 DbpString("Authenticating using key:");
5866c187 1572 memcpy(key,htd->crypto.key,6); //HACK; 4 or 6?? I read both in the code.
52244230
HJ
1573 memcpy(writedata, htd->crypto.data, 4);
1574 Dbhexdump(6,key,false);
1575 blocknr = page;
1576 bQuiet = false;
1577 bCrypto = false;
1578 bAuthenticating = false;
1579 bQuitTraceFull = true;
1580 writestate = WRITE_STATE_START;
1581 } break;
1582 default: {
1583 Dbprintf("Error, unknown function: %d",htf);
1584 return;
1585 } break;
d19929cb 1586 }
5866c187 1587
d19929cb 1588 LED_D_ON();
1589 hitag2_init();
5866c187 1590
d19929cb 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;
5866c187 1594
d19929cb 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);
1597
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);
1601 RELAY_OFF();
1602
1603 // Disable modulation at default, which means enable the field
1604 LOW(GPIO_SSC_DOUT);
1605
1606 // Give it a bit of time for the resonant antenna to settle.
1607 SpinDelay(30);
5866c187 1608
d19929cb 1609 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1610 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
1611
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;
5866c187 1615
1616 // Disable timer during configuration
1617 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
d19929cb 1618 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
5866c187 1619
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;
1622
1623 // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
d19929cb 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;
5866c187 1626
d19929cb 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;
1630
1631 // Reset the received frame, frame count and timing info
1632 frame_count = 0;
1633 response = 0;
1634 lastbit = 1;
1635 bStop = false;
1636
52244230
HJ
1637 // Tag specific configuration settings (sof, timings, etc.)
1638 if (htf < 10){
1639 // hitagS settings
1640 reset_sof = 1;
1641 t_wait = 200;
1642 //DbpString("Configured for hitagS reader");
1643 } else if (htf < 20) {
1644 // hitag1 settings
1645 reset_sof = 1;
1646 t_wait = 200;
1647 //DbpString("Configured for hitag1 reader");
1648 } else if (htf < 30) {
1649 // hitag2 settings
1650 reset_sof = 4;
1651 t_wait = HITAG_T_WAIT_2;
1652 //DbpString("Configured for hitag2 reader");
d19929cb 1653 } else {
52244230
HJ
1654 Dbprintf("Error, unknown hitag reader type: %d",htf);
1655 return;
1656 }
d19929cb 1657 while(!bStop && !BUTTON_PRESS()) {
1658 // Watchdog hit
1659 WDT_HIT();
5866c187 1660
d19929cb 1661 // Check if frame was captured and store it
1662 if(rxlen > 0) {
1663 frame_count++;
1664 if (!bQuiet) {
47e18126 1665 if (!LogTraceHitag(rx,rxlen,response,0,false)) {
d19929cb 1666 DbpString("Trace full");
1667 if (bQuitTraceFull) {
1668 break;
1669 } else {
1670 bQuiet = true;
1671 }
1672 }
1673 }
1674 }
5866c187 1675
d19929cb 1676 // By default reset the transmission buffer
1677 tx = txbuf;
1678 switch(htf) {
52244230
HJ
1679 case WHT2F_CRYPTO: {
1680 bStop = !hitag2_crypto(rx,rxlen,tx,&txlen, true);
1681 } break;
1682 default: {
1683 Dbprintf("Error, unknown function: %d",htf);
1684 return;
1685 } break;
d19929cb 1686 }
5866c187 1687
d19929cb 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;
5866c187 1691
d19929cb 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)));
5866c187 1698
52244230 1699 //Dbprintf("DEBUG: Sending reader frame");
5866c187 1700
d19929cb 1701 // Transmit the reader frame
1702 hitag_reader_send_frame(tx,txlen);
1703
5866c187 1704 // Enable and reset external trigger in timer for capturing future frames
d19929cb 1705 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1706
1707 // Add transmitted frame to total count
1708 if(txlen > 0) {
1709 frame_count++;
1710 if (!bQuiet) {
1711 // Store the frame in the trace
47e18126 1712 if (!LogTraceHitag(tx,txlen,HITAG_T_WAIT_2,0,true)) {
d19929cb 1713 if (bQuitTraceFull) {
1714 break;
1715 } else {
1716 bQuiet = true;
1717 }
1718 }
1719 }
1720 }
52244230 1721
d19929cb 1722 // Reset values for receiving frames
1723 memset(rx,0x00,sizeof(rx));
1724 rxlen = 0;
1725 lastbit = 1;
1726 bSkip = true;
1727 tag_sof = reset_sof;
1728 response = 0;
52244230 1729 //Dbprintf("DEBUG: Waiting to receive frame");
921e6399 1730 uint32_t errorCount = 0;
1731
d19929cb 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) {
5866c187 1736 // Retrieve the new timing values
d19929cb 1737 int ra = (AT91C_BASE_TC1->TC_RA/T0);
5866c187 1738
d19929cb 1739 // Reset timer every frame, we have to capture the last edge for timing
1740 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
5866c187 1741
d19929cb 1742 LED_B_ON();
5866c187 1743
d19929cb 1744 // Capture tag frame (manchester decoding using only falling edges)
1745 if(ra >= HITAG_T_EOF) {
1746 if (rxlen != 0) {
921e6399 1747 //Dbprintf("DEBUG: Wierd1");
d19929cb 1748 }
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)
921e6399 1754
1755 //need to test to verify we don't exceed memory...
1756 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
5866c187 1757 // break;
921e6399 1758 //}
d19929cb 1759 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1760 rxlen++;
1761 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1762 rxlen++;
1763 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
1764 // Manchester coding example |_-|...|_-|-_| (0...01)
5866c187 1765
921e6399 1766 //need to test to verify we don't exceed memory...
1767 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
5866c187 1768 // break;
921e6399 1769 //}
d19929cb 1770 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1771 rxlen++;
5866c187 1772 // We have to skip this half period at start and add the 'one' the second time
d19929cb 1773 if (!bSkip) {
1774 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1775 rxlen++;
1776 }
1777 lastbit = !lastbit;
1778 bSkip = !bSkip;
1779 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
1780 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
921e6399 1781
1782 //need to test to verify we don't exceed memory...
1783 //if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) {
5866c187 1784 // break;
921e6399 1785 //}
d19929cb 1786 if (tag_sof) {
1787 // Ignore bits that are transmitted during SOF
1788 tag_sof--;
1789 } else {
1790 // bit is same as last bit
1791 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
1792 rxlen++;
1793 }
1794 } else {
52244230
HJ
1795 //Dbprintf("DEBUG: Wierd2");
1796 errorCount++;
d19929cb 1797 // Ignore wierd value, is to small to mean anything
1798 }
1799 }
921e6399 1800 //if we saw over 100 wierd values break it probably isn't hitag...
1801 if (errorCount >100) break;
d19929cb 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) {
1804 if (rxlen>0) break;
1805 }
1806 }
5866c187 1807
52244230
HJ
1808 // Wait some extra time for flash to be programmed
1809 if ((rxlen == 0) && (writestate == WRITE_STATE_PROG))
1810 {
1811 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
1812 while(AT91C_BASE_TC0->TC_CV < T0*(HITAG_T_PROG - HITAG_T_WAIT_MAX));
1813 }
d19929cb 1814 }
921e6399 1815 //Dbprintf("DEBUG: Done waiting for frame");
5866c187 1816
d19929cb 1817 LED_B_OFF();
1818 LED_D_OFF();
1819 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1820 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1821 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
f86d6b55 1822 //Dbprintf("frame received: %d",frame_count);
4c16ae80 1823 //DbpString("All done");
1824 cmd_send(CMD_ACK,bSuccessful,0,0,(byte_t*)tag.sectors,48);
d19929cb 1825}
Impressum, Datenschutz