1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
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
7 //-----------------------------------------------------------------------------
8 // Data and Graph commands
9 //-----------------------------------------------------------------------------
15 //#include "proxusb.h"
16 #include "proxmark3.h"
20 #include "cmdparser.h"
24 static int CmdHelp(const char *Cmd
);
26 int CmdAmp(const char *Cmd
)
28 int i
, rising
, falling
;
29 int max
= INT_MIN
, min
= INT_MAX
;
31 for (i
= 10; i
< GraphTraceLen
; ++i
) {
32 if (GraphBuffer
[i
] > max
)
34 if (GraphBuffer
[i
] < min
)
40 for (i
= 0; i
< GraphTraceLen
; ++i
) {
41 if (GraphBuffer
[i
+ 1] < GraphBuffer
[i
]) {
48 if (GraphBuffer
[i
+ 1] > GraphBuffer
[i
]) {
62 * Generic command to demodulate ASK.
64 * Argument is convention: positive or negative (High mod means zero
65 * or high mod means one)
67 * Updates the Graph trace with 0/1 values
72 int Cmdaskdemod(const char *Cmd
)
75 int c
, high
= 0, low
= 0;
77 // TODO: complain if we do not give 2 arguments here !
78 // (AL - this doesn't make sense! we're only using one argument!!!)
79 sscanf(Cmd
, "%i", &c
);
81 /* Detect high and lows and clock */
83 for (i
= 0; i
< GraphTraceLen
; ++i
)
85 if (GraphBuffer
[i
] > high
)
86 high
= GraphBuffer
[i
];
87 else if (GraphBuffer
[i
] < low
)
90 if (c
!= 0 && c
!= 1) {
91 PrintAndLog("Invalid argument: %s", Cmd
);
95 if (GraphBuffer
[0] > 0) {
100 for (i
= 1; i
< GraphTraceLen
; ++i
) {
101 /* Transitions are detected at each peak
102 * Transitions are either:
103 * - we're low: transition if we hit a high
104 * - we're high: transition if we hit a low
105 * (we need to do it this way because some tags keep high or
106 * low for long periods, others just reach the peak and go
109 if ((GraphBuffer
[i
] == high
) && (GraphBuffer
[i
- 1] == c
)) {
110 GraphBuffer
[i
] = 1 - c
;
111 } else if ((GraphBuffer
[i
] == low
) && (GraphBuffer
[i
- 1] == (1 - c
))){
115 GraphBuffer
[i
] = GraphBuffer
[i
- 1];
118 RepaintGraphWindow();
122 int CmdAutoCorr(const char *Cmd
)
124 static int CorrelBuffer
[MAX_GRAPH_TRACE_LEN
];
126 int window
= atoi(Cmd
);
129 PrintAndLog("needs a window");
132 if (window
>= GraphTraceLen
) {
133 PrintAndLog("window must be smaller than trace (%d samples)",
138 PrintAndLog("performing %d correlations", GraphTraceLen
- window
);
140 for (int i
= 0; i
< GraphTraceLen
- window
; ++i
) {
142 for (int j
= 0; j
< window
; ++j
) {
143 sum
+= (GraphBuffer
[j
]*GraphBuffer
[i
+ j
]) / 256;
145 CorrelBuffer
[i
] = sum
;
147 GraphTraceLen
= GraphTraceLen
- window
;
148 memcpy(GraphBuffer
, CorrelBuffer
, GraphTraceLen
* sizeof (int));
150 RepaintGraphWindow();
154 int CmdBitsamples(const char *Cmd
)
159 for (int i
= 0; i
< n
; i
+= 12) {
160 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {i
, 0, 0}};
162 WaitForResponse(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
, NULL
);
164 for (int j
= 0; j
< 48; j
++) {
165 for (int k
= 0; k
< 8; k
++) {
166 if(sample_buf
[j
] & (1 << (7 - k
))) {
167 GraphBuffer
[cnt
++] = 1;
169 GraphBuffer
[cnt
++] = 0;
175 RepaintGraphWindow();
180 * Convert to a bitstream
182 int CmdBitstream(const char *Cmd
)
190 int hithigh
, hitlow
, first
;
192 /* Detect high and lows and clock */
193 for (i
= 0; i
< GraphTraceLen
; ++i
)
195 if (GraphBuffer
[i
] > high
)
196 high
= GraphBuffer
[i
];
197 else if (GraphBuffer
[i
] < low
)
198 low
= GraphBuffer
[i
];
202 clock
= GetClock(Cmd
, high
, 1);
206 for (i
= 0; i
< (int)(gtl
/ clock
); ++i
)
211 /* Find out if we hit both high and low peaks */
212 for (j
= 0; j
< clock
; ++j
)
214 if (GraphBuffer
[(i
* clock
) + j
] == high
)
216 else if (GraphBuffer
[(i
* clock
) + j
] == low
)
218 /* it doesn't count if it's the first part of our read
219 because it's really just trailing from the last sequence */
220 if (first
&& (hithigh
|| hitlow
))
221 hithigh
= hitlow
= 0;
225 if (hithigh
&& hitlow
)
229 /* If we didn't hit both high and low peaks, we had a bit transition */
230 if (!hithigh
|| !hitlow
)
233 AppendGraph(0, clock
, bit
);
234 // for (j = 0; j < (int)(clock/2); j++)
235 // GraphBuffer[(i * clock) + j] = bit ^ 1;
236 // for (j = (int)(clock/2); j < clock; j++)
237 // GraphBuffer[(i * clock) + j] = bit;
240 RepaintGraphWindow();
244 int CmdBuffClear(const char *Cmd
)
246 UsbCommand c
= {CMD_BUFF_CLEAR
};
252 int CmdDec(const char *Cmd
)
254 for (int i
= 0; i
< (GraphTraceLen
/ 2); ++i
)
255 GraphBuffer
[i
] = GraphBuffer
[i
* 2];
257 PrintAndLog("decimated by 2");
258 RepaintGraphWindow();
262 /* Print our clock rate */
263 int CmdDetectClockRate(const char *Cmd
)
265 int clock
= DetectClock(0);
266 PrintAndLog("Auto-detected clock rate: %d", clock
);
270 int CmdFSKdemod(const char *Cmd
)
272 static const int LowTone
[] = {
273 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
274 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
275 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
276 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
277 1, 1, 1, 1, 1, -1, -1, -1, -1, -1
279 static const int HighTone
[] = {
280 1, 1, 1, 1, 1, -1, -1, -1, -1,
281 1, 1, 1, 1, -1, -1, -1, -1,
282 1, 1, 1, 1, -1, -1, -1, -1,
283 1, 1, 1, 1, -1, -1, -1, -1,
284 1, 1, 1, 1, -1, -1, -1, -1,
285 1, 1, 1, 1, -1, -1, -1, -1, -1,
288 int lowLen
= sizeof (LowTone
) / sizeof (int);
289 int highLen
= sizeof (HighTone
) / sizeof (int);
290 int convLen
= (highLen
> lowLen
) ? highLen
: lowLen
;
291 uint32_t hi
= 0, lo
= 0;
294 int minMark
= 0, maxMark
= 0;
296 for (i
= 0; i
< GraphTraceLen
- convLen
; ++i
) {
297 int lowSum
= 0, highSum
= 0;
299 for (j
= 0; j
< lowLen
; ++j
) {
300 lowSum
+= LowTone
[j
]*GraphBuffer
[i
+j
];
302 for (j
= 0; j
< highLen
; ++j
) {
303 highSum
+= HighTone
[j
] * GraphBuffer
[i
+ j
];
305 lowSum
= abs(100 * lowSum
/ lowLen
);
306 highSum
= abs(100 * highSum
/ highLen
);
307 GraphBuffer
[i
] = (highSum
<< 16) | lowSum
;
310 for(i
= 0; i
< GraphTraceLen
- convLen
- 16; ++i
) {
311 int lowTot
= 0, highTot
= 0;
312 // 10 and 8 are f_s divided by f_l and f_h, rounded
313 for (j
= 0; j
< 10; ++j
) {
314 lowTot
+= (GraphBuffer
[i
+j
] & 0xffff);
316 for (j
= 0; j
< 8; j
++) {
317 highTot
+= (GraphBuffer
[i
+ j
] >> 16);
319 GraphBuffer
[i
] = lowTot
- highTot
;
320 if (GraphBuffer
[i
] > maxMark
) maxMark
= GraphBuffer
[i
];
321 if (GraphBuffer
[i
] < minMark
) minMark
= GraphBuffer
[i
];
324 GraphTraceLen
-= (convLen
+ 16);
325 RepaintGraphWindow();
327 // Find bit-sync (3 lo followed by 3 high)
328 int max
= 0, maxPos
= 0;
329 for (i
= 0; i
< 6000; ++i
) {
331 for (j
= 0; j
< 3 * lowLen
; ++j
) {
332 dec
-= GraphBuffer
[i
+ j
];
334 for (; j
< 3 * (lowLen
+ highLen
); ++j
) {
335 dec
+= GraphBuffer
[i
+ j
];
343 // place start of bit sync marker in graph
344 GraphBuffer
[maxPos
] = maxMark
;
345 GraphBuffer
[maxPos
+ 1] = minMark
;
349 // place end of bit sync marker in graph
350 GraphBuffer
[maxPos
] = maxMark
;
351 GraphBuffer
[maxPos
+1] = minMark
;
353 PrintAndLog("actual data bits start at sample %d", maxPos
);
354 PrintAndLog("length %d/%d", highLen
, lowLen
);
357 bits
[sizeof(bits
)-1] = '\0';
359 // find bit pairs and manchester decode them
360 for (i
= 0; i
< arraylen(bits
) - 1; ++i
) {
362 for (j
= 0; j
< lowLen
; ++j
) {
363 dec
-= GraphBuffer
[maxPos
+ j
];
365 for (; j
< lowLen
+ highLen
; ++j
) {
366 dec
+= GraphBuffer
[maxPos
+ j
];
369 // place inter bit marker in graph
370 GraphBuffer
[maxPos
] = maxMark
;
371 GraphBuffer
[maxPos
+ 1] = minMark
;
373 // hi and lo form a 64 bit pair
374 hi
= (hi
<< 1) | (lo
>> 31);
376 // store decoded bit as binary (in hi/lo) and text (in bits[])
384 PrintAndLog("bits: '%s'", bits
);
385 PrintAndLog("hex: %08x %08x", hi
, lo
);
389 int CmdGrid(const char *Cmd
)
391 sscanf(Cmd
, "%i %i", &PlotGridX
, &PlotGridY
);
392 PlotGridXdefault
= PlotGridX
;
393 PlotGridYdefault
= PlotGridY
;
394 RepaintGraphWindow();
398 int CmdHexsamples(const char *Cmd
)
403 sscanf(Cmd
, "%i %i", &requested
, &offset
);
404 if (offset
% 4 != 0) {
405 PrintAndLog("Offset must be a multiple of 4");
412 if (requested
== 0) {
419 for (int i
= offset
; i
< n
+offset
; i
+= 12) {
420 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {i
, 0, 0}};
422 WaitForResponse(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
, NULL
);
423 for (int j
= 0; j
< 48; j
+= 8) {
424 PrintAndLog("%02x %02x %02x %02x %02x %02x %02x %02x",
436 if (delivered
>= requested
)
439 if (delivered
>= requested
)
445 int CmdHide(const char *Cmd
)
451 int CmdHpf(const char *Cmd
)
456 for (i
= 10; i
< GraphTraceLen
; ++i
)
457 accum
+= GraphBuffer
[i
];
458 accum
/= (GraphTraceLen
- 10);
459 for (i
= 0; i
< GraphTraceLen
; ++i
)
460 GraphBuffer
[i
] -= accum
;
462 RepaintGraphWindow();
466 int CmdSamples(const char *Cmd
)
471 n
= strtol(Cmd
, NULL
, 0);
473 if (n
> 16000) n
= 16000;
475 PrintAndLog("Reading %d samples\n", n
);
476 for (int i
= 0; i
< n
; i
+= 12) {
477 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {i
, 0, 0}};
479 WaitForResponse(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
, NULL
);
480 for (int j
= 0; j
< 48; j
++) {
481 GraphBuffer
[cnt
++] = ((int)sample_buf
[j
]) - 128;
484 PrintAndLog("Done!\n");
486 RepaintGraphWindow();
490 int CmdLoad(const char *Cmd
)
492 FILE *f
= fopen(Cmd
, "r");
494 PrintAndLog("couldn't open '%s'", Cmd
);
500 while (fgets(line
, sizeof (line
), f
)) {
501 GraphBuffer
[GraphTraceLen
] = atoi(line
);
505 PrintAndLog("loaded %d samples", GraphTraceLen
);
506 RepaintGraphWindow();
510 int CmdLtrim(const char *Cmd
)
514 for (int i
= ds
; i
< GraphTraceLen
; ++i
)
515 GraphBuffer
[i
-ds
] = GraphBuffer
[i
];
518 RepaintGraphWindow();
523 * Manchester demodulate a bitstream. The bitstream needs to be already in
524 * the GraphBuffer as 0 and 1 values
526 * Give the clock rate as argument in order to help the sync - the algorithm
527 * resyncs at each pulse anyway.
529 * Not optimized by any means, this is the 1st time I'm writing this type of
530 * routine, feel free to improve...
532 * 1st argument: clock rate (as number of samples per clock rate)
533 * Typical values can be 64, 32, 128...
535 int CmdManchesterDemod(const char *Cmd
)
543 int hithigh
, hitlow
, first
;
549 /* check if we're inverting output */
552 PrintAndLog("Inverting output");
557 while(*Cmd
== ' '); // in case a 2nd argument was given
560 /* Holds the decoded bitstream: each clock period contains 2 bits */
561 /* later simplified to 1 bit after manchester decoding. */
562 /* Add 10 bits to allow for noisy / uncertain traces without aborting */
563 /* int BitStream[GraphTraceLen*2/clock+10]; */
565 /* But it does not work if compiling on WIndows: therefore we just allocate a */
567 uint8_t BitStream
[MAX_GRAPH_TRACE_LEN
];
569 /* Detect high and lows */
570 for (i
= 0; i
< GraphTraceLen
; i
++)
572 if (GraphBuffer
[i
] > high
)
573 high
= GraphBuffer
[i
];
574 else if (GraphBuffer
[i
] < low
)
575 low
= GraphBuffer
[i
];
579 clock
= GetClock(Cmd
, high
, 1);
581 int tolerance
= clock
/4;
583 /* Detect first transition */
584 /* Lo-Hi (arbitrary) */
585 /* skip to the first high */
586 for (i
= 0; i
< GraphTraceLen
; i
++)
587 if (GraphBuffer
[i
] == high
)
589 /* now look for the first low */
590 for (; i
< GraphTraceLen
; i
++)
592 if (GraphBuffer
[i
] == low
)
599 /* If we're not working with 1/0s, demod based off clock */
602 bit
= 0; /* We assume the 1st bit is zero, it may not be
603 * the case: this routine (I think) has an init problem.
606 for (; i
< (int)(GraphTraceLen
/ clock
); i
++)
612 /* Find out if we hit both high and low peaks */
613 for (j
= 0; j
< clock
; j
++)
615 if (GraphBuffer
[(i
* clock
) + j
] == high
)
617 else if (GraphBuffer
[(i
* clock
) + j
] == low
)
620 /* it doesn't count if it's the first part of our read
621 because it's really just trailing from the last sequence */
622 if (first
&& (hithigh
|| hitlow
))
623 hithigh
= hitlow
= 0;
627 if (hithigh
&& hitlow
)
631 /* If we didn't hit both high and low peaks, we had a bit transition */
632 if (!hithigh
|| !hitlow
)
635 BitStream
[bit2idx
++] = bit
^ invert
;
639 /* standard 1/0 bitstream */
643 /* Then detect duration between 2 successive transitions */
644 for (bitidx
= 1; i
< GraphTraceLen
; i
++)
646 if (GraphBuffer
[i
-1] != GraphBuffer
[i
])
651 // Error check: if bitidx becomes too large, we do not
652 // have a Manchester encoded bitstream or the clock is really
654 if (bitidx
> (GraphTraceLen
*2/clock
+8) ) {
655 PrintAndLog("Error: the clock you gave is probably wrong, aborting.");
658 // Then switch depending on lc length:
659 // Tolerance is 1/4 of clock rate (arbitrary)
660 if (abs(lc
-clock
/2) < tolerance
) {
661 // Short pulse : either "1" or "0"
662 BitStream
[bitidx
++]=GraphBuffer
[i
-1];
663 } else if (abs(lc
-clock
) < tolerance
) {
664 // Long pulse: either "11" or "00"
665 BitStream
[bitidx
++]=GraphBuffer
[i
-1];
666 BitStream
[bitidx
++]=GraphBuffer
[i
-1];
670 PrintAndLog("Warning: Manchester decode error for pulse width detection.");
671 PrintAndLog("(too many of those messages mean either the stream is not Manchester encoded, or clock is wrong)");
675 PrintAndLog("Error: too many detection errors, aborting.");
682 // At this stage, we now have a bitstream of "01" ("1") or "10" ("0"), parse it into final decoded bitstream
683 // Actually, we overwrite BitStream with the new decoded bitstream, we just need to be careful
684 // to stop output at the final bitidx2 value, not bitidx
685 for (i
= 0; i
< bitidx
; i
+= 2) {
686 if ((BitStream
[i
] == 0) && (BitStream
[i
+1] == 1)) {
687 BitStream
[bit2idx
++] = 1 ^ invert
;
688 } else if ((BitStream
[i
] == 1) && (BitStream
[i
+1] == 0)) {
689 BitStream
[bit2idx
++] = 0 ^ invert
;
691 // We cannot end up in this state, this means we are unsynchronized,
695 PrintAndLog("Unsynchronized, resync...");
696 PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)");
700 PrintAndLog("Error: too many decode errors, aborting.");
707 PrintAndLog("Manchester decoded bitstream");
708 // Now output the bitstream to the scrollback by line of 16 bits
709 for (i
= 0; i
< (bit2idx
-16); i
+=16) {
710 PrintAndLog("%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
731 /* Modulate our data into manchester */
732 int CmdManchesterMod(const char *Cmd
)
736 int bit
, lastbit
, wave
;
739 clock
= GetClock(Cmd
, 0, 1);
743 for (i
= 0; i
< (int)(GraphTraceLen
/ clock
); i
++)
745 bit
= GraphBuffer
[i
* clock
] ^ 1;
747 for (j
= 0; j
< (int)(clock
/2); j
++)
748 GraphBuffer
[(i
* clock
) + j
] = bit
^ lastbit
^ wave
;
749 for (j
= (int)(clock
/2); j
< clock
; j
++)
750 GraphBuffer
[(i
* clock
) + j
] = bit
^ lastbit
^ wave
^ 1;
752 /* Keep track of how we start our wave and if we changed or not this time */
753 wave
^= bit
^ lastbit
;
757 RepaintGraphWindow();
761 int CmdNorm(const char *Cmd
)
764 int max
= INT_MIN
, min
= INT_MAX
;
766 for (i
= 10; i
< GraphTraceLen
; ++i
) {
767 if (GraphBuffer
[i
] > max
)
768 max
= GraphBuffer
[i
];
769 if (GraphBuffer
[i
] < min
)
770 min
= GraphBuffer
[i
];
774 for (i
= 0; i
< GraphTraceLen
; ++i
) {
775 GraphBuffer
[i
] = (GraphBuffer
[i
] - ((max
+ min
) / 2)) * 1000 /
779 RepaintGraphWindow();
783 int CmdPlot(const char *Cmd
)
789 int CmdSave(const char *Cmd
)
791 FILE *f
= fopen(Cmd
, "w");
793 PrintAndLog("couldn't open '%s'", Cmd
);
797 for (i
= 0; i
< GraphTraceLen
; i
++) {
798 fprintf(f
, "%d\n", GraphBuffer
[i
]);
801 PrintAndLog("saved to '%s'", Cmd
);
805 int CmdScale(const char *Cmd
)
807 CursorScaleFactor
= atoi(Cmd
);
808 if (CursorScaleFactor
== 0) {
809 PrintAndLog("bad, can't have zero scale");
810 CursorScaleFactor
= 1;
812 RepaintGraphWindow();
816 int CmdThreshold(const char *Cmd
)
818 int threshold
= atoi(Cmd
);
820 for (int i
= 0; i
< GraphTraceLen
; ++i
) {
821 if (GraphBuffer
[i
] >= threshold
)
826 RepaintGraphWindow();
830 int CmdZerocrossings(const char *Cmd
)
832 // Zero-crossings aren't meaningful unless the signal is zero-mean.
839 for (int i
= 0; i
< GraphTraceLen
; ++i
) {
840 if (GraphBuffer
[i
] * sign
>= 0) {
841 // No change in sign, reproduce the previous sample count.
843 GraphBuffer
[i
] = lastZc
;
845 // Change in sign, reset the sample count.
847 GraphBuffer
[i
] = lastZc
;
855 RepaintGraphWindow();
859 static command_t CommandTable
[] =
861 {"help", CmdHelp
, 1, "This help"},
862 {"amp", CmdAmp
, 1, "Amplify peaks"},
863 {"askdemod", Cmdaskdemod
, 1, "<0|1> -- Attempt to demodulate simple ASK tags"},
864 {"autocorr", CmdAutoCorr
, 1, "<window length> -- Autocorrelation over window"},
865 {"bitsamples", CmdBitsamples
, 0, "Get raw samples as bitstring"},
866 {"bitstream", CmdBitstream
, 1, "[clock rate] -- Convert waveform into a bitstream"},
867 {"buffclear", CmdBuffClear
, 1, "Clear sample buffer and graph window"},
868 {"dec", CmdDec
, 1, "Decimate samples"},
869 {"detectclock", CmdDetectClockRate
, 1, "Detect clock rate"},
870 {"fskdemod", CmdFSKdemod
, 1, "Demodulate graph window as a HID FSK"},
871 {"grid", CmdGrid
, 1, "<x> <y> -- overlay grid on graph window, use zero value to turn off either"},
872 {"hexsamples", CmdHexsamples
, 0, "<blocks> [<offset>] -- Dump big buffer as hex bytes"},
873 {"hide", CmdHide
, 1, "Hide graph window"},
874 {"hpf", CmdHpf
, 1, "Remove DC offset from trace"},
875 {"load", CmdLoad
, 1, "<filename> -- Load trace (to graph window"},
876 {"ltrim", CmdLtrim
, 1, "<samples> -- Trim samples from left of trace"},
877 {"mandemod", CmdManchesterDemod
, 1, "[i] [clock rate] -- Manchester demodulate binary stream (option 'i' to invert output)"},
878 {"manmod", CmdManchesterMod
, 1, "[clock rate] -- Manchester modulate a binary stream"},
879 {"norm", CmdNorm
, 1, "Normalize max/min to +/-500"},
880 {"plot", CmdPlot
, 1, "Show graph window (hit 'h' in window for keystroke help)"},
881 {"samples", CmdSamples
, 0, "[128 - 16000] -- Get raw samples for graph window"},
882 {"save", CmdSave
, 1, "<filename> -- Save trace (from graph window)"},
883 {"scale", CmdScale
, 1, "<int> -- Set cursor display scale"},
884 {"threshold", CmdThreshold
, 1, "<threshold> -- Maximize/minimize every value in the graph window depending on threshold"},
885 {"zerocrossings", CmdZerocrossings
, 1, "Count time between zero-crossings"},
886 {NULL
, NULL
, 0, NULL
}
889 int CmdData(const char *Cmd
)
891 CmdsParse(CommandTable
, Cmd
);
895 int CmdHelp(const char *Cmd
)
897 CmdsHelp(CommandTable
);