]> git.zerfleddert.de Git - proxmark3-svn/blame - client/cmddata.c
ADD: @marshmellow42 's fixed version of the ISO11784 FDX-B
[proxmark3-svn] / client / cmddata.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// Data and Graph commands
9//-----------------------------------------------------------------------------
10
7fe9b0b7 11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <limits.h>
902cb3c0 15#include "proxmark3.h"
7fe9b0b7 16#include "data.h"
17#include "ui.h"
18#include "graph.h"
19#include "cmdparser.h"
d51b2eda 20#include "util.h"
7fe9b0b7 21#include "cmdmain.h"
22#include "cmddata.h"
7db5f1ca 23#include "lfdemod.h"
31abe49f 24#include "usb_cmd.h"
73d04bb4 25#include "crc.h"
ad6219fc 26#include "crc16.h"
27
31abe49f 28
4118b74d 29uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN];
ec75f5c1 30uint8_t g_debugMode;
2b3af97d 31size_t DemodBufferLen;
7fe9b0b7 32static int CmdHelp(const char *Cmd);
33
4118b74d 34//set the demod buffer with given array of binary (one bit per byte)
35//by marshmellow
ec75f5c1 36void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx)
4118b74d 37{
13d77ef9 38 if (buff == NULL)
39 return;
40
41 if ( size >= MAX_DEMOD_BUF_LEN)
42 size = MAX_DEMOD_BUF_LEN;
43
ec75f5c1 44 size_t i = 0;
45 for (; i < size; i++){
46 DemodBuffer[i]=buff[startIdx++];
ba1a299c 47 }
48 DemodBufferLen=size;
49 return;
4118b74d 50}
51
ec75f5c1 52int CmdSetDebugMode(const char *Cmd)
53{
e0165dcf 54 int demod=0;
55 sscanf(Cmd, "%i", &demod);
56 g_debugMode=(uint8_t)demod;
57 return 1;
ec75f5c1 58}
59
2d2f7d19 60int usage_data_printdemodbuf(){
61 PrintAndLog("Usage: data printdemodbuffer x o <offset>");
62 PrintAndLog("Options: ");
63 PrintAndLog(" h This help");
64 PrintAndLog(" x output in hex (omit for binary output)");
65 PrintAndLog(" o <offset> enter offset in # of bits");
66 return 0;
67}
68
4118b74d 69//by marshmellow
abd6112f 70void printDemodBuff(void)
4118b74d 71{
ba1a299c 72 int bitLen = DemodBufferLen;
2767fc02 73 if (bitLen<1) {
ba1a299c 74 PrintAndLog("no bits found in demod buffer");
75 return;
76 }
77 if (bitLen>512) bitLen=512; //max output to 512 bits if we have more - should be plenty
e0165dcf 78
2767fc02 79 char *bin = sprint_bin_break(DemodBuffer,bitLen,16);
80 PrintAndLog("%s",bin);
81
ba1a299c 82 return;
4118b74d 83}
84
8d960002 85int CmdPrintDemodBuff(const char *Cmd)
86{
2d2f7d19 87 char hex[512]={0x00};
88 bool hexMode = false;
89 bool errors = false;
90 uint8_t offset = 0;
91 char cmdp = 0;
92 while(param_getchar(Cmd, cmdp) != 0x00)
93 {
94 switch(param_getchar(Cmd, cmdp))
95 {
96 case 'h':
97 case 'H':
98 return usage_data_printdemodbuf();
99 case 'x':
100 case 'X':
101 hexMode = true;
102 cmdp++;
103 break;
104 case 'o':
105 case 'O':
106 offset = param_get8(Cmd, cmdp+1);
107 if (!offset) errors = true;
108 cmdp += 2;
109 break;
110 default:
111 PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
112 errors = true;
113 break;
114 }
115 if(errors) break;
e0165dcf 116 }
2d2f7d19 117 //Validations
118 if(errors) return usage_data_printdemodbuf();
119
120 int numBits = (DemodBufferLen-offset) & 0x7FC; //make sure we don't exceed our string
121
122 if (hexMode){
123 char *buf = (char *) (DemodBuffer + offset);
124 numBits = binarraytohex(hex, buf, numBits);
e0165dcf 125 if (numBits==0) return 0;
2d2f7d19 126 PrintAndLog("DemodBuffer: %s",hex);
e0165dcf 127 } else {
2d2f7d19 128 //setDemodBuf(DemodBuffer, DemodBufferLen-offset, offset);
129 char *bin = sprint_bin_break(DemodBuffer+offset,numBits,16);
130 PrintAndLog("DemodBuffer:\n%s",bin);
e0165dcf 131 }
132 return 1;
8d960002 133}
7fe9b0b7 134
2767fc02 135//by marshmellow
78f5b1a7 136//this function strictly converts >1 to 1 and <1 to 0 for each sample in the graphbuffer
137int CmdGetBitStream(const char *Cmd)
138{
e0165dcf 139 int i;
140 CmdHpf(Cmd);
141 for (i = 0; i < GraphTraceLen; i++) {
142 if (GraphBuffer[i] >= 1) {
143 GraphBuffer[i] = 1;
144 } else {
145 GraphBuffer[i] = 0;
146 }
147 }
148 RepaintGraphWindow();
149 return 0;
78f5b1a7 150}
151
d5a72d2f 152//by marshmellow
abd6112f 153//print 64 bit EM410x ID in multiple formats
b41534d1 154void printEM410x(uint32_t hi, uint64_t id)
2fc2150e 155{
e0165dcf 156 if (id || hi){
157 uint64_t iii=1;
158 uint64_t id2lo=0;
159 uint32_t ii=0;
160 uint32_t i=0;
161 for (ii=5; ii>0;ii--){
162 for (i=0;i<8;i++){
163 id2lo=(id2lo<<1LL) | ((id & (iii << (i+((ii-1)*8)))) >> (i+((ii-1)*8)));
164 }
165 }
166 if (hi){
167 //output 88 bit em id
2767fc02 168 PrintAndLog("\nEM TAG ID : %06X%016llX", hi, id);
e0165dcf 169 } else{
170 //output 40 bit em id
2767fc02 171 PrintAndLog("\nEM TAG ID : %010llX", id);
172 PrintAndLog("Unique TAG ID : %010llX", id2lo);
e0165dcf 173 PrintAndLog("\nPossible de-scramble patterns");
174 PrintAndLog("HoneyWell IdentKey {");
175 PrintAndLog("DEZ 8 : %08lld",id & 0xFFFFFF);
176 PrintAndLog("DEZ 10 : %010lld",id & 0xFFFFFFFF);
177 PrintAndLog("DEZ 5.5 : %05lld.%05lld",(id>>16LL) & 0xFFFF,(id & 0xFFFF));
178 PrintAndLog("DEZ 3.5A : %03lld.%05lld",(id>>32ll),(id & 0xFFFF));
179 PrintAndLog("DEZ 3.5B : %03lld.%05lld",(id & 0xFF000000) >> 24,(id & 0xFFFF));
180 PrintAndLog("DEZ 3.5C : %03lld.%05lld",(id & 0xFF0000) >> 16,(id & 0xFFFF));
181 PrintAndLog("DEZ 14/IK2 : %014lld",id);
182 PrintAndLog("DEZ 15/IK3 : %015lld",id2lo);
183 PrintAndLog("DEZ 20/ZK : %02lld%02lld%02lld%02lld%02lld%02lld%02lld%02lld%02lld%02lld",
184 (id2lo & 0xf000000000) >> 36,
185 (id2lo & 0x0f00000000) >> 32,
186 (id2lo & 0x00f0000000) >> 28,
187 (id2lo & 0x000f000000) >> 24,
188 (id2lo & 0x0000f00000) >> 20,
189 (id2lo & 0x00000f0000) >> 16,
190 (id2lo & 0x000000f000) >> 12,
191 (id2lo & 0x0000000f00) >> 8,
192 (id2lo & 0x00000000f0) >> 4,
193 (id2lo & 0x000000000f)
194 );
195 uint64_t paxton = (((id>>32) << 24) | (id & 0xffffff)) + 0x143e00;
196 PrintAndLog("}\nOther : %05lld_%03lld_%08lld",(id&0xFFFF),((id>>16LL) & 0xFF),(id & 0xFFFFFF));
2767fc02 197 PrintAndLog("Pattern Paxton : %lld [0x%llX]", paxton, paxton);
e0165dcf 198
199 uint32_t p1id = (id & 0xFFFFFF);
200 uint8_t arr[32] = {0x00};
201 int i =0;
202 int j = 23;
203 for (; i < 24; ++i, --j ){
204 arr[i] = (p1id >> i) & 1;
205 }
206
207 uint32_t p1 = 0;
208
209 p1 |= arr[23] << 21;
210 p1 |= arr[22] << 23;
211 p1 |= arr[21] << 20;
212 p1 |= arr[20] << 22;
213
214 p1 |= arr[19] << 18;
215 p1 |= arr[18] << 16;
216 p1 |= arr[17] << 19;
217 p1 |= arr[16] << 17;
218
219 p1 |= arr[15] << 13;
220 p1 |= arr[14] << 15;
221 p1 |= arr[13] << 12;
222 p1 |= arr[12] << 14;
223
224 p1 |= arr[11] << 6;
225 p1 |= arr[10] << 2;
226 p1 |= arr[9] << 7;
227 p1 |= arr[8] << 1;
228
229 p1 |= arr[7] << 0;
230 p1 |= arr[6] << 8;
231 p1 |= arr[5] << 11;
232 p1 |= arr[4] << 3;
233
234 p1 |= arr[3] << 10;
235 p1 |= arr[2] << 4;
236 p1 |= arr[1] << 5;
237 p1 |= arr[0] << 9;
2767fc02 238 PrintAndLog("Pattern 1 : %d [0x%X]", p1, p1);
e0165dcf 239
240 uint16_t sebury1 = id & 0xFFFF;
241 uint8_t sebury2 = (id >> 16) & 0x7F;
242 uint32_t sebury3 = id & 0x7FFFFF;
2767fc02 243 PrintAndLog("Pattern Sebury : %d %d %d [0x%X 0x%X 0x%X]", sebury1, sebury2, sebury3, sebury1, sebury2, sebury3);
e0165dcf 244 }
245 }
246 return;
eb191de6 247}
248
fef74fdc 249int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo )
13d77ef9 250{
fef74fdc 251 size_t idx = 0;
252 size_t BitLen = DemodBufferLen;
253 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
254 memcpy(BitStream, DemodBuffer, BitLen);
255 if (Em410xDecode(BitStream, &BitLen, &idx, hi, lo)){
256 //set GraphBuffer for clone or sim command
257 setDemodBuf(BitStream, BitLen, idx);
e0165dcf 258 if (g_debugMode){
fef74fdc 259 PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen);
e0165dcf 260 printDemodBuff();
261 }
fef74fdc 262 if (verbose){
263 PrintAndLog("EM410x pattern found: ");
264 printEM410x(*hi, *lo);
265 }
e0165dcf 266 return 1;
267 }
268 return 0;
13d77ef9 269}
fef74fdc 270
271int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose)
272{
273 if (!ASKDemod(Cmd, FALSE, FALSE, 1)) return 0;
274 return AskEm410xDecode(verbose, hi, lo);
275}
276
e888ed8e 277//by marshmellow
e770c648 278//takes 3 arguments - clock, invert and maxErr as integers
279//attempts to demodulate ask while decoding manchester
280//prints binary found and saves in graphbuffer for further commands
281int CmdAskEM410xDemod(const char *Cmd)
282{
e0165dcf 283 char cmdp = param_getchar(Cmd, 0);
284 if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') {
285 PrintAndLog("Usage: data askem410xdemod [clock] <0|1> [maxError]");
286 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
287 PrintAndLog(" <invert>, 1 for invert output");
288 PrintAndLog(" [set maximum allowed errors], default = 100.");
289 PrintAndLog("");
290 PrintAndLog(" sample: data askem410xdemod = demod an EM410x Tag ID from GraphBuffer");
291 PrintAndLog(" : data askem410xdemod 32 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/32");
292 PrintAndLog(" : data askem410xdemod 32 1 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/32 and inverting data");
293 PrintAndLog(" : data askem410xdemod 1 = demod an EM410x Tag ID from GraphBuffer while inverting data");
294 PrintAndLog(" : data askem410xdemod 64 1 0 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/64 and inverting data and allowing 0 demod errors");
295 return 0;
296 }
e0165dcf 297 uint64_t lo = 0;
fef74fdc 298 uint32_t hi = 0;
299 return AskEm410xDemod(Cmd, &hi, &lo, true);
e770c648 300}
301
fef74fdc 302//by marshmellow
303//Cmd Args: Clock, invert, maxErr, maxLen as integers and amplify as char == 'a'
304// (amp may not be needed anymore)
305//verbose will print results and demoding messages
306//emSearch will auto search for EM410x format in bitstream
307//askType switches decode: ask/raw = 0, ask/manchester = 1
308int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType)
e888ed8e 309{
e0165dcf 310 int invert=0;
311 int clk=0;
312 int maxErr=100;
fef74fdc 313 int maxLen=0;
314 uint8_t askAmp = 0;
315 char amp = param_getchar(Cmd, 0);
e0165dcf 316 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
fef74fdc 317 sscanf(Cmd, "%i %i %i %i %c", &clk, &invert, &maxErr, &maxLen, &amp);
318 if (!maxLen) maxLen = 512*64;
e0165dcf 319 if (invert != 0 && invert != 1) {
320 PrintAndLog("Invalid argument: %s", Cmd);
321 return 0;
322 }
323 if (clk==1){
324 invert=1;
325 clk=0;
326 }
fef74fdc 327 if (amp == 'a' || amp == 'A') askAmp=1;
e0165dcf 328 size_t BitLen = getFromGraphBuf(BitStream);
2767fc02 329 if (g_debugMode) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen);
fef74fdc 330 if (BitLen<255) return 0;
23f0a7d8 331 if (maxLen<BitLen && maxLen != 0) BitLen = maxLen;
fef74fdc 332
333 int errCnt = askdemod(BitStream, &BitLen, &clk, &invert, maxErr, askAmp, askType);
334 if (errCnt<0 || BitLen<16){ //if fatal error (or -1)
2767fc02 335 if (g_debugMode) PrintAndLog("DEBUG: no data found %d, errors:%d, bitlen:%d, clock:%d",errCnt,invert,BitLen,clk);
e0165dcf 336 return 0;
337 }
2767fc02 338 if (errCnt>maxErr){
339 if (g_debugMode) PrintAndLog("DEBUG: Too many errors found, errors:%d, bits:%d, clock:%d",errCnt, BitLen, clk);
340 return 0;
341 }
342 if (verbose || g_debugMode) PrintAndLog("\nUsing Clock:%d, Invert:%d, Bits Found:%d",clk,invert,BitLen);
e0165dcf 343
344 //output
e0165dcf 345 setDemodBuf(BitStream,BitLen,0);
fef74fdc 346 if (verbose || g_debugMode){
347 if (errCnt>0) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt);
348 if (askType) PrintAndLog("ASK/Manchester decoded bitstream:");
349 else PrintAndLog("ASK/Raw decoded bitstream:");
350 // Now output the bitstream to the scrollback by line of 16 bits
351 printDemodBuff();
352
353 }
354 uint64_t lo = 0;
355 uint32_t hi = 0;
e0165dcf 356 if (emSearch){
fef74fdc 357 AskEm410xDecode(true, &hi, &lo);
e0165dcf 358 }
359 return 1;
eb191de6 360}
361
4ac906d1 362//by marshmellow
fef74fdc 363//takes 5 arguments - clock, invert, maxErr, maxLen as integers and amplify as char == 'a'
4ac906d1 364//attempts to demodulate ask while decoding manchester
365//prints binary found and saves in graphbuffer for further commands
366int Cmdaskmandemod(const char *Cmd)
367{
e0165dcf 368 char cmdp = param_getchar(Cmd, 0);
fef74fdc 369 if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') {
370 PrintAndLog("Usage: data rawdemod am [clock] <invert> [maxError] [maxLen] [amplify]");
371 PrintAndLog(" [set clock as integer] optional, if not set, autodetect");
372 PrintAndLog(" <invert>, 1 to invert output");
373 PrintAndLog(" [set maximum allowed errors], default = 100");
374 PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)");
375 PrintAndLog(" <amplify>, 'a' to attempt demod with ask amplification, default = no amp");
e0165dcf 376 PrintAndLog("");
377 PrintAndLog(" sample: data rawdemod am = demod an ask/manchester tag from GraphBuffer");
378 PrintAndLog(" : data rawdemod am 32 = demod an ask/manchester tag from GraphBuffer using a clock of RF/32");
379 PrintAndLog(" : data rawdemod am 32 1 = demod an ask/manchester tag from GraphBuffer using a clock of RF/32 and inverting data");
380 PrintAndLog(" : data rawdemod am 1 = demod an ask/manchester tag from GraphBuffer while inverting data");
381 PrintAndLog(" : data rawdemod am 64 1 0 = demod an ask/manchester tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
382 return 0;
383 }
fef74fdc 384 return ASKDemod(Cmd, TRUE, TRUE, 1);
4ac906d1 385}
386
eb191de6 387//by marshmellow
d5a72d2f 388//manchester decode
eb191de6 389//stricktly take 10 and 01 and convert to 0 and 1
390int Cmdmandecoderaw(const char *Cmd)
391{
e0165dcf 392 int i =0;
393 int errCnt=0;
394 size_t size=0;
fef74fdc 395 int invert=0;
e0165dcf 396 size_t maxErr = 20;
397 char cmdp = param_getchar(Cmd, 0);
1f918317 398 if (strlen(Cmd) > 5 || cmdp == 'h' || cmdp == 'H') {
fef74fdc 399 PrintAndLog("Usage: data manrawdecode [invert] [maxErr]");
e0165dcf 400 PrintAndLog(" Takes 10 and 01 and converts to 0 and 1 respectively");
401 PrintAndLog(" --must have binary sequence in demodbuffer (run data askrawdemod first)");
fef74fdc 402 PrintAndLog(" [invert] invert output");
1f918317 403 PrintAndLog(" [maxErr] set number of errors allowed (default = 20)");
e0165dcf 404 PrintAndLog("");
405 PrintAndLog(" sample: data manrawdecode = decode manchester bitstream from the demodbuffer");
406 return 0;
407 }
408 if (DemodBufferLen==0) return 0;
409 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
410 int high=0,low=0;
411 for (;i<DemodBufferLen;++i){
412 if (DemodBuffer[i]>high) high=DemodBuffer[i];
413 else if(DemodBuffer[i]<low) low=DemodBuffer[i];
414 BitStream[i]=DemodBuffer[i];
415 }
1f918317 416 if (high>7 || low <0 ){
2767fc02 417 PrintAndLog("Error: please raw demod the wave first then manchester raw decode");
e0165dcf 418 return 0;
419 }
1f918317 420
fef74fdc 421 sscanf(Cmd, "%i %i", &invert, &maxErr);
e0165dcf 422 size=i;
fef74fdc 423 errCnt=manrawdecode(BitStream, &size, invert);
e0165dcf 424 if (errCnt>=maxErr){
425 PrintAndLog("Too many errors: %d",errCnt);
426 return 0;
427 }
428 PrintAndLog("Manchester Decoded - # errors:%d - data:",errCnt);
2767fc02 429 PrintAndLog("%s", sprint_bin_break(BitStream, size, 16));
e0165dcf 430 if (errCnt==0){
431 uint64_t id = 0;
432 uint32_t hi = 0;
433 size_t idx=0;
434 if (Em410xDecode(BitStream, &size, &idx, &hi, &id)){
435 //need to adjust to set bitstream back to manchester encoded data
436 //setDemodBuf(BitStream, size, idx);
437
438 printEM410x(hi, id);
439 }
440 }
441 return 1;
d5a72d2f 442}
443
444//by marshmellow
445//biphase decode
446//take 01 or 10 = 0 and 11 or 00 = 1
1e090a61 447//takes 2 arguments "offset" default = 0 if 1 it will shift the decode by one bit
448// and "invert" default = 0 if 1 it will invert output
2767fc02 449// the argument offset allows us to manually shift if the output is incorrect - [EDIT: now auto detects]
d5a72d2f 450int CmdBiphaseDecodeRaw(const char *Cmd)
451{
ba1a299c 452 size_t size=0;
b41534d1 453 int offset=0, invert=0, maxErr=20, errCnt=0;
b4fb11ba 454 char cmdp = param_getchar(Cmd, 0);
455 if (strlen(Cmd) > 3 || cmdp == 'h' || cmdp == 'H') {
b41534d1 456 PrintAndLog("Usage: data biphaserawdecode [offset] [invert] [maxErr]");
457 PrintAndLog(" Converts 10 or 01 to 1 and 11 or 00 to 0");
b4fb11ba 458 PrintAndLog(" --must have binary sequence in demodbuffer (run data askrawdemod first)");
e0165dcf 459 PrintAndLog(" --invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester");
b4fb11ba 460 PrintAndLog("");
461 PrintAndLog(" [offset <0|1>], set to 0 not to adjust start position or to 1 to adjust decode start position");
462 PrintAndLog(" [invert <0|1>], set to 1 to invert output");
b41534d1 463 PrintAndLog(" [maxErr int], set max errors tolerated - default=20");
b4fb11ba 464 PrintAndLog("");
465 PrintAndLog(" sample: data biphaserawdecode = decode biphase bitstream from the demodbuffer");
466 PrintAndLog(" sample: data biphaserawdecode 1 1 = decode biphase bitstream from the demodbuffer, set offset, and invert output");
467 return 0;
468 }
b41534d1 469 sscanf(Cmd, "%i %i %i", &offset, &invert, &maxErr);
470 if (DemodBufferLen==0){
471 PrintAndLog("DemodBuffer Empty - run 'data rawdemod ar' first");
b4fb11ba 472 return 0;
473 }
b41534d1 474 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
475 memcpy(BitStream, DemodBuffer, DemodBufferLen);
476 size = DemodBufferLen;
1e090a61 477 errCnt=BiphaseRawDecode(BitStream, &size, offset, invert);
b41534d1 478 if (errCnt<0){
479 PrintAndLog("Error during decode:%d", errCnt);
480 return 0;
481 }
482 if (errCnt>maxErr){
b4fb11ba 483 PrintAndLog("Too many errors attempting to decode: %d",errCnt);
484 return 0;
485 }
b41534d1 486
487 if (errCnt>0){
2767fc02 488 PrintAndLog("# Errors found during Demod (shown as 7 in bit stream): %d",errCnt);
b41534d1 489 }
490 PrintAndLog("Biphase Decoded using offset: %d - # invert:%d - data:",offset,invert);
2767fc02 491 PrintAndLog("%s", sprint_bin_break(BitStream, size, 16));
b41534d1 492
493 if (offset) setDemodBuf(DemodBuffer,DemodBufferLen-offset, offset); //remove first bit from raw demod
b4fb11ba 494 return 1;
eb191de6 495}
496
b41534d1 497//by marshmellow
498// - ASK Demod then Biphase decode GraphBuffer samples
499int ASKbiphaseDemod(const char *Cmd, bool verbose)
500{
501 //ask raw demod GraphBuffer first
502 int offset=0, clk=0, invert=0, maxErr=0, ans=0;
503 ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr);
504 if (ans>0)
615f21dd 505 ans = ASKDemod(Cmd+2, FALSE, FALSE, 0);
b41534d1 506 else
fef74fdc 507 ans = ASKDemod(Cmd, FALSE, FALSE, 0);
b41534d1 508 if (!ans) {
fef74fdc 509 if (g_debugMode || verbose) PrintAndLog("Error AskDemod: %d", ans);
b41534d1 510 return 0;
511 }
512
513 //attempt to Biphase decode DemodBuffer
514 size_t size = DemodBufferLen;
515 uint8_t BitStream[MAX_DEMOD_BUF_LEN];
516 memcpy(BitStream, DemodBuffer, DemodBufferLen);
615f21dd 517 int errCnt = BiphaseRawDecode(BitStream, &size, offset, invert);
b41534d1 518 if (errCnt < 0){
519 if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode: %d", errCnt);
520 return 0;
521 }
522 if (errCnt > maxErr) {
523 if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode too many errors: %d", errCnt);
524 return 0;
525 }
526 //success set DemodBuffer and return
527 setDemodBuf(BitStream, size, 0);
528 if (g_debugMode || verbose){
529 PrintAndLog("Biphase Decoded using offset: %d - # errors:%d - data:",offset,errCnt);
530 printDemodBuff();
531 }
532 return 1;
533}
534//by marshmellow - see ASKbiphaseDemod
535int Cmdaskbiphdemod(const char *Cmd)
536{
e0165dcf 537 char cmdp = param_getchar(Cmd, 0);
fef74fdc 538 if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') {
539 PrintAndLog("Usage: data rawdemod ab [offset] [clock] <invert> [maxError] [maxLen] <amplify>");
e0165dcf 540 PrintAndLog(" [offset], offset to begin biphase, default=0");
541 PrintAndLog(" [set clock as integer] optional, if not set, autodetect");
542 PrintAndLog(" <invert>, 1 to invert output");
543 PrintAndLog(" [set maximum allowed errors], default = 100");
fef74fdc 544 PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)");
e0165dcf 545 PrintAndLog(" <amplify>, 'a' to attempt demod with ask amplification, default = no amp");
546 PrintAndLog(" NOTE: <invert> can be entered as second or third argument");
547 PrintAndLog(" NOTE: <amplify> can be entered as first, second or last argument");
548 PrintAndLog(" NOTE: any other arg must have previous args set to work");
549 PrintAndLog("");
550 PrintAndLog(" NOTE: --invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester");
551 PrintAndLog("");
fef74fdc 552 PrintAndLog(" sample: data rawdemod ab = demod an ask/biph tag from GraphBuffer");
553 PrintAndLog(" : data rawdemod ab 0 a = demod an ask/biph tag from GraphBuffer, amplified");
554 PrintAndLog(" : data rawdemod ab 1 32 = demod an ask/biph tag from GraphBuffer using an offset of 1 and a clock of RF/32");
555 PrintAndLog(" : data rawdemod ab 0 32 1 = demod an ask/biph tag from GraphBuffer using a clock of RF/32 and inverting data");
556 PrintAndLog(" : data rawdemod ab 0 1 = demod an ask/biph tag from GraphBuffer while inverting data");
557 PrintAndLog(" : data rawdemod ab 0 64 1 0 = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
558 PrintAndLog(" : data rawdemod ab 0 64 1 0 0 a = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp");
e0165dcf 559 return 0;
560 }
561 return ASKbiphaseDemod(Cmd, TRUE);
b41534d1 562}
563
8d960002 564//by marshmellow
565//attempts to demodulate and identify a G_Prox_II verex/chubb card
566//WARNING: if it fails during some points it will destroy the DemodBuffer data
567// but will leave the GraphBuffer intact.
568//if successful it will push askraw data back to demod buffer ready for emulation
569int CmdG_Prox_II_Demod(const char *Cmd)
570{
e0165dcf 571 if (!ASKbiphaseDemod(Cmd, FALSE)){
572 if (g_debugMode) PrintAndLog("ASKbiphaseDemod failed 1st try");
573 return 0;
574 }
575 size_t size = DemodBufferLen;
576 //call lfdemod.c demod for gProxII
577 int ans = gProxII_Demod(DemodBuffer, &size);
578 if (ans < 0){
579 if (g_debugMode) PrintAndLog("Error gProxII_Demod");
580 return 0;
581 }
582 //got a good demod
583 uint32_t ByteStream[65] = {0x00};
584 uint8_t xorKey=0;
585 uint8_t keyCnt=0;
586 uint8_t bitCnt=0;
587 uint8_t ByteCnt=0;
588 size_t startIdx = ans + 6; //start after preamble
589 for (size_t idx = 0; idx<size-6; idx++){
590 if ((idx+1) % 5 == 0){
591 //spacer bit - should be 0
592 if (DemodBuffer[startIdx+idx] != 0) {
593 if (g_debugMode) PrintAndLog("Error spacer not 0: %d, pos: %d",DemodBuffer[startIdx+idx],startIdx+idx);
594 return 0;
595 }
596 continue;
597 }
598 if (keyCnt<8){ //lsb first
599 xorKey = xorKey | (DemodBuffer[startIdx+idx]<<keyCnt);
600 keyCnt++;
601 if (keyCnt==8 && g_debugMode) PrintAndLog("xorKey Found: %02x", xorKey);
602 continue;
603 }
604 //lsb first
605 ByteStream[ByteCnt] = ByteStream[ByteCnt] | (DemodBuffer[startIdx+idx]<<bitCnt);
606 bitCnt++;
607 if (bitCnt % 8 == 0){
608 if (g_debugMode) PrintAndLog("byte %d: %02x",ByteCnt,ByteStream[ByteCnt]);
609 bitCnt=0;
610 ByteCnt++;
611 }
612 }
613 for (uint8_t i = 0; i < ByteCnt; i++){
614 ByteStream[i] ^= xorKey; //xor
615 if (g_debugMode) PrintAndLog("byte %d after xor: %02x", i, ByteStream[i]);
616 }
617 //now ByteStream contains 64 bytes of decrypted raw tag data
618 //
619 uint8_t fmtLen = ByteStream[0]>>2;
620 uint32_t FC = 0;
621 uint32_t Card = 0;
622 uint32_t raw1 = bytebits_to_byte(DemodBuffer+ans,32);
623 uint32_t raw2 = bytebits_to_byte(DemodBuffer+ans+32, 32);
624 uint32_t raw3 = bytebits_to_byte(DemodBuffer+ans+64, 32);
625
626 if (fmtLen==36){
627 FC = ((ByteStream[3] & 0x7F)<<7) | (ByteStream[4]>>1);
628 Card = ((ByteStream[4]&1)<<19) | (ByteStream[5]<<11) | (ByteStream[6]<<3) | (ByteStream[7]>>5);
629 PrintAndLog("G-Prox-II Found: FmtLen %d, FC %d, Card %d",fmtLen,FC,Card);
630 } else if(fmtLen==26){
631 FC = ((ByteStream[3] & 0x7F)<<1) | (ByteStream[4]>>7);
632 Card = ((ByteStream[4]&0x7F)<<9) | (ByteStream[5]<<1) | (ByteStream[6]>>7);
633 PrintAndLog("G-Prox-II Found: FmtLen %d, FC %d, Card %d",fmtLen,FC,Card);
634 } else {
635 PrintAndLog("Unknown G-Prox-II Fmt Found: FmtLen %d",fmtLen);
636 }
637 PrintAndLog("Raw: %08x%08x%08x", raw1,raw2,raw3);
638 setDemodBuf(DemodBuffer+ans, 96, 0);
639 return 1;
8d960002 640}
641
fef74fdc 642//by marshmellow - see ASKDemod
4ac906d1 643int Cmdaskrawdemod(const char *Cmd)
644{
e0165dcf 645 char cmdp = param_getchar(Cmd, 0);
fef74fdc 646 if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') {
647 PrintAndLog("Usage: data rawdemod ar [clock] <invert> [maxError] [maxLen] [amplify]");
e0165dcf 648 PrintAndLog(" [set clock as integer] optional, if not set, autodetect");
649 PrintAndLog(" <invert>, 1 to invert output");
650 PrintAndLog(" [set maximum allowed errors], default = 100");
fef74fdc 651 PrintAndLog(" [set maximum Samples to read], default = 32768 (1024 bits at rf/64)");
e0165dcf 652 PrintAndLog(" <amplify>, 'a' to attempt demod with ask amplification, default = no amp");
653 PrintAndLog("");
fef74fdc 654 PrintAndLog(" sample: data rawdemod ar = demod an ask tag from GraphBuffer");
655 PrintAndLog(" : data rawdemod ar a = demod an ask tag from GraphBuffer, amplified");
656 PrintAndLog(" : data rawdemod ar 32 = demod an ask tag from GraphBuffer using a clock of RF/32");
657 PrintAndLog(" : data rawdemod ar 32 1 = demod an ask tag from GraphBuffer using a clock of RF/32 and inverting data");
658 PrintAndLog(" : data rawdemod ar 1 = demod an ask tag from GraphBuffer while inverting data");
659 PrintAndLog(" : data rawdemod ar 64 1 0 = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
660 PrintAndLog(" : data rawdemod ar 64 1 0 0 a = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp");
e0165dcf 661 return 0;
662 }
fef74fdc 663 return ASKDemod(Cmd, TRUE, FALSE, 0);
4ac906d1 664}
665
73d04bb4 666int AutoCorrelate(int window, bool SaveGrph, bool verbose)
7fe9b0b7 667{
e0165dcf 668 static int CorrelBuffer[MAX_GRAPH_TRACE_LEN];
669 size_t Correlation = 0;
670 int maxSum = 0;
671 int lastMax = 0;
672 if (verbose) PrintAndLog("performing %d correlations", GraphTraceLen - window);
673 for (int i = 0; i < GraphTraceLen - window; ++i) {
674 int sum = 0;
675 for (int j = 0; j < window; ++j) {
676 sum += (GraphBuffer[j]*GraphBuffer[i + j]) / 256;
677 }
678 CorrelBuffer[i] = sum;
679 if (sum >= maxSum-100 && sum <= maxSum+100){
680 //another max
681 Correlation = i-lastMax;
682 lastMax = i;
683 if (sum > maxSum) maxSum = sum;
684 } else if (sum > maxSum){
685 maxSum=sum;
686 lastMax = i;
687 }
688 }
689 if (Correlation==0){
690 //try again with wider margin
691 for (int i = 0; i < GraphTraceLen - window; i++){
692 if (CorrelBuffer[i] >= maxSum-(maxSum*0.05) && CorrelBuffer[i] <= maxSum+(maxSum*0.05)){
693 //another max
694 Correlation = i-lastMax;
695 lastMax = i;
696 //if (CorrelBuffer[i] > maxSum) maxSum = sum;
697 }
698 }
699 }
700 if (verbose && Correlation > 0) PrintAndLog("Possible Correlation: %d samples",Correlation);
701
702 if (SaveGrph){
703 GraphTraceLen = GraphTraceLen - window;
704 memcpy(GraphBuffer, CorrelBuffer, GraphTraceLen * sizeof (int));
705 RepaintGraphWindow();
706 }
707 return Correlation;
73d04bb4 708}
7fe9b0b7 709
9f7bbd24 710int usage_data_autocorr(void)
711{
e0165dcf 712 //print help
713 PrintAndLog("Usage: data autocorr [window] [g]");
714 PrintAndLog("Options: ");
715 PrintAndLog(" h This help");
716 PrintAndLog(" [window] window length for correlation - default = 4000");
717 PrintAndLog(" g save back to GraphBuffer (overwrite)");
718 return 0;
9f7bbd24 719}
720
73d04bb4 721int CmdAutoCorr(const char *Cmd)
722{
e0165dcf 723 char cmdp = param_getchar(Cmd, 0);
724 if (cmdp == 'h' || cmdp == 'H')
725 return usage_data_autocorr();
726 int window = 4000; //set default
727 char grph=0;
728 bool updateGrph = FALSE;
729 sscanf(Cmd, "%i %c", &window, &grph);
730
731 if (window >= GraphTraceLen) {
732 PrintAndLog("window must be smaller than trace (%d samples)",
733 GraphTraceLen);
734 return 0;
735 }
736 if (grph == 'g') updateGrph=TRUE;
737 return AutoCorrelate(window, updateGrph, TRUE);
7fe9b0b7 738}
739
740int CmdBitsamples(const char *Cmd)
741{
e0165dcf 742 int cnt = 0;
743 uint8_t got[12288];
952a8bb5 744
e0165dcf 745 GetFromBigBuf(got,sizeof(got),0);
746 WaitForResponse(CMD_ACK,NULL);
7fe9b0b7 747
e0165dcf 748 for (int j = 0; j < sizeof(got); j++) {
749 for (int k = 0; k < 8; k++) {
750 if(got[j] & (1 << (7 - k))) {
751 GraphBuffer[cnt++] = 1;
752 } else {
753 GraphBuffer[cnt++] = 0;
754 }
755 }
756 }
757 GraphTraceLen = cnt;
758 RepaintGraphWindow();
759 return 0;
7fe9b0b7 760}
761
7fe9b0b7 762int CmdBuffClear(const char *Cmd)
763{
e0165dcf 764 UsbCommand c = {CMD_BUFF_CLEAR};
765 SendCommand(&c);
766 ClearGraph(true);
767 return 0;
7fe9b0b7 768}
769
770int CmdDec(const char *Cmd)
771{
e0165dcf 772 for (int i = 0; i < (GraphTraceLen / 2); ++i)
773 GraphBuffer[i] = GraphBuffer[i * 2];
774 GraphTraceLen /= 2;
775 PrintAndLog("decimated by 2");
776 RepaintGraphWindow();
777 return 0;
7fe9b0b7 778}
698b649e
MHS
779/**
780 * Undecimate - I'd call it 'interpolate', but we'll save that
781 * name until someone does an actual interpolation command, not just
782 * blindly repeating samples
783 * @param Cmd
784 * @return
785 */
786int CmdUndec(const char *Cmd)
787{
c856ceae
MHS
788 if(param_getchar(Cmd, 0) == 'h')
789 {
790 PrintAndLog("Usage: data undec [factor]");
791 PrintAndLog("This function performs un-decimation, by repeating each sample N times");
792 PrintAndLog("Options: ");
793 PrintAndLog(" h This help");
794 PrintAndLog(" factor The number of times to repeat each sample.[default:2]");
795 PrintAndLog("Example: 'data undec 3'");
796 return 0;
797 }
798
799 uint8_t factor = param_get8ex(Cmd, 0,2, 10);
698b649e
MHS
800 //We have memory, don't we?
801 int swap[MAX_GRAPH_TRACE_LEN] = { 0 };
c856ceae
MHS
802 uint32_t g_index = 0 ,s_index = 0;
803 while(g_index < GraphTraceLen && s_index < MAX_GRAPH_TRACE_LEN)
698b649e 804 {
c856ceae
MHS
805 int count = 0;
806 for(count = 0; count < factor && s_index+count < MAX_GRAPH_TRACE_LEN; count ++)
807 swap[s_index+count] = GraphBuffer[g_index];
808 s_index+=count;
698b649e 809 }
698b649e 810
c856ceae
MHS
811 memcpy(GraphBuffer,swap, s_index * sizeof(int));
812 GraphTraceLen = s_index;
813 RepaintGraphWindow();
698b649e
MHS
814 return 0;
815}
7fe9b0b7 816
ec75f5c1 817//by marshmellow
818//shift graph zero up or down based on input + or -
819int CmdGraphShiftZero(const char *Cmd)
820{
821
e0165dcf 822 int shift=0;
823 //set options from parameters entered with the command
824 sscanf(Cmd, "%i", &shift);
825 int shiftedVal=0;
826 for(int i = 0; i<GraphTraceLen; i++){
827 shiftedVal=GraphBuffer[i]+shift;
828 if (shiftedVal>127)
829 shiftedVal=127;
830 else if (shiftedVal<-127)
831 shiftedVal=-127;
832 GraphBuffer[i]= shiftedVal;
833 }
834 CmdNorm("");
835 return 0;
ec75f5c1 836}
837
6de43508 838//by marshmellow
839//use large jumps in read samples to identify edges of waves and then amplify that wave to max
2767fc02 840//similar to dirtheshold, threshold commands
6de43508 841//takes a threshold length which is the measured length between two samples then determines an edge
842int CmdAskEdgeDetect(const char *Cmd)
843{
e0165dcf 844 int thresLen = 25;
845 sscanf(Cmd, "%i", &thresLen);
49bbc60a 846
e0165dcf 847 for(int i = 1; i<GraphTraceLen; i++){
848 if (GraphBuffer[i]-GraphBuffer[i-1]>=thresLen) //large jump up
49bbc60a 849 GraphBuffer[i-1] = 127;
e0165dcf 850 else if(GraphBuffer[i]-GraphBuffer[i-1]<=-1*thresLen) //large jump down
49bbc60a 851 GraphBuffer[i-1] = -127;
e0165dcf 852 }
853 RepaintGraphWindow();
e0165dcf 854 return 0;
6de43508 855}
856
7fe9b0b7 857/* Print our clock rate */
ba1a299c 858// uses data from graphbuffer
f3bf15e4 859// adjusted to take char parameter for type of modulation to find the clock - by marshmellow.
7fe9b0b7 860int CmdDetectClockRate(const char *Cmd)
861{
f3bf15e4 862 char cmdp = param_getchar(Cmd, 0);
fef74fdc 863 if (strlen(Cmd) > 6 || strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') {
864 PrintAndLog("Usage: data detectclock [modulation] <clock>");
f3bf15e4 865 PrintAndLog(" [modulation as char], specify the modulation type you want to detect the clock of");
fef74fdc 866 PrintAndLog(" <clock> , specify the clock (optional - to get best start position only)");
f3bf15e4 867 PrintAndLog(" 'a' = ask, 'f' = fsk, 'n' = nrz/direct, 'p' = psk");
868 PrintAndLog("");
869 PrintAndLog(" sample: data detectclock a = detect the clock of an ask modulated wave in the GraphBuffer");
870 PrintAndLog(" data detectclock f = detect the clock of an fsk modulated wave in the GraphBuffer");
871 PrintAndLog(" data detectclock p = detect the clock of an psk modulated wave in the GraphBuffer");
872 PrintAndLog(" data detectclock n = detect the clock of an nrz/direct modulated wave in the GraphBuffer");
873 }
874 int ans=0;
875 if (cmdp == 'a'){
fef74fdc 876 ans = GetAskClock(Cmd+1, true, false);
f3bf15e4 877 } else if (cmdp == 'f'){
878 ans = GetFskClock("", true, false);
879 } else if (cmdp == 'n'){
880 ans = GetNrzClock("", true, false);
881 } else if (cmdp == 'p'){
882 ans = GetPskClock("", true, false);
883 } else {
884 PrintAndLog ("Please specify a valid modulation to detect the clock of - see option h for help");
885 }
886 return ans;
7fe9b0b7 887}
66707a3b 888
2767fc02 889char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert)
890{
891 char *fskType;
892 if (fchigh==10 && fclow==8){
893 if (invert) //fsk2a
894 fskType = "FSK2a";
895 else //fsk2
896 fskType = "FSK2";
897 } else if (fchigh == 8 && fclow == 5) {
898 if (invert)
899 fskType = "FSK1";
900 else
901 fskType = "FSK1a";
902 } else {
903 fskType = "FSK??";
904 }
905 return fskType;
906}
907
2fc2150e 908//by marshmellow
eb191de6 909//fsk raw demod and print binary
6de43508 910//takes 4 arguments - Clock, invert, fchigh, fclow
911//defaults: clock = 50, invert=1, fchigh=10, fclow=8 (RF/10 RF/8 (fsk2a))
4ac906d1 912int FSKrawDemod(const char *Cmd, bool verbose)
b3b70669 913{
e0165dcf 914 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
915 //set defaults
916 int rfLen = 0;
917 int invert = 0;
918 int fchigh = 0;
919 int fclow = 0;
920
921 //set options from parameters entered with the command
922 sscanf(Cmd, "%i %i %i %i", &rfLen, &invert, &fchigh, &fclow);
923
924 if (strlen(Cmd)>0 && strlen(Cmd)<=2) {
925 if (rfLen==1){
2eec55c8 926 invert = 1; //if invert option only is used
e0165dcf 927 rfLen = 0;
928 }
929 }
930
931 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
932 size_t BitLen = getFromGraphBuf(BitStream);
933 if (BitLen==0) return 0;
934 //get field clock lengths
935 uint16_t fcs=0;
e0165dcf 936 if (fchigh==0 || fclow == 0){
2eec55c8 937 fcs = countFC(BitStream, BitLen, 1);
e0165dcf 938 if (fcs==0){
939 fchigh=10;
940 fclow=8;
941 }else{
942 fchigh = (fcs >> 8) & 0xFF;
943 fclow = fcs & 0xFF;
944 }
945 }
946 //get bit clock length
947 if (rfLen==0){
948 rfLen = detectFSKClk(BitStream, BitLen, fchigh, fclow);
949 if (rfLen == 0) rfLen = 50;
950 }
e0165dcf 951 int size = fskdemod(BitStream,BitLen,(uint8_t)rfLen,(uint8_t)invert,(uint8_t)fchigh,(uint8_t)fclow);
952 if (size>0){
953 setDemodBuf(BitStream,size,0);
954
955 // Now output the bitstream to the scrollback by line of 16 bits
2767fc02 956 if (verbose || g_debugMode) {
957 PrintAndLog("\nUsing Clock:%d, invert:%d, fchigh:%d, fclow:%d", rfLen, invert, fchigh, fclow);
958 PrintAndLog("%s decoded bitstream:",GetFSKType(fchigh,fclow,invert));
959 printDemodBuff();
e0165dcf 960 }
961
962 return 1;
963 } else{
2767fc02 964 if (g_debugMode) PrintAndLog("no FSK data found");
e0165dcf 965 }
966 return 0;
b3b70669 967}
968
4ac906d1 969//by marshmellow
970//fsk raw demod and print binary
971//takes 4 arguments - Clock, invert, fchigh, fclow
972//defaults: clock = 50, invert=1, fchigh=10, fclow=8 (RF/10 RF/8 (fsk2a))
973int CmdFSKrawdemod(const char *Cmd)
974{
e0165dcf 975 char cmdp = param_getchar(Cmd, 0);
976 if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') {
977 PrintAndLog("Usage: data rawdemod fs [clock] <invert> [fchigh] [fclow]");
978 PrintAndLog(" [set clock as integer] optional, omit for autodetect.");
979 PrintAndLog(" <invert>, 1 for invert output, can be used even if the clock is omitted");
980 PrintAndLog(" [fchigh], larger field clock length, omit for autodetect");
981 PrintAndLog(" [fclow], small field clock length, omit for autodetect");
982 PrintAndLog("");
983 PrintAndLog(" sample: data rawdemod fs = demod an fsk tag from GraphBuffer using autodetect");
984 PrintAndLog(" : data rawdemod fs 32 = demod an fsk tag from GraphBuffer using a clock of RF/32, autodetect fc");
985 PrintAndLog(" : data rawdemod fs 1 = demod an fsk tag from GraphBuffer using autodetect, invert output");
986 PrintAndLog(" : data rawdemod fs 32 1 = demod an fsk tag from GraphBuffer using a clock of RF/32, invert output, autodetect fc");
987 PrintAndLog(" : data rawdemod fs 64 0 8 5 = demod an fsk1 RF/64 tag from GraphBuffer");
988 PrintAndLog(" : data rawdemod fs 50 0 10 8 = demod an fsk2 RF/50 tag from GraphBuffer");
989 PrintAndLog(" : data rawdemod fs 50 1 10 8 = demod an fsk2a RF/50 tag from GraphBuffer");
990 return 0;
991 }
992 return FSKrawDemod(Cmd, TRUE);
4ac906d1 993}
994
eb191de6 995//by marshmellow (based on existing demod + holiman's refactor)
996//HID Prox demod - FSK RF/50 with preamble of 00011101 (then manchester encoded)
997//print full HID Prox ID and some bit format details if found
b3b70669 998int CmdFSKdemodHID(const char *Cmd)
999{
e0165dcf 1000 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
1001 uint32_t hi2=0, hi=0, lo=0;
1002
1003 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1004 size_t BitLen = getFromGraphBuf(BitStream);
1005 if (BitLen==0) return 0;
1006 //get binary from fsk wave
1007 int idx = HIDdemodFSK(BitStream,&BitLen,&hi2,&hi,&lo);
1008 if (idx<0){
1009 if (g_debugMode){
1010 if (idx==-1){
1011 PrintAndLog("DEBUG: Just Noise Detected");
1012 } else if (idx == -2) {
1013 PrintAndLog("DEBUG: Error demoding fsk");
1014 } else if (idx == -3) {
1015 PrintAndLog("DEBUG: Preamble not found");
1016 } else if (idx == -4) {
1017 PrintAndLog("DEBUG: Error in Manchester data, SIZE: %d", BitLen);
1018 } else {
1019 PrintAndLog("DEBUG: Error demoding fsk %d", idx);
1020 }
1021 }
1022 return 0;
1023 }
1024 if (hi2==0 && hi==0 && lo==0) {
1025 if (g_debugMode) PrintAndLog("DEBUG: Error - no values found");
1026 return 0;
1027 }
1028 if (hi2 != 0){ //extra large HID tags
1029 PrintAndLog("HID Prox TAG ID: %x%08x%08x (%d)",
1030 (unsigned int) hi2, (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF);
1031 }
1032 else { //standard HID tags <38 bits
1033 uint8_t fmtLen = 0;
1034 uint32_t fc = 0;
1035 uint32_t cardnum = 0;
1036 if (((hi>>5)&1)==1){//if bit 38 is set then < 37 bit format is used
1037 uint32_t lo2=0;
1038 lo2=(((hi & 31) << 12) | (lo>>20)); //get bits 21-37 to check for format len bit
1039 uint8_t idx3 = 1;
1040 while(lo2>1){ //find last bit set to 1 (format len bit)
1041 lo2=lo2>>1;
1042 idx3++;
1043 }
1044 fmtLen =idx3+19;
1045 fc =0;
1046 cardnum=0;
1047 if(fmtLen==26){
1048 cardnum = (lo>>1)&0xFFFF;
1049 fc = (lo>>17)&0xFF;
1050 }
1051 if(fmtLen==34){
1052 cardnum = (lo>>1)&0xFFFF;
1053 fc= ((hi&1)<<15)|(lo>>17);
1054 }
1055 if(fmtLen==35){
1056 cardnum = (lo>>1)&0xFFFFF;
1057 fc = ((hi&1)<<11)|(lo>>21);
1058 }
1059 }
1060 else { //if bit 38 is not set then 37 bit format is used
1061 fmtLen = 37;
1062 fc = 0;
1063 cardnum = 0;
1064 if(fmtLen == 37){
1065 cardnum = (lo>>1)&0x7FFFF;
1066 fc = ((hi&0xF)<<12)|(lo>>20);
1067 }
1068 }
1069 PrintAndLog("HID Prox TAG ID: %x%08x (%d) - Format Len: %dbit - FC: %d - Card: %d",
1070 (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF,
1071 (unsigned int) fmtLen, (unsigned int) fc, (unsigned int) cardnum);
1072 }
1073 setDemodBuf(BitStream,BitLen,idx);
1074 if (g_debugMode){
1075 PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen);
1076 printDemodBuff();
1077 }
1078 return 1;
ec75f5c1 1079}
1080
04d2721b 1081//by marshmellow
1082//Paradox Prox demod - FSK RF/50 with preamble of 00001111 (then manchester encoded)
ec75f5c1 1083//print full Paradox Prox ID and some bit format details if found
1084int CmdFSKdemodParadox(const char *Cmd)
1085{
e0165dcf 1086 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
1087 uint32_t hi2=0, hi=0, lo=0;
1088
1089 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1090 size_t BitLen = getFromGraphBuf(BitStream);
1091 if (BitLen==0) return 0;
1092 //get binary from fsk wave
1093 int idx = ParadoxdemodFSK(BitStream,&BitLen,&hi2,&hi,&lo);
1094 if (idx<0){
1095 if (g_debugMode){
1096 if (idx==-1){
1097 PrintAndLog("DEBUG: Just Noise Detected");
1098 } else if (idx == -2) {
1099 PrintAndLog("DEBUG: Error demoding fsk");
1100 } else if (idx == -3) {
1101 PrintAndLog("DEBUG: Preamble not found");
1102 } else if (idx == -4) {
1103 PrintAndLog("DEBUG: Error in Manchester data");
1104 } else {
1105 PrintAndLog("DEBUG: Error demoding fsk %d", idx);
1106 }
1107 }
1108 return 0;
1109 }
1110 if (hi2==0 && hi==0 && lo==0){
1111 if (g_debugMode) PrintAndLog("DEBUG: Error - no value found");
1112 return 0;
1113 }
1114 uint32_t fc = ((hi & 0x3)<<6) | (lo>>26);
1115 uint32_t cardnum = (lo>>10)&0xFFFF;
1116 uint32_t rawLo = bytebits_to_byte(BitStream+idx+64,32);
1117 uint32_t rawHi = bytebits_to_byte(BitStream+idx+32,32);
1118 uint32_t rawHi2 = bytebits_to_byte(BitStream+idx,32);
1119
1120 PrintAndLog("Paradox TAG ID: %x%08x - FC: %d - Card: %d - Checksum: %02x - RAW: %08x%08x%08x",
1121 hi>>10, (hi & 0x3)<<26 | (lo>>10), fc, cardnum, (lo>>2) & 0xFF, rawHi2, rawHi, rawLo);
1122 setDemodBuf(BitStream,BitLen,idx);
1123 if (g_debugMode){
1124 PrintAndLog("DEBUG: idx: %d, len: %d, Printing Demod Buffer:", idx, BitLen);
1125 printDemodBuff();
1126 }
1127 return 1;
b3b70669 1128}
1129
2fc2150e 1130//by marshmellow
eb191de6 1131//IO-Prox demod - FSK RF/64 with preamble of 000000001
1132//print ioprox ID and some format details
b3b70669 1133int CmdFSKdemodIO(const char *Cmd)
1134{
e0165dcf 1135 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
1136 //set defaults
1137 int idx=0;
1138 //something in graphbuffer?
1139 if (GraphTraceLen < 65) {
1140 if (g_debugMode)PrintAndLog("DEBUG: not enough samples in GraphBuffer");
1141 return 0;
1142 }
1143 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1144 size_t BitLen = getFromGraphBuf(BitStream);
1145 if (BitLen==0) return 0;
1146
1147 //get binary from fsk wave
1148 idx = IOdemodFSK(BitStream,BitLen);
1149 if (idx<0){
1150 if (g_debugMode){
1151 if (idx==-1){
1152 PrintAndLog("DEBUG: Just Noise Detected");
1153 } else if (idx == -2) {
1154 PrintAndLog("DEBUG: not enough samples");
1155 } else if (idx == -3) {
1156 PrintAndLog("DEBUG: error during fskdemod");
1157 } else if (idx == -4) {
1158 PrintAndLog("DEBUG: Preamble not found");
1159 } else if (idx == -5) {
1160 PrintAndLog("DEBUG: Separator bits not found");
1161 } else {
1162 PrintAndLog("DEBUG: Error demoding fsk %d", idx);
1163 }
1164 }
1165 return 0;
1166 }
1167 if (idx==0){
2767fc02 1168 if (g_debugMode){
e0165dcf 1169 PrintAndLog("DEBUG: IO Prox Data not found - FSK Bits: %d",BitLen);
2767fc02 1170 if (BitLen > 92) PrintAndLog("%s", sprint_bin_break(BitStream,92,16));
e0165dcf 1171 }
1172 return 0;
1173 }
1174 //Index map
1175 //0 10 20 30 40 50 60
1176 //| | | | | | |
1177 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
1178 //-----------------------------------------------------------------------------
1179 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
1180 //
1181 //XSF(version)facility:codeone+codetwo (raw)
1182 //Handle the data
1183 if (idx+64>BitLen) {
2767fc02 1184 if (g_debugMode) PrintAndLog("not enough bits found - bitlen: %d",BitLen);
e0165dcf 1185 return 0;
1186 }
1187 PrintAndLog("%d%d%d%d%d%d%d%d %d",BitStream[idx], BitStream[idx+1], BitStream[idx+2], BitStream[idx+3], BitStream[idx+4], BitStream[idx+5], BitStream[idx+6], BitStream[idx+7], BitStream[idx+8]);
1188 PrintAndLog("%d%d%d%d%d%d%d%d %d",BitStream[idx+9], BitStream[idx+10], BitStream[idx+11],BitStream[idx+12],BitStream[idx+13],BitStream[idx+14],BitStream[idx+15],BitStream[idx+16],BitStream[idx+17]);
1189 PrintAndLog("%d%d%d%d%d%d%d%d %d facility",BitStream[idx+18], BitStream[idx+19], BitStream[idx+20],BitStream[idx+21],BitStream[idx+22],BitStream[idx+23],BitStream[idx+24],BitStream[idx+25],BitStream[idx+26]);
1190 PrintAndLog("%d%d%d%d%d%d%d%d %d version",BitStream[idx+27], BitStream[idx+28], BitStream[idx+29],BitStream[idx+30],BitStream[idx+31],BitStream[idx+32],BitStream[idx+33],BitStream[idx+34],BitStream[idx+35]);
1191 PrintAndLog("%d%d%d%d%d%d%d%d %d code1",BitStream[idx+36], BitStream[idx+37], BitStream[idx+38],BitStream[idx+39],BitStream[idx+40],BitStream[idx+41],BitStream[idx+42],BitStream[idx+43],BitStream[idx+44]);
1192 PrintAndLog("%d%d%d%d%d%d%d%d %d code2",BitStream[idx+45], BitStream[idx+46], BitStream[idx+47],BitStream[idx+48],BitStream[idx+49],BitStream[idx+50],BitStream[idx+51],BitStream[idx+52],BitStream[idx+53]);
1193 PrintAndLog("%d%d%d%d%d%d%d%d %d%d checksum",BitStream[idx+54],BitStream[idx+55],BitStream[idx+56],BitStream[idx+57],BitStream[idx+58],BitStream[idx+59],BitStream[idx+60],BitStream[idx+61],BitStream[idx+62],BitStream[idx+63]);
1194
1195 uint32_t code = bytebits_to_byte(BitStream+idx,32);
1196 uint32_t code2 = bytebits_to_byte(BitStream+idx+32,32);
1197 uint8_t version = bytebits_to_byte(BitStream+idx+27,8); //14,4
1198 uint8_t facilitycode = bytebits_to_byte(BitStream+idx+18,8) ;
1199 uint16_t number = (bytebits_to_byte(BitStream+idx+36,8)<<8)|(bytebits_to_byte(BitStream+idx+45,8)); //36,9
1200 uint8_t crc = bytebits_to_byte(BitStream+idx+54,8);
1201 uint16_t calccrc = 0;
1202
1203 for (uint8_t i=1; i<6; ++i){
1204 calccrc += bytebits_to_byte(BitStream+idx+9*i,8);
e0165dcf 1205 }
1206 calccrc &= 0xff;
1207 calccrc = 0xff - calccrc;
1208
1209 char *crcStr = (crc == calccrc) ? "crc ok": "!crc";
1210
1211 PrintAndLog("IO Prox XSF(%02d)%02x:%05d (%08x%08x) [%02x %s]",version,facilitycode,number,code,code2, crc, crcStr);
1212 setDemodBuf(BitStream,64,idx);
1213 if (g_debugMode){
1214 PrintAndLog("DEBUG: idx: %d, Len: %d, Printing demod buffer:",idx,64);
1215 printDemodBuff();
1216 }
1217 return 1;
b3b70669 1218}
1e090a61 1219
1e090a61 1220//by marshmellow
1221//AWID Prox demod - FSK RF/50 with preamble of 00000001 (always a 96 bit data stream)
1222//print full AWID Prox ID and some bit format details if found
1223int CmdFSKdemodAWID(const char *Cmd)
1224{
1225
e0165dcf 1226 //int verbose=1;
1227 //sscanf(Cmd, "%i", &verbose);
1228
1229 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
1230 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1231 size_t size = getFromGraphBuf(BitStream);
1232 if (size==0) return 0;
1233
1234 //get binary from fsk wave
1235 int idx = AWIDdemodFSK(BitStream, &size);
1236 if (idx<=0){
1237 if (g_debugMode==1){
1238 if (idx == -1)
1239 PrintAndLog("DEBUG: Error - not enough samples");
1240 else if (idx == -2)
1241 PrintAndLog("DEBUG: Error - only noise found");
1242 else if (idx == -3)
1243 PrintAndLog("DEBUG: Error - problem during FSK demod");
1244 else if (idx == -4)
1245 PrintAndLog("DEBUG: Error - AWID preamble not found");
1246 else if (idx == -5)
1247 PrintAndLog("DEBUG: Error - Size not correct: %d", size);
1248 else
1249 PrintAndLog("DEBUG: Error %d",idx);
1250 }
1251 return 0;
1252 }
1253
1254 // Index map
1255 // 0 10 20 30 40 50 60
1256 // | | | | | | |
1257 // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96
1258 // -----------------------------------------------------------------------------
1259 // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1
1260 // premable bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96
1261 // |---26 bit---| |-----117----||-------------142-------------|
1262 // b = format bit len, o = odd parity of last 3 bits
1263 // f = facility code, c = card number
1264 // w = wiegand parity
1265 // (26 bit format shown)
1e090a61 1266
e0165dcf 1267 //get raw ID before removing parities
1268 uint32_t rawLo = bytebits_to_byte(BitStream+idx+64,32);
1269 uint32_t rawHi = bytebits_to_byte(BitStream+idx+32,32);
1270 uint32_t rawHi2 = bytebits_to_byte(BitStream+idx,32);
1271 setDemodBuf(BitStream,96,idx);
1272
1273 size = removeParity(BitStream, idx+8, 4, 1, 88);
1274 if (size != 66){
1275 if (g_debugMode==1) PrintAndLog("DEBUG: Error - at parity check-tag size does not match AWID format");
1276 return 0;
1277 }
1278 // ok valid card found!
1279
1280 // Index map
1281 // 0 10 20 30 40 50 60
1282 // | | | | | | |
1283 // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456
1284 // -----------------------------------------------------------------------------
1285 // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000
1286 // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
1287 // |26 bit| |-117--| |-----142------|
1288 // b = format bit len, o = odd parity of last 3 bits
1289 // f = facility code, c = card number
1290 // w = wiegand parity
1291 // (26 bit format shown)
1292
1293 uint32_t fc = 0;
1294 uint32_t cardnum = 0;
1295 uint32_t code1 = 0;
1296 uint32_t code2 = 0;
1297 uint8_t fmtLen = bytebits_to_byte(BitStream,8);
1298 if (fmtLen==26){
1299 fc = bytebits_to_byte(BitStream+9, 8);
1300 cardnum = bytebits_to_byte(BitStream+17, 16);
1301 code1 = bytebits_to_byte(BitStream+8,fmtLen);
1302 PrintAndLog("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo);
1303 } else {
1304 cardnum = bytebits_to_byte(BitStream+8+(fmtLen-17), 16);
1305 if (fmtLen>32){
1306 code1 = bytebits_to_byte(BitStream+8,fmtLen-32);
1307 code2 = bytebits_to_byte(BitStream+8+(fmtLen-32),32);
1308 PrintAndLog("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo);
1309 } else{
1310 code1 = bytebits_to_byte(BitStream+8,fmtLen);
1311 PrintAndLog("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo);
1312 }
1313 }
1314 if (g_debugMode){
1315 PrintAndLog("DEBUG: idx: %d, Len: %d Printing Demod Buffer:", idx, 96);
1316 printDemodBuff();
1317 }
1318 //todo - convert hi2, hi, lo to demodbuffer for future sim/clone commands
1319 return 1;
1e090a61 1320}
1321
1322//by marshmellow
1323//Pyramid Prox demod - FSK RF/50 with preamble of 0000000000000001 (always a 128 bit data stream)
1324//print full Farpointe Data/Pyramid Prox ID and some bit format details if found
1325int CmdFSKdemodPyramid(const char *Cmd)
1326{
e0165dcf 1327 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
1328 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1329 size_t size = getFromGraphBuf(BitStream);
1330 if (size==0) return 0;
1331
1332 //get binary from fsk wave
1333 int idx = PyramiddemodFSK(BitStream, &size);
1334 if (idx < 0){
1335 if (g_debugMode==1){
1336 if (idx == -5)
1337 PrintAndLog("DEBUG: Error - not enough samples");
1338 else if (idx == -1)
1339 PrintAndLog("DEBUG: Error - only noise found");
1340 else if (idx == -2)
1341 PrintAndLog("DEBUG: Error - problem during FSK demod");
1342 else if (idx == -3)
1343 PrintAndLog("DEBUG: Error - Size not correct: %d", size);
1344 else if (idx == -4)
1345 PrintAndLog("DEBUG: Error - Pyramid preamble not found");
1346 else
1347 PrintAndLog("DEBUG: Error - idx: %d",idx);
1348 }
1349 return 0;
1350 }
1351 // Index map
1352 // 0 10 20 30 40 50 60
1353 // | | | | | | |
1354 // 0123456 7 8901234 5 6789012 3 4567890 1 2345678 9 0123456 7 8901234 5 6789012 3
1355 // -----------------------------------------------------------------------------
1356 // 0000000 0 0000000 1 0000000 1 0000000 1 0000000 1 0000000 1 0000000 1 0000000 1
1357 // premable xxxxxxx o xxxxxxx o xxxxxxx o xxxxxxx o xxxxxxx o xxxxxxx o xxxxxxx o
1358
1359 // 64 70 80 90 100 110 120
1360 // | | | | | | |
1361 // 4567890 1 2345678 9 0123456 7 8901234 5 6789012 3 4567890 1 2345678 9 0123456 7
1362 // -----------------------------------------------------------------------------
1363 // 0000000 1 0000000 1 0000000 1 0110111 0 0011000 1 0000001 0 0001100 1 1001010 0
1364 // xxxxxxx o xxxxxxx o xxxxxxx o xswffff o ffffccc o ccccccc o ccccccw o ppppppp o
1365 // |---115---||---------71---------|
1366 // s = format start bit, o = odd parity of last 7 bits
1367 // f = facility code, c = card number
1368 // w = wiegand parity, x = extra space for other formats
1369 // p = unknown checksum
1370 // (26 bit format shown)
1371
1372 //get bytes for checksum calc
1373 uint8_t checksum = bytebits_to_byte(BitStream + idx + 120, 8);
1374 uint8_t csBuff[14] = {0x00};
1375 for (uint8_t i = 0; i < 13; i++){
1376 csBuff[i] = bytebits_to_byte(BitStream + idx + 16 + (i*8), 8);
1377 }
1378 //check checksum calc
1379 //checksum calc thanks to ICEMAN!!
1380 uint32_t checkCS = CRC8Maxim(csBuff,13);
1381
1382 //get raw ID before removing parities
1383 uint32_t rawLo = bytebits_to_byte(BitStream+idx+96,32);
1384 uint32_t rawHi = bytebits_to_byte(BitStream+idx+64,32);
1385 uint32_t rawHi2 = bytebits_to_byte(BitStream+idx+32,32);
1386 uint32_t rawHi3 = bytebits_to_byte(BitStream+idx,32);
1387 setDemodBuf(BitStream,128,idx);
1388
1389 size = removeParity(BitStream, idx+8, 8, 1, 120);
1390 if (size != 105){
1391 if (g_debugMode==1)
1392 PrintAndLog("DEBUG: Error at parity check - tag size does not match Pyramid format, SIZE: %d, IDX: %d, hi3: %x",size, idx, rawHi3);
1393 return 0;
1394 }
1395
1396 // ok valid card found!
1397
1398 // Index map
1399 // 0 10 20 30 40 50 60 70
1400 // | | | | | | | |
1401 // 01234567890123456789012345678901234567890123456789012345678901234567890
1402 // -----------------------------------------------------------------------
1403 // 00000000000000000000000000000000000000000000000000000000000000000000000
1404 // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
1405
1406 // 71 80 90 100
1407 // | | | |
1408 // 1 2 34567890 1234567890123456 7 8901234
1409 // ---------------------------------------
1410 // 1 1 01110011 0000000001000110 0 1001010
1411 // s w ffffffff cccccccccccccccc w ppppppp
1412 // |--115-| |------71------|
1413 // s = format start bit, o = odd parity of last 7 bits
1414 // f = facility code, c = card number
1415 // w = wiegand parity, x = extra space for other formats
1416 // p = unknown checksum
1417 // (26 bit format shown)
1418
1419 //find start bit to get fmtLen
1420 int j;
1421 for (j=0; j<size; j++){
1422 if(BitStream[j]) break;
1423 }
1424 uint8_t fmtLen = size-j-8;
1425 uint32_t fc = 0;
1426 uint32_t cardnum = 0;
1427 uint32_t code1 = 0;
1428 //uint32_t code2 = 0;
1429 if (fmtLen==26){
1430 fc = bytebits_to_byte(BitStream+73, 8);
1431 cardnum = bytebits_to_byte(BitStream+81, 16);
1432 code1 = bytebits_to_byte(BitStream+72,fmtLen);
1433 PrintAndLog("Pyramid ID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi3, rawHi2, rawHi, rawLo);
1434 } else if (fmtLen==45){
1435 fmtLen=42; //end = 10 bits not 7 like 26 bit fmt
1436 fc = bytebits_to_byte(BitStream+53, 10);
1437 cardnum = bytebits_to_byte(BitStream+63, 32);
1438 PrintAndLog("Pyramid ID Found - BitLength: %d, FC: %d, Card: %d - Raw: %08x%08x%08x%08x", fmtLen, fc, cardnum, rawHi3, rawHi2, rawHi, rawLo);
1439 } else {
1440 cardnum = bytebits_to_byte(BitStream+81, 16);
1441 if (fmtLen>32){
1442 //code1 = bytebits_to_byte(BitStream+(size-fmtLen),fmtLen-32);
1443 //code2 = bytebits_to_byte(BitStream+(size-32),32);
1444 PrintAndLog("Pyramid ID Found - BitLength: %d -unknown BitLength- (%d), Raw: %08x%08x%08x%08x", fmtLen, cardnum, rawHi3, rawHi2, rawHi, rawLo);
1445 } else{
1446 //code1 = bytebits_to_byte(BitStream+(size-fmtLen),fmtLen);
1447 PrintAndLog("Pyramid ID Found - BitLength: %d -unknown BitLength- (%d), Raw: %08x%08x%08x%08x", fmtLen, cardnum, rawHi3, rawHi2, rawHi, rawLo);
1448 }
1449 }
1450 if (checksum == checkCS)
1451 PrintAndLog("Checksum %02x passed", checksum);
1452 else
1453 PrintAndLog("Checksum %02x failed - should have been %02x", checksum, checkCS);
1454
1455 if (g_debugMode){
1456 PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, 128);
1457 printDemodBuff();
1458 }
1459 return 1;
1e090a61 1460}
1461
ad6219fc 1462// FDX-B ISO11784/85 demod (aka animal tag) BIPHASE, inverted, rf/32, with preamble of 00000000001 (128bits)
7f96433c 1463// 8 databits + 1 parity (1)
0df669a2 1464// CIITT 16 chksum
1465// NATIONAL CODE, ICAR database
ad6219fc 1466// COUNTRY CODE (ISO3166) or http://cms.abvma.ca/uploads/ManufacturersISOsandCountryCodes.pdf
0df669a2 1467// FLAG (animal/non-animal)
22a6a62f 1468/*
146938 IDbits
147010 country code
14711 extra app bit
147214 reserved bits
14731 animal bit
147416 ccitt CRC chksum over 64bit ID CODE.
147524 appli bits.
1476
ad6219fc 1477-- sample: 985121004515220 [ 37FF65B88EF94 ]
22a6a62f 1478*/
ad6219fc 1479int CmdFDXBdemodBI(const char *Cmd){
7f96433c 1480
1481 int invert = 1;
1482 int clk = 32;
1483 int errCnt = 0;
ad6219fc 1484 int maxErr = 0;
7f96433c 1485 uint8_t BitStream[MAX_DEMOD_BUF_LEN];
1486 size_t size = getFromGraphBuf(BitStream);
1487
ad6219fc 1488 errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0);
1489 if ( errCnt < 0 || errCnt > maxErr ) {
1490 if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: 32", errCnt);
0df669a2 1491 return 0;
1492 }
615f21dd 1493
ad6219fc 1494 errCnt = BiphaseRawDecode(BitStream, &size, maxErr, 1);
1495 if (errCnt < 0 || errCnt > maxErr ) {
7f96433c 1496 if (g_debugMode) PrintAndLog("Error BiphaseRawDecode: %d", errCnt);
0df669a2 1497 return 0;
7f96433c 1498 }
0df669a2 1499
ad6219fc 1500 int preambleIndex = FDXBdemodBI(BitStream, &size);
7f96433c 1501 if (preambleIndex < 0){
ad6219fc 1502 if (g_debugMode) PrintAndLog("Error FDXBDemod , no startmarker found :: %d",preambleIndex);
7f96433c 1503 return 0;
1504 }
0df669a2 1505
ad6219fc 1506 setDemodBuf(BitStream, 128, preambleIndex);
7f96433c 1507
ad6219fc 1508 size = removeParity(BitStream, preambleIndex + 11, 9, 2, 128-11);
1509 if ( size <= 103 ) {
1510 if (g_debugMode) PrintAndLog("Error removeParity:: %d", size);
1511 return 0;
0df669a2 1512 }
ad6219fc 1513 if (g_debugMode) {
1514 char *bin = sprint_bin_break(BitStream,size,16);
1515 PrintAndLog("DEBUG BinStream:\n%s",bin);
1516 }
1517 PrintAndLog("\nFDX-B / ISO 11784/5 Animal Tag ID Found:");
1518 if (g_debugMode) PrintAndLog("startmarker %d; Size %d", preambleIndex, size);
1519
1520 //got a good demod
1521
1522 //marshmellows
1523 uint64_t NationalCode = ((uint64_t)(bytebits_to_byteLSBF(BitStream+32,6)) << 32) | bytebits_to_byteLSBF(BitStream,32);
1524 uint32_t countryCode = bytebits_to_byteLSBF(BitStream+38,10);
1525 uint8_t dataBlockBit = BitStream[48];
1526 uint32_t reservedCode = bytebits_to_byteLSBF(BitStream+49,14);
1527 uint8_t animalBit = BitStream[63];
1528
1529 uint16_t crc16 = bytebits_to_byteLSBF(BitStream+64,16);
1530 uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24);
1531
1532 uint64_t rawid = ((uint64_t)bytebits_to_byte(BitStream+32,32) << 32) | bytebits_to_byte(BitStream,32);
1533 uint8_t raw[8];
1534 num_to_bytes(rawid, 8, raw);
1535 PrintAndLog("%s", sprint_hex(raw,8));
1536 uint16_t crcCalc = crc16_ccitt_rev( raw ,8);
1537
1538 PrintAndLog("Animal ID: %u-%012llu", countryCode, NationalCode);
1539 PrintAndLog("National Code: %012llu", NationalCode);
1540 PrintAndLog("CountryCode: %u", countryCode);
1541 PrintAndLog("Extended Data: %s", dataBlockBit ? "True" : "False");
1542 PrintAndLog("reserved Code: %u", reservedCode);
1543 PrintAndLog("Animal Tag: %s", animalBit ? "True" : "False");
1544 PrintAndLog("CRC: 0x%02X", crc16);
1545 PrintAndLog("CRC : %X == %X %s", crc16, crcCalc, ( crcCalc == crc16 )?"ok":"!" );
1546 PrintAndLog("Extended: 0x%X", extended);
1547
1548/*
1549 //uint16_t crcCalc = crc16_ccitt( ByteStream, 8);
1550 PrintAndLog("Application ID: %04X", applicationid);
1551 */
615f21dd 1552 return 1;
22a6a62f 1553
615f21dd 1554}
1555
1556
e770c648 1557//by marshmellow
1558//attempt to psk1 demod graph buffer
4ac906d1 1559int PSKDemod(const char *Cmd, bool verbose)
e770c648 1560{
e0165dcf 1561 int invert=0;
1562 int clk=0;
1563 int maxErr=100;
1564 sscanf(Cmd, "%i %i %i", &clk, &invert, &maxErr);
1565 if (clk==1){
1566 invert=1;
1567 clk=0;
1568 }
1569 if (invert != 0 && invert != 1) {
1570 if (verbose) PrintAndLog("Invalid argument: %s", Cmd);
1571 return 0;
1572 }
1573 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1574 size_t BitLen = getFromGraphBuf(BitStream);
1575 if (BitLen==0) return -1;
2eec55c8 1576 uint8_t carrier=countFC(BitStream, BitLen, 0);
e0165dcf 1577 if (carrier!=2 && carrier!=4 && carrier!=8){
1578 //invalid carrier
1579 return 0;
1580 }
1581 int errCnt=0;
1582 errCnt = pskRawDemod(BitStream, &BitLen, &clk, &invert);
1583 if (errCnt > maxErr){
2767fc02 1584 if (g_debugMode || verbose) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt);
e0165dcf 1585 return 0;
1586 }
1587 if (errCnt<0|| BitLen<16){ //throw away static - allow 1 and -1 (in case of threshold command first)
2767fc02 1588 if (g_debugMode || verbose) PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt);
e0165dcf 1589 return 0;
1590 }
2767fc02 1591 if (verbose || g_debugMode){
1592 PrintAndLog("\nUsing Clock:%d, invert:%d, Bits Found:%d",clk,invert,BitLen);
e0165dcf 1593 if (errCnt>0){
2767fc02 1594 PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt);
e0165dcf 1595 }
1596 }
1597 //prime demod buffer for output
1598 setDemodBuf(BitStream,BitLen,0);
1599 return 1;
4118b74d 1600}
e770c648 1601
4118b74d 1602// Indala 26 bit decode
1603// by marshmellow
1604// optional arguments - same as CmdpskNRZrawDemod (clock & invert)
1605int CmdIndalaDecode(const char *Cmd)
1606{
b4fb11ba 1607 int ans;
1608 if (strlen(Cmd)>0){
1609 ans = PSKDemod(Cmd, 0);
1610 } else{ //default to RF/32
1611 ans = PSKDemod("32", 0);
1612 }
4118b74d 1613
7a8a982b 1614 if (!ans){
ec75f5c1 1615 if (g_debugMode==1)
b4fb11ba 1616 PrintAndLog("Error1: %d",ans);
ba1a299c 1617 return 0;
1618 }
1619 uint8_t invert=0;
2b3af97d 1620 ans = indala26decode(DemodBuffer, &DemodBufferLen, &invert);
ba1a299c 1621 if (ans < 1) {
ec75f5c1 1622 if (g_debugMode==1)
b4fb11ba 1623 PrintAndLog("Error2: %d",ans);
ba1a299c 1624 return -1;
1625 }
a1d17964 1626 char showbits[251]={0x00};
84871873 1627 if (invert)
b4fb11ba 1628 if (g_debugMode==1)
e0165dcf 1629 PrintAndLog("Had to invert bits");
ec75f5c1 1630
ba1a299c 1631 //convert UID to HEX
1632 uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7;
1633 int idx;
1634 uid1=0;
1635 uid2=0;
1636 PrintAndLog("BitLen: %d",DemodBufferLen);
1637 if (DemodBufferLen==64){
1638 for( idx=0; idx<64; idx++) {
1639 uid1=(uid1<<1)|(uid2>>31);
1640 if (DemodBuffer[idx] == 0) {
1641 uid2=(uid2<<1)|0;
1642 showbits[idx]='0';
1643 } else {
1644 uid2=(uid2<<1)|1;
1645 showbits[idx]='1';
1646 }
1647 }
1648 showbits[idx]='\0';
1649 PrintAndLog("Indala UID=%s (%x%08x)", showbits, uid1, uid2);
1650 }
1651 else {
1652 uid3=0;
1653 uid4=0;
1654 uid5=0;
1655 uid6=0;
1656 uid7=0;
1657 for( idx=0; idx<DemodBufferLen; idx++) {
1658 uid1=(uid1<<1)|(uid2>>31);
1659 uid2=(uid2<<1)|(uid3>>31);
1660 uid3=(uid3<<1)|(uid4>>31);
1661 uid4=(uid4<<1)|(uid5>>31);
1662 uid5=(uid5<<1)|(uid6>>31);
1663 uid6=(uid6<<1)|(uid7>>31);
1664 if (DemodBuffer[idx] == 0) {
1665 uid7=(uid7<<1)|0;
1666 showbits[idx]='0';
1667 }
1668 else {
1669 uid7=(uid7<<1)|1;
1670 showbits[idx]='1';
1671 }
1672 }
1673 showbits[idx]='\0';
1674 PrintAndLog("Indala UID=%s (%x%08x%08x%08x%08x%08x%08x)", showbits, uid1, uid2, uid3, uid4, uid5, uid6, uid7);
1675 }
b4fb11ba 1676 if (g_debugMode){
1677 PrintAndLog("DEBUG: printing demodbuffer:");
1678 printDemodBuff();
1679 }
ba1a299c 1680 return 1;
4118b74d 1681}
1682
411105e0 1683int CmdPSKNexWatch(const char *Cmd)
1684{
1685 if (!PSKDemod("", false)) return 0;
1686 uint8_t preamble[28] = {0,0,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
1687 size_t startIdx = 0, size = DemodBufferLen;
1688 bool invert = false;
1689 if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)){
1690 // if didn't find preamble try again inverting
1691 if (!PSKDemod("1", false)) return 0;
1692 size = DemodBufferLen;
1693 if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)) return 0;
1694 invert = true;
1695 }
1696 if (size != 128) return 0;
1697 setDemodBuf(DemodBuffer, size, startIdx+4);
1698 startIdx = 8+32; //4 = extra i added, 8 = preamble, 32 = reserved bits (always 0)
1699 //get ID
1700 uint32_t ID = 0;
1701 for (uint8_t wordIdx=0; wordIdx<4; wordIdx++){
1702 for (uint8_t idx=0; idx<8; idx++){
1703 ID = (ID << 1) | DemodBuffer[startIdx+wordIdx+(idx*4)];
1704 }
1705 }
1706 //parity check (TBD)
1707
1708 //checksum check (TBD)
1709
1710 //output
1711 PrintAndLog("NexWatch ID: %d", ID);
1712 if (invert){
1713 PrintAndLog("Had to Invert - probably NexKey");
1714 for (uint8_t idx=0; idx<size; idx++)
1715 DemodBuffer[idx] ^= 1;
1716 }
1717
1718 CmdPrintDemodBuff("x");
1719 return 1;
1720}
1721
04d2721b 1722// by marshmellow
e770c648 1723// takes 3 arguments - clock, invert, maxErr as integers
1724// attempts to demodulate nrz only
1725// prints binary found and saves in demodbuffer for further commands
b4a2fcf6 1726int NRZrawDemod(const char *Cmd, bool verbose)
e770c648 1727{
e0165dcf 1728 int invert=0;
1729 int clk=0;
1730 int maxErr=100;
1731 sscanf(Cmd, "%i %i %i", &clk, &invert, &maxErr);
1732 if (clk==1){
1733 invert=1;
1734 clk=0;
1735 }
1736 if (invert != 0 && invert != 1) {
1737 PrintAndLog("Invalid argument: %s", Cmd);
1738 return 0;
1739 }
1740 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
1741 size_t BitLen = getFromGraphBuf(BitStream);
1742 if (BitLen==0) return 0;
1743 int errCnt=0;
1744 errCnt = nrzRawDemod(BitStream, &BitLen, &clk, &invert, maxErr);
1745 if (errCnt > maxErr){
1746 if (g_debugMode) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt);
1747 return 0;
1748 }
2eec55c8 1749 if (errCnt<0 || BitLen<16){ //throw away static - allow 1 and -1 (in case of threshold command first)
e0165dcf 1750 if (g_debugMode) PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt);
1751 return 0;
1752 }
1753 if (verbose || g_debugMode) PrintAndLog("Tried NRZ Demod using Clock: %d - invert: %d - Bits Found: %d",clk,invert,BitLen);
1754 //prime demod buffer for output
1755 setDemodBuf(BitStream,BitLen,0);
1756
2767fc02 1757 if (errCnt>0 && (verbose || g_debugMode)) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt);
e0165dcf 1758 if (verbose || g_debugMode) {
1759 PrintAndLog("NRZ demoded bitstream:");
1760 // Now output the bitstream to the scrollback by line of 16 bits
1761 printDemodBuff();
1762 }
1763 return 1;
b4a2fcf6 1764}
1765
1766int CmdNRZrawDemod(const char *Cmd)
1767{
e0165dcf 1768 char cmdp = param_getchar(Cmd, 0);
1769 if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') {
1770 PrintAndLog("Usage: data rawdemod nr [clock] <0|1> [maxError]");
1771 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
1772 PrintAndLog(" <invert>, 1 for invert output");
1773 PrintAndLog(" [set maximum allowed errors], default = 100.");
1774 PrintAndLog("");
1775 PrintAndLog(" sample: data rawdemod nr = demod a nrz/direct tag from GraphBuffer");
1776 PrintAndLog(" : data rawdemod nr 32 = demod a nrz/direct tag from GraphBuffer using a clock of RF/32");
1777 PrintAndLog(" : data rawdemod nr 32 1 = demod a nrz/direct tag from GraphBuffer using a clock of RF/32 and inverting data");
1778 PrintAndLog(" : data rawdemod nr 1 = demod a nrz/direct tag from GraphBuffer while inverting data");
1779 PrintAndLog(" : data rawdemod nr 64 1 0 = demod a nrz/direct tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
1780 return 0;
1781 }
1782 return NRZrawDemod(Cmd, TRUE);
e770c648 1783}
1784
1785// by marshmellow
1786// takes 3 arguments - clock, invert, maxErr as integers
04d2721b 1787// attempts to demodulate psk only
1788// prints binary found and saves in demodbuffer for further commands
e770c648 1789int CmdPSK1rawDemod(const char *Cmd)
4118b74d 1790{
e0165dcf 1791 int ans;
1792 char cmdp = param_getchar(Cmd, 0);
1793 if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') {
1794 PrintAndLog("Usage: data rawdemod p1 [clock] <0|1> [maxError]");
1795 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
1796 PrintAndLog(" <invert>, 1 for invert output");
1797 PrintAndLog(" [set maximum allowed errors], default = 100.");
1798 PrintAndLog("");
1799 PrintAndLog(" sample: data rawdemod p1 = demod a psk1 tag from GraphBuffer");
1800 PrintAndLog(" : data rawdemod p1 32 = demod a psk1 tag from GraphBuffer using a clock of RF/32");
1801 PrintAndLog(" : data rawdemod p1 32 1 = demod a psk1 tag from GraphBuffer using a clock of RF/32 and inverting data");
1802 PrintAndLog(" : data rawdemod p1 1 = demod a psk1 tag from GraphBuffer while inverting data");
1803 PrintAndLog(" : data rawdemod p1 64 1 0 = demod a psk1 tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors");
1804 return 0;
1805 }
1806 ans = PSKDemod(Cmd, TRUE);
1807 //output
1808 if (!ans){
1809 if (g_debugMode) PrintAndLog("Error demoding: %d",ans);
1810 return 0;
1811 }
7a8a982b 1812
2767fc02 1813 PrintAndLog("PSK1 demoded bitstream:");
e0165dcf 1814 // Now output the bitstream to the scrollback by line of 16 bits
1815 printDemodBuff();
1816 return 1;
4118b74d 1817}
1818
04d2721b 1819// by marshmellow
19ff0210 1820// takes same args as cmdpsk1rawdemod
04d2721b 1821int CmdPSK2rawDemod(const char *Cmd)
1822{
e0165dcf 1823 int ans=0;
1824 char cmdp = param_getchar(Cmd, 0);
1825 if (strlen(Cmd) > 10 || cmdp == 'h' || cmdp == 'H') {
1826 PrintAndLog("Usage: data rawdemod p2 [clock] <0|1> [maxError]");
1827 PrintAndLog(" [set clock as integer] optional, if not set, autodetect.");
1828 PrintAndLog(" <invert>, 1 for invert output");
1829 PrintAndLog(" [set maximum allowed errors], default = 100.");
1830 PrintAndLog("");
1831 PrintAndLog(" sample: data rawdemod p2 = demod a psk2 tag from GraphBuffer, autodetect clock");
1832 PrintAndLog(" : data rawdemod p2 32 = demod a psk2 tag from GraphBuffer using a clock of RF/32");
1833 PrintAndLog(" : data rawdemod p2 32 1 = demod a psk2 tag from GraphBuffer using a clock of RF/32 and inverting output");
1834 PrintAndLog(" : data rawdemod p2 1 = demod a psk2 tag from GraphBuffer, autodetect clock and invert output");
1835 PrintAndLog(" : data rawdemod p2 64 1 0 = demod a psk2 tag from GraphBuffer using a clock of RF/64, inverting output and allowing 0 demod errors");
1836 return 0;
1837 }
1838 ans=PSKDemod(Cmd, TRUE);
1839 if (!ans){
1840 if (g_debugMode) PrintAndLog("Error demoding: %d",ans);
1841 return 0;
1842 }
1843 psk1TOpsk2(DemodBuffer, DemodBufferLen);
1844 PrintAndLog("PSK2 demoded bitstream:");
1845 // Now output the bitstream to the scrollback by line of 16 bits
1846 printDemodBuff();
1847 return 1;
04d2721b 1848}
1849
19ff0210 1850// by marshmellow - combines all raw demod functions into one menu command
1851int CmdRawDemod(const char *Cmd)
1852{
1853 char cmdp = Cmd[0]; //param_getchar(Cmd, 0);
1854
23f0a7d8 1855 if (strlen(Cmd) > 20 || cmdp == 'h' || cmdp == 'H' || strlen(Cmd)<2) {
19ff0210 1856 PrintAndLog("Usage: data rawdemod [modulation] <help>|<options>");
b41534d1 1857 PrintAndLog(" [modulation] as 2 char, 'ab' for ask/biphase, 'am' for ask/manchester, 'ar' for ask/raw, 'fs' for fsk, ...");
1858 PrintAndLog(" 'nr' for nrz/direct, 'p1' for psk1, 'p2' for psk2");
19ff0210 1859 PrintAndLog(" <help> as 'h', prints the help for the specific modulation");
1860 PrintAndLog(" <options> see specific modulation help for optional parameters");
1861 PrintAndLog("");
1fbf8956 1862 PrintAndLog(" sample: data rawdemod fs h = print help specific to fsk demod");
19ff0210 1863 PrintAndLog(" : data rawdemod fs = demod GraphBuffer using: fsk - autodetect");
b41534d1 1864 PrintAndLog(" : data rawdemod ab = demod GraphBuffer using: ask/biphase - autodetect");
19ff0210 1865 PrintAndLog(" : data rawdemod am = demod GraphBuffer using: ask/manchester - autodetect");
1866 PrintAndLog(" : data rawdemod ar = demod GraphBuffer using: ask/raw - autodetect");
1867 PrintAndLog(" : data rawdemod nr = demod GraphBuffer using: nrz/direct - autodetect");
1868 PrintAndLog(" : data rawdemod p1 = demod GraphBuffer using: psk1 - autodetect");
1869 PrintAndLog(" : data rawdemod p2 = demod GraphBuffer using: psk2 - autodetect");
1870 return 0;
1871 }
1872 char cmdp2 = Cmd[1];
1873 int ans = 0;
1874 if (cmdp == 'f' && cmdp2 == 's'){
f8f894a5 1875 ans = CmdFSKrawdemod(Cmd+2);
b41534d1 1876 } else if(cmdp == 'a' && cmdp2 == 'b'){
f8f894a5 1877 ans = Cmdaskbiphdemod(Cmd+2);
19ff0210 1878 } else if(cmdp == 'a' && cmdp2 == 'm'){
f8f894a5 1879 ans = Cmdaskmandemod(Cmd+2);
19ff0210 1880 } else if(cmdp == 'a' && cmdp2 == 'r'){
f8f894a5 1881 ans = Cmdaskrawdemod(Cmd+2);
19ff0210 1882 } else if(cmdp == 'n' && cmdp2 == 'r'){
f8f894a5 1883 ans = CmdNRZrawDemod(Cmd+2);
19ff0210 1884 } else if(cmdp == 'p' && cmdp2 == '1'){
f8f894a5 1885 ans = CmdPSK1rawDemod(Cmd+2);
19ff0210 1886 } else if(cmdp == 'p' && cmdp2 == '2'){
f8f894a5 1887 ans = CmdPSK2rawDemod(Cmd+2);
19ff0210 1888 } else {
1889 PrintAndLog("unknown modulation entered - see help ('h') for parameter structure");
1890 }
1891 return ans;
1892}
1893
7fe9b0b7 1894int CmdGrid(const char *Cmd)
1895{
e0165dcf 1896 sscanf(Cmd, "%i %i", &PlotGridX, &PlotGridY);
1897 PlotGridXdefault= PlotGridX;
1898 PlotGridYdefault= PlotGridY;
1899 RepaintGraphWindow();
1900 return 0;
7fe9b0b7 1901}
1902
1903int CmdHexsamples(const char *Cmd)
1904{
e0165dcf 1905 int i, j;
1906 int requested = 0;
1907 int offset = 0;
1908 char string_buf[25];
1909 char* string_ptr = string_buf;
1910 uint8_t got[BIGBUF_SIZE];
1911
1912 sscanf(Cmd, "%i %i", &requested, &offset);
1913
1914 /* if no args send something */
1915 if (requested == 0) {
1916 requested = 8;
1917 }
1918 if (offset + requested > sizeof(got)) {
1919 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > %d", BIGBUF_SIZE);
1920 return 0;
1921 }
1922
1923 GetFromBigBuf(got,requested,offset);
1924 WaitForResponse(CMD_ACK,NULL);
1925
1926 i = 0;
1927 for (j = 0; j < requested; j++) {
1928 i++;
1929 string_ptr += sprintf(string_ptr, "%02x ", got[j]);
1930 if (i == 8) {
1931 *(string_ptr - 1) = '\0'; // remove the trailing space
1932 PrintAndLog("%s", string_buf);
1933 string_buf[0] = '\0';
1934 string_ptr = string_buf;
1935 i = 0;
1936 }
1937 if (j == requested - 1 && string_buf[0] != '\0') { // print any remaining bytes
1938 *(string_ptr - 1) = '\0';
1939 PrintAndLog("%s", string_buf);
1940 string_buf[0] = '\0';
1941 }
1942 }
1943 return 0;
7fe9b0b7 1944}
1945
7fe9b0b7 1946int CmdHide(const char *Cmd)
1947{
e0165dcf 1948 HideGraphWindow();
1949 return 0;
7fe9b0b7 1950}
1951
78f5b1a7 1952//zero mean GraphBuffer
7fe9b0b7 1953int CmdHpf(const char *Cmd)
1954{
e0165dcf 1955 int i;
1956 int accum = 0;
7fe9b0b7 1957
e0165dcf 1958 for (i = 10; i < GraphTraceLen; ++i)
1959 accum += GraphBuffer[i];
1960 accum /= (GraphTraceLen - 10);
1961 for (i = 0; i < GraphTraceLen; ++i)
1962 GraphBuffer[i] -= accum;
7fe9b0b7 1963
e0165dcf 1964 RepaintGraphWindow();
1965 return 0;
7fe9b0b7 1966}
f6d9fb17
MHS
1967typedef struct {
1968 uint8_t * buffer;
1969 uint32_t numbits;
1970 uint32_t position;
ad6219fc 1971} BitstreamOut;
f6d9fb17
MHS
1972
1973bool _headBit( BitstreamOut *stream)
1974{
1975 int bytepos = stream->position >> 3; // divide by 8
1976 int bitpos = (stream->position++) & 7; // mask out 00000111
1977 return (*(stream->buffer + bytepos) >> (7-bitpos)) & 1;
1978}
1979
1980uint8_t getByte(uint8_t bits_per_sample, BitstreamOut* b)
1981{
1982 int i;
1983 uint8_t val = 0;
1984 for(i =0 ; i < bits_per_sample; i++)
1985 {
1986 val |= (_headBit(b) << (7-i));
1987 }
1988 return val;
1989}
7fe9b0b7 1990
1fbf8956 1991int getSamples(const char *Cmd, bool silent)
7fe9b0b7 1992{
e0165dcf 1993 //If we get all but the last byte in bigbuf,
1994 // we don't have to worry about remaining trash
1995 // in the last byte in case the bits-per-sample
1996 // does not line up on byte boundaries
1997
1998 uint8_t got[BIGBUF_SIZE-1] = { 0 };
1999
2000 int n = strtol(Cmd, NULL, 0);
2001
2002 if (n == 0)
2003 n = sizeof(got);
2004
2005 if (n > sizeof(got))
2006 n = sizeof(got);
2007
2008 PrintAndLog("Reading %d bytes from device memory\n", n);
2009 GetFromBigBuf(got,n,0);
2010 PrintAndLog("Data fetched");
2011 UsbCommand response;
2012 WaitForResponse(CMD_ACK, &response);
2013 uint8_t bits_per_sample = 8;
2014
2015 //Old devices without this feature would send 0 at arg[0]
2016 if(response.arg[0] > 0)
2017 {
2018 sample_config *sc = (sample_config *) response.d.asBytes;
2019 PrintAndLog("Samples @ %d bits/smpl, decimation 1:%d ", sc->bits_per_sample
2020 , sc->decimation);
2021 bits_per_sample = sc->bits_per_sample;
2022 }
2023 if(bits_per_sample < 8)
2024 {
2025 PrintAndLog("Unpacking...");
2026 BitstreamOut bout = { got, bits_per_sample * n, 0};
2027 int j =0;
e6432f05 2028 for (j = 0; j * bits_per_sample < n * 8 && j < n; j++) {
e0165dcf 2029 uint8_t sample = getByte(bits_per_sample, &bout);
2030 GraphBuffer[j] = ((int) sample )- 128;
2031 }
2032 GraphTraceLen = j;
2033 PrintAndLog("Unpacked %d samples" , j );
2034 }else
2035 {
2036 for (int j = 0; j < n; j++) {
2037 GraphBuffer[j] = ((int)got[j]) - 128;
2038 }
2039 GraphTraceLen = n;
2040 }
2041
2042 RepaintGraphWindow();
2043 return 0;
1fbf8956 2044}
2045
2046int CmdSamples(const char *Cmd)
2047{
e0165dcf 2048 return getSamples(Cmd, false);
7fe9b0b7 2049}
2050
d6a120a2
MHS
2051int CmdTuneSamples(const char *Cmd)
2052{
3aa4014b 2053 int timeout = 0;
2054 printf("\nMeasuring antenna characteristics, please wait...");
ba1a299c 2055
3aa4014b 2056 UsbCommand c = {CMD_MEASURE_ANTENNA_TUNING};
2057 SendCommand(&c);
2058
2059 UsbCommand resp;
2060 while(!WaitForResponseTimeout(CMD_MEASURED_ANTENNA_TUNING,&resp,1000)) {
2061 timeout++;
2062 printf(".");
2063 if (timeout > 7) {
2064 PrintAndLog("\nNo response from Proxmark. Aborting...");
2065 return 1;
2066 }
2067 }
2068
2069 int peakv, peakf;
2070 int vLf125, vLf134, vHf;
2071 vLf125 = resp.arg[0] & 0xffff;
2072 vLf134 = resp.arg[0] >> 16;
2073 vHf = resp.arg[1] & 0xffff;;
2074 peakf = resp.arg[2] & 0xffff;
2075 peakv = resp.arg[2] >> 16;
2076 PrintAndLog("");
2077 PrintAndLog("# LF antenna: %5.2f V @ 125.00 kHz", vLf125/1000.0);
2078 PrintAndLog("# LF antenna: %5.2f V @ 134.00 kHz", vLf134/1000.0);
2079 PrintAndLog("# LF optimal: %5.2f V @%9.2f kHz", peakv/1000.0, 12000.0/(peakf+1));
2080 PrintAndLog("# HF antenna: %5.2f V @ 13.56 MHz", vHf/1000.0);
0d0d0499 2081
2767fc02 2082 #define LF_UNUSABLE_V 2948 // was 2000. Changed due to bugfix in voltage measurements. LF results are now 47% higher.
2083 #define LF_MARGINAL_V 14739 // was 10000. Changed due to bugfix bug in voltage measurements. LF results are now 47% higher.
2084 #define HF_UNUSABLE_V 3167 // was 2000. Changed due to bugfix in voltage measurements. HF results are now 58% higher.
2085 #define HF_MARGINAL_V 7917 // was 5000. Changed due to bugfix in voltage measurements. HF results are now 58% higher.
0d0d0499 2086
2087 if (peakv < LF_UNUSABLE_V)
3aa4014b 2088 PrintAndLog("# Your LF antenna is unusable.");
0d0d0499 2089 else if (peakv < LF_MARGINAL_V)
3aa4014b 2090 PrintAndLog("# Your LF antenna is marginal.");
0d0d0499 2091 if (vHf < HF_UNUSABLE_V)
3aa4014b 2092 PrintAndLog("# Your HF antenna is unusable.");
0d0d0499 2093 else if (vHf < HF_MARGINAL_V)
3aa4014b 2094 PrintAndLog("# Your HF antenna is marginal.");
2095
0d0d0499 2096 if (peakv >= LF_UNUSABLE_V) {
2097 for (int i = 0; i < 256; i++) {
2098 GraphBuffer[i] = resp.d.asBytes[i] - 128;
2099 }
2100 PrintAndLog("Displaying LF tuning graph. Divisor 89 is 134khz, 95 is 125khz.\n");
2101 PrintAndLog("\n");
2102 GraphTraceLen = 256;
2103 ShowGraphWindow();
abd16c45 2104 RepaintGraphWindow();
ba1a299c 2105 }
2106
b4fb11ba 2107 return 0;
d6a120a2
MHS
2108}
2109
3aa4014b 2110
7fe9b0b7 2111int CmdLoad(const char *Cmd)
2112{
e0165dcf 2113 char filename[FILE_PATH_SIZE] = {0x00};
2114 int len = 0;
b915fda3 2115
e0165dcf 2116 len = strlen(Cmd);
2117 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
2118 memcpy(filename, Cmd, len);
b915fda3 2119
e0165dcf 2120 FILE *f = fopen(filename, "r");
2121 if (!f) {
2122 PrintAndLog("couldn't open '%s'", filename);
2123 return 0;
2124 }
2125
2126 GraphTraceLen = 0;
2127 char line[80];
2128 while (fgets(line, sizeof (line), f)) {
2129 GraphBuffer[GraphTraceLen] = atoi(line);
2130 GraphTraceLen++;
2131 }
2132 fclose(f);
2133 PrintAndLog("loaded %d samples", GraphTraceLen);
2134 RepaintGraphWindow();
2135 return 0;
7fe9b0b7 2136}
2137
2138int CmdLtrim(const char *Cmd)
2139{
e0165dcf 2140 int ds = atoi(Cmd);
cc15a118 2141 if (GraphTraceLen<=0) return 0;
e0165dcf 2142 for (int i = ds; i < GraphTraceLen; ++i)
2143 GraphBuffer[i-ds] = GraphBuffer[i];
2144 GraphTraceLen -= ds;
7fe9b0b7 2145
e0165dcf 2146 RepaintGraphWindow();
2147 return 0;
7fe9b0b7 2148}
ec75f5c1 2149
2150// trim graph to input argument length
9ec1416a 2151int CmdRtrim(const char *Cmd)
2152{
e0165dcf 2153 int ds = atoi(Cmd);
9ec1416a 2154
e0165dcf 2155 GraphTraceLen = ds;
9ec1416a 2156
e0165dcf 2157 RepaintGraphWindow();
2158 return 0;
9ec1416a 2159}
7fe9b0b7 2160
7fe9b0b7 2161int CmdNorm(const char *Cmd)
2162{
e0165dcf 2163 int i;
2164 int max = INT_MIN, min = INT_MAX;
7fe9b0b7 2165
e0165dcf 2166 for (i = 10; i < GraphTraceLen; ++i) {
2167 if (GraphBuffer[i] > max)
2168 max = GraphBuffer[i];
2169 if (GraphBuffer[i] < min)
2170 min = GraphBuffer[i];
2171 }
7fe9b0b7 2172
e0165dcf 2173 if (max != min) {
2174 for (i = 0; i < GraphTraceLen; ++i) {
ba1a299c 2175 GraphBuffer[i] = (GraphBuffer[i] - ((max + min) / 2)) * 256 /
e0165dcf 2176 (max - min);
ba1a299c 2177 //marshmelow: adjusted *1000 to *256 to make +/- 128 so demod commands still work
e0165dcf 2178 }
2179 }
2180 RepaintGraphWindow();
2181 return 0;
7fe9b0b7 2182}
2183
2184int CmdPlot(const char *Cmd)
2185{
e0165dcf 2186 ShowGraphWindow();
2187 return 0;
7fe9b0b7 2188}
2189
2190int CmdSave(const char *Cmd)
2191{
e0165dcf 2192 char filename[FILE_PATH_SIZE] = {0x00};
2193 int len = 0;
b915fda3 2194
e0165dcf 2195 len = strlen(Cmd);
2196 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
2197 memcpy(filename, Cmd, len);
2198
b915fda3 2199
e0165dcf 2200 FILE *f = fopen(filename, "w");
2201 if(!f) {
2202 PrintAndLog("couldn't open '%s'", filename);
2203 return 0;
2204 }
2205 int i;
2206 for (i = 0; i < GraphTraceLen; i++) {
2207 fprintf(f, "%d\n", GraphBuffer[i]);
2208 }
2209 fclose(f);
2210 PrintAndLog("saved to '%s'", Cmd);
2211 return 0;
7fe9b0b7 2212}
2213
2214int CmdScale(const char *Cmd)
2215{
e0165dcf 2216 CursorScaleFactor = atoi(Cmd);
2217 if (CursorScaleFactor == 0) {
2218 PrintAndLog("bad, can't have zero scale");
2219 CursorScaleFactor = 1;
2220 }
2221 RepaintGraphWindow();
2222 return 0;
7fe9b0b7 2223}
2224
d51b2eda
MHS
2225int CmdDirectionalThreshold(const char *Cmd)
2226{
e0165dcf 2227 int8_t upThres = param_get8(Cmd, 0);
2228 int8_t downThres = param_get8(Cmd, 1);
2229
2230 printf("Applying Up Threshold: %d, Down Threshold: %d\n", upThres, downThres);
2231
2232 int lastValue = GraphBuffer[0];
2233 GraphBuffer[0] = 0; // Will be changed at the end, but init 0 as we adjust to last samples value if no threshold kicks in.
2234
2235 for (int i = 1; i < GraphTraceLen; ++i) {
2236 // Apply first threshold to samples heading up
2237 if (GraphBuffer[i] >= upThres && GraphBuffer[i] > lastValue)
2238 {
2239 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
2240 GraphBuffer[i] = 1;
2241 }
2242 // Apply second threshold to samples heading down
2243 else if (GraphBuffer[i] <= downThres && GraphBuffer[i] < lastValue)
2244 {
2245 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
2246 GraphBuffer[i] = -1;
2247 }
2248 else
2249 {
2250 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
2251 GraphBuffer[i] = GraphBuffer[i-1];
2252
2253 }
2254 }
2255 GraphBuffer[0] = GraphBuffer[1]; // Aline with first edited sample.
2256 RepaintGraphWindow();
2257 return 0;
d51b2eda
MHS
2258}
2259
7fe9b0b7 2260int CmdZerocrossings(const char *Cmd)
2261{
e0165dcf 2262 // Zero-crossings aren't meaningful unless the signal is zero-mean.
2263 CmdHpf("");
2264
2265 int sign = 1;
2266 int zc = 0;
2267 int lastZc = 0;
2268
2269 for (int i = 0; i < GraphTraceLen; ++i) {
2270 if (GraphBuffer[i] * sign >= 0) {
2271 // No change in sign, reproduce the previous sample count.
2272 zc++;
2273 GraphBuffer[i] = lastZc;
2274 } else {
2275 // Change in sign, reset the sample count.
2276 sign = -sign;
2277 GraphBuffer[i] = lastZc;
2278 if (sign > 0) {
2279 lastZc = zc;
2280 zc = 0;
2281 }
2282 }
2283 }
2284
2285 RepaintGraphWindow();
2286 return 0;
7fe9b0b7 2287}
2288
ba1a299c 2289static command_t CommandTable[] =
7fe9b0b7 2290{
e0165dcf 2291 {"help", CmdHelp, 1, "This help"},
49bbc60a 2292 {"askedgedetect", CmdAskEdgeDetect, 1, "[threshold] Adjust Graph for manual ask demod using the length of sample differences to detect the edge of a wave (use 20-45, def:25)"},
e0165dcf 2293 {"askem410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"},
2294 {"askgproxiidemod", CmdG_Prox_II_Demod, 1, "Demodulate a G Prox II tag from GraphBuffer"},
2295 {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"},
fef74fdc 2296 {"biphaserawdecode",CmdBiphaseDecodeRaw,1, "[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"},
e0165dcf 2297 {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"},
e0165dcf 2298 {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"},
2299 {"dec", CmdDec, 1, "Decimate samples"},
2300 {"detectclock", CmdDetectClockRate, 1, "[modulation] Detect clock rate of wave in GraphBuffer (options: 'a','f','n','p' for ask, fsk, nrz, psk respectively)"},
ad6219fc 2301 {"fdxbdemod", CmdFDXBdemodBI , 1, "Demodulate a FDX-B ISO11784/85 Biphase tag from GraphBuffer"},
e0165dcf 2302 {"fskawiddemod", CmdFSKdemodAWID, 1, "Demodulate an AWID FSK tag from GraphBuffer"},
2303 //{"fskfcdetect", CmdFSKfcDetect, 1, "Try to detect the Field Clock of an FSK wave"},
2304 {"fskhiddemod", CmdFSKdemodHID, 1, "Demodulate a HID FSK tag from GraphBuffer"},
2305 {"fskiodemod", CmdFSKdemodIO, 1, "Demodulate an IO Prox FSK tag from GraphBuffer"},
2306 {"fskpyramiddemod", CmdFSKdemodPyramid, 1, "Demodulate a Pyramid FSK tag from GraphBuffer"},
2307 {"fskparadoxdemod", CmdFSKdemodParadox, 1, "Demodulate a Paradox FSK tag from GraphBuffer"},
2308 {"getbitstream", CmdGetBitStream, 1, "Convert GraphBuffer's >=1 values to 1 and <1 to 0"},
2309 {"grid", CmdGrid, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
2310 {"hexsamples", CmdHexsamples, 0, "<bytes> [<offset>] -- Dump big buffer as hex bytes"},
2311 {"hide", CmdHide, 1, "Hide graph window"},
2312 {"hpf", CmdHpf, 1, "Remove DC offset from trace"},
2313 {"load", CmdLoad, 1, "<filename> -- Load trace (to graph window"},
2314 {"ltrim", CmdLtrim, 1, "<samples> -- Trim samples from left of trace"},
2315 {"rtrim", CmdRtrim, 1, "<location to end trace> -- Trim samples from right of trace"},
fef74fdc 2316 {"manrawdecode", Cmdmandecoderaw, 1, "[invert] [maxErr] -- Manchester decode binary stream in DemodBuffer"},
e0165dcf 2317 {"norm", CmdNorm, 1, "Normalize max/min to +/-128"},
2318 {"plot", CmdPlot, 1, "Show graph window (hit 'h' in window for keystroke help)"},
2d2f7d19 2319 {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] [o] <offset> -- print the data in the DemodBuffer - 'x' for hex output"},
e0165dcf 2320 {"pskindalademod", CmdIndalaDecode, 1, "[clock] [invert<0|1>] -- Demodulate an indala tag (PSK1) from GraphBuffer (args optional)"},
411105e0 2321 {"psknexwatchdemod",CmdPSKNexWatch, 1, "Demodulate a NexWatch tag (nexkey, quadrakey) (PSK1) from GraphBuffer"},
e0165dcf 2322 {"rawdemod", CmdRawDemod, 1, "[modulation] ... <options> -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"},
2323 {"samples", CmdSamples, 0, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"},
2324 {"save", CmdSave, 1, "<filename> -- Save trace (from graph window)"},
2325 {"scale", CmdScale, 1, "<int> -- Set cursor display scale"},
2326 {"setdebugmode", CmdSetDebugMode, 1, "<0|1> -- Turn on or off Debugging Mode for demods"},
2327 {"shiftgraphzero", CmdGraphShiftZero, 1, "<shift> -- Shift 0 for Graphed wave + or - shift value"},
e0165dcf 2328 {"dirthreshold", CmdDirectionalThreshold, 1, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."},
2329 {"tune", CmdTuneSamples, 0, "Get hw tune samples for graph window"},
2330 {"undec", CmdUndec, 1, "Un-decimate samples by 2"},
2331 {"zerocrossings", CmdZerocrossings, 1, "Count time between zero-crossings"},
2332 {NULL, NULL, 0, NULL}
7fe9b0b7 2333};
2334
2335int CmdData(const char *Cmd)
2336{
e0165dcf 2337 CmdsParse(CommandTable, Cmd);
2338 return 0;
7fe9b0b7 2339}
2340
2341int CmdHelp(const char *Cmd)
2342{
e0165dcf 2343 CmdsHelp(CommandTable);
2344 return 0;
7fe9b0b7 2345}
Impressum, Datenschutz