]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/hitag2.c
05ac1f5e8e0a81258d4919c89a7ddd2f43795ddc
[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
25 static bool bQuiet;
26
27 bool bCrypto;
28 bool bAuthenticating;
29 bool bPwd;
30 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 //#define TRACE_LENGTH 3000
65 //uint8_t *trace = (uint8_t *) BigBuf;
66 //int traceLen = 0;
67 //int rsamples = 0;
68
69 #define AUTH_TABLE_OFFSET FREE_BUFFER_OFFSET
70 #define AUTH_TABLE_LENGTH FREE_BUFFER_SIZE
71 byte_t* auth_table = (byte_t *)BigBuf+AUTH_TABLE_OFFSET;
72 size_t auth_table_pos = 0;
73 size_t auth_table_len = AUTH_TABLE_LENGTH;
74
75 byte_t password[4];
76 byte_t NrAr[8];
77 byte_t key[8];
78 uint64_t cipher_state;
79
80 /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
81 // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
82 // For educational purposes only.
83 // No warranties or guarantees of any kind.
84 // This code is released into the public domain by its author.
85
86 // Basic macros:
87
88 #define u8 uint8_t
89 #define u32 uint32_t
90 #define u64 uint64_t
91 #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))
92 #define rev16(x) (rev8 (x)+(rev8 (x>> 8)<< 8))
93 #define rev32(x) (rev16(x)+(rev16(x>>16)<<16))
94 #define rev64(x) (rev32(x)+(rev32(x>>32)<<32))
95 #define bit(x,n) (((x)>>(n))&1)
96 #define bit32(x,n) ((((x)[(n)>>5])>>((n)))&1)
97 #define inv32(x,i,n) ((x)[(i)>>5]^=((u32)(n))<<((i)&31))
98 #define rotl64(x, n) ((((u64)(x))<<((n)&63))+(((u64)(x))>>((0-(n))&63)))
99
100 // Single bit Hitag2 functions:
101
102 #define i4(x,a,b,c,d) ((u32)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
103
104 static const u32 ht2_f4a = 0x2C79; // 0010 1100 0111 1001
105 static const u32 ht2_f4b = 0x6671; // 0110 0110 0111 0001
106 static const u32 ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
107
108 static u32 _f20 (const u64 x)
109 {
110 u32 i5;
111
112 i5 = ((ht2_f4a >> i4 (x, 1, 2, 4, 5)) & 1)* 1
113 + ((ht2_f4b >> i4 (x, 7,11,13,14)) & 1)* 2
114 + ((ht2_f4b >> i4 (x,16,20,22,25)) & 1)* 4
115 + ((ht2_f4b >> i4 (x,27,28,30,32)) & 1)* 8
116 + ((ht2_f4a >> i4 (x,33,42,43,45)) & 1)*16;
117
118 return (ht2_f5c >> i5) & 1;
119 }
120
121 static u64 _hitag2_init (const u64 key, const u32 serial, const u32 IV)
122 {
123 u32 i;
124 u64 x = ((key & 0xFFFF) << 32) + serial;
125
126 for (i = 0; i < 32; i++)
127 {
128 x >>= 1;
129 x += (u64) (_f20 (x) ^ (((IV >> i) ^ (key >> (i+16))) & 1)) << 47;
130 }
131 return x;
132 }
133
134 static u64 _hitag2_round (u64 *state)
135 {
136 u64 x = *state;
137
138 x = (x >> 1) +
139 ((((x >> 0) ^ (x >> 2) ^ (x >> 3) ^ (x >> 6)
140 ^ (x >> 7) ^ (x >> 8) ^ (x >> 16) ^ (x >> 22)
141 ^ (x >> 23) ^ (x >> 26) ^ (x >> 30) ^ (x >> 41)
142 ^ (x >> 42) ^ (x >> 43) ^ (x >> 46) ^ (x >> 47)) & 1) << 47);
143
144 *state = x;
145 return _f20 (x);
146 }
147
148 static u32 _hitag2_byte (u64 * x)
149 {
150 u32 i, c;
151
152 for (i = 0, c = 0; i < 8; i++) c += (u32) _hitag2_round (x) << (i^7);
153 return c;
154 }
155
156 size_t nbytes(size_t nbits) {
157 return (nbits/8)+((nbits%8)>0);
158 }
159
160 int hitag2_reset(void)
161 {
162 tag.state = TAG_STATE_RESET;
163 tag.crypto_active = 0;
164 return 0;
165 }
166
167 int hitag2_init(void)
168 {
169 // memcpy(&tag, &resetdata, sizeof(tag));
170 hitag2_reset();
171 return 0;
172 }
173
174 static void hitag2_cipher_reset(struct hitag2_tag *tag, const byte_t *iv)
175 {
176 uint64_t key = ((uint64_t)tag->sectors[2][2]) |
177 ((uint64_t)tag->sectors[2][3] << 8) |
178 ((uint64_t)tag->sectors[1][0] << 16) |
179 ((uint64_t)tag->sectors[1][1] << 24) |
180 ((uint64_t)tag->sectors[1][2] << 32) |
181 ((uint64_t)tag->sectors[1][3] << 40);
182 uint32_t uid = ((uint32_t)tag->sectors[0][0]) |
183 ((uint32_t)tag->sectors[0][1] << 8) |
184 ((uint32_t)tag->sectors[0][2] << 16) |
185 ((uint32_t)tag->sectors[0][3] << 24);
186 uint32_t iv_ = (((uint32_t)(iv[0]))) |
187 (((uint32_t)(iv[1])) << 8) |
188 (((uint32_t)(iv[2])) << 16) |
189 (((uint32_t)(iv[3])) << 24);
190 tag->cs = _hitag2_init(rev64(key), rev32(uid), rev32(iv_));
191 }
192
193 static int hitag2_cipher_authenticate(uint64_t* cs, const byte_t *authenticator_is)
194 {
195 byte_t authenticator_should[4];
196 authenticator_should[0] = ~_hitag2_byte(cs);
197 authenticator_should[1] = ~_hitag2_byte(cs);
198 authenticator_should[2] = ~_hitag2_byte(cs);
199 authenticator_should[3] = ~_hitag2_byte(cs);
200 return (memcmp(authenticator_should, authenticator_is, 4) == 0);
201 }
202
203 static int hitag2_cipher_transcrypt(uint64_t* cs, byte_t *data, unsigned int bytes, unsigned int bits)
204 {
205 int i;
206 for(i=0; i<bytes; i++) data[i] ^= _hitag2_byte(cs);
207 for(i=0; i<bits; i++) data[bytes] ^= _hitag2_round(cs) << (7-i);
208 return 0;
209 }
210
211 // Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
212 // TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
213 // Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
214 // T0 = TIMER_CLOCK1 / 125000 = 192
215 #define T0 192
216
217 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
218 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
219
220 #define HITAG_FRAME_LEN 20
221 #define HITAG_T_STOP 36 /* T_EOF should be > 36 */
222 #define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
223 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
224 #define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
225 //#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
226 #define HITAG_T_EOF 80 /* T_EOF should be > 36 */
227 #define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
228 #define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
229 #define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
230
231 #define HITAG_T_TAG_ONE_HALF_PERIOD 10
232 #define HITAG_T_TAG_TWO_HALF_PERIOD 25
233 #define HITAG_T_TAG_THREE_HALF_PERIOD 41
234 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57
235
236 #define HITAG_T_TAG_HALF_PERIOD 16
237 #define HITAG_T_TAG_FULL_PERIOD 32
238
239 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13
240 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25
241 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41
242 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
243
244
245 static void hitag_send_bit(int bit) {
246 LED_A_ON();
247 // Reset clock for the next bit
248 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
249
250 // Fixed modulation, earlier proxmark version used inverted signal
251 if(bit == 0) {
252 // Manchester: Unloaded, then loaded |__--|
253 LOW(GPIO_SSC_DOUT);
254 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
255 HIGH(GPIO_SSC_DOUT);
256 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
257 } else {
258 // Manchester: Loaded, then unloaded |--__|
259 HIGH(GPIO_SSC_DOUT);
260 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
261 LOW(GPIO_SSC_DOUT);
262 while(AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
263 }
264 LED_A_OFF();
265 }
266
267 static void hitag_send_frame(const byte_t* frame, size_t frame_len)
268 {
269 // Send start of frame
270 for(size_t i=0; i<5; i++) {
271 hitag_send_bit(1);
272 }
273
274 // Send the content of the frame
275 for(size_t i=0; i<frame_len; i++) {
276 hitag_send_bit((frame[i/8] >> (7-(i%8)))&1);
277 }
278
279 // Drop the modulation
280 LOW(GPIO_SSC_DOUT);
281 }
282
283 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 // LogTrace(rx,nbytes(rxlen),0,0,false);
403 // LogTrace(tx,nbytes(*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 // SpinDelayUs(16*8);
432 } else {
433 // One bit: |_--|
434 while(AT91C_BASE_TC0->TC_CV < T0*28);
435 // SpinDelayUs(22*8);
436 }
437 LED_A_OFF();
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 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 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 memcpy(tag.sectors[1],key+2,4);
535 } else if (blocknr == 2) {
536 tag.sectors[2][0] = 0x00;
537 tag.sectors[2][1] = 0x00;
538 tag.sectors[2][2] = key[0];
539 tag.sectors[2][3] = key[1];
540 }
541 blocknr++;
542 bCrypto = false;
543 }
544 } else {
545 *txlen = 5;
546 memcpy(tx,"\xc0",nbytes(*txlen));
547 }
548 } break;
549
550 // Received UID, crypto tag answer
551 case 32: {
552 if (!bCrypto) {
553 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;
554 uint32_t ui32uid = rx[0] | ((uint32_t)rx[1]) << 8 | ((uint32_t)rx[2]) << 16 | ((uint32_t)rx[3]) << 24;
555 cipher_state = _hitag2_init(rev64(ui64key), rev32(ui32uid), 0);
556 memset(tx,0x00,4);
557 memset(tx+4,0xff,4);
558 hitag2_cipher_transcrypt(&cipher_state,tx+4,4,0);
559 *txlen = 64;
560 bCrypto = true;
561 bAuthenticating = true;
562 } else {
563 // Check if we received answer tag (at)
564 if (bAuthenticating) {
565 bAuthenticating = false;
566 } else {
567 // Store the received block
568 memcpy(tag.sectors[blocknr],rx,4);
569 blocknr++;
570 }
571 if (blocknr > 7) {
572 DbpString("Read succesful!");
573 bSuccessful = true;
574 return false;
575 }
576 *txlen = 10;
577 tx[0] = 0xc0 | (blocknr << 3) | ((blocknr^7) >> 2);
578 tx[1] = ((blocknr^7) << 6);
579 }
580 } break;
581
582 // Unexpected response
583 default: {
584 Dbprintf("Uknown frame length: %d",rxlen);
585 return false;
586 } break;
587 }
588
589
590 if(bCrypto) {
591 // We have to return now to avoid double encryption
592 if (!bAuthenticating) {
593 hitag2_cipher_transcrypt(&cipher_state,tx,*txlen/8,*txlen%8);
594 }
595 }
596
597 return true;
598 }
599
600
601 bool hitag2_authenticate(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
602 // Reset the transmission frame length
603 *txlen = 0;
604
605 // Try to find out which command was send by selecting on length (in bits)
606 switch (rxlen) {
607 // No answer, try to resurrect
608 case 0: {
609 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
610 if (bCrypto) {
611 DbpString("Authentication failed!");
612 return false;
613 }
614 *txlen = 5;
615 memcpy(tx,"\xc0",nbytes(*txlen));
616 } break;
617
618 // Received UID, crypto tag answer
619 case 32: {
620 if (!bCrypto) {
621 *txlen = 64;
622 memcpy(tx,NrAr,8);
623 bCrypto = true;
624 } else {
625 DbpString("Authentication succesful!");
626 // We are done... for now
627 return false;
628 }
629 } break;
630
631 // Unexpected response
632 default: {
633 Dbprintf("Uknown frame length: %d",rxlen);
634 return false;
635 } break;
636 }
637
638 return true;
639 }
640
641 bool hitag2_test_auth_attempts(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
642 // Reset the transmission frame length
643 *txlen = 0;
644
645 // Try to find out which command was send by selecting on length (in bits)
646 switch (rxlen) {
647 // No answer, try to resurrect
648 case 0: {
649 // Stop if there is no answer while we are in crypto mode (after sending NrAr)
650 if (bCrypto) {
651 Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed!",NrAr[0],NrAr[1],NrAr[2],NrAr[3],NrAr[4],NrAr[5],NrAr[6],NrAr[7]);
652 bCrypto = false;
653 if ((auth_table_pos+8) == auth_table_len) {
654 return false;
655 }
656 auth_table_pos += 8;
657 memcpy(NrAr,auth_table+auth_table_pos,8);
658 }
659 *txlen = 5;
660 memcpy(tx,"\xc0",nbytes(*txlen));
661 } break;
662
663 // Received UID, crypto tag answer, or read block response
664 case 32: {
665 if (!bCrypto) {
666 *txlen = 64;
667 memcpy(tx,NrAr,8);
668 bCrypto = true;
669 } else {
670 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]);
671 bCrypto = false;
672 if ((auth_table_pos+8) == auth_table_len) {
673 return false;
674 }
675 auth_table_pos += 8;
676 memcpy(NrAr,auth_table+auth_table_pos,8);
677 }
678 } break;
679
680 default: {
681 Dbprintf("Uknown frame length: %d",rxlen);
682 return false;
683 } break;
684 }
685
686 return true;
687 }
688
689 void SnoopHitag(uint32_t type) {
690 int frame_count;
691 int response;
692 int overflow;
693 bool rising_edge;
694 bool reader_frame;
695 int lastbit;
696 bool bSkip;
697 int tag_sof;
698 byte_t rx[HITAG_FRAME_LEN];
699 size_t rxlen=0;
700
701 // Clean up trace and prepare it for storing frames
702 iso14a_set_tracing(TRUE);
703 iso14a_clear_trace();
704
705 auth_table_len = 0;
706 auth_table_pos = 0;
707 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
708
709 DbpString("Starting Hitag2 snoop");
710 LED_D_ON();
711
712 // Set up eavesdropping mode, frequency divisor which will drive the FPGA
713 // and analog mux selection.
714 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT);
715 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
716 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
717 RELAY_OFF();
718
719 // Configure output pin that is connected to the FPGA (for modulating)
720 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
721 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
722
723 // Disable modulation, we are going to eavesdrop, not modulate ;)
724 LOW(GPIO_SSC_DOUT);
725
726 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
727 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
728 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
729
730 // Disable timer during configuration
731 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
732
733 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
734 // external trigger rising edge, load RA on rising edge of TIOA.
735 uint32_t t1_channel_mode = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_BOTH | AT91C_TC_ABETRG | AT91C_TC_LDRA_BOTH;
736 AT91C_BASE_TC1->TC_CMR = t1_channel_mode;
737
738 // Enable and reset counter
739 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
740
741 // Reset the received frame, frame count and timing info
742 memset(rx,0x00,sizeof(rx));
743 frame_count = 0;
744 response = 0;
745 overflow = 0;
746 reader_frame = false;
747 lastbit = 1;
748 bSkip = true;
749 tag_sof = 4;
750
751 while(!BUTTON_PRESS()) {
752 // Watchdog hit
753 WDT_HIT();
754
755 // Receive frame, watch for at most T0*EOF periods
756 while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) {
757 // Check if rising edge in modulation is detected
758 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
759 // Retrieve the new timing values
760 int ra = (AT91C_BASE_TC1->TC_RA/T0);
761
762 // Find out if we are dealing with a rising or falling edge
763 rising_edge = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME) > 0;
764
765 // Shorter periods will only happen with reader frames
766 if (!reader_frame && rising_edge && ra < HITAG_T_TAG_CAPTURE_ONE_HALF) {
767 // Switch from tag to reader capture
768 LED_C_OFF();
769 reader_frame = true;
770 memset(rx,0x00,sizeof(rx));
771 rxlen = 0;
772 }
773
774 // Only handle if reader frame and rising edge, or tag frame and falling edge
775 if (reader_frame != rising_edge) {
776 overflow += ra;
777 continue;
778 }
779
780 // Add the buffered timing values of earlier captured edges which were skipped
781 ra += overflow;
782 overflow = 0;
783
784 if (reader_frame) {
785 LED_B_ON();
786 // Capture reader frame
787 if(ra >= HITAG_T_STOP) {
788 if (rxlen != 0) {
789 //DbpString("wierd0?");
790 }
791 // Capture the T0 periods that have passed since last communication or field drop (reset)
792 response = (ra - HITAG_T_LOW);
793 } else if(ra >= HITAG_T_1_MIN ) {
794 // '1' bit
795 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
796 rxlen++;
797 } else if(ra >= HITAG_T_0_MIN) {
798 // '0' bit
799 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
800 rxlen++;
801 } else {
802 // Ignore wierd value, is to small to mean anything
803 }
804 } else {
805 LED_C_ON();
806 // Capture tag frame (manchester decoding using only falling edges)
807 if(ra >= HITAG_T_EOF) {
808 if (rxlen != 0) {
809 //DbpString("wierd1?");
810 }
811 // Capture the T0 periods that have passed since last communication or field drop (reset)
812 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
813 response = ra-HITAG_T_TAG_HALF_PERIOD;
814 } else if(ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
815 // Manchester coding example |-_|_-|-_| (101)
816 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
817 rxlen++;
818 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
819 rxlen++;
820 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
821 // Manchester coding example |_-|...|_-|-_| (0...01)
822 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
823 rxlen++;
824 // We have to skip this half period at start and add the 'one' the second time
825 if (!bSkip) {
826 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
827 rxlen++;
828 }
829 lastbit = !lastbit;
830 bSkip = !bSkip;
831 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
832 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
833 if (tag_sof) {
834 // Ignore bits that are transmitted during SOF
835 tag_sof--;
836 } else {
837 // bit is same as last bit
838 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
839 rxlen++;
840 }
841 } else {
842 // Ignore wierd value, is to small to mean anything
843 }
844 }
845 }
846 }
847
848 // Check if frame was captured
849 if(rxlen > 0) {
850 frame_count++;
851 if (!LogTrace(rx,nbytes(rxlen),response,0,reader_frame)) {
852 DbpString("Trace full");
853 break;
854 }
855
856 // Check if we recognize a valid authentication attempt
857 if (nbytes(rxlen) == 8) {
858 // Store the authentication attempt
859 if (auth_table_len < (AUTH_TABLE_LENGTH-8)) {
860 memcpy(auth_table+auth_table_len,rx,8);
861 auth_table_len += 8;
862 }
863 }
864
865 // Reset the received frame and response timing info
866 memset(rx,0x00,sizeof(rx));
867 response = 0;
868 reader_frame = false;
869 lastbit = 1;
870 bSkip = true;
871 tag_sof = 4;
872 overflow = 0;
873
874 LED_B_OFF();
875 LED_C_OFF();
876 } else {
877 // Save the timer overflow, will be 0 when frame was received
878 overflow += (AT91C_BASE_TC1->TC_CV/T0);
879 }
880 // Reset the frame length
881 rxlen = 0;
882 // Reset the timer to restart while-loop that receives frames
883 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
884 }
885 LED_A_ON();
886 LED_B_OFF();
887 LED_C_OFF();
888 LED_D_OFF();
889 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
890 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
891 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
892 LED_A_OFF();
893
894 // Dbprintf("frame received: %d",frame_count);
895 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
896 // DbpString("All done");
897 }
898
899 void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) {
900 int frame_count;
901 int response;
902 int overflow;
903 byte_t rx[HITAG_FRAME_LEN];
904 size_t rxlen=0;
905 byte_t tx[HITAG_FRAME_LEN];
906 size_t txlen=0;
907 bool bQuitTraceFull = false;
908 bQuiet = false;
909
910 // Clean up trace and prepare it for storing frames
911 iso14a_set_tracing(TRUE);
912 iso14a_clear_trace();
913 auth_table_len = 0;
914 auth_table_pos = 0;
915 memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
916
917 DbpString("Starting Hitag2 simulation");
918 LED_D_ON();
919 hitag2_init();
920
921 if (tag_mem_supplied) {
922 DbpString("Loading hitag2 memory...");
923 memcpy((byte_t*)tag.sectors,data,48);
924 }
925
926 uint32_t block = 0;
927 for (size_t i=0; i<12; i++) {
928 for (size_t j=0; j<4; j++) {
929 block <<= 8;
930 block |= tag.sectors[i][j];
931 }
932 Dbprintf("| %d | %08x |",i,block);
933 }
934
935 // Set up simulator mode, frequency divisor which will drive the FPGA
936 // and analog mux selection.
937 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT);
938 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
939 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
940 RELAY_OFF();
941
942 // Configure output pin that is connected to the FPGA (for modulating)
943 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
944 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
945
946 // Disable modulation at default, which means release resistance
947 LOW(GPIO_SSC_DOUT);
948
949 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
950 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
951
952 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
953 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
954 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
955
956 // Disable timer during configuration
957 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
958
959 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
960 // external trigger rising edge, load RA on rising edge of TIOA.
961 AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_RISING | AT91C_TC_ABETRG | AT91C_TC_LDRA_RISING;
962
963 // Enable and reset counter
964 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
965
966 // Reset the received frame, frame count and timing info
967 memset(rx,0x00,sizeof(rx));
968 frame_count = 0;
969 response = 0;
970 overflow = 0;
971
972 while(!BUTTON_PRESS()) {
973 // Watchdog hit
974 WDT_HIT();
975
976 // Receive frame, watch for at most T0*EOF periods
977 while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) {
978 // Check if rising edge in modulation is detected
979 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
980 // Retrieve the new timing values
981 int ra = (AT91C_BASE_TC1->TC_RA/T0) + overflow;
982 overflow = 0;
983
984 // Reset timer every frame, we have to capture the last edge for timing
985 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
986
987 LED_B_ON();
988
989 // Capture reader frame
990 if(ra >= HITAG_T_STOP) {
991 if (rxlen != 0) {
992 //DbpString("wierd0?");
993 }
994 // Capture the T0 periods that have passed since last communication or field drop (reset)
995 response = (ra - HITAG_T_LOW);
996 } else if(ra >= HITAG_T_1_MIN ) {
997 // '1' bit
998 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
999 rxlen++;
1000 } else if(ra >= HITAG_T_0_MIN) {
1001 // '0' bit
1002 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1003 rxlen++;
1004 } else {
1005 // Ignore wierd value, is to small to mean anything
1006 }
1007 }
1008 }
1009
1010 // Check if frame was captured
1011 if(rxlen > 4) {
1012 frame_count++;
1013 if (!bQuiet) {
1014 if (!LogTrace(rx,nbytes(rxlen),response,0,true)) {
1015 DbpString("Trace full");
1016 if (bQuitTraceFull) {
1017 break;
1018 } else {
1019 bQuiet = true;
1020 }
1021 }
1022 }
1023
1024 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1025 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1026
1027 // Process the incoming frame (rx) and prepare the outgoing frame (tx)
1028 hitag2_handle_reader_command(rx,rxlen,tx,&txlen);
1029
1030 // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit,
1031 // not that since the clock counts since the rising edge, but T_Wait1 is
1032 // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low)
1033 // periods. The gap time T_Low varies (4..10). All timer values are in
1034 // terms of T0 units
1035 while(AT91C_BASE_TC0->TC_CV < T0*(HITAG_T_WAIT_1-HITAG_T_LOW));
1036
1037 // Send and store the tag answer (if there is any)
1038 if (txlen) {
1039 // Transmit the tag frame
1040 hitag_send_frame(tx,txlen);
1041 // Store the frame in the trace
1042 if (!bQuiet) {
1043 if (!LogTrace(tx,nbytes(txlen),0,0,false)) {
1044 DbpString("Trace full");
1045 if (bQuitTraceFull) {
1046 break;
1047 } else {
1048 bQuiet = true;
1049 }
1050 }
1051 }
1052 }
1053
1054 // Reset the received frame and response timing info
1055 memset(rx,0x00,sizeof(rx));
1056 response = 0;
1057
1058 // Enable and reset external trigger in timer for capturing future frames
1059 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1060 LED_B_OFF();
1061 }
1062 // Reset the frame length
1063 rxlen = 0;
1064 // Save the timer overflow, will be 0 when frame was received
1065 overflow += (AT91C_BASE_TC1->TC_CV/T0);
1066 // Reset the timer to restart while-loop that receives frames
1067 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
1068 }
1069 LED_B_OFF();
1070 LED_D_OFF();
1071 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1072 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1073 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1074 // Dbprintf("frame received: %d",frame_count);
1075 // Dbprintf("Authentication Attempts: %d",(auth_table_len/8));
1076 // DbpString("All done");
1077 }
1078
1079 void ReaderHitag(hitag_function htf, hitag_data* htd) {
1080 int frame_count;
1081 int response;
1082 byte_t rx[HITAG_FRAME_LEN];
1083 size_t rxlen=0;
1084 byte_t txbuf[HITAG_FRAME_LEN];
1085 byte_t* tx = txbuf;
1086 size_t txlen=0;
1087 int lastbit;
1088 bool bSkip;
1089 int reset_sof;
1090 int tag_sof;
1091 int t_wait = HITAG_T_WAIT_MAX;
1092 bool bStop;
1093 bool bQuitTraceFull = false;
1094
1095 // Reset the return status
1096 bSuccessful = false;
1097
1098 // Clean up trace and prepare it for storing frames
1099 iso14a_set_tracing(TRUE);
1100 iso14a_clear_trace();
1101 DbpString("Starting Hitag reader family");
1102
1103 // Check configuration
1104 switch(htf) {
1105 case RHT2F_PASSWORD: {
1106 Dbprintf("List identifier in password mode");
1107 memcpy(password,htd->pwd.password,4);
1108 blocknr = 0;
1109 bQuitTraceFull = false;
1110 bQuiet = false;
1111 bPwd = false;
1112 } break;
1113
1114 case RHT2F_AUTHENTICATE: {
1115 DbpString("Authenticating using nr,ar pair:");
1116 memcpy(NrAr,htd->auth.NrAr,8);
1117 Dbhexdump(8,NrAr,false);
1118 bQuiet = false;
1119 bCrypto = false;
1120 bAuthenticating = false;
1121 bQuitTraceFull = true;
1122 } break;
1123
1124 case RHT2F_CRYPTO: {
1125 DbpString("Authenticating using key:");
1126 memcpy(key,htd->crypto.key,6);
1127 Dbhexdump(6,key,false);
1128 blocknr = 0;
1129 bQuiet = false;
1130 bCrypto = false;
1131 bAuthenticating = false;
1132 bQuitTraceFull = true;
1133 } break;
1134
1135 case RHT2F_TEST_AUTH_ATTEMPTS: {
1136 Dbprintf("Testing %d authentication attempts",(auth_table_len/8));
1137 auth_table_pos = 0;
1138 memcpy(NrAr,auth_table,8);
1139 bQuitTraceFull = false;
1140 bQuiet = false;
1141 bCrypto = false;
1142 } break;
1143
1144 default: {
1145 Dbprintf("Error, unknown function: %d",htf);
1146 return;
1147 } break;
1148 }
1149
1150 LED_D_ON();
1151 hitag2_init();
1152
1153 // Configure output and enable pin that is connected to the FPGA (for modulating)
1154 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
1155 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
1156
1157 // Set fpga in edge detect with reader field, we can modulate as reader now
1158 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD);
1159
1160 // Set Frequency divisor which will drive the FPGA and analog mux selection
1161 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
1162 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
1163 RELAY_OFF();
1164
1165 // Disable modulation at default, which means enable the field
1166 LOW(GPIO_SSC_DOUT);
1167
1168 // Give it a bit of time for the resonant antenna to settle.
1169 SpinDelay(30);
1170
1171 // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering
1172 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0);
1173
1174 // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames
1175 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
1176 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
1177
1178 // Disable timer during configuration
1179 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1180
1181 // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
1182 // external trigger rising edge, load RA on falling edge of TIOA.
1183 AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_FALLING | AT91C_TC_ABETRG | AT91C_TC_LDRA_FALLING;
1184
1185 // Enable and reset counters
1186 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1187 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1188
1189 // Reset the received frame, frame count and timing info
1190 frame_count = 0;
1191 response = 0;
1192 lastbit = 1;
1193 bStop = false;
1194
1195 // Tag specific configuration settings (sof, timings, etc.)
1196 if (htf < 10){
1197 // hitagS settings
1198 reset_sof = 1;
1199 t_wait = 200;
1200 DbpString("Configured for hitagS reader");
1201 } else if (htf < 20) {
1202 // hitag1 settings
1203 reset_sof = 1;
1204 t_wait = 200;
1205 DbpString("Configured for hitag1 reader");
1206 } else if (htf < 30) {
1207 // hitag2 settings
1208 reset_sof = 4;
1209 t_wait = HITAG_T_WAIT_2;
1210 DbpString("Configured for hitag2 reader");
1211 } else {
1212 Dbprintf("Error, unknown hitag reader type: %d",htf);
1213 return;
1214 }
1215
1216 while(!bStop && !BUTTON_PRESS()) {
1217 // Watchdog hit
1218 WDT_HIT();
1219
1220 // Check if frame was captured and store it
1221 if(rxlen > 0) {
1222 frame_count++;
1223 if (!bQuiet) {
1224 if (!LogTrace(rx,nbytes(rxlen),response,0,false)) {
1225 DbpString("Trace full");
1226 if (bQuitTraceFull) {
1227 break;
1228 } else {
1229 bQuiet = true;
1230 }
1231 }
1232 }
1233 }
1234
1235 // By default reset the transmission buffer
1236 tx = txbuf;
1237 switch(htf) {
1238 case RHT2F_PASSWORD: {
1239 bStop = !hitag2_password(rx,rxlen,tx,&txlen);
1240 } break;
1241 case RHT2F_AUTHENTICATE: {
1242 bStop = !hitag2_authenticate(rx,rxlen,tx,&txlen);
1243 } break;
1244 case RHT2F_CRYPTO: {
1245 bStop = !hitag2_crypto(rx,rxlen,tx,&txlen);
1246 } break;
1247 case RHT2F_TEST_AUTH_ATTEMPTS: {
1248 bStop = !hitag2_test_auth_attempts(rx,rxlen,tx,&txlen);
1249 } break;
1250 default: {
1251 Dbprintf("Error, unknown function: %d",htf);
1252 return;
1253 } break;
1254 }
1255
1256 // Send and store the reader command
1257 // Disable timer 1 with external trigger to avoid triggers during our own modulation
1258 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1259
1260 // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting,
1261 // Since the clock counts since the last falling edge, a 'one' means that the
1262 // falling edge occured halfway the period. with respect to this falling edge,
1263 // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
1264 // All timer values are in terms of T0 units
1265 while(AT91C_BASE_TC0->TC_CV < T0*(t_wait+(HITAG_T_TAG_HALF_PERIOD*lastbit)));
1266
1267 // Transmit the reader frame
1268 hitag_reader_send_frame(tx,txlen);
1269
1270 // Enable and reset external trigger in timer for capturing future frames
1271 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
1272
1273 // Add transmitted frame to total count
1274 if(txlen > 0) {
1275 frame_count++;
1276 if (!bQuiet) {
1277 // Store the frame in the trace
1278 if (!LogTrace(tx,nbytes(txlen),HITAG_T_WAIT_2,0,true)) {
1279 if (bQuitTraceFull) {
1280 break;
1281 } else {
1282 bQuiet = true;
1283 }
1284 }
1285 }
1286 }
1287
1288 // Reset values for receiving frames
1289 memset(rx,0x00,sizeof(rx));
1290 rxlen = 0;
1291 lastbit = 1;
1292 bSkip = true;
1293 tag_sof = reset_sof;
1294 response = 0;
1295
1296 // Receive frame, watch for at most T0*EOF periods
1297 while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_WAIT_MAX) {
1298 // Check if falling edge in tag modulation is detected
1299 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
1300 // Retrieve the new timing values
1301 int ra = (AT91C_BASE_TC1->TC_RA/T0);
1302
1303 // Reset timer every frame, we have to capture the last edge for timing
1304 AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
1305
1306 LED_B_ON();
1307
1308 // Capture tag frame (manchester decoding using only falling edges)
1309 if(ra >= HITAG_T_EOF) {
1310 if (rxlen != 0) {
1311 //DbpString("wierd1?");
1312 }
1313 // Capture the T0 periods that have passed since last communication or field drop (reset)
1314 // We always recieve a 'one' first, which has the falling edge after a half period |-_|
1315 response = ra-HITAG_T_TAG_HALF_PERIOD;
1316 } else if(ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
1317 // Manchester coding example |-_|_-|-_| (101)
1318 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1319 rxlen++;
1320 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1321 rxlen++;
1322 } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
1323 // Manchester coding example |_-|...|_-|-_| (0...01)
1324 rx[rxlen / 8] |= 0 << (7-(rxlen%8));
1325 rxlen++;
1326 // We have to skip this half period at start and add the 'one' the second time
1327 if (!bSkip) {
1328 rx[rxlen / 8] |= 1 << (7-(rxlen%8));
1329 rxlen++;
1330 }
1331 lastbit = !lastbit;
1332 bSkip = !bSkip;
1333 } else if(ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
1334 // Manchester coding example |_-|_-| (00) or |-_|-_| (11)
1335 if (tag_sof) {
1336 // Ignore bits that are transmitted during SOF
1337 tag_sof--;
1338 } else {
1339 // bit is same as last bit
1340 rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
1341 rxlen++;
1342 }
1343 } else {
1344 // Ignore wierd value, is to small to mean anything
1345 }
1346 }
1347
1348 // We can break this loop if we received the last bit from a frame
1349 if (AT91C_BASE_TC1->TC_CV > T0*HITAG_T_EOF) {
1350 if (rxlen>0) break;
1351 }
1352 }
1353 }
1354 LED_B_OFF();
1355 LED_D_OFF();
1356 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
1357 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
1358 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1359 Dbprintf("frame received: %d",frame_count);
1360 DbpString("All done");
1361 cmd_send(CMD_ACK,bSuccessful,0,0,(byte_t*)tag.sectors,48);
1362 }
Impressum, Datenschutz