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