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