]> cvs.zerfleddert.de Git - proxmark3-svn/blame_incremental - client/cmdlfem4x.c
FIXED: Merged all Holimans code-review issues which should fix a lot of memoryleaks.
[proxmark3-svn] / client / cmdlfem4x.c
... / ...
CommitLineData
1 //-----------------------------------------------------------------------------
2// Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
3//
4// This code is licensed to you under the terms of the GNU GPL, version 2 or,
5// at your option, any later version. See the LICENSE.txt file for the text of
6// the license.
7//-----------------------------------------------------------------------------
8// Low frequency EM4x commands
9//-----------------------------------------------------------------------------
10
11#include <stdio.h>
12#include <string.h>
13#include <inttypes.h>
14#include "proxmark3.h"
15#include "ui.h"
16#include "graph.h"
17#include "cmdmain.h"
18#include "cmdparser.h"
19#include "cmddata.h"
20#include "cmdlf.h"
21#include "cmdlfem4x.h"
22#include "util.h"
23#include "data.h"
24#define LF_TRACE_BUFF_SIZE 12000
25#define LF_BITSSTREAM_LEN 1000
26
27char *global_em410xId;
28
29static int CmdHelp(const char *Cmd);
30
31/* Read the ID of an EM410x tag.
32 * Format:
33 * 1111 1111 1 <-- standard non-repeatable header
34 * XXXX [row parity bit] <-- 10 rows of 5 bits for our 40 bit tag ID
35 * ....
36 * CCCC <-- each bit here is parity for the 10 bits above in corresponding column
37 * 0 <-- stop bit, end of tag
38 */
39int CmdEM410xRead(const char *Cmd)
40{
41 int i, j, clock, header, rows, bit, hithigh, hitlow, first, bit2idx, high, low;
42 int parity[4];
43 char id[11];
44 char id2[11];
45 int retested = 0;
46 uint8_t BitStream[MAX_GRAPH_TRACE_LEN];
47 high = low = 0;
48
49 /* Detect high and lows and clock */
50 for (i = 0; i < GraphTraceLen; i++)
51 {
52 if (GraphBuffer[i] > high)
53 high = GraphBuffer[i];
54 else if (GraphBuffer[i] < low)
55 low = GraphBuffer[i];
56 }
57
58 /* get clock */
59 clock = GetClock(Cmd, high, 0);
60
61
62 /* parity for our 4 columns */
63 parity[0] = parity[1] = parity[2] = parity[3] = 0;
64 header = rows = 0;
65
66 /* manchester demodulate */
67 bit = bit2idx = 0;
68 for (i = 0; i < (int)(GraphTraceLen / clock); i++)
69 {
70 hithigh = 0;
71 hitlow = 0;
72 first = 1;
73
74 /* Find out if we hit both high and low peaks */
75 for (j = 0; j < clock; j++)
76 {
77 if (GraphBuffer[(i * clock) + j] == high)
78 hithigh = 1;
79 else if (GraphBuffer[(i * clock) + j] == low)
80 hitlow = 1;
81
82 /* it doesn't count if it's the first part of our read
83 because it's really just trailing from the last sequence */
84 if (first && (hithigh || hitlow))
85 hithigh = hitlow = 0;
86 else
87 first = 0;
88
89 if (hithigh && hitlow)
90 break;
91 }
92
93 /* If we didn't hit both high and low peaks, we had a bit transition */
94 if (!hithigh || !hitlow)
95 bit ^= 1;
96
97 BitStream[bit2idx++] = bit;
98 }
99
100retest:
101 /* We go till 5 before the graph ends because we'll get that far below */
102 for (i = 1; i < bit2idx - 5; i++)
103 {
104 /* Step 2: We have our header but need our tag ID */
105 if (header == 9 && rows < 10)
106 {
107 /* Confirm parity is correct */
108 if ((BitStream[i] ^ BitStream[i+1] ^ BitStream[i+2] ^ BitStream[i+3]) == BitStream[i+4])
109 {
110 /* Read another byte! */
111 sprintf(id+rows, "%x", (8 * BitStream[i]) + (4 * BitStream[i+1]) + (2 * BitStream[i+2]) + (1 * BitStream[i+3]));
112 sprintf(id2+rows, "%x", (8 * BitStream[i+3]) + (4 * BitStream[i+2]) + (2 * BitStream[i+1]) + (1 * BitStream[i]));
113 rows++;
114
115 /* Keep parity info */
116 parity[0] ^= BitStream[i];
117 parity[1] ^= BitStream[i+1];
118 parity[2] ^= BitStream[i+2];
119 parity[3] ^= BitStream[i+3];
120
121 /* Move 4 bits ahead */
122 i += 4;
123 }
124
125 /* Damn, something wrong! reset */
126 else
127 {
128 PrintAndLog("Thought we had a valid tag but failed at word %d (i=%d)", rows + 1, i);
129
130 /* Start back rows * 5 + 9 header bits, -1 to not start at same place */
131 i -= 9 + (5 * rows) - 5;
132
133 rows = header = 0;
134 }
135 }
136
137 /* Step 3: Got our 40 bits! confirm column parity */
138 else if (rows == 10)
139 {
140 /* We need to make sure our 4 bits of parity are correct and we have a stop bit */
141 if (BitStream[i] == parity[0] && BitStream[i+1] == parity[1] &&
142 BitStream[i+2] == parity[2] && BitStream[i+3] == parity[3] &&
143 BitStream[i+4] == 0)
144 {
145 /* Sweet! */
146 PrintAndLog("EM410x Tag ID: %s", id);
147 PrintAndLog("Unique Tag ID: %s", id2);
148
149 global_em410xId = id;
150
151 /* Stop any loops */
152 return 1;
153 }
154
155 /* Crap! Incorrect parity or no stop bit, start all over */
156 else
157 {
158 rows = header = 0;
159
160 /* Go back 59 bits (9 header bits + 10 rows at 4+1 parity) */
161 i -= 59;
162 }
163 }
164
165 /* Step 1: get our header */
166 else if (header < 9)
167 {
168 /* Need 9 consecutive 1's */
169 if (BitStream[i] == 1)
170 header++;
171
172 /* We don't have a header, not enough consecutive 1 bits */
173 else
174 header = 0;
175 }
176 }
177
178 /* if we've already retested after flipping bits, return */
179 if (retested++){
180 return 0;
181 }
182
183 /* if this didn't work, try flipping bits */
184 for (i = 0; i < bit2idx; i++)
185 BitStream[i] ^= 1;
186
187 goto retest;
188}
189
190/* emulate an EM410X tag
191 * Format:
192 * 1111 1111 1 <-- standard non-repeatable header
193 * XXXX [row parity bit] <-- 10 rows of 5 bits for our 40 bit tag ID
194 * ....
195 * CCCC <-- each bit here is parity for the 10 bits above in corresponding column
196 * 0 <-- stop bit, end of tag
197 */
198int CmdEM410xSim(const char *Cmd)
199{
200 int i, n, j, h, binary[4], parity[4];
201
202 char cmdp = param_getchar(Cmd, 0);
203 uint8_t uid[5] = {0x00};
204
205 if (cmdp == 'h' || cmdp == 'H') {
206 PrintAndLog("Usage: lf em4x sim <UID>");
207 PrintAndLog("");
208 PrintAndLog(" sample: lf em4x sim 0F0368568B");
209 return 0;
210 }
211
212 if (param_gethex(Cmd, 0, uid, 10)) {
213 PrintAndLog("UID must include 10 HEX symbols");
214 return 0;
215 }
216
217 PrintAndLog("Starting simulating with UID %02X %02X %02X %02X %02X", uid[0],uid[1],uid[2],uid[3],uid[4]);
218
219
220 /* clock is 64 in EM410x tags */
221 int clock = 64;
222
223 /* clear our graph */
224 ClearGraph(1);
225
226 /* write it out a few times */
227 for (h = 0; h < 4; h++)
228 {
229 /* write 9 start bits */
230 for (i = 0; i < 9; i++)
231 AppendGraph(0, clock, 1);
232
233 /* for each hex char */
234 parity[0] = parity[1] = parity[2] = parity[3] = 0;
235 for (i = 0; i < 10; i++)
236 {
237 /* read each hex char */
238 sscanf(&Cmd[i], "%1x", &n);
239 for (j = 3; j >= 0; j--, n/= 2)
240 binary[j] = n % 2;
241
242 /* append each bit */
243 AppendGraph(0, clock, binary[0]);
244 AppendGraph(0, clock, binary[1]);
245 AppendGraph(0, clock, binary[2]);
246 AppendGraph(0, clock, binary[3]);
247
248 /* append parity bit */
249 AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]);
250
251 /* keep track of column parity */
252 parity[0] ^= binary[0];
253 parity[1] ^= binary[1];
254 parity[2] ^= binary[2];
255 parity[3] ^= binary[3];
256 }
257
258 /* parity columns */
259 AppendGraph(0, clock, parity[0]);
260 AppendGraph(0, clock, parity[1]);
261 AppendGraph(0, clock, parity[2]);
262 AppendGraph(0, clock, parity[3]);
263
264 /* stop bit */
265 AppendGraph(0, clock, 0);
266 }
267
268 /* modulate that biatch */
269 CmdManchesterMod("64");
270
271 /* booyah! */
272 RepaintGraphWindow();
273
274 CmdLFSim("");
275 return 0;
276}
277
278/* Function is equivalent of lf read + data samples + em410xread
279 * looped until an EM410x tag is detected
280 *
281 * Why is CmdSamples("16000")?
282 * TBD: Auto-grow sample size based on detected sample rate. IE: If the
283 * rate gets lower, then grow the number of samples
284 * Changed by martin, 4000 x 4 = 16000,
285 * see http://www.proxmark.org/forum/viewtopic.php?pid=7235#p7235
286
287*/
288int CmdEM410xWatch(const char *Cmd)
289{
290 int read_h = (*Cmd == 'h');
291 do
292 {
293 if (ukbhit()) {
294 printf("\naborted via keyboard!\n");
295 break;
296 }
297
298 CmdLFRead(read_h ? "h" : "");
299 CmdSamples("16000");
300
301 } while (
302 !CmdEM410xRead("")
303 );
304 return 0;
305}
306
307int CmdEM410xWatchnSpoof(const char *Cmd)
308{
309 CmdEM410xWatch(Cmd);
310 PrintAndLog("# Replaying : %s",global_em410xId);
311 CmdEM410xSim(global_em410xId);
312 return 0;
313}
314
315/* Read the transmitted data of an EM4x50 tag
316 * Format:
317 *
318 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
319 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
320 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
321 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
322 * CCCCCCCC <- column parity bits
323 * 0 <- stop bit
324 * LW <- Listen Window
325 *
326 * This pattern repeats for every block of data being transmitted.
327 * Transmission starts with two Listen Windows (LW - a modulated
328 * pattern of 320 cycles each (32/32/128/64/64)).
329 *
330 * Note that this data may or may not be the UID. It is whatever data
331 * is stored in the blocks defined in the control word First and Last
332 * Word Read values. UID is stored in block 32.
333 */
334int CmdEM4x50Read(const char *Cmd)
335{
336 int i, j, startblock, skip, block, start, end, low, high;
337 bool complete= false;
338 int tmpbuff[MAX_GRAPH_TRACE_LEN / 64];
339 char tmp[6];
340
341 high= low= 0;
342 memset(tmpbuff, 0, MAX_GRAPH_TRACE_LEN / 64);
343
344 /* first get high and low values */
345 for (i = 0; i < GraphTraceLen; i++)
346 {
347 if (GraphBuffer[i] > high)
348 high = GraphBuffer[i];
349 else if (GraphBuffer[i] < low)
350 low = GraphBuffer[i];
351 }
352
353 /* populate a buffer with pulse lengths */
354 i= 0;
355 j= 0;
356 while (i < GraphTraceLen)
357 {
358 // measure from low to low
359 while ((GraphBuffer[i] > low) && (i<GraphTraceLen))
360 ++i;
361 start= i;
362 while ((GraphBuffer[i] < high) && (i<GraphTraceLen))
363 ++i;
364 while ((GraphBuffer[i] > low) && (i<GraphTraceLen))
365 ++i;
366 if (j>=(MAX_GRAPH_TRACE_LEN/64)) {
367 break;
368 }
369 tmpbuff[j++]= i - start;
370 }
371
372 /* look for data start - should be 2 pairs of LW (pulses of 192,128) */
373 start= -1;
374 skip= 0;
375 for (i= 0; i < j - 4 ; ++i)
376 {
377 skip += tmpbuff[i];
378 if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194)
379 if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130)
380 if (tmpbuff[i+2] >= 190 && tmpbuff[i+2] <= 194)
381 if (tmpbuff[i+3] >= 126 && tmpbuff[i+3] <= 130)
382 {
383 start= i + 3;
384 break;
385 }
386 }
387 startblock= i + 3;
388
389 /* skip over the remainder of the LW */
390 skip += tmpbuff[i+1]+tmpbuff[i+2];
391 while (skip < MAX_GRAPH_TRACE_LEN && GraphBuffer[skip] > low)
392 ++skip;
393 skip += 8;
394
395 /* now do it again to find the end */
396 end= start;
397 for (i += 3; i < j - 4 ; ++i)
398 {
399 end += tmpbuff[i];
400 if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194)
401 if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130)
402 if (tmpbuff[i+2] >= 190 && tmpbuff[i+2] <= 194)
403 if (tmpbuff[i+3] >= 126 && tmpbuff[i+3] <= 130)
404 {
405 complete= true;
406 break;
407 }
408 }
409
410 if (start >= 0)
411 PrintAndLog("Found data at sample: %i",skip);
412 else
413 {
414 PrintAndLog("No data found!");
415 PrintAndLog("Try again with more samples.");
416 return 0;
417 }
418
419 if (!complete)
420 {
421 PrintAndLog("*** Warning!");
422 PrintAndLog("Partial data - no end found!");
423 PrintAndLog("Try again with more samples.");
424 }
425
426 /* get rid of leading crap */
427 sprintf(tmp,"%i",skip);
428 CmdLtrim(tmp);
429
430 /* now work through remaining buffer printing out data blocks */
431 block= 0;
432 i= startblock;
433 while (block < 6)
434 {
435 PrintAndLog("Block %i:", block);
436 // mandemod routine needs to be split so we can call it for data
437 // just print for now for debugging
438 CmdManchesterDemod("i 64");
439 skip= 0;
440 /* look for LW before start of next block */
441 for ( ; i < j - 4 ; ++i)
442 {
443 skip += tmpbuff[i];
444 if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194)
445 if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130)
446 break;
447 }
448 while (GraphBuffer[skip] > low)
449 ++skip;
450 skip += 8;
451 sprintf(tmp,"%i",skip);
452 CmdLtrim(tmp);
453 start += skip;
454 block++;
455 }
456 return 0;
457}
458
459int CmdEM410xWrite(const char *Cmd)
460{
461 uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value
462 int card = 0xFF; // invalid card value
463 unsigned int clock = 0; // invalid clock value
464
465 sscanf(Cmd, "%" PRIx64 " %d %d", &id, &card, &clock);
466
467 // Check ID
468 if (id == 0xFFFFFFFFFFFFFFFF) {
469 PrintAndLog("Error! ID is required.\n");
470 return 0;
471 }
472 if (id >= 0x10000000000) {
473 PrintAndLog("Error! Given EM410x ID is longer than 40 bits.\n");
474 return 0;
475 }
476
477 // Check Card
478 if (card == 0xFF) {
479 PrintAndLog("Error! Card type required.\n");
480 return 0;
481 }
482 if (card < 0) {
483 PrintAndLog("Error! Bad card type selected.\n");
484 return 0;
485 }
486
487 // Check Clock
488 if (card == 1)
489 {
490 // Default: 64
491 if (clock == 0)
492 clock = 64;
493
494 // Allowed clock rates: 16, 32 and 64
495 if ((clock != 16) && (clock != 32) && (clock != 64)) {
496 PrintAndLog("Error! Clock rate %d not valid. Supported clock rates are 16, 32 and 64.\n", clock);
497 return 0;
498 }
499 }
500 else if (clock != 0)
501 {
502 PrintAndLog("Error! Clock rate is only supported on T55x7 tags.\n");
503 return 0;
504 }
505
506 if (card == 1) {
507 PrintAndLog("Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock);
508 // NOTE: We really should pass the clock in as a separate argument, but to
509 // provide for backwards-compatibility for older firmware, and to avoid
510 // having to add another argument to CMD_EM410X_WRITE_TAG, we just store
511 // the clock rate in bits 8-15 of the card value
512 card = (card & 0xFF) | (((uint64_t)clock << 8) & 0xFF00);
513 }
514 else if (card == 0)
515 PrintAndLog("Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock);
516 else {
517 PrintAndLog("Error! Bad card type selected.\n");
518 return 0;
519 }
520
521 UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}};
522 SendCommand(&c);
523
524 return 0;
525}
526
527int CmdReadWord(const char *Cmd)
528{
529 int Word = -1; //default to invalid word
530 UsbCommand c;
531
532 sscanf(Cmd, "%d", &Word);
533
534 if ( (Word > 15) | (Word < 0) ) {
535 PrintAndLog("Word must be between 0 and 15");
536 return 1;
537 }
538
539 PrintAndLog("Reading word %d", Word);
540
541 c.cmd = CMD_EM4X_READ_WORD;
542 c.d.asBytes[0] = 0x0; //Normal mode
543 c.arg[0] = 0;
544 c.arg[1] = Word;
545 c.arg[2] = 0;
546 SendCommand(&c);
547 WaitForResponse(CMD_ACK, NULL);
548
549 uint8_t data[LF_TRACE_BUFF_SIZE] = {0x00};
550
551 GetFromBigBuf(data,LF_TRACE_BUFF_SIZE,3560); //3560 -- should be offset..
552 WaitForResponseTimeout(CMD_ACK,NULL, 1500);
553
554 for (int j = 0; j < LF_TRACE_BUFF_SIZE; j++) {
555 GraphBuffer[j] = ((int)data[j]);
556 }
557 GraphTraceLen = LF_TRACE_BUFF_SIZE;
558
559 uint8_t bits[LF_BITSSTREAM_LEN] = {0x00};
560 uint8_t * bitstream = bits;
561 manchester_decode(GraphBuffer, LF_TRACE_BUFF_SIZE, bitstream,LF_BITSSTREAM_LEN);
562 RepaintGraphWindow();
563 return 0;
564}
565
566int CmdReadWordPWD(const char *Cmd)
567{
568 int Word = -1; //default to invalid word
569 int Password = 0xFFFFFFFF; //default to blank password
570 UsbCommand c;
571
572 sscanf(Cmd, "%d %x", &Word, &Password);
573
574 if ( (Word > 15) | (Word < 0) ) {
575 PrintAndLog("Word must be between 0 and 15");
576 return 1;
577 }
578
579 PrintAndLog("Reading word %d with password %08X", Word, Password);
580
581 c.cmd = CMD_EM4X_READ_WORD;
582 c.d.asBytes[0] = 0x1; //Password mode
583 c.arg[0] = 0;
584 c.arg[1] = Word;
585 c.arg[2] = Password;
586 SendCommand(&c);
587 WaitForResponse(CMD_ACK, NULL);
588
589 uint8_t data[LF_TRACE_BUFF_SIZE] = {0x00};
590
591 GetFromBigBuf(data,LF_TRACE_BUFF_SIZE,3560); //3560 -- should be offset..
592 WaitForResponseTimeout(CMD_ACK,NULL, 1500);
593
594 for (int j = 0; j < LF_TRACE_BUFF_SIZE; j++) {
595 GraphBuffer[j] = ((int)data[j]);
596 }
597 GraphTraceLen = LF_TRACE_BUFF_SIZE;
598
599 uint8_t bits[LF_BITSSTREAM_LEN] = {0x00};
600 uint8_t * bitstream = bits;
601 manchester_decode(GraphBuffer, LF_TRACE_BUFF_SIZE, bitstream, LF_BITSSTREAM_LEN);
602 RepaintGraphWindow();
603 return 0;
604}
605
606int CmdWriteWord(const char *Cmd)
607{
608 int Word = 16; //default to invalid block
609 int Data = 0xFFFFFFFF; //default to blank data
610 UsbCommand c;
611
612 sscanf(Cmd, "%x %d", &Data, &Word);
613
614 if (Word > 15) {
615 PrintAndLog("Word must be between 0 and 15");
616 return 1;
617 }
618
619 PrintAndLog("Writing word %d with data %08X", Word, Data);
620
621 c.cmd = CMD_EM4X_WRITE_WORD;
622 c.d.asBytes[0] = 0x0; //Normal mode
623 c.arg[0] = Data;
624 c.arg[1] = Word;
625 c.arg[2] = 0;
626 SendCommand(&c);
627 return 0;
628}
629
630int CmdWriteWordPWD(const char *Cmd)
631{
632 int Word = 16; //default to invalid word
633 int Data = 0xFFFFFFFF; //default to blank data
634 int Password = 0xFFFFFFFF; //default to blank password
635 UsbCommand c;
636
637 sscanf(Cmd, "%x %d %x", &Data, &Word, &Password);
638
639 if (Word > 15) {
640 PrintAndLog("Word must be between 0 and 15");
641 return 1;
642 }
643
644 PrintAndLog("Writing word %d with data %08X and password %08X", Word, Data, Password);
645
646 c.cmd = CMD_EM4X_WRITE_WORD;
647 c.d.asBytes[0] = 0x1; //Password mode
648 c.arg[0] = Data;
649 c.arg[1] = Word;
650 c.arg[2] = Password;
651 SendCommand(&c);
652 return 0;
653}
654
655static command_t CommandTable[] =
656{
657 {"help", CmdHelp, 1, "This help"},
658 {"410xread", CmdEM410xRead, 1, "[clock rate] -- Extract ID from EM410x tag"},
659 {"410xsim", CmdEM410xSim, 0, "<UID> -- Simulate EM410x tag"},
660 {"410xwatch", CmdEM410xWatch, 0, "['h'] -- Watches for EM410x 125/134 kHz tags (option 'h' for 134)"},
661 {"410xspoof", CmdEM410xWatchnSpoof, 0, "['h'] --- Watches for EM410x 125/134 kHz tags, and replays them. (option 'h' for 134)" },
662 {"410xwrite", CmdEM410xWrite, 1, "<UID> <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"},
663 {"4x50read", CmdEM4x50Read, 1, "Extract data from EM4x50 tag"},
664 {"rd", CmdReadWord, 1, "<Word 1-15> -- Read EM4xxx word data"},
665 {"rdpwd", CmdReadWordPWD, 1, "<Word 1-15> <Password> -- Read EM4xxx word data in password mode "},
666 {"wr", CmdWriteWord, 1, "<Data> <Word 1-15> -- Write EM4xxx word data"},
667 {"wrpwd", CmdWriteWordPWD, 1, "<Data> <Word 1-15> <Password> -- Write EM4xxx word data in password mode"},
668 {NULL, NULL, 0, NULL}
669};
670
671int CmdLFEM4X(const char *Cmd)
672{
673 CmdsParse(CommandTable, Cmd);
674 return 0;
675}
676
677int CmdHelp(const char *Cmd)
678{
679 CmdsHelp(CommandTable);
680 return 0;
681}
Impressum, Datenschutz