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