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