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