]> git.zerfleddert.de Git - proxmark3-svn/blame - client/cmddata.c
Some more fixes to longer lf recordings. Now also supports longer snoops, and an...
[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
MHS
24#include "usb_cmd.h"
25
4118b74d 26uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN];
27int DemodBufferLen;
7fe9b0b7 28static int CmdHelp(const char *Cmd);
29
4118b74d 30//set the demod buffer with given array of binary (one bit per byte)
31//by marshmellow
ba1a299c 32void setDemodBuf(uint8_t *buff,int size)
4118b74d 33{
ba1a299c 34 int i=0;
35 for (; i < size; ++i){
36 DemodBuffer[i]=buff[i];
37 }
38 DemodBufferLen=size;
39 return;
4118b74d 40}
41
42//by marshmellow
43void printDemodBuff()
44{
ba1a299c 45 uint32_t i = 0;
46 int bitLen = DemodBufferLen;
47 if (bitLen<16) {
48 PrintAndLog("no bits found in demod buffer");
49 return;
50 }
51 if (bitLen>512) bitLen=512; //max output to 512 bits if we have more - should be plenty
52 for (i = 0; i <= (bitLen-16); i+=16) {
53 PrintAndLog("%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i",
54 DemodBuffer[i],
55 DemodBuffer[i+1],
56 DemodBuffer[i+2],
57 DemodBuffer[i+3],
58 DemodBuffer[i+4],
59 DemodBuffer[i+5],
60 DemodBuffer[i+6],
61 DemodBuffer[i+7],
62 DemodBuffer[i+8],
63 DemodBuffer[i+9],
64 DemodBuffer[i+10],
65 DemodBuffer[i+11],
66 DemodBuffer[i+12],
67 DemodBuffer[i+13],
68 DemodBuffer[i+14],
69 DemodBuffer[i+15]);
70 }
71 return;
4118b74d 72}
73
74
7fe9b0b7 75int CmdAmp(const char *Cmd)
76{
77 int i, rising, falling;
78 int max = INT_MIN, min = INT_MAX;
79
80 for (i = 10; i < GraphTraceLen; ++i) {
81 if (GraphBuffer[i] > max)
82 max = GraphBuffer[i];
83 if (GraphBuffer[i] < min)
84 min = GraphBuffer[i];
85 }
86
87 if (max != min) {
88 rising = falling= 0;
89 for (i = 0; i < GraphTraceLen; ++i) {
90 if (GraphBuffer[i + 1] < GraphBuffer[i]) {
91 if (rising) {
92 GraphBuffer[i] = max;
93 rising = 0;
94 }
95 falling = 1;
96 }
97 if (GraphBuffer[i + 1] > GraphBuffer[i]) {
98 if (falling) {
99 GraphBuffer[i] = min;
100 falling = 0;
101 }
102 rising= 1;
103 }
104 }
105 }
106 RepaintGraphWindow();
107 return 0;
108}
109
110/*
111 * Generic command to demodulate ASK.
112 *
113 * Argument is convention: positive or negative (High mod means zero
114 * or high mod means one)
115 *
116 * Updates the Graph trace with 0/1 values
117 *
118 * Arguments:
119 * c : 0 or 1
120 */
2fc2150e 121 //this method is dependant on all highs and lows to be the same(or clipped) this creates issues[marshmellow] it also ignores the clock
7fe9b0b7 122int Cmdaskdemod(const char *Cmd)
123{
124 int i;
125 int c, high = 0, low = 0;
ba1a299c 126
7fe9b0b7 127 // TODO: complain if we do not give 2 arguments here !
128 // (AL - this doesn't make sense! we're only using one argument!!!)
129 sscanf(Cmd, "%i", &c);
ba1a299c 130
7fe9b0b7 131 /* Detect high and lows and clock */
ba1a299c 132 // (AL - clock???)
7fe9b0b7 133 for (i = 0; i < GraphTraceLen; ++i)
134 {
135 if (GraphBuffer[i] > high)
136 high = GraphBuffer[i];
137 else if (GraphBuffer[i] < low)
138 low = GraphBuffer[i];
139 }
eb191de6 140 high=abs(high*.75);
141 low=abs(low*.75);
7fe9b0b7 142 if (c != 0 && c != 1) {
143 PrintAndLog("Invalid argument: %s", Cmd);
144 return 0;
145 }
b3b70669 146 //prime loop
7fe9b0b7 147 if (GraphBuffer[0] > 0) {
148 GraphBuffer[0] = 1-c;
149 } else {
150 GraphBuffer[0] = c;
151 }
152 for (i = 1; i < GraphTraceLen; ++i) {
153 /* Transitions are detected at each peak
154 * Transitions are either:
155 * - we're low: transition if we hit a high
156 * - we're high: transition if we hit a low
157 * (we need to do it this way because some tags keep high or
158 * low for long periods, others just reach the peak and go
159 * down)
160 */
ae2f73c1 161 //[marhsmellow] change == to >= for high and <= for low for fuzz
162 if ((GraphBuffer[i] == high) && (GraphBuffer[i - 1] == c)) {
7fe9b0b7 163 GraphBuffer[i] = 1 - c;
ae2f73c1 164 } else if ((GraphBuffer[i] == low) && (GraphBuffer[i - 1] == (1 - c))){
7fe9b0b7 165 GraphBuffer[i] = c;
166 } else {
167 /* No transition */
168 GraphBuffer[i] = GraphBuffer[i - 1];
169 }
170 }
171 RepaintGraphWindow();
172 return 0;
173}
174
d5a72d2f 175//by marshmellow
176void printBitStream(uint8_t BitStream[], uint32_t bitLen)
177{
2fc2150e 178 uint32_t i = 0;
179 if (bitLen<16) {
180 PrintAndLog("Too few bits found: %d",bitLen);
181 return;
182 }
183 if (bitLen>512) bitLen=512;
2df8c079 184 for (i = 0; i <= (bitLen-16); i+=16) {
2fc2150e 185 PrintAndLog("%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i",
186 BitStream[i],
187 BitStream[i+1],
188 BitStream[i+2],
189 BitStream[i+3],
190 BitStream[i+4],
191 BitStream[i+5],
192 BitStream[i+6],
193 BitStream[i+7],
194 BitStream[i+8],
195 BitStream[i+9],
196 BitStream[i+10],
197 BitStream[i+11],
198 BitStream[i+12],
199 BitStream[i+13],
200 BitStream[i+14],
201 BitStream[i+15]);
202 }
ba1a299c 203 return;
2fc2150e 204}
d5a72d2f 205//by marshmellow
ba1a299c 206//print EM410x ID in multiple formats
eb191de6 207void printEM410x(uint64_t id)
2fc2150e 208{
eb191de6 209 if (id !=0){
0e74c023 210 uint64_t iii=1;
211 uint64_t id2lo=0; //id2hi=0,
eb191de6 212 uint32_t ii=0;
213 uint32_t i=0;
0e74c023 214 for (ii=5; ii>0;ii--){
2fc2150e 215 for (i=0;i<8;i++){
ba1a299c 216 id2lo=(id2lo<<1LL) | ((id & (iii << (i+((ii-1)*8)))) >> (i+((ii-1)*8)));
2fc2150e 217 }
218 }
0e74c023 219 //output em id
eb191de6 220 PrintAndLog("EM TAG ID : %010llx", id);
0e74c023 221 PrintAndLog("Unique TAG ID: %010llx", id2lo); //id2hi,
eb191de6 222 PrintAndLog("DEZ 8 : %08lld",id & 0xFFFFFF);
223 PrintAndLog("DEZ 10 : %010lld",id & 0xFFFFFF);
224 PrintAndLog("DEZ 5.5 : %05lld.%05lld",(id>>16LL) & 0xFFFF,(id & 0xFFFF));
225 PrintAndLog("DEZ 3.5A : %03lld.%05lld",(id>>32ll),(id & 0xFFFF));
226 PrintAndLog("DEZ 14/IK2 : %014lld",id);
0e74c023 227 PrintAndLog("DEZ 15/IK3 : %015lld",id2lo);
eb191de6 228 PrintAndLog("Other : %05lld_%03lld_%08lld",(id&0xFFFF),((id>>16LL) & 0xFF),(id & 0xFFFFFF));
ba1a299c 229 }
eb191de6 230 return;
231}
232
d5a72d2f 233//by marshmellow
ba1a299c 234//take binary from demod buffer and see if we can find an EM410x ID
eb191de6 235int CmdEm410xDecode(const char *Cmd)
236{
237 uint64_t id=0;
4118b74d 238 // uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
239 // uint32_t i=0;
240 // i=getFromGraphBuf(BitStream);
ba1a299c 241 id = Em410xDecode(DemodBuffer,DemodBufferLen);
eb191de6 242 printEM410x(id);
d5a72d2f 243 if (id>0) return 1;
2fc2150e 244 return 0;
245}
246
f822a063 247
e888ed8e 248//by marshmellow
eb191de6 249//takes 2 arguments - clock and invert both as integers
ba1a299c 250//attempts to demodulate ask while decoding manchester
e888ed8e 251//prints binary found and saves in graphbuffer for further commands
9e6dd4eb 252int Cmdaskmandemod(const char *Cmd)
e888ed8e 253{
ba1a299c 254 int invert=0;
255 int clk=0;
eb191de6 256 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
ba1a299c 257 sscanf(Cmd, "%i %i", &clk, &invert);
e888ed8e 258 if (invert != 0 && invert != 1) {
259 PrintAndLog("Invalid argument: %s", Cmd);
260 return 0;
261 }
ba1a299c 262
263 size_t BitLen = getFromGraphBuf(BitStream);
f822a063 264 // PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen);
eb191de6 265 int errCnt=0;
266 errCnt = askmandemod(BitStream, &BitLen,&clk,&invert);
ba1a299c 267 if (errCnt<0||BitLen<16){ //if fatal error (or -1)
268 // PrintAndLog("no data found %d, errors:%d, bitlen:%d, clock:%d",errCnt,invert,BitLen,clk);
e888ed8e 269 return 0;
ba1a299c 270 }
f822a063 271 PrintAndLog("\nUsing Clock: %d - Invert: %d - Bits Found: %d",clk,invert,BitLen);
ba1a299c 272
d5a72d2f 273 //output
eb191de6 274 if (errCnt>0){
275 PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt);
e888ed8e 276 }
eb191de6 277 PrintAndLog("ASK/Manchester decoded bitstream:");
278 // Now output the bitstream to the scrollback by line of 16 bits
ba1a299c 279 setDemodBuf(BitStream,BitLen);
280 printDemodBuff();
eb191de6 281 uint64_t lo =0;
282 lo = Em410xDecode(BitStream,BitLen);
d5a72d2f 283 if (lo>0){
284 //set GraphBuffer for clone or sim command
d5a72d2f 285 PrintAndLog("EM410x pattern found: ");
286 printEM410x(lo);
ac914e56 287 return 1;
d5a72d2f 288 }
ac914e56 289 //if (BitLen>16) return 1;
eb191de6 290 return 0;
291}
292
293//by marshmellow
d5a72d2f 294//manchester decode
eb191de6 295//stricktly take 10 and 01 and convert to 0 and 1
296int Cmdmandecoderaw(const char *Cmd)
297{
298 int i =0;
299 int errCnt=0;
ba1a299c 300 size_t size=0;
eb191de6 301 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
302 int high=0,low=0;
ba1a299c 303 for (;i<DemodBufferLen;++i){
304 if (DemodBuffer[i]>high) high=DemodBuffer[i];
305 else if(DemodBuffer[i]<low) low=DemodBuffer[i];
306 BitStream[i]=DemodBuffer[i];
eb191de6 307 }
308 if (high>1 || low <0 ){
309 PrintAndLog("Error: please raw demod the wave first then mancheseter raw decode");
310 return 0;
311 }
ba1a299c 312 size=i;
313 errCnt=manrawdecode(BitStream, &size);
2df8c079 314 if (errCnt>=20){
315 PrintAndLog("Too many errors: %d",errCnt);
316 return 0;
317 }
eb191de6 318 PrintAndLog("Manchester Decoded - # errors:%d - data:",errCnt);
ba1a299c 319 printBitStream(BitStream, size);
eb191de6 320 if (errCnt==0){
ba1a299c 321 uint64_t id = 0;
322 id = Em410xDecode(BitStream, size);
323 if (id>0) setDemodBuf(BitStream, size);
324 printEM410x(id);
eb191de6 325 }
d5a72d2f 326 return 1;
327}
328
329//by marshmellow
330//biphase decode
331//take 01 or 10 = 0 and 11 or 00 = 1
332//takes 1 argument "offset" default = 0 if 1 it will shift the decode by one bit
ba1a299c 333// since it is not like manchester and doesn't have an incorrect bit pattern we
d5a72d2f 334// cannot determine if our decode is correct or if it should be shifted by one bit
335// the argument offset allows us to manually shift if the output is incorrect
336// (better would be to demod and decode at the same time so we can distinguish large
337// width waves vs small width waves to help the decode positioning) or askbiphdemod
338int CmdBiphaseDecodeRaw(const char *Cmd)
339{
340 int i = 0;
341 int errCnt=0;
ba1a299c 342 size_t size=0;
d5a72d2f 343 int offset=0;
344 int high=0, low=0;
ba1a299c 345 sscanf(Cmd, "%i", &offset);
d5a72d2f 346 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
347 //get graphbuffer & high and low
ba1a299c 348 for (;i<DemodBufferLen;++i){
349 if(DemodBuffer[i]>high)high=DemodBuffer[i];
350 else if(DemodBuffer[i]<low)low=DemodBuffer[i];
351 BitStream[i]=DemodBuffer[i];
d5a72d2f 352 }
353 if (high>1 || low <0){
354 PrintAndLog("Error: please raw demod the wave first then decode");
355 return 0;
356 }
ba1a299c 357 size=i;
358 errCnt=BiphaseRawDecode(BitStream, &size, offset);
d5a72d2f 359 if (errCnt>=20){
360 PrintAndLog("Too many errors attempting to decode: %d",errCnt);
361 return 0;
362 }
363 PrintAndLog("Biphase Decoded using offset: %d - # errors:%d - data:",offset,errCnt);
ba1a299c 364 printBitStream(BitStream, size);
d5a72d2f 365 PrintAndLog("\nif bitstream does not look right try offset=1");
366 return 1;
eb191de6 367}
368
d5a72d2f 369
eb191de6 370//by marshmellow
371//takes 2 arguments - clock and invert both as integers
372//attempts to demodulate ask only
373//prints binary found and saves in graphbuffer for further commands
374int Cmdaskrawdemod(const char *Cmd)
375{
ba1a299c 376 int invert=0;
377 int clk=0;
eb191de6 378 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
ba1a299c 379 sscanf(Cmd, "%i %i", &clk, &invert);
eb191de6 380 if (invert != 0 && invert != 1) {
381 PrintAndLog("Invalid argument: %s", Cmd);
382 return 0;
383 }
ba1a299c 384 size_t BitLen = getFromGraphBuf(BitStream);
eb191de6 385 int errCnt=0;
ba1a299c 386 errCnt = askrawdemod(BitStream, &BitLen,&clk,&invert);
387 if (errCnt==-1||BitLen<16){ //throw away static - allow 1 and -1 (in case of threshold command first)
388 PrintAndLog("no data found");
eb191de6 389 return 0;
ba1a299c 390 }
f822a063 391 PrintAndLog("Using Clock: %d - invert: %d - Bits Found: %d",clk,invert,BitLen);
eb191de6 392 //PrintAndLog("Data start pos:%d, lastBit:%d, stop pos:%d, numBits:%d",iii,lastBit,i,bitnum);
ba1a299c 393 //move BitStream back to DemodBuffer
394 setDemodBuf(BitStream,BitLen);
395
396 //output
eb191de6 397 if (errCnt>0){
398 PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt);
399 }
400 PrintAndLog("ASK demoded bitstream:");
401 // Now output the bitstream to the scrollback by line of 16 bits
402 printBitStream(BitStream,BitLen);
952a8bb5 403
f822a063 404 return 1;
e888ed8e 405}
406
7fe9b0b7 407int CmdAutoCorr(const char *Cmd)
408{
409 static int CorrelBuffer[MAX_GRAPH_TRACE_LEN];
410
411 int window = atoi(Cmd);
412
413 if (window == 0) {
414 PrintAndLog("needs a window");
415 return 0;
416 }
417 if (window >= GraphTraceLen) {
418 PrintAndLog("window must be smaller than trace (%d samples)",
419 GraphTraceLen);
420 return 0;
421 }
422
423 PrintAndLog("performing %d correlations", GraphTraceLen - window);
424
425 for (int i = 0; i < GraphTraceLen - window; ++i) {
426 int sum = 0;
427 for (int j = 0; j < window; ++j) {
428 sum += (GraphBuffer[j]*GraphBuffer[i + j]) / 256;
429 }
430 CorrelBuffer[i] = sum;
431 }
432 GraphTraceLen = GraphTraceLen - window;
433 memcpy(GraphBuffer, CorrelBuffer, GraphTraceLen * sizeof (int));
434
435 RepaintGraphWindow();
436 return 0;
437}
438
439int CmdBitsamples(const char *Cmd)
440{
441 int cnt = 0;
90d74dc2 442 uint8_t got[12288];
952a8bb5 443
90d74dc2 444 GetFromBigBuf(got,sizeof(got),0);
445 WaitForResponse(CMD_ACK,NULL);
7fe9b0b7 446
90d74dc2 447 for (int j = 0; j < sizeof(got); j++) {
7fe9b0b7 448 for (int k = 0; k < 8; k++) {
90d74dc2 449 if(got[j] & (1 << (7 - k))) {
7fe9b0b7 450 GraphBuffer[cnt++] = 1;
451 } else {
452 GraphBuffer[cnt++] = 0;
453 }
454 }
7fe9b0b7 455 }
456 GraphTraceLen = cnt;
457 RepaintGraphWindow();
458 return 0;
459}
460
461/*
462 * Convert to a bitstream
463 */
464int CmdBitstream(const char *Cmd)
465{
466 int i, j;
467 int bit;
468 int gtl;
469 int clock;
470 int low = 0;
471 int high = 0;
472 int hithigh, hitlow, first;
473
474 /* Detect high and lows and clock */
475 for (i = 0; i < GraphTraceLen; ++i)
476 {
477 if (GraphBuffer[i] > high)
478 high = GraphBuffer[i];
479 else if (GraphBuffer[i] < low)
480 low = GraphBuffer[i];
481 }
482
483 /* Get our clock */
484 clock = GetClock(Cmd, high, 1);
485 gtl = ClearGraph(0);
486
487 bit = 0;
488 for (i = 0; i < (int)(gtl / clock); ++i)
489 {
490 hithigh = 0;
491 hitlow = 0;
492 first = 1;
493 /* Find out if we hit both high and low peaks */
494 for (j = 0; j < clock; ++j)
495 {
496 if (GraphBuffer[(i * clock) + j] == high)
497 hithigh = 1;
498 else if (GraphBuffer[(i * clock) + j] == low)
499 hitlow = 1;
500 /* it doesn't count if it's the first part of our read
501 because it's really just trailing from the last sequence */
502 if (first && (hithigh || hitlow))
503 hithigh = hitlow = 0;
504 else
505 first = 0;
506
507 if (hithigh && hitlow)
508 break;
509 }
510
511 /* If we didn't hit both high and low peaks, we had a bit transition */
512 if (!hithigh || !hitlow)
513 bit ^= 1;
514
515 AppendGraph(0, clock, bit);
ba1a299c 516 // for (j = 0; j < (int)(clock/2); j++)
517 // GraphBuffer[(i * clock) + j] = bit ^ 1;
518 // for (j = (int)(clock/2); j < clock; j++)
519 // GraphBuffer[(i * clock) + j] = bit;
7fe9b0b7 520 }
ba1a299c 521
7fe9b0b7 522 RepaintGraphWindow();
523 return 0;
524}
525
526int CmdBuffClear(const char *Cmd)
527{
528 UsbCommand c = {CMD_BUFF_CLEAR};
529 SendCommand(&c);
530 ClearGraph(true);
531 return 0;
532}
533
534int CmdDec(const char *Cmd)
535{
536 for (int i = 0; i < (GraphTraceLen / 2); ++i)
537 GraphBuffer[i] = GraphBuffer[i * 2];
538 GraphTraceLen /= 2;
539 PrintAndLog("decimated by 2");
540 RepaintGraphWindow();
541 return 0;
542}
543
544/* Print our clock rate */
ba1a299c 545// uses data from graphbuffer
7fe9b0b7 546int CmdDetectClockRate(const char *Cmd)
547{
d5a72d2f 548 GetClock("",0,0);
ba1a299c 549 //int clock = DetectASKClock(0);
550 //PrintAndLog("Auto-detected clock rate: %d", clock);
7fe9b0b7 551 return 0;
552}
66707a3b 553
2fc2150e 554//by marshmellow
eb191de6 555//fsk raw demod and print binary
f822a063 556//takes 4 arguments - Clock, invert, rchigh, rclow
557//defaults: clock = 50, invert=0, rchigh=10, rclow=8 (RF/10 RF/8 (fsk2a))
e888ed8e 558int CmdFSKrawdemod(const char *Cmd)
b3b70669 559{
eb191de6 560 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
b3b70669 561 //set defaults
f822a063 562 int rfLen = 50;
563 int invert=0;
564 int fchigh=10;
565 int fclow=8;
b3b70669 566 //set options from parameters entered with the command
ba1a299c 567 sscanf(Cmd, "%i %i %i %i", &rfLen, &invert, &fchigh, &fclow);
568
b3b70669 569 if (strlen(Cmd)>0 && strlen(Cmd)<=2) {
f822a063 570 //rfLen=param_get8(Cmd, 0); //if rfLen option only is used
b3b70669 571 if (rfLen==1){
572 invert=1; //if invert option only is used
573 rfLen = 50;
574 } else if(rfLen==0) rfLen=50;
ba1a299c 575 }
f822a063 576 PrintAndLog("Args invert: %d - Clock:%d - fchigh:%d - fclow: %d",invert,rfLen,fchigh, fclow);
eb191de6 577 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
ba1a299c 578 size_t BitLen = getFromGraphBuf(BitStream);
579 int size = fskdemod(BitStream,BitLen,(uint8_t)rfLen,(uint8_t)invert,(uint8_t)fchigh,(uint8_t)fclow);
d5a72d2f 580 if (size>0){
581 PrintAndLog("FSK decoded bitstream:");
ba1a299c 582 setDemodBuf(BitStream,size);
583
d5a72d2f 584 // Now output the bitstream to the scrollback by line of 16 bits
585 if(size > (8*32)+2) size = (8*32)+2; //only output a max of 8 blocks of 32 bits most tags will have full bit stream inside that sample size
586 printBitStream(BitStream,size);
587 } else{
588 PrintAndLog("no FSK data found");
eb191de6 589 }
b3b70669 590 return 0;
591}
592
eb191de6 593//by marshmellow (based on existing demod + holiman's refactor)
594//HID Prox demod - FSK RF/50 with preamble of 00011101 (then manchester encoded)
595//print full HID Prox ID and some bit format details if found
b3b70669 596int CmdFSKdemodHID(const char *Cmd)
597{
598 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
b3b70669 599 uint32_t hi2=0, hi=0, lo=0;
ba1a299c 600
eb191de6 601 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
ba1a299c 602 size_t BitLen = getFromGraphBuf(BitStream);
b3b70669 603 //get binary from fsk wave
ba1a299c 604 size_t size = HIDdemodFSK(BitStream,BitLen,&hi2,&hi,&lo);
eb191de6 605 if (size<0){
606 PrintAndLog("Error demoding fsk");
607 return 0;
608 }
d5a72d2f 609 if (hi2==0 && hi==0 && lo==0) return 0;
eb191de6 610 if (hi2 != 0){ //extra large HID tags
ba1a299c 611 PrintAndLog("HID Prox TAG ID: %x%08x%08x (%d)",
eb191de6 612 (unsigned int) hi2, (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF);
ba1a299c 613 setDemodBuf(BitStream,BitLen);
d5a72d2f 614 return 1;
eb191de6 615 }
616 else { //standard HID tags <38 bits
617 //Dbprintf("TAG ID: %x%08x (%d)",(unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF); //old print cmd
d5a72d2f 618 uint8_t fmtLen = 0;
eb191de6 619 uint32_t fc = 0;
620 uint32_t cardnum = 0;
621 if (((hi>>5)&1)==1){//if bit 38 is set then < 37 bit format is used
622 uint32_t lo2=0;
84871873 623 lo2=(((hi & 31) << 12) | (lo>>20)); //get bits 21-37 to check for format len bit
eb191de6 624 uint8_t idx3 = 1;
625 while(lo2>1){ //find last bit set to 1 (format len bit)
626 lo2=lo2>>1;
627 idx3++;
b3b70669 628 }
ba1a299c 629 fmtLen =idx3+19;
eb191de6 630 fc =0;
631 cardnum=0;
d5a72d2f 632 if(fmtLen==26){
eb191de6 633 cardnum = (lo>>1)&0xFFFF;
634 fc = (lo>>17)&0xFF;
635 }
d5a72d2f 636 if(fmtLen==34){
eb191de6 637 cardnum = (lo>>1)&0xFFFF;
638 fc= ((hi&1)<<15)|(lo>>17);
639 }
d5a72d2f 640 if(fmtLen==35){
eb191de6 641 cardnum = (lo>>1)&0xFFFFF;
642 fc = ((hi&1)<<11)|(lo>>21);
b3b70669 643 }
b3b70669 644 }
eb191de6 645 else { //if bit 38 is not set then 37 bit format is used
84871873 646 fmtLen = 37;
647 fc = 0;
648 cardnum = 0;
649 if(fmtLen == 37){
eb191de6 650 cardnum = (lo>>1)&0x7FFFF;
651 fc = ((hi&0xF)<<12)|(lo>>20);
652 }
ba1a299c 653 }
654 PrintAndLog("HID Prox TAG ID: %x%08x (%d) - Format Len: %dbit - FC: %d - Card: %d",
eb191de6 655 (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF,
d5a72d2f 656 (unsigned int) fmtLen, (unsigned int) fc, (unsigned int) cardnum);
ba1a299c 657 setDemodBuf(BitStream,BitLen);
d5a72d2f 658 return 1;
b3b70669 659 }
b3b70669 660 return 0;
661}
662
2fc2150e 663//by marshmellow
eb191de6 664//IO-Prox demod - FSK RF/64 with preamble of 000000001
665//print ioprox ID and some format details
b3b70669 666int CmdFSKdemodIO(const char *Cmd)
667{
668 //raw fsk demod no manchester decoding no start bit finding just get binary from wave
669 //set defaults
ba1a299c 670 int idx=0;
d5a72d2f 671 //something in graphbuffer
672 if (GraphTraceLen < 65) return 0;
eb191de6 673 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
ba1a299c 674 size_t BitLen = getFromGraphBuf(BitStream);
eb191de6 675 //get binary from fsk wave
d5a72d2f 676 // PrintAndLog("DEBUG: got buff");
ba1a299c 677 idx = IOdemodFSK(BitStream,BitLen);
eb191de6 678 if (idx<0){
d5a72d2f 679 //PrintAndLog("Error demoding fsk");
eb191de6 680 return 0;
681 }
d5a72d2f 682 // PrintAndLog("DEBUG: Got IOdemodFSK");
eb191de6 683 if (idx==0){
d5a72d2f 684 //PrintAndLog("IO Prox Data not found - FSK Data:");
685 //if (BitLen > 92) printBitStream(BitStream,92);
686 return 0;
b3b70669 687 }
b3b70669 688 //Index map
689 //0 10 20 30 40 50 60
690 //| | | | | | |
691 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
692 //-----------------------------------------------------------------------------
693 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11
694 //
695 //XSF(version)facility:codeone+codetwo (raw)
696 //Handle the data
d5a72d2f 697 if (idx+64>BitLen) return 0;
eb191de6 698 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]);
ba1a299c 699 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]);
f822a063 700 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]);
701 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]);
702 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]);
703 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]);
704 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]);
ba1a299c 705
eb191de6 706 uint32_t code = bytebits_to_byte(BitStream+idx,32);
ba1a299c 707 uint32_t code2 = bytebits_to_byte(BitStream+idx+32,32);
f822a063 708 uint8_t version = bytebits_to_byte(BitStream+idx+27,8); //14,4
709 uint8_t facilitycode = bytebits_to_byte(BitStream+idx+18,8) ;
eb191de6 710 uint16_t number = (bytebits_to_byte(BitStream+idx+36,8)<<8)|(bytebits_to_byte(BitStream+idx+45,8)); //36,9
ba1a299c 711 PrintAndLog("IO Prox XSF(%02d)%02x:%05d (%08x%08x)",version,facilitycode,number,code,code2);
712 int i;
713 for (i=0;i<64;++i)
714 DemodBuffer[i]=BitStream[idx++];
715
716 DemodBufferLen=64;
d5a72d2f 717 return 1;
b3b70669 718}
e888ed8e 719int CmdFSKdemod(const char *Cmd) //old CmdFSKdemod needs updating
7fe9b0b7 720{
721 static const int LowTone[] = {
722 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
723 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
724 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
725 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
726 1, 1, 1, 1, 1, -1, -1, -1, -1, -1
727 };
728 static const int HighTone[] = {
729 1, 1, 1, 1, 1, -1, -1, -1, -1,
730 1, 1, 1, 1, -1, -1, -1, -1,
731 1, 1, 1, 1, -1, -1, -1, -1,
732 1, 1, 1, 1, -1, -1, -1, -1,
733 1, 1, 1, 1, -1, -1, -1, -1,
734 1, 1, 1, 1, -1, -1, -1, -1, -1,
735 };
736
737 int lowLen = sizeof (LowTone) / sizeof (int);
738 int highLen = sizeof (HighTone) / sizeof (int);
b915fda3 739 int convLen = (highLen > lowLen) ? highLen : lowLen;
7fe9b0b7 740 uint32_t hi = 0, lo = 0;
741
742 int i, j;
743 int minMark = 0, maxMark = 0;
952a8bb5 744
7fe9b0b7 745 for (i = 0; i < GraphTraceLen - convLen; ++i) {
746 int lowSum = 0, highSum = 0;
747
748 for (j = 0; j < lowLen; ++j) {
749 lowSum += LowTone[j]*GraphBuffer[i+j];
750 }
751 for (j = 0; j < highLen; ++j) {
752 highSum += HighTone[j] * GraphBuffer[i + j];
753 }
754 lowSum = abs(100 * lowSum / lowLen);
755 highSum = abs(100 * highSum / highLen);
756 GraphBuffer[i] = (highSum << 16) | lowSum;
757 }
758
759 for(i = 0; i < GraphTraceLen - convLen - 16; ++i) {
760 int lowTot = 0, highTot = 0;
761 // 10 and 8 are f_s divided by f_l and f_h, rounded
762 for (j = 0; j < 10; ++j) {
763 lowTot += (GraphBuffer[i+j] & 0xffff);
764 }
765 for (j = 0; j < 8; j++) {
766 highTot += (GraphBuffer[i + j] >> 16);
767 }
768 GraphBuffer[i] = lowTot - highTot;
769 if (GraphBuffer[i] > maxMark) maxMark = GraphBuffer[i];
770 if (GraphBuffer[i] < minMark) minMark = GraphBuffer[i];
771 }
772
773 GraphTraceLen -= (convLen + 16);
774 RepaintGraphWindow();
775
b3b70669 776 // Find bit-sync (3 lo followed by 3 high) (HID ONLY)
7fe9b0b7 777 int max = 0, maxPos = 0;
778 for (i = 0; i < 6000; ++i) {
779 int dec = 0;
780 for (j = 0; j < 3 * lowLen; ++j) {
781 dec -= GraphBuffer[i + j];
782 }
783 for (; j < 3 * (lowLen + highLen ); ++j) {
784 dec += GraphBuffer[i + j];
785 }
786 if (dec > max) {
787 max = dec;
788 maxPos = i;
789 }
790 }
791
792 // place start of bit sync marker in graph
793 GraphBuffer[maxPos] = maxMark;
794 GraphBuffer[maxPos + 1] = minMark;
795
796 maxPos += j;
797
798 // place end of bit sync marker in graph
799 GraphBuffer[maxPos] = maxMark;
800 GraphBuffer[maxPos+1] = minMark;
801
802 PrintAndLog("actual data bits start at sample %d", maxPos);
803 PrintAndLog("length %d/%d", highLen, lowLen);
ba1a299c 804
805 uint8_t bits[46];
806 bits[sizeof(bits)-1] = '\0';
807
7fe9b0b7 808 // find bit pairs and manchester decode them
809 for (i = 0; i < arraylen(bits) - 1; ++i) {
810 int dec = 0;
811 for (j = 0; j < lowLen; ++j) {
812 dec -= GraphBuffer[maxPos + j];
813 }
814 for (; j < lowLen + highLen; ++j) {
815 dec += GraphBuffer[maxPos + j];
816 }
817 maxPos += j;
818 // place inter bit marker in graph
819 GraphBuffer[maxPos] = maxMark;
820 GraphBuffer[maxPos + 1] = minMark;
821
822 // hi and lo form a 64 bit pair
823 hi = (hi << 1) | (lo >> 31);
824 lo = (lo << 1);
825 // store decoded bit as binary (in hi/lo) and text (in bits[])
826 if(dec < 0) {
827 bits[i] = '1';
828 lo |= 1;
829 } else {
830 bits[i] = '0';
831 }
832 }
833 PrintAndLog("bits: '%s'", bits);
834 PrintAndLog("hex: %08x %08x", hi, lo);
835 return 0;
836}
e888ed8e 837
4118b74d 838int CmdDetectNRZpskClockRate(const char *Cmd)
839{
ba1a299c 840 GetNRZpskClock("",0,0);
841 return 0;
4118b74d 842}
843
844int PSKnrzDemod(const char *Cmd){
ba1a299c 845 int invert=0;
846 int clk=0;
847 sscanf(Cmd, "%i %i", &clk, &invert);
848 if (invert != 0 && invert != 1) {
849 PrintAndLog("Invalid argument: %s", Cmd);
850 return -1;
851 }
852 uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
853 size_t BitLen = getFromGraphBuf(BitStream);
854 int errCnt=0;
855 errCnt = pskNRZrawDemod(BitStream, &BitLen,&clk,&invert);
856 if (errCnt<0|| BitLen<16){ //throw away static - allow 1 and -1 (in case of threshold command first)
857 //PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt);
858 return -1;
859 }
860 PrintAndLog("Tried PSK/NRZ Demod using Clock: %d - invert: %d - Bits Found: %d",clk,invert,BitLen);
861
862 //prime demod buffer for output
863 setDemodBuf(BitStream,BitLen);
864 return errCnt;
4118b74d 865}
866// Indala 26 bit decode
867// by marshmellow
868// optional arguments - same as CmdpskNRZrawDemod (clock & invert)
869int CmdIndalaDecode(const char *Cmd)
870{
84871873 871 uint8_t verbose = 1;
872 int ans;
873 if (strlen(Cmd)>0){
874 if (Cmd[0]=='0'){
875 verbose=0;
876 ans = PSKnrzDemod("32");
877 }else{
878 ans = PSKnrzDemod(Cmd);
879 }
880 } else{ //default to RF/32
881 ans = PSKnrzDemod("32");
882 }
4118b74d 883
ba1a299c 884 if (ans < 0){
84871873 885 if (verbose)
886 PrintAndLog("Error1: %d",ans);
ba1a299c 887 return 0;
888 }
889 uint8_t invert=0;
890 ans = indala26decode(DemodBuffer,(size_t *) &DemodBufferLen, &invert);
891 if (ans < 1) {
84871873 892 if (verbose)
893 PrintAndLog("Error2: %d",ans);
ba1a299c 894 return -1;
895 }
896 char showbits[251];
84871873 897 if (invert)
898 if (verbose)
899 PrintAndLog("Had to invert bits");
ba1a299c 900 //convert UID to HEX
901 uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7;
902 int idx;
903 uid1=0;
904 uid2=0;
905 PrintAndLog("BitLen: %d",DemodBufferLen);
906 if (DemodBufferLen==64){
907 for( idx=0; idx<64; idx++) {
908 uid1=(uid1<<1)|(uid2>>31);
909 if (DemodBuffer[idx] == 0) {
910 uid2=(uid2<<1)|0;
911 showbits[idx]='0';
912 } else {
913 uid2=(uid2<<1)|1;
914 showbits[idx]='1';
915 }
916 }
917 showbits[idx]='\0';
918 PrintAndLog("Indala UID=%s (%x%08x)", showbits, uid1, uid2);
919 }
920 else {
921 uid3=0;
922 uid4=0;
923 uid5=0;
924 uid6=0;
925 uid7=0;
926 for( idx=0; idx<DemodBufferLen; idx++) {
927 uid1=(uid1<<1)|(uid2>>31);
928 uid2=(uid2<<1)|(uid3>>31);
929 uid3=(uid3<<1)|(uid4>>31);
930 uid4=(uid4<<1)|(uid5>>31);
931 uid5=(uid5<<1)|(uid6>>31);
932 uid6=(uid6<<1)|(uid7>>31);
933 if (DemodBuffer[idx] == 0) {
934 uid7=(uid7<<1)|0;
935 showbits[idx]='0';
936 }
937 else {
938 uid7=(uid7<<1)|1;
939 showbits[idx]='1';
940 }
941 }
942 showbits[idx]='\0';
943 PrintAndLog("Indala UID=%s (%x%08x%08x%08x%08x%08x%08x)", showbits, uid1, uid2, uid3, uid4, uid5, uid6, uid7);
944 }
945 return 1;
4118b74d 946}
947
4118b74d 948int CmdPskClean(const char *Cmd)
949{
ba1a299c 950 uint8_t bitStream[MAX_GRAPH_TRACE_LEN]={0};
951 size_t bitLen = getFromGraphBuf(bitStream);
952 pskCleanWave(bitStream, bitLen);
953 setGraphBuf(bitStream, bitLen);
954 return 0;
4118b74d 955}
956
957//by marshmellow
958//takes 2 arguments - clock and invert both as integers
959//attempts to demodulate ask only
960//prints binary found and saves in graphbuffer for further commands
961int CmdpskNRZrawDemod(const char *Cmd)
962{
84871873 963 uint8_t verbose = 1;
964 int errCnt;
965 if (strlen(Cmd)>0){
966 if (Cmd[0]=='0')
967 verbose=0;
968 }
969
970 errCnt = PSKnrzDemod(Cmd);
ba1a299c 971 //output
972 if (errCnt<0) return 0;
973 if (errCnt>0){
84871873 974 if (verbose)
975 PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt);
ba1a299c 976 }
977 PrintAndLog("PSK or NRZ demoded bitstream:");
978 // Now output the bitstream to the scrollback by line of 16 bits
979 printDemodBuff();
980
981 return 1;
4118b74d 982}
983
7fe9b0b7 984int CmdGrid(const char *Cmd)
985{
986 sscanf(Cmd, "%i %i", &PlotGridX, &PlotGridY);
7ddb9900 987 PlotGridXdefault= PlotGridX;
988 PlotGridYdefault= PlotGridY;
7fe9b0b7 989 RepaintGraphWindow();
990 return 0;
991}
992
993int CmdHexsamples(const char *Cmd)
994{
4961e292 995 int i, j;
7fe9b0b7 996 int requested = 0;
997 int offset = 0;
4961e292 998 char string_buf[25];
999 char* string_ptr = string_buf;
90d74dc2 1000 uint8_t got[40000];
952a8bb5 1001
4961e292 1002 sscanf(Cmd, "%i %i", &requested, &offset);
90d74dc2 1003
4961e292 1004 /* if no args send something */
1005 if (requested == 0) {
90d74dc2 1006 requested = 8;
1007 }
90d74dc2 1008 if (offset + requested > sizeof(got)) {
1009 PrintAndLog("Tried to read past end of buffer, <bytes> + <offset> > 40000");
4961e292 1010 return 0;
952a8bb5 1011 }
90d74dc2 1012
4961e292 1013 GetFromBigBuf(got,requested,offset);
90d74dc2 1014 WaitForResponse(CMD_ACK,NULL);
1015
4961e292 1016 i = 0;
1017 for (j = 0; j < requested; j++) {
1018 i++;
1019 string_ptr += sprintf(string_ptr, "%02x ", got[j]);
1020 if (i == 8) {
1021 *(string_ptr - 1) = '\0'; // remove the trailing space
1022 PrintAndLog("%s", string_buf);
1023 string_buf[0] = '\0';
1024 string_ptr = string_buf;
1025 i = 0;
1026 }
1027 if (j == requested - 1 && string_buf[0] != '\0') { // print any remaining bytes
1028 *(string_ptr - 1) = '\0';
1029 PrintAndLog("%s", string_buf);
1030 string_buf[0] = '\0';
7fe9b0b7 1031 }
ba1a299c 1032 }
7fe9b0b7 1033 return 0;
1034}
1035
7fe9b0b7 1036int CmdHide(const char *Cmd)
1037{
1038 HideGraphWindow();
1039 return 0;
1040}
1041
1042int CmdHpf(const char *Cmd)
1043{
1044 int i;
1045 int accum = 0;
1046
1047 for (i = 10; i < GraphTraceLen; ++i)
1048 accum += GraphBuffer[i];
1049 accum /= (GraphTraceLen - 10);
1050 for (i = 0; i < GraphTraceLen; ++i)
1051 GraphBuffer[i] -= accum;
1052
1053 RepaintGraphWindow();
1054 return 0;
1055}
f6d9fb17
MHS
1056typedef struct {
1057 uint8_t * buffer;
1058 uint32_t numbits;
1059 uint32_t position;
1060}BitstreamOut;
1061
1062bool _headBit( BitstreamOut *stream)
1063{
1064 int bytepos = stream->position >> 3; // divide by 8
1065 int bitpos = (stream->position++) & 7; // mask out 00000111
1066 return (*(stream->buffer + bytepos) >> (7-bitpos)) & 1;
1067}
1068
1069uint8_t getByte(uint8_t bits_per_sample, BitstreamOut* b)
1070{
1071 int i;
1072 uint8_t val = 0;
1073 for(i =0 ; i < bits_per_sample; i++)
1074 {
1075 val |= (_headBit(b) << (7-i));
1076 }
1077 return val;
1078}
7fe9b0b7 1079
8d183c53 1080int CmdSamples(const char *Cmd)
7fe9b0b7 1081{
31abe49f
MHS
1082 //If we get all but the last byte in bigbuf,
1083 // we don't have to worry about remaining trash
1084 // in the last byte in case the bits-per-sample
1085 // does not line up on byte boundaries
1086 uint8_t got[40000-1];
ba1a299c 1087
d6d20c54 1088 int n = strtol(Cmd, NULL, 0);
1089 if (n == 0)
31abe49f 1090 n = sizeof(got);
d6d20c54 1091
1092 if (n > sizeof(got))
1093 n = sizeof(got);
ba1a299c 1094
f6d9fb17
MHS
1095 PrintAndLog("Reading %d bytes from device memory\n", n);
1096 GetFromBigBuf(got,n,0);
1097 PrintAndLog("Data fetched");
1098 UsbCommand response;
1099 WaitForResponse(CMD_ACK, &response);
31abe49f
MHS
1100 uint8_t bits_per_sample = 8;
1101
1102 //Old devices without this feature would send 0 at arg[0]
1103 if(response.arg[0] > 0)
1104 {
1105 sample_config *sc = (sample_config *) response.d.asBytes;
1106 PrintAndLog("Samples @ %d bits/smpl, decimation 1:%d ", sc->bits_per_sample
1107 , sc->decimation);
1108 bits_per_sample = sc->bits_per_sample;
1109 }
f6d9fb17
MHS
1110 if(bits_per_sample < 8)
1111 {
1112 PrintAndLog("Unpacking...");
1113 BitstreamOut bout = { got, bits_per_sample * n, 0};
1114 int j =0;
31abe49f 1115 for (j = 0; j * bits_per_sample < n * 8 && j < sizeof(GraphBuffer); j++) {
f6d9fb17
MHS
1116 uint8_t sample = getByte(bits_per_sample, &bout);
1117 GraphBuffer[j] = ((int) sample )- 128;
1118 }
1119 GraphTraceLen = j;
1120 PrintAndLog("Unpacked %d samples" , j );
1121 }else
1122 {
1123 for (int j = 0; j < n; j++) {
1124 GraphBuffer[j] = ((int)got[j]) - 128;
1125 }
1126 GraphTraceLen = n;
f6d9fb17
MHS
1127 }
1128
1129 RepaintGraphWindow();
1130 return 0;
7fe9b0b7 1131}
1132
d6a120a2
MHS
1133int CmdTuneSamples(const char *Cmd)
1134{
3aa4014b 1135 int timeout = 0;
1136 printf("\nMeasuring antenna characteristics, please wait...");
ba1a299c 1137
3aa4014b 1138 UsbCommand c = {CMD_MEASURE_ANTENNA_TUNING};
1139 SendCommand(&c);
1140
1141 UsbCommand resp;
1142 while(!WaitForResponseTimeout(CMD_MEASURED_ANTENNA_TUNING,&resp,1000)) {
1143 timeout++;
1144 printf(".");
1145 if (timeout > 7) {
1146 PrintAndLog("\nNo response from Proxmark. Aborting...");
1147 return 1;
1148 }
1149 }
1150
1151 int peakv, peakf;
1152 int vLf125, vLf134, vHf;
1153 vLf125 = resp.arg[0] & 0xffff;
1154 vLf134 = resp.arg[0] >> 16;
1155 vHf = resp.arg[1] & 0xffff;;
1156 peakf = resp.arg[2] & 0xffff;
1157 peakv = resp.arg[2] >> 16;
1158 PrintAndLog("");
1159 PrintAndLog("# LF antenna: %5.2f V @ 125.00 kHz", vLf125/1000.0);
1160 PrintAndLog("# LF antenna: %5.2f V @ 134.00 kHz", vLf134/1000.0);
1161 PrintAndLog("# LF optimal: %5.2f V @%9.2f kHz", peakv/1000.0, 12000.0/(peakf+1));
1162 PrintAndLog("# HF antenna: %5.2f V @ 13.56 MHz", vHf/1000.0);
1163 if (peakv<2000)
1164 PrintAndLog("# Your LF antenna is unusable.");
1165 else if (peakv<10000)
1166 PrintAndLog("# Your LF antenna is marginal.");
1167 if (vHf<2000)
1168 PrintAndLog("# Your HF antenna is unusable.");
1169 else if (vHf<5000)
1170 PrintAndLog("# Your HF antenna is marginal.");
1171
1172 for (int i = 0; i < 256; i++) {
1173 GraphBuffer[i] = resp.d.asBytes[i] - 128;
ba1a299c 1174 }
1175
d5a72d2f 1176 PrintAndLog("Done! Divisor 89 is 134khz, 95 is 125khz.\n");
1177 PrintAndLog("\n");
3aa4014b 1178 GraphTraceLen = 256;
1179 ShowGraphWindow();
1180
1181 return 0;
d6a120a2
MHS
1182}
1183
3aa4014b 1184
7fe9b0b7 1185int CmdLoad(const char *Cmd)
1186{
b915fda3 1187 char filename[FILE_PATH_SIZE] = {0x00};
1188 int len = 0;
1189
1190 len = strlen(Cmd);
1191 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
1192 memcpy(filename, Cmd, len);
1193
1194 FILE *f = fopen(filename, "r");
7fe9b0b7 1195 if (!f) {
b915fda3 1196 PrintAndLog("couldn't open '%s'", filename);
7fe9b0b7 1197 return 0;
1198 }
1199
1200 GraphTraceLen = 0;
1201 char line[80];
1202 while (fgets(line, sizeof (line), f)) {
1203 GraphBuffer[GraphTraceLen] = atoi(line);
1204 GraphTraceLen++;
1205 }
1206 fclose(f);
1207 PrintAndLog("loaded %d samples", GraphTraceLen);
1208 RepaintGraphWindow();
1209 return 0;
1210}
1211
1212int CmdLtrim(const char *Cmd)
1213{
1214 int ds = atoi(Cmd);
1215
1216 for (int i = ds; i < GraphTraceLen; ++i)
1217 GraphBuffer[i-ds] = GraphBuffer[i];
1218 GraphTraceLen -= ds;
1219
1220 RepaintGraphWindow();
1221 return 0;
1222}
9ec1416a 1223int CmdRtrim(const char *Cmd)
1224{
1225 int ds = atoi(Cmd);
1226
1227 GraphTraceLen = ds;
1228
1229 RepaintGraphWindow();
1230 return 0;
1231}
7fe9b0b7 1232
1233/*
1234 * Manchester demodulate a bitstream. The bitstream needs to be already in
1235 * the GraphBuffer as 0 and 1 values
1236 *
1237 * Give the clock rate as argument in order to help the sync - the algorithm
1238 * resyncs at each pulse anyway.
1239 *
1240 * Not optimized by any means, this is the 1st time I'm writing this type of
1241 * routine, feel free to improve...
1242 *
1243 * 1st argument: clock rate (as number of samples per clock rate)
1244 * Typical values can be 64, 32, 128...
1245 */
1246int CmdManchesterDemod(const char *Cmd)
1247{
1248 int i, j, invert= 0;
1249 int bit;
1250 int clock;
fddf220a 1251 int lastval = 0;
7fe9b0b7 1252 int low = 0;
1253 int high = 0;
1254 int hithigh, hitlow, first;
1255 int lc = 0;
1256 int bitidx = 0;
1257 int bit2idx = 0;
1258 int warnings = 0;
1259
1260 /* check if we're inverting output */
c6f1fb9d 1261 if (*Cmd == 'i')
7fe9b0b7 1262 {
1263 PrintAndLog("Inverting output");
1264 invert = 1;
fffad860 1265 ++Cmd;
7fe9b0b7 1266 do
1267 ++Cmd;
1268 while(*Cmd == ' '); // in case a 2nd argument was given
1269 }
1270
1271 /* Holds the decoded bitstream: each clock period contains 2 bits */
1272 /* later simplified to 1 bit after manchester decoding. */
1273 /* Add 10 bits to allow for noisy / uncertain traces without aborting */
1274 /* int BitStream[GraphTraceLen*2/clock+10]; */
1275
1276 /* But it does not work if compiling on WIndows: therefore we just allocate a */
1277 /* large array */
90e278d3 1278 uint8_t BitStream[MAX_GRAPH_TRACE_LEN] = {0};
7fe9b0b7 1279
1280 /* Detect high and lows */
1281 for (i = 0; i < GraphTraceLen; i++)
1282 {
1283 if (GraphBuffer[i] > high)
1284 high = GraphBuffer[i];
1285 else if (GraphBuffer[i] < low)
1286 low = GraphBuffer[i];
1287 }
1288
1289 /* Get our clock */
1290 clock = GetClock(Cmd, high, 1);
1291
1292 int tolerance = clock/4;
1293
1294 /* Detect first transition */
1295 /* Lo-Hi (arbitrary) */
1296 /* skip to the first high */
1297 for (i= 0; i < GraphTraceLen; i++)
1298 if (GraphBuffer[i] == high)
1299 break;
1300 /* now look for the first low */
1301 for (; i < GraphTraceLen; i++)
1302 {
1303 if (GraphBuffer[i] == low)
1304 {
1305 lastval = i;
1306 break;
1307 }
1308 }
1309
1310 /* If we're not working with 1/0s, demod based off clock */
1311 if (high != 1)
1312 {
1313 bit = 0; /* We assume the 1st bit is zero, it may not be
1314 * the case: this routine (I think) has an init problem.
1315 * Ed.
1316 */
1317 for (; i < (int)(GraphTraceLen / clock); i++)
1318 {
1319 hithigh = 0;
1320 hitlow = 0;
1321 first = 1;
1322
1323 /* Find out if we hit both high and low peaks */
1324 for (j = 0; j < clock; j++)
1325 {
1326 if (GraphBuffer[(i * clock) + j] == high)
1327 hithigh = 1;
1328 else if (GraphBuffer[(i * clock) + j] == low)
1329 hitlow = 1;
1330
1331 /* it doesn't count if it's the first part of our read
1332 because it's really just trailing from the last sequence */
1333 if (first && (hithigh || hitlow))
1334 hithigh = hitlow = 0;
1335 else
1336 first = 0;
1337
1338 if (hithigh && hitlow)
1339 break;
1340 }
1341
1342 /* If we didn't hit both high and low peaks, we had a bit transition */
1343 if (!hithigh || !hitlow)
1344 bit ^= 1;
1345
1346 BitStream[bit2idx++] = bit ^ invert;
1347 }
1348 }
1349
1350 /* standard 1/0 bitstream */
1351 else
1352 {
1353
1354 /* Then detect duration between 2 successive transitions */
1355 for (bitidx = 1; i < GraphTraceLen; i++)
1356 {
1357 if (GraphBuffer[i-1] != GraphBuffer[i])
1358 {
b3b70669 1359 lc = i-lastval;
1360 lastval = i;
1361
1362 // Error check: if bitidx becomes too large, we do not
1363 // have a Manchester encoded bitstream or the clock is really
1364 // wrong!
1365 if (bitidx > (GraphTraceLen*2/clock+8) ) {
1366 PrintAndLog("Error: the clock you gave is probably wrong, aborting.");
1367 return 0;
1368 }
1369 // Then switch depending on lc length:
1370 // Tolerance is 1/4 of clock rate (arbitrary)
1371 if (abs(lc-clock/2) < tolerance) {
1372 // Short pulse : either "1" or "0"
1373 BitStream[bitidx++]=GraphBuffer[i-1];
1374 } else if (abs(lc-clock) < tolerance) {
1375 // Long pulse: either "11" or "00"
1376 BitStream[bitidx++]=GraphBuffer[i-1];
1377 BitStream[bitidx++]=GraphBuffer[i-1];
1378 } else {
7fe9b0b7 1379 // Error
1380 warnings++;
b3b70669 1381 PrintAndLog("Warning: Manchester decode error for pulse width detection.");
1382 PrintAndLog("(too many of those messages mean either the stream is not Manchester encoded, or clock is wrong)");
7fe9b0b7 1383
1384 if (warnings > 10)
1385 {
1386 PrintAndLog("Error: too many detection errors, aborting.");
1387 return 0;
1388 }
1389 }
1390 }
1391 }
1392
1393 // At this stage, we now have a bitstream of "01" ("1") or "10" ("0"), parse it into final decoded bitstream
1394 // Actually, we overwrite BitStream with the new decoded bitstream, we just need to be careful
1395 // to stop output at the final bitidx2 value, not bitidx
1396 for (i = 0; i < bitidx; i += 2) {
1397 if ((BitStream[i] == 0) && (BitStream[i+1] == 1)) {
1398 BitStream[bit2idx++] = 1 ^ invert;
b3b70669 1399 } else if ((BitStream[i] == 1) && (BitStream[i+1] == 0)) {
1400 BitStream[bit2idx++] = 0 ^ invert;
1401 } else {
1402 // We cannot end up in this state, this means we are unsynchronized,
1403 // move up 1 bit:
1404 i++;
7fe9b0b7 1405 warnings++;
b3b70669 1406 PrintAndLog("Unsynchronized, resync...");
1407 PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)");
7fe9b0b7 1408
1409 if (warnings > 10)
1410 {
1411 PrintAndLog("Error: too many decode errors, aborting.");
1412 return 0;
1413 }
1414 }
1415 }
1416 }
1417
1418 PrintAndLog("Manchester decoded bitstream");
1419 // Now output the bitstream to the scrollback by line of 16 bits
1420 for (i = 0; i < (bit2idx-16); i+=16) {
1421 PrintAndLog("%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
1422 BitStream[i],
1423 BitStream[i+1],
1424 BitStream[i+2],
1425 BitStream[i+3],
1426 BitStream[i+4],
1427 BitStream[i+5],
1428 BitStream[i+6],
1429 BitStream[i+7],
1430 BitStream[i+8],
1431 BitStream[i+9],
1432 BitStream[i+10],
1433 BitStream[i+11],
1434 BitStream[i+12],
1435 BitStream[i+13],
1436 BitStream[i+14],
1437 BitStream[i+15]);
1438 }
1439 return 0;
1440}
1441
1442/* Modulate our data into manchester */
1443int CmdManchesterMod(const char *Cmd)
1444{
1445 int i, j;
1446 int clock;
1447 int bit, lastbit, wave;
1448
1449 /* Get our clock */
1450 clock = GetClock(Cmd, 0, 1);
1451
1452 wave = 0;
1453 lastbit = 1;
1454 for (i = 0; i < (int)(GraphTraceLen / clock); i++)
1455 {
1456 bit = GraphBuffer[i * clock] ^ 1;
1457
1458 for (j = 0; j < (int)(clock/2); j++)
1459 GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave;
1460 for (j = (int)(clock/2); j < clock; j++)
1461 GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave ^ 1;
1462
1463 /* Keep track of how we start our wave and if we changed or not this time */
1464 wave ^= bit ^ lastbit;
1465 lastbit = bit;
1466 }
1467
1468 RepaintGraphWindow();
1469 return 0;
1470}
1471
1472int CmdNorm(const char *Cmd)
1473{
1474 int i;
1475 int max = INT_MIN, min = INT_MAX;
1476
1477 for (i = 10; i < GraphTraceLen; ++i) {
1478 if (GraphBuffer[i] > max)
1479 max = GraphBuffer[i];
1480 if (GraphBuffer[i] < min)
1481 min = GraphBuffer[i];
1482 }
1483
1484 if (max != min) {
1485 for (i = 0; i < GraphTraceLen; ++i) {
ba1a299c 1486 GraphBuffer[i] = (GraphBuffer[i] - ((max + min) / 2)) * 256 /
7fe9b0b7 1487 (max - min);
ba1a299c 1488 //marshmelow: adjusted *1000 to *256 to make +/- 128 so demod commands still work
7fe9b0b7 1489 }
1490 }
1491 RepaintGraphWindow();
1492 return 0;
1493}
1494
1495int CmdPlot(const char *Cmd)
1496{
1497 ShowGraphWindow();
1498 return 0;
1499}
1500
1501int CmdSave(const char *Cmd)
1502{
b915fda3 1503 char filename[FILE_PATH_SIZE] = {0x00};
1504 int len = 0;
1505
1506 len = strlen(Cmd);
1507 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
1508 memcpy(filename, Cmd, len);
1509
1510
1511 FILE *f = fopen(filename, "w");
7fe9b0b7 1512 if(!f) {
b915fda3 1513 PrintAndLog("couldn't open '%s'", filename);
7fe9b0b7 1514 return 0;
1515 }
1516 int i;
1517 for (i = 0; i < GraphTraceLen; i++) {
1518 fprintf(f, "%d\n", GraphBuffer[i]);
1519 }
1520 fclose(f);
1521 PrintAndLog("saved to '%s'", Cmd);
1522 return 0;
1523}
1524
1525int CmdScale(const char *Cmd)
1526{
1527 CursorScaleFactor = atoi(Cmd);
1528 if (CursorScaleFactor == 0) {
1529 PrintAndLog("bad, can't have zero scale");
1530 CursorScaleFactor = 1;
1531 }
1532 RepaintGraphWindow();
1533 return 0;
1534}
1535
1536int CmdThreshold(const char *Cmd)
1537{
1538 int threshold = atoi(Cmd);
1539
1540 for (int i = 0; i < GraphTraceLen; ++i) {
1541 if (GraphBuffer[i] >= threshold)
1542 GraphBuffer[i] = 1;
1543 else
7bb9d33e 1544 GraphBuffer[i] = -1;
7fe9b0b7 1545 }
1546 RepaintGraphWindow();
1547 return 0;
1548}
1549
d51b2eda
MHS
1550int CmdDirectionalThreshold(const char *Cmd)
1551{
1552 int8_t upThres = param_get8(Cmd, 0);
1553 int8_t downThres = param_get8(Cmd, 1);
ba1a299c 1554
d51b2eda 1555 printf("Applying Up Threshold: %d, Down Threshold: %d\n", upThres, downThres);
952a8bb5 1556
d51b2eda
MHS
1557 int lastValue = GraphBuffer[0];
1558 GraphBuffer[0] = 0; // Will be changed at the end, but init 0 as we adjust to last samples value if no threshold kicks in.
952a8bb5 1559
d51b2eda
MHS
1560 for (int i = 1; i < GraphTraceLen; ++i) {
1561 // Apply first threshold to samples heading up
1562 if (GraphBuffer[i] >= upThres && GraphBuffer[i] > lastValue)
1563 {
1564 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1565 GraphBuffer[i] = 1;
1566 }
1567 // Apply second threshold to samples heading down
1568 else if (GraphBuffer[i] <= downThres && GraphBuffer[i] < lastValue)
1569 {
1570 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1571 GraphBuffer[i] = -1;
1572 }
1573 else
1574 {
1575 lastValue = GraphBuffer[i]; // Buffer last value as we overwrite it.
1576 GraphBuffer[i] = GraphBuffer[i-1];
1577
1578 }
1579 }
1580 GraphBuffer[0] = GraphBuffer[1]; // Aline with first edited sample.
1581 RepaintGraphWindow();
1582 return 0;
1583}
1584
7fe9b0b7 1585int CmdZerocrossings(const char *Cmd)
1586{
1587 // Zero-crossings aren't meaningful unless the signal is zero-mean.
1588 CmdHpf("");
1589
1590 int sign = 1;
1591 int zc = 0;
1592 int lastZc = 0;
1593
1594 for (int i = 0; i < GraphTraceLen; ++i) {
1595 if (GraphBuffer[i] * sign >= 0) {
1596 // No change in sign, reproduce the previous sample count.
1597 zc++;
1598 GraphBuffer[i] = lastZc;
1599 } else {
1600 // Change in sign, reset the sample count.
1601 sign = -sign;
1602 GraphBuffer[i] = lastZc;
1603 if (sign > 0) {
1604 lastZc = zc;
1605 zc = 0;
1606 }
1607 }
1608 }
1609
1610 RepaintGraphWindow();
1611 return 0;
1612}
1613
ba1a299c 1614static command_t CommandTable[] =
7fe9b0b7 1615{
1616 {"help", CmdHelp, 1, "This help"},
1617 {"amp", CmdAmp, 1, "Amplify peaks"},
57c69556 1618 {"askdemod", Cmdaskdemod, 1, "<0 or 1> -- Attempt to demodulate simple ASK tags"},
d6d20c54 1619 {"askmandemod", Cmdaskmandemod, 1, "[clock] [invert<0|1>] -- Attempt to demodulate ASK/Manchester tags and output binary (args optional[clock will try Auto-detect])"},
1620 {"askrawdemod", Cmdaskrawdemod, 1, "[clock] [invert<0|1>] -- Attempt to demodulate ASK tags and output binary (args optional[clock will try Auto-detect])"},
7fe9b0b7 1621 {"autocorr", CmdAutoCorr, 1, "<window length> -- Autocorrelation over window"},
d5a72d2f 1622 {"biphaserawdecode",CmdBiphaseDecodeRaw,1,"[offset] Biphase decode binary stream already in graph buffer (offset = bit to start decode from)"},
7fe9b0b7 1623 {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"},
1624 {"bitstream", CmdBitstream, 1, "[clock rate] -- Convert waveform into a bitstream"},
1625 {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"},
1626 {"dec", CmdDec, 1, "Decimate samples"},
ba1a299c 1627 {"detectclock", CmdDetectClockRate, 1, "Detect ASK clock rate"},
e888ed8e 1628 {"fskdemod", CmdFSKdemod, 1, "Demodulate graph window as a HID FSK"},
1629 {"fskhiddemod", CmdFSKdemodHID, 1, "Demodulate graph window as a HID FSK using raw"},
1630 {"fskiodemod", CmdFSKdemodIO, 1, "Demodulate graph window as an IO Prox FSK using raw"},
d6d20c54 1631 {"fskrawdemod", CmdFSKrawdemod, 1, "[clock rate] [invert] [rchigh] [rclow] Demodulate graph window from FSK to binary (clock = 50)(invert = 1|0)(rchigh = 10)(rclow=8)"},
7fe9b0b7 1632 {"grid", CmdGrid, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
ba1a299c 1633 {"hexsamples", CmdHexsamples, 0, "<bytes> [<offset>] -- Dump big buffer as hex bytes"},
7fe9b0b7 1634 {"hide", CmdHide, 1, "Hide graph window"},
1635 {"hpf", CmdHpf, 1, "Remove DC offset from trace"},
7fe9b0b7 1636 {"load", CmdLoad, 1, "<filename> -- Load trace (to graph window"},
1637 {"ltrim", CmdLtrim, 1, "<samples> -- Trim samples from left of trace"},
9ec1416a 1638 {"rtrim", CmdRtrim, 1, "<location to end trace> -- Trim samples from right of trace"},
7fe9b0b7 1639 {"mandemod", CmdManchesterDemod, 1, "[i] [clock rate] -- Manchester demodulate binary stream (option 'i' to invert output)"},
eb191de6 1640 {"manrawdecode", Cmdmandecoderaw, 1, "Manchester decode binary stream already in graph buffer"},
7fe9b0b7 1641 {"manmod", CmdManchesterMod, 1, "[clock rate] -- Manchester modulate a binary stream"},
ba1a299c 1642 {"norm", CmdNorm, 1, "Normalize max/min to +/-128"},
7ddb9900 1643 {"plot", CmdPlot, 1, "Show graph window (hit 'h' in window for keystroke help)"},
ba1a299c 1644 {"pskclean", CmdPskClean, 1, "Attempt to clean psk wave"},
1645 {"pskdetectclock",CmdDetectNRZpskClockRate, 1, "Detect ASK, PSK, or NRZ clock rate"},
d6d20c54 1646 {"pskindalademod",CmdIndalaDecode, 1, "[clock] [invert<0|1>] -- Attempt to demodulate psk indala tags and output ID binary & hex (args optional[clock will try Auto-detect])"},
1647 {"psknrzrawdemod",CmdpskNRZrawDemod, 1, "[clock] [invert<0|1>] -- Attempt to demodulate psk or nrz tags and output binary (args optional[clock will try Auto-detect])"},
90d74dc2 1648 {"samples", CmdSamples, 0, "[512 - 40000] -- Get raw samples for graph window"},
7fe9b0b7 1649 {"save", CmdSave, 1, "<filename> -- Save trace (from graph window)"},
1650 {"scale", CmdScale, 1, "<int> -- Set cursor display scale"},
dbf444a1 1651 {"threshold", CmdThreshold, 1, "<threshold> -- Maximize/minimize every value in the graph window depending on threshold"},
ba1a299c 1652 {"dirthreshold", CmdDirectionalThreshold, 1, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."},
1653 {"tune", CmdTuneSamples, 0, "Get hw tune samples for graph window"},
7fe9b0b7 1654 {"zerocrossings", CmdZerocrossings, 1, "Count time between zero-crossings"},
1655 {NULL, NULL, 0, NULL}
1656};
1657
1658int CmdData(const char *Cmd)
1659{
1660 CmdsParse(CommandTable, Cmd);
1661 return 0;
1662}
1663
1664int CmdHelp(const char *Cmd)
1665{
1666 CmdsHelp(CommandTable);
1667 return 0;
1668}
Impressum, Datenschutz