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