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 memcpy(dataout
, bitStream
, bitlength
);
131 int GetT55x7Clock( const int * data
, const size_t len
, int peak
){
133 int i
,lastpeak
,clock
;
137 /* Detect peak if we don't have one */
139 for (i
= 0; i
< len
; ++i
) {
140 if (data
[i
] > peak
) {
146 for (i
= 1; i
< len
; ++i
) {
147 /* if this is the beginning of a peak */
148 if ( data
[i
-1] != data
[i
] && data
[i
] == peak
) {
149 /* find lowest difference between peaks */
150 if (lastpeak
&& i
- lastpeak
< clock
)
151 clock
= i
- lastpeak
;
156 //defaults clock to precise values.
171 //PrintAndLog(" Found Clock : %d - trying to adjust", clock);
173 // When detected clock is 31 or 33 then then return
174 int clockmod
= clock
%8;
177 else if ( clockmod
== 1 )
183 int DetectFirstTransition(const int * data
, const size_t len
, int threshold
){
186 /* now look for the first threshold */
187 for (; i
< len
; ++i
) {
188 if (data
[i
] == threshold
) {
195 int ManchesterConvertFrom255(const int * data
, const size_t len
, uint8_t * dataout
, int high
, int low
, int clock
, int startIndex
){
197 int i
, j
, z
, hithigh
, hitlow
, bitIndex
, startType
;
202 int damplimit
= (int)((high
/ 2) * 0.3);
203 int dampHi
= (high
/2)+damplimit
;
204 int dampLow
= (high
/2)-damplimit
;
207 // i = clock frame of data
208 for (; i
< (int)(len
/ clock
); i
++)
213 z
= startIndex
+ (i
*clock
);
216 /* Find out if we hit both high and low peaks */
217 for (j
= 0; j
< clock
; j
++)
219 if (data
[z
+j
] == high
){
221 if ( startType
== -1)
225 if (data
[z
+j
] == low
){
227 if ( startType
== -1)
231 if (hithigh
&& hitlow
)
235 // No high value found, are we in a dampening field?
237 //PrintAndLog(" # Entering damp test at index : %d (%d)", z+j, j);
238 for (j
= 0; j
< clock
; j
++)
241 (data
[z
+j
] <= dampHi
&& data
[z
+j
] >= dampLow
)
248 /* Manchester Switching..
253 dataout
[bitIndex
++] = 1;
254 else if (startType
== 1)
255 dataout
[bitIndex
++] = 0;
257 dataout
[bitIndex
++] = 2;
259 if ( isDamp
> clock
/2 ) {
269 int ManchesterConvertFrom1(const int * data
, const size_t len
, uint8_t * dataout
, int clock
, int startIndex
){
271 PrintAndLog(" Path B");
273 int i
,j
, bitindex
, lc
, tolerance
, warnings
;
275 int upperlimit
= len
*2/clock
+8;
279 uint8_t decodedArr
[len
];
281 /* Detect duration between 2 successive transitions */
282 for (bitindex
= 1; i
< len
; i
++) {
284 if (data
[i
-1] != data
[i
]) {
288 // Error check: if bitindex becomes too large, we do not
289 // have a Manchester encoded bitstream or the clock is really wrong!
290 if (bitindex
> upperlimit
) {
291 PrintAndLog("Error: the clock you gave is probably wrong, aborting.");
294 // Then switch depending on lc length:
295 // Tolerance is 1/4 of clock rate (arbitrary)
296 if (abs((lc
-clock
)/2) < tolerance
) {
297 // Short pulse : either "1" or "0"
298 decodedArr
[bitindex
++] = data
[i
-1];
299 } else if (abs(lc
-clock
) < tolerance
) {
300 // Long pulse: either "11" or "00"
301 decodedArr
[bitindex
++] = data
[i
-1];
302 decodedArr
[bitindex
++] = data
[i
-1];
305 PrintAndLog("Warning: Manchester decode error for pulse width detection.");
307 PrintAndLog("Error: too many detection errors, aborting.");
315 * We have a decodedArr of "01" ("1") or "10" ("0")
316 * parse it into final decoded dataout
318 for (i
= 0; i
< bitindex
; i
+= 2) {
320 if ((decodedArr
[i
] == 0) && (decodedArr
[i
+1] == 1)) {
322 } else if ((decodedArr
[i
] == 1) && (decodedArr
[i
+1] == 0)) {
327 PrintAndLog("Unsynchronized, resync...");
328 PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)");
331 PrintAndLog("Error: too many decode errors, aborting.");
337 PrintAndLog("%s", sprint_hex(dataout
, j
));
341 void ManchesterDiffDecodedString(const uint8_t* bitstream
, size_t len
, uint8_t invert
){
343 * We have a bitstream of "01" ("1") or "10" ("0")
344 * parse it into final decoded bitstream
347 uint8_t decodedArr
[(len
/2)+1];
353 for (i
= 0; i
< len
; i
+= 2) {
355 uint8_t first
= bitstream
[i
];
356 uint8_t second
= bitstream
[i
+1];
358 if ( first
== second
) {
362 PrintAndLog("Error: too many decode errors, aborting.");
366 else if ( lastbit
!= first
) {
367 decodedArr
[j
++] = 0 ^ invert
;
370 decodedArr
[j
++] = 1 ^ invert
;
375 PrintAndLog("%s", sprint_hex(decodedArr
, j
));
378 void PrintPaddedManchester( uint8_t* bitStream
, size_t len
, size_t blocksize
){
380 PrintAndLog(" Manchester decoded : %d bits", len
);
382 uint8_t mod
= len
% blocksize
;
383 uint8_t div
= len
/ blocksize
;
386 // Now output the bitstream to the scrollback by line of 16 bits
387 for (i
= 0; i
< div
*blocksize
; i
+=blocksize
) {
388 PrintAndLog(" %s", sprint_bin(bitStream
+i
,blocksize
) );
392 PrintAndLog(" %s", sprint_bin(bitStream
+i
, mod
) );
395 void iceFsk(int * data
, const size_t len
){
397 //34359738 == 125khz (2^32 / 125) =
400 float phase_offset
= 0.00f
; // carrier phase offset
401 float frequency_offset
= 0.30f
; // carrier frequency offset
402 float wn
= 0.01f
; // pll bandwidth
403 float zeta
= 0.707f
; // pll damping factor
404 float K
= 1000; // pll loop gain
405 size_t n
= len
; // number of samples
407 // generate loop filter parameters (active PI design)
408 float t1
= K
/(wn
*wn
); // tau_1
409 float t2
= 2*zeta
/wn
; // tau_2
411 // feed-forward coefficients (numerator)
412 float b0
= (4*K
/t1
)*(1.+t2
/2.0f
);
414 float b2
= (4*K
/t1
)*(1.-t2
/2.0f
);
416 // feed-back coefficients (denominator)
417 // a0 = 1.0 is implied
422 float v0
=0.0f
, v1
=0.0f
, v2
=0.0f
;
425 float phi
= phase_offset
; // input signal's initial phase
426 float phi_hat
= 0.0f
; // PLL's initial phase
430 float complex output
[n
];
432 for (i
=0; i
<n
; i
++) {
435 phi
+= frequency_offset
;
437 // generate complex sinusoid
438 y
= cosf(phi_hat
) + _Complex_I
*sinf(phi_hat
);
442 // compute error estimate
443 float delta_phi
= cargf( x
* conjf(y
) );
446 // print results to standard output
447 printf(" %6u %12.8f %12.8f %12.8f %12.8f %12.8f\n",
449 crealf(x
), cimagf(x
),
450 crealf(y
), cimagf(y
),
453 // push result through loop filter, updating phase estimate
456 v2
= v1
; // shift center register to upper register
457 v1
= v0
; // shift lower register to center register
459 // compute new lower register
460 v0
= delta_phi
- v1
*a1
- v2
*a2
;
462 // compute new output
463 phi_hat
= v0
*b0
+ v1
*b1
+ v2
*b2
;
467 for (i
=0; i
<len
; ++i
){
468 data
[i
] = (int)crealf(output
[i
]);
475 void iceFsk2(int * data
, const size_t len
){
480 // for (i=0; i<len-5; ++i){
481 // for ( j=1; j <=5; ++j) {
482 // output[i] += data[i*j];
488 for (i
=0; i
<len
; ++i
){
492 tmp
= (100 * (data
[i
]-rest
)) / rest
;
493 output
[i
] = (tmp
> 60)? 100:0;
497 for (j
=0; j
<len
; ++j
)
501 void iceFsk3(int * data
, const size_t len
){
505 float fc
= 0.1125f
; // center frequency
507 // create very simple low-pass filter to remove images (2nd-order Butterworth)
508 float complex iir_buf
[3] = {0,0,0};
509 float b
[3] = {0.003621681514929, 0.007243363029857, 0.003621681514929};
510 float a
[3] = {1.000000000000000, -1.822694925196308, 0.837181651256023};
512 // process entire input file one sample at a time
513 float sample
= 0; // input sample read from file
514 float complex x_prime
= 1.0f
; // save sample for estimating frequency
517 for (i
=0; i
<len
; ++i
) {
521 // remove DC offset and mix to complex baseband
522 x
= (sample
- 127.5f
) * cexpf( _Complex_I
* 2 * M_PI
* fc
* i
);
524 // apply low-pass filter, removing spectral image (IIR using direct-form II)
525 iir_buf
[2] = iir_buf
[1];
526 iir_buf
[1] = iir_buf
[0];
527 iir_buf
[0] = x
- a
[1]*iir_buf
[1] - a
[2]*iir_buf
[2];
528 x
= b
[0]*iir_buf
[0] +
532 // compute instantaneous frequency by looking at phase difference
533 // between adjacent samples
534 float freq
= cargf(x
*conjf(x_prime
));
535 x_prime
= x
; // retain this sample for next iteration
537 output
[i
] =(freq
> 0)? 10 : -10;
541 for (j
=0; j
<len
; ++j
)
547 for (j
=0; j
<len
; ++j
){
548 if ( data
[j
] == 10) break;
553 if ( data
[j
] == -10 ) break;
557 int fieldlen
= stopOne
-startOne
;
559 fieldlen
= (fieldlen
== 39 || fieldlen
== 41)? 40 : fieldlen
;
560 fieldlen
= (fieldlen
== 59 || fieldlen
== 51)? 50 : fieldlen
;
561 if ( fieldlen
!= 40 && fieldlen
!= 50){
562 printf("Detected field Length: %d \n", fieldlen
);
563 printf("Can only handle len 40 or 50. Aborting...");
567 // FSK sequence start == 000111
569 for (i
=0; i
<len
; ++i
){
571 for ( j
= 0; j
< 6*fieldlen
; ++j
){
580 printf("000111 position: %d \n", startPos
);
582 startPos
+= 6*fieldlen
+5;
587 for (i
=startPos
; i
< len
; i
+= 40){
588 bit
= data
[i
]>0 ? 1:0;
594 for (i
=startPos
; i
< len
; i
+= 50){
595 bit
= data
[i
]>0 ? 1:0;
596 printf("%d", bit
); }
601 float complex cexpf (float complex Z
)
604 double rho
= exp (__real__ Z
);
605 __real__ Res
= rho
* cosf(__imag__ Z
);
606 __imag__ Res
= rho
* sinf(__imag__ Z
);