1 //-----------------------------------------------------------------------------
2 // Copyright (C) Jonathan Westhues, 2005
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // See LICENSE.txt for the text of the license.
16 //-----------------------------------------------------------------------------
17 // Miscellaneous routines for low frequency tag operations.
18 // Tags supported here so far are Texas Instruments (TI), HID, EM4x05, EM410x
19 // Also routines for raw mode reading/simulating of LF waveform
20 //-----------------------------------------------------------------------------
24 #include "proxmark3_arm.h"
27 #include "fpgaloader.h"
31 #include "commonutil.h"
36 #include "lfsampling.h"
37 #include "protocols.h"
39 #include "flashmem.h" // persistence on flash
40 #include "appmain.h" // print stack
43 Notes about EM4xxx timings.
45 The timing values differs between cards, we got EM410x, EM43x5, EM445x etc.
46 We are trying to unify and enable the Proxmark3 to easily detect and select correct timings automatic.
47 The measures from datasheets doesn't always match correct the hardware features of RDV4 antenans and we still wanted to let other devices with other custom antennas
48 still benefit from this repo. This is why its configurable and we use to set these dynamic settings in device external flash memory.
51 // VALUES TAKEN FROM EM4x function: SendForward
52 // START_GAP = 440; (55*8) cycles at 125kHz (8us = 1cycle)
53 // WRITE_GAP = 128; (16*8)
54 // WRITE_1 = 256 32*8; (32*8)
56 // These timings work for 4469/4269/4305 (with the 55*8 above)
57 // WRITE_0 = 23*8 , 9*8
60 Short note about timers on Proxmark device ARM. They are a bit differently implemented and gives decent correctness.
62 SAM7S has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
63 TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
65 New timer implementation in ticks.c, which is used in LFOPS.c
67 1 fc = 8 μs = 12 ticks
69 Terms you find in different datasheets and how they match.
70 1 Cycle = 8 microseconds (μs) == 1 field clock (fc)
72 Note about HITAG timing
73 Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
74 T0 = TIMER_CLOCK1 / 125000 = 192
77 ==========================================================================================================
79 ==========================================================================================================
81 ATA5577 Downlink Protocol Timings.
82 Note: All absolute times assume TC = 1 / fC = 8 μs (fC = 125 kHz)
84 Note: These timings are from the datasheet and doesn't map the best to the features of the RVD4 LF antenna.
85 RDV4 LF antenna has high voltage and the drop of power when turning off the rf field takes about 1-2 TC longer.
87 -----------------------------------------------------------------------
88 Fixed-bit-length Protocol | Normal Downlink | Fast Downlink |
89 ------------------------------+-----------------------------------+-----------------------------------+------
90 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
91 |------------+--------+--------+-----------+-----------+-----------+-----------+-----------+-----------+------|
92 | Start gap | | Sgap | 8 | 15 | 50 | 8 | 15 | 50 | Tc |
93 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
94 |------------+--------+--------+-----------+-----------+-----------+-----------+-----------+-----------+------|
95 | coding | 0 data | d0 | 16 | 24 | 32 | 8 | 12 | 16 | Tc |
96 | | 1 data | d1 | 48 | 56 | 64 | 24 | 28 | 32 | Tc |
97 -------------------------------------------------------------------------------------------------------------
99 -----------------------------------------------------------------------
100 Long Leading Reference | Normal Downlink | Fast Downlink |
101 ------------------------------+-----------------------------------+-----------------------------------+------
102 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
103 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
104 | Start gap | | Sgap | 8 | 10 | 50 | 8 | 10 | 50 | Tc |
105 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
106 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
107 | Write | Ref | | 152 | 160 | 168 | 140 | 144 | 148 | Tc |
108 | data | Pulse | dref | 136 clocks + 0 data bit | 132 clocks + 0 data bit | Tc |
109 | coding |--------+---------+-----------------------------------+-----------------------------------+------|
110 | | 0 data | d0 |dref – 143 |dref – 136 |dref – 128 |dref – 135 |dref – 132 |dref – 124 | Tc |
111 | | 1 data | d1 |dref – 111 |dref – 104 |dref – 96 |dref – 119 |dref – 116 |dref – 112 | Tc |
112 -------------------------------------------------------------------------------------------------------------
114 -----------------------------------------------------------------------
115 Leading-zero Reference | Normal Downlink | Fast Downlink |
116 ------------------------------+-----------------------------------+-----------------------------------+------
117 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
118 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
119 | Start gap | | Sgap | 8 | 10 | 50 | 8 | 10 | 50 | Tc |
120 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
121 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
122 | Write | Ref | dref | 12 | – | 72 | 8 | – | 68 | Tc |
123 | data | 0 data | d0 | dref – 7 | dref | dref + 8 | dref – 3 | dref | dref + 4 | Tc |
124 | coding | 1 data | d1 | dref + 9 | dref + 16 | dref + 24 | dref + 5 | dref + 8 | dref + 12 | Tc |
125 -------------------------------------------------------------------------------------------------------------
127 -----------------------------------------------------------------------
128 1-of-4 Coding | Normal Downlink | Fast Downlink |
129 ------------------------------+-----------------------------------+-----------------------------------+------
130 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
131 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
132 | Start gap | | Sgap | 8 | 10 | 50 | 8 | 10 | 50 | Tc |
133 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
134 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
135 | Write | Ref 00 | dref | 8 | – | 68 | 12 | – | 72 | Tc |
136 | data |00 data | d00 | dref – 7 | dref | dref + 8 | dref – 3 | dref | dref+ 4 | Tc |
137 | coding |01 data | d01 | dref + 9 | dref + 16 | dref + 24 | dref + 5 | dref + 8 | dref + 12 | Tc |
138 | |10 data | d10 | dref + 25 | dref + 32 | dref + 40 | dref + 13 | dref + 16 | dref + 20 | Tc |
139 | |11 data | d11 | dref + 41 | dref + 48 | dref + 56 | dref + 21 | dref + 24 | dref + 28 | Tc |
140 -------------------------------------------------------------------------------------------------------------
142 Initial values if not in flash
148 Explanations for array T55xx_Timing below
151 SG WG Bit 00 Bit 01 Bit 10 Bit 11 RG
152 --------------------------------------------------------------------
153 { 29 , 17 , 15 , 47 , 0 , 0 , 15 }, // Default Fixed
154 { 29 , 17 , 15 , 50 , 0 , 0 , 15 }, // Long Leading Ref.
155 { 29 , 17 , 15 , 40 , 0 , 0 , 15 }, // Leading 0
156 { 29 , 17 , 15 , 31 , 47 , 63 , 15 } // 1 of 4
158 static t55xx_configurations_t T55xx_Timing
= {
162 { 29 * 8, 17 * 8, 15 * 8, 47 * 8, 15 * 8, 0, 0 }, // Default Fixed
163 { 29 * 8, 17 * 8, 15 * 8, 47 * 8, 15 * 8, 0, 0 }, // Long Leading Ref.
164 { 29 * 8, 17 * 8, 15 * 8, 40 * 8, 15 * 8, 0, 0 }, // Leading 0
165 { 29 * 8, 17 * 8, 15 * 8, 31 * 8, 15 * 8, 47 * 8, 63 * 8 } // 1 of 4
167 // PM3GENERIC or like official repo
168 { 31 * 8, 20 * 8, 18 * 8, 50 * 8, 15 * 8, 0, 0 }, // Default Fixed
169 { 31 * 8, 20 * 8, 18 * 8, 50 * 8, 15 * 8, 0, 0 }, // Long Leading Ref.
170 { 31 * 8, 20 * 8, 18 * 8, 40 * 8, 15 * 8, 0, 0 }, // Leading 0
171 { 31 * 8, 20 * 8, 18 * 8, 34 * 8, 15 * 8, 50 * 8, 66 * 8 } // 1 of 4
177 // Some defines for readability
178 #define T55XX_DLMODE_FIXED 0 // Default Mode
179 #define T55XX_DLMODE_LLR 1 // Long Leading Reference
180 #define T55XX_DLMODE_LEADING_ZERO 2 // Leading Zero
181 #define T55XX_DLMODE_1OF4 3 // 1 of 4
182 #define T55XX_LONGLEADINGREFERENCE 4 // Value to tell Write Bit to send long reference
184 // ATA55xx shared presets & routines
185 static uint32_t GetT55xxClockBit(uint8_t clock
) {
188 return T55x7_BITRATE_RF_128
;
190 return T55x7_BITRATE_RF_100
;
192 return T55x7_BITRATE_RF_64
;
194 return T55x7_BITRATE_RF_50
;
196 return T55x7_BITRATE_RF_40
;
198 return T55x7_BITRATE_RF_32
;
200 return T55x7_BITRATE_RF_16
;
202 return T55x7_BITRATE_RF_8
;
208 void printT55xxConfig(void) {
210 #define PRN_NA sprintf(s + strlen(s), _RED_("n/a") " | ");
212 DbpString(_CYAN_("LF T55XX config"));
213 Dbprintf(" [r] [a] [b] [c] [d] [e] [f] [g]");
214 Dbprintf(" mode |start|write|write|write| read|write|write");
215 Dbprintf(" | gap | gap | 0 | 1 | gap | 2 | 3");
216 Dbprintf("---------------------------+-----+-----+-----+-----+-----+-----+------");
218 for (uint8_t i
= 0; i
< 4; i
++) {
221 memset(s
, 0, sizeof(s
));
224 case T55XX_DLMODE_FIXED
:
225 sprintf(s
, _YELLOW_("fixed bit length") _GREEN_(" (default)") " |");
227 case T55XX_DLMODE_LLR
:
228 sprintf(s
, _YELLOW_(" long leading reference") " |");
230 case T55XX_DLMODE_LEADING_ZERO
:
231 sprintf(s
, _YELLOW_(" leading zero") " |");
233 case T55XX_DLMODE_1OF4
:
234 sprintf(s
, _YELLOW_(" 1 of 4 coding reference") " |");
240 if (T55xx_Timing
.m
[i
].start_gap
!= 0xFFFF) {
241 sprintf(s
+ strlen(s
), " %3d | ", T55xx_Timing
.m
[i
].start_gap
/ 8);
246 if (T55xx_Timing
.m
[i
].write_gap
!= 0xFFFF) {
247 sprintf(s
+ strlen(s
), "%3d | ", T55xx_Timing
.m
[i
].write_gap
/ 8);
252 if (T55xx_Timing
.m
[i
].write_0
!= 0xFFFF) {
253 sprintf(s
+ strlen(s
), "%3d | ", T55xx_Timing
.m
[i
].write_0
/ 8);
258 if (T55xx_Timing
.m
[i
].write_1
!= 0xFFFF) {
259 sprintf(s
+ strlen(s
), "%3d | ", T55xx_Timing
.m
[i
].write_1
/ 8);
264 if (T55xx_Timing
.m
[i
].read_gap
!= 0xFFFF) {
265 sprintf(s
+ strlen(s
), "%3d | ", T55xx_Timing
.m
[i
].read_gap
/ 8);
270 if (T55xx_Timing
.m
[i
].write_2
!= 0xFFFF && i
== T55XX_DLMODE_1OF4
) {
271 sprintf(s
+ strlen(s
), "%3d | ", T55xx_Timing
.m
[i
].write_2
/ 8);
276 if (T55xx_Timing
.m
[i
].write_3
!= 0xFFFF && i
== T55XX_DLMODE_1OF4
) {
277 sprintf(s
+ strlen(s
), "%3d | ", T55xx_Timing
.m
[i
].write_3
/ 8);
284 DbpStringEx(FLAG_LOG
, s
, sizeof(s
));
289 void setT55xxConfig(uint8_t arg0
, const t55xx_configurations_t
*c
) {
290 for (uint8_t i
= 0; i
< 4; i
++) {
291 if (c
->m
[i
].start_gap
!= 0)
292 T55xx_Timing
.m
[i
].start_gap
= c
->m
[i
].start_gap
;
294 if (c
->m
[i
].write_gap
!= 0)
295 T55xx_Timing
.m
[i
].write_gap
= c
->m
[i
].write_gap
;
297 if (c
->m
[i
].write_0
!= 0)
298 T55xx_Timing
.m
[i
].write_0
= c
->m
[i
].write_0
;
300 if (c
->m
[i
].write_1
!= 0)
301 T55xx_Timing
.m
[i
].write_1
= c
->m
[i
].write_1
;
303 if (i
== T55XX_DLMODE_1OF4
) {
304 if (c
->m
[i
].write_2
!= 0)
305 T55xx_Timing
.m
[i
].write_2
= c
->m
[i
].write_2
;
307 if (c
->m
[i
].write_3
!= 0)
308 T55xx_Timing
.m
[i
].write_3
= c
->m
[i
].write_3
;
311 T55xx_Timing
.m
[i
].write_2
= 0x00;
312 T55xx_Timing
.m
[i
].write_3
= 0x00;
314 if (c
->m
[i
].read_gap
!= 0)
315 T55xx_Timing
.m
[i
].read_gap
= c
->m
[i
].read_gap
;
321 // shall persist to flashmem
332 uint8_t *buf
= BigBuf_malloc(T55XX_CONFIG_LEN
);
333 Flash_CheckBusy(BUSY_TIMEOUT
);
334 uint16_t res
= Flash_ReadDataCont(T55XX_CONFIG_OFFSET
, buf
, T55XX_CONFIG_LEN
);
341 memcpy(buf
, &T55xx_Timing
, T55XX_CONFIG_LEN
);
343 // delete old configuration
344 Flash_CheckBusy(BUSY_TIMEOUT
);
346 Flash_Erase4k(3, 0xD);
349 res
= Flash_Write(T55XX_CONFIG_OFFSET
, buf
, T55XX_CONFIG_LEN
);
351 if (res
== T55XX_CONFIG_LEN
&& g_dbglevel
> 1) {
352 DbpString("T55XX Config save " _GREEN_("success"));
359 t55xx_configurations_t
*getT55xxConfig(void) {
360 return &T55xx_Timing
;//_FixedBit;
363 void loadT55xxConfig(void) {
370 uint8_t *buf
= BigBuf_malloc(T55XX_CONFIG_LEN
);
372 Flash_CheckBusy(BUSY_TIMEOUT
);
373 uint16_t isok
= Flash_ReadDataCont(T55XX_CONFIG_OFFSET
, buf
, T55XX_CONFIG_LEN
);
376 // verify read mem is actual data.
377 uint8_t cntA
= T55XX_CONFIG_LEN
, cntB
= T55XX_CONFIG_LEN
;
378 for (int i
= 0; i
< T55XX_CONFIG_LEN
; i
++) {
379 if (buf
[i
] == 0xFF) cntA
--;
380 if (buf
[i
] == 0x00) cntB
--;
382 if (!cntA
|| !cntB
) {
387 if (buf
[0] != 0xFF) // if not set for clear
388 memcpy((uint8_t *)&T55xx_Timing
, buf
, T55XX_CONFIG_LEN
);
390 if (isok
== T55XX_CONFIG_LEN
) {
391 if (g_dbglevel
> 1) DbpString("T55XX Config load success");
398 static bool prev_keep
= false;
401 * Function to do a modulation and then get samples.
405 * @param command (in binary char array)
407 void ModThenAcquireRawAdcSamples125k(uint32_t delay_off
, uint16_t period_0
, uint16_t period_1
,
408 const uint8_t *symbol_extra
, uint16_t *period_extra
, uint8_t *command
,
409 bool verbose
, bool keep_field_on
, uint32_t samples
, bool ledcontrol
) {
412 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
414 // use lf config settings
415 sample_config
*sc
= getSamplingConfig();
416 LFSetupFPGAForADC(sc
->divisor
, true);
417 // this causes the field to turn on for uncontrolled amount of time, so we'll turn it off
421 // Make sure the tag is reset
422 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
433 BigBuf_Clear_keep_EM();
435 // if delay_off = 0 then just bitbang 1 = antenna on 0 = off for respective periods.
436 bool bitbang
= (delay_off
== 0);
437 // now modulate the reader field
439 // Some tags need to be interrogated very soon after activation else they enter their emulation mode
440 // Therefore it's up to the caller to add an initial symbol of adequate duration, except for bitbang mode.
442 turn_read_lf_on(20000);
443 // HACK it appears the loop and if statements take up about 7us so adjust waits accordingly...
444 uint8_t hack_cnt
= 7;
445 if (period_0
< hack_cnt
|| period_1
< hack_cnt
) {
446 DbpString("[!] Warning periods cannot be less than 7us in bit bang mode");
447 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
448 if (ledcontrol
) LED_D_OFF();
449 reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC
, PM3_EINVARG
, NULL
, 0);
453 // hack2 needed--- it appears to take about 8-16us to turn the antenna back on
454 // leading to ~ 1 to 2 125kHz samples extra in every off period
455 // so we should test for last 0 before next 1 and reduce period_0 by this extra amount...
456 // but is this time different for every antenna or other hw builds??? more testing needed
458 // prime cmd_len to save time comparing strings while modulating
460 while (command
[cmd_len
] != '\0' && command
[cmd_len
] != ' ')
465 for (counter
= 0; counter
< cmd_len
; counter
++) {
466 // if cmd = 0 then turn field off
467 if (command
[counter
] == '0') {
468 // if field already off leave alone (affects timing otherwise)
470 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
471 if (ledcontrol
) LED_D_OFF();
474 // note we appear to take about 7us to switch over (or run the if statements/loop...)
475 WaitUS(period_0
- hack_cnt
);
476 // else if cmd = 1 then turn field on
478 // if field already on leave alone (affects timing otherwise)
480 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER
| FPGA_LF_ADC_READER_FIELD
);
481 if (ledcontrol
) LED_D_ON();
484 // note we appear to take about 7us to switch over (or run the if statements/loop...)
485 WaitUS(period_1
- hack_cnt
);
488 } else { // old mode of cmd read using delay as off period
489 while (*command
!= '\0' && *command
!= ' ') {
490 if (ledcontrol
) LED_D_ON();
491 if (*command
== '0') {
492 turn_read_lf_on(period_0
);
493 } else if (*command
== '1') {
494 turn_read_lf_on(period_1
);
496 for (uint8_t i
= 0; i
< LF_CMDREAD_MAX_EXTRA_SYMBOLS
; i
++) {
497 if (*command
== symbol_extra
[i
]) {
498 turn_read_lf_on(period_extra
[i
]);
504 if (ledcontrol
) LED_D_OFF();
505 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
509 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, sc
->divisor
);
512 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER
| FPGA_LF_ADC_READER_FIELD
);
515 DoAcquisition_config(verbose
, samples
, ledcontrol
);
518 if (!keep_field_on
) {
519 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
521 prev_keep
= keep_field_on
;
522 // tell client we are done
523 reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC
, PM3_SUCCESS
, NULL
, 0);
526 /* blank r/w tag data stream
527 ...0000000000000000 01111111
528 1010101010101010101010101010101010101010101010101010101010101010
531 101010101010101[0]000...
533 [5555fe852c5555555555555555fe0000]
535 void ReadTItag(bool ledcontrol
) {
537 // some hardcoded initial params
538 // when we read a TI tag we sample the zerocross line at 2MHz
539 // TI tags modulate a 1 as 16 cycles of 123.2kHz
540 // TI tags modulate a 0 as 16 cycles of 134.2kHz
541 #define FSAMPLE 2000000
542 #define FREQLO 123200
543 #define FREQHI 134200
545 signed char *dest
= (signed char *)BigBuf_get_addr();
546 uint16_t n
= BigBuf_max_traceLen();
547 // 128 bit shift register [shift3:shift2:shift1:shift0]
548 uint32_t shift3
= 0, shift2
= 0, shift1
= 0, shift0
= 0;
550 int i
, cycles
= 0, samples
= 0;
551 // how many sample points fit in 16 cycles of each frequency
552 uint32_t sampleslo
= (FSAMPLE
<< 4) / FREQLO
, sampleshi
= (FSAMPLE
<< 4) / FREQHI
;
553 // when to tell if we're close enough to one freq or another
554 uint32_t threshold
= (sampleslo
- sampleshi
+ 1) >> 1;
556 // TI tags charge at 134.2kHz
557 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
558 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, LF_DIVISOR_134
); //~134kHz
560 // Place FPGA in passthrough mode, in this mode the CROSS_LO line
561 // connects to SSP_DIN and the SSP_DOUT logic level controls
562 // whether we're modulating the antenna (high)
563 // or listening to the antenna (low)
564 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU
);
566 // get TI tag data into the buffer
567 AcquireTiType(ledcontrol
);
569 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
571 for (i
= 0; i
< n
- 1; i
++) {
572 // count cycles by looking for lo to hi zero crossings
573 if ((dest
[i
] < 0) && (dest
[i
+ 1] > 0)) {
575 // after 16 cycles, measure the frequency
578 samples
= i
- samples
; // number of samples in these 16 cycles
580 // TI bits are coming to us lsb first so shift them
581 // right through our 128 bit right shift register
582 shift0
= (shift0
>> 1) | (shift1
<< 31);
583 shift1
= (shift1
>> 1) | (shift2
<< 31);
584 shift2
= (shift2
>> 1) | (shift3
<< 31);
587 // check if the cycles fall close to the number
588 // expected for either the low or high frequency
589 if ((samples
> (sampleslo
- threshold
)) && (samples
< (sampleslo
+ threshold
))) {
590 // low frequency represents a 1
591 shift3
|= (1u << 31);
592 } else if ((samples
> (sampleshi
- threshold
)) && (samples
< (sampleshi
+ threshold
))) {
593 // high frequency represents a 0
595 // probably detected a gay waveform or noise
596 // use this as gaydar or discard shift register and start again
597 shift3
= shift2
= shift1
= shift0
= 0;
601 // for each bit we receive, test if we've detected a valid tag
603 // if we see 17 zeroes followed by 6 ones, we might have a tag
604 // remember the bits are backwards
605 if (((shift0
& 0x7fffff) == 0x7e0000)) {
606 // if start and end bytes match, we have a tag so break out of the loop
607 if (((shift0
>> 16) & 0xff) == ((shift3
>> 8) & 0xff)) {
608 cycles
= 0xF0B; //use this as a flag (ugly but whatever)
616 // if flag is set we have a tag
617 if (cycles
!= 0xF0B) {
618 DbpString("Info: No valid tag detected.");
620 // put 64 bit data into shift1 and shift0
621 shift0
= (shift0
>> 24) | (shift1
<< 8);
622 shift1
= (shift1
>> 24) | (shift2
<< 8);
624 // align 16 bit crc into lower half of shift2
625 shift2
= ((shift2
>> 24) | (shift3
<< 8)) & 0x0ffff;
627 // if r/w tag, check ident match
628 if (shift3
& (1 << 15)) {
629 DbpString("Info: TI tag is rewriteable");
630 // only 15 bits compare, last bit of ident is not valid
631 if (((shift3
>> 16) ^ shift0
) & 0x7fff) {
632 DbpString("Error: Ident mismatch!");
634 DbpString("Info: TI tag ident is valid");
637 DbpString("Info: TI tag is readonly");
640 // WARNING the order of the bytes in which we calc crc below needs checking
641 // i'm 99% sure the crc algorithm is correct, but it may need to eat the
642 // bytes in reverse or something
646 crc
= update_crc16(crc
, (shift0
) & 0xff);
647 crc
= update_crc16(crc
, (shift0
>> 8) & 0xff);
648 crc
= update_crc16(crc
, (shift0
>> 16) & 0xff);
649 crc
= update_crc16(crc
, (shift0
>> 24) & 0xff);
650 crc
= update_crc16(crc
, (shift1
) & 0xff);
651 crc
= update_crc16(crc
, (shift1
>> 8) & 0xff);
652 crc
= update_crc16(crc
, (shift1
>> 16) & 0xff);
653 crc
= update_crc16(crc
, (shift1
>> 24) & 0xff);
655 Dbprintf("Info: Tag data: %x%08x, crc=%x", (unsigned int)shift1
, (unsigned int)shift0
, (unsigned int)shift2
& 0xFFFF);
656 if (crc
!= (shift2
& 0xffff)) {
657 Dbprintf("Error: CRC mismatch, expected %x", (unsigned int)crc
);
659 DbpString("Info: CRC is good");
665 static void WriteTIbyte(uint8_t b
) {
668 // modulate 8 bits out to the antenna
669 for (i
= 0; i
< 8; i
++) {
671 // stop modulating antenna 1ms
674 // modulate antenna 1ms
678 // stop modulating antenna 0.3ms
681 // modulate antenna 1.7ms
688 void AcquireTiType(bool ledcontrol
) {
690 // tag transmission is <20ms, sampling at 2M gives us 40K samples max
691 // each sample is 1 bit stuffed into a uint32_t so we need 1250 uint32_t
692 #define TIBUFLEN 1250
695 uint32_t *buf
= (uint32_t *)BigBuf_get_addr();
697 //clear buffer now so it does not interfere with timing later
698 BigBuf_Clear_ext(false);
700 // Set up the synchronous serial port
701 AT91C_BASE_PIOA
->PIO_PDR
= GPIO_SSC_DIN
;
702 AT91C_BASE_PIOA
->PIO_ASR
= GPIO_SSC_DIN
;
704 // steal this pin from the SSP and use it to control the modulation
705 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
706 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
708 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_SWRST
;
709 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_RXEN
| AT91C_SSC_TXEN
;
711 // Sample at 2 Mbit/s, so TI tags are 16.2 vs. 14.9 clocks long
712 // 48/2 = 24 MHz clock must be divided by 12
713 AT91C_BASE_SSC
->SSC_CMR
= 12;
715 AT91C_BASE_SSC
->SSC_RCMR
= SSC_CLOCK_MODE_SELECT(0);
716 AT91C_BASE_SSC
->SSC_RFMR
= SSC_FRAME_MODE_BITS_IN_WORD(32) | AT91C_SSC_MSBF
;
717 // Transmit Clock Mode Register
718 AT91C_BASE_SSC
->SSC_TCMR
= 0;
719 // Transmit Frame Mode Register
720 AT91C_BASE_SSC
->SSC_TFMR
= 0;
721 // iceman, FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER) ?? the code above? can it be replaced?
722 if (ledcontrol
) LED_D_ON();
727 // Charge TI tag for 50ms.
730 // stop modulating antenna and listen
733 if (ledcontrol
) LED_D_OFF();
737 if (AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
) {
738 buf
[i
] = AT91C_BASE_SSC
->SSC_RHR
; // store 32 bit values in buffer
740 if (i
>= TIBUFLEN
) break;
745 // return stolen pin to SSP
746 AT91C_BASE_PIOA
->PIO_PDR
= GPIO_SSC_DOUT
;
747 AT91C_BASE_PIOA
->PIO_ASR
= GPIO_SSC_DIN
| GPIO_SSC_DOUT
;
749 char *dest
= (char *)BigBuf_get_addr();
753 for (i
= TIBUFLEN
- 1; i
>= 0; i
--) {
754 for (j
= 0; j
< 32; j
++) {
755 if (buf
[i
] & (1u << j
)) {
764 FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER
);
767 // arguments: 64bit data split into 32bit idhi:idlo and optional 16bit crc
768 // if crc provided, it will be written with the data verbatim (even if bogus)
769 // if not provided a valid crc will be computed from the data and written.
770 void WriteTItag(uint32_t idhi
, uint32_t idlo
, uint16_t crc
, bool ledcontrol
) {
771 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
773 crc
= update_crc16(crc
, (idlo
) & 0xff);
774 crc
= update_crc16(crc
, (idlo
>> 8) & 0xff);
775 crc
= update_crc16(crc
, (idlo
>> 16) & 0xff);
776 crc
= update_crc16(crc
, (idlo
>> 24) & 0xff);
777 crc
= update_crc16(crc
, (idhi
) & 0xff);
778 crc
= update_crc16(crc
, (idhi
>> 8) & 0xff);
779 crc
= update_crc16(crc
, (idhi
>> 16) & 0xff);
780 crc
= update_crc16(crc
, (idhi
>> 24) & 0xff);
782 Dbprintf("Writing to tag: %x%08x, crc=%x", idhi
, idlo
, crc
);
784 // TI tags charge at 134.2kHz
785 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, LF_DIVISOR_134
); //~134kHz
786 // Place FPGA in passthrough mode, in this mode the CROSS_LO line
787 // connects to SSP_DIN and the SSP_DOUT logic level controls
788 // whether we're modulating the antenna (high)
789 // or listening to the antenna (low)
790 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU
);
793 if (ledcontrol
) LED_A_ON();
795 // steal this pin from the SSP and use it to control the modulation
796 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
;
797 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
799 // writing algorithm:
800 // a high bit consists of a field off for 1ms and field on for 1ms
801 // a low bit consists of a field off for 0.3ms and field on for 1.7ms
802 // initiate a charge time of 50ms (field on) then immediately start writing bits
803 // start by writing 0xBB (keyword) and 0xEB (password)
804 // then write 80 bits of data (or 64 bit data + 16 bit crc if you prefer)
805 // finally end with 0x0300 (write frame)
806 // all data is sent lsb first
807 // finish with 50ms programming time
811 WaitMS(50); // charge time
813 WriteTIbyte(0xbb); // keyword
814 WriteTIbyte(0xeb); // password
815 WriteTIbyte((idlo
) & 0xff);
816 WriteTIbyte((idlo
>> 8) & 0xff);
817 WriteTIbyte((idlo
>> 16) & 0xff);
818 WriteTIbyte((idlo
>> 24) & 0xff);
819 WriteTIbyte((idhi
) & 0xff);
820 WriteTIbyte((idhi
>> 8) & 0xff);
821 WriteTIbyte((idhi
>> 16) & 0xff);
822 WriteTIbyte((idhi
>> 24) & 0xff); // data hi to lo
823 WriteTIbyte((crc
) & 0xff); // crc lo
824 WriteTIbyte((crc
>> 8) & 0xff); // crc hi
825 WriteTIbyte(0x00); // write frame lo
826 WriteTIbyte(0x03); // write frame hi
828 WaitMS(50); // programming time
830 if (ledcontrol
) LED_A_OFF();
832 // get TI tag data into the buffer
833 AcquireTiType(ledcontrol
);
835 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
836 DbpString("Now use `lf ti reader` to check");
840 // note: a call to FpgaDownloadAndGo(FPGA_BITSTREAM_LF) must be done before, but
841 // this may destroy the bigbuf so be sure this is called before calling SimulateTagLowFrequencyEx
842 void SimulateTagLowFrequencyEx(int period
, int gap
, bool ledcontrol
, int numcycles
) {
847 //FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE );
848 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT
);
852 uint8_t *buf
= BigBuf_get_addr();
854 // set frequency, get values from 'lf config' command
855 sample_config
*sc
= getSamplingConfig();
857 if ((sc
->divisor
== 1) || (sc
->divisor
< 0) || (sc
->divisor
> 255))
858 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, LF_DIVISOR_134
); //~134kHz
859 else if (sc
->divisor
== 0)
860 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, LF_DIVISOR_125
); //125kHz
862 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, sc
->divisor
);
864 AT91C_BASE_PIOA
->PIO_PER
= GPIO_SSC_DOUT
| GPIO_SSC_CLK
;
865 AT91C_BASE_PIOA
->PIO_OER
= GPIO_SSC_DOUT
;
866 AT91C_BASE_PIOA
->PIO_ODR
= GPIO_SSC_CLK
;
872 if (numcycles
> -1) {
873 if (x
!= numcycles
) {
876 // exit without turning off field
881 if (ledcontrol
) LED_D_ON();
883 // wait until SSC_CLK goes HIGH
884 // used as a simple detection of a reader field?
885 while (!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_CLK
)) {
888 if (data_available() || BUTTON_PRESS())
895 if (ledcontrol
) LED_D_OFF();
904 //wait until SSC_CLK goes LOW
905 while (AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_SSC_CLK
) {
908 if (BUTTON_PRESS() || data_available())
926 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
927 if (ledcontrol
) LED_D_OFF();
930 void SimulateTagLowFrequency(int period
, int gap
, bool ledcontrol
) {
931 SimulateTagLowFrequencyEx(period
, gap
, ledcontrol
, -1);
935 #define DEBUG_FRAME_CONTENTS 1
936 void SimulateTagLowFrequencyBidir(int divisor
, int max_bitlen
) {
939 // compose fc/X fc/Y waveform (FSKx)
940 static void fcAll(uint8_t fc
, int *n
, uint8_t clock
, int16_t *remainder
) {
941 uint8_t *dest
= BigBuf_get_addr();
942 uint8_t halfFC
= fc
>> 1;
943 uint8_t wavesPerClock
= (clock
+ *remainder
) / fc
;
944 // loop through clock - step field clock
945 for (uint8_t idx
= 0; idx
< wavesPerClock
; idx
++) {
946 // put 1/2 FC length 1's and 1/2 0's per field clock wave (to create the wave)
947 memset(dest
+ (*n
), 0, fc
- halfFC
); //in case of odd number use extra here
948 memset(dest
+ (*n
) + (fc
- halfFC
), 1, halfFC
);
951 *remainder
= (clock
+ *remainder
) % fc
;
952 // if we've room for more than a half wave, add a full wave and use negative remainder
953 if (*remainder
> halfFC
) {
954 memset(dest
+ (*n
), 0, fc
- halfFC
); //in case of odd number use extra here
955 memset(dest
+ (*n
) + (fc
- halfFC
), 1, halfFC
);
961 // prepare a waveform pattern in the buffer based on the ID given then
962 // simulate a HID tag until the button is pressed
963 void CmdHIDsimTAGEx(uint32_t hi2
, uint32_t hi
, uint32_t lo
, uint8_t longFMT
, bool ledcontrol
, int numcycles
) {
966 HID tag bitstream format
967 The tag contains a 44bit unique code. This is sent out MSB first in sets of 4 bits
968 A 1 bit is represented as 6 fc8 and 5 fc10 patterns (manchester 10) during 2 clock periods. (1bit = 1clock period)
969 A 0 bit is represented as 5 fc10 and 6 fc8 patterns (manchester 01)
970 A fc8 is inserted before every 4 bits
971 A special start of frame pattern is used consisting a0b0 where a and b are neither 0
972 nor 1 bits, they are special patterns (a = set of 12 fc8 and b = set of 10 fc10)
979 // special start of frame marker containing invalid Manchester bit sequences
980 uint8_t bits
[8 + 8 * 2 + 84 * 2] = { 0, 0, 0, 1, 1, 1, 0, 1 };
985 // Ensure no more than 84 bits supplied
987 DbpString("Tags can only have 84 bits.");
990 bitlen
= 8 + 8 * 2 + 84 * 2;
991 hi2
|= 0x9E00000; // 9E: long format identifier
992 manchesterEncodeUint32(hi2
, 16 + 12, bits
, &n
);
993 manchesterEncodeUint32(hi
, 32, bits
, &n
);
994 manchesterEncodeUint32(lo
, 32, bits
, &n
);
998 DbpString("[!] tags can only have 44 bits. - USE lf simfsk for larger tags");
1001 bitlen
= 8 + 44 * 2;
1002 manchesterEncodeUint32(hi
, 12, bits
, &n
);
1003 manchesterEncodeUint32(lo
, 32, bits
, &n
);
1005 CmdFSKsimTAGEx(10, 8, 0, 50, bitlen
, bits
, ledcontrol
, numcycles
);
1008 void CmdHIDsimTAG(uint32_t hi2
, uint32_t hi
, uint32_t lo
, uint8_t longFMT
, bool ledcontrol
) {
1009 CmdHIDsimTAGEx(hi2
, hi
, lo
, longFMT
, ledcontrol
, -1);
1010 reply_ng(CMD_LF_HID_SIMULATE
, PM3_EOPABORTED
, NULL
, 0);
1013 // prepare a waveform pattern in the buffer based on the ID given then
1014 // simulate a FSK tag until the button is pressed
1015 // arg1 contains fcHigh and fcLow, arg2 contains STT marker and clock
1016 void CmdFSKsimTAGEx(uint8_t fchigh
, uint8_t fclow
, uint8_t separator
, uint8_t clk
, uint16_t bitslen
, const uint8_t *bits
, bool ledcontrol
, int numcycles
) {
1018 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1020 // free eventually allocated BigBuf memory
1022 BigBuf_Clear_ext(false);
1027 int16_t remainder
= 0;
1030 //int fsktype = ( fchigh == 8 && fclow == 5) ? 1 : 2;
1033 for (i
= 0; i
< bitslen
; i
++) {
1035 fcAll(fchigh
, &n
, clk
, &remainder
);
1037 fcAll(fclow
, &n
, clk
, &remainder
);
1042 Dbprintf("FSK simulating with rf/%d, fc high %d, fc low %d, STT %d, n %d", clk
, fchigh
, fclow
, separator
, n
);
1044 if (ledcontrol
) LED_A_ON();
1045 SimulateTagLowFrequencyEx(n
, 0, ledcontrol
, numcycles
);
1046 if (ledcontrol
) LED_A_OFF();
1049 // prepare a waveform pattern in the buffer based on the ID given then
1050 // simulate a FSK tag until the button is pressed
1051 // arg1 contains fcHigh and fcLow, arg2 contains STT marker and clock
1052 void CmdFSKsimTAG(uint8_t fchigh
, uint8_t fclow
, uint8_t separator
, uint8_t clk
, uint16_t bitslen
, const uint8_t *bits
, bool ledcontrol
) {
1053 CmdFSKsimTAGEx(fchigh
, fclow
, separator
, clk
, bitslen
, bits
, ledcontrol
, -1);
1054 reply_ng(CMD_LF_FSK_SIMULATE
, PM3_EOPABORTED
, NULL
, 0);
1057 // compose ask waveform for one bit(ASK)
1058 static void askSimBit(uint8_t c
, int *n
, uint8_t clock
, uint8_t manchester
) {
1059 uint8_t *dest
= BigBuf_get_addr();
1060 uint8_t halfClk
= clock
/ 2;
1061 // c = current bit 1 or 0
1062 if (manchester
== 1) {
1063 memset(dest
+ (*n
), c
, halfClk
);
1064 memset(dest
+ (*n
) + halfClk
, c
^ 1, halfClk
);
1066 memset(dest
+ (*n
), c
, clock
);
1071 static void biphaseSimBit(uint8_t c
, int *n
, uint8_t clock
, uint8_t *phase
) {
1072 uint8_t *dest
= BigBuf_get_addr();
1073 uint8_t halfClk
= clock
/ 2;
1075 memset(dest
+ (*n
), c
^ 1 ^ *phase
, halfClk
);
1076 memset(dest
+ (*n
) + halfClk
, c
^ *phase
, halfClk
);
1078 memset(dest
+ (*n
), c
^ *phase
, clock
);
1084 static void stAskSimBit(int *n
, uint8_t clock
) {
1085 uint8_t *dest
= BigBuf_get_addr();
1086 uint8_t halfClk
= clock
/ 2;
1087 //ST = .5 high .5 low 1.5 high .5 low 1 high
1088 memset(dest
+ (*n
), 1, halfClk
);
1089 memset(dest
+ (*n
) + halfClk
, 0, halfClk
);
1090 memset(dest
+ (*n
) + clock
, 1, clock
+ halfClk
);
1091 memset(dest
+ (*n
) + clock
* 2 + halfClk
, 0, halfClk
);
1092 memset(dest
+ (*n
) + clock
* 3, 1, clock
);
1095 static void leadingZeroAskSimBits(int *n
, uint8_t clock
) {
1096 uint8_t *dest
= BigBuf_get_addr();
1097 memset(dest
+ (*n
), 0, clock
* 8);
1101 static void leadingZeroBiphaseSimBits(int *n, uint8_t clock, uint8_t *phase) {
1102 uint8_t *dest = BigBuf_get_addr();
1103 for (uint8_t i = 0; i < 8; i++) {
1104 memset(dest + (*n), 0 ^ *phase, clock);
1112 // args clock, ask/man or askraw, invert, transmission separator
1113 void CmdASKsimTAG(uint8_t encoding
, uint8_t invert
, uint8_t separator
, uint8_t clk
,
1114 uint16_t size
, const uint8_t *bits
, bool ledcontrol
) {
1115 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1120 if (encoding
== 2) { //biphase
1123 // iceman, if I add this, the demod includes these extra zero and detection fails.
1124 // now, I only need to figure out just to add carrier without modulation
1125 // the old bug, with adding ask zeros messed up the phase variable and deteion failed because of it in LF FDX
1126 // leadingZeroBiphaseSimBits(&n, clk, &phase);
1128 for (i
= 0; i
< size
; i
++) {
1129 biphaseSimBit(bits
[i
] ^ invert
, &n
, clk
, &phase
);
1131 if (phase
== 1) { //run a second set inverted to keep phase in check
1132 for (i
= 0; i
< size
; i
++) {
1133 biphaseSimBit(bits
[i
] ^ invert
, &n
, clk
, &phase
);
1136 } else { // ask/manchester || ask/raw
1138 leadingZeroAskSimBits(&n
, clk
);
1140 for (i
= 0; i
< size
; i
++) {
1141 askSimBit(bits
[i
] ^ invert
, &n
, clk
, encoding
);
1143 if (encoding
== 0 && bits
[0] == bits
[size
- 1]) { //run a second set inverted (for ask/raw || biphase phase)
1144 for (i
= 0; i
< size
; i
++) {
1145 askSimBit(bits
[i
] ^ invert
^ 1, &n
, clk
, encoding
);
1149 if (separator
== 1 && encoding
== 1)
1150 stAskSimBit(&n
, clk
);
1151 else if (separator
== 1)
1152 Dbprintf("sorry but separator option not yet available");
1156 Dbprintf("ASK simulating with rf/%d, invert %d, encoding %s (%d), separator %d, n %d"
1159 , (encoding
== 2) ? "ASK/BI" : (encoding
== 1) ? "ASK/MAN" : "RAW/MAN"
1165 if (ledcontrol
) LED_A_ON();
1166 SimulateTagLowFrequency(n
, 0, ledcontrol
);
1167 if (ledcontrol
) LED_A_OFF();
1168 reply_ng(CMD_LF_ASK_SIMULATE
, PM3_EOPABORTED
, NULL
, 0);
1171 //carrier can be 2,4 or 8
1172 static void pskSimBit(uint8_t waveLen
, int *n
, uint8_t clk
, uint8_t *curPhase
, bool phaseChg
) {
1173 uint8_t *dest
= BigBuf_get_addr();
1174 uint8_t halfWave
= waveLen
/ 2;
1178 // write phase change
1179 memset(dest
+ (*n
), *curPhase
^ 1, halfWave
);
1180 memset(dest
+ (*n
) + halfWave
, *curPhase
, halfWave
);
1185 //write each normal clock wave for the clock duration
1186 for (; i
< clk
; i
+= waveLen
) {
1187 memset(dest
+ (*n
), *curPhase
, halfWave
);
1188 memset(dest
+ (*n
) + halfWave
, *curPhase
^ 1, halfWave
);
1193 // args clock, carrier, invert,
1194 void CmdPSKsimTAG(uint8_t carrier
, uint8_t invert
, uint8_t clk
, uint16_t size
,
1195 const uint8_t *bits
, bool ledcontrol
) {
1196 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1200 uint8_t curPhase
= 0;
1201 for (i
= 0; i
< size
; i
++) {
1202 if (bits
[i
] == curPhase
) {
1203 pskSimBit(carrier
, &n
, clk
, &curPhase
, false);
1205 pskSimBit(carrier
, &n
, clk
, &curPhase
, true);
1211 Dbprintf("PSK simulating with rf/%d, fc/%d, invert %d, n %d", clk
, carrier
, invert
, n
);
1213 if (ledcontrol
) LED_A_ON();
1214 SimulateTagLowFrequency(n
, 0, ledcontrol
);
1215 if (ledcontrol
) LED_A_OFF();
1216 reply_ng(CMD_LF_PSK_SIMULATE
, PM3_EOPABORTED
, NULL
, 0);
1219 // compose nrz waveform for one bit(NRZ)
1220 static void nrzSimBit(uint8_t c
, int *n
, uint8_t clock
) {
1221 uint8_t *dest
= BigBuf_get_addr();
1222 // uint8_t halfClk = clock / 2;
1223 // c = current bit 1 or 0
1224 memset(dest
+ (*n
), c
, clock
);
1229 void CmdNRZsimTAG(uint8_t invert
, uint8_t separator
, uint8_t clk
, uint16_t size
,
1230 const uint8_t *bits
, bool ledcontrol
) {
1232 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
);
1239 leadingZeroAskSimBits(&n
, clk
);
1241 for (i
= 0; i
< size
; i
++) {
1242 nrzSimBit(bits
[i
] ^ invert
, &n
, clk
);
1245 if (bits
[0] == bits
[size
- 1]) {
1246 for (i
= 0; i
< size
; i
++) {
1247 nrzSimBit(bits
[i
] ^ invert
^ 1, &n
, clk
);
1252 Dbprintf("sorry but separator option not yet available");
1256 Dbprintf("NRZ simulating with rf/%d, invert %d, separator %d, n %d"
1263 if (ledcontrol
) LED_A_ON();
1264 SimulateTagLowFrequency(n
, 0, ledcontrol
);
1265 if (ledcontrol
) LED_A_OFF();
1266 reply_ng(CMD_LF_NRZ_SIMULATE
, PM3_EOPABORTED
, NULL
, 0);
1269 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
1270 int lf_hid_watch(int findone
, uint32_t *high
, uint32_t *low
, bool ledcontrol
) {
1273 uint32_t hi2
= 0, hi
= 0, lo
= 0;
1275 // Configure to go in 125kHz listen mode
1276 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
1278 uint8_t *dest
= BigBuf_get_addr();
1279 BigBuf_Clear_keep_EM();
1284 BigBuf_Clear_keep_EM();
1286 int res
= PM3_SUCCESS
;
1291 if (data_available() || BUTTON_PRESS()) {
1292 res
= PM3_EOPABORTED
;
1296 DoAcquisition_default(-1, false, ledcontrol
);
1299 // 50 * 128 * 2 - big enough to catch 2 sequences of largest format
1300 size
= MIN(12800, BigBuf_max_traceLen());
1302 int idx
= HIDdemodFSK(dest
, &size
, &hi2
, &hi
, &lo
, &dummyIdx
);
1303 if (idx
< 0) continue;
1305 if (idx
> 0 && lo
> 0 && (size
== 96 || size
== 192)) {
1306 // go over previously decoded manchester data and decode into usable tag ID
1307 if (hi2
!= 0) { //extra large HID tags 88/192 bits
1308 Dbprintf("TAG ID: " _GREEN_("%x%08x%08x") " (%d)",
1314 } else { //standard HID tags 44/96 bits
1317 uint32_t cardnum
= 0;
1319 if (((hi
>> 5) & 1) == 1) { //if bit 38 is set then < 37 bit format is used
1321 lo2
= (((hi
& 31) << 12) | (lo
>> 20)); //get bits 21-37 to check for format len bit
1323 while (lo2
> 1) { //find last bit set to 1 (format len bit)
1331 cardnum
= (lo
>> 1) & 0xFFFF;
1332 fac
= (lo
>> 17) & 0xFF;
1335 cardnum
= (lo
>> 1) & 0x7FFFF;
1336 fac
= ((hi
& 0xF) << 12) | (lo
>> 20);
1339 cardnum
= (lo
>> 1) & 0xFFFF;
1340 fac
= ((hi
& 1) << 15) | (lo
>> 17);
1343 cardnum
= (lo
>> 1) & 0xFFFFF;
1344 fac
= ((hi
& 1) << 11) | (lo
>> 21);
1346 } else { //if bit 38 is not set then 37 bit format is used
1348 cardnum
= (lo
>> 1) & 0x7FFFF;
1349 fac
= ((hi
& 0xF) << 12) | (lo
>> 20);
1351 Dbprintf("TAG ID: " _GREEN_("%x%08x (%d)") " - Format Len: " _GREEN_("%d") " bit - FC: " _GREEN_("%d") " - Card: "_GREEN_("%d"),
1367 hi2
= hi
= lo
= idx
= 0;
1369 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1371 if (ledcontrol
) LEDsoff();
1375 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
1376 int lf_awid_watch(int findone
, uint32_t *high
, uint32_t *low
, bool ledcontrol
) {
1381 uint8_t *dest
= BigBuf_get_addr();
1382 BigBuf_Clear_keep_EM();
1386 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
1388 int res
= PM3_SUCCESS
;
1393 if (data_available() || BUTTON_PRESS()) {
1394 res
= PM3_EOPABORTED
;
1398 DoAcquisition_default(-1, false, ledcontrol
);
1401 size
= MIN(12800, BigBuf_max_traceLen());
1403 //askdemod and manchester decode
1404 int idx
= detectAWID(dest
, &size
, &dummyIdx
);
1406 if (idx
<= 0 || size
!= 96) continue;
1408 // 0 10 20 30 40 50 60
1410 // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96
1411 // -----------------------------------------------------------------------------
1412 // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1
1413 // premable bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96
1414 // |---26 bit---| |-----117----||-------------142-------------|
1415 // b = format bit len, o = odd parity of last 3 bits
1416 // f = facility code, c = card number
1417 // w = wiegand parity
1418 // (26 bit format shown)
1420 //get raw ID before removing parities
1421 uint32_t rawLo
= bytebits_to_byte(dest
+ idx
+ 64, 32);
1422 uint32_t rawHi
= bytebits_to_byte(dest
+ idx
+ 32, 32);
1423 uint32_t rawHi2
= bytebits_to_byte(dest
+ idx
, 32);
1425 size
= removeParity(dest
, idx
+ 8, 4, 1, 88);
1426 if (size
!= 66) continue;
1427 // ok valid card found!
1430 // 0 10 20 30 40 50 60
1432 // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456
1433 // -----------------------------------------------------------------------------
1434 // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000
1435 // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
1436 // |26 bit| |-117--| |-----142------|
1437 // b = format bit len, o = odd parity of last 3 bits
1438 // f = facility code, c = card number
1439 // w = wiegand parity
1440 // (26 bit format shown)
1442 uint8_t fmtLen
= bytebits_to_byte(dest
, 8);
1444 uint32_t fac
= bytebits_to_byte(dest
+ 9, 8);
1445 uint32_t cardnum
= bytebits_to_byte(dest
+ 17, 16);
1446 uint32_t code1
= bytebits_to_byte(dest
+ 8, fmtLen
);
1447 Dbprintf("AWID Found - Bit length: " _GREEN_("%d") ", FC: " _GREEN_("%d") ", Card: " _GREEN_("%d") " - Wiegand: %x, Raw: %08x%08x%08x", fmtLen
, fac
, cardnum
, code1
, rawHi2
, rawHi
, rawLo
);
1449 uint32_t cardnum
= bytebits_to_byte(dest
+ 8 + (fmtLen
- 17), 16);
1451 uint32_t code1
= bytebits_to_byte(dest
+ 8, fmtLen
- 32);
1452 uint32_t code2
= bytebits_to_byte(dest
+ 8 + (fmtLen
- 32), 32);
1453 Dbprintf("AWID Found - Bit length: " _GREEN_("%d") " -unknown bit length- (%d) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen
, cardnum
, code1
, code2
, rawHi2
, rawHi
, rawLo
);
1455 uint32_t code1
= bytebits_to_byte(dest
+ 8, fmtLen
);
1456 Dbprintf("AWID Found - Bit length: " _GREEN_("%d") " -unknown bit length- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen
, cardnum
, code1
, rawHi2
, rawHi
, rawLo
);
1466 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1468 if (ledcontrol
) LEDsoff();
1472 int lf_em410x_watch(int findone
, uint32_t *high
, uint64_t *low
, bool ledcontrol
) {
1474 size_t size
, idx
= 0;
1475 int clk
= 0, invert
= 0, maxErr
= 20;
1479 uint8_t *dest
= BigBuf_get_addr();
1482 BigBuf_Clear_keep_EM();
1484 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
1486 int res
= PM3_SUCCESS
;
1490 if (data_available() || BUTTON_PRESS()) {
1491 res
= PM3_EOPABORTED
;
1495 DoAcquisition_default(-1, false, ledcontrol
);
1497 size
= MIN(16385, BigBuf_max_traceLen());
1499 //askdemod and manchester decode
1500 int errCnt
= askdemod(dest
, &size
, &clk
, &invert
, maxErr
, 0, 1);
1501 if (errCnt
> 50) continue;
1505 int type
= Em410xDecode(dest
, &size
, &idx
, &hi
, &lo
);
1508 Dbprintf("EM TAG ID: " _GREEN_("%02x%08x") " - ( %05d_%03d_%08d )",
1509 (uint32_t)(lo
>> 32),
1511 (uint32_t)(lo
& 0xFFFF),
1512 (uint32_t)((lo
>> 16LL) & 0xFF),
1513 (uint32_t)(lo
& 0xFFFFFF));
1516 Dbprintf("EM XL TAG ID: " _GREEN_("%06x%08x%08x") " - ( %05d_%03d_%08d )",
1518 (uint32_t)(lo
>> 32),
1520 (uint32_t)(lo
& 0xFFFF),
1521 (uint32_t)((lo
>> 16LL) & 0xFF),
1522 (uint32_t)(lo
& 0xFFFFFF));
1525 uint64_t data
= (lo
<< 20) >> 20;
1526 // Convert back to Short ID
1527 uint64_t id
= ((uint64_t)hi
<< 16) | (lo
>> 48);
1528 if ((data
& 0xFFFFFFFF) == 0) {
1529 Dbprintf("EM TAG ID: " _GREEN_("%02x%08x") " - ( %05d_%03d_%08d ) Electra "_GREEN_("%i"),
1530 (uint32_t)(id
>> 32),
1532 (uint32_t)(id
& 0xFFFF),
1533 (uint32_t)((id
>> 16LL) & 0xFF),
1534 (uint32_t)(id
& 0xFFFFFF),
1535 (uint32_t)(data
>> 32));
1537 Dbprintf("EM TAG ID: " _GREEN_("%02x%08x") " - ( %05d_%03d_%08d ) on 128b frame with data "_GREEN_("%03x%08x"),
1538 (uint32_t)(id
>> 32),
1540 (uint32_t)(id
& 0xFFFF),
1541 (uint32_t)((id
>> 16LL) & 0xFF),
1542 (uint32_t)(id
& 0xFFFFFF),
1543 (uint32_t)(data
>> 32),
1553 hi
= lo
= size
= idx
= 0;
1557 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1559 if (ledcontrol
) LEDsoff();
1563 int lf_io_watch(int findone
, uint32_t *high
, uint32_t *low
, bool ledcontrol
) {
1566 uint32_t code
= 0, code2
= 0;
1567 uint8_t version
= 0, facilitycode
= 0;
1568 uint16_t number
= 0;
1570 uint8_t *dest
= BigBuf_get_addr();
1571 BigBuf_Clear_keep_EM();
1575 // Configure to go in 125kHz listen mode
1576 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
1578 int res
= PM3_SUCCESS
;
1583 if (data_available() || BUTTON_PRESS()) {
1584 res
= PM3_EOPABORTED
;
1588 DoAcquisition_default(-1, false, ledcontrol
);
1590 size_t size
= MIN(12000, BigBuf_max_traceLen());
1592 //fskdemod and get start index
1593 int idx
= detectIOProx(dest
, &size
, &dummyIdx
);
1594 if (idx
< 0) continue;
1598 //0 10 20 30 40 50 60
1600 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
1601 //-----------------------------------------------------------------------------
1602 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 checksum 11
1605 //00000000 0 11110000 1 11100000 1 00000001 1 00000011 1 10110110 1 01110101 11
1606 //preamble F0 E0 01 03 B6 75
1607 // How to calc checksum,
1608 // http://www.proxmark.org/forum/viewtopic.php?id=364&p=6
1609 // F0 + E0 + 01 + 03 + B6 = 28A
1613 //XSF(version)facility:codeone+codetwo
1615 // if(findone){ //only print binary if we are doing one
1616 // Dbprintf("%d%d%d%d%d%d%d%d %d",dest[idx], dest[idx+1], dest[idx+2],dest[idx+3],dest[idx+4],dest[idx+5],dest[idx+6],dest[idx+7],dest[idx+8]);
1617 // Dbprintf("%d%d%d%d%d%d%d%d %d",dest[idx+9], dest[idx+10],dest[idx+11],dest[idx+12],dest[idx+13],dest[idx+14],dest[idx+15],dest[idx+16],dest[idx+17]);
1618 // Dbprintf("%d%d%d%d%d%d%d%d %d",dest[idx+18],dest[idx+19],dest[idx+20],dest[idx+21],dest[idx+22],dest[idx+23],dest[idx+24],dest[idx+25],dest[idx+26]);
1619 // Dbprintf("%d%d%d%d%d%d%d%d %d",dest[idx+27],dest[idx+28],dest[idx+29],dest[idx+30],dest[idx+31],dest[idx+32],dest[idx+33],dest[idx+34],dest[idx+35]);
1620 // Dbprintf("%d%d%d%d%d%d%d%d %d",dest[idx+36],dest[idx+37],dest[idx+38],dest[idx+39],dest[idx+40],dest[idx+41],dest[idx+42],dest[idx+43],dest[idx+44]);
1621 // Dbprintf("%d%d%d%d%d%d%d%d %d",dest[idx+45],dest[idx+46],dest[idx+47],dest[idx+48],dest[idx+49],dest[idx+50],dest[idx+51],dest[idx+52],dest[idx+53]);
1622 // Dbprintf("%d%d%d%d%d%d%d%d %d%d",dest[idx+54],dest[idx+55],dest[idx+56],dest[idx+57],dest[idx+58],dest[idx+59],dest[idx+60],dest[idx+61],dest[idx+62],dest[idx+63]);
1624 code
= bytebits_to_byte(dest
+ idx
, 32);
1625 code2
= bytebits_to_byte(dest
+ idx
+ 32, 32);
1626 version
= bytebits_to_byte(dest
+ idx
+ 27, 8); //14,4
1627 facilitycode
= bytebits_to_byte(dest
+ idx
+ 18, 8);
1628 number
= (bytebits_to_byte(dest
+ idx
+ 36, 8) << 8) | (bytebits_to_byte(dest
+ idx
+ 45, 8)); //36,9
1630 Dbprintf("IO Prox " _GREEN_("XSF(%02d)%02x:%05d") " (%08x%08x) (%s)", version
, facilitycode
, number
, code
, code2
);
1638 version
= facilitycode
= 0;
1641 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1643 if (ledcontrol
) LEDsoff();
1647 /*------------------------------
1648 * T5555/T5557/T5567/T5577 routines
1649 *------------------------------
1650 * NOTE: T55x7/T5555 configuration register definitions moved to protocols.h
1652 * Relevant communication times in microsecond
1653 * To compensate antenna falling times shorten the write times
1654 * and enlarge the gap ones.
1655 * Q5 tags seems to have issues when these values changes.
1658 void turn_read_lf_on(uint32_t delay
) {
1659 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER
| FPGA_LF_ADC_READER_FIELD
);
1661 // measure antenna strength.
1662 //int adcval = ((MAX_ADC_LF_VOLTAGE * (SumAdc(ADC_CHAN_LF, 32) >> 1)) >> 14);
1666 void turn_read_lf_off(uint32_t delay
) {
1667 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1671 // Macro for code readability
1672 #define BITSTREAM_BYTE(x) ((x) >> 3) // iceman note: isn't this NIBBLE???
1673 #define BITSTREAM_BIT(x) ((x) & 7)
1675 #define T55_LLR_REF (136 * 8)
1677 // Write one bit to chip
1678 static void T55xxWriteBit(uint8_t bit
, uint8_t downlink_idx
) {
1683 turn_read_lf_on(T55xx_Timing
.m
[downlink_idx
].write_0
);
1687 turn_read_lf_on(T55xx_Timing
.m
[downlink_idx
].write_1
);
1690 // send bits 10 (1 of 4)
1691 turn_read_lf_on(T55xx_Timing
.m
[downlink_idx
].write_2
);
1694 // send bits 11 (1 of 4)
1695 turn_read_lf_on(T55xx_Timing
.m
[downlink_idx
].write_3
);
1698 // send Long Leading Reference
1699 turn_read_lf_on(T55xx_Timing
.m
[downlink_idx
].write_0
+ T55_LLR_REF
);
1703 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1704 WaitUS(T55xx_Timing
.m
[downlink_idx
].write_gap
);
1707 // Function to abstract an Arbitrary length byte array to store bit pattern.
1708 // bit_array - Array to hold data/bit pattern
1709 // start_offset - bit location to start storing new bits.
1710 // data - up to 32 bits of data to store
1711 // num_bits - how many bits (low x bits of data) Max 32 bits at a time
1712 // max_len - how many bytes can the bit_array hold (ensure no buffer overflow)
1713 // returns "Next" bit offset / bits stored (for next store)
1714 static uint8_t T55xx_SetBits(uint8_t *bs
, uint8_t start_offset
, uint32_t data
, uint8_t num_bits
, uint8_t max_len
) {
1715 int8_t next_offset
= start_offset
;
1717 // Check if data will fit.
1718 if ((start_offset
+ num_bits
) <= (max_len
* 8)) {
1719 // Loop through the data and store
1720 for (int8_t offset
= (num_bits
- 1); offset
>= 0; offset
--) {
1722 if ((data
>> offset
) & 1)
1723 bs
[BITSTREAM_BYTE(next_offset
)] |= (1 << BITSTREAM_BIT(next_offset
)); // Set 1
1725 bs
[BITSTREAM_BYTE(next_offset
)] &= (0xff ^ (1 << BITSTREAM_BIT(next_offset
))); // Set 0
1730 // Note: This should never happen unless some code changes cause it.
1731 // So short message for coders when testing.
1732 Dbprintf(_RED_("T55 too many bits"));
1737 // Send one downlink command to the card
1738 static void T55xx_SendCMD(uint32_t data
, uint32_t pwd
, uint16_t arg
) {
1742 xxxx xxxxxxx1 0x001 password mode (Y/N)
1743 xxxx xxxxxx1x 0x002 page (0|1)
1744 xxxx xxxxx1xx 0x004 test mode (Y/N)
1745 xxxx xxx11xxx 0x018 selected downlink mode (0|1|2|3|)
1746 xxxx xx1xxxxx 0x020 !reg_readmode (ICEMAN ?? Why use negative in the bool ??)
1747 xxxx x1xxxxxx 0x040 called for a read, so no data packet (Y/N)
1748 xxxx 1xxxxxxx 0x080 reset (Y/N)
1749 xxx1 xxxxxxxx 0x100 brute force (Y/N)
1750 111x xxxxxxxx 0xE00 block to write (0-7)
1752 bool t55_send_pwdmode
= (arg
& 0x1);
1753 bool t55_send_page
= ((arg
>> 1) & 0x1);
1754 bool t55_send_testmode
= ((arg
>> 2) & 0x1);
1755 bool t55_send_regreadmode
= ((arg
>> 5) & 0x1);
1756 bool t55_send_readcmd
= ((arg
>> 6) & 0x1);
1757 bool t55_send_reset
= ((arg
>> 7) & 0x1);
1758 bool t55_brute_mem
= ((arg
>> 8) & 0x1);
1760 uint8_t downlink_mode
= (arg
>> 3) & 0x03;
1761 uint8_t block_no
= (arg
>> 9) & 0x07;
1763 // no startup delay when in bruteforce command
1764 uint8_t start_wait
= (t55_brute_mem
) ? 0 : 4;
1766 // Max Downlink Command size ~74 bits, so 10 bytes (80 bits)
1768 memset(bs
, 0x00, sizeof(bs
));
1772 // build bit stream to send.
1775 if (downlink_mode
== T55XX_DLMODE_LEADING_ZERO
)
1776 len
= T55xx_SetBits(bs
, len
, 0, 1, sizeof(bs
));
1778 // add 1 of 4 reference bit
1779 if (downlink_mode
== T55XX_DLMODE_1OF4
) {
1780 len
= T55xx_SetBits(bs
, len
, 0, 1, sizeof(bs
));
1782 len
= T55xx_SetBits(bs
, len
, 0, 1, sizeof(bs
));
1786 if (t55_send_reset
) {
1788 len
= T55xx_SetBits(bs
, len
, 0, 2, sizeof(bs
));
1791 if (t55_send_testmode
)
1792 Dbprintf(_YELLOW_("Using Test Mode"));
1794 len
= T55xx_SetBits(bs
, len
, t55_send_testmode
? 0 : 1, 1, sizeof(bs
));
1796 len
= T55xx_SetBits(bs
, len
, t55_send_testmode
? 1 : t55_send_page
, 1, sizeof(bs
));
1798 if (t55_send_pwdmode
) {
1799 // Leading 0 and 1 of 4 00 fixed bits if passsword used
1800 if ((downlink_mode
== T55XX_DLMODE_LEADING_ZERO
) || (downlink_mode
== T55XX_DLMODE_1OF4
)) {
1801 len
= T55xx_SetBits(bs
, len
, 0, 2, sizeof(bs
));
1803 len
= T55xx_SetBits(bs
, len
, pwd
, 32, sizeof(bs
));
1807 if (t55_send_regreadmode
== false)
1808 len
= T55xx_SetBits(bs
, len
, 0, 1, sizeof(bs
));
1810 // Add Data if a write command
1811 if (t55_send_readcmd
== false)
1812 len
= T55xx_SetBits(bs
, len
, data
, 32, sizeof(bs
));
1815 if (t55_send_regreadmode
== false)
1816 len
= T55xx_SetBits(bs
, len
, block_no
, 3, sizeof(bs
));
1819 // Send Bits to T55xx
1820 // Set up FPGA, 125kHz
1821 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
1823 // make sure tag is fully powered up...
1826 // Trigger T55x7 in mode.
1827 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1828 WaitUS(T55xx_Timing
.m
[downlink_mode
].start_gap
);
1830 // If long leading 0 send long reference pulse
1831 if (downlink_mode
== T55XX_DLMODE_LLR
)
1832 T55xxWriteBit(T55XX_LONGLEADINGREFERENCE
, downlink_mode
);//Timing); // Send Long Leading Start Reference
1835 if ((downlink_mode
== T55XX_DLMODE_1OF4
) && (len
> 0)) { // 1 of 4 need to send 2 bits at a time
1836 for (uint8_t i
= 0; i
< len
- 1; i
+= 2) {
1837 sendbits
= (bs
[BITSTREAM_BYTE(i
)] >> (BITSTREAM_BIT(i
)) & 1) << 1; // Bit i
1838 sendbits
+= (bs
[BITSTREAM_BYTE(i
+ 1)] >> (BITSTREAM_BIT(i
+ 1)) & 1); // Bit i+1;
1839 T55xxWriteBit(sendbits
& 3, downlink_mode
);
1842 for (uint8_t i
= 0; i
< len
; i
++) {
1843 sendbits
= (bs
[BITSTREAM_BYTE(i
)] >> BITSTREAM_BIT(i
));
1844 T55xxWriteBit(sendbits
& 1, downlink_mode
);
1849 // Send T5577 reset command then read stream (see if we can identify the start of the stream)
1850 void T55xxResetRead(uint8_t flags
, bool ledcontrol
) {
1852 uint8_t downlink_mode
= ((flags
>> 3) & 3);
1853 uint8_t arg
= 0x80 | downlink_mode
;
1855 if (ledcontrol
) LED_A_ON();
1857 //clear buffer now so it does not interfere with timing later
1858 BigBuf_Clear_keep_EM();
1860 T55xx_SendCMD(0, 0, arg
);
1862 turn_read_lf_on(T55xx_Timing
.m
[downlink_mode
].read_gap
);
1865 DoPartialAcquisition(0, false, BigBuf_max_traceLen(), 0, ledcontrol
);
1867 // Turn the field off
1868 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1869 reply_ng(CMD_LF_T55XX_RESET_READ
, PM3_SUCCESS
, NULL
, 0);
1870 if (ledcontrol
) LED_A_OFF();
1873 void T55xxDangerousRawTest(const uint8_t *data
, bool ledcontrol
) {
1874 // supports only default downlink mode
1875 const t55xx_test_block_t
*c
= (const t55xx_test_block_t
*)data
;
1877 uint8_t start_wait
= 4;
1878 uint8_t bs
[128 / 8];
1879 memset(bs
, 0x00, sizeof(bs
));
1881 if (c
->bitlen
== 0 || c
->bitlen
> 128 || c
->time
== 0)
1882 reply_ng(CMD_LF_T55XX_DANGERRAW
, PM3_EINVARG
, NULL
, 0);
1883 for (uint8_t i
= 0; i
< c
->bitlen
; i
++)
1884 len
= T55xx_SetBits(bs
, len
, c
->data
[i
], 1, sizeof(bs
));
1886 if (g_dbglevel
> 1) {
1887 Dbprintf("LEN %i, TIMING %i", len
, c
->time
);
1888 for (uint8_t i
= 0; i
< len
; i
++) {
1889 uint8_t sendbits
= (bs
[BITSTREAM_BYTE(i
)] >> BITSTREAM_BIT(i
));
1890 Dbprintf("%02i: %i", i
, sendbits
& 1);
1894 if (ledcontrol
) LED_A_ON();
1895 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
1896 // make sure tag is fully powered up...
1898 // Trigger T55x7 in mode.
1899 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1900 WaitUS(T55xx_Timing
.m
[0].start_gap
);
1901 for (uint8_t i
= 0; i
< len
; i
++) {
1902 uint8_t sendbits
= (bs
[BITSTREAM_BYTE(i
)] >> BITSTREAM_BIT(i
));
1903 T55xxWriteBit(sendbits
& 1, 0);
1905 turn_read_lf_on(c
->time
);
1906 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1907 reply_ng(CMD_LF_T55XX_DANGERRAW
, PM3_SUCCESS
, NULL
, 0);
1908 if (ledcontrol
) LED_A_OFF();
1911 // Write one card block in page 0, no lock
1912 //void T55xxWriteBlockExt(uint32_t data, uint8_t blockno, uint32_t pwd, uint8_t flags) {
1913 void T55xxWriteBlock(uint8_t *data
, bool ledcontrol
) {
1917 xxxxxxx1 0x01 PwdMode
1919 xxxxx1xx 0x04 testMode
1920 xxx11xxx 0x18 downlink mode
1921 xx1xxxxx 0x20 !reg_readmode
1922 x1xxxxxx 0x40 called for a read, so no data packet
1926 t55xx_write_block_t
*c
= (t55xx_write_block_t
*)data
;
1927 // c->data, c->blockno, c->pwd, c->flags
1929 bool testMode
= ((c
->flags
& 0x04) == 0x04);
1931 c
->flags
&= (0xff ^ 0x40); // Called for a write, so ensure it is clear/0
1933 if (ledcontrol
) LED_A_ON();
1934 T55xx_SendCMD(c
->data
, c
->pwd
, c
->flags
| (c
->blockno
<< 9));
1936 // Perform write (nominal is 5.6 ms for T55x7 and 18ms for E5550,
1937 // so wait a little more)
1939 // "there is a clock delay before programming"
1940 // - programming takes ~5.6ms for t5577 ~18ms for E5550 or t5567
1941 // so we should wait 1 clock + 5.6ms then read response?
1942 // but we need to know we are dealing with t5577 vs t5567 vs e5550 (or q5) marshmellow...
1944 //TESTMODE TIMING TESTS:
1945 // <566us does nothing
1946 // 566-568 switches between wiping to 0s and doing nothing
1947 // 5184 wipes and allows 1 block to be programmed.
1948 // indefinite power on wipes and then programs all blocks with bitshifted data sent.
1949 turn_read_lf_on(5184);
1952 turn_read_lf_on(20 * 1000);
1953 //could attempt to do a read to confirm write took
1954 // as the tag should repeat back the new block
1955 // until it is reset, but to confirm it we would
1956 // need to know the current block 0 config mode for
1957 // modulation clock another details to demod the response...
1958 // response should be (for t55x7) a 0 bit then (ST if on)
1959 // block data written in on repeat until reset.
1961 //DoPartialAcquisition(20, false, 12000, ledcontrol);
1964 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1966 reply_ng(CMD_LF_T55XX_WRITEBL
, PM3_SUCCESS
, NULL
, 0);
1967 if (ledcontrol
) LED_A_OFF();
1972 void T55xxWriteBlock(uint8_t *data) {
1973 t55xx_write_block_t *c = (t55xx_write_block_t *)data;
1974 T55xxWriteBlockExt(c->data, c->blockno, c->pwd, c->flags);
1975 // reply_ng(CMD_LF_T55XX_WRITEBL, PM3_SUCCESS, NULL, 0);
1979 // Read one card block in page [page]
1980 void T55xxReadBlockExt(uint16_t flags, uint8_t block, uint32_t pwd, bool ledcontrol) {
1983 xxxx xxxxxxx1 0x0001 PwdMode
1984 xxxx xxxxxx1x 0x0002 Page
1985 xxxx xxxxx1xx 0x0004 testMode
1986 xxxx xxx11xxx 0x0018 downlink mode
1987 xxxx xx1xxxxx 0x0020 !reg_readmode
1988 xxxx x1xxxxxx 0x0040 called for a read, so no data packet
1989 xxxx 1xxxxxxx 0x0080 reset
1990 xxx1 xxxxxxxx 0x0100 brute / leave field on
1992 size_t samples = 12000;
1993 bool brute_mem = (flags & 0x0100) >> 8;
1995 if (ledcontrol) LED_A_ON();
1997 if (brute_mem) samples = 1024;
1999 // Set Read Flag to ensure SendCMD does not add "data" to the packet
2002 // RegRead Mode true block = 0xff, so read without an address
2003 if (block == 0xff) flags |= 0x20;
2005 //make sure block is at max 7
2008 //clear buffer now so it does not interfere with timing later
2009 BigBuf_Clear_keep_EM();
2011 T55xx_SendCMD(0, pwd, flags | (block << 9)); //, true);
2013 // Turn field on to read the response
2014 // 137*8 seems to get to the start of data pretty well...
2015 // but we want to go past the start and let the repeating data settle in...
2017 // turn_read_lf_on(210*8); // issues with block 1 reads so dropping down seemed to help
2018 turn_read_lf_on(137 * 8);
2021 // Now do the acquisition
2022 DoPartialAcquisition(0, false, samples, 0, ledcontrol);
2024 // Turn the field off
2026 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2027 reply_ng(CMD_LF_T55XX_READBL, PM3_SUCCESS, NULL, 0);
2028 if (ledcontrol) LED_A_OFF();
2032 // Read one card block in page [page]
2033 void T55xxReadBlock(uint8_t page
, bool pwd_mode
, bool brute_mem
, uint8_t block
, uint32_t pwd
, uint8_t downlink_mode
, bool ledcontrol
) {
2036 xxxx xxxxxxx1 0x0001 PwdMode
2037 xxxx xxxxxx1x 0x0002 Page
2038 xxxx xxxxx1xx 0x0004 testMode
2039 xxxx xxx11xxx 0x0018 downlink mode
2040 xxxx xx1xxxxx 0x0020 !reg_readmode
2041 xxxx x1xxxxxx 0x0040 called for a read, so no data packet
2042 xxxx 1xxxxxxx 0x0080 reset
2043 xxx1 xxxxxxxx 0x0100 brute / leave field on
2045 uint16_t flags
= 0x0040; // read packet
2046 if (pwd_mode
) flags
|= 0x0001;
2047 if (page
) flags
|= 0x0002;
2048 flags
|= (downlink_mode
& 3) << 3;
2049 if (brute_mem
) flags
|= 0x0100;
2051 sample_config old_config
;
2052 sample_config
*curr_config
= getSamplingConfig();
2053 memcpy(&old_config
, curr_config
, sizeof(sample_config
));
2054 old_config
.verbose
= false;
2056 setDefaultSamplingConfig();
2058 size_t samples
= 12000;
2060 if (ledcontrol
) LED_A_ON();
2062 if (brute_mem
) samples
= 2048;
2064 //-- Set Read Flag to ensure SendCMD does not add "data" to the packet
2067 // RegRead Mode true block = 0xff, so read without an address
2068 if (block
== 0xff) flags
|= 0x20;
2070 //make sure block is at max 7
2073 //clear buffer now so it does not interfere with timing later
2074 BigBuf_Clear_keep_EM();
2076 T55xx_SendCMD(0, pwd
, flags
| (block
<< 9)); //, true);
2078 // Turn field on to read the response
2079 // 137*8 seems to get to the start of data pretty well...
2080 // but we want to go past the start and let the repeating data settle in...
2082 // turn_read_lf_on(210*8); // issues with block 1 reads so dropping down seemed to help
2083 turn_read_lf_on(137 * 8);
2086 // Now do the acquisition
2087 DoPartialAcquisition(0, false, samples
, 1000, ledcontrol
);
2089 // Turn the field off
2090 if (brute_mem
== false) {
2091 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2092 reply_ng(CMD_LF_T55XX_READBL
, PM3_SUCCESS
, NULL
, 0);
2093 if (ledcontrol
) LED_A_OFF();
2096 // reset back to old / save config
2097 setSamplingConfig(&old_config
);
2101 void T55xx_ChkPwds(uint8_t flags
, bool ledcontrol
) {
2103 #define CHK_SAMPLES_SIGNAL 2048
2106 DbpString(_CYAN_("T55XX Check pwds using flashmemory starting"));
2108 DbpString(_CYAN_("T55XX Check pwds starting"));
2111 // First get baseline and setup LF mode.
2112 uint8_t *buf
= BigBuf_get_addr();
2113 uint8_t downlink_mode
= (flags
>> 3) & 0x03;
2114 uint64_t b1
, baseline_faulty
= 0;
2116 DbpString("Determine baseline...");
2118 // collect baseline for failed attempt ( should give me block1 )
2122 T55xxReadBlock(0, 0, true, 0, 0, downlink_mode
, ledcontrol
);
2123 for (uint16_t j
= 0; j
< CHK_SAMPLES_SIGNAL
; ++j
) {
2124 b1
+= (buf
[j
] * buf
[j
]);
2128 baseline_faulty
+= b1
;
2130 baseline_faulty
>>= 5;
2132 if (g_dbglevel
>= DBG_DEBUG
)
2133 Dbprintf("Baseline " _YELLOW_("%llu"), baseline_faulty
);
2135 uint8_t *pwds
= BigBuf_get_EM_addr();
2136 uint16_t pwd_count
= 0;
2143 payload
.found
= false;
2144 payload
.candidate
= 0;
2150 uint8_t counter
[2] = {0x00, 0x00};
2151 isok
= Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_pages64k
), counter
, sizeof(counter
));
2152 if (isok
!= sizeof(counter
))
2155 pwd_count
= (uint16_t)(counter
[1] << 8 | counter
[0]);
2159 // since flash can report way too many pwds, we need to limit it.
2160 // bigbuff EM size is determined by CARD_MEMORY_SIZE
2161 // a password is 4bytes.
2162 uint16_t pwd_size_available
= MIN(CARD_MEMORY_SIZE
, pwd_count
* 4);
2164 // adjust available pwd_count
2165 pwd_count
= pwd_size_available
/ 4;
2167 isok
= Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_pages64k
) + 2, pwds
, pwd_size_available
);
2168 if (isok
!= pwd_size_available
)
2171 Dbprintf("Password dictionary count " _YELLOW_("%d"), pwd_count
);
2175 uint64_t curr
, prev
= 0;
2178 for (uint32_t i
= 0; i
< pwd_count
; i
++) {
2180 uint32_t pwd
= bytes_to_num(pwds
+ (i
* 4), 4);
2182 T55xxReadBlock(0, true, true, 0, pwd
, downlink_mode
, ledcontrol
);
2185 for (uint16_t j
= 0; j
< CHK_SAMPLES_SIGNAL
; ++j
) {
2186 sum
+= (buf
[j
] * buf
[j
]);
2191 int64_t tmp_dist
= (baseline_faulty
- sum
);
2192 curr
= ABS(tmp_dist
);
2194 if (g_dbglevel
>= DBG_DEBUG
)
2195 Dbprintf("%08x has distance " _YELLOW_("%llu"), pwd
, curr
);
2204 payload
.found
= true;
2205 payload
.candidate
= bytes_to_num(pwds
+ (idx
* 4), 4);
2212 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2213 if (ledcontrol
) LEDsoff();
2214 reply_ng(CMD_LF_T55XX_CHK_PWDS
, PM3_SUCCESS
, (uint8_t *)&payload
, sizeof(payload
));
2218 void T55xxWakeUp(uint32_t pwd
, uint8_t flags
, bool ledcontrol
) {
2220 flags
|= 0x01 | 0x40 | 0x20; //Password | Read Call (no data) | reg_read no block
2221 if (ledcontrol
) LED_B_ON();
2223 T55xx_SendCMD(0, pwd
, flags
);
2225 //-- Turn and leave field on to let the begin repeating transmission
2226 turn_read_lf_on(20 * 1000);
2227 reply_ng(CMD_LF_T55XX_WAKEUP
, PM3_SUCCESS
, NULL
, 0);
2230 /*-------------- Cloning routines -----------*/
2231 static void WriteT55xx(const uint32_t *blockdata
, uint8_t startblock
, uint8_t numblocks
, bool ledcontrol
) {
2234 if (blockdata
== NULL
|| numblocks
== 0) {
2235 reply_ng(CMD_LF_T55XX_WRITEBL
, PM3_EINVARG
, NULL
, 0);
2239 t55xx_write_block_t cmd
= {
2244 // write in reverse order since we don't want to set
2245 // a password enabled configuration first....
2246 while (numblocks
--) {
2249 cmd
.data
= blockdata
[numblocks
];
2250 cmd
.blockno
= startblock
+ numblocks
;
2252 // since this fct sends a NG packet every time, this loop will send I number of NG
2253 T55xxWriteBlock((uint8_t *)&cmd
, ledcontrol
);
2257 static void WriteEM4x05(uint32_t *blockdata
, uint8_t startblock
, uint8_t numblocks
, bool ledcontrol
) {
2258 if (g_dbglevel
== DBG_DEBUG
) {
2259 Dbprintf("# | data ( EM4x05 )");
2260 Dbprintf("--+----------------");
2263 for (uint8_t i
= startblock
; i
< (uint8_t)(startblock
+ numblocks
); i
++) {
2265 blockdata
[i
- startblock
] = reflect(blockdata
[i
- startblock
], 32);
2267 if (g_dbglevel
== DBG_DEBUG
) {
2268 Dbprintf("%i | %08x", i
, blockdata
[i
- startblock
]);
2272 if (g_dbglevel
== DBG_DEBUG
) {
2273 Dbprintf("--+----------------");
2276 for (uint8_t i
= numblocks
+ startblock
; i
> startblock
; i
--) {
2277 EM4xWriteWord(i
- 1, blockdata
[i
- 1 - startblock
], 0, 0, ledcontrol
);
2281 // Copy HID id to card and setup block 0 config
2282 void CopyHIDtoT55x7(uint32_t hi2
, uint32_t hi
, uint32_t lo
, uint8_t longFMT
, bool q5
, bool em
, bool ledcontrol
) {
2283 uint32_t data
[] = {0, 0, 0, 0, 0, 0, 0};
2284 uint8_t last_block
= 0;
2287 // Ensure no more than 84 bits supplied
2288 if (hi2
> 0xFFFFF) {
2289 DbpString("Tags can only have 84 bits");
2292 // Build the 6 data blocks for supplied 84bit ID
2294 // load preamble (1D) & long format identifier (9E manchester encoded)
2295 data
[1] = 0x1D96A900 | (manchesterEncode2Bytes((hi2
>> 16) & 0xF) & 0xFF);
2296 // load raw id from hi2, hi, lo to data blocks (manchester encoded)
2297 data
[2] = manchesterEncode2Bytes(hi2
& 0xFFFF);
2298 data
[3] = manchesterEncode2Bytes(hi
>> 16);
2299 data
[4] = manchesterEncode2Bytes(hi
& 0xFFFF);
2300 data
[5] = manchesterEncode2Bytes(lo
>> 16);
2301 data
[6] = manchesterEncode2Bytes(lo
& 0xFFFF);
2303 // Ensure no more than 44 bits supplied
2305 DbpString("Tags can only have 44 bits, if you want more use long format");
2308 // Build the 3 data blocks for supplied 44bit
2311 // 24 bits left. ie 12 bits of data, not 16..
2312 data
[1] = 0x1D000000 | (manchesterEncode2Bytes(hi
& 0xFFF) & 0xFFFFFF);
2313 data
[2] = manchesterEncode2Bytes(lo
>> 16);
2314 data
[3] = manchesterEncode2Bytes(lo
& 0xFFFF);
2316 // load chip config block
2317 data
[0] = T55x7_BITRATE_RF_50
| T55x7_MODULATION_FSK2a
| last_block
<< T55x7_MAXBLOCK_SHIFT
;
2319 //TODO add selection of chip for Q5 or T55x7
2321 data
[0] = T5555_SET_BITRATE(50) | T5555_MODULATION_FSK2
| T5555_INVERT_OUTPUT
| last_block
<< T5555_MAXBLOCK_SHIFT
;
2323 data
[0] = (EM4x05_SET_BITRATE(50) | EM4x05_MODULATION_FSK2
| EM4x05_SET_NUM_BLOCKS(last_block
));
2324 // EM4x05_INVERT not available on EM4305, so let's invert manually
2325 for (uint8_t i
= 1; i
<= last_block
; i
++) {
2326 data
[i
] = data
[i
] ^ 0xFFFFFFFF;
2330 if (ledcontrol
) LED_D_ON();
2332 WriteEM4x05(data
, 4, last_block
+ 1, ledcontrol
);
2334 WriteT55xx(data
, 0, last_block
+ 1, ledcontrol
);
2336 if (ledcontrol
) LED_D_OFF();
2337 reply_ng(CMD_LF_HID_CLONE
, PM3_SUCCESS
, NULL
, 0);
2340 // clone viking tag to T55xx
2341 void CopyVikingtoT55xx(const uint8_t *blocks
, bool q5
, bool em
, bool ledcontrol
) {
2343 uint32_t data
[] = {T55x7_BITRATE_RF_32
| T55x7_MODULATION_MANCHESTER
| (2 << T55x7_MAXBLOCK_SHIFT
), 0, 0};
2345 data
[0] = T5555_SET_BITRATE(32) | T5555_MODULATION_MANCHESTER
| 2 << T5555_MAXBLOCK_SHIFT
;
2347 data
[0] = (EM4x05_SET_BITRATE(32) | EM4x05_MODULATION_MANCHESTER
| EM4x05_SET_NUM_BLOCKS(2));
2350 data
[1] = bytes_to_num(blocks
, 4);
2351 data
[2] = bytes_to_num(blocks
+ 4, 4);
2353 // Program the data blocks for supplied ID and the block 0 config
2355 WriteEM4x05(data
, 4, 3, ledcontrol
);
2357 WriteT55xx(data
, 0, 3, ledcontrol
);
2359 if (ledcontrol
) LED_D_OFF();
2360 reply_ng(CMD_LF_VIKING_CLONE
, PM3_SUCCESS
, NULL
, 0);
2363 int copy_em410x_to_t55xx(uint8_t card
, uint8_t clock
, uint32_t id_hi
, uint32_t id_lo
, bool add_electra
, bool ledcontrol
) {
2365 // Define 9bit header for EM410x tags
2366 #define EM410X_HEADER 0x1FF
2367 #define EM410X_ID_LENGTH 40
2369 uint32_t clockbits
= 0;
2370 if (card
== 1) { //t55x7
2371 clockbits
= GetT55xxClockBit(clock
);
2372 if (clockbits
== 0) {
2373 Dbprintf("Invalid clock rate: %d", clock
);
2379 uint64_t id
= EM410X_HEADER
;
2380 uint64_t rev_id
= 0; // reversed ID
2381 int c_parity
[4]; // column parity
2382 int r_parity
= 0; // row parity
2384 // Reverse ID bits given as parameter (for simpler operations)
2385 for (i
= 0; i
< EM410X_ID_LENGTH
; ++i
) {
2387 rev_id
= (rev_id
<< 1) | (id_lo
& 1);
2390 rev_id
= (rev_id
<< 1) | (id_hi
& 1);
2395 for (i
= 0; i
< EM410X_ID_LENGTH
; ++i
) {
2396 int id_bit
= rev_id
& 1;
2399 // Don't write row parity bit at start of parsing
2401 id
= (id
<< 1) | r_parity
;
2402 // Start counting parity for new row
2409 // First elements in column?
2411 // Fill out first elements
2412 c_parity
[i
] = id_bit
;
2414 // Count column parity
2415 c_parity
[i
% 4] ^= id_bit
;
2418 id
= (id
<< 1) | id_bit
;
2422 // Insert parity bit of last row
2423 id
= (id
<< 1) | r_parity
;
2425 // Fill out column parity at the end of tag
2426 for (i
= 0; i
< 4; ++i
)
2427 id
= (id
<< 1) | c_parity
[i
];
2432 if (ledcontrol
) LED_D_ON();
2435 uint32_t data
[] = {0, (uint32_t)(id
>> 32), (uint32_t)(id
& 0xFFFFFFFF)};
2438 clock
= (clock
== 0) ? 64 : clock
;
2439 Dbprintf("Clock rate: %d", clock
);
2441 uint32_t electra
[] = { 0x7E1EAAAA, 0xAAAAAAAA };
2447 if (card
== 1) { // T55x7
2448 data
[0] = clockbits
| T55x7_MODULATION_MANCHESTER
| (blocks
<< T55x7_MAXBLOCK_SHIFT
);
2449 } else if (card
== 2) { // EM4x05
2450 data
[0] = (EM4x05_SET_BITRATE(clock
) | EM4x05_MODULATION_MANCHESTER
| EM4x05_SET_NUM_BLOCKS(blocks
));
2451 } else { // T5555 (Q5)
2452 data
[0] = T5555_SET_BITRATE(clock
) | T5555_MODULATION_MANCHESTER
| (blocks
<< T5555_MAXBLOCK_SHIFT
);
2456 WriteEM4x05(data
, 4, 3, ledcontrol
);
2458 WriteEM4x05(electra
, 7, 2, ledcontrol
);
2461 WriteT55xx(data
, 0, 3, ledcontrol
);
2463 WriteT55xx(electra
, 3, 2, ledcontrol
);
2467 if (ledcontrol
) LEDsoff();
2469 Dbprintf("Tag %s written with 0x%08x%08x",
2470 card
== 0 ? "T5555" : (card
== 1 ? "T55x7" : "EM4x05"),
2471 (uint32_t)(id
>> 32),
2476 Dbprintf("Electra 0x%08x%08x\n", electra
[0], electra
[1]);
2482 //-----------------------------------
2483 // EM4469 / EM4305 routines
2484 //-----------------------------------
2485 // Below given command set.
2486 // Commands are including the even parity, binary mirrored
2487 #define FWD_CMD_LOGIN 0xC
2488 #define FWD_CMD_WRITE 0xA
2489 #define FWD_CMD_READ 0x9
2490 #define FWD_CMD_PROTECT 0x3
2491 #define FWD_CMD_DISABLE 0x5
2493 static uint8_t forwardLink_data
[64]; //array of forwarded bits
2494 static uint8_t *forward_ptr
; //ptr for forward message preparation
2495 static uint8_t fwd_bit_sz
; //forwardlink bit counter
2496 static uint8_t *fwd_write_ptr
; //forwardlink bit pointer
2498 //====================================================================
2499 // prepares command bits
2501 //====================================================================
2502 //--------------------------------------------------------------------
2503 // VALUES TAKEN FROM EM4x function: SendForward
2504 // START_GAP = 440; (55*8) cycles at 125kHz (8us = 1cycle)
2505 // WRITE_GAP = 128; (16*8)
2506 // WRITE_1 = 256 32*8; (32*8)
2508 // These timings work for 4469/4269/4305 (with the 55*8 above)
2509 // WRITE_0 = 23*8 , 9*8
2511 static uint8_t Prepare_Cmd(uint8_t cmd
) {
2513 *forward_ptr
++ = 0; //start bit
2514 *forward_ptr
++ = 0; //second pause for 4050 code
2516 *forward_ptr
++ = cmd
;
2518 *forward_ptr
++ = cmd
;
2520 *forward_ptr
++ = cmd
;
2522 *forward_ptr
++ = cmd
;
2524 return 6; //return number of emitted bits
2527 //====================================================================
2528 // prepares address bits
2530 //====================================================================
2531 static uint8_t Prepare_Addr(uint8_t addr
) {
2533 register uint8_t line_parity
;
2537 for (i
= 0; i
< 6; i
++) {
2538 *forward_ptr
++ = addr
;
2539 line_parity
^= addr
;
2543 *forward_ptr
++ = (line_parity
& 1);
2545 return 7; //return number of emitted bits
2548 //====================================================================
2549 // prepares data bits intreleaved with parity bits
2551 //====================================================================
2552 static uint8_t Prepare_Data(uint16_t data_low
, uint16_t data_hi
) {
2554 register uint8_t column_parity
;
2555 register uint8_t i
, j
;
2556 register uint16_t data
;
2561 for (i
= 0; i
< 4; i
++) {
2562 register uint8_t line_parity
= 0;
2563 for (j
= 0; j
< 8; j
++) {
2564 line_parity
^= data
;
2565 column_parity
^= (data
& 1) << j
;
2566 *forward_ptr
++ = data
;
2569 *forward_ptr
++ = line_parity
;
2574 for (j
= 0; j
< 8; j
++) {
2575 *forward_ptr
++ = column_parity
;
2576 column_parity
>>= 1;
2580 return 45; //return number of emitted bits
2583 //====================================================================
2584 // Forward Link send function
2585 // Requires: forwarLink_data filled with valid bits (1 bit per byte)
2586 // fwd_bit_count set with number of bits to be sent
2587 //====================================================================
2588 static void SendForward(uint8_t fwd_bit_count
, bool fast
) {
2590 // iceman, 21.3us increments for the USclock verification.
2591 // 55FC * 8us == 440us / 21.3 === 20.65 steps. could be too short. Go for 56FC instead
2592 // 32FC * 8us == 256us / 21.3 == 12.018 steps. ok
2593 // 16FC * 8us == 128us / 21.3 == 6.009 steps. ok
2594 #ifndef EM_START_GAP
2595 #define EM_START_GAP (55 * 8)
2598 fwd_write_ptr
= forwardLink_data
;
2599 fwd_bit_sz
= fwd_bit_count
;
2601 if (fast
== false) {
2602 // Set up FPGA, 125kHz or 95 divisor
2603 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
2605 // force 1st mod pulse (start gap must be longer for 4305)
2606 fwd_bit_sz
--; //prepare next bit modulation
2609 turn_read_lf_off(EM_START_GAP
);
2610 turn_read_lf_on(18 * 8);
2612 // now start writing with bitbanging the antenna. (each bit should be 32*8 total length)
2613 while (fwd_bit_sz
-- > 0) { //prepare next bit modulation
2614 if (((*fwd_write_ptr
++) & 1) == 1) {
2617 turn_read_lf_off(23 * 8);
2618 turn_read_lf_on(18 * 8);
2623 static void EM4xLoginEx(uint32_t pwd
) {
2624 forward_ptr
= forwardLink_data
;
2625 uint8_t len
= Prepare_Cmd(FWD_CMD_LOGIN
);
2626 len
+= Prepare_Data(pwd
& 0xFFFF, pwd
>> 16);
2627 SendForward(len
, false);
2628 //WaitUS(20); // no wait for login command.
2634 void EM4xBruteforce(uint32_t start_pwd
, uint32_t n
, bool ledcontrol
) {
2635 // With current timing, 18.6 ms per test = 53.8 pwds/s
2636 reply_ng(CMD_LF_EM4X_BF
, PM3_SUCCESS
, NULL
, 0);
2638 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2640 if (ledcontrol
) LED_A_ON();
2642 LFSetupFPGAForADC(LF_DIVISOR_125
, true);
2644 uint32_t candidates_found
= 0;
2645 for (uint32_t pwd
= start_pwd
; pwd
< 0xFFFFFFFF; pwd
++) {
2647 if (((pwd
- start_pwd
) & 0x3F) == 0x00) {
2650 if (BUTTON_PRESS() || data_available()) {
2651 Dbprintf("EM4x05 Bruteforce Interrupted");
2656 // Report progress every 256 attempts
2657 if (((pwd
- start_pwd
) & 0xFF) == 0x00) {
2658 Dbprintf("Trying: %06Xxx", pwd
>> 8);
2662 forward_ptr
= forwardLink_data
;
2663 uint8_t len
= Prepare_Cmd(FWD_CMD_LOGIN
);
2664 len
+= Prepare_Data(pwd
& 0xFFFF, pwd
>> 16);
2665 SendForward(len
, true);
2668 DoPartialAcquisition(0, false, 350, 1000, ledcontrol
);
2670 uint8_t *mem
= BigBuf_get_addr();
2672 if (mem
[334] < 128) {
2674 Dbprintf("Password candidate: " _GREEN_("%08X"), pwd
);
2675 if ((n
!= 0) && (candidates_found
== n
)) {
2676 Dbprintf("EM4x05 Bruteforce Stopped. %i candidate%s found", candidates_found
, candidates_found
> 1 ? "s" : "");
2681 // Beware: if smaller, tag might not have time to be back in listening state yet
2685 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2686 if (ledcontrol
) LEDsoff();
2689 void EM4xLogin(uint32_t pwd
, bool ledcontrol
) {
2692 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2695 if (ledcontrol
) LED_A_ON();
2697 // clear buffer now so it does not interfere with timing later
2698 BigBuf_Clear_ext(false);
2703 // We need to acquire more than needed, to help demodulators finding the proper modulation
2704 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol
);
2707 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2708 reply_ng(CMD_LF_EM4X_LOGIN
, PM3_SUCCESS
, NULL
, 0);
2709 if (ledcontrol
) LEDsoff();
2712 void EM4xReadWord(uint8_t addr
, uint32_t pwd
, uint8_t usepwd
, bool ledcontrol
) {
2715 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2718 if (ledcontrol
) LED_A_ON();
2720 // clear buffer now so it does not interfere with timing later
2721 BigBuf_Clear_ext(false);
2723 /* should we read answer from Logincommand?
2733 forward_ptr
= forwardLink_data
;
2734 uint8_t len
= Prepare_Cmd(FWD_CMD_READ
);
2735 len
+= Prepare_Addr(addr
);
2737 SendForward(len
, false);
2741 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol
);
2744 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2745 reply_ng(CMD_LF_EM4X_READWORD
, PM3_SUCCESS
, NULL
, 0);
2746 if (ledcontrol
) LEDsoff();
2749 void EM4xWriteWord(uint8_t addr
, uint32_t data
, uint32_t pwd
, uint8_t usepwd
, bool ledcontrol
) {
2752 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2755 if (ledcontrol
) LED_A_ON();
2757 // clear buffer now so it does not interfere with timing later
2758 BigBuf_Clear_ext(false);
2760 /* should we read answer from Logincommand?
2770 forward_ptr
= forwardLink_data
;
2771 uint8_t len
= Prepare_Cmd(FWD_CMD_WRITE
);
2772 len
+= Prepare_Addr(addr
);
2773 len
+= Prepare_Data(data
& 0xFFFF, data
>> 16);
2775 SendForward(len
, false);
2777 if (tearoff_hook() == PM3_ETEAROFF
) { // tearoff occurred
2779 reply_ng(CMD_LF_EM4X_WRITEWORD
, PM3_ETEAROFF
, NULL
, 0);
2781 // Wait 20ms for write to complete?
2782 // No, when write is denied, err preamble comes much sooner
2783 //WaitUS(10820); // tPC+tWEE
2785 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol
);
2788 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2789 reply_ng(CMD_LF_EM4X_WRITEWORD
, PM3_SUCCESS
, NULL
, 0);
2791 if (ledcontrol
) LEDsoff();
2794 void EM4xProtectWord(uint32_t data
, uint32_t pwd
, uint8_t usepwd
, bool ledcontrol
) {
2797 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2800 if (ledcontrol
) LED_A_ON();
2802 // clear buffer now so it does not interfere with timing later
2803 BigBuf_Clear_ext(false);
2805 /* should we read answer from Logincommand?
2815 forward_ptr
= forwardLink_data
;
2816 uint8_t len
= Prepare_Cmd(FWD_CMD_PROTECT
);
2817 len
+= Prepare_Data(data
& 0xFFFF, data
>> 16);
2819 SendForward(len
, false);
2821 if (tearoff_hook() == PM3_ETEAROFF
) { // tearoff occurred
2823 reply_ng(CMD_LF_EM4X_PROTECTWORD
, PM3_ETEAROFF
, NULL
, 0);
2825 // Wait 20ms for write to complete?
2826 // No, when write is denied, err preamble comes much sooner
2827 //WaitUS(13640); // tPC+tPR
2829 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol
);
2831 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2832 reply_ng(CMD_LF_EM4X_PROTECTWORD
, PM3_SUCCESS
, NULL
, 0);
2834 if (ledcontrol
) LEDsoff();
2840 COTAG needs the reader to send a startsequence and the card has an extreme slow datarate.
2841 because of this, we can "sample" the data signal but we interpreate it to Manchester direct.
2843 This behavior looks very similar to old ancient Motorola Flexpass
2845 -----------------------------------------------------------------------
2846 According to patent EP0040544B1:
2851 Divide by 384 counter
2853 PULSE repetition 5.82ms
2857 Also references to a half-bit format and leading zero.
2858 -----------------------------------------------------------------------
2860 READER START SEQUENCE:
2862 burst 800 us gap 2.2 ms
2863 burst 3.6 ms gap 2.2 ms
2864 burst 800 us gap 2.2 ms
2867 This triggers COTAG tag to response
2870 void Cotag(uint32_t arg0
, bool ledcontrol
) {
2872 # define OFF(x) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); WaitUS((x)); }
2875 # define ON(x) { FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD); WaitUS((x)); }
2877 uint8_t rawsignal
= arg0
& 0xF;
2879 if (ledcontrol
) LED_A_ON();
2881 LFSetupFPGAForADC(LF_FREQ2DIV(132), true); //132
2883 //clear buffer now so it does not interfere with timing later
2885 BigBuf_Clear_ext(false);
2887 // send COTAG start pulse
2888 // http://www.proxmark.org/forum/viewtopic.php?id=4455
2898 ON(2000) // ON(3400)
2900 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, LF_FREQ2DIV(66)); // 66kHz
2902 switch (rawsignal
) {
2904 doCotagAcquisition();
2905 reply_ng(CMD_LF_COTAG_READ
, PM3_SUCCESS
, NULL
, 0);
2909 uint8_t *dest
= BigBuf_malloc(COTAG_BITS
);
2910 uint16_t bits
= doCotagAcquisitionManchester(dest
, COTAG_BITS
);
2911 reply_ng(CMD_LF_COTAG_READ
, PM3_SUCCESS
, dest
, bits
);
2915 DoAcquisition_config(false, 0, ledcontrol
);
2916 reply_ng(CMD_LF_COTAG_READ
, PM3_SUCCESS
, NULL
, 0);
2920 reply_ng(CMD_LF_COTAG_READ
, PM3_SUCCESS
, NULL
, 0);
2926 // Turn the field off
2927 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2928 if (ledcontrol
) LEDsoff();