1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2009 Michael Gernoth <michael at gernoth.net>
3 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
8 //-----------------------------------------------------------------------------
10 //-----------------------------------------------------------------------------
17 #include <readline/readline.h>
19 #include "loclass/cipherutils.h"
22 //#include <liquid/liquid.h>
23 #define M_PI 3.14159265358979323846264338327
25 double CursorScaleFactor
;
26 int PlotGridX
, PlotGridY
, PlotGridXdefault
= 64, PlotGridYdefault
= 64;
28 int flushAfterWrite
= 0; //buzzy
29 extern pthread_mutex_t print_lock
;
31 static char *logfilename
= "proxmark3.log";
33 void PrintAndLog(char *fmt
, ...)
37 va_list argptr
, argptr2
;
38 static FILE *logfile
= NULL
;
41 // lock this section to avoid interlacing prints from different threats
42 pthread_mutex_lock(&print_lock
);
44 if (logging
&& !logfile
) {
45 logfile
=fopen(logfilename
, "a");
47 fprintf(stderr
, "Can't open logfile, logging disabled!\n");
52 int need_hack
= (rl_readline_state
& RL_STATE_READCMD
) > 0;
55 saved_point
= rl_point
;
56 saved_line
= rl_copy_text(0, rl_end
);
58 rl_replace_line("", 0);
62 va_start(argptr
, fmt
);
63 va_copy(argptr2
, argptr
);
65 printf(" "); // cleaning prompt
71 rl_replace_line(saved_line
, 0);
72 rl_point
= saved_point
;
77 if (logging
&& logfile
) {
78 vfprintf(logfile
, fmt
, argptr2
);
79 fprintf(logfile
,"\n");
84 if (flushAfterWrite
== 1) //buzzy
89 pthread_mutex_unlock(&print_lock
);
92 void SetLogFilename(char *fn
)
97 int manchester_decode( int * data
, const size_t len
, uint8_t * dataout
){
100 int i
, clock
, high
, low
, startindex
;
101 low
= startindex
= 0;
103 uint8_t bitStream
[len
];
105 memset(bitStream
, 0x00, len
);
107 /* Detect high and lows */
108 for (i
= 0; i
< len
; i
++) {
111 else if (data
[i
] < low
)
116 clock
= GetT55x7Clock( data
, len
, high
);
117 startindex
= DetectFirstTransition(data
, len
, high
);
119 //PrintAndLog(" Clock : %d", clock);
120 //PrintAndLog(" startindex : %d", startindex);
123 bitlength
= ManchesterConvertFrom255(data
, len
, bitStream
, high
, low
, clock
, startindex
);
125 bitlength
= ManchesterConvertFrom1(data
, len
, bitStream
, clock
, startindex
);
127 //if ( bitlength > 0 )
128 // PrintPaddedManchester(bitStream, bitlength, clock);
130 memcpy(dataout
, bitStream
, bitlength
);
134 int GetT55x7Clock( const int * data
, const size_t len
, int peak
){
136 int i
,lastpeak
,clock
;
140 /* Detect peak if we don't have one */
142 for (i
= 0; i
< len
; ++i
) {
143 if (data
[i
] > peak
) {
149 for (i
= 1; i
< len
; ++i
) {
150 /* if this is the beginning of a peak */
151 if ( data
[i
-1] != data
[i
] && data
[i
] == peak
) {
152 /* find lowest difference between peaks */
153 if (lastpeak
&& i
- lastpeak
< clock
)
154 clock
= i
- lastpeak
;
159 //defaults clock to precise values.
174 //PrintAndLog(" Found Clock : %d - trying to adjust", clock);
176 // When detected clock is 31 or 33 then then return
177 int clockmod
= clock
%8;
180 else if ( clockmod
== 1 )
186 int DetectFirstTransition(const int * data
, const size_t len
, int threshold
){
189 /* now look for the first threshold */
190 for (; i
< len
; ++i
) {
191 if (data
[i
] == threshold
) {
198 int ManchesterConvertFrom255(const int * data
, const size_t len
, uint8_t * dataout
, int high
, int low
, int clock
, int startIndex
){
200 int i
, j
, z
, hithigh
, hitlow
, bitIndex
, startType
;
205 int damplimit
= (int)((high
/ 2) * 0.3);
206 int dampHi
= (high
/2)+damplimit
;
207 int dampLow
= (high
/2)-damplimit
;
210 // i = clock frame of data
211 for (; i
< (int)(len
/ clock
); i
++)
216 z
= startIndex
+ (i
*clock
);
219 /* Find out if we hit both high and low peaks */
220 for (j
= 0; j
< clock
; j
++)
222 if (data
[z
+j
] == high
){
224 if ( startType
== -1)
228 if (data
[z
+j
] == low
){
230 if ( startType
== -1)
234 if (hithigh
&& hitlow
)
238 // No high value found, are we in a dampening field?
240 //PrintAndLog(" # Entering damp test at index : %d (%d)", z+j, j);
241 for (j
= 0; j
< clock
; j
++)
244 (data
[z
+j
] <= dampHi
&& data
[z
+j
] >= dampLow
)
251 /* Manchester Switching..
256 dataout
[bitIndex
++] = 1;
257 else if (startType
== 1)
258 dataout
[bitIndex
++] = 0;
260 dataout
[bitIndex
++] = 2;
262 if ( isDamp
> clock
/2 ) {
272 int ManchesterConvertFrom1(const int * data
, const size_t len
, uint8_t * dataout
, int clock
, int startIndex
){
274 PrintAndLog(" Path B");
276 int i
,j
, bitindex
, lc
, tolerance
, warnings
;
278 int upperlimit
= len
*2/clock
+8;
282 uint8_t decodedArr
[len
];
284 /* Detect duration between 2 successive transitions */
285 for (bitindex
= 1; i
< len
; i
++) {
287 if (data
[i
-1] != data
[i
]) {
291 // Error check: if bitindex becomes too large, we do not
292 // have a Manchester encoded bitstream or the clock is really wrong!
293 if (bitindex
> upperlimit
) {
294 PrintAndLog("Error: the clock you gave is probably wrong, aborting.");
297 // Then switch depending on lc length:
298 // Tolerance is 1/4 of clock rate (arbitrary)
299 if (abs((lc
-clock
)/2) < tolerance
) {
300 // Short pulse : either "1" or "0"
301 decodedArr
[bitindex
++] = data
[i
-1];
302 } else if (abs(lc
-clock
) < tolerance
) {
303 // Long pulse: either "11" or "00"
304 decodedArr
[bitindex
++] = data
[i
-1];
305 decodedArr
[bitindex
++] = data
[i
-1];
308 PrintAndLog("Warning: Manchester decode error for pulse width detection.");
310 PrintAndLog("Error: too many detection errors, aborting.");
318 * We have a decodedArr of "01" ("1") or "10" ("0")
319 * parse it into final decoded dataout
321 for (i
= 0; i
< bitindex
; i
+= 2) {
323 if ((decodedArr
[i
] == 0) && (decodedArr
[i
+1] == 1)) {
325 } else if ((decodedArr
[i
] == 1) && (decodedArr
[i
+1] == 0)) {
330 PrintAndLog("Unsynchronized, resync...");
331 PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)");
334 PrintAndLog("Error: too many decode errors, aborting.");
340 PrintAndLog("%s", sprint_hex(dataout
, j
));
344 void ManchesterDiffDecodedString(const uint8_t* bitstream
, size_t len
, uint8_t invert
){
346 * We have a bitstream of "01" ("1") or "10" ("0")
347 * parse it into final decoded bitstream
350 uint8_t decodedArr
[(len
/2)+1];
356 for (i
= 0; i
< len
; i
+= 2) {
358 uint8_t first
= bitstream
[i
];
359 uint8_t second
= bitstream
[i
+1];
361 if ( first
== second
) {
365 PrintAndLog("Error: too many decode errors, aborting.");
369 else if ( lastbit
!= first
) {
370 decodedArr
[j
++] = 0 ^ invert
;
373 decodedArr
[j
++] = 1 ^ invert
;
378 PrintAndLog("%s", sprint_hex(decodedArr
, j
));
381 void PrintPaddedManchester( uint8_t* bitStream
, size_t len
, size_t blocksize
){
383 PrintAndLog(" Manchester decoded : %d bits", len
);
385 uint8_t mod
= len
% blocksize
;
386 uint8_t div
= len
/ blocksize
;
389 // Now output the bitstream to the scrollback by line of 16 bits
390 for (i
= 0; i
< div
*blocksize
; i
+=blocksize
) {
391 PrintAndLog(" %s", sprint_bin(bitStream
+i
,blocksize
) );
395 PrintAndLog(" %s", sprint_bin(bitStream
+i
, mod
) );
398 void iceFsk(int * data
, const size_t len
){
400 //34359738 == 125khz (2^32 / 125) =
403 float phase_offset
= 0.00f
; // carrier phase offset
404 float frequency_offset
= 0.30f
; // carrier frequency offset
405 float wn
= 0.01f
; // pll bandwidth
406 float zeta
= 0.707f
; // pll damping factor
407 float K
= 1000; // pll loop gain
408 size_t n
= len
; // number of samples
410 // generate loop filter parameters (active PI design)
411 float t1
= K
/(wn
*wn
); // tau_1
412 float t2
= 2*zeta
/wn
; // tau_2
414 // feed-forward coefficients (numerator)
415 float b0
= (4*K
/t1
)*(1.+t2
/2.0f
);
417 float b2
= (4*K
/t1
)*(1.-t2
/2.0f
);
419 // feed-back coefficients (denominator)
420 // a0 = 1.0 is implied
425 float v0
=0.0f
, v1
=0.0f
, v2
=0.0f
;
428 float phi
= phase_offset
; // input signal's initial phase
429 float phi_hat
= 0.0f
; // PLL's initial phase
433 float complex output
[n
];
435 for (i
=0; i
<n
; i
++) {
438 phi
+= frequency_offset
;
440 // generate complex sinusoid
441 y
= cosf(phi_hat
) + _Complex_I
*sinf(phi_hat
);
445 // compute error estimate
446 float delta_phi
= cargf( x
* conjf(y
) );
449 // print results to standard output
450 printf(" %6u %12.8f %12.8f %12.8f %12.8f %12.8f\n",
452 crealf(x
), cimagf(x
),
453 crealf(y
), cimagf(y
),
456 // push result through loop filter, updating phase estimate
459 v2
= v1
; // shift center register to upper register
460 v1
= v0
; // shift lower register to center register
462 // compute new lower register
463 v0
= delta_phi
- v1
*a1
- v2
*a2
;
465 // compute new output
466 phi_hat
= v0
*b0
+ v1
*b1
+ v2
*b2
;
470 for (i
=0; i
<len
; ++i
){
471 data
[i
] = (int)crealf(output
[i
]);
478 void iceFsk2(int * data
, const size_t len
){
483 // for (i=0; i<len-5; ++i){
484 // for ( j=1; j <=5; ++j) {
485 // output[i] += data[i*j];
491 for (i
=0; i
<len
; ++i
){
495 tmp
= (100 * (data
[i
]-rest
)) / rest
;
496 output
[i
] = (tmp
> 60)? 100:0;
500 for (j
=0; j
<len
; ++j
)
504 void iceFsk3(int * data
, const size_t len
){
508 float fc
= 0.1125f
; // center frequency
510 // create very simple low-pass filter to remove images (2nd-order Butterworth)
511 float complex iir_buf
[3] = {0,0,0};
512 float b
[3] = {0.003621681514929, 0.007243363029857, 0.003621681514929};
513 float a
[3] = {1.000000000000000, -1.822694925196308, 0.837181651256023};
515 // process entire input file one sample at a time
516 float sample
= 0; // input sample read from file
517 float complex x_prime
= 1.0f
; // save sample for estimating frequency
520 for (i
=0; i
<len
; ++i
) {
524 // remove DC offset and mix to complex baseband
525 x
= (sample
- 127.5f
) * cexpf( _Complex_I
* 2 * M_PI
* fc
* i
);
527 // apply low-pass filter, removing spectral image (IIR using direct-form II)
528 iir_buf
[2] = iir_buf
[1];
529 iir_buf
[1] = iir_buf
[0];
530 iir_buf
[0] = x
- a
[1]*iir_buf
[1] - a
[2]*iir_buf
[2];
531 x
= b
[0]*iir_buf
[0] +
535 // compute instantaneous frequency by looking at phase difference
536 // between adjacent samples
537 float freq
= cargf(x
*conjf(x_prime
));
538 x_prime
= x
; // retain this sample for next iteration
540 output
[i
] =(freq
> 0)? 10 : -10;
544 for (j
=0; j
<len
; ++j
)
550 for (j
=0; j
<len
; ++j
){
551 if ( data
[j
] == 10) break;
556 if ( data
[j
] == -10 ) break;
560 int fieldlen
= stopOne
-startOne
;
561 printf("FIELD Length: %d \n", fieldlen
);
564 // FSK sequence start == 000111
566 for (i
=0; i
<len
; ++i
){
568 for ( j
= 0; j
< 6*fieldlen
; ++j
){
577 printf("000111 position: %d \n", startPos
);
579 startPos
+= 6*fieldlen
+1;
583 for (i
=startPos
; i
< len
; i
+= 40){
592 for (i
=startPos
; i
< len
; i
+= 50){
602 float complex cexpf (float complex Z
)
605 double rho
= exp (__real__ Z
);
606 __real__ Res
= rho
* cosf(__imag__ Z
);
607 __imag__ Res
= rho
* sinf(__imag__ Z
);