]> cvs.zerfleddert.de Git - proxmark3-svn/blame - client/cmdlfem4x.c
Merge remote-tracking branch 'upstream/master'
[proxmark3-svn] / client / cmdlfem4x.c
CommitLineData
a553f267 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
7fe9b0b7 11#include <stdio.h>
9e13f875 12#include <string.h>
ec564290 13#include <inttypes.h>
2b4898ec 14#include "cmdlfem4x.h"
902cb3c0 15#include "proxmark3.h"
7fe9b0b7 16#include "ui.h"
3fe4ff4f 17#include "util.h"
acf0582d 18#include "data.h"
7fe9b0b7 19#include "graph.h"
20#include "cmdparser.h"
21#include "cmddata.h"
22#include "cmdlf.h"
7666f460 23#include "cmdmain.h"
23f0a7d8 24#include "lfdemod.h"
4ab135c0 25#include "protocols.h"
50acfd37 26#include "util_posix.h"
6ac4cb27 27
35aa230e 28uint64_t g_em410xId=0;
7fe9b0b7 29
30static int CmdHelp(const char *Cmd);
31
66707a3b 32int CmdEMdemodASK(const char *Cmd)
33{
3fe4ff4f 34 char cmdp = param_getchar(Cmd, 0);
cc15a118 35 int findone = (cmdp == '1') ? 1 : 0;
23f0a7d8 36 UsbCommand c={CMD_EM410X_DEMOD};
37 c.arg[0]=findone;
38 SendCommand(&c);
39 return 0;
66707a3b 40}
41
35aa230e 42//by marshmellow
43//print 64 bit EM410x ID in multiple formats
44void printEM410x(uint32_t hi, uint64_t id)
45{
46 if (id || hi){
47 uint64_t iii=1;
48 uint64_t id2lo=0;
49 uint32_t ii=0;
50 uint32_t i=0;
51 for (ii=5; ii>0;ii--){
52 for (i=0;i<8;i++){
53 id2lo=(id2lo<<1LL) | ((id & (iii << (i+((ii-1)*8)))) >> (i+((ii-1)*8)));
54 }
55 }
56 if (hi){
57 //output 88 bit em id
58 PrintAndLog("\nEM TAG ID : %06X%016" PRIX64, hi, id);
59 } else{
60 //output 40 bit em id
61 PrintAndLog("\nEM TAG ID : %010" PRIX64, id);
62 PrintAndLog("\nPossible de-scramble patterns");
63 PrintAndLog("Unique TAG ID : %010" PRIX64, id2lo);
64 PrintAndLog("HoneyWell IdentKey {");
65 PrintAndLog("DEZ 8 : %08" PRIu64,id & 0xFFFFFF);
66 PrintAndLog("DEZ 10 : %010" PRIu64,id & 0xFFFFFFFF);
67 PrintAndLog("DEZ 5.5 : %05lld.%05" PRIu64,(id>>16LL) & 0xFFFF,(id & 0xFFFF));
68 PrintAndLog("DEZ 3.5A : %03lld.%05" PRIu64,(id>>32ll),(id & 0xFFFF));
69 PrintAndLog("DEZ 3.5B : %03lld.%05" PRIu64,(id & 0xFF000000) >> 24,(id & 0xFFFF));
70 PrintAndLog("DEZ 3.5C : %03lld.%05" PRIu64,(id & 0xFF0000) >> 16,(id & 0xFFFF));
71 PrintAndLog("DEZ 14/IK2 : %014" PRIu64,id);
72 PrintAndLog("DEZ 15/IK3 : %015" PRIu64,id2lo);
73 PrintAndLog("DEZ 20/ZK : %02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64 "%02" PRIu64,
74 (id2lo & 0xf000000000) >> 36,
75 (id2lo & 0x0f00000000) >> 32,
76 (id2lo & 0x00f0000000) >> 28,
77 (id2lo & 0x000f000000) >> 24,
78 (id2lo & 0x0000f00000) >> 20,
79 (id2lo & 0x00000f0000) >> 16,
80 (id2lo & 0x000000f000) >> 12,
81 (id2lo & 0x0000000f00) >> 8,
82 (id2lo & 0x00000000f0) >> 4,
83 (id2lo & 0x000000000f)
84 );
85 uint64_t paxton = (((id>>32) << 24) | (id & 0xffffff)) + 0x143e00;
47af8c5f 86 PrintAndLog("}\nOther : %05" PRIu64 "_%03" PRIu64 "_%08" PRIu64 "",(id&0xFFFF),((id>>16LL) & 0xFF),(id & 0xFFFFFF));
35aa230e 87 PrintAndLog("Pattern Paxton : %" PRIu64 " [0x%" PRIX64 "]", paxton, paxton);
88
89 uint32_t p1id = (id & 0xFFFFFF);
90 uint8_t arr[32] = {0x00};
47af8c5f 91 int i =0;
35aa230e 92 int j = 23;
93 for (; i < 24; ++i, --j ){
94 arr[i] = (p1id >> i) & 1;
95 }
96
97 uint32_t p1 = 0;
98
99 p1 |= arr[23] << 21;
100 p1 |= arr[22] << 23;
101 p1 |= arr[21] << 20;
102 p1 |= arr[20] << 22;
47af8c5f 103
35aa230e 104 p1 |= arr[19] << 18;
105 p1 |= arr[18] << 16;
106 p1 |= arr[17] << 19;
107 p1 |= arr[16] << 17;
47af8c5f 108
35aa230e 109 p1 |= arr[15] << 13;
110 p1 |= arr[14] << 15;
111 p1 |= arr[13] << 12;
112 p1 |= arr[12] << 14;
113
114 p1 |= arr[11] << 6;
115 p1 |= arr[10] << 2;
116 p1 |= arr[9] << 7;
117 p1 |= arr[8] << 1;
118
119 p1 |= arr[7] << 0;
120 p1 |= arr[6] << 8;
121 p1 |= arr[5] << 11;
122 p1 |= arr[4] << 3;
123
124 p1 |= arr[3] << 10;
125 p1 |= arr[2] << 4;
126 p1 |= arr[1] << 5;
127 p1 |= arr[0] << 9;
128 PrintAndLog("Pattern 1 : %d [0x%X]", p1, p1);
129
130 uint16_t sebury1 = id & 0xFFFF;
131 uint8_t sebury2 = (id >> 16) & 0x7F;
132 uint32_t sebury3 = id & 0x7FFFFF;
133 PrintAndLog("Pattern Sebury : %d %d %d [0x%X 0x%X 0x%X]", sebury1, sebury2, sebury3, sebury1, sebury2, sebury3);
134 }
135 }
136 return;
137}
138
7fe9b0b7 139/* Read the ID of an EM410x tag.
140 * Format:
141 * 1111 1111 1 <-- standard non-repeatable header
142 * XXXX [row parity bit] <-- 10 rows of 5 bits for our 40 bit tag ID
143 * ....
144 * CCCC <-- each bit here is parity for the 10 bits above in corresponding column
145 * 0 <-- stop bit, end of tag
146 */
35aa230e 147int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo )
7fe9b0b7 148{
35aa230e 149 size_t idx = 0;
b9957414 150 uint8_t BitStream[512]={0};
151 size_t BitLen = sizeof(BitStream);
152 if ( !getDemodBuf(BitStream, &BitLen) ) return 0;
153
154 if (Em410xDecode(BitStream, &BitLen, &idx, hi, lo)) {
35aa230e 155 //set GraphBuffer for clone or sim command
b8fdac9e 156 setDemodBuf(DemodBuffer, (BitLen==40) ? 64 : 128, idx+1);
9fe4507c 157 setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx+1)*g_DemodClock));
158
b9957414 159 if (g_debugMode) {
35aa230e 160 PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen);
161 printDemodBuff();
162 }
b9957414 163 if (verbose) {
35aa230e 164 PrintAndLog("EM410x pattern found: ");
165 printEM410x(*hi, *lo);
166 g_em410xId = *lo;
167 }
168 return 1;
169 }
170 return 0;
171}
172
173//askdemod then call Em410xdecode
174int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose)
175{
176 bool st = true;
177 if (!ASKDemod_ext(Cmd, false, false, 1, &st)) return 0;
178 return AskEm410xDecode(verbose, hi, lo);
179}
180
181//by marshmellow
182//takes 3 arguments - clock, invert and maxErr as integers
183//attempts to demodulate ask while decoding manchester
184//prints binary found and saves in graphbuffer for further commands
185int CmdAskEM410xDemod(const char *Cmd)
186{
187 char cmdp = param_getchar(Cmd, 0);
188 if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') {
189 PrintAndLog("Usage: lf em 410xdemod [clock] <0|1> [maxError]");
190 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
191 PrintAndLog(" <invert>, 1 for invert output");
192 PrintAndLog(" [set maximum allowed errors], default = 100.");
193 PrintAndLog("");
194 PrintAndLog(" sample: lf em 410xdemod = demod an EM410x Tag ID from GraphBuffer");
195 PrintAndLog(" : lf em 410xdemod 32 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/32");
196 PrintAndLog(" : lf em 410xdemod 32 1 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/32 and inverting data");
197 PrintAndLog(" : lf em 410xdemod 1 = demod an EM410x Tag ID from GraphBuffer while inverting data");
198 PrintAndLog(" : lf em 410xdemod 64 1 0 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/64 and inverting data and allowing 0 demod errors");
23f0a7d8 199 return 0;
200 }
35aa230e 201 uint64_t lo = 0;
202 uint32_t hi = 0;
203 return AskEm410xDemod(Cmd, &hi, &lo, true);
7fe9b0b7 204}
205
c8518913 206int usage_lf_em410x_sim(void) {
207 PrintAndLog("Simulating EM410x tag");
208 PrintAndLog("");
209 PrintAndLog("Usage: lf em 410xsim [h] <uid> <clock>");
210 PrintAndLog("Options:");
211 PrintAndLog(" h - this help");
212 PrintAndLog(" uid - uid (10 HEX symbols)");
213 PrintAndLog(" clock - clock (32|64) (optional)");
214 PrintAndLog("samples:");
215 PrintAndLog(" lf em 410xsim 0F0368568B");
216 PrintAndLog(" lf em 410xsim 0F0368568B 32");
217 return 0;
218}
219
13d77ef9 220// emulate an EM410X tag
7fe9b0b7 221int CmdEM410xSim(const char *Cmd)
222{
3fe4ff4f 223 int i, n, j, binary[4], parity[4];
224
225 char cmdp = param_getchar(Cmd, 0);
226 uint8_t uid[5] = {0x00};
227
c8518913 228 if (cmdp == 'h' || cmdp == 'H') return usage_lf_em410x_sim();
daa4fbae 229 /* clock is 64 in EM410x tags */
415274a7 230 uint8_t clock = 64;
3fe4ff4f 231
232 if (param_gethex(Cmd, 0, uid, 10)) {
233 PrintAndLog("UID must include 10 HEX symbols");
234 return 0;
235 }
415274a7 236 param_getdec(Cmd,1, &clock);
daa4fbae 237
238 PrintAndLog("Starting simulating UID %02X%02X%02X%02X%02X clock: %d", uid[0],uid[1],uid[2],uid[3],uid[4],clock);
50acfd37 239 PrintAndLog("Press pm3-button to abort simulation");
7fe9b0b7 240
23f0a7d8 241
242 /* clear our graph */
243 ClearGraph(0);
244
245 /* write 9 start bits */
246 for (i = 0; i < 9; i++)
247 AppendGraph(0, clock, 1);
248
249 /* for each hex char */
250 parity[0] = parity[1] = parity[2] = parity[3] = 0;
251 for (i = 0; i < 10; i++)
252 {
253 /* read each hex char */
254 sscanf(&Cmd[i], "%1x", &n);
255 for (j = 3; j >= 0; j--, n/= 2)
256 binary[j] = n % 2;
257
258 /* append each bit */
259 AppendGraph(0, clock, binary[0]);
260 AppendGraph(0, clock, binary[1]);
261 AppendGraph(0, clock, binary[2]);
262 AppendGraph(0, clock, binary[3]);
263
264 /* append parity bit */
265 AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]);
266
267 /* keep track of column parity */
268 parity[0] ^= binary[0];
269 parity[1] ^= binary[1];
270 parity[2] ^= binary[2];
271 parity[3] ^= binary[3];
272 }
273
274 /* parity columns */
275 AppendGraph(0, clock, parity[0]);
276 AppendGraph(0, clock, parity[1]);
277 AppendGraph(0, clock, parity[2]);
278 AppendGraph(0, clock, parity[3]);
279
280 /* stop bit */
281 AppendGraph(1, clock, 0);
47af8c5f 282
23f0a7d8 283 CmdLFSim("0"); //240 start_gap.
284 return 0;
7fe9b0b7 285}
286
50acfd37
F
287int usage_lf_em410x_brute(void) {
288 PrintAndLog("Bruteforcing by emulating EM410x tag");
289 PrintAndLog("");
290 PrintAndLog("Usage: lf em 410xbrute [h] ids.txt");
291 PrintAndLog("Options:");
292 PrintAndLog(" h - this help");
293 PrintAndLog(" ids.txt - file with id in HEX format one per line");
294 PrintAndLog(" clock - clock (32|64) (optional)");
295 PrintAndLog("samples:");
296 PrintAndLog(" lf em 410xbrute ids.txt");
297 PrintAndLog(" lf em 410xbrute ids.txt 32");
298 return 0;
299}
300
301int CmdEM410xBrute(const char *Cmd)
302{
303 char filename[FILE_PATH_SIZE]={0};
47af8c5f
F
304 FILE *f = NULL;
305 char buf[11];
50acfd37
F
306 int i, n, j, binary[4], parity[4];
307
47af8c5f 308 char cmdp = param_getchar(Cmd, 0);
1ccba0b9 309 uint8_t uid[5] = {0x00};
50acfd37 310
1ccba0b9
F
311 if (cmdp == 'h' || cmdp == 'H') return usage_lf_em410x_sim();
312 /* clock is 64 in EM410x tags */
313 uint8_t clock = 64;
50acfd37 314
47af8c5f 315 param_getdec(Cmd,1, &clock);
50acfd37
F
316
317 param_getstr(Cmd, 0, filename);
50acfd37 318
47af8c5f
F
319 if (strlen(filename) > 0) {
320 if ((f = fopen(filename, "r")) == NULL) {
321 PrintAndLog("Error: Could not open IDs file [%s]",filename);
322 return 1;
323 }
324 } else {
325 PrintAndLog("Error: Please specify a filename");
326 return 1;
327 }
50acfd37 328
50acfd37
F
329
330 while( fgets(buf, sizeof(buf), f) ) {
331 msleep(1000);
332 if (strlen(buf) < 10 || buf[9] == '\n') continue;
333 while (fgetc(f) != '\n' && !feof(f)); //goto next line
334
335 //The line start with # is comment, skip
47af8c5f
F
336 if( buf[0]=='#' ) continue;
337
50acfd37
F
338 buf[10] = 0;
339 //PrintAndLog("ID: %s", buf);
47af8c5f
F
340
341 if (param_gethex(buf, 0, uid, 10)) {
342 PrintAndLog("UID must include 10 HEX symbols");
343 return 0;
344 }
345
346 PrintAndLog("Starting simulating UID %02X%02X%02X%02X%02X clock: %d", uid[0],uid[1],uid[2],uid[3],uid[4],clock);
347
348 /* clear our graph */
349 ClearGraph(0);
350
351 /* write 9 start bits */
352 for (i = 0; i < 9; i++)
353 AppendGraph(0, clock, 1);
354
1ccba0b9
F
355 /* for each hex char */
356 parity[0] = parity[1] = parity[2] = parity[3] = 0;
357 for (i = 0; i < 10; i++){
358 /* read each hex char */
359 sscanf(&buf[i], "%1x", &n);
360 for (j = 3; j >= 0; j--, n/= 2)
361 binary[j] = n % 2;
362
363 /* append each bit */
364 AppendGraph(0, clock, binary[0]);
365 AppendGraph(0, clock, binary[1]);
366 AppendGraph(0, clock, binary[2]);
367 AppendGraph(0, clock, binary[3]);
368
369 /* append parity bit */
370 AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]);
47af8c5f 371
1ccba0b9
F
372 /* keep track of column parity */
373 parity[0] ^= binary[0];
374 parity[1] ^= binary[1];
375 parity[2] ^= binary[2];
376 parity[3] ^= binary[3];
377 }
378
379 /* parity columns */
380 AppendGraph(0, clock, parity[0]);
381 AppendGraph(0, clock, parity[1]);
382 AppendGraph(0, clock, parity[2]);
383 AppendGraph(0, clock, parity[3]);
47af8c5f 384
1ccba0b9
F
385 /* stop bit */
386 AppendGraph(1, clock, 0);
50acfd37 387
1ccba0b9 388 CmdLFSim("0"); //240 start_gap.
50acfd37 389
1ccba0b9 390 memset(buf, 0, sizeof(buf));
50acfd37 391
1ccba0b9 392 }
47af8c5f 393
1ccba0b9 394 fclose(f);
47af8c5f 395
1ccba0b9 396 return 0;
50acfd37
F
397}
398
399
3fe4ff4f 400/* Function is equivalent of lf read + data samples + em410xread
47af8c5f
F
401 * looped until an EM410x tag is detected
402 *
3fe4ff4f 403 * Why is CmdSamples("16000")?
404 * TBD: Auto-grow sample size based on detected sample rate. IE: If the
405 * rate gets lower, then grow the number of samples
47af8c5f 406 * Changed by martin, 4000 x 4 = 16000,
3fe4ff4f 407 * see http://www.proxmark.org/forum/viewtopic.php?pid=7235#p7235
35aa230e 408 *
409 * EDIT -- capture enough to get 2 complete preambles at the slowest data rate known to be used (rf/64) (64*64*2+9 = 8201) marshmellow
3fe4ff4f 410*/
7fe9b0b7 411int CmdEM410xWatch(const char *Cmd)
412{
3fe4ff4f 413 do {
414 if (ukbhit()) {
415 printf("\naborted via keyboard!\n");
416 break;
417 }
b9957414 418 lf_read(true, 8201);
35aa230e 419 } while (!CmdAskEM410xDemod(""));
13d77ef9 420
3fe4ff4f 421 return 0;
7fe9b0b7 422}
423
23f0a7d8 424//currently only supports manchester modulations
c3bfb9c7 425int CmdEM410xWatchnSpoof(const char *Cmd)
426{
427 CmdEM410xWatch(Cmd);
35aa230e 428 PrintAndLog("# Replaying captured ID: %010"PRIx64, g_em410xId);
1fbf8956 429 CmdLFaskSim("");
430 return 0;
c3bfb9c7 431}
432
6e984446 433int CmdEM410xWrite(const char *Cmd)
434{
435 uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value
436 int card = 0xFF; // invalid card value
437 unsigned int clock = 0; // invalid clock value
438
2b11c7c7 439 sscanf(Cmd, "%" SCNx64 " %d %d", &id, &card, &clock);
6e984446 440
441 // Check ID
442 if (id == 0xFFFFFFFFFFFFFFFF) {
443 PrintAndLog("Error! ID is required.\n");
444 return 0;
445 }
446 if (id >= 0x10000000000) {
447 PrintAndLog("Error! Given EM410x ID is longer than 40 bits.\n");
448 return 0;
449 }
450
451 // Check Card
452 if (card == 0xFF) {
453 PrintAndLog("Error! Card type required.\n");
454 return 0;
455 }
456 if (card < 0) {
457 PrintAndLog("Error! Bad card type selected.\n");
458 return 0;
459 }
460
461 // Check Clock
76346455 462 // Default: 64
463 if (clock == 0)
464 clock = 64;
465
466 // Allowed clock rates: 16, 32, 40 and 64
467 if ((clock != 16) && (clock != 32) && (clock != 64) && (clock != 40)) {
468 PrintAndLog("Error! Clock rate %d not valid. Supported clock rates are 16, 32, 40 and 64.\n", clock);
6e984446 469 return 0;
470 }
471
472 if (card == 1) {
473 PrintAndLog("Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock);
474 // NOTE: We really should pass the clock in as a separate argument, but to
475 // provide for backwards-compatibility for older firmware, and to avoid
476 // having to add another argument to CMD_EM410X_WRITE_TAG, we just store
477 // the clock rate in bits 8-15 of the card value
76346455 478 card = (card & 0xFF) | ((clock << 8) & 0xFF00);
479 } else if (card == 0) {
6e984446 480 PrintAndLog("Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock);
76346455 481 card = (card & 0xFF) | ((clock << 8) & 0xFF00);
482 } else {
6e984446 483 PrintAndLog("Error! Bad card type selected.\n");
484 return 0;
485 }
486
487 UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}};
488 SendCommand(&c);
489
490 return 0;
491}
492
4c6ccc2b 493//**************** Start of EM4x50 Code ************************
23f0a7d8 494bool EM_EndParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType)
495{
496 if (rows*cols>size) return false;
497 uint8_t colP=0;
cc15a118 498 //assume last col is a parity and do not test
23f0a7d8 499 for (uint8_t colNum = 0; colNum < cols-1; colNum++) {
500 for (uint8_t rowNum = 0; rowNum < rows; rowNum++) {
501 colP ^= BitStream[(rowNum*cols)+colNum];
502 }
503 if (colP != pType) return false;
504 }
505 return true;
506}
507
508bool EM_ByteParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType)
509{
510 if (rows*cols>size) return false;
511 uint8_t rowP=0;
512 //assume last row is a parity row and do not test
513 for (uint8_t rowNum = 0; rowNum < rows-1; rowNum++) {
514 for (uint8_t colNum = 0; colNum < cols; colNum++) {
515 rowP ^= BitStream[(rowNum*cols)+colNum];
516 }
517 if (rowP != pType) return false;
518 }
519 return true;
520}
521
522uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool pTest)
523{
524 if (size<45) return 0;
525 uint32_t code = bytebits_to_byte(BitStream,8);
526 code = code<<8 | bytebits_to_byte(BitStream+9,8);
527 code = code<<8 | bytebits_to_byte(BitStream+18,8);
528 code = code<<8 | bytebits_to_byte(BitStream+27,8);
529 if (verbose || g_debugMode){
530 for (uint8_t i = 0; i<5; i++){
cc15a118 531 if (i == 4) PrintAndLog(""); //parity byte spacer
23f0a7d8 532 PrintAndLog("%d%d%d%d%d%d%d%d %d -> 0x%02x",
533 BitStream[i*9],
534 BitStream[i*9+1],
535 BitStream[i*9+2],
536 BitStream[i*9+3],
537 BitStream[i*9+4],
538 BitStream[i*9+5],
539 BitStream[i*9+6],
540 BitStream[i*9+7],
541 BitStream[i*9+8],
542 bytebits_to_byte(BitStream+i*9,8)
543 );
544 }
545 if (pTest)
546 PrintAndLog("Parity Passed");
547 else
548 PrintAndLog("Parity Failed");
549 }
23f0a7d8 550 return code;
551}
7666f460 552/* Read the transmitted data of an EM4x50 tag from the graphbuffer
7fe9b0b7 553 * Format:
554 *
555 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
556 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
557 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
558 * XXXXXXXX [row parity bit (even)] <- 8 bits plus parity
559 * CCCCCCCC <- column parity bits
560 * 0 <- stop bit
561 * LW <- Listen Window
562 *
563 * This pattern repeats for every block of data being transmitted.
564 * Transmission starts with two Listen Windows (LW - a modulated
565 * pattern of 320 cycles each (32/32/128/64/64)).
566 *
567 * Note that this data may or may not be the UID. It is whatever data
568 * is stored in the blocks defined in the control word First and Last
569 * Word Read values. UID is stored in block 32.
570 */
cc15a118 571 //completed by Marshmellow
23f0a7d8 572int EM4x50Read(const char *Cmd, bool verbose)
573{
cc15a118 574 uint8_t fndClk[] = {8,16,32,40,50,64,128};
47af8c5f 575 int clk = 0;
23f0a7d8 576 int invert = 0;
23f0a7d8 577 int tol = 0;
578 int i, j, startblock, skip, block, start, end, low, high, minClk;
cc15a118 579 bool complete = false;
23f0a7d8 580 int tmpbuff[MAX_GRAPH_TRACE_LEN / 64];
23f0a7d8 581 uint32_t Code[6];
582 char tmp[6];
23f0a7d8 583 char tmp2[20];
49bbc60a 584 int phaseoff;
cc15a118 585 high = low = 0;
23f0a7d8 586 memset(tmpbuff, 0, MAX_GRAPH_TRACE_LEN / 64);
cc15a118 587
588 // get user entry if any
589 sscanf(Cmd, "%i %i", &clk, &invert);
47af8c5f 590
23f0a7d8 591 // first get high and low values
cc15a118 592 for (i = 0; i < GraphTraceLen; i++) {
23f0a7d8 593 if (GraphBuffer[i] > high)
594 high = GraphBuffer[i];
595 else if (GraphBuffer[i] < low)
596 low = GraphBuffer[i];
597 }
598
cc15a118 599 i = 0;
600 j = 0;
601 minClk = 255;
602 // get to first full low to prime loop and skip incomplete first pulse
603 while ((GraphBuffer[i] < high) && (i < GraphTraceLen))
604 ++i;
605 while ((GraphBuffer[i] > low) && (i < GraphTraceLen))
606 ++i;
607 skip = i;
608
609 // populate tmpbuff buffer with pulse lengths
610 while (i < GraphTraceLen) {
23f0a7d8 611 // measure from low to low
cc15a118 612 while ((GraphBuffer[i] > low) && (i < GraphTraceLen))
23f0a7d8 613 ++i;
614 start= i;
cc15a118 615 while ((GraphBuffer[i] < high) && (i < GraphTraceLen))
23f0a7d8 616 ++i;
cc15a118 617 while ((GraphBuffer[i] > low) && (i < GraphTraceLen))
23f0a7d8 618 ++i;
619 if (j>=(MAX_GRAPH_TRACE_LEN/64)) {
620 break;
621 }
622 tmpbuff[j++]= i - start;
cc15a118 623 if (i-start < minClk && i < GraphTraceLen) {
624 minClk = i - start;
625 }
23f0a7d8 626 }
627 // set clock
cc15a118 628 if (!clk) {
23f0a7d8 629 for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) {
630 tol = fndClk[clkCnt]/8;
47af8c5f 631 if (minClk >= fndClk[clkCnt]-tol && minClk <= fndClk[clkCnt]+1) {
23f0a7d8 632 clk=fndClk[clkCnt];
633 break;
634 }
635 }
cc15a118 636 if (!clk) return 0;
6e984446 637 } else tol = clk/8;
23f0a7d8 638
639 // look for data start - should be 2 pairs of LW (pulses of clk*3,clk*2)
cc15a118 640 start = -1;
641 for (i= 0; i < j - 4 ; ++i) {
23f0a7d8 642 skip += tmpbuff[i];
cc15a118 643 if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) //3 clocks
644 if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) //2 clocks
645 if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) //3 clocks
646 if (tmpbuff[i+3] >= clk-tol) //1.5 to 2 clocks - depends on bit following
23f0a7d8 647 {
648 start= i + 4;
649 break;
650 }
651 }
cc15a118 652 startblock = i + 4;
23f0a7d8 653
654 // skip over the remainder of LW
49bbc60a 655 skip += tmpbuff[i+1] + tmpbuff[i+2] + clk;
47af8c5f 656 if (tmpbuff[i+3]>clk)
49bbc60a 657 phaseoff = tmpbuff[i+3]-clk;
658 else
659 phaseoff = 0;
23f0a7d8 660 // now do it again to find the end
661 end = skip;
cc15a118 662 for (i += 3; i < j - 4 ; ++i) {
23f0a7d8 663 end += tmpbuff[i];
cc15a118 664 if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) //3 clocks
665 if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) //2 clocks
666 if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) //3 clocks
667 if (tmpbuff[i+3] >= clk-tol) //1.5 to 2 clocks - depends on bit following
23f0a7d8 668 {
669 complete= true;
670 break;
671 }
672 }
673 end = i;
674 // report back
675 if (verbose || g_debugMode) {
676 if (start >= 0) {
cc15a118 677 PrintAndLog("\nNote: one block = 50 bits (32 data, 12 parity, 6 marker)");
23f0a7d8 678 } else {
cc15a118 679 PrintAndLog("No data found!, clock tried:%d",clk);
23f0a7d8 680 PrintAndLog("Try again with more samples.");
cc15a118 681 PrintAndLog(" or after a 'data askedge' command to clean up the read");
23f0a7d8 682 return 0;
683 }
23f0a7d8 684 } else if (start < 0) return 0;
cc15a118 685 start = skip;
23f0a7d8 686 snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk*47);
47af8c5f 687 // save GraphBuffer - to restore it later
3fd7fce4 688 save_restoreGB(GRAPH_SAVE);
47af8c5f 689 // get rid of leading crap
cc15a118 690 snprintf(tmp, sizeof(tmp), "%i", skip);
23f0a7d8 691 CmdLtrim(tmp);
692 bool pTest;
cc15a118 693 bool AllPTest = true;
23f0a7d8 694 // now work through remaining buffer printing out data blocks
695 block = 0;
696 i = startblock;
cc15a118 697 while (block < 6) {
23f0a7d8 698 if (verbose || g_debugMode) PrintAndLog("\nBlock %i:", block);
699 skip = phaseoff;
47af8c5f 700
23f0a7d8 701 // look for LW before start of next block
cc15a118 702 for ( ; i < j - 4 ; ++i) {
23f0a7d8 703 skip += tmpbuff[i];
704 if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol)
705 if (tmpbuff[i+1] >= clk-tol)
706 break;
707 }
49bbc60a 708 if (i >= j-4) break; //next LW not found
23f0a7d8 709 skip += clk;
49bbc60a 710 if (tmpbuff[i+1]>clk)
711 phaseoff = tmpbuff[i+1]-clk;
712 else
713 phaseoff = 0;
23f0a7d8 714 i += 2;
fef74fdc 715 if (ASKDemod(tmp2, false, false, 1) < 1) {
3fd7fce4 716 save_restoreGB(GRAPH_RESTORE);
cc15a118 717 return 0;
718 }
23f0a7d8 719 //set DemodBufferLen to just one block
720 DemodBufferLen = skip/clk;
721 //test parities
47af8c5f 722 pTest = EM_ByteParityTest(DemodBuffer,DemodBufferLen,5,9,0);
23f0a7d8 723 pTest &= EM_EndParityTest(DemodBuffer,DemodBufferLen,5,9,0);
724 AllPTest &= pTest;
725 //get output
cc15a118 726 Code[block] = OutputEM4x50_Block(DemodBuffer,DemodBufferLen,verbose, pTest);
727 if (g_debugMode) PrintAndLog("\nskipping %d samples, bits:%d", skip, skip/clk);
23f0a7d8 728 //skip to start of next block
729 snprintf(tmp,sizeof(tmp),"%i",skip);
730 CmdLtrim(tmp);
731 block++;
cc15a118 732 if (i >= end) break; //in case chip doesn't output 6 blocks
23f0a7d8 733 }
734 //print full code:
735 if (verbose || g_debugMode || AllPTest){
49bbc60a 736 if (!complete) {
737 PrintAndLog("*** Warning!");
738 PrintAndLog("Partial data - no end found!");
739 PrintAndLog("Try again with more samples.");
740 }
47af8c5f 741 PrintAndLog("Found data at sample: %i - using clock: %i", start, clk);
cc15a118 742 end = block;
743 for (block=0; block < end; block++){
23f0a7d8 744 PrintAndLog("Block %d: %08x",block,Code[block]);
745 }
49bbc60a 746 if (AllPTest) {
23f0a7d8 747 PrintAndLog("Parities Passed");
49bbc60a 748 } else {
23f0a7d8 749 PrintAndLog("Parities Failed");
cc15a118 750 PrintAndLog("Try cleaning the read samples with 'data askedge'");
49bbc60a 751 }
23f0a7d8 752 }
753
754 //restore GraphBuffer
3fd7fce4 755 save_restoreGB(GRAPH_RESTORE);
23f0a7d8 756 return (int)AllPTest;
757}
758
7fe9b0b7 759int CmdEM4x50Read(const char *Cmd)
760{
23f0a7d8 761 return EM4x50Read(Cmd, true);
7fe9b0b7 762}
763
4c6ccc2b 764//**************** Start of EM4x05/EM4x69 Code ************************
7666f460 765int usage_lf_em_read(void) {
766 PrintAndLog("Read EM4x05/EM4x69. Tag must be on antenna. ");
767 PrintAndLog("");
e39a92bb 768 PrintAndLog("Usage: lf em 4x05readword [h] <address> <pwd>");
7666f460 769 PrintAndLog("Options:");
770 PrintAndLog(" h - this help");
771 PrintAndLog(" address - memory address to read. (0-15)");
772 PrintAndLog(" pwd - password (hex) (optional)");
773 PrintAndLog("samples:");
e39a92bb 774 PrintAndLog(" lf em 4x05readword 1");
775 PrintAndLog(" lf em 4x05readword 1 11223344");
7666f460 776 return 0;
777}
6f1a5978 778
4c6ccc2b 779// for command responses from em4x05 or em4x69
780// download samples from device and copy them to the Graphbuffer
781bool downloadSamplesEM() {
782 // 8 bit preamble + 32 bit word response (max clock (128) * 40bits = 5120 samples)
47af8c5f 783 uint8_t got[6000];
4c6ccc2b 784 GetFromBigBuf(got, sizeof(got), 0);
785 if ( !WaitForResponseTimeout(CMD_ACK, NULL, 4000) ) {
786 PrintAndLog("command execution time out");
787 return false;
6f1a5978 788 }
4c6ccc2b 789 setGraphBuf(got, sizeof(got));
790 return true;
e39a92bb 791}
792
793bool EM4x05testDemodReadData(uint32_t *word, bool readCmd) {
34ff8985 794 // em4x05/em4x69 command response preamble is 00001010
4c6ccc2b 795 // skip first two 0 bits as they might have been missed in the demod
796 uint8_t preamble[] = {0,0,1,0,1,0};
e39a92bb 797 size_t startIdx = 0;
e39a92bb 798
34ff8985 799 // set size to 20 to only test first 14 positions for the preamble or less if not a read command
800 size_t size = (readCmd) ? 20 : 11;
801 // sanity check
802 size = (size > DemodBufferLen) ? DemodBufferLen : size;
803 // test preamble
e88096ba 804 if ( !preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx, true) ) {
e39a92bb 805 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305 preamble not found :: %d", startIdx);
806 return false;
807 }
4c6ccc2b 808 // if this is a readword command, get the read bytes and test the parities
e39a92bb 809 if (readCmd) {
4c6ccc2b 810 if (!EM_EndParityTest(DemodBuffer + startIdx + sizeof(preamble), 45, 5, 9, 0)) {
811 if (g_debugMode) PrintAndLog("DEBUG: Error - End Parity check failed");
812 return false;
813 }
e88096ba 814 // test for even parity bits and remove them. (leave out the end row of parities so 36 bits)
47af8c5f 815 if ( removeParity(DemodBuffer, startIdx + sizeof(preamble),9,0,36) == 0 ) {
e39a92bb 816 if (g_debugMode) PrintAndLog("DEBUG: Error - Parity not detected");
817 return false;
818 }
819
e88096ba 820 setDemodBuf(DemodBuffer, 32, 0);
f516ff08 821 //setClockGrid(0,0);
9fe4507c 822
4c6ccc2b 823 *word = bytebits_to_byteLSBF(DemodBuffer, 32);
e39a92bb 824 }
825 return true;
6f1a5978 826}
827
47af8c5f 828// FSK, PSK, ASK/MANCHESTER, ASK/BIPHASE, ASK/DIPHASE
59f726c9 829// should cover 90% of known used configs
830// the rest will need to be manually demoded for now...
e39a92bb 831int demodEM4x05resp(uint32_t *word, bool readCmd) {
6f1a5978 832 int ans = 0;
6f1a5978 833
834 // test for FSK wave (easiest to 99% ID)
34212c66 835 if (GetFskClock("", false, false)) {
6f1a5978 836 //valid fsk clocks found
837 ans = FSKrawDemod("0 0", false);
838 if (!ans) {
4c6ccc2b 839 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: FSK Demod failed, ans: %d", ans);
6f1a5978 840 } else {
e39a92bb 841 if (EM4x05testDemodReadData(word, readCmd)) {
842 return 1;
6f1a5978 843 }
844 }
845 }
59f726c9 846 // PSK clocks should be easy to detect ( but difficult to demod a non-repeating pattern... )
34212c66 847 ans = GetPskClock("", false, false);
6980d66b 848 if (ans>0) {
849 //try psk1
34212c66 850 ans = PSKDemod("0 0 6", false);
59f726c9 851 if (!ans) {
4c6ccc2b 852 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: PSK1 Demod failed, ans: %d", ans);
59f726c9 853 } else {
e39a92bb 854 if (EM4x05testDemodReadData(word, readCmd)) {
855 return 1;
6980d66b 856 } else {
857 //try psk2
858 psk1TOpsk2(DemodBuffer, DemodBufferLen);
859 if (EM4x05testDemodReadData(word, readCmd)) {
860 return 1;
861 }
862 }
863 //try psk1 inverted
34212c66 864 ans = PSKDemod("0 1 6", false);
6980d66b 865 if (!ans) {
4c6ccc2b 866 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: PSK1 Demod failed, ans: %d", ans);
6980d66b 867 } else {
868 if (EM4x05testDemodReadData(word, readCmd)) {
869 return 1;
870 } else {
871 //try psk2
872 psk1TOpsk2(DemodBuffer, DemodBufferLen);
873 if (EM4x05testDemodReadData(word, readCmd)) {
874 return 1;
875 }
876 }
59f726c9 877 }
878 }
6f1a5978 879 }
880
4c6ccc2b 881 // manchester is more common than biphase... try first
6980d66b 882 bool stcheck = false;
883 // try manchester - NOTE: ST only applies to T55x7 tags.
884 ans = ASKDemod_ext("0,0,1", false, false, 1, &stcheck);
885 if (!ans) {
4c6ccc2b 886 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: ASK/Manchester Demod failed, ans: %d", ans);
6980d66b 887 } else {
888 if (EM4x05testDemodReadData(word, readCmd)) {
889 return 1;
6f1a5978 890 }
891 }
892
6980d66b 893 //try biphase
34212c66 894 ans = ASKbiphaseDemod("0 0 1", false);
47af8c5f 895 if (!ans) {
4c6ccc2b 896 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: ASK/biphase Demod failed, ans: %d", ans);
6980d66b 897 } else {
898 if (EM4x05testDemodReadData(word, readCmd)) {
899 return 1;
6f1a5978 900 }
901 }
902
6980d66b 903 //try diphase (differential biphase or inverted)
34212c66 904 ans = ASKbiphaseDemod("0 1 1", false);
47af8c5f 905 if (!ans) {
4c6ccc2b 906 if (g_debugMode) PrintAndLog("DEBUG: Error - EM4305: ASK/biphase Demod failed, ans: %d", ans);
6980d66b 907 } else {
908 if (EM4x05testDemodReadData(word, readCmd)) {
909 return 1;
59f726c9 910 }
6980d66b 911 }
912
6f1a5978 913 return -1;
914}
915
fa1e00cf 916int EM4x05ReadWord_ext(uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *wordData) {
7666f460 917 UsbCommand c = {CMD_EM4X_READ_WORD, {addr, pwd, usePwd}};
918 clearCommandBuffer();
23f0a7d8 919 SendCommand(&c);
47af8c5f 920 UsbCommand resp;
7666f460 921 if (!WaitForResponseTimeout(CMD_ACK, &resp, 2500)){
922 PrintAndLog("Command timed out");
923 return -1;
924 }
4c6ccc2b 925 if ( !downloadSamplesEM() ) {
6f1a5978 926 return -1;
7666f460 927 }
6f1a5978 928 int testLen = (GraphTraceLen < 1000) ? GraphTraceLen : 1000;
929 if (graphJustNoise(GraphBuffer, testLen)) {
930 PrintAndLog("no tag not found");
931 return -1;
932 }
59f726c9 933 //attempt demod:
fa1e00cf 934 return demodEM4x05resp(wordData, true);
935}
936
937int EM4x05ReadWord(uint8_t addr, uint32_t pwd, bool usePwd) {
e39a92bb 938 uint32_t wordData = 0;
fa1e00cf 939 int success = EM4x05ReadWord_ext(addr, pwd, usePwd, &wordData);
4c6ccc2b 940 if (success == 1)
33a1fe96 941 PrintAndLog("%s Address %02d | %08X", (addr>13) ? "Lock":" Got",addr,wordData);
4c6ccc2b 942 else
fa1e00cf 943 PrintAndLog("Read Address %02d | failed",addr);
4c6ccc2b 944
e39a92bb 945 return success;
946}
947
948int CmdEM4x05ReadWord(const char *Cmd) {
949 uint8_t addr;
950 uint32_t pwd;
951 bool usePwd = false;
952 uint8_t ctmp = param_getchar(Cmd, 0);
953 if ( strlen(Cmd) == 0 || ctmp == 'H' || ctmp == 'h' ) return usage_lf_em_read();
954
955 addr = param_get8ex(Cmd, 0, 50, 10);
956 // for now use default input of 1 as invalid (unlikely 1 will be a valid password...)
957 pwd = param_get32ex(Cmd, 1, 1, 16);
47af8c5f 958
e39a92bb 959 if ( (addr > 15) ) {
960 PrintAndLog("Address must be between 0 and 15");
961 return 1;
962 }
4c6ccc2b 963 if ( pwd == 1 ) {
e39a92bb 964 PrintAndLog("Reading address %02u", addr);
4c6ccc2b 965 } else {
e39a92bb 966 usePwd = true;
967 PrintAndLog("Reading address %02u | password %08X", addr, pwd);
968 }
61500621 969
4c6ccc2b 970 return EM4x05ReadWord(addr, pwd, usePwd);
54a942b0 971}
972
e39a92bb 973int usage_lf_em_dump(void) {
974 PrintAndLog("Dump EM4x05/EM4x69. Tag must be on antenna. ");
975 PrintAndLog("");
976 PrintAndLog("Usage: lf em 4x05dump [h] <pwd>");
977 PrintAndLog("Options:");
978 PrintAndLog(" h - this help");
979 PrintAndLog(" pwd - password (hex) (optional)");
980 PrintAndLog("samples:");
981 PrintAndLog(" lf em 4x05dump");
982 PrintAndLog(" lf em 4x05dump 11223344");
983 return 0;
984}
985
986int CmdEM4x05dump(const char *Cmd) {
987 uint8_t addr = 0;
988 uint32_t pwd;
989 bool usePwd = false;
990 uint8_t ctmp = param_getchar(Cmd, 0);
991 if ( ctmp == 'H' || ctmp == 'h' ) return usage_lf_em_dump();
992
993 // for now use default input of 1 as invalid (unlikely 1 will be a valid password...)
994 pwd = param_get32ex(Cmd, 0, 1, 16);
47af8c5f 995
e39a92bb 996 if ( pwd != 1 ) {
997 usePwd = true;
998 }
999 int success = 1;
1000 for (; addr < 16; addr++) {
1001 if (addr == 2) {
1002 if (usePwd) {
34212c66 1003 PrintAndLog(" PWD Address %02u | %08X",addr,pwd);
e39a92bb 1004 } else {
34212c66 1005 PrintAndLog(" PWD Address 02 | cannot read");
e39a92bb 1006 }
1007 } else {
1008 success &= EM4x05ReadWord(addr, pwd, usePwd);
1009 }
1010 }
1011
1012 return success;
1013}
1014
1015
7666f460 1016int usage_lf_em_write(void) {
1017 PrintAndLog("Write EM4x05/EM4x69. Tag must be on antenna. ");
1018 PrintAndLog("");
4ab135c0 1019 PrintAndLog("Usage: lf em 4x05writeword [h] a <address> d <data> p <pwd> [s] [i]");
7666f460 1020 PrintAndLog("Options:");
4ab135c0 1021 PrintAndLog(" h - this help");
1022 PrintAndLog(" a <address> - memory address to write to. (0-15)");
47af8c5f 1023 PrintAndLog(" d <data> - data to write (hex)");
4ab135c0 1024 PrintAndLog(" p <pwd> - password (hex) (optional)");
1025 PrintAndLog(" s - swap the data bit order before write");
1026 PrintAndLog(" i - invert the data bits before write");
7666f460 1027 PrintAndLog("samples:");
4ab135c0 1028 PrintAndLog(" lf em 4x05writeword a 5 d 11223344");
1029 PrintAndLog(" lf em 4x05writeword a 5 p deadc0de d 11223344 s i");
7666f460 1030 return 0;
1031}
59f726c9 1032
6a772a12 1033// note: em4x05 doesn't have a way to invert data output so we must invert the data prior to writing
1034// it if invertion is needed. (example FSK2a vs FSK)
1035// also em4x05 requires swapping word data when compared to the data used for t55xx chips.
4ab135c0 1036int EM4x05WriteWord(uint8_t addr, uint32_t data, uint32_t pwd, bool usePwd, bool swap, bool invert) {
1037 if (swap) data = SwapBits(data, 32);
713045f8 1038
4ab135c0 1039 if (invert) data ^= 0xFFFFFFFF;
713045f8 1040
e39a92bb 1041 if ( (addr > 15) ) {
7666f460 1042 PrintAndLog("Address must be between 0 and 15");
51b614aa 1043 return -1;
23f0a7d8 1044 }
4ab135c0 1045 if ( !usePwd ) {
1046 PrintAndLog("Writing address %d data %08X", addr, data);
1047 } else {
713045f8 1048 PrintAndLog("Writing address %d data %08X using password %08X", addr, data, pwd);
7666f460 1049 }
713045f8 1050
7666f460 1051 uint16_t flag = (addr << 8 ) | usePwd;
713045f8 1052
7666f460 1053 UsbCommand c = {CMD_EM4X_WRITE_WORD, {flag, data, pwd}};
1054 clearCommandBuffer();
23f0a7d8 1055 SendCommand(&c);
713045f8 1056 UsbCommand resp;
e39a92bb 1057 if (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)){
7666f460 1058 PrintAndLog("Error occurred, device did not respond during write operation.");
1059 return -1;
1060 }
4c6ccc2b 1061 if ( !downloadSamplesEM() ) {
1062 return -1;
7666f460 1063 }
713045f8 1064 //check response for 00001010 for write confirmation!
59f726c9 1065 //attempt demod:
e39a92bb 1066 uint32_t dummy = 0;
1067 int result = demodEM4x05resp(&dummy,false);
59f726c9 1068 if (result == 1) {
1069 PrintAndLog("Write Verified");
34ff8985 1070 } else {
1071 PrintAndLog("Write could not be verified");
59f726c9 1072 }
1073 return result;
54a942b0 1074}
1075
4ab135c0 1076int CmdEM4x05WriteWord(const char *Cmd) {
1077 bool errors = false;
1078 bool usePwd = false;
1079 uint32_t data = 0xFFFFFFFF;
1080 uint32_t pwd = 0xFFFFFFFF;
1081 bool swap = false;
1082 bool invert = false;
1083 uint8_t addr = 16; // default to invalid address
6a772a12 1084 bool gotData = false;
4ab135c0 1085 char cmdp = 0;
1086 while(param_getchar(Cmd, cmdp) != 0x00)
1087 {
1088 switch(param_getchar(Cmd, cmdp))
1089 {
1090 case 'h':
1091 case 'H':
1092 return usage_lf_em_write();
1093 case 'a':
1094 case 'A':
1095 addr = param_get8ex(Cmd, cmdp+1, 16, 10);
1096 cmdp += 2;
1097 break;
1098 case 'd':
1099 case 'D':
1100 data = param_get32ex(Cmd, cmdp+1, 0, 16);
6a772a12 1101 gotData = true;
4ab135c0 1102 cmdp += 2;
1103 break;
1104 case 'i':
1105 case 'I':
1106 invert = true;
1107 cmdp++;
1108 break;
1109 case 'p':
1110 case 'P':
1111 pwd = param_get32ex(Cmd, cmdp+1, 1, 16);
1112 if (pwd == 1) {
1113 PrintAndLog("invalid pwd");
1114 errors = true;
1115 }
1116 usePwd = true;
1117 cmdp += 2;
1118 break;
1119 case 's':
1120 case 'S':
1121 swap = true;
1122 cmdp++;
1123 break;
1124 default:
1125 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
1126 errors = true;
1127 break;
1128 }
1129 if(errors) break;
1130 }
1131 //Validations
1132 if(errors) return usage_lf_em_write();
1133
1134 if ( strlen(Cmd) == 0 ) return usage_lf_em_write();
1135
6a772a12 1136 if (!gotData) {
1137 PrintAndLog("You must enter the data you want to write");
1138 return usage_lf_em_write();
1139 }
4ab135c0 1140 return EM4x05WriteWord(addr, data, pwd, usePwd, swap, invert);
1141}
1142
0a85edf4 1143void printEM4x05config(uint32_t wordData) {
4ab135c0 1144 uint16_t datarate = EM4x05_GET_BITRATE(wordData);
0a85edf4 1145 uint8_t encoder = ((wordData >> 6) & 0xF);
1146 char enc[14];
1147 memset(enc,0,sizeof(enc));
1148
1149 uint8_t PSKcf = (wordData >> 10) & 0x3;
1150 char cf[10];
1151 memset(cf,0,sizeof(cf));
1152 uint8_t delay = (wordData >> 12) & 0x3;
1153 char cdelay[33];
1154 memset(cdelay,0,sizeof(cdelay));
4ab135c0 1155 uint8_t numblks = EM4x05_GET_NUM_BLOCKS(wordData);
1156 uint8_t LWR = numblks+5-1; //last word read
0a85edf4 1157 switch (encoder) {
1158 case 0: snprintf(enc,sizeof(enc),"NRZ"); break;
1159 case 1: snprintf(enc,sizeof(enc),"Manchester"); break;
1160 case 2: snprintf(enc,sizeof(enc),"Biphase"); break;
1161 case 3: snprintf(enc,sizeof(enc),"Miller"); break;
1162 case 4: snprintf(enc,sizeof(enc),"PSK1"); break;
1163 case 5: snprintf(enc,sizeof(enc),"PSK2"); break;
1164 case 6: snprintf(enc,sizeof(enc),"PSK3"); break;
1165 case 7: snprintf(enc,sizeof(enc),"Unknown"); break;
1166 case 8: snprintf(enc,sizeof(enc),"FSK1"); break;
1167 case 9: snprintf(enc,sizeof(enc),"FSK2"); break;
1168 default: snprintf(enc,sizeof(enc),"Unknown"); break;
1169 }
1170
1171 switch (PSKcf) {
1172 case 0: snprintf(cf,sizeof(cf),"RF/2"); break;
1173 case 1: snprintf(cf,sizeof(cf),"RF/8"); break;
1174 case 2: snprintf(cf,sizeof(cf),"RF/4"); break;
1175 case 3: snprintf(cf,sizeof(cf),"unknown"); break;
1176 }
1177
1178 switch (delay) {
1179 case 0: snprintf(cdelay, sizeof(cdelay),"no delay"); break;
1180 case 1: snprintf(cdelay, sizeof(cdelay),"BP/8 or 1/8th bit period delay"); break;
1181 case 2: snprintf(cdelay, sizeof(cdelay),"BP/4 or 1/4th bit period delay"); break;
1182 case 3: snprintf(cdelay, sizeof(cdelay),"no delay"); break;
1183 }
4ab135c0 1184 uint8_t readLogin = (wordData & EM4x05_READ_LOGIN_REQ)>>18;
1185 uint8_t readHKL = (wordData & EM4x05_READ_HK_LOGIN_REQ)>>19;
1186 uint8_t writeLogin = (wordData & EM4x05_WRITE_LOGIN_REQ)>>20;
1187 uint8_t writeHKL = (wordData & EM4x05_WRITE_HK_LOGIN_REQ)>>21;
1188 uint8_t raw = (wordData & EM4x05_READ_AFTER_WRITE)>>22;
1189 uint8_t disable = (wordData & EM4x05_DISABLE_ALLOWED)>>23;
1190 uint8_t rtf = (wordData & EM4x05_READER_TALK_FIRST)>>24;
1191 uint8_t pigeon = (wordData & (1<<26))>>26;
0a85edf4 1192 PrintAndLog("ConfigWord: %08X (Word 4)\n", wordData);
4ab135c0 1193 PrintAndLog("Config Breakdown:");
33a1fe96 1194 PrintAndLog(" Data Rate: %02u | RF/%u", wordData & 0x3F, datarate);
0a85edf4 1195 PrintAndLog(" Encoder: %u | %s", encoder, enc);
1196 PrintAndLog(" PSK CF: %u | %s", PSKcf, cf);
1197 PrintAndLog(" Delay: %u | %s", delay, cdelay);
4ab135c0 1198 PrintAndLog(" LastWordR: %02u | Address of last word for default read - meaning %u blocks are output", LWR, numblks);
47af8c5f
F
1199 PrintAndLog(" ReadLogin: %u | Read Login is %s", readLogin, readLogin ? "Required" : "Not Required");
1200 PrintAndLog(" ReadHKL: %u | Read Housekeeping Words Login is %s", readHKL, readHKL ? "Required" : "Not Required");
1201 PrintAndLog("WriteLogin: %u | Write Login is %s", writeLogin, writeLogin ? "Required" : "Not Required");
1202 PrintAndLog(" WriteHKL: %u | Write Housekeeping Words Login is %s", writeHKL, writeHKL ? "Required" : "Not Required");
4ab135c0 1203 PrintAndLog(" R.A.W.: %u | Read After Write is %s", raw, raw ? "On" : "Off");
1204 PrintAndLog(" Disable: %u | Disable Command is %s", disable, disable ? "Accepted" : "Not Accepted");
1205 PrintAndLog(" R.T.F.: %u | Reader Talk First is %s", rtf, rtf ? "Enabled" : "Disabled");
1206 PrintAndLog(" Pigeon: %u | Pigeon Mode is %s\n", pigeon, pigeon ? "Enabled" : "Disabled");
0a85edf4 1207}
1208
fa1e00cf 1209void printEM4x05info(uint8_t chipType, uint8_t cap, uint16_t custCode, uint32_t serial) {
1210 switch (chipType) {
0a85edf4 1211 case 9: PrintAndLog("\n Chip Type: %u | EM4305", chipType); break;
1212 case 4: PrintAndLog(" Chip Type: %u | Unknown", chipType); break;
1213 case 2: PrintAndLog(" Chip Type: %u | EM4469", chipType); break;
fa1e00cf 1214 //add more here when known
0a85edf4 1215 default: PrintAndLog(" Chip Type: %u Unknown", chipType); break;
fa1e00cf 1216 }
1217
1218 switch (cap) {
0a85edf4 1219 case 3: PrintAndLog(" Cap Type: %u | 330pF",cap); break;
1220 case 2: PrintAndLog(" Cap Type: %u | %spF",cap, (chipType==2)? "75":"210"); break;
1221 case 1: PrintAndLog(" Cap Type: %u | 250pF",cap); break;
1222 case 0: PrintAndLog(" Cap Type: %u | no resonant capacitor",cap); break;
1223 default: PrintAndLog(" Cap Type: %u | unknown",cap); break;
fa1e00cf 1224 }
1225
0a85edf4 1226 PrintAndLog(" Cust Code: %03u | %s", custCode, (custCode == 0x200) ? "Default": "Unknown");
fa1e00cf 1227 if (serial != 0) {
0a85edf4 1228 PrintAndLog("\n Serial #: %08X\n", serial);
fa1e00cf 1229 }
1230}
1231
34ff8985 1232void printEM4x05ProtectionBits(uint32_t wordData) {
33a1fe96 1233 for (uint8_t i = 0; i < 15; i++) {
1234 PrintAndLog(" Word: %02u | %s", i, (((1 << i) & wordData ) || i < 2) ? "Is Write Locked" : "Is Not Write Locked");
1235 if (i==14) {
1236 PrintAndLog(" Word: %02u | %s", i+1, (((1 << i) & wordData ) || i < 2) ? "Is Write Locked" : "Is Not Write Locked");
1237 }
34ff8985 1238 }
1239}
1240
fa1e00cf 1241//quick test for EM4x05/EM4x69 tag
1242bool EM4x05Block0Test(uint32_t *wordData) {
1243 if (EM4x05ReadWord_ext(0,0,false,wordData) == 1) {
1244 return true;
1245 }
1246 return false;
1247}
1248
1249int CmdEM4x05info(const char *Cmd) {
1250 //uint8_t addr = 0;
0a85edf4 1251 uint32_t pwd;
fa1e00cf 1252 uint32_t wordData = 0;
0a85edf4 1253 bool usePwd = false;
fa1e00cf 1254 uint8_t ctmp = param_getchar(Cmd, 0);
1255 if ( ctmp == 'H' || ctmp == 'h' ) return usage_lf_em_dump();
1256
1257 // for now use default input of 1 as invalid (unlikely 1 will be a valid password...)
0a85edf4 1258 pwd = param_get32ex(Cmd, 0, 1, 16);
47af8c5f 1259
0a85edf4 1260 if ( pwd != 1 ) {
1261 usePwd = true;
1262 }
fa1e00cf 1263
0a85edf4 1264 // read word 0 (chip info)
1265 // block 0 can be read even without a password.
47af8c5f 1266 if ( !EM4x05Block0Test(&wordData) )
fa1e00cf 1267 return -1;
47af8c5f 1268
fa1e00cf 1269 uint8_t chipType = (wordData >> 1) & 0xF;
1270 uint8_t cap = (wordData >> 5) & 3;
1271 uint16_t custCode = (wordData >> 9) & 0x3FF;
47af8c5f 1272
0a85edf4 1273 // read word 1 (serial #) doesn't need pwd
fa1e00cf 1274 wordData = 0;
1275 if (EM4x05ReadWord_ext(1, 0, false, &wordData) != 1) {
1276 //failed, but continue anyway...
1277 }
1278 printEM4x05info(chipType, cap, custCode, wordData);
1279
47af8c5f 1280 // read word 4 (config block)
fa1e00cf 1281 // needs password if one is set
0a85edf4 1282 wordData = 0;
1283 if ( EM4x05ReadWord_ext(4, pwd, usePwd, &wordData) != 1 ) {
1284 //failed
4ab135c0 1285 PrintAndLog("Config block read failed - might be password protected.");
0a85edf4 1286 return 0;
1287 }
1288 printEM4x05config(wordData);
34ff8985 1289
1290 // read word 14 and 15 to see which is being used for the protection bits
1291 wordData = 0;
1292 if ( EM4x05ReadWord_ext(14, pwd, usePwd, &wordData) != 1 ) {
1293 //failed
1294 return 0;
1295 }
1296 // if status bit says this is not the used protection word
1297 if (!(wordData & 0x8000)) {
1298 if ( EM4x05ReadWord_ext(15, pwd, usePwd, &wordData) != 1 ) {
1299 //failed
1300 return 0;
1301 }
1302 }
1303 if (!(wordData & 0x8000)) {
1304 //something went wrong
1305 return 0;
1306 }
1307 printEM4x05ProtectionBits(wordData);
1308
0a85edf4 1309 return 1;
fa1e00cf 1310}
1311
1312
2d4eae76 1313static command_t CommandTable[] =
7fe9b0b7 1314{
35aa230e 1315 {"help", CmdHelp, 1, "This help"},
47af8c5f 1316 {"410xread", CmdEMdemodASK, 0, "[findone] -- Extract ID from EM410x tag (option 0 for continuous loop, 1 for only 1 tag)"},
35aa230e 1317 {"410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"},
1318 {"410xsim", CmdEM410xSim, 0, "<UID> [clock rate] -- Simulate EM410x tag"},
50acfd37 1319 {"410xbrute", CmdEM410xBrute, 0, "ids.txt [clock rate] -- Bruteforcing by simulating EM410x tags (1 UID/s)"},
e39a92bb 1320 {"410xwatch", CmdEM410xWatch, 0, "['h'] -- Watches for EM410x 125/134 kHz tags (option 'h' for 134)"},
1321 {"410xspoof", CmdEM410xWatchnSpoof, 0, "['h'] --- Watches for EM410x 125/134 kHz tags, and replays them. (option 'h' for 134)" },
1322 {"410xwrite", CmdEM410xWrite, 0, "<UID> <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"},
35aa230e 1323 {"4x05dump", CmdEM4x05dump, 0, "(pwd) -- Read EM4x05/EM4x69 all word data"},
1324 {"4x05info", CmdEM4x05info, 0, "(pwd) -- Get info from EM4x05/EM4x69 tag"},
1325 {"4x05readword", CmdEM4x05ReadWord, 0, "<Word> (pwd) -- Read EM4x05/EM4x69 word data"},
fa1e00cf 1326 {"4x05writeword", CmdEM4x05WriteWord, 0, "<Word> <data> (pwd) -- Write EM4x05/EM4x69 word data"},
35aa230e 1327 {"4x50read", CmdEM4x50Read, 1, "demod data from EM4x50 tag from the graph buffer"},
23f0a7d8 1328 {NULL, NULL, 0, NULL}
7fe9b0b7 1329};
1330
1331int CmdLFEM4X(const char *Cmd)
1332{
23f0a7d8 1333 CmdsParse(CommandTable, Cmd);
1334 return 0;
7fe9b0b7 1335}
1336
1337int CmdHelp(const char *Cmd)
1338{
23f0a7d8 1339 CmdsHelp(CommandTable);
1340 return 0;
7fe9b0b7 1341}
Impressum, Datenschutz