]> git.zerfleddert.de Git - proxmark3-svn/blob - client/cmdlfem4x.c
ADD: @piwi's fixes to "hf snoop" where it empties the bigbuffer before snooping.
[proxmark3-svn] / client / cmdlfem4x.c
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 "util.h"
17 #include "graph.h"
18 #include "cmdparser.h"
19 #include "cmddata.h"
20 #include "cmdlf.h"
21 #include "cmdlfem4x.h"
22 #include "lfdemod.h"
23
24 #define llx PRIx64
25
26 char *global_em410xId;
27
28 static int CmdHelp(const char *Cmd);
29
30 int CmdEMdemodASK(const char *Cmd)
31 {
32 char cmdp = param_getchar(Cmd, 0);
33 int findone = (cmdp == '1') ? 1 : 0;
34 UsbCommand c={CMD_EM410X_DEMOD};
35 c.arg[0]=findone;
36 SendCommand(&c);
37 return 0;
38 }
39
40 /* Read the ID of an EM410x tag.
41 * Format:
42 * 1111 1111 1 <-- standard non-repeatable header
43 * XXXX [row parity bit] <-- 10 rows of 5 bits for our 40 bit tag ID
44 * ....
45 * CCCC <-- each bit here is parity for the 10 bits above in corresponding column
46 * 0 <-- stop bit, end of tag
47 */
48 int CmdEM410xRead(const char *Cmd)
49 {
50 uint32_t hi=0;
51 uint64_t lo=0;
52
53 if(!AskEm410xDemod("", &hi, &lo, false)) return 0;
54 PrintAndLog("EM410x pattern found: ");
55 printEM410x(hi, lo);
56 if (hi){
57 PrintAndLog ("EM410x XL pattern found");
58 return 0;
59 }
60 char id[12] = {0x00};
61 sprintf(id, "%010llx",lo);
62
63 global_em410xId = id;
64 return 1;
65 }
66
67 // emulate an EM410X tag
68 int CmdEM410xSim(const char *Cmd)
69 {
70 int i, n, j, binary[4], parity[4];
71
72 char cmdp = param_getchar(Cmd, 0);
73 uint8_t uid[5] = {0x00};
74
75 if (cmdp == 'h' || cmdp == 'H') {
76 PrintAndLog("Usage: lf em4x em410xsim <UID>");
77 PrintAndLog("");
78 PrintAndLog(" sample: lf em4x em410xsim 0F0368568B");
79 return 0;
80 }
81
82 if (param_gethex(Cmd, 0, uid, 10)) {
83 PrintAndLog("UID must include 10 HEX symbols");
84 return 0;
85 }
86
87 PrintAndLog("Starting simulating UID %02X%02X%02X%02X%02X", uid[0],uid[1],uid[2],uid[3],uid[4]);
88 PrintAndLog("Press pm3-button to about simulation");
89
90 /* clock is 64 in EM410x tags */
91 int clock = 64;
92
93 /* clear our graph */
94 ClearGraph(0);
95
96 /* write 9 start bits */
97 for (i = 0; i < 9; i++)
98 AppendGraph(0, clock, 1);
99
100 /* for each hex char */
101 parity[0] = parity[1] = parity[2] = parity[3] = 0;
102 for (i = 0; i < 10; i++)
103 {
104 /* read each hex char */
105 sscanf(&Cmd[i], "%1x", &n);
106 for (j = 3; j >= 0; j--, n/= 2)
107 binary[j] = n % 2;
108
109 /* append each bit */
110 AppendGraph(0, clock, binary[0]);
111 AppendGraph(0, clock, binary[1]);
112 AppendGraph(0, clock, binary[2]);
113 AppendGraph(0, clock, binary[3]);
114
115 /* append parity bit */
116 AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]);
117
118 /* keep track of column parity */
119 parity[0] ^= binary[0];
120 parity[1] ^= binary[1];
121 parity[2] ^= binary[2];
122 parity[3] ^= binary[3];
123 }
124
125 /* parity columns */
126 AppendGraph(0, clock, parity[0]);
127 AppendGraph(0, clock, parity[1]);
128 AppendGraph(0, clock, parity[2]);
129 AppendGraph(0, clock, parity[3]);
130
131 /* stop bit */
132 AppendGraph(1, clock, 0);
133
134 CmdLFSim("0"); //240 start_gap.
135 return 0;
136 }
137
138 /* Function is equivalent of lf read + data samples + em410xread
139 * looped until an EM410x tag is detected
140 *
141 * Why is CmdSamples("16000")?
142 * TBD: Auto-grow sample size based on detected sample rate. IE: If the
143 * rate gets lower, then grow the number of samples
144 * Changed by martin, 4000 x 4 = 16000,
145 * see http://www.proxmark.org/forum/viewtopic.php?pid=7235#p7235
146 */
147 int CmdEM410xWatch(const char *Cmd)
148 {
149 do {
150 if (ukbhit()) {
151 printf("\naborted via keyboard!\n");
152 break;
153 }
154
155 CmdLFRead("s");
156 getSamples("8201",true); //capture enough to get 2 complete preambles (4096*2+9)
157 } while (!CmdEM410xRead(""));
158
159 return 0;
160 }
161
162 //currently only supports manchester modulations
163 int CmdEM410xWatchnSpoof(const char *Cmd)
164 {
165 CmdEM410xWatch(Cmd);
166 PrintAndLog("# Replaying captured ID: %s",global_em410xId);
167 CmdLFaskSim("");
168 return 0;
169 }
170
171 int CmdEM410xWrite(const char *Cmd)
172 {
173 uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value
174 int card = 0xFF; // invalid card value
175 unsigned int clock = 0; // invalid clock value
176
177 sscanf(Cmd, "%" PRIx64 " %d %d", &id, &card, &clock);
178
179 // Check ID
180 if (id == 0xFFFFFFFFFFFFFFFF) {
181 PrintAndLog("Error! ID is required.\n");
182 return 0;
183 }
184 if (id >= 0x10000000000) {
185 PrintAndLog("Error! Given EM410x ID is longer than 40 bits.\n");
186 return 0;
187 }
188
189 // Check Card
190 if (card == 0xFF) {
191 PrintAndLog("Error! Card type required.\n");
192 return 0;
193 }
194 if (card < 0) {
195 PrintAndLog("Error! Bad card type selected.\n");
196 return 0;
197 }
198
199 // Check Clock
200 if (card == 1)
201 {
202 // Default: 64
203 if (clock == 0)
204 clock = 64;
205
206 // Allowed clock rates: 16, 32 and 64
207 if ((clock != 16) && (clock != 32) && (clock != 64)) {
208 PrintAndLog("Error! Clock rate %d not valid. Supported clock rates are 16, 32 and 64.\n", clock);
209 return 0;
210 }
211 }
212 else if (clock != 0)
213 {
214 PrintAndLog("Error! Clock rate is only supported on T55x7 tags.\n");
215 return 0;
216 }
217
218 if (card == 1) {
219 PrintAndLog("Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock);
220 // NOTE: We really should pass the clock in as a separate argument, but to
221 // provide for backwards-compatibility for older firmware, and to avoid
222 // having to add another argument to CMD_EM410X_WRITE_TAG, we just store
223 // the clock rate in bits 8-15 of the card value
224 card = (card & 0xFF) | (((uint64_t)clock << 8) & 0xFF00);
225 }
226 else if (card == 0)
227 PrintAndLog("Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock);
228 else {
229 PrintAndLog("Error! Bad card type selected.\n");
230 return 0;
231 }
232
233 UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}};
234 SendCommand(&c);
235 return 0;
236 }
237
238 bool EM_EndParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType)
239 {
240 if (rows*cols>size) return false;
241 uint8_t colP=0;
242 //assume last col is a parity and do not test
243 for (uint8_t colNum = 0; colNum < cols-1; colNum++) {
244 for (uint8_t rowNum = 0; rowNum < rows; rowNum++) {
245 colP ^= BitStream[(rowNum*cols)+colNum];
246 }
247 if (colP != pType) return false;
248 }
249 return true;
250 }
251
252 bool EM_ByteParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType)
253 {
254 if (rows*cols>size) return false;
255 uint8_t rowP=0;
256 //assume last row is a parity row and do not test
257 for (uint8_t rowNum = 0; rowNum < rows-1; rowNum++) {
258 for (uint8_t colNum = 0; colNum < cols; colNum++) {
259 rowP ^= BitStream[(rowNum*cols)+colNum];
260 }
261 if (rowP != pType) return false;
262 }
263 return true;
264 }
265
266 uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool pTest)
267 {
268 if (size<45) return 0;
269 uint32_t code = bytebits_to_byte(BitStream,8);
270 code = code<<8 | bytebits_to_byte(BitStream+9,8);
271 code = code<<8 | bytebits_to_byte(BitStream+18,8);
272 code = code<<8 | bytebits_to_byte(BitStream+27,8);
273 if (verbose || g_debugMode){
274 for (uint8_t i = 0; i<5; i++){
275 if (i == 4) PrintAndLog(""); //parity byte spacer
276 PrintAndLog("%d%d%d%d%d%d%d%d %d -> 0x%02x",
277 BitStream[i*9],
278 BitStream[i*9+1],
279 BitStream[i*9+2],
280 BitStream[i*9+3],
281 BitStream[i*9+4],
282 BitStream[i*9+5],
283 BitStream[i*9+6],
284 BitStream[i*9+7],
285 BitStream[i*9+8],
286 bytebits_to_byte(BitStream+i*9,8)
287 );
288 }
289 if (pTest)
290 PrintAndLog("Parity Passed");
291 else
292 PrintAndLog("Parity Failed");
293 }
294 return code;
295 }
296 /* Read the transmitted data of an EM4x50 tag
297 * Format:
298 *
299 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
300 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
301 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
302 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
303 * CCCCCCCC <- column parity bits
304 * 0 <- stop bit
305 * LW <- Listen Window
306 *
307 * This pattern repeats for every block of data being transmitted.
308 * Transmission starts with two Listen Windows (LW - a modulated
309 * pattern of 320 cycles each (32/32/128/64/64)).
310 *
311 * Note that this data may or may not be the UID. It is whatever data
312 * is stored in the blocks defined in the control word First and Last
313 * Word Read values. UID is stored in block 32.
314 */
315 //completed by Marshmellow
316 int EM4x50Read(const char *Cmd, bool verbose)
317 {
318 uint8_t fndClk[] = {8,16,32,40,50,64,128};
319 int clk = 0;
320 int invert = 0;
321 int tol = 0;
322 int i, j, startblock, skip, block, start, end, low, high, minClk;
323 bool complete = false;
324 int tmpbuff[MAX_GRAPH_TRACE_LEN / 64];
325 uint32_t Code[6];
326 char tmp[6];
327 char tmp2[20];
328 int phaseoff;
329 high = low = 0;
330 memset(tmpbuff, 0, MAX_GRAPH_TRACE_LEN / 64);
331
332 // get user entry if any
333 sscanf(Cmd, "%i %i", &clk, &invert);
334
335 // save GraphBuffer - to restore it later
336 save_restoreGB(1);
337
338 // first get high and low values
339 for (i = 0; i < GraphTraceLen; i++) {
340 if (GraphBuffer[i] > high)
341 high = GraphBuffer[i];
342 else if (GraphBuffer[i] < low)
343 low = GraphBuffer[i];
344 }
345
346 i = 0;
347 j = 0;
348 minClk = 255;
349 // get to first full low to prime loop and skip incomplete first pulse
350 while ((GraphBuffer[i] < high) && (i < GraphTraceLen))
351 ++i;
352 while ((GraphBuffer[i] > low) && (i < GraphTraceLen))
353 ++i;
354 skip = i;
355
356 // populate tmpbuff buffer with pulse lengths
357 while (i < GraphTraceLen) {
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 if (i-start < minClk && i < GraphTraceLen) {
371 minClk = i - start;
372 }
373 }
374 // set clock
375 if (!clk) {
376 for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) {
377 tol = fndClk[clkCnt]/8;
378 if (minClk >= fndClk[clkCnt]-tol && minClk <= fndClk[clkCnt]+1) {
379 clk=fndClk[clkCnt];
380 break;
381 }
382 }
383 if (!clk) return 0;
384 } else tol = clk/8;
385
386 // look for data start - should be 2 pairs of LW (pulses of clk*3,clk*2)
387 start = -1;
388 for (i= 0; i < j - 4 ; ++i) {
389 skip += tmpbuff[i];
390 if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) //3 clocks
391 if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) //2 clocks
392 if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) //3 clocks
393 if (tmpbuff[i+3] >= clk-tol) //1.5 to 2 clocks - depends on bit following
394 {
395 start= i + 4;
396 break;
397 }
398 }
399 startblock = i + 4;
400
401 // skip over the remainder of LW
402 skip += tmpbuff[i+1] + tmpbuff[i+2] + clk;
403 if (tmpbuff[i+3]>clk)
404 phaseoff = tmpbuff[i+3]-clk;
405 else
406 phaseoff = 0;
407 // now do it again to find the end
408 end = skip;
409 for (i += 3; i < j - 4 ; ++i) {
410 end += tmpbuff[i];
411 if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) //3 clocks
412 if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) //2 clocks
413 if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) //3 clocks
414 if (tmpbuff[i+3] >= clk-tol) //1.5 to 2 clocks - depends on bit following
415 {
416 complete= true;
417 break;
418 }
419 }
420 end = i;
421 // report back
422 if (verbose || g_debugMode) {
423 if (start >= 0) {
424 PrintAndLog("\nNote: one block = 50 bits (32 data, 12 parity, 6 marker)");
425 } else {
426 PrintAndLog("No data found!, clock tried:%d",clk);
427 PrintAndLog("Try again with more samples.");
428 PrintAndLog(" or after a 'data askedge' command to clean up the read");
429 return 0;
430 }
431 } else if (start < 0) return 0;
432 start = skip;
433 snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk*47);
434 // get rid of leading crap
435 snprintf(tmp, sizeof(tmp), "%i", skip);
436 CmdLtrim(tmp);
437 bool pTest;
438 bool AllPTest = true;
439 // now work through remaining buffer printing out data blocks
440 block = 0;
441 i = startblock;
442 while (block < 6) {
443 if (verbose || g_debugMode) PrintAndLog("\nBlock %i:", block);
444 skip = phaseoff;
445
446 // look for LW before start of next block
447 for ( ; i < j - 4 ; ++i) {
448 skip += tmpbuff[i];
449 if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol)
450 if (tmpbuff[i+1] >= clk-tol)
451 break;
452 }
453 if (i >= j-4) break; //next LW not found
454 skip += clk;
455 if (tmpbuff[i+1]>clk)
456 phaseoff = tmpbuff[i+1]-clk;
457 else
458 phaseoff = 0;
459 i += 2;
460 if (ASKDemod(tmp2, false, false, 1) < 1) {
461 save_restoreGB(0);
462 return 0;
463 }
464 //set DemodBufferLen to just one block
465 DemodBufferLen = skip/clk;
466 //test parities
467 pTest = EM_ByteParityTest(DemodBuffer,DemodBufferLen,5,9,0);
468 pTest &= EM_EndParityTest(DemodBuffer,DemodBufferLen,5,9,0);
469 AllPTest &= pTest;
470 //get output
471 Code[block] = OutputEM4x50_Block(DemodBuffer,DemodBufferLen,verbose, pTest);
472 if (g_debugMode) PrintAndLog("\nskipping %d samples, bits:%d", skip, skip/clk);
473 //skip to start of next block
474 snprintf(tmp,sizeof(tmp),"%i",skip);
475 CmdLtrim(tmp);
476 block++;
477 if (i >= end) break; //in case chip doesn't output 6 blocks
478 }
479 //print full code:
480 if (verbose || g_debugMode || AllPTest){
481 if (!complete) {
482 PrintAndLog("*** Warning!");
483 PrintAndLog("Partial data - no end found!");
484 PrintAndLog("Try again with more samples.");
485 }
486 PrintAndLog("Found data at sample: %i - using clock: %i", start, clk);
487 end = block;
488 for (block=0; block < end; block++){
489 PrintAndLog("Block %d: %08x",block,Code[block]);
490 }
491 if (AllPTest) {
492 PrintAndLog("Parities Passed");
493 } else {
494 PrintAndLog("Parities Failed");
495 PrintAndLog("Try cleaning the read samples with 'data askedge'");
496 }
497 }
498
499 //restore GraphBuffer
500 save_restoreGB(0);
501 return (int)AllPTest;
502 }
503
504 int CmdEM4x50Read(const char *Cmd)
505 {
506 return EM4x50Read(Cmd, true);
507 }
508
509 int CmdReadWord(const char *Cmd)
510 {
511 int Word = -1; //default to invalid word
512 UsbCommand c;
513
514 sscanf(Cmd, "%d", &Word);
515
516 if ( (Word > 15) | (Word < 0) ) {
517 PrintAndLog("Word must be between 0 and 15");
518 return 1;
519 }
520
521 PrintAndLog("Reading word %d", Word);
522
523 c.cmd = CMD_EM4X_READ_WORD;
524 c.d.asBytes[0] = 0x0; //Normal mode
525 c.arg[0] = 0;
526 c.arg[1] = Word;
527 c.arg[2] = 0;
528 SendCommand(&c);
529 return 0;
530 }
531
532 int CmdReadWordPWD(const char *Cmd)
533 {
534 int Word = -1; //default to invalid word
535 int Password = 0xFFFFFFFF; //default to blank password
536 UsbCommand c;
537
538 sscanf(Cmd, "%d %x", &Word, &Password);
539
540 if ( (Word > 15) | (Word < 0) ) {
541 PrintAndLog("Word must be between 0 and 15");
542 return 1;
543 }
544
545 PrintAndLog("Reading word %d with password %08X", Word, Password);
546
547 c.cmd = CMD_EM4X_READ_WORD;
548 c.d.asBytes[0] = 0x1; //Password mode
549 c.arg[0] = 0;
550 c.arg[1] = Word;
551 c.arg[2] = Password;
552 SendCommand(&c);
553 return 0;
554 }
555
556 int CmdWriteWord(const char *Cmd)
557 {
558 int Word = 16; //default to invalid block
559 int Data = 0xFFFFFFFF; //default to blank data
560 UsbCommand c;
561
562 sscanf(Cmd, "%x %d", &Data, &Word);
563
564 if (Word > 15) {
565 PrintAndLog("Word must be between 0 and 15");
566 return 1;
567 }
568
569 PrintAndLog("Writing word %d with data %08X", Word, Data);
570
571 c.cmd = CMD_EM4X_WRITE_WORD;
572 c.d.asBytes[0] = 0x0; //Normal mode
573 c.arg[0] = Data;
574 c.arg[1] = Word;
575 c.arg[2] = 0;
576 SendCommand(&c);
577 return 0;
578 }
579
580 int CmdWriteWordPWD(const char *Cmd)
581 {
582 int Word = 16; //default to invalid word
583 int Data = 0xFFFFFFFF; //default to blank data
584 int Password = 0xFFFFFFFF; //default to blank password
585 UsbCommand c;
586
587 sscanf(Cmd, "%x %d %x", &Data, &Word, &Password);
588
589 if (Word > 15) {
590 PrintAndLog("Word must be between 0 and 15");
591 return 1;
592 }
593
594 PrintAndLog("Writing word %d with data %08X and password %08X", Word, Data, Password);
595
596 c.cmd = CMD_EM4X_WRITE_WORD;
597 c.d.asBytes[0] = 0x1; //Password mode
598 c.arg[0] = Data;
599 c.arg[1] = Word;
600 c.arg[2] = Password;
601 SendCommand(&c);
602 return 0;
603 }
604
605 static command_t CommandTable[] =
606 {
607 {"help", CmdHelp, 1, "This help"},
608 {"em410xdemod", CmdEMdemodASK, 0, "[findone] -- Extract ID from EM410x tag (option 0 for continuous loop, 1 for only 1 tag)"},
609 {"em410xread", CmdEM410xRead, 1, "[clock rate] -- Extract ID from EM410x tag in GraphBuffer"},
610 {"em410xsim", CmdEM410xSim, 0, "<UID> -- Simulate EM410x tag"},
611 {"em410xwatch", CmdEM410xWatch, 0, "['h'] -- Watches for EM410x 125/134 kHz tags (option 'h' for 134)"},
612 {"em410xspoof", CmdEM410xWatchnSpoof, 0, "['h'] --- Watches for EM410x 125/134 kHz tags, and replays them. (option 'h' for 134)" },
613 {"em410xwrite", CmdEM410xWrite, 0, "<UID> <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"},
614 {"em4x50read", CmdEM4x50Read, 1, "Extract data from EM4x50 tag"},
615 {"readword", CmdReadWord, 1, "<Word> -- Read EM4xxx word data"},
616 {"readwordPWD", CmdReadWordPWD, 1, "<Word> <Password> -- Read EM4xxx word data in password mode"},
617 {"writeword", CmdWriteWord, 1, "<Data> <Word> -- Write EM4xxx word data"},
618 {"writewordPWD", CmdWriteWordPWD, 1, "<Data> <Word> <Password> -- Write EM4xxx word data in password mode"},
619 {NULL, NULL, 0, NULL}
620 };
621
622 int CmdLFEM4X(const char *Cmd)
623 {
624 CmdsParse(CommandTable, Cmd);
625 return 0;
626 }
627
628 int CmdHelp(const char *Cmd)
629 {
630 CmdsHelp(CommandTable);
631 return 0;
632 }
Impressum, Datenschutz