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