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