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