]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/hitag2.c
12bea2e507e209cf80850af1bc830c2ddf48221a
[proxmark3-svn] / armsrc / hitag2.c
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
4 // the license.
5 //-----------------------------------------------------------------------------
6 // Hitag2 emulation (preliminary test version)
7 //
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
17 //-----------------------------------------------------------------------------
18
19 #include "proxmark3.h"
20 #include "apps.h"
21 #include "util.h"
22 #include "hitag2.h"
23 #include "string.h"
24 #include "BigBuf.h"
25
26 static bool bQuiet;
27 static bool bCrypto;
28 static bool bAuthenticating;
29 static bool bPwd;
30 static bool bSuccessful;
31
32 struct hitag2_tag {
33 uint32_t uid;
34 enum {
35 TAG_STATE_RESET = 0x01, // Just powered up, awaiting GetSnr
36 TAG_STATE_ACTIVATING = 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
37 TAG_STATE_ACTIVATED = 0x03, // Activation complete, awaiting read/write commands
38 TAG_STATE_WRITING = 0x04, // In write command, awaiting sector contents to be written
39 } state;
40 unsigned int active_sector;
41 byte_t crypto_active;
42 uint64_t cs;
43 byte_t sectors[12][4];
44 };
45
46 static struct hitag2_tag tag = {
47 .state = TAG_STATE_RESET,
48 .sectors = { // Password mode: | Crypto mode:
49 [0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
50 [1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
51 [2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
52 [3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
53 [4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
54 [5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
55 [6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
56 [7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
57 [8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
58 [9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
59 [10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
60 [11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
61 },
62 };
63
64 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
65 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
66 #define AUTH_TABLE_LENGTH 2744
67 static byte_t* auth_table;
68 static size_t auth_table_pos = 0;
69 static size_t auth_table_len = AUTH_TABLE_LENGTH;
70
71 static byte_t password[4];
72 static byte_t NrAr[8];
73 static byte_t key[8];
74 static uint64_t cipher_state;
75
76 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
77 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
78 // For educational purposes only.
79 // No warranties or guarantees of any kind.
80 // This code is released into the public domain by its author.
81
82 // Basic macros:
83
84 #define u8 uint8_t
85 #define u32 uint32_t
86 #define u64 uint64_t
87 #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))
88 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
89 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
90 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
91 #define bit(x,n) (((x)>>(n))&1)
92 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
93 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
94 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
95
96 // Single bit Hitag2 functions:
97
98 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
99
100 static const u32 ht2_f4a = 0x2C79; // 0010 1100 0111 1001
101 static const u32 ht2_f4b = 0x6671; // 0110 0110 0111 0001
102 static const u32 ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
103
104 static u32 _f20 (const u64 x)
105 {
106 u32 i5;
107
108 i5 = ((ht2_f4a >> i4 (x, 1, 2, 4, 5)) & 1)* 1
109 + ((ht2_f4b >> i4 (x, 7,11,13,14)) & 1)* 2
110 + ((ht2_f4b >> i4 (x,16,20,22,25)) & 1)* 4
111 + ((ht2_f4b >> i4 (x,27,28,30,32)) & 1)* 8
112 + ((ht2_f4a >> i4 (x,33,42,43,45)) & 1)*16;
113
114 return (ht2_f5c >> i5) & 1;
115 }
116
117 static u64 _hitag2_init (const u64 key, const u32 serial, const u32 IV)
118 {
119 u32 i;
120 u64 x = ((key & 0xFFFF) << 32) + serial;
121
122 for (i = 0; i < 32; i++)
123 {
124 x >>= 1;
125 x += (u64) (_f20 (x) ^ (((IV >> i) ^ (key >> (i+16))) & 1)) << 47;
126 }
127 return x;
128 }
129
130 static u64 _hitag2_round (u64 *state)
131 {
132 u64 x = *state;
133
134 x = (x >> 1) +
135 ((((x >> 0) ^ (x >> 2) ^ (x >> 3) ^ (x >> 6)
136 ^ (x >> 7) ^ (x >> 8) ^ (x >> 16) ^ (x >> 22)
137 ^ (x >> 23) ^ (x >> 26) ^ (x >> 30) ^ (x >> 41)
138 ^ (x >> 42) ^ (x >> 43) ^ (x >> 46) ^ (x >> 47)) & 1) << 47);
139
140 *state = x;
141 return _f20 (x);
142 }
143
144 // "MIKRON" = O N M I K R
145 // Key = 4F 4E 4D 49 4B 52 - Secret 48-bit key
146 // Serial = 49 43 57 69 - Serial number of the tag, transmitted in clear
147 // Random = 65 6E 45 72 - Random IV, transmitted in clear
148 //~28~DC~80~31 = D7 23 7F CE - Authenticator value = inverted first 4 bytes of the keystream
149
150 // The code below must print out "D7 23 7F CE 8C D0 37 A9 57 49 C1 E6 48 00 8A B6".
151 // The inverse of the first 4 bytes is sent to the tag to authenticate.
152 // The rest is encrypted by XORing it with the subsequent keystream.
153
154 static u32 _hitag2_byte (u64 * x)
155 {
156 u32 i, c;
157
158 for (i = 0, c = 0; i < 8; i++) c += (u32) _hitag2_round (x) << (i^7);
159 return c;
160 }
161
162 static int hitag2_reset(void) {
163 tag.state = TAG_STATE_RESET;
164 tag.crypto_active = 0;
165 return 0;
166 }
167
168 static int hitag2_init(void) {
169 hitag2_reset();
170 return 0;
171 }
172
173 static void hitag2_cipher_reset(struct hitag2_tag *tag, const byte_t *iv)
174 {
175 uint64_t key = ((uint64_t)tag->sectors[2][2]) |
176 ((uint64_t)tag->sectors[2][3] << 8) |
177 ((uint64_t)tag->sectors[1][0] << 16) |
178 ((uint64_t)tag->sectors[1][1] << 24) |
179 ((uint64_t)tag->sectors[1][2] << 32) |
180 ((uint64_t)tag->sectors[1][3] << 40);
181 uint32_t uid = ((uint32_t)tag->sectors[0][0]) |
182 ((uint32_t)tag->sectors[0][1] << 8) |
183 ((uint32_t)tag->sectors[0][2] << 16) |
184 ((uint32_t)tag->sectors[0][3] << 24);
185 uint32_t iv_ = (((uint32_t)(iv[0]))) |
186 (((uint32_t)(iv[1])) << 8) |
187 (((uint32_t)(iv[2])) << 16) |
188 (((uint32_t)(iv[3])) << 24);
189 tag->cs = _hitag2_init(rev64(key), rev32(uid), rev32(iv_));
190 }
191
192 static int hitag2_cipher_authenticate(uint64_t* cs, const byte_t *authenticator_is)
193 {
194 byte_t authenticator_should[4];
195 authenticator_should[0] = ~_hitag2_byte(cs);
196 authenticator_should[1] = ~_hitag2_byte(cs);
197 authenticator_should[2] = ~_hitag2_byte(cs);
198 authenticator_should[3] = ~_hitag2_byte(cs);
199 return (memcmp(authenticator_should, authenticator_is, 4) == 0);
200 }
201
202 static int hitag2_cipher_transcrypt(uint64_t* cs, byte_t *data, unsigned int bytes, unsigned int bits)
203 {
204 int i;
205 for(i=0; i<bytes; i++) data[i] ^= _hitag2_byte(cs);
206 for(i=0; i<bits; i++) data[bytes] ^= _hitag2_round(cs) << (7-i);
207 return 0;
208 }
209
210 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
211 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
212 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
213 // T0 = TIMER_CLOCK1 / 125000 = 192
214 #define T0 192
215
216 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
217 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
218
219 #define HITAG_FRAME_LEN 20
220 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
221 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
222 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
223 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
224 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
225 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
226 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
227 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
228 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
229
230 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
231 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
232 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
233 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
234
235 #define HITAG_T_TAG_HALF_PERIOD 16
236 #define HITAG_T_TAG_FULL_PERIOD 32
237
238 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
239 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
240 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
241 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
242
243
244 static void hitag_send_bit(int bit) {
245 LED_A_ON();
246 // Reset clock for the next bit
247 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
248
249 // Fixed modulation, earlier proxmark version used inverted signal
250 if(bit == 0) {
251 // Manchester: Unloaded, then loaded |__--|
252 LOW(GPIO_SSC_DOUT);
253 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
254 HIGH(GPIO_SSC_DOUT);
255 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
256 } else {
257 // Manchester: Loaded, then unloaded |--__|
258 HIGH(GPIO_SSC_DOUT);
259 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
260 LOW(GPIO_SSC_DOUT);
261 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
262 }
263 LED_A_OFF();
264 }
265
266 static void hitag_send_frame(const byte_t* frame, size_t frame_len)
267 {
268 // Send start of frame
269 for(size_t i=0; i<5; i++) {
270 hitag_send_bit(1);
271 }
272
273 // Send the content of the frame
274 for(size_t i=0; i<frame_len; i++) {
275 hitag_send_bit((frame[i/8] >> (7-(i%8)))&1);
276 }
277
278 // Drop the modulation
279 LOW(GPIO_SSC_DOUT);
280 }
281
282
283 static void hitag2_handle_reader_command(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen)
284 {
285 byte_t rx_air[HITAG_FRAME_LEN];
286
287 // Copy the (original) received frame how it is send over the air
288 memcpy(rx_air,rx,nbytes(rxlen));
289
290 if(tag.crypto_active) {
291 hitag2_cipher_transcrypt(&(tag.cs),rx,rxlen/8,rxlen%8);
292 }
293
294 // Reset the transmission frame length
295 *txlen = 0;
296
297 // Try to find out which command was send by selecting on length (in bits)
298 switch (rxlen) {
299 // Received 11000 from the reader, request for UID, send UID
300 case 05: {
301 // Always send over the air in the clear plaintext mode
302 if(rx_air[0] != 0xC0) {
303 // Unknown frame ?
304 return;
305 }
306 *txlen = 32;
307 memcpy(tx,tag.sectors[0],4);
308 tag.crypto_active = 0;
309 }
310 break;
311
312 // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
313 case 10: {
314 unsigned int sector = (~( ((rx[0]<<2)&0x04) | ((rx[1]>>6)&0x03) ) & 0x07);
315 // Verify complement of sector index
316 if(sector != ((rx[0]>>3)&0x07)) {
317 //DbpString("Transmission error (read/write)");
318 return;
319 }
320
321 switch (rx[0] & 0xC6) {
322 // Read command: 11xx x00y
323 case 0xC0:
324 memcpy(tx,tag.sectors[sector],4);
325 *txlen = 32;
326 break;
327
328 // Inverted Read command: 01xx x10y
329 case 0x44:
330 for (size_t i=0; i<4; i++) {
331 tx[i] = tag.sectors[sector][i] ^ 0xff;
332 }
333 *txlen = 32;
334 break;
335
336 // Write command: 10xx x01y
337 case 0x82:
338 // Prepare write, acknowledge by repeating command
339 memcpy(tx,rx,nbytes(rxlen));
340 *txlen = rxlen;
341 tag.active_sector = sector;
342 tag.state=TAG_STATE_WRITING;
343 break;
344
345 // Unknown command
346 default:
347 Dbprintf("Uknown command: %02x %02x",rx[0],rx[1]);
348 return;
349 break;
350 }
351 }
352 break;
353
354 // Writing data or Reader password
355 case 32: {
356 if(tag.state == TAG_STATE_WRITING) {
357 // These are the sector contents to be written. We don't have to do anything else.
358 memcpy(tag.sectors[tag.active_sector],rx,nbytes(rxlen));
359 tag.state=TAG_STATE_RESET;
360 return;
361 } else {
362 // Received RWD password, respond with configuration and our password
363 if(memcmp(rx,tag.sectors[1],4) != 0) {
364 DbpString("Reader password is wrong");
365 return;
366 }
367 *txlen = 32;
368 memcpy(tx,tag.sectors[3],4);
369 }
370 }
371 break;
372
373 // Received RWD authentication challenge and respnse
374 case 64: {
375 // Store the authentication attempt
376 if (auth_table_len < (AUTH_TABLE_LENGTH-8)) {
377 memcpy(auth_table+auth_table_len,rx,8);
378 auth_table_len += 8;
379 }
380
381 // Reset the cipher state
382 hitag2_cipher_reset(&tag,rx);
383 // Check if the authentication was correct
384 if(!hitag2_cipher_authenticate(&(tag.cs),rx+4)) {
385 // The reader failed to authenticate, do nothing
386 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]);
387 return;
388 }
389 // Succesful, but commented out reporting back to the Host, this may delay to much.
390 // 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]);
391
392 // Activate encryption algorithm for all further communication
393 tag.crypto_active = 1;
394
395 // Use the tag password as response
396 memcpy(tx,tag.sectors[3],4);
397 *txlen = 32;
398 }
399 break;
400 }
401
402 // LogTraceHitag(rx,rxlen,0,0,false);
403 // LogTraceHitag(tx,*txlen,0,0,true);
404
405 if(tag.crypto_active) {
406 hitag2_cipher_transcrypt(&(tag.cs), tx, *txlen/8, *txlen%8);
407 }
408 }
409
410 static void hitag_reader_send_bit(int bit) {
411 LED_A_ON();
412 // Reset clock for the next bit
413 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
414
415 // Binary puls length modulation (BPLM) is used to encode the data stream
416 // This means that a transmission of a one takes longer than that of a zero
417
418 // Enable modulation, which means, drop the the field
419 HIGH(GPIO_SSC_DOUT);
420
421 // Wait for 4-10 times the carrier period
422 while(AT91C_BASE_TC0->TC_CV < T0*6);
423 // SpinDelayUs(8*8);
424
425 // Disable modulation, just activates the field again
426 LOW(GPIO_SSC_DOUT);
427
428 if(bit == 0) {
429 // Zero bit: |_-|
430 while(AT91C_BASE_TC0->TC_CV < T0*22);
431
432 } else {
433 // One bit: |_--|
434 while(AT91C_BASE_TC0->TC_CV < T0*28);
435 }
436 LED_A_OFF();
437 }
438
439
440 static void hitag_reader_send_frame(const byte_t* frame, size_t frame_len)
441 {
442 // Send the content of the frame
443 for(size_t i=0; i<frame_len; i++) {
444 hitag_reader_send_bit((frame[i/8] >> (7-(i%8)))&1);
445 }
446 // Send EOF
447 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
448 // Enable modulation, which means, drop the the field
449 HIGH(GPIO_SSC_DOUT);
450 // Wait for 4-10 times the carrier period
451 while(AT91C_BASE_TC0->TC_CV < T0*6);
452 // Disable modulation, just activates the field again
453 LOW(GPIO_SSC_DOUT);
454 }
455
456 size_t blocknr;
457
458 static bool hitag2_password(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
459 // Reset the transmission frame length
460 *txlen = 0;
461
462 // Try to find out which command was send by selecting on length (in bits)
463 switch (rxlen) {
464 // No answer, try to resurrect
465 case 0: {
466 // Stop if there is no answer (after sending password)
467 if (bPwd) {
468 DbpString("Password failed!");
469 return false;
470 }
471 *txlen = 5;
472 memcpy(tx,"\xc0",nbytes(*txlen));
473 } break;
474
475 // Received UID, tag password
476 case 32: {
477 if (!bPwd) {
478 *txlen = 32;
479 memcpy(tx,password,4);
480 bPwd = true;
481 memcpy(tag.sectors[blocknr],rx,4);
482 blocknr++;
483 } else {
484
485 if(blocknr == 1){
486 //store password in block1, the TAG answers with Block3, but we need the password in memory
487 memcpy(tag.sectors[blocknr],tx,4);
488 } else {
489 memcpy(tag.sectors[blocknr],rx,4);
490 }
491
492 blocknr++;
493 if (blocknr > 7) {
494 DbpString("Read succesful!");
495 bSuccessful = true;
496 return false;
497 }
498 *txlen = 10;
499 tx[0] = 0xc0 | (blocknr << 3) | ((blocknr^7) >> 2);
500 tx[1] = ((blocknr^7) << 6);
501 }
502 } break;
503
504 // Unexpected response
505 default: {
506 Dbprintf("Uknown frame length: %d",rxlen);
507 return false;
508 } break;
509 }
510 return true;
511 }
512
513 static bool hitag2_crypto(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
514 // Reset the transmission frame length
515 *txlen = 0;
516
517 if(bCrypto) {
518 hitag2_cipher_transcrypt(&cipher_state,rx,rxlen/8,rxlen%8);
519 }
520
521 // Try to find out which command was send by selecting on length (in bits)
522 switch (rxlen) {
523 // No answer, try to resurrect
524 case 0: {
525 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
526 if (bCrypto) {
527 // Failed during authentication
528 if (bAuthenticating) {
529 DbpString("Authentication failed!");
530 return false;
531 } else {
532 // Failed reading a block, could be (read/write) locked, skip block and re-authenticate
533 if (blocknr == 1) {
534 // Write the low part of the key in memory
535 memcpy(tag.sectors[1],key+2,4);
536 } else if (blocknr == 2) {
537 // Write the high part of the key in memory
538 tag.sectors[2][0] = 0x00;
539 tag.sectors[2][1] = 0x00;
540 tag.sectors[2][2] = key[0];
541 tag.sectors[2][3] = key[1];
542 } else {
543 // Just put zero's in the memory (of the unreadable block)
544 memset(tag.sectors[blocknr],0x00,4);
545 }
546 blocknr++;
547 bCrypto = false;
548 }
549 } else {
550 *txlen = 5;
551 memcpy(tx,"\xc0",nbytes(*txlen));
552 }
553 } break;
554
555 // Received UID, crypto tag answer
556 case 32: {
557 if (!bCrypto) {
558 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;
559 uint32_t ui32uid = rx[0] | ((uint32_t)rx[1]) << 8 | ((uint32_t)rx[2]) << 16 | ((uint32_t)rx[3]) << 24;
560 cipher_state = _hitag2_init(rev64(ui64key), rev32(ui32uid), 0);
561 memset(tx,0x00,4);
562 memset(tx+4,0xff,4);
563 hitag2_cipher_transcrypt(&cipher_state,tx+4,4,0);
564 *txlen = 64;
565 bCrypto = true;
566 bAuthenticating = true;
567 } else {
568 // Check if we received answer tag (at)
569 if (bAuthenticating) {
570 bAuthenticating = false;
571 } else {
572 // Store the received block
573 memcpy(tag.sectors[blocknr],rx,4);
574 blocknr++;
575 }
576 if (blocknr > 7) {
577 DbpString("Read succesful!");
578 bSuccessful = true;
579 return false;
580 }
581 *txlen = 10;
582 tx[0] = 0xc0 | (blocknr << 3) | ((blocknr^7) >> 2);
583 tx[1] = ((blocknr^7) << 6);
584 }
585 } break;
586
587 // Unexpected response
588 default: {
589 Dbprintf("Uknown frame length: %d",rxlen);
590 return false;
591 } break;
592 }
593
594
595 if(bCrypto) {
596 // We have to return now to avoid double encryption
597 if (!bAuthenticating) {
598 hitag2_cipher_transcrypt(&cipher_state, tx, *txlen/8, *txlen%8);
599 }
600 }
601
602 return true;
603 }
604
605
606 static bool hitag2_authenticate(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
607 // Reset the transmission frame length
608 *txlen = 0;
609
610 // Try to find out which command was send by selecting on length (in bits)
611 switch (rxlen) {
612 // No answer, try to resurrect
613 case 0: {
614 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
615 if (bCrypto) {
616 DbpString("Authentication failed!");
617 return false;
618 }
619 *txlen = 5;
620 memcpy(tx,"\xc0",nbytes(*txlen));
621 } break;
622
623 // Received UID, crypto tag answer
624 case 32: {
625 if (!bCrypto) {
626 *txlen = 64;
627 memcpy(tx,NrAr,8);
628 bCrypto = true;
629 } else {
630 DbpString("Authentication succesful!");
631 return true;
632 }
633 } break;
634
635 // Unexpected response
636 default: {
637 Dbprintf("Uknown frame length: %d",rxlen);
638 return false;
639 } break;
640 }
641
642 return true;
643 }
644
645
646 static bool hitag2_test_auth_attempts(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
647
648 // Reset the transmission frame length
649 *txlen = 0;
650
651 // Try to find out which command was send by selecting on length (in bits)
652 switch (rxlen) {
653 // No answer, try to resurrect
654 case 0: {
655 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
656 if (bCrypto) {
657 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]);
658
659 // Removing failed entry from authentiations table
660 memcpy(auth_table+auth_table_pos,auth_table+auth_table_pos+8,8);
661 auth_table_len -= 8;
662
663 // Return if we reached the end of the authentications table
664 bCrypto = false;
665 if (auth_table_pos == auth_table_len) {
666 return false;
667 }
668
669 // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
670 memcpy(NrAr,auth_table+auth_table_pos,8);
671 }
672 *txlen = 5;
673 memcpy(tx,"\xc0",nbytes(*txlen));
674 } break;
675
676 // Received UID, crypto tag answer, or read block response
677 case 32: {
678 if (!bCrypto) {
679 *txlen = 64;
680 memcpy(tx,NrAr,8);
681 bCrypto = true;
682 } else {
683 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]);
684 bCrypto = false;
685 if ((auth_table_pos+8) == auth_table_len) {
686 return false;
687 }
688 auth_table_pos += 8;
689 memcpy(NrAr,auth_table+auth_table_pos,8);
690 }
691 } break;
692
693 default: {
694 Dbprintf("Uknown frame length: %d",rxlen);
695 return false;
696 } break;
697 }
698
699 return true;
700 }
701
702
703 void SnoopHitag(uint32_t type) {
704 int frame_count;
705 int response;
706 int overflow;
707 bool rising_edge;
708 bool reader_frame;
709 int lastbit;
710 bool bSkip;
711 int tag_sof;
712 byte_t rx[HITAG_FRAME_LEN];
713 size_t rxlen=0;
714
715 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
716
717 // Clean up trace and prepare it for storing frames
718 set_tracing(TRUE);
719 clear_trace();
720
721 auth_table_len = 0;
722 auth_table_pos = 0;
723
724 BigBuf_free();
725 auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
726 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
727
728 DbpString("Starting Hitag2 snoop");
729 LED_D_ON();
730
731 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
732 // and analog mux selection.
733 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE);
734 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
735 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
736 RELAY_OFF();
737
738 // Configure output pin that is connected to the FPGA (for modulating)
739 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
740 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
741
742 // Disable modulation, we are going to eavesdrop, not modulate ;)
743 LOW(GPIO_SSC_DOUT);
744
745 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
746 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
747 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
748
749 // Disable timer during configuration
750 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
751
752 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
753 // external trigger rising edge, load RA on rising edge of TIOA.
754 uint32_t t1_channel_mode = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_BOTH | AT91C_TC_ABETRG | AT91C_TC_LDRA_BOTH;
755 AT91C_BASE_TC1->TC_CMR = t1_channel_mode;
756
757 // Enable and reset counter
758 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
759
760 // Reset the received frame, frame count and timing info
761 memset(rx,0x00,sizeof(rx));
762 frame_count = 0;
763 response = 0;
764 overflow = 0;
765 reader_frame = false;
766 lastbit = 1;
767 bSkip = true;
768 tag_sof = 4;
769
770 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
771 // Watchdog hit
772 WDT_HIT();
773
774 // Receive frame, watch for at most T0*EOF periods
775 while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) {
776 // Check if rising edge in modulation is detected
777 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
778 // Retrieve the new timing values
779 int ra = (AT91C_BASE_TC1->TC_RA/T0);
780
781 // Find out if we are dealing with a rising or falling edge
782 rising_edge = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME) > 0;
783
784 // Shorter periods will only happen with reader frames
785 if (!reader_frame && rising_edge && ra < HITAG_T_TAG_CAPTURE_ONE_HALF) {
786 // Switch from tag to reader capture
787 LED_C_OFF();
788 reader_frame = true;
789 memset(rx,0x00,sizeof(rx));
790 rxlen = 0;
791 }
792
793 // Only handle if reader frame and rising edge, or tag frame and falling edge
794 if (reader_frame != rising_edge) {
795 overflow += ra;
796 continue;
797 }
798
799 // Add the buffered timing values of earlier captured edges which were skipped
800 ra += overflow;
801 overflow = 0;
802
803 if (reader_frame) {
804 LED_B_ON();
805 // Capture reader frame
806 if(ra >= HITAG_T_STOP) {
807 if (rxlen != 0) {
808 //DbpString("wierd0?");
809 }
810 // Capture the T0 periods that have passed since last communication or field drop (reset)
811 response = (ra - HITAG_T_LOW);
812 } else if(ra >= HITAG_T_1_MIN ) {
813 // '1' bit
814 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
815 rxlen++;
816 } else if(ra >= HITAG_T_0_MIN) {
817 // '0' bit
818 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
819 rxlen++;
820 } else {
821 // Ignore wierd value, is to small to mean anything
822 }
823 } else {
824 LED_C_ON();
825 // Capture tag frame (manchester decoding using only falling edges)
826 if(ra >= HITAG_T_EOF) {
827 if (rxlen != 0) {
828 //DbpString("wierd1?");
829 }
830 // Capture the T0 periods that have passed since last communication or field drop (reset)
831 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
832 response = ra-HITAG_T_TAG_HALF_PERIOD;
833 } else if(ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
834 // Manchester coding example |-_|_-|-_| (101)
835 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
836 rxlen++;
837 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
838 rxlen++;
839 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
840 // Manchester coding example |_-|...|_-|-_| (0...01)
841 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
842 rxlen++;
843 // We have to skip this half period at start and add the 'one' the second time
844 if (!bSkip) {
845 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
846 rxlen++;
847 }
848 lastbit = !lastbit;
849 bSkip = !bSkip;
850 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
851 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
852 if (tag_sof) {
853 // Ignore bits that are transmitted during SOF
854 tag_sof--;
855 } else {
856 // bit is same as last bit
857 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
858 rxlen++;
859 }
860 } else {
861 // Ignore wierd value, is to small to mean anything
862 }
863 }
864 }
865 }
866
867 // Check if frame was captured
868 if(rxlen > 0) {
869 frame_count++;
870 if (!LogTraceHitag(rx,rxlen,response,0,reader_frame)) {
871 DbpString("Trace full");
872 break;
873 }
874
875 // Check if we recognize a valid authentication attempt
876 if (nbytes(rxlen) == 8) {
877 // Store the authentication attempt
878 if (auth_table_len < (AUTH_TABLE_LENGTH-8)) {
879 memcpy(auth_table+auth_table_len,rx,8);
880 auth_table_len += 8;
881 }
882 }
883
884 // Reset the received frame and response timing info
885 memset(rx,0x00,sizeof(rx));
886 response = 0;
887 reader_frame = false;
888 lastbit = 1;
889 bSkip = true;
890 tag_sof = 4;
891 overflow = 0;
892
893 LED_B_OFF();
894 LED_C_OFF();
895 } else {
896 // Save the timer overflow, will be 0 when frame was received
897 overflow += (AT91C_BASE_TC1->TC_CV/T0);
898 }
899 // Reset the frame length
900 rxlen = 0;
901 // Reset the timer to restart while-loop that receives frames
902 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
903 }
904 LED_A_ON();
905 LED_B_OFF();
906 LED_C_OFF();
907 LED_D_OFF();
908 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
909 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
910 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
911 LED_A_OFF();
912 set_tracing(TRUE);
913 // Dbprintf("frame received: %d",frame_count);
914 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
915 // DbpString("All done");
916 }
917
918 void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) {
919 int frame_count;
920 int response;
921 int overflow;
922 byte_t rx[HITAG_FRAME_LEN];
923 size_t rxlen=0;
924 byte_t tx[HITAG_FRAME_LEN];
925 size_t txlen=0;
926 bool bQuitTraceFull = false;
927 bQuiet = false;
928
929 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
930
931 // Clean up trace and prepare it for storing frames
932 set_tracing(TRUE);
933 clear_trace();
934
935 auth_table_len = 0;
936 auth_table_pos = 0;
937 byte_t* auth_table;
938 BigBuf_free();
939 auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
940 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
941
942 DbpString("Starting Hitag2 simulation");
943 LED_D_ON();
944 hitag2_init();
945
946 if (tag_mem_supplied) {
947 DbpString("Loading hitag2 memory...");
948 memcpy((byte_t*)tag.sectors,data,48);
949 }
950
951 uint32_t block = 0;
952 for (size_t i=0; i<12; i++) {
953 for (size_t j=0; j<4; j++) {
954 block <<= 8;
955 block |= tag.sectors[i][j];
956 }
957 Dbprintf("| %d | %08x |",i,block);
958 }
959
960 // Set up simulator mode, frequency divisor which will drive the FPGA
961 // and analog mux selection.
962 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD);
963 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
964 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
965 RELAY_OFF();
966
967 // Configure output pin that is connected to the FPGA (for modulating)
968 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
969 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
970
971 // Disable modulation at default, which means release resistance
972 LOW(GPIO_SSC_DOUT);
973
974 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
975 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
976
977 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
978 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
979 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
980
981 // Disable timer during configuration
982 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
983
984 // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
985 // external trigger rising edge, load RA on rising edge of TIOA.
986 AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_RISING | AT91C_TC_ABETRG | AT91C_TC_LDRA_RISING;
987
988 // Reset the received frame, frame count and timing info
989 memset(rx,0x00,sizeof(rx));
990 frame_count = 0;
991 response = 0;
992 overflow = 0;
993
994 // Enable and reset counter
995 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
996
997 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
998 // Watchdog hit
999 WDT_HIT();
1000
1001 // Receive frame, watch for at most T0*EOF periods
1002 while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) {
1003 // Check if rising edge in modulation is detected
1004 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
1005 // Retrieve the new timing values
1006 int ra = (AT91C_BASE_TC1->TC_RA/T0) + overflow;
1007 overflow = 0;
1008
1009 // Reset timer every frame, we have to capture the last edge for timing
1010 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1011
1012 LED_B_ON();
1013
1014 // Capture reader frame
1015 if(ra >= HITAG_T_STOP) {
1016 if (rxlen != 0) {
1017 //DbpString("wierd0?");
1018 }
1019 // Capture the T0 periods that have passed since last communication or field drop (reset)
1020 response = (ra - HITAG_T_LOW);
1021 } else if(ra >= HITAG_T_1_MIN ) {
1022 // '1' bit
1023 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1024 rxlen++;
1025 } else if(ra >= HITAG_T_0_MIN) {
1026 // '0' bit
1027 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1028 rxlen++;
1029 } else {
1030 // Ignore wierd value, is to small to mean anything
1031 }
1032 }
1033 }
1034
1035 // Check if frame was captured
1036 if(rxlen > 4) {
1037 frame_count++;
1038 if (!bQuiet) {
1039 if (!LogTraceHitag(rx,rxlen,response,0,true)) {
1040 DbpString("Trace full");
1041 if (bQuitTraceFull) {
1042 break;
1043 } else {
1044 bQuiet = true;
1045 }
1046 }
1047 }
1048
1049 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1050 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1051
1052 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1053 hitag2_handle_reader_command(rx,rxlen,tx,&txlen);
1054
1055 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1056 // not that since the clock counts since the rising edge, but T_Wait1 is
1057 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1058 // periods. The gap time T_Low varies (4..10). All timer values are in
1059 // terms of T0 units
1060 while(AT91C_BASE_TC0->TC_CV < T0*(HITAG_T_WAIT_1-HITAG_T_LOW));
1061
1062 // Send and store the tag answer (if there is any)
1063 if (txlen) {
1064 // Transmit the tag frame
1065 hitag_send_frame(tx,txlen);
1066 // Store the frame in the trace
1067 if (!bQuiet) {
1068 if (!LogTraceHitag(tx,txlen,0,0,false)) {
1069 DbpString("Trace full");
1070 if (bQuitTraceFull) {
1071 break;
1072 } else {
1073 bQuiet = true;
1074 }
1075 }
1076 }
1077 }
1078
1079 // Reset the received frame and response timing info
1080 memset(rx,0x00,sizeof(rx));
1081 response = 0;
1082
1083 // Enable and reset external trigger in timer for capturing future frames
1084 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1085 LED_B_OFF();
1086 }
1087 // Reset the frame length
1088 rxlen = 0;
1089 // Save the timer overflow, will be 0 when frame was received
1090 overflow += (AT91C_BASE_TC1->TC_CV/T0);
1091 // Reset the timer to restart while-loop that receives frames
1092 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
1093 }
1094 LED_B_OFF();
1095 LED_D_OFF();
1096 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1097 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1098 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1099
1100 DbpString("Sim Stopped");
1101 set_tracing(TRUE);
1102 }
1103
1104 void ReaderHitag(hitag_function htf, hitag_data* htd) {
1105 int frame_count;
1106 int response;
1107 byte_t rx[HITAG_FRAME_LEN];
1108 size_t rxlen=0;
1109 byte_t txbuf[HITAG_FRAME_LEN];
1110 byte_t* tx = txbuf;
1111 size_t txlen=0;
1112 int lastbit;
1113 bool bSkip;
1114 int reset_sof;
1115 int tag_sof;
1116 int t_wait = HITAG_T_WAIT_MAX;
1117 bool bStop;
1118 bool bQuitTraceFull = false;
1119
1120 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1121 // Reset the return status
1122 bSuccessful = false;
1123
1124 // Clean up trace and prepare it for storing frames
1125 set_tracing(TRUE);
1126 clear_trace();
1127
1128 DbpString("Starting Hitag reader family");
1129
1130 // Check configuration
1131 switch(htf) {
1132 case RHT2F_PASSWORD: {
1133 Dbprintf("List identifier in password mode");
1134 memcpy(password,htd->pwd.password,4);
1135 blocknr = 0;
1136 bQuitTraceFull = false;
1137 bQuiet = false;
1138 bPwd = false;
1139 } break;
1140
1141 case RHT2F_AUTHENTICATE: {
1142 DbpString("Authenticating using nr,ar pair:");
1143 memcpy(NrAr,htd->auth.NrAr,8);
1144 Dbhexdump(8,NrAr,false);
1145 bQuiet = false;
1146 bCrypto = false;
1147 bAuthenticating = false;
1148 bQuitTraceFull = true;
1149 } break;
1150
1151 case RHT2F_CRYPTO: {
1152 DbpString("Authenticating using key:");
1153 memcpy(key,htd->crypto.key,4); //HACK; 4 or 6?? I read both in the code.
1154 Dbhexdump(6,key,false);
1155 blocknr = 0;
1156 bQuiet = false;
1157 bCrypto = false;
1158 bAuthenticating = false;
1159 bQuitTraceFull = true;
1160 } break;
1161
1162 case RHT2F_TEST_AUTH_ATTEMPTS: {
1163 Dbprintf("Testing %d authentication attempts",(auth_table_len/8));
1164 auth_table_pos = 0;
1165 memcpy(NrAr, auth_table, 8);
1166 bQuitTraceFull = false;
1167 bQuiet = false;
1168 bCrypto = false;
1169 } break;
1170
1171 default: {
1172 Dbprintf("Error, unknown function: %d",htf);
1173 set_tracing(FALSE);
1174 return;
1175 } break;
1176 }
1177
1178 LED_D_ON();
1179 hitag2_init();
1180
1181 // Configure output and enable pin that is connected to the FPGA (for modulating)
1182 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
1183 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
1184
1185 // Set fpga in edge detect with reader field, we can modulate as reader now
1186 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD);
1187
1188 // Set Frequency divisor which will drive the FPGA and analog mux selection
1189 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
1190 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
1191 RELAY_OFF();
1192
1193 // Disable modulation at default, which means enable the field
1194 LOW(GPIO_SSC_DOUT);
1195
1196 // Give it a bit of time for the resonant antenna to settle.
1197 SpinDelay(30);
1198
1199 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1200 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
1201
1202 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1203 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
1204 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
1205
1206 // Disable timer during configuration
1207 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1208
1209 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1210 // external trigger rising edge, load RA on falling edge of TIOA.
1211 AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_FALLING | AT91C_TC_ABETRG | AT91C_TC_LDRA_FALLING;
1212
1213 // Enable and reset counters
1214 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1215 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1216
1217 // Reset the received frame, frame count and timing info
1218 frame_count = 0;
1219 response = 0;
1220 lastbit = 1;
1221 bStop = false;
1222
1223 // Tag specific configuration settings (sof, timings, etc.)
1224 if (htf < 10){
1225 // hitagS settings
1226 reset_sof = 1;
1227 t_wait = 200;
1228 DbpString("Configured for hitagS reader");
1229 } else if (htf < 20) {
1230 // hitag1 settings
1231 reset_sof = 1;
1232 t_wait = 200;
1233 DbpString("Configured for hitag1 reader");
1234 } else if (htf < 30) {
1235 // hitag2 settings
1236 reset_sof = 4;
1237 t_wait = HITAG_T_WAIT_2;
1238 DbpString("Configured for hitag2 reader");
1239 } else {
1240 Dbprintf("Error, unknown hitag reader type: %d",htf);
1241 set_tracing(FALSE);
1242 return;
1243 }
1244
1245 while(!bStop && !BUTTON_PRESS()) {
1246 // Watchdog hit
1247 WDT_HIT();
1248
1249 // Check if frame was captured and store it
1250 if(rxlen > 0) {
1251 frame_count++;
1252 if (!bQuiet) {
1253 if (!LogTraceHitag(rx,rxlen,response,0,false)) {
1254 DbpString("Trace full");
1255 if (bQuitTraceFull) {
1256 break;
1257 } else {
1258 bQuiet = true;
1259 }
1260 }
1261 }
1262 }
1263
1264 // By default reset the transmission buffer
1265 tx = txbuf;
1266 switch(htf) {
1267 case RHT2F_PASSWORD: {
1268 bStop = !hitag2_password(rx,rxlen,tx,&txlen);
1269 } break;
1270 case RHT2F_AUTHENTICATE: {
1271 bStop = !hitag2_authenticate(rx,rxlen,tx,&txlen);
1272 } break;
1273 case RHT2F_CRYPTO: {
1274 bStop = !hitag2_crypto(rx,rxlen,tx,&txlen);
1275 } break;
1276 case RHT2F_TEST_AUTH_ATTEMPTS: {
1277 bStop = !hitag2_test_auth_attempts(rx,rxlen,tx,&txlen);
1278 } break;
1279 default: {
1280 Dbprintf("Error, unknown function: %d",htf);
1281 set_tracing(FALSE);
1282 return;
1283 } break;
1284 }
1285
1286 // Send and store the reader command
1287 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1288 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1289
1290 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1291 // Since the clock counts since the last falling edge, a 'one' means that the
1292 // falling edge occured halfway the period. with respect to this falling edge,
1293 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1294 // All timer values are in terms of T0 units
1295 while(AT91C_BASE_TC0->TC_CV < T0*(t_wait+(HITAG_T_TAG_HALF_PERIOD*lastbit)));
1296
1297 // Transmit the reader frame
1298 hitag_reader_send_frame(tx,txlen);
1299
1300 // Enable and reset external trigger in timer for capturing future frames
1301 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1302
1303 // Add transmitted frame to total count
1304 if(txlen > 0) {
1305 frame_count++;
1306 if (!bQuiet) {
1307 // Store the frame in the trace
1308 if (!LogTraceHitag(tx,txlen,HITAG_T_WAIT_2,0,true)) {
1309 if (bQuitTraceFull) {
1310 break;
1311 } else {
1312 bQuiet = true;
1313 }
1314 }
1315 }
1316 }
1317
1318 // Reset values for receiving frames
1319 memset(rx,0x00,sizeof(rx));
1320 rxlen = 0;
1321 lastbit = 1;
1322 bSkip = true;
1323 tag_sof = reset_sof;
1324 response = 0;
1325
1326 // Receive frame, watch for at most T0*EOF periods
1327 while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_WAIT_MAX) {
1328 // Check if falling edge in tag modulation is detected
1329 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
1330 // Retrieve the new timing values
1331 int ra = (AT91C_BASE_TC1->TC_RA/T0);
1332
1333 // Reset timer every frame, we have to capture the last edge for timing
1334 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
1335
1336 LED_B_ON();
1337
1338 // Capture tag frame (manchester decoding using only falling edges)
1339 if(ra >= HITAG_T_EOF) {
1340 if (rxlen != 0) {
1341 //DbpString("wierd1?");
1342 }
1343 // Capture the T0 periods that have passed since last communication or field drop (reset)
1344 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1345 response = ra-HITAG_T_TAG_HALF_PERIOD;
1346 } else if(ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
1347 // Manchester coding example |-_|_-|-_| (101)
1348 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1349 rxlen++;
1350 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1351 rxlen++;
1352 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
1353 // Manchester coding example |_-|...|_-|-_| (0...01)
1354 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1355 rxlen++;
1356 // We have to skip this half period at start and add the 'one' the second time
1357 if (!bSkip) {
1358 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1359 rxlen++;
1360 }
1361 lastbit = !lastbit;
1362 bSkip = !bSkip;
1363 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
1364 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1365 if (tag_sof) {
1366 // Ignore bits that are transmitted during SOF
1367 tag_sof--;
1368 } else {
1369 // bit is same as last bit
1370 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
1371 rxlen++;
1372 }
1373 } else {
1374 // Ignore wierd value, is to small to mean anything
1375 }
1376 }
1377
1378 // We can break this loop if we received the last bit from a frame
1379 if (AT91C_BASE_TC1->TC_CV > T0*HITAG_T_EOF) {
1380 if (rxlen>0) break;
1381 }
1382 }
1383 }
1384 LED_B_OFF();
1385 LED_D_OFF();
1386 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1387 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1388 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1389 Dbprintf("DONE: frame received: %d",frame_count);
1390 cmd_send(CMD_ACK,bSuccessful,0,0,(byte_t*)tag.sectors,48);
1391 set_tracing(FALSE);
1392 }
Impressum, Datenschutz